Rectangle 27 45

For Rails 3 and 4, since you are using the helper from a controller you can use the view_context

# in the controller code
view_context.link_to '...', '...'

# instead of using your mixin code 
link_to '...', '...'

For Rails 2, since you are using the helper from a controller you can actually access the @template member variable of the controller, the @template is the view and already has the UrlHelper mixed in

# in the controller code
@template.link_to '...', '...'

# instead of using your mixin code 
link_to '...', '...'

if you need to use the urlhelper from code other than the controller, your solution is probably the way to go

@TylerCollier - maybe this has changed with rails 3? it worked on 2

helpers - How to mixin and call link_to from controller in Rails? - St...

ruby-on-rails helpers actionview link-to mixins
Rectangle 27 27

You're using the flash helper from seyhunak's twitter-bootstrap-rails gem. Instead of using the helper, you can set up the code yourself and see how everything works.

Rails uses :notice and :alert as flash message keys. Twitter Bootstrap provides a base class .alert with additional classes .alert-success and .alert-error (see the Bootstrap documentation on alerts). A bit of parsing is required to get a Rails notice message to be styled with the Twitter Bootstrap alert-success style. Any other message, including a Rails alert message, will be styled with the Twitter Bootstrap alert-error style.

By default, Twitter Bootstrap applies a green background to .alert-success and a red background to .alert-error. Twitter Bootstrap provides a third class .alert-info with a blue background. With a little hacking, its possible to create a Rails flash message with a custom name, such as :info, that will display with the Bootstrap .alert-info class. However, its wise to stick with the Rails convention of using only alert and notice. Earlier versions of Rails used "error" but the current practice is to use "alert" instead of "error."

You can include code to display flash messages directly in your application layout file or you can create a partial. Here's an example with a partial.

First, what goes in the application layout:

# app/views/layouts/application.html.erb 
.
.
.
<%= render 'layouts/messages' %>
.
.
.

Next, the partial that gets included in the application layout:

# app/views/layouts/_messages.html.erb
# Rails flash messages styled for Bootstrap 3.0
# works with Rails 4.0 or Rails 4.1
<% flash.each do |name, msg| %>
  <% if msg.is_a?(String) %>
    <div class="alert alert-<%= name.to_s == 'notice' ? 'success' : 'danger' %>">
      <button type="button" class="close" data-dismiss="alert" aria-hidden="true">&times;</button>
      <%= content_tag :div, msg, :id => "flash_#{name}" %>
    </div>
  <% end %>
<% end %>

And an example of setting two different flash messages in a controller:

class VisitorsController < ApplicationController

  def new
    flash[:notice] = 'Welcome!'
    flash[:alert] = 'My birthday is soon.'
  end

end

For an alternative that accommodates four different flash message types (success, error, alert, notice), see an example of Rails Flash Messages using Twitter Bootstrap.

Here's a link to my Rails Bootstrap example app on GitHub which contains the flash message code. It may help to clone the example and check it as a reference implementation.

How about if I want to have it work with ajax?

Should probably be "danger" instead of "error" as alert-error is not a bootstrap class

Doug, thanks for pointing that out. I've updated the code for Bootstrap 3.0 and it works with Rails 4.0 or Rails 4.1.

How to define Flash Notifications with Twitter Bootstrap Rails gem - S...

ruby-on-rails ruby-on-rails-3 twitter-bootstrap flash-message
Rectangle 27 11

This situation is where Task, async, and await really shine. Here's the same example, refactored to take full advantage of async (it also uses some helper classes from my AsyncEx library to clean up the mapping code):

// First, a base class that takes care of the Task -> IAsyncResult mapping.
// In .NET 4.5, you would use HttpTaskAsyncHandler instead.
public abstract class HttpAsyncHandlerBase : IHttpAsyncHandler
{
    public abstract Task ProcessRequestAsync(HttpContext context);

    IAsyncResult IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, object extraData)
    {
        var task = ProcessRequestAsync(context);
        return Nito.AsyncEx.AsyncFactory.ToBegin(task, cb, extraData);
    }

    void EndProcessRequest(IAsyncResult result)
    {
        Nito.AsyncEx.AsyncFactory.ToEnd(result);
    }

    void ProcessRequest(HttpContext context)
    {
        EndProcessRequest(BeginProcessRequest(context, null, null));
    }

    public virtual bool IsReusable
    {
        get { return true; }
    }
}

// Now, our (async) Task implementation
public class MyAsyncHandler : HttpAsyncHandlerBase
{
    public override async Task ProcessRequestAsync(HttpContext context)
    {
        using (var webClient = new WebClient())
        {
            var data = await webClient.DownloadDataTaskAsync("http://my resource");
            context.Response.ContentType = "text/xml";
            context.Response.OutputStream.Write(data, 0, data.Length);
        }
    }
}

(As noted in the code, .NET 4.5 has a HttpTaskAsyncHandler which is similar to our HttpAsyncHandlerBase above).

The really cool thing about async is that it doesn't take any threads while doing the background operation:

  • An ASP.NET request thread kicks off the request, and it starts downloading using the WebClient.
  • While the download is going, the await actually returns out of the async method, leaving the request thread. That request thread is returned back to the thread pool - leaving 0 (zero) threads servicing this request.
  • When the download completes, the async method is resumed on a request thread. That request thread is briefly used just to write the actual response.

This is the optimal threading solution (since a request thread is required to write the response).

The original example also uses threads optimally - as far as the threading goes, it's the same as the async-based code. But IMO the async code is easier to read.

async

