text:
Q: I am having this referenced before assignment error in my code and I can't get it to work even after implementing the "global" [RESOLVED]
I can't seem to get it to work as I've done as they've said in [this post][1], it was previously working until I added the "BfToAA" section, which is a modified copy of the "BfToARN", I don't think I got any error as this global fix was enough for before, I leave all my code next for you to see and maybe give advice on making it work.
#This is my "main"
def ElegirCamino():

    #here you can input your brainF*ck code that is going to be translated
    print("Inserte usted su código en notación especificada en el  README.txt")
    códigoBf = input()

    #here the code is sent to be translated to ARN by the convention that I've made.
    i=0
    print("El anterior código traducido a ARN según los datos datos en el README.txt es:")
    while i<len(códigoBf):
        BfToARN(códigoBf[i], i)
        i += 1
    códigoARN = códigoARN + "UAA"
    print(códigoARN)

    #here the code is sent to be translated to nucleic acids by the convention that I've made.
    i=0
    print("Lo que en ácidos nucléicos es:")
    while i<len(códigoBf):
        BfToAA(códigoBf[i], i)
        i += 1
    códigoAA = códigoAA + "STOP"
    print(códigoAA)

def BfToARN(Bf, i):
    if i==0:
        global códigoARN
        códigoARN = "AUG"

    if(Bf == '+'):
        códigoARN = códigoARN + "UUU"
    elif(Bf == '-'):
        códigoARN = códigoARN + "UUA"
    elif(Bf == '.'):
        códigoARN = códigoARN + "UCU"
    elif(Bf == ','):
        códigoARN = códigoARN + "UAU"
    elif(Bf == '['):
        códigoARN = códigoARN + "UGU"
    elif(Bf == ']'):
        códigoARN = códigoARN + "UGG"
    elif(Bf == '<'):
        códigoARN = códigoARN + "CCU"
    elif(Bf == '>'):
        códigoARN = códigoARN + "CGU"
    else:
        print("    ERROR. Se esperaba uno de los caracteres del lenguaje Bf pero se ha encontrado un: \""+ Bf + "\"")

def BfToAA(Bf, i):
    if i==0:
        global códigoAA
        códigoAA = "Met "

    if(Bf == '+'):
        códigoAA = códigoAA + "Phe "
    elif(Bf == '-'):
        códigoAA = códigoAA + "Leu "
    elif(Bf == '.'):
        códigoAA = códigoAA + "Ser "
    elif(Bf == ','):
        códigoAA = códigoAA + "Tyr "
    elif(Bf == '['):
        códigoAA = códigoAA + "Cys "
    elif(Bf == ']'):
        códigoAA = códigoAA + "Trp "
    elif(Bf == '<'):
        códigoAA = códigoAA + "Pro "
    elif(Bf == '>'):
        códigoAA = códigoAA + "Arg "
    else:
        print("    ERROR. Se esperaba uno de los caracteres del lenguaje Bf pero se ha encontrado un: \""+ Bf + "\"")

ElegirCamino()

Thanks to everybody that anwsered and helped me understeand my mistakes here.
[1]: https://es.stackoverflow.com/questions/171863/local-variable-referenced-before-assignment

A: def BfToAA(Bf, i):
    global códigoAA

    if i==0:
        códigoAA = "Met "

you were assigning global in conditional statement which might not execute if condition is not true. Same with other functions as well

A: Your main mistake is assigning globals in the condition statement and not including the global keywords in your "main" function. I modified your code so that it runs. Take notice of where the global keyword is in both of the functions.

#This is my "main"
def ElegirCamino():
    global códigoARN
    global códigoAA
    #here you can input your brainF*ck code that is going to be translated
    print("Inserte usted su código en notación especificada en el  README.txt")
    códigoBf = input()

    #here the code is sent to be translated to ARN by the convention that I've made.
    i=0
    print("El anterior código traducido a ARN según los datos datos en el README.txt es:")
    while i<len(códigoBf):
        BfToARN(códigoBf[i], i)
        i += 1
    códigoARN = códigoARN + "UAA"
    print(códigoARN)

    #here the code is sent to be translated to nucleic acids by the convention that I've made.
    i=0
    print("Lo que en ácidos nucléicos es:")
    while i<len(códigoBf):
        BfToAA(códigoBf[i], i)
        i += 1
    códigoAA = códigoAA + "STOP"
    print(códigoAA)

def BfToARN(Bf, i):
    global códigoARN

    if i==0:
        códigoARN = "AUG"
    if(Bf == '+'):
        códigoARN = códigoARN + "UUU"
    elif(Bf == '-'):
        códigoARN = códigoARN + "UUA"
    elif(Bf == '.'):
        códigoARN = códigoARN + "UCU"
    elif(Bf == ','):
        códigoARN = códigoARN + "UAU"
    elif(Bf == '['):
        códigoARN = códigoARN + "UGU"
    elif(Bf == ']'):
        códigoARN = códigoARN + "UGG"
    elif(Bf == '<'):
        códigoARN = códigoARN + "CCU"
    elif(Bf == '>'):
        códigoARN = códigoARN + "CGU"
    else:
        print("    ERROR. Se esperaba uno de los caracteres del lenguaje Bf pero se ha encontrado un: \""+ Bf + "\"")

def BfToAA(Bf, i):
    global códigoAA
    if i==0:
        códigoAA = "Met "
    if(Bf == '+'):
        códigoAA = códigoAA + "Phe "
    elif(Bf == '-'):
        códigoAA = códigoAA + "Leu "
    elif(Bf == '.'):
        códigoAA = códigoAA + "Ser "
    elif(Bf == ','):
        códigoAA = códigoAA + "Tyr "
    elif(Bf == '['):
        códigoAA = códigoAA + "Cys "
    elif(Bf == ']'):
        códigoAA = códigoAA + "Trp "
    elif(Bf == '<'):
        códigoAA = códigoAA + "Pro "
    elif(Bf == '>'):
        códigoAA = códigoAA + "Arg "
    else:
        print("    ERROR. Se esperaba uno de los caracteres del lenguaje Bf pero se ha encontrado un: \""+ Bf + "\"")

ElegirCamino()

A: ElegirCamino() doesn't know anything about códigoARN and códigoAA
It should be something like this:

The difference between global and local variables is that global var can be accessed all over but local vars can not, but here's the trick you can use global in python to tell the function that you're in to reference to this global var and use it as its own local variable.
I recommend reading more on the topic because there's also other ways


text:
Q: combobox doesn't use vcl style highlight color. I'm using a combobox with the vcl styles enabled, but when i run the application the highlight color used by the combobox is the windows highlight color and not of the vcl styles.
How i can fix this, i mean use the vcl style highlight color in the combobox?

