text:
Q: How can I do this in Java? (REL. TO FUNCTIONS) How can I make a function like String.toUpperCase() , where suppose I make a function Character.isVowel()
Where, I'll simply have to write 'A'.isVowel() and get a boolean result; just like "code".toUpperCase();
which gives me output , CODE.
Only if possible ; can you tell me how can I do so?

A: You cannot do this by extending Character because it is a final class (you cannot extend it), but even if you could, you could not just simply cast for example your character to the subclass (you would had to make a corresponding constructor for example).
You could however try something like:
public class Main {

    //Supports only english vowels (uperrcase, or lowercase):
    public static boolean isVowel(final int codePoint) {
        return "aeiouyAEIOUY".indexOf(codePoint) >= 0;
    }

    public static void main(final String[] args) {
        System.out.println(isVowel('A')); //true.
        System.out.println(isVowel('b')); //false.
    }
}

but again you will have to define all the vowels of all languages manually (both uppercase and lowercase).
I also checked regexes in Java, but did not find anything about a Vowel class for example.

A: I am not sure what you want to know. If you only want to create a upper case string out of a lower case string use toUpperCase(). Or do you want to know how to extend the String class? Suraj Gautam answerd this question in the comments:

String is an immutable class. You cannot extend it.

A: Methods that look like instance methods although they are not part of the actual class are called "Extension methods". Java does currently not support them. See also this question.


text:
Q: Regex to replace specified lower case char to upper case in Javascript Webstorm IDE I'm coding with Jetbrain's Webstorm IDE and have code like this:
'box-sizing': 'border-box',
'user-select': 'none',

I have to convert this to:
'boxSizing': 'border-box',
'userSelect': 'none',

I try to using Webstorm's regex replacement with regular expression:
(?<='\w+)-(\w)(?=\w+':)

and replacement is:
\U$1

But it fails because it doesn't match anything.