An ASP.NET request thread kicks off the request, and it starts downloading using the WebClient. -----well only for IO operations which the drivers do the work and then later it is tranferd to a threadpool thread. if it doesnt use IO operations , there will(!!!!) be a background thread to do the operations.

@RoyiNamir: A background thread is only used if you explicitly request one (e.g., Task.Run). With only a handful of exceptions (e.g., asynchronously reading from a MemoryStream), the BCL will never do this on your behalf. So it's really easy to avoid unnecessary background threads - just don't use them!

You wrote : "The really cool thing about async is that it doesn't take any threads while doing the background operation:".......and Im just saying that it does take a background thread , unless you use IO asynchronous methods (e.g. FileStream.BeginRead ). this will not tie a thread ....while downloading regularly --- will tie a thread ( background thread)

Not sure what you're getting at. A WebClient download using DownloadDataTaskAsync does not take a background thread.

async - by itself - will not use any background threads. Unless you explicitly tell it to by calling Task.Run.

asp.net - Using Task or async/await in IHttpAsyncHandler - Stack Overf...

asp.net threadpool task-parallel-library async-await ihttpasynchandler
Rectangle 27 206

The best use case I can think of is in caching AJAX responses. Here's a modified example from Rebecca Murphey's intro post on the topic:

var cache = {};

function getData( val ){

    // return either the cached value or jqXHR object wrapped Promise
    return $.when(
        cache[ val ] || 
        $.ajax('/foo/', {
            data: { value: val },
            dataType: 'json',
            success: function( resp ){
                cache[ val ] = resp;
            }
        })
    );
}

getData('foo').then(function(resp){
    // do something with the response, which may
    // or may not have been retrieved using an
    // XHR request.
});

Basically, if the value has already been requested once before it's returned immediately from the cache. Otherwise, an AJAX request fetches the data and adds it to the cache. The $.when/.then doesn't care about any of this; all you need to be concerned about is using the response, which is passed to the .then() handler in both cases. jQuery.when() handles a non-Promise/Deferred as a Completed one, immediately executing any .done() or .then() on the chain.

Deferreds are perfect for when the task may or may not operate asynchronously, and you want to abstract that condition out of the code.

Another real world example using the $.when helper:

$.when($.getJSON('/some/data/'), $.get('template.tpl')).then(function (data, tmpl) {

    $(tmpl) // create a jQuery object out of the template
    .tmpl(data) // compile it
    .appendTo("#target"); // insert it into the DOM

});

Two brilliants examples. I implemented something similar to the 2nd one, but with 4 ajax requests, and it performs well, in addition to be far more legible, compact, logic, maintainable, etc. jQuery.Deferred is a real good thing.

Caching will not work if the result is falsy value. Also I don't like the fact getData returns 2 different types depending on the branch taken.

I dont understand how the first code example even works: I understand the case where the object is not cached, but if it is then wont cache[ val ] NOT return a promise (the jquery documentation says that the parameter is the data returned by the sender) meaning that the member access of .then will error...right? What am I missing?

javascript - How can jQuery deferred be used? - Stack Overflow

javascript jquery jquery-deferred
Rectangle 27 206

The best use case I can think of is in caching AJAX responses. Here's a modified example from Rebecca Murphey's intro post on the topic:

var cache = {};

function getData( val ){

    // return either the cached value or jqXHR object wrapped Promise
    return $.when(
        cache[ val ] || 
        $.ajax('/foo/', {
            data: { value: val },
            dataType: 'json',
            success: function( resp ){
                cache[ val ] = resp;
            }
        })
    );
}

getData('foo').then(function(resp){
    // do something with the response, which may
    // or may not have been retrieved using an
    // XHR request.
});

Basically, if the value has already been requested once before it's returned immediately from the cache. Otherwise, an AJAX request fetches the data and adds it to the cache. The $.when/.then doesn't care about any of this; all you need to be concerned about is using the response, which is passed to the .then() handler in both cases. jQuery.when() handles a non-Promise/Deferred as a Completed one, immediately executing any .done() or .then() on the chain.

Deferreds are perfect for when the task may or may not operate asynchronously, and you want to abstract that condition out of the code.

Another real world example using the $.when helper:

$.when($.getJSON('/some/data/'), $.get('template.tpl')).then(function (data, tmpl) {

    $(tmpl) // create a jQuery object out of the template
    .tmpl(data) // compile it
    .appendTo("#target"); // insert it into the DOM

});

Two brilliants examples. I implemented something similar to the 2nd one, but with 4 ajax requests, and it performs well, in addition to be far more legible, compact, logic, maintainable, etc. jQuery.Deferred is a real good thing.

Caching will not work if the result is falsy value. Also I don't like the fact getData returns 2 different types depending on the branch taken.

I dont understand how the first code example even works: I understand the case where the object is not cached, but if it is then wont cache[ val ] NOT return a promise (the jquery documentation says that the parameter is the data returned by the sender) meaning that the member access of .then will error...right? What am I missing?

javascript - How can jQuery deferred be used? - Stack Overflow

javascript jquery jquery-deferred
Rectangle 27 2

I had the same problem and I solved using a helper. Try this on your css:

background-image: image-url("hero-000.jpg");

Unfortunately I have tried that but it didn't solve the problem.

Did you run heroku run bash on your terminal?

ruby on rails - CSS Background Images Not Showing in Heroku - Stack Ov...

css ruby-on-rails heroku
Rectangle 27 27

Here is the binary equivalent of COPY FROM for Python 3:

from io import BytesIO
from struct import pack
import psycopg2

