text:
Q: How to do the right positioning of css elements? I'm doing a slider based on noUi Slider. Was trying to achieve so to say "an elegant" solution. Since my ui handle is big I made the ui base slightly bigger with extra values in base. But those values are not allowed and handle will jump back to the allowed values. I decided to put plus and minus buttons to the place where restricted values are.
But the problem is that I can't achieve the effect that when you move the handle on to the control symbols (plus/minus) they would hide behind the handle. In my case they remain on top. And I have trouble resolving this issue.
Some help/advice would be great.
Here's my code (styles are on JSFiddle):
$(document).ready(function(){

    var sliders = document.getElementById('red'),
        input = document.getElementById('handle'),
        sliderPlus = document.getElementById('slider-amount-plus'),
        sliderMinus = document.getElementById('slider-amount-minus'),
        termCur = 500;

    noUiSlider.create(sliders, {
        start: termCur,
        step: 50,
        connect: "lower",
        range: {
            'min': 0,
            'max': 1100
        },
        pips: {
            mode: 'values',
            values: [100, 500, 1000],
            density: 4.5
        }
    });
    $('
' + termCur + ' zł' + '
').appendTo($('.noUi-handle', sliders));

sliders.noUiSlider.on('change', function ( values, handle ) {
    if ( values[handle] < 100 ) {
        sliders.noUiSlider.set(100);
    } else if ( values[handle] > 1000 ) {
        sliders.noUiSlider.set(1000);
    }
});
sliders.noUiSlider.on('update', function( values ) {
    termCur = values;
    if( termCur >= 100 && termCur <= 1000 ) {
    $('.value', sliders).text(parseInt(termCur) + ' zł');}
});
sliderPlus.addEventListener('click', function(){
    if(termCur < 1000) {
        var setValue = parseInt(termCur) + 50;
        sliders.noUiSlider.set(setValue);
    }
});
sliderMinus.addEventListener('click', function(){
    if(termCur > 100) {
        var setValue = parseInt(termCur) - 50;
        sliders.noUiSlider.set(setValue);
    }
});

https://jsfiddle.net/o7Ly845j/

A: Groups of elements with a common parent that move forward or backward together in the stacking order make up what is known as a stacking context. A full understanding of stacking contexts is key to really grasping how z-index and the stacking order work.
Every stacking context has a single HTML element as its root element. When a new stacking context is formed on an element, that stacking context confines all of its child elements to a particular place in the stacking order. That means that if an element is contained in a stacking context at the bottom of the stacking order, there is no way to get it to appear in front of another element in a different stacking context that is higher in the stacking order, even with a z-index of a billion!

New stacking contexts can be formed on an element in one of these ways:

*

*When an element is the root element of a document (the  element)

*When an element has a position value other than static and a z-index value other than auto

*When an element has an opacity value less than 1

*In addition to opacity, several CSS properties also create stacking contexts. These include: transforms, filters, css-regions, paged
  media, and possibly others.

Here are the basic rules to determine stacking order within a single stacking context (from back to front):

*

*The stacking context's root element

*Positioned elements (and their children) with negative z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)

*Non-positioned elements (ordered by appearance in the HTML)

*Positioned elements (and their children) with a z-index value of auto (ordered by appearance in the HTML)

*Positioned elements (and their children) with positive z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)
Note: positioned elements with negative z-indexes are ordered first within a stacking context, which means they appear behind all other elements. Because of this, it becomes possible for an element to appear behind its own parent, which is normally not possible. This will only work if the element's parent is in the same stacking context and is not the root element of that stacking context.

I created a "hackish" way to do this with jQuery, you can view the Fiddle here.  This isn't a permanent solution though, I'm working on abstracting the positioning as it's using static values.  I will also figure out why the CSS won't behave and post that here.
     $(document).mousemove(function (e) {
         var newpos = $(".noUi-handle").offset().left;

         if (newpos < 0) {
             $(".slider-minus").hide();
         } else {
             $(".slider-minus").show();
         }

         if (newpos > 830) {
             $(".slider-plus").hide();
         } else {
             $(".slider-plus").show();
         }
    });

update
Here is a better version,  now working on why the CSS won't do it for you.

A: So, taking the last @zgood fiddle, I guessed that the problem wasn't so much z order anymore, it was because both the slider bar and the plus/minus elements were getting the events, and by the time the plus/minus events got a hold of it, the slider was already at 1100 or 0.  So I changed the events around so the plus/minus got the event first and stopped it from going to the bar.  I really only had to stop mousedown and most of the problems fixed itself.  After that, I could take out all the > 100 and < 1000 checks, because the bar behaved itself.
I also noticed that the slider button covered up the plus/minus once you got to 50/1050.  So I changed the plus/minus to z-index:13 instead of 3 in the fiddle.  I'm not sure which is better, so try 3 and 13 and make your own decision.
https://jsfiddle.net/guyschalnat/radpjf47/2/
$(document).ready(function(){

    var sliders = document.getElementById('red'),
        input = document.getElementById('handle'),
        termCur = 500;

    noUiSlider.create(sliders, {
        start: termCur,
        step: 50,
        connect: "lower",
        range: {
            'min': 0,
            'max': 1100
        },
        pips: {
            mode: 'values',
            values: [100, 500, 1000],
            density: 4.5
        }
    });
    $('
' + termCur + ' zł' + '
').appendTo($('.noUi-handle', sliders));

    var c = $('#red > span').clone(true);
    $('#red > span').remove();
    $('.noUi-base').prepend(c);

    sliders.noUiSlider.on('update', function( values ) {
        var val = parseInt(values);
        termCur = val;
        $('.value', sliders).text(termCur + ' zł');
    });
    $('#slider-amount-plus').click(function(e){
        if(termCur < 1100) {
            termCur = termCur + 50;
            sliders.noUiSlider.set(termCur);
            $('.value', sliders).text(termCur + ' zł');
        }
       e.stopPropagation();
    }).mousedown(function(e){
       e.stopPropagation();
    });
    $('#slider-amount-minus').click(function(e){
        if(termCur > 0) {
            termCur = termCur - 50;
            sliders.noUiSlider.set(termCur);
            $('.value', sliders).text(termCur + ' zł');
        }
    }).mousedown(function(e){
       e.stopPropagation();
    });

});


text:
Q: Basic Sublime Text Plugin Development: view.run_command('example') does not work I'm trying to use Will Bond's guide to creating a Sublime Text plugin (http://code.tutsplus.com/tutorials/how-to-create-a-sublime-text-2-plugin--net-22685).
Step 1 of the guide says to create a default plugin with the following code:
import sublime, sublime_plugin

class ExampleCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        self.view.insert(edit, 0, "Hello, World!")

This plugin gets saved as Prefixr.py in:
Sublime_Text_3_Location/Packages/Prefixr

I then type the following command into the Sublime Text console:
view.run_command('example')

And this should insert "Hello, World!" at the beginning of my currently viewed file.
However, when I enter the command, nothing happens. No "Hello, World!" appears in my file. Restarting Sublime Text does not fix it. Neither does running the command from different files.
Any idea why the command does not work?

A: I believe this didn't work for me at first because there were some other plugins "before" this one that were trying to import "sublimePlugin" which my ST3 Win7 instance didn't like.  I had to import "sublime_plugin".

A: I know this is way old but another stupid error I ran in to was that when I saved my file i accidently saved it as a py3 file and not a py file, duh!

redpajama_set_name: RedPajamaStackExchange


text:
Q: How Do I Open a New Webbrowser Tab in Vb.net application I have a Form1 with button1 and a webbrowser1. When I click on button1, I want to open a new web browser tab in the same form, not in Firefox or Internet Explorer or Chrome.
I tried using TabControl but am not sure how that works since it does not resize and its kind of annoying. I just want to open a new tab with web browser in the form.
Public Class Form1
  Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim wb As New WebBrowser
    wb.Navigate("www.google.com")
    Dim tab As New TabPage("Title")
    tab.Controls.Add(wb)
    TabControl1.TabPages.Add(tab)
    TabControl1.SelectedTab = tab
    tab.Size = New System.Drawing.Size(280, 174)
  End Sub
End Class

A: To add a new Tabbed browser, first u need to add a new Tab to your existing TabControl,
once the new Tab is added, then you need to add a new browser control into the created Tab
Private Sub btnAddTab_Click(sender As Object, e As EventArgs)
    Dim page As New TabPage(String.Format("Tab # {0}", tabControl1.TabPages.Count + 1))
    tabControl1.TabPages.Add(page)
    Dim browser As New WebBrowser()
    page.Controls.Add(browser)
    browser.Dock = DockStyle.Fill
    browser.Navigate(New Uri("http://www.google.co.in"))

End Sub

A: Create your own TabPage so that you can handle events and controls easly:
Public Class WBTab
    Inherits TabPage 'it actually is a tabpage
    Public WithEvents WB As New WebBrowser 'that has a single webbrowser in it
    Sub New(ByVal URL As String) 'when the page is created, show it and load the URL
        WB.Dock = DockStyle.Fill
        Me.Controls.Add(WB)
        WB.Navigate(URL)
    End Sub

    Private Sub WebBrowser1_DocumentCompleted(sender As System.Object, e As System.Windows.Forms.WebBrowserDocumentCompletedEventArgs) Handles WB.DocumentCompleted
        Me.Text = WB.DocumentTitle 'when the page is loaded you may now show its title in your tab.
    End Sub

    Private Sub WB_Navigating(sender As Object, e As System.Windows.Forms.WebBrowserNavigatingEventArgs) Handles WB.Navigating
        Me.Text = e.Url.ToString
    End Sub
End Class

Now it is ready to be used:
Dim google As New WBTab("google.com") 'create a new tab with URL
TabControl1.TabPages.Add(google) 'show it

A: This should work:
 Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim tabpage As New TabPage
    tabpage.Text = "New Tab"

    TabControl1.TabPages.Add(tabpage)

    Dim webBrowser As New WebBrowser
    TabControl1.SelectedTab = tabpage
    tabpage.Controls.Add(webBrowser)
    webBrowser.Dock = DockStyle.Fill
    webBrowser.Navigate("http://www.stackoverflow.com")
End Sub


text:
Q: Parse string/stringbuilder into class, how should I go about it? All the data I have to parse is currently stored into a StringBuilder and I would like to parse it into my class list:
StringBuilder data = new StringBuilder(length);

So I have my class assigned to a list:
public class Messages
{
    public DateTime Sent { get; set; }
    public string User {get; set; }
    public MessageType TypeUsed { get; set; }
    public string Message { get; set; }
}

public enum MessageType
{
    System,
    Info,
    Warn
}

public List<Messages> myList = new List<Messages>();

Now here are some messages samples that I need to parse:
[13:49:13] [System Message] <Username>  has openned blocked website
[13:49:14] <Username> accessed file X
[13:52:46] [System Message] <Username>  has entered this room
[13:52:49] [System Message] <Username>  has left this room

My doubt here is what would be the best way to parse it.
Time is present in all messages.
Usernaem is always with <>
When there is no [System Message] or [Warn Message] it is a Info type message.
Message is the rest example:
has left this room
accessed file X
has openned blocked website

Now here is where I am still thinking what to use.
I could use a regex to extract each string something like this:
Regex getData = new Regex(@"^\[(\d{1,2}:\d{1,2}:\d{1,2})\] \[([A-Za-z]+)\] ");

But then I would basicly need to make several checks for each message so I was not so confortable with it.
Tought about using split for example:
string line = item.Replace("[", "").Replace("]", "");
string[] fields = line.Split(' ');

and then I would check the split cases would be easy to detect the MessageType but not so reliable I think.
I would like some advices and ideas of how I could go along with this ?
Maybe I am just overcomplicating the logic :/

A: A regex is probably most convenient here. Try this one:
^\[(\d{2}:\d{2}:\d{2})\]\s*(\[(System|Warn)[\w\s]*\])?\s*<([^>]*)>\s*(.*)$

Translation:

*

*Starting at the beginning of the line, match [##:##:##] into capture group 1

*Then optionally match the System/Warn specifiers into capture group 2 and 3 (2 holds all the text in brackets, 3 only the System/Warn keyword)

*Then capture the username inside angle brackets into capture group 4

*And finally the message text in group 5

By testing the contents of group 2 or 3 for each line you know what type of message it is. All the other fields are ready to use straight from the capture groups.
Update:
Here's sample code as per the above:
var regex = new Regex(@"^\[(\d{2}:\d{2}:\d{2})\]\s*(\[(System|Warn)[\w\s]*\])?\s*<([^>]*)>\s*(.*)$");
var input = new[]
    {
        "[13:49:13] [System Message] <Username>  has openned blocked website",
        "[13:49:14] <Username> accessed file X",
        "[13:52:46] [System Message] <Username>  has entered this room",
        "[13:52:49] [System Message] <Username>  has left this room"
    };

foreach (var line in input) {
    var match = regex.Match(line);
    if (!match.Success) {
        throw new ArgumentException();
    }

    Console.WriteLine("NEW MESSAGE:");
    Console.WriteLine("     Time: " + match.Groups[1]);
    Console.WriteLine("     Type: " + match.Groups[2]);
    Console.WriteLine("     User: " + match.Groups[4]);
    Console.WriteLine("     Text: " + match.Groups[5]);

}


text:
Q: I trained Tensorflow object detection for letter detection but when using the infrance it somehow, detects cars I have followed step by step the Tensorflow Training Custom Object Detector with the goal in mind to detect letters, I've done everything by the book, but when running the inference_from_saved_model_tf2_colab.ipynb, it just return bboxes of cars(or maybe other things too that I'm not aware of), and does not detect letters at all...
this is the pretrained model I've used -ssd_resnet50_v1_fpn_640x640_coco17_tpu-8
someone have any idea about why this happened and what should I do?


text:
Q: XAML Binding Width of Listview Column I am loocking to get the same columns width on my two ListViews with binding, currently I found the tool of visual studio: "Create data Binding" and selecting ElementName and my ListView_Original but inside are too many properties and I cant found ColumnDefinition anyway:

I am trying using Width="{Binding Width, ElementName=ListView_FP, Source=Column_Number, Mode=OneWay}" without results but I guess I am near the solution.

What is the correct way to do a binding width of the ColumnDefinition
  of other Listview.

This is the original listview:
<ListView x:Name="ListView_Original" MaxHeight="400" HorizontalAlignment="Stretch" VerticalAlignment="Top" BorderBrush="Black" BorderThickness="1" Background="WhiteSmoke" SelectionChanged="ListView_Original_SelectionChanged" >
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        </Style>
    </ListView.ItemContainerStyle>
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid Padding="0" Margin="0" ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Auto">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="*" x:name="Column_Number"/>
                    <ColumnDefinition Width="*" x:name="Column_Name"/>
                    <ColumnDefinition Width="*" x:name="Column_Skill"//>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="40"/>
                </Grid.RowDefinitions>
                <TextBox Grid.Column="0" TextWrapping="Wrap" BorderBrush="Black" IsReadOnly="True" TextAlignment="Left" IsHitTestVisible="False" x:Name="TextBox_Number" Text="{Binding Path=Number}"/>
                <TextBox Grid.Column="1" TextWrapping="Wrap" BorderBrush="Black" IsReadOnly="True" TextAlignment="Center" IsHitTestVisible="False" x:Name="TextBox_Name" Text="{Binding Path=Name}"/>
                <TextBox Grid.Column="2" TextWrapping="Wrap" BorderBrush="Black" IsReadOnly="True" TextAlignment="Center" IsHitTestVisible="False" x:Name="TextBox_Skill" Text="{Binding Path=Skill}"/>
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

And this is the listview what its columns should do binding:
<ListView x:Name="ListView_Copy" MaxHeight="400" HorizontalAlignment="Stretch" VerticalAlignment="Top" BorderBrush="Black" BorderThickness="1" Background="WhiteSmoke" SelectionChanged="ListView_Copy_SelectionChanged" >
    <ListView.ItemTemplate>
        <DataTemplate>
            <Grid Padding="0" Margin="0" ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Auto">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="{Binding Width, ElementName=ListView_FP, Source=Column_Number, Mode=OneWay}"/>
                    <ColumnDefinition Width="{Binding Width, ElementName=ListView_FP, Source=Column_Name, Mode=OneWay}"/>
                    <ColumnDefinition Width="{Binding Width, ElementName=ListView_FP, Source=Column_Skill, Mode=OneWay}"/>
                </Grid.ColumnDefinitions>
                <Grid.RowDefinitions>
                    <RowDefinition Height="40"/>
                </Grid.RowDefinitions>
                <TextBox Grid.Column="0" TextWrapping="Wrap" BorderBrush="Black" IsReadOnly="True" TextAlignment="Left" IsHitTestVisible="False" x:Name="TextBox_Number" Text="{Binding Path=Number}"/>
                <TextBox Grid.Column="1" TextWrapping="Wrap" BorderBrush="Black" IsReadOnly="True" TextAlignment="Center" IsHitTestVisible="False" x:Name="TextBox_Name" Text="{Binding Path=Name}"/>
                <TextBox Grid.Column="2" TextWrapping="Wrap" BorderBrush="Black" IsReadOnly="True" TextAlignment="Center" IsHitTestVisible="False" x:Name="TextBox_Skill" Text="{Binding Path=Skill}"/>
            </Grid>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

Any help is appreciated.

A: x:Name property used in a DataTemplate are not available outside of it, so you have to going to bind the ColumnDefinition Width to a value that can be accesible by both ListView's DataTemplates.
I've created a sample based on your code that was able to get the same, dynamic width in both ColumnDefinitions using binding.
First, I have this shared DataTemplate for ListViews:
<Page.Resources>
    <DataTemplate x:Key="SimpleTemplate">
        <Grid>
            <Grid.ColumnDefinitions>
                <ColumnDefinition x:Name="MainDefinition" Width="{Binding ElementName=MainPageName, Path=SameWidth, Converter={StaticResource DoubleToGridLength}, Mode=OneWay}"/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>

            <SymbolIcon Symbol="Accept" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
            <TextBlock Grid.Column="1" Text="{Binding}" VerticalAlignment="Center" FontSize="16"/>
        </Grid>
    </DataTemplate>
</Page.Resources>

Then, my ListViews:
<ListView Grid.Row="1"
          ItemsSource="{x:Bind ListOneItems}"
          ItemTemplate="{StaticResource SimpleTemplate}"/>
<ListView Grid.Row="1"
          Grid.Column="2"
          ItemsSource="{x:Bind ListTwoItems}"
          ItemTemplate="{StaticResource SimpleTemplate}"/>

And the Page's code-behind:
private double _sameWidth;

public double SameWidth
{
    get { return _sameWidth; }
    set { _sameWidth = value; OnPropertyChanged(); }
}

public ObservableCollection<string> ListOneItems { get; set; }

public ObservableCollection<string> ListTwoItems { get; set; }

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    base.OnNavigatedTo(e);

    var text =
        @"Fugiat laborum cupidatat labore ad dolor officia Lorem ipsum cillum cupidatat dolore enim. Irure aliqua tempor non cupidatat est excepteur nisi labore magna nisi in consequat. Minim ex magna nulla deserunt ad. Proident pariatur deserunt ex voluptate proident irure. Dolore cillum dolor proident eu mollit amet nisi non velit sint.";
    var listOneWords = text.Split(' ').ToList().Take(10);
    var listTwoWords = text.Split(' ').ToList().Skip(10).Take(10);
    ListOneItems = new ObservableCollection<string>(listOneWords);
    ListTwoItems = new ObservableCollection<string>(listTwoWords);
    SameWidth = 48;
}

Also, you would need the DoubleToGridLengthConverter:
public class DoubleToGridLengthConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, string language)
    {
        var width = (double) value;
        var length = new GridLength(width);
        return length;
    }

    public object ConvertBack(object value, Type targetType, object parameter, string language)
    {
        throw new System.NotImplementedException();
    }
}

