Q:

Use of hyphens when qualifying a noun

I am editing a bit of text, and I need to know: should there be a hyphen in the following passage?
"While transecting the designated territory, survey-team members collected numerous artifacts."
Could it just be "survey team members"? Or "survey team-members"?

A:

They are members of a survey team, so the three-word compound is produced from the two-word compound of survey + team and the word members.
Hence the logical possibilities of all the permutations of closed, open and hypenated are:

survey team members (all open).
surveyteam members (closed + open)
surveyteammembers (all closed)
survey-team members (hyptenated + open)
survey team–members (open and dash)
survey-team–members (hyphenated and dash).
surveyteam-members (closed and hypen).

Note that we don't try closing team and members if we haven't closed survey and team, as we would never close a compound where part of the compound was itself an open or hyphenated compound.
Note also that we use an en-dash (–) not a hyphen (-) when part of a compound is itself an open or hyphenated compound.
Now, of those possibilities, closed compounds are not common in English, unless the term is heavily used, or we are seeking to coin a specific new meaning, so let's remove them from the list:

survey team members (all open).
survey-team members (hyptenated + open)
survey team–members (open and dash)
survey-team–members (hyphenated and dash).

These are each cases one could make an argument for, and it becomes more a matter of judgement now. One guide is to consider the possibility of misreading if one's eye happened upon the right most part of the compound. Since members must be members of something, if our eye hits upon "members" alone on a page, we're going to seek to find out what they are members of, so the en-dash offers little to help. We can therefore dismiss the two possibilities that use a dash:

survey team members (all open).
survey-team members (hyptenated + open)

Of the remaining two, there's less to argue very strongly in favour of one or the other. I started writing this answer thinking I was going to say both of these could be reasonably chosen, but I'd lean toward that with the hyphen. I now think I'd lean toward that with no hyphen. They're definitely both allowable, there's only matters of taste and preference to pick between them. As a tie-breaker, hyphenated forms seem to be increasingly less common, which argues for using the fully-open "survey team members".
I would possibly change my mind in the context of the wider piece. If there were other teams involved in what it described, that would lean me toward hyphenating, because the risk of misreading without it has increased. Conversely, if the survey team/survey-team are mentioned repeatedly, that would lean me against hyphenating, as the repetition of the phrase decreases the risk of misreading, and slightly increases the visual irritation of the hyphen.
If you're writing or editing to a particular style-guide, then what it has to say about compound nouns over-rules this, though even they can be quite vague on this matter, some times.


Q:

Intellisense not working when trying to define an xmlns in VS2012

I am trying to add a namespace to one of my usercontrols in xaml. In visual studio 2010 I could just type xmlns:blahblah= and it would add the quotations and offer me a whole list of suggestions of assemblies to add as namespace definitions.
In visual studio 2012 I start typing it out and I'm immediately getting xaml errors as I'm typing and no suggestions. The problem is, I don't know what the exact ones I need to add, so I'm a little dependent on the intellisense.
Regular intellisense works just fine. Why is this?

A:

The problem seems to have been the fact that I was using .NET 4.0 Client Profile for my application. I went ahead and transferred it over to .NET 4.5(full), but I am sure .NET 4.0(full) would work just as well. It seemed to have fixed nearly all of the intellisense problems I've been having.
I don't know what the downsides are to switching will be, though for 4.5 there isn't even a Client Profile version


Q:

How can the placement of data points in a graph be adjusted?

As part of an important presentation, I've created the following diagram showing statistical data over 5 periods of time.

The data for each period consists a pair of a bar charts with a corresponding dot for each bar.
Now, here's my question:
Does anybody know how to place the dots directly above their respective bars instead of centered in the middle?

A:

The dot series needs to be an XY/ScatterChart type.  Then, just adjust your dot series X values to match your series position.
In your example, assuming that your XY chart is on the primary axis, you should set:

First blue dot X value approx.
0.85, then add 1 for each additional dot
First yellow dot X value 1.15, then add 1 for each additional dot


Q:

Why don't replicants have emotions?

According to the Blade Runner's press kit, replicants were "A genetically engineered creature composed entirely of organic substance."
If they're not robots, why are they not capable of emotions (obviously shown in the idea of the Voight Kampff test)? Did they make them without emotions on purpose, and if so why, or is there a reason a "genetically engineered creature" can't have emotions?

A:

Replicants certainly do have emotions - Roy Batty exhibits anger and ultimately sadness; several of them exhibit fear at being discovered and retired.
However, they are relatively underdeveloped, emotionally speaking. Replicants are physically matured and "born" at full adult growth - they don't go through a childhood to socially and emotionally mature like regular humans. The VK test is not aimed at detecting a lack of emotion - it is designed to detect inappropriate response to emotionally stimulating scenarios.
It seems that this emotionally stunting is known to be a problem - one of the reasons for the programmed short life-spans of the Nexus-6 models is because they become more "emotionally erratic" - Roy, Pris, Leon, and Zora are all close to the end of their life.
Tyrell Corporation were working on improving this - by programming in childhood memories - thereby providing some emotional maturity to the fresh new replicant.


Q:

What to do during Math PhD to have options in industry?

I have recently been accepted to a top five math PhD program. The department seems to have a good mix of pure and applied math, and there are plenty of opportunities for collaboration with other departments (Stats, CS, Econ, etc.)
I am most interested in pursuing math more on the applied side of things. Moreover, I would like options outside of academia once I graduate. Looking at the previous PhD alumni, this does not seem to be a problem - anyone not in academics is doing pretty interesting stuff in finance, data science, consulting, machine learning. However, I want to make sure I am not missing something along the way that these students did which enabled them to have broad and attractive job prospects.
I am especially interested in Analysis, Probability, Stats, Machine Learning, Econ, Mathematical Biology, Cryptography, and Applied topology. I would be happy to do work involving any one of these.
My questions are these:

What should I do during my PhD to be able to have good non-academic job prospects after graduating? (Would something like a PhD minor be helpful?)
How does it differ by field? If I want to do something like quantitative finance, what do I need to do versus if I want to do something like data science?
How can I find out more information about question two. As things change and evolve, how can I find out what it is I need in order to be accepted for positions and jobs involving areas that interest me?

I am not sure if I am exactly asking the right question, so if someone else has suggestions of what I should be asking, please suggest.
Note: There are a number of questions on this site that ask similar questions, ("I'm doing math but I want to go into industry") However I think my question is rather different. Firstly, I am hoping to pursue research with applications during my PhD, rather than focusing on super pure math. Secondly, I am asking this question before I have even started my PhD, hoping to know what I should do before, during, and after my program. Most of the other questions basically have the theme "I did a PhD in pure math, now what?"

A:

Based on my own interactions with graduate students and post-docs, I would suggest:

Develop skills that are useful to potential employers.  This includes basic communication skills and a broad background in data analysis and modeling as well as buzz-word computer skills (R, Python, Deep Learning, etc.)
Develop cultural-competence for the corporate world.  Learn how to dress and act the part, preferably by immersing yourself in the corporate world through an internship.
Have some examples of your work (besides your papers and dissertation) to show to potential employers.

A:

Another important factor here is choice of advisor. Look through the faculty profiles and see if you can find a good fit. This would be someone with industry experience, or that has managed to assign their students to industry jobs past graduation. It would be good to be advised by someone who'll be able to help you get internships at relevant companies and direct your research in the direction you want.
In my experience, math PhDs (with a smattering of CS/Econ/Stats) are highly employable in industry, even if they err on the purer side of research.
I know several people who studied pure math and applied their problem solving skills in internships with very good outcomes, let alone if you are learning applied skills on the way. Other soft skills that you acquire will be extremely useful in industry - writing papers, speaking skills, problem solving and so on.
PhD studies are also an excellent time to try out transitioning your ideas into startups. Most good universities have tech connections to help you do that, try to look into that.
Good luck!

A:

Instead of thinking in vague terms about how your mathematical training can be applied in industry, I think it is much more fruitful to focus on problems in the real world that excite you.  Most math PhDs pursue research problems by letting curiosity guide them.  Things don't suddenly change just because you're going into industry.  Particularly in the current era because of the tech boom, there are tremendous opportunities for bright, mathematically minded people in industry.
It isn't just power point presentations and talking to clients.  Of course there's nothing wrong with that if that's the kind of thing you like.  My point is just that mathematicians have a rare ability to think deeply and get to the core of a technical problem and many corporations are realizing the value they can bring.
If you haven't heard of them, two people to read about are Eric Lander and Jim Simons.  Both started out as mathematicians and went on to become great figures in the fields of biology and finance respectively.  It is notable that Jim started out trading in a discretionary manner and only later incorporated quantitative techniques.  So rather than viewing "industry" as some monolith, think about what problems you want to solve and be confident that your mathematical training will give you a leg up.


Q:

How to use Data.Data?

As I'm not familiar with rank-N types, the type signature of gfoldl is a troublesome for me:
gfoldl :: (forall d b. Data d => c (d -> b) -> d -> c b)
-> (forall g. g -> c g)
-> a
-> c a

The only functions I can think of are \xs y -> ($y) <$> xs and pure, respectively.
Other functions such as gunfold and gmapT have similar problems. So what are notable examples of nontrivial uses of them?

A:

For the gmapT case the mkT function is defined for this purpose in the original paper.
mkT :: (Typeable a, Typeable b ) => (b -> b) -> a -> a
mkT f = fromMaybe id (cast f)

For example to increment all int fields in the A, you can write something like
data A = A {f :: Int, s :: Int} deriving (Data, Typeable)

ex = gmapT (mkT inc) (A 2 3) where
  inc :: Int -> Int
  inc = (+1)

To make it clearer the ex function can be written like this too:
ex2 = gmapT f (A 2 3) where
  f :: (Data a ) =>  a -> a
  f a = case cast a of
    Nothing -> a
    (Just (b :: Int)) -> fromJust $ cast (b + 1)


Q:

DataGrid column bind to a item of the List

The ItemsSource of DataGrid is a List<myClass>, and myClass has a List<int> Property.
Now I want to bind the first item of the List<int> to the first column of the DataGrid, and the second item to the second column.
How to do it?
XMAL:
<DataGrid.Columns>
     <DataGridTextColumn Header="MyClass Name" Binding="{Binding Name}" ></DataGridTextColumn>
     <DataGridTextColumn Header="First Item of Numbers" Binding="{Binding ??}" ></DataGridTextColumn>
     <DataGridTextColumn Header="Second Item of Numbers" Binding="{Binding ??}" ></DataGridTextColumn>
</DataGrid.Columns>

c#:
class MyClass
{
        public string Name{ get; set; }
        public List<int> Numbers= new List<int>();
}

A:

You can specify the index of the collection.
Example:
Text = "{Binding MyClasses[0]}"

Text = "{Binding MyClasses[1]}"


Q:

Multi-Output Classification with Keras

I am using keras to build a multi-output classification model. My dataset is such as

[x1,x2,x3,x4,y1,y2,y3]