# Two rows of data; "id" is not in the upstream data source
# Columns: node, ts, val1, val2
data = [(23253, 342, -15.336734, 2494627.949375),
        (23256, 348, 43.23524, 2494827.949375)]

conn = psycopg2.connect("dbname=mydb user=postgres")
curs = conn.cursor()

# Determine starting value for sequence
curs.execute("SELECT nextval('num_data_id_seq')")
id_seq = curs.fetchone()[0]

# Make a binary file object for COPY FROM
cpy = BytesIO()
# 11-byte signature, no flags, no header extension
cpy.write(pack('!11sii', b'PGCOPY\n\377\r\n\0', 0, 0))

# Columns: id, node, ts, val1, val2
# Zip: (column position, format, size)
row_format = list(zip(range(-1, 4),
                      ('i', 'i', 'h', 'f', 'd'),
                      ( 4,   4,   2,   4,   8 )))
for row in data:
    # Number of columns/fields (always 5)
    cpy.write(pack('!h', 5))
    for col, fmt, size in row_format:
        value = (id_seq if col == -1 else row[col])
        cpy.write(pack('!i' + fmt, size, value))
    id_seq += 1  # manually increment sequence outside of database

# File trailer
cpy.write(pack('!h', -1))

# Copy data to database
cpy.seek(0)
curs.copy_expert("COPY num_data FROM STDIN WITH BINARY", cpy)

# Update sequence on database
curs.execute("SELECT setval('num_data_id_seq', %s, false)", (id_seq,))
conn.commit()

I rewrote the above approach to writing the files for COPY. My data in Python is in NumPy arrays, so it makes sense to use these. Here is some example data with with 1M rows, 7 columns:

import psycopg2
import numpy as np
from struct import pack
from io import BytesIO
from datetime import datetime

conn = psycopg2.connect("dbname=mydb user=postgres")
curs = conn.cursor()

# NumPy record array
shape = (7, 2000, 500)
print('Generating data with %i rows, %i columns' % (shape[1]*shape[2], shape[0]))

dtype = ([('id', 'i4'), ('node', 'i4'), ('ts', 'i2')] +
         [('s' + str(x), 'f4') for x in range(shape[0])])
data = np.empty(shape[1]*shape[2], dtype)
data['id'] = np.arange(shape[1]*shape[2]) + 1
data['node'] = np.tile(np.arange(shape[1]) + 1, shape[2])
data['ts'] = np.repeat(np.arange(shape[2]) + 1, shape[1])
data['s0'] = np.random.rand(shape[1]*shape[2]) * 100
prv = 's0'
for nxt in data.dtype.names[4:]:
    data[nxt] = data[prv] + np.random.rand(shape[1]*shape[2]) * 10
    prv = nxt
CREATE TABLE num_data_binary
(
  id integer PRIMARY KEY,
  node integer NOT NULL,
  ts smallint NOT NULL,
  s0 real,
  s1 real,
  s2 real,
  s3 real,
  s4 real,
  s5 real,
  s6 real
) WITH (OIDS=FALSE);
num_data_text

Here are some simple helper functions to prepare the data for COPY (both text and binary formats) by using the information in the NumPy record array:

def prepare_text(dat):
    cpy = BytesIO()
    for row in dat:
        cpy.write('\t'.join([repr(x) for x in row]) + '\n')
    return(cpy)

def prepare_binary(dat):
    pgcopy_dtype = [('num_fields','>i2')]
    for field, dtype in dat.dtype.descr:
        pgcopy_dtype += [(field + '_length', '>i4'),
                         (field, dtype.replace('<', '>'))]
    pgcopy = np.empty(dat.shape, pgcopy_dtype)
    pgcopy['num_fields'] = len(dat.dtype)
    for i in range(len(dat.dtype)):
        field = dat.dtype.names[i]
        pgcopy[field + '_length'] = dat.dtype[i].alignment
        pgcopy[field] = dat[field]
    cpy = BytesIO()
    cpy.write(pack('!11sii', b'PGCOPY\n\377\r\n\0', 0, 0))
    cpy.write(pgcopy.tostring())  # all rows
    cpy.write(pack('!h', -1))  # file trailer
    return(cpy)

This how I'm using the helper functions to benchmark the two COPY format methods:

def time_pgcopy(dat, table, binary):
    print('Processing copy object for ' + table)
    tstart = datetime.now()
    if binary:
        cpy = prepare_binary(dat)
    else:  # text
        cpy = prepare_text(dat)
    tendw = datetime.now()
    print('Copy object prepared in ' + str(tendw - tstart) + '; ' +
          str(cpy.tell()) + ' bytes; transfering to database')
    cpy.seek(0)
    if binary:
        curs.copy_expert('COPY ' + table + ' FROM STDIN WITH BINARY', cpy)
    else:  # text
        curs.copy_from(cpy, table)
    conn.commit()
    tend = datetime.now()
    print('Database copy time: ' + str(tend - tendw))
    print('        Total time: ' + str(tend - tstart))
    return

time_pgcopy(data, 'num_data_text', binary=False)
time_pgcopy(data, 'num_data_binary', binary=True)

Here is the output from the last two time_pgcopy commands:

Processing copy object for num_data_text
Copy object prepared in 0:01:15.288695; 84355016 bytes; transfering to database
Database copy time: 0:00:37.929166
        Total time: 0:01:53.217861
Processing copy object for num_data_binary
Copy object prepared in 0:00:01.296143; 80000021 bytes; transfering to database
Database copy time: 0:00:23.325952
        Total time: 0:00:24.622095