A: That should be one for RRUZ. :)
See his blog post: http://theroadtodelphi.wordpress.com/2012/03/14/vcl-styles-and-owner-draw/
(keep the rep for his soon-to-come answer, but you'll get a start ^_^)

A: As far i know, the only workaround for this issue, is ownerdraw the combobox
Try these steps

*

*Set the Style property of the combobox to csOwnerDrawFixed

*In the OnDrawItem event use the vcl styes methods to draw the combobox items.

Check this sample code
uses
 Vcl.Styles,
 Vcl.Themes,

procedure TForm115.ComboBox1DrawItem(Control: TWinControl; Index: Integer;
const
  ColorStates: array[Boolean] of TStyleColor = (scComboBoxDisabled, scComboBox);
  FontColorStates: array[Boolean] of TStyleFont = (sfComboBoxItemDisabled, sfComboBoxItemNormal);
var
  LStyles  : TCustomStyleServices;
begin
  LStyles  :=StyleServices;
  with Control as TComboBox do
  begin
    Canvas.Brush.Color := LStyles.GetStyleColor(ColorStates[Control.Enabled]);
    Canvas.Font.Color  := LStyles.GetStyleFontColor(FontColorStates[Control.Enabled]);

    if odSelected in State then
     Canvas.Brush.Color := LStyles.GetSystemColor(clHighlight);

    Canvas.FillRect(Rect) ;
    Canvas.TextOut(Rect.Left+2, Rect.Top, Items[Index]);
  end;
end;

For more info you can check this article Vcl Styles and Owner Draw. Also you can use the Vcl.Styles.OwnerDrawFix unit (part of the  vcl-styles-utils project) which incudes a set of owner draws routines for components like TListBox, TComboBox and TListView.

redpajama_set_name: RedPajamaStackExchange


text:
Q: In Laravel 5.2, why is the customized validator not able to get the correct value of a field that has been changed? I'm using before_or_equal for the start date and after_or_equal for the end date using these customized validators. The problem is that for example I purposely made the start date later than the end date and an error below the field is shown. I click the end date and its error also shows but I change it to a valid date that is after the start date. It turns green. But the error of the start date persists even if I click on its field. It is as if the before_or_equal being used on start date still reads the previous end date.
I have to change the start date to a different date for its error to disappear. Now this exactly isn't the right thing to happen.
What am I doing wrong here?
Validator::extend('after_or_equal', function($attribute, $value, $parameters, $validator) {
    $validator->addReplacer('after_or_equal', function ($message, $attribute, $rule, $parameters) use ($value) {
        $startDateName = $parameters[0];
        return str_replace(':start_date', request($startDateName), $message);
    });
    return strtotime($validator->getData()[$parameters[0]]) <= strtotime($value);
});

Validator::extend('before_or_equal', function($attribute, $value, $parameters, $validator) {
    $validator->addReplacer('before_or_equal', function ($message, $attribute, $rule, $parameters) use ($value) {
        $endDateName = $parameters[0];
        return str_replace(':end_date', request($endDateName), $message);
    });
    $endDateName = $parameters[0];
    if(request($endDateName) != null) {
      return strtotime($validator->getData()[$parameters[0]]) >= strtotime($value);
    } else {
      return true;
    }
});


text:
Q: Efficiently using Acora / Existence of results in iterator?
*

*I'm using the acora library in Python to try and search for multiple keywords in multiple strings.

*It has two functions I can use to search: findall and finditer

*findall returns a list of matches, a bit like an regex findall.

*finditer returns an iterator, finding the results one by one

>>> import acora
>>> builder = acora.AcoraBuilder('ab', 'bc', 'de')
>>> ac = builder.build()
>>> ac.findall('this-is-my-testing-phrase-which-has-ab-and-bc-and-de')
[('ab', 36), ('bc', 43), ('de', 50)]

*

*All I want to know is if there is a single match at all. I don't want to waste more processing power seeing if there's anything else like in findall. So the fact that ab is in there at all is good enough.

Can I find this with the iterator? Just see if theres at most one match?
I'm asking this because I just timed acora vs basic string matching with 2 nested loops and its 4 times slower, which seems ridiculous.

A: Just realized I can basically just loop through the iter object and break as soon as a result comes through.


text:
Q: Static hint in variable length arrays I'm a bit confused at the difference here, in C99:
int myfunc (int array[n], int n) { ... }

will not compile. As far as I know you must always put the reference to the array size first, so it has to be written:
int myfunc (int n, int array[n]) { ... }

But if you supply the static keyword, this works absolutely fine:
int myfunc (int array[static 1], int n) { ... }

This order if far preferable to me, as I'm used to having arrays come first in a function call, but why is this possible?
Edit: Realising that the third example isn't actually a VLA helps...
For reference, this was the piece of code I was looking at that led to the question:
int sum_array(int n, int m, int a[n][m])
{
  int i, j, sum = 0;
  for (i = 0; i < n; i++)
    for (j = 0; j < m; j++)
      sum += a[i][j];
  return sum;
}

A: The reason why
int myfunc (int n, int array[n]) { ... }

is valid and
int myfunc (int array[n], int n) { ... }

is not is due to the lexical scoping rules of C. An identifier cannot be used before it has been introduced in the scope. There are a few exceptions to this rule but this one is not one of them.
EDIT: here is the relevant paragraph of the C Standard:

(C99, 6.2.1p7) "Any other identifier has scope that begins just after the completion of its declarator."

This rule also applies to parameters declaration at function prototype scope.

A: The reason for error has already been explained to you: you have to declare n before you can use it in other declarations.
However, it is worth noting that none of these declarations actually declare variable length arrays, as you seem to believe.
It is true that syntax with [n] was first allowed in C99 and that it is formally a VLA declaration, but nevertheless in the given context all of these declarations declare array as a parameter of int * type, just like it has always been in C89/90. The [n] part is not a hint of any kind. The fact that you can use [n] in this declaration is indeed a side-effect of VLA support, but this is where any relationship with VLA ends. That [n] is simply ignored.
A "hint" declaration requires keyword static inside the []. So, your declaration with [static 1] is equivalent to classic int array[1] declaration (meaning that 1 is ignored and the parameter has type int *) except that it gives the compiler a hint that at least 1 element must exist at the memory location pointed by array.

A: It's because arrays must be declared with a constant value so you cannot create an array using a variable size and therefore cannot pass an array with a variable size. Also if it is just a single-dimension array you don't need to pass a value in at all, that is the point of passing in the second parameter to tell you the length of your array.
To get this to work properly just write the function header like this:
int myfunc (int myArray[], int n) {...}

The order shouldn't matter, but you cannot have the size of an array you are passing be variable it must be a constant value.

A: If you are using GCC and are willing to use some of their extensions, you can accomplish what you wish right here:
int myFunc (int len; /* notice the semicolon!! */ int data[len], int len)
{

}

The documentation for this extension (Variable Length Arrays) is here.
Please note that this extension is NOT available in clang for some reason, I'm not quite sure why, though.

A: EDIT: Derp, scope, of course.
My question is; why do you need to do it at all?  You're really getting a pointer anyway (you can't pass arrays to a function in C, they degrade to a pointer, regardless of the function's signature).  It helps to let the caller know the expected size of the input, but beyond that it is useless.  Since they are already passing the size, just use...
int myfunc(int arr[], size_t size) {
    // ...
}

Or
int myfunc(int *arr, size_t size) {
    // ...
}


text:
Q: Xamarin ContentView/View Lifecycle Version
Xamarin.Android 8.2
Xamarin.Forms 2.5
Short question
How do I, or should I let a ContentView know the life cycle state of its containing Page (e.g. Appearing, Disappearing, Sleeping)
Long question
I am learning how to create a reusable Xamarin ContentView. I decide to create a control <LabelCarousel/> that will display its children label one after another.
The problem is I have no idea how to stop the background timer that switches the content
Sample

Usage
<local:LabelCarousel>
    Hello
    Hola
</local:LabelCarousel>

Implementation
namespace XamarinStart.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    [ContentProperty("LabelContainer")]
    public partial class LabelCarousel : ContentView
    {
        [Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]
        [Description("Labels"), Category("Data")]
        public List<Element> LabelContainer { get; } = new List<Element>();

        private int _index = 0;
        private Timer _timer = new Timer(2000);

        public LabelCarousel ()
        {
            InitializeComponent ();

            _timer.Elapsed += TimerEvent;
            _timer.Start();

        }

        private void TimerEvent(object sender, ElapsedEventArgs e)
        {
            if (_index >= LabelContainer.Count)
            {
                _index = 0;
            }

            var selected = LabelContainer[_index++];
            ChangeLabel((Label)selected);
        }

        private void ChangeLabel(Label lbl)
        {
            Device.BeginInvokeOnMainThread(async () =>
            {
                await this.FadeTo(0);
                Content = lbl;
                await this.FadeTo(1);
            });
        }
    }
}

Problem
When I put this app into background, or push another activity on the top of this one, the timer is still running, wasting the CPU resource. Is there any good idea to let the reusable ContentView notified when the parent page changes the state?
Related Posts
https://forums.xamarin.com/discussion/38989/contentview-lifecycle
https://forums.xamarin.com/discussion/65140/we-need-a-way-for-contentview-and-viewcells-to-monitor-their-own-lifecycle
Thank you!

A: I figured out one possibility myself by using the class extension to add AttachLifecycleToPage method to all Element object.
Basically, the principle behind the extension is tracing up the Parent along the UI tree. However, when the ContentView is initiated (i.e., ctor is called), it may not be attached to a parent yet, or its parent (if any) is not attached to a page. That's why I listen to the PropertyChanged event of the Element whose Parent is temporarily null. Once the Element gets attached, the searching process continues.
Note that the AttachLifecycleToPage should not be synchronous in the Element ctor, which will causes a dead lock.
Extension code
namespace XamarinStart.Extensions
{
    public static class PageAwareExtension
    {
        public static void AttachLifecycleToPage(this Element element, EventHandler onAppearing = null,
            EventHandler onDisappearing = null)
        {
            var task = new Task(() =>
            {
                var page = GetPage(element);
                if (page == null)
                {
                    return;
                }

                if (onAppearing != null)
                {
                    page.Appearing += onAppearing;
                }

                if (onDisappearing != null)
                {
                    page.Disappearing += onDisappearing;
                }
            });
            task.Start();
            return;
        }
        public static Page GetPage(this Element element, int timeout = -1)
        {
            if (element is Page) return (Page)element;

            Element el = element;
            // go up along the UI tree
            do
            {
                if (el.Parent == null)
                {
                    // either not attached to any parent, or no intend to attach to any page (is that possible?)
                    var signal = new AutoResetEvent(false);
                    PropertyChangedEventHandler handler = (object sender, PropertyChangedEventArgs args) =>
                    {
                        // https://github.com/xamarin/Xamarin.Forms/blob/master/Xamarin.Forms.Core/Element.cs
                        // Setting Parent property is tracked
                        Element senderElement = (Element) sender;
                        if (args.PropertyName == "Parent" && senderElement.Parent != null)
                        {
                            signal.Set();
                        }
                    };
                    el.PropertyChanged += handler;

                    var gotSignal = signal.WaitOne(timeout);
                    if (!gotSignal)
                    {
                        throw new TimeoutException("Cannot find the parent of the element");
                    }

                    el.PropertyChanged -= handler;
                } // if parent is null

                el = el.Parent;

            } while (! (el is Page));

            return (Page) el;
        }
    }
}

Modified LabelCarousel
    public LabelCarousel ()
    {
        InitializeComponent ();

        _timer.Elapsed += TimerEvent;
        _timer.Start();

        this.AttachLifecycleToPage(OnAppearing, OnDisappearing);
    }
    private void OnDisappearing(object sender, EventArgs eventArgs)
    {
        _timer.Stop();
    }

    private void OnAppearing(object sender, EventArgs eventArgs)
    {
        _timer.Start();
    }

Well, I am not sure if this dirty hack can cause some side effect. I hope that eventually the official release will have the ContentView with full life cycle support.


text:
Q: React.js form validation with Joi-Browser not working as expected I'm trying to make a multi-step form using React.js and material UI. for validation purpose I am using Joi-Browser. But I am getting error from Joi while validation, stating that error: ValidationError: "value" must be an object
I am very new to React.js Please guide me what I am doing wrong here.
here what I have tried so far.
class ServiceRequestForm extends Component {

    state = {
        step: 1,
        service_category: [],
        user : [
            {
                full_name: '',
                address_one: '',
            }
        ],

        hasError: false
    }

     schema = Joi.object().keys({
        full_name: Joi.string().alphanum().min(3).max(100).required(),
        address_one: Joi.string().required(),

    });
    validate = () => {
        const result = Joi.validate(this.state.user, this.schema)
        console.log(result)
    }
    // Proceed to next step

    nextStep = () => {
        const { step } = this.state;
        this.setState({
            step: step + 1
        });
    }
    // Proceed to prev step

    prevStep = () => {
        const { step } = this.state;
        this.setState({
            step: step - 1
        });
    }

// handle select

    handleChange = (event)=> {
        this.setState(oldValues => ({
          ...oldValues,
          [event.target.name]: event.target.value,
        }));
      }
// handle input

     handleChangeInput = name => event => {
         this.setState({ [name]: event.target.value });
       };

    handleSubmit = ()=>{
          this.validate();
      }

    render() {

        const { step } = this.state;
        const { service_category } = this.state;

        const { full_name, address_one } = this.state.user;

        const values = { service_category,  full_name, address_one };

        switch (step) {
            case 1:
                return (
                    <CategoryForm
                        nextStep={this.nextStep}
                        handleChange={this.handleChange}
                        values={values}
                    />
                );
            case 2:
                return (
                    <AddressForm
                        prevStep={this.prevStep}
                        handleChangeInput={this.handleChangeInput}
                        handleSubmit={this.handleSubmit}
                        values={values}

                    />
                );
            case 3:
                return (
                    <ThankYouPage

                    />
                );

        }
    }
}

export default ServiceRequestForm;

// Category form
export default class CategoryForm extends Component {

    continue = e => {
        e.preventDefault();
        this.setState({ hasError: false });
        if (!this.props.values.service_category) {
            console.log(this.props.hasError);
            this.setState({ hasError: true });
        }
        else {
            this.props.nextStep();
        }

    }

    render() {

      const { handleChange, values, classes, nextStep, hasError } = this.props;

        return (

Select service you want

                <form>
                    <FormControl error={hasError}>

                        <Select
                            value={values.service_category}
                            onChange={handleChange}
                            inputProps={{
                                name: 'service_category'

                            }}

                        >
                            <MenuItem value="">
                                Select Category
                            </MenuItem>
                            <MenuItem value={10}>House Maid</MenuItem>
                            <MenuItem value={20}>Electricians</MenuItem>
                            <MenuItem value={30}>Plumber</MenuItem>
                        </Select>
                        <FormHelperText>Please select service category</FormHelperText>
                        {hasError && <FormHelperText>This is required!</FormHelperText>}
                    </FormControl>
                </form>

                <Button variant="contained" color="primary" onClick={this.continue}>Next</Button>

        )
    }
}

// address form
export default class AddressForm extends Component {

    back = e => {
        e.preventDefault();
        this.props.prevStep();
    }

    render() {

        const { handleChangeInput, values, classes, handleSubmit, prevStep, hasError, full_name } = this.props;

        return (

Address

                <TextField

                    label="Full Name"
                    //className={classes.textField}
                    value={values.full_name}
                    onChange={handleChangeInput('full_name')}
                    margin="normal"
                    variant="outlined"
                />

                <TextField

                    label="Address Line 1"
                    //className={classes.textField}
                    value={values.address_one}
                    onChange={handleChangeInput('address_one')}
                    margin="normal"
                    variant="outlined"
                />

                <Button variant="contained" color="primary" onClick={handleSubmit}>Submit</Button>
                <Button variant="contained" color="primary" onClick={prevStep}>Back</Button>

        );
    }
}

A: Schema can be just an object.
Try using like below.
{
full_name: Joi.string().alphanum().min(3).max(100).required(),
address_one: Joi.string().required(),
}

No need to specify
Joi.object().keys(


text:
Q: Android Retrofit library Okhtpp3 issue in Eclipse IDE I'm working on a Eclipse Project, in which I'm using Retrofit Library for REST API call, and  I'm facing "java.lang.NoClassDefFoundError:okhttp3.HttpUrl".Image1. I have added the needed libraries too Image3.
The same project works well in android studio if i add the libraries as a dependency and enable mutidex true.
But in eclipse i'm not getting the solution.
Can anyone hep me out?


text:
Q: How to configure memprof in a Rails 2.3.14 application? I have added these lines in my config/initializer
require 'memprof/middleware'
config.middlewares.use(Memprof::Middleware)

require 'memprof/tracer'
config.middleware.insert(0, Memprof::Tracer)

Getting this error
config/environments/development.rb:98:in `load_environment': undefined method `middlewares' for #<Rails::Configuration:0xb73dd47c> (NoMethodError)
    from /usr/lib/ruby/gems/1.8/gems/rails-2.3.14/lib/initializer.rb:386:in `load_environment'
    from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.14/lib/active_support/core_ext/kernel/reporting.rb:11:in `silence_warnings'
    from /usr/lib/ruby/gems/1.8/gems/rails-2.3.14/lib/initializer.rb:379:in `load_environment'
    from /usr/lib/ruby/gems/1.8/gems/rails-2.3.14/lib/initializer.rb:137:in `process'
    from /usr/lib/ruby/gems/1.8/gems/rails-2.3.14/lib/initializer.rb:113:in `send'
    from /usr/lib/ruby/gems/1.8/gems/rails-2.3.14/lib/initializer.rb:113:in `run'
    from /home/krunals/ms/trunk/2012-06-18-01-MangoApps/config/environment.rb:22
    from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:49:in `gem_original_require'
    from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:49:in `require'
    from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.14/lib/active_support/dependencies.rb:182:in `require'
    from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.14/lib/active_support/dependencies.rb:547:in `new_constants_in'
    from /usr/lib/ruby/gems/1.8/gems/activesupport-2.3.14/lib/active_support/dependencies.rb:182:in `require'
    from /usr/lib/ruby/gems/1.8/gems/rails-2.3.14/lib/commands/server.rb:84
    from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:49:in `gem_original_require'
    from /usr/local/lib/site_ruby/1.8/rubygems/custom_require.rb:49:in `require'
    from script/server:3

A: instead of
config.middlewares.use(Memprof::Middleware)

try
config.middleware.use(Memprof::Middleware)


text:
Q: Ant xmltask  creates an empty "xmlns" attribute value I have an XML file as follows:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<CustomObject>
</CustomObjects>

I apply the XMLTask attr in the following way:
<attr path="/CustomObject" attr="xmlns" value="test"/>

I expect the XML file to now include the attribute xmlns with the value "test"
The actual output is as follows:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<CustomObject xmlns="">
</CustomObjects>

Has anyone ran into this problem before? or has any indication as what may be the problem?

A: It looks like xmltask cannot create attributes with the name xmlns. This appears to be a known bug: #8 attr name="xmlns" does not work on Mac.
In XML, xmlns is a reserved attribute name. It refers to the default namespace. For more about default namespaces, see Namespace Defaulting in the Namespaces in XML 1.0 W3C Recommendation.
As an alternative solution, consider using XSLT to add a namespace to the root element.


text:
Q: LPC1788 microcontroller intermittently not sending USB messages I'm developing code for the NXP LPC1788 microcontroller, and part of my work is making the product based on it USB-compatible. Most of the legwork is done and in general communication over USB works almost as well as over CAN.
However, one of the issues I've been encountering is that, when producing a constant output of USB messages from the microcontroller that are sent pretty close together, some of these messages are occasionally dropped.
I'm using a custom driver I wrote based on WinUSB to receive the messages on the PC side, and I originally suspected that the problem was on the receiving end of things. However, using USBLyzer I'm now confident that the problem is on the sending side - the USBLyzer logs perfectly match logs produced from what I get out of WinUsb_ReadPipe().
The LPC1788 uses USB 2.0 Full Speed protocol and I've confirmed that information is being sent and received at around 12 MHz using a probe, which is what it should be.
The device is configured to make use of two endpoints: logical endpoint 2 IN and logical endpoint 2 OUT. Both of these are configured for bulk transfer with a maximum packet size of 64 bytes.
I would think that messages are being sent around 500-600 microseconds apart at the least (I've introduced an artificial 500 us delay in the thread and message transmission should take a lot less time than that). This is about what I got last week; I can't check now as my debugging tools are acting up.
This is the USB initialisation code for the microcontroller:
void USBInit()
{
  // Configure USB pins.
  PINSEL_ConfigPin(0, 29, 1); // USB_D+1
  PINSEL_ConfigPin(0, 30, 1); // USB_D-1
  PINSEL_ConfigPin(1, 18, 1); // USB_UP_LED1
  PINSEL_ConfigPin(2,  9, 1); // USB_CONNECT1
  PINSEL_ConfigPin(1, 30, 2); // USB_VBUS

  // Turn on power and clock
  CLKPWR_ConfigPPWR(CLKPWR_PCONP_PCUSB, ENABLE);

  PINSEL_SetPinMode(1, 30, PINSEL_BASICMODE_PLAINOUT);

  // Set DEV_CLK_EN and AHB_CLK_EN.
  LPC_USB->USBClkCtrl |= 0x12;

  // Wait until change is reflected in clock status register.
  while((LPC_USB->USBClkSt & 0x12) != 0x12);

  // Enable NVIC USB interrupts.
  NVIC_EnableIRQ(USB_IRQn);

  // Reset the USB.
  USBReset();

  // Set device address to 0x0 and enable device & connection.
  USBSetAddress(0);
}

This is the code used by the microcontroller to send messages via USB:
uint32_t USB_Send(uint32_t endpoint, uint8_t *pData, uint32_t count)
{
  // Convert into a form that can be sent successfully using USB.
  uint8_t data[USB_MAX_PACKET_SIZE];

  for(int i=0; i < count; i++)
  {
    data[i*2] = hex[(pData[i] >> 4)];
    data[(i*2)+1] = hex[(pData[i] & 0xF)];
  }

  return USBWriteEndpoint(endpoint, data, count*2);
}

uint32_t USBWriteEndpoint(uint32_t endpoint, uint8_t *pData, uint32_t count)
{
  uint32_t i;

  LPC_USB->Ctrl = ((endpoint & 0xF) << 2) | CTRL_WR_EN;

  LPC_USB->TxPLen = count;

  for(i=0; i < (count+3)/4; i++)
  {
    LPC_USB->TxData = *((__packed uint32_t *)pData);
    pData += 4;
  }

  LPC_USB->Ctrl = 0;
  USBValidateEndpoint(endpoint);
  return count;
}

void USBValidateEndpoint(uint32_t endpoint)
{
  writeSIEEndpointCommand(endpoint, CMD_VALID_BUF);
}

void writeSIECommandData(uint32_t cmd, uint32_t data)
{
  LPC_USB->DevIntClr = CCEMTY_INT;
  LPC_USB->CmdCode = cmd;
  while((LPC_USB->DevIntSt & CCEMTY_INT) == 0);
  LPC_USB->DevIntClr = CCEMTY_INT;
  LPC_USB->CmdCode = data;
  while((LPC_USB->DevIntSt & CCEMTY_INT) == 0);
}

EDIT
To give an idea of what's happening, this is a log file produced from my USB driver's receive function (the one from USBLyzer is practically identical):
0000030D000D
0000010D002D0004001B0024
0000000D0FFF001600310016
0000010D002D0004001F0028
0000020D00280028001B002D
0000030D0009
0000000D0FFF001600310016
0000010D002D0004001F0028
0000020D00280028001B002D
0000030D0009
0000010D002D0004001F0028
0000020D00280028001B002D
0000030D0009
0000010D002D0004001F0028
0000020D00280028001B002D
0000030D0009
0000010D002D0004001F0028
0000020D00280028001B002D
0000030D0009
0000000D0FFF001600310016
0000010D002D0004001F0028
0000020D00280028001B002D
0000030D0009
0000010D002D0004001F0028

I should be receiving messages in the following cycle:
0000000D...
0000010D...
0000020D...
0000030D...

You can see from this log that some of the messages in the cycle are getting skipped.
EDIT 2
Included below are excerpts from the raw and filtered capture logs produced by USBLyzer. The raw logs mostly consist of cancelled requests because my driver is poll-driven and uses a timeout.
Raw logs:
USBlyzer Report

Capture List

Type    Seq Time    Elapsed Duration    Request Request Details Raw Data    I/O C:I:E   Device Object   Device Name Driver Name IRP Status
START   0001    11:09:15.413
URB 0002    11:09:18.484    3.071197 s      Bulk or Interrupt Transfer  10 bytes data   30 30 30 30 30 30 31 46...  out 01:00:02    FFFFFA800FC98440h   USBPDO-11   usbhub  FFFFFA801142FAB0h
00000000  30 30 30 30 30 30 31 46 30 31                    0000001F01
URB 0003    11:09:18.484    3.071212 s      Bulk or Interrupt Transfer  64 bytes buffer     in  01:00:82    FFFFFA800FC98440h   USBPDO-11   usbhub  FFFFFA8010E965A0h
URB 0004-0002   11:09:18.484    3.071371 s  174 us  Bulk or Interrupt Transfer  10 bytes buffer     out 01:00:02    FFFFFA800FC98440h   USBPDO-11   usbhub  FFFFFA801142FAB0h   Success (Success)
URB 0005-0003   11:09:18.485    3.071586 s  374 us  Bulk or Interrupt Transfer          in  01:00:82    FFFFFA800FC98440h   USBPDO-11   usbhub  FFFFFA8010E965A0h   Cancelled (Canceled)
URB 0006    11:09:18.485    3.071608 s      Bulk or Interrupt Transfer  64 bytes buffer     in  01:00:82    FFFFFA800FC98440h   USBPDO-11   usbhub  FFFFFA8010E965A0h
URB 0007-0006   11:09:18.486    3.072582 s  974 us  Bulk or Interrupt Transfer          in  01:00:82    FFFFFA800FC98440h   USBPDO-11   usbhub  FFFFFA8010E965A0h   Cancelled (Canceled)
URB 0008    11:09:18.486    3.072603 s      Bulk or Interrupt Transfer  64 bytes buffer     in  01:00:82    FFFFFA800FC98440h   USBPDO-11   usbhub  FFFFFA8010E965A0h
URB 0009-0008   11:09:18.487    3.073598 s  996 us  Bulk or Interrupt Transfer          in  01:00:82    FFFFFA800FC98440h   USBPDO-11   usbhub  FFFFFA8010E965A0h   Cancelled (Canceled)
URB 0010    11:09:18.487    3.073630 s      Bulk or Interrupt Transfer  64 bytes buffer     in  01:00:82    FFFFFA800FC98440h   USBPDO-11   usbhub  FFFFFA8010E965A0h
URB 0011-0010   11:09:18.488    3.074601 s  970 us  Bulk or Interrupt Transfer          in  01:00:82    FFFFFA800FC98440h   USBPDO-11   usbhub  FFFFFA8010E965A0h   Cancelled (Canceled)
[...]
URB 2504-2501   11:09:19.734    4.320666 s  161 us  Bulk or Interrupt Transfer  14 bytes buffer     out 01:00:02    FFFFFA800FC98440h   USBPDO-11   usbhub  FFFFFA800CF662D0h   Success (Success)
URB 2505-2503   11:09:19.734    4.320785 s  192 us  Bulk or Interrupt Transfer  24 bytes data   30 30 30 30 30 30 30 44...  in  01:00:82    FFFFFA800FC98440h   USBPDO-11   usbhub  FFFFFA8010E965A0h   Success (Success)
00000000  30 30 30 30 30 30 30 44 30 46 46 46 30 30 31 36  0000000D0FFF0016
00000010  30 30 33 31 30 30 31 42                          0031001B

Filtered logs:
USBlyzer Report

Capture List

Type    Seq Time    Elapsed Duration    Request Request Details Raw Data    I/O C:I:E   Device Object   Device Name Driver Name IRP Status
URB 0004-0002   11:09:18.484    3.071371 s  174 us  Bulk or Interrupt Transfer  10 bytes buffer     out 01:00:02    FFFFFA800FC98440h   USBPDO-11   usbhub  FFFFFA801142FAB0h   Success (Success)
URB 2504-2501   11:09:19.734    4.320666 s  161 us  Bulk or Interrupt Transfer  14 bytes buffer     out 01:00:02    FFFFFA800FC98440h   USBPDO-11   usbhub  FFFFFA800CF662D0h   Success (Success)
URB 2505-2503   11:09:19.734    4.320785 s  192 us  Bulk or Interrupt Transfer  24 bytes data   30 30 30 30 30 30 30 44...  in  01:00:82    FFFFFA800FC98440h   USBPDO-11   usbhub  FFFFFA8010E965A0h   Success (Success)
00000000  30 30 30 30 30 30 30 44 30 46 46 46 30 30 31 36  0000000D0FFF0016
00000010  30 30 33 31 30 30 31 42                          0031001B
URB 2507-2506   11:09:19.734    4.321309 s  459 us  Bulk or Interrupt Transfer  24 bytes data   30 30 30 30 30 31 30 44...  in  01:00:82    FFFFFA800FC98440h   USBPDO-11   usbhub  FFFFFA8010E965A0h   Success (Success)
00000000  30 30 30 30 30 31 30 44 30 30 32 44 30 30 30 34  0000010D002D0004
00000010  30 30 31 46 30 30 32 44                          001F002D
URB 2511-2510   11:09:19.735    4.321931 s  311 us  Bulk or Interrupt Transfer  24 bytes data   30 30 30 30 30 32 30 44...  in  01:00:82    FFFFFA800FC98440h   USBPDO-11   usbhub  FFFFFA8010E965A0h   Success (Success)
00000000  30 30 30 30 30 32 30 44 30 30 32 38 30 30 32 38  0000020D00280028
00000010  30 30 31 42 30 30 33 31                          001B0031
URB 2513-2512   11:09:19.735    4.322306 s  332 us  Bulk or Interrupt Transfer  12 bytes data   30 30 30 30 30 33 30 44...  in  01:00:82    FFFFFA800FC98440h   USBPDO-11   usbhub  FFFFFA8010E965A0h   Success (Success)
00000000  30 30 30 30 30 33 30 44 30 30 30 44              0000030D000D
URB 2725-2724   11:09:19.840    4.426662 s  89 us   Bulk or Interrupt Transfer  24 bytes data   30 30 30 30 30 30 30 44...  in  01:00:82    FFFFFA800FC98440h   USBPDO-11   usbhub  FFFFFA8010E965A0h   Success (Success)
00000000  30 30 30 30 30 30 30 44 30 46 46 46 30 30 31 36  0000000D0FFF0016
00000010  30 30 33 31 30 30 31 42                          0031001B
URB 2727-2726   11:09:19.840    4.427183 s  471 us  Bulk or Interrupt Transfer  24 bytes data   30 30 30 30 30 31 30 44...  in  01:00:82    FFFFFA800FC98440h   USBPDO-11   usbhub  FFFFFA8010E965A0h   Success (Success)
00000000  30 30 30 30 30 31 30 44 30 30 32 44 30 30 30 34  0000010D002D0004
00000010  30 30 31 46 30 30 32 44                          001F002D
URB 2731-2730   11:09:19.841    4.427803 s  209 us  Bulk or Interrupt Transfer  24 bytes data   30 30 30 30 30 32 30 44...  in  01:00:82    FFFFFA800FC98440h   USBPDO-11   usbhub  FFFFFA8010E965A0h   Success (Success)
00000000  30 30 30 30 30 32 30 44 30 30 32 38 30 30 32 38  0000020D00280028
00000010  30 30 31 42 30 30 33 31                          001B0031

A: Do you have a hardware USB analyzer available? I'm not sure how USBLyzer works but I presume it is still using the Windows USB subsystem at the lowest levels. My experience with Windows USB subsystem has been that it is extremely bug-riddled - one particular example was when transferring data that is an exact multiple of the max frame size, it doesn't work. I'm not saying this is your exact problem - we had different symptoms from what you are reporting - but in your shoes I would look at a) changing the max amount of data your transmitting end will send in one frame so it's not an exact multiple of the frame size, and b) getting a hardware USB analyzer to see what is actually on the wire.

A: The problem might be the USB_IRQHandler interrupting your write function. That would leave the USB unexpected in a different state, thus the write fails.
You can temporary disable the IRQ as a workaround:
uint32_t USBWriteEndpoint(uint32_t endpoint, uint8_t *pData, uint32_t count)
{
  uint32_t i;
  NVIC_DisableIRQ(USB_IRQn);    // USB IRQ handlaer must not run ...
  LPC_USB->Ctrl = ((endpoint & 0xF) << 2) | CTRL_WR_EN;

  LPC_USB->TxPLen = count;

  for(i=0; i < (count+3)/4; i++)
  {
    LPC_USB->TxData = *((__packed uint32_t *)pData);
    pData += 4;
  }

  LPC_USB->Ctrl = 0;
  USBValidateEndpoint(endpoint);
  NVIC_EnableIRQ(USB_IRQn); // ... until we are here. Enable USB IRQ again
  return count;
}

A: I think I've managed to make some significant improvements in the way that the microcontroller sends USB messages.
On page 400 of the LPC178x/7x user manual, I saw a description for how to properly handle sending data from the device to the host using a bulk IN endpoint. It was pretty lucky that I eventually stumbled across it since it was within the DMA section of the chapter (and I'm not using DMA so until now I've ignored it).
Based on what I read there, I added the following method:
// Params:      endpoint - the logical endpoint number.
// Returns:     TRUE if at least one write buffer is free,
//              FALSE otherwise.
// Description: Checks that the IN endpoint has a free write buffer.
uint8_t USBCheckInEndpointFree(uint32_t endpoint)
{
  uint16_t data;
  uint32_t physicalEndpoint = getEndpointPhysicalAddress(endpoint);

  writeSIECommand(CMD_SEL_EP(physicalEndpoint));
  data = readSIECommandData(DAT_SEL_EP(physicalEndpoint));

  return (data & 0x1) == 0;
}

I changed USBWriteEndpoint to the following:
uint32_t USBWriteEndpoint(uint32_t endpoint, uint8_t *pData, uint32_t count)
{
  uint32_t i = 0;
  NVIC_DisableIRQ(USB_IRQn);

  if((endpoint & 0xF) != 0)
  {
    while(getSendMessageFlag(endpoint & 0xF) != 0);
    setSendMessageFlag(endpoint & 0xF);
  }

  while(!USBCheckInEndpointFree(endpoint))
  {
    uint32_t physicalEndpoint = getEndpointPhysicalAddress(endpoint);

    writeSIECommand(CMD_SEL_EP(physicalEndpoint));
    ITM_EVENT32_WITH_PC(3, readSIECommandData(DAT_SEL_EP(physicalEndpoint)));
  }

  LPC_USB->Ctrl = ((endpoint & 0xF) << 2) | CTRL_WR_EN;

  LPC_USB->TxPLen = count;

  for(i=0; i < (count+3)/4; i++)
  {
    LPC_USB->TxData = *((__packed uint32_t *)(pData+i*4));
    //pData += 4;
  }

  ITM_EVENT32_WITH_PC(4, (pData[4] << 24) | (pData[5] << 16) | (pData[6] << 8) | pData[7]);

  LPC_USB->Ctrl = 0;
  USBValidateEndpoint(endpoint);

  NVIC_EnableIRQ(USB_IRQn);
  return count;
}

The ITM_EVENT32_WITH_PC macro is used for debugging.
While sending USB messages at a high rate, I noticed this pattern in the event timeline:

In that image, the lines within the third channel show where the thread is caught within the while loop because none of the write buffers of the endpoint I'm using are free. The lines in the fourth channel are where a message is written to one of the endpoint's write buffers.
The LPC1788 uses double-buffering for bulk and isochronous endpoints, so what you're seeing in that image is the following:

*

*The microcontroller tries to send a USB message to the host. Both write buffers are free, so it picks one and uses that.

*The micro tries to send a second message. It uses the remaining free write buffer.

*The micro tries to send a third message. Both buffers are in use so it has to wait. That produces the series of lines in the third channel while the micro polls the endpoint status.

*Eventually one of the buffers (probably the first one used) becomes free, and the message is written to that.

*The micro tries to send a fourth message. Both buffers are in use and the micro apparently has to wait a fair while before one of them becomes free.

*Eventually one of the buffers becomes free and it writes the message to that.

Before adding in that additional check, I got behaviour like this:

Clearly without the check, the endpoint's buffers are getting overwritten!
To check how well this change resolved the problem, I created a Python script with a simple algorithm that I chose to evaluate performance by comparing how well the output from the USB logs (generated by one of my USB drivers on the PC end) conforms to a perfect cycle (which is what I'd ideally want).
I did three runs of my program with the additional check and three runs of my program without it, each time leaving it running long enough for 1000 USB messages to be received and recorded in a log file by the DLL.
The three logs with the additional check were USBLogGood1.txt ... USBLogGood3.txt. The three without the check were USBLogBad1.txt ... USBLogBad3.txt.
The Python code is given below:
# Checks how well the USB is performing by checking how
# closely the stream of USB messages returned by the DLL
# matches a perfect cyclical pattern.

from statistics import *

cycle = [1,2,3,4]
sampleSize = 1000

class Globals:
    totalCount = 0
    errorCount = 0

usbLogFile = "usbLog.txt"

usbGoodLogFiles = ["usbLogGood1.txt",
                   "usbLogGood2.txt",
                   "usbLogGood3.txt"]

usbBadLogFiles = ["usbLogBad1.txt",
                  "usbLogBad2.txt",
                  "usbLogBad3.txt"]

# Switch between sets of log files.
usbLogFiles = usbBadLogFiles

# Read log file.
def readLog(logFile):
    with open(logFile) as fIn:
        return fIn.readlines()

# Converts raw log data into a list of cycle values.
def processLog(log):
    data = []

    for line in log:
        data.append(processLogLine(line))

    return data

# Converts raw log line into a cycle value.
def processLogLine(logLine):
    l = logLine.replace("Message ", "")
    return int(l[5],16)+1

# Counts distance in one direction, so the distance
# will be high if i2 is behind i1.
def getListDistance(val1, val2):
    cycleLen = len(cycle)
    i1 = cycle.index(val1)
    i2 = cycle.index(val2)

    if i1 <= i2:
        return i2 - i1
    else:
        return (cycleLen - i1) + i2

def getNextValueInCycle(val):
    cycleLen = len(cycle)
    i = cycle.index(val)
    if i < cycleLen-1:
        return cycle[i+1]
    else:
        return cycle[0]

def checkCycleValue(expected, value):
    Globals.totalCount += 1

    if value != expected:
        Globals.errorCount += getListDistance(expected, value)

    expected = getNextValueInCycle(value)
    return expected

def getPerformance():
    return 1-float(Globals.errorCount)/float(Globals.totalCount)

def printPerformance():
    print("Sampled %d values. USB performance: %0.1f%%"
          % (Globals.totalCount, getPerformance()*100))

# Read log file and evaluate performance.
def evaluatePerformance(logFile):
    Globals.totalCount = 0
    Globals.errorCount = 0

    log = readLog(logFile)
    data = processLog(log)
    if not data:
        print("No data available")
        return

    if len(data) < sampleSize:
        print("Not enough data available to meet requirements")
        return
    else:
        data = data[:sampleSize]

    expected = data[0]
    for value in data:
        expected = checkCycleValue(expected, value)

    return getPerformance()

def printAggregatePerformanceData(logFiles, performances):
    performances = [100*p for p in performances]

    for f, p in zip(logFiles, performances):
        print("%s: %0.2f%%" % (f, p))

    print("\nAverage performance: %0.2f%%" % mean(performances))
    print("Standard deviation: %0.2f" % stdev(performances))

def main():
    performances = []
    for logFile in usbLogFiles:
        performances.append(evaluatePerformance(logFile))

    printAggregatePerformanceData(usbLogFiles, performances)

if __name__ == "__main__":
    main()

With the good set of logs, I got the following output:
usbLogGood1.txt: 93.70%
usbLogGood2.txt: 92.50%
usbLogGood3.txt: 92.60%

Average performance: 92.93%
Standard deviation: 0.67

For the bad set, I got this:
usbLogBad1.txt: 16.60%
usbLogBad2.txt: 13.80%
usbLogBad3.txt: 14.10%

Average performance: 14.83%
Standard deviation: 1.54

By adding in the additional check to make sure a write buffer is free, I managed to increase the 'performance' of the USB by around 78.1% (100% means a perfect cycle of USB messages: 1,2,3,4,1,2,3,4,1,2,3,4...).
In addition to this, I found that the message throughput about doubled when I put the check in, despite the delays associated with waiting in while loops.
92.93% still isn't perfect, but the manual talks about checking for ACKS from the host as well as just free write endpoints. I tried to do that earlier (without apparent success), but this was before I tried this check. Hopefully, if I implement both together I can get the USB performance to rival that of CAN.
Edit: The wait for ACK thing didn't work, but if I force a 1ms delay in between sending messages, I can get a performance of ~99.99...%.
This is not an ideal solution since 1ms is quite a long time to be delaying for, so I'm leaving the question unresolved for now.
EDIT
I quite firmly believe at this point that the issue is mainly with the PC-side driver I wrote. It doesn't read fast enough.


text:
Q: How to read a 3 int array to find middle and max numbers in Java? If a user inputs [3, 5, 2]
How would I write a code so that it would correlate 3 to "a", 5 to "b", and 2 to "c"?
public static void main(String[] args) {

    int a = input.nextInt();
    int b = input.nextInt();
    int c = input.nextInt();
    int x = 0;
    int t = 0;

    {
        //MIN
        x=a;
        if ((b < x))t=b;
        if ((c < x))x=c;

        //MAX
        t=a;
        if ((b > t)) t=b;
        if ((c > t)) t=c;
    }

    int m = a+b+c-x-t;
    System.out.print(m+t);
}

}
I'd like to not have separate int inputs for each variable, but one array.

A: That should work fine:
    Scanner scanner = new Scanner(new File("input.txt"));
    List<Integer> list = new ArrayList<Integer>();
    scanner.nextInt(); // this solution omits number of datasets. we don't really need it
    while (scanner.hasNext()) { // do we have one more line?
        list.clear(); // we need empty list
        for (int i=0;i<3;i++) { // read 3 numbers
            list.add(scanner.nextInt());
        }
        Collections.sort(list);
        Integer max = list.get(2);
        Integer middle = list.get(1);
        System.out.println(max+middle);
    }


text:
Q: How to handle GCM upstream messaging error cases? I'm using "Upstream messaging" feature of GCM to send registration id to backend.
You need to sign the form to use this functionality, which i did but doesn't receive a confirmation yet.
Basicly what i'm doing is calling register and then sending obtained id using send(SENDER_ID@gcm.googleapis.com, msgId, 0, data). So TTL is 0. But im still receiving an error in my broadcast receiver (gcm messageType is "send_error" with "error"="SERVICE_NOT_AVAILBLE", probably because "upstream" is not enabled yet for this project).
The point is how can i ensure that the message was successfully delivered? I can receive a message on an error, but there is no message in case of success.
Should i send an extra message to device from my server that everything was OK and wait on a client side for that message?
I think i can rephrase last questing: "Can i make a synchronous send()?". I don't need a TTL (thats why i'm sending 0 TTL), just want to send registration id to my server over the cloud (GCM).

A: this is best example to GCM Notification from server to android.
(android-to-could)
reference link
this is best example for cloud-to-message in android
reference link
I hope its useful to you.


text:
Q: how to prevent user from accessing other account's email when assigned under same application with same secret key in AZURE Portal? I'm new to this.
I have registered an app called Oauth Test for email authentication.
Then created a secret key to access the app.
I assigned this app to two users.
Now user A is using secret key and his own email id to access the mailbox.
User B is again using secret key and his own email id to access the mailbox. Its working fine for both the users.
The problem is if user A uses secret key with user B's email id, he is able to read B's emails. I want to prevent this and make it limited to that particular user only.
is there any way to assign same app to multiple users but create different secret keys for each user so that they cannot cross login to each other's mailbox?

A: The best practice is to use an App Registration, in that way the user uses their Azure AD credentials, not a common key.
Please check this documentation https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app
Hope this helps!


text:
Q: Add text under "Place Order" button at WooCommerce checkout I would like to add some text under the "Place Order" button at WooCommerce checkout.
I'm using the woocommerce_review_order_after_submit hook:
add_action( 'woocommerce_review_order_after_submit', 'add_after_checkout_button' );

function add_after_checkout_button() {
echo '
By clicking on the purchase button, you agree to our Terms of Service and Privacy Policy
';
}

Result (screenshot): https://ibb.co/F38bxDf
Could someone please help me edit this code to:

*

*Add some space at the top (between the text and the "Place Order"
button)

*Center align the text

*Turn "Terms of Service" and "Privacy Policy" into clickable links

*Decrease the line-height of the text

*Decrease the font size

Is there a way to give this text a CSS class so I can control the styling of it with custom CSS? Or is possible to somehow type the custom CSS in the code snippet itself?
EDIT:
I've got 2 pieces of code.
Nr 1:
add_action( 'woocommerce_review_order_after_submit', 'add_after_checkout_button' );

function add_after_checkout_button() {

echo '
By clicking on the purchase button, you agree to our Terms of Service and Privacy Policy
';
}

and
Nr 2:

        SSL encrypted payment

        100% money-back guarantee

Code snippet Nr 1 solves my initial question.
Code snippet Nr 2 is an addition to display "encrypted payment" and "money-back guarantee" above the text as per my request in the comments.
I don't know how to merge these 2 pieces of code into 1.

A: You could add a class like this:
function add_after_checkout_button() {
    echo '
By clicking on the purchase button, you agree to our Terms of Service and Privacy Policy
';
}

Or use css inline like this:
function add_after_checkout_button() {
    echo '
By clicking on the purchase button, you agree to our Terms of Service and Privacy Policy
';
}

To turn the text into links just use a Terms and Service tag inside, just like you already did with the
.
EDIT:
HTML and CSS code to add an "encrypted payment" and "money-back guarantee" as requested in the comments:

        SSL encrypted payment

        100% money-back guarantee

.row {
    display: flex;
    text-align: center;
}

.column {
    flex: 50%;
}

A: You should just add a class to your  tag

 and style it in your style.css file in your child theme.
For the links, just add tags  around the words "Terms of Service" and "Privacy Policy"


text:
Q: Vue native color picker @input when no change is made Here's a situation: I have a regular non-Vue component color picker with the simple <input type="color"/> which works almost perfect, except in one case. The case being, when there's already a color existing in the picker and all the user does is click "Ok". I would expect that the vue @input or @change event would fire and set the color value even if the user didn't choose a different color. However, when the user simply clicks "Ok" and does not choose a new color, there is no event fired for either @change or @input. What's a way to fire this event in such a case?

A: That functionality is unfortunately not available.
You can use @focus, with the caveat that it will fire when you click, and when you exit (cancel or OK)
You could add some custom @blur and @focus events to get something similar, but I think using just @focus (triggered on click too) may work in most scenarios


text:
Q: Pseudo-code for rules of probability? I am having a hard time in Stats understanding some basic rules of probability and set-theory, namely $P(A|B)$, $P(A\ \textrm{and}\ B)$ and $P(A\ \textrm{or}\ B)$ where $A$ and $B$ depend on each other. I use Mathematica all the time through my school, and I love to program in my free-time (sometimes writing small scripts for Mathematica).
I can understand confusing subjects that deal with logic when they are in a programming language syntax, so I thought I could understand what's going on better if I had a written syntax to look at. Will anyone bother to help?

A: The Wolfram Demonstration Project has 13 submissions that use Bayes Theorem:
See here

More specifically:
Probability Of Being Sick After Having Tested Positive For A Disease
Bayes's Theorem And Inverse Probability
Total Probability And Bayes's Theorem
All of these will have downloadable code to help you learn this.
Good luck.


text:
Q: Check if Elements in an Array are of a SubClass in Java let's assume that I want to check if values within an Object array are of the superclass or subclass let's say for instance that my super class is Called Animal, I declare an array of type Animal
Animal myAnimals[] = new Animal[];

Now suppose that there are subclasses of Animal like Lion, Tiger, Elephant, etc. If I were to loop through an array, how would I differentiate the subclasses (Lion, Tiger, etc.) from the superclass Animal? Thanks!

A: Using instanceof

At run time, the result of the instanceof operator is true if [...]
  the reference could be cast (§15.16) to the ReferenceType without
  raising a ClassCastException.

for (Animal a : myAnimals) {
    if (a instanceof Lion) System.out.println("Lion");
    // etc.
}

A: As @YassinHajaj already said you can use the instanceof operator:
 for (Animal animal : animals) {

     if (animal instanceof Tiger) {

           Tiger tiger = (Tiger) animal;
     }
 }

However this results in unstructured code, besides this is hard to maintain. I personally prefer an more object oriented way.
As @JBNizet suggested in a comment you can use polymorphism. That's good but not perfect: you will need to change the implementation of all animal classes in order to add some logic.

Visitor pattern
However if you combine this with the visitor pattern. This will become very powerful because you can separate the logic into a visitor class:
interface AnimalVisitor {

    void visitLion(Lion lion);
    void visitFish(Fish fish);

    // Gets called when animal does not override the accept method:
    void visitDefault(Animal animal);
}

class Animal {

    public void accept(AnimalVisitor visitor) {
        visitor.visitDefault(this);
    }
}

class Fish extends Animal {

    @Override
    public void accept(AnimalVisitor visitor) {
        visitor.visitFish(this);
    }
}

class Lion extends Animal {

    @Override
    public void accept(AnimalVisitor visitor) {
        visitor.visitLion(this);
    }
}

Then you can easily replace your loop with something like this:
AnimalVisitor visitor = new AnimalVisitor() {

    @Override
    public void visitLion(Lion lion) {
        // Do something with lion
    }

    @Override
    public void visitFish(Fish fish) {
        // Do something with fish
    }
}

for (Animal animal : animals) {
    animal.accept(visitor);
}

We can even take this one step further:
Reflective visitors
Since it is annoying to add for every different kind of animal an specific visitAnimal method, we can make use of reflection to avoid this! This will result in smaller and cleaner code:
interface Visitable { }

class Animal implements Visitable {

    // No accept method
}

class Fish extends Animal {}
class Goldfish extends Fish {}
class Shark extends Fish {}

// Take for example this visitor:

class BittenByVisitor extends ReflectiveVisitor {

    private Surfer surfer;

    public BitByVisitor(surfer) {
        this.surfer = surfer;
    }

    // We only care about the sharks:

    public void visit(Shark shark) {

        surfer.die();
    }

    // Any other fish is just the same:

    public void visit(Fish fish) {

        surface.decreaseHealthBy(1);
    }

    // It also works with interfaces:
    public void visit(VerySmallFish fish) {

        // Do nothing by purpose!
    }
}

And here an implementation of the reflective visitor:
abstract class ReflectiveVisitor {

    public void visit(Visitable v) throws NoSuchMethodException {
        Method m = findMethod(v);

        try {
            m.invoke(this, new Object[] { v });
        }

        catch ( IllegalAccessException e1 ) { /* code handling */ }
        catch ( InvocationTargetException e2 ) { /* code handling */ }
    }

    private Method findMethod(Visitable v) throws NoSuchMethodException {

        String methodName = "visit";
        Class visitable = v.getClass();

        while ( isAncestorOf("Visitable", visitable) {

            Class visitor = getClass();

            while ( isAncestorOf("Visitor", visitor) {

                try {
                    Method m = visitor.getDeclaredMethod(methodName, new Class[]{visitable});
                    return m;
                } catch ( NoSuchMethodException e ) {
                    visitor = visitor.getSuperclass();
                }
            }

            visitable = visitable.getSuperclass();
        }

        String errMsg = "put error message here";
        throw new NoSuchMethodException(errMsg);
    }

    private boolean isAncestorOf(String ancestorName, Class descendant) {

        try {
            return Class.forName(ancestorName).isAssignableFrom(descendant);
        }
        catch ( ClassNotFoundException e ) { /* code handling */ }
            return false;
        }
    }
}

Source code is taken from this paper.
I personally like to use a reflective visitor which avoids the Visitable class. You can define it like this:
class ReflectiveVisitor<T> {

    public void visit(T visitable);
}

A: You could iterate every element and check the subtype by using instanceof..


text:
Q: Why isn't my UILabel centered? I'm trying to center my UILabel horizontally.  This is what it ends up looking like (notice its no center).

    ReflectionView *aReflectionView = [[ReflectionView alloc]initWithFrame:CGRectMake(((self.view.bounds.size.width / 2) - 150), 40, 300, 90)];
    UILabel *aLabel = [[UILabel alloc]initWithFrame:CGRectMake(((self.view.bounds.size.width / 2) - 150), 0, 300, 90)];
    aLabel.textAlignment = UITextAlignmentCenter;
    aLabel.text = @"1 lbs";
    self.weightLabel = aLabel;
    [aReflectionView addSubview:self.weightLabel];
    self.weightReflectionView = aReflectionView;
    [self.view addSubview:self.weightReflectionView ];
    [self.weightReflectionView  updateReflection];

A: The textAlignment property will align text within the frame of the UILabel, not outside of it. My ASCII skills are a little rusty, but here's what I mean. Consider the labels below, where the | indicates the left/right edge of the label.

|173 lbs    | => left aligned
|    173 lbs| => right aligned
|  173 lbs  | => center aligned (not exactly centered in terms of its superview)

Now consider the same label contained within another view, where the outer [] represent the edges of the containing view, and the inner | represents the edges of the contained label. Notice how the inner label is not exactly centered within its superview, and is slightly pushed to the right (2 spaces away from the left, and 1 space closer to the right).

[  |173 lbs    | ] => left aligned
[  |    173 lbs| ] => right aligned
[  |  173 lbs  | ] => center aligned

If you want the label to be center aligned within the superview or the screen at all times, you would want to make sure the width of the label matches its container, and then set textAlignment to center. Here's how:

[|173 lbs      |] => left aligned
[|      173 lbs|] => right aligned
[|   173 lbs   |] => center aligned (perfectly aligned)

This is a common case where you want the subview to match the exact size of the superview. You can use the bounds property to easily do that.
ReflectionView *aReflectionView = [[ReflectionView alloc] initWithFrame:..];
// Use the bounds of the superview to set the subview's frame.
UILabel *aLabel = [[UILabel alloc] initWithFrame:aReflectionView.bounds];

As a UI debugging tip, try changing the background of the problematic view (label) to show exactly what area it is taking, which usually helps solving many such problems.

A: Just for debugging purposes, try setting the backgroundColor of aLabel and aReflectionView to see where they're being placed.
aLabel.backgroundColor = [UIColor redColor];
aReflectionView.backgroundColor = [UIColor blueColor];

You should see that the aReflectionView is properly centered within its superview, but the aLabel, contained within it, is not.  Why not?  Because of this line:
UILabel *aLabel = [[UILabel alloc]initWithFrame:CGRectMake(((self.view.bounds.size.width / 2) - 150), 0, 300, 90)];

Since aLabel is contained within aReflectionView, it should be centered within the aReflectionView bounds, not the bounds of self.view.  Scroll right to see the change:
UILabel *aLabel = [[UILabel alloc]initWithFrame:CGRectMake(((aReflectionView.bounds.size.width / 2) - 150), 0, 300, 90)];

For your purposes, it may be better to make aLabel simply fill aReflectionView:
UILabel *aLabel = [[UILabel alloc]initWithFrame:aReflectionView.bounds];

A: The problem is not the alignment of the text in the UILabel, but rather the alignment of the UILabel itself. Specifically, you're creating the UILabel to be center aligned according to the width of the self.view (notably the width), but you're adding it to the aReflectionView (which is narrower, offset from the left edge of the self.view, and is already centered on the screen). The net effect in this case, is that you're getting the offset from the left edge of the self.view twice, once in the x coordinate of the aReflectionView and then again in the x coordinate of the aLabel which you've put in the aReflectionView, which is clearly not your intent. The easiest fix is probably something like:
UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectMake(((aReflectionView.bounds.size.width / 2) - 150), 0, 300, 90)];

Bottom line, center the label on the view you're putting it on.

A: For those Googling, I have an answer for them. Problem was, I had some escape characters to designate a new line within the code like so:
self.emptyLabel.text = @"No likes yet! \n\
\
\n(Like some cards to save them here)";

That caused the text to be aligned off-center. Simply remove them like so:
self.emptyLabel.text = @"No likes yet! \n\n(Like some cards to save them here)";


text:
Q: Regex to capture this field? I would like to extract the the parameter name corresponding to the value 123.
For both these strings
[param1=456&param2=123]
[param2=123&param1=456]

I would like to find this value
param2

This regex works for the first line, but not for the second
&([\S]*)123

This regex works for the second line, but not for the first
[&|\[]([\S]*)123

A: This regex will look for the name that is matched with 123
(\w+)(?:=123)[&\]]

*

*\w+ is matching one or more alphanumeric characters,

*(?:...) is for a non capturing group so that you don't get the '=123' part

*=123 is looking for the equality with the value you want

*[&\]] is looking to match a ']' or '&' right after '=123'

*

*If the square brackets are not part of your string, then you could look for the end of the string instead with [&$]


text:
Q: How to emulate keys through ssh / NMSSH I'm looking for some help on how to simulate keys through strings / SSH. I've been using the SSH Framework NMSSH. I've got sending all the commands working through the channel.write command except one. I need to send the command Ctrl + C to abort out of something. Any idea's on how to do this? I'm not sure how to send a "Key" along with the string.

A: Ctrl-C is the character at codepoint 3. It's formally known as ETX (end of text), and it's part of the "control character" block. It's a non-printing character, so you have to express it using a special character sequence. I'm not a swift programmer, but it looks like you'd specify it like this:
let ctrlC: Character = "\u{3}"


text:
Q: Implement massactions in grid using ui_component magento2 How to Implement massactions in grid using ui_component magento2. I have created my ui_component and need to implement massactions. I have also created controllers for the required paths. But, somehow it is just not working. I'm using magento 2.1 C.E.
ui_component/test_grid.xml
<massaction name="listing_massaction">
    <argument name="data" xsi:type="array">
        <item name="config" xsi:type="array">
            <item name="selectProvider" xsi:type="string">test_grid.test_grid.test_grid_columns.ids</item>
            <item name="component" xsi:type="string">Magento_Ui/js/grid/tree-massactions</item>
            <item name="indexField" xsi:type="string">entity_id</item>
        </item>
    </argument>
    <action name="accept">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="type" xsi:type="string">accepted</item>
                <item name="label" xsi:type="string" translate="true">Accept</item>
                <item name="url" xsi:type="string">test/Index/Massaccept</item>
            </item>
        </argument>
    </action>
</massaction>

Index/Massaccept.php
<?php
    namespace Vendor\Module\Controller\Adminhtml\Index;
    use \Vendor\Module\Model\TestFactory;

    class Massaccept extends \Magento\Backend\App\Action {

        protected $resultPageFactory = false;
        protected $_fasctcureFactory;

        public function __construct(
            TestFactory $testFactory,
            \Magento\Framework\View\Result\PageFactory $resultPageFactory,
            \Magento\Backend\App\Action\Context $context
            ) {
            $this->_testFactory = $testFactory;
            $this->resultPageFactory = $resultPageFactory;
            parent::__construct($context);
        }

        public function execute() {
            die("working");
            $ids = $this->getRequest()->getParam('id');
            $model = $this->_testFactory->create();

            foreach($ids as $id) {
                $model->load($id);
                $model->getStatus();
                $model->setStatus('Processing');
                $model->save();
            }
            $resultRedirect = $this->resultRedirectFactory->create();
            $resultRedirect->setRefererOrBaseUrl();
            return $resultRedirect;
        }
    }

My controllers are in the path:
Vendor/Module/Controller/Adminhtml/Index/Massaccept.php
Vendor/Module/Controller/Adminhtml/Index/Massreject.php
The mass actions are visible on the grid, but are not redirecting anywhere.Redirect is not working for using above code.
All I'm getting is this error:
Uncaught TypeError: Cannot read property 'total' of undefined in massactions.js:52

A: Please try this. It's working fine for me.
<massaction name="listing_massaction">
        <action name="delete">
            <argument name="data" xsi:type="array">
                <item name="config" xsi:type="array">
                    <item name="type" xsi:type="string">delete</item>
                    <item name="label" xsi:type="string" translate="true">Delete</item>
                    <item name="url" xsi:type="url" path="test/index/massDelete"/>
                    <item name="confirm" xsi:type="array">
                        <item name="title" xsi:type="string" translate="true">Delete Items</item>
                        <item name="message" xsi:type="string" translate="true">Are you sure you wan't to delete selected items?</item>
                    </item>
                </item>
            </argument>
        </action>
    </massaction>

Your controller name like MassDelete.php
This is my MassActive.php
Please refer this and change  your massaccept.php file and then check after that.
namespace Dedicated\Grid\Controller\Adminhtml\Item;
use Magento\Framework\Controller\ResultFactory;
use Magento\Backend\App\Action\Context;
use Magento\Ui\Component\MassAction\Filter;
use Dedicated\Grid\Model\ResourceModel\Grid\CollectionFactory;

class MassActive extends \Dedicated\Grid\Controller\Adminhtml\Item
{

/**
 * @var Filter
 */
protected $filter;

/**
 * @var CollectionFactory
 */
protected $collectionFactory;

/**
 * @param Context $context
 * @param Filter $filter
 * @param CollectionFactory $collectionFactory
 */
public function __construct(Context $context, Filter $filter, CollectionFactory $collectionFactory)
{
    $this->filter = $filter;
    $this->collectionFactory = $collectionFactory;
    parent::__construct($context);
}
/**
 * Delete action
 *
 * @return \Magento\Backend\Model\View\Result\Redirect
 */
public function execute()
{
    $collection = $this->filter->getCollection($this->collectionFactory->create());
    $collectionSize = $collection->getSize();

    foreach ($collection as $template) {
        $template->setIsActive(true);
        $template->save();
    }

    $this->messageManager->addSuccess(__('A total of %1 record(s) have been changed.', $collectionSize));

    /** @var \Magento\Backend\Model\View\Result\Redirect $resultRedirect */
    $resultRedirect = $this->resultFactory->create(ResultFactory::TYPE_REDIRECT);
    return $resultRedirect->setPath('*/*/');
}
}

A: You have to pass path like test/index/massdelete and test/index/massaccept in below arguments.
 <action name="reject">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="type" xsi:type="string">rejected</item>
                <item name="label" xsi:type="string" translate="true">Reject</item>
                <item name="url" xsi:type="url" path="*/*/MassDelete"><item/>
                <item name="confirm" xsi:type="array">
                    <item name="title" xsi:type="string" translate="true">Reject items</item>
                    <item name="message" xsi:type="string" translate="true">Are you sure to reject selected Requests?</item>
                </item>
            </item>
        </argument>
    </action>
    <action name="accept">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="type" xsi:type="string">accepted</item>
                <item name="label" xsi:type="string" translate="true">Accept</item>
                <item name="url" xsi:type="string">test/Index/Massaccept</item>
            </item>
        </argument>
    </action>

You have to replace with below code,
 <action name="reject">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="type" xsi:type="string">rejected</item>
                <item name="label" xsi:type="string" translate="true">Reject</item>
                <item name="url" xsi:type="url" path="test/index/massDelete"><item/>
                <item name="confirm" xsi:type="array">
                    <item name="title" xsi:type="string" translate="true">Reject items</item>
                    <item name="message" xsi:type="string" translate="true">Are you sure to reject selected Requests?</item>
                </item>
            </item>
        </argument>
    </action>
    <action name="accept">
        <argument name="data" xsi:type="array">
            <item name="config" xsi:type="array">
                <item name="type" xsi:type="string">accepted</item>
                <item name="label" xsi:type="string" translate="true">Accept</item>
                <item name="url" xsi:type="string">test/index/massAccept</item>
            </item>
        </argument>
    </action>

Your controller file path should be MassDelete.php and MassAccept.php


text:
Q: Lightning Data Service to clear Lookup field Using the LDS native functionality we can modify the contents of a lookup field using a lightning:inputfield element, however clearing the field out and saving has no effect. See the inputfield assigned to ContactId on Cases below.
<aura:component implements="flexipage:availableForRecordHome,force:hasRecordId,force:hasSObjectName">

<aura:attribute name="record" type="Object"/>
<aura:attribute name="simpleRecord" type="Object"/>
<aura:attribute name="recordError" type="String"/>
<force:recordData aura:id="recordLoader"
                  recordId="{!v.recordId}"
                  layoutType="FULL"
                  targetRecord="{!v.record}"
                  targetFields="{!v.simpleRecord}"
                  targetError="{!v.recordError}"
                  mode="EDIT"
                  recordUpdated="{!c.handleRecordUpdated}"
                  />

    <lightning:recordEditForm recordId="{!v.recordId}"
                              aura:id="recordEditForm"
                              objectApiName="Case" >

            <lightning:layout multipleRows="true">
                <lightning:layoutItem >
                    <lightning:inputField fieldName="Description" />
                </lightning:layoutItem>
            </lightning:layout>

        <lightning:inputField fieldName="Description" />
        <lightning:inputField fieldName="ContactId" />
        <lightning:button type="submit" name="update" label="Update" />
    </lightning:recordEditForm>

Are there any workarounds to this limitation?

A: One thought is to give the inputFields an aura:id so you can attach a change event handler where you have a custom function that evaluates truthiness and clears out the value by hand.
That's a bit heavy handed, but I've used onchange handlers on force namespaced components because their internal change event wasnt behaving as expected.
This might be the same case?


text:
Q: Execute multiple shell scripts of same name under several sub-directories I am using a shell script from a parent directory to call multiple other shell scripts, all having the same name, but under separate subdirectories. Let me elaborate below:
Parent directory: Script deploy_modules.sh
SubDir A: deploy.sh
SubDir B: deploy.sh
SubDir C: deploy.sh
....
SubDir Z: deploy.sh

The script deploy_modules.sh calls each of the sub-directory's deploy.sh sequentially by entering that directory, calling the script, then exiting and entering the next one.
Is there a way to sequentially execute all the deploy.sh files in a single line command? I need the command to be generic enough to automatically include any newly added sub-directory with another deploy.sh, and not give error if one or more of the sub-directories are removed.

A: This would find all deploy.sh scripts in the subdirectories to wherever the current directory is - and execute them.
Without doing cd down into the subdirectories:
for dep in */deploy.sh; do "$dep"; done

Doing cd down into each subdirectory:
for dep in */deploy.sh; do (cd "$(dirname "$dep")"; ./deploy.sh) done

A: Something like
find Parentdir -maxdepth 1 -name deploy.sh -exec {} \;

Omit the maxdepth option, if you want to include deploy scripts further down in your tree as well.
In case you need to execute the deployment script from inside the directory it is in (though you don't mention this in your question), use -execdir instead of -exec.


text:
Q: How to apply custom jQuery UI button class on asp.net button I have been trying to apply custom jquery ui css class on asp.net button but some how it is not working.
It works fine if i use my css class with button control as shown on attached image (first button). I need to use asp.net button for some reasons and would like to have it in same look as button control.
    <button id="btnLogin2"  type ="button" onserverclick ="btnLogin_Click"  runat="server" aria-disabled="false" role="button" class="ui-button ui-widget ui-state-default cssbox-ui-corner-all cssbox-ui-corner-all:hover ui-button-text-icon-primary">

                  Login
    </button>

But css is not being applied on asp.net button.
   <asp:Button ID="btnLogin" Text=" Login " runat="server" CSSClass="cssbox-ui-corner-all cssbox-ui-corner-all:hover ui-button-text-icon-primary ui-button-icon-primary ui-icon cssbox-okbtn" />

Custom CSS class
    .cssbox-okbtn {
        background-image: url('/images/icons/jquery_ui/ok.png') !important;
    }

    .cssbox-ui-corner-all {
        width:265px;
        border-radius: 0px;
        background: none repeat scroll 0% 0% #1A7BC9;
        background: linear-gradient(to bottom, #1A7BC9 0px, #1A7BC9 100%);
        filter: progid:DXImageTransform.Microsoft.gradient(GradientType=0,startColorstr='#1A7BC9', endColorstr='#1A7BC9');/*For IE7-8-9*/
        border: 1px solid #1A7BC9;
        height: 35px;
        font-size: 12px;
    }

     .cssbox-ui-corner-all:hover {
        border-radius: 0px;
        background: none repeat scroll 0% 0% #9CC8F7;
        color: #404040;
        border: 1px solid #9CC8F7;
        filter: none;
    }

js script to apply okay button class
    $(function () {
        $("input:submit").button({
            icons: { primary: 'cssbox-okbtn' }
        }).hide().after('<button>').next().button({
            icons:
            {
                primary: 'cssbox-okbtn'
            },
            label: $("input:submit").val()

        });

Second one is asp.net button.

Page Source

                <button onclick="__doPostBack('ctl00$ContentPlaceHolder1$btnLogin2','')" id="ctl00_ContentPlaceHolder1_btnLogin2" type="button" aria-disabled="false" role="button" class="ui-button ui-widget ui-state-default cssbox-ui-corner-all cssbox-ui-corner-all:hover ui-button-text-icon-primary">

                  Login
                </button>

                <input type="submit" name="ctl00$ContentPlaceHolder1$btnLogin" value=" Login " id="ctl00_ContentPlaceHolder1_btnLogin" class="cssbox-ui-corner-all cssbox-ui-corner-all:hover ui-button-text-icon-primary ui-button-icon-primary ui-icon cssbox-okbtn" />


text:
Q: No Sound other then Drumming! Its been almost 47 days that I am using Ubuntu 13.04, and today I came to know that Ubuntu has its tones for different actions like for

*

*ShutDown

*Login

*Logout

*New Device Inserted

but after booting it only plays drumming tone, I think that's for notifying system is ready but what about others. How can I enable them , I want all the tones present in
/usr/share/sounds/ubuntu/stereo

in action. Only system-ready.ogg is working.

I have tried
sudo cp /usr/share/sounds/ubuntu/stereo/* /usr/share/sounds/

but even it doesn't work out.


text:
Q: shell rename file names with non-printable characters I'm trying to find a way to batch rename file names which originally contains Japanese characters, which are non-printable in my shell.There is clearly something I'm missing here in understanding how regex works, in this use case,
When I run ls I have this :
AIR?t?H?[????002.jpg
AIR?t?H?[????009.jpg
AIR?t?H?[????075.jpg

And ls -ldb * give me this:
AIR\342t\342H\374[\342\353\342\307002.jpg
AIR\342t\342H\374[\342\353\342\307009.jpg
AIR\342t\342H\374[\342\353\342\307075.jpg

Basically I want to match and replace everything between AIR and [0-9]*
I'm currently looking at something like that :
find AIR*.jpg -type f -exec sed -ri 's/(?<=AIR)(.*?)([0-9]*)/\2test/' {} +

But i get this error:

sed: -e expression #1, char 31: Invalid preceding regular expression

I have also tried using
echo AIR�t�H�\[����002.jpg | sed -r 's/AIR([^[:print:]\t\r])*/\1toto/g'

But it rename AIR instead of the "special character" group

toto�t�H�[����002.jpg

And
echo AIR�t�H�\[����002.jpg | sed -r 's/AIR([^[:print:]\t\r])*/\2toto/g'

returns

sed: -e expression #1, char 33: invalid reference \2 on `s' command's RHS

Also tr seems it could be an option but I don't have only special characters within my two groups AIR and [0-9]* so here is what I got:
echo AIR�t�H�\[����002.jpg | tr -c '[:print:]\t\r\n'test '[ *]'

returns:

AIR t H [    002.jpg

A: sed substitution looks for instances (all instances since you're using g) matching the first argument, and replaces the full match with the second argument. So if you include "AIR" in the first argument, it will be replaced — you need to include it in the second argument if you want to keep it. When sed complains of an invalid reference, it means you haven't defined a corresponding group in the first argument (using \( and \), or ( and ) since you've specified -r).
Since you're looking for "AIR" followed by any characters followed by digits, I would suggest the following:
sed -r 's/AIR([^[:digit:]]*)([[:digit:]]+).jpg/AIRtest\2.jpg/g'

This replaces "AIR" with "AIR", any non-digits with "test", and keeps all the digits thereafter. If you don't need to process the characters between "AIR" and the digits, you can ignore them:
sed -r 's/AIR[^[:digit:]]*([[:digit:]]+).jpg/AIRtest\1.jpg/g'

If you have the Perl rename, you can transpose this to rename your files:
rename 's/AIR[^[:digit:]]*([[:digit:]]+).jpg/AIRtest\1.jpg/g' AIR*.jpg

or
rename 's/AIR[^[:digit:]]*([[:digit:]]+).jpg/AIRtest$1.jpg/g' AIR*.jpg

(rename prefers $ for group references).


text:
Q: Chrome extension: Slide out menu from the left of Chrome window Is it possible add a functionality in the extension that when you mouse over the left edge of Chrome window a menu with some options (what options is not important now) will slide out?

A: no, Chrome does not have API to show such panel or handle such kind of event. The only possible workaround is to add you own div to left side of each webpage and show such pane as part of the webpage


text:
Q: sigaction not working when used with ctypes I'm trying to adapt sigaction to be used with ctypes:
import signal
import ctypes as c
import os

libc = c.cdll.LoadLibrary("libc.so.6")

class sig_value(c.Union):
    _fields_ = [
        ("sival_int", c.c_int),
        ("sival_ptr", c.c_void_p)
    ]

class siginfo_t(c.Structure):
    _fields_ = [
        ("si_signo", c.c_int),
        ("si_code", c.c_int),
        ("si_value", sig_value),
        ("si_errno", c.c_int),
        ("si_pid", c.c_int),
        ("si_uid", c.c_int),
        ("si_addr", c.c_void_p),
        ("si_status", c.c_int),
        ("si_band", c.c_int),
    ]

handler_c_type = c.CFUNCTYPE(None, c.c_int, c.POINTER(siginfo_t), c.c_void_p)

class sigaction_t(c.Structure):
    _fields_ = [
        ("sa_handler", c.c_void_p),
        ("sa_sigaction", handler_c_type),
        ("sa_mask", c.c_int),
        ("sa_flags", c.c_int),
        ("sa_restorer", c.c_void_p),
    ]

libc.sigaction.argtypes = c.c_int,c.POINTER(sigaction_t),c.POINTER(sigaction_t)
libc.sigemptyset.argtypes = c.POINTER(c.c_int),

def py_handler(sig, siginfo, ucontext):
    print(sig, siginfo, ucontext)

handler = handler_c_type(py_handler)

sa = sigaction_t()
sa_mask = c.c_int(0)
sa.sa_mask = sa_mask
libc.sigemptyset(c.byref(sa_mask))
sa.sa_sigaction = handler
sa.sa_flags = 0x4 #SA_SIGINFO
libc.sigaction(c.c_int(signal.SIGUSR2), c.byref(sa), None)

In this code, I'm just setting a handler to receive SIGUSR2 signal with a value issued by sigqueue. Even though this code is not crashing, python's default handler for SIGUSR2 is the one that's being called. So when I receive the signal, the script exits. What could I be missing here?


text:
Q: Jaspersoft Studio: how to set the legend title? I'm using Jaspersoft Studio 6.6.0 Eclipse plugin and jasperreports library. For a bar chart, I'd like to set a title for the legend. How can I do it?
According to Jaspersoft Wiki, there is an "advanced" property "legend.title.text". It suggests I should enter it manually in "Advanced" tab, but in Jaspersoft Studio 6.6.0 Eclipse plugin there is no such thing as free-text property field, just a bunch of pre-defined properties. Am I blind? Or is this feature reserved for paid products?

A: JasperReports (and Jaspersoft Studio Community Edition) charts are based on JFreeChart.  The wiki article talks about JasperReports Server Professional, which is a different product that features Ad Hoc charts based on Highcharts.
With JasperReports charts there's no built in feature to specify a title for the legend.
However, you can implement that on your own as a chart customizer (or chart theme, but that's a little more complicated).  The chart customizer would read a chart element property and use the JFreeChart to create a title for the legend.  It would look something like this:
import org.jfree.chart.JFreeChart;
import org.jfree.chart.block.BlockContainer;
import org.jfree.chart.block.LabelBlock;
import org.jfree.chart.title.LegendTitle;
import org.jfree.ui.RectangleEdge;

import net.sf.jasperreports.engine.JRChart;
import net.sf.jasperreports.engine.JRChartCustomizer;
import net.sf.jasperreports.engine.JRPropertiesMap;

public class LegendTitleCustomizer implements JRChartCustomizer {
    @Override
    public void customize(JFreeChart chart, JRChart jasperChart) {
        JRPropertiesMap elementProperties = jasperChart.getPropertiesMap();
        String legendTitleText = elementProperties.getProperty("legend.title.text");
        if (legendTitleText != null) {
            LegendTitle legend = chart.getLegend();
            BlockContainer legendItems = legend.getItemContainer();
            BlockContainer legendWrapper = new BlockContainer();
            LabelBlock label = new LabelBlock(legendTitleText);
            legendWrapper.add(label, RectangleEdge.TOP);
            legendWrapper.add(legendItems, RectangleEdge.BOTTOM);
            legend.setWrapper(legendWrapper);
        }
    }
}

The chart element in the report would need to specify the chart customizer class and the property value:
<barChart>
    <chart customizerClass="LegendTitleCustomizer">
        <reportElement x="0" y="50" width="270" height="175">
            <propertyExpression name="legend.title.text">"Series"</propertyExpression>
        </reportElement>
        ...


text:
Q: Vertically expandable Composite I'm building an SWT UI, and it has a window (Shell) with three Composites stacked one below the other. I want that:

*

*all to expand to the maximum possible width (width of the window)

*the first and third Composites have a height of 100px each

*the third composite expand to a height of height_of_parent - 200px - any_margins_or_paddings.

Objective 2 is trivial, and I did Objective 1 using the ColumnLayout defined here.
How do impolement Objective 3?
Many thanks :)
PS: I'm very new to SWT.

A: I would use a GridLayout and do something like this:
GridLayout layout = new GridLayout();
parent.setLayout(layout);

GridData data1 = new GridData(SWT.LEFT, SWT.FILL, false, true);
data1.heightHint = 100;
widget1.setLayoutData(data1);

GridData data2 = new GridData(SWT.LEFT, SWT.FILL, false, true);
data2.heightHint = 100;
widget2.setLayoutData(data2);

GridData data3 = new GridData(SWT.LEFT, SWT.TOP, false, false);
data3.heightHint = Math.max(1, parent.getSize().y - 200 - layout.marginHeight * 2);
widget3.setLayoutData(data3);

parent.addControlListener(new ControlAdapter() {
    public void controlResized(ControlEvent e) {
        GridData data = (GridData)widget3.getLayoutData();
        data.heightHint = parent.getSize().y - 200 - layout.marginHeight * 2;
        widget3.setLayoutData(data);
        parent.layout(true);
    }
});


text:
Q: Idiomatic way of implementing nested matrices in golang
*

*I am trying to represent a hypergraph in memory. Are there any better data structures for this task beside nested matrices? A nested matrix is a matrix which can have elements of both the "native" type (let's say int for the sake of simplicity) and matrices.

*This is the beginning of such a matrix. Are there any rough edges in the code, to make it look more idiomatic? How to make it look more idiomatic?
The code:
package main

import "fmt"

type Matricial interface {
    Put(interface{}, ...int)
    Get(...int) interface{}
}

type Matrix struct {
    Matricial
    values map[int]interface{}
}

func NewMatrix() *Matrix {
    m := &Matrix{}
    m.values = make(map[int]interface{})
    return m
}

func (m *Matrix) Set(atom interface{}, pos ...int) {
    firstdim := pos[0]
    if val, ok := m.values[firstdim]; ok {
        fmt.Println("map key exists", val)
        switch converted := val.(type) {
        case int:
            m.values[firstdim] = converted
        default:
            fmt.Println("ERR: unknown type: %T", val)
        }
    } else {
        if len(pos[1:]) > 0 {
            newm := NewMatrix()
            m.values[firstdim] = newm
            newm.Set(atom, pos[1:]...)
        } else {
            m.values[firstdim] = atom
        }
    }
}
func (m *Matrix) Get(pos ...int) interface{} {
    if len(pos) == 1 {
        return m.values[pos[0]]
    } else {
        switch accessor := m.values[pos[0]].(type) {
        case Matricial:
            return accessor.Get(pos[1:]...)
        default:
            return nil
        }
    }
    return nil
}

func main() {
    m := NewMatrix()
    m.Set(42, 2, 3, 4)
    m.Set(43, 0)
    fmt.Println(m.Get(2, 3))
    fmt.Println(m.Get(2, 3, 4))
    fmt.Println(m.Get(0))
}

The data structure must allow connecting hyperedges with other hyperedges (i.e. handling hyperedges as though they were nodes).

A: *

*A nested matrix (adopting your definition of the term) seems a reasonable representation for hypergraph, not knowing anything more about your application anyway.  An example Go implementation is the power set example at Rosetta code.

*It is not idiomatic to embed an interface.  For example, if you rename the Put method of Matricial to be Set, which is what I think you meant, then you can just delete the Matricial field of Matrix and your program produces the same output.


text:
Q: How to eliminate whitespace when scrolling [fixed sidebar] Let me first try to illustrate the problem
I have a webpage which contains a header and a sidenav. The sidenav is fixed in css, since I don't its content to move when scrolling.
When the page isn't scrolled down it works as intended, somewhat like this

However when I scroll i don't want whitespace on top of the sidenav. Currently when I scroll down the page, it looks somewhat like this

The intended behavior should be something like this

How do I go about this in css? Do I mess with the z-index of the elements? so the sidenav is behind the header when the page isn't scrolled? Or do I dynamically add to the sidenav's size when scrolling?
And how would either of these options be done in css?

A: As I understand, you have to set z-index of the header higher than the sidenav
Stack Snippet

.header {
  height: 100px;
  background: #000000;
  position: relative;
  z-index:999;
}

body {
  margin: 0;
}

.sidebar {
  position: fixed;
  left: 0;
  top: 0px;
  width: 100px;
  background: red;
  height: 100%;
  padding-top:100px;
}

.content {
  height: 1000px;
  background: yellow;
}


text:
Q: Python Index Error - Out of Bounds for axis 0 I have dataset like the following in the txt file. (First column is=userid, second column is=locationid)
Normally my dataset is big but I created a dummy dataset to better explain my problem.
I'm trying to create a matrix like in the code below. row will be userid column location id. Since this dataset shows the location ids visited by the users, I assign the value 1 in the code to the locations they visited in the matrix.
I am getting an indexerror.IndexError: index 801 is out of bounds for axis 0 with size 50
I tried different user_num and poi_num but still doesn't work
datausers.txt
801 32332
801 14470
801 33847
501 10259
501 34041
501 10201
301 15810
301 34827
301 19264
401 34834
401 35407
401 36115

Code
import numpy as np
from collections import defaultdict
from itertools import islice
import pandas as pd

train_file = "datausers.txt"
user_num = 20
poi_num = 20

training_matrix = np.zeros((user_num, poi_num))
train_data = list(islice(open(train_file, 'r'), 10))

for eachline in train_data:
    uid, lid= eachline.strip().split()
    uid, lid = int(uid), int(lid)
    training_matrix[uid, lid] = 1.0

Error

Expected Output
4x12 Matrix because we have 4 unique users and 12 unique location
[1 0 1 0 1 0 0 0 0 0 0 0
 0 1 0 1 0 1 0 0 0 0 0 0
...
]

For example for first row
1 0 1 0 1 0 0 0 0 0 0 0
User 801 visited 3 locations and those are 1. (The location of the 1's can be variable I gave it to be an example)

A: As you have tagged the question with pandas, here is one way of approaching the problem with str.get_dummies method of the pandas Series:
df = pd.read_csv('datausers.txt', sep='\s+', names=['userid', 'locationid'], index_col=0)
out = df['locationid'].astype(str).str.get_dummies().sum(level=0)

Result
For the sample data
>>> out
        10201  10259  14470  15810  19264  32332  33847  34041  34827  34834  35407  36115
userid
801         0      0      1      0      0      1      1      0      0      0      0      0
501         1      1      0      0      0      0      0      1      0      0      0      0
301         0      0      0      1      1      0      0      0      1      0      0      0
401         0      0      0      0      0      0      0      0      0      1      1      1

If you need numpy array instead:
>>> out.to_numpy()

array([[0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0],
       [1, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0],
       [0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0],
       [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1]])


text:
Q: how to store data in arrays, use functions for I want to save data into an array using the for function. the following script is used:
int[] U;
int k = 0;

String ukecil = i.getStringExtra("ukecil");
String ubesar = i.getStringExtra("ubesar");

int ukk = Integer.parseInt(ukecil);
int ukb = Integer.parseInt(ubesar);

for (int j=ukk; j<=ukb; j++){
  U[k]= j;
  k++;
}

tx_uk1.setText(U[0]);
tx_uk2.setText(U[1]);
tx_uk3.setText(U[2]);

then I want to display data in text view.
but there is an error which is:
java.lang.NullPointerException: Attempt to write to null array

this section error:
U[k]= j;

A: You need to specify the size of the array.
int[] U=new int[size];

If you want dynamic size, use ArrayList.
ArrayList<Integer> U = new ArrayList<Integer>();
U.add(k++,j); //index,element

A: Here's the full code
ArrayList<Integer> U = new ArrayList<>();
int k = 0;

String ukecil = i.getStringExtra("ukecil");
String ubesar = i.getStringExtra("ubesar");

int ukk = Integer.parseInt(ukecil);
int ukb = Integer.parseInt(ubesar);

for (int j=ukk; j<=ukb; j++){
     U.add(k++,j);//Updated
}

tx_uk1.setText(U.get(0)+"");
tx_uk2.setText(U.get(1)+"");
tx_uk3.setText(U.get(2)+"");

Hope this helps.......