The final part is a Slider binded to SameWidth property that change the ColumnDefinition Width dynamically.
<Slider x:Name="MainSlider" Grid.ColumnSpan="2"
            Minimum="48"
            Maximum="120"
            Value="{x:Bind SameWidth, Mode=TwoWay}"/>

Hope this helps you!


text:
Q: Android fetching values from Firebase Database Hello so I've been strugging for awhile now. I want to consult someone about my code. I want to apply
a coloring function to my app.
When the person presses the button when it's at its:

*

*GREEN state it updates the value on the database to BEING HOUSEKEPT

*YELLOW state when pressed sends READY FOR INSPECTION RoomStatus

*RED state when pressed sends READY FOR HOUSEKEEPING RoomStatus
It was working earlier but when I tried to restrict the users that users who are Housekeepers can't access the RED STATE which are for House Keepers, I inserted somewhere in my code where I want to implement it.
I'm going over loops here can somebody tell me where I did wrong?
Here's my code:
        Button room1;
        private DatabaseReference mFirebaseDatabase, mFirebaseDatabase1, mFirebaseDatabase1room;
        private FirebaseDatabase mFirebaseInstance;
        private DatabaseReference referenceroom1;
        private  String roomStat;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_navi_to_scan2);
            mFirebaseInstance = FirebaseDatabase.getInstance();
            mFirebaseDatabase1 = mFirebaseInstance.getReference("Rooms");
            mFirebaseDatabase = mFirebaseInstance.getReference("Users");
            mFirebaseDatabase1room = mFirebaseInstance.getReference("Rooms").child("Room1");
            referenceroom1 = mFirebaseDatabase1.child("Room1").child("RoomStatus");

            room1 = (Button) findViewById(R.id.rm1Btn);

            mFirebaseDatabase1.child("Room1").addValueEventListener(new ValueEventListener() { //attach listener

                @Override
                public void onDataChange(DataSnapshot dataSnapshot) { //something changed!

                    for (DataSnapshot locationSnapshot : dataSnapshot.getChildren()) {
                        String location = locationSnapshot.getValue().toString();

                        if (location.equals("READY FOR HOUSEKEEPING")) {
                            room1.setBackgroundColor(Color.GREEN);
                            roomStat = "Green";
                        } else if (location.equals("BEING HOUSEKEPT")) {
                            room1.setBackgroundColor(Color.YELLOW);
                            roomStat = "Yellow";
                        } else {
                            room1.setBackgroundColor(Color.RED);
                            roomStat = "Red";
                        }

                        if (roomStat.equals("Green")) {

                            room1.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    String message = "BEING HOUSEKEPT";
                                    DatabaseReference reference = mFirebaseDatabase1.child("Room1").child("RoomStatus");
                                    reference.setValue(message);
                                    Intent next1 = new Intent(getApplicationContext(), ReaderActivity3.class);
                                    startActivity(next1);
                                }
                            });

                        } else if (roomStat.equals("Yellow")) {
                            room1.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    String message = "READY FOR INSPECTION";
                                    DatabaseReference reference = mFirebaseDatabase1.child("Room1").child("RoomStatus");
                                    reference.setValue(message);
                                    Intent next1 = new Intent(getApplicationContext(), ReaderActivity2.class);
                                    startActivity(next1);

                                }
                            });

                        } else {
                            room1.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                    String message = "READY FOR HOUSEKEEPING";
                                    DatabaseReference reference = mFirebaseDatabase1.child("Room1").child("RoomStatus");
                                    reference.setValue(message);
                                    Intent next1 = new Intent(getApplicationContext(), ReaderActivity.class);
                                    startActivity(next1);

                                    //I ALSO WANT TO PUT A CONDITION HERE FETCHING  userType from Structure
                                    // mFirebaseDatabase = mFirebaseInstance.getReference("Users").child("userKey");
                                    //but doing this would mean that I would have to put a listener inside, would that be okay? I tried when this
                                    //was working at first but it didin't and now the whole thing is not working

                                }
                            });

                        }
                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) { //update UI here if error occurred.

                }
            });

        }

