Python : call function from another class in python

Question: Can anyont tell me how to call method from another class?
when i click on ok button then i call def insert(self): method.I am using code
def insert(self):
    #insert data after call add_expense() method
    RowsExpense().add_expense()

after insert data i call RowsExpense().add_expense().its calling because print('llllll') shows in console.But self.add_widget(r) not working because row not showing on screen.

demo.py
from kivy.app import App
from kivy.lang import Builder
from kivy.core.window import Window
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import BooleanProperty, ListProperty, StringProperty, ObjectProperty, NumericProperty
from kivy.uix.popup import Popup

Window.clearcolor = (0.5, 0.5, 0.5, 1)
Window.size = (500, 400)

class User(Popup):
    total_value = ObjectProperty(None)

    def __init__(self, **kwargs):
        super(User, self).__init__(**kwargs)

    def add_more(self):
        self.ids.rows.add_more()

    def add_more2(self):
        self.ids.rowsExpense.add_expense()

class ExtraPopup(Popup):
    mode = StringProperty("")

    def __init__(self, obj, **kwargs):
        super(ExtraPopup, self).__init__(**kwargs)

    def add_extra(self):
        self.ids.rowsExtra.add_row()

    def insert(self):
        #insert data after call add_expense() method
        RowsExpense().add_expense()

class RowExtra(BoxLayout):
    col_data = ListProperty(["?", "?", "?", "?", "?", "?", "?", "?"])
    button_text = StringProperty("")
    mode = StringProperty("")

    def __init__(self, **kwargs):
        super(RowExtra, self).__init__(**kwargs)
        self.col_data[0] = ''
        self.col_data[1] = ''
        self.col_data[2] = ''

class RowsExtra(BoxLayout):
    #orientation = "vertical"
    row_count = 0
    button_text = StringProperty("")
    textName = StringProperty("")

    def __init__(self, **kwargs):
        super(RowsExtra, self).__init__(**kwargs)

    def add_row(self):
        for x in range(0, 3):
            self.row_count += 1
            r = RowExtra(button_text=str(self.row_count))
            self.add_widget(r)

class Row(BoxLayout):
    col_data = ListProperty(["?", "?", "?", "?", "?"])
    name = ObjectProperty(None)
    button_text = StringProperty("")
    col_data3 = StringProperty("")
    col_data4 = StringProperty("")

    def __init__(self, **kwargs):
        super(Row, self).__init__(**kwargs)

    def add_seller_expenses(self):
        self.mode = "Add"
        popup = ExtraPopup(self)
        popup.ids.rowsExtra.textName = self.ids.name.text
        popup.ids.rowsExtra.add_row()
        popup.open()

class Rows(BoxLayout):
    row_count = 0

    def __init__(self, **kwargs):
        super(Rows, self).__init__(**kwargs)
        self.add_more()

    def add_more(self):
        self.row_count += 1
        self.add_widget(Row(button_text=str(self.row_count)))

class RowExpense(BoxLayout):
    col_data = ListProperty(["?", "?", "?"])
    button_text = StringProperty("")

    def __init__(self, **kwargs):
        super(RowExpense, self).__init__(**kwargs)
        self.col_data[0] = ' '

class RowsExpense(BoxLayout):
    row_count = 0

    def __init__(self, **kwargs):
        super(RowsExpense, self).__init__(**kwargs)

    def add_expense(self):
        print('llllll')
        for x in range(0, 3):
            self.row_count += 1
            r = RowExpense(button_text=str(self.row_count))
            self.add_widget(r)

class rv(BoxLayout):
    data_items = ListProperty([])
    mode = StringProperty("")

    def __init__(self, **kwargs):
        super(rv, self).__init__(**kwargs)

    def add(self):
        self.mode = "Add"
        popup = User()
        popup.open()

class MainMenu(BoxLayout):
    content_area = ObjectProperty()

    def display(self):
        self.rv = rv()
        self.content_area.add_widget(self.rv)

class demo(App):

    def build(self):
        return MainMenu()

if __name__ == '__main__':
    demo().run()

demo.kv
<Row>:
    size_hint_y: None
    height: self.minimum_height
    height: 40

    Button:
        text: root.button_text
        size_hint_x: None
        top: 200

    TextInput:
        id : name
        text: root.col_data3
        width: 300
    TextInput:
        id: number_input
        text: root.col_data4
        width: 300
        input_filter: 'int'

    Button:
        text: "Button"
        size_hint_x: None
        top: 200
        on_press: root.add_seller_expenses()

<Rows>:
    size_hint_y: None
    height: self.minimum_height
    orientation: "vertical"

<User>:
    id: user
    BoxLayout:
        orientation: "vertical"
        padding : 20, 5

        BoxLayout:
            orientation: "horizontal"
            #padding : 10, 10
            spacing: 10, 10
            size: 450, 40
            size_hint: None, None

            Label:
                size_hint_x: .2
                text: "Number"
                text_size: self.size
                valign: 'bottom'
                halign: 'center'

            Label:
                size_hint_x: .4
                text: "name"
                text_size: self.size
                valign: 'bottom'
                halign: 'center'

            Label:
                size_hint_x: .4
                text: "Value"
                text_size: self.size
                valign: 'bottom'
                halign: 'center'

        ScrollView:
            Rows:
                id: rows

        BoxLayout:
            orientation: "horizontal"
            size_hint_x: .2
            size_hint_y: .2

            Button:
                text: "+Add More"
                on_press: root.add_more()

        BoxLayout:
            orientation: "horizontal"
            size_hint: 1, 1

            BoxLayout:
                orientation: "vertical"
                padding: 10, 5
                size_hint: .5, 1

                BoxLayout:
                    orientation: "horizontal"
                    spacing: 10, 10
                    size: 600, 50
                    size_hint: 1, None

                    Label:
                        text: "SN"
                        text_size: self.size
                        size_hint_x: .3
                        halign: "center"

                ScrollView:
                    RowsExpense:
                        id: rowsExpense

                BoxLayout:
                    orientation: "horizontal"
                    size_hint_x: .2
                    size_hint_y: .2

                    Button:
                        text: "+Add More"
                        on_press: root.add_more2()

<rv>:
    BoxLayout:
        orientation: "vertical"

        Button:
            size_hint: .25, .03
            text: "+Add"
            on_press: root.add()

        GridLayout:
            size_hint: 1, None
            size_hint_y: None
            height: 25
            cols: 3

        BoxLayout:
            orientation: "vertical"

<ExtraPopup>:
    title: " Extra"
    title_size: 20
    title_font: "Verdana"
    size_hint: None, None
    size: 400, 400
    auto_dismiss: False

    BoxLayout:
        orientation: "vertical"
        padding : 10, 5
        spacing: 10, 10

        BoxLayout:
            orientation: "horizontal"
            spacing: 10, 10
            size: 550, 30
            size_hint: 1, None

            Label:
                size_hint_x: .3
                text: "SN"
                text_size: self.size
                valign: 'bottom'
                halign: 'center'

            Label:
                size_hint_x: .7
                text: "Name"
                text_size: self.size
                valign: 'bottom'
                halign: 'center'

        ScrollView:
            RowsExtra:
                id: rowsExtra

        BoxLayout:
            orientation: "horizontal"
            size_hint_x: .3
            size_hint: .15, .1

            Button:
                text: "+Add More"
                valign: 'bottom'
                on_press: root.add_extra()

        BoxLayout:
            orientation: "horizontal"
            padding : 10, 5
            spacing: 10, 10
            size_hint: .5, .2
            pos_hint: {'x': .25, 'y':.25}
            Button:
                text: 'Ok'
                id: ok_text
                on_release:
                    root.insert()
                    root.dismiss()

            Button:
                text: 'Cancel'
                #size_hint_x: .5
                on_release: root.dismiss()

<RowExtra>:
    size_hint_y: None
    height: self.minimum_height
    height: 30

    Button:
        text: root.button_text
        size_hint_x: .3
        #top: 200

    TextInput:
        text: root.col_data[1]
        size_hint_x: .7

<RowsExtra>:
    size_hint_y: None
    height: self.minimum_height
    orientation: "vertical"

<RowsExpense>:
    size_hint_y: None
    height: self.minimum_height
    orientation: "vertical"

<RowExpense>:
    size_hint_y: None
    height: self.minimum_height
    height: 30

    TextInput:
        text: root.col_data[0]
        multiline: False

<MenuButton@Button>:
    text_size: self.size
    valign: "middle"
    padding_x: 5
    size : (100, 40)
    size_hint : (None, None)
    background_color: 90 , 90, 90, 90
    background_normal: ''
    color: 0, 0.517, 0.705, 1
    border: (0, 10, 0, 0)

<MainMenu>:
    content_area: content_area

    BoxLayout:
        orientation: 'vertical'
        spacing : 10

        BoxLayout:
            canvas.before:
                Rectangle:
                    pos: self.pos
                    size: self.size

            size_hint_y: 2

            MenuButton:
                text: 'Menu'
                size : (50, 12)
                on_release: root.display()

        BoxLayout:
            id: content_area
            size_hint_y: 30

Answer: You're calling class method while You should call instance method instead.
You need to store reference to Your RowsExpense instance in Your root class and run Your method through that reference. Then You can either pass that reference to the class through which You want to run the method  as an argument in it's init function or use plain old:
App.get_running_app().root.whateverYouwanttodohere()


Java Multicast Socket doesn't receive anything on Windows

Question: I need to send and receive in multicast.
I posted the question on StackOverflow Forum for checking my code: https://stackoverflow.com/questions/50131973/java-multicast-socket-doesnt-receive-anything-on-windows
I tried my code on Ubuntu and it works perfectly.
Now I'm doing experiments on Windows 10.
I use multicast socket to send and receive DatagramPacket.
If the InetAddress of datagram is "126.96.36.199" for multicasting, it doesn't work.
Otherwise, when I use a LAN connected machine's IP, it works.
Receiver:
    MulticastSocket multiSocket = new MulticastSocket(3575);
    InetAddress groupMulticast = InetAddress.getByName( "188.8.131.52" );
    multiSocket.joinGroup(groupMulticast);
    DatagramPacket packetReceive = new DatagramPacket( bufReceive, bufReceive.length );
    try {
        multiSocket.receive( packetReceive );
    } catch (IOException e) { e.printStackTrace(); }

Sender:
    MulticastSocket multiSocket = new MulticastSocket(3575);
    InetAddress groupMulticast = InetAddress.getByName( "126.96.36.199" );
    multiSocket.joinGroup(groupMulticast);
    byte[] bufSend = new byte[255];

    DatagramPacket packetSend = new DatagramPacket( bufSend, bufSend.length,
                                    groupMulticast, 3575 );
    try {
        multiSocket.send(packetSend);
    } catch (IOException e) { e.printStackTrace(); }

