EzDevInfo.com

construct

PHP project/micro-package generator.

What is the rationale behind this code block in java?

What is the rationale behind making this kind of code valid in java? Does it exist for some particular reason or is it just a byproduct of other Java language design decisions? Can't you just use the consructor to achieve the same effect?

class Student
{
    {
        System.out.println("Called when Student class is instantiated.");
    }
}

Source: (StackOverflow)

init function for structs

I realize that Go does not have classes but pushes the idea of structs instead.

Do structs have any sort of initialization function that can be called similar to a __construct() function of a class?

Example:

type Console struct {
    X int
    Y int
}

func (c *Console) init() {
    c.X = "5"
}

// Here I want my init function to run
var console Console

// or here if I used
var console Console = new(Console)

Source: (StackOverflow)

Advertisements

Why parameterized constructor can't be called while creating array of class Objects?

I am new to C++, I need some clarification about the constructor and my question here is:

  1. Can we use a parameterized constructor while creating an array of class objects?
  2. Or is it only possible to use a default constructor when creating an array of class objects?

Please explain how it can be done, or why it can't. I need a deeper understanding about this.


Source: (StackOverflow)

"Could not execute Model_Hotel::__construct()" with mysql_fetch_object, properties remain uninitialized

I'm running PHP 5.3.6 with MAMP 2.0.1 on Mac OS X Lion and I'm using Kohana 3.1.3.1.

I try to override the __set() and __get() methods of the standard Kohana ORM module with my own methods. Some of my models extend my class which extends the ORM class.

<?php

class ORM_Localization extends ORM
{

    protected static $_language_cache = array();
    protected $_languages = array();

    public function __construct($id = NULL)
    {
        parent::__construct($id);

        // Load languages which are accepted by the client
        $this->_languages = array_keys(Application::languages());
    }

    public function __get($name)
    {
        /* Debugging #1 */ echo 'GET'.$name;
        /* Debugging #2 */ // exit;
        return $this->localization($name);
    }

    public function __set($name, $value)
    {
        /* Debugging #3 */ var_dump($this->_table_columns);
        /* Debugging #4 */ echo 'SET::'.$name;
        /* Debugging #5 */ // exit;
        $this->localization($name, $value);
    }

    public function localization($name, $value = NULL)
    {
        if (!array_key_exists($name, $this->_table_columns)) {
            // Load avaiable languages from database if not already done
            if (empty(ORM_Localization::$_language_cache)) {
                ORM_Localization::$_language_cache = ORM::factory('languages')
                    ->find_all()
                    ->as_array('id', 'identifier');
            }

            $languages = array();

            // Find the IDs of the languages from the database which match the given language
            foreach ($this->languages as $language) {
                $parts = explode('-', $language);

                do {
                    $identifier = implode('-', $parts);

                    if ($id = array_search($identifier, ORM_Localization::$_language_cache)) {
                        $languages[] = $id;
                    }

                    array_pop($parts);
                } while($parts);
            }

            // Find localization
            foreach ($languages as $language) {
                $localization = $this->localizations->where('language_id', '=', $language)->find();

                try {
                    if ($value === NULL) {
                        return $localization->$name;
                    } else {
                        $localization->$name = $value;
                    }
                } catch (Kohana_Exception $exception) {}
            }
        }

        if ($value === NULL) {
            return parent::__get($name);
        } else {
            parent::__set($name, $value);
        }
    }

}

But in PHP 5.3.6, I get the following error message:

Exception [ 0 ]: Could not execute Model_Hotel::__construct()

Model_Hotel extends this class and does not have an own construct. This is the code of Model_Hotel, a standard Kohana ORM model: http://pastie.org/private/vuyig90phwqr9f34crwg

With PHP 5.2.17, I get another one:

ErrorException [ Warning ]: array_key_exists() [function.array-key-exists]: The second argument should be either an array or an object

In Kohana, my model which extends my class is called by mysql_fetch_object(), somewhere deep in the orm modules code.