Here's my structure:

Can you help me identify what's the problem with how i implemented this?

A: I see nothing wrong, try debugging. Android is buggy nowadays, especially when you're connecting to a cloud database. In the left side of the run button the bug shaped one. Debug.
Or maybe you could try to show your location which is your string, to check if you pulled the right info from your database. You can use logs. A guide can be found here
https://developer.android.com/studio/debug/am-logcat.html


text:
Q: Why do i get Name is not defined error for python when i defined it on another function? Why do i get the name is not defined error as shown below at the line "for character in SECRET_WORD:" even though earlier on in "def category" function that i have created, i defined SECRET_WORD to be SECRET_WORD = random.choice(word_list)?
  import random

    # Store the category and values into a dictionary
    categories = {
        "objects": ["tables", "ladders", "chairs"],
        "animals": ["chicken", "dog", "cat"],
        "sports": ["basketball", "soccer", "rugby"]

    }

    def category():
        print("Please enter category name: ")
        response = ''

        #Keep prompting the user to only enter allowed category values
        while response.lower() not in categories:
            # join(map(str, list((*categories,))) is used for retrieving the key values i.e. the category values from the dictionary "categories" and then join them as a string in order to display the allowed values back to the user
            response = input(' One among the following [%s] : \n' % ', '.join(map(str, list((*categories,)))))

        if response in categories:
            word_list = categories.get(response)
            # Print a random value from the chosen category
            print(random.choice(word_list)
            SECRET_WORD = random.choice(word_list)
            LENGTH_WORD = len(SECRET_WORD)
            GUESS_WORD = []
            ALPHABET = "abcdefghijklmnopqrstuvwxyz"
            letter_storage = []

    def prepare_secret_word() -> None:
        """Prepare secret word and inform user of it"""
        for character in SECRET_WORD: # <---------------- Name "SECRET_WORD" not defined error here"
            GUESS_WORD.append("-")
        print("Ok, so the word You need to guess has", LENGTH_WORD, "characters")
        print("Be aware that You can enter only 1 letter from a-z\n\n")
        print_word_to_guess(GUESS_WORD)

    # Call the function
    category()
    prepare_secret_word()

updated changes with my latest code (theres still error) shown below
  import random

category_lists = {
    "objects": ["tables", "ladders", "chairs"],
    "animals": ["chicken", "dog", "cat"],
    "sports": ["basketball", "soccer", "rugby"]

}

def category():
    print("Please enter category name: ")
    response = ''
    while response.lower() not in category_lists:
        # join(map(str, list((*categories,))) is used for retrieving the key values i.e. the category values from the dictionary "categories" and then join them as a string in order to display the allowed values back to the user
        response = input(' One among the following [%s] : \n' % ', '.join(map(str, list((*category_lists,)))))

    if response in category_lists:
        word_list = category_lists.get(response)
        # do what ever you want with the list
        SECRET_WORD = random.choice(word_list)
        LENGTH_WORD = len(SECRET_WORD)
        return SECRET_WORD
        return LENGTH_WORD

GUESS_WORD = []
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
letter_storage = []

def prepare_secret_word() -> None:
    """Prepare secret word and inform user of it"""
    SECRET_WORD = category()
    LENGTH_WORD = category()
    for character in SECRET_WORD: # printing blanks for each letter in secret word
        GUESS_WORD.append("-")
    print("Ok, so the word You need to guess has", LENGTH_WORD, "characters")
    print("Be aware that You can enter only 1 letter from a-z\n\n")

category()
prepare_secret_word()

A: You can make this:
def category():
    if response in categories:
        SECRET_WORD = random.choice(word_list)
    else:  # define else result
        SECRET_WORD = ''
    return SECRET_WORD

def prepare_secret_word():
    # get variable from function
    SECRET_WORD = category()
    for character in SECRET_WORD:
        #####

# run
prepare_secret_word()


text:
Q: Float to date in mysql We have a script that saves some rows in a table and one of them is filled with Time.now.to_f. So we have values like:
1330017921.1065
1330018520.80347
Is there a way to convert this to a date directly in MySQL I now I can use Time.at but I need a row mysql query.

A: i guess this is a microtime.
if you don't need milliseconds, you could query something like
SELECT * FROM table WHERE datefield = FROM_UNIXTIME(rounded_unixtime)

where rounded_unixtime would be in your case 1330017921


text:
Q: Can't read Amazon S3 Object meta-data using .Net API, what am I doing wrong? I've read the S3 documentation several times and I'm adding metadata to an S3 object with this code...
PutObjectRequest titledRequest = new PutObjectRequest();
titledRequest.WithTimeout(3600000)
.WithMetaData("outputfolder", outputFolder)
.WithBucketName(AWS_BUCKET_NAME)
.WithKey(objectKey)
.WithAutoCloseStream(true)
.WithInputStream(fs);

When reading the object from the S3 bucket I'm using this code....
string outputFolder = response.Metadata["x-amz-meta-outputfolder"];

But I'm getting an empty string every time even though the outputFolder variable definitely has a value.
Am I doing something really silly wrong here? As far as I can tell this is consistent with the documentation

A: string outputFolder = response.Metadata["outputfolder"];

will do.

A: use this instead of reading the meta from putobject response
GetObjectMetadataRequest request = new GetObjectMetadataRequest()
                    .WithKey("Key")
                    .WithBucketName("");
GetObjectMetadataResponse response = s3Client.GetObjectMetaData(request);
response."choose properety to retrieve"

hope this may help

A: Codes verified to work.
// upload & add outputfolder to metadata

var S3Client = new AmazonS3Client();

var Request = new PutObjectRequest {
                  BucketName = bucketname,Key = S3Name,FilePath = Filepath };

Request.Metadata.Add("outputfolder",@"C:\test");

PutObjectResponse Response = S3Client.PutObject(Request);

// download and retrieve metadata

var S3Client = new AmazonS3Client();

var Request = new GetObjectRequest { BucketName = bucketname,Key = S3Name };

GetObjectResponse Response = S3Client.GetObject(Request);

// this works

string outputFolder = Response.Metadata["x-amz-meta-outputfolder"];

// so does this - no need for the x-amz-meta- prefix

string outputFolder = Response.Metadata["outputfolder"];


text:
Q: Branches diverged after pull instead of push I accidentally did git pull instead of git push and got a merge conflict. I was surprised that git tried a merge at all, because the remote branch didn't receive any commits since my last pull/push. Since I didn't want to do a pull/merge, I did git reset --hard followed by git merge --abort. I tried to push, but got the message:
On branch my_branch
Your branch and 'origin/my_branch' have diverged,
and have 17 and 1 different commit each, respectively.
  (use "git pull" to merge the remote branch into yours)
nothing to commit, working directory clean

How can I get back to the state before the accidental pull to be able to push my local commits to the remote branch?

A: your remote did get a commit pushed. You can have a look at the git tree using this command:
git log --all --graph --decorate --oneline

maybe you did a git commit --amend or something like that on the one commit that is already on the remote. Analyse the output of the command above (and post it maybe in your question) to see which commit you want to keep.
Since you are working on your personal branch, you might consider (note that this is not ideal) to crush your (1) remote commit with your (17) local commits, using
git push -f

WARNING: in this case you will "lose" that one remote commit.
If you want to keep that one remote commit, you might consider first rebasing your local work onto that commit, before pushing
git rebase origin/my_branch
git push


text:
Q: JSON accessing array objects using a named index Suppose I have this HTML
<form action="#" action="get">

    <select name="college" id="college" onchange="selection('college', 'course')">
        <option value="">Select an Option</option>
        <option value="amity">Amity University</option>
        <option value="indraprastha">Indraprasth University</option>
    </select>

    <select name="course" id="course" onchange="selection('course', 'stream')" >
        <option value="">Select an Option</option>
    </select>

    <select name="stream" id="stream">
        <option value="">Select an Option</option>
    </select>

</form>

I have this JSON,
{
  "amity":{
    "course":[
      {
        "name":"B.Tech",
        "value":"btech",
        "stream":[
          {
            "name":"Computer Science",
            "value":"cse"
          },
          {
            "name":"Information Technology",
            "value":"cse"
          },
          {
            "name":"Aerospace Engg.",
            "value":"cse"
          }
        ]
      },
      {
        "name":"M.Tech",
        "value":"mtech",
        "stream":[
          {
            "name":"Networking",
            "value":"net"
          },
          {
            "name":"telecommunications",
            "value":"tc"
          }
        ]
      }
    ]
  }
}

The Javascript is,
function selection(s1, s2) {
    var first = document.getElementById(s1),
        second = document.getElementById(s2);

    var college = $('#college').val(),
        cr = $('#course').val(),
        st = $('#stream').val(),
        se = $('#sem').val();

    $.getJSON("json/select.json", function(data) {

    switch(s1) {
        case 'college':
            $.each(data[college].course, function(key, value) {
                second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
            }); break;

        case 'course':
            $.each(data[college].course[].stream, function(key, value) {
                second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
            }); break;
    }
});
}

I am making a dynamic drop-down menu where the next drop down values are fetched from JSON object file, using the reference of previous values. As suggested from my this question (link), I am able to get the value of course (second drop-down) using the course array in the object.
Now, since the values in the second select menu(course) are filled dynamically, I can't figure out how to take the corresponding course array element to fill the next select menu options for stream array.
Since the course property in JSON is an array, I don't know which index element element is chosen from second menu (See the switch case for 'course', the data[college].course[] index is empty). The hardcoded [0] works, but that's not dynamic then.
How to access the stream array using the values of course grabbed from second menu.
I hope I am clear. Thanks in advance!

A: Just iterate through array of courses to get the stream dynamically:
for (var i = 0; i < data[college].course.length; i++) {
    currentStream = data[college].course[i].stream;
}

I.e. using your code:
for (var i = 0; i < data[college].course.length; i++) {
    $.each(data[college].course[i].stream, function(key, value) {
        second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
    });
}

Finding the current stream for your selected course:
// assuming cr = "btech"
for (var i = 0; i < data[college].course.length; i++) {
    if (data[college].course[i].value == cr) {
        currentStream = data[college].course[i].stream;
        break;
    }
}

$.each(currentStream, function(key, value) {
    second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
});

A: function selection(s1, s2) {
var first = document.getElementById(s1),
    second = document.getElementById(s2);

var college = $('#college').val(),
    cr = $('#course').val(),
    st = $('#stream').val(),
    se = $('#sem').val();

$.getJSON("json/select.json", function(data) {

switch(s1) {
    case 'college':
        $.each(data[college].course, function(key, value) {
            second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
        }); break;

    case 'course':
        var course = data[college].course;
        for(var i = 0;i<course.length;i++){
            if(course[i].name === cr){ //cr is selected option
                $.each(course[i].stream, function(key, value) {
            second.innerHTML += '<option value="'+ value.value +'">'+ value.name +'</option>';
            }
        }

        }); break;
}

});
}


text:
Q: MongooseIm Rest API connection issue with local Setup I have setup the mongooseim [3.3.0] ubuntu 14.04 & it works perfect with android client setup. Then I need to test the REST API for creating room , Then I have got this error when running the swagger documentation.
curl -X GET --header 'Accept: application/json' --header 'Authorization: Basic dXNlcjpwYXNzd29yZA==' 'http://localhost:8089/api/rooms'

curl: (52) Empty reply from server

This is the mongooseim configs which related to REST API.
{ 8089 , ejabberd_cowboy, [
      {num_acceptors, 10},
      {transport_options, [{max_connections, 1024}]},
      {protocol_options, [{compress, true}]},
      {ssl, [{certfile, "priv/ssl/fake_cert.pem"}, {keyfile, "priv/ssl/fake_key.pem"}, {password, ""}]},
      {modules, [
          {"_", "/api/sse", lasse_handler, [mongoose_client_api_sse]},
          {"_", "/api/messages/[:with]", mongoose_client_api_messages, []},
          {"_", "/api/contacts/[:jid]", mongoose_client_api_contacts, []},
          {"_", "/api/rooms/[:id]",    mongoose_client_api_rooms, []},
          {"_", "/api/rooms/[:id]/config",    mongoose_client_api_rooms_config, []},
          {"_", "/api/rooms/:id/users/[:user]",    mongoose_client_api_rooms_users, []},
          {"_", "/api/rooms/[:id]/messages",    mongoose_client_api_rooms_messages, []}
      ]}
  ]}

This is the swagger document I have referred. https://mongooseim.readthedocs.io/en/3.3.0/swagger/index.html

A: I noticed the following things:

*

*The curl example you provided tries to send the request to MongooseIM over HTTP

*Based on the part of the config file you provided I can see that MongooseIM expects HTTPS traffic.

It looks like changing the endpoint in your curl command to https://localhost:8089/api/rooms will help. Of course, if you run the command on the same machine as MongooseIM is running. Otherwise, please change the localhost to a proper name or IP address of the machine.
What's more, in the config file I can see that the REST API is configured with the default, fake and self-signed certificates. I strongly encourage you to change it to real certificates. For the sake of testing, you will need to add the option -k to your curl command in order to skip cert verification.


text:
Q: Parse out a value from json in swift I am trying to parse out a int value in the variable but its returning nil or 0 The value I want is from the customer_group_id. I am using swift. I have parsed out other information from the json file, but it keeps messing up at this stage.
  print("My Loyalty rank: " , newJson["loyalty_rank"][0]["customer_group_id"].string)
  myRank = newJson["loyalty_rank"][0]["customer_group_id"].intValue

Here is the json file
{ "id":298,
  "name":"桃子 桜",
  "total_points_earned":164,
  "points_available_to_spend":164,
  "loyalty_rank":{
       "customer_group_id":9,
       "name":"Baby Bee",
       "ratio":1
   },
  "order_history":[
  { }
  ],
 "barcode_id":"C-00000298"
 }

A: loyalty_rank is [String:AnyObject] means its Dictionary not an array ...
try to print it like
     // if its string
     print("My Loyalty rank: " , newJson["loyalty_rank"]["customer_group_id"].string)

     // if its Int
     print("My Loyalty rank: " , newJson["loyalty_rank"]["customer_group_id"].intValue)

Better to use if let or guard like
    if let customerId = newJson["loyalty_rank"]["customer_group_id"].intValue{
        // customerId is int value
   }
   else{
       // not an int
   }


text:
Q: Trigger an event when a set of images are loaded I am loading images dynamically with JQuery. Some images can be big and I don't want to show any images unless all the images are completely loaded. So I have something like :
$('#mydiv img').load(function ()
{
    $('#mydiv').animate(
    {
        'width' : data.width,
        'height' : data.height
    },800);

    $('#loading').remove();
});

So I though this would mean "when all the images in "mydiv" are loaded, resize the div and remove the "loading" item". But now I think that it actually means "when AT LEAST ONE image is loaded...".
Then how can I solve my problem?

A: What you need is a variable outside the scope that keeps count when an image finishes loading
var fin = 0;

Then on each load function() you increment.
$('#mydiv img').load(function ()
{
    fin++;
    if(fin == $('#mydiv img').length){
       $('#mydiv').animate({
           'width' : data.width,
           'height' : data.height
       },800);
       $('#loading').remove();
    }
});

A: This would reside in a triggered event. For example a click event:
Blanco
var all_loaded = true;

$('#mydiv img').each(function() {
    $(this).error(function (){
        all_loaded = false;
    });
})

if (all_loaded) {
    $('#mydiv').animate({'width' : data.width, 'height' : data.height},800);
    $('#loading').remove();
}

With click event
$('#myButton').click(function() {
    var all_loaded = true;

    $('#mydiv img').each(function() {
        $(this).error(function (){
            all_loaded = false;
        });
    })

    if (all_loaded) {
        $('#mydiv').animate({'width' : data.width, 'height' : data.height},800);
        $('#loading').remove();
    }
});

If you really want the code to wait until all images you are loaded (which is dangerous to create an infinite loop), you can just keep re-looping the .each() until all_loaded is not longer equal to false. Like;
while (all_loaded !== true) {
    var all_loaded = true;

    $('#mydiv img').each(function() {
        $(this).error(function (){
            all_loaded = false;
        });
    })

    if (all_loaded) {
        $('#mydiv').animate({'width' : data.width, 'height' : data.height},800);
        $('#loading').remove();
    }
}

Updated version
$('#myButton').click(function() {
    var all_loaded = false;

    while (all_loaded !== true) {
        var all_loaded = true;

        $('#mydiv img').each(function() {
            $(this).load().error(function (){
                all_loaded = false;
            });
        })

        if (all_loaded) {
            $('#mydiv').animate({'width' : data.width, 'height' : data.height},800);
            $('#loading').remove();
        }
    }
});

A: The code below will add an attribute 'data-loaded' for each loaded image. It will then check if the number of loaded images equals the number of images in #mydiv and execute the animation only after the last image is loaded:
$('#mydiv img').load(function ()
{
    $(this).attr('data-loaded', '');
    if ($('#mydiv img[data-loaded]').length == $('#mydiv img').length)
    {
        $('#mydiv').animate(
        {
            'width' : data.width,
            'height' : data.height
        },800);

        $('#loading').remove();
    }
});


text:
Q: Componente não atualiza Estou criando um componente Vue de gráfico do Plotly. No carregamento inicial o componente é carregado com os valores iniciais corretos, mas quanto atualizado a propriedade do componente, ele não é atualizado.
Componente:

<template>
    <div
    ref="plot1"
    id="plot1"
    ></div>
</template>

<script>
  import * as Plotly from 'plotly.js'

  export default {
    name: 'graph',
    props: ['plot_data'],
    data: function () {
      return {
        data_plot: this.plot_data,
        layout: { },
      }
    },
    methods: {

    },
    mounted () {
      Plotly.plot(this.$refs.plot1, this.data_plot, this.layout, { displayModeBar: false })
    },
  }

</script>

Página que insere o componente:
<graph
              :plot_data="data_plot"
              :layout="layout"
              :display-mode-bar="false"
></graph>

import graph from './component/Graph.vue'

...

data () {
      return {
      ....
        data_plot: [{ x: [3, 2, 1], y: [3, 2, 1], type: 'scatter' }],
      }
    },

      send_site: function () {
        console.log(this.$refs.tuple_ann.value)
        var data = new FormData()
        ....
        axios.post('http://localhost:8000/api_app/ann/', data, { headers: { 'Content-Type': 'multipart/form-data' } })
          .then((response) => {
            ....
            this.data_plot = [{ x: response.data.x, y: response.data.y, type: 'scatter' }]
          })
      },

A variável data_plot é atualizada corretamente após o request, mas o componente "graph" não é atualizado. O que poderia ser?
Obrigado.

A: Resolvi o problema adicionando o atributo key="data_plot" no .
<graph
  :plot_data="data_plot"
  :key="data_plot"
  :layout="layout"
  :display-mode-bar="false"
></graph>


text:
Q: Is there a system that generates ID strings for the purpose of high probability error correction with minimal length? I need a system that generates IDs to be printed, sent out, and later reentered into our database. The forms are usually faxed in and out and therefor some fidelity is lost. I need the IDs to be as short as possible to minimize the work to be done manually reentering them, but they need to be unique enough to allow for automatic error correction.
I have worked with fuzzy search before and understand the concept of probabilistic matching, but not with unique IDs that I am generating for that purpose.
Edit: I think that several of you had a very good point about the QR code which has very robust error correction built in. Eventually, we will move to that type of solution, but for now, the IDs need to be human readable.
Yes, they could simply be printed bigger, or multiple times on different parts of the paper. However, that is not the solution that I have been asked to research/develop and it does not handle human error when typing in the code.

A: *

*Firs, of course, I suggest you to use bar-code or qr-code, if you print your form yourself.

*If [1] is not possible - I suggest you select from alphabet special subset of character, aren't like each to others in drawing - it will decrease error probability after scanning.
For example, for numbers 0-9 lets you use ABCEHJKLNO; There is removed
D->C, F->E, G->C, I->J, M->H; And, when you receive "M" - convert it to "H", and so on. This is simple "OCR error correction code".

*Add one char = checksum. This is some "hash(ID) % 10" for base 10 numbers.


text:
Q: pic16f877A bootloader error I have installed bootloader into my pic16f877A and now i am trying to write a  program into pic.But after connecting to my computer it gives error as
 Connected to \\.\COM1 at 115200
 Searching for PIC ...
 pic sending unknown data:  "K" <>  0h=
 Check baudrate & Start Write while PIC is not sending serial data (e.g. in reset)
 ERROR!

I am using tiny bootloader to program pic16f877A.
I have used this blog https://alselectro.wordpress.com/2014/10/01/pic-boot-loaderno-programmer-required-to-fuse-hex-file/#comment-1159 for instructions to install bootloader.
Have checked my connections but not able to understand whats the problem.I also checked my pic16f877A voltages and found that at pin26(Rx) i am getting high voltage(+5) and pin25 (Tx) is zero.
My max232 capacitor connections are same as in the blog.I also wanted to know how can i make sure that bootloader is successfully installed and working fine.
Now i am getting following error:
 Connected to \\.\COM1 at 115200
 Searching for PIC ...
 Wait 200 ms
 Rcv:type= 0h=Not found,
 ERROR!

my rs232 connection:


text:
Q: jQuery bind event not firing on elements loaded via $().load() I have a DIV that is in an .html file that is loaded into my document via:
$(document).Ready( function() {
    $("#contentDiv").load("some.html")

    //some.html contains a button id=saveButton
    $("#saveButton").click( function () {
        alert("Here I am!");
    }

});

The event will not fire.  If I cut the content of some.html and put it in the document, uhm, "physically", the event will fire.
So, I am pretty sure this issue is related to the fact that the html is injected via .load().
It's bothersome, because if you look at the page source, all the HTML is in fact there, including the button.
So, the question is, is there ANY way to make this work?  I am using .load() to reduce page complexity and increase readability, and, code-folding notwithstanding, I really do not want to have to pull all this HTML into the document.
EDIT: This code was just typed in off the cuff.  It's not a cut-n-past of the actual code, and it is just to demonstrate what the problem is.  But, thanks for pointing it out.
EDIT2:  Grrrrrrr.  });