A: Assuming, regex is selected in search/replace fields of IntelliJ IDE.
In search field:
(.*?)(\-)(.*?\':)

and in Replace field:
$1\u$3

Hit replace. It should transform
'box-sizing': 'border-box',
'user-select': 'none',

Into
'boxSizing': 'border-box',
'userSelect': 'none',

redpajama_set_name: RedPajamaStackExchange


text:
Q: Implementing attention with beam search in tensorflow I have written my own code with reference to this wonderful tutorial and I am not able to get results when using attention with beam search as per my understanding in the class AttentionModel the _build_decoder_cell function creates separate decoder cell and attention wrapper for inference mode , assuming this ( which i think is incorrect and cant find a way around it ) ,
with tf.name_scope("Decoder"):

mem_units = 2*dim
dec_cell = tf.contrib.rnn.BasicLSTMCell( 2*dim )
beam_cel = tf.contrib.rnn.BasicLSTMCell( 2*dim )
beam_width = 3
out_layer = Dense( output_vocab_size )

with tf.name_scope("Training"):
    attn_mech = tf.contrib.seq2seq.BahdanauAttention( num_units = mem_units,  memory = enc_rnn_out, normalize=True)
    attn_cell = tf.contrib.seq2seq.AttentionWrapper( cell = dec_cell,attention_mechanism = attn_mech )

    batch_size = tf.shape(enc_rnn_out)[0]
    initial_state = attn_cell.zero_state( batch_size = batch_size , dtype=tf.float32 )
    initial_state = initial_state.clone(cell_state = enc_rnn_state)

    helper = tf.contrib.seq2seq.TrainingHelper( inputs = emb_x_y , sequence_length = seq_len )
    decoder = tf.contrib.seq2seq.BasicDecoder( cell = attn_cell, helper = helper, initial_state = initial_state ,output_layer=out_layer )
    outputs, final_state, final_sequence_lengths= tf.contrib.seq2seq.dynamic_decode(decoder=decoder,impute_finished=True)

    training_logits = tf.identity(outputs.rnn_output )
    training_pred = tf.identity(outputs.sample_id )

with tf.name_scope("Inference"):

    enc_rnn_out_beam   = tf.contrib.seq2seq.tile_batch( enc_rnn_out   , beam_width )
    seq_len_beam       = tf.contrib.seq2seq.tile_batch( seq_len       , beam_width )
    enc_rnn_state_beam = tf.contrib.seq2seq.tile_batch( enc_rnn_state , beam_width )

    batch_size_beam      = tf.shape(enc_rnn_out_beam)[0]   # now batch size is beam_width times

    # start tokens mean be the original batch size so divide
    start_tokens = tf.tile(tf.constant([27], dtype=tf.int32), [ batch_size_beam//beam_width ] )
    end_token = 0

    attn_mech_beam = tf.contrib.seq2seq.BahdanauAttention( num_units = mem_units,  memory = enc_rnn_out_beam, normalize=True)
    cell_beam = tf.contrib.seq2seq.AttentionWrapper(cell=beam_cel,attention_mechanism=attn_mech_beam,attention_layer_size=mem_units)

    initial_state_beam = cell_beam.zero_state(batch_size=batch_size_beam,dtype=tf.float32).clone(cell_state=enc_rnn_state_beam)

    my_decoder = tf.contrib.seq2seq.BeamSearchDecoder( cell = cell_beam,
                                                       embedding = emb_out,
                                                       start_tokens = start_tokens,
                                                       end_token = end_token,
                                                       initial_state = initial_state_beam,
                                                       beam_width = beam_width
                                                       ,output_layer=out_layer)

    beam_output, t1 , t2 = tf.contrib.seq2seq.dynamic_decode(  my_decoder,
                                                                maximum_iterations=maxlen )

    beam_logits = tf.no_op()
    beam_sample_id = beam_output.predicted_ids

when i call beam _sample_id after training i am not getting correct result.
my guess is that we are supposed to using the same attention wrapper but that is not possible since we have to tile_sequence for beam search to be used.
Any insights / suggestion would be much appreciated.
i have also created an issue for this in their main repository Issue-93

A: I'm not sure what do you mean by "I am not able to get results" but I'm assuming that your model is not making use of the wieghts learnt while training .
if this is the case  , then first of all you need to know that its all about variable sharing  , the first thing you need to do is that you get rid of the different variable scopes between the training and inferring and instead you need to use some thing like
remove the
with tf.name_scope("Training"):

and use :
with tf.variable_scope("myScope"):

and then remove the
with tf.name_scope("Inference"):

and use instead
with tf.variable_scope("myScope" , reuse=True):

also at the beginning of your and after with tf.variable_scope("myScope" )
enc_rnn_out   = tf.contrib.seq2seq.tile_batch( enc_rnn_out   , 1 )
seq_len       = tf.contrib.seq2seq.tile_batch( seq_len       , 1 )
enc_rnn_state = tf.contrib.seq2seq.tile_batch( enc_rnn_state , 1 )

this will insure that your inference variables and training variables have the same signature and are shared  ,
I have tested this when I was following the same tutorial that you have mentioned , my model is still training as I'm writing this post but I can see that the accuracy increasing as we speak , which indicates that the solution should work for you as well .
thank you

A: You can use tf.cond() to create different pathes between training and inference stage:
def get_tile_batch(enc_output, source_sequence_length, enc_state, useBeamSearch):
    enc_output = tf.contrib.seq2seq.tile_batch(enc_output, multiplier=useBeamSearch)
    source_sequence_length = tf.contrib.seq2seq.tile_batch(source_sequence_length, multiplier=useBeamSearch)
    enc_state = tf.contrib.seq2seq.tile_batch(enc_state, multiplier=useBeamSearch)
    return enc_output, source_sequence_length, enc_state

## for beam search: at training stage, use tile_batch multiplier = 1,
## at infer stage, use tile_batch multiplier = useBeamSearch
## tile_batch is just duplicate every sample in a batch,
## so it'll change batch_size to batch_size * useBeamSearch at runtime once batch_size was determined
enc_output, source_sequence_length, enc_state = tf.cond(
    self.on_infer, # is inference stage?
    lambda: get_tile_batch(enc_output, source_sequence_length, enc_state, useBeamSearch=useBeamSearch),
    lambda: get_tile_batch(enc_output, source_sequence_length, enc_state, useBeamSearch=1)
)

# attention mechanism
attention_mechanism = tf.contrib.seq2seq.BahdanauAttention(num_units=rnn_size, memory=enc_output, memory_sequence_length=source_sequence_length)
dec_cell = tf.contrib.seq2seq.AttentionWrapper(dec_cell, attention_mechanism)
## for beam search: change batch_size to batch_size * useBeamSearch at infer stage
decoder_initial_state = tf.cond(
    self.on_infer, # is inference stage?
    lambda: dec_cell.zero_state(batch_size=batch_size * useBeamSearch, dtype=tf.float32),
    lambda: dec_cell.zero_state(batch_size=batch_size * 1, dtype=tf.float32)
)
enc_state = decoder_initial_state.clone(cell_state=enc_state)


text:
Q: Why ESLint doesn't see all the quotes problems of a JS file? Problem: ESLint doesn't see all the quotes problems in my JS file where I use React.
Expected: See that ESLint checks my errors and show them to me .
Things that I tried: I changed some quotes to see the difference and I saw that for the imports ESLint is working, but in the components it doesn't. I checked my rules and there is the 'quotes' rule. I checked my errors to be exactly and just for quotes and I saw that there weren't any problems.

I will attach an image with the problem:

As you can see, in the first line is everything ok, because I put double quotes. Then in the second and in the third lines there are simple quotes and ESLint can see them. It can be seen that ESLint can see just the quotes problem, nothing more.
And then, then it comes the problem. At the 'flex-container' it can't see that there must be double quotes and it can't fix that. And it's not just an exeption, because on the last line are also single quotes and it can't see that.
My .eslintrc.json file:
{
    "env": {
        "browser": true,
        "es2021": true,
        "node": true,
        "amd": true,
        "jquery": true
    },
    "extends": [
        "eslint:recommended",
        "plugin:react/recommended"
    ],
    "parserOptions": {
        "ecmaVersion": 12,
        "sourceType": "module"
    },
    "rules": {
        "react/prop-types": "off",
        "react/jsx-uses-react": "warn",
        "react/react-in-jsx-scope": "off",
        "quotes": [
            "error",
            "double",
            {
                "avoidEscape": true
            }
        ]
    },
    "globals": {
        "React": true,
        "ReactDOM": true,
        "ReactRedux": true,
        "ReactRouterDOM": true,
        "Redux": true
    },
    "settings": {
        "react": {
            "version": "detect"
        }
    }
}

There I changed some properties for rules, to put 'error' instead of 'off' or 'warn', but it is the same.
What can I do?

A: So, the answer from the ESLint authors is:
"The quotes rule works as intended in this case, because it checks only string literals.
For JSX attributes you can use the jsx-quotes rule, as in this demo."


text:
Q: How do I stop evaluating a list of functions once I've caught an exception I have three functions I map over, I wish to stop evaluation upon catching an exception.
I can catch the exception, but am not getting the behavior I want. It could be that I'm thinking about this problem in the incorrect way (maybe I shouldn't be map a list of functions in this case), and would appreciate this being pointed out. Here's what I think is the relevant code.
import qualified Control.Exception as C
data JobException = PreProcessFail
                  | JobFail
                  | ChartFail
                     deriving (Show, Typeable)

instance C.Exception JobException

type ProcessState = MVar ProcessConfig

data ProcessConfig = PConfig { model :: ServerModel
                             , ipAddress :: String
                             , cookie :: Cookie
                             } deriving Show

exceptionHandler :: JobException -> IO ()
exceptionHandler exception = do
   writeFile "testException.txt" ("caught exception " ++ (show exception))
-- much more functionality will be put here once I get the logic correct
preProcess :: ProcessState -> IO ()
preProcess sModel = do
   putStrLn ("preProcessing" )

initiateJob :: ProcessState -> IO ()
initiateJob sModel = do
   C.throw JobFail
   putStrLn ("in progress")
makeChart :: ProcessState -> IO ()
makeChart sModel = do
     putStrLn ("chart making")

So now, when I test this out in ghci, this is what happens.
a <- mapM (flip Control.Exception.catch exceptionHandler) [preProcess world, initiateJob world, makeChart world]
Loading package filepath-1.2.0.0 ... linking ... done.
Loading package unix-2.4.2.0 ... linking ... done.
preProcessing
chart making

I should not be seeing the string "chart making". How do I abort the evaluation of the list upon throwing an exception?

A: mapM maps the function then sequences the list. So you've got a catch around each action in the list separately. What you want is to sequence the list into a single action, and then catch the exception once so interrupting everything else in the list. The following works:
(flip Control.Exception.catch exceptionHandler) $ sequence_ [preProcess world, initiateJob world, makeChart world]


text:
Q: Significant change in estimate with new observation? Suppose I have some yearly observations (e.g. rates) $x_1$,$x_2$...,$x_{t-1}$. I estimate some parameter of interest as $\bar{x}_{t-1}=\frac{1}{t-1}\sum_i{x_i}$.
Now at year $t$, I get a new observation $x_t$, so that I can compute $\bar{x}_{t}$.

*

*How can I "decide" if I need to update my estimate from $\bar{x}_{t-1}$ to $\bar{x}_{t}$?

*I get new observations for subsequent years, how can I "decide" to update my estimate or not?

A: Your estimate of $\bar{x}_{t-1}$ is an estimate of a different quantity than your estimate of $\bar{x}_t$. So, you should always update, but recognize you are estimating something else each time.
Let's make this more concrete. Suppose your $x_i$ are average interest rates on a particular type of investment. Then $\bar{x}_t$ is the average interest rate over the previous $t$ years. $\bar{x}_{t-1}$ is the average over years $1$ to $t-1$.

A: I have never used it for this kind of problem, but I think what you are asking for is the information lost by modelling the value of interest, say $\bar{x}$, by using either $\bar{X}_t$ or $\bar{X}_{t-1}$. If that's the case, my first guess would be to use the Akaike's Information Criterion (AIC) (or the AICc if you have a low number of samples) in order to estimate the (relative) information loss of using $\bar{X}_t$ or $\bar{X}_{t-1}$: if the value of the AIC for both models is less than 2, then both models are indistinguishable, and it makes no sense to update the model.
The only "problem" of using the AIC is that you need a model for the likelihood; however, if you have a relatively large number of observations, you can rely on the Central Limit Theorem if you are willing to put constraints on the stochastic process that makes up the noise.

A: Related to Peter Flom's point, what is the population you are trying to estimate the parameter in?
If you expect x to be similarly reflected in all years (and assume year to year differences are just random error), then you could just do a power calculation to find out the number of observations needed to estimate a mean value at a given level of precision.

A: $\bar{X}_t = \frac{(t-1)}{t}\bar{X}_{t-1} + \frac{1}{t}X_t$ so I suppose you could say that if $\frac{1}{t}(X_t - \bar{X}_{t-1}) > \epsilon$, then update.  You can make similar formulas for more than one year.


text:
Q: Fixed Header Grid View ASP.NET I gone through lots of examples for fixed header grid view, and tried few options using div and java scripts. the one i didnot work from the example,  is there anything i miss here.
 CSS
.gridViewHeader
{
     background-color:Navy;
    color:blue;
    font-size:12px;
    font-weight:bold;
    position:relative;
    z-index:10;
   top:expression(<%= gv.HeaderRow %>.offsetParent.scrollTop-2);
}

design source

        <asp:GridView ID="gv" runat="server" CellPadding="4" PageSize="50" RowHeaderColumn="True"
            AllowPaging="True" BackColor="White" BorderColor="#3366CC" BorderStyle="None"
            BorderWidth="1px" CssClass="gridViewHeader">
            <PagerSettings Mode="NumericFirstLast" />
            <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" VerticalAlign="Middle" />
            <RowStyle BackColor="White" ForeColor="#003399" BorderStyle="Inset" HorizontalAlign="Center"
                VerticalAlign="Middle" Wrap="False" />
            <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
        </asp:GridView>

        <asp:HiddenField ID="hiddenfield1" runat="server"  />
    </asp:Content>

A: you can use
<HeaderStyle CssClass="gridViewHeader" />

For your sample
<asp:GridView ID="gv" runat="server" CellPadding="4" PageSize="50" RowHeaderColumn="True"
            AllowPaging="True" BackColor="White" BorderColor="#3366CC" BorderStyle="None"
            BorderWidth="1px" >

            <HeaderStyle CssClass="gridViewHeader" />

            <PagerSettings Mode="NumericFirstLast" />
            <PagerStyle BackColor="#99CCCC" ForeColor="#003399" HorizontalAlign="Left" VerticalAlign="Middle" />
            <RowStyle BackColor="White" ForeColor="#003399" BorderStyle="Inset" HorizontalAlign="Center"
                VerticalAlign="Middle" Wrap="False" />
            <SelectedRowStyle BackColor="#009999" Font-Bold="True" ForeColor="#CCFF99" />
        </asp:GridView>

A: This CSS will fix your problem:
.GVFixedHeader { font-weight:bold; background-color: Green; position:relative;
             top:expression(this.parentNode.parentNode.parentNode.scrollTop-1);}

A: I just did this very thing. I used this article as a reference.
http://csharpdotnetfreak.blogspot.com/2009/07/scrollable-gridview-fixed-headers-asp.html
The trick is to create a table and then place the grid inside a div just under the that table. Set the width of the detail cells the same width as the cells in the gridview. Then make sure the scroll bar stays on and then the grid and the table will line up in the event there are not enough rows to actually need the scrolling function.


text:
Q: How to change color of menukeys? I cannot understand how to change the colors of the text in the menus typeset using menukeys.  A minimal example (taken from the menukeys manual) follows:
\documentclass[12pt]{article}
\usepackage[T1]{fontenc}
\usepackage{xcolor}
\usepackage{menukeys}
\pagestyle{empty}

\begin{document}
\noindent%
\menu{Alfa > Beta > Gamma} \\
\directory{One / Two / Three} \\
\keys{\cmd + \shift + 4} \\[4ex]
\renewmenumacro{\menu}[>]{roundedmenus}
\menu{Alfa > Beta > Gamma} \\[4ex]
\changemenucolor{menu}{txt}{named}{red}
\changemenucolor{roundedmenus}{txt}{named}{red}
\menu{Alfa > Beta > Gamma}
\end{document}

(the second \changemenucolor has been added since the first one didn't work; but the \renewmenumacro works like expected).  Any hint?

A: Indeed the menukeys manual could contain a few more examples, but I'm sure that Tobi will do something for it (sooner or later).
Anyway, when you issue the command \changemenucolor you have to refer to a  "color theme" as a first argument (see Section 4.3 of the documentation:
\changemenucolor{<theme name>}{<element>}{<model>}{<color definition>}

There are two predefined color themes, gray and blacknwhite. You can even create new ones through the command \newmenucolortheme.
Anyway, unless you change it with \changemenucolortheme, the one used by default is gray, so the command you have to issue is
\changemenucolor{gray}{txt}{named}{red}

Complete MWE:
\documentclass[12pt]{article}
\usepackage[T1]{fontenc}
\usepackage{xcolor}
\usepackage{menukeys}
\pagestyle{empty}

\begin{document}
\noindent%
\menu{Alfa > Beta > Gamma} \\
\directory{One / Two / Three} \\
\keys{\cmd + \shift + 4} \\[4ex]
\renewmenumacro{\menu}[>]{roundedmenus}
\menu{Alfa > Beta > Gamma} \\[4ex]
\changemenucolor{gray}{txt}{named}{red}
\menu{Alfa > Beta > Gamma}
\end{document}

Output:


text:
Q: How to override a module method in rails I have a module that is included in a model. In this module, there is a foo method that I would like to override without modifying the existing model and module code.
My idea was to create a file /lib/my_module_extend.rb.
I don't know how to override the method in question because it's not like overriding a method in a class. I usually do:
module MyOriginalClassExtend
  ...
end

MyOriginalClass.class_eval do
  prepend(MyOriginalClassExtend)
end

but class_eval is not possible for a module. Do you have any idea?

A: You can follow the same approach as for open class in ruby. You could just write an extension file in config/initializers and the method will be overridden when the application is loaded.
The below one could be more useful for anyone using Mongoid as the ORM for their application.
I created a extension file for Mongoid::Document module as follows config/initializers/mongoid_document_ext.rb
module Mongoid
  module Document
    def as_json(options={})
      hs = super(options)
      hs["id"] = hs.delete("_id").to_s rescue nil
      hs
    end
  end
end

This monkey patching worked pretty well for me!


text:
Q: mocha, how to handle test cases duplicate code? as you can see, my test case have duplicate part.
How can I handle this? Just write a common function to reuse?
Is there a way of mocha to handle this?
 it('test case 1', function() {
    var target = {
        a: 1,
        b: 1
    };
    var source = {
        c: 1
    };
    expect(deepMerge(target, source)).to.deep.equal({a: 1, b: 1, c: 1});

    //dulplicate
    expect(target).to.eql(target);
    expect(source).to.eql(source);
});

it('test case 2', function() {
    var target = {
        a: 1,
        b: 1
    };
    var source = {
        a: 2,
        c: 1
    };

    expect(deepMerge(target, source)).to.deep.equal({a: 2, b: 1, c: 1});
    //dulplicate
    expect(target).to.eql(target);
    expect(source).to.eql(source);
});
//more test cases also have the duplicate part.

A: you can place all the duplicate expect cases in some function and call that function in every it block;

function duplicateTests(target, source) {
    expect(target).to.eql(target);
    expect(source).to.eql(source);
};

it('test case 1', function() {
    var target = {
        a: 1,
        b: 1
    };
    var source = {
        c: 1
    };
    expect(deepMerge(target, source)).to.deep.equal({a: 1, b: 1, c: 1});

  duplicateTests(target, source);
});

it('test case 2', function() {
    var target = {
        a: 1,
        b: 1
    };
    var source = {
        a: 2,
        c: 1
    };

    expect(deepMerge(target, source)).to.deep.equal({a: 2, b: 1, c: 1});
    duplicateTests(target, source);
});
//more test cases also have the duplicate part.


text:
Q: Request for member 'uitextfield' in something not a structure or union? working through several other problems I have found myself at this point. I have learnt alot about the stuff I am trying to do but this one I am completely stumped on.
I am writing a textfield format for a login I would like to have on my app, and because apple don't have anything that resembling a textfield mask I have decided to write my own custom cell that looks like it has a mask on it but all I will be doing is concatenating textfields in the background.
However I have struck a problem. I am trying to call textField:shouldChangeCharactersInRange:replacementString: of a UITextField in my Subclassed UITableViewCell as outlined in my code below. However Im receiving Request for member 'uitextfield' in something not a structure or union error... any help would be appreciated.
////.h
@interface RegisterDeviceViewController : UIViewController <UITableViewDelegate, UITextFieldDelegate> {

    RegisterDeviceViewController *registerDeviceViewController;

    //UITextFields for the registration cell
    UITextField *regFieldOne;
    UITextField *regFieldTwo;
    UITextField *regFieldThree;
    UITextField *regFieldFour;

    UITableViewCell *myRegistrationField;
    UITableViewCell *mySubmitButton;

}
//UITextFields for the registration cell
@property (nonatomic, retain) IBOutlet UITextField *regFieldOne;
@property (nonatomic, retain) IBOutlet UITextField *regFieldTwo;
@property (nonatomic, retain) IBOutlet UITextField *regFieldThree;
@property (nonatomic, retain) IBOutlet UITextField *regFieldFour;

@property (nonatomic, retain) IBOutlet UITableViewCell *myRegistrationField;
@property (nonatomic, retain) IBOutlet UITableViewCell *mySubmitButton;

@end

/////.m
#import "RegisterDeviceViewController.h"

@implementation RegisterDeviceViewController

//Custom registration cell fields
@synthesize regFieldOne;
@synthesize regFieldTwo;
@synthesize regFieldThree;
@synthesize regFieldFour;

@synthesize myRegistrationField;
@synthesize mySubmitButton;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    self.title = @"Registration";
    [super viewDidLoad];
}

//Sets number of sections in the table
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

// Sets the number of rows in each section.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

//Loads both Custom cells into each section
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"mythingy"];
    if (cell == nil) {
        cell = myRegistrationField;
    }

    UITableViewCell *cellButton = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:@"mummy"];
    if (cellButton == nil) {
        cellButton = mySubmitButton;
    }

    if (indexPath.section == 0) {
        return cell;

        cell.regFieldOne.delegate = self; //This is where the error is.
    }
    return cellButton;

}