This sender doens't work. But if I change this:
InetAddress groupMulticast = InetAddress.getByName( "188.8.131.52" );

with this:
InetAddress groupMulticast = InetAddress.getByName( "192.168.0.21" );

where 192.168.0.21 is IP address of receiver connected in LAN, it works.
Ho can I send in multicasting?
Answer: Try this code.
public class Server3 {

public static void main(String[] args) throws IOException {
    MulticastSocket multiSocket = new MulticastSocket(3575);
    InetAddress groupMulticast = InetAddress.getByName("220.127.116.11");
    multiSocket.setBroadcast(true);
    multiSocket.joinGroup(groupMulticast);

    while (true) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }
        System.out.println("Sending...");
        String msg = "Hai";
        byte[] bufSend = msg.getBytes();

        DatagramPacket packetSend = new DatagramPacket(bufSend, bufSend.length, groupMulticast, 3575);
        try {
            multiSocket.send(packetSend);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
}
public class Client3 {
public static void main(String[] args) throws IOException {
    MulticastSocket multiSocket = new MulticastSocket(3575);
    InetAddress groupMulticast = InetAddress.getByName("184.108.40.206");
    multiSocket.setBroadcast(true);
    multiSocket.joinGroup(groupMulticast);
    byte[] bufReceive = new byte[1024];
    while (true) {
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
        System.out.println("Receiving...");
        DatagramPacket packetReceive = new DatagramPacket(bufReceive, bufReceive.length);
        try {
            multiSocket.receive(packetReceive);
            System.out.println("msg...");
            System.out.println(new String(bufReceive));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
}

Comment: Welcome to Server Fault! Code should include a explanation of what you are changing or doing with it.


Is writing "System.AppContext" in code behind not supported in .net 4.5.1?

Question: I need long path support for my .net 4.5.1 WPF application.
This setting in App.config works (long paths are supported):
<runtime>
    <AppContextSwitchOverrides value="Switch.System.IO.UseLegacyPathHandling=false;Switch.System.IO.BlockLongPaths=false" />
</runtime>

So I tried to set in in code, but it does not change the behaviour:
public App()
{
    // returns correct type:
    Type type = Type.GetType("System.AppContext");
    if (type != null)
    {
        // returns correct switch:
        MethodInfo setSwitch = type.GetMethod("SetSwitch", BindingFlags.Public | BindingFlags.Static);
        setSwitch.Invoke(null, new object[] { "Switch.System.IO.UseLegacyPathHandling", false });
        setSwitch.Invoke(null, new object[] { "Switch.System.IO.BlockLongPaths", false });
    }
}

Is that "code behind setting" not supported in .net 4.5.1?
Answer:
Is that "code behind setting" not supported in .net 4.5.1?

No, it isn't. You should use AppContext.SetSwitch to set the switches programmatically but since this API was introduced in .NET Framework 4.6, the only officially supported way to set the switches on earlier versions is to use the App.config file.


relation between minimal polynomial and jordan normal form

Question: I just solved some exercises on minimal polynomials and i remember that there is a relation between the minimal polynomial and the jordan normal form.
But my question is the following : knowing the minimal polynomial of a given matrix $A$ what information can we get about the jordan normal form (without computing it).
Thanks in advance!
Comment: http://math.stackexchange.com/questions/82607/why-does-the-largest-jordan-block-determine-the-degree-for-that-factor-in-the-mi?rq=1  has some information. I'm not sure there's much more you can do.
Answer: The multiplicity of an eigenvalue in the minimal polynomial is the size of that eigenvalue's largest Jordan block.  See the "Complex matrices" topic in Wikipedia article "Jordan normal form."


Undefined method 'save' for nil Rails

Question: I'm completely new on Rails. I'm trying to learn it by building a forum following a video on youtube.
However, I'm stuck in a error and just have no idea how to solve it. I keep getting "undefined method 'save' for nil.
The code:
Controller
class PostsController < ApplicationController
def index
end

def new
  @post = Post.new
end

def create
  @post = Post.new[post_params]

  if @post.save
    flash[:success] = "Saved"
    redirect_to action: :show
  else
    flash[:error] = "There was a problem adding"
    render action: :new
  end
end

def post_params
  params[:post].permit(:title, :content)
end

new.html.haml
%h1 New post

= render 'form'

_form.html.haml
= simple_form_for @post do |f|
= f.input :title
= f.input :content
= f.submit

CreatePosts
class CreatePosts < ActiveRecord::Migration[5.1]
  def change
    create_table :posts do |t|
      t.string :title
      t.text :content

      t.timestamps
    end
  end
end

Does anybody know what is going wrong here?
Comment: `@post = Post.new[post_params]` should be `@post = Post.new(post_params)`
Answer: You are not using the new method correctly (read the doc).
Change this :
@post = Post.new[post_params]

To this :
@post = Post.new(post_params)

Comment: and change the typo at  strong params as well ^_^

Undefined method 'save' for nil Rails


About two ways to compute a special limit and what is incorrect?

Question: I have an question in compute the following limit:
$$
\lim_{n\to \infty} \frac{1}{n} +\frac{2}{n} +...+\frac{n}{n}
$$
I know that the answer is:
$$
\lim_{n\to \infty} \frac{1}{n} +\frac{2}{n} +...+\frac{n}{n}
=
\lim_{n\to \infty} \frac{\frac{n(n+1)}{2}}{n}
=
\infty
$$
but a way for compute this limit is:
$$
\lim_{n\to \infty} \frac{1}{n} +\frac{2}{n} +...+\frac{n}{n}
=
\lim_{n\to \infty}\frac{1}{n} +
\lim_{n\to \infty}\frac{2}{n} +
\ldots +
\lim_{n\to \infty}\frac{n}{n}
=
\lim_{n\to \infty} 0+0+\ldots +1
=1
$$
what second way is not true?
Comment: Try applying your logic to:$$\lim_{n\to\infty}\left(\frac1n+\frac1n+\dotsb+\frac1n\right)$$where there are $n$ terms. On the one hand, you'd think this is equal to $0+0+\dotsb+0=0$. On the other hand, you know that it's equal to $1$ _for every value of $n$,_ so the limit must be $1$!
Comment: @amirbahadory I gave you a "+1 vote" for your question and added it to my favorites!
Answer: You can't distribute the limit over a number of summands that depends on $n$, as shown. The first solution is correct. You have
$${1\over n }\sum_{k=1}^n k = {n+1\over 2}$$
Answer: From my point, your method has some question. As is well known, if we add finte terms in the sense of limit, then you can plus every term after you calculate every limit, but if there are infinite terms, you can not do like this.
Answer: You tried something like
$$
\lim_{n\to\infty} \sum_{k=1}^n \frac{k}{n} =
\lim_{N\to\infty} \sum_{k=1}^N \lim_{n\to\infty} \frac{k}{n}
$$
and tried to synchronize $N$ and $n$ somehow.
Answer: In the OP, the conclusion that the limit
$$\lim_{n\to \infty}\left(\frac1 n+\frac2 n+\cdots+\frac{n}{n}\right)=0+0+\cdots +1=1$$
is incorrect.
We can see this more clearly by writing
$$\frac1 n+\frac2 n+\frac3n+\cdots+\frac{n-3}{n}+\frac{n-2}{n}+\frac{n-1}{n}+\frac{n}{n}$$
Now, we see that all of the last terms after the "dots" approach $1$ as $n\to \infty$.
So, in order to approach this problem correctly, we need to write all of the terms as
$$\frac1 n+\frac2 n+\frac3n+\frac4n+\cdots+\frac{n-3}{n}+\frac{n-2}{n}+\frac{n-1}{n}+\frac{n}{n}=\frac1n\sum_{k=1}^n\,k=\frac1n \frac{n(n+1)}{2}=\frac{(n+1)}{2}$$
and now clearly the limit is $\infty$.


Transactions and form api

Question: Is it possible to use FAPI and transactions?
I need to implement a validation that makes a query to check something and on the submit I need to update the database.
I thought to open a transaction on the validation callback and set it on the $form_state and then commit my transaction on the submit handler. I didn't liked this solution but was the best that I could think.
How do you solve this kind of things on drupal? What do you think about my solution?
Answer: Can you use FAPI with transactions: Yes.
But you can't or rather shouldn't use it the way you describe. Transactions only take effect when you commit them, so there really is no point in starting the transaction in the validation. Also what happens if you have a validation error, you won't commit the transaction. I believe that starting a transaction will effect other incoming queries as well.
Transactions are only good if you want to do multiple queries at once, and do all or nothing. Like insert data in main table and revision table and then update the revision number in main table.
What are you trying to do that makes you think that you should make transaction in such a way?
Comment: I need to check if someone has already used a code on the validation handler and then on the submit handler I need to mark the code as used. How you you do that using FAPI?
Comment: @LuizGuilherme There is a huge difference between using code that interacts with each other on the validation and submit handler and opening a SQL transaction which effectively blocks all incoming queries until the transaction is committed. You should use $form_state to send info from validate to submit handler.

Transactions and form api


String splitting and wrapping

Question: Suppose I am given this string-
String A_Old[]="010.011.100.000.111";

On every occurrence of "000" I am expected to break the string and wrap the end towards the front of the string. The resultant should look like this-
String A_New[]="111.010.011.100";

Any help on how to tackle this problem would be appreciated.
Also, what do I do when there are multiple occurrences of "000"?
String A_Old[]="010.011.100.000.111.001.011.000.101.110";

should convert to :
String A_New[]="101.110.111.001.011.010.011.100";

Code in java or c++ is understood and appreciated.

EDIT
This was what I thought would work-
String b[]=A_Old.split(".000.",2);    //should split the string in 2 parts.
A_New=b[1].concat(b[0]);              // concatenation with a loss of a period

I was told to avoid the loss of the period as well as not using dummy variables. Both of which fails here. Any idea on how to tackle this?
Comment: I have no idea how to go about solving this. I was told not to use dummy variables.Moreover, the periods are causing me a lot of trouble.
Comment: For Java (below 8), you're going to want to use some combination of the `split` method of `String`, the `asList` method of `Arrays`, the `reverse` method of `Collections`, the `toArray` method of `Collection` and the `join` method of Apache commons `StringUtils`, in that order.  I recommend researching the Javadocs of each of these separately.
Comment: An answer has been accepted that doesn't provide a recursive solution, or even a solution devoid of intermediate variables.  Has that requirement now been relaxed?  There has been an updated Perl solution which provides both, leaving translation to other powerful languages such as Java an exercise for the reader. ;)
Comment: Thanks @DavidO but as you rightly said, I've relaxed the recursive solution part. You wouldn't want to deprive me of the opportunity to learn by myself would you ? :) have a good day
Answer: "No dummy variables" sounds like a recursive solution is sought.  Is this a Scheme class?
Here's a Perl solution. C++11 is sufficiently high-level to provide most of the facilities demonstrated here:
my @tests = (
    '010.011.100.000.111',
    '010.011.100.000.111.001.011.000.101.110'
);

foreach ( @tests ) {
  print "$_ => ", rotate($_), "\n";  # Call our rotate routine, and show results.
}

sub rotate {
  # Split the string into components, reverse their order, join them with '.'
  return join('.', reverse split /(?:^|\.)000(?:\.|$)/, shift);
}

No dummy variables.  In fact, no explicit variables either.
Here's how the split regex works:
(?:^|\.) # Match either start of string, or a dot.
000      # Match three zeros.
(?:\.|$) # Match either a dot, or the end of string.

This permits the 000 to appear anywhere in the string (including beginning or end).  If it appears at the beginning, there will not need to be a leading dot.  If it appears at the end, a trailing dot will not be required.  Anywhere else, dots must surround the 000.
Update:
Here is a recursive solution using Perl.  From what I've read of the Java solutions (I'm not a Java guy), it seems like translation should be straightforward for someone with some Java background.
my @tests = (
    '010.011.100.000.111',
    '010.011.100.000.111.001.011.000.101.110'
);

foreach ( @tests ) {
  print "($_)  =>  (", rotate($_), ")\n";
}

sub rotate {
  my( $ok, $rest ) = split /(?:^|\.)000(?:\.|$)/, $_[0], 2;
  return $ok unless defined $rest;
  return join( '.', rotate($rest), $ok);
}

Update2:
And here's another Perl solution that eliminates any explicit variables, using only subroutine parameters:
my @tests = (
    '010.011.100.000.111',
    '010.011.100.000.111.001.011.000.101.110'
);

foreach ( @tests ) {
  print "($_)  =>  (", rotate($_), ")\n";
}

sub rotate {
  return sub {
    return $_[0] unless defined $_[1];
    return join( '.', rotate($_[1]), $_[0]);
  }->( split /(?:^|\.)000(?:\.|$)/, shift, 2 );
}

I have no idea how one would translate that Java. I suspect translation would become a little more difficult, though I'm confident there must exist a semantically equivalent C++11 solution.
Comment: Thank you, I found this helpful to understand the split regex workings.However, I am not familiar with PERL so, I am unsure whether it works the same way in java.
Comment: At least I know it proved helpful at some level, though aside from the Java or C++ requirement, it does provide a recursive solution that uses no intermediate variables, and that works even if '000' appears at the beginning or end of the string.  If I ever find another 30 minutes I may translate the final solution to C++11 just for fun.  Don't hold your breath though. ;)
Answer: By Using Split method and reverse forloop in java
public static void main(String[] args) {
 //insert code here

     String A_Old="010.011.100.000.111.001.011.000.101.110";
     String A_new ="";
     String newe[]=A_Old.split("\\.000");

     for(int i=newe.length-1;i>=0;i--){
         A_new+=newe[i];

     }
     System.out.print(A_new.replaceFirst("\\.", ""));
 }

Comment: Still needs to make the 'dot' character optional in the '`.000.`' sequence, in case it appears at the beginning or end of the string.
Comment: Yes, and in fact, (I could be wrong but...) Java's split takes a regex, so the dot is going to be treated as a metacharacter that matches anything, not as a literal dot.
Comment: Yes, this is exactly what I've tried to imitate.However, is there a recursive function that I could probably use?
Comment: @DavidO Well, I wasn't going to request for a recursive solution.I was looking forward to solve that part myself.Can you please cut the hostility? I have learnt where I was going wrong before,apparently there is something about the regex int I missed before
Answer: To rotate the list, you wanna split and then concatenate in the order you want.  You probably want to check for blanks/if it's the last element.
public static void main(String[] args)
{
    String inString = "010.011.100.000.111";
    String outString = "";
    String[] arr = inString.split("\\.000\\.");
    outString = arr[0];
    for(int i = 1; i < arr.length; i++)
    {
      outString = outString + arr[i];
    }

    System.out.println(outString);
}

Comment: Can you please tell me why you used " split("\\.000\\.") "
Comment: Java interprets the Split string as RegEx which considers the . character as matching ANY single character.  To match only a literal . you have to escape it hence \.  But in Java strings \ is an escape character so you have to escape it hence \\.
Answer: I tried it in java:
public static String convert(String in) {
    String[] strs = in.split("\\.*000\\.*");
    StringBuilder sb = new StringBuilder();
    for (int i = strs.length - 1; i >= 0; --i) {
        sb.append(strs[i]);
        if (i > 0 && strs[i - 1].length() > 0) {
            sb.append(".");
        }
    }
    return sb.toString();
}

public static void main(String[] args) {
    System.out.println(convert("010.011.100.000.111"));
    System.out.println(convert("010.011.100.000.111.001.011.000.101.110"));
    System.out.println(convert("010.011.100.111"));
    System.out.println(convert("000.010.011.100.111"));
    System.out.println(convert("010.011.100.111.000"));
    System.out.println(convert("000.010.011.100.111.000"));
}

Output:
111.010.011.100
101.110.111.001.011.010.011.100
010.011.100.111
010.011.100.111
010.011.100.111
010.011.100.111

Comment: This was helpful. Could you please explain why you did this?
split("\\.*000\\.*");
Comment: It's a regexp, which `\\.*` means `.` can appear zero or one time, so it can split string by `000` or `000.` or `.000` or `.000.`.

String splitting and wrapping


AIC, likelihood, loglikelihood confusion

Question: AIC values (from a fitted model, for example) are positive. So are the likelihood values. Are the log-likelihood values positive or negative? Here, in Wikipedia page concerning likelihood ratio test the log-likelihood values are negative and the less negative value indicates better fit.
But in this page, there is -(log-likelihood) (meaning negative of the log-likelihood) and it says that more negative value indicates better fit. In R the logLik-function from a model gives negative values, but if I have only the likelihood and I want a log-likelihood from it, I have to take negative of the logarithm???
So my question is fairly simple, when comparing those values (AIC, likelihood, logarithmic likelihood) from 2 different models, which (of which kind, more or less negative) value indicates better model?
Here is also some statistic as an example, could some one "translate" this info as words for me =) (I am using msts and tbats from forecast-function)
> fit1$likelihood
   [1] 90871.47
> fit2$likelihood
[1] 90785.92
> fit1$AIC
[1] 90909.47
> fit2$AIC
[1] 90839.92
# AIC from likelihood, par1 refers to number of fitted parameters
> 2*par1-2*log(fit1$likelihood)
[1] -14.8344
> 2*par2-2*log(fit2$likelihood) # AIC from likelihood
[1] -10.83252

So why I wont get the same AIC values when calculating "by hand"? Which one are the correct ones?
Comment: I think the confusion may be due to thinking of the log-likelihood when you are really looking at the log of the likelihood ratio (likelihood for model1/likelihood for model2).  So depending on which is the better model the likelihood ratio can be >  1 or < 1.hence the log-likelihood ratio can be .>  0 or < 0 respectively.
Comment: [AIC can be negative](http://stats.stackexchange.com/questions/84076/negative-values-for-aic-in-general-mixed-model).
Comment: The smallest AIC is the best.
Comment: okay, I didn't know that. But still, is bigger AIC value then indicating better model or how can I compare the values?
Comment: Ah, that explains a lot
Comment: I think you need to explain your example in more detail.
Comment: Please refrain from adding more questions to your initial questions. Also, please add more details, as now you're asking about implementation details and it's completely unclear from your example where to gather this information. See my edited answer.
Comment: You shouldn't change your question like that. Rather, create new questions. Now the answer makes no sense given the text of your question.
Comment: @Finebug Your first comment above told the OP not to add to more questions to the initial question.  So he changed the question and made things worse.  He should have done what your later comment said. Got to feel bad for novices.
Comment: I have asked new question know. I am sorry that I dont know all the manners considering writing here (yet..). Maybe I get an answer if everyone is not already too irritated on me.
Answer: AIC will be negative whenever $k<\ln(L)$ (see this question and answers Negative values for AIC in General Mixed Model). Also keep in mind the log-likelihood can be positive, since the likelihood function is usually a probability density, i.e. it's always positive and can exceed $1$.
The interpretation, when comparing models, is the same though. The smallest AIC provides the "best" model, in the sense that it tends towards models with small $k$ and large $\ln{(L)}$.
Regarding likelihood, the higher the "better". Also, as log-likelihood is a monotonic transformation of likelihood, the same applies. This makes sense, since we want to minimize $\text {AIC}$:
$$\text {AIC} = 2k -2\ln(L)$$

Regarding your example in R, I'm pretty sure fit1$likelihood and fit2$likelihood are actually two times the negative log-likelihoods. The reason is simple:
fit1$likelihood - fit1$AIC
#[1] -38
fit2$likelihood - fit2$AIC
#[1] -54

If the AIC calculation is right, this means fit1 has 19 parameters and fit2 has 27 parameters.
Comment: A minor point, the likelihood is always positive.
Comment: @MichaelChernick True, will state explicitly.
Comment: I added an example to my question, but thanks, this was also helpful


Sending formatted text with UCMA 2.0

Question: Has anyone been successful in sending formatted text over an Instant Message flow using the UCMA 2.0 sdk?
It doesn't seem to be very well documented on MSDN.  Are there any examples out there?  Any books that talk about this?
Answer: Ran into this issue myself earlier today on a project at work. I don't have my code accessible to me at the moment, but it's essentially capable by doing the following...
<code>MimePartContentDescription text;
MimePartContentDescription html;
MimePartContentDescription package;

text = new MimePartContentDescription(
    new ContentType("text/plain"),
    Encoding.UTF8.GetBytes(message_text) );

html = new MimePartContentDescription(
    new ContentType("text/html"),
    Encoding.UTF8.GetBytes(message_html) );

package = new MimePartContentDescription(
    new ContentType("multipart/alternative"), null
);

package.Add(html);
package.Add(text);

// Call BeginSendMessage ... SendMessageCompleted is async callback.
imFlow.BeginSendMessage(package.ContentType, package.GetBody, SendMessageCompleted, imFlow)
</code>
This method wraps two versions of the message into a single 'package' (if you will) that will degrade gracefully, providing the plain text version to clients that cannot handle the HTML, or will provide the HTML if the client supports it.
Credit goes to 'mdip' for posting the above code solution...
http://social.msdn.microsoft.com/Forums/en/ucmanagedsdk/thread/c532bbb9-f593-4443-85af-4e0708b8532c
Comment: This does not work for me.  Using UCMA 3.0 the mobile platform's (android) client sees a 'toaster' message but no actual message content.  The Lync Windows client does receive the HTML message as intended.  I've tried posting to that MSDN forum but always get some BS message about technical trouble.  Starting to loose patience with this SDK.
Comment: Also, it should be package.GetBody().  It is a method.
Answer: My understanding is that message prompts are simply strings.  If you want to add formatting to a string, a suggestion could be to use common html formatting in the prompt then pump the prompt received into an HTML aware control.

Sending formatted text with UCMA 2.0


Migrating an iOS application using Cocoapods 1.0.1 from Swift 2.2 to 3.0

Question: I'm currently upgrading an iOS app from Swift 2.2 to 3.0.  I have pointed all of my pod dependencies to their Swift 3 versions and have migrated my code.  However, when I run pod install and try to open my Workspace, Xcode still wants me to convert the "Pods" project to the latest Swift syntax:

The project "Pods" has targets that contain source code developed with an earlier version of Swift.

But I've already upgraded my dependencies to their Swift 3.0 versions.  What gives?
(This is a canonical Q&A pair to help future users who encounter this issue)
Answer: I had this issue with Cocoapods 1.0.1 where I needed to manually specify the SWIFT_VERSION of the installed targets to be 3.0:
post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['SWIFT_VERSION'] = '3.0'
    end
  end
end

My complete Podfile (for a test/development pod):
source 'https://github.com/CocoaPods/Specs.git'

use_frameworks!

target 'MyApp' do
  pod "MyPod", :path => "../"
end

target 'MyApp_Tests' do
  pod "MyPod", :path => "../"
end

post_install do |installer|
  installer.pods_project.targets.each do |target|
    target.build_configurations.each do |config|
      config.build_settings['SWIFT_VERSION'] = '3.0'
    end
  end
end

Issue #5521 - Compiler Version for Xcode 8 helped find this workaround.
Comment: @JonShier do I have to subscribe to a specific beta channel to get release candidate versions?  I didn't see that with a normal "`pod update`.
Answer: I suggest using their release candidate version
sudo gem install cocoapods --pre

Then do a pod install again
Comment: Right, but if you're on a team that is not supporting pre-release and release candidates versions of Cocoapods (and are stuck on 1.0.1), this isn't a viable solution.
Comment: Use Swift Package Manager instead?


Reordenação de dicionário, trocar valores por chaves

Question: Eu tenho o seguinte dicionário:
tests_dict = {'test 1': ['Manuel', 'Mariana', 'Filipa'], 'test 2': ['Manuel', 'Filipa', 'Mariana'], 'test 3': ['Mariana', 'Manuel', 'Filipa']}

O que preciso, é que chaves do novo dicionário sejam os nomes das pessoas, com o test feito e o lugar (indice) onde o nome respetivo está na lista do dicionário atual, formato desejado:
peps_dict = {'Manuel': {'test 1': 1, 'test 2': 1, 'test 3': 2}, 'Mariana': {'test 1': 2, 'test 2': 3, 'test 3': 1}, 'Filipa': {'test 1': 3, 'test 2': 2, 'test 3': 3}}

Como se vê, o Manuel no test 1 ficou em primeiro no test 2 também ficou em primeiro e no test 3 ficou em segundo, estas posições têm como base o indice das listas no dicionário original, e somar 1, porque é um sistema de rank e não pode haver abaixo do primeiro lugar (0 não faz sentido)
Comment: Use ĩndices começando em 0. Se a palavra está na primeira posição, seu indice deve ser "0" e não "1".
Comment: Sim é verdade, isto é um sistema de rank é com base no indice mas o 0 equivale ao primeiro lugar, tal como coloquei no formato desejado. Vou fixar isso, desculpe o mau entendido
Comment: @jsbueno, também reparei nisso, mas segui-me pelo formato desejado, porque achei também que era isso que fazia sentido neste contexto e pela explicação do AP, "... Manuel no test 1 ficou em primeiro..."
Comment: @Miguel - claro, você tem que responder o que foi perguntado. Mas vale a pena comentar na resposta, qual a melhor forma de deixar os índices.
Comment: Concordo @jsbueno, claro que sim, quanto mais claro melhor
Answer: Então temos:
tests_dict = {'test 1': ['Manuel', 'Mariana', 'Filipa'], 'test 2': ['Manuel', 'Filipa', 'Mariana'], 'test 3': ['Mariana', 'Manuel', 'Filipa']}

Pode fazer assim:
1. Esta primeira maneira é mais didática, acho que assim percebe a lógica que está por de trás disto:
peps_dict = {}
for test in tests_dict:
    for indx, name in enumerate(tests_dict[test], 1): # vamos percorrer os nomes e respetivo indice em cada lista, começando em 1
        if name not in peps_dict: # se o nome ainda nao estiver presente como chave no nosso novo dionario
            peps_dict[name] = {} # vamos declara-lo como um dicionario tambem
        peps_dict[name][test] = indx # ex: peps_dict['Manuel']['test 1'] = 1, {'Manuel': {'test 1': 1}}

DEMONSTRAÇÂO
2. Nesta maneira vamos importar defaultdict, que neste caso permite que possamos excluir a verificação if name not in peps_dict, desta maneira não há KeyError no nosso novo dicionário, e cada chave (nome) por default definimos que seja um dicionário também:
from collections import defaultdict

peps_dict = defaultdict(dict)
for test in tests_dict:
    for indx, name in enumerate(tests_dict[test], 1):
        peps_dict[name][test] = indx

DEMONSTRAÇÂO
Uma alternativa, NESTE caso, ao defaultdict é usar setdefault (Graças ao @JJoao que me lembrou desta em comentário), e assim escusa também de fazer o import, este método é aplicável só a dicionários:
peps_dict = {}
for test in tests_dict:
    for indx, name in enumerate(tests_dict[test], 1):
        peps_dict.setdefault(name,{})[test] = indx

DEMONSTRAÇÃo
3. Esta ultima fiz mais pelo desafio, a lógica muda um pouco em relação à primeira. Vamos percorrer todos os nomes, juntamos todos os nomes numa só lista ((name for listN in tests_dict.values() for name in listN)), generator neste caso, e adicionamos cada n como sendo uma chave do nosso dicionário, e depois por via de dict compreension populamos-los com os valores correspondentes ({test: tests_dict[test].index(n) + 1}, vamos buscar o indice que o nome tem na lista original e somamos 1)
peps_dict = {}
names = (name for listN in tests_dict.values() for name in listN)
for n in names:
    peps_dict[n] = {test: tests_dict[test].index(n) + 1 for test in tests_dict if n in tests_dict[test]}

DEMONSTRAÇÃO
Esta ultima pode ser reduzida para:
names = (name for listN in tests_dict.values() for name in listN)
peps_dict = {n: {test: tests_dict[test].index(n) + 1 for test in tests_dict if n in tests_dict[test]} for n in names}

DEMOSTRAÇÃO
Output (print(peps_dict)) para os casos acima:

{'Manuel': {'test 1': 1, 'test 2': 1, 'test 3': 2}, 'Filipa': {'test 1': 3, 'test 2': 2, 'test 3': 3}, 'Mariana': {'test 1': 2, 'test 2': 3, 'test 3': 1}}

PS: Todo este  exercício parte do presuposto que não existem nomes iguais em cada lista, caso existam dois "Manuel" numa lista o ultimo a ser percorrido vai-se sobrepôr ao primeiro, não podem haver chaves iguais
Comment: Obrigado @JJoao, acrescentei essa alternativa na resposta
Comment: cool! sugestão na primeira substituir o if por `peps_dict.setdefault(name,{})
`
Comment: obrigado eu: nunca me tinha lembrado de `setdefault(name,{})[...]=...`
Comment: hehe (: , @JJoao , é mais curto assim


Progress Bar to prevent repeated WebForm Submissions?

Question: I'm getting duplicate webform submissions from what I call "Happy Clickers". I would like to implement a progress bar when someone submits a webform to prevent them from clicking multiple times. I tried the pgbar module, but it's not the solution that I am looking for.
Can anyone recommend a Drupal module to accomplish this? I'm using Drupal 7.
Thanks-in-Advance,
John
Answer: If you just want to limit Happy Clickers, in the webform go to Form settings and there are options for Total submissions limit & Per user submission limit. I would suggest changing the Per user submission limit to once every minute.
Comment: But does that stop them from click,click,click they just keep hitting the Submit repeatably. I need to disable any further clicks and display a progress bar until the submission is complete.
Comment: AFAIK that will require a JavaScript solution to disable the submit button once pressed see http://stackoverflow.com/questions/2323948/disabling-the-button-after-once-click
Answer: Used the Hide_Submit module to hide the submit button while the webform is being processed.
Problem solved!


how to give Azure Service Principal the same rights as my own user?

Question: I'm researching Azure and wanted to use a Service Principal when logging in through Azure CLI instead of authenticating through the web login method. I created a Service Principal with az ad sp create-for-rbac with the scope on the root of my subscription and role 'Owner'. I can succesfully login using the Service Principal but when I try to do az ad sp list, I get the error that I don't have enough privileges:
azure.graphrbac.models.graph_error.GraphErrorException: Insufficient privileges to complete the operation.
When I look at the Access control (IAM) tab in my subscription blade in the portal, I can see the Service Principal is Owner, and my own account is both Owner and Service administrator.
Is there a way to give the Service Principal exactly the same rights as my own account has?
Answer: Apparently giving an SP the 'Owner' role is not enough. You have the give it the 'Directory Readers' role. This is not possible using the Azure CLI or Portal though. You have to use the Azure AD Graph API, easiest way to do this is using https://graphexplorer.azurewebsites.net/.
Second caveat is, you can't use the graphexplorer site using your own Azure account (in my case I had a simple personal Azure setup with only myself as admin), but you have to create a user in your Azure AD. I gave it the Global Administrator role just to be sure, I'm not certain what the minimum role would be to be able to use the Graph API.
Now, the steps to add give the SP the Directory Readers role are a bit long to explain here, I found them here: https://lnx.azurewebsites.net/directory-roles-for-azure-ad-service-principal/
Not sure why this needs to be so convoluted and why this is not to be found in the documentation.
Answer: If your sp has Owner role, the command az ad sp list could list your sps.
I suggest you could close your current shell and  re-open a new shell, using following command to login your subscription.
az login --service-principal -u <client id> -p <client secret> --tenant <tenant id>

Comment: If possible, I suggest you could test it on Azure Cloud Shell.
Comment: on cloud shell az login is disabled cause it automatically authenticates. I already login the way you propose, but still, it seems I have hardly any rights.
Comment: @NicolasMommaerts Sorry for the later reply. Do you check your sp role on Azure Portal? Like this https://imgur.com/a/ohm4d
Comment: @NicolasMommaerts Also, what is your Azure CLi version? `az -v`. The latest version is 2.0.23. If you don't use the latest version, I suggest you could update it. `sudo apt-get update && sudo apt-get upgrade`. See this [document](https://docs.microsoft.com/en-us/cli/azure/install-azure-cli?view=azure-cli-latest#update-the-cli).
Comment: np, and happy new year! I was already using az cli 2.0.23. The IAM tab in my subscription shows the sp as Owner, I had also tried giving it the Security Admin and User Access Administrator role, but that didn't help either. It seems I can do about anything with the sp, except for sp related stuff. I can't create another sp with my sp for example, which makes it hard to setup an AKS cluster in an automated way.
Comment: @NicolasMommaerts It is very strange. I am sure if your sp has owner role. you could create aks cluster. If possible, could you create a new sp? Another question the account your login Azure Portal has owner role? The account has permission to create a sp?
Comment: Your user which use login Portal has `Global Administrator` permission? Like this https://imgur.com/a/9Gb32 ?
Comment: I already recreated the sp a couple of times :) First with az ad sp create, later with az ad sp create-for-rbac. My own portal user is global admin yes, like in the image. When I try to create an sp, using the first sp, I get the following error: https://imgur.com/a/Hi94Y In AAD I have the option 'Users can register applications' enabled (already was by default).
Comment: @NicolasMommaerts It is like a permission issue. Could you share your steps to create this sp.
Comment: @NicolasMommaerts I suggest you could create this sp on Azure Portal and give it Owner role. See this link https://docs.microsoft.com/en-us/azure/azure-resource-manager/resource-group-create-service-principal-portal
Comment: I created a new sp on the Azure Portal according to the link you gave me, exactly the same problem when doing az ad sp list...
Comment: I solved it, will add the solution as an answer. You were right, it were permissions missing (obviously), but it is not so easy to add them.


How to execute a bat file inside exe? (exe created using WinRAR sfx)

Question: I want to create an exe file which includes mysql.msi and java.zip. I have written vbscript to install mysql and extract java file in C: drive. It works fine.
Now my problem is:
Convert the source folder as exe by using WinRAR sfx option.
How can I execute the vbscript or bat file (for executing vbscript) when I click the created exe?
Has anybody a solution?
Answer: SFX commands: Setup i.e., Setup = <program>
SFX will try to execute  after successful extraction. The folder containing extracted files is set as the current before executing . If a program name contains spaces, it must be enclosed in quotes.
Example
Setup = setup.exe
Comment: follow this link : http://www.jackmccarthy.com/malware/WinRAR_Archive_Creation.htm
Comment: does this work for non-executable stuff? e.g. will Setup=home.html open the file in default browser?
Comment: @tumchaaditya Right now, I don't have access to windows machine(I'm on my Linux machine), why don't you try it yourself .. sorry for being not so helpful .. Have a Good day!
Comment: @tumchaaditya For getting opened a file not being an executable by the application registered as default application for the file according to file extension create a batch file with first line being `start "" "File To Open"` and second line being `del "%~f0"` and add this batch file to the archive and specify this batch file as executable to run after extraction. The batch file opens the file in default application (browser for *.htm) using command __start__ and then deletes itself.


Binary Tree in Java

Question: I am trying to code up my own binary tree. Though I could find many examples for a binary search tree, I decided to write this myself.
So far, I've come upto this:
public class bTree {
bnode root=null;

void add(int val){
    bnode newnode= new bnode(val);
    bnode curr = this.root;
    bnode parent = null;

    if(this.root == null){
        this.root = newnode;
        System.out.println("Inserted at root \t"+newnode.value);
    }
    else{
            while( curr != null){
            System.out.println("Current Left and Right\t"+curr.left+"\t"+curr.right);

            if(curr.left == null){
                curr =  curr.left;
                curr = newnode;
                System.out.println("Inserted Left\t" +newnode.value);
                return;
            }
            if(curr.right ==  null){
                curr =  curr.right;
                curr = newnode;
                System.out.println("Inserted Right\t" +newnode.value);
                return;
            }
        }
    }
}

When I try to add the values to the binary tree, only the root is able to add the values. I am slowly trying to write the rest of the code where it finds the left child to be full and backtracks and all the cases. My question is why is it not even adding the next value to the left most child (in the second call to it). I'd really appreciate it if you don't give me the code, I want to learn.
Answer: In your statements here:
        if(curr.left == null){
            curr =  curr.left;
            curr = newnode;
            ...
        }

When you make the assignment "curr = curr.left", "curr" gets assigned null and is no longer referencing anything in the tree. So that the tree will reference it, you'll need assign the left link of "curr" to the new node
        if(curr.left == null){
            curr.left = newnode;
            ...
        }

Here's a picture showing the difference between the two:
Answer:
Why is it not even adding the next value to the left most child in the second call to it?

Because this do not assign curr.left to newnode:
curr = curr.left;
curr = newnode;

Fix:
curr = curr.left = newnode;

Note that there are still other bugs in your code. You'll find them out with more calls.
Answer: because when you enter you else {} curr is always != null (because curr=root and root!=null), so the loop never executes
Comment: Alright. but I don't want it to run into an infi loop. So how else could I stop it?
Comment: the easiest solution is to use recursion instead. if you look around at almost any other tree impl you'll see recursion

Binary Tree in Java


Deletando imagem local do produto Laravel

Question: Bom tenho um produto e tenho uma imagem sendo gravada localmente.
Preciso que no backend quando o produto for deletado a imagem local seja deletada.
Quando faço o delete apaga os dados do banco apaga as informações da imagem no banco, porém não apaga a imagem local.
Qual seria o melhor jeito de fazer?
A minha rota :
Route::get('/{id}/destroy',['as'=>'products.destroy', 'uses'=>'AdminProductsController@destroy']);

A minha função para deletar o produto:
public function destroy($id)
{
    $this->productModel->find($id)->delete();

    return redirect()->route('products');
}

Função para remover imagem na view de imagens
 public function destroyImage(ProductImage $productImage, $id)
{
    $image = $productImage->find($id);

    if(file_exists(public_path() .'/uploads/'.$image->id.'.'.$image->extension)) {

        Storage::disk('public_local')->delete($image->id . '.' . $image->extension);
    }

    $product = $image->product;
    $image->delete();

    return redirect()->route('products.images', ['id'=>$product->id]);

}

Comment: A imagem local seria na maquina no cliente?
Comment: No servidor local
Answer: Ao deletar o produto, seu método destroy precisa também deletar o arquivo criado.
Você pode fazer isso diretamente no método:
public function destroy($id)
{
    $disk = Storage::disk('local');

    $this->productModel->find($id);
    $disk->delete($this->productModel->filePath);

    $this->productModel->delete();

    return redirect()->route('products');
}

Uma forma mais elegante seria usar o event deleting() do Eloquent:
No método boot() do seu app\Providers\AppProvider.php insira:
public function boot()
{
    \Namespace\Para\Product::deleting(function ($product) {
         Storage::disk('local')->delete($product->filePath);

         return true;
    });
}

PS.: Estou assumindo que você está armazenando o nome do arquivo no banco ($product->filePath)
Comment: ErrorException in Local.php line 200:
unlink(C:\xampp\htdocs\projeto\public\uploads\): Permission denied , procurei mas n consegui resolver esse erro de permissão... alguma dica?
Comment: Já definiu as permissões na pasta?
Comment: dei permissão de tudo para 'todos'
Comment: Como fica um `dd($product->filePath)` ? Aparece o caminho completo para o arquivo?
Comment: retornou null.. editei o post e postei o meu destroy da imagem... dessa forma deletando somente a imagem deleta na pasta..
Comment: @raphael estou assumindo que você está armazenando o nome do arquivo no banco ($product->filePath). Você precisa alterar essa linha para o campo no seu banco que armazena o nome do arquivo
Comment: @raphael conseguiu ?
Comment: tinha dado um tempo nesse projeto pois estou focado em outro.. mas depois volto pra dizer se ja resolvi.. vlw pela ajuda


Why does scheduleAtFixedRate(task, delay, period) not work as scheduled?

Question: I am to use a timer using timertask to check the wifi status after every minute in an android app. Here I have to check whether wifi radio is on or off after every minute. If the wifi radio is off I have to turn it on and when wifi radio is on the timer works fine as scheduled. But when wifi radio is turned off at the beginning or turned off while the app is running the scheduled task doesn't work as scheduled and it seems working quicker. What should I do to fix this?
      TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                try {
                    ConnectivityManager connMgr = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);