x1,x2,x3 are the features, and y1,y2,y3 are the labels, the y1,y2,y3 are multi-classes.
And I already built a model (I ingore some hidden layers):
def baseline_model(input_dim=23,output_dim=3):
    model_in = Input(shape=(input_dim,))
    model = Dense(input_dim*5,kernel_initializer='uniform',input_dim=input_dim)(model_in)
    model = Activation(activation='relu')(model)
    model = Dropout(0.5)(model)

    ...................

    model = Dense(output_dim,kernel_initializer='uniform')(model)
    model = Activation(activation='sigmoid')(model)

    model = Model(model_in,model)
    model.compile(optimizer='adam',loss='binary_crossentropy', metrics=['accuracy'])
    return model

And then I try to use the method of keras to make it support classification:
estimator = KerasClassifier(build_fn=baseline_model)
estimator.fit()
estimator.predict(df[0:10])

But I found that the result is not multi-output, only one dimension is output.

[0,0,0,0,0,0,0,0,0,0]

So for the multi-output classification problem, we can not use KerasClassifier function to learn it?

A:

You do not need to wrap the model in KerasClassifier. That wrapper is so that you can use the Keras model with Scikit-Learn. The type of model (classifier, regression, multiclass classifier, etc) is ultimately determined by the shape and activation of the final layer of your model.
You can simply use model.fit() function that is part of Keras. Make sure that you pass the data into the function. You can see more info on the fit function here: https://keras.io/models/model/#fit
Also your loss is setup as binary_crossentropy. For a multi-class problem you will want to use categorical_crossentropy.
model.compile(optimizer='adam',loss='categorical_crossentropy', metrics=['accuracy'])

This model isn't really what Keras refers to as multi-output as far as I can tell. With multi-output you are trying to get the output from several different layers and possibly apply different loss functions to them.
Base on the setup in your question you would be able to use the Keras Sequential model instead of the Functional model if you wanted. Keras recommends using the Sequential model if you can because its simpler. https://keras.io/getting-started/sequential-model-guide/


Q:

Selenium Webdriver Testing - Python

I wonder, what is the advantage of using selenium for automation if at the end of the test he emits no reports where the test passed or failed?

A:

Selenium isn't actually a testing framework, it's a browser driver.  You don't write tests in Selenium any more than you write GUI apps in OpenGL.  You usually write tests in a unit testing framework like unittest, or something like nose or lettuce built on top of it.  Your tests then use Selenium to interact with a browser, as they use a database API to access the DB or an HTTP library to communicate with web services.


Q:

How to build a web App with Git front end utils?

I know how to work in git. But, now I want to set up a git server in my org. so that developers can access it via internet from any where around the globe. I know about Github and I want to build my own custom git server for my organisation developers alone and I donot wish to outsource it to git hub like apps.
I need to provide browser based front end apart from console based. My server machine have windows Operating system. and we use java for our webdevelopment

A:

Take a look at "Web Interface" section of InterfacesFrontendsAndTools page on Git wiki, and at Gitweb page, also on Git wiki.

Below there is (probably incomplete) list of various git web interfaces and integrated git hosting solutions:
Pure web interfaces (I guess that most commonly used are gitweb and cgit):

gitweb (README) - in Perl, part of git
cgit - in C
viewgit - in PHP
GitPHP - in PHP
git-php: 1, 2, 3 - in PHP
ginatra - in Ruby, using Sinatra framework
Gitalist and Gitcat - in Perl, using Catalyst framework
django-git and django-gitweb - in Python, using Django framework

Git hosting solutions (forges) with built-in web interface:

Gitorious - in Ruby
InDefero - in PHP
GitHub:FI - in Ruby, proprietary


Q:

Iterate Over String Fields in Struct

I'm looking to iterate over the string fields of a struct so I can do some clean-up/validation (with strings.TrimSpace, strings.Trim, etc).
Right now I have a messy switch-case that's not really scalable, and as this isn't in a hot spot of my application (a web form) it seems leveraging reflect is a good choice here.
I'm at a bit of a roadblock for how to implement this however, and the reflect docs are a little confusing to me (I've been digging through some other validation packages, but they're way too heavyweight + I'm using gorilla/schema for the unmarshalling part already):

Iterate over the struct
For each field of type string, apply whatever I need to from the strings package i.e. field = strings.TrimSpace(field)
If there exists a field.Tag.Get("max"), we'll use that value (strconv.Atoi, then unicode.RuneCountInString)
Provide an error slice that's also compatible with the error interface type
type FormError []string

type Listing struct {
        Title string `max:"50"`
        Location string `max:"100"`
        Description string `max:"10000"`
        ExpiryDate time.Time
        RenderedDesc template.HTML
        Contact string `max:"255"`
    }

    // Iterate over our struct, fix whitespace/formatting where possible
    // and return errors encountered
    func (l *Listing) Validate() error {

       typ := l.Elem().Type()

       var invalid FormError
       for i = 0; i < typ.NumField(); i++ {
           // Iterate over fields
           // For StructFields of type string, field = strings.TrimSpace(field)
           // if field.Tag.Get("max") != "" {
           //     check max length/convert to int/utf8.RuneCountInString
                  if max length exceeded, invalid = append(invalid, "errormsg")
       }

       if len(invalid) > 0 {
           return invalid
       }

       return nil
   }

   func (f FormError) Error() string {
       var fullError string
       for _, v := range f {
           fullError =+ v + "\n"
       }
       return "Errors were encountered during form processing: " + fullError
   }

Thanks in advance.

A:

What you want is primarily the methods on reflect.Value called NumFields() int and Field(int). The only thing you're really missing is the string check and SetString method.
package main

import "fmt"
import "reflect"
import "strings"

type MyStruct struct {
    A,B,C string
    I int
    D string
    J int
}

func main() {
    ms := MyStruct{"Green ", " Eggs", " and ", 2, " Ham      ", 15}
    // Print it out now so we can see the difference
    fmt.Printf("%s%s%s%d%s%d\n", ms.A, ms.B, ms.C, ms.I, ms.D, ms.J)

    // We need a pointer so that we can set the value via reflection
    msValuePtr := reflect.ValueOf(&ms)
    msValue := msValuePtr.Elem()

    for i := 0; i < msValue.NumField(); i++ {
        field := msValue.Field(i)

        // Ignore fields that don't have the same type as a string
        if field.Type() != reflect.TypeOf("") {
            continue
        }

        str := field.Interface().(string)
        str = strings.TrimSpace(str)
        field.SetString(str)
    }
    fmt.Printf("%s%s%s%d%s%d\n", ms.A, ms.B, ms.C, ms.I, ms.D, ms.J)
}

(Playground link)
There are two caveats here:

You need a pointer to what you're going to change. If you have a value, you'll need to return the modified result.
Attempts to modify unexported fields generally will cause reflect to panic. If you plan on modifying unexported fields, make sure to do this trick inside the package.

This code is rather flexible, you can use switch statements or type switches (on the value returned by field.Interface()) if you need differing behavior depending on the type.
Edit: As for the tag behavior, you seem to already have that figured out. Once you have field and have checked that it's a string, you can just use field.Tag.Get("max") and parse it from there.
Edit2: I made a small error on the tag. Tags are part of the reflect.Type of a struct, so to get them you can use (this is a bit long-winded) msValue.Type().Field(i).Tag.Get("max")
(Playground version of the code you posted in the comments with a working Tag get).

A:

I got beat to the punch, but since I went to the work, here's a solution:
type FormError []*string

type Listing struct {
    Title        string `max:"50"`
    Location     string `max:"100"`
    Description  string `max:"10000"`
    ExpiryDate   time.Time
    RenderedDesc template.HTML
    Contact      string `max:"255"`
}

// Iterate over our struct, fix whitespace/formatting where possible
// and return errors encountered
func (l *Listing) Validate() error {
    listingType := reflect.TypeOf(*l)
    listingValue := reflect.ValueOf(l)
    listingElem := listingValue.Elem()

    var invalid FormError = []*string{}
    // Iterate over fields
    for i := 0; i < listingElem.NumField(); i++ {
        fieldValue := listingElem.Field(i)
        // For StructFields of type string, field = strings.TrimSpace(field)
        if fieldValue.Type().Name() == "string" {
            newFieldValue := strings.TrimSpace(fieldValue.Interface().(string))
            fieldValue.SetString(newFieldValue)

            fieldType := listingType.Field(i)
            maxLengthStr := fieldType.Tag.Get("max")
            if maxLengthStr != "" {
                maxLength, err := strconv.Atoi(maxLengthStr)
                if err != nil {
                    panic("Field 'max' must be an integer")
                }
                //     check max length/convert to int/utf8.RuneCountInString
                if utf8.RuneCountInString(newFieldValue) > maxLength {
                    //     if max length exceeded, invalid = append(invalid, "errormsg")
                    invalidMessage := `"`+fieldType.Name+`" is too long (max allowed: `+maxLengthStr+`)`
                    invalid = append(invalid, &invalidMessage)
                }
            }
        }
    }

    if len(invalid) > 0 {
        return invalid
    }

    return nil
}

func (f FormError) Error() string {
    var fullError string
    for _, v := range f {
        fullError = *v + "\n"
    }
    return "Errors were encountered during form processing: " + fullError
}

I see you asked about how to do the tags. Reflection has two components: a type and a value. The tag is associated with the type, so you have to get it separately than the field: listingType := reflect.TypeOf(*l). Then you can get the indexed field and the tag from that.


Q:

Calling click event of a button serverside

How can I click or load the click() event of a button in codebehind?
I already tried
      btn.Click();

but this gives an error. I am using ASP.NET

A:

I will assume that you have a button called Button1
and that you have double clicked it to create an event handler.
To simulate the button click in code, you simply
call the event handler:
Button1_Click(object sender, EventArgs e).
e.g. in your Page Load Event
protected void Page_Load(object sender, EventArgs e)
{
    //This simulates the button click from within your code.
    Button1_Click(Button1, EventArgs.Empty);
}

protected void Button1_Click(object sender, EventArgs e)
{
    //Do some stuff in the button click event handler.
}

A:

If you don't need the context provided by the sender and eventargs then you can just refactor to create a method (eg DoStuff()) and make your event handler just call that. Then when you want to call the same functionality from elsewhere you can just call DoStuff(). It really depends on whether you want to actually simulate a click or not. If you want to simulate a click then other methods are better.

A:

Do you wish to call all the event handlers attached to the button, or just one?
If just one, call the handler:
 btn.btn_Click(btn, new EventArgs());

If all of them, trigger the event:
 var tmpEvent = btn.Click;
 if (tmpEvent != null)
      tmpEvent(btn, new EventArgs());


Q:

A Problem with a Proof Concerning the Properties of Orthogonal Matricies

OK, I'm working on the following problem and don't understand how my Linear Algebra text has made it to a certain conclusion here is the problem:

Let u be a unit vector in $R^{n}$ and let $H = I - 2\textbf{u}\textbf{u}^{T}$.  Show that H is both orthogonal and hence it's own inverse.

So here is the work, I've done and it corresponds with the book, up until a point anyway:

