Drools functions

Question: Recently I'm working with drools and I want to make some special checks on some objects. I need to use functions in the when section of the rule, but I'm getting an error. Example:
function boolean newFunction(int a){
  if(a>0)
    return true;
  else
    return false;
}

rule "new rule"
salience 100
dialect "mvel"
when
  eval(newFunction(1))
then
  System.out.println("OK");
end

The error i get always is:
unable to resolve method using strict-mode: java.lang.Object.newFunction(java.lang.Integer)

Is there no support on drools for functions in whensection?
Thanks!
Comment: As mentioned in the answers, Drools functions are not for use in the LHS. However, I'm assuming that you are asking this because you're actually looking to achieve re-use of code in your LHS. To achieve this, you can use the "extends" keyword. i.e. `rule "a rule" extends "another rule"`. Unfortunately, this rather useful piece of functionality is not mentioned in the Drools documentation.
Answer: The short answer is: no.
This is because the facts need to be in the working memory.
What you can do, is to have a rule that takes all types of a certain class from the working memory, applies a function in the then section and inserts that new value in the working memory.
edit
This answer, originally posted on 2012, is not more relevant as newer versions of drools do support functions on the when clause.
Answer: Very likely an MVEL or an integration bug - function call adapters did not box/unbox primitive types.
I see the question is quite old, but the problem has been since fixed (tested with 6.3.0-SNAPSHOT). For older versions, I'd try using boxed types : function boolean newFunction( Integer a ) ...
Answer: Along the lines of the selected answer above, after some experimentation I found that it is possible to create an external java method, whose class can be imported into the rules file, and wrapped in a MVEL function wrapper (Boolean) which can then can be called from the LHS as a parameter to an eval statement.
[External Java POJO_Class.myMethod]

import com.mypackage.POJO_Class;

function Boolean myFunctionName() {
   POJO_Class myClass = new POJO_Class();
   return myClass.myMethod(Parameters);
}

rule "Test Rule"
    when
      eval ( myFunctionName(parameters) )
    then
end

Answer: I'm not certain why you are getting the error you are getting, but I was using the following for some debugging yesterday in a query (an LHS so I'm guessing same as a rule)
function boolean say(Object s) {
      Debug.log("Say %s\n", s);
      return true;
}

the query just did eval(say($object)) to help me see whether it ever got invoked. I'm running a snapshot of 6.1 from a week or so ago. Maybe try getting it working (doing anything) just taking Object and work from there - it might be Number or Integer is where you end up on the argument rather than int?

Drools functions


PHP Array to PHP variables

Question: I got a PHP multidimensional array, I want to create variables from it first element as variable name and the second element as the variable value. I want to use this logic to print create the variables based on the language selected, the first column always will have the same names but the second value will generate different strings based on the language selected.
 Array
(
    [0] => Array
        (
            [0] => el1
            [1] => Grouping
        )

    [1] => Array
        (
            [0] => el2
            [1] => Type
        )

    [2] => Array
        (
            [0] => el3
            [1] => Starting Date
        )

    [3] => Array
        (
            [0] => el4
            [1] => Ending Date
        )

    [4] => Array
        (
            [0] => el5
            [1] => Section
        )

    [5] => Array
        (
            [0] => el6
            [1] => Cell
        )

    [6] => Array
        (
            [0] => el7
            [1] => Client
        )

    [7] => Array
        (
            [0] => el8
            [1] => Status
        )

    [8] => Array
        (
            [0] => el9
            [1] => Article
        )

    [9] => Array
        (
            [0] => el10
            [1] => Search
        )

)

I want to assign the [0] value as a variable name and [1] as the variable value, the declaration should be in this way related to my array presented before:
<?php
    el1="Grouping";
    el2="Type";
    el3="Starting Date";
?>

... and so on.
I want to echo out on the HTML page the string from the variable.
Answer: Try this :
foreach ($array as $index => $subarray) {
    ${$subarray[0]} = $subarray[1];
}

You loop throught your big array
You get the first value with key 0 and transform it as variable : see documentation
You assign the value with key 1 and assign it to your variable

Test :
$array = array(
    0 => array(
        0 => "test",
        1 => "value"
    ),
    1 => array(
        0 => "test2",
        1 => "value2"
    )
);

foreach ($array as $index => $subarray) {
    ${$subarray[0]} = $subarray[1];
}

var_dump($test, $test2);

The output is :
string 'value' (length=5)
string 'value2' (length=6)

Answer: A simple loop through the array should do the trick:
foreach ($data as $item) {
 $temp = $item[0];
 ${$temp} = $item[1];
}

PHP Array to PHP variables


ranking in a descending order in R

Question: I want to rank the variables in my dataset in a descending order of the Number of Plants used. I tried ranking in .csv and then exporting it in R. But even then, the plot was not ranked in the required order. Here is my dataset
df <- structure(list(Lepidoptera.Family = structure(c(3L, 2L, 5L, 1L, 4L, 6L),
   .Label = c("Hesperiidae", "Lycaenidae", "Nymphalidae", "Papilionidae", "Pieridae","Riodinidae"), class = "factor"),
           LHP.Families = c(55L, 55L, 15L, 14L, 13L, 1L)),
    .Names = c("Lepidoptera.Family", "LHP.Families"),
    class = "data.frame", row.names = c(NA, -6L))

library(ggplot2)
library(reshape2)

gg <- melt(df,id="Lepidoptera.Family", value.name="LHP.Families", variable.name="Type")

ggplot(gg, aes(x=Lepidoptera.Family, y=LHP.Families, fill=Type))+
       geom_bar(stat="identity")+
      coord_flip()+facet_grid(Type~.)

How do i rank them in a descending order? Also, i want to combine 3 plots into one. How can i go about it?
Answer: The reason this is happening is that ggplot plots the x variables that are factors in the ordering of the underlying values (recall that factors are stored as numbers underneath the covers). If you want to graph them in an alternate order, you should change the order of the levels before plotting
gg$Lepidoptera.Family<-with(gg,
                     factor(Lepidoptera.Family,
                            levels=Lepidoptera.Family[order(LHP.Families)]))

Comment: to be fair I think @Paul Hiemstra 's answer below is nicer (the use of reorder is cleaner). I would suggest rejecting mine and accepting his.
Comment: +1 Your solution is perfectly valid, so the acceptance is fine.
Comment: I was unable to use @Paul Hiemstra's method. I did not know where to enter the command. I tried entering it after specifying the df, but then the plot was the same as original and was not ordered.

Can i use the same command to order different columns in the same dataset and obtain corresponding plots with ordered values with same row names?
Comment: ah yes, it seems it is missing the final assignment into Lepidoptera.Family, I believe the full command should be
df = within(df,
  Lepidoptera.Family<-factor(Lepidoptera.Family, levels = reorder(Lepidoptera.Family, LHP.Families))
)     and yes, you should be able to do this for other factors
Answer: The trick is to reorder the levels of the Lepidoptera.Family factor, which by default is alphabetical:
df = within(df, {
    factor(Lepidoptera.Family, levels = reorder(Lepidoptera.Family, LHP.Families))
})

gg <- melt(df,id="Lepidoptera.Family", value.name="LHP.Families", variable.name="Type")
ggplot(gg, aes(x=Lepidoptera.Family, y=LHP.Families, fill=Type))+ geom_bar(stat="identity")+ coord_flip()+facet_grid(Type~.)

ranking in a descending order in R


Full outer join on 3 tables

Question: I'm trying to get a full result set of all combinations from 3 tables, but its not working because I can't figure out how to tell SQL-Server 2008 what I want.
I have simplified it down to the following similar problem... I have 3 tables:
table `date_ranges`:
  --------------------------------------------------------
| start_day                  | end_day                     |
| -------------------------------------------------------- |
| November, 01 2015 14:37:00 | November, 02 2015 00:00:00  |
| November, 02 2015 00:00:00 | November, 03 2015 00:00:00  |
| November, 03 2015 00:00:00 | November, 04 2015 00:00:00  |
| November, 04 2015 00:00:00 | November, 04 2015 02:00:00  |
  --------------------------------------------------------

table `sites`:
  ----
| site |
| ---- |
| 1    |
| 2    |
| 3    |
| 4    |
  ----

table `all_data`:
  --------------------------------------
| data_date                  | data_site |
| ---------------------------|---------- |
| November, 02 2015 15:35:00 | 1         |
  --------------------------------------

and I want to get the following result:
  -------------------------------------------------------------------------------------------------------
| data_date                  | data_site | start_day                  | end_day                    | site |
| ------------------------------------------------------------------------------------------------------- |
| null                       | null      | November, 01 2015 14:37:00 | November, 02 2015 00:00:00 | 1    |
| November, 02 2015 15:35:00 | 1         | November, 02 2015 00:00:00 | November, 03 2015 00:00:00 | 1    |
| null                       | null      | November, 03 2015 00:00:00 | November, 04 2015 00:00:00 | 1    |
| null                       | null      | November, 04 2015 00:00:00 | November, 04 2015 02:00:00 | 1    |
| null                       | null      | November, 01 2015 14:37:00 | November, 02 2015 00:00:00 | 2    |
| null                       | null      | November, 02 2015 00:00:00 | November, 03 2015 00:00:00 | 2    |
| null                       | null      | November, 03 2015 00:00:00 | November, 04 2015 00:00:00 | 2    |
| null                       | null      | November, 04 2015 00:00:00 | November, 04 2015 02:00:00 | 2    |
| null                       | null      | November, 01 2015 14:37:00 | November, 02 2015 00:00:00 | 3    |
| null                       | null      | November, 02 2015 00:00:00 | November, 03 2015 00:00:00 | 3    |
| null                       | null      | November, 03 2015 00:00:00 | November, 04 2015 00:00:00 | 3    |
| null                       | null      | November, 04 2015 00:00:00 | November, 04 2015 02:00:00 | 3    |
| null                       | null      | November, 01 2015 14:37:00 | November, 02 2015 00:00:00 | 4    |
| null                       | null      | November, 02 2015 00:00:00 | November, 03 2015 00:00:00 | 4    |
| null                       | null      | November, 03 2015 00:00:00 | November, 04 2015 00:00:00 | 4    |
| null                       | null      | November, 04 2015 00:00:00 | November, 04 2015 02:00:00 | 4    |
  -------------------------------------------------------------------------------------------------------

But instead I can only figure out how to get the following result (see fiddle here):
  -------------------------------------------------------------------------------------------------------
| data_date                  | data_site | start_day                  | end_day                    | site |
| ------------------------------------------------------------------------------------------------------- |
| null                       | null      | November, 01 2015 14:37:00 | November, 02 2015 00:00:00 | null |
| November, 02 2015 15:35:00 | 1         | November, 02 2015 00:00:00 | November, 03 2015 00:00:00 | 1    |
| null                       | null      | November, 03 2015 00:00:00 | November, 04 2015 00:00:00 | null |
| null                       | null      | November, 04 2015 00:00:00 | November, 04 2015 02:00:00 | null |
| null                       | null      | null                       | null                       | 2    |
| null                       | null      | null                       | null                       | 3    |
| null                       | null      | null                       | null                       | 4    |
  -------------------------------------------------------------------------------------------------------