//This delegate method is not being called.
//textField:shouldChangeCharactersInRange:replacementString:
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    int length = [regFieldOne.text length] ;
    if (length >= MAXLENGTH && ![string isEqualToString:@""]) {
        regFieldOne.text = [regFieldOne.text substringToIndex:MAXLENGTH];
        return NO;
    }
    return YES;
}

..........

A: regFieldDone is not a member of cell (table view cell). Its a member of your class register device view controller. If you are trying to set regFieldDone's delegate to self, then change that statement to regFieldDone.delegate = self
EDIT: You can directly set all text field's delegate to RegisterDeviceViewController (file owner) from the xib file.
You have only set regFieldDone's delegate to self, what about other textField's delegate? So when you edit other textField's, the delegate method will not get called.
You should notice that shouldChangeCharactersInRange... method gets called while editing regFieldDone and doesnt while editing other textField's. I advice you to set all textField's delegate to self, either programatically or from xib file.


text:
Q: Galois group of quartic polynomial
Let $f(x)$ be a quartic polynomial over $\mathbb{Q}$, and let $K$ be the splitting field of $f(x)$ over $\mathbb{Q}$.

I know that the following facts:

*

*If $f(x)$ is separable over $\mathbb{Q}$, then the Galois group $G_{f}$ of $f(x)$ is isomorphic to the symmetric group $S_{4}$.

*$f(x)$ is irreducible over $\mathbb{Q}$ if and only if $G_{f}$ is isomorphic to a transitive subgroup of the symmetric group $S_{4}$.
What can we say about that the Galois group for an arbitrary quartic polynomial over $\mathbb{Q}$?
Some problem claims that if $f(x)$ is a quartic polynomial over $\mathbb{Q}$ with splitting field $K$ satisfying $[K:\mathbb{Q}]=8$, then $G_{f}\cong D_{4}$, where $D_{4}$ is the dihedral group of order $8$.
I think we need the condition separability or irreducibility of $f(x)$ over $\mathbb{Q}$ is needed, but there's nothing like that.
Do I miss something or have a misconception? Give some advice or comments. Thank you!


text:
Q: Math behind rotation in MS Paint For those who don't know, MS Paint only has the options to rotate an image by right angles. To carry out an arbitrary rotation ($\theta^\circ$), the following hack is suggested:

*

*Horizontal skew by $\theta$

*Vertical Stretch by $\displaystyle \frac{1}{\cos^2\theta}$

*Vertical Skew by  $-\theta$

*Horizontal and Vertical Stretch by $\cos \theta$

I would like to know how this works.
(I guess one way would be to show that multiplying the above operations represented as matrices should return the $2$D rotation matrix, but I do not know what are the matrix representations for the intermediate steps.)

A: Use a planar affine transformation.
As you pointed out, your operations are translation, rotation, shearing (skew) and scaling (stretch). We will represent each point on your image in homogeneous coordinates which allows us to use the composite matrix operations. Homogeneous coordinates just means that we tack on a $1$. So if a point has the coordinates $(x,y)$ the vector in homogeneous coordinates is
$$u = \begin{bmatrix} x \\ y \\ 1 \end{bmatrix} $$
The transformation matrix to translate the image by $t_x$ and $t_y$ is:
$$ T = \begin{bmatrix} 1 & 0 & t_x \\ 0 & 1 & t_y \\ 0 & 0 & 1 \end{bmatrix} $$
The rotation matrix to rotate it by $\theta$ degrees is:
$$ T = \begin{bmatrix} \cos \theta & -\sin \theta & 0 \\ \sin \theta & \cos \theta & 0 \\ 0 & 0 & 1 \end{bmatrix} $$
The scaling matrix to scale each dimension is:
$$ T = \begin{bmatrix} s_x & 0 & 0 \\ 0 & s_y & 0 \\ 0 & 0 & 1 \end{bmatrix} $$
The shearing matrix:
$$ T = \begin{bmatrix} 1 & a_x & 0 \\ a_x & 1 & 0 \\ 0 & 0 & 1 \end{bmatrix} $$
And all you have to do is multiply these matrices to composite these transformations. E.g. suppose you wanted to rotate and shear:
$$
\begin{bmatrix}x' \\ y' \\ w' \end{bmatrix} =
\begin{bmatrix} \cos \theta & -\sin \theta & 0 \\ \sin \theta & \cos \theta & 0 \\ 0 & 0 & 1 \end{bmatrix}
\begin{bmatrix} 1 & a_x & 0 \\ a_y & 1 & 0 \\ 0 & 0 & 1 \end{bmatrix}
\begin{bmatrix}x \\ y \\ 1 \end{bmatrix}
$$
And to obtain the point in screen coordinates just normalize by $w$, i.e.
$$(x', y') = (x'/w',y'/w')$$

A: It is worth noting that you can accomplish rotation with only a single trip to the Resize and Skew menu.
Paint applies the operations in the order: Resize, Skew Horizontal, Skew Vertical.
As a sequence of matrix transforms acting on a column vector, that is:
$$(\begin{bmatrix}1&0\\K_v&1\end{bmatrix}(\begin{bmatrix}1&K_h\\0&1\end{bmatrix}(\begin{bmatrix}S_h&0\\0&S_v\end{bmatrix}\begin{bmatrix}x\\y\end{bmatrix})))$$
Where $K_v$ and $K_h$ are the vertical and horizontal skew factors, and $S_v$ and $S_h$ are likewise the scale factors.
Because matrix multiplication is associative, let's remove the parentheses and multiply these transforms from left to right to give an equivilent single-matrix transform:
$$\begin{bmatrix}S_h&K_hS_v\\S_hK_v&K_hK_vS_v+S_v\end{bmatrix}\begin{bmatrix}x\\y\end{bmatrix}$$
Setting this matrix equal to the rotation matrix, $\begin{bmatrix} \cos(θ) & \sin(θ) \\ -\sin(θ) & \cos(θ) \end{bmatrix}$, we get a system of equations which we can solve for our scale and skew factors:
$$S_h = \cos(θ)$$
$$K_h = \sin(θ)cos(θ)$$
$$S_v =1/\cos(θ)$$
$$K_v = -\tan(θ)$$
These variables describe factors in an affine transformation, but paint wants "% Resizing" and "degrees skew", so input:
$$\%R_h = 100*S_h=100*\cos(θ)$$
$$\%R_v = 100*S_v=100/\cos(θ)$$
$$DegSk_h = \arctan(K_h)=\arctan(\sin(θ)\cos(θ))$$
$$DegSk_v = \arctan(K_v) = \arctan(-\tan(θ))=-θ$$
As an operational note: Paint will automatically resize your selection after a skew if the skew transformation would put the selection outside of the canvas, so make sure you have plenty of room around your selection.

A: Let's call the transformations $T_1,T_2,T_3,T_4$. The horizontal skew $T_1$ through angle $\theta$ should send $e_1=\begin{pmatrix}1\\0\end{pmatrix}$ to  $e_1$ and send $e_2=\begin{pmatrix}0\\1\end{pmatrix}$ to $\begin{pmatrix}\tan\theta\\1\end{pmatrix}$. So the matrix implementing this transformation (which I'll also call $T_1$) has these vectors as its columns: $T_1=\begin{pmatrix}1&\tan\theta\\0&1\end{pmatrix}$.
Similar considerations give $T_2=\begin{pmatrix}1&0\\0&1/(\cos^2\theta)\end{pmatrix}$, $T_3=\begin{pmatrix}1&0\\-\tan\theta&1\end{pmatrix}$ and $T_4=(\cos \theta) I$. Multiplying these matrices together:
$ T_4T_3T_2T_1=\begin{pmatrix}\cos\theta&\sin\theta\\ -\sin\theta&\cos\theta\end{pmatrix}$
which is the matrix of rotation by the angle $\theta$ in a clockwise direction (as you can verify by figuring out what the columns of this rotation transformation should be).

A: In fact, you can apply any invertible linear transformation $\binom xy\mapsto \begin{pmatrix}a&b\\c&d\end{pmatrix}\binom xy$ to your image by only using a sequence of skew, stretch and flip transformations. This is due to the fact that the invertible matrices are generated by the so-called elementary matrices:

*

*The elementary skew matrices are the matrices of the form $\begin{pmatrix}1&a\\0&1\end{pmatrix}$ and $\begin{pmatrix}1&0\\a&1\end{pmatrix}$ for $a\in\mathbb R$. With these you can apply any linear transformation which doesn't change the area of the image and which doesn't change the orientation of the image. In fancier language: the skew matrices generate the special linear group.

*The elementary stretch matrices are of the form $\begin{pmatrix}a&0\\0&1\end{pmatrix}$ and $\begin{pmatrix}1&0\\0&a\end{pmatrix}$ for $a> 0$. Combining these with the matrices above, we can generate any invertible matrix which doesn't change the orientation of the image.