A: load() is asynchronus so you need to the job in the callback :
$(document).ready(function() {
    $("#contentDiv").load("some.html", function(){
        //some.html contains a button id=saveButton
        $("#saveButton").click( function () {
            alert("Here I am!");
        });
    });
});

Hope it helps :)

A: one way is by adding to the some.html the script line which will be loaded as the div appears.
You can add this script to some.html(in a script tag):
registerButton();

and then you can define registerButton() in your current document.
other way, if I remember correctly is by using something like the function bind( )

A: jquery load() function is asynchronous. If you want to bind events to the loaded content, you should put the code into the callback function:
$(document).ready(function() {
    $("#contentDiv").load("some.html", function() {
        //you should put here your event handler
    });

});

A: If you want to fire event on element which was not available at the time when DOM was ready then you need to use .on event.
http://api.jquery.com/on/
$("#saveButton").on("click", function() {
      alert("Here I am!");
});

A: Your issue is that jquery load() function is asynchronous as @lucas mention. But his code has syntax errors, try this:
    $(document).ready(function () {
        $("#contentDiv").load("some.html", function () {
            $("#saveButton").click(function () {
                alert("Here I am!");
            });
        });
    });

Hope it helps now

A: You need to bind the event handler either after the load OR to the container of the HTML from the load
$(document).ready(function() {
  $("#contentDiv").load("some.html", function() {
    $("#saveButton").on('click',function() {
      alert("Here I am! Bound in callback");
    });
  });
});