So both the NumPy file and file database steps are way faster with the binary approach. The obvious difference is how Python prepares the COPY file, which is really slow for text. Generally speaking, the binary format loads into the database in 2/3 of the time as the text format for this schema.

Lastly, I compared the values in both tables within the database to see if the numbers were different. About 1.46% of the rows have different values for column s0, and this fraction increases to 6.17% for s6 (probably related on the random method that I used). The non-zero absolute differences between all 70M 32-bit float values range between 9.3132257e-010 and 7.6293945e-006. These small differences between the text and binary loading methods are due to the loss of precision from the float text float conversions required for the text format method.

Pretty cool. Did you write that yourself of get it from somewhere? And does it actually improve performance?

If it works, cool! Format aside, the solution however is to use psycopg's copy_expert().

@Erwin, yes I programmed it using the excellent docs for copy, struct and dtype. Benchmarks are in, and are looking good.

@MikeToews I have noticed one thing in your code, that you have got value of sequence then updated its value back again, or solution could be to define sql as COPY table(column1,column2) FROM STDIN WITH BINARY. Is there any special reason to do so. am using method by defining column names, this command works on terminal but do nothing in copy_expert.

I created a gem around this for ruby. Most of the data types are supported. github.com/pbrumm/pg_data_encoder

python - Use binary COPY table FROM with psycopg2 - Stack Overflow

python postgresql bulkinsert binary-data psycopg2
Rectangle 27 7

It is an interesting point, if a word becomes 'boilerplate' in names then its probably a bit whiffy - if not quite a real smell. Perhaps using a 'Helper' folder and then allowing it to appear in the namespace keeps its use without overusing the word?

Application.Helper.SharePoint
Application.Helper.Authentication

language agnostic - Is the word "Helper" in a class name a code smell?...

class language-agnostic helper naming
Rectangle 27 15

This is very possible if you write your own helper. We are using a custom $ helper to accomplish this type of interaction (and more):

/*///////////////////////

Adds support for passing arguments to partials. Arguments are merged with 
the context for rendering only (non destructive). Use `:token` syntax to 
replace parts of the template path. Tokens are replace in order.

USAGE: {{$ 'path.to.partial' context=newContext foo='bar' }}
USAGE: {{$ 'path.:1.:2' replaceOne replaceTwo foo='bar' }}

///////////////////////////////*/

Handlebars.registerHelper('$', function(partial) {
    var values, opts, done, value, context;
    if (!partial) {
        console.error('No partial name given.');
    }
    values = Array.prototype.slice.call(arguments, 1);
    opts = values.pop();
    while (!done) {
        value = values.pop();
        if (value) {
            partial = partial.replace(/:[^\.]+/, value);
        }
        else {
            done = true;
        }
    }
    partial = Handlebars.partials[partial];
    if (!partial) {
        return '';
    }
    context = _.extend({}, opts.context||this, _.omit(opts, 'context', 'fn', 'inverse'));
    return new Handlebars.SafeString( partial(context) );
});

To have access to the passed arguments, you need to look for them into the 'hash' object: {{hash.foo}}. (I'm new with handlebars and this took me a while to figure out) - Thanks, great helper!

Note, this requires you to have your partials pre-compiled before using the helper. I'm using Handlebars in node.js, and found that this wasn't always the case (the partials were compiled on demand). I had to add a simple helper to pre-compile partials after they were loaded, then this worked great!

@Dan any chance you could share that helper? :)

hbs.registerPartials(path.join(__dirname, '/views/partials'), function() {     	utils.precompileHandlebarsPartials(hbs);     });              // Pre compile the partials      	precompileHandlebarsPartials : function(hbs) {     		var partials = hbs.handlebars.partials;     		for (var partial in partials) {     			if (typeof partials[partial] === 'string') {     				partials[partial] = hbs.handlebars.compile(partials[partial]);     			}     		};     	}

@Dan Probably better to add it as its own answer.

javascript - Passing variables through handlebars partial - Stack Over...

javascript html handlebars.js templating
Rectangle 27 13

This is dead easy to do. I built the following convenience wrappers. They are structured so that you can construct an assembly from fragments of source code defining methods or expressions and invoke them by name using the helper methods of DynamicCodeManager.

The code is compiled on demand in response to invocation. Adding more methods will cause automatic recompilation on next invocation.

You provide only a method body. If you don't want to return a value then return null and don't bother to use the object returned by InvokeMethod.

If you use this in commercial code do me a favour and credit my work. The real jewel in this library is the invocation support. Getting the code to compile isn't the problem, it's invocation. It's quite tricky to get reflection to correctly match the method signature when you have a variable length parameter list. This is the reason for the existence of DynamicBase: the compiler resolves method binding to this explicitly declared base class giving us access to the right VMT. From there on in it all comes out in the wash.

I should also point out that this capability makes your desktop application vulnerable to script injection attacks. You should either take great care to vet the origin of script or reduce the trust level under which the generated assembly runs.

using System.Reflection;

namespace Dynamo
{
  public abstract class DynamicBase
  {
    public bool EvaluateCondition(string methodName, params object[] p)
    {
      methodName = string.Format("__dm_{0}", methodName);
      BindingFlags flags = BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic;
      return (bool)GetType().InvokeMember(methodName, flags, null, this, p);
    }
    public object InvokeMethod(string methodName, params object[] p)
    {
      BindingFlags flags = BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic;
      return GetType().InvokeMember(methodName, flags, null, this, p);
    }
    public double Transform(string functionName, params object[] p)
    {
      functionName = string.Format("__dm_{0}", functionName);
      BindingFlags flags = BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.NonPublic;
      return (double)GetType().InvokeMember(functionName, flags, null, this, p);
    }
  }
}
using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Text;
using Microsoft.CSharp;