                    NetworkInfo networkInfo     = connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

                    if(!networkInfo.isAvailable()){
                        mainWifi.setWifiEnabled(true);
                    }
                    else{
                        // Wifi is available
                    }

                    if(networkInfo.isConnected()){
                        // Connected to a WiFi network.
                    }
                }
                catch(Exception e){

                }
            }
        };
        timerT.scheduleAtFixedRate(timerTask, 0, 60000);

Answer: Straight from the Android docs for Timer:

With fixed-rate execution, the start time of each successive run of a task is scheduled without regard for when the previous run took place. This may result in a series of bunched-up runs (one launched immediately after another) if delays prevent the timer from starting tasks on time.

It's impossible to explain the specific behavior you're observing without knowing a lot more about your code than you have posted, but the above is probably what's going on.
You probably want to be using fixed-period scheduling, which according to the docs, behaves more like what you seem to want:

With the default fixed-period execution, each successive run of a task is scheduled relative to the start time of the previous run, so two runs are never fired closer together in time than the specified period.
Comment: Well, thank you and I have published my sample code at the edited question.
Comment: @Droidy - I don't know exactly what's going on, but my guess is that when the radio is first turned off, checking the network availability and/or connectivity takes a long time (possibly waiting for a time-out). Then, because of the delay, all subsequent checks are then bunched up as the docs describe. Try using `schedule` instead of `scheduleAtFixedRate` and the runs should execute on a more regular schedule regardless of delays.
Comment: I have tried schedule also. But the situation is same. This happens only when wifi radio is turned off. If the wifi radio is on all the time, it works fine.
Comment: You're sure that it is this timer task (and this one alone) that is running more frequently? I can't see how it could if you are calling `schedule()` instead of `scheduleAtFixedRate()`. (Note that the second one will start one minute after the first one _starts_, not one minute after it finishes, so uneven execution times may make it _appear_ to be running faster, but that should not be a steady state condition.) You say that it "seems" to be quicker; how are you determining how quickly it is running?
Comment: I had some toast messages for conditions, where the things seemed quicker. I think I got this one Tedd. Yeah, it is the start time of the task. Thank you for your help.