OR use: (not needed that it be in the document ready just that the contentDiv be present)
$("#contentDiv").on('click','#saveButton',function(){
     alert("Here I am! bound to container div");
});

EDIT: load on the SAVE button click (per comments) (this makes no sense though)
$(document).ready(function() {
  $("#saveButton").on('click',function() {
    $("#contentDiv").load("some.html", function() {
      alert("Here I am! Bound in callback");
    });
  });
});


text:
Q: Iterative renormalizations of a rotation (Underlying job: I am trying to construct an adic representation of a rotation.)
The question involves an iterative construction. At step $n$, one constructs a partition $P_n$ of $(0,1)$ and a map $\beta_n \colon (0,1) \to (0,1)$ (it could be clearer to use some indices:  $\beta_n \colon (0,1)_n \to (0,1)_{n+1}$). Roughly speaking this construction will allow to define a sequence of labels $P_n(x_n)$ of a point $x \in (0,1)$, and the problem is to retrieve $x$ from this sequence.
(n=1) Let $T_1$ be a rotation with irrational step $\theta \in (0,\frac12)$ and define the interval $J=(1-\theta,1)$.  The integer $a= \lfloor \frac{1}{\theta} \rfloor -1 \geq 1$ is the smallest integer such that $(0,1)$ is covered by $J$, $T_1(J)$, $\ldots$, $T_1^{a+1}(J)$.
One has the periodic approximation of $T_1$ shown by the following tower decomposition with base $B=(a\theta, 1) = J \cup T_1^{a+1}(J)$:

Denote by $P_1$ the partition of $(0,1)$ whose blocks can be seen in the picture:
$$
P_1 = \bigl\{J, T_1(J), \ldots, T_1^a(J), (a\theta, 1-\theta)\bigr\}.
$$
The orbits of this periodic approximation define an equivalence relation: each point in $x\in J$ is glued with $T_1(x)$, $\ldots$, $T_1^a(x)$, and the class of a point $x \in (a\theta, 1-\theta)$ is the singleton $\{x\}$. We take the base $B$ as the set of representatives, and for every $x \in (0,1)$, we denote by $d_1(x) \in B$ the representative of the class of $x$.
Now, the transformation induced by $T_1$ on $B$ is isomorphic to a rotation $T_2$ with irrational step
$$
\theta'=\frac{\theta}{1-a\theta}=\frac{1}{1+G(\theta)} > \frac{1}{2}
$$
where $G$ is the Gauss function. The isomorphism $g_1\colon B \to (0,1)$ between the induced transformation and $T_2$ is the natural affine map. The map $\boxed{\beta_1=g_1 \circ d_1}$ sends the action space of $T_1$ to the action space of $T_2$.
(n=2) We proceed as before with $T_2$ and $J = (0, 1-\theta')$. This is the similar construction for the case of a step ($\theta'$) in $(\frac12, 1)$. This time, setting $\phi=1-\theta'$, one has a tower decomposition with base $B = (0, 1-a\phi)$, where $a = \lfloor \frac{1}{1-\theta} \rfloor -1$.

And we have the partition of $(0,1)$:
$$
P_2 = \bigl\{J, T_2(J), \ldots, T_2^a(J), (\phi, 1-a\phi)\bigr\},
$$
and the representatives $d_2(x) \in B$.
Now, the transformation induced by $T_2$ on $B$ is isomorphic to the rotation $T_3$ with irrational step
$$
\frac{1-(a+1)\phi}{1-a\phi}=\frac{G(\phi)}{1+G(\phi)} < \frac{1}{2},
$$
we denote by $g_2$ the isomorphism (affine map) and we set $\boxed{\beta_2=g_2 \circ d_2}$.
(n) We can continue so on. We get the partitions $P_n$ and the maps $\beta_n$.
My question is the following one.
Denote $x_1=x$, $x_2= \beta_1(x_1)$, $\ldots$, $x_{n+1}=\beta_n(x_n)$, $\ldots$.
Do we know (almost) every $x \in (0,1)$ if we know the block $P_n(x_n)$ of the partition $P_n$ to which $x_n$ belongs for every $n$ ?

A: Yes, this is how we got it - but then it was left out because it was too bulky if my memory serves me. A short English version can be found in Section 3 of my survey http://www.maths.manchester.ac.uk/~nikita/ad.pdf
The following papers may be also useful: http://link.springer.com/article/10.1007/BF02788235
http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.662.3253&rep=rep1&type=pdf

A: I get the idea. Apply the second cut-and-stack to the first tower decomposition. This is shown on this picture (where I denote $x_n$ instead of $P_n(x_n)$):

An important point: $(3\theta, 1-\theta)$ goes to $(0, \phi)$ by the affine map $g_1$.
The value of $P_2(x_2)$ corresponds to one of the black pieces surrounded by a red line. If it is $1$, one necessarily has $P_1(x_1)=0$. Otherwise, one necessarily has $P_1(x_1)\neq 0$, and the value of $P_1(x_1)$ corresponds to one of the intervals in the black piece selected by $P_2(x_2)$.
Thus, knowing $P_1(x_1)$, one knows an interval $I_1(x)$ to which $x$ belongs. Then, knowing in addition $P_2(x_2)$, one knows an interval $I_2(x) \subset I_1(x)$ to which $x$ belongs. It is possible that $I_2(x)=I_1(x)$ (when $x \in (3\theta, 1-\theta)$) but in this case one has a strict inclusion $I_3(x) \subset I_2(x)$ when we continue at step $n=3$. Continuing so on, one gets intervals $I_n(x) \ni x$ whose lengths go to $0$, and $I_n(x)$ is given by $P_1(x_1)$, $\ldots$, $P_n(x_n)$. Finally one knows $x$ if one knows all the $P_n(x_n)$.


text:
Q: ASP.NET MVC 3, Action Filters, and Autofac Dependency Injection On ASP.NET MVC 2 I have an ActionFilterAttribute called [Transaction] that starts an NHibernate transaction before executing the action and commits or rolls it back afterward, depending on whether or not an exception was thrown. The ISession instance is HttpRequestScoped() and injected by Autofac. It looks like this and works great:
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class)]
public sealed class TransactionAttribute : ActionFilterAttribute
{
    private ITransaction transaction;

    public TransactionAttribute()
    {
        this.Order = 0;
    }

    public ISession Session
    {
        get;
        set;
    }

    public override void OnActionExecuted(
        ActionExecutedContext filterContext)
    {
        if (this.Session != null && this.transaction != null)
        {
            try
            {
                if (this.transaction.IsActive)
                {
                    if (filterContext.Exception == null)
                    {
                        this.transaction.Commit();
                    }
                    else
                    {
                        this.transaction.Rollback();
                    }
                }
            }
            finally
            {
                this.transaction.Dispose();
                this.transaction = null;
            }
        }
    }

    public override void OnActionExecuting(
        ActionExecutingContext filterContext)
    {
        if (this.Session != null)
        {
            this.transaction = this.Session.BeginTransaction();
        }
    }
}

Fantastic. Seems to be a common pattern.
In the ASP.NET MVC 3 notes, I see this little blurb under "Breaking Changes" (emphasis mine):

In previous versions of ASP.NET MVC, action filters were created per request except in a few cases. This behavior was never a guaranteed behavior but merely an implementation detail and the contract for filters was to consider them stateless. In ASP.NET MVC 3, filters are cached more aggressively. Therefore, any custom action filters which improperly store instance state might be broken.