using the following incorrect query:
select * from all_data d
full outer join date_ranges r on (r.start_day <= d.data_date and d.data_date < r.end_day)
full outer join sites s on s.site = d.data_site

Comment: `cross join` may hold the clue
Answer: A combination of CROSS JOIN and LEFT JOIN should do the trick for you.
Something like this..
SQL Fiddle
SELECT *
FROM DATE_RANGES R
    CROSS JOIN SITES S
    LEFT OUTER JOIN ALL_DATA D ON (R.START_DAY <= D.DATA_DATE AND D.DATA_DATE < R.END_DAY)
                                        AND S.SITE = D.DATA_SITE

Comment: I would just use `between` in the join condition
Comment: does `between` include the lower but not the upper date in the range?

Full outer join on 3 tables


How can I get my DisplayLink monitor running (again) - 15.10, Asus MB168B+

Question: I have been installing Ubuntu on a laptop (Samsung QX410-SO2), and while there have been hurdles, my Asus DisplayLink monitor is one of the things that worked immediately after driver install.
I first set it up yesterday, and it was working well and behaving as expected. After resuming from sleep later in the day, the monitor was blank. I needed to be portable so I wasn't worried about it - disconnected and walked away.
Now, I can't get the monitor to be recognized at all. I am very new to Ubuntu, but I would really like to get this working again.
To get it working originally, I downloaded displaylink-driver-1.0.335.run  from displaylink.com. After that I plugged the monitor in and after a short delay it just worked.
I am seeing the monitor recognized in dmesg output :
<code>[    2.090374] usb 1-1.2.1: New USB device found, idVendor=17e9, idProduct=ff03
[    2.090380] usb 1-1.2.1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[    2.090384] usb 1-1.2.1: Product: MB168B+
[    2.090386] usb 1-1.2.1: Manufacturer: DisplayLink
[    2.090389] usb 1-1.2.1: SerialNumber: DALMTF138452
[    2.808469] clocksource: Switched to clocksource tsc
[    7.078269] EXT4-fs (sda5): mounted filesystem with ordered data mode. Opts: (null)
[    7.254436] systemd[1]: Failed to insert module 'kdbus': Function not implemented
</code>
Though the last outputs from dmesg don't look good :
<code>[    9.646516] ACPI Warning: \_SB_.PCI0.P0P2.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20150619/nsarguments-95)
[    9.646696] bbswitch: detected an Optimus _DSM function
[    9.646711] bbswitch: Succesfully loaded. Discrete card 0000:01:00.0 is on
[    9.697280] [ ] evdi_init Initialising logging on level 5
[    9.820542] vgaarb: this pci device is not a vga device
[    9.823280] ACPI Warning: \_SB_.PCI0.P0P2.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20150619/nsarguments-95)
[    9.823391] ACPI Warning: \_SB_.PCI0.P0P2.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20150619/nsarguments-95)
[    9.823457] ACPI Warning: \_SB_.PCI0.P0P2.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20150619/nsarguments-95)
[    9.823522] ACPI Warning: \_SB_.PCI0.P0P2.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20150619/nsarguments-95)
[    9.823587] ACPI Warning: \_SB_.PCI0.P0P2.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20150619/nsarguments-95)
[    9.823652] ACPI Warning: \_SB_.PCI0.P0P2.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20150619/nsarguments-95)
[    9.823764] ACPI Warning: \_SB_.PCI0.P0P2.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20150619/nsarguments-95)
[    9.823830] ACPI Warning: \_SB_.PCI0.P0P2.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20150619/nsarguments-95)
[    9.890237] ACPI Warning: \_SB_.PCI0.P0P2.PEGP._DSM: Argument #4 type mismatch - Found [Buffer], ACPI requires [Package] (20150619/nsarguments-95)
[   10.548062] i2400m_usb 2-1.3:1.0: WiMAX interface wmx0 (64:d4:da:1c:31:40) ready
[   10.666277] vgaarb: this pci device is not a vga device
[   12.989696] wlp2s0: authenticate with 60:a4:4c:69:a8:50
[   12.995823] wlp2s0: send auth to 60:a4:4c:69:a8:50 (try 1/3)
[   12.997655] wlp2s0: authenticated
[   12.997848] wlp2s0: waiting for beacon from 60:a4:4c:69:a8:50
[   13.013135] wlp2s0: associate with 60:a4:4c:69:a8:50 (try 1/3)
[   13.019591] wlp2s0: RX AssocResp from 60:a4:4c:69:a8:50 (capab=0x411 status=0 aid=2)
[   13.023237] wlp2s0: associated
[   13.023288] IPv6: ADDRCONF(NETDEV_CHANGE): wlp2s0: link becomes ready
[   14.012644] i2400m_usb 2-1.3:1.0: untested minor fw version 9.3.2
[   14.012652] i2400m_usb 2-1.3:1.0: firmware interface version 9.3.2
[   14.020531] usbcore: registered new interface driver i2400m_usb
[   14.022466] i2400m_usb 2-1.3:1.0 enx64d4da1c3140: renamed from wmx0
[   16.425187] [D] add_store  increasing device count to 1
[   16.425524] [D] evdi_crtc_init drm_crtc_init: 0
[   16.425529] [D] evdi_encoder_init drm_encoder_init: 0
[   16.425630] [D] evdi_detect Painter is disconnected
[   16.425637] evdi evdi.0: No connectors reported connected with modes
[   16.425641] [drm] Cannot find any crtc or sizes - going 1024x768
[   16.427967] evdi evdi.0: fb1: evdidrmfb frame buffer device
[   16.427978] [drm] evdi: evdi_stats_init
[   16.427990] [drm] Initialized evdi 1.0.68 19700101 on minor 2
[   16.428865] [W] evdi_painter_disconnect (dev=0) An unknown connection to ffff88003555c400 tries to close us - ignoring
[   16.429307] [W] evdi_painter_disconnect (dev=0) An unknown connection to ffff88003555c400 tries to close us - ignoring
[   16.473118] [D] evdi_detect Painter is disconnected
[   16.473163] [D] evdi_detect Painter is disconnected
[   16.473619] [D] evdi_painter_crtc_state_notify (dev=0) Notifying crtc state: 0
[   16.473625] [D] evdi_painter_crtc_state_notify (dev=0) Notifying crtc state: 0
[   18.661534] Non-volatile memory driver v1.3
[   22.851144] [W] evdi_painter_disconnect (dev=0) An unknown connection to ffff8800c5260c00 tries to close us - ignoring
[   22.863078] [D] evdi_painter_connect (dev=2) Connected with ffff8800c5260c00
[   22.863086] [D] evdi_painter_connect (dev=2) Edid (3 bytes): 00 ff ff
[   22.863091] [D] evdi_detect (dev=2) Painter is connected
[   22.865501] [D] evdi_detect (dev=2) Painter is connected
[   22.865511] [D] evdi_painter_get_edid (dev=2) 00 ff ff
</code>
Is there an obvious clue here that I am missing?
Answer: This laptop has two graphics cards - an Intel built-in, and NVidia discrete card. I switched to the intel card (using nvidia prime), rebooted, and my display is back.
<code>sudo prime-select intel
</code>
I am posting this in case it can help anyone in the future, but if anyone knows how to keep the Asus Monitor running while still using the NVidia card that would be the preferred solution.
Comment: I keep reading through different channels that DisplayLink does not work at all with the Intel's 3d libGL library. I actually installed Ubuntu and Arch both with working Bumblee/Prime profiles and in both cases the DisplayLink failed to work. This time I am installing Ubuntu with only the Nvidia stuff to see if I get a different result.


AttributeError: 'NoneType' object has no attribute 'split' when trying to split a column data

Question: In this problem I am trying to split a column of data on the basis of space present in between the words.
When I am using the same code for other columns say "Body/Title" the code is working fine  but when trying with intended column "Tags" it is not working , giving me error AttributeError: 'NoneType' object has no attribute 'split'.
df_no_dup.head()

start = datetime.now()
df_no_dup["tag_count"] = df_no_dup["Tags"].apply(lambda text: len(text.split(" ")))

print("Time taken to run this cell :", datetime.now() - start)
df_no_dup.head()

Error that I am getting Output of df_no_dup.head()
Comment: Try `len(str(text).split(" "))`
Answer: If you want to split the date, try this :
import datetime
start = datetime.datetime.now()
b = str(start).split(" ")
print(b)
>>['2019-09-03', '08:57:41.724462']

or simply :
start.hour
>> 8
start.year
>> 2019
start.minute
>> 57

and so on
Answer: Use:
df_no_dup["tag_count"] = df_no_dup["Tags"].apply(lambda text: len(text.split(" ")) if text else 0)

Answer: To split the text and store the number of words in a separate column try this:
df_no_dup["tag_count"] = df_no_dup["Tags"].str.split(" ").str.len()


writing data to target in gnu make file

Question: could you please let me know what is wrong with the the following
the file first has the data one. and I am trying to write hello to firstfile. it is not working.
firstfile:first
    echo "hello" ;  > $@
but the following one works
firstfile:first
    for f in $^;do echo "hello" ; done  > $@
could you please let me know what is the difference.
Comment: `echo "hello" ;  > $@` -> `echo "hello"   > $@`. One command. Not two.
Answer: It seems echo "hello"; is executed first then some blank is written to the firstfile. and the for loop echo command result hello may be taken as string hello and the string is written to the firstfile. could please conform it.
Answer: ; is a command separator in the shell. So your first recipe:
firstfile:first
    echo "hello" ;  > $@

is equivalent to:
firstfile:first
    echo "hello"    # writes "hello" to your console
    > $@            # writes an empty string to `firstfile`

Change it to:
firstfile:first
    echo "hello"  > $@