Phase portait of 3 by 3 matrix.

Question: Consider the following linear system $x = Ax$, where $x\in\mathbb R^3$ and
$$\begin{bmatrix}
-3 & 0 & 0 \\
0 & 3 & -2 \\
0 & 1 & 1 \end{bmatrix}.$$
Draw the phase portrait nearby the origin as precisely, without computing the eigenvectors of the matrix.
I found $-3,2+i$ and $2-i$ are the eigenvalues. How could I figure out the  phase portrait nearby the origin. Please help me out to solve it.
Comment: drawing it out on $\mathbb{R}^3$? that's going to be messy
Comment: yea I know  any how can you provide me a hint @ More
Comment: its going to be a spiral  source on one plane, and then an asymptotic stable lines passing through the spiral center on that plane.
Comment: Now if you want to know which plane has the spiral source, you can go an compute the eigenvectors corresponding to 2+i and  2−i. Btw spiral source means the solution is moving away from the origin in a spiral way (opposite of a spiral asymptotic stable)
Comment: thank you , I got something I like to figure out with out using eigen vectors so that I was wondering.
Answer: The first thing to notice is the block-diagonal form of the matrix: it has diagonal blocks $(3)$  and $\begin{pmatrix} 3 & -2 \\ 1 & 1\end{pmatrix}$, with zeros elsewhere. This means that the system $x'=Ax$ decouples into an ODE for $x_1$, and an ODE system for $x_2,x_3$; there is no interaction between these two systems. It's easy to solve $x_1'=-3x_1$: exponential decay, the orbits approach the plane $x_1=0$.
The system for $(x_2,x_3)$ is planar,  and the eigenvalues (complex, with positive real part) indicate unstable spiral. Orbits spiral out counterclockwise, as you can see from a planar sketch.
Hence, the complete picture is: all trajectories approach the plane $x_1=0$, but move away from the origin of that plane in a spiraling fashion. It's sort of like the formation of a spiral galaxy from a shapeless cloud of gas.