Oops.

*

*Does this mean I'm hosed if I upgrade to MVC 3?

*If action filters are no longer instanced per request, how will we get request-scoped dependencies into our action filters?

Thanks for any insight.

A: I just asked a similar question on google forums.
Here is the link https://groups.google.com/forum/#!topic/autofac/a0qqp2b3WA8
I got the answer:
builder.RegisterType<ExtensibleActionInvoker>().As<IActionInvoker>();

builder.RegisterControllers(Assembly.GetExecutingAssembly()).InjectActionInvoker();

Then you can use property injection in your attributes.

A: Oh yuck.... Nicholas, you might need to store your ISession and Transaction in HttpContext.Items, which you should be able to get to via the ActionExecutedContext/ActionExecutingContext (perhaps setting it in the OnActionExecuting event handler), instead of keeping them in instance members.  Either that, or you could call a ServiceLocator inside your filter to grab them for you (also yuck).
Now I have to go look through my MVC 3 code and see if I have any similar problems myself!


text:
Q: Android Realm Insert on conflict ignore Does anyone know a way how to solve a problem?
I need to implement data storage with Realm.
I receive from network JSON object convert him to realm object Card and save it. I expand Card object with extra field favorite and change it manually from an application.
Every time when network operation executes insertOrUpdate wipes value, and insert throws an exception 'RealmPrimaryKeyConstraintException' because I have @PrimaryKey definition.
Is there exist in Realm feature how to use an insert with a particular update on Insert with Ignore?

A: Card card = realm.where(Card.class).equalTo(CardFields.ID, cardId).findFirst(); // https://github.com/cmelchior/realmfieldnameshelper
if(card == null) {
    card = realm.createObject(Card.class, cardId);
}
card.setFavorite(true);

Or
Card card = realm.where(Card.class).equalTo(CardFields.ID, cardId).findFirst(); // https://github.com/cmelchior/realmfieldnameshelper
if(card == null) {
    card = new Card();
    card.setId(cardId);
}
card.setFavorite(true);
realm.insertOrUpdate(card);

Basically, if you don't want to overwrite the object, then you should query it and manipulate it, otherwise create it.


text:
Q: Is Bose-Einstein condensation a quantum phase transition? Classical phase transitions are driven by thermal fluctuations which die out at $T = 0$, hence classical phase transitions don't happen at zero temperature. Quantum phase transitions are driven by quantum fluctuations which prevail at $T = 0$ and thus can lead to macroscopic change in the system (quantum phase transition). This is the case in the superfluid-Mott insulator transition in the Bose-Hubbard model, for example, which is due to interactions.
Bose-Einstein condensation (BEC) is a consequence of quantum statistics, it is not directly related to any microscopic parameter in the hamiltonian. A real phase transition (not a crossover) from classical thermal gas to a condensate happens at non-zero temperature. This suggests that BEC is a classical phase transition. Contrary, in Subir Sachdev's book I find a graph (Fig 16.4) that suggests BEC is a quantum phase transition like any other, with a quantum critical point at $T = 0$ and $\mu<0$. As a specific example, we could consider a weakly-interacting Bose-gas in three dimensions.
In other words, what is the defining feature of a quantum phase transition: Either it happens only at $T = 0$ or it happens not only at $T > 0$ but also at $T = 0$?

A: The terminology is an absolute mess. The way I think about it, the defining feature of a quantum phase transition is:

A quantum phase transition is a phase transition that takes place in a system that lives in $d$-dimensional space, but whose universal properties are described by a $(d+1)$-dimensional field theory.

