text:
Q: TreeView - множественное выделение по типу ноды Предисловие
Решаю для меня сложную задачку по визуализации данных, проект большой и требует рефакторинга, застрял. Не могу рефакторить, пока не приму архитектурное решение по данной фиче. Поэтому создал отдельный демо-проект, чтобы воспроизвести то, что мне требуется.
Это не простой TreeView с мультиселектом, поэтому готовые решения с гитхаба мне не подошли, к тому же мне требуется особая визуализация, которой я уже смог добиться в XAML разметке. Проблема только с логикой.
Задача

*

*Дано дерево элементов, каждая нода имеет свой айдишник и тип.

*TreeView отображает эти ноды в виде визуального дерева. Ноды могут быть выбранными (активными) или не выбранными (не активными).

*По умолчанию выбраны ноды верхнего уровня.

*Одновременно может быть выбрана только одна нода для каждого типа. - вот здесь застрял

*Всегда должно быть выбрано постоянное количество нод, сколько типов нод присутствует в дереве - столько и выбрано.

*Отдельно должна формироваться коллекция с айдишниками выбранных. На основе этой коллекции я буду заполнять другой контрол контентом.

Для видимости, вот реализация интерфейса INPC
public class NotifyPropertyChanged : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

Данные
public enum TreeNodeType
{
    Red,
    Green,
    Blue
}

public class TreeItem : NotifyPropertyChanged
{
    private TreeNodeType _nodeType;
    private int _nodeId;
    private ObservableCollection<TreeItem> _items;
    private bool _selected;
    private bool _active;

    public int NodeId
    {
        get => _nodeId;
        set
        {
            _nodeId = value;
            OnPropertyChanged();
        }
    }
    public TreeNodeType NodeType
    {
        get => _nodeType;
        set
        {
            _nodeType = value;
            OnPropertyChanged();
        }
    }
    public ObservableCollection<TreeItem> Items // TreeViewItem.ItemsSource
    {
        get => _items;
        set
        {
            _items = value;
            OnPropertyChanged();
        }
    }
    public bool Selected // TreeViewItem.IsSelected
    {
        get => _selected;
        set
        {
            _selected = value;
            Active = value;
            OnPropertyChanged();
        }
    }
    public bool Active // моя попытка выделять элемент
    {
        get => _active;
        set
        {
            if (value) _active = !_active;
            OnPropertyChanged();
        }
    }
}

View Model
public class MainViewModel : NotifyPropertyChanged
{
    private ObservableCollection<TreeItem> _treeItems;
    private ObservableCollection<int> _selectedItems;

    public ObservableCollection<TreeItem> TreeItems
    {
        get => _treeItems;
        set
        {
            _treeItems = value;
            OnPropertyChanged();
        }
    }

    public ObservableCollection<int> SelectedItems // сюда хочу записать айдищшники выбранных нод
    {
        get => _selectedItems;
        set
        {
            _selectedItems = value;
            OnPropertyChanged();
        }
    }

    public MainViewModel()
    {
        // тестовые данные
        TreeItems = new ObservableCollection<TreeItem>
        {
            new TreeItem
            {
                NodeId = 0,
                NodeType = TreeNodeType.Red,
                Items = new ObservableCollection<TreeItem>
                {
                    new TreeItem
                    {
                        NodeId = 1,
                        NodeType = TreeNodeType.Red,
                        Items = new ObservableCollection<TreeItem>
                        {
                            new TreeItem { NodeId = 2, NodeType = TreeNodeType.Green },
                            new TreeItem { NodeId = 3, NodeType = TreeNodeType.Red }
                        }
                    },
                    new TreeItem { NodeId = 4, NodeType = TreeNodeType.Red }
                },
                Selected = true
            },
            new TreeItem
            {
                NodeId = 5,
                NodeType = TreeNodeType.Blue,
                Items = new ObservableCollection<TreeItem>
                {
                    new TreeItem
                    {
                        NodeId = 6,
                        NodeType = TreeNodeType.Blue,
                        Items = new ObservableCollection<TreeItem>
                        {
                            new TreeItem { NodeId = 7, NodeType = TreeNodeType.Blue }
                        }
                    },
                    new TreeItem { NodeId = 8, NodeType = TreeNodeType.Green }
                },
                Selected = true
            },
            new TreeItem
            {
                NodeId = 9,
                NodeType = TreeNodeType.Green,
                Selected = true
            }
        };

        SelectedItems = new ObservableCollection<int>();
    }
}

Разметка
<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition/>
        <ColumnDefinition/>
    </Grid.ColumnDefinitions>
    <TreeView ItemsSource="{Binding TreeItems}">
        <TreeView.Resources>
            <Style TargetType="{x:Type TreeView}">
                <Setter Property="OverridesDefaultStyle" Value="True" />
                <Setter Property="SnapsToDevicePixels" Value="True" />
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type TreeView}">
                            <ItemsPresenter/>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
            <Style TargetType="TreeViewItem">
                <Setter Property="ItemsSource" Value="{Binding Items}"/>
                <Setter Property="IsSelected" Value="{Binding Selected}"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate>
                            <StackPanel>
                                <StackPanel Margin="2" >
                                    <Border BorderThickness="1" HorizontalAlignment="Center" Margin="2">
                                        <Border.Style>
                                            <Style TargetType="{x:Type Border}">
                                                <Style.Triggers>
                                                    <DataTrigger Binding="{Binding Active}" Value="True">
                                                        <Setter Property="BorderBrush" Value="Black"/>
                                                    </DataTrigger>
                                                </Style.Triggers>
                                            </Style>
                                        </Border.Style>
                                        <Grid>
                                            <Rectangle Width="30" Height="30" Margin="2">
                                                <Rectangle.Style>
                                                    <Style TargetType="Rectangle">
                                                        <Style.Triggers>
                                                            <DataTrigger Binding="{Binding NodeType}" Value="Red">
                                                                <Setter Property="Fill" Value="Red"/>
                                                            </DataTrigger>
                                                            <DataTrigger Binding="{Binding NodeType}" Value="Green">
                                                                <Setter Property="Fill" Value="Green"/>
                                                            </DataTrigger>
                                                            <DataTrigger Binding="{Binding NodeType}" Value="Blue">
                                                                <Setter Property="Fill" Value="Blue"/>
                                                            </DataTrigger>
                                                        </Style.Triggers>
                                                    </Style>
                                                </Rectangle.Style>
                                            </Rectangle>
                                            <TextBlock Text="{Binding NodeId}" HorizontalAlignment="Center" VerticalAlignment="Center" Foreground="White"/>
                                        </Grid>
                                    </Border>
                                </StackPanel>
                                <ItemsPresenter/>
                            </StackPanel>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
                <Setter Property="ItemsPanel">
                    <Setter.Value>
                        <ItemsPanelTemplate>
                            <StackPanel Orientation="Horizontal"/>
                        </ItemsPanelTemplate>
                    </Setter.Value>
                </Setter>
            </Style>
        </TreeView.Resources>
        <TreeView.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel Orientation="Horizontal"/>
            </ItemsPanelTemplate>
        </TreeView.ItemsPanel>
    </TreeView>
    <ItemsControl Grid.Column="1" ItemsSource="{Binding SelectedItems}"/>
</Grid>

Подскажите, куда копать? Как найти ранее выделенную ноду этого же типа, снять с нее выделение, и только после этого выделить текущую?

A: Что то вы намудрили с этим Selected vs Active, по хорошему логику с отметками вынести куда то модель нужно и протестировать. Я то просто сделал ваш пример работоспособным. Что я сделал:
В главной модели добавил пару методов
    public void Deactive(TreeNodeType type)
    {
        if (TreeItems != null)
            foreach (var treeItem in TreeItems)
                Deactive(treeItem, type);
    }

    private void Deactive(TreeItem node, TreeNodeType type)
    {
        if (node.Active && node.NodeType == type)
        {
            node.Active = false;
        }

        if (node.Items != null)
            foreach (var item in node.Items)
                Deactive(item, type);
    }