$H^{T} = (I − 2\textbf{u}\textbf{u}^{T})^{T} $
$ = I^{T} − 2(\textbf{u}^{T})^{T} \textbf{u}^{T} $
$ = I − 2\textbf{u}\textbf{u}^{T} = H$

So far so good...

$H^{T}H = H^{2}$
$ = (I − 2\textbf{u}\textbf{u}^{T} )^{2} $
$ = I − 4\textbf{u}\textbf{u}^{T} + 4\textbf{u}\textbf{u}^{T} \textbf{u}\textbf{u}^{T} $

It's at this point the textbook's answer diverges from mine, and states that the previous statement is equal to $ I - 4\textbf{u}\textbf{u}^{T} + 4\textbf{u}\textbf{u}^{T}$.  While this is what I want, why is $4\textbf{u}\textbf{u}^{T} \textbf{u}\textbf{u}^{T} = 4\textbf{u}\textbf{u}^{T}$ and not say equal to some value $4(\textbf{u}\textbf{u}^{T})^{2}$?

A:

Your assumption is that $\mathbf{u}$ is a unit vector. This means that $$\mathbf{u}^\mathrm{T}\mathbf{u} = \|\mathbf{u}\|^2 = 1$$
You then have
$$4\mathbf{u}\mathbf{u}^\mathrm{T}\mathbf{u}\mathbf{u}^\mathrm{T} = 4\mathbf{u}(\mathbf{u}^\mathrm{T}\mathbf{u})\mathbf{u}^\mathrm{T} = 4\mathbf{u}\|\mathbf{u}\|^2\mathbf{u}^\mathrm{T}=4\mathbf{u}\mathbf{u}^\mathrm{T}$$


Q:

Will Phonegap or Cordova apps receive push notifications when app not opened?

I have serious doubt. If Phonegap(or Cordova) apps won't run in background how can I get the GCM/FCM push notifications when my app is not in use or not opened ?
Is there any way to solve this problem ?
What is Chrome push notifications, can I use that with Phonegap apps ?

A:

Using Cordova plugin FCM, your push notifications will work when app is open or closed. Both on Android and iOS.
Your app does not need to be running in the background to receive push notifications.


Q:

How to get notified after the event ends

In my UWP app I am using DynamicOverflowItemsChanging event of a CommandBar my usecase is not very complex, I tried to solve another problem I had by using this event, see the answer of this post.
So as shown in the answer in the link I provided above, I am trying to invoke this event and sync the visibility of MoreButton now the problem is this event is fired when the secondary overflow menu of command bar doesn't have the item removed or added yet, so they still show the items which they had before the event was fired, but when this event is completed then transfer of items is also completed.

So in short I want to raise another event somehow or get notified when the DynamicOverflowItemsChanging completes its execution, so I can have the correct data and set the visibility of more button correctly. or in other words I want to implement a behaviour of DynamicOverflowItemsChanged event, which unfortunately doesn't exist in the api, so I am looking for an alternative way.

I know I can invoke another event right at the end (just before DynamicOverflowItemsChanging event is finished), but that way I still don't get the correct values, correct values only become available when this event finishes its execution. Like we can do with Task.Then() so when a task completes another can automatically start, so I want something like that here . any suggestions would be appreciated.
protected override void OnApplyTemplate()
{

    var barr = (CommandBar)GetTemplateChild("MediaControlsCommandBar");

    //the event to control the dynamicoverflow automatically.
    barr.DynamicOverflowItemsChanging += (s, e) =>
    {
        if (_secondarycontrols.Items.Count == 0 && e.Action == CommandBarDynamicOverflowAction.AddingToOverflow)
            _moreButton.Visibility = Visibility.Visible;
        else if (_secondarycontrols.Items.Count == 1 && e.Action == CommandBarDynamicOverflowAction.RemovingFromOverflow)
            _moreButton.Visibility = Visibility.Collapsed;
    };//when this event finishes here I want to get notified.

    //base implementation
    base.OnApplyTemplate();
}

A:

Warm greetings, fellow Microsoft Student Partner :-) .
The quick and dirty hack would be to add a Task.Delay to the end of the handler and hope the items will have changed until the delay is over. This is of course really ugly and error prone. I would suggest a different solution.
You already have access to the _secondarycontrols which is a CommandBarOverflowPresenter. This is very useful, because Items property has a VectorChanged event which is fired whenever an item is added, removed or changed. This means, you can actually use this event and move your logic inside it instead of using the DynamicOverflowItemsChanging event. You can then directly check for the number of items which will be accurate.


Q:

Bullets and pasting into flow document

I need to paste some rtf text from a datagrid into a flow document. I want to paste it at the caret position in the richtextbox. This works except when i have a bullet or Numbered list. It will paste it before the bullet or number.
I have searched every where for this with no luck.
private void dgStandardText_MouseDoubleClick(object sender, MouseButtonEventArgs e) {
 if (dgStandardText.SelectedItems.Count > 0) {
  foreach(DataRowView row in dgStandardText.SelectedItems) {
   byte[] byteArray = Encoding.ASCII.GetBytes(row[3].ToString());
   using(MemoryStream ms = new MemoryStream(byteArray)) {
    TextRange tr = new TextRange(txtAreaText.CaretPosition, txtAreaText.CaretPosition);
    tr.Load(ms, DataFormats.Rtf);
   }
  }
 }
 NeedSave = true;
 dgStandardText.SelectedItems.Clear();
}

 Before Paste
 After Paste

A:

This seems to happen when the content you're pasting includes block elements, as opposed to inline elements.  For plain text, WPF seems to treat newlines (e.g., \r\n) as paragraph breaks, so multi-line content would be translated into multiple blocks.  What you want to do is insert just the inline content from each of those source blocks, such that it goes into the current block of the target document (in this case, a list item).  Do this for the first source block, then insert a paragraph break, update the caret position, and move on to the next block.
Is the content of the grid row actually RTF content, or is it plain text?  If it's plain text, then this should be pretty straightforward.  Try changing your foreach loop body to something like this:
var text = row[3].ToString();

var lines = text.Split(
    new[] { '\r', '\n' },
    StringSplitOptions.RemoveEmptyEntries);

foreach (var line in lines)
{
    var p = txtAreaText.CaretPosition;

    txtAreaText.BeginChange();

    p.InsertTextInRun(line);
    p = p.InsertParagraphBreak();

    txtAreaText.EndChange();
    txtAreaText.CaretPosition = p;
}

Now, if the source content really is RTF, then things will get more complicated.  I suspect you'll need to load it into an in-memory flow document and walk through the elements to figure out where the paragraph breaks are.  For each paragraph, locate the inline contents that intersect the selection range, and insert them into the target document.  Insert a paragraph break when you reach the end of each paragraph in the source range, just like in the example above.
I'm afraid the Documents API is the one area of WPF that I haven't explored very thoroughly, so I can only give you a general idea of what to do.  Perhaps someone else can provide more detail.


Q:

MongoDB query returns null even though it is available in the collection after migrating from mlab to mongoDB atlas

I am migrating a database from Mlab to MongoDB Atlas. We had to upgrade the npm version of mongodb to 3.4.1 as the MongoDB atlas database version is 4.2.5.
The connection function has been updated as said in this answer. But after upgrading the npm version to 3.4.1 the findOne query returns a null value even-though the document is available in the collection. Here is the code section related of the findOne query,
  db.collection('organisations').findOne({ _id: database.ObjectID(orgState) })
    .then((activeOrganisation) => {
      console.log(activeOrganisation);
      data.activeOrganisation = activeOrganisation;
      callback(null, activeOrganisation);
    }, (error) => {
      callback(error, null);
    });

Because of this I was wondering whether there is a problem with the database connection so I tested it with running db.serverConfig.isConnected() , db.databaseName and db.listCollections().toArray(). The isconnected returned true and the returned database name is also correct. But db.listCollections().toArray() returned an empty array which means there are no collections in my database which cannot be.
Then I tried a findOneAndUpdate query just to check what happens with that. Here is the relevant code for it,
db.collection('users').findOneAndUpdate(
        { emails: { $elemMatch: { email: "rajitha1591@outlook.com" } } },
        { $addToSet: { unsubscribedEmails: "models" } })
        .then((result) => {
          console.log(result);

            if (!result) {
                console.error('Error: ', 'User not found')
            }
            console.log('Output: ', 'Sucessfully unsubscribed');
            callback(null,'Successful')
        }, (error) => {
            callback(error, null);
        });

The result contained,
{
  lastErrorObject: { n: 0, updatedExisting: false },
  value: null,
  ok: 1,
  '$clusterTime': {
    clusterTime: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1586436331 },
    signature: { hash: [Binary], keyId: [Long] }
  },
  operationTime: Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1586436331 }
}

This clearly says that the document didn't got updated(updatedExisting: false). I checked the related document in MongoDB Atlas using the web browser as well and the document wasn't updated by adding the "models" value to the unsubscribedEmails array.
In addition to that I tried a fresh install of node_modules by  deleting the package-lock.json as well.
Since I migrated the database from mlab is it a possibility that  exceeding limits  of MongoDB shared cluster  to occur this issue.
It would be nice to hear suggestions regarding this issue

A:

The structure of holding databases are different in mlab and mongoDB Atlas. The mlab shared cluster represents one database while the mongoDB atlas shared cluster can contain multiple databases.
The below image shows the mlab databases.

Here is an image when you go inside of a database

After the migration process (migrated using the tool provided by mlab and Atlas). It created a shared clusted named maturify-demo and a database named maturify_demo. Look at the below images.
Atlas cluster

Database inside the cluster

During the migration process it changed the cluster name that was used in Mlab (maturify_demo to maturify-demo)
When connecting to the database using the client I used maturify-demo as the Db name thinking that the cluster represents a database as Mlab (cachedDb = client.db('maturify-demo');). Which actually has to be maturify_demo. But when I am testing the database connection using db.serverConfig.isConnected() and db.databaseName. It returned true and maturify-demo which was a bit confusing where it shows a database which is not available in MongoDB Atlas. As @Joe mentioned in the below comment it allows to add documents as a new database even though the database currently does not exist.


Q:

What are all of the quotes in the OP of Eden of the East from?

In the Eden of the East opening, there are a lot of quotes from different sources. The only one I know the origin of is "The abuse of greatness is when it disjoins remorse from power," which is from Julius Caesar by William Shakespeare. I don't know what the other quotes that show up on the screen are from or are in reference to. Can someone tell me?

A:

This blogpost has a transcript of all of the text from the opening. Not all of them are famous quotes.

"I saw you in Heaven
  and heard of your glory
  You saved our world from the fallen angels
  I saw Messiah standing
  Standing before me with no words
  Nothing but "Hope"
  When we lost dread, a Demon was laughing
  But now you are showing us wonder
  Giving your love
  With awe, down on my knees again
  I've got to know you're the one
  The only one reveals the world"

This is repeated multiple times throughout the OP and seems to be part of the song 東のエデン挿入歌「Reveal The World」

"The abuse of greatness is when it disjoins remorse from power."

As you've noted, it's Brutus from Julius Caesar, by William Shakespeare.