namespace Dynamo
{
  public static class DynamicCodeManager
  {
    #region internal statics and constants
    static Dictionary<string, string> _conditionSnippet = new Dictionary<string, string>();
    static Dictionary<string, string> _methodSnippet = new Dictionary<string, string>();
    static string CodeStart = "using System;\r\nusing System.Collections.Generic;\r\n//using System.Linq;\r\nusing System.Text;\r\nusing System.Data;\r\nusing System.Reflection;\r\nusing System.CodeDom.Compiler;\r\nusing Microsoft.CSharp;\r\nnamespace Dynamo\r\n{\r\n  public class Dynamic : DynamicBase\r\n  {\r\n";
    static string DynamicConditionPrefix = "__dm_";
    static string ConditionTemplate = "    bool {0}{1}(params object[] p) {{ return {2}; }}\r\n";
    static string MethodTemplate = "    object {0}(params object[] p) {{\r\n{1}\r\n    }}\r\n";
    static string CodeEnd = "  }\r\n}";
    static List<string> _references = new List<string>("System.dll,System.dll,System.Data.dll,System.Xml.dll,mscorlib.dll,System.Windows.Forms.dll".Split(new char[] { ',' }));
    static Assembly _assembly = null;
    #endregion

    public static Assembly Assembly { get { return DynamicCodeManager._assembly; } }

    #region manage snippets
    public static void Clear()
    {
      _methodSnippet.Clear();
      _conditionSnippet.Clear();
      _assembly = null;
    }
    public static void Clear(string name)
    {
      if (_conditionSnippet.ContainsKey(name))
      {
        _assembly = null;
        _conditionSnippet.Remove(name);
      }
      else if (_methodSnippet.ContainsKey(name))
      {
        _assembly = null;
        _methodSnippet.Remove(name);
      }
    }

    public static void AddCondition(string conditionName, string booleanExpression)
    {
      if (_conditionSnippet.ContainsKey(conditionName))
        throw new InvalidOperationException(string.Format("There is already a condition called '{0}'", conditionName));
      StringBuilder src = new StringBuilder(CodeStart);
      src.AppendFormat(ConditionTemplate, DynamicConditionPrefix, conditionName, booleanExpression);
      src.Append(CodeEnd);
      Compile(src.ToString()); //if the condition is invalid an exception will occur here
      _conditionSnippet[conditionName] = booleanExpression;
      _assembly = null;
    }

    public static void AddMethod(string methodName, string methodSource)
    {
      if (_methodSnippet.ContainsKey(methodName))
        throw new InvalidOperationException(string.Format("There is already a method called '{0}'", methodName));
      if (methodName.StartsWith(DynamicConditionPrefix))
        throw new InvalidOperationException(string.Format("'{0}' is not a valid method name because the '{1}' prefix is reserved for internal use with conditions", methodName, DynamicConditionPrefix));
      StringBuilder src = new StringBuilder(CodeStart);
      src.AppendFormat(MethodTemplate, methodName, methodSource);
      src.Append(CodeEnd);
      Trace.TraceError("SOURCE\r\n{0}", src);
      Compile(src.ToString()); //if the condition is invalid an exception will occur here
      _methodSnippet[methodName] = methodSource;
      _assembly = null;
    }
    #endregion

    #region use snippets
    public static object InvokeMethod(string methodName, params object[] p)
    {
      DynamicBase _dynamicMethod = null;
      if (_assembly == null)
      {
        Compile();
        _dynamicMethod = _assembly.CreateInstance("Dynamo.Dynamic") as DynamicBase;
      }
      return _dynamicMethod.InvokeMethod(methodName, p);
    }

    public static bool Evaluate(string conditionName, params object[] p)
    {
      DynamicBase _dynamicCondition = null;
      if (_assembly == null)
      {
        Compile();
        _dynamicCondition = _assembly.CreateInstance("Dynamo.Dynamic") as DynamicBase;
      }
      return _dynamicCondition.EvaluateCondition(conditionName, p);
    }

    public static double Transform(string functionName, params object[] p)
    {
      DynamicBase _dynamicCondition = null;
      if (_assembly == null)
      {
        Compile();
        _dynamicCondition = _assembly.CreateInstance("Dynamo.Dynamic") as DynamicBase;
      }
      return _dynamicCondition.Transform(functionName, p);
    }
    #endregion

    #region support routines
    public static string ProduceConditionName(Guid conditionId)
    {
      StringBuilder cn = new StringBuilder();
      foreach (char c in conditionId.ToString().ToCharArray()) if (char.IsLetterOrDigit(c)) cn.Append(c);
      string conditionName = cn.ToString();
      return string.Format("_dm_{0}",cn);
    }
    private static void Compile()
    {
      if (_assembly == null)
      {
        StringBuilder src = new StringBuilder(CodeStart);
        foreach (KeyValuePair<string, string> kvp in _conditionSnippet)
          src.AppendFormat(ConditionTemplate, DynamicConditionPrefix, kvp.Key, kvp.Value);
        foreach (KeyValuePair<string, string> kvp in _methodSnippet)
          src.AppendFormat(MethodTemplate, kvp.Key, kvp.Value);
        src.Append(CodeEnd);
        Trace.TraceError("SOURCE\r\n{0}", src);
        _assembly = Compile(src.ToString());
      }
    }
    private static Assembly Compile(string sourceCode)
    {
      CompilerParameters cp = new CompilerParameters();
      cp.ReferencedAssemblies.AddRange(_references.ToArray());
      cp.ReferencedAssemblies.Add(Assembly.GetExecutingAssembly().ManifestModule.FullyQualifiedName);
      cp.CompilerOptions = "/target:library /optimize";
      cp.GenerateExecutable = false;
      cp.GenerateInMemory = true;
      CompilerResults cr = (new CSharpCodeProvider()).CompileAssemblyFromSource(cp, sourceCode);
      if (cr.Errors.Count > 0) throw new CompilerException(cr.Errors);
      return cr.CompiledAssembly;
    }
    #endregion