Phase portait of 3 by 3 matrix.


Is there a way to enable Basic Auth for only one specific type of node?

Question: Can't really find much useful in the way of googling.
I have a special content case on my site where I have created a page template which displays a series of blocks in my theme code. To apply this template to this particular page, I made a custom node type for it. However, this content is (and should be) restricted only to users with a certain permission, which I accomplished via the Content Access plugin.
I want to use wkhtmltopdf to output a PDF of that page for internal use. The only way I think I can get the node instance to allow wkhtmltopdf to view it is to run wkhtmltopdf with the --custom-header flag with an Authorization header. I need this to happen once per day, and was thinking of setting up a cron task to run wkhtmltopdf nightly on a Linux system (so far I have just been testing it manually on a Windows system where the node had no permission requirements and everything seems fine).
I know that enabling basic auth for certain paths is a thing I can do using a plugin, but this content is not defined by a plugin and is just a node I created using the Drupal interface.
Is this possible, or do I have to tear it down and start over and build a new custom plugin?
Answer: Probably there is no one here, that has tried the method you've described. I would start with a custom entity, use the basic auth or create a new authentication provider and apply this for the entity route. You can do this with drupal console within a minute.
And you don't need contrib code to configure access for the custom entity, because here you can do what you want in core. I wouldn't use an Access plugin from contrib, until there is a stable release.
Comment: I think I'm going to go with this option. Unfortunately now I am having problems getting the code to output an actual HTML document instead of a div snippet. Going to make a separate thread about this.
Answer: Solution 1 - override the node access controller
The node entity type, defines the node access controller. This is done through annotation (system that allow you to define things through comments.)
If you use hook_entity_type_alter you can change the node access controller to a subclass you make and implement any kind of logic.
Solution 2 - use basic auth on all pages
Is there any reason why you shouldn't be able to authenticate with basic auth on all pages. Drupal has this feature OOB from the basic_auth module, so you simply could turn it on. I don't see that being a security info as you would need to pass credentials on all requests (instead of logging in once and using a cookie).
You need to enable for global use, look the cookie authenticator:
user.authentication.cookie:
  class: Drupal\user\Authentication\Provider\Cookie
  arguments: ['@session_configuration', '@database']
  tags:
    - { name: authentication_provider, provider_id: 'cookie', priority: 0, global: TRUE }