"Mail
  Own date
  Media tool
  Appli
  Camera
  Phone book
  Iseg
  Music
  Service
  Setting
  You've got mail
  Calling
  Talking"

These seem to be options (partially obscured) of the phone.

"Let me walk with you when I'm lost in the wild
  I know you always lead me to another Eden
  Let me bless your name, O Lord, O Lord
  Your words will never fade away
  Since we believe you're the light on earth
  Reveals the world"

Also from the "Reveal the world" song lyrics.
The rest seems to be proper names and instances from the show itself, like "noblesse oblige", and "Juiz", and "Selecao system
12 persons selected in Japan". So the only real quote I guess is from the Julius Caesar play.


Q:

how to check which files has been changed between two revisions in Mercurial / Tortoise Hg?

how to check which files has been changed between two revisions in Mercurial / Tortoise Hg?
I have tried visual diff of tortoiseHg, it do not highlight which specific files have been added, changed or unchanged and you have to click every file to get details

A:

CLI-version: hg diff -r START -r END --stat
Sample:
>hg diff -r 4 -r tip --stat
 404.php        |    4 ++--
 functions.php  |    2 +-
 readme.txt     |   28 +++++++++++++++++-----------
 screenshot.png |  Bin
 sidebar.php    |    2 +-
 style.css      |    4 ++--
 6 files changed, 23 insertions(+), 17 deletions(-)


Q:

PushPlugin not found in iOS application using cordova

I am trying to use the PushPlugin to develop an iOS application. I am facing the following error:
DEPRECATION NOTICE: The Connection ReachableViaWWAN return value of '2g' is deprecated as of Cordova version 2.6.0 and will be changed to 'cellular' in a future release.

2013-12-23 17:19:52.362 myApp[537:60b] CDVPlugin class PushPlugin (pluginName: PushPlugin) does not exist.

2013-12-23 17:19:52.363 miniOrangeAuthenticator[537:60b] ERROR: Plugin 'PushPlugin' not found, or is not a CDVPlugin. Check your plugin mapping in config.xml.

2013-12-23 17:19:52.364 miniOrangeAuthenticator[537:60b] -[CDVCommandQueue executePending] [Line 116] FAILED pluginJSON = [

  "PushPlugin1458195152",

  "PushPlugin",

  "register",

  [

    {

      "alert" : "true",

      "ecb" : "onNotificationAPN",

      "sound" : "true",

      "badge" : "true"

    }

  ]

]

I have added the dependency in the config.xml file as follows:
<feature>
    <param name="ios-package" value="PushPlugin" />
</feature>

i also tried the old plugins format with the following code:
<plugin name="PushPlugin" value="com.phonegap.plugins.PushPlugin" />

Even that gave me the same error.
I am trying on a real iOS device.
what may be the issue here?

A:

Which version of cordova are you using?
I installed that plugin with cordova 2.9 and I remember that I had some problem importing the files in xcode.
If you are using cordova 3.x on iOS you just have to add the plugin via command line (on android you have also to manually copy a file, but on iOS it's not necessary).
EDIT to answer the question in the comment: the only thing I can think of is that you initialize the plugin before the "device ready" event is fired. This is the code I use:
var initPushNotification = function() {
    var pushNotification = window.plugins.pushNotification;
    pushNotification.register(
        tokenHandler,
        errorHandler, {
            "badge":"true",
            "sound":"true",
            "alert":"true",
            "ecb":"onNotificationAPN"
        });
};

function onDeviceReady() {
    // other stuff here...
    initPushNotification();
}


Q:

Why do we rarely see recumbents and almost never see velomobiles?

Recumbent bicycles are more efficient than ordinary upright bicycles, and velomobiles are even more efficient. Then why do we see them so rarely on the road? Is it because they are expensive, or are there some non-financial, significant disadvantages?

A:

Talked to a guy who had a velomobile at a local charity ride. He said the thing cost $5000. Recumbents, while not as expensive as velomobiles are also quite expensive. Usually over $2000. That could be part of the reason. Sure, with economies of scale, they could be made cheaper, but that's kind of a chicken and an egg problem.  Also, even though recumbents and velomobiles are so much more efficient, they do have quite a few of their own problems.  Because they have so much extra weight, they tend to be quite a bit slower on the hills. Many people also don't like being so close to the ground.  I like being able to stand on my pedals and see over most of the cars when riding in traffic.  Also, regular bikes are pretty efficient these days. For $1000 you can get a pretty good bike. And one last thing. Don't underestimate the "conformity" factor.  Many people don't want to be seen as weird, or outsiders, and want to fit in with social norms. Riding a bike is already going against social norms in many places. For some people, having a recumbent just takes things a bit outside their comfort zone.

A:

I switched to a recumbent about 10 years ago in 2002, when I was 48.  I rented one for a ride and was so impressed with the comfort and speed that I eventually changed over.  My current rig has a full fairing and full-length spandex wrap.
Arguments:
1 - Cost.  I waited over 2 years to buy due to the cost, then started out with a $900 bike (which I soon traded in for a $2,000 TourEasy, which ran up to $3,000 with fairing, lights, etc.).  Many friends and family considered me crazy, but I live in an area where I can get almost everywhere by bike.  In 2007, I spent less than $100 on gasoline.  Since then I've been averaging 500-750 miles each year in my auto and 5,000 to 6,000 miles on my bike).  For my situation, the cost was high, but the savings have been much higher.
2 - Comfort.  No contest.  There's a reason furniture does not use diamond-frame bicycle posture.  No crotch numbness, neck issues, etc.  These discomforts did not bother me before 45, but the comfort factor (for me) seems to be a bigger factor every year.  The fairing and wrap offer even more comfort when the weather turns extreme--usually a light jacket and tights is sufficient, even in single-digit temperatures; and the shade compensates for less wind in the heat (plus no need  for sunscreen).
3 - Performance.  I can blast up a hill like a parachute in water--the best I can say for uphill riding on a recumbent is that maybe it builds character.  Downhills and flats, though, are great--the fairing aerodynamics help.  Speeds (note, I'm almost 60 years old, diabetic, and had a triple bypass a couple of years ago, so these speed won't be impressive):  Sustained on a flat - 25-30 mph; steep downhill with a tailwind - 50-60 mph;  steep uphill - no comment (thank God for low gears!).  Much wider turning radius.  No flipping over the handlebars, though, on hard stops.  Another performance feature relates to comfort--I can ride for hours and hours and hours, and rides over 100 miles makes me tired and my legs sore the next day, but no discomfort in my butt, back, neck, or other parts.
4 - Dork factor.  I don't care (see number 2 and 3 above).  However, reactions seem to be pronounced.  Young kids say "Oooooh!  Cool!"  Older kids divide between "What the #$%#$ is that?" and "I want one!"  I get tons of questions.  I get noticed--so I try to obey all the traffic signs/signals and be considerate, which is not necessarily how I rode before.  It also gets noticed when parked, sometimes attracting thieves and vandals.
5 - Safety.  Bikes are dangerous around cars.  Car drivers just aren't looking for us and don't see us--and often don't bear any blame when they run us down.  To mitigate this, I use bright lights, brightly colored wraps, and a motorcycle helmet (allowed by the upright posture)--and avoid as much car traffic as I can.  So far, so good (I was hit 3 times on my DF [Diamond Frame bike]).
6 - Accommodation.  A definite minus.  Normal bike racks, bike carriers, bus racks, etc. usually won't work.  Much longer and heavier than my DF was.  No carrying it over my head through crowds.
Every person will have different priorities.  You have to try one to know if it's for you or not.

A:

My regular (commuting) bike is an old Cannondale mountain bike with road slicks. It's great for city riding, but it murders my back, crotch, hands, feet, etc. on long trips.
So, a couple years ago I bought a Bacchetta Giro 26 recumbent bike specifically for a 2000+ mile ride. I've used it since for rides of longer than a day. So here's my two cents:
Comfort: Riding a 'bent consists of sitting in a lawn chair doing leg-presses all day. IMO, no diamond frame bike (DF) will ever come anywhere close to matching a 'bent for comfort. Over the last week of my trip I rode back-to-back-to-back-to-back 110+ mile days with no issues other than some soreness in my knees. Best of all, you can look at the scenery instead of the asphalt, without craning your neck. This is a massive plus.
Safety: The bike I bought has 26" wheels front and rear. My head is a few inches lower than on a DF, but I've never had any issues with visibility. I rode through several major metropolitan areas in fairly heavy traffic and never felt unsafe or invisible.
Dork factor: Everyone is fascinated by the bike. Everyone. I had a Hell's Angels looking dude shout "nice hog" at me at one point. Lots of people ask if I built it myself. One guy pulled over to take a photo. Every single person who has remarked on the bike has been enthusiastic and friendly, with one (group) exception: spandex-clad road riders, who generally pretend they don't see me.
Hills: Climbing hills on a 'bent isn't all that tough. It just requires persistence. You won't blast up a hill, but you can climb for hours on end. The biggest negative is that on a steep hill, if you stop for any reason, it can be damn near impossible to get going again. Also, balance becomes an issue at very low speeds.
All that said, 'bents are ideal for touring, so-so for daily utilitarian use, and of course illegal for racing. Of those three uses, touring is the rarest, and it's pretty hard to build a market around something most people don't do.
It's a pity, IMO — 'bents are a lot of fun, but most folks will never know it. But then again, I've got mine and get a lot of use out of it. If other people miss out, that's their problem, not mine. I expect most recumbent riders feel the same way.


Q:

Emacs as git editor does not load COMMIT_EDITMSG

I am using git (on linux) and want to use emacs as editor. However after git config --global core.editor emacs any git commit open emacs in *scratch* buffer and does not load COMMIT_EDITMSG at all.
How to force them to work with each other? So git commit will open emacs editor with  COMMIT_EDITMSG loaded?

A:

Executing emacs ./.git/COMMIT_EDITMSG had the same behavior (scratch buffer was opened). That's because owner of .emacs.d folder was root. All I need to do is simply change the owner sudo chown -hR logcat:logcat .emacs.d/


Q:

Odd click issues (Python & Pygame)

I'm creating a program that makes a box move when I select it (By clicking) then clicking again where it needs to go. But this doesn't work. Instead the object moves a few pixels then stutters.
import pygame
import sys
import time
import Test_Class
from pygame import gfxdraw

pygame.init()

black = (1, 1, 1)
white = (255, 255, 255)
red = (255, 0, 0)
orange = (255, 130, 28)
light_orange = (255, 139, 36)
yellow = (231, 231, 42)
green2 = (0, 130, 15)
green = (0, 255, 0)
cyan = (60, 142, 176)
light_blue = (165, 165, 255)
blue = (0, 0, 255)
grey = (127, 127, 127)
light_grey = (191, 191, 191)
purple = (140, 57, 188)
brown = (112, 68, 37)
pink = (237, 167, 203)
dark_grey = (64, 64, 64)

display_width = 1260
display_height = 900

Bob = Test_Class.Army(400, 600)
game_display = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("WW1 game")
clock = pygame.time.Clock()

def game_loop():
    game_exit = False
    while not game_exit:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_exit = True
                pygame.quit()
                quit()
                sys.exit()
        game_display.fill(light_grey)
        Bob.shape()
        Bob.selection1()
        Bob.movement()
        pygame.display.update()
        clock.tick(60)

game_loop()
pygame.quit()
quit()
sys.exit()

import pygame
import sys
import time
from pygame import gfxdraw

pygame.init()

black = (1, 1, 1)
white = (255, 255, 255)
red = (255, 0, 0)
orange = (255, 130, 28)
light_orange = (255, 139, 36)
yellow = (231, 231, 42)
green2 = (0, 130, 15)
green = (0, 255, 0)
cyan = (60, 142, 176)
light_blue = (165, 165, 255)
blue = (0, 0, 255)
grey = (127, 127, 127)
light_grey = (191, 191, 191)
purple = (140, 57, 188)
brown = (112, 68, 37)
pink = (237, 167, 203)
dark_grey = (64, 64, 64)

display_width = 1260
display_height = 900

game_display = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("WW1 game")
clock = pygame.time.Clock()

class Army:
    def __init__(self, posx, posy):
        self.posx = posx
        self.posy = posy
        self.movex = posx
        self.object = []
        self.movey = posy
        self.select = False

    def shape(self):
        gfxdraw.box(game_display, (self.posx, self.posy, 48, 30), black)
        gfxdraw.box(game_display, (self.posx + 2, self.posy + 2, 43, 26), blue)
        pygame.draw.line(game_display, black, (self.posx, self.posy + 1),
                         (self.posx + 47, self.posy + 28), 3)

    def movement(self):
        if self.movex > self.posx:
            self.posx += 2
        elif self.movex < self.posx:
            self.posx -= 2
        if self.movey > self.posy:
            self.posy += 2
        elif self.movey < self.posy:
            self.posy -= 2

    def selection1(self):
        mouse = pygame.mouse.get_pos()
        if self.posx + 48 > mouse[0] > self.posx and self.posy + 30 > mouse[1] > self.posy:
            click = pygame.mouse.get_pressed()
            if click[0] == 1:
                gfxdraw.box(game_display, (self.posx + 2, self.posy + 2, 43, 26), light_blue)
                pygame.draw.line(game_display, dark_grey, (self.posx, self.posy + 1), (self.posx + 47, self.posy + 28), 3)
                self.select = True
        while self.select is True:
            click = pygame.mouse.get_pressed()
            if click[0] == 1:
                print("True")
                mouse = pygame.mouse.get_pos()
                self.movex = mouse[0]
                self.movey = mouse[1]
                self.select = False
                pygame.display.update()
                clock.tick(60)

Edit: Added everything required to test this.

A:

The stutter
The stutter happens if you click somewhere that's not divisible by 2, since you're tank is moving by 2 pixels each loop. So if you're clicking at x = 201 and your tank is at x = 200 it'll move to 202, and then back to 200 and repeat. Same is true for y.
A solution to the problem could be to add 1 to x or y if they're are odd. In other words: make it so the user's selected position only is in even numbers. Another solution could be to add the distance between for example posx and movex if the current distance is less than the amount of pixels the tank is moving. Like this:
def movement(self):
    if self.movex > self.posx:
        self.posx += 2 if abs(self.posx - self.movex) > 2 else abs(self.posx - self.movex)
    elif self.movex < self.posx:
        self.posx -= 2 if abs(self.posx - self.movex) > 2 else abs(self.posx - self.movex)
    if self.movey > self.posy:
        self.posy += 2 if abs(self.posy - self.movey) > 2 else abs(self.posy - self.movey)
    elif self.movey < self.posy:
        self.posy -= 2 if abs(self.posy - self.movey) > 2 else abs(self.posy - self.movey)

Selecting and moving
The problem is that you're checking if the mouse button is down, rather than if the mouse button is clicked. This means that if you're holding down the mouse button for longer than 1/60 ≈ 0.017 seconds, you're both selecting and moving the tank.
A solution could be to create two methods, select_tank and select_pos, which could be called in the event loop when the user presses the mouse button. I split your method selection1 and took away som unnecessary code. Also, notice that I put a line of code in draw to make it change color depending on whether it's selected or not.
class Army(object):
    def __init__(self, posx, posy):
        self.posx = posx
        self.posy = posy
        self.movex = posx
        self.movey = posy
        self.select = False

    def draw(self):
        color = blue if not self.select else light_blue
        gfxdraw.box(game_display, (self.posx, self.posy, 48, 30), black)
        gfxdraw.box(game_display, (self.posx + 2, self.posy + 2, 43, 26), color)
        pygame.draw.line(game_display, black, (self.posx, self.posy + 1),(self.posx + 47, self.posy + 28), 3)

    def move(self):
        if self.movex > self.posx:
            self.posx += 2 if abs(self.posx - self.movex) > 2 else abs(self.posx - self.movex)
        elif self.movex < self.posx:
            self.posx -= 2 if abs(self.posx - self.movex) > 2 else abs(self.posx - self.movex)
        if self.movey > self.posy:
            self.posy += 2 if abs(self.posy - self.movey) > 2 else abs(self.posy - self.movey)
        elif self.movey < self.posy:
            self.posy -= 2 if abs(self.posy - self.movey) > 2 else abs(self.posy - self.movey)

    def select_tank(self):
        mouse = pygame.mouse.get_pos()
        if self.posx + 48 > mouse[0] > self.posx and self.posy + 30 > mouse[1] > self.posy:
            self.select = True

    def select_pos(self):
        mouse = pygame.mouse.get_pos()
        self.movex = mouse[0]
        self.movey = mouse[1]
        self.select = False

def game_loop():
    game_exit = False
    while not game_exit:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_exit = True
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if bob.select:
                    bob.select_pos()
                else:
                    bob.select_tank()
        game_display.fill(light_grey)
        bob.move()
        bob.draw()
        pygame.display.update()
        clock.tick(60)

Remarks

Use just lower case letters and underscores for your variable names to don't get others confused whether it's a class or variable.
If you're importing from your own classes, make sure you don't have code that's being run unnecessary. In your Test_Class you set the display mode and captions when it's being imported. This is when you could use if __name__ == "__main__":.
Don't repeat unnecessary code. In your code you're using 4 functions that terminates, when you only need 1. In selection1 you're updating the screen and calling clock.tick method even if you're doing it in the game loop.
When asking questions on Stack overflow, make sure to give the readers Minimal, Complete, and Verifiable code. You could have removed most of the color constants, import time (since you're not using it) and self.object in the Army class (also unused). It would make the code a bit shorter and thus slightly easier to read.


Q:

Reduce the name of a ASCII

I have to use a script to convert AscII to Raster, and I used one I found from GeoNet. But now, the problem is to reduce the name of the AscII files, because I can't name the Raster with more than 13 characters.
MDT05-0561-H30-LIDAR.asc is the name of files, and then, without changing the ".asc", because there is a looping reading this part, how can I reduce the formentioned name to "MDT05-0561.asc" name?
import arcgisscripting, os

# Create the Geoprocessor
gp = arcgisscripting.create()

# Set local variables
InAsciiFile = None
inDir = ""
OutRaster = ""
gp.outputCoordinateSystem = "etrs_89_wkd.prj"

for InAsciiFile in os.listdir(inDir):
    InAsciiFile =list(InAsciiFile)
    InAsciiFile.remove('-H30-LIDAR')
#because all of them have the last part: -H30-LIDAR

if InAsciiFile.rsplit(".")[-1] == "asc":
     print InAsciiFile
   # Process: ASCIIToRaster_conversion
    gp.ASCIIToRaster_conversion(os.path.join(inDir,InAsciiFile), os.path.join(OutRaster,InAsciiFile.rsplit(".")[0]), "FLOAT")

A:

Use slicing to extract the first 10 characters, and the os.path.splitext function to append the original extension:
OutAsciiFile = InAsciiFile[:10] + os.path.splitext(InAsciiFile)[1]
This method will work without looking for a specific string.


Q:

Pass an actor as parameter

For example, I have
trait Logger {
  def log(m: Message) = ???
}

If I want to pass a Logger as parameter I would simple call def foo(l: Logger).
But if I have
trait Logger {
  def log(m: Message) = ???
  def receive = {
    case m: Message = log(m)
  }
}

,I must pass an ActorRef to be able to call !/? etc on it. But that completely breaks type safety - def log(ar: ActorRef), and nothing says that it should be an Logger underneath.
So, in the end I'd like to call
class Foo(logger: Logger) {
  def foo(m: Message) = logger ! message
}

A:

Well, yes. That's just how Akka works, because actors can change behavior. See How to restrict actor messages to specific types?.
Solution 1: define a wrapper class like
case class LoggerActor(ar: ActorRef) {
  def log(m: Message) = ar ! m
}

And then use LoggerActor where you want to make sure you have a Logger. Of course, if you want to do it everywhere, you'll probably want to automate creation of these classes somehow.
Solution 2: Use Akka Typed. Note it's experimental. I won't copy the documentation from there.
Solution 3: Use Scalaz actors instead, which were typed from the beginning. See https://github.com/scalaz/scalaz/blob/series/7.3.x/tests/src/test/scala/scalaz/concurrent/ActorTest.scala for usage examples. For your case it could be
val logger = new Logger { ... }
val loggerActor = new Actor[Message](logger.log)


Q:

Tag management 2019

New year, new tag management thread.
Rules of the game are basically the same:

Post your suggestion as an answer here if you see

A particularly bad tag (a rule of thumb: «if I can't imagine a person classifying a tag as either interesting or ignored, I'm getting rid of it»),
A tag that should be a synonym of an existing one,
A tag that used for two or more completely unrelated things,
A need to create a new tag;

Upvote/downvote/comment as your agree/disagree with suggestions, so please post different suggestions in separate answers;
Wait a couple of days before implementing a suggestion.
After the problem described in an answer is resolved, please edit it to say so.
If your tag suggestion exists in a separate question, please provide a link to the question in your suggestion.

See also:

The list with pending and approved synonyms.
The tagging chatroom for extended discussion on tagging.
Last year's thread to look for suggestions that need to be implemented.

Also, note that one may use [tag:calculus] for calculus, i.e. tags on the main site, and [meta-tag:discussion] for discussion, i.e. for tags on the meta site.

A:

Proposal to blacklist generalization
Reason: It's overly broad and there is no real mathematical content in it. Also, the tag has been created and removed several times.

A:

Resolved.  All questions with cohomological-operations have been retagged to cohomology-operations (or neither tag, in a few cases where the tag was inappropriate) and cohomological-operations will be automatically deleted soon

Apparently we have tags cohomology-operations and cohomological-operations, with 10 and 20 questions respectively (including 1 with both), different tag excerpts, and a tag wiki for the first one only. I don't know the topic very well, but the excerpts seem to describe essentially the same context. Should these tags be merged?

A:

Resolved: fixedpoints renamed to fixed-points.

For consistency with other multiple-word tags. Separating words with hyphens increases readability.


Q:

How can I reduce the time that Eclipse PDT needs to startup?

I'm a very patient guy but seems very annoying the long time that Eclipse takes to let me start working.
Why is that? I have a clean PDT distribution download form the Zend site. No extra plugins added.
Is this only happening to me? Does anyone else notice this delay?
Best,
Demian

A:

Run eclipse from the command line with these arguments to assign more memory to it:
eclipse -vmargs -Xms512m -Xmx1g
Note: I assume you have a RAM of 2 or more gigs


Q:

Differences between data/type constructors and functions?

Could anyone explain to me what are the differences between data/type constructors and functions? Haskell mix them and give us a universal interface (all looks like functions, in particular, we can partially apply them), while the ML family languages distinguish them.

A:

Your dichotomy "Haskell vs. the ML world" is wrong¹. SML also promotes constructors to functions, and Caml Light used to. I'm not sure why it was removed in OCaml, I think the designer thought there wasn't a real need for it.
There are deep reasons why constructors are slightly particular. They can be used in patterns, while general functions cannot -- I guess this can be explained in term of polarized logic and focusing². Also, a constructor applied to values can be considered a value, while this is not true for general functions. It is common in call-by-value languages to restrict recursive values definition to a subclass that allows constructor application, but not general function application.
I agree that the "semantic sugar" of promoting all constructors to functions is nice. I think however that this would not be so useful if we had a nice syntactic sugar for short abstraction, such as Scala's Some(_).
Whether constructors should be curryfied (your "partial application" remark) or not is a different and orthogonal question, in my opinion.
¹: besides being a wrong dichotomy, the tone of your question has a certain taste of "Haskellers and MLers, here is the ring, please fight !". It may not be intentional, but anyway you should probably avoid such formulations. Language design is made of compromises, and assuming when two different languages made different choices that one of them is right and not the other is not a good approach.
PS: the question has since been edited and is now much more neutral. Thanks for editing.

²: as requested by petebu, here is a little more (actually a lot more) information on "focusing and polarity". I would like to point out that I'm really not an expert on this topic (hence the "I guess").
I would recommend first the paper Focusing on Pattern Matching (PDF) by Neelakantan Krishnaswami, 2009. It contains an introduction for people not proficient in polarised logic and focusing (but you need to be at least familiar with sequent calculus). As usual in sequent calculus, types/propositions are introduced "on the right" and eliminated/deconstructed "on the left". But here we separate types by "polarity", product and sums being positive and functions negative (my intuition is that product/sums are data while functions are computations, but the separation is motivated by very natural considerations of their behaviour in sequent calculus), and the paper shows that left-elimination of arrow types corresponds to function application, while left-elimination of sum/product types corresponds to pattern matching. There is a case construct that behaves similarly to pattern matching (with some differences), that eliminates positives, so could not be applied to functions.
The other important reference would be Focusing on Binding and Computation, by Dan Licata, Noam Zeilberger and Robert Harper, 2008 (note that if you're planning to submit a paper on these topics, "Focusing on ..." is becoming a bit cliché). It emphasizes much less the link with ML-style pattern matching, but introduces the very nice idea that while computational arrows are "negative on the left" (easily seen as the classical equivalence A→B ≡ ¬A∨B), one may introduce a different arrow, "positive on the left", therefore positively polarized, that can be pattern-matched. It turns out that this arrow is a good match for representing variable bindings (if you're familiar with Higher Order Abstract Syntax, the idea is that the left polarity rules out "exotic terms" that try to compute on their variables), so that terms with variables bindings are data structure that can be pattern-matched like sums or products.
I found their paper a bit hard to read, so I would start with Dan Licata's slides. Finally, Robert Harper has made other slides that provides a different intuition in termes of inductive judgements/derivations : the positive arrows represent derivability (could you build a derivation of C under the hypothesis A and B?) while negative arrows represent admissibility (given derivations of A and B, how would you rewrite/explore/manipulate them to build a derivation of C ?). Very interesting stuff.


Q:

How to make webhooks working with nginx+gunicorn+django+pytelegrambotapi

I'm trying to deploy telegram bot(usign pyTelegramBotApi) on django, using nginx+gunicorn.
I already have fomain and Let's Encrypt cert for it, https is working and django rendered pages are accessible.
But I have no idea, why bot isn't receiving any data.
Am I doing something wrong on deployment step?
Django view to handle webhooks:
def telegram(request):
    if request.method == 'POST':
        json_string = request.POST.get()
        update = telebot.types.Update.de_json(json_string)
        bot.process_new_updates([update])
    return HttpResponse('')

def set_hook(request):
    bot.remove_webhook()
    bot.set_webhook(url='https://<my domain>.tk/bot{}'.format(API_TOKEN))
    return HttpResponse('')

nginx config:
server {
    server_name <my domain>.tk www.<my domain>.tk default_server;
    listen 80;

    return 301 https://<my domain>.tk;
}

server {
    server_name www.<my domain>.tk;
    listen 443 ssl http2;

    ssl_certificate /etc/letsencrypt/live/<my domain>.tk/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/<my domain>.tk/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/<my domain>.tk/chain.pem;

    ssl_stapling on;
    ssl_stapling_verify on;

    add_header Strict-Transport-Security "max-age=31536000";

    return 301 https://<my domain>.tk$request_uri;
}

server {

    server_name <my domain>.tk;
    listen 443 ssl http2;

    ssl_certificate /etc/letsencrypt/live/<my domain>.tk/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/<my domain>.tk/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/<my domain>.tk/chain.pem;

    ssl_stapling on;
    ssl_stapling_verify on;

    add_header Strict-Transport-Security "max-age=31536000";

    add_header X-Frame-Options "SAMEORIGIN";

    location /.well-known {
        root /var/www/html; # Понадобится для letsencrypt
    }

    location = /favicon.ico {
        alias /home/ubuntu/<my domain>/static/favicon.ico;
    }
    location = /robots.txt {
        alias /home/ubuntu/<my domain>/static/robots.txt;
    }

    location /static/ {
        root /home/ubuntu/<my domain>/;
    }
    location /media/ {
        root /home/ubuntu/<my domain>/;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/ubuntu/<my domain>/socket.sock;
    }
}

GUnicorn service conf:
[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=ubuntu
Group=www-data
WorkingDirectory=/home/ubuntu/<my domain>/
ExecStart=/home/ubuntu/<my domain>/venv/bin/gunicorn --access-logfile - --error-logfile error.log --workers 2 --bind unix:/home/ubuntu/<my domain>/socket.sock fri_weekend_bot.wsgi:application

[Install]
WantedBy=multi-user.target

A:

My problem was hiding inside django part.
By default, all django views require CSRF auth.
All I had to do is to place @csrf_exempt decorator on telegram() view to avoid this.
@csrf_exempt
def telegram(request):
    if request.method == 'POST':
        json_string = json.dumps(json.loads(request.body))
        update = telebot.types.Update.de_json(json_string)
        bot.process_new_updates([update])
    return HttpResponse('')


Q:

How to get the row number which satisfies a condition

I have a table in an Excel sheet having three columns. one column contains the person name, 2nd column contain the company name and 3rd column contains the city name.
Name    Company City
abc     mn      C1
asd     th      C2
qwe     mn      C1
aqw     kj      C1
ert     mn      C2

Here I have written a macro in Excel 2007/2010 to get the person's names that are working for company "mn" and are in "C1" city.
Can anybody help me out???

A:

I think just sort the area by Company and then by City is the easiest way to discover the employees. But something like this should work too:
Sub SearchEmployeeByCompanyAndCity(company As String, city As String, start As Range)
    Dim i, j As Integer
    i = 1
    j = 1
    While (start.Cells(i, j).Value <> "")
        If start.Cells(i, j + 1).Value = company And start.Cells(i, j + 2).Value = city Then
            MsgBox start.Cells(i, j)
        End If
        i = i + 1
    Wend
End Sub

Sub Test()
    SearchEmployeeByCompanyAndCity "mn", "C1", Worksheets(1).Range("A1")
End Sub


Q:

Prove that a linear subspace of $C([0,1])$ is closed

Prove that the set
  $$ W= \{f \in C([0, 1]):f(0)=0\}$$
  is a closed linear subspace of $C([0,1]).$

Here $C([0, 1])$ is the space of continuous functions equipped with the uniform norm  $||f||_\infty = \sup_{x\in[0,1]}|f(x)|$.
I need some help in how to proceed  with this problem.
First, I want to prove that $W$ is, indeed, a subset of $C([0,1])$. For this, we have that for any two functions $f,g\in W$, $f+g\in W$, since $f(0) + g(0) = 0$. Then, also for any $\lambda \in \mathbb{R}$, we have that $\lambda f \in W$, since $\lambda f(0) = 0$. Finally, we also have $0 \in W$. So $W$ is a linear subspace of $C([0, 1])$.
My problem is how to prove that $W$ is closed. Based on the definition of a closed set, I wanted to show that a sequence of continuous functions $f_n$ converges uniformly to $f$ and that this $f$ is also in $W$. I started with something like this:
Let $f_n$ be a sequence of continuous functions such that $f_n(0) = 0$ for any $n\in \mathbb{N}$. We need to prove that $f_n \to f$, uniformly. i.e $$ \|f_n - f\|_\infty = \sup_{x\in[0,1]} |f_n(x) - f(x)|\to 0$$ as $n\to \infty$.
How can I proceed?

A:

The linear functional $L(x)=x(0)$ is a continuous linear map from $C[0,1]$ to $\mathbb{C}$ because it is bounded, i.e., $|T(x)|=|x(0)| \le \|x\|$. Therefore the inverse image of $\{0\}$ under $T$ is closed, which is the subspace $W$.


Q:

:iCal Event not added into organizer calendar

I am creating ics file with 2 attendee and a organizer.
Event is properly creating for both attendees and response is also received when they accept/reject the event. I am sending same invite to organizer as well. On organizer end, event is not adding into their calendar (accept/reject buttons are grayed out). Following two messages are showing:

At the meeting organizer, you do not need to respond to the meeting.
Meeting cannot be found in the Calendar.

How I can change the event so that it also create in organizer calendar?
BEGIN:VCALENDAR
PRODID:-//Appointment Confirmation Event//EN
VERSION:2.0
CALSCALE:GREGORIAN
METHOD:REQUEST
BEGIN:VEVENT
DTSTART:20200506T190000Z
DTEND:20200506T200000Z
DTSTAMP:20200506T190000Z
ORGANIZER:mailto:test1@test.com
UID:Interview_47461@sterlinghoffman.com
ATTENDEE;PARTSTAT=NEEDS-ACTION;ROLE=REQ_PARTICIPANT;RSVP=TRUE:mailto:test2@test.com
ATTENDEE;PARTSTAT=NEEDS-ACTION;ROLE=REQ_PARTICIPANT;RSVP=TRUE:mailto:test3@test.com
X-MICROSOFT-CDO-OWNERAPPTID:-486846808
CREATED:20200504T130737Z
DESCRIPTION:
LOCATION:at 3423
SEQUENCE:0
SUMMARY:Phone Meeting
TRANSP:OPAQUE
END:VEVENT
END:VCALENDAR

I tried with adding organizer as attendee but it not works.
ATTENDEE;PARTSTAT=ACCEPTED;ROLE=CHAIR;RSVP=TRUE;mailto:test1@test.com

A:

Since it sounds like the ics file is not being generated by the organisers outlook calendar, then two possible solutions suggest themselves:
1) On the assumption that it would be redundant / duplication to add an event to organisers calendar (who would be assumed by the application to have already created the event in itself) possibly the more robust solution for across calendar applications: add a sent-by, as per https://icalendar.org/iCalendar-RFC-5545/3-8-4-3-organizer.html
ORGANIZER;SENT-BY="mailto:jane_doe@example.com":
  mailto:jsmith@example.com

2) This might be an outlook bug.  A quick search come up with same error messages https://developermessaging.azurewebsites.net/2011/09/30/accepting-ical-appts-in-outlook-when-you-are-the-organiser/ and indicates a hotfix. See also How can I add an ICS meeting automatically to the Organizer's calendar?
See also:
iCalendar does not create an event for organizer
ics not updating organizer calendar,
Sending iCalendar to an user who's also the organizer of the event (the last comment to answer about redundancy to add to organiser


Q:

Best method to put url in href for SEO

if possible, I would like to know what is the best practies for SEO to put url in
Method 1:

Method 2:

Can you help me?

A:

Bots can interpret relative as well as absolute URLs and follow them.
I would prefer absolute URLs as we can govern what the urls are, rather than leaving it to bot to find out and follow through them. It also provides the flexibility of switching the protocols from http to https:// even though the page is non secure or vice versa. Hope this helps.


Q:

How to obtain namespace of a custom lang in Racket?

I'm implementing a custom language in Racket in which I would like to provide an eval procedure bound to the namespace of this custom language.
my-lang.rkt:
#lang racket

(provide #%module-begin #%top #%datum #%app)
(provide quote)
(provide (rename-out [a b] [my-eval eval]))

(define-namespace-anchor anchor)
(define ns (namespace-anchor->namespace anchor)) ; wrong namespace

(define (my-eval x) (eval x ns))

(define a 1)

test.rkt:
#lang s-exp "my-lang.rkt"

(eval 'a)
(eval 'b)

As implemented, since ns is the namespace of my-lang.rkt, (eval 'a) evaluates to 1 while (eval 'b) fails.
I would like ns to be bound to the namespace of test.rkt so that (eval 'a) fails and (eval 'b) returns 1.
How should I define ns?

A:

Here's a way using parameter and macro. There might be a better way:
;; my-lang.rkt
#lang racket

(provide #%top #%datum #%app (rename-out [@#%module-begin #%module-begin])
         quote
         (rename-out [a b] [my-eval eval]))

(require syntax/parse/define
         racket/splicing)

(define current-ns (make-parameter #f))

(define-syntax-parser @#%module-begin
  [(_ . xs)
   #'(#%module-begin
      (define-namespace-anchor anchor)
      (splicing-parameterize ([current-ns (namespace-anchor->namespace anchor)])
        . xs))])

(define (my-eval x) (eval x (current-ns)))

(define a 1)

;; test.rkt
#lang s-exp "my-lang.rkt"

(eval 'b) ;=> 1
(eval 'a)
;; a: undefined;
;; cannot reference an identifier before its definition


Q:

Weird behavior of NERDTreeFind function

I have keymap in my init.vim file
nmap <silent> <leader>y :call NERDTreeFind()<cr>

It opens a default file in the NERDTree window from vim's command line by typing :NERDTreeFind as it expected.
But when I'm pressing the shortcut <leader>y I got this message:
E117: Unknown function: NERDTreeFind

What might be a problem here?
I'm using neovim under OSX.

A:

Judging by the documentation, NERDTreeFind is a command, not a function. This means you do not need :call.
nnoremap <silent> <leader>y :NERDTreeFind<cr>


Q:

Hyperlink not working on popup

I have a website Here.
There's a pop up window that appears as soon as the page is loaded. However, I'm unable to utilize links in the HTML content.
Here's the HTML...

Updates to the AR Toolbox

• Check out the new rotating Announcement Board on the AR Toolbox!

• Have you seen the new SUO Tour yet? Click here to check it out!

• South University and The Education Foundation Scholarship Committee are now on SharePoint. Click  here!

When you look at the popup, you'll see all my links are grouped in the upper right corner of the popup window, with the 'X'.
Here's the CSS for the Popup...
#blanket {
   background-color:#111;
   opacity: 0.65;
   filter: alpha(opacity=65)
   *background:none;
   position:absolute;
   z-index: 9001;
   top:0px;
   left:0px;
   width:100%;
}

#popUpDiv {
    position:absolute;
    background-color: #fff;
    background-image:url(../images/popup_bg.png);
    background-repeat:no-repeat;
    width:400px;
    height:400px;
    border:5px solid #000;
    z-index: 9002;
}

#popUpDiv a {
    background-image: url(../images/x.png);
    background-repeat: no-repeat;
    position:absolute; top:10px; right:10px}

I think it lies in the '#popUpDiv a' section, but I'm not sure how to fix it.
Any ideas?
Edit: Here is the jsfiddle
On the 2nd bullet, you'll see "Click to check it out!" when it should be "Click here to check it out!"
On the 3rd bullet, you'll see "Click", when it should be "Click here."
But, again, all the the links are bundled up in the top right-hand corner for some reason.

A:

Instead of applying the style to a, just create a style class and apply that to the popUpDiv. Like this...
#popUpDiv .close {
    background-image: url(../images/x.png);
    background-repeat: no-repeat;
    position:absolute;
    top:10px;
    right:10px
}

and apply it to the popup href...

jsFiddle DEMO here
Hope this helps!


Q:

Implementing a view controller that can handle two different view types

Sorry if the title sounds confusing, but I couldn't come up with anything better.
Basically I have a view controller that manages a paging scroll view which displays several images fetched from a database. I'm new to MVC, and I've tried to write my code following this pattern in the best way I could (my experience is merely based on looking at other people's code and understanding how Apple's classes work, so it may be flawed; I'd be grateful if you could tell me if it is).
This is what I've done: I have a custom view class which contains an UIScrollView, and has two public properties: dataSource and delegate. The data source object has to conform to a protocol I've defined; it returns the number of images and the images themselves. The delegate gets notified when the selected page changes.
I hope I got it right. In any case it works; I'm able to re-implement the data source without any problem (if I need to), and the code that provides the data is separated from the code that displays it.
But now I have a problem: I need to be able to replace the paging scroll view with a CoverFlow-like view duplicating as little code as possible. I know there must be a better way to accomplish this, without having to create another view controller class using this CoverFlow view. The two view classes have similar methods and work in similar ways, so it would make sense to use the same view controller code, instead of duplicating it.
Perhaps I could write an abstract class with generic methods and write two implementations of it, one for the scroll view and one for the CoverFlow view, and then instantiate one of the two in the controller, based on a parameter passed to it. Is this the best way to achieve this?
I hope this is not too confusing and that my approach isn't too much flawed. Thanks.

A:

You generally want separate view controllers for separate views because you end up having to check which type of view you are using in every single methods. Then special cases creep in and your code becomes a mess. Besides, you might decide to ditch one view entirely at some point. The more modular the code the better.
The key idea of the Model-View-Controller design is that the views are logically separated from the data model. The model should be the actual core of the program and it should provide data for all the views via the controllers. If you have properly implemented the design, you will not have much customization and little duplication of code because the model will support every possible view with alternation.
In most apps, it is the controllers that are the most customized and you should not spend much effort attempting to prevent duplication. If you find yourself duplicated code between controllers, chances are you have either model or view logic in the controller that shouldn't be there.
In your case, it looks like the datasource object interfaces with your model (like a UITableViewDataSource object does) and since both views use the same logic you can use the same delegate for both views if you define the appropriate protocol. Each view will need a custom delegate to handle customization but that is part of the Delegate design pattern which you should employ.


Q:

When to delete allocated memory of returned value

When I delete the memory of b for the given function "lowerCaseWord(char* a)"? I need to return the value of b, so I can't delete it before the line "return b;". Do I need to use another variable? Or does the compiler delete it alone(even though its not good programming)?
char* lowerCaseWord(char* a)
{
    char *b=new char[strlen(a)];
    for (int i = 0; i < strlen(a); i++)
    {
        b[i] = tolower(a[i]);
    }
    return b;

}

A:

You need to delete[] it outside the function by yourself, even though it's not a good practice. Such as:
char* rtv = lowerCaseWord(a);
// process with rtv
// ...
delete[] rtv;

It's better to use smart pointer to avoid manual memory management, such as:
std::unique_ptr<char[]> lowerCaseWord(char* a)
{
    ...
}

then
std::unique_ptr<char[]> rtv = lowerCaseWord(a);
// process with rtv
// ...

As @FrerichRaabe pointed, basically using raw pointer is not a good idea, you may want to use std::string directly.


Q:

Regular expression "AND OR" for [left | right] || [top | bottom]

I am trying to write a regex that will match the following YACC expression:
[left | right] || [top | bottom]:
It should match: (left or right) AND OR (top or bottom). OR '|' is simple to do but '||' I can't figure it out.
This expression is part of a CSS gradient grammar defined by W3C:
<linear-gradient> = linear-gradient(
    [ [ <angle> | to <side-or-corner> ] ,]?
    <color-stop>[, <color-stop>]+
)

<side-or-corner> = [left | right] || [top | bottom]

Edit:
Giving: left top
Matched: left top
Giving: left
Matched: left
Giving: right bottom
Matched: right bottom
Giving: right 20px
Matched: right
Hope this explains it better.
Thank you

A:

If I understood correctly, you want either a side (left/right/top/bottom) or a corner (top-left,bottom-right...).
This can be solved as something like :
/^((left|right|top|bottom)|((top|bottom)delimiter(left|right)))$/

you can, of course, reverse the order of the sides for corner notation (to output corners as left-top and not top-left)  :
/^((left|right|top|bottom)|((left|right)delimiter(top|bottom)))$/

Note that delimiter is your desired delimiter (can be an empty space or a minus sign).
Hope this helps!
P.S. : I heard your call for help on twitter :P.
update
based on your edit, I think now I understand what you need :
/^((left|right|top|bottom)|((left|right|(-?\d*(\.\d+)?(px|em|\%)))\s+(top|bottom|(-?\d*(\.\d+)?(px|em|\%)))))$/

This regex now matches a side (left/top/right/bottom) or two sides defined by left & top values, which can be either the direction keywords (left/top/right/bottom) or an actual value (such as 100px or 1.4em).
The value regex (-?\d*(\.\d+)?(px|em|\%)) matches any floating number (even without the first zero : .123 instead of 0.123) followed by a unit of measurement (here you can supply a full list of units)
Here's some of my (javascript) test which passed:
var pattern = /^((left|right|top|bottom)|((left|right|(-?\d*(\.\d+)?(px|em|\%)))\s+(top|bottom|(-?\d*(\.\d+)?(px|em|\%)))))$/;
pattern.test('left bottom');   // true
pattern.test('-10px top');     // true
pattern.test('-.23em 140%');   // true

final update

removed the start & end characters
switched the order of the side and corner patterns, prioritizing the corner pattern to match first

/(((left|right|(-?\d*(\.\d+)?(px|em|\%)))\s+(top|bottom|(-?\d*(\.\d+)?(px|em|\%))))|(left|right|top|bottom))/


Q:

PHP - Same post is showing instead of the next post

        <?php
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        $args = array(
            'post_type' => 'post',
            'posts_per_page' => 7,
            'paged' => $paged );
        $wp_query = new WP_Query($args);
        $count = 0;

        while ( have_posts() ) : the_post(); ?>
            <?php echo get_the_title(); ?>
            <?php
                $count++;
                if ($count === 1) { ?>

<?php echo get_the_title(); ?>

                                <?php $content = get_the_content(); echo mb_strimwidth($content, 0, 200, '...');?>

            <?php }
                while ($count <= 2) {
                    $count++ ?>

<?php echo get_the_title(); ?>

                                <?php $content = get_the_content(); echo mb_strimwidth($content, 0, 200, '...');?>

            <?php }
                while ($count <= 4) {
                    $count++ ?>

<?php echo get_the_title(); ?>

                                <?php $content = get_the_content(); echo mb_strimwidth($content, 0, 200, '...');?>

            <?php }
            ?>
        <?php endwhile; ?>

        <?php next_posts_link( '← Older posts', $wp_query ->max_num_pages); ?>
        <?php previous_posts_link( 'Newer posts →' ); ?>

I'm struggling to understand why the if and while statements are looping the same post but directly after this line:
while ( have_posts()) : the_post();

Where I am echoing the title this shows the list of posts instead.
What I am trying to achieve here is create a different html layout for each post that is outputted in the loop.
Cheers

A:

I think you are trying to loop over your query result as shown in the WP_Query official documentation.
Also, not sure why you would do while loops like you were inside the main post loop itself so I changed those to if statements.
Something like this is what I believe you are after:
<?php
        $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
        $args = array(
            'post_type' => 'post',
            'posts_per_page' => 7,
            'paged' => $paged );
        $wp_query = new WP_Query($args);
        $count = 0;

        if(! $wp_query->have_posts())
            die('no posts!'); // ADDED - Handle this more elegantly

        while ( $wp_query->have_posts() ) : $wp_query->the_post(); // ADDED - Use query result object?>
            <?php echo get_the_title(); ?>
            <?php
                $count++;
                if ($count === 1) { ?>

<?php echo get_the_title(); ?>

                                <?php $content = get_the_content(); echo mb_strimwidth($content, 0, 200, '...');?>

            <?php }
                if ($count <= 2) {
                    ?>

<?php echo get_the_title(); ?>

                                <?php $content = get_the_content(); echo mb_strimwidth($content, 0, 200, '...');?>

            <?php }
                if  ($count <= 4) { // ADDED - Be careful, this will fire as well as the if statement above it since they are both <= 2
                    ?>

<?php echo get_the_title(); ?>

                                <?php $content = get_the_content(); echo mb_strimwidth($content, 0, 200, '...');?>

            <?php }
            ?>
        <?php endwhile; ?>

        <?php next_posts_link( '← Older posts', $wp_query ->max_num_pages); ?>
        <?php previous_posts_link( 'Newer posts →' ); ?>


Q:

XML Schema defining only attribute datatypes and all node values as string

Is it possible to define a XML Schema which only defines attribute datatypes and all node values as string?
I am dealing with a very large XML file which has the following structure:
<A>
    <A_x1 label="xyz" id="1234">string data</A_x1>
    <A_x2 label="xzy" id="1235">string data</A_x2>
    <A_x...>string data</A_x...>
    ...
</A>
<B>
    <B_x1 label="yzx" id="1236">string data</B_x1>
    <B_x2 label="zyx" id="1237">string data</B_x2>
    <B_x...>string data</B_x...>
    ...
</B>
<C>
    ...
</C>
...

The number of subnodes of A, or B, or ... is variable!
And sometimes there is a node A_x1 and sometimes there is not.
All i know for sure is every leave node has two attributes, where 'label' is of datatype string and 'id' is of datatype int.
I think this can be defined by :
<?xml version="1.0" encoding="UTF-8"?>
<xs:schema attributeFormDefault="unqualified" elementFormDefault="qualified" xmlns:xs="http://www.w3.org/2001/XMLSchema">
  <xs:attribute name="label" type="xs:string"/>
  <xs:attribute name="id"    type="xs:short"/>
</xs:schema>

But how do i define a schema which states every node named "A_x..." or "B_x..." or ... holds data of type string?
Or every leave node holds data of type string.
I could not find a way to use regular expressions for node names in an XML schema, is this even possible?
Or what is the solution to this problem? If there is one.

A:

Unfortunately, even in XSD 1.1, the only way to allow elements that have any name is to permit them with an xs:any wildcard, and xs:any does not allow you to constrain the types of the elements that it matches.
You could define all the constraints with XSD 1.1 assertions:
every $e in child::* satisfies if exists($e/@id) then $e/@id castable as xs:short
but frankly, if you're doing this, then you're getting so little value out of XSD that you might as well use a different technology for your validation, e.g.  XSLT or schematron.
Another possibility (often overlooked) is to validate using a pipeline that first transforms (using XSLT), and then validates (using XSD). In this case the transformation part would convert all the element names A_x1 into standard element name AA say.
A third possibility is to generate a schema for your specific instance document (again using XSLT) and then validate against that schema. In this case your generated schema could define all the A_x1 elements as members of the substitution group of some abstract element AA, and these elements would therefore be validated against the type defined for AA.


Q:

too many conditions

I have this piece of code I developed but it doesn't look efficient to me, can anyone improve it please.
 private void AddToDataBase(SPItemEventProperties properties)
    {
        DataAccess DA = new DataAccess(ConnectionString());

        DetailsRow result = DA.GetDetails(properties.WebUrl);

        if (result != null && string.IsNullOrEmpty(result.URL))
        {
            DA.DeleteDetails(properties.WebUrl);
        }

        if (bool.Parse(properties.ListItem.Properties["Regular Customer"].ToString()) == true)
        {
            DA.InsertDetails(properties.Name, properties.WebUrl, DateTime.Now);
        }
        else
        {
            if (NumberOfInvoices(properties) > 0)
            {
                DA.InsertDetails(properties.Name, properties.WebUrl, DateTime.Now);
            }

            else
            {
                DeleteInvoiceDocument(properties);
            }
        }
    }

A:

Since I don't have the SharePoint libraries I wasn't able to test my solution, but it should work.

Use proper indentation and formatting.
== true is redundant and can be removed.
Instead of the following:
bool.Parse(properties.ListItem.Properties["Regular Customer"].ToString())

just convert to bool (casting won't work because of SharePoint):
Convert.ToBoolean(properties.ListItem.Properties["Regular Customer"])

Reduce nesting by using else if instead of else { if (...) }
Use || instead of two seperate conditions with the same associated code to avoid redundancy.

Result of refactoring
private void AddToDataBase(SPItemEventProperties properties)
{
    DataAccess dataAccess = new DataAccess(ConnectionString());
    DetailsRow result = dataAccess.GetDetails(properties.WebUrl);
    bool isRegular = Convert.ToBoolean(properties.ListItem.Properties["Regular Customer"])

    if (result != null && string.IsNullOrEmpty(result.URL))
    {
        dataAccess.DeleteDetails(properties.WebUrl);
    }

    if (isRegular || NumberOfInvoices(properties) > 0)
    {
        dataAccess.InsertDetails(properties.Name, properties.WebUrl, DateTime.Now);
    }
    else
    {
        DeleteInvoiceDocument(properties);
    }
}


Q:

What are named pipes?

What are they and how do they work?
Context happens to be SQL Server

A:

Both on Windows and POSIX systems, named-pipes provide a way for inter-process communication to occur among processes running on the same machine.  What named pipes give you is a way to send your data without having the performance penalty of involving the network stack.
Just like you have a server listening to a IP address/port for incoming requests, a server can also set up a named pipe which can listen for requests.  In either cases, the client process (or the DB access library) must know the specific address (or pipe name) to send the request.   Often, a commonly used standard default exists (much like port 80 for HTTP, SQL server uses port 1433 in TCP/IP; \\.\pipe\sql\query for a named pipe).
By setting up additional named pipes, you can have multiple DB servers running, each with its own request listeners.
The advantage of named pipes is that it  is usually much faster, and frees up network stack resources.
--
BTW, in the Windows world, you can also have named pipes to remote machines -- but in that case, the named pipe is transported over TCP/IP, so you will lose performance.   Use named pipes for local machine communication.

A:

Unix and Windows both have things called "Named pipes", but they behave differently. On Unix, a named pipe is a one-way street which typically has just one reader and one writer - the writer writes, and the reader reads, you get it?
On Windows, the thing called a "Named pipe" is an IPC object more like a TCP socket - things can flow both ways and there is some metadata (You can obtain the credentials of the thing on the other end etc).
Unix named pipes appear as a special file in the filesystem and can be accessed with normal file IO commands including the shell. Windows ones don't, and need to be opened with a special system call (after which they behave mostly like a normal win32 handle).
Even more confusing, Unix has something called a "Unix socket" or AF_UNIX socket, which works more like (but not completely like) a win32 "named pipe", being bidirectional.

A:

Linux Pipes
First In First Out (FIFO) interproccess communication mechanism.
Unnamed Pipes
On the command line, represented by a "|" between two commands.
Named Pipes
A FIFO special file. Once created, you can use the pipe just like a normal file(open, close, write, read, etc).
To create a named pipe, called "myPipe", from the command line (man page):
mkfifo myPipe

To create a named pipe from c, where "pathname" is the name you would like the pipe to have and "mode" contains the permissions you want the pipe to have (man page):
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);


Q:

Imprimir todos os 0

Eu declarei a seguinte variável:
int sequencia = 000000000;

Na hora de imprimir, está imprimindo apenas um 0.
Alguém sabe como faço pra imprimir todos os 0 (zeros) ?
Como faço um auto-incremento a ponto que a cada volta (for) o valor altere para: 000000001,000000002 até chegar 999999999 ?

A:

for (int i = 0; i <= 999999999; i++) {
    System.out.println(String.format("%09d", i));
}

Veja o exemplo acima funcionando no IDEONE


Q:

C# How to pass in number as float to functions ?

I created a validation function as below:
public static T getAsDigit<T>( this Textbox tb, float min, float max  ){
}

Most of the time, the validation range is specificed in integers. It works fine. But when I try to pass in decimals, it give me error sth like can't convert double to float, I have to change defination to double.
I am new to C#, how can I pass in the digits as float ? without doing sth unintuitive like Convert.toFloat('1.3').
My use case only requires 3 decimal place precision, value range 0.000 ~ 10.000. Is there any disadvantage in using float versus double in C#? Since I used and saw people use float a lot in sql when decimal() is optional.

A:

Use f literal: getAsDigit(1.34f)
Or cast value to float getAsDigit((float)1.34)