Добавил в ноду ссылку на главную модель
public class TreeItem : NotifyPropertyChanged
{
    ....
    public MainViewModel MainViewModel { get; set; }

Чуть поправил логику на Selected/Active
    public bool Selected // TreeViewItem.IsSelected
    {
        get => _selected;
        set
        {
            _selected = value;
            if (value)
                Active = value;
            OnPropertyChanged();
        }
    }
    public bool Active // моя попытка выделять элемент
    {
        get => _active;
        set
        {
            if (value) MainViewModel.Deactive(NodeType);
            _active = value;
            OnPropertyChanged();
        }
    }

Что вышло из этого

Закинул что наклепал на Github. Но повторюсь, я бы такую логику вынес куда то в модель, а то вся эта мешанина через лет 5 вам аукнется.


text:
Q: Compiler warnings and -(void)forwardInvocation:(NSInvocation *)iInvocation I have a class which is mostly delegating its method implementations to a member variable.
To simplify writing it I implemented
-(void)forwardInvocation:(NSInvocation *)iInvocation;

and
-(NSMethodSignature*)methodSignatureForSelector:(SEL)aSelector;

This enabled my class to implement a few protocols without a large amount of boilerplate code.
It is working pretty well, except that the compiler is throwing warnings for all the methods I am not implementing, which are actually forwarded to the member variable.
Is there a way for me to tell the system that those methods are in fact implemented, or to shut up just those warnings for just that source?
The compiler is emitting 3 kinds of warnings:

*

*Method in Protocol not implemented

*Property XXX requires method XXX

*to be implemented Incomplete implementation

In the code bellow the class of the object I delegate to is ShareUser and the instance is _user
-(void)forwardInvocation:(NSInvocation *)iInvocation
{
    SEL aSelector = [iInvocation selector];
    if ([ShareUser instancesRespondToSelector:aSelector])
        [iInvocation invokeWithTarget:_user];
    else
        [self doesNotRecognizeSelector:aSelector];
}
-(NSMethodSignature*)methodSignatureForSelector:(SEL)aSelector
{
    if ([ShareUser instancesRespondToSelector:aSelector])
        return [ShareUser instanceMethodSignatureForSelector:aSelector];

    return nil;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using lidR to count number of pulse returns at different intervals? I am trying to get the number of pulse at different height interval.
I have used the lidR package to do this before with the code below but it seems that recent update in the package breaks my code. My main error is that when I run the function I get an error that says the ScanAngle and PulseID no longer exist. Any help on which function I should use now?
The following code used to work:
# the number of points is computed.
grid_metrics3d(lidar1, length(Z),res = 0.5)

# Cloud of points is voxelized with a 1-meter resolution and in each voxel
# the mean scan angle of points is computed.
grid_metrics3d(lidar1, mean(Angle),res = 0.5)

# Define your own metric function
myMetrics = function(i, ScanAngleRank, PointSourceID)
{
  ret = list(
   npulse  = length(unique(PointSourceID)),
   angle   = mean(ScanAngleRank),
   imean   = mean(i))

   return(ret)
}

voxels1 = grid_metrics3d(lidar1, myMetrics(Intensity, ScanAngle, PointID ),res = 0.5)
plot(voxels1)

A: You were almost there. You missed to compute the pulseID with laspulse() and you missed that the scan angle is stored in ScanAngleRank
Since lidR 2.0.0 pulseID is no longer computed at read time. And since rlas 1.3.0 that introduced support of LAS 1.4 format the attribute ScanAngle is now ScanAngleRank. The name ScanAngle is reserved for angle stored in LAS 1.4 format. This latest modification is known to break former codes like yours but was required to better fit with LAS specifications
LASfile <- system.file("extdata", "Megaplot.laz", package="lidR")
las = readLAS(LASfile)
las = laspulse(las)

myMetrics = function(I, A, ID)
{
  ret = list(
    npulse  = length(unique(ID)),
    angle   = mean(A),
    imean   = mean(I))

  return(ret)
}

voxels1 = grid_metrics3d(las, ~myMetrics(Z, ScanAngleRank, pulseID), res = 10)
plot(voxels1, "npulse")

Also notice that PointSourceID is not at all related to your question.  PointSourceID usually records an ID for each flightline


text:
Q: Attaching data/object to a tab in tabbed layout I have created a tab Layout which creates a tab for every doctor object i have in a List. Currently i am setting the tab title as doctor name but when a tab is selected, I want to get the id of the corresponding doctor. I could get this from the position in the list but i am hoping there is a cleaner solution. Is there any way to attach an object or even just an id to a tab on creation so that i can access it directly from the selected tab when my listener is fired?
tabLayout.addTab(tabLayout.newTab().setText("All"));
for(Doctors doctor: list)
{
    TabLayout.Tab tempTab = tabLayout.newTab().setText(doctor.getName());
    tempTab.setIcon(R.drawable.john_smith_photo);

    //here i would like to put doctor.getId() into my tab
    tabLayout.addTab(tempTab);
}

A: Have you tried using setTag() method? See docs. You can use it in any class that extends View and you can store data with it. To retrieve the data, you can use getTag(). Also works for TabLayout.Tab.

Tags can also be used to store data within a view without resorting to another data structure.

It's as simple as:
tempTab.setTag(doctor.getId());


text:
Q: Convert Fixed Value to Floating Value in SPSS I have data in '0' and '1' form in my SPSS data file, but according to my client's need I have to convert it in the form '1','2','3','4','5','6','7','8','9','10','11'.
Is there any way to do so in SPSS? If there is, please do let me know.
Thanks

A: Assuming @Jinesh Sutar is correct in the above comment, to change your multiple variables into a single categorical variable you can use the following syntax. varx and newvar would obviously need renamed for your dataset.
IF (var1=1) newvar=1.
IF (var2=1) newvar=2.
IF (var3=1) newvar=3.
IF (var4=1) newvar=4.
IF (var5=1) newvar=5.
IF (var6=1) newvar=6.
IF (var7=1) newvar=7.
IF (var8=1) newvar=8.
IF (var9=1) newvar=9.
IF (var10=1) newvar=10.
IF (var11=1) newvar=11.
EXECUTE.

A: Nikhil, if I am correct, the data you must be having is in checked/ unchecked form. You need to convert it into Item numbers per column. This can be done using vectors in SPSS:
vector multin = var1 to var11.
loop #i=1 to 11.
if (multin(#i)=1) multin(#i)=#i.
end loop.
exe.

Using this, there is no need to create a new variable(newvar).


text:
Q: Shopify product page - update slick slider to selected variant I added a slick slider to Shopify's Boundless theme's product page and it properly displays the products images. The part where I'm having trouble is making the slider update to match the selected variant.
Here is the relevant JS:

productVariantCallback: function(variant) {
      var $pageLink = $(selectors.pageLink, this.$container);

      if (variant) {
        if (variant.featured_image) {
           var newImg = variant.featured_image;
          var el = $(selectors.variantImage)[0];

          var $slider=$('#product-slides');
          if( $slider.length ) {
            var newImgBase = newImg.src.substring(0, newImg.src.lastIndexOf('.')).split(':').pop();

            if( $slider.hasClass('slick-initialized') ) {
              var newIndex =   $('#product-slides.slick-initialized img[src^="' + newImgBase + '"]')

              .closest('.slick-slide')
              .last()
              .data('slick-index');
              console.log( 'Goto slide ' + newIndex );
              $slider.slickGoTo( newIndex, true  );
            } else {
              var newIndex =   $('#product-slides img').index( $('#product-slides img[src^="' + newImgBase + '"]'));
              Shopify.sliderInitAt = newIndex ;
            }
          }

// more code, but I don't believe it is relevant to the issue

and the relevant chunks of liquid:

  {% assign current_variant = product.selected_or_first_available_variant %}

  {% assign featured_image = current_variant.featured_image | default: product.featured_image %}

  <meta itemprop="url" content="{{ shop.url }}{{ product.url }}">
  <meta itemprop="image" content="{{ featured_image | img_url: 'grande' }}">
  <meta itemprop="name" content="{{ product.title }}{% if product.variants.size > 1 and product.selected_variant %} - {{ current_variant.title }}{% endif %}">

    {% assign first_image = featured_image %}

    {% if product.images.size > 1 and section.settings.skip_first_product_image and first_image == product.featured_image %}
      {% assign first_image = product.images[1] %}
    {% endif %}

    {% if product.images.size > 0 %}

            {% for image in product.images %}

          {% endfor %}

            {% for image in product.images %}

            {% endfor %}

    {% endif %}

            {% form 'product', product, id:form_id, class:form_class, data-cart-form: '' %}

          <select name="id" id="ProductSelect-{{ section.id }}">
              {% for variant in product.variants %}
                <option {% if variant == product.selected_or_first_available_variant %} selected="selected" {% endif %} {% unless variant.available %} disabled="disabled" {% endunless %} value="{{ variant.id }}" data-sku="{{ variant.sku }}">{{ variant.title }} - {% if variant.available %}{{ variant.price | money_with_currency }}{% else %}{{ 'products.product.sold_out' | t }}{% endif %}</option>
              {% endfor %}
            </select>

          {% endform %}

coding is not at all my field, so I have no idea what I'm saying when I say: I think it might be that my images need to be indexed on the liquid side then referenced on the JS side

A:


text:
Q: How to know which process is causing high memory usage on DB? I've got one Onesight alert mail stating below:
Short Description: Onesight Alert: ZEUS DB Monitor (zeus04)
Description:
Solaris 5.8: vmstat memory(free) - Free Memory for zeus04 2065112   8:06:02 AM IST    2 min
  Free Memory below 4GB: Value was 3,965,488 , threshold is 4194304.0 - 12:36:02 AM IST
Upon issuing OS level commands below I got the following understanding:
prstat
This command returned me the top process ID(3578) which is using more CPU. then,
prstat -Lm -p 3578
this command returned me the following output:
PID USERNAME USR SYS TRP TFL DFL LCK SLP LAT VCX ICX SCL SIG PROCESS/LWPID
3578 oracle 0.7 2.3 1.6 0.0 0.0 90 4.4 1.5 483 235 1K 0 java/838694
3578 oracle 0.3 0.0 0.2 0.0 0.0 95 1.5 0.1 52 8 41 0 java/839336
I thought some Java process would be running so asked the Apps Support team and the said:
we believe this process is related to the Oracle OEM agent Java process
Now how do i drill down the issue and resolve because free memory is going below 2GB almost everyday.
DB environment details:
OS:Solaris 5.8(Unix)
DB version: 10.2.0.5
Memory size:64 GB
Regards,
Ritu

A: The software you use is out of date. An advantage of that is that there could very well be a solution provided in My Oracle Support. The Oracle OEM agent have lot's of problems in many versions. Prepare for patching the agents or use a daily restart agent procedure. The Oracle OEM agent is part of the Grid Control monitoring infra structure so you could take it down without harming the application that is using the database[s] that the agent is monitoring.


text:
Q: Generate the double cover of $\text{O}_3 \mathbb{R}$ Two questions when I read the book Representation Theory: a first course by Fulton and Harris in Page 300.
If $D$ is the unit ball in $\mathbb{R}^3$, there is a double covering
\begin{align*}
\text{S}^3 = D^3/\partial D^3 &\to \text{SO}_3 \mathbb{R}
\end{align*}
which sends a vector v in $D^3$ to rotation by the angle $2\pi||v|| $ about the unit vector $v/||v||$. (the origin and the unit sphere $\partial D^3$ are sent to the identity transformation).
1. Can we know $S^3=D^3/\partial D^3$ without this map? (from another way)

i.e If we check the map is a double covering of $\text{SO}_3\mathbb{R}$, we will get $S^3=D^3/\partial D^3$ because the doble covering of $\text{SO}_3\mathbb{R}$ is $S^3$.

Edit: $D^2/\partial D^2\cong S^2$ is easy to see. $S^3=D^3/\partial D^3$ is similar to it.
This covering is even easier to see for the entire orthogonal group $\text{O}_3\mathbb{R}$ which is generated by reflection $R_v$ in unit vectors $v$(with $\pm v$ determining the same reflection): we can describe the double cover of $\text{O}_3 \mathbb{R}$ as the group generated by unit vectors $v$, with relations
\begin{align}
v_1\cdot v_2\dots v_{n-1} \cdot v_n = w_1\cdot w_2\dots w_{m-1} \cdot w_m
\end{align}
whenever the compositions of the corresponding reflections are equal, i.e whenever
\begin{align*}
R_{v_1}\circ \dots \circ R_{v_n}=R_{w_1}\circ \dots \circ R_{w_m}
\end{align*}
and also relations
\begin{align*}
(-v)\cdot(-w)=v\cdot w
\end{align*}
for all pairs of unit vectors $v$ and $w$. (Note that if we restricted ourselves to products of even numbers of the generators $v \in \partial D^3$ we could get back to the double cover of $\text{SO}_3\mathbb{R}$).
2. I don't understand what role the relations $ v_1\cdot v_2\dots v_{n-1} \cdot v_n = w_1\cdot w_2\dots w_{m-1} \cdot w_m$ play in generating the double cover of $\text{O}_3\mathbb{R}$. I think two reflection will make a rotation like dihedral group, but i don't know other things.


text:
Q: Can anyone explain why a B-H curve with Hysteresis doesn't result in a highly non-linear input-output transfer function for a transformer? See the attached picture of a typical hysteresis loop, it is clearly highly non-linear even if you keep the signal small enough to stay out of the saturation region (beyond points b,e). So my question is why does this not result in a non-linear transfer function through the transformer from primary to secondary? Ampere's Law dictates that the H field generated is proportional to the current in the primary, so if I have a sinusoidal current as the input the graph below suggests that this will result in a B field which is a (non-linearly) distorted sinusoid and then the induced voltage in the secondary will be proportional to dB/dt, so it cannot be a sinusoid either, so an input sinusoid doesn't result in an output sinusoid and => the system is not linear. Yet transformers are routinely used in applications like audio where linearity is critical. So it seems that in general transformer transfer functions are linear but I just cant understand how they manage this given the Hysteresis effect, can anyone explain this ?
Thanks,

A: "the H field generated is proportional to the current in the primary" ... no, it's proportional to the difference between primary and secondary current (latter scaled by turns ratio).
So the nonlinearity only applies to the magnetising current. Now, if you drive the transformer from a finite source impedance, that nonlinear current translates to a nonlinearity in the voltage across the transformer itself.
Assume 10% nonlinearity from the region of the B-H curve we actually use, and the magnetising current is 10% of the total, the nonlinearity in the primary current is 1%.
Furthermore, assume the source impedance is 10% of the load impedance (scaled by N^2) and primary impedance in parallel, so that 10% of the driving voltage is developed across it by the total primary current: that 1% current nonlinearity results in 0.1% nonlinearity on the secondary voltage.
So a 10% B-H nonlinearity in this example results in 0.1% nonlinearity in the transfer function. And to reduce it further you can reduce the source impedance of whatever drives the transformer.

A:
if I have a sinusoidal current as the input

You don't normally have a current driven primary, you have a voltage driven primary and, as saturation starts to kick-in, you get a higher current than for an unsaturating primary. The two effects of increased current at the peaks and decreasing dB/dt (at the peaks) I guess will tend to resolve themselves to something like linear volts out. Here's a pretty picture from the web that supports this general idea: -

Note that current is not very sinusoidal yet flux, despite the non-linearity is seemingly sinusoidal. Here's what that site says: -

When a ferromagnetic material approaches magnetic flux saturation,
  disproportionately greater levels of magnetic field force (mmf) are
  required to deliver equal increases in magnetic field flux (Φ).
  Because mmf is proportional to current through the magnetizing coil
  (mmf = NI, where "N" is the number of turns of wire in the coil and
  "I" is the current through it), the large increases of mmf required to
  supply the needed increases in flux results in large increases in coil
  current. Thus, coil current increases dramatically at the peaks in
  order to maintain a flux waveform that isn't distorted, accounting for
  the bell-shaped half-cycles of the current waveform in the above plot.

If you looked at the equivalent circuit of a transformer you'd see that any distortion in the magnetization current (providing input leakage components are relatively small and the input voltage waveform can be sustained in shape) won't affect the voltage across the ideal transformer: -

I\$_M\$ is the magnetization current and this current doesn't contribute to the creation of V\$_S\$ even if it is really badly shaped and peaky. Providing Rp and Xp don't generate too much of a volt drop (that would reflect the horrible shape of Im) then I think distortion will not be as bad as you believe it might be.

A: Compared to actual transformer behavior, the typical textbook hysteresis curve is highly exaggerated. See this page.

Of course we don't want to use the bits at the ends where it is saturating.


text:
Q: What is the domain of $x^{2x}$ What is the domain of $f(x)=x^{2x}$?
If $f(x)=(x^2)^x $then $f$ is defined for every real number but if $f(x)=(x^x)^2$ then $f$ is only defined and "nice" (excluding the negative $-p/q$ fractions) for positive real numbers.
Should we say $f(x)=e^{2x\log(x)}$ is only defined for positive $x$?
Thanks

A: I would say that it's defined only for positive numbers. Let's look at a simpler problem: what is the domain of $x^\frac12$? I can say "I could always write it as $(x^2)^\frac14$." The issue is order of operations. Unless you have parantheses, you need to calculate the exponent first. See for example https://en.wikipedia.org/wiki/Order_of_operations#Serial_exponentiation


text:
Q: How should a 'Virtual ListCtrl' access the 'Model Data' to populate it's list? I have a class called MVC which provides separation and acts as a broker between wxFrame/UI and the Model Data.
class diagram
To keep things simple, MVC was made a member variable of wxFrame.
class MAIN_FRAME: public wxFrame
{

public:
    MAIN_FRAME();

public:
    MVC MODEL;
};

wxFrame implements a 'virtual wxListCtrl' to request the list data from MVC.
However, I'm not clear on the best way for the 'virtual ListCtrl' to access the MVC, specifically in the overloaded function which requests the list data.  The problem being that MyVirtualListCtrl is separate from wxFrame so doesn't have scope to access wxFrame member variable MVC:
wxString MyVirtualListCtrl::OnGetItemText( long item_, long col_  ) const
{

   // If no data then populate list cells with "Empty".
   if( this->MVC.empty() )
   {
       return _( "Empty" ) ;
   }

   // Use item and column to return the correct data for that particular cell.

   // mock solution
   >>wxString s = MVC.get_data( item_, col_ );<<
   >>return s;<<

}

A: When constructing your MyVirtualListCtrl class, you can give it a reference to the MAIN_FRAME or, arguably better, directly to its MODEL and then just use it. As you can safely assume that MAIN_FRAME (and hence its model) will outlive MyVirtualListCtrl, because the frame children are destroyed when the frame itself is, this is safe from the object life-time point of view.


text:
Q: Why is 'Components' tree structure empty - RTC source control In RTC source control when I expand the Team Area I have this view :

I can see the stream and its components. What decides if components should appear in Components folder ? As can be seen in screenshot this is currently empty. For other developers this is populated with components even though they cannot see the streams ?

A: You see all components that are visible to you.
In other words, it depends on the ownership for each component.

*

*Any component owned by the project area or your Team Area would be displayed in the Component section.

*Any component owned by a single resource (a member of the RTC project area) or another Team Area (that you aren't part of) won't be displayed there.

The same would apply for the streams: check the owner of those streams to understand why a resource doesn't see it.

Whats the point of hiding a stream if the components themselves are not hidden ?

The point (in hiding Stream even though it doesn't hide component) is preventing users to deliver to that stream: they can still work on the same set of component (visible because of the right ownership), but they can no longer see (and deliver to) a given Stream.


text:
Q: Query with EXISTS-subquery taking about 280 ms in 80 % of cases, and less than 1 ms in 20 % of cases I noticed a query that seemed to take way too long most of the time, so I investigated it with the Laravel query logger (to get the time and the actual SQL from the query builder).
Excerpt:
>>> DB::flushQueryLog(); DB::enableQueryLog(); Company::findAllByNameOrAlias('Frankfurt University of Applied Sciences'); DB::getQueryLog()
=> [
     [
       "query" => "select * from `companies` where (`name` = ? or exists (select * from `company_aliases` where `companies`.`id` = `company_aliases`.`company_id` and `name` = ?)) and `companies`.`deleted_at` is null",
       "bindings" => [
         "Frankfurt University of Applied Sciences",
         "Frankfurt University of Applied Sciences",
       ],
       "time" => 278.46,
     ],
   ]
>>> DB::flushQueryLog(); DB::enableQueryLog(); Company::findAllByNameOrAlias('Frankfurt University of Applied Sciences'); DB::getQueryLog()
=> [
     [
       "query" => "select * from `companies` where (`name` = ? or exists (select * from `company_aliases` where `companies`.`id` = `company_aliases`.`company_id` and `name` = ?)) and `companies`.`deleted_at` is null",
       "bindings" => [
         "Frankfurt University of Applied Sciences",
         "Frankfurt University of Applied Sciences",
       ],
       "time" => 0.72,
     ],
   ]
>>> DB::flushQueryLog(); DB::enableQueryLog(); Company::findAllByNameOrAlias('Frankfurt University of Applied Sciences'); DB::getQueryLog()
=> [
     [
       "query" => "select * from `companies` where (`name` = ? or exists (select * from `company_aliases` where `companies`.`id` = `company_aliases`.`company_id` and `name` = ?)) and `companies`.`deleted_at` is null",
       "bindings" => [
         "Frankfurt University of Applied Sciences",
         "Frankfurt University of Applied Sciences",
       ],
       "time" => 0.67,
     ],
   ]
>>> DB::flushQueryLog(); DB::enableQueryLog(); Company::findAllByNameOrAlias('Frankfurt University of Applied Sciences'); DB::getQueryLog()
=> [
     [
       "query" => "select * from `companies` where (`name` = ? or exists (select * from `company_aliases` where `companies`.`id` = `company_aliases`.`company_id` and `name` = ?)) and `companies`.`deleted_at` is null",
       "bindings" => [
         "Frankfurt University of Applied Sciences",
         "Frankfurt University of Applied Sciences",
       ],
       "time" => 298.88,
     ],
   ]

Notice the query times.
The use case: I am looking for companies by name, but we want to be able to specify aliases that identify the same company. The companies table has an index on name, and the company_aliases table has an index on name, too. company_aliases.company_id has a foreign key constraint referencing companies.id.
Cherry on top: The table company_aliases is empty.
EXPLAIN for the above query:

id
select_type
table
type
possible_keys
key
key_len
ref
rows
Extra

1
PRIMARY
companies
ALL
companies_name_index
NULL
NULL
NULL
241068
Using where

2
MATERIALIZED
company_aliases
ref
company_aliases_company_id_foreign,company_aliases_name_index
company_aliases_name_index
1022
const
1
Using index condition

Leaving out the company_aliases table and searching in companies only, gives sub 1 ms run times consistently.
>>> DB::flushQueryLog(); DB::enableQueryLog(); Company::where('name', 'Frankfurt University of Applied Sciences')->first(); DB::getQueryLog()
=> [
     [
       "query" => "select * from `companies` where `name` = ? and `companies`.`deleted_at` is null limit 1",
       "bindings" => [
         "Frankfurt University of Applied Sciences",
       ],
       "time" => 0.84,
     ],
   ]
>>> DB::flushQueryLog(); DB::enableQueryLog(); Company::where('name', 'Frankfurt University of Applied Sciences')->first(); DB::getQueryLog()
=> [
     [
       "query" => "select * from `companies` where `name` = ? and `companies`.`deleted_at` is null limit 1",
       "bindings" => [
         "Frankfurt University of Applied Sciences",
       ],
       "time" => 0.95,
     ],
   ]
>>> DB::flushQueryLog(); DB::enableQueryLog(); Company::where('name', 'Frankfurt University of Applied Sciences')->first(); DB::getQueryLog()
=> [
     [
       "query" => "select * from `companies` where `name` = ? and `companies`.`deleted_at` is null limit 1",
       "bindings" => [
         "Frankfurt University of Applied Sciences",
       ],
       "time" => 0.83,
     ],
   ]
>>> DB::flushQueryLog(); DB::enableQueryLog(); Company::where('name', 'Frankfurt University of Applied Sciences')->first(); DB::getQueryLog()
=> [
     [
       "query" => "select * from `companies` where `name` = ? and `companies`.`deleted_at` is null limit 1",
       "bindings" => [
         "Frankfurt University of Applied Sciences",
       ],
       "time" => 0.73,
     ],
   ]
>>> DB::flushQueryLog(); DB::enableQueryLog(); Company::where('name', 'Frankfurt University of Applied Sciences')->first(); DB::getQueryLog()
=> [
     [
       "query" => "select * from `companies` where `name` = ? and `companies`.`deleted_at` is null limit 1",
       "bindings" => [
         "Frankfurt University of Applied Sciences",
       ],
       "time" => 0.6,
     ],
   ]
>>> DB::flushQueryLog(); DB::enableQueryLog(); Company::where('name', 'Frankfurt University of Applied Sciences')->first(); DB::getQueryLog()
=> [
     [
       "query" => "select * from `companies` where `name` = ? and `companies`.`deleted_at` is null limit 1",
       "bindings" => [
         "Frankfurt University of Applied Sciences",
       ],
       "time" => 0.9,
     ],
   ]
>>> DB::flushQueryLog(); DB::enableQueryLog(); Company::where('name', 'Frankfurt University of Applied Sciences')->first(); DB::getQueryLog()
=> [
     [
       "query" => "select * from `companies` where `name` = ? and `companies`.`deleted_at` is null limit 1",
       "bindings" => [
         "Frankfurt University of Applied Sciences",
       ],
       "time" => 0.86,
     ],
   ]
>>> DB::flushQueryLog(); DB::enableQueryLog(); Company::where('name', 'Frankfurt University of Applied Sciences')->first(); DB::getQueryLog()
=> [
     [
       "query" => "select * from `companies` where `name` = ? and `companies`.`deleted_at` is null limit 1",
       "bindings" => [
         "Frankfurt University of Applied Sciences",
       ],
       "time" => 0.64,
     ],
   ]
>>> DB::flushQueryLog(); DB::enableQueryLog(); Company::where('name', 'Frankfurt University of Applied Sciences')->first(); DB::getQueryLog()
=> [
     [
       "query" => "select * from `companies` where `name` = ? and `companies`.`deleted_at` is null limit 1",
       "bindings" => [
         "Frankfurt University of Applied Sciences",
       ],
       "time" => 0.53,
     ],
   ]
>>> DB::flushQueryLog(); DB::enableQueryLog(); Company::where('name', 'Frankfurt University of Applied Sciences')->first(); DB::getQueryLog()
=> [
     [
       "query" => "select * from `companies` where `name` = ? and `companies`.`deleted_at` is null limit 1",
       "bindings" => [
         "Frankfurt University of Applied Sciences",
       ],
       "time" => 0.47,
     ],
   ]
>>> DB::flushQueryLog(); DB::enableQueryLog(); Company::where('name', 'Frankfurt University of Applied Sciences')->first(); DB::getQueryLog()
=> [
     [
       "query" => "select * from `companies` where `name` = ? and `companies`.`deleted_at` is null limit 1",
       "bindings" => [
         "Frankfurt University of Applied Sciences",
       ],
       "time" => 0.55,
     ],
   ]
>>> DB::flushQueryLog(); DB::enableQueryLog(); Company::where('name', 'Frankfurt University of Applied Sciences')->first(); DB::getQueryLog()
=> [
     [
       "query" => "select * from `companies` where `name` = ? and `companies`.`deleted_at` is null limit 1",
       "bindings" => [
         "Frankfurt University of Applied Sciences",
       ],
       "time" => 0.53,
     ],
   ]
>>> DB::flushQueryLog(); DB::enableQueryLog(); Company::where('name', 'Frankfurt University of Applied Sciences')->first(); DB::getQueryLog()
=> [
     [
       "query" => "select * from `companies` where `name` = ? and `companies`.`deleted_at` is null limit 1",
       "bindings" => [
         "Frankfurt University of Applied Sciences",
       ],
       "time" => 0.66,
     ],
   ]
>>> DB::flushQueryLog(); DB::enableQueryLog(); Company::where('name', 'Frankfurt University of Applied Sciences')->first(); DB::getQueryLog()
=> [
     [
       "query" => "select * from `companies` where `name` = ? and `companies`.`deleted_at` is null limit 1",
       "bindings" => [
         "Frankfurt University of Applied Sciences",
       ],
       "time" => 0.79,
     ],
   ]
>>> DB::flushQueryLog(); DB::enableQueryLog(); Company::where('name', 'Frankfurt University of Applied Sciences')->first(); DB::getQueryLog()
=> [
     [
       "query" => "select * from `companies` where `name` = ? and `companies`.`deleted_at` is null limit 1",
       "bindings" => [
         "Frankfurt University of Applied Sciences",
       ],
       "time" => 0.84,
     ],
   ]

A search in company_aliases is as fast as a search in companies, so it's a viable workaround to query companies and, if no result was found, query company_aliases. The total query time is still below 2 ms. Essentially, I am just moving the lazy evaluation of the OR into my PHP code. But this shouldn't be faster than executing the same logic entirely in the DB.
What's the reason?

A: "A search in company_aliases is as fast as a search in companies, so it's a viable workaround to query companies and, if no result was found, query company_aliases. The total query time is still below 2 ms. Essentially, I am just moving the lazy evaluation of the OR into my PHP code. But this shouldn't be faster than executing the same logic entirely in the DB."
That's not the same logic. The query is saying give me the rows in companies that either have the same name as this value or can be found in company_aliases with this value. There's nothing which tells it to stop when it finds a match.
You can expand the OR condition manually:
select *
from  `companies`
where  `name` = ?
and    `companies`.`deleted_at` is null
union all
select *
from  `companies`
where  exists (select null
               from   `company_aliases`
               where  `companies`.`id` = `company_aliases`.`company_id`
               and    `name` = ?
              )
and    `companies`.`deleted_at` is null
and   ( `name` <> ? or `name` is null)

This should give you a plan which uses an index on companies.name to satisfy the first part, and it should use an index on company_aliases.name followed by a loop to companies based on id for the second part. Assuming those indexes exist, you should be fine.


text:
Q: Disallow non-local storage of an object I need to write a class in C++ that acquires a hardware resource and releases it again when it is destroyed. Basically that can be done in the constructor and destructor of the class. The difficulty I'm having is that I want this class to be usable as a local object only.
So basically:
struct Magic
{
  Magic(const Settings& settings)
  {
    acquireHardware(settings);
  }
  ~Magic()
  {
    releaseHardware();
  }
  // Magic does not need to store the settings or a reference to them
};

This should be allowed:
void useAllTheHardware(const Settings& settings)
{
  Magic useHardwareWith(settings);
  ...
  // destructor releases the hardware
}

This should fail:
struct badIdea
{
  badIdea(const Settings& settings)
    : settings_(settings),
    useHardwareWith_(settings)
  {
  }
  Settings settings_;
  Magic useHardwareWith_;
};
badIdea mustFail(settings); // <-- not allowed

My environment is exception-free (embedded, and compiled with gcc -fno-exceptions), and if things go terribly wrong there's usually no way of handling that except fixing the bug that caused the crash.
How can I do that?

A: You can't quite do it, but you can come close:
#include <cstddef>

#include <new>

struct Magic
{
    enum promise
    {
        i_promise_not_to_put_this_in_another_class
    };

    void *operator new(size_t) = delete;
    void *operator new[](size_t) = delete;
    void operator delete(void *) = delete;
    void operator delete[](void *) = delete;

    Magic(promise) {}
    Magic(Magic&&) = delete;
    Magic(const Magic&) = delete;
    Magic& operator = (Magic&&) = delete;
    Magic& operator = (const Magic&) = delete;
    ~Magic() {}
};

struct WhyIsThisABadIdea
{
    Magic m;

    WhyIsThisABadIdea() : m(Magic::i_promise_not_to_put_this_in_another_class) {} // obvious lies
};

int main()
{
    Magic m(Magic::i_promise_not_to_put_this_in_another_class); // okay
    //new Magic(Magic::i_promise_not_to_put_this_in_another_class); // error
    WhyIsThisABadIdea bad; // okay
}

A: I really don't like answering my own question here, especially because I realized that I asked the wrong question. I was too much focused on OO terms and habits, but the reality is that what I wanted was a prodedure, not a class or anything that can actually store a state. Sorry for that.
Here's my (not quite working) solution (improved solution below):
I remembered that there are macros that manage "atomic blocks" by clearing an interrupt enable flag when the block is entered, and restoring it after the block was run. I had a look at those and they are basically just a for loop.
Together with an anonymous struct definition in the for loop initialization (https://stackoverflow.com/a/11255852) this grew to a solution that works for me:
#include <iostream>

struct Settings
{
    Settings(int v_) : v(v_) {}
    int v;
};

//https://stackoverflow.com/a/11255852
#define useHardwareWith(settings)                   \
acquireHardware(settings);                          \
for(                                                \
  struct                                            \
  {                                                 \
    bool done()                                     \
    {                                               \
      return done_;                                 \
    }                                               \
    bool run()                                      \
    {                                               \
      releaseHardware();                            \
      done_ = true;                                 \
    }                                               \
    bool done_;                                     \
  } magic = {false}; !magic.done() ; magic.run())

void acquireHardware(const Settings& settings)
{
  std::cout << "acquire(" << settings.v << ")\n";
}

void releaseHardware()
{
  std::cout << "release()\n";
}

int main()
{
  Settings settings(1);
  useHardwareWith(settings)
  {
    std::cout << "Doing important hardware stuff\n";
  }
}

Output:
acquire(1)
Doing important hardware stuff
release()

Online demo: http://ideone.com/eT91hD
The for macro cannot be stored, so it's not disallowing non-local storage, but simply doing something in a specific order.

This is better
Above solution has a major problem: release() is not called when break or return is called in the loop, because release() is in the "increment" part, and not in a destructor. Unfortunately, a destructor for the anonymous cannot be defined. So I added a named inner struct to do that:
#include <iostream>

struct Settings
{
    Settings(int v_) : v(v_) {}
    int v;
};

//https://stackoverflow.com/a/11255852
#define useHardwareWith(settings)                   \
acquireHardware(settings);                          \
for(                                                \
  struct                                            \
  {                                                 \
    struct inner                                    \
    {                                               \
      inner() : done_(false)                        \
      {                                             \
      }                                             \
      ~inner()                                      \
      {                                             \
        releaseHardware();                          \
      }                                             \
      bool done_;                                   \
    };                                              \
    bool done() const                               \
    {                                               \
      return inner_.done_;                          \
    }                                               \
    bool run()                                      \
    {                                               \
      inner_.done_ = true;                          \
    }                                               \
    inner inner_;                                   \
  } magic; !magic.done() ; magic.run())

void acquireHardware(const Settings& settings)
{
  std::cout << "acquire(" << settings.v << ")\n";
}

void releaseHardware()
{
  std::cout << "release()\n";
}

void doHardwareStuff(const Settings& settings)
{
  useHardwareWith(settings)
  {
    if (settings.v == 0)
    {
        std::cout << "side-exit\n";
        return;
    }
    std::cout << "Doing important hardware stuff\n";
  }
}

int main()
{
  Settings settings(0);
  doHardwareStuff(settings);
  doHardwareStuff(Settings(1));
}

Online demo: http://ideone.com/z3Qm8a

A: I don't think you can prevent the creation of objects with static storage duration (e.g. C++ - Prevent global instantiation?)
You could run a check at runtime:
bool ALLOW = false;

struct Magic
{
  // ...

  ~Magic()
  {
    if (!ALLOW)
      std::cerr << "Some diagnostic message\n";
    releaseHardware();
  }
};

int main()
{
  ALLOW = true;

  // ...

  ALLOW = false;  // reset before main() ends
  return 0;
}

The destructor of variables with static storage duration

*

*is called after main() ends and

*for this reason it will print an error message

Of course this is only a check, but can be quite useful to correct the code.
Consider that it doesn't prevent something like:
int main()
{
   Magic useHardwareWith(settings);

   // ...
}


text:
Q: Approximate an inner class within an interface? This is mainly for neatness in a WPF project using Dependency Injection
In Java I can do the following:
public interface MyInjectable
{
    void ExampleMethod();

    public class Impl : MyInjectable
    {
        void ExampleMethod()
        {

        }
    }
}

Which is nice when using DI frameworks, as you call the inner class MyInjectable.Impl() to instatiate the class, and just write MyInjectable elsewhere.
In C# I must do this:
public interface IMyInjectable
{
    void ExampleMethod();
}

public class MyInjectable: IMyInjectable
{
    void ExampleMethod()
    {

    }
}

IE I have to name the class something unique and a separate interface. Is there a better way to do this, or any workaround to get something that approximates an inner Impl class inside an interface?

A: To my knowledge, there's no 'better' way to address this in C#. Usually, because of the little remnant of Hungarian notation in C#, interfaces are, like in the OP, usually prefixed with I (e.g. IMyInjectable), which leaves free the unprefixed name (e.g. MyInjectable) for an implementation.
If, however, the code mostly consists of IFoo/Foo pairs, it's most likely violating the Reused Abstractions Principle. If possible, reconsider the application architecture to address that code smell.


text:
Q: key error when writing dictionaries with common keys to csv I trying to write a few dictionaries with common keys to a csv, but keep getting a key error:
TotalData = dict1, dict2, dict3

with open(self.pathString, 'wb') as ofile:
   writer = csv.writer(ofile, quoting=csv.QUOTE_NONE, delimiter='\t')
   writer.writerow(['field1', 'field2', 'field3'])
       for key in sorted(ConsoSom.iterkeys(), key=lambda x: str(x)):
           writer.writerow([key] + ['{0:.2f}'.format(d[key]) for d in TotalData])

My error gives me KeyError: u'dict3key'
UPDATE: This is because the keys are not always present. I am wondering how to leave a blank space if the key is not present.
my desired result is:
field1, field2, field3
id1, value1, second1
id2,  , second2
id3, value3, second3

A: Use dict.get:
TotalData = dict1, dict2, dict3

with open(self.pathString, 'wb') as ofile:
   writer = csv.writer(ofile, quoting=csv.QUOTE_NONE, delimiter='\t')
   writer.writerow(['field1', 'field2', 'field3'])
       for key in sorted(ConsoSom.iterkeys(), key=lambda x: str(x)):
           writer.writerow([key] + ['{0:.2f}'.format(d.get(key, 0)) for d in TotalData])


text:
Q: ¿Cómo puedo seleccionar las columnas de una consulta a la api de google cloud compute con el fin de mostrar algunos datos de la respuesta de la api? from pprint import pprint
from googleapiclient import discovery

from google.oauth2 import service_account
credentials = service_account.Credentials.from_service_account_file(
    '**Ubicación de la key**')
service = discovery.build('compute', 'v1', credentials=credentials)

project = "project-id"

request = service.instances().aggregatedList(project = project)
while request is not None:
    response = request.execute()
    instance = response.get('items', {})
    for instance in instance.values():
      for a in instance.get('instances', []):
          pprint(instance)
    request = service.instances().aggregatedList_next(previous_request=request, previous_response=response)

El código me da como resultado una lista con las instancias del proyecto.
Necesito que ejecute la lista de instancias con los parámetros específicos de id, zona, status, networkInterfaces, disks.


text:
Q: Line Breaking on Mobile I posted a sentence in a single line in my wordpress site and it is showing perfect in laptop but in mobile devices the sentence is breaking into two lines, I want to fix this into one line.
The issue:(Check from the images)
(mobile view)

(laptop view)

A: From what I gather, the single line(s) is simply too long for the mobile viewport. At the expense of SEO rating, you could try to make the font size smaller to compensate for sentence length. I'm not sure how else you'd tackle guitar tabs in mobile inside what I assume to be a code block.


text:
Q: How do I delete a spreadsheet file using Google Spreadsheets API? I can easily create one, update it, and access it with no problems but there doesn't seem to be an API call to delete it? You can delete sheets from the file but not the file itself?
I tried using google drive scopes, however, when I try to list files or delete them, I keep receiving a (403) Forbidden error.

A: AFAIK and as explicitly stated in the documentation, Google Sheets API (formerly Google Spreadsheets API) gives you full control over the content and appearance of your spreadsheet data.

This API is useful for:

*

*Managing the worksheets in a Google Sheets file

*Consuming the rows of a worksheet

*Managing cells in a worksheet by position

Note that your spreadsheets and your other Google docs are all stored in Google Drive. So, to delete files, you should be using Files: delete method of Google Drive API.
Tried this with the Try-it and  my dummy sheet file was deleted with a 204 response (means delete successful).


text:
Q: Why is TYPE_ORIENTATION deprecated since API 8.0 ? Why is TYPE_ORIENTATION deprecated since API 8.0 for ANdroid? There's a cross in eclipse but the code runs perfectly fine.

A: In the Google I/O 2012 conference about sensors here: http://youtu.be/Q0V_ld7iNw4?t=23m23s at 23 minutes and 23 seconds it spoke about deprecating that function because on different devices such as tablets and smartphones, the default orientation is landscape in tablet, and portrait in handsets. If the coder is not aware of this, it will cause their device to run differently on these environments or when it gets rotated by 45 degrees. Its better to first get the device's default orientation by using  SensorManager.getOrientation() then perform your sensor computation accordingly.

A: Depreciated code still works but it isn't guaranteed to work on future APIs. They are depreciated by code that works more effectively (and must operate that way as well), either with other code or as a whole. You should avoid depreciated code unless you really need to use it.

A: Because tablets are typically different than the default orientation used to be. (It was portrait, meaning the screen was taller than it was wide when held as normally expected. Tablets mean that the default is that the screen is wider than it is tall.)
This mean that a better mechanism needed to be found, which is android.view.Display.getOrientation().
For more info, see this blog post.
Deprecated means "This has been replaced by something better. It will still work for now, but you should look for the new replacement because it may stop working in the future", which explains why the code "runs perfectly fine" for you. It may work for years (or stop working in the next release), which is why you get the warning.


text:
Q: PHP number formatting back
I can formating number 169480 to 169,480.
But I can't 169,480 to simple 169480.
How can I do this?

I don't need any decimals and comma just a simple number.

A: This should work for you:
(I just use str_replace() to replace ', . and , with a empty string)
<?php

    $number = "169,480";
    echo str_replace(array("'", ".", ","), "", $number);

?>

Output:
169480

A: Try this..
If number have any "," or "." means following code use for remove that

<?php
$number="169,480";
 echo str_replace([',', '.'], '', $number);


text:
Q: Visual Studio 2017 failing to install nuget package in .NET 4.7 project I'm getting the following error when attempting to install a nuget package into a standard .NET framework 4.7 project:
The specified path, file name, or both are too long. The fully qualified file name must be less than 260 characters, and the directory name must be less than 248 characters.
I'm using Visual Studio 2017 15.3.3 Enterprise (latest and greatest).
Given that this is my package, I have full control over the source code. The interesting part is that I have used this package in the past with no changes in the name, but for this go round, I rebuilt it to add a feature and am now getting this error.
Even more interesting is that I have packages from the same library, with the same namespace conventions, with longer names, that work just fine and have installed into this same project with no problems at all.
I have already tried shrinking the package name, shrinking the class names within the package itself, cleaning out the build directory, cleaning out the package home from the nuget server (it's a local server with the latest nuget.server installed which otherwise works just fine), and even clearing out the bin directory of the project in question, clearing out ALL the bin directories of ALL the ancestors to the "offending" package, clearing out the package cache, rebooting the computer and rebuilding the entire nuget package chain from scratch, all to no avail. I was told by one of the MS MVP's that "they fixed that". Apparently not.
Any help would be appreciated here, I'm at my wit's end and have run out of ideas to try.
Thanks.

A: There is another reason for this error message by the compiler.
While building , make sure the source code is placed at a folder location which is less than 260 characters long.
For example, a path like C:\Users\User\source\Services\Exp\Sample-web-application-indot-net-displaying-RestAPI\Sample-web-application-indot-net-displaying-RestAPI\SportsStore is around 150 characters long but there are sub folders in the solution which in turn have source code files and so on.
Sometimes the overall length of the path of some files breaches the 260 character length.
I think the future versions of Visual Studio would have a bigger length allowance. Until then, we can make sure that our file names are not too long.

A: I was running into the same issue after I moved a project to another folder. In my case I closed VS renamed the .vs folder in root to 1.vs (effectively removing it) and re-opend my project.

A: In my case, I was first trying to install a package using Manage Nuget Packages for Solutions and was getting this error. Then I tried installing same package using Package Manager Console and it worked fine. I again uninstalled that package and tried installing using Manage Nuget Packages for Solutions and this time it worked fine as well.

A: OK, big Thank You  @danmosemsft who suggested digging around with the SysInternals process monitor. After fiddling with it for a bit, I finally figured out how to narrow the result set to just file activity. What I noticed, and the nuget engineers should TAKE NOTE of this: The problem was NOT a too-long project name, rather, nuget was attempting to update a package that was no longer there. Why it went away is a mystery yet to be solved. I normally stay out of the packages directory and do not fuss with the packages.config file. I think that this might have to do with my impatience waiting for VS to start, load all the goodies and then allow me to perform a "Manage NuGet packages" - update all. I remember seeing an update to either NUnit or FluentAssertions that wanted to perform some additional file activity aside from just installing the next version, a script I believe. Can't speak to it with assurance, I wasn't paying that much attention as third party updates usually "just work". I didn't see the "finished" line from NuGet so I think that was the root of my problem. Rather than wait until VS has settled down, I pushed it a bit (hey, the buttons responded so there shouldn't be any problems...).
As a result, the packages directory was absolutely chock full of old stuff that did NOT belong there. So, I manually cleaned up all the cruft, manually cleaned up the packages.config file, restarted VS, waited for it to settle down, performed my NuGet updates and viola! no problem - HAVING NOT CHANGED ANY OF THE ANCESTRAL PACKAGE NAMES BY EVEN A SINGLE CHARACTER.
So, what do I conclude from this? It is my belief, and the guys that actually build nuget and nuget.server should take a closer look at the errors being thrown, such that I think that the error is not so much a path too long error, rather it's a "hey, I didn't find the file I expected so the file name is full of junk (and probably too long now) so I'll throw an error that says it's too long and quit". It's seemingly a failure to handle a missing package/package directory that is causing this particular problem
I solved my problem by ensuring that all the package directories were clean of all junk and rebuilding from a clean source. My problem is now solved.
Thanks to all of you that responded.
Update: While the above contributed to the solution, it was NOT the answer. Here is the sequence of events that led to this problem and it's ultimate resolution.
The solution was created in the C:\User\Sam\Documents\Visual Studio 2017\Projects directory with the specified name of AWE.Lib.ADO.MsSqlSvr.ServerEntityHandler. This worked just fine, no errors. However due to a change in naming scheme from on high, the root directory for this project was changed from "C:\User\Sam\Documents\Visual Studio 2017\Projects" to "C:\User\Sam\Documents\Visual Studio 2017\Projects\DotNet_4.7\AWE 8.x". No problem, I thought - given that a co-worker who also happens to be a MS MVP had told me that all naming length restrictions had been removed in VS 2017. So...I moved the project from it's current home to the directory specified. Compiles just fine, brings in UPDATED BUT ALREADY INSTALLED nuget packages just fine, etc.
Or so I thought. When I needed to add a NEW (one that had not been a part of the solution before) nuget package to the mix, I received the above error. Turns out that the new name of the receiving solution is a few characters longer than VS will accept - the naming length restrictions are STILL IN PLACE.
How did I finally solve the problem: After struggling with this, I threw my hands up and decided to start all over again - a true File | New. So, I started with a new solution named as follows:
"C:\Users\Sam\Documents\Visual Studio 2017\Projects\DotNet_4.7\AWE 8.x\AWE.Lib.ADO.MsSqlSvr.HndlrServerEntity"
THIS GENERATES AN ERROR - name too long. I wondered at Nuget's error in that it specifies that the name should be less than 248 characters in length or 260 maximum.
What I am allowed to use iaw the new solution dialog is this: "C:\Users\Sam\Documents\Visual Studio 2017\Projects\DotNet_4.7\AWE 8.x\AWE.Lib.ADO.MsSqlSvr.HndlrServerEnt", for a total of 106 characters in length. If the directory is shortened, I can add to the length of the name. If I shorten the length of the actual solution name, again, VS'll accept it. So long as the total length of directory plus solution name is less than or equal to 106 characters, there isn't a problem.
The nasty bit comes from creating the solution in one location and having it work in all respects just fine, moving said solution to a different directory, still having it function in all respects (I did NOT need to add any new nuget packages yet), then trying to add a new nuget package to the mix after the move. THAT is what triggered the above nuget error.
So...the ultimate "fix", use a shorter name as it seems that 106 characters is the limit despite what the error messages are saying (and what the MS MVP was told/told me).

A: Well in my experience all i had to do is move the entire project to my c: drive, delete unnecessary folders to ensure the path would be shorter. Done deal.

A: This error comes to me when I tried to copy the project folder to OneDrive and the problem is that OneDrive is not uploading long name files.
I've fixed this issue by just copying the project folder then paste it in the new laptop using USB.
I wish this could help

A: Move the folder of the project to a folder within a few levels from the root dir. For example the Desktop and voila.

A: Try to close Solution from File->Close Solution and opening it again.
For my case uninstalling, installing, or even updating NuGet packages, nothing was working but reopening(sometimes you can also close and open Visual Studio again) the Solution did the magic.


text:
Q: How can I programmatically position a view using relative points? What is the best way to position a view relative to the size of its superview, when the bounds of the superview are not yet known?
I am trying to avoid hard-coding coordinates if it is at all possible. Perhaps this is silly, and if so, that's a perfectly acceptable answer.
I've run into this many times when working with custom UI. The most recent example is that I'm trying to replace the UINavigationItem plain-text title with a custom view. I want that view to fill the superview, but in addition, I want a UIActivityIndicatorView on the right side, inset about 2 pixels and centered vertically. Here's the code:
- (void) viewDidLoad
{
    [super viewDidLoad];

    customTitleView = [[UIView alloc] initWithFrame:CGRectZero];
    customTitleView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;

    titleLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    titleLabel.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    titleLabel.lineBreakMode = UILineBreakModeWordWrap;
    titleLabel.numberOfLines = 2;
    titleLabel.minimumFontSize = 11.0;
    titleLabel.font = [UIFont systemFontOfSize:17.0];
    titleLabel.adjustsFontSizeToFitWidth = YES;
    [customTitleView addSubview:titleLabel];

    spinnerView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    spinnerView.center = CGPointMake(customTitleView.bounds.size.width - (spinnerView.bounds.size.width / 2) - 2,
                                     customTitleView.bounds.size.height / 2);
    spinnerView.hidesWhenStopped = YES;
    [customTitleView addSubview:spinnerView];

    self.navigationItem.titleView = customTitleView;
    [customTitleView release];
}

Here's my problem: at the time that this code runs, customTitleView.bounds is still zeroes. The auto-resizing mask hasn't had a chance to do its thing yet, but I very much want those values so that I can compute the relative positions of other sub-views (here, the activity indicator).
Is this possible without being ugly?

A: The only reason customTitleView.bounds has zero width and height is because you've initialized it that way by using CGRectZero.  You can initialize the view with any nonzero size and then define its subviews in relation to that arbitrary size.  As long as you've defined the autoresizing behaviors of the subviews properly, their layout will be adjusted appropriately when the frame of the superview changes at runtime.
For example:
- (void) viewDidLoad
{
    [super viewDidLoad];

    customTitleView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 100.0f, 100.0f)];
    customTitleView.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;

    titleLabel = [[UILabel alloc] initWithFrame:customTitleView.bounds];
    titleLabel.autoresizingMask = UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth;
    titleLabel.lineBreakMode = UILineBreakModeWordWrap;
    titleLabel.numberOfLines = 2;
    titleLabel.minimumFontSize = 11.0;
    titleLabel.font = [UIFont systemFontOfSize:17.0];
    titleLabel.adjustsFontSizeToFitWidth = YES;
    [customTitleView addSubview:titleLabel];
    [titleLabel release];

    spinnerView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
    spinnerView.center = CGPointMake(customTitleView.bounds.size.width - (spinnerView.bounds.size.width / 2) - 2,
                                     customTitleView.bounds.size.height / 2);
    spinnerView.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
    spinnerView.hidesWhenStopped = YES;
    [customTitleView addSubview:spinnerView];
    [spinnerView release];

    self.navigationItem.titleView = customTitleView;
    [customTitleView release];
}


text:
Q: What is the negative point in the knock down action? When you knock down someone, there is a negative point that shows below the experience line as you can see in the picture with a red arrow

What is that point referring to? What is it subtracting? From what total?

A: It's the health/hitpoints from the enemies


text:
Q: File names with spaces as bulk arguments If I have a list of files, some of which have spaces in their names, generated from, say:
find . -iname "*hs" | grep foo

How can I pass them as arguments to a single process like process name1 name2 ...?
Note that I want to pass all file names as individual arguments to a single process, so standard for f in * solutions won't work

A: find . -iname "*hs*" -exec grep foo {} +

find . -iname "*hs*" -print0 | xargs -0 grep foo

Both work; the first might even be a little more efficient, unless the + option groups fewer files into a command line than xargs does.
If you're generating the file names via shell globbing, then:
grep foo *hs*

preserves the spacing in file names.  Using ls to generate the names is very problematic.

Filtering names

The grep command was meant to filter the list of filenames before the bulk process, not to search the contents of the files themselves.

So you want names that match both 'hs' and 'foo'?  In that case, you are best off using find still:
find . \( -iname "*hs*" -a -iname "*foo*" \) -exec grep foo {} +

Use the boolean capabilities of find.
GNU grep extensions -Z and -z
If you can't do that (your grep regex needs to be too complex for find), then you're in difficulties unless you've got a (hypothetical?) version of grep that will read 'lines' delimited by nulls.

-Z, --null
  Output  a zero byte (the ASCII NUL character) instead of the character that normally follows a
  file name.  For example, grep -lZ outputs a zero byte after each file name instead of the
  usual newline.  This option makes the output unambiguous, even in the presence of file names
  containing unusual characters like newlines.  This option can be used with commands like
  find -print0,  perl -0, sort -z, and xargs -0 to process arbitrary file names, even
  those that contain newline characters.

This is almost what's wanted, but not quite.  The POSIX 2008 getdelim() function would be the tool to use; add a -z option to grep for the purpose, and then use grep -lzZ .... to filter the find ... -print0 data before it is fed to xargs -0.
The quote above is from the manual page on Mac OS X 10.7.5, and the GNU grep is version 2.5.1.  Maybe a more recent version of GNU grep is better equipped to help?
And lo and behold, GNU grep 2.14 supports the requisite option:

-z, --null-data
  Treat the input as a set of lines, each terminated by a zero byte (the ASCII NUL character) instead of a newline. Like the -Z or --null option, this option can be used with commands like 'sort -z' to process arbitrary file names.

Run a script from find
The other option, not to be ignored, is to create a script to be run by the find command:
find . -iname "*hs*" -exec ./list-foo +

Where the list-foo script might be:
for arg in "$@"
do
    case "$arg" in
    (*foo*) echo "$arg";;   # This will still cause problems
    esac
done

This identifies the files; the echo is sub-optimal.  Maybe you need to capture the names in an array, and then invoke the final command using the array:
array=( )
i=0
for arg in "$@"
do
    case "$arg" in
    (*foo*) array[$((i++))]="$arg";;
    esac
done

if [ "$i" -gt 0 ]
then real_work "${array[@]}"
fi

Where real_work is the program (script?) that does the real work.  You can throw list-foo away once you're done with it, unless you're going to be doing the same filtering job over and over.

Globbing names that contain a space
You can glob names that contain a space by escaping the space:
rm -i -- *\ *

This expands to just the file names with spaces in the name, which helps in cleaning up a directory with file names containing files created for testing the answers to this question.


text:
Q: Perl Thrift client to Hive? I'd like to connect to a Hadoop-based Hive datastore using Perl.
Hive allows connection using the Thrift interface (http://wiki.apache.org/hadoop/Hive/HiveClient), and there is a Thrift implementation for Perl (e.g. http://metacpan.org/pod/Thrift::XS). However, the only Thrift client I found is a Cassandra client.
Any ideas if such a client exists, or how to create it?
Maybe it's even possible to connect without explicitly defining one?
(PS - there is also an ODBC/JDBC interface to Hive, but installing these modules is a headache, and would be a last resort)
thanks!

A: After some reading (most notably: blog.fingertap.org/?1a253760), I succeeded in creating a Perl Thrift client, and using it to query my server.
Steps:

*

*Download, build and install Thrift: http://incubator.apache.org/thrift/download/.
Don't forget to make install the code in lib/perl.

*Download the infrastructure's .thrift files from Hive's SVN, under the dist of your Hive installation (http://svn.apache.org/viewvc/hive/). The files I have used: fb303.thrift, queryplan.thrift, hive_metastore.thrift and thrift_hive.thrift.
I have located them manually, but there might be better ways of doing that.

*Generate the Perl code using thrift:
thrift -r --gen perl hive_service.thrift
Note: I had to build the directory tree for the required includes, and use the -I directive to this tree's root. I got the required structure from the errors thrift threw at me, but again, there might be more elegant ways of doing that.
Now, the following Perl code, written around the lines of the python example in Hive's client Wiki, works for me:
use Thrift;

use Thrift::Socket;
use Thrift::FramedTransport;
use Thrift::BinaryProtocol;
use lib <LOCATION OF GENERATED PERL CODE>;
use ThriftHive;

# init variables ($host, $port, $query)
#

my $socket = Thrift::Socket->new($host, $port);
my $transport = Thrift::BufferedTransport->new($socket);
my $protocol = Thrift::BinaryProtocol->new($transport);
my $client = ThriftHiveClient->new($protocol);

eval {$transport->open()}; #do something with Exceptions
eval {$client->execute($query)};

for (my $i = 0; $i < $count; $i++)
{
   my $row;
   eval {$row = $client->fetchOne()};

   #use $row
}

$transport->close();

A: In case this is helpful, I've recently uploaded this to the CPAN:
https://metacpan.org/module/Thrift::API::HiveClient
It's still not yet fully documented, and has no tests, but I'm happy to take any patches anybody wants to send! :)

A: It may be helpful to note that Thrift itself ships with a Perl library in the lib folder.
http://svn.apache.org/viewvc/thrift/trunk/lib/perl/lib/


text:
Q: Multi search JDBC I have a form with table and different text fields. I want to make multi parameter search, but my method searchPlayer works only if all text fields are filled. Even though I haven't filled one field (but other are filled), it doesn't work and returns empty table.
What should I change to make search possible if I have filled some of fields, but not all together?
private static String SEARCH_PLAYER =
    "SELECT * FROM fbdb.Players WHERE Number_of_player= ? "
     + "and Full_name LIKE ? "
     + "and Playing_position LIKE ? "
     + "and Height LIKE ? and Weight LIKE ? "
     + "and Nationality LIKE ? and Date_birth LIKE ?";

public String ifnull(String s){
    if (s==null){
        return "%";
    }
    return s;
}

public JTable searchPlayer(JTable table, JTextField tfNumOfPlayer,
                           JTextField tfNamePlayer,
                           JTextField tfPlayingPosition,
                           JTextField tfHeight,
                           JTextField tfWeight,
                           JTextField tfNationality,
                           JTextField tfDateBirth) throws SQLException {

    PreparedStatement pstm = con.prepareStatement(SEARCH_PLAYER);

    pstm.setString (1, ifnull(tfNumOfPlayer.getText()));
    pstm.setString (2, ifnull(tfNamePlayer.getText()));
    pstm.setString (3, ifnull(tfPlayingPosition.getText()));
    pstm.setString (4, ifnull(tfHeight.getText()));
    pstm.setString (5, ifnull(tfWeight.getText()));
    pstm.setString (6, ifnull(tfNationality.getText()));
    pstm.setString (7, ifnull(tfDateBirth.getText()));

    ResultSet rs=pstm.executeQuery();
    ResultSetMetaData rsmd = rs.getMetaData();
    Vector<Object> data = new Vector<Object>();
    Vector<String> columnNames = new Vector<String>();

    for (int n = 1; n <= rsmd.getColumnCount(); n++) {
        columnNames.add(rsmd.getColumnName(n));
    }

    while (rs.next()){
        Vector<Object> row = new Vector<Object>();
       for (int n = 1; n <= rsmd.getColumnCount(); n++) {
           row.add(rs.getObject(n));
       }
       data.add(row);
    }
    DefaultTableModel dtm = new DefaultTableModel(data,columnNames);
    table.setModel(dtm);
    return table;
}


text:
Q: Debian 7 - Startx fails to start system When I boot into the second primary boot loader, I get to the text based console to boot when I type 'startx'. The screen loads, and goes black for 10 seconds. Then when it loads a white screen appears with a computer monitor an sad face on it. Under it, it says
"Oh no! Something has gone wrong"
A problem has occurred and the system can't recover. Please log out and try again

When I click the logout button in the console it reports the errors as follows:
X.Org X Server 1.12.4
Release Date: 2012-08-27
X Protocol Version 11, revision 0
build operating system: Linux 3.2.0-4-amd64 x86_64 Debian
....
The XKEYBOARD Keypmap compiler (xkbcomp) reports:
> warning:  compat map for group 2 redefined
> using new definition
> warning:  compat map for group 3 redefined
> using new definition
> warning:  compat map for group 4 redefined
> using new definition
Errors from xkbcomp are not fatal to the X server
xinit: connection to X server lost

Waiting for X server to shut down server terminated successfully (0). closing the file

Does anyone know how I can successfully boot into my operating system with startx and avoid getting these errors?


text:
Q: My JTextArea doesn't work properly I have the following function that works with a linked list and a text area. Inside this function I have the while loop, it iterates until the list is empty and prints each element into a text area. After this, it removes the first element of the list and it goes back to the while again. The problem that I have is that I have to clear the TextArea after it prints all the elements of the list, but when it removes the first element and reaches the while again it doesn't print anything in the TextArea and I don't know how to fix it
public void function() {
        Node e;
        while(!list.isEmpty()) {
            print();
            e = list.getFirst();
            list.remove(e);
        }
    }

    public void print() {
        Iterator<Node> it = list.iterator();
        while(it.hasNext()) {
            Node c = (Node)it.next();
            textArea1.append("ID: "+c.ID+"\n");
        }
        textArea1.setText("");
    }


text:
Q: I need your help with the sentence How are you liking your stay in Berlin? - Is this sentence correct?
or it should be: How do you like your stay in Berlin?

A: There are two features in the sentence:
First is the use of how in the sense not of by what means/method but to refer to the quality or extent of the state referred to in the verb.
 - How {ie how well or badly) are you doing/getting on?
 - How are you feeling?
This structure is quite normal colloquial usage.
Second is the use of the continuous present, as opposed to the simple present in the case of the verb to like.  Normally for an embedded state, such as liking, the simple present is used.

I like ice cream.
  I hate cloves.
  I love jazz.
  I detest frogs' legs.

But, in fact, when the state is seen as in some way part of a present (and temporary) state, the continuous present can be and often is used.  It is no different from saying:

How are you enjoying your stay in Berlin.

The enjoyment will end with the stay.  So will the 'liking'.  In my British English, it 'like was not used in this way in my childhood.  But it is now.


text:
Q: Javafx method for finding TreeItem by value returning null I have created a method for searching a JavaFX TreeView and returning the TreeItem that matches a given value but it returns a TreeView with a value of null. I have added a couple of sysouts and it does correctly find the TreeItem but it still returns an empty one.
    public void addDirToTree(Directory parentDir, Directory newDir) {
        TreeItem<Label> parentTreeItem = findTreeItemByName(this.getRoot(),parentDir.getName());
        System.out.println(parentTreeItem);
        parentTreeItem.getChildren().add(createTreeItem(newDir));
    }

    private static TreeItem<Label> findTreeItemByName(TreeItem<Label> parentTreeItem, String name) {
        for (TreeItem<Label> treeItem: parentTreeItem.getChildren()) {
            if (treeItem.getValue().getText().equals(name)) {
                System.out.println(treeItem);
                return treeItem;
            }
            findTreeItemByName(treeItem,name);
        }

        return parentTreeItem;
    }

Output:
TreeItem [ value: Label@402c2e44[styleClass=label]'new' ]
TreeItem [ value: null ]

These methods are inside a class that extends TreeView which is why this.getRoot() is passed

A: I don't understand why you have a TreeItem<Label>. The intention is that TreeItem should wrap a piece of data, not a UI element.
Your recursion is incorrectly implemented. If the correct TreeItem is not found in the immediate descendants of the supplied TreeItem, you then recursively search the descendants of those items, but don't do anything with the any result you find, instead returning the originally-supplied item.
You need something like this:
private static TreeItem<String> findTreeItemByName(TreeItem<String> parentTreeItem, String name) {
    // if the supplied item is the one we're looking for, just return it:
    if (parentTreeItem.getValue().equals(name)) {
        return parentTreeItem;
    }
    // Recursively search child items and return one if found:
    for (TreeItem<String> treeItem: parentTreeItem.getChildren()) {
        TreeItem<String> item = findTreeItemByName(treeItem,name);
        if (item != null) return item;
    }
    // We didn't find a match: return null:
    return null;
}


text:
Q: Drop Down List Validation in Excel Cell inside a userform I am displaying Excel inside a VBA form as suggested here.

I need to show a validation drop down list in the Excel present inside the VBA form as below

I tried below code. It is showing compilation error. The same code works in a normal Excel window.
With Me.Spreadsheet1.Range("A1").Validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
xlBetween, Formula1:=ValidationList
.IgnoreBlank = True
.InCellDropdown = True
.InputTitle = ""
.ErrorTitle = ""
.InputMessage = ""
.ErrorMessage = ""
.ShowInput = True
.ShowError = True
End With

below is the error.


text:
Q: IE11 not positioning my box in correct position. Workaround? when I use left:15% on one of my box placements, it shows up exactly where it should be in all browsers, except IE. I'm using IE 11, so i'm not sure if it is also not working in previous versions of ie.
i've never added an exception for a browser before.
how would i add this: left: 20%
just for internet explorer, probably all version i'm thinking.
here is the page I'm referencing for visual reference.
http://alleystoeden.org/testing3/contact-photographer-nina-sutherland.html

A: Instead of targeting a specific browser, try to find and fix the problem.
For example, try margin-left instead of left. Functionally it should do the same. Maybe more xbrowser.
.box {
  margin-left: 15%;
}


text:
Q: Check the encoding of text in SQlite I'm having a nightmare dealing with non Eurpean texts in SQlite. I think the problem is that SQlite isn't encoding the text in UTF8. So I want to check what the encoding is, and hopefully change it to utf8. I encoded a CSV in UTF8 and simply imported it to SQlite but the non-roman text is garbled.
I would like to know:
1)how to check the encoding.
2)How to change the encoding if it is not utf8. I've been reading about Pragma encoding, but I'm not sure how to use this.
I used OpenOffice 3 to create a spreadsheet with half ENglish and half Japanese text. Next I saved the file as a CSV using utf8. This part seems to be ok. I also tried to do it using Google Docs and it worked fine. Next I opened SQlite Browser and did CSV import. The ENglish text shows up perfectly, but the Japanese text is garbled symbols. I think sqlite is using a dfferent encoding (perhaps utf16?).

A: You can test the encoding with this pragma:
PRAGMA encoding;

You cannot change the encoding for an existing database.  To create a new database with a specific encoding, open a SQLite connection to a blank file, run this pragma:
PRAGMA encoding = "UTF-8";

And then create your database.
If you have a database and need a different encoding, then you need to create a new database with the new encoding, and then recreate the schema and import all the data.
However, if you have a problem with garbled text it's pretty much always a problem with one of the tools being used, not SQLite itself.  Even if SQLite is using a different encoding depending, the only end result is that it will cause some extra computation as SQLite converts from stored encoding to API-requested encoding constantly.  If you're using anything other than the C-level API's, then you should never care about encoding--the API's used by the tool you're using will dictate what encoding should be used.
Many SQLite tools have shown issues mangling text into our out of SQLite, including command line shells.  Try running SQLite from a command line and tell it to import the file itself instead of going through SQLite Browser.

A: I also experienced a similar issue. I used SQLiteStudio to access the database and export data. SQLiteStudio does not handle UTF8 special characters correctly, however, the SQLite database itself contains the correct UTF8 characters. I ended up writing a code snippet in C# to connect to the database, run my query, and export the data. This approach worked fine.


text:
Q: "Preparing logs for uploading" In my Android Studio catlog, I've noticed that these calls show up quite often:

11-09 09:19:19.671 19615-19631/? I/PlayCommon: [351] com.google.android.play.a.h.e(262): Preparing logs for uploading
11-09 09:19:19.681 19615-19631/? W/PlayCommon: [351] com.google.android.play.a.h.a(656): No account for auth token provided
11-09 09:19:19.682 19615-19631/? I/PlayCommon: [351] com.google.android.play.a.h.a(503): Connecting to server: https://play.googleapis.com/play/log?format=raw&proto_v2=true
11-09 09:19:19.683 19615-19631/? E/PlayCommon: [351] com.google.android.play.a.h.a(533): Failed to connect to server: java.net.UnknownHostException: Unable to resolve host "play.googleapis.com": No address associated with hostname

This happens even when wifi is off. My concerns are privacy and performance (I noticed these calls before a freeze, which might or might not be related).
I would like to disable this automatic log sending to google. Ideally, stopping it altogether rather than blocking it with a firewall.
If it's not possible to do this from within my app, I'm also open to other ways of accomplishing it (rooting the device, etc).
Also, if someone could explain what these are and what they send, I would appreciate learning.
Thanks.
P.S. I'm on Marshmallow, in case that's useful to know.

A: This might be simply diagnostic logs sent to Google or could be more concerning data.
To find out which, the packet stream would need to be captured.
Of course everything would be encrypted which makes the problem (aside from lack of transparency,  thanks do no evil Google) two fold of breaking the encryption just to determine the data sensitivity that is being transmitted to Google.


text:
Q: Shiny: How do I use the session information from the URL outside a reactive routine I'm trying to subset data for plotting based on parameters in the URL string and do it only once for an entire shiny session.  The data comes from a large database and I don't need to retrieve it over and over again as the use changes the graphic parameters.  Each subsequent plot should be derived from this initial data frame.  I've tried the following only to see the following message: Operation not allowed without an active reactive context.
server <- function(input, output, session) {
  URLString <- parseQueryString(session$clientData$url_search)
  con <- dbConnect(
  RMariaDB::MariaDB(), ....
)
queryString = paste(
"SELECT * FROM Data where UniqueID = '",
URLString['UniqueID'],
sep = ""
)
res <- dbSendQuery(con, queryString)
fetchedRows = data.frame(dbFetch(res))
dbClearResult(res)
dbDisconnect(con)

Thanks

A: session$clientData$url_search is a reactive value, but you can access it in a non-reactive fashion using shiny::isolate().
library(shiny)

ui <- fluidPage(
  tags$a(href = "?param=123", "?param=123")
)

server <- function(input, output, session) {
  URLString <- parseQueryString(isolate(session$clientData$url_search))
  print(URLString)
}

shinyApp(ui, server)


text:
Q: Python string to attribute How can I achieve such job:
def get_foo(someobject, foostring):
    return someobject.foostring

IE:
if I do get_foo(obj, "name") it should be calling obj.name (see input as string but I call it as an attritube.
Thanks

A: If someobject has an attribute named foostring then
def get_foo(someobject, foostring):
    return getattr(someobject,foostring)

or if you want to set an attribute to the supplied object then:
def set_foo(someobject, foostring, value):
    return setattr(someobject,foostring, value)

Try it

A: You should use setattr and getattr:
setattr(object,'property',value)
getattr(object,'property',default)

A: Use the builtin function getattr.

getattr(object, name[, default])
Return the value of the named attribute of object. name must be a string. If the string is the name of one of the object's attributes, the result is the value of that attribute. For example, getattr(x, 'foobar') is equivalent to x.foobar. If the named attribute does not exist, default is returned if provided, otherwise AttributeError is raised.


text:
Q: Uploading files larger than allowed in servers POST settings I'm creating a site in which user can upload his docs.
Settings on server:
upload_max_filesize 2M
post_max_size 2M

The FTP uploading is unlimited.
Is there a way to allow the user upload larger files via FORM?

A: You could try by ini_set function to set the php values for upload_max_filesize at runtime.
but that won't work because the variable is not setted in time so that it can really ovverride the php.ini directives.
So, if you can't access the apache conf, you can try to set this kind of things in the .htaccess
I'd also suggest to set the post_max_size that could help a lot.
php_value upload_max_filesize 32M
php_value post_max_size 32M

A: If you don't have access to edit php.ini, you can use your .htaccess file:
php_value upload_max_filesize 10M

According to http://www.php.net/manual/en/ini.list.php:

Entry can be set in php.ini, .htaccess or httpd.conf

It's worth noting that as always, if you edit your php.ini or apache httpd.conf you'll need to restart apache before you see the changes reflected in your web environment.

A: POST is HTTP, and so are forms.  HTTP is not FTP.
Unless you install some sort of FTP UI plugin (or Java/Flash app), or simply expose the FTP to the users, you're not going to be able to circumvent this.

A: If you really need a way and cannot change upload_max_filesize, let your users split the file up into parts below 2M. You can join them on the server.
Maybe you could show the users a list of the uploaded parts. Whenever the user uploaded all parts, he clicks "All parts uploaded" and then the server joins them.

A: No, there is no other way than editing exactly those two php.ini settings.