Solution 3 - generate a cookie used for requests
Another solution would be to login with Drupal (simply post the login form and get the cookie in return) and you could just add the cookie in all requests. That would provide you access. The services modules in Drupal core might help making some of these things a bit easier.
Comment: Thank you for the answer. #2 seems acceptable, but embarrassingly enough I can't figure out how to do it. I have the module enabled but don't see this option anywhere to turn it on, and basic auth is only working on modules where I've explicitly specified it in the routing.yml. Every guide I found is talking about the REST module and I don't think that's what I'm looking for. Am I missing something?
Comment: @saramm1 Seems like the basic auth isn't global by default, so looks like you need to add that information in the service definition, or create your own service using the same class.
Comment: Hmm, I think I'm in way over my head here. I don't understand what a drupal service is or how to create one.
Comment: @saramm1 A service is just a reusable class which does something, like cookie auth handling, basic auth handling etc. What makes it a service is a few lines of yml which defines a name, class location, other services that the service depend on and some metadata. When you make it a service other services can use it, or by giving it tags you it will automatically be used for some things. How to alter service: https://www.drupal.org/docs/8/api/services-and-dependency-injection/altering-existing-services-providing-dynamic-services


Pathauto: Custom punctuation replacement

Question: Instead of having Pathauto replace punctuation in the path alias with a default separator ( dash for example ), or remove it, can we somehow specify a custom input to replace with?
For example, " could be replaced with inches
Answer: You can use hook_pathauto_alias_alter().


Farseer: Object not bouncing back from static objects

Question: I have a dynamic circular object bounded inside four static rectangle objects. Consider a ball inside a box with the static rectangle objects simulating the walls of the box . IgnoreGravity is set to true for circular object. I want the circular object to hit and bounce back from the  walls. However, when the circular object collides with the wall, it stucks to it and moves along the wall instead of bouncing back.
Following is the code I am using:
Body CircleBody;

const int CircleRadiusInPixels = 20;
const int CircleCentreXInPixels = 100;
const int CircleCentreYInPixels = 100;
Texture2D CircleTexture;

Body[] RectangleBody;
Texture2D RectangleTexture;

struct RectagleProperties
{
    public int WidthInPixels;
    public int HeightInPixels;
    public int CenterXPositionInPixels;
    public int CenterYPositionInPixels;

    public RectagleProperties(int Width, int Height, int X, int Y)
    {
        WidthInPixels = Width;
        HeightInPixels = Height;
        CenterXPositionInPixels = X;
        CenterYPositionInPixels = Y;
    }

};

RectagleProperties[] rectangleProperties;

World world;

const float PixelsPerMeter = 128.0f;
float GetMetres(int Pixels)
{
    return (float)(Pixels / PixelsPerMeter);
}

int GetPixels(float Metres)
{
    return (int)(Metres * PixelsPerMeter);
}

protected override void LoadContent()
{
    ...
    RectangleTexture = Content.Load<Texture2D>("Sprites/SquareBrick");
    CircleTexture = Content.Load<Texture2D>("Sprites/Circle");

    world = new World(new Vector2(0, 9.8f));

    CircleBody = BodyFactory.CreateCircle(world, GetMetres(CircleRadiusInPixels),
                                          1,
                                          new Vector2(
                                                GetMetres(CircleCentreXInPixels),
                                                GetMetres(CircleCentreYInPixels)));
    CircleBody.BodyType = BodyType.Dynamic;
    CircleBody.IgnoreGravity = true;
    CircleBody.LinearVelocity = new Vector2(1, 1);

    rectangleProperties = new RectagleProperties[4];
    rectangleProperties[0] = new RectagleProperties(800, 20, 400, 10);
    rectangleProperties[1] = new RectagleProperties(800, 20, 400, 460);
    rectangleProperties[2] = new RectagleProperties(20, 480, 10, 240);
    rectangleProperties[3] = new RectagleProperties(20, 480, 790, 240);

    RectangleBody = new Body[4];
    for (int i = 0; i < rectangleProperties.Length; i++)
    {
        RectangleBody[i] = BodyFactory.CreateRectangle(world,
                                                       GetMetres(rectangleProperties[i].WidthInPixels),
                                                       GetMetres(rectangleProperties[i].HeightInPixels),
                                                       0.5f,
                                                       new Vector2(GetMetres(rectangleProperties[i].CenterXPositionInPixels),
                                                                   GetMetres(rectangleProperties[i].CenterYPositionInPixels)));
        RectangleBody[i].BodyType = BodyType.Static;

    }
    ....
}

After a little digging around I found out that the VelocityConstraint was causing the collision to be treated as inelastic. However, if I reduce the value of VelocityConstraint then it results in weird collision response.
Does anybody know how to get the ball object bounce back after colliding with the static objects?
Answer: Since you haven't posted the contents of the Update-method where the problem probably lies i will make a qualified guess.
This seems to be related to a very common problem:
Say that the circular object has a certain speed.
In event of a collision you reverse the speed over the walls axis and the speed is reduced a bit either by gravity or something else.
Now you apply the new speed in order to resolve the collision but since the speed is reduced it is not enough to resolve the collision which means the object will still be colliding with the wall in the next update.
This will cause the speed to be reversed over and over since the object will never gain enough speed to get out of the collision again.
The solution to this is to move the object out of collision preferably on the shortest axis (check out the "Separating axis theorem") before proceeding with other code.
Comment: Thanks for your response. As far as I remember I wasn't doing anything special in the Update method, other than Updating farseer and getting the latest co-ordinates of the objects from farseer. What you have described makes sense, but I was expecting that the Farseer engine should have moved the ball/circle out of the bounds of colliding object. I wasn't doing any of that in the collision handler.
Comment: I think i forgot that this was made with Farseer somewhere along writing this post.
Farseer should of course be doing this correctly.
But it has to have a reason right?
And I've seen this happen several times before.
Anyways, i hope my answer helped you in some way.


How can a team win while rain stopped play permanently in 2nd innings?

Question: The Team bat first scored 144/3 after 20 overs in T20 format match.. second Team scored 34/2 in 8.4overs . then rain stopped the play. who will won the match? explain please.
Answer: That depends on what method of resolution the league or competition has designated for this case.  If they use net run rate, for example, then team 1 has 7.2/over and team 2 has 3.9/over, so team 1 wins.  If they use Duckworth-Lewis, then the par score for team 2 would be 56, so team 1 wins.  (There are several online resources to calculate D/L; results may vary.)  There are other methods as well.
Comment: All tournaments organised under ICC's standards *have to* use the D/L method.


Angular Material Table: "Can't bind to 'dataSource' since it isn't a known property of 'table'"

Question: I'm trying to add a table in my Angular app from Angular firstname.lastname@example.com (as shown here).
I copy / pasted the code from the Angular Material official documentation but I still get the error:

Can't bind to 'dataSource' since it isn't a known property of 'table'