*Finally, we need the flip matrices $\begin{pmatrix}-1&0\\0&1\end{pmatrix}$ and $\begin{pmatrix}1&0\\0&-1\end{pmatrix}$ to change the orientation of the image ("flip it inside out", like turning a paper around and looking at it from behind).
As an example, we can interchange the x and y axes, that is, map $\binom xy$ to $\binom yx$, by the following operations:

*

*Shear horizontally by 45 degrees.

*Shear vertically by -45 degrees.

*Shear horizontally by 45 degrees.

*Flip vertically.

A: I think the following matrix product gives an explanation.
The first step is given by the matrix
$$
S_1=\left(\begin{array}{cc}1&\tan\theta\\0&1\end{array}\right).
$$
The second step corresponds to
$$
D_1=\left(\begin{array}{cc}1&0\\0&\frac{1}{\cos^2\theta}\end{array}\right).
$$
The second shearing operation corresponds to
$$
S_2=\left(\begin{array}{cc}1&0\\-\tan\theta&1\end{array}\right).
$$
At this point we have done $S_2D_1S_1$ that after a little bit of matrix manipulation and using the identity $\sin^2\theta +\cos^2\theta=1$ becomes
$$
S_2D_1S_1=\left(\begin{array}{cc}1&\tan\theta\\-\tan\theta&1\end{array}\right).
$$
The last step amounts to a scalar multiplication by $\cos\theta$ and gives us the familiar rotation matrix
$$
\cos\theta S_2D_1S_1=\left(\begin{array}{rc}\cos\theta&\sin\theta\\-\sin\theta&\cos\theta\end{array}\right).
$$

Edit: I got to use this as an exercise in a freshman course that just ended. I was actually a bit unhappy with that youtube video, because it doesn't show the transitions from one step to the other. To fix this problem I made an animation, where the four steps are done gradually: in steps one and three I continuously move the shear (skew) parameter from zero to the desired value. Similarly in steps two and four the scaling parameter changes continuously from one to the proper value. All the steps are done sequentially.


text:
Q: Run Java Code Online codepad.org allow you to run C,C++,D etc code online but not Java... is there a site that I can use for Java?

A: Ideone is the best site for the online code running, debugging and it provides extra performance stats also.
Without Sign Up, you can run code upto of maximum 5 sec, and for signup, upto a max of 15 sec. And for Signup, the code management and history is also too good.
However, it has some maximum amount of submissions per month for registered users.
www.ideone.com
It supports more than 40 languages, and is integrated with SPOJ and RecruitCoders.

A: Compilr is an online java compiler. It provides syntax highlighting and reports any errors back to you.  It's a project I'm working on, so if you have any feedback please leave a comment!

A: http://ideone.com/ideone/Index/submit/
 you can run your java code

A: Some new java online compiler and runner:

*

*Java Launch

*Srikanthdaggumalli
These sites are in under development. But you can view the compilation errors, Runtime Exceptions as well as output of a java program by clicking on the TryItYourself link.

A: rextester runs java snippets
Also accessible as runjavaonline.com

A: I found this online java compiler and runner. It work also with threads and showing results immediately. http://www.browxy.com

A: there is also http://ideone.com/ (supports many languages)

A: OpenCode appears to be a project at the MIT Media Lab for running Java Code online in a web browser interface. Years ago, I played around a lot at TopCoder. It runs a Java Web Start app, though, so you would need a Java run time installed.

A: Zamples is another site where you write a java code and run it online. Here you have possibility to choose jdk version also.
http://www.zamples.com/JspExplorer/index.jsp?format=jdk16cl


text:
Q: Search filter from array on Angular I have application which stores a list of cars.I wanted to add Search property into my project.I decided to use pipe and ngModel for my searchBox in order to do that.I have an array of those cars being listened by subscribe() whenever anything changes on it.In the pipe,I have const obj variable and it filters the array according to ngModel from component as I wish.But angular gives error and says ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined: [object Object],[object Object],[object Object]'. Current value: 'undefined: '. .I guess its undefined at first thats why its happening.But I added if block in order to check undefined or not, not to get this error .Here's my components and pipe below
Car-List Component.html
  <form class="example" style="margin:auto;max-width:200px">
    <input [(ngModel)]="nameBrand" type="text" placeholder="Search.." name="search2">
  </form>

      <app-car-item
        *ngFor="let carEl of cars | orderName:nameBrand ;let i = index"
        [car]="carEl"
        [index]="i"
        >
      </app-car-item>

OrderPipe.ts
@Pipe({
  name: 'orderName',
})
export class OrderNamePipe implements PipeTransform{
  constructor(private carService:CarService)
  {

  }
  transform(value: any, arg1: any)
   {
      const obj = this.carService.getCars().filter(s => s.brand.includes(arg1));
      if(obj)
      {
           this.carService.setCars(obj);
     }
    }
  }

Car-list.component.ts
  ngOnInit() {
    this.subscription=this.carService.carsChanged
    .subscribe(
     (cars:Car[])=>
     {
       this.cars=cars;
     }
    );
    this.cars = this.carService.getCars();
    }

Car.Service.ts
        export class CarService
    {
       carsChanged=new Subject<Car[]>();
       private cars: Car[]=[
            new Car(
               'Dodge Viper SRT10',
               'Coupe',
               2017,
               645,
               600,
               'Gasoline',
               'Used',
               'http://cdn-ds.com/stock/2010-Dodge-Viper-SRT10-ACR-Ltd-Avail-Akron-OH/seo/ECL2585-1B3AZ6JZ6AV100278/sz_88264/b22eddbbf045c389bd39e4ede1328f13.jpg',
               970000
           ),
           new Car(
            'Chevrolet Camaro',
            'Coupe',
            2012,
            432,
            600,
            'Gasoline',
            'Used',
            'https://carimages.com.au/MdzpzcZ7iNNuMu7RlH3Eg5t30CM=/fit-in/800x540/filters:stretch(FFFFFF)/vehicles/used/2018/CHEVROLET/CAMARO/2018-CHEVROLET-CAMARO-used-78-JWF447-1.jpg',
            274000
        ),
        new Car(
            'Bentley Continental-GT',
            'Coupe',
            2018,
            601,
            489,
            'Gasoline',
            'New',
            'https://cdn1.autoexpress.co.uk/sites/autoexpressuk/files/2017/11/4bentleycontinentalgt.jpg',
            4150000
        )
       ]
       constructor()
       {}
       setCars(cars: Car[]) {
        this.cars = cars;
        this.carsChanged.next(this.cars.slice());
 getCars()
   {
    return this.cars;
   }
      }

Car-Model.ts
export class Car{
    public brand:string;
    public type:string;
    public year:number;
    public bhp:number;
    public torque:number;
    public fuel:string;
    public condition:string;
    public imageUrl:string;
    public price:number;

    constructor(brand:string,type:string,year:number,bhp:number,torque:number,fuel:string,condition:string,imageUrl:string,price:number)
    {
        this.brand=brand;
        this.type=type;
        this.year=year;
        this.bhp=bhp;
        this.torque=torque;
        this.fuel=fuel;
        this.condition=condition;
        this.imageUrl=imageUrl;
        this.price=price;
    }
}

A: I don't think its a good way to use the data from the service inside your pipe. Try this pipe instead,
import { Pipe, PipeTransform, Injectable } from '@angular/core';

@Pipe({
    name: 'orderName'
})

@Injectable()
export class OrderNamePipe implements PipeTransform {
    transform(items: any[], field: string, value: string): any[] {
        if (!items) {
            return [];
        }
        if (!field || !value) {
            return items;
        }
        return items.filter(singleItem => singleItem[field].toLowerCase().includes(value.toLowerCase()));
    }
}

This way, your pipe is reusable. Change your template to,
<app-car-item
    *ngFor="let carEl of cars | orderName : 'brand' : nameBrand ;let i = index"
    [car]="carEl"
    [index]="i"
    >
</app-car-item>

The 'brand' is specified since you need to filter based on that field.


text:
Q: Need suggestion on Parser Design Strategy I need a suggestion on Parser Design Strategy
Consider type1, type2, type3 are three different csv files with different formats which will be parsed by Parser1, Parser2, Parser3 respectively.
In future this will evolve to parse info from other sources like dbs.
Also there will be new parsers to come. what is the best way to design the parser? is factory/ abstract factory a good candidate?
Some benefits and examples would be helpful?
Type1 - Parser1
Type2 - Parser2
Type3 - Parser3

I have put down my code, looking for valuable suggestions.
interface Parser<T>{
    public List<T> parse (string s);
}

//where T - data model

class Parser1CSV implements Parser<Model1>{
    //implement
    //s-csv file
    public List<Model1> parse (string s){
    }
}

class Parser1DB implements Parser<Model1>{
    //implement
    //s- connection string
    public List<Model1> parse (string s){
    }
}

class Parser2CSV implements Parser<Model2>{
    //implement
    //s-csv file
    public List<Model2> parse (string s){
    }
}

//same way other parsers are implemented

interface AbstarctFactory<T>{
    public Parser<T> createParser();
}

class Parser1Factory implements AbstarctFactory<Model1>{
    private String type;
    Parser1Factory(String type){
        this.type = type;
    }

    public Parser<Model1> createParser(){
        if(type.equals("CSV"){
            return new Parser1CSV();
        }else if(type.equals("DB"){
            return Parser1DB();
        }else{
            throw UnSupportedOperationException("Not Supported.");
        }
    }
}

//same way other parser factories are implemented

class ParserFactory{
    public static <T> Parser<T> getParser(AbstarctFactory<T> factory){
        factory.createParser();
    }
}

//Usage:
Parser<Model1> parser = ParserFactory.getParser(new Parser1Factory("CSV"));
List<Model1> list = parser.parse(file);

Currently, I'm not using DI framework. What will be the benefits and impact when I needed to use?

A: 1) Design issues have room for personal interpretation/taste, but all in all I like your approach very much, it's common in the industry due to its flexibility & modularity.
Sometimes I could do without the hierarchy of Factories, but obviously that varies depending on circumstances.
2) What's the use of your "class ParserFactory"? I don't see that it adds flexibility/decoupling, as opposed to the good old "new Parser1Factory("CSV").createParser()"... but perhaps you had some viable design intent which I've missed.
3) Regarding DI, I could mainly testify to Spring - your code will play very nicely with it. The point of DI is "ok, you know how to create parsers, now how do you pass them on to the business code"? E.g. if you have some 'BankService':
// Without DI:
public class BankService {
   private AbstarctFactory factory= new Parser1Factory();
   public void depositFundsFromFile(File file){
      //  use factory
   }
}
// With DI:
public class BankService {
   @Autowired
   private AbstarctFactory factory; // will be injected by the framework
   public void depositFundsFromFile(File file){
      //  use factory
   }
}

=> DI makes BankService truly independent of the concrete factory type: BankService doesn't contain the concrete commitment "new Parser1Factory", so it's ready to work with any factory, it even allows several BankService instances to co-exist , each with a different factory type... Then you'll give the framework separate instructions as to how to create your concrete factori(es) , e.g. "new Parser1Factory("CSV"). With spring such separate instructions come in XML files, or in @Configuration code.
4) Depending on requirements, the DI could also inject a Parser rather than a factory (again, the framework will need separate instructions for Parser creation):
public class BankService ... {
   @Autowired
   private Parser parser; // will be injected from the framework
   public void depositFundsFromFile(File file){
      //  use parser
   }
}