However, if I echo the called property in __set() and exit (#4 and #5) afterwards, it outputs "SET::id" and doesn't show the error message.

If I var_dump() $this->_table_columns (or any other property of this class, #3), I get "NULL" which is the value that this property has before it's initialized. If I repeat the same with $this->_languages, I get an empty array which should be filled with several languages. It's like the class was never initialized with the __construct. This explains the error which I get in PHP 5.2.17, because $this->_table_columns is NULL and not an array.

I can uncomment my __construct and I still get the same error, the fault has to be in my localization() method.

I searched for several days now and I have absolutely no idea what could be wrong.


Source: (StackOverflow)

What does 'Language Construct' mean?

I am learning C from 'Programming in C' by Stephen Kochan.

Though the author is careful from the beginning only not to confuse the students with jargon, but occasionally he has used few terms without explaining their meaning. I have figured out the meaning of many such terms with the help of internet.

However, I could not understand the exactly meaning of the phrase 'language construct', and unfortunately the web doesn't provide a good explanation.

Considering I am a beginner, what does 'language construct' mean?


Source: (StackOverflow)

How to check version of python modules?

I just installed the python modules: construct and statlib with setuptools like this:

# Install setuptools to be able to download the following
sudo apt-get install python-setuptools

# Install statlib for lightweight statistical tools
sudo easy_install statlib

# Install construct for packing/unpacking binary data
sudo easy_install construct

I want to be able to (programmatically) check their versions. Is there an equivalent to python --version I can run from the command line?

My python version is 2.7.3.


Source: (StackOverflow)

What is this Hash-like/Tree-like Construct Called?

I want to create a "Config" class that acts somewhere between a hash and a tree. It's just for storing global values, which can have a context.

Here's how I use it:

Config.get("root.parent.child_b") #=> "value"

Here's what the class might look like:

class Construct

  def get(path)
    # split path by "."
    # search tree for nodes
  end

  def set(key, value)
    # split path by "."
    # create tree node if necessary
    # set tree value
  end

  def tree
    {
      :root => {
        :parent => {
          :child_a => "value",
          :child_b => "another value"
        },
        :another_parent => {
          :something => {
            :nesting => "goes on and on"
          }
        }
      }
    }
  end

end

Is there a name for this kind of thing, somewhere between Hash and Tree (not a Computer Science major)? Basically a hash-like interface to a tree.

Something that outputs like this:

t = TreeHash.new
t.set("root.parent.child_a", "value")
t.set("root.parent.child_b", "another value")

desired output format:

t.get("root.parent.child_a") #=> "value"
t.get("root") #=> {"parent" => {"child_a" => "value", "child_b" => "another value"}}

instead of this:

t.get("root") #=> nil

or this (which you get the value from by calling {}.value)

t.get("root") #=> {"parent" => {"child_a" => {}, "child_b" => {}}}

Source: (StackOverflow)

How to implement Haskell *Maybe* construct in D?

I want to implement Maybe from Haskell in D, just for the hell of it. This is what I've got so far, but it's not that great. Any ideas how to improve it?

class Maybe(a = int){ }  //problem 1: works only with ints

class Just(alias a) : Maybe!(typeof(a)){ }

class Nothing : Maybe!(){ }


Maybe!int doSomething(in int k){

  if(k < 10)
    return new Just!3;  //problem 2: can't say 'Just!k'
  else
    return new Nothing;
}

Haskell Maybe definition:

data  Maybe a = Nothing | Just a

Source: (StackOverflow)

Java recreate string from hashcode

Is there any way that I can use a hashcode of a string in java, and recreate that string?

e.g. something like this:

String myNewstring = StringUtils.createFromHashCode("Hello World".hashCode());
if (!myNewstring.equals("Hello World"))
    System.out.println("Hmm, something went wrong: " + myNewstring);

I say this, because I must turn a string into an integer value, and reconstruct that string from that integer value.


Source: (StackOverflow)

PHP: using $this in constructor

I have an idea of using this syntax in php. It illustrates that there are different fallback ways to create an object

function __construct() {

   if(some_case())
      $this = method1();
   else
      $this = method2();

}

Is this a nightmare? Or it works?


Source: (StackOverflow)

Patterns for Python object transformation (encoding, decoding, deserialization, serialization)

I've been working with the parsing module construct and have found myself really enamored with the declarative nature of it's data structures. For those of you unfamiliar with it, you can write Python code that essentially looks like what you're trying to parse by nesting objects when you instantiate.

Example:

ethernet = Struct("ethernet_header",
   Bytes("destination", 6),
   Bytes("source", 6),
   Enum(UBInt16("type"),
       IPv4 = 0x0800,
       ARP = 0x0806,
       RARP = 0x8035,
       X25 = 0x0805,
       IPX = 0x8137,
       IPv6 = 0x86DD,
   ),
)

While construct doesn't really support storing values inside this structure (you can either parse an abstract Container into a bytestream or a bytestream into an abstract container), I want to extend the framework so that parsers can also store values as they parse through so that they can be accessed in dot notation ethernet.type.

But in doing so, think the best possible solution here would be a generic method of writing encoding/decoding mechanisms so that you could register an encode/decode mechanism and be able to produce a variety of outputs from the abstract data structure (the parser itself), as well as the output of the parser.

To give you an example, by default when you run an ethernet packed through the parser, you end up with something like a dict:

Container(name='ethernet_header', 
    destination='\x01\x02\x03\x04\x05\x06', 
    source='\x01\x02\x03\x04\x05\x06', 
    type=IPX
)

I don't want to have to parse things twice - I would ideally like to have the parser generate the 'target' object/strings/bytes in a configurable manner.

The root of the idea is that you could have various 'plugins' registered for consuming or processing structures so that you could programatically generate XML or Graphviz diagrams as well as being able to convert from bytes to Python dicts. The crux of the task is, walk a tree of nodes and based on the encoder/decoder, transform and return the transformed objects.

So the question is essentially - what patterns are best suited for this purpose?


codec style:

I've looked at the codecs module, which is fairly elegant in that you create encoding mechanisms, register that your class can encode things and you can specify the specific encoding you want on the fly.

'blah blah'.encode('utf8')


serdes (serializer, deserializer):

There's are a couple examples of existing serdes modules for Python, off the top of my head JSON springs to mind - but the problem with it is that it's very specific and doesn't support arbitrary formats easily. You can either encode or decode JSON and thats basically it. There's a variety of serdes constructed like this, some use the loads,*dumps* methods, some don't. It's a crapshoot.

objects = json.loads('{'a': 1, 'b': 2})


visitor pattern(?):

I'm not terribly familiar with the visitor pattern, but it does seem to have some mechanisms that might be applicable - the idea being that (if I understand this correctly), you'd setup a visitor for nodes and it'd walk the tree and apply some transformation (and return the new objects?).. I'm hazy here.


other?:

Are there other mechanisms that might be more pythonic or already be written? I considered perhaps using ElementTree and subclassing Elements - but I wanted to consult stackoverflow before doing something daft.


Source: (StackOverflow)

Construct parsing for unaligned int field?

I am using this nice little package "construct" for binary data parsing. However, I ran into a case where the format is defined as:

31     24 23              0
+-------------------------+
| status |  an int number |
+-------------------------+

Basically, the higher 8 bits are used for status, and 3 bytes left for integer: an int type with higher bits masked off. I am a bit lost on what is the proper way of defining the format:

  • The brute force way is to define it as ULInt32 and do bit masking myself
  • Is there anyway I can use BitStruct to save the trouble?

Edit

Assuming Little Endian and based on jterrace's example and swapped=True suggestion, I think this is what will work in my case:

sample = "\xff\x01\x01\x01"
c = BitStruct("foo", BitField("i", 24, swapped=True), BitField("status", 8))
c.parse(sample)
Container({'i': 66047, 'status': 1})

Thanks

Oliver


Source: (StackOverflow)

What kind of c function is this?

I was reading "Compiler Design in C" book. In the basics section I found a c snippet for lexer something like this -

static int Lookahead = -1;
int match(token)
int token;
{
 if(Lookahead == -1)
    Lookahead = lex();

 return token == Lookahead;
}

void advance(){
   Lookahead = lex();
}

I got confuse about how this match function get compiled on gnu gcc. So I wrote a function that looks like

int a(token)
int token;
{
 printf("Value of token is %d", token);
}
int main()
{
 printf("Hello world!\n");
 a(1);
 return 0;
}

And I am getting following output-

Hello world! Value of token is 1

But I dont getting the reason behind that function declaration. What the benefit of declaring function this way? And how the value of token being 1? Why its not a compile error? Is it some kind of function declaration in C?

Thanks for checking my question. Any kind of help will be great.


Source: (StackOverflow)

Call function inside __construct with php

A simple PHP problem I couldn't find the answer to.

Is it possible to call a function from the "__construct()"?

For example if I use the My_Controller solution here. If I add my own function below, like if I have a more advanced auth, can I call it from the construct?


Source: (StackOverflow)

Java equivalent of Python's "construct" library

Is there a Java equivalent of Python's "construct" library? I want to write "structs" like so:

message = Struct("message",
    UBInt8("protocol"),
    UBInt16("length"),
    MetaField("data", lambda ctx: ctx["length"])
)

It doesn't have to specifically be a library with some sort of abstraction using the Java language. I mean, it could be a "portable" format, with an API for parsing the documents. I guess this could work out with XML, but it would be be a lot more ugly.

I realize I could just inter-operate with Python, but I don't want to do that.


Source: (StackOverflow)