Comment: @sri Welcome to Stackoverflow! Please see [What should I do when someone answers my question?](http://stackoverflow.com/help/someone-answers)

writing data to target in gnu make file


Wiring C wire in at a older unit

Question: e3eb-012h is the model number for a wiring diagram...
Trying to add a WiFi thermostat to my house, there is a blue wire ran but like most other topics on here it is not currently connected at the unit side of the wire... Feel like I should tie into one of the grey wires coming off the transformer but not completely sure and not trying to burn up my ac...
Appreciate the help!
Comment: Can you post photos of the wiring diagram, as well as the make of the furnace please?
Comment: Is that the model number of the furnace, the thermostat, your car, what? Including both the brand and model numbers of all devices is most helpful.
Comment: Interesting: Instruction 6 says "not to exceed 120V" but the schematic calls for 240V on the transformer!
Answer: An actual picture of the control board would help, but according to a wiring diagram that I can find any grey wire is the 0v reference from the 24v transformer.

Wiring C wire in at a older unit


CustomControl (Dropdownlist) in asp.net

Question: how to write events using delegates in customcontrol(Dropsownlist)
Comment: You might want to add a little more detail about what you've tried, what hasn't worked, etc. The community isn't here to write your code for you.
Answer: Here is sample using event in custom control:
<code>  using System;
  using System.Web.UI;

  namespace CustomControls
  {
     public class MyButton: Control, IPostBackEventHandler
     {
        // Defines the Click event.
        public event EventHandler Click;

        // OnClick dispatches the event to delegates that
        // are registered with the Click event.
        // Controls that derive from MyButton can handle the
        // Click event by overriding OnClick
        // instead of attaching a delegate. The event data
        // is passed as an argument to this method.
        protected virtual void OnClick(EventArgs e)
        {
           if (Click != null)
           {
              Click(this, e);
           }
        }

        // Method of IPostBackEventHandler that raises change events.
        public void RaisePostBackEvent(string eventArgument)
        {
           OnClick(EventArgs.Empty);
        }

        protected override void Render(HtmlTextWriter output)
        {
           output.Write("<INPUT TYPE = submit name = " + this.UniqueID +
              " Value = 'Click Me' />");
        }
     }
  }
</code>

CustomControl (Dropdownlist) in asp.net


Installing ubuntu on an HP chromebook

Question: I have a chrome book. hp chromebook 14.
I want to install ubuntu on it.
No dual booting. just simple ubuntu.
is there a way?
Comment: I think the only way to install Ubuntu on a Chromebook is to keep Chrome OS, since Crouton is required.
Comment: I tried. couldnt find it. thats why im here.
I guess I have to edit the bios somehow
Comment: @Zacharee1 Most software doesnt work for some reason. tried to use Qt, doesnt even open.
Comment: @tomkis that doesn't mean installing Ubuntu by itself will fix those problems. This sounds a lot like an XY Problem. Ask about your problem, not about a solution you're trying.
Comment: What I do before installing Ubuntu is check the hardware compatibility list found on Ubuntu.com. If its there it works, if not then it may or may not work. I looked for your HP Chromebook and did not see it on the list.
Comment: There are 3 different models, please specify which one you have http://www.chromium.org/chromium-os/developer-information-for-chrome-os-devices xicronic's answer is mostly correct, but installation methods can differ from model to model and GalliumOS is not an offical flavor, thus questions regarding it should be asked somewhere else e.g. Unix & Linux SE.
Answer: I would recommend taking a look at GalliumOS. It's based on Xubuntu 16.04 but with certain modifications to run better on Chromebooks, such as special kernel patches for audio support. Linked above is their hardware compatibility chart detailing which Chromebooks are compatible with GalliumOS, and what steps are needed to install it.

Installing ubuntu on an HP chromebook


How many triangles are there whose sides are prime numbers and have a perimeter equal to $29$?

Question:
Perimeter of a triangle is equal to $29$ and the values of all three sides are prime number. How many many incongruent triangles we have with this properties?

$1)2\qquad\qquad\qquad2)3\qquad\qquad\qquad3)4\qquad\qquad\qquad4)5$

First I realized that we can't have a side equal to $2$ because then perimeter will be even number. And we know that if $a,b,c$ are the values of sides we have:
$$a+b>c$$
Hence $29-c>c$ and $c<14.5$, similarly we have $a<14.5$  and $b<14.5$,  so we have $a,b,c\in\{3,5,7,11,13\}$ and $a+b+c=29$
From here is it possible to proceed without Try and Error ?
Comment: Why would one side $=2$ imply an even perimeter?
Comment: @lulu  Oh I forget the case that two sides can be $2$. but anyway in this case the third side is $25$ which is not a prime number.
Comment: Yes, that is a good argument for excluding $2$.
Comment: Beyond that, I think trial and error really is the way to go.  It's quite fast.
Comment: @lulu Yes, it seems the only way. thank you for the help!
Comment: @fGDu94 The longest side must be less than $\frac {29}2=14.5$ (the triangle condition)
Answer: Modulo $6$ the residues of the primes are $3,-1,1,-1,1$ respectively – and our target has residue $-1$ modulo $6$. If we use two $3$s the last side must be $23$, which is impossible. If we use one $3$ the other two sides must have residue $1$ each and sum to $26$ – the only possibility is $13$ and $13$. If no $3$s, there must be two residue $-1$ numbers and one residue $1$ number:

If the residue $1$ number is $7$, we can only have $11$ and $11$
If that number is $13$, we can only have $5$ and $11$

Hence there are $3$ incongruent admissible triangles: $\{3,13,13\},\{7,11,11\},\{5,11,13\}$.
Answer: You have set up the problem really well.
Let's think about how trial and error would work.  The only solution with a $3$ in it is $3+13+13$.  Now, can we upgrade the $3$ to a $5$ and reduce $2$ from one of the other sides?  Yes, that would lead to $5+11+13$.  That is the only solution with a $5$.  Can we do it again?  Yes, but moving the $5$ to a $7$ has to be balanced by reducing the other $13$, because $9$ is not prime.  Therefore, $7+11+11$ is the only solution with a $7$ in it.
Since you couldn't have any solutions without a $3, 5,$ or $7$ with a total of $29$, those are the only three solutions.


Uniqueness of minimizer of Lagrangian

Question: I have recently started calculus of variations and face the following task:

Consider the Lagrangian $$L(y',y):=|y'|$$ on the space of curves $$U = \{y\in C^2([0;T];\mathbb R): y(0)=a, y(T=1)=b \}$$ For which values of $a$ and $b$ does the functional $$A=\int_0^TL(y',y)dx$$ admit a unique minimizer? For which $a$ and $b$ does it admit infinitely many minimizers?

I tried to use Euler-Lagrange equation, but it gave nothing ($0=0$). Also $L(y',y)=|y'|$ is not strictly convex, so the unique theorem can't be applied.
Then I tried to calculate the integral directly
$$\int_0^T|y'|=\dfrac{y|y|}{2}\bigg|_0^T=\dfrac{y(T)|y(T)|}{2}-\dfrac{y(0)|y(0)|}{2}=\dfrac{b|b|-a|a|}{2}$$
so it doesn't really depend on curve, but only on endpoints,
 so I should have infinitely many minimizers for any $a,b$, but it doesn't really corresponds with question.
Thank for any help.
Comment: Your computation of the integral looks suspicious. Test it with $y(t)=t$, which belongs to $U$ with $a=0, b=T$. The correct result is $\int_0^T |y'|dt=T$. Your method gives $\tfrac{T^2}{2}$.
Comment: Thanks, I see my mistake because of lack of attention. I integrated $|y|$ instead of $|y'|$.
Answer: You are correct that, in general, there are an infinite number of minimizes for  $U = \{y\in C^2([0;T];\mathbb R): y(0)=a, y(T=1)=b \},  $ $\int_0^T |y'|$ . These correspond to the smooth, monotonic functions over $[0,T]$ with $y(0)=a, y(T) = b$. The value taken by the integral at the minimizer is $|a-b|$.
However, you obtain a unique minimizer when $a=b$, the constant function $y(x)=a$. The value taken by the integral of the minimizer is 0. If you take a non-constant $y$, when $a=b$, there will certainly be a point at which $y'$ changes sign. This will "mess" with the integral $\int_0^T |y'|$, and have its result be greater than 0. So the solution is to set $a=b$ and have the constant function as the only minimizer.
Comment: Thank you. I was going in the right direction, but had some problems. Can you explain, please, why do we need condition on monotonicity in the case $a\ne b$? In my opinion, it would be required, if we didn't have the absolute value of $|y'|$ under the integral.
Comment: Your integral was wrong.You have to start with the [definition](https://i.imgur.com/Q2sERrn.png) of the absolute-value function to compute it. You see it's a "nice" function, but only when $y'$ is of constant sign. The  correct way to compute $\int_0^T|y'|$ is to partition $[0,T]$ as a sequence of intervals, such that $sgn(y')$ is constant on each interval. Then do the sum of the integrals over said intervals. To see why this is true, take a simple function with y' negative, and compute the integral.Do the same for pozitive.Don't use the Euler-Lagrange equation, as |x|' is discontinuous.
Comment: This is a good explanation.

Uniqueness of minimizer of Lagrangian


Understanding and applying Burnside's lemma

Question: Recently I have questioned in here to understand the terms used for expressing Burnside's lemma $|X/G|=\frac{1}{|G|}\sum_{g\in G}|X^g|$. Someone explained the terms like the following way but I can not understand it.
Here a group $G$ acts on a set $X$. $X/G$ is the quotient of $X$ by $G$; that is, the set of orbits $\{G\cdot x\mid x\in X\}$, or equivalently the set of equivalence classes of $X$ where the equivalence relation is that $x\sim y$ if there is an element $g\in G$ so that $g\cdot x=y$. $X^g$ is the set of fixed points of a group element $g\in G$; i.e. $X^g=\{x\in X\mid g\cdot x=x\}$. So what the equation is saying that the umber of orbits is equal to the average number of fixed points.
I want to solve Necklace problem using Burnside's lemma .What do I need to do or know for intuitive understanding of Burnside's lemma and having capability to apply this lemma to solve the above problem?
Comment: A friendly suggestion from your friendly community moderator: Search the site. There are many examples with varying degrees of explanations. You also learn to use the site more efficiently - well worth your while for the future.
Answer: I think first try to see that this sum equal to $1$ if there is only one orbit i.e the action is transitive.
Let the action is transitive, We need to show that
$$\sum_{g\in G}|X^g|=|G|.$$
Note that we are making over sum as $a$ can be element of both $X^{g_1}$
 and $X^{g_2}$. How many times we over sum $a$ ?
Not surprisingly, $|Stab(a)|$ times. Since it is true for every elements of $X$, the sum is equal to $|Stab(a)||X|=|G|$. Thus, we are done.
In general, the sum is equal to $|G|$ on every orbits then the result follows.
Answer: Consider a matrix whose columns are indexed by elements of $G$ and whose rows are indexed by elements of $X$ with the property that the entry $(g, x)$ of the matrix is either $1$ or $0$ depending on whether $g$ fixes $x$ or not.
Start with an element $x \in X.$ The sum of the elements of the row $x$ is equals to $|G_x|,$ the stabilizer of $x.$ Also for any $y \in G.x := \{gx | g \in G\},$ the sum of the elements of the row is $y$ is again $|G_y|,$ because $G_x$ and $G_y$ are conjugate. Now $|G/G_x| = |G.x| \Rightarrow$ the sum of all the row-sums, as $y$ varies over a fixed orbit, is $|G|$ and this is independent of orbits. But the orbits partitioned $X$ into disjoint subsets. So the sum of the all the entries of the matrix is $|G| \times r,$ where $r$ is the number of distinct orbits of $X.$
On the other hand, the sum of the elements of a column $g$ is clearly $|X^g|.$ So the sum of the column-sums is $\sum_{g \in G} |X^g|.$


What is the name of the helmet shown on the loading screen?

Question: So I saw a helmet during a loading screen and can't figure out what it is. I know it's not part of any of the sets, but I can't figure out what it is.

Anyone know what that is?
Answer: The helmet in question is the Blades Helmet:

It's all black with three gold claw like things trailing back down the helmet originating from one point in the dead center of the crown of the helmet.

Helmets similar to your initial description that also appear on loading screens are:
The Jagged Crown (left) and the drangonscale helmet (right).
Comment: the blades helmet also appears in loading screens if I remember correctly
Comment: @spartacus major hat-tip in your direction for the hint to the answer, I haven't pursued the Blades quests myself so I don't think I'd triggered their artifacts in the loading screen
Comment: @Rory I haven't done their quests yet either, matter of fact I've been avoiding the main questline like the plague, but it still shows up often enough.
Answer: This is the Blades Helmet. I think its a carry on from Oblivion as you can get a sweet set of blades armour on that too. As for the golden trims on the top it is a dragon to signify that they were once great dragonslayers.
Comment: heres another tip without meaning to sound condiscending the description in the bottom right corner usually gives a good insight into the origin of the item displayed


Faster execution within a For Next loop

Question: I'm looking to make this piece of code faster at runtime and maybe, even, better built.
If you have an idea, I'm interested. Thank you. Claude.
TextBox1.AutoCompleteCustomSource.Clear()

For i As Integer = 0 To ListBox2.Items.Count - 1
     TextBox1.AutoCompleteCustomSource.Add(ListBox2.Items(i))
Next

ListBox2 contains only sorted unique strings, which allows me to not write in the TextBox1 text box, a duplicate string.
Comment: How did these *unique strings* end up inside a ListBox? Do you have a collection of strings stored somewhere else? Do you need the ListBox at all? When is this code run? Why do you have `TextBox1.AutoCompleteCustomSource.Clear()` there? Are you resetting the collection when *something happens*? On what condition? How often? Why don't you set the entire collection of string as the `AutoCompleteCustomSource` all at once (e.g., `TextBox1.AutoCompleteCustomSource = [Some list of strings]`)?
Comment: 1) How did these unique strings end up inside a ListBox? From a Treeview.
2) Do you have a collection of strings stored somewhere else? In the Treeview cited above.
3) Do you need the ListBox at all? When is this code run? Yes, I really need it.
4) When is this code run? When I create a new blank form to fill in my text boxes.
5) Why do you have TextBox1.AutoCompleteCustomSource.Clear() there? In order to reset the list.
6) Are you resetting the collection when something happens? No.
7) On what condition? Only when I create a new form.
8) How often? Right now a hundred times a day.
Comment: 9) Why don't you set the entire collection of string as the AutoCompleteCustomSource all at once (e.g., TextBox1.AutoCompleteCustomSource = [Some list of strings])? Good, because I didn't think about it.
Comment: *From a Treeview*: same question. So, what is the approx. number of strings you're dealing with? + You got them somewhere, what is the source? -- Now, these strings are used in a TreeView, a ListBox and another collection used for the AutoComplete feature. Anywhere else? Another collection filled by the data source? -- If you have it, use it. -- I could argue that these *strings* are used in too many places, but I won't do that :)
Answer: Bind AutoCompleteCustomSource to AutoCompleteStringCollection:
    Dim strArr As String() = ListBox2.Items.OfType(Of String)().ToArray()
    Dim MySource As New AutoCompleteStringCollection()
    MySource.AddRange(strArr)
    TextBox1.AutoCompleteCustomSource = MySource
    TextBox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend
    TextBox1.AutoCompleteSource = AutoCompleteSource.CustomSource