    public static bool HasItem(string methodName)
    {
      return _conditionSnippet.ContainsKey(methodName) || _methodSnippet.ContainsKey(methodName);
    }
  }
}

I didn't check this yet, but it looks fantastic. Thanks for sharing. I am particuallry happy because I can provide only method body.

if (_assembly == null)     {         Compile();         _dynamicCondition = ...;     }     return _dynamicCondition.Transform(functionName, p);
_dynamicCondition = ...;
if{}

Also, CompilerException is not defined, so users of this code should define it themself.

Transform method looks unimplemented. You cannot add a dynamic function/method that is callable using Transform. Anyway this classes are fantastic! :)

Execute a string in C# 4.0 - Stack Overflow

c#
Rectangle 27 2

Here's one way to do it using a helper function that will account for days that do not have 24 observations.

library(xts)
xtime <- timeBasedSeq('2015-01-01/2015-01-30 23')
set.seed(21)
df <- xts(rnorm(length(xtime),30,4), xtime)

tHourly <- function(x) {
  # initialize result matrix for all 24 hours
  dnames <- list(format(index(x[1]), "%Y-%m-%d"),
                 paste0("H", 0:23))
  res <- matrix(NA, 1, 24, dimnames = dnames)
  # transpose day's rows and set colnames
  tx <- t(x)
  colnames(tx) <- paste0("H", .indexhour(x))
  # update result object and return
  res[,colnames(tx)] <- tx
  res
}
# split on days, apply tHourly to each day, rbind results
p_mat <- split(df, f="days", drop=FALSE, k=1)
p_list <- lapply(p_mat, tHourly)
p_hmat <- do.call(rbind, p_list)

Convert continuous time-series data into daily-hourly representation u...

r time-series xts zoo
Rectangle 27 1

You could loop through the properties on your ViewModel server side using a helper method.

public T ViewModelToUpper<T>(T viewModel) where T : class
{
    foreach (var property in viewModel.GetType().GetProperties())
    {
        var value = property.GetValue(viewModel, null);
        if (value is string)
        {
            property.SetValue(viewModel, value.ToString().ToUpper());
        }
    }

    return viewModel;
}

Then you can call viewModel = ClassName.ViewModelToUpper(viewModel). Now you don't have to worry about doing it for every string property as this will happen anyway.

asp.net mvc - force Uppercase using EditorFor Razor view - Stack Overf...

asp.net-mvc entity-framework
Rectangle 27 1

The short answer is: you can't using the helper. You have to build it by hand.

Interesting but I'm working with an ActionResult so I can't do the Url.Action in the backend part... seems like I will have to change things around.

c# - Use a list or array to build a query string in MVC3 - Stack Overf...

c# asp.net-mvc
Rectangle 27 2

Using the built-in features of robot

The robot framework user guide has a section titled Timestamping output files which describes how to do this.

All output files listed in this section can be automatically timestamped with the option --timestampoutputs (-T). When this option is used, a timestamp in the format YYYYMMDD-hhmmss is placed between the extension and the base name of each file. The example below would, for example, create such output files as output-20080604-163225.xml and mylog-20080604-163225.html:

To specify a folder, this too is documented in the user guide, in the section Output Directory, under Different Output Files:

...The default output directory is the directory where the execution is started from, but it can be altered with the --outputdir (-d) option. The path set with this option is, again, relative to the execution directory, but can naturally be given also as an absolute path...

You can write a script (in python, bash, powershell, etc) that performs two duties:

  • launches pybot with all the options you wan

You then just use this helper script instead of calling pybot directly.

robotframework - How to save Robot framework test run logs in some fol...

robotframework
Rectangle 27 6

This recursive function returns all dimensions of a given array or false if one or more dimensions are not straight (i.e. different sizes between array items). It uses a helper function to determine whether two simple arrays are the same (read the function comments before using it).

// pre: a !== b, each item is a scalar
function array_equals(a, b)
{
  return a.length === b.length && a.every(function(value, index) {
    return value === b[index];
  });
};

function getdim(arr)
{
  if (/*!(arr instanceof Array) || */!arr.length) {
    return []; // current array has no dimension
  }
  var dim = arr.reduce(function(result, current) {
    // check each element of arr against the first element
    // to make sure it has the same dimensions
    return array_equals(result, getdim(current)) ? result : false;
  }, getdim(arr[0]));

  // dim is either false or an array
  return dim && [arr.length].concat(dim);
}

console.log(getdim(123)); // []
console.log(getdim([1])); // [1]
console.log(getdim([1, 2])); // [2]
console.log(getdim([1, [2]])); // false
console.log(getdim([[1, 2], [3]])); // false
console.log(getdim([[1, 2],[1, 2]])); // [2, 2]
console.log(getdim([[1, 2],[1, 2],[1, 2]])); // [3, 2]

console.log(getdim([[[1, 2, 3],[1, 2, 4]],[[2, 1, 3],[4, 4, 6]]])); // [2, 2, 3]