5) You could consider implementing Springs' FactoryBean interface, though you really don't have to: it's a legitimate decision to avoid framework-dependent code.


text:
Q: jQuery OrgChart how to set ajax request headers using https://github.com/dabeng/OrgChart how would I set request headers on ajax call
I was trying the following
$('#chart-container').orgchart({
            'data' : '/api/v1/profiles/orgchart/',
            'beforeSend': function(xhr){xhr.setRequestHeader('X-CSRF-TOKEN', token);},
            'nodeContent': 'account_firstname'
        });

but this do not work

A: Why don't you get json datasource with ajax and then create orgchart with the fetched datasource by your ajax request.
$.ajax({
  'url': '/api/v1/profiles/orgchart/',
  'beforeSend': function(xhr){xhr.setRequestHeader('X-CSRF-TOKEN', token);},
})
.done(function( data ) {
   $('#chart-container').orgchart({
        'data' : data
        'nodeContent': 'account_firstname'
    });
});


text:
Q: X86 assembly instruction to MIPS instruction (Port, IN, I/O) In X86, there is an instruction called IN:
https://c9x.me/x86/html/file_module_x86_id_139.html
https://en.wikipedia.org/wiki/X86_instruction_listings
MIPS does not have this instruction:
http://www.mrc.uidaho.edu/mrc/people/jff/digital/MIPSir.html
I want to write my own IN instruction in MIPS.
How can this be done?
We are writing an operating system using C and MIPS:
https://github.com/uu-os-2018/project-iota
This function results in:
Error: unrecognized opcode inb $2,lo
static inline uint8_t inb(uint16_t port)  {
     uint8_t ret;
    asm volatile ( "inb %1, %0"
                   : "=a"(ret)
                   : "Nd"(port) );
    return ret;
}

A: The significant difference between in/out and memory access instructions is in how the hardware behaves. There is no way for software to make a system that uses I/O-mapped I/O work with memory instructions or vice-versa. Since MIPS systems use only memory-mapped I/O, there is no possible use for in/out instructions.

A: The predecessors of the x86 family (the 8080 and 8085 processors) only had a 16-bit address bus and thus could only use a total of 64 kB of memory.
Reserving some of this space for devices was seen as problematic as it limited the small amount of memory even more. So the processors got a second address space (I/O space), with an additional 64 kB, by using IN and OUT instructions instead of load and store. The difference appeared externally as a special pin, in essence giving the CPU  a 17th address bit.
When Intel designed the 8086, they followed this design from the 8085 as some kind of limited backward compatibility. Despite this the original PC reserved the space between 640 kB and 1 MB for devices using memory mapped I/O. The video board, for example, appeared in this space.
The designers of the MIPS series didn't have those concerns about predecessors, and having gigabytes of address space from the start they didn't see a problem in using some 64 kB of this space for devices. That way they also only had to provide load and store instructions and could skip the IN and OUT.


text:
Q: XML API Request returns "d3p1" for arrays or sub-classes Using Postman, C#, .NET Framework 4.7
I make a GET request from Postman with content-accept set to "application/xml" and my .NET Framework Web API will respond with XML (brilliant!).  I have not needed to serialize anything manually as .NET Framework serializes my response object with when I return Request.CreateResponse(HttpStatusCode.OK, myResponse).
However, it seems to include extra things which I am not familiar with and I am wondering if they can be removed via Global.asax settings or similar?

*

*xmlns="http://schemas.datacontract.org/2004/07/dto.MyModels" is something I would like to remove!

*"d3p1" is not something I have come across when creating XML. Can I remove it somehow?

*<error i:nil="true" /> pops up when something is null. Is it possible to just be  or just not appear when it is null?

So, The XML response looks like this:
<SimpleResponse xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datacontract.org/2004/07/dto.MyModels">
    <error i:nil="true" />
    <result>
        <bookList xmlns:d3p1="http://schemas.datacontract.org/2004/07/dto.MyModels.Shared">
            <d3p1:Book>
                <d3p1:bookname>Book 1 Name</d3p1:bookname>
                <d3p1:serial>ZMeTaQ1kejh0mJYGHE4+1a4Y2juU6tMDd5zYDqN4tqI=</d3p1:serial>
                <d3p1:id>4</d3p1:id>

            </d3p1:Book>
            <d3p1:Book>
                <d3p1:bookname>Hello World</d3p1:bookname>
                <d3p1:serial>9lM16kho3bgsrG+wRh4ejtZjwrYJwp6FbRqnnZ4CJPA=</d3p1:serial>
                <d3p1:id>5</d3p1:id>
            </d3p1:Book>
            <d3p1:Book>
                <d3p1:bookname>Ding</d3p1:bookname>
                <d3p1:serial>XCqqKB+Wi3i4z6nN1Ry8IHtar6ogojjiqxMfvfgC0qc=</d3p1:serial>
                <d3p1:id>6</d3p1:id>
            </d3p1:Book>
        </bookList>
        <author xmlns:d3p1="http://schemas.datacontract.org/2004/07/dto.Models.Android.Shared">
            <d3p1:pictureId>0</d3p1:pictureId>
            <d3p1:websiteurl i:nil="true" />
            <d3p1:email i:nil="true" />
            <d3p1:name>Jo Blogs</d3p1:size>
            <d3p1:age>0</d3p1:size>
        </author>
    </result>
</SimpleResponse>

My classes look something like this:
public string error { get; set;}
public class SimpleResponse
{
 public List<Book> bookList { get; set; }
 public Author author { get; set; }
}

public class Book
{
    public string bookname { get; set; }
    public string serial { get; set; }
    public int id { get; set; }
}

public class Author
{
    public string pictureId{ get; set; }
    public string websiteurl { get; set; }
    public string email { get; set; }
    public string name { get; set; }
    public int age { get; set; }
}

A: xmlns="http://schemas.datacontract.org/2004/07/dto.MyModels" is something I would like to remove!
"d3p1" is not something I have come across when creating XML. Can I remove it somehow?
The attributes:

*

*xmlns="http://schemas.datacontract.org/2004/07/dto.MyModels"

*xmlns:d3p1="http://schemas.datacontract.org/2004/07/dto.MyModels.Shared"
are both XML namespace declarations.  The first establishes a default XML namespace for your XML document; the second declares a namespace to which all child elements prefaced with d3p1: belong.
From the specific namespace chosen, it's apparent you are using DataContractSerializer for XML serialization.  This serializer assigns XML namespaces according to rules documented in Data Contract Names: Data Contract Namespaces

By default, any given CLR namespace (in the format Clr.Namespace) is mapped to the namespace http://schemas.datacontract.org/2004/07/Clr.Namespace. To override this default, apply the ContractNamespaceAttribute attribute to the entire module or assembly. Alternatively, to control the data contract namespace for each type, set the Namespace property of the DataContractAttribute.

Since you don't want an XML namespace for any of your types, the first option would appear to be the easiest: apply the following attributes to your assembly:
[assembly: ContractNamespaceAttribute("", ClrNamespace = "dto.MyModels")]
[assembly: ContractNamespaceAttribute("", ClrNamespace = "dto.MyModels.Shared")]
[assembly: ContractNamespaceAttribute("", ClrNamespace = "dto.Models.Android.Shared")]

Alternatively, you could apply data contract attributes to your types:
[DataContract(Name = "Book", Namespace = "")]
public class Book
{
    [DataMember]
    public string bookname { get; set; }
    [DataMember]
    public string serial { get; set; }
    [DataMember]
    public int id { get; set; }
}

Note that data contract serialization is opt-in so you will need to apply [DataMember] to each member to be serialized.
As a final alternative, you could switch to using XmlSerializer which has no default XML namespace.  To do that you will need to apply [XmlSerializerFormat] to your service contract as shown in Manually Switching to the XmlSerializer.
<error i:nil="true" /> pops up when something is null. Is it possible to just be  or just not appear when it is null?
These null elements can be removed by setting DataMemberAttribute.EmitDefaultValue on reference type data members as shown in this answer to Can I configure the DataContractSerializer to not create optional (i.e. Nullable<> and List<>) elements in output XML? by Darren Clark:
[DataContract(Name = "Book", Namespace = "")]
public class Book
{
    [DataMember(EmitDefaultValue = false)]
    public string bookname { get; set; }
    [DataMember(EmitDefaultValue = false)]
    public string serial { get; set; }
    [DataMember]
    public int id { get; set; }
}

Alternatively you could switch to XmlSerializer which does not output null reference values by default.


text:
Q: Multiple item combo box with headers? Is it possible to have "column headers" on a combo box bound to multiple items? For example a combo box that displays a persons name. The combo box would display John Doe. But I'd like to display column headers:
First   Last
John    Doe
Jane    Doe
Jimmy   Doe

Is this possible without the use of a data grid?
What about a simple solution that includes the use of a data grid? I found one solution for embedding a data grid into a combo box but it looks difficult and requires MS Blend.
I'd be happy if I could just get some headers as the first row in the drop down.
G
Here is my xaml code with HB's attempt that produces a compile error as mentioned in the comments.
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:dg="http://schemas.microsoft.com/wpf/2008/toolkit"

<ComboBox Name="cboPlaceNames" Grid.IsSharedSizeScope="True" ItemsSource="{DynamicResource items}" Height="22" Width="285" Margin="0,6,165,0" SelectedIndex="0" HorizontalAlignment="Right" VerticalAlignment="Top" SelectionChanged="cboPlaceNames_SelectionChanged">
  <ComboBox.Resources>
    <CompositeCollection x:Key="items">
      <ComboBoxItem IsEnabled="False">
        <Grid TextElement.FontWeight="Bold">
          <Grid.ColumnDefinitions>
            <ColumnDefinition SharedSizeGroup="A"/>
            <ColumnDefinition Width="5"/>
            <ColumnDefinition SharedSizeGroup="B"/>
            <ColumnDefinition Width="5"/>
            <ColumnDefinition SharedSizeGroup="C"/>
          </Grid.ColumnDefinitions>
          <Grid.Children>
            <TextBlock Grid.Column="0" Text="Name"/>
            <TextBlock Grid.Column="2" Text="CLLI"/>
            <TextBlock Grid.Column="4" Text="Street"/>
          </Grid.Children>
        </Grid>
      </ComboBoxItem>
      <Separator/>
      <CollectionContainer Collection="{Binding Source={x:Reference cboPlaceNames}, Path=DataContext.Data}"/>
    </CompositeCollection>

    <DataTemplate DataType="x:Type obj:PlaceName">
      <Grid>
        <Grid.ColumnDefinitions>
          <ColumnDefinition SharedSizeGroup="A"/>
          <ColumnDefinition Width="5"/>
          <ColumnDefinition SharedSizeGroup="B"/>
          <ColumnDefinition Width="5"/>
          <ColumnDefinition SharedSizeGroup="C"/>
        </Grid.ColumnDefinitions>
        <Grid.Children>
          <TextBlock Grid.Column="0" Text="{Binding Name}"/>
          <TextBlock Grid.Column="2" Text="{Binding CLLI}"/>
          <TextBlock Grid.Column="4" Text="{Binding Street}"/>
        </Grid.Children>
      </Grid>
    </DataTemplate>
  </ComboBox.Resources>