Comment: Thank you Xingyu Zhao. Excellent!
Answer: you can try this:
for each i to listbox.items.count -1
TextBox1.AutoCompleteCustomSource.Add(ListBox2.Items(i))
next
end for

the form goes catch i in real time and add list intem -1 then go to other line and terminate end

Faster execution within a For Next loop


Eclipse stops running reason = "breakpoint"

Question: I am working with eclipse using C++.  It was working fine till yesterday. Now when I use break points and debug I get a stopped,reason="breakpoint-hit" error and then eclipse stops.  Has anyone seen this error and anyone know how to fix it?
I have used breakpoints before to help me debug.  Instead of the step into, step over, and step out options, Eclipse stops running.  I am not doing anything out of the usual with breakpoints, I tried them at several different points and got the same problem.
Comment: Well, that's what breakpoints are for: to stop your program.
Comment: Question: why did you use breakpoints?
Comment: @Chris, My program doesn't pause like when I normally use breakpoints. My program dies.
Answer: Eclipse obviously has problems with debugging while you use the console for typing in input. Is that your case? I had that problem and while googling for a solution, I finally came upon a recommendation that while debugging, you should pass input to your program from a file rather than typing it to the console.
The recommendation can be found here:
http://webcourse.cs.technion.ac.il/234122/Spring2011/en/faq_Working%20with%20Eclipse%20CDT.html
(It's the question that starts with "I have a problem with debugging in Eclipse.".)
Hope this helps.


Android Alert Dialog in 2.1

Question: How do i customize alert dialog like GTasks
Answer: You can create a custom dialog box and make it as you want.
Yes you can change your Dialog box as you want.You can do this by creating a custom dialog box.
 Step1.Create a style in String file in res

Step2. Create the xml file in layouts
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/layout_quit"
              android:orientation="horizontal"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:background="@drawable/image which u want to show"
 >

Step3. Write code of custom dialog box in src

    class Custom_Dialog extends Dialog {

        protected Custom_Dialog(Context context, int theme) {
            super(context, theme);
            // TODO Auto-generated constructor stub
        }

    }
private void show_alert() {
        final Custom_Dialog alertbox = new Custom_Dialog(this, R.style.myQuitDialog);
        Window window = alertbox.getWindow();
        window.setBackgroundDrawableResource(android.R.color.transparent);
        window.requestFeature(window.FEATURE_NO_TITLE);

        alertbox.show();
        alertbox.setCancelable(true);
        alertbox.setCanceledOnTouchOutside(true);

                 alertbox.dismiss();
            }

    }

This is all what you need and accept it if you feel it satisfied you.
Comment: Thanks for your help i have found a following Github Repo which will help you to customize alert dialog, button, edittext etc.

  [1]: https://github.com/ChristopheVersieux/HoloEverywhere
Comment: Then what i will do with this @DineshAnandan. The above is the same thing to create a custom dialog box which you needed
Comment: I agree with you but i need ICS UI so I used the Github Repo. Your help much appreciated.
Comment: if you to really appreciate me then you can accept or vote my answer
Answer: Check this,
http://mgmblog.com/2010/06/10/arrayadapter-and-alertdialog-for-single-choice-items/

Android Alert Dialog in 2.1


How can I apply lambda function to 2 values in a row (lambda> missing 1 required argument)?

Question: I have a dataset of 2 columns: age_group, target(0,1).
I want to create 3rd column "count"(value counts of age_group). It has to look up if target is good and bad and put its corresponding count.
5 bins for ages:
df['age_group'] = pd.cut(df['age'], [17,22,26,32,45,50,60])

40 rows:
age_group       target
0   (45, 50]    bad
1   (45, 50]    bad
2   (32, 45]    good
3   (32, 45]    good
4   (50, 60]    bad
5   (32, 45]    bad
6   (26, 32]    good
7   (50, 60]    good
8   (32, 45]    bad
9   (17, 22]    good
10  (32, 45]    good

I could groupby by target:
df.groupby('target').age_group.value_counts().to_frame()

                          age_group
target       age_group
bad          (32, 45]      7
             (26, 32]      3
             (45, 50]      3
             (50, 60]      3
             (17, 22]      2
good         (32, 45]      8
             (17, 22]      4
             (50, 60]      4
             (45, 50]      3
             (26, 32]      2
             (22, 26]      1

but in this dataframe only age_group is the main accessible column. I can't access 'target' column and specific values for good, bad target.
I want to look up each age_group  AND its target and put the corresponding value in "count" column.
so I'm doing this ugly workaround function.
def get_value_count_for_age_group_category(age_group, target):
    bad_vals = df[df['bad']==1]['age_group'].value_counts().sort_index()
    good_vals = df[df['good']==1]['age_group'].value_counts().sort_index()
    values = age_freq.values.tolist()
    keys = age_freq.keys()
    if target == 'bad':
        for k in keys:
            if age_group == pd.Interval(32,45):
                return bad_vals[0]
            elif age_group == pd.Interval(50, 60):
                return bad_vals[1]
            elif age_group == pd.Interval(45, 50):
                return bad_vals[2]
            elif age_group == pd.Interval(26, 32):
                return bad_vals[3]
            elif age_group == pd.Interval(22, 26):
                return bad_vals[4]
            elif age_group == pd.Interval(17,22):
                return bad_vals[5]
    else:
        for k in keys:
            if age_group == pd.Interval(32,45):
                return good_vals[0]
            elif age_group == pd.Interval(50, 60):
                return good_vals[1]
            elif age_group == pd.Interval(45, 50):
                return good_vals[2]
            elif age_group == pd.Interval(26, 32):
                return good_vals[3]
            elif age_group == pd.Interval(22, 26):
                return good_vals[4]
            elif age_group == pd.Interval(17,22):
                return good_vals[5]

this is not working, passing 2 values - age_group and its target to a lambda function:
n['count'] = n[['age_group', 'target']].apply(lambda num:get_value_count_for_age_group_category(num, target) )

lambda>() missing 1 required positional argument:
Comment: what is you expected output?
Comment: @moys, my output is df with 3 columns, similar to groupby function i wrote. I want 3rd column added to main dataframe
Answer: Does this work for you?
df.groupby('target').age_group.value_counts().reset_index(name='count')

Input
age_group   target
0   (45, 50)    bad
1   (45, 50)    bad
2   (32, 45)    good
3   (32, 45)    good
4   (50, 60)    bad
5   (32, 45)    bad
6   (26, 32)    good
7   (50, 60)    good
8   (32, 45)    bad
9   (17, 22)    good
10  (32, 45)    good

Output
  target    age_group   count
0   bad     (32, 45)    2
1   bad     (45, 50)    2
2   bad     (50, 60)    1
3   good    (32, 45)    3
4   good    (17, 22)    1
5   good    (26, 32)    1
6   good    (50, 60)    1

If 'zero' vales are alse needed, plesae use below
df1=df.groupby('target').age_group.value_counts().reset_index(name='count')
df1.set_index(['target','age_group']).unstack(fill_value=0).stack().reset_index()

output
  target    age_group   count
0   bad     (17, 22)    0
1   bad     (26, 32)    0
2   bad     (32, 45)    2
3   bad     (45, 50)    2
4   bad     (50, 60)    1
5   good    (17, 22)    1
6   good    (26, 32)    1
7   good    (32, 45)    3
8   good    (45, 50)    0
9   good    (50, 60)    1

Comment: i always suspect there is one liner in pandas. but i dont know it.. so i try to write some horrible pile of code
Comment: also that one liner is  not giving age_group if its count is 0! to build a bar chart by target i need all values for all age groups..


Rolling window from time-series