(If your immediate reaction is "The terminology 'quantum phase transition' does not at all convey that idea!" ... then you're right.)
Consider an infinitely large quantum system (at any temperature, zero or otherwise) that is near, but not necessarily at, a phase transition. Its equilibrium statistical properties are described by fields on a $(d+1)$-dimensional space that is given by the Cartesian product of the (infinitely large) actual spatial manifold $M$ times a compactified (i.e. periodic, and so finite) dimension called the "imaginary time" dimension, whose "circumference" (periodicity) is the inverse temperature $\beta$. Away from the transition, the quantum effects are certainly important even at finite temperature, as the corresponding classical system is described by a completely different $d$-dimensional field theory with no imaginary time direction.
However, very close the transition, the correlation length $\xi$ diverges. In particular, if the temperature is greater than zero and so $\beta$ is finite, then as you get very close to the transition, the correlation length inevitably eventually becomes much larger than $\beta$. In this case, the field value gets "locked" to a single value as you circle around the imaginary time direction, and that degree of freedom effectively drops out. So the dynamically fluctuating fields only live on the infinitely large spatial manifold $M$, just as in the classical case. So (only when you are extremely close to the transition), the imaginary time dimension becomes unimportant and the quantum statistical properties become identical to that of the corresponding classical critical system. That's why phase transitions of quantum systems at finite temperature are called "classical"; they are "actually" quantum, but the quantum effects do not affect the universal properties that are captured by field theory.
But for a quantum phase transition that occurs at zero temperature, the imaginary time period $\beta$ is infinite, so it actually isn't periodic at all; the imaginary time direction is simply another infinitely large dimension. If the dynamical exponent $z = 1$, which is often the case, then the imaginary time dimension is more or less on the same footing as the $d$ spatial dimensions, up to unimportant constants.
That's why the Mermin-Wagner theorem sometimes allows spontaneous symmetry breaking at one lower spatial dimension than usual at zero temperature (e.g. spontaneous breaking of continuous symmetries in $d = 2$ spatial dimensions); the infinitely large quantum imaginary time dimension effectively gives you a third dimension to play with. In a completely classical system, nothing unusual would happen at zero temperature, and no new types of spontaneous symmetry breaking would become allowed as they do in the quantum case.
What's really going on here under the hood is that there are three relevant length scales that all formally go to infinity at a zero-temperature quantum phase transition: the spatial system size $L$, the inverse temperature $\beta$, and the correlation length $\xi$. In any real system, none of these three will be literally infinite, and which field theory accurately describes the statistical physics depends on their relative ratios. In the regime $L, \beta \gg \xi$, it's a $(d+1)$-dimensional quantum field theory and a quantum phase transition; in the regime $L \gg \xi \gg \beta$ it's a $d$-dimensional classical field theory and a classical phase transition; and in the regime $\xi \geq L$ you can't really use field theory at all, and you're screwed.

A: As I understand it, the terminology "quantum phase transition" is used for a change in the ordering/structure of a system at absolute zero temperature (therefore also zero entropy) taking place owing to a changing external parameter such as volume or applied field or something like that. BEC in three dimensions is not like that. It is a change taking place at some non-zero temperature, as a parameter such as density or temperature is changed. It has a critical point at a finite temperature. The order parameter starts to grow abruptly as the temperature passes through the critical point. Therefore it is not a quantum phase transition.
(In a preliminary treatment of BEC one may take as order parameter the ground state population. In more advanced treatments one uses other things such as measures of correlations.)
Finally, a remark on terminology. I think it is a pity the terminology got formed the way it did, because it suggests that there is something extra-quantum about systems at zero temperature, when this is not true. Systems are quantum no matter what their temperature, and quantum physics often has something useful to add to the discussion of phase transitions at any temperature (BEC being a particularly telling example). Also, when you read statements that phase transitions are "driven by" fluctuations I often wonder in what sense the word "driven" is being used. For a quantum phase transition, the change in the system's ground state is owing to the change in the Hamiltonian, so it is not "driven" in the sense of "caused" by anything other than that. So in what sense is the word "driven" being used? (Thus my answer  finishes with a query back to the questioner, but I hope others will comment).

A: When talking about the BEC transition, one usually thinks of the finite-temperature phase transition that happens in 3D for interacting bosons. This transition is in the universality class of the 3D classical XY model, and describes the transition between a normal gas and a BEC. More generally, in $d\geq 2$, it is a classical transition between a normal gas and a superfluid.
This, of course, does not qualify as a quantum phase transition, as defined by a transition between two phases of matter that happens at zero-temperature when a non-thermal parameter is varied. (Side note: a transition that happens at finite-temperature when changing a non-thermal parameter does NOT qualify as a quantum phase transition either.)
The transition discussed by Sachdev is indeed a quantum phase transition, between the vacuum (empty system), and a BEC (more generally, in $d\geq 1$, between the vacuum and a superfluid). While this is indeed a transition from a non-condensed state to a BEC, it is of a completely different nature than the finite-temperature BEC. First, the critical point is somewhat trivial, since it corresponds to an empty state (with zero chemical potential), and all its properties can be computed somewhat easily. (For instance, the propagator is not renormalized, and is thus the one of a free non-relativistic particle, with dynamical exponent $z=2$.) Second, its universality class is a new one, sometimes called the dilute Bose gas universality class. However, it is interesting to consider, because it also describes other quantum phase transitions, both for strongly interacting bosons in the context of the Mott transition with non-conserved density (the so-called generic transition), and a transition in quantum XY spin models in presence of a transverse magnetic field. Finally, this quantum critical point influences the shape of the phase diagram at low enough temperature, and is the terminal point of the critical line of the finite-temperature BEC transition as one lowers the chemical potential.

A: Bose-Einstein condensation is not a quantum phase transition.
Quantum phase transitions occur only at zero temperature, and become crossovers for any $T\neq 0$. In the same way that the paramagnetic-ferromagnetic Ising transition only occurs at zero external field, and becomes a crossover for any $H\neq 0$.
Experimentally, of course, you'd only probe the $T\rightarrow 0$ limit but you'd still call it a phase transition. Because, why not. So you'd (practically) consider quantum phase transitions happening also at $T\neq 0$.
The reasoning behind all this is that there are two energy scales$^\dagger$:

*

*thermal: $k_{\mathrm{B}} T$

*quantum: $\hbar \omega$
Only when $T=0$ the thermal energy scale vanishes completely and the quantum one can dominate and control the dynamics. In the Ising analogy, these correspond to the external field interaction energy $\mu H$ and the inter-particle interaction $J$ respectively.
Hence, in quantum phase transitions, temperature drops out completely. The transition is then driven by something else. An order parameter. Magnetisation, disorder strength. Interaction strength. Both. Etc.
Classical (temperature-driven) phase transitions are characterised by power-law divergence of several parameters, for example the correlation length $\xi_\ell$ and the correlation time $\xi_t$:
$$ \xi_\ell \propto |T-T_{\mathrm{c}}|^{-\nu}, $$
$$ \xi_t \propto |T-T_{\mathrm{c}}|^{-\nu'}. $$
We could come up with a characteristic frequency scale by taking $\omega_c \sim 1/\xi_t$:
$$ \omega_c \sim 1/\xi_t \propto |T-T_{\mathrm{c}}|^{\nu'} \rightarrow 0 \quad \mathrm{as} \quad T\rightarrow T_{\mathrm{c}}.$$
The above argument is sometimes used to justify why the quantum energy scale $\hbar \omega_c$ is always going to be shadowed by the thermal one in the vicinity of $T_{\mathrm{c}}$, thereby not playing any effect. And requiring $T=0$ to really be dominant.

Contrary, in Subir Sachdev's book I find a graph (Fig 16.4) that
  suggests BEC is a quantum phase transition like any other, with a
  quantum critical point at $T=0$ and $\mu<0$. As a specific example, we could
  consider a weakly-interacting Bose-gas in three dimensions.

Bose-Einstein condensation is a non-interacting effect. The fact that a macroscopically occupied ground state occurs despite interactions is more complicated and, I would say, another matter. As you said, BEC is driven by particle statistics only.
I don't have the book but I am assuming the figure you are referring to is the the same as fig. 3 here. In eq. 50 on the same page he has a dependence $\mu/u_0$ where $u_0$ depends on the interaction strength $a$. So in the non-interacting limit $a\rightarrow 0$, that goes away and the reasoning stops being applicable.
The chemical potential cannot be thought as the external parameter driving a quantum phase transition as you don't have independent control over it. It is determined by the system itself, as explained here.

$^\dagger$: Though I am not aware of situations where these two energy scales directly compete against each other, there are phase diagrams (e.g. unitary Bose gas) where you can go from BEC to thermal Bose gas by varying $T$, and from BEC to unitary BEC changing the interaction strength $a$. These are all crossovers but still, food for thoughts.

A: In three dimensions Bose-Einstein condensation happens at finite temperature but in one and two spatial dimensions it happens at $T=0$.


text:
Q: Show/Hide DIV's based on specific link click I have a page that lists a series of content. I then have filters so someone can narrow down their search. I'd like to show/hide a block of information in my sidebar according to the filter that someone has clicked on. Basically clicking on a filter will show/hide these DIV's.
Here are two of the filters. Notice the one that is currently selected has an added class of "active" in two places.

       Category 1

       Category 2

When the page loads, Category 1 is active by default so I will show my corresponding DIV "block-1" by default.
Here is where the magic needs to be: When the filter link is clicked on above I would like to show/hide two DIV's that I have loaded.

content
    <—— Hide this one.

content
 <—— Display this one.

It is also important that when a user clicks back on the first Category that it goes back to the default view of showing just the first block.
UPDATE: It took a long while but I finally figured it out. Using the "duplicate" answer here I tailored it to my needs. I also used some other code to add the necessary "rel" attributes that I needed.

A: This is definitely possible with simple js and CSS, however the hurdle will be in making it not look jarring. I would recommend using jQuery isotope. http://isotope.metafizzy.co. It isn't just for layouts, it also handles filtering quite nicely. If you don't need it for layout at all you could also use https://mixitup.kunkalabs.com

A: You can do this with toggle function : http://jsfiddle.net/AU8fX/1/
$( ".filterbutton" ).on( "click", function() {
    $('.block').toggle();
});

A: You say your JS isn't that good, let's see if I can give you enough clues:
Category 1

Html5 has the data-group attributes. I wrote target, but you can put anything there, it can be for your just code.
You can get that when clicked:
$('.filterbutton').on('click', function(){
    // do something with the click
    alert( $(this).data('target') ); // I alert it, you van use this as a selector
}):

You can togglethe active class very easy with some code in the onclick:
$('.active').removeClass('active');
$(this).addClass('active');

To show and hide elements:
$('.SomeElements').hide();
$( specific selector).show();


text:
Q: How can i display parallely updated record id from mysql using curl with jquery in php I am getting some wrong display with updated records in mysql. My requirement is there are 4 process in my webpage. First user clicks on process one ( i am calling this as round one) some records start update in database. At the same time i want to show which record updated to User. For this i used curl and jquery.I am getting output but that was not in correct. At the time of updating i am inserting updated time using the below code.
<?php

   $microtime = microtime(true);
   $microtime_replace = str_replace('.','',$microtime);

?>

So for each record updated time in microsecods will be insert in database like microseconds "5134", "6000","6789" like this.When user clicks on Start Round one button i am calling one javascript function for executing updated process in ajax call.That javascript function is StartRoundOne(). In this function i am calling
setInterval(function(){displayUpdatedIds()},100);

In displayUpdatedIds() i am calling curl process.
function displayUpdatedIds()
{
   jQuery.ajax({
       type: 'GET',
       crossDomain:true,
       async: false,
       url: "curlProcess.php",
       success: function(valid_result){

                      if(valid_result){
                        jQuery("#UpdatedIds").html(valid_result)  ;
                      }
                }
    });
}

In UpdatedIds div tag those ids will display.
The code in curlProcess.php
<?php

   $the_url = $path./getUpdatedIds.php;
   $ch = curl_init();
   curl_setopt($ch, CURLOPT_URL, $the_url);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_REFERER, $_SERVER['REQUEST_URI']);
   $result = curl_exec($ch);
   curl_close($ch);
   echo $result;

?>

Below code i am trying to get updated ids for displaying one by one from
getUpdatedIds.php file.
$reconciledpid = getdata("temp_table","pid","round_status='R1_DONE' and last_updated = (select max(last_updated) FROM temp_table where round_status='R1_DONE' order by pid asc limit 0,1)");
echo $reconciledpid;

In database records are properly updated with last_updated time.like
firstrecord at 3456 micro seconds
second record at 4000 micro seconds.
third record at 4500 micro seconds.
fourth record at 4890 micro seconds.
fifth record at 5300 micro seconds.

like this. At the time of executing for every 100 microseconds
displayUpdatedIds() will call and get the updated ids. But for me i am not
getting all the updated ids one by one.
The output what i am expecting is (in database all the records updated order by id)
for example in that table i am having total of 7 records. My desired out put is
just i am showing one by one.
 1/10
 2/10
 3/10
 4/10
 5/10
 6/10
 7/10

Some updated ids skipped , don't know why this happend.
But i am getting like this
2/10
4/10
5/10
7/10

Please suggest me where i am doing wrong. Sorry for my bad english if there any typos.
I need parallely updated record need to display to user.


text:
Q: how to define a "select *" JPA predicate with eager fetch? i have the following 3 entities (note the hierarchy of lazy collections):
@Entity
public class ObjectEntity {
   @OneToMany(fetch = FetchType.LAZY)
   Set<ObjectInstanceEntity> instances;
}

@Entity
public class ObjectInstanceEntity {
   @OneToMany(fetch = FetchType.LAZY)
   Set<ObjectInstanceClientEntity> clients;
}

@Entity
public class ObjectInstanceClientEntity {
   //nothing special
}

and i also have the spring-data-jpa repository for the root entity:
public interface ObjectEntityRepository extends JpaRepository<ObjectEntity, UUID>, JpaSpecificationExecutor<ObjectEntity>{
}

im trying use the Page<T> findAll(Specification<T> spec, Pageable pageable) method on JpaSpecificationExecutor to bring in a page's worth of ObjectEntitys while eagerly loading all the collections (instances and instances.clients). this is where im stuck:
private final Specification<ObjectEntity> spec = new Specification<ObjectEntity>() {
    @Override
    public Predicate toPredicate(Root<ObjectEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        root.fetch("instances", JoinType.LEFT);
        root.fetch("instances.clients", JoinType.LEFT); //this doesnt work
        return cb.; //what do i put here? any(null) ?
    }
};

whats the correct way to construct the predicate so that all lazy colelctions are brought in?

A: The fetch() method returns a Fetch object that could be used as "root" of a new fetch().
The fetch is stored into the Root object, you don't have to return it.
In your case:
private final Specification<ObjectEntity> spec = new Specification<ObjectEntity>() {
    @Override
    public Predicate toPredicate(Root<ObjectEntity> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
        root.fetch("instances", JoinType.LEFT).fetch("clients", JoinType.LEFT); //this should work
    }
};


text:
Q: collocation for the noun "quote" I was wondering how we use the noun "quote" in a sentence. Specifically, what verbs should we use after it? Can we use the verb say as in:

A quote says, "Gender equality is more than a goal in itself."

A: I feel it would sound more correct and specific to write who said the quote.

[Person] (once) [wrote/said], "Gender equality is more than a goal in itself."

As a side note: I would shy away from the use of "once" here- "[Person] once said" sounds cliché.

A: Strictly speaking you can't use that, because a quote doesn't literally speak, but is passive. Figuratively speaking, you have the poetic freedom to use metaphors. Simpler (not better) to say is: to be.
The problem is however easily avoided, because quotes are already identified as such from an attribution, that has to be in context of the quote; otherwise direct speech quotation would be a mistake. I mean, I would try to conjoin your given example and the declaration which you would have linked back to from your example.


text:
Q: preventing juno-atom from recloning all julia packages I am new to both julia and atom and trying to set them both up together. I installed juno for atom and am trying to run a julia script. I relocated my package directory for Julia from ~, because at my workplace there is a limit on space in said directory.
how do I make atom recognize the packages are in a different directory?
I am currently working on a CENTOS machine.

A: Find your .juliarc.jl file, and insert the line
ENV["JULIA_PKGDIR"] = # your package directory

BTW this issue is unrelated to Atom. It is the julia installation that keeps track of the package directory.


text:
Q: Send Arguments to Python from C++/CLI I have a Python function in file query.py which is like this:
def dr2_query(ra=None, dec=None, obj='TEST', filename=None, radius=17):

I am trying to call this from C++/CLI like this:
ProcessStartInfo^ psi = gcnew ProcessStartInfo();
psi->FileName = "C:\\Program Files\\Python38\\python.exe";
String^ script = "C:\\ProgramData\\Astrowerks\\CCDLABx64\\query.py";
String^ cval1 = "text1";
String^ cval2 = "text2";
String^ object = "test";
String^ filename = "c:\\test.txt";
String^ radius = "17";

psi->Arguments = String::Format(script + " {0} {1} {2} {3} {4}", cval1, cval2, object, filename, radius);

Process^ proc = ::Diagnostics::Process::Start(psi);

However when I run it it gives an error of "unrecognized arguments" from Python. How do I send the arguments correctly to the Python function?

A: That error is being output by the Python script, specifically from its use of argparse. (Note the error message in that example is the same as yours.)
Run query.py -h to see how you should be passing arguments.


text:
Q: Limit $\lim_{n\to\infty}\left(\frac n{n^2+1}+\frac n{n^2+2}+\frac n{n^2+3}+\dots+\frac n{n^2+n}\right)$ Here is a question:
Show that the limit exists and find it
$$\lim_{n\to\infty}\left(\frac n{n^2+1}+\frac n{n^2+2}+\frac n{n^2+3}+\dots+\frac n{n^2+n}\right)$$
I'm finding it a bit tricky to evaluate the limit of this series. I tried finding the limit of each term, but I think that's not the correct approach. How should I go about solving it? Can I use squeeze theorem here? If so, then how?


text:
Q: My  structure gets nested while running I have the following code in Visual studio

 Navigation

But while running it, it looks like this in the browser:

 Navigation

Does anyone know why this happens and how to fix it?

A: As Leo said and with my personal experience, can you try adding:

And also, would you please remove the
 from inside of the ?
To add to it, you can give something like to hide the text completely:
.icon-bar {overflow: hidden; text-indent: -100%;}


text:
Q: PHP mailer multiple address
Possible Duplicate:
PHPMailer AddAddress()

Here is my code.

require('class.phpmailer.php');
$mail = new PHPMailer();

$email = 'email1@test.example, email2@test.example, email3@test.example';

    $sendmail = "$email";

    $mail->AddAddress($sendmail,"Subject");
    $mail->Subject = "Subject";
    $mail->Body    = $content;

    if(!$mail->Send()) { # sending mail failed
        $msg="Unknown Error has Occured. Please try again Later.";
    }
    else {
        $msg="Your Message has been sent. We'll keep in touch with you soon.";
    }
}

The Problem
if $email value is only 1. It will send. But multiple don't send. What should I do for this. I know that in mail function you have to separate multiple emails by comma. But not working in phpmailer.

A: You need to call the AddAddress method once for every recipient. Like so:
$mail->AddAddress('person1@domain.example', 'Person One');
$mail->AddAddress('person2@domain.example', 'Person Two');
// ..

Better yet, add them as Carbon Copy recipients.
$mail->AddCC('person1@domain.example', 'Person One');
$mail->AddCC('person2@domain.example', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.
$recipients = array(
   'person1@domain.example' => 'Person One',
   'person2@domain.example' => 'Person Two',
   // ..
);
foreach($recipients as $email => $name)
{
   $mail->AddCC($email, $name);
}


text:
Q: ¿Cómo crear un boton y juntar un poco los elementos en android studio? tengo un NavigationDrawer en mi código, pero los items aparecen muy separados unos de otros, hacia abajo como en la imagen.

¿Cómo hago para juntarlos un poco? ¿y cómo hago para crear un botón dentro de ese menú desplegable?
La flecha roja indica lo que quisiera que es juntar los objectos para que estén menos separados el número 5 de la palabra "juegos".
<menu

xmlns:android="http://schemas.android.com/apk/res/android">

  <item

      android:title="juegos">
    <menu>

        <item
            android:title="5">
        </item>
    </menu>

  </item>

    <item
        android:title="Dinero">
        <menu>

            <item
                android:title="u$d: 55">

            </item>

        </menu>

    </item>

    <item
        android:title="Pais"
        android:id="@+id/perfilUsuario_fundaciones_ayudadas">
        <menu>

            <item
                android:title="7">
            </item>
        </menu>
    </item>

    <item
        android:title="Paises Ayudados">
        <menu>
            <item
                android:title="2">
            </item>
        </menu>
    </item>

    <group android:checkableBehavior="single">

        <item
            android:id="@+id/pe"
            android:icon="@drawable/corazon"
            android:title="@string/historial"
            />

        <item
            android:id="@+id/perfilUsuario_opciones"
            android:icon="@drawable/ic_menu_manage"
            android:title="@string/opciones" />

        <item
            android:id="@+id/btn_cerrarSesion"
            android:title="@string/cerrar_sesi_n"
            >
        </item>
    </group>

</menu>

A: Lo que desea va contra los guidelines, de hecho en realidad no lo puedes cambiar si estas agregando dentro de un item un elemento menú y a su ves otro item:
<item
      android:title="juegos">
    <menu>
        <item
            android:title="5">
        </item>
    </menu>
...
...
...

Lo único que puedes cambiar aquí es el espacio entre los grupos, sobreescribiendo estos valores dentro de tu archivo dimens.xml
<dimen name="design_navigation_padding_top_default" tools:override="true">120dp</dimen>
    <dimen name="design_navigation_separator_vertical_padding" tools:override="true">120dp</dimen>
    <dimen name="design_navigation_padding_bottom" tools:override="true">120dp</dimen>

Pero los espacios entre los elementos del menú no podrías cambiarlos, ya que la vista esta diseñada para mostrar únicamente el icono y el titulo:
  <item
                android:id="@+id/my_item"
                android:icon="@drawable/ic_app"
                android:title="Mi Titulo" />

Te sugiero otra opción como crear tus vistas personalizadas, por ejemplo revisa el NavDrawerItem (drawer_list_item.xml) de este ejemplo

y también puedes hacerr uso de un ExpandableListView.

A: Para reducir el espacio entre los items simplemente reduce el valor del margin que estés usando en ellos. Por otro lado, te aconsejo usar padding si no lo estas haciendo. Si pudieses proporcionar el código de tu XML sería de ayuda a la hora de dar una respuesta más concreta.
Un saludo.

A: Un Navigation Drawer es un contenedor de otros View, por ende son personalizables, tendria que generar el layout del campo que contiene un ListView, asegurando en este un margin minimo arriba y abajo, posterior a esto usando un Base adapter dentro del activity que maneja la vista donde este mostrando el Navigation Drawer, cargar cada item del menu asociando el layout creado anteriormente, y ya finalmente el listview cargarlo dentro del Navigation Drawer.


text:
Q: Show more info (margin, padding, etc.) in Brackets Live Preview In Brackets Live Preview, when editing the CSS styling of the shown webpage, the selected element in editor is highlighted with blue boundaries in the live web page.
My question is if there is any setting or extension (which I couldn't find) that will show more information about the element on the live preview - for example, the margin, the padding, size in px, etc.

A: Checking the current version of Brackets, the functionality that I asked about is by default implemented in Live Preview mode. The margin and padding of inspected elements are now shown.

A: If you are unhappy with the browser's native inspector there are addons available such as firebug etc.


text:
Q: Opening docx or pptx files in Office Web Apps 2013 results in the error "Sorry, Word Web App ran into a problem opening this document The problem I am facing matches exactly with the problem I have found here. They provide solution also but I am not able to understand it. Can someone please explain it in detail?
Following is the problem I've copied from the site.
Problem: Opening docx or pptx files in Office Web Apps 2013 results in the error "Sorry, Word Web App ran into a problem opening this document. To view this document please open it in Microsoft Word."

Resolution:  I don't like it but I had to remove the link to the WCA farm, rebuild the WCA farm and hoop SP2013 back to the WCA farm.  [sic].  Other documents were opening and I realised that my bindings were incorrect after I rebuilt.


text:
Q: How to indent the item in the theorem environment of ams-gsm package I use gsm package to write my latex file. Normally, in the theorem environment, the item are indented a small space from the left margin. I want to indent it all  to the left margin like the following picture:

Here is a minimal working example:
\documentclass{gsm-l}
\usepackage{amsmath}
\newtheorem{theorem}{Theorem}
\begin{document}
\begin{theorem} This is the theorem.
\begin{enumerate}
\item The first item
\item The second item
\item Are they indented as my purpose?
\end{enumerate}
\end{theorem}
\end{document}

Please help me.

A: This really has nothing to do with the theorem environment provided by the document class through \newtheorem. Instead, it's the default behaviour of a list (including enumerate and itemize). You can modify the indentation using some of enumitem's interfaces. Below I've set the leftmargin to be automatically calculated using *, which results in a flush-left setting:

\documentclass{gsm-l}
\usepackage{amsmath,enumitem}% http://ctan.org/pkg/{amsmath,enumitem}
\setlist[enumerate]{leftmargin=*}
\newtheorem{theorem}{Theorem}
\begin{document}
\begin{theorem} This is the theorem.
  \begin{enumerate}
    \item The first item
    \item The second item
    \item The third item that is a tad longer and should span more than
      a single line, and naturally flow to a second line.
  \end{enumerate}
\end{theorem}
\end{document}

\setlist[enumerate] changes the default behaviour of enumerate at the document level, across all levels of nesting. If you wish to have a more localized change, you can supply an optional argument to the environment instead using the following interface:
\begin{enumerate}[leftmargin=*]
  ...
\end{enumerate}

A: document classes based on amsbook (including gsm-l) set up the indentation
to be too large, as observed here.
the mechanism used at ams to decrease it is to override the default margin settings,
which must be done \AtBeginDocument, since that is how they are initially defined:
\AtBeginDocument{%
  \labelsep=5pt\relax
  \setcounter{enumi}{13}\setcounter{enumii}{13}%
  \setcounter{enumiii}{13}\setcounter{enumiv}{13}%
  \settowidth\leftmargini{\labelenumi\hskip\labelsep}%
%%  \advance\leftmargini by \normalparindent % this is the culprit
  \settowidth\leftmarginii{\labelenumii\hskip\labelsep}%
  \settowidth\leftmarginiii{\labelenumiii\hskip\labelsep}%
  \settowidth\leftmarginiv{\labelenumiv\hskip\labelsep}%
  \setcounter{enumi}{0}\setcounter{enumii}{0}%
  \setcounter{enumiii}{0}\setcounter{enumiv}{0}%
  \leftmarginv=10pt  \leftmarginvi=\leftmarginv
  \leftmargin=\leftmargini
  \labelwidth=\leftmargini \advance\labelwidth-\labelsep
  \@listi}

since this is not set up as a command definition, it is not readily patched by
techniques defined in etoolbox as i understand it.


text:
Q: How to assigning BaseController values from unit test in ASP.NET MVC We are trying to add unit test in our existing MVC application. Our all controllers inherits a BaseController which is given below:
public class BaseController : Controller
{
    public virtual Tenant Tenant
    {
        get { return System.Web.HttpContext.Current.Items["Tenant"] as Tenant; }
    }
}

Now, here's a sample controller inherits BaseController and works very well:
public class DefaultController : BaseController
{
    public ActionResult Index()
    {
        // TODO: repository calls
        return View();
    }
}

But as soon as I add string tenantid = Tenant.Id; in above controller (given below), my unit test fails.
public class DefaultController : BaseController
{
    public ActionResult Index()
    {
        // TODO: repository calls
        string tenantid = Tenant.Id;
        return View();
    }
}

This looks like System.Web.HttpContext.Current.Items["Tenant"] is null during unit test run, how do I assign that value in BaseController from unit test?

A: Current controller tightly coupled to implementation concerns (HttpContext) that make it difficult to unit test it in isolation.
Review current design and decouple from HttpContext.Current which is null as IIS is not available when unit testing.
Also Controller already has a HttpContext property
public HttpContextBase HttpContext { get; }

that tries to decouple by using HttpContextBase which able to be mocked.
That property can be accessed and set via the ControllerContext.
So first update the controller to use local HttpContext property
public class BaseController : Controller {
    public virtual Tenant Tenant {
        get { return HttpContext.Items["Tenant"] as Tenant; }
    }
}

Now that the controller is using a context that can be mocked, it can be unit tested as needed.
//Arrange
var tenant = new Tenant() {
    //...
};
var mockHttpContext = new Mock<HttpContextBase>(); //USING MOQ
mockHttpContext.Setup(_ => _.Items["Tenant"]).Returns(tenant);

var controller = new DefaultController();
controller.ControllerContext =
    new ControllerContext(mockHttpContext.Object, new System.Web.Routing.RouteData(), controller);

//Act
var result = controller.Index();

//Assert
//...