</ComboBox>

A: The simplest way to add columns headers to combobox is to use listview in combobox.
The following code is give the solution to it.
            <ComboBox HorizontalAlignment="Center"
                      IsTextSearchEnabled="False" Width="200"
                      IsEditable="True" Text="{Binding }">
                 <ListView ItemsSource="{Binding YOURITEMSOURCE}"
                        SelectedItem="{Binding Path=SELECTEDITEMSOURCE}"
                         Height="200" ScrollViewer.VerticalScrollBarVisibility="Visible">
                           <ListView.View>
                               <GridView>
                                  <GridViewColumn Width="130"  Header="Name" DisplayMemberBinding="{Binding Name}"   />
                                  <GridViewColumn Width="130" Header="Occupation" DisplayMemberBinding="{Binding Occupation}" />
                                  <GridViewColumn Width="130"  Header="Age" DisplayMemberBinding="{Binding Age}" />
                                  <GridViewColumn Width="130" Header="Salary" DisplayMemberBinding="{Binding Salary}" />
                               </GridView>
                           </ListView.View>
                  </ListView>

            </ComboBox>

A: Example:
<ComboBox Name="cb" Grid.IsSharedSizeScope="True" ItemsSource="{DynamicResource items}">
    <ComboBox.Resources>
        <CompositeCollection x:Key="items">
            <ComboBoxItem IsEnabled="False">
                <Grid TextElement.FontWeight="Bold">
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition SharedSizeGroup="A"/>
                        <ColumnDefinition Width="5"/>
                        <ColumnDefinition SharedSizeGroup="B"/>
                    </Grid.ColumnDefinitions>
                    <Grid.Children>
                        <TextBlock Grid.Column="0" Text="Name"/>
                        <TextBlock Grid.Column="2" Text="Occupation"/>
                    </Grid.Children>
                </Grid>
            </ComboBoxItem>
            <Separator/>
            <CollectionContainer Collection="{Binding Source={x:Reference cb}, Path=DataContext.Data}"/>
        </CompositeCollection>

        <DataTemplate DataType="{x:Type obj:Employee}">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition SharedSizeGroup="A"/>
                    <ColumnDefinition Width="5"/>
                    <ColumnDefinition SharedSizeGroup="B"/>
                </Grid.ColumnDefinitions>
                <Grid.Children>
                    <TextBlock Grid.Column="0" Text="{Binding Name}"/>
                    <TextBlock Grid.Column="2" Text="{Binding Occupation}"/>
                </Grid.Children>
            </Grid>
        </DataTemplate>
    </ComboBox.Resources>
</ComboBox>

Note that getting the Collection-binding right is not that easy because there is neither DataContext nor VisualTree to rely on, ElementName and RelativeSource does not work, this is because CompositeCollection is just a collection, not a FrameworkElement.
Other than that the way this is done is via Grids that have shared size columns. The DataTemplate is applied automatically via the DataType.

Edit: Setting the header-ComboBoxItem's IsHitTestVisible property to False is not enough since it still can be selected using the keyboard. I now changed it to IsEnabled="False" which fades out the item a bit. You could probably re-template that item to not do that. Or if you find another way of disabling it from selection that would of course work out too.

A: I liked Nandha's answer because this was what I was trying to achieve.  However, the text field of the combo box will not work correctly.
Since I am lazy, to get around this I created a StackPanel of Horizontal orientation, with a TextBox bound to a field from the selected item, and the Combo Box with the embedded ListView. The Combo Box now has a width of 20 so just the down arrow shows (you can play with the width and margins to get just the right look.  This makes the text box look like a combo box, with all the benefits of the ListView, and much less coding.
I hope this helps.enter image description here

A: Apply the following style to the ComboBox.
<Style x:Key="ListViewComboBox" TargetType="{x:Type ComboBox}">
    <Style.Resources>
        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
                         Color="LightBlue"/>
    </Style.Resources>
    <Setter Property="ScrollViewer.CanContentScroll" Value="true"/>
    <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Auto"/>
    <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
    <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"/>
    <Setter Property="BorderBrush" Value="Black"/>
    <Setter Property="BorderThickness" Value="1"/>
    <Setter Property="FontFamily" Value="Arial"/>
    <Setter Property="FontSize" Value="12"/>
    <Setter Property="Foreground" Value="Black"/>
    <Setter Property="Margin" Value="0"/>
    <Setter Property="Padding" Value="0"/>
    <Setter Property="VerticalContentAlignment" Value="Center"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ComboBox}">
                <Border Background="{TemplateBinding Background}"
                        BorderBrush="{TemplateBinding BorderBrush}"
                        BorderThickness="{TemplateBinding BorderThickness}"
                        CornerRadius="3"
                        SnapsToDevicePixels="True">
                    <Grid>
                        <Border x:Name="Border">
                            <Popup x:Name="PART_Popup" AllowsTransparency="true" IsOpen="{TemplateBinding IsDropDownOpen}" Placement="Bottom" PopupAnimation="{DynamicResource {x:Static SystemParameters.ComboBoxPopupAnimationKey}}" Focusable="False">
                                <Border x:Name="Shdw"
                                        MaxHeight="{TemplateBinding MaxDropDownHeight}"
                                        MinWidth="{Binding ActualWidth, ElementName=Border}">
                                    <Border x:Name="DropDownBorder"
                                            Background="{DynamicResource {x:Static SystemColors.WindowBrushKey}}"
                                            BorderBrush="{TemplateBinding BorderBrush}"
                                            BorderThickness="1">
                                        <ListView KeyboardNavigation.DirectionalNavigation="Contained"
                                                  ItemsSource="{TemplateBinding ItemsSource}"
                                                  SelectedItem="{Binding Mode=TwoWay, Path=SelectedItem, RelativeSource={RelativeSource Mode=TemplatedParent}}"
                                                  View="{TemplateBinding Tag}"/>
                                    </Border>
                                </Border>
                            </Popup>
                        </Border>
                        <DockPanel Margin="2">
                            <FrameworkElement DockPanel.Dock="Right"
                                              Width="{DynamicResource {x:Static SystemParameters.VerticalScrollBarWidthKey}}"/>
                            <Border x:Name="SelectedItemBorder" Margin="{TemplateBinding Padding}">
                                <Grid>
                                    <ContentPresenter Content="{TemplateBinding SelectionBoxItem}"
                                                      ContentStringFormat="{TemplateBinding SelectionBoxItemStringFormat}"
                                                      ContentTemplate="{TemplateBinding SelectionBoxItemTemplate}"
                                                      ContentTemplateSelector="{TemplateBinding ItemTemplateSelector}"
                                                      HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                                      Margin="1,1,1,1"
                                                      SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"
                                                      VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                                </Grid>
                            </Border>
                        </DockPanel>
                        <ToggleButton x:Name="DropDownToggleButton"
                                      ClickMode="Press"
                                      Focusable="false"
                                      Foreground="{TemplateBinding BorderBrush}"
                                      IsChecked="{Binding IsDropDownOpen, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
                                      Margin="2"
                                      MinHeight="0"
                                      MinWidth="0"
                                      Width="Auto"/>
                    </Grid>
                </Border>
                <ControlTemplate.Triggers>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsSelectionBoxHighlighted" Value="true"/>
                            <Condition Property="IsDropDownOpen" Value="false"/>
                        </MultiTrigger.Conditions>
                        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
                    </MultiTrigger>
                    <Trigger Property="IsSelectionBoxHighlighted" Value="true">
                        <Setter Property="Background" TargetName="SelectedItemBorder" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                    </Trigger>
                    <Trigger Property="HasItems" Value="false">
                        <Setter Property="MinHeight" TargetName="DropDownBorder" Value="95"/>
                    </Trigger>
                    <Trigger Property="IsEnabled" Value="false">
                        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                        <Setter Property="Background" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
                    </Trigger>
                    <Trigger Property="IsGrouping" Value="true">
                        <Setter Property="ScrollViewer.CanContentScroll" Value="false"/>
                    </Trigger>
                    <Trigger Property="HasDropShadow" SourceName="PART_Popup" Value="true">
                        <Setter Property="Margin" TargetName="Shdw" Value="0,0,5,5"/>
                    </Trigger>
                    <Trigger Property="IsReadOnly" Value="True">
                        <Setter Property="Visibility" TargetName="DropDownToggleButton" Value="Collapsed"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="IsEditable" Value="true">
            <Setter Property="IsTabStop" Value="false"/>
            <Setter Property="Padding" Value="1"/>
            <Setter Property="Template" Value="{StaticResource ComboBoxEditableTemplate}"/>
        </Trigger>
    </Style.Triggers>
</Style>

Apply the View you want to the Tag property of the ComboBox
<ComboBox ItemsSource={Binding Items}>
    <ComboBox.ItemTemplate>
        <DataTemplate>
            <!-- Enter your item template shown as the selected item. -->
        </DataTemplate>
    </ComboBox.ItemTemplate>
    <ComboBox.Tag>
        <GridView>
            <GridViewColumn DisplayMemberBinding="{Binding Name}"
                            Header="Name"
                            Width="100"/>
        </GridView>
    </ComboBox.Tag>
</ComboBox>

Thats all folks.

A: I like H.B.'s answer, but unfortunately when I use it I see databinding errors in the output for the header ComboBoxItem's HorizontalContentAlignment and VerticalContentAlignment properties:

Cannot find source for binding with reference 'RelativeSource
  FindAncestor, AncestorType='System.Windows.Controls.ItemsControl',
  AncestorLevel='1''. BindingExpression:Path=HorizontalContentAlignment;
  DataItem=null; target element is 'ComboBoxItem' (Name=''); target
  property is 'HorizontalContentAlignment' (type 'HorizontalAlignment')