console.log(getdim([[[1, 2, 3], [1, 2, 4]], [[2, 1], [4, 4]]])); // false

Also I've explicitly checked the parameter is an array, because the length property could be anything, not necessary an array (e.g. [{length:100},{length:200}] and this code screws up)

@AlvinWong Thanks for the feedback. I suppose the conditions should be strengthened if objects may occur; I've added it as a code comment though.

You finally decided that you cannot omit the part of comparing two arrays :P

How can I get the dimensions of a multidimensional Javascript array? -...

javascript arrays
Rectangle 27 51

Ok, so everything in CodeIgniter runs through the super-magic $this variable. This only works for classes, as $this basically defines the current class.

$this->load->model('whatever');

In models, you are also using a class. It is slightly different here, as $this only contains useful stuff as you are extending from Model. Still, $this is still valid.

When you are using a helper or a library, you need to find that "instance" or $this equivalent.

$ci =& get_instance();

makes $ci contain the exact same stuff/code/usefulness as $this, even though you are not in a class, or not in a class that inherits it.

2 pints, eh? Then what is the usefullness of a library/helper? Why not just use models?

Of course seeing as everything is a PHP class you CAN put whatever you like wherever you like. Generally speaking in CodeIgniter it is broken down as "database interaction/business logic" = models, simple functions go in helpers and general classes are libraries.

Codeigniter: Get Instance - Stack Overflow

codeigniter
Rectangle 27 269

A compiled list of possible sources of improvement are below:

  • Make use of a profiler to discover memory leaks and performance problems in your application. personally I suggest dotTrace
  • Run your site in Release mode, not Debug mode, when in production, and also during performance profiling. Release mode is much faster. Debug mode can hide performance problems in your own code.
  • Use CompiledQuery.Compile() recursively avoiding recompilation of your query expressions
OutputCacheAttribute
  • Utilize ETags and expiration - Write your custom ActionResult methods if necessary
  • Consider using the RouteName to organize your routes and then use it to generate your links, and try not to use the expression tree based ActionLink method.
  • Consider implementing a route resolution caching strategy
  • Put repetitive code inside your PartialViews, avoid render it xxxx times: if you end up calling the same partial 300 times in the same view, probably there is something wrong with that. Explanation And Benchmarks
  • Use Forms Authentication, Keep your frequently accessed sensitive data in the authentication ticket
  • Consider second level cache for your queries and add them an scope and a timeout i.e. NHibernate Second Cache
  • Optimize your client side, use a tool like YSlow for suggestions to improve performance
  • Use AJAX to update components of your UI, avoid a whole page update when possible.
  • Consider implement a pub-sub architecture -i.e. Comet- for content delivery against reload based in timeouts.
  • Move charting and graph generation logic to the client side if possible. Graph generation is a expensive activity. Deferring to the client side your server from an unnecessary burden, and allows you to work with graphs locally without make a new request (i.e. Flex charting, jqbargraph, MoreJqueryCharts).
  • Use CDN's for scripts and media content to improve loading on the client side (i.e. Google CDN)
  • Minify -Compile- your JavaScript in order to improve your script size
  • Keep cookie size small, since cookies are sent to the server on every request.

If you use Razor, add the following code in your global.asax.cs, by default, Asp.Net MVC renders with an aspx engine and a razor engine. This only uses the RazorViewEngine.

ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new RazorViewEngine());
<system.webServer>
    <urlCompression doDynamicCompression="true" doStaticCompression="true" dynamicCompressionBeforeCache="true"/>
 </system.webServer>
  • Flush your HTML as soon as it is generated (in your web.config) and disable viewstate if you are not using it <pages buffer="true" enableViewState="false">

wait you mean i do lose performance when i e.g. have a view that displays a result set by irritating through an IList and call Render.PartialView("Row", item) for each list item? how much do i lose? or how could i measure the performance gain?

@SDReyes - what is the meaning of pub-sub architecture?

This is cool. Uber Profiler link is dead though. Should this be linked to one of the ORM specific profilers instead?

.net - How do I improve ASP.NET MVC application performance? - Stack O...

.net asp.net-mvc performance iis
Rectangle 27 3

preorder(node)
  if node == null then return
  print node.value
  preorder(node.left) 
  preorder(node.right)

Using a stack to store the leaf nodes I added the values onto them and was able to transverse the stack and change into lea nodes.

the parse tree leafs using preorder would give me a stack of [+ 10 4]

Using a helper function I could convert this into a

parsing - Converting Parse Tree Into AST (Abstract Syntax Tree) C++ - ...

c++ parsing abstract-syntax-tree parse-tree
Rectangle 27 206

Custom Classes in Laravel 5, the Easy Way

Step 1: Create your Helpers (or other custom class) file and give it a matching namespace. Write your class and method:

<?php // Code within app\Helpers\Helper.php

namespace App\Helpers;