Question: I am wondering if there is a simple and neat way to create a rolling window representation from a time-series data, using Pandas (etc)?
For example, consider the following Series object:
x = pd.Series(np.linspace(0,10,100))
df_wind = pd.DataFrame(roll_wind_func(x, wind_size=5))
Out:
           0         1         2         3             4
0   0.000000  0.324699  0.614213  0.837166  9.694003e-01
1   0.324699  0.614213  0.837166  0.969400  9.965845e-01
2   0.614213  0.837166  0.969400  0.996584  9.157733e-01
3   0.837166  0.969400  0.996584  0.915773  7.357239e-01
4   0.969400  0.996584  0.915773  0.735724  4.759474e-01
5   0.996584  0.915773  0.735724  0.475947  1.645946e-01
6   0.915773  0.735724  0.475947  0.164595 -1.645946e-01
7   0.735724  0.475947  0.164595 -0.164595 -4.759474e-01
8   0.475947  0.164595 -0.164595 -0.475947 -7.357239e-01
9   0.164595 -0.164595 -0.475947 -0.735724 -9.157733e-01
10 -0.164595 -0.475947 -0.735724 -0.915773 -9.965845e-01
11 -0.475947 -0.735724 -0.915773 -0.996584 -9.694003e-01
12 -0.735724 -0.915773 -0.996584 -0.969400 -8.371665e-01
13 -0.915773 -0.996584 -0.969400 -0.837166 -6.142127e-01
14 -0.996584 -0.969400 -0.837166 -0.614213 -3.246995e-01
15 -0.969400 -0.837166 -0.614213 -0.324699 -2.449294e-16

I have implemented (though ugly) the roll_wind_func(data=, wind_size=), but I'm wondering if Pandas offers a simpler solution (without loops)
Comment: Here's an efficient one using NumPy strides - http://stackoverflow.com/a/40085052/3293881
Answer: How about:
pd.DataFrame({i: x.shift(-i) for i in range(5)}).dropna()

Comment: thanks, but I added `.dropna()` at the end to get the desired result.

Rolling window from time-series


How do I transport items upwards from a monster trap?

Question: Is there a way to transport items upwards from, say, a monster trap? Water flow works fine downwards.
Comment: Great question! My solution would be to move the mobs upwards and then kill them, as to my knowledge you can't move items upwards.
Comment: Items (the kind you can collect by walking over them) sink in water so you can't move them up using water, but mobs can be transfered upwards in a water ladder.
Comment: I'm not sure, but I know boats move upwards when pushed against a water ladder, so if items experience the same behaviour, there might be some way to drive them towards a water ladder. You'd need some collection system at the top though.
Comment: This is a great question, but spawners will not actually spawn anything unless you are close to them that may be an issue if you want items flowing in always.
Answer: Edit: With the addition of pistons into Minecraft, YouTuber Basxt came up with a very clever way to make an "item elevator", using pistons. However, since pistons can only push 12 blocks at a time, you'd need to make many of these elevators that pass the items off to each other in order to transport items a large distance upwards.