I tried the following:
Replacing table tag with mat-table, resulting in

mat-table is not a known element

Deleting the brackets in [dataSource]="dataSource" as dataSource="dataSource", resulting in (Webdeveloper console error this time, this could be the solution but I don't know how to fix it even after some searches)

Can't bind to 'matHeaderRowDef' since it isn't a known property of 'tr' (used in the '_UsersComponent' component template).

importing MatTableModule from '@angular/material' instead of '@angular/material/table' in app.module.ts, resulting in

@angular/material has no expôrted member MatTableModule

Add import {CdkTableModule} from '@angular/cdk/table'; and importing it, changing nothing.
The MatTableModule is declared and imported in app.module.ts, where the UsersComponent using it is also declared and imported.
Here are all versions used in the project:
@angular-devkit/architect       0.1702.2
@angular-devkit/build-angular   17.2.2
@angular-devkit/core            17.2.2
@angular-devkit/schematics      17.2.2
@angular/cdk                    17.2.1
@angular/cli                    17.2.2
@angular/material               17.2.1
@schematics/angular             17.2.2
rxjs                            7.8.1
typescript                      5.3.3
zone.js                         0.14.4
Here is my app.module.ts file's content:
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { BrowserModule } from '@angular/platform-browser';

import { MatListModule } from '@angular/material/list';
import { MatToolbarModule } from '@angular/material/toolbar';
import { MatSidenavModule } from '@angular/material/sidenav';

import { AppComponent } from './app.component';
import { TopbarComponent } from './topbar/topbar.component';
import { LeftmenuComponent } from './leftmenu/leftmenu.component';
import { NavleftbarComponent } from './navleftbar/navleftbar.component';

import { MatIconModule } from '@angular/material/icon';
import {MatTableModule} from '@angular/material/table';
import { MatButtonModule } from '@angular/material/button';
import {CdkTableModule} from '@angular/cdk/table';

import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
import { UsersComponent } from './users/users.component';

@NgModule({
  declarations: [
    AppComponent,
    TopbarComponent,
    LeftmenuComponent,
    NavleftbarComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    MatToolbarModule,
    MatSidenavModule,
    MatListModule,
    MatButtonModule,
    MatIconModule,
    MatTableModule,
    UsersComponent,
    CdkTableModule
  ],
  providers: [
    provideAnimationsAsync()
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Here's the users.component.ts's file content:
import { Component } from '@angular/core';
import { MatTableModule } from '@angular/material/table';

export interface UserElement {
  firstname: string;
  lastName: string;
  email: string;
  microsoftEmail: string;
  class: string;
}

const ELEMENT_DATA: UserElement[] = [{
  firstname: "Pierrick",
  lastName: "MARTELLIERE",
  email: "firstname.lastname@example.com",
  microsoftEmail: "email@example.com",
  class: "GPME24"
}];

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrl: './users.component.css',
  standalone: true,
})

export class UsersComponent {
  displayedColumns: string[] = ['firstName', 'lastName', 'email', 'microsoftEmail', 'class'];
  dataSource = ELEMENT_DATA;
  clickedRows = new Set<UserElement>();
}

And the users.component.html:

  <ng-container matColumnDef="firstName">
     Prénom
     {{element.position}}
  </ng-container>

  <ng-container matColumnDef="lastName">
     Name
     {{element.name}}
  </ng-container>

  <ng-container matColumnDef="email">
     Email
     {{element.weight}}
  </ng-container>

  <ng-container matColumnDef="microsoftEmail">
     Compte Microsoft
     {{element.symbol}}
  </ng-container>

  <ng-container matColumnDef="class">
     Classe
     {{element.symbol}}
  </ng-container>

I really don't see what I am missing, some help would be welcome.
Answer: Your component is a standalone component.
From your source:
@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrl: './users.component.css',
  standalone: true, // ---> Standalone!
})

Which means it is acting as its own module. You should import the MatTable here, isntead of your application Module.
@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrl: './users.component.css',
  standalone: true,
  imports: [MatTableModule], // ---> import done directly here!
})

Another option, is maybe you did not want a standalone component? Since I see it inside your imports of your AppModule. You then need simply to remove the standlone:true part in its declaration.
Comment: They are empty because you are displaying properties that are not in the UserElement interface.
Comment: You might want to read more about standalone components here: https://blog.angular-university.io/angular-standalone-components/
Comment: Thank you very much for spotting this incoherence, now the table is well displayed (there as much rows as objects in my dataSource, but each row is blank. Could you know what it come from ?
Thanks also for the related link about standalone components.
Comment: Thanks again for everything ! I accepted your answer :)
Answer: UserElement doesn't have the properties:
{{element.position}} {{element.name}} {{element.weight}}

Change it to
{{element.firstName}} {{element.lastName}}

Comment: haha i think table in angular material is weird
Comment: Yeah this didn't even trigger an error on console nor shell...
Comment: Anyway this was not the answer to the question, but it caused the table to display blank rows so it helped me as well :) Thanks !


having issue with ordering my arrayLust

Question: I want to return the top k ratables from the ArrayList based on the  Comparator "c" in order . so the first element is the first ratable according to the comparator c.
this is my code
public static ArrayList<Ratable> getTopK(ArrayList<Ratable> list, int k, Comparator c) {
        ArrayList<Ratable> ratables;

        if (c.toString().contains("AlphabeticalComparator")) {
            ratables = AlphabeticalComparator.compare(list);
        } else if (c.toString().contains("NumberOfRatingsComparator")) {
            ratables = NumberOfRatingsComparator.compare(list);
        } else {
            Scanner in = new Scanner(System.in);
            System.out.println("Enter Extra Reviews and value of extra ratings: ");
            int extraReviews = in.nextInt();
            double extraRatings = in.nextDouble();
            ratables = BayesianAverageComparator.compare(list, extraReviews, extraRatings);
        }

        ArrayList<Ratable> subList = new ArrayList<Ratable>(ratables.subList(0, k));
        return subList;
    }

    }

My autograder is telling me it is not ordered the way it needs to be what can I do?
Answer: You can use Collections.sort(list, comparator).

having issue with ordering my arrayLust


Qualitative understanding of Fisher Information