These don't crash the program, but they do clutter up the output and cause perceptible delays when running debug builds. Whatever's causing them seems to be deep in the bowels of ComboBox or ComboBoxItem; in any case, I couldn't figure out any way to prevent them (setting these properties manually or via a Style didn't help). So I ended up going with a slight variation. This is longer and hackier than I like things to be, but it gets the job done:
<ComboBox Name="cb" Grid.IsSharedSizeScope="True" ItemsSource="{DynamicResource items}">
 <ComboBox.Resources>
    <!-- We'll use this dummy value to represent the header row. -->
    <!-- The type and value are arbitrary; we just need a unique type -->
    <!-- for DataTemplate selection to work with. -->
    <system:Int32 x:Key="HeaderPlaceholder">-1</system:Int32>

    <CompositeCollection x:Key="items">
      <StaticResource ResourceKey="HeaderPlaceholder" />
      <CollectionContainer Collection="{Binding Source={x:Reference cb},
         Path=DataContext.Data}"/>
    </CompositeCollection>

    <!-- DataTemplate for the header item -->
    <DataTemplate DataType="{x:Type system:Int32}">
      <DataTemplate.Resources>
        <!-- Make the TextBlocks black even though they are disabled -->
        <Style TargetType="TextBlock">
          <Style.Triggers>
            <Trigger Property="IsEnabled" Value="False">
              <Setter Property="Foreground" Value="Black" />
            </Trigger>
          </Style.Triggers>
        </Style>
      </DataTemplate.Resources>

      <StackPanel>
        <Grid TextElement.FontWeight="Bold">
          <Grid.ColumnDefinitions>
            <ColumnDefinition SharedSizeGroup="A"/>
            <ColumnDefinition Width="5"/>
            <ColumnDefinition SharedSizeGroup="B"/>
          </Grid.ColumnDefinitions>
          <Grid.Children>
              <TextBlock Grid.Column="0" Text="Name"/>
              <TextBlock Grid.Column="2" Text="Occupation"/>
          </Grid.Children>
        </Grid>
        <Separator />
      </StackPanel>
    </DataTemplate>

    <!-- DataTemplate for a normal, selectable item -->
    <DataTemplate DataType="{x:Type obj:Employee}">
      <Grid>
        <Grid.ColumnDefinitions>
          <ColumnDefinition SharedSizeGroup="A"/>
          <ColumnDefinition Width="5"/>
          <ColumnDefinition SharedSizeGroup="B"/>
        </Grid.ColumnDefinitions>
        <Grid.Children>
          <TextBlock Grid.Column="0" Text="{Binding Name}"/>
          <TextBlock Grid.Column="2" Text="{Binding Occupation}"/>
        </Grid.Children>
      </Grid>
    </DataTemplate>
  </ComboBox.Resources>

  <ComboBox.ItemContainerStyle>
    <!-- Make sure the header item is disabled so it can't be selected -->
    <Style TargetType="ComboBoxItem">
      <Style.Triggers>
        <Trigger Property="DataContext" Value="{StaticResource HeaderPlaceholder}">
          <Setter Property="IsEnabled" Value="False" />
        </Trigger>
      </Style.Triggers>
    </Style>
  </ComboBox.ItemContainerStyle>
</ComboBox>


text:
Q: Path format is illegal I want to ask about a  easy question , but I faced a problem.
I want to get the time when the program is executed
Console.WriteLine(DateTime.Now);

And I want to output a .log file , the file name will have program execution time
String path2 = "C:\\temp"+DateTime.Now+".log";
StreamWriter path = File.CreateText(path2);
path.WriteLine(DateTime.Now);

But it is telling me Path format is illegal.
And I want ask another question
string a12 = aaa.Element("a12").tostring();
String path2 = "C:\\temp" + a12.ToString + ".log";

But it tell me "Path format is illegal"
How can I resolve it?
Thanks

A: That's because DateTime.Now converted to string by default contains time information (e.g. 8:53). Semicolon is illegal in path name.
If you meant only date to be in your file name, you could use:
String path2 = "C:\\temp" + DateTime.Now.ToString("d") + ".log";

(Edit) For some cultures this still can lead to invalid values, so as others pointed out, it is best to use explicit formatter:
String path2 = "C:\\temp" + DateTime.Now.ToString("yyyy-MM-dd") + ".log";

A: You want to escape your \ in the "" quoted string, and also there are characters in the result of DateTime.Now that cannot be in paths.  You'll need to escape/replace those as well.

A: When you put DateTime.Now into a path, you risk adding characters that aren't valid as a path (like the : separator. That is the reason you get this error message.
You could replace it with a .:
string path2 = Path.Combine
               ( @"C:\temp\"
               , DateTime.Now.ToString("yyyy-MM-dd.HH24.mm.ss")
               , ".log"
               );

A: DateTime.Now probably contains illegal characters depending on your local system settings. To get a valid and consistent file name independent on the culture the system is installed in you should create the log file name by hand, for instance like this:
String path2 = "C:\\temp" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".log";

A: String path2 = String.Format("C:\\temp{0}.log", DateTime.Now.ToString("yyyyMMdd"));

Since filename cannot take "/" which was created by DateTime.Now.ToString("d") and hence creating issue.


text:
Q: React-redux error when webpack: SyntaxError: Unexpected token Here is a strange problem, here is the code:
...
const PrivateRoute = ({status, component: Component, ...rest}) => (
    <Route {...rest} render={ props => (
      status ?
        (<Component {...props}/>) :
        (<Redirect to="/login"/>)
    )}/>
)

