text:
Q: Aplication crashes when returning to previous View - Thread 1: EXC_BAD_ACCESS I have two basic views with labels, text fields and swiches:

First view is the root view of the navigation controller. There is a named segue from first view to second view as "next" called when clicking the bar button "İleri" in first view. Here is my code for both ViewController:
HMXNewPersonelStep1ViewController.h
HMXNewPersonelStep1ViewController.m
HMXNewPersonelStep2ViewController.h
HMXNewPersonelStep2ViewController.m
I am running the application clicking button "İleri" in first view and navigating to second view with no problem. But when i click button "Geri" in second view, program navigates back to firs view, i can see the fisrt view for a short time, and application crashes with following error:
Thread 1: EXC_BAD_ACCESS

It crashes on:

Debug trace:

Debug detail for [_NSDictionaryM dealloc]:
libobjc.A.dylib`-[NSObject release]:
0x11339d0:  pushl  %ebp
0x11339d1:  movl   %esp, %ebp
0x11339d3:  pushl  %edi
0x11339d4:  pushl  %esi
0x11339d5:  subl   $16, %esp
0x11339d8:  calll  0x11339dd                 ; -[NSObject release] + 13
0x11339dd:  popl   %edi
0x11339de:  movl   8(%ebp), %esi
0x11339e1:  movl   %esi, (%esp)
0x11339e4:  calll  0x1132541                 ; _objc_rootReleaseWasZero
0x11339e9:  testb  %al, %al
0x11339eb:  je     0x11339ff                 ; -[NSObject release] + 47
0x11339ed:  movl   995643(%edi), %eax
0x11339f3:  movl   %eax, 4(%esp)
0x11339f7:  movl   %esi, (%esp)
0x11339fa:  calll  0x113108c                 ; objc_msgSend
0x11339ff:  addl   $16, %esp                 ; This line was highlighted
0x1133a02:  popl   %esi
0x1133a03:  popl   %edi
0x1133a04:  popl   %ebp
0x1133a05:  ret

I have enabled Zombie Objects as suggested and here is the message before crash:
2013-10-07 17:07:23.113 Arendi[5783:c07] *** -[UIDeviceRGBColor release]: message sent to deallocated instance 0x8171e90

A: I have changed the UISwitch Thumb Tint color to default and problem solved.
I hate Xcode! Thanks for all answers and tips.

A: Because you are using a NavigationController,
It should have been set automatically without any additional back button.
Perhaps, processing of backButtonClicked:sender(HMXNewPersonelStep2ViewController.m) are unnecessary.

A: you have declared activeField as strong but using the property directly. may be its releasing your text fields prematurely. add @synthesize for it and try.

A: When touch back geri button maybe you try to reach 2nd view object? Try to use AllExceptions and see.
Or if you use internet connection like Asihttprequest, clear or cancel your instance delegate.
Merhaba kardeş, eğer 1.viewe döndüğünde 2. viewde birşeyler değişmeye çalışıyorsa bundan kaynaklanıyordur büyük ihtimalle. Asihttprequest kullanıp değişiklikleri serverea yazıyorsan ve daha bağlantı sonucu dönmeeden geriye basıyorsan bu çok normaldir.


text:
Q: Can we programmatically search highlighted text in RichTextBox of WPF As shown at the end below, using Microsoft WORD VBA, we can search all highlighted texts in MS WORD document. Same can be achieved using C# in a legacy MS Office VSTO add-in. Question: How can we programmatically get TexRanges of all highlighted texts in a WPF RichTextBox?
WPF RichTextBox Display:

Code to get rtf:
string sRTF = "";
TextRange tr = new TextRange(rtbTest.Document.ContentStart, rtbTest.Document.ContentEnd);

using (MemoryStream ms = new MemoryStream())
{
    tr.Save(ms, DataFormats.Rtf);
    sRTF = ASCIIEncoding.Default.GetString(ms.ToArray());
}

Debug.Write(sRTF);

RTF output:
In the following output, We can see the rtf for the highlighted text test is {\lang9\highlight2\ltrch test}. How can we programmatically get the highlighted text (i.e. test) here. This is just an example., I mean to get all highlighted texts programmatically?
{\rtf1\ansi\ansicpg1252\uc1\htmautsp\deff2{\fonttbl{\f0\fcharset0 Times New Roman;}{\f2\fcharset0 Calibri;}}{\colortbl\red0\green0\blue0;\red255\green255\blue255;\red255\green255\blue0;}\loch\hich\dbch\pard\plain\ltrpar\itap0{\lang1033\fs18\f2\cf0 \cf0\ql{\fs22\f2 {\lang9\ltrch This is a }{\lang9\highlight2\ltrch test}{\lang9\ltrch  for a WPF RichTextBox}\li0\ri0\sa200\sb0\fi0\ql\par}
{\f2 {\ltrch }\li0\ri0\sa0\sb0\fi0\ql\par}
}
}

Can we achieve the same programmatically in a WPF RichTextBox like we do (for example) in a WORD Document through a VBA macro shown below or through c# in a legacy VSTO add-in:
Selection.Find.ClearFormatting
Selection.Find.Highlight = True
With Selection.Find
    .Text = ""
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindContinue
    .Format = True
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
Selection.Find.Execute
Selection.Find.Execute

A: To understand what is algorithm can be used to analyze a content of the FlowDocument the best way to read the Flexible Content Display With Flow Documents post or, for example, read the chapter "Documents" in book MacDonald M. - Pro WPF 4.5 in C#. Windows Presentation Foundation in .NET 4.5 (The Experts Voice in .NET), 2012.
So, the FlowDocument contains BlockCollection Blocks property.  This is the top-level blocks of the whole the FlowDocument content.
Code below uses this property to parse and analyze all elements in the FlowDocument recursively, including to search for text fragments with a specified background color.
For the test purpose the application window contains the Color ComboBox  which allows to choose an some color and paint selected fragments of text using the Set Color button. The Search color text button starts scanning the document, finds the text colored with the specified color and uses the created TextRange list to repainting the text in pink.

MainWindow.xaml
<Window ...
        Title="MainWindow" Height="350" Width="500" >
    <Grid>

        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <RichTextBox Name="rtb" BorderBrush="LightGreen"
                     Padding="5" Margin="10" VerticalScrollBarVisibility="Auto">
            <FlowDocument>
                <Paragraph>
                    <Run>?</Run>
                </Paragraph>
            </FlowDocument>
        </RichTextBox>
        <Grid Grid.Row="1" Margin="5">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="auto"/>
                <ColumnDefinition Width="auto" MinWidth="60"/>
                <ColumnDefinition Width="Auto"/>
                <ColumnDefinition Width="*"/>
            </Grid.ColumnDefinitions>

            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
                <RowDefinition Height="Auto"/>
            </Grid.RowDefinitions>

            <Label Content="Color: " />
            <ComboBox x:Name="ComboColor" Grid.Column="1" Width="150" Margin="3" SelectedValuePath="Name" >
                <ComboBox.ItemTemplate>
                    <DataTemplate>
                        <StackPanel Orientation="Horizontal">
                            <Rectangle Fill="{Binding Name}" Width="16" Height="16" Margin="0,0,5,0" />
                            <TextBlock Text="{Binding Name}" />
                        </StackPanel>
                    </DataTemplate>
                </ComboBox.ItemTemplate>
            </ComboBox>

            <Button Content="Set color" Grid.Row="1" Grid.Column="1" Padding="3" Margin="3" Click="SetColor_Click"/>
            <Button Content="Search colored text" Grid.Row="2" Grid.Column="1" Padding="3" Margin="3" Click="Search_Click"/>
        </Grid>

    </Grid>
</Window>

MainWindow.xaml.cs
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace WpfApp17
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            ComboColor.ItemsSource = typeof(Colors).GetProperties();
            ComboColor.SelectedValue = "Brown";
        }

        private void Search_Click(object sender, RoutedEventArgs e)
        {
            Parsing(rtb);
        }

        public void Parsing(RichTextBox rtb)
        {
            // Get selected color
            var c = System.Drawing.Color.FromName(ComboColor.SelectedValue.ToString());

            var parser = new RtfDocumentParser();

            // Initialization with selected color
            parser.Init(Color.FromArgb(c.A, c.R, c.G, c.B));

            // Processing
            parser.Analyze(rtb);

            // Color found TextRanges to pink
            foreach (var tr in parser.TextRanges)
            {
                tr.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Colors.Pink));
            }
        }

        private void SetColor_Click(object sender, RoutedEventArgs e)
        {
            var selection = rtb.Selection;
            if (!selection.IsEmpty)
            {
                var c = System.Drawing.Color.FromName(ComboColor.SelectedValue.ToString());
                selection.ApplyPropertyValue(TextElement.BackgroundProperty, new SolidColorBrush(Color.FromArgb(c.A, c.R, c.G, c.B)));
            }
        }
    }
}

RtfDocumentParser.cs
using System;
using System.Collections.Generic;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace WpfApp17
{
    public class RtfDocumentParser
    {
        #region Public properties

        public Color SearchColor { get; private set; }
        public IList<TextRange> TextRanges { get; private set; }
        #endregion

        #region Private properties

        private TextPointer Start { get; set; }
        private TextPointer End { get; set; }
        #endregion

        #region ctor
        public RtfDocumentParser()
        {
            Init(Colors.Yellow);
        }
        #endregion

        #region Public methods
        public void Init(Color color)
        {
            SearchColor = color;
            TextRanges = new List<TextRange>();
        }

        public void Analyze(RichTextBox rtb)
        {
            ParseBlockCollection(rtb.Document.Blocks);
            CloseRange();
        }
        #endregion

        #region Private methods

        private void ParseBlockCollection(BlockCollection blocks)
        {
            foreach (var block in blocks)
            {
                CloseRange();

                if (block is Paragraph para) { ParseInlineCollection(para.Inlines); }
                else if (block is List list)
                {
                    foreach (var litem in list.ListItems)
                    {
                        CloseRange();
                        TextRange range = new TextRange(litem.ElementStart, litem.ElementEnd);
                        ParseBlockCollection(litem.Blocks);
                    }
                }
                else if (block is Table table)
                {
                    foreach (TableRowGroup rowGroup in table.RowGroups)
                    {
                        foreach (TableRow row in rowGroup.Rows)
                        {
                            foreach (var cell in row.Cells)
                            {
                                ParseBlockCollection(cell.Blocks);
                            }
                        }
                    }
                }
                else if (block is BlockUIContainer blockui) { /* blockui.Child */ }
                else if (block is Section section) { ParseBlockCollection(section.Blocks); }
                else { throw new NotImplementedException(); }
            }
        }

        public void ParseInlineCollection(InlineCollection inlines)
        {
            foreach (var inline in inlines)
            {
                if (inline is Run r)
                {
                    Analyze(r);
                }
                else if (inline is InlineUIContainer || inline is LineBreak lbreak)
                {
                    CloseRange();
                }
                else if (inline is Span span)
                {
                    ParseInlineCollection(span.Inlines);
                }
            }
        }

        private void Analyze(Run run)
        {
            if (run.Background is SolidColorBrush rBrush)
            {
                CheckPositions(rBrush.Color, run.ElementStart, run.ElementEnd);
            }
            else if (run.Parent is Span span && span.Background is SolidColorBrush sBrush)
            {
                CheckPositions(sBrush.Color, run.ElementStart, run.ElementEnd);
            }
            else if (End != null)
            {
                CloseRange();
            }
        }

        private void CheckPositions(Color color, TextPointer start, TextPointer end)
        {
            if (color == SearchColor)
            {
                if (Start == null)
                {
                    Start = start;
                }
                else if (!IsMatch(start, End))
                {
                    TextRanges.Add(new TextRange(Start, End));
                    Start = start;
                }
                End = end;
            }
            else if (End != null)
            {
                CloseRange();
            }
        }

        private bool IsMatch(TextPointer start, TextPointer position)
        {
            for (; position != null; position = position.GetNextContextPosition(LogicalDirection.Forward))
            {
                //var context = position.GetPointerContext(LogicalDirection.Forward);
                if (start.CompareTo(position) == 0)
                    return true; // Match
            }
            return false;
        }

        private void CloseRange()
        {
            if (End is TextPointer)
            {
                TextRanges.Add(new TextRange(Start, End));
            }
            Start = End = null;
        }

        #endregion
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prevent computer from sleeping in C++ I need a way to prevent the computer from sleeping, turn it on/off at runtime.
I believe SetThreadExecutionState does that for windows, now I am looking for a way to do that in Linux.

A: Answer for Linux only, I unfortunately don't know how this works on Unix systems:
You should use systemd inhibitors for this (inhibitor locks are also available on non-systemd distributions, provided by elogind). These can be controlled using DBus API so if you are using Qt you can use the QDBus module for that (other DBus libraries are also available, I don't think there is a specific library for C/C++ for working with systemd inhibitors, the DBus API is simple and language-idependent).

A: There are some C++ wrappers:
https://github.com/martinhaefner/simppl
https://github.com/makercrew/dbus-sample
https://dbus-cxx.github.io/
http://dbus-cplusplus.sourceforge.net/
And DBusBindings https://www.freedesktop.org/wiki/Software/DBusBindings/
I am on Qt and below is the code I am using which is a modified version of the code in this answer
void MainWindow::toggleSleepPevention()
{
#ifdef Q_OS_LINUX
    const int MAX_SERVICES = 2;

    QDBusConnection bus = QDBusConnection::sessionBus();
    if(bus.isConnected())
    {
        QString services[MAX_SERVICES] =
        {
            "org.freedesktop.ScreenSaver",
            "org.gnome.SessionManager"
        };
        QString paths[MAX_SERVICES] =
        {
            "/org/freedesktop/ScreenSaver",
            "/org/gnome/SessionManager"
        };

        static uint cookies[2];

        for(int i = 0; i < MAX_SERVICES ; i++)
        {
            QDBusInterface screenSaverInterface( services[i], paths[i],services[i], bus);

            if (!screenSaverInterface.isValid())
                continue;

            QDBusReply<uint> reply;

            if(preferences.preventSleep == true)
            {
                reply = screenSaverInterface.call("Inhibit", "nzuri-video Downloader", "REASON");
            }
            else
            {
                reply  = screenSaverInterface.call("UnInhibit", cookies[i]);
            }

            if (reply.isValid())
            {
                cookies[i] = reply.value();

                // qDebug()<<"succesful: " << reply;
            }
            else
            {
                // QDBusError error =reply.error();
                // qDebug()<<error.message()<<error.name();
            }
        }
    }

#elif defined  Q_OS_WIN

    EXECUTION_STATE result;

    if(preferences.preventSleep == true)
        result = SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED);
    else
        result = SetThreadExecutionState(ES_CONTINUOUS);

    if(result == NULL)
        qDebug() << "EXECUTION_STATE failed";

#endif
}


text:
Q: Linux C Programming - kill() and sleep() I have some code that simply creates a child process and then the parent and child take turns doing math on a variable and output the results. I have it working now, but I accidentally discovered that it only worked when I put a sleep() before my kill() when putting a sleep in to observe the results on the file itself. Can anyone explain this behavior to me? Without sleep() the child process never runs. I'm using Linux on VM VirtualBox on Windows 8, and this is HW so I'm not allowed to use pipe().
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <signal.h>
#include <string.h>

void sigHandler(int signo)
{
    signal(signo, sigHandler);
}

int main(int argc, char * argv[])
{
    int file;
    int x = 0;
    pid_t pid;
    char filename[17] = "sigpong_temp.txt";
    file = creat(filename, S_IRWXU);
    fprintf(stdout, "initial value %d\n", x);
    const int csize = 10;
    char c[csize];

    sprintf(c, "%d", x);
    write(file, &c, strlen(c));
    close(file);
    file = open(filename, O_RDWR);
    signal(SIGUSR1, sigHandler);
    pid = fork();

    if (pid > 0) {
        for (int i = 0; i < 5; i++) {
            lseek(file, 0, SEEK_SET);
            read(file, &c, csize);
            x = atoi(c);
            x++;
            sprintf(c, "%d", x);
            fprintf(stdout, "Parent: x =\t%d\n", x);
            lseek(file, 0, SEEK_SET);
            write(file, &c, strlen(c));
            sleep(1);
            kill(pid, SIGUSR1);
            pause();
        }
        close(file);
        _exit(EXIT_SUCCESS);
    }

    else {
        for (int i = 0; i < 5; i++) {
            pause();
            lseek(file, 0, SEEK_SET);
            read(file, &c, csize);
            x = atoi(c);
            x = x * 10;
            sprintf(c, "%d", x);
            fprintf(stdout, "Child: x =\t%d\n", x);
            lseek(file, 0, SEEK_SET);
            write(file, &c, strlen(c));
            kill(getppid(), SIGUSR1);
        }
        close(file);
        exit(EXIT_SUCCESS);
    }
}


text:
Q: How to change angular's default module While learning about angular modules, I started wondering if we can change the angular's default module or not.
I tried it but failed.
Changes I made to the files:
I created a new dir under src directory named: core which contains the following class: core.module.ts
import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { CoreComponent }  from './core.component';

@NgModule({
  imports:      [ BrowserModule ],
  declarations: [ CoreComponent ],
  bootstrap:    [ CoreComponent ]
})
export class CoreModule { }

core dir also contains the core.component.ts
import { Component } from "@angular/core";

@Component({
    selector: 'core',
    template: `<h2> Core Component Welcome you</h2>`
})
export class CoreComponent { }

Following changes were made to the main.ts
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { environment } from './environments/environment';
import { CoreModule } from './core/core.module';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(CoreModule)
  .catch(err => console.error(err));

and index.html
<core>loading core component</core>

I know in real world scenario no one would bother changing the app module, but i just want to understand how things work, so if you can kindly help me understand how things are working, what am i missing, or if its not even possible to change the default module.
Update:
Console doesn't report any errors, but the content doesn't load. Instead of displaying (comes from core.component.ts template portion):

Core Component Welcome you.

It's only displaying (comes from index.html portion):

loading core component

A: app.module is consider a root module and root module has just few difference from other angular module
1⃣ import BrowserModule
2⃣ one of the declared component at latest must add to bootstrap array
3⃣ add a element in the index.html match the bootstrap components selector
4⃣ set the new module as root module by pass a module refrence to bootstrapModule method of  platformBrowserDynamic object at main.ts.
core.module.ts
@NgModule({
  imports: [BrowserModule], //  1⃣
  declarations: [CoreComponent],
  bootstrap: [CoreComponent] //  2⃣
})
export class CoreModule {}

index.html
<core>loading</core> <!-- //  3⃣-->

main.ts
platformBrowserDynamic().bootstrapModule(CoreModule) //  4⃣
 .then(ref => {

 })
 .catch(err => console.error(err));

demo

check this bootstrapping  for more details.


text:
Q: Computing probability in roulette Andy plays european roulette and bets the lowest amount of 10 dollar at red and he's going to double the amount until he wins. Which is the probability he wins before he has spent all his 1 000 dollar he has brought to the casino?
I think this may be solved using complement event. He may double 5 times (10+20+40+80+160+320=630) and I get P(he succeed) = 1 - (18/37)^5 ≈ 0,97.
But the answer should be 0,98.
Anyone can help?
Thanks in advance.

A: The player can make 6 games... Moreover the probability that he don't get red is $19/37$ so the answer is $1-(19/37)^6$.


text:
Q: Call function after load So I need to call function after load html template in directive..
app.directive('myDivModal',function () {
    var controller = ['$scope',function ($scope) {
        //some code here..
    }];
    return {
        restrict: "E",
        scope: {
            myprops: '=props'
        },
        controller: controller,
        templateUrl: 'modal.html',
        link:function (scope, elem, attr,controller,transcludeFn) {
            $('#firstId').datepicker({
                format: 'dd-mm-yyyy'
            });
        }
    }
});

and
<input type="text" id="{{myprops.id}}" readonly="readonly" ng-model="start" >
<input type="text" id="{{myprops.id}}" readonly="readonly" ng-model="end" >

I need #firstId that to bind to id="{{myprops.id}}Dp1" .. but the function is started before HTML I try almost everything like post, compile post and so on, but nothing work so help me.

A: Use $timeout function in link:
// You might need this timeout to be sure it runs after DOM render.
$timeout(function () {
    //your code
    $('#firstId').datepicker({
      format: 'dd-mm-yyyy'
    });
}, 0,false);

And this is possibly a duplicate question of Execute Javascript after directive template has been loaded

A: I think @DB.Null is correct try adding a class property to your html elements and then apply:
$('.startDate').datepicker({
    format: 'dd-mm-yyyy'
});

A: Update your controller:
var controller = ['$scope',function ($scope) {

  ...
  $scope.$on('my-tpl-ready', function() {

    $('#firstId').datepicker({
      format: 'dd-mm-yyyy'
    });

  });

}];

Also add this to your template:
<div ... ng-init="$emit('my-tpl-ready')">
  ...
</div>


text:
Q: uploading error when using carrierwave and uploadify i was trying for uploadify with carrierwave to support multiple file upload but it is giving me this error GET http://localhost:3000/users/uploadify.swf?preventswfcaching=1361694618739.
Basically i ve one model named as user. For single upload it is working fine with carrierwave but for multiple file it is not.
I ve followed this tutorial.
In users/_form.rb

<%= f.label "Upload Images"%>
<%= f.file_field :image, :multiple => true %>

I m using mongoid so the model is like this
class User
 include Mongoid::Document
 field :name, type: String
 field :description, type: String
 field :image, type: String

   mount_uploader :image, ImageUploader
 end

I m not getting what is the error. Please help me out.

A: Here's a complete solution for multiple image uploads with Carrierwave:
To do just follow these steps.
rails new multiple_image_upload_carrierwave

In gem file
gem 'carrierwave'

Then run the following
bundle install
rails generate uploader Avatar

Create post scaffold
rails generate scaffold post title:string

Create post_attachment scaffold
rails generate scaffold post_attachment post_id:integer avatar:string

Then run
rake db:migrate

In post.rb
class Post < ActiveRecord::Base
   has_many :post_attachments
   accepts_nested_attributes_for :post_attachments
end

In post_attachment.rb
class PostAttachment < ActiveRecord::Base
   mount_uploader :avatar, AvatarUploader
   belongs_to :post
end

In post_controller.rb
def show
   @post_attachments = @post.post_attachments.all
end

def new
   @post = Post.new
   @post_attachment = @post.post_attachments.build
end

def create
   @post = Post.new(post_params)

   respond_to do |format|
     if @post.save
       params[:post_attachments]['avatar'].each do |a|
         @post_attachment = @post.post_attachments.create!(:avatar => a, :post_id => @post.id)
       end
       format.html { redirect_to @post, notice: 'Post was successfully created.' }
     else
       format.html { render action: 'new' }
     end
   end
 end

 private
   def post_params
      params.require(:post).permit(:title, post_attachments_attributes: [:id, :post_id, :avatar])
   end

In views/posts/_form.html.erb
<%= form_for(@post, :html => { :multipart => true }) do |f| %>

     <%= f.label :title %>

     <%= f.text_field :title %>

   <%= f.fields_for :post_attachments do |p| %>

       <%= p.label :avatar %>

       <%= p.file_field :avatar, :multiple => true, name: "post_attachments[avatar][]" %>

   <% end %>

     <%= f.submit %>

<% end %>

To edit an attachment and list of attachment for any post. In views/posts/show.html.erb

<%= notice %>

  Title:
  <%= @post.title %>

<% @post_attachments.each do |p| %>
  <%= image_tag p.avatar_url %>
  <%= link_to "Edit Attachment", edit_post_attachment_path(p) %>
<% end %>

<%= link_to 'Edit', edit_post_path(@post) %> |
<%= link_to 'Back', posts_path %>

Update form to edit an attachment views/post_attachments/_form.html.erb
<%= image_tag @post_attachment.avatar %>
<%= form_for(@post_attachment) do |f| %>

    <%= f.label :avatar %>

    <%= f.file_field :avatar %>

     <%= f.submit %>

<% end %>

Modify update method in post_attachment_controller.rb
def update
  respond_to do |format|
    if @post_attachment.update(post_attachment_params)
      format.html { redirect_to @post_attachment.post, notice: 'Post attachment was successfully updated.' }
    end
  end
end

In rails 3 no need to define strong parameters and as you can define attribute_accessible in both the model and accept_nested_attribute to post model because attribute accessible is deprecated in rails 4.
For edit an attachment we cant modify all the attachments at a time. so we will replace attachment one by one, or you can modify as per your rule, Here I just show you how to update any attachment.


text:
Q: Passing an array of numbers to a recursive Java program I am writting a program that displays m(i) for i = 1,2,3,4,5,107,1060. The result should be a double value. Whereas the series is m(i) = 1/2 + 2/3 +.....i/i+1
I am trying to pass the required numbers by using an array. But I'm getting a compatibility problem. So far I have this:
public class Recursive {
    public static void main(String[] args){
        int[] s;
        s = new int[]{1,2,3,4,5,107,1060};

        System.out.println(""   ,m(s));
    }

    public static double m(int i){
        double result;
        if(i > 1){
            result = i/(i + 1) + m(i - 1);
        } else{
            result = i/(i + 1);
        }
        return result;
    }
}

A: Based on the comments you received, most folks think your question is asking for:
public class Recursive {

    public static double m(int i) {
        double result = i / (i + 1.0);

        if (i > 1) {
            result += m(i - 1);
        }

        return result;
    }

    public static void main(String[] args) {
        int[] s = {1, 2, 3, 4, 5, 107, 1060};

        for (int i : s) {
            System.out.println("m(" + i + ") = " + m(i));
        }
    }
}

As the sequence should be 1/2 + 2/3 + 3/4 + 4/5+ 5/6 + 107/108+
  1060/1061

This clarifies that you're really asking for:
public class Recursive {

    public static double m(int i, int[] s) {
        double result = s[i] / (s[i] + 1.0);

        if (i > 0) {
            result += m(i - 1, s);
        }

        return result;
    }

    public static void main(String[] args) {
        int[] s = {1, 2, 3, 4, 5, 107, 1060};

        System.out.println(m(s.length - 1, s));
    }
}

Which works except when s is an empty array -- just like the other potential answer to your question.

A: The method m() needs an argument which is an int but you are passing the whole array. Keep a for loop and pass the m() for every element or handle the logic in the m()

A: First you need to pass the array as an argument to the method m(),
or you could have the array declared at the class level to avoid the recursion overhead.  For this small array let's take the 1st approach.
Then, inside m() you made a logical mistake that you must fix.
You need to sum s[i]/s[i] + 1 and not i / (i + 1).
Also the condition in the if statement from i > 1 to i > 0 because the indexes of an array are 0 based:
public static void main(String[] args){
    int[] s = new int[]{1, 2, 3, 4, 5, 107, 1060};
    System.out.println(m(s, 6));
}

public static double m(int[] s, int i){
    double result;
    if(i > 0){
        result = 1.0 * s[i]/(s[i] + 1) + m(s, i - 1);
    } else{
        result = 1.0 * s[i]/(s[i] + 1);
    }
    return result;
}

The factor 1.0 that is multiplied is needed to avoid the integer division:
s[i]/(s[i] + 1)

which would always result to 0


text:
Q: Change login to use a dialog box rather than a separate web page Stack Exchange websites redirect the user to another page for logging in or signing up. Being frank, I don't like this.
The website Flipkart does this a better way. At the upper right of the page, there's two links: one for 'Login' and another for 'Signup'. If we click either of them, a dialog box appears to log in, not another web page. It would be nice if Stack Exchange implemented this.

A: While there is some annoyance factor to going via the login page it does have the advantage that it is unlikely to be interfered with by pop-up blockers and will work on just about any browser - not all browsers support pop-ups.  Other such methods rely on java/JavaScript, etc., which again some browsers do not support and some/many users have disabled for security reasons.
To work around the scenario of I would like to comment/vote/whatever on the page that I am on and do not wish to have to find it again after logging on you can - in many browsers - right click on the login link and select open in new tab, login on the new tab and then go to the original and refresh (F5) - you will find that you are still on the same page but now you are logged in.

A: The login method employed by flipkart is vulnerable to MITM attacks.
The form/page is not served over HTTPS, thus, content can be injected into the page by anyone between yourself and flipkart. Not as secure as it probably should be. (see details on this blog post by Troy Hunt).
Our login forms are always served over HTTPS. Making them popups will only make them less secure when they come up on pages served as HTTP.
Arguably, we don't deal with money on the Stack Exchange Q&A sites, but we do take username/password pair for the Stack Exchange OpenId provider, that can be used anywhere an OpenId is accepted - so making the form less secure is not an option.
This is a minor annoyance to you, but imagine the annoyance if your username and password were harvested by a malicious third party and used for nefarious deeds.


text:
Q: How do I create a circle with a grid inside and mark occupied cells in R? How would I create a circle with a grid inside it and then fill in cells that are occupied based on an X,Y coordinate system.
My circle looks like this (numbers are position numbers):

And I have set up my X,Y system with position 1 as -2,4.....
Thanks,
Alissa

A: plot(5*c(1,0,-1,0), 5*c(0,1,0,-1) ,col="transparent")  # set coordinate range
abline(h=-5:5); abline(v=-5:5)  # the grid
polygon(  4.3*sin(seq(0,2*pi,length=100)),
          4.3*cos(seq(0,2*pi,length=100)) )  # the circle
abline(h=0,v=0,lwd=2)  # the axes
 text( x=c( (1:4)-2.5,(1:6)-3.5, (1:8)-4.5, (1:8)-4.5, #offsets to center in cells
        (1:8)-4.5, (1:8)-4.5,  (1:6)-3.5, (1:4)-2.5 ),
   y=c( rep(4,4), rep(3,6), rep(2,8), rep(1,8),
            rep(0,8), rep(-1,8), rep(-2,6), rep(-3,4) )-0.5,
   labels=1:52)

Suppressing the axis labels, the axis ticks,  and removing the "overhang" is a simple matter of supplying the correct graphics parameters (for xaxs, yaxs, xaxt, yaxt, xlab and ylab) to the plot function call. Perhaps:
 ..., , xaxs="i", yaxs="i", xaxt="n", yaxt="n", ylab="", xlab="")

Which would produce this:


text:
Q: select as many rows as possible, to guarantee the item density of each column Suppose we have a 0-1 matrix, like:
0, 1, 1, 1, 1
1, 1, 1, 1, 1
1, 0, 1, 0, 1
1, 1, 1, 1, 1
0, 1, 1, 0, 1
1, 1, 0, 1, 0

The goal is to select as many rows as possible from this matrix, to form a new matrix, and guarantee that in the new matrix, each column contains not-less-than 80% of 1.
For example to the above matrix, the result will be:
0, 1, 1, 1, 1
1, 1, 1, 1, 1
1, 0, 1, 0, 1
1, 1, 1, 1, 1
1, 1, 0, 1, 0

Greedy algorithm doesn't work for this problem obviously, neither does a normal DP as I see.
In the real problem, the matrix will have about 7000 rows and 100 columns. And since there would be a few all-1 rows, so there will always exist at least one solution.
Could anyone help to inspire me? Thanks.

A: Implementation of simplistic answer:
(simplistic because the search is "timid" - it only takes one step before evaluating if the state is acceptable, it doesn't re-prioritise to look for rows that will help the columns reaching 80% quicker.
code.rb:
#!/usr/bin/env ruby
data = [
[0, 1, 1, 1, 1 ],
[1, 1, 1, 1, 1 ],
[1, 0, 1, 0, 1 ],
[1, 1, 1, 1, 1 ],
[0, 1, 1, 0, 1 ],
[1, 1, 0, 1, 0 ]
]

# array with blocks of different average densities
data = 990.times.collect do
         limit = rand(1000)
         100.times.collect do
          rand(1000) <= limit ? 1 : 0
        end
      end + 10.times.collect { 100.times.collect { 1 } }

#puts "data = #{data.inspect}"

def sum(list)
  list.inject(0){|res,v| res + v}
end

def column_percent(array)
  multiplier = 100.0 / array.count
  array.transpose.collect{|column| sum(column) * multiplier}
end

sorted_data = data.sort{|a,b| sum(b) <=> sum(a)}

#puts sorted_data.inspect
puts "Data percentages: #{column_percent(data).inspect}"
puts "Average over data: #{column_percent(data).min.inspect}"

solution = [ ]
consider = sorted_data
discarded = [ ]
loops = 0
done_something = true
achieved = [ ]
while (done_something)
  loops += 1
  done_something = false
  while (!consider.empty?)
    row = consider.shift
    #puts "Considerring: #{row.inspect}"
    if column_percent(solution + [ row ]).min >= 80.0
      done_something = true
      solution.push row
    else
      discarded.push row
    end
  end
  achieved << solution.count
  consider = discarded
  discarded = [ ]
end

puts "solution: #{solution.inspect}" if solution.count < 10
puts "solution.percents = #{column_percent(solution).inspect}"
puts "min solution.percents = #{column_percent(solution).min.inspect}"
puts "solution has #{solution.count.inspect} rows"
puts "consider has #{consider.count.inspect} rows"
puts "went through #{loops} loops, achievment at end of each loop: #{achieved.inspect} rows"

exit

END
Results:
Data percentages: [66.66666666666667, 83.33333333333334, 83.33333333333334, 66.66666666666667, 83.33333333333334]
Average over data: 66.66666666666667
solution: [[1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]
solution.percents = [100.0, 100.0, 100.0, 100.0, 100.0]
min solution.percents = 100.0
solution has 2 rows
consider has 4 rows
went through 2 loops, achievment at end of each loop: [2, 2] rows

$ time ruby code.rb # 1000 rows

Data percentages: [50.900000000000006, 48.900000000000006, 50.2, 49.7, 47.5, 50.800000000000004, 50.2, 48.900000000000006, 51.300000000000004, 49.1, 49.900000000000006, 48.7, 49.7, 48.900000000000006, 50.300000000000004, 52.400000000000006, 51.0, 49.900000000000006, 50.800000000000004, 49.6, 49.0, 50.1, 49.1, 48.7, 50.800000000000004, 49.0, 49.2, 49.900000000000006, 48.800000000000004, 50.1, 50.2, 49.6, 49.900000000000006, 50.2, 50.900000000000006, 49.2, 51.7, 49.300000000000004, 48.400000000000006, 49.400000000000006, 49.5, 49.6, 47.7, 50.0, 46.900000000000006, 51.0, 50.0, 51.5, 50.5, 49.300000000000004, 49.1, 50.400000000000006, 47.800000000000004, 51.800000000000004, 50.2, 49.400000000000006, 49.400000000000006, 49.0, 51.5, 48.0, 53.7, 49.1, 51.300000000000004, 50.400000000000006, 50.800000000000004, 48.900000000000006, 50.6, 47.0, 50.300000000000004, 49.400000000000006, 50.800000000000004, 51.300000000000004, 52.900000000000006, 50.0, 51.300000000000004, 47.800000000000004, 51.300000000000004, 47.6, 49.900000000000006, 54.5, 49.5, 51.800000000000004, 50.800000000000004, 50.400000000000006, 51.0, 50.1, 47.7, 49.6, 53.300000000000004, 50.2, 49.7, 51.5, 47.900000000000006, 49.7, 48.0, 48.6, 49.6, 48.900000000000006, 50.1, 50.7]
Average over data: 46.900000000000006
solution.percents = [84.02366863905326, 83.13609467455622, 85.50295857988166, 81.65680473372781, 80.17751479289942, 82.54437869822486, 83.13609467455622, 81.95266272189349, 82.54437869822486, 80.4733727810651, 87.27810650887574, 82.84023668639054, 83.4319526627219, 82.54437869822486, 80.76923076923077, 84.31952662721893, 81.36094674556213, 85.79881656804734, 82.24852071005917, 83.72781065088758, 81.65680473372781, 82.24852071005917, 80.76923076923077, 82.54437869822486, 85.20710059171599, 83.72781065088758, 80.17751479289942, 83.72781065088758, 82.84023668639054, 81.95266272189349, 84.61538461538461, 80.17751479289942, 81.95266272189349, 81.36094674556213, 84.02366863905326, 84.61538461538461, 84.02366863905326, 83.72781065088758, 82.24852071005917, 84.31952662721893, 84.02366863905326, 84.02366863905326, 80.17751479289942, 82.84023668639054, 80.4733727810651, 82.84023668639054, 83.13609467455622, 82.84023668639054, 80.17751479289942, 80.17751479289942, 82.84023668639054, 83.72781065088758, 80.17751479289942, 81.95266272189349, 81.95266272189349, 82.84023668639054, 80.76923076923077, 81.95266272189349, 81.95266272189349, 82.84023668639054, 85.20710059171599, 83.4319526627219, 83.72781065088758, 80.17751479289942, 84.31952662721893, 82.54437869822486, 86.09467455621302, 81.95266272189349, 82.54437869822486, 81.95266272189349, 81.95266272189349, 83.72781065088758, 83.4319526627219, 84.61538461538461, 86.68639053254438, 81.06508875739645, 83.4319526627219, 80.76923076923077, 80.76923076923077, 85.79881656804734, 82.84023668639054, 85.79881656804734, 84.31952662721893, 82.24852071005917, 84.02366863905326, 80.76923076923077, 80.17751479289942, 84.9112426035503, 83.72781065088758, 84.61538461538461, 83.13609467455622, 84.61538461538461, 84.61538461538461, 82.54437869822486, 80.76923076923077, 82.84023668639054, 80.4733727810651, 80.17751479289942, 82.84023668639054, 80.17751479289942]
min solution.percents = 80.17751479289942
solution has 338 rows
consider has 662 rows
went through 3 loops, achievment at end of each loop: [337, 338, 338] rows

real    0m7.588s
user    0m7.435s
sys 0m0.142s

Time for 7000 random rows:
achieved: 2742
Accepted: [1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 0, 1, 0, 1, 0, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1]
achieved: 2743
achieved: 2743
solution.percents = [81.18847976667881, 80.42289464090412, 81.00619759387531, 80.93328472475392, 80.67808968282901, 80.38643820634341, 81.22493620123952, 81.55304411228582, 81.22493620123952, 80.20415603353992, 80.45935107546481, 81.22493620123952, 80.56872037914691, 80.02187386073642, 81.15202333211812, 82.39154210718192, 80.02187386073642, 80.24061246810062, 81.26139263580022, 80.38643820634341, 80.02187386073642, 80.27706890266131, 80.16769959897921, 81.00619759387531, 80.49580751002551, 81.37076193948232, 81.69886985052861, 80.24061246810062, 81.00619759387531, 80.34998177178271, 80.20415603353992, 81.69886985052861, 81.51658767772511, 80.64163324826832, 80.02187386073642, 80.02187386073642, 80.02187386073642, 80.02187386073642, 80.34998177178271, 80.27706890266131, 80.02187386073642, 80.16769959897921, 80.82391542107182, 81.29784907036091, 81.77178271965002, 80.75100255195042, 81.84469558877142, 80.53226394458622, 80.02187386073642, 80.86037185563251, 80.09478672985782, 81.18847976667881, 81.15202333211812, 80.31352533722202, 82.28217280349982, 82.02697776157491, 81.48013124316441, 80.64163324826832, 80.89682829019321, 81.11556689755741, 81.26139263580022, 80.64163324826832, 80.64163324826832, 80.45935107546481, 80.86037185563251, 80.31352533722202, 80.05833029529711, 81.40721837404301, 81.00619759387531, 81.77178271965002, 80.96974115931461, 81.22493620123952, 81.37076193948232, 80.49580751002551, 80.05833029529711, 80.89682829019321, 81.44367480860372, 80.02187386073642, 80.02187386073642, 81.55304411228582, 80.67808968282901, 80.49580751002551, 81.26139263580022, 80.02187386073642, 80.27706890266131, 80.42289464090412, 80.45935107546481, 81.55304411228582, 81.77178271965002, 80.45935107546481, 81.73532628508931, 80.75100255195042, 83.04775792927451, 80.45935107546481, 80.02187386073642, 80.02187386073642, 81.04265402843602, 81.51658767772511, 80.89682829019321, 81.58950054684651]
min solution.percents = 80.02187386073642
solution has 2743 rows
consider has 4267 rows
went through 3 loops, achievment at end of each loop: [2742, 2743, 2743] rows
real    5m57.637s
user    5m57.446s
sys 0m0.335s


text:
Q: On IE cursor is comming always at start in textarea I am dealing with textarea, and on click of this I am calling one replace function which will remove some specified string in textarea, this is the basic operation.
Expected behavior after clicking on textarea
1) At first click :

*

*It should remove specified string from textarea

*Cursor should come at end of string

2) more than one click :
- Cursor should come at where ever user clicks in text area
Below is my replace function....
function replace(id,transFromDb) {
    newStr = $("#"+id).val();
 var len = null;
  if(transFromDb == '') {
   newStr = newStr.replace(Lang.Message27,'');
   newStr = newStr.replace(Lang.Message28,'');

  }
  else {
   newStr = newStr.replace(Lang.Message28,'');
   newStr = newStr.replace(Lang.Message27,'');
  }

  /* change font weight as bold. */
  $("#"+id).css({"fontWeight":"bold"});
  $("#"+id).val(newStr);
}

Assume that Lang.Message is specified string.
It's working above behavior with FF.
Facing issue on IE, it always keep cursor position at first.
Please provide any solution....
Thanks in Adavance
Pravin

A: $("#idOfTextarea").focus(function() {
  replace($(this).attr("id"), "");
});

I'm not sure what the second parameter of replace is receiving, so I've just put an empty string in, you'll have to fill that in yourself.
There's clean and easy code for moving the cursor to the end of the textarea here.


text:
Q: extract text from html tags using regex My HTML text looks like this..I want to extract only PLAIN TEXT from HTML text using REGEX in python (NOT USING HTML PARSERS)

Irrespective of the kind of small business you own, using traditional sales and marketing tactics can prove to be expensive.

How to find exact regex to get the plain text?

A: You can do this with Javascript with a simple selector method and then retrieving the .innerHTML property.
//select the class for which you want to pull the HTML from
let div = document.getElementsByClassName('text-div');
//select the first element of NodeList returned from selector method and get the inner HTML
let text = div[0].innerHTML;

This will select the element whose HTML you want to retrieve and then it will pull the inner HTML text, assuming you only want what is between the HTML tags and not the tags themselves.
Regex is not necessary for this.  You'd have to implement the Regex with JS or some back-end and as long as you can insert a JS script into your project, then you can get the inner HTML.
If you're scraping data, your library in whatever language will most likely have selector methods and ways to easily retrieve the HTML text without the need for Regex.

A: You might be better of using a parser here:
import html, xml.etree.ElementTree as ET

# decode
string = """

Irrespective of the kind of small business you own, using traditional sales and marketing tactics can prove to be expensive.

"""

# construct the dom
root = ET.fromstring(html.unescape(string))

# search it
for p in root.findall("*"):
    print(p.text)

This yields
Irrespective of the kind of small business you own, using traditional sales and marketing tactics can prove to be expensive.

Obviously, you might want to change the xpath, thus have a look at the possibilities.

Addendum:
It is possible to use a regular expression here, but this approach is really error-prone and not advisable:
import re

string = """

Irrespective of the kind of small business you own, using traditional sales and marketing tactics can prove to be expensive.

"""

rx = re.compile(r'(\b[A-Z][\w\s,]+\.)')

print(rx.findall(string))
# ['Irrespective of the kind of small business you own, using traditional sales and marketing tactics can prove to be expensive.']

The idea is to look for an uppercase letter and match word characters, whitespaces and commas up to a dot. See a demo on regex101.com.


text:
Q: Retrieving a javascript variable created in an onchange javascript event I have the following simple form from which a user can select a state to view information on:
<form style="position:absolute; top:65px; left:650px">
    Select State to View:
    <select id="myList" onchange="load_state_data(); xml = getStateInfo();">
      <option selected="selected"></option>
        <?php
            foreach($stateNames as $state){
                echo('<option>'.$state.'</option>');
            }
        ?>
    </select>
</form>

My javascript is as follows:
function load_state_data() {
    var state_name = $("#myList option:selected").val();
    $.ajax({
        type: 'post',
        url: 'state_data.php',
        dataType: "xml",
        data: {
            state_name: $("#myList option:selected").val()
        },
        success: function (data) {
            //clear out previous values
            for (j = 0; j < 5; j++) {
                $('#top_name_' + j).html("");
                $('#top_score_' + j).html("");
            }

            $(data).find('TOP').each(function (index) {
                $('#top_name_' + index).html($(this).find('COMPANY_NAME').text());
                $('#top_score_' + index).html($(this).find('Q_SCORE').text());
            });

            //initialize my temp arrays for reverse ordering the results
            var botName = new Array();
            var botScore = new Array()

            //clear out previous values
            for (j = 0; j < 5; j++) {
                $('#bot_name_' + j).html("");
                $('#bot_score_' + j).html("");
            }

            $(data).find('BOTTOM').each(function (index) {
                //$('#bot_name_'+index).html($(this).find('COMPANY_NAME').text());
                //$('#bot_score_'+index).html($(this).find('Q_SCORE').text());
                botName[index] = $(this).find("COMPANY_NAME").text();
                botScore[index] = $(this).find("Q_SCORE").text();
                j = index;
            });
            var newOrderName = botName.reverse();
            var newOrderScore = botScore.reverse();
            for (i = 0; i < newOrderName.length; i++) {
                $('#bot_name_' + i).html(newOrderName[i]);
                $('#bot_score_' + i).html(newOrderScore[i]);
            }

            //clear the variables from memory
            delete botName;
            delete botScore;
            delete newOrderName;
            delete newOrderScore;

            //cycle through results and save my locations to an array of the map markers
            var inst_info = new Array();
            $(data).find('INST_MARKER').each(function (index) {
                inst_info[index] = [parseFloat($(this).find('LAT').text()),
                parseFloat($(this).find('LONG').text()),
                $(this).find('COMPANY_NAME').text(), $(this).find('Q_SCORE').text()];
            });

            $(data).find('INST_COUNT').each(function () {
                $('#num_total').html($(this).find('NUM_TOTAL').text());
                $('#num_null').html($(this).find('NUM_NULL').text());
            });
            return (inst_info);
        },
        error: function (data) {
            alert('There was an error. Please try again shortly.');
        }
    });
};

I need to access the inst_info generated in this script back on the page it is called from (see form above).  Is this possible, and, if so, how?  I have tried using inst_info = function load_state_data, but that doesn't work.

A: This isn't really possible. The event handler fires asynchronously at some point in time, and there's no code to "return" a value to. Whatever happens in the event handler load_state_data() is isolated from your main javascript code, because nobody knows when, and if at all, it will happen.
You have to do whatever it is you want to do right in the event handler.

A:
I need to access the inst_info generated in this script back on the page it is called from (see form above). Is this possible, and, if so, how?

No. The inst_info is created in the callback function for the success event of your asynchronous request. From there it is available, and you will be able to call a function that sets the state information.
All this happens in the future, after your load_state_data function returns. Yet, you might return a Promise for the data, on which other callback functions can be registered to be executed as soon as the data is available.

    //clear the variables from memory
    delete ...

This code does not work, it is a misuse of the delete operator. You don't need to do this anyway, JavaScript is a garbage-collected language.


text:
Q: Java3D: I'm trying to place 4 cubes next to each other. Why do I get only one cube? I'm basically trying to create a shape via Java3D and only one cube appears on the screen. I want to put the cubes in a line or a column, but I just can't figure out what I'm doing wrong. Obviously this is only part of the code, only the method to create cubes.
private void createCubes() {
                Cuboid box = new Cuboid(0.03f, 0.03f, 0.03f, cubeAppearance);
                Cuboid box2 = new Cuboid(0.03f, 0.03f, 0.03f, cubeAppearance);
                Cuboid box3 = new Cuboid(0.03f, 0.03f, 0.03f, cubeAppearance);
                Cuboid box4 = new Cuboid(0.03f, 0.03f, 0.03f, cubeAppearance);

                Vector3f vector = new Vector3f(0f, .3f, 0f);

                TransformGroup tg = new TransformGroup();
                Transform3D transform = new Transform3D();
                transform.setTranslation(vector);

                tg.addChild(box);
                tg.setTransform(transform);
                tg.addChild(box2);
                tg.setTransform(transform);
                tg.addChild(box3);
                tg.setTransform(transform);
                tg.addChild(box4);
                tg.setTransform(transform);

                rootGroup.addChild(tg);

A: Why do you think your code should put the cubes in a row/column? They all have the same coordinates, sizes, transforms and belong to the same transform group...
You have to create a new transform and transform group for each box you want placed separately.
Something like this should do the trick for 4 boxes:
TransformGroup getNewBox(float hpos) {
  Cuboid box = new Cuboid(0.03f, 0.03f, 0.03f, cubeAppearance);
  TransformGroup tg = new TransformGroup();
  Transform3D transform = new Transform3D();
  Vector3f vector = new Vector3f(0f, hposf, 0f);
  transform.setTranslation(vector);
  tg.addChild(box);
  tg.setTransform(transform);
  return tg;
}

{
  rootGroup.addChild(getNewBox(0f);
  rootGroup.addChild(getNewBox(0.3f);
  rootGroup.addChild(getNewBox(0.6f);
  rootGroup.addChild(getNewBox(0.9f);
}


text:
Q: How can I use get header from within my plugin? I'm writing a plugin to do some specific business logic - edit records for authenticated users, etc.
Rather than having the overhead of a form processing plugin that uses stuff in template tags. I've created a rewrite do redirect like:
/mylisting/909  ->/wp-content/themes/myplugin/edit.php?id=909

Which seems to make sense as I'm keeping the very specific logic to an individual plugin.
The problem is, I want to use my theme within my plugins files as they'll be output in the site's frontend and as such I want them to have the same look and feel.
So I've tried
    get_header();
    include('../mytheme/header.php')
As well as including wp-load.php
...None of which work (I get fatal errors)
Any help?

A:
The problem is, I want to use my theme within my plugins files as
  they'll be output in the site's frontend and as such I want them to
  have the same look and feel.

You already have your answer. You're trying to wrap WordPress and it's theme around your plugin rather than working within the designed mode of operation.
If you already have your plugin why don't you simply write a shortcode handling function to output your page? That way you have all of the functionality of WordPress, the look and feel of your theme; but you also follow WordPress standards and convention.
For a good introduction to writing plugins take a look at the WordPress Codex, it has links to tutorials at the bottom.

A:
I've created a rewrite do redirect like:
/mylisting/909  ->/wp-content/themes/myplugin/edit.php?id=909

Which seems to make sense as I'm keeping the very specific logic to an individual plugin.

There is a better way: Create an endpoint, use your code in a callback handler for the new URL. You get the whole theme environment for free here: get_header(), sidebars, menus etc.
Do not forget to call exit; at the end of your endpoint, othrwise WordPress will use the theme files again. :)
The plugin URI is never a good address to edit or create content: It might be on another domain where the cookies are available, and no user is ever logged in.


text:
Q: Working for Stack Exchange, who and how? I would like to know, how can a user become a Stack Exchange employee? What if I've asked a lot of questions and earned good badges and a lot of points? How is it possible? I've read Stack Exchange employs some users to post questions and answer answers. Is this true? What about other jobs with Stack Exchange, what are they, and how could it be possible to get them?
Thanks.

A: We don't employ anybody who's sole and primary job is to post or answer questions. Well, outside of meta sites where we solicit feedback or respond to bug reports or questions like yours. But even then, it's not a core part of anyone's job.
We're not that different from other tech companies out there. We have job openings, people apply to them, and some get hired. Existing site participation is nice to see, but it's not a requirement for or a guarantee of getting hired.


text:
Q: How to put correctly glyph icon right align and text align centered I am working on a project in bootstrap and my problem is I wanted to align the text in navigation bar to center and glyphicons to right and I tried like navbar-right and text align center but it's not working for me correctly please help me on this.

            toggle navigation

        logo here

SOME TEXT HERE

A: In li tag after glyphicons add padding css to 50% than text will come at center


text:
Q: How can I use "dash.properties.Synced" in the Dash web app? | Python I'm referring to this post so that I can use data from different tabs in the Dash web app.
But I couldn't use dash.properties.Synced and getting the error AttributeError: module 'dash' has no attribute 'properties'.
Sample Code
import dash
import dash_html_components as html
import dash_core_components as dcc
import dash_daq as daq

from dash.dependencies import Input, Output, State

external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']

app = dash.Dash(__name__, external_stylesheets=external_stylesheets)
app.config["suppress_callback_exceptions"] = True

app.layout = html.Div([
    dcc.Store(id="num_output", storage_type='session',),
    dcc.Tabs(id='tabs-example', value='tab-1', children=[
        dcc.Tab(label='Tab one', value='tab-1'),
        dcc.Tab(label='Tab two', value='tab-2'),
    ]),
    html.Div(id='tabs-example-content')
])

@app.callback(Output('tabs-example-content', 'children'),
              Input('tabs-example', 'value'))
def render_content(tab):
    if tab == 'tab-1':
        return html.Div([
            html.H3('Tab content 1'),
            # dcc.Store(id="num_output", storage_type='local',),  # session, local
            html.Div(id="num_output2",),
            html.Div([daq.NumericInput(
                id="num_input",
                label='Vehicles',
                labelPosition='top',
                value=dash.properties.Synced(
                    id='store_model',
                    property='data',
                    default=4
                ),
            ), ], style={'marginLeft': 20, 'marginRight': 20, 'width': '5%', 'display': 'inline-block'}),

        ])
    elif tab == 'tab-2':
        return html.Div([
            html.H3('Tab content 2'),
            html.Div(id="num_output2",),
        ])

@app.callback(
    Output('num_output', 'data'),
    Input('num_input', 'value'))
def render_content(data):
    return data

@app.callback(
    Output('num_output2', 'children'),
    Input('num_output', 'modified_timestamp'),
    State('num_output', 'data'))
def render_content(ts, data):
    if data:
        return html.H4(f'out {data}')

if __name__ == '__main__':
    app.run_server(debug=True)

A: The example code with dash.properties.Synced is not a real API, it is a made-up suggestion from the poster as a possible way to help solve the problem.
I'm not aware of anyone taking this idea forwards.
It is possible to share state across tabs by using global and local 'store' objects that you write-to when updating from within a tab, and that you read-from when drawing the content on the tab.  See my attempt at describing this on the original post


text:
Q: Why there is not a shell process in remote host when using SSH with specific command? I call this in my local machine
ssh -t   anon@192.168.50.81 -p 10086 'echo $SHELL && pstree'

I got /bin/zsh and a normal pstree output without shell process.
Why? And is the first output a fake one?

A: Some shells, like zsh, do not fork a child process to execute the last command in a command line or script. Since the exit status of the line or script is the same as the exit status of the last command, they call exec() in the shell process without forking. So if you execute
sleep 5 && pstree

it will fork a child for sleep, wait for it to finish, then call exec() to run pstree.
Since the pstree process replaces the shell, you don't see the shell in the process tree. pstree will be the child of sshd.
If you change it to
pstree && sleep 5

then you should see the shell in the pstree output, because pstree is no longer the last command.


text:
Q: Conditional Formatting of Row based on multiple cells I am trying to write a formula that will cover A3:AB311, where col f:L has checkboxes and N:AB have dates that are filled in. I want to highlight the entirety of a row if all the boxes in F:L are checked and there is text in each cell in N:AB.
Here is the formula that I have come up with but it only highlights F:L and even then just whichever ones are checked, not if all are checked.
=AND($F3:$L3 = TRUE, NOT(ISBLANK($N3:$T3)), NOT(ISBLANK($V3:$AB3)))
here is a scrubbed version of the doc that I am working with.
https://docs.google.com/spreadsheets/d/15lsA-by2vJOzp8N-_9NxLkkSmYPMAvRcVQ9Gb7KMj-Y/edit?usp=sharing
Line 31 is the only one that should be highlighted
Id really appreciate any assistance you guys could offer, ive been working on this off and on for a few days now.

A: You can use this formula:
=AND($F3:$L3,counta($N3:$T3)=columns($N3:$T3),counta($V3:$AB3)=columns($V3:$AB3))


text:
Q: provide password while unzipping a .zip file I have a zip file that asks for password while extracting. How to provide this password while extracting it in powershell script?
I have been looking into the Expand-Archive, but it does not show how to insert this password. I have already have the password encrypted in a text file:
"P@ssword1" | ConvertTo-SecureString -AsPlainText -Force | ConvertFrom-SecureString | Out-File "C:\Temp 2\Password.txt"

How to feed the password from the file to the Expand-Archive command ? or what other options are there ?

A: As per the built-in help files and the online PowerShell documentation, the Expand-Archive cmdlet provides no means for this use case, nor does it have an option to add a password.
All cmdlets that do provide such a mechanism, have a '-Credential' switch.
# Find all cmdlets / functions with a target parameter
Get-Command -CommandType Function |
Where-Object { $_.parameters.keys -match 'credential'} |
Out-GridView -PassThru -Title 'Available functions which has a specific parameter'

Get-Command -CommandType Cmdlet |
Where-Object { $_.parameters.keys -match 'credential'} |
Out-GridView -PassThru -Title 'Results for cmdlets which has a specific parameter'

Even the native .Net namespace, 'System.IO.Compression' does not provide it. Though there is a project that has been around for a long while to do this with .Net.
About DotNetZip - DotNetZip Documentation
Old project
DotNetZip - CodeProject
Forked version
NuGet Gallery | DotNetZip 1.13.5
Yet, this is not PowerShell specific. It's just a standalone '.exe' to use, just like 7zip, WinZip, etc. Yet, if you are willing to dig at the source code and turn it into a module to use, that's a decision for you to make.
Point of note:
There are already modules in the MS powershellgallery.com that have already done this.
Find-Package -Name '*DotNetZip*'

Name                           Version          Source           Summary
----                           -------          ------           -------
DotNetZip                      1.13.5           nuget.org        A library for dealing with zip, bzip and zlib from .Net
DotNetZip.Reduced              1.9.1.8          nuget.org        DotNetZip is an easy-to-use, FAST, FREE class library and toolset for manipulating zip files or ...
XAct.IO.Compression.DotNetZip  1.1.17040.3290   nuget.org        An XActLib assembly: a library to work with the essentials of DotNetZip.
VirtualPath.DotNetZip          0.3.9            nuget.org        DotNetZip library wrapper for VirtualPath
DotNetZip.NetStandard          1.12.0           nuget.org        A library for dealing with zip, bzip and zlib from .Net
DotNetZip.Zlib.vNextUnofficial 1.9.8.3          nuget.org        DotNetZip vNext port
DotNetZip.Zip.vNextUnofficial  1.9.8.3          nuget.org        DotNetZip vNext port
DotNetZip.Android              1.13.5           nuget.org        A library for dealing with zip, bzip and zlib from .Net
DotNetZip.iOS                  1.13.5           nuget.org        A library for dealing with zip, bzip and zlib from .Net
Bardock.Utils.Web.Mvc.DotNe... 1.0.0            nuget.org        MVC and DotNetZip utilities
...
RI.Framework.Extensions.Dot... 0.7.0            nuget.org        Decoupling & Utilities Framework
DotNetZipforWindows8.1         1.0.0            nuget.org        i make same changes to make this is a package for zip file with password for windows 8.1 and win...

So, use the modules above or you need to shell out to a 3rdP tool, like 7zip, etc...
C:\>"C:\Program Files\7-Zip\7z.exe" a D:\Temp\mytest.zip D:\Temp\mytest.txt -pSecret

7-Zip 19.00 (x64) : Copyright (c) 1999-2018 Igor Pavlov : 2019-02-21

Scanning the drive:
1 file, 64 bytes (1 KiB)

Creating archive: D:\Temp\mytest.zip

Add new data to archive: 1 file, 64 bytes (1 KiB)

Files read from disk: 1
Archive size: 230 bytes (1 KiB)
Everything is Ok

C:\>"C:\Program Files\7-Zip\7z.exe" x D:\Temp\mytest.zip D:\Temp\mytest.txt -pSecret

7-Zip 19.00 (x64) : Copyright (c) 1999-2018 Igor Pavlov : 2019-02-21

Scanning the drive for archives:
1 file, 230 bytes (1 KiB)

Extracting archive: D:\Temp\mytest.zip
--
Path = D:\Temp\mytest.zip
Type = zip
Physical Size = 230

No files to process
Everything is Ok

Files: 0
Size:       0
Compressed: 230

There are several articles regarding how to properly leverage external cmds with PowerShell.

PowerShell: Running Executables
Solve Problems with External Command Lines in PowerShell
Top 5 tips for running external commands in Powershell
Using Windows PowerShell to run old command-line tools (and their
  weirdest parameters)
Execution of external commands in PowerShell done right
https://mnaoumov.wordpress.com/2015/03/31/execution-of-external-commands-native-applications-in-powershell-done-right-part-2
https://mnaoumov.wordpress.com/2015/04/05/execution-of-external-commands-native-applications-in-powershell-done-right-part-3

Quoting is also important when doing this

Quoating specifics

So, you'd end up with this ...
# Using the call operator
& 'C:\Program Files\7-Zip\7z.exe' a 'D:\Temp\mytest.zip' 'D:\Temp\mytest.txt' -pSecret
& 'C:\Program Files\7-Zip\7z.exe' x 'D:\Temp\mytest.zip' 'D:\Temp\mytest.txt' -pSecret

Or using Start-Process with that same string.

A: I installed a module called "7Zip4Powershell" and provided the following command to extract a password protected .zip file.
Expand-7Zip -ArchiveFileName "$($downloadedPath)\$($library.Name)" -TargetPath $extractedPath -SecurePassword (Get-Content $unpackingPassword | ConvertTo-SecureString)


text:
Q: Key column does not exist in table. SQL So I tried looking up other questions and tried them, but I was not able to figure out why my SQL was not working. It keeps saying that DepartmentID table does not exist and I have it declared as my primary key under Department.
CREATE TABLE EMPLOYEE(
SSN INT NOT NULL,
WorkID INT NOT NULL,
BirthDate DATE NOT NULL,
Name VARCHAR(20) NOT NULL,
UNIQUE(WorkID),
PRIMARY KEY(SSN),
FOREIGN KEY(DepartmentID) REFERENCES DEPARTMENT(DepartmentID),
FOREIGN KEY(DeviceID) REFERENCES DEVICE(DeviceID)
);

CREATE TABLE DEPARTMENT(
DepartmentID INT NOT NULL,
DepartmentName VARCHAR (20) NOT NULL,
PRIMARY KEY(DepartmentID),
UNIQUE(DepartmentName)
);

CREATE TABLE PRODUCT(
ProductID INT NOT NULL,
Name VARCHAR(20) NOT NULL,
Isle VARCHAR(5) NOT NULL,
Company VARCHAR(20) NOT NULL,
PRIMARY KEY(ProductID),
FOREIGN KEY(DepartmentID) REFERENCES DEPARTMENT(DepartmentID)
);

CREATE TABLE DEVICE(
DeviceID INT NOT NULL,
DateReceived DATE NOT NULL,
PRIMARY KEY(DeviceID)
);

CREATE TABLE SALES(
SalesID INT NOT NULL,
Profit INT NOT NULL,
Revenue INT NOT NULL,
PRIMARY KEY(SalesID)
);

CREATE TABLE AmountSold(
FOREIGN KEY (SalesID) REFERENCES SALES(SalesID),
FOREIGN KEY (ProductID) REFERENCES PRODUCT(ProductID)
);

A: The problem was that you were making foreign key but the column DepartmentID
 doesn't exist on that table in which you were referencing and the second was
 that your order wasn't correct.
CREATE TABLE DEPARTMENT(
DepartmentID INT NOT NULL,
DepartmentName VARCHAR (20) NOT NULL,
PRIMARY KEY(DepartmentID),
UNIQUE(DepartmentName)
);

CREATE TABLE DEVICE(
DeviceID INT NOT NULL,
DateReceived DATE NOT NULL,
PRIMARY KEY(DeviceID)
);

CREATE TABLE EMPLOYEE(
SSN INT NOT NULL,
WorkID INT NOT NULL,
BirthDate DATE NOT NULL,
DepartmentID INT NOT NULL,
DeviceID INT NOT NULL,
Name VARCHAR(20) NOT NULL,
UNIQUE(WorkID),
PRIMARY KEY(SSN),
FOREIGN KEY(DepartmentID) REFERENCES DEPARTMENT(DepartmentID),
FOREIGN KEY(DeviceID) REFERENCES DEVICE(DeviceID)
);

CREATE TABLE PRODUCT(
ProductID INT NOT NULL,
Name VARCHAR(20) NOT NULL,
DepartmentID INT NOT NULL,
Isle VARCHAR(5) NOT NULL,
Company VARCHAR(20) NOT NULL,
PRIMARY KEY(ProductID),
FOREIGN KEY(DepartmentID) REFERENCES DEPARTMENT(DepartmentID)
);

CREATE TABLE SALES(
SalesID INT NOT NULL,
Profit INT NOT NULL,
Revenue INT NOT NULL,
PRIMARY KEY(SalesID)
);

CREATE TABLE AmountSold(
FOREIGN KEY (SalesID) REFERENCES SALES(SalesID),
FOREIGN KEY (ProductID) REFERENCES PRODUCT(ProductID)
);

A: The problem here you didn't declared the DepartmentId column in Employee table. Also execute the parent table first followed by the ones referring
 CREATE TABLE DEPARTMENT(
 DepartmentID INT NOT NULL,
 DepartmentName VARCHAR (20) NOT NULL,
 PRIMARY KEY(DepartmentID)
 );

 CREATE TABLE DEVICE(
 DeviceID INT NOT NULL,
 DateReceived DATE NOT NULL,
 PRIMARY KEY(DeviceID)
 );

 CREATE TABLE EMPLOYEE(
 SSN INT NOT NULL,
 WorkID INT NOT NULL,
 BirthDate DATE NOT NULL,
 Name VARCHAR(20) NOT NULL,
 DepartmentID INT,
 DeviceID INT ,
 UNIQUE(WorkID),
 PRIMARY KEY(SSN),
 FOREIGN KEY(DepartmentID) REFERENCES DEPARTMENT(DepartmentID),
 FOREIGN KEY(DeviceID) REFERENCES DEVICE(DeviceID)
 );

 CREATE TABLE PRODUCT(
 ProductID INT NOT NULL,
 Name VARCHAR(20) NOT NULL,
 Isle VARCHAR(5) NOT NULL,
 Company VARCHAR(20) NOT NULL,
 DepartmentID INT,
 PRIMARY KEY(ProductID),
 FOREIGN KEY(DepartmentID) REFERENCES DEPARTMENT(DepartmentID)
 );

 CREATE TABLE SALES(
 SalesID INT NOT NULL,
 Profit INT NOT NULL,
 Revenue INT NOT NULL,
 PRIMARY KEY(SalesID)
 );

 CREATE TABLE AmountSold(
 SalesId INT NOT NULL,
 ProductId INT NOT NULL,
 FOREIGN KEY (SalesID) REFERENCES SALES(SalesID),
 FOREIGN KEY (ProductID) REFERENCES PRODUCT(ProductID)
 );


text:
Q: hide an image from facebook I want Facebook to ignore a particular image on a page. Is there any tag I can use that will hide an image from Facebook when users share a page?
We are using Joomla 3.4. The article pages that have an intro section that displays on category listing pages but is hidden on the actual article page. The intro section has a thumbnail 75 x 75.
In the main body of the article there is a larger image that we would like to display on Facebook but the og:image always selects the thumbnail first.
Is there any way I can add some parameter to the thumbnail so that it will be ignored?

A: Why don't you explicitly specify the larger image in your og:image tag? If you specify more than one og:image, as far as I know the first one is selected.
See

*

*https://developers.facebook.com/docs/sharing/webmasters#images

*https://developers.facebook.com/docs/sharing/webmasters/optimizing#cachingimages

*https://developers.facebook.com/docs/sharing/best-practices#images


text:
Q: Is Sodium for Java a good fit for using it with Scala+ScalaFX? After watching this talk I decided to try to make a Scala/ScalaFX app in a reactive style. Naturally, after this talk, I am thinking about using the Java implementation of the Sodium library for this task. I am unsure, however, how compatible it is with Scala?
Would Sodium Java be a good way to build a reactive ScalaFX app or should I look for a more suitable framework for this task ?
Here is a more specific question to people who already tried this combination:
What difficulties ( if any ) did arise when combining Sodium Java with Scala/ScalaFX ?


text:
Q: Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack Below code throw an exception at "Item.Update();"
    private void AddEmail()
    {
        site = SPContext.Current.Site;
        web = site.RootWeb;

        SPSecurity.RunWithElevatedPrivileges(delegate()
        {
            using (site = SPContext.Current.Site)
            {
                using (web = site.RootWeb)
                {
                    try
                    {
                        SPList list = web.Lists["Newsletter"];
                        SPListItem Item = list.Items.Add();
                        web.AllowUnsafeUpdates = true;
                        Item["Title"] = txtEmail.Text;
                        Item.Update();
                        SendEmail();

                        txtEmail.Text = "";
                    }
                    catch (Exception ex)
                    {
                        ltrMessage.Text = ex.Message;
                    }
                }
            }
        });
    }

Can anyone help me get over this ?

A: When running inside RunWithElevatedPrivileges, do not use SPContext.Current. Instead create a new SPSite object, passing in SPContext.Current.Site.Url.


text:
Q: Java 17 java.lang.reflect.InaccessibleObjectException: Unable to make field private final java.time.ZoneOffset I have been trying to convert a json string to variables my java program can use but when i run this it doesnt work.
(responseString is a valid json string)
GetConversion conversion = new ObjectMapper().readValue(responseString, GetConversion.class);

class GetConversion{
private State state;
private Swupdate swupdate;
private String type;
private String name;
private String modelid;
private String manufacturername;
private String productname;
private Capabilities capabilities;
private Config config;
private String uniqueid;
private String swversion;
private String swconfigid;
private String productid;

public State getState() { return state; }
public void setState(State value) { this.state = value; }

public Swupdate getSwupdate() { return swupdate; }
public void setSwupdate(Swupdate value) { this.swupdate = value; }

public String getType() { return type; }
public void setType(String value) { this.type = value; }

public String getName() { return name; }
public void setName(String value) { this.name = value; }

public String getModelid() { return modelid; }
public void setModelid(String value) { this.modelid = value; }

public String getManufacturername() { return manufacturername; }
public void setManufacturername(String value) { this.manufacturername = value; }

public String getProductname() { return productname; }
public void setProductname(String value) { this.productname = value; }

public Capabilities getCapabilities() { return capabilities; }
public void setCapabilities(Capabilities value) { this.capabilities = value; }

public Config getConfig() { return config; }
public void setConfig(Config value) { this.config = value; }

public String getUniqueid() { return uniqueid; }
public void setUniqueid(String value) { this.uniqueid = value; }

public String getSwversion() { return swversion; }
public void setSwversion(String value) { this.swversion = value; }

public String getSwconfigid() { return swconfigid; }
public void setSwconfigid(String value) { this.swconfigid = value; }

public String getProductid() { return productid; }
public void setProductid(String value) { this.productid = value; }
}

class Capabilities {
   private boolean certified;
   private Control control;
   private Streaming streaming;

    public boolean getCertified() { return certified; }
    public void setCertified(boolean value) { this.certified = value; }

    public Control getControl() { return control; }
    public void setControl(Control value) { this.control = value; }

    public Streaming getStreaming() { return streaming; }
    public void setStreaming(Streaming value) { this.streaming = value; }
}

class Control {
    private long mindimlevel;
    private long maxlumen;
    private String colorgamuttype;
    private double[][] colorgamut;
    private CT ct;

    public long getMindimlevel() { return mindimlevel; }
    public void setMindimlevel(long value) { this.mindimlevel = value; }

    public long getMaxlumen() { return maxlumen; }
    public void setMaxlumen(long value) { this.maxlumen = value; }

    public String getColorgamuttype() { return colorgamuttype; }
    public void setColorgamuttype(String value) { this.colorgamuttype = value; }

    public double[][] getColorgamut() { return colorgamut; }
    public void setColorgamut(double[][] value) { this.colorgamut = value; }

    public CT getCT() { return ct; }
    public void setCT(CT value) { this.ct = value; }
}

class CT {
    private long min;
    private long max;

    public long getMin() { return min; }
    public void setMin(long value) { this.min = value; }

    public long getMax() { return max; }
    public void setMax(long value) { this.max = value; }
}

class Streaming {
    private boolean renderer;
    private boolean proxy;

    public boolean getRenderer() { return renderer; }
    public void setRenderer(boolean value) { this.renderer = value; }

    public boolean getProxy() { return proxy; }
    public void setProxy(boolean value) { this.proxy = value; }
}

class Config {
    private String archetype;
    private String function;
    private String direction;
    private Startup startup;

    public String getArchetype() { return archetype; }
    public void setArchetype(String value) { this.archetype = value; }

    public String getFunction() { return function; }
    public void setFunction(String value) { this.function = value; }

    public String getDirection() { return direction; }
    public void setDirection(String value) { this.direction = value; }

    public Startup getStartup() { return startup; }
    public void setStartup(Startup value) { this.startup = value; }
}

class Startup {
    private String mode;
    private boolean configured;

    public String getMode() {
        return mode;
    }

    public void setMode(String value) {
        this.mode = value;
    }

    public boolean getConfigured() {
        return configured;
    }

    public void setConfigured(boolean value) {
        this.configured = value;
    }
}

class State {
    private boolean on;
    private long bri;
    private long hue;
    private long sat;
    private String effect;
    private double[] xy;
    private long ct;
    private String alert;
    private String colormode;
    private String mode;
    private boolean reachable;

    public boolean getOn() { return on; }
    public void setOn(boolean value) { this.on = value; }

    public long getBri() { return bri; }
    public void setBri(long value) { this.bri = value; }

    public long getHue() { return hue; }
    public void setHue(long value) { this.hue = value; }

    public long getSat() { return sat; }
    public void setSat(long value) { this.sat = value; }

    public String getEffect() { return effect; }
    public void setEffect(String value) { this.effect = value; }

    public double[] getXy() { return xy; }
    public void setXy(double[] value) { this.xy = value; }

    public long getCT() { return ct; }
    public void setCT(long value) { this.ct = value; }

    public String getAlert() { return alert; }
    public void setAlert(String value) { this.alert = value; }

    public String getColormode() { return colormode; }
    public void setColormode(String value) { this.colormode = value; }

    public String getMode() { return mode; }
    public void setMode(String value) { this.mode = value; }

    public boolean getReachable() { return reachable; }
    public void setReachable(boolean value) { this.reachable = value; }
}

class Swupdate {
    private String state;
    private OffsetDateTime lastinstall;

    public String getState() { return state; }

    public OffsetDateTime getLastinstall() { return lastinstall; }
}

I believe it may have something to do with the last part of the code "public OffsetDateTime getLastinstall() { return lastinstall; }" because the error mentions java.time.OffsetDateTime and this is where that is called.
When I run this it gives a this error:
Exception in thread "main" java.lang.reflect.InaccessibleObjectException: Unable to make field private final java.time.ZoneOffset java.time.OffsetDateTime.offset accessible: module java.base does not "opens java.time" to unnamed module @3578436e
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:354)
at java.base/java.lang.reflect.AccessibleObject.checkCanSetAccessible(AccessibleObject.java:297)
at java.base/java.lang.reflect.Field.checkCanSetAccessible(Field.java:178)
at java.base/java.lang.reflect.Field.setAccessible(Field.java:172)
at com.fasterxml.jackson.databind.util.ClassUtil.checkAndFixAccess(ClassUtil.java:891)
at com.fasterxml.jackson.databind.deser.impl.FieldProperty.fixAccess(FieldProperty.java:102)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBuilder._fixAccess(BeanDeserializerBuilder.java:484)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBuilder.build(BeanDeserializerBuilder.java:350)
at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.buildBeanDeserializer(BeanDeserializerFactory.java:245)
at com.fasterxml.jackson.databind.deser.BeanDeserializerFactory.createBeanDeserializer(BeanDeserializerFactory.java:137)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer2(DeserializerCache.java:411)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createDeserializer(DeserializerCache.java:349)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:264)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244)
at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142)
at com.fasterxml.jackson.databind.DeserializationContext.findNonContextualValueDeserializer(DeserializationContext.java:467)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.resolve(BeanDeserializerBase.java:473)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:293)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244)
at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142)
at com.fasterxml.jackson.databind.DeserializationContext.findNonContextualValueDeserializer(DeserializationContext.java:467)
at com.fasterxml.jackson.databind.deser.BeanDeserializerBase.resolve(BeanDeserializerBase.java:473)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCache2(DeserializerCache.java:293)
at com.fasterxml.jackson.databind.deser.DeserializerCache._createAndCacheValueDeserializer(DeserializerCache.java:244)
at com.fasterxml.jackson.databind.deser.DeserializerCache.findValueDeserializer(DeserializerCache.java:142)
at com.fasterxml.jackson.databind.DeserializationContext.findRootValueDeserializer(DeserializationContext.java:477)
at com.fasterxml.jackson.databind.ObjectMapper._findRootDeserializer(ObjectMapper.java:4190)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4009)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3004)
at sendCommands.Loft.runGet(Loft.java:141)
at sendCommands.Loft.routine(Loft.java:103)
at sendCommands.Main.main(Main.java:7)

Help fix this pls. The json I used for response string is :
{
    "state": {
        "on": true,
        "bri": 198,
        "hue": 25360,
        "sat": 254,
        "effect": "none",
        "xy": [
            0.1749,
            0.6963
        ],
        "ct": 500,
        "alert": "none",
        "colormode": "xy",
        "mode": "homeautomation",
        "reachable": true
    },
    "swupdate": {
        "state": "noupdates",
        "lastinstall": "2021-08-13T13:51:54"
    },
    "type": "Extended color light",
    "name": "Hue color spot 6",
    "modelid": "LCG002",
    "manufacturername": "Signify Netherlands B.V.",
    "productname": "Hue color spot",
    "capabilities": {
        "certified": true,
        "control": {
            "mindimlevel": 200,
            "maxlumen": 300,
            "colorgamuttype": "C",
            "colorgamut": [
                [
                    0.6915,
                    0.3083
                ],
                [
                    0.17,
                    0.7
                ],
                [
                    0.1532,
                    0.0475
                ]
            ],
            "ct": {
                "min": 153,
                "max": 500
            }
        },
        "streaming": {
            "renderer": true,
            "proxy": true
        }
    },
    "config": {
        "archetype": "spotbulb",
        "function": "mixed",
        "direction": "downwards",
        "startup": {
            "mode": "safety",
            "configured": true
        }
    },
    "uniqueid": "00:17:88:01:08:3f:fb:56-0b",
    "swversion": "1.88.2",
    "swconfigid": "4AF23F6F",
    "productid": "Philips-LCG002-1-GU10ECLv2"
}

A: It looks to me like it's a problem with Jackson attempting to serialize an OffsetDateTime field - it's trying to access the OffsetDateTime's private 'offset' property.
Jackson needs to be told how to serialize OffsetDateTime properly.
You can either add another Jackson library dependency to take care of this, or write a custom object mapper, if you need a format not provided by the library.
See Jackson date-format for OffsetDateTime in Spring Boot

A: I encountered a similar issue when I was unit testing Twilio SMS.
I solved the issue by registering JavaTimeModule on the ObjectMapper.
        String json = "{\"status\": \"sent\"}";
        ObjectMapper mapper = new ObjectMapper();
        mapper.registerModule(new JavaTimeModule());
        var message = Message.fromJson(json, mapper);