class Helper
{
    public static function shout(string $string)
    {
        return strtoupper($string);
    }
}
<?php // Code within config/app.php

    'aliases' => [
     ...
        'Helper' => App\Helpers\Helper::class,
     ...

Step 3: Use it in your Blade template:

<!-- Code within resources/views/template.blade.php -->

{!! Helper::shout('this is how to use autoloading correctly!!') !!}

Extra Credit: Use this class anywhere in your Laravel app:

<?php // Code within app/Http/Controllers/SomeController.php

namespace App\Http\Controllers;

use Helper;

class SomeController extends Controller
{

    public function __construct()
    {
        Helper::shout('now i\'m using my helper class in a controller!!');
    }
    ...

To be clear, this answer doesn't actually deal with helpers, which are global-namespaced functions. Instead, it encourages converting helpers to class methods. This is generally the best approach, but doesn't actually answer the question asked here, which is why other answers are so complex by comparison.

Function helper means it is available in Blade as well.How do you make this function available in blade? You cannot call Helper::prettyJason(parameters) in blade.

aliases
app/config.php
'Helper'  => App\Helpers\Helper::class,
Helper::prettyJson();

@DanHunsaker edited to directly answer the question, and it's still the same simple approach. You can also just write your own custom blade directives: stackoverflow.com/questions/28290332/

Yeah, I dug through the framework once and found where they pulled the helpers in. And again, I completely agree that methods of namespaced static classes are a much cleaner fit than what's being requested - or recommended - most of the time. The fact is, helpers aren't really The Laravel Way in the first place, but rather a holdover from CodeIgniter 2.x that still hasn't been phased out. So my pedantry about this approach not answering the OP exactly as asked is more an attempt to highlight the fact that you don't get helpers, but rather something better.

php - Best practices for custom helpers on Laravel 5 - Stack Overflow

php laravel laravel-5
Rectangle 27 2

C# can do indexed properties, but these must be implemented using a helper class which has an indexer. This method will work with early-bound VB but not with late-bound VB:

using System;


class MyClass {
    protected string get_MyProperty(string Param1, string Param2)
    {
        return "foo: " + Param1 + "; bar: " + Param2;
    }

    protected void set_MyProperty(string Param1, string Param2, string NewValue)
    {
        // nop
    }
    // Helper class
    public class MyPropertyAccessor {
        readonly MyClass myclass;
        internal MyPropertyAccessor(MyClass m){
            myclass = m;
        }
        public string this [string param1, string param2]{
             get {
                 return myclass.get_MyProperty(param1, param2);
             }
             set {
                 myclass.set_MyProperty(param1, param2, value);
             }
        }
    }
    public readonly MyPropertyAccessor MyProperty;
    public MyClass(){
        MyProperty = new MyPropertyAccessor(this);
    }
}


public class Program
{
    public static void Main()
    {
        Console.WriteLine("Hello World");

        var mc = new MyClass();
        Console.WriteLine(mc.MyProperty["a", "b"]);
    }

}

This is a workaround which takes advantage of two facts about VB. One is that in the array index operator is the same as the function call operator - round brackets (parens). The other is that VB will allow us to omit the name of the default property.

If the property is get-only, you don't need to bother with this. Just use a function, and this will behave the same as array access for late-bound code.

Using the two facts above, we can see that these are equivalent in VB

// VB Syntax: PropName could either be an indexed property or a function
varName = obj.PropName(index1).Value
obj.PropName(index1).Value = varName

// But if Value is the default property of obj.PropName(index1) 
// this is equivalent:
varName = obj.PropName(index1)
obj.PropName(index1) = varName

This means that instead of doing the this:

//Property => Object with Indexer
// C# syntax
obj.PropName[index1];

We can do this:

// C# syntax
obj.PropName(index1).Value

So here is the example code, with a single parameter.

class HasIndexedProperty {
    protected string get_PropertyName(int index1){
        // replace with your own implementation
        return string.Format("PropertyName: {0}", index1);
    }
    protected void set_PropertyName(int index1, string v){
        // this is an example - put your implementation here
    }
    // This line provides the indexed property name as a function.
    public string PropertyName(int index1){
        return new HasIndexedProperty_PropertyName(this, index1);
    }
    public class HasIndexedProperty_PropertyName{
        protected HasIndexedProperty _owner;
        protected int _index1;
        internal HasIndexedProperty_PropertyName(
            HasIndexedProperty owner, int index1){
            _owner = owner; _index1 = index1;
        }
        // This line makes the property Value the default
        [DispId(0)]
        public string Value{
            get {
                return _owner.get_PropertyName(_index1);
            }
            set {
                _owner.set_PropertyName(_index1, value);
            }
        }
    }
}

The limitation is that to work, this depends on the call being made in a context where the result is coerced to a non-object type. For example

varName = obj.PropName(99)

Since the Set keyword was not used, VB knows that it must get the default property for use here.

Again, when passing to a function which takes for example a string, this will work. Internally VariantChangeType will be called to convert the object to the correct type, which if coercing to a non-object will access the default property.

The problem may occur when passing directly as a parameter to a function which takes a Variant as an argument. In this case the accessor object will be passed. As soon as the object is used in a non-object context (e.g. an assignment or conversion to string) the default property will be fetched. However this will be the value at the time it is converted, not the time it was originally accessed. This may or may not be an issue.

This issue can be worked around however by having the accessor object cache the value it returns to ensure it is the value as at the time the accessor was created.

Thanks Ben. Unfortunately, the VB6 DLL property returns a Variant, which I'm converting to an object. As I said, the VB6 DLL is only ever used as late-bound, and the compatible DLL I'm trying to create will only be used late-bound as well. What I need is some way to tell the compiler to combine two methods (setter and getter) and have them look like a single parameterized property in COM when used by VB6.

You are correct, this doesn't work with late-bound VB. I have an alternative which does that I will post shortly.

OK I will add a fully generic version next, (object-typed Value, so only really suitable for late-bound code). You can easily expand on this with typed versions for the types you need.

Thanks again, Ben. This has been very helpful. I did run into another issue, however. I updated my original question with the issue, plus more of how I'm implementing the changes.

It has to be a method not a property for the reasons explained in the "workaround" section of the answer.

.net - How to make C# COM class support parameterized properties from ...

c# .net dll com vb6