Begin original answer:
There is no way to transfer items upwards. However, specific to your point about transporting items from a monster trap, you can instead move the mobs upwards and kill them above.
YouTuber EthosLab has a 4 part tutorial on how to make a mob trap. His system contains a tunnel that transports the mobs upwards, and the information he gives (audio) about it is very useful.
Part 1:
Comment: Sometimes... people talk... slowly... and finish normal... sentences... like a question?... As you can see... this can be... annoying?
Comment: Ethos has really improved since his early stuff O.o
Comment: @StuartPegg [Uptalk](http://en.wikipedia.org/wiki/High_rising_terminal) in this video appears to be serving the "not finished yet" pragmatics function.
Comment: @SevenSidedDie: Or instead is just a symptom of insecurity; not unexpected when recording a video for an unknown audience. That article made me laugh though: "moronic interrogative" pffft!
Answer: In the 1.5 update, Minecraft now includes Droppers, which can face upwards. By chaining them together with a bit of redstone you can easily move items up any vertical distance:

It's essentially just a repeating pattern like this:
Comment: At least two of the snapshots killed this particular elevator design...
Comment: @Unionhawk I'll have to do more research later...
Comment: [Comparators no longer cause updates continuously](https://mojang.atlassian.net/browse/MC-6077) and [droppers/dispensers no longer shoot when updated](https://mojang.atlassian.net/browse/MC-846). You can simply use a redstone clock instead to fix this setup.
Answer: A horizontally "crushing" block powered by a piston would pop all items in its spot up one.  You could theoretically use a "zipper" type piston shaft to pop the items upward.  The only catch is that the items need to have nowhere else to go but up.
Answer: There is a conveyor belt mod for 1.8.1 that can be used to craft conveyor belts and item-detecting conveyor belts. These can be used to transport items horizontally, and with redstone and pistons, to transport items up a slope.
Its easy - just have a look at the "How to make Conveyor Belt" section here.
Comment: Welcome to Gaming.SE Marko. Here, and on most other StackExchange websites, we frown on people simply dumping a link with no explanation. First, it requires that the user visit it to gain any useful information, and second, and more critically, external links frequently die. If the link rots, your post becomes meaningless and might frustrate a user trying to find an answer.
Comment: Marko, I've edited this to explain what you're linking to and point to the correct section of the page. Your posts are much more likely to get a good response if you can include an explanation like this, rather than just a link.
Comment: Er...okay usually i frown on people downvoting "just link" posts, but I agree on this one. The link doesn't even go to the correct page.
Answer: Another solution is to go down yourself with a cart or a boat, you can drive past the pick-up point.
Then use a booster or a water boat elevator to go back up quickly, some players use this in a horizontal way if your base is far away from your collector. But it would work similar in the vertical way...
Answer:

It may not be efficient for materials, and it might be slow, but it certainly gets items moving upwards. The previously posted youtube video in this thread doesn't work in 1.2.3 because of a change in water physics at some point.
Answer: Set up a loading hopper and a storage minecart at the bottom, and an unloading hopper at the top. Then you just have to do a spiral rail track; something like a 3x3 powered track where it's not a curve, around a redstone block.
Comment: @Robotnik I edited with what I think tommy was going for. Is better?
Comment: Hi Tommy, welcome to Arqade! I'm unsure how this answer will help raise dropped items to the surface. Can you please elaborate?
Comment: @SevenSidedDie - Ah, that makes more sense. +1
Answer: Suffocating items
This only works in Minecraft 1.8 and some snapshots
If you suffocate a item, it will move upward in 1.8. There are different designs for this, but the most commonly used one uses a fence. It is build like this with water in front of the dispenser:

Then on top of the fences, blocks are placed in a 3 by 3 pattern, expanding upwards, trapping the items as they glitch into fence and move upward:

Dropper based
There have been a large number of dropper based designs:
The torch based tower design
These towers are designed with a stack of torches next to hoppers, duo to the speed of which torches can propagate a signal, and the fact that only 1 clock edge is useful, it usually means that these kind of systems can only move 1 item every 2 seconds, half the speed of a hopper chain. This can be migrated using a item divider that divides item fairly between set hopper routes.
A simple torch based design looks like:

Independent dropper system
In this kind of design, every dropper is independent from the whole story, meaning that every dropper has its own comparator, and its own driving circuit. The downside of the method is that it uses a lot of quartz in its design, but comes with the advantage of driving the droppers at the speed of hoppers, while handling stalls in the output correctly. A simple design that cooperates this technique is:

This design has 2 droppers placed above each other, and the left circuit processes the upper hopper, while the right circuit controls the lowest hopper, this circuit is also flat, so it can be stacked seamlessly up itself to reach higher places.
Redstone beam dropper design
While torches work, using a row of redstone blocks with pistons to trigger the droppers yields higher transfer rates, because every update of the chain triggers the droppers and moves an item. This system requires a move complex driving circuit because the redstone blocks need to be moved up and down.
Slime block based elevators
Slime blocks have the ability to launch entity upward, by combining this with suspended water blocks above signs, you can move the items to the next piston with slime for even increased height. A simple shaft (without control circuity) for this looks like:

Minecart based systems
You can also use chest/hopper minecarts to move items up and down, this is as simple as building an item loader at the bottom, and an item unloader at the top.
Command blocks
Even though command blocks are cheating, this is useful in adventure maps. By placing a command block on a loop and executing the command <code>/tp @a[r=5,type=Item] ~ ~10 ~</code>, you can move items up if they come in a radius of 5 blocks of the command block.
Answer: I would use a mob elevator using ladders and water, then kill them at a higher point and use water to push you items were they need to go.
Comment: Hi, Bob, and welcome to Arqade!  Could you add a picture describing what you mean? Some people might not be familiar with this method.
Answer: I recently remembered a YouTube video from a well-known Minecraft YouTuber (who I have currently forgotton the name of) who realised items, when squished into blocks, would rise upwards. I came up with this simple video to demonstrate (I initially thought this question mentioned moving resources upwards, hence the auto-smelter).
In the video, the minecart is filled with ores that gets parked over a hopper. The hopper empties into a furnace and the furnace is supplied with a chest+hopper full of coal. The smelted gold is then dropped into a dropper which then drops the smelted ore into a water channel (this is where the output from your mob trap would flow into) which then flows into a 3x3 pool. When you decide enough items are in, you flick a switch to send a 3x3x1 grid of blocks upward which forces the items/mob drops into a 3x3xX colum of glass blocks (I've just used glass to demonstrate, any block will work here.
Once the items have reached the top, they are carried away in a water flow into a series of hoppers and into a chest.
I could have made this higer but I chose the wrong preset for the world which meant I was at the height limit.

Or you could use Minecarts with Hoppers on an automatic circuit to move them up, but, y'know, why make things easy? Would also likely be more expensive, using iron and gold to build the rails.
Answer: You could use mods, Buildcraft, Redpower, and Thaumcraft have very well fleshed out item transfer mechanics. (pipes for the first 2, magical means for thaumcraft)
If you absolutely must do it the vanilla way, pistons and/or droppers are your best bet for upwards item transfer.
Answer: You could use pistons to extend upwards every time a item drops onto a presureplate
Comment: but...the item is on a pressure plate...


Symfony - image in response - speed, optimization

Question: I generate dynamically graphic in my controller:

if not file exists (unique filename) then generate graphic and save it
return RedirectResponse($url)

(3. I've tried also:
    $fp = fopen($url, "rb");
    $str = stream_get_contents($fp);
    fclose($fp);

    $response = new Response($str, 200);
    $response->headers->set('Content-Type', 'image/png');
    return $response;

)
I need it to generate dynamically userbars for users [on this graphic some text will be automatically updating if some changes will be done on my websites].
So it's important for me that this script works fast and doesn't kill my server/bandwitch. To achieve that I've made cache where all generated graphics are stored. But i've got a problem with speed, solutions which i've described above are pretty slow, when i've tested it in chrome with developer tool (F12) then it shows me that both solution (2. and 3.) takes about ~1s (when the same graphics [without controllers etc. just direct url to .png] loads 44ms).
So if only for me it takes about ~1s per graphic then if for example 1000 users will generate at the same time this graphic it can slower my website I think.
Please help, do you know any faster ways to do that?
PS. Redirect isn't most desire thing for me, because I would prefer to leave url as it is, for example smth/username/userbar/ insted of smth/img/userbars/cache/blabla.png. But if it will be much faster then I can stand it :).
EDIT: To be clear: I'm not looking for solution to cache images, my problem is that returning images via controller (already generated images, just from ftp) takes about 1s, when normally if you do for example

it takes about 44ms.
Answer: You can use Varnish to cache the images, Varnish is a HTTP proxy that sits in front of the webserver. It takes some time & knowledge to configure it, but it is a very good piece of software.
Alternatively, you may cache the images in memory using shared memory, memcache, or redis. This would probably be less effectly than Varnish, but it would save the filesystem IO.
You should test where the most time is spent, I expect it's a combination of file I/O and PHP parsing time, but as we saying in Dutch, "Measuring is knowing" ;)
Here's a simple example which should give you the general idea on how to do that:
<?php
class MyClass
{
  function __construct()
  {
     $this->timer = array(
       'start' => microtime(True);
     );
   }

  function myAction()
  {
    $this->timer['startaction'] = microtime(True);

    $fp = fopen($url, "rb");
    $this->timer['startstream'] = microtime(True);
    $str = stream_get_contents($fp);
    fclose($fp);
    $this->timer['endstream'] = microtime(True);

    $response = new Response($str, 200);
    $response->headers->set('Content-Type', 'image/png');

    $this->timer['endaction'] = microtime(True);
    print_r($this->timer)
    return $response;
  }
}

Another thing that may be an option is to use HTML/CSS to show the graphs. This may or may not work depending in what your graphs look like but I've used this in the past and it worked quite well.
Comment: "is to use HTML/CSS to show the graphs" what do you mean?
I don't see it because I need first to get some statistics from database, so I would prefere to pass it by Controller.

I think that a problem is in returning this image (using stream_get_contents or redirection which takes about 800ms).
By the way, maybe I'm totaly wrong and my solution isn't so bad? If it only affects on loading image for user and it won't slow down server than I think it could be as it is?  As I see you focused on storing generated images, but a real problem is in returning this image :).
Comment: This times which I've written down above refers to loading images from cache. Load already generated image from ftp via controller takes about 1s and I would like to improve it.
Comment: Thanks for advice, i've tested it and generally it isn't so bad. When I generated graphic separately then it loads only about 150ms (doesn't matter if by redirect or stream_get_contents) so it's not so bad i think. Loading it directly takes about 32ms, but I check if file exists, get information from database and get graphic, so it seems to be good.


How to detect user is idle or inactivity in jetpack compose?

Question: Suppose I have an action to be executed after a certain amount of time without the user touching the screen. How can I implement a timer that executes an action when it times out, but starts over user trigger a switch
Answer: Use LaunchedEffect:
LaunchedEffect(key = <your switch state>) {
   delay(<certain amount of time in milliseconds>)
   executeAction() // action to be executed
}

LaunchedEffect restarts its lambda when key changes. So this code will call executeAction() after specified delay only if the key remains the same. If User toggles Switch, its state changes and LaunchedEffect restarts and delay() will be called again.
Comment: ? please more spesific bro
Comment: @Taka Nendra Han See updated answer
Comment: A link to documentation would be nice here :)


socket send throws timeout error

Question: I have a  proxy client between two servers. The main server S1 is on the internet. The proxy client and the second server S2 sit in the same intranet. I have the following code (parts left out for simplicity) which is responsible for forwarding data coming from S2 'as is' to S1:
fsctimeout = 0.01

function send_data(sock, data, i, l)
    local p,err,q = sock:send(data, i, l)
    if(err == "timeout" and q ~= l) then
        fsctimeout = fsctimeout * 2
        sock:settimeout(fsctimeout)
        send_data(sock, data, q + 1, l)
        fsctimeout = fsctimeout / 2
        sock:settimeout(fsctimeout)
    end
end

while not e do

rect, _, st = socket.select({csc, fsc}, nil, .01) --csc is S1, fsc is S2 sockets.

    if(rect[fsc] ~= nil and csc ~= nil) then
        local data, err, part = fsc:receive(8192)
        if(data ~= nil) then
            send_data(csc, data, 1, data:len())
            totalBytesFromFP = totalBytesFromFP + data:len()
        end
        if(part ~= nil) then
            send_data(csc, part, 1, part:len())
            totalBytesFromFP = totalBytesFromFP + part:len()
        end
    end
 end

I wrote the send_data function so that if a send timeouts, it will double the socket timeout and try again. But now sometimes the programs gets stuck inside the send_data function without being successful in sending data. What can I do here? (I am testing trying to send a 1MB file, for small amounts of data this problem doesn't seem to be happenning.)
Answer: You change timeout for the first time only after you get "timeout" error, but it never happens because by default send is blocking (so it will never times out).
Just add csc:settimeout(fsctimeout) before your loop.

socket send throws timeout error


Cannot deserialize ArrayList object out of String from nested XML to Java POJO using Jackson

Question: I have a REST service that calls an external endpoint which returns XML response.
Project dependencies are basically Lombok, spring starter web and jackson.
<dependency>
  <groupId>com.fasterxml.jackson.dataformat</groupId>
  <artifactId>jackson-dataformat-xml</artifactId>
  <version>2.13.3</version>
</dependency>

Here is the current XML response received once the endpoint is called:
<?xml version="1.0" encoding="UTF-8"?>
<Publication_MarketDocument xmlns="urn:iec62325.351:tc57wg16:451-3:publicationdocument:7:0">
   <mRID>032af514c4a34ede9911c84cda33a547</mRID>
   <revisionNumber>1</revisionNumber>
   <type>A44</type>
   <sender_MarketParticipant.mRID codingScheme="A01">10X1001A1001A450</sender_MarketParticipant.mRID>
   <sender_MarketParticipant.marketRole.type>A32</sender_MarketParticipant.marketRole.type>
   <receiver_MarketParticipant.mRID codingScheme="A01">10X1001A1001A450</receiver_MarketParticipant.mRID>
   <receiver_MarketParticipant.marketRole.type>A33</receiver_MarketParticipant.marketRole.type>
   <createdDateTime>2022-09-01T12:15:32Z</createdDateTime>
   <period.timeInterval>
      <start>2015-12-31T23:00Z</start>
      <end>2016-01-02T23:00Z</end>
   </period.timeInterval>
   <TimeSeries>
      <mRID>1</mRID>
      <businessType>A62</businessType>
      <in_Domain.mRID codingScheme="A01">10YCZ-CEPS-----N</in_Domain.mRID>
      <out_Domain.mRID codingScheme="A01">10YCZ-CEPS-----N</out_Domain.mRID>
      <currency_Unit.name>EUR</currency_Unit.name>
      <price_Measure_Unit.name>MWH</price_Measure_Unit.name>
      <curveType>A01</curveType>
      <Period>
         <timeInterval>
            <start>2015-12-31T23:00Z</start>
            <end>2016-01-01T23:00Z</end>
         </timeInterval>
         <resolution>PT60M</resolution>
         <Point>
            <position>1</position>
            <price.amount>16.50</price.amount>
         </Point>
         <Point>
            <position>2</position>
            <price.amount>15.50</price.amount>
         </Point>
         <Point>
            <position>3</position>
            <price.amount>14.00</price.amount>
         </Point>
         <Point>
            <position>4</position>
            <price.amount>10.01</price.amount>
         </Point>
         <Point>
            <position>5</position>
            <price.amount>8.97</price.amount>
         </Point>
         <Point>
            <position>6</position>
            <price.amount>12.23</price.amount>
         </Point>
         <Point>
            <position>7</position>
            <price.amount>12.10</price.amount>
         </Point>
         <Point>
            <position>8</position>
            <price.amount>14.00</price.amount>
         </Point>
         <Point>
            <position>9</position>
            <price.amount>5.00</price.amount>
         </Point>
         <Point>
            <position>10</position>
            <price.amount>10.01</price.amount>
         </Point>
         <Point>
            <position>11</position>
            <price.amount>14.50</price.amount>
         </Point>
         <Point>
            <position>12</position>
            <price.amount>5.00</price.amount>
         </Point>
         <Point>
            <position>13</position>
            <price.amount>6.00</price.amount>
         </Point>
         <Point>
            <position>14</position>
            <price.amount>11.05</price.amount>
         </Point>
         <Point>
            <position>15</position>
            <price.amount>21.00</price.amount>
         </Point>
         <Point>
            <position>16</position>
            <price.amount>25.00</price.amount>
         </Point>
         <Point>
            <position>17</position>
            <price.amount>31.20</price.amount>
         </Point>
         <Point>
            <position>18</position>
            <price.amount>34.02</price.amount>
         </Point>
         <Point>
            <position>19</position>
            <price.amount>35.00</price.amount>
         </Point>
         <Point>
            <position>20</position>
            <price.amount>34.50</price.amount>
         </Point>
         <Point>
            <position>21</position>
            <price.amount>34.03</price.amount>
         </Point>
         <Point>
            <position>22</position>
            <price.amount>30.00</price.amount>
         </Point>
         <Point>
            <position>23</position>
            <price.amount>28.13</price.amount>
         </Point>
         <Point>
            <position>24</position>
            <price.amount>21.80</price.amount>
         </Point>
      </Period>
   </TimeSeries>
   <TimeSeries>
      <mRID>2</mRID>
      <businessType>A62</businessType>
      <in_Domain.mRID codingScheme="A01">10YCZ-CEPS-----N</in_Domain.mRID>
      <out_Domain.mRID codingScheme="A01">10YCZ-CEPS-----N</out_Domain.mRID>
      <currency_Unit.name>EUR</currency_Unit.name>
      <price_Measure_Unit.name>MWH</price_Measure_Unit.name>
      <curveType>A01</curveType>
      <Period>
         <timeInterval>
            <start>2016-01-01T23:00Z</start>
            <end>2016-01-02T23:00Z</end>
         </timeInterval>
         <resolution>PT60M</resolution>
         <Point>
            <position>1</position>
            <price.amount>0.01</price.amount>
         </Point>
         <Point>
            <position>2</position>
            <price.amount>1.00</price.amount>
         </Point>
         <Point>
            <position>3</position>
            <price.amount>0.01</price.amount>
         </Point>
         <Point>
            <position>4</position>
            <price.amount>0.01</price.amount>
         </Point>
         <Point>
            <position>5</position>
            <price.amount>2.01</price.amount>
         </Point>
         <Point>
            <position>6</position>
            <price.amount>1.00</price.amount>
         </Point>
         <Point>
            <position>7</position>
            <price.amount>0.01</price.amount>
         </Point>
         <Point>
            <position>8</position>
            <price.amount>1.00</price.amount>
         </Point>
         <Point>
            <position>9</position>
            <price.amount>5.11</price.amount>
         </Point>
         <Point>
            <position>10</position>
            <price.amount>22.00</price.amount>
         </Point>
         <Point>
            <position>11</position>
            <price.amount>41.29</price.amount>
         </Point>
         <Point>
            <position>12</position>
            <price.amount>51.08</price.amount>
         </Point>
         <Point>
            <position>13</position>
            <price.amount>51.09</price.amount>
         </Point>
         <Point>
            <position>14</position>
            <price.amount>61.93</price.amount>
         </Point>
         <Point>
            <position>15</position>
            <price.amount>50.00</price.amount>
         </Point>
         <Point>
            <position>16</position>
            <price.amount>53.04</price.amount>
         </Point>
         <Point>
            <position>17</position>
            <price.amount>100.00</price.amount>
         </Point>
         <Point>
            <position>18</position>
            <price.amount>64.83</price.amount>
         </Point>
         <Point>
            <position>19</position>
            <price.amount>58.02</price.amount>
         </Point>
         <Point>
            <position>20</position>
            <price.amount>32.29</price.amount>
         </Point>
         <Point>
            <position>21</position>
            <price.amount>35.08</price.amount>
         </Point>
         <Point>
            <position>22</position>
            <price.amount>22.00</price.amount>
         </Point>
         <Point>
            <position>23</position>
            <price.amount>22.00</price.amount>
         </Point>
         <Point>
            <position>24</position>
            <price.amount>16.00</price.amount>
         </Point>
      </Period>
   </TimeSeries>
</Publication_MarketDocument>

And below are all the Java classes that I am using in order to map the above XML to POJOs.
PublicationMarketDocument class
@Data
public class PublicationMarketDocument {
    @JsonProperty("revisionNumber")
    private String revisionNumber;
    @JsonProperty("period.timeInterval")
    private TimeInterval timeInterval;
    @JsonProperty("TimeSeries")
    private List<TimeSeries> timeSeries;
}

TimeInterval class
@Data
public class TimeInterval {
    @JsonProperty("start")
    private String start;
    @JsonProperty("end")
    private String end;
}

TimeSeries class
@Data
public class TimeSeries {
    @JsonProperty("businessType")
    private String businessType;
    @JsonProperty("in_Domain.mRID")
    private String inDomain;
    @JsonProperty("out_Domain.mRID")
    private String outDomain;
    @JsonProperty("currency_Unit.name")
    private String currencyName;
    @JsonProperty("price_Measure_Unit.name")
    private String priceMeasureUnitName;
    @JsonProperty("curveType")
    private String curveType;
    @JsonProperty("Period")
    private Period period;
}

Period class
@Data
public class Period {

    @JsonProperty("timeInterval")
    private TimeInterval timeInterval;
    @JsonProperty("resolution")
    private String resolution;
    @JsonProperty("Point")
    private List<Point> point;
}

Point class
@Data
public class Point {
    @JsonProperty("position")
    String position;
    @JsonProperty("price.amount")
    String priceAmount;
}

Here is the controller class used to actually invoke the external API:
@RestController
@RequestMapping("/api/v1/")
@Slf4j
public class FetchController {

    @GetMapping(value = "day-ahead-prices", produces = MediaType.APPLICATION_JSON_VALUE)
    public ResponseEntity<PublicationMarketDocument> getDayAheadPrices() {

        String localUrl = URL + "&periodStart=" + pStart + "&periodEnd=" + pEnd;

        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<PublicationMarketDocument> response = restTemplate.getForEntity(localUrl, PublicationMarketDocument.class);

        return new ResponseEntity<>(response.getBody(), HttpStatus.OK);

    }
}

Here is the error received on app initiliazation:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.web.client.RestClientException: Error while extracting response for type [class com.example.openvpp.models.MarketDataModel] and content type [text/xml]; nested exception is org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot construct instance of `com.example.openvpp.models.TimeSeries` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('1'); nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot construct instance of `com.example.openvpp.models.TimeSeries` (although at least one Creator exists): no String-argument constructor/factory method to deserialize from String value ('1')
 at [Source: (org.springframework.util.StreamUtils$NonClosingInputStream); line: 16, column: 10] (through reference chain: com.example.openvpp.models.MarketDataModel["TimeSeries"]->java.util.ArrayList[0])] with root cause

Below approximate result is obtained only if we do not have the TimeSeries and Point fields as Lists in the caller classes. Once we wrap them as List<>, the problem occurs.
{
    "revisionNumber": "1",
    "period.timeInterval": {
        "start": "2015-12-31T23:00Z",
        "end": "2016-01-01T23:00Z"
    },
    "TimeSeries": {
        "businessType": "A62",
        "in_Domain.mRID": "10YCZ-CEPS-----N",
        "out_Domain.mRID": "10YCZ-CEPS-----N",
        "currency_Unit.name": "EUR",
        "price_Measure_Unit.name": "MWH",
        "curveType": "A01",
        "Period": {
            "timeInterval": {
                "start": "2015-12-31T23:00Z",
                "end": "2016-01-01T23:00Z"
            },
            "resolution": "PT60M",
            "Point": {
                "position": "24",
                "price.amount": "21.80"
            }
        }
    }
}

The main problem that I am facing is deserializing the nested XML fields to TimeSeries and Point List Objects. Already tried adding @JsonFormat(with = JsonFormat.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY) to both of them with no success.
Also tried this annotation @JsonDeserialize(as=ArrayList.class, contentAs=Point.class) however error remains the same.
Is there an elegant way to do it at the moment and is this a drawback of jackson library itself?
I do not have control over the external XML endpoint. Furthermore I do not control an ObjectMapper instance since I want Jackson to do the mapping of the XML to Java POJOs entirely.
PS Adding here the final results obtained after @qdoot advised of using the @JacksonXmlElementWrapper(useWrapping = false) annotation. Hope this helps for someone looking at this in the future.
{
    "revisionNumber": "1",
    "period.timeInterval": {
        "start": "2015-12-31T23:00Z",
        "end": "2016-01-02T23:00Z"
    },
    "TimeSeries": [
        {
            "businessType": "A62",
            "in_Domain.mRID": "10YCZ-CEPS-----N",
            "out_Domain.mRID": "10YCZ-CEPS-----N",
            "currency_Unit.name": "EUR",
            "price_Measure_Unit.name": "MWH",
            "curveType": "A01",
            "Period": {
                "timeInterval": {
                    "start": "2015-12-31T23:00Z",
                    "end": "2016-01-01T23:00Z"
                },
                "resolution": "PT60M",
                "Point": [
                    {
                        "position": "1",
                        "price.amount": "16.50"
                    },
                    {
                        "position": "2",
                        "price.amount": "15.50"
                    },
                    {
                        "position": "3",
                        "price.amount": "14.00"
                    },
                    {
                        "position": "4",
                        "price.amount": "10.01"
                    },
                    {
                        "position": "5",
                        "price.amount": "8.97"
                    },
                    {
                        "position": "6",
                        "price.amount": "12.23"
                    },
                    {
                        "position": "7",
                        "price.amount": "12.10"
                    },
                    {
                        "position": "8",
                        "price.amount": "14.00"
                    },
                    {
                        "position": "9",
                        "price.amount": "5.00"
                    },
                    {
                        "position": "10",
                        "price.amount": "10.01"
                    },
                    {
                        "position": "11",
                        "price.amount": "14.50"
                    },
                    {
                        "position": "12",
                        "price.amount": "5.00"
                    },
                    {
                        "position": "13",
                        "price.amount": "6.00"
                    },
                    {
                        "position": "14",
                        "price.amount": "11.05"
                    },
                    {
                        "position": "15",
                        "price.amount": "21.00"
                    },
                    {
                        "position": "16",
                        "price.amount": "25.00"
                    },
                    {
                        "position": "17",
                        "price.amount": "31.20"
                    },
                    {
                        "position": "18",
                        "price.amount": "34.02"
                    },
                    {
                        "position": "19",
                        "price.amount": "35.00"
                    },
                    {
                        "position": "20",
                        "price.amount": "34.50"
                    },
                    {
                        "position": "21",
                        "price.amount": "34.03"
                    },
                    {
                        "position": "22",
                        "price.amount": "30.00"
                    },
                    {
                        "position": "23",
                        "price.amount": "28.13"
                    },
                    {
                        "position": "24",
                        "price.amount": "21.80"
                    }
                ]
            }
        },
        {
            "businessType": "A62",
            "in_Domain.mRID": "10YCZ-CEPS-----N",
            "out_Domain.mRID": "10YCZ-CEPS-----N",
            "currency_Unit.name": "EUR",
            "price_Measure_Unit.name": "MWH",
            "curveType": "A01",
            "Period": {
                "timeInterval": {
                    "start": "2016-01-01T23:00Z",
                    "end": "2016-01-02T23:00Z"
                },
                "resolution": "PT60M",
                "Point": [
                    {
                        "position": "1",
                        "price.amount": "0.01"
                    },
                    {
                        "position": "2",
                        "price.amount": "1.00"
                    },
                    {
                        "position": "3",
                        "price.amount": "0.01"
                    },
                    {
                        "position": "4",
                        "price.amount": "0.01"
                    },
                    {
                        "position": "5",
                        "price.amount": "2.01"
                    },
                    {
                        "position": "6",
                        "price.amount": "1.00"
                    },
                    {
                        "position": "7",
                        "price.amount": "0.01"
                    },
                    {
                        "position": "8",
                        "price.amount": "1.00"
                    },
                    {
                        "position": "9",
                        "price.amount": "5.11"
                    },
                    {
                        "position": "10",
                        "price.amount": "22.00"
                    },
                    {
                        "position": "11",
                        "price.amount": "41.29"
                    },
                    {
                        "position": "12",
                        "price.amount": "51.08"
                    },
                    {
                        "position": "13",
                        "price.amount": "51.09"
                    },
                    {
                        "position": "14",
                        "price.amount": "61.93"
                    },
                    {
                        "position": "15",
                        "price.amount": "50.00"
                    },
                    {
                        "position": "16",
                        "price.amount": "53.04"
                    },
                    {
                        "position": "17",
                        "price.amount": "100.00"
                    },
                    {
                        "position": "18",
                        "price.amount": "64.83"
                    },
                    {
                        "position": "19",
                        "price.amount": "58.02"
                    },
                    {
                        "position": "20",
                        "price.amount": "32.29"
                    },
                    {
                        "position": "21",
                        "price.amount": "35.08"
                    },
                    {
                        "position": "22",
                        "price.amount": "22.00"
                    },
                    {
                        "position": "23",
                        "price.amount": "22.00"
                    },
                    {
                        "position": "24",
                        "price.amount": "16.00"
                    }
                ]
            }
        }
    ]
}

Comment: Please provide the code that actually makes the conversion with the ObjectMapper I assume...
Comment: @Stempler, please note that I do not have such code in the codebase. I would like to do the implementation without involving ObjectMapper explicitly and want Jackson to take care of the conversion from XML response above to Java POJOs.
Comment: What was missing from my post above was only the actual controller class, so I added it for sanity reasons although it is not essential in this case.
Answer: You might try @JacksonXmlElementWrapper
   @JacksonXmlElementWrapper(useWrapping=false)
   private List<Point> point;

Comment: This actually helped! I added above annotation with `useWrapping=false` to both the `List point` and `List timeSeries` fields. Now I have what I want without the need to use ObjectMapper explicitly for the conversion. Thank you @qdoot!


A polynomial of degree $n$ has at most $n$ roots.

Question: I'm auditing a number theory course. I'm trying to prove the following:

A polynomial of degree $n$ has at most $n$ roots

I know there are many proofs of this on SE, however none are particularly accessible (for me, at least). I know a bit of number theory, and a bit of abstract algebra. Any good starting points or hints?
Comment: "None are particularly accessible" how come? Besides, what coefficients do those polynomials have?
Comment: It will be difficult for anyone to answer this if you do not explain what troubles you have understanding those other proofs.
Comment: I assume that the coefficients are drawn from a field. Argue by induction on the degree. The assertion plainly holds if the degree is 1. Assume the result for all polynomials of degree (n-1) as your induction hypothesis. Now consider a polynomial of degree n. If it has no roots there is nothing to prove. It it has a root, factor it out and use the induction hypothesis.
Comment: Does this answer your question? [How do I prove that a polynomial F\[x\] of degree n has at most n roots](https://math.stackexchange.com/questions/219115/how-do-i-prove-that-a-polynomial-fx-of-degree-n-has-at-most-n-roots)
Comment: That's not the fundamental theorem of algebra. That theorem says that a *complex* polynomial has *exactly* $n$ roots (if we include multiplicity). So do you need a proof of the claim you wrote, or of the FTOA?
Comment: My apologies. I need a proof of the claim as written.
Comment: You might need this  https://en.m.wikipedia.org/wiki/Polynomial_remainder_theorem and the Unique Factorization Property of a polynomial ring over a field.
Comment: Do you know polynomial division?
Answer: Hint:  There's a factor theorem saying that if $a$ is a root, then $p(x)$ has $x-a$ as a factor.


Is %$var dereferencing a Perl hash?

Question: I'm sending a subroutine a hash, and fetching it with my($arg_ref) = @_;
But what exactly is %$arg_ref? Is %$ dereferencing the hash?
Answer: $arg_ref is a scalar since it uses the $ sigil.  Presumably, it holds a hash reference.  So yes, %$arg_ref deferences that hash reference.  Another way to write it is %{$arg_ref}.  This makes the intent of the code a bit more clear, though more verbose.
To quote from perldata(1):
 Scalar values are always named with '$', even when referring
 to a scalar that is part of an array or a hash.  The '$'
 symbol works semantically like the English word "the" in
 that it indicates a single value is expected.

     $days               # the simple scalar value "days"
     $days[28]           # the 29th element of array @days
     $days{'Feb'}        # the 'Feb' value from hash %days
     $#days              # the last index of array @days

So your example would be:
     %$arg_ref           # hash dereferenced from the value "arg_ref"

my($arg_ref) = @_; grabs the first item in the function's argument stack and places it in a local variable called $arg_ref.  The caller is responsible for passing a hash reference.  A more canonical way to write that is:
my $arg_ref = shift;

To create a hash reference you could start with a hash:
some_sub(\%hash);

Or you can create it with an anonymous hash reference:
some_sub({pi => 3.14, C => 4}); # Pi is a gross approximation.

Comment: The $ sigil does not mean a scalar variable. It means a scalar *value*, as in $hash{key} and $array[$num]. In this case it's a scalar variable because it's a scalar value and there is no indexing chars after it.
Comment: Prototyping can be used to remove the reference-passing responsibility from the caller.
Comment: I don't think teaching prototyping the new Perl programmers is a good idea.  It was a big barrier coming from C and Pascal.  I needed to learn the true value of passing lists before prototypes made any sense to me.  It might be handy here, however.
Comment: I don't think I said $ indicated a variable of any sort.  But I went ahead and added quote from perldata that draws out the meaning of the $ sigil.
Comment: @chaos  Perl prototyping bad.  Avoid!  Flee!  Not only is it difficult to use and loaded with traps, but the user thinks they're passing a copy to a subroutine when they're really passing a reference which the routine might modify.
Answer: Instead of dereferencing the entire hash like that, you can grab individual items with
$arg_ref->{key}

Answer: A good brief introduction to references (creating them and using them) in Perl is perldoc perfeftut. You can also read it online (or get it as a pdf). (It talks more about references in complex data structures than in terms of passing in and out of subroutines, but the syntax is the same.)
Answer: my %hash = ( fred => 'wilma',
             barney => 'betty');
my $hashref = \%hash;
my $freds_wife = $hashref->{fred};
my %hash_copy = %$hash # or %{$hash} as noted above.

Soo, what's the point of the syntax flexibility?  Let's try this:
my %flintstones = ( fred => { wife => 'wilma',
                              kids => ['pebbles'],
                              pets => ['dino'],
                            }
                    barney => { # etc ... }
                  );

Actually for deep data structures like this it's often more convenient to start with a ref:
my $flintstones = { fred => { wife => 'Wilma',
                               kids => ['Pebbles'],
                               pets => ['Dino'],
                              },
                   };

OK, so fred gets a new pet, 'Velociraptor'
push @{$flintstones->{fred}->{pets}}, 'Velociraptor';

How many pets does Fred have?
scalar @ {flintstones->{fred}->{pets} }
Let's feed them ...
for my $pet ( @ {flintstones->{fred}->{pets} } ) {
    feed($pet)
}

and so on.  The curly-bracket soup can look a bit daunting at first, but it becomes quite easy to deal with them in the end, so long as you're consistent in the way that you deal with them.
Answer: Since it's somewhat clear this construct is being used to provide a hash reference as a list of named arguments to a sub it should also be noted that this
sub foo {
  my ($arg_ref) = @_;
  # do something with $arg_ref->{keys}
}

may be overkill as opposed to just unpacking @_
sub bar {
  my ($a, $b, $c) = @_;
  return $c / ( $a * $b );
}

Depending on how complex the argument list is.

Is %$var dereferencing a Perl hash?


Texture is uncentered

Question: So, I'm trying to do a very basic program in OpenGL. Everything went fine, had issues with texturing but now it's all solved.
But now, I have a little issue. The texture shows, but it isn't "centered". I tried changing the vertex positions, but nope, it doesn't work.
Here's an image showing what's happening:

Here's some code that might help:
My includes:
#include"GL/glew.h"
#include"GL/glut.h"
#include"GLFW/glfw3.h"
#ifdef _WIN32
#include <Windows.h>
#else
#include <unistd.h>
#endif
#include <iostream>
#include <fstream>
#include <vector>
#include <string>

#include <stdio.h>
#include "SOIL/SOIL.h"

Main code (i hid some code lines):
int image_width, image_height;
unsigned char* image = SOIL_load_image("face.png", &image_width, &image_height, NULL,
SOIL_LOAD_RGBA);

GLuint texture0;

glBindTexture(GL_TEXTURE_2D, texture0);
glGenTextures(1, &texture0);
glActiveTexture(GL_TEXTURE0);

glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_BORDER);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);

if (image)
{
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image_width, image_height, 0, GL_RGBA,
GL_UNSIGNED_BYTE, image);
}
else
{
cout << "ERROR::TEXTURE_LOADING_fAILED" << "\n";
}

//Draw first 2 vertices
glEnable(GL_TEXTURE_2D);

glBegin(GL_QUADS);
glColor3ub(255, 255, 255); //Start vert. color

glTexCoord2f(-.5f, .5f); glVertex2f(-.5, .5); //A
glTexCoord2f(.5f, .5f); glVertex2f(.5, .5); //B
glTexCoord2f(.5f, -.5f); glVertex2f(.5, -.5); //C
glTexCoord2f(-.5f, -.5f); glVertex2f(-.5, -.5); //D

glEnd();

SOIL_free_image_data(image);

glFlush();
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
//glutPostRedisplay();

What I want to do is center the texture to its own center. It's already on (0,0), but I can't manage to "re-center" the texture. Can anyone help me? I'd appreciate it, I'm very VERY new to OpenGL stuff.
Answer: The texture coordinates need to be in range [0.0, 1.0]:
glTexCoord2f(0.0f, 1.0f); glVertex2f(-.5, .5); //A
glTexCoord2f(1.0f, 1.0f); glVertex2f(.5, .5); //B
glTexCoord2f(1.0f, 0.0f); glVertex2f(.5, -.5); //C
glTexCoord2f(0.0f, 0.0f); glVertex2f(-.5, -.5); //D

(0, 0) is the bottom left and (1, 1) is the top right coordinate of the texture. You want to map the bottom left of the texture to the vertex coordinate (-0.5, -0.5) and the top right of the texture to the vertex coordinate (0.5, 0.5).
Comment: Thanks! That worked. I'll mark it as solution whenever i can after sleeping because there's a 12 minute delay.

Texture is uncentered


Does the stealth cruiser have innate stealth weapons capability?

Question: Does the stealth cruiser have innate stealth weapons capability or must you seek out the augmentation during your voyage?
Answer: No, no Stealth Weapons capability as standard
The Stealth Cruiser does not appear to have built in Stealth Weapons capability.
How I tested it
For the sake of testing I upgraded the stealth capability so I had a maximum duration, engaged an enemy, waited until my weapons were charged and then stealthed. Upon first impression it seemed as though Stealth Weapons capability was built in, as I was able to fire both weapons while cloaked without being pulled out of cloak.
However, upon further testing it appears that the duration of the cloak was affected quite significantly once weapons had been fired:

In this image, I activated my fully upgraded cloaking system the moment I heard the enemy fire at me. This was just enough time for all of my weapons to come online, so while the game was paused (and I was taking this screenshot), I targeted the enemy ship with my two lasers and then unpaused the game:

You can see the lasers firing on the screenshot, I only unpaused the game for a brief second before pausing again, and as you can see this halved the duration of cloak. It appears that for each weapon fired about 20% of the overall cloak duration is removed, so if I had fired my beam weapon as well I would have expected the remaining cloak time to be around 30% of its total duration.
Firing the same weapons in the same way with the Stealth Weapons augmentation completely negates this drain on the cloak duration, so I can only conclude that no - the Stealth Cruiser does not have innate Stealth Weapons capabilities.
Comment: With _any_ ship, firing while cloaked doesn't immediately cancel the cloak, instead it just makes the cloak end faster. Have you timed cloak-while-firing vs. cloak-without-firing?
Comment: Awesome work testing this.
Comment: Not only does it have `Stealth Weapons`, but it's a free, hidden slot. You can have three ship modifications in addition to the `Stealth Weapons`, and can never get rid of SW.
Comment: @rsegal but in exchange, you start with no shields and really should use one of those augmentation slots for shields at the first available opportunity
Comment: Sure, but that's the tradeoff. Strangely, stealth also dodges asteroids, or nobody would survive to buy shields.