Question: I'm struggling with understanding what Fisher Information is. Here is my thought process.
We begin with the PDF $f(x)$ of some distribution. Let's assume we are dealing with a continuous case on the real line. Then, in the framework of the statistics class, we say that our distribution also depends on some parameter $\theta$, which is unknown. So, our PDF becomes a function of two parameters - $f(x,\theta)$.
We observe an experiment. We get some results $X_1$, $X_2$, ..., $X_n$, that are i.i.d. We consider the joint PDF function $g(\bar X,\theta)=f(X_1,\theta)f(X_2,\theta)...f(X_n,\theta)$.
With the experiment result known, our function $g$ becomes a function of only one variable $\theta$ and is denoted by $g(\theta|\bar X)$. And it is now called the likelihood function.
We are now interested in knowing how much this particular experiment result is informative. The quantity assigned is the Fisher Information, that is defined by:
$I(\theta)=E_{\theta} [\frac{d}{d\theta}(ln(g(\theta |\bar X))^2]$.
First thing i don't understand is the role of the function $ln$ here. Taking it as it is, my further understanding is following:
We consider the graph of the likelihood function $g(\theta)$. Then, we consider the slope of this function. Because, the bigger the slope is, the bigger the difference between the likelihood function values on close values of $\theta$ will be, and we will be able to locate $\theta$ more precisely (hence, "more information"). Now, we don't know the exact value of $\theta$, so we would like to average that slope value over all domain of $\theta$. We will also have to account for the fact that different values of $\theta$ can appear with different probabilities. The function of expected value $E$, then, is exactly what we need.
We arrive at this: $E_{\theta} [\frac{d}{d\theta}(ln(g(\theta |\bar X))]$=$\int _{\Theta} {\frac{d}{dt}(ln(g(t |\bar X))\theta(t)dt}$, where $\theta (t)$ is the PDF of the parameter $\theta$ and $\Theta$ is the domain of $\theta$. Now, this itself is not very representative, since the slope, being negative or positive, can cancel out, so we add squaring, and arrive at the definition.
Now, I don't understand how $I$ is a function and not a number (depending on our experiment result)- after we've taken the integral, $\theta$ must be gone. And, I also don't understand why is it that in the problems I am given in the class, I am given the distribution of $X_i$, and not of the parameter $\theta$.
What are the mistakes and missing points in my reasoning?
Comment: Cross-posted at https://stats.stackexchange.com/q/474914/119261.
Answer: Under certain regularity conditions, there is an equivalent form of the Fisher information.
$$I(\theta) = E_\theta \left[\left(\frac{d}{d\theta} \ln g(\theta \mid X)\right)^2\right] = -E_\theta \left[\frac{d^2}{d\theta^2} \ln g(\theta \mid X)\right]$$
This form involving the second derivative has an intuitive interpretation: it captures the curvature of the log likelihood function: a high Fisher information at some $\theta$ indicates that the log likelihood is sharply peaked there. I think your attempt to interpret the other form (the square of the first derivative) is ok too.
Regarding the logarithm, Wikipedia notes that some sources use a different definition where the logarithm is absent. I haven't encountered this myself, and would not bother with this alternate definition. Basing your interpretations on the shape of the log likelihood as you have attempted to do is fine. As for why we usually consider the log likelihood instead of the likelihood, it is because this quantity shows up naturally, most notably as the Cramer-Rao lower bound.
$I$ is still a function of $\theta$. The expectation is taken with respect to the randomness in the data $X$, but the expectation itself still depends on $\theta$. I think your use of $\theta(t)$ for the PDF with parameter $\theta$ is a little problematic; one usually uses $f_\theta$ or something similar. After taking that integral, the quantity you obtain will depend on $\theta$ since the density depends on $\theta$.


Customize user registration form by adding/modifying fields in the form and handling submit function

Question: I am new to drupal.
I need to customize a registration form by adding fields like id,mobile etc.
Can I accomplish this by creating a custom module?
If yes could anyone please help me with a brief idea on creating and overriding the default user registration submit function. I have to insert these details to another table and also have to pass the data as a service request.
Ive created a custom module with function
function module_form_alter(&$form,&$form_state,$form_id){
$form['#submit'] = 'module_form_submit';

if($form_id == 'user_register_form'){
    //print_r($form_id);
    $form['email'] = array(
            '#type' => 'textfield',
          '#title' => t('id'),
          '#default_value' => '',
          '#size' => 60,
          '#maxlength' => 15,
          '#required' => TRUE,
     );
    }
}

function module_form_submit($form, &$form_state){
  echo "test";
 exit();
}

module_form_alter is being called and I can see the new field on the registration screen but the submit function is still not called. I need to override the default drupal register submit.
I already have the following function in my theme template.php
function templatename_theme() {
  $items = array();

  $items['user_login'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'portal') . '/templates',
    'template' => 'user-login',
    'preprocess functions' => array(
     'portal_preprocess_user_login'
    ),
  );
  $items['user_register_form'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'portal') . '/templates',
    'template' => 'user-register-form',
    'preprocess functions' => array(
      'portal_preprocess_user_register_form'
    ),
  );
  $items['user_pass'] = array(
    'render element' => 'form',
    'path' => drupal_get_path('theme', 'portal') . '/templates',
    'template' => 'user-pass',
    'preprocess functions' => array(
      'portal_preprocess_user_pass'
    ),
  );

  return $items;
}

user-register-form.tpl.php

    <?php print drupal_render_children($form); ?>

And page--user--register.tpl.php with the html

<a href="<?php echo $home; ?>"><img src="<?php echo drupal_get_path('theme', 'portal') . '/images/logo.png'; ?>"  width="100"><?php echo $createaccount; ?>

            <?php
            $elements = drupal_get_form("user_register_form");
            $form = drupal_render($elements);
            echo  $form ?>

     <?php if ($messages):?>

                <?php print $messages; ?>

        <?php endif; ?>

Is this approach fine or should I change this approach inorder to make my custom module functional?
One problem, I need to validate this form in client side, Ive added js in module_form_user_register_form_alter function as
         $form['#attached']['js'] = array(drupal_get_path('module', 'modulenamne').'/js/myjs.js',);
File is loaded but when clicked on submit the js is not working, instead the page is loading and drupal submit is executing.
Answer: If it is not crucial for you to have the additional fields in custom code, I would highly recommend you to make use of the fact that user is a fieldable entity and you can add additional fields easily to it via administration at "admin/config/people/accounts/fields" - this way you do not need to handle saving of the data and display of form elements.
When doing so, you can still make use of custom validation or submit handlers or fiddle with the form and fields easily using the same technique you are using - hook_form_alter and add your submit handler to do whatever logic you require.
Back to your approach — the reason why your submit function is not being called is that you are assigning a string to it instead of adding an element to the array. Try this:
$form['#submit'][] = 'module_form_submit'; (notice the empty brackets on the left side).
If you want to completely overwrite the submit functions array use this:
$form['#submit'] = array('module_form_submit'); - but this will cause that the user will not be created and data saved (unless you do that by hand in your custom submit handler), this also cancels whatever some contrib modules to with the registration form, so you might have unexpected issues.
Edit after comments:
If you do want to keep the default behaviour, but do your logic before everything, you can put your submit handler as first, as they are executed based on their order in the array like this:
array_unshift($form['#submit'], 'module_form_submit');
Comment: Thanks for the response, the reason why I removed the array was for overriding the default submit handler of user registration, I need my submit handler to execute first, check some conditions, and only then allow the drupal registration submit to execute.Any thoughts?
Comment: I tried adding the extra fields through "admin/config/people/accounts/fields" ,this approach is okay for me, however I needed to replace the username field with new field 'ID' , is that possible?
Comment: I updated my questions based on your comments. When it comes to the username field - no you cannot change that, it is a mandatory column in the `users` table, the User entity cannot be created without it. In a case that you need such custom behaviour you might need to consider using something else than user register form, maybe a content type or webform approach.
Comment: Thanks for your comments. I am planning to go for webform approach.But for this I need to manual insert in the users table.
Comment: I have tried with this method to override the submit handler  $form['#submit'] = array_unshift($form['#submit'], 'module_form_submit'); but its throwing a warning "Warning: Invalid argument supplied for foreach() in form_execute_handlers() (line 1501 of /var/www/html/account/includes/form.inc)"
Comment: Sorry, that was a typo I updated the answer - you dont assign the result of `array_unshift` because the array is passed by reference.
Comment: That works! The user details are not inserted until my custom  submit is executed.Thanks a lot!


How to visualize a range (min/med/max)?

Question: I'm looking for a visually compelling yet immediately understandable  way to visualize a range of data (min, median, max)
Considerations:

The approach should be understandable to a wide variety of people
Ideally, would allow for the comparison to another set of data
Ideally, will work okay or both high and low N cases

What new ways can you think of to visualize this type of data?
Here are some examples:
Example 1: Here is how a range of data and a comparison is displayed on Glassdoor:

Example 2: Here is how a range of data and a comparison is displayed on Indeed:

Example 3: Here is another very similar example from CareerBuilder:

Example 4: and Trucar's visualization of a range of data (car prices paid by many users).
This is likely pushing the realm of understandability by an average audience.
Comment: one vote for the glassdoor style
Comment: @whuber, no, my understanding of a range does not differ from what you'd expect. These just happen to be the only examples I can easily find online that are close (and, are from large consumer web sites).
Comment: The first one is the only one of the three that clearly identifies the three values you mentioned. You might consider a boxplot-without-the-box.
Comment: It is curious that neither examples 2 nor 3 actually show ranges in the usual sense of the word. That raises the question of what you understand a "range" to be.  Does it differ from the conventional meaning of the interval from the least to the greatest value of a set of numbers?
Comment: By a boxplot-without-the-box I meant something like [this](http://i.imgur.com/wo78O1z.png); this is easy to generate in R.
Comment: [Here](http://stats.stackexchange.com/questions/64880/software-to-produce-confidence-interval-error-bars-from-summary-statistics-witho/64889#64889) is one script in R you could adapt to generate @Glen_b's suggestion.
Comment: @AndreSilva That's nice. I just called boxplot with the median replicated two additional times, plus the min and max, then set `range=0`.
Comment: Can any of you think of any other large consumer web sites that might be displaying similar information using a different visual approach?
Comment: What tasks do you need a viewer to be able to do? And, what is the metric? Speed? Accuracy?
Answer: Example number 1 seems to be nice if you have different minimum thresholds among the categories.
As pointed by Glen_b and whuber, it seems that examples number 2 and number 3 do not show the ranges of your categories, but just one unique statistic (it could be the median, or the maximum values) at the top of the horizontal bars.
The example number 4 is a little bit strange because the bell curve does not represent the distribution of the bars (for example, the blue light dot 'average paid' is the average of the bell curve, not the average of quantities shown in the bars). It is not "visually compelling yet immediately understandable" to me.
As you asked for another option, I would suggest the boxplot, which shows:

outliers (the dots),
minimum and maximum values without considering outliers (the end of the whiskers)1,
first and third quartiles (the edges of the box), and
median (the horizontal bar inside the box).

Each box is a category. Order the boxes from left to right starting with the category with greatest median.
The example number 1 is simpler to understand, so it will depend if a boxplot will really help.
1: see whuber's comment for clarification.
Comment: +1 But please note that boxplot whiskers conventionally--and by original design--do *not* necessarily extend to the extrema. They stop at the most extreme *non-outlying* data. Outliers--defined as those beyond invisible "fences" determined by the medians and quartiles (or "hinges")--are depicted separately with point-like symbols. In my experience, too, boxplots take a lot of explaining to people who are not educated in their use. That would be most older people and probably a lot of middle-aged ones, too.

How to visualize a range (min/med/max)?


Migrating from one dedicated linux server to another?

Question: I have a dedicated server running ubuntu server 9.04 for web, database and mail. There's about 5 GB of data on the entire hard drive.
I want to migrate the server to a more affordable dedicated server provider but I am unsure how to do this.

Can I clone an entire hard drive? What about hardware specific files/dirs?
Or maybe there is a saner approach?
The future hosting will probably have another version of ubuntu, so should I upgrade our current server before migrating? How about migrating apache, mysql and postfix?
Answer: My suggestion is to take backups of everything and restore it on the new server. Ie:

Dump databases and restore them on the new server
Copy webserver, database, email configs on the new one

Of course it requires a little downtime. There are some things you can do to make the downtime smaller:

Do a previous rsync for all email data, then after everything configured and tested stop the service on the old server, rsync only the new data and start the new server.
Use mysql replication to keep data on both servers until the time to 'switch'
The rsync approach can be used with all other data (even db, but I suggest you to use a dump or replication to minimize the choice of error).

Also remember that this is a procedure that needs to be carefully planned and executed or data loss may happen.
Comment: This was my initial idea but the problem is that the "settings" are scattered all over the OS. Since it is so easy to forget one data migration step, I'm afraid that the migration will be very cumbersome.
Comment: [GTD](http://www.davidco.com/what_is_gtd.php) :) Create a list of tasks and go one by one. A little brainstorm is really needed. Also, all configurations should be on /etc (it's the [FHS](http://www.pathname.com/fhs/) and Debian/Ubuntu way) unless you installed things without using packages or proprietary stuff on `/opt`.
Comment: You just made an argument for my most prized practice. Next time, consider documenting every change you make to a production server on a private wiki. That way you know exactly where and what settings exist and how the server was setup. It may seem like a cumbersome task but its saved me several times. Also great for the company if you leave or get sick.
Comment: +1, although #2 is not something to take lightly.  And once the new server is up-and-running on the latest LTS release (you may/likely will run into some PHP 5.3 "deprecated" errors that you'll want to clean up if you're hosting a PHP app), just schedule/notify your users of some downtime to do the final rsync and mysqldump.
Comment: @ianlbc It's one of the first practices I implement when I get to a new place. I use [dokuwiki](http://www.dokuwiki.org/dokuwiki) for it's simplicity and text based backend.
Answer: You may be interested in exploring the possibility to use FSArchiver, http://www.fsarchiver.org/Main_Page
Answer: A few relevant things I've learned by trial and error (mostly error):

Document the steps as you go so you have a record the next time you do it (there will always be a next time). That way you won't forget any steps and it permits someone else to do it as well.
If you can switch components piece by piece it will be easier to diagnose issues. For example, keep the mail/database on the original server and just move the web server to the new server. Skip this if your application cannot easily handle inter-server but it is something to consider if you need to scale your system to multiple servers. This method is particularly useful if you need to minimize downtime.
I wouldn't try just copying the raw database files from one server to another unless you are sure the database supports it. If you just have a few 100MB of databases I would just create a dump on the old server and restore on the new one. For larger databases it will be significantly quicker to setup replication.
If using rsync or scp to copy files from one server to another make sure the user you use has read permissions for all the files. For example, I once used rsync to copy over some files from /etc but didn't have read permissions for some files. By the time I found out some files were missing it was too late (the old server was wiped). Since then I have always used tar as root on the old server to backup directories and then rsync/scp the tar archive over.
Answer: If you have found your new provider, have you asked them how they like to do this?  You may want to know the details of the from/to environments, including hardware, to pick the best approach.
Also, inquiring about ease of migration and available support may help you choose your new provider!
Comment: The new provider basically told be I have to do this myself and get started with getting services up and running and then migrate the data. Not terribly useful but I understand that the process is pretty complex.