function mapStateToProps(state) {
  return {
    status: state.user.status
}

export default connect(mapStateToProps)(PrivateRoute)

The error when doing webpack -d -w:
ERROR in ./public/javascripts/src/admin/components/PrivateRoute.jsx
Module build failed: SyntaxError: Unexpected token (4:53)

  2 | import { Route, Redirect } from 'react-router-dom'
  3 |
> 4 | const PrivateRoute = ({status, component: Component, ...rest}) => (
    |                                                      ^
  5 |   <Route {...rest} render={ props => (
  6 |     status ?
  7 |       (<Component {...props}/>) :

The code is just follow the tutorial over here.
However, the code blow also uses the '...' in Route {...rest}. When I remove the first '...', the second and third doesn't produce the error. Why does that happen?

A: This is experimental syntax. You need to include object-rest-spread plugin in your babel config. Or use a preset that includes this plugin. For example stage-3
As of this

When I remove the first '...', the second and third doesn't produce the error. Why does that happen?

<Route {...rest} is handled by jsx plugin included into react preset. Repl.

A: Update you .eslintrc.js, set experimentalObjectRestSpread to ecmaFeatures as true.
parserOptions: {
  ecmaVersion: 7,
  sourceType: 'module',
  ecmaFeatures: {
    jsx: true,
    experimentalObjectRestSpread: true
  }
}

See https://eslint.org/docs/rules/rest-spread-spacing


text:
Q: Freemarker : Convert unix timestamp string to date format string I am getting unix timestamp in String format in my ftl file. I want to reformat date to readable string such as "yyyy-MM-dd".
How should I convert timestamp to formatted date string ?

A: I got date in required format using below code:
calBookingEntry.getStartTime()?number?number_to_datetime?string["yyyy-MM-dd"]


text:
Q: Bitlocker PIN rejected after dual-install of Ubuntu with encryption I have a Thinkpad with Windows 10 installed, with Bitlocker setup and previously working. I've just installed Ubuntu along-side Windows, and I enabled the "encrypt my home drive" option during install. I am using grub as a boot manager.
I can boot into and run Ubuntu fine. If I select Windows from the grub menu, I get to the Bitlocker screen as I normally would, but it no longer accepts the PIN? Is there any recovery from this?
Update: If I bypass grub, get the regular system boot menu and choose "Windows boot loader" from there, the Bitlocker PIN is accepted.
So, something about accessing the Windows boot loader from grub is not playing nicely with Bitlocker. Is there any solution to this?


text:
Q: How can I scroll text inside of a div using js? I want to scroll the content of the div which is some text, without any tags it's just like "some text"
I have set the height of the div to be 600px and overflow property as auto, so I all want is after some interval the content i.e the text should be scrolled to the next 600px of the div.
EDIT:
So, what I actually want is, when I paste some content in the div, it should scroll down after some interval
HTML:
<!DOCTYPE html>

              Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut rhoncus dui eget tortor feugiat iaculis. Morbi et dolor in felis viverra efficitur. Integer id laoreet arcu. Mauris turpis nibh, scelerisque sed tristique non, hendrerit in erat. Duis interdum nisl risus, ac ultrices ipsum auctor at. Aliquam faucibus iaculis metus sit amet tincidunt. Vestibulum cursus urna vel nunc imperdiet suscipit. Ut eu augue egestas, porta orci lobortis, pharetra orci. Morbi eu tellus quis nisi tempor accumsan nec eu urna.

CSS:
.paper-content{
height: 600px;
overflow: auto;
}

JS:
function scrollToBottom(){
  alert('here');
  document.getElementById('note').scrollTop = document.getElementById('note').scrollTop + 100;

}

// Convert copied text to plaintext
document.querySelector("#note").addEventListener('paste', (event) => {

  event.preventDefault();

  var text = event.clipboardData.getData("text/plain");

  document.execCommand("insertHTML", false, text);

  setTimeout(scrollToBottom, 1000);

})

Like I have,
First Image
then after some interval, it should be scrolled to,
Second Image
Thank you!

A: Using scrollTop you can achieve what you want

setInterval(function() {
  document.getElementById('text-content').scrollTop = document.getElementById('text-content').scrollTop + 100;
}, 2000)
#text-content {
    width: 200px;
    height: 400px;
    border: 1px soild;
    overflow: auto;
 }

Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit  Lorem ipsum dolor sit


text:
Q: Perl to find the extension of file I have a program that takes directory name as input from user and searches all files inside the directory and prints the contents of file.  Is there any way so that I can read the extension of file and read the contents of file that are of specified extension?  For example, it should read contents of file that is in ".txt" format.
My code is
use strict;
use warnings;
use File::Basename;
#usr/bin/perl
print "enter  a directory name\n";
my $dir = <>;
print "you have entered $dir \n";
chomp($dir);
opendir DIR, $dir or die "cannot open directory $!";
while ( my $file = readdir(DIR) ) {
    next if ( $file =~ m/^\./ );
    my $filepath = "${dir}${file}";
    print "$filepath\n";
    print " $file \n";

    open( my $fh, '<', $filepath ) or die "unable to open the $file  $!";
    while ( my $row = <$fh> ) {
        chomp $row;
        print "$row\n";
    }
}

A: To get just the ".txt" files, you can use a file test operator (-f : regular file) and a regex.
my @files = grep { -f && /\.txt$/ } readdir $dir;

Otherwise, you can look for just text files, using perl's -T (ascii-text file test operator)
my @files = grep { -T } readdir $dir;

Otherwise you can try even this:
my @files = grep {-f} glob("$dir/*.txt");

A: You're pretty close here. You have a main loop that looks like this:
while ( my $file = readdir(DIR) ) {
    next if $file =~ /^\./; # skip hidden files

    # do stuff
}

See where you're skipping loop iterations if the filename starts with a dot. That's an excellent place to put any other skip requirements that you have - like skipping files that don't end with '.txt'.
while ( my $file = readdir(DIR) ) {
    next if $file =~ /^\./; # skip hidden files
    next unless $file =~ /\.txt$/i; # skip non-text files

    # do stuff
}

In the same way as your original test checked for the start of the string (^) followed by a literal dot (\.), we're now searching for a dot (\.) followed by txt and the end of the string ($). Note that I've also added the /i option to the match operator to make the match case-insensitive - so that we match ".TXT" as well as ".txt".
It's worth noting that the extension of a file is a terrible way to work out what the file contains.

A: Try this. Below code gives what you expect.
use warnings;
use strict;
print "Enter the directory name: ";
chomp(my $dir=<>);
print "Enter the file extension type: "; #only type the file format. like txt  rtf
chomp(my $ext=<>);
opendir('dir',"$dir");
my @files = grep{m/.$ext/g} readdir('dir');
foreach my $ech(@files){
    open('file',"$dir/$ech");
    print <file>;
}

I'm store the all file from the particular directory to store the one array and i get the particular file format by using the grep command. Then open the files into the foreach condition


text:
Q: CakePHP 2.x .htaccess: Get 500 Internal Server Error Problem solved

*

*Changed all folder and file permissions to 755

*All .htaccess files
with absolute paths (/app/webroot/)

I moved my CakePHP 2.x website to another hoster (cyon.ch). Now i got 500 Internal Server Error. I tryed all the fixed who are recommended for the 1and1 hoster, but they won't work.
The error comes from the /app/webroot/.htacces file, cause the others seems to work. If i try to call a image from the webroot/img directory, it works fine (www.myDomain.ch/img/myPicture.jpg), but not the index.php file.
AddType text/x-component .htc

<IfModule mod_rewrite.c>
    RewriteEngine On

    # FORCE WWW
    RewriteCond %{HTTP_HOST} !^www\.myDomain\.ch$
    RewriteRule ^(.*)$ http://www.myDomain.ch/$1 [R=301,L]

    # REMOVE TRAILING SLASHES
    RewriteRule ^(.*)/$ http://%{HTTP_HOST}/$1 [R=301,L]

    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^(.*)$ index.php [QSA,L]
</IfModule>

The "FORCE WWW" and "REMOVE TRAILING SLASHED" are ok as well, if i type myDomain.ch/, i'll got redirect to www.myDomain.ch.
My Domain points to /path/to/root/public_html. Thats also the folder, in which the cake app folder is located.
Any idea?
Thanks in advance!
Edit: I found this error in the error log (Permissions for index.php are set to 755)
SoftException in Application.cpp:256: File "/home/myUsername/public_html/app/webroot/index.php" is writeable by group


text:
Q: Matlab - Tail recursive vector sum How should I write a tail recursive function to compute the sum of a vector?
The function takes 2 input arguments: a vector v and sum.
Tail recursion means that the last part of the function must call itself.
I have a basic shell of what the function should look like, but I am unsure about how to write the recursive part.
function result = vectorSum(v,sum)
%takes a vector v and the returns the sum of all elements in the vector
if length(v) == 0
    result = 0;
elseif length(v) == 1
    result = v;
else
    result = vectorSum(v,sum)
end
end

The function returns a result of 0 for an empty vector, and if the vector's length is 1 it returns the value v(1).

A: Your solution has two main problems:

*

*The results are not accumulated - You simply call the vectorSum function without considering the result from previous calls.

*The size of the problem is not reduced at each recursive call.

The are several ways to implement this recursion, I suggest the following approach:
function result = vectorSum(v)
%takes a vector v and the returns the sum of all elements in the vector
if length(v) == 0
    result = 0;
else
    result = v(end) + vectorSum(v(1:end-1));
end
end


text:
Q: how to upload mp3 file and get its duration in laravel 4.2 I'd like to upload a MP3 file in Laravel and then get the duration of the MP3. Here's my code, but it's not working:
$music_file = Input::file('audio_path');
$file_music = date('Y-m-d-H-i-s')."-".$music_file->getClientOriginalName();
$path = public_path('assets/music/' . $file_music);
$path = $music_file->getRealPath();

A: for moving MP3
$music_file = Input::file('audio_path');
$file_music = date('Y-m-d-H-i-s')."-".$music_file->getClientOriginalName();
$path = public_path('assets/music/' . $file_music);
$music_file->move($path,$file_music);

A: After observing many doubts on this subject I will leave here a step by step with the solution I found for this problem.
For this we will use the getid3 package, a media file parser.
This solution was tested on Laravel 6.x, but it is compatible with several versions of Laravel.
1 - To install it on Laravel using the Composer, at the root of the project using the console type:
$ composer require james-heinrich/getid3

In this example we will create an endpoint to send an .mp3 file and return its duration.
2 - Create a Route to send the file:
Route::post('media', 'FilesController@media');

3 - Create a Controller to get the file and return the duration:
class FilesController extends Controller
{
    public function media(Request $request)
    {
        $file = $request->file('upload');
        if(!empty($request->file('upload'))) {
            $getID3 = new \getID3;
            $ThisFileInfo = $getID3->analyze($file);
            $len= @$ThisFileInfo['playtime_string']; // playtime in minutes:seconds, formatted string
            return $len;
        }
    }

4 - Sending the file:
Test using POSTMAN (good to check if everything in Laravel is OK):

Note: the upload field in POSTMAN is of type FILE.
Using Curl / PHP
<?php

    $curl = curl_init();

    curl_setopt_array($curl, array(
      CURLOPT_URL => "https://localhost/api/media",
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 0,
      CURLOPT_FOLLOWLOCATION => true,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => array('upload'=> new CURLFILE('/home/fellipe/Desktop/android-timeless.mp3')),
      CURLOPT_HTTPHEADER => array(
        "Content-Type: application/x-www-form-urlencoded",
        "Accept: application/json"
      ),
    ));

    $response = curl_exec($curl);

    curl_close($curl);
    echo $response;


text:
Q: What mechanism will generate Dirac neutrinos? Giving mass to neutrinos is not a problem. The problem is to explain its smallness. Once right-handed neutrinos $\nu_R$'s are included in the Standard Model (SM), the Majorana mass for $\nu_R$ must also be included unless that is forbidden by some symmetry. This automatically and unavoidably leads to the robust conclusion that the mass eigenstates (both light and heavy) are Majorana type.
So my question is what mechanism will generate Dirac neutrinos?

A: I am not entirely sure but I think without introducing new symmetries to the SM this is not possible and still then it is not quite natural. So I'll just summarize my ideas on this and see if someone can come up with something better.
To have a Dirac mass term you need to have some right handed neutrino $\nu_R$. As you said the general approach within the seesaw type 1 is to introduce a right handed singlet $\nu_R$ which gives you both a Dirac and Majorana mass term
$$\mathcal{L}_m=\overline{L} \Phi\nu_R+\frac{1} {2} m_R\nu_R^TC\nu_R$$
Now since the Majorana mass term is only allowed due to $\nu_R$ being a singlet in the SM framework we need to change this to forbid this term.
A possibility to do so would be to just give $\nu_R$ a hyper charge so that the Majorana term is forbidden. All we need to do then is to introduce a second Higgs field with the corresponding hyper charge to allow for the Dirac term to appear. However this is not really a mechanism to produce massive neutrinos since the hyper charge would lead to a non-vanishing electric charge of the right handed neutrino and the additional Higgs. Neutrinos are neutral particles so this does not work and would have been seen in experiments. Also giving the new Higgs a non vanishing vev will break the electromagnetic ${\rm U(1)}$.
Therefore we need to introduce new symmetries to the theory to forbid the Majorana term to appear. Two possibilities are promoting the accidental lepton number symmetry to a ${\rm U(1)}$ gauge symmetry or introducing an additional ${\rm SU(2)_R}$ acting similar to its left-handed counterpart such that the Higgs transforms as
$$\Phi\rightarrow U\Phi V^\dagger$$ for $U\in {\rm SU(2)_L}$ and $V\in {\rm SU(2)_R}$.
Interestingly the latter case necessarily comes with right handed neutrinos. Both symmetries would allow Dirac mass terms while forbidding the Majorana term. However both would probably need to be broken to hide the otherwise appearing massless gauge bosons. This breaking will again introduce Majorana terms for neutrinos.
One could avoid the breaking by assigning very small couplings to the new symmetries but this is a rather unnatural way and would call for some mechanism to explain the smallness of the couplings.
So in summary to my knowledge the only way to make neutrinos pure Dirac particles is to introduce new symmetries. One can however argue if we really need to speak of Majorana neutrinos in the case that the Majorana term is vanishingly small.


text:
Q: Why won't my boolean work correctly? Sorry for the very open question title, but I can't really figure out what is wrong exactly. I wanted to save a little time when writing semantic types, which are usually subscript but are often recursive, leading to types within types, like this:
D<e,<s,t>>
The easiest solution seemed to me to use a boolean which checks whether I am within Type Brackets (<>) already; if so, \type would not use \textsubscript, if not, \type would set the boolean to true and use \textsubscript; the last command in \type would set the boolean to false if it had been false when the command was called. This is a minimal example:
\documentclass{article}
\usepackage{etoolbox}

\newbool{intype}
\newcommand{\type}[1]{\ifbool{intype}{$\langle$#1$\rangle$}{\setbool{intype}{true}\textsubscript{$\langle$#1$\rangle$}}\setbool{intype}{false}}

\begin{document}
D\type{\type{$\tau$,\type{$s,t$}},\type{$\tau$,\type{$s$,$t$}}}
\end{document}

The expected output is D<<τ,<s,t>>,<τ,<s,t>>.
The output I get is D<<τ,<s,t>>,<τ,<s,t>>.
This is really confusing - If my solution doesn't work, why isn't the <s,t> bit in the first pair of brackets lower than the τ?
 Sorry for that long line of code btw, as far as I can tell, adding spaces or line breaks produces unwanted spaces in the output.

A: You are setting it false too soon, but you can just use the grouping to set it back automatically:

\documentclass{article}
\usepackage{etoolbox}

\newbool{intype}
\newcommand{\type}[1]{%
  \ifbool{intype}%
  {$\langle$#1$\rangle$}%
  {\textsubscript{\setbool{intype}{true}$\langle$#1$\rangle$}}%
  }

\begin{document}
D\type{\type{$\tau$,\type{$s,t$}},\type{$\tau$,\type{$s$,$t$}}}
\end{document}

A: The boolean is set to false in the wrong place.
Here's a different implementation, based on grouping, that avoids code repetition. Since \textsubscript typesets its argument in a group, the "outer" definition of \type will be restored as soon as the subscript has been typeset.
\documentclass{article}

\newcommand{\type}[1]{%
  \textsubscript{\let\type\innertype\innertype{#1}}%
}
\newcommand{\innertype}[1]{$\langle$#1$\rangle$}

\begin{document}
D\type{\type{$\tau$,\type{$s,t$}},\type{$\tau$,\type{$s$,$t$}}}
\end{document}


text:
Q: emberjs {{#if variable }} boolean will not display as true I set a simple boolean (isEditing) in the 'categories' controller to equal 'true' when the
{{action "edit" this}} button is clicked.
The variable will not set itself to true when 'edit' is clicked. I console.log'd to make sure 'edit' knew i was clicking it, and it did. This seems so simple in the emberjs website and i don't know why im having such trouble with now.
categories controller
VpcYeoman.CategoriesController = Ember.ArrayController.extend({
    isEditing: false,
    actions: {
        editingyeah: function(){
            console.log('Testing console'); //this works
            this.set('isEditing', true); //this doesnt change to true since the {{Else}} is what is being rendered.
        }
    },

});

categories.hbs
    {{#each}}

          {{#if isEditing}}
          {{view Ember.TextField valueBinding=name}}
          NOOOOOOOO
          {{else}}

          {{view Ember.TextField valueBinding=name}}
            {{#linkTo 'category' this}}
              {{name}}
            {{/linkTo}}

          {{/if}}

    {{/each}}

A: It's because you are looping through each category, so the context within the each helper is your category. It's looking for an isEditing property on the category, not the one you have in the controller.
Since you are passing the category in to the action, you can access it as an argument in the action's function, and set the property on the category instead:
actions: {
    editingyeah: function(category){
        category.set('isEditing', true);
    }
}

A: I saw your problem after I posted my comment. You don't have an isEditing variable defined in your scope. You're using the #each helper, which changes the scope of the template. You either have to keep the scope when using #each, or use a #with helper.
{{#each item in model}}
    {{! isEditing is available now }}
    {{! But you have to do item.name instead of name}}
{{/each}}

Or
{{#with this.isEditing as isEditing}}
    {{#each}} ... {{/each}}
{{/with}}