Q:

RTFString Containing NSASCIIStringEncoding Special Characters?

I have a string in my cocoa GUI that needs to have special formatting (fonts, colors, etc.). Naturally, I'm using an attributed string. For convenience, I Init the string as an RTF:
NSString *inputString = @"This string has special characters";
NSString *rtfString = [NSString stringWithFormat:@"{@"***LENGTHY RTF FORMATTING STRING *** %@", inputString];
NSAttributedString *testString = [[NSAttributedString alloc] initWithRTF:[rtfString dataUsingEncoding:NSUTF8StringEncoding] documentAttributes:nil];

The problem is, the "inputString" might have special characters, which are not displayed properly due to the UTF8Encoding. They're replaced with other symbols.
é is left as Å©.
So, right now I'm doing this:
NSData* intermediateDataString=[inputString dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

inputString = [[[NSString alloc] initWithData:intermediateDataString encoding:NSUTF8StringEncoding] autorelease];

This does not display the unexpected characters, but it does remove all accents and leaves in their stead the unaccented letter - é is left as e.
This is an improvement since everything can be read, but it is far from ideal.
Thoughts?

A:

I would do something like this. First, create a dummy attributed string:
NSString *dummyRTFString = @"***LENGTHY RTF FORMATTING STRING *** A";
NSAttributedString *dummyAS = [[NSAttributedString alloc]
                                      initWithRTF:[rtfString dataUsingEncoding:NSUTF8StringEncoding]
                               documentAttributes:nil];

and obtain the attributes:
NSDictionary*attributes=[dummyAS attributesAtIndex:0 effectiveRange:NULL];
[dummyAS release];

Now I will use this attribute to create another attributed string:
NSAttributedString* as=[[NSAttributedString alloc] initWithString:inputString attributes:attributes];

Another approach is to use HTML instead of RTF; then you can include non-ascii characters as unicode in it.


Q:

How to get Name of Authenticated user in ASP.NET Core application using Azure Active Directory

In a ASP.NET Core application with Azure AD Connected and Configured. I am able to get the NameIdentifier using this code:
var user = User.FindFirst(ClaimTypes.NameIdentifier).Value; ✔

When trying to get just a name with the following line of code:
var user = User.FindFirst(ClaimTypes.Name).Value; ❌

I receive the following error:

Object reference not set to an instance of an object.

Looked up in Azure Active Directory the user does have a full first and last name. Tried many examples online, it looks like the name should be showing.
UPDATE:
Finally figured it out, at first I managed to get all the human readable text like this:
foreach (Claim item in User.Claims)
{
    if (item.Type.Contains("name"))
    {
      var username = item.Value;
    }
}

this is much better
var userName = User.FindFirst("name").Value;

A:

According to document : https://docs.microsoft.com/en-us/azure/architecture/multitenant-identity/claims :

In ASP.NET Core, the OpenID Connect middleware converts some of the claim types when it populates the Claims collection for the user principal:

oid > http://schemas.microsoft.com/identity/claims/objectidentifier
tid > http://schemas.microsoft.com/identity/claims/tenantid
unique_name >
  http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name
upn > http://schemas.xmlsoap.org/ws/2005/05/identity/claims/upn

So that if the unique_name exists in ID token , the middleware will  populate the value of ClaimTypes.Name . But according to document : Microsoft identity platform ID tokens:

unique_name     :  Provides a human readable value that identifies the subject of the token. This value isn't guaranteed to be unique within a tenant and should be used only for display purposes. Only issued in v1.0 id_tokens.

So that the claim only issued in Azure AD V1.0 id tokens ,and it isn't guaranteed to be unique within a tenant .
You can get the user's name and email by (The profile scope is required to receive the claims & test with Azure AD V2.0 app):
var userName = User.FindFirst("name").Value;
var Email = User.FindFirst("preferred_username").Value;

If you want to know the first name and last name of current user , you may acquire access token for Microsoft Graph , call user endpoint with token and check the givenName/surname values from response :
https://docs.microsoft.com/en-us/graph/api/user-get?view=graph-rest-1.0&tabs=http


Q:

shiny: passing reactiveValues to conditionalPanel

Can I pass a reactiveValues to a conditionalPanel's condition? If so, how?
Here is what I have tried in the conditionalPanel ui.R:
conditionalPanel(condition = "values.cond == 0", etc.

where I have defined values$cond in server.R:
values <- reactiveValues(cond = 0)

I have also tried alternatives like "values.cond == true", without success.
library("shiny")
runGist("https://gist.github.com/anonymous/8281021")

See the code:
https://gist.github.com/anonymous/8281021

A:

As @jdharrison pointed out, you have the problem, that you have reactive values or any other data on the server side and the conditional panel is a JS condition + some HTML on the client side. Hence, if you want to dynamically update the JS condition according to some value you calculated on the server side, you need to get the data from the server to the client. I think what you could do is use an still undocumented feature of shiny to pass custom data from the server to the client. I wrote a blog post on how to do that: http://ryouready.wordpress.com/2013/11/20/sending-data-from-client-to-server-and-back-using-shiny/
I guess you could use that approach to dynamically update the JS panel condition. You would need to write a JS function that does this after the data has been passed. So this boils down to replacing the data-display-if attribute of the conditionalPanel output with the values you want.
Another idea: If your UI strongly depends on calculations on the server side you may want to consider creating the (sidebar) content dynamically using renderUI.
EDIT: Btw, that's what @jdharrison referred to in his second comment.

A:

You can also do it by rendering text. UI:
shinyUI(
  fluidPage(
    # Application title
    titlePanel("Test"),

    sidebarLayout(
      sidebarPanel(
        actionButton("ShowCond", "Show Conditional Panel"),
        conditionalPanel(
          condition = "output.test=='5'",
          actionButton("CheckFile", "Check file")
        )
      ),
      mainPanel(
        verbatimTextOutput("test")
      )
    )
  )
)

Server:
shinyServer(function(input, output, session) {
  var <- eventReactive(input$ShowCond, {
    5
  })

  output$test <- renderText({
    var()
  })
})

The catch is here that it doesn't work without the verbatimTextOutput. You need to include it somewhere on your UI side. However, you could reuse it as a message.
EDIT:
It is also possible without the verbatimtext. By default Shiny suspends all output when they are not displayed. However, this can be changed by setting the following option for a specific output variable:
outputOptions(output, "test", suspendWhenHidden=FALSE)

In this case, there is nor more need to use verbatimtext (and the corresponding rendertext).
Source: https://shinydata.wordpress.com/2015/02/02/a-few-things-i-learned-about-shiny-and-reactive-programming/#use-of-isolate-to-prevent-accidental-dependencies


Q:

Creating encrypted build parameter in TeamCity 8.0 from REST API

I'm trying to write a PowerShell script that creates a parameter in a TeamCity build configuration, this is simple to do with the REST API.
Just set up an authenticated webclient and make a PUT request to the parameters of the build config:
$webclient.UploadString("http://Server:8111/httpAuth/app/rest/buildTypes/buildID/parameters/Password, "PUT", "PasswordString")

But this parameter contains a password and needs to be stored as a Password type in Team City.
I know I can change the type of the parameter manually from TeamCity's UI but is there a way to automate this with the REST API (otherwise I'll be doing this manually for over 100 build configs)

A:

Jetbrains got back to me about this issue and explained that this type of functionality is not available until the release of 8.1
As an alternative, there is a way of defining the parameter in the build's parent project, the parameter is then inherited to all builds under that project.
It's perfect for my situation as the password can be stored in the root project and inherited automatically across all builds.


Q:

What is `git checkout --orphan` used for?

I've just discovered git checkout --orphan, but I don't know how to use it. Its help page says it creates a new unparented branch.
In the master branch, I've tried git checkout --orphan br, only to see the files in the working directory change to “Changes to be committed”, and the git log saying fatal: bad default revision 'HEAD'.
So what's the advantage of using  git checkout --orphan?

A:

The core use for git checkout --orphan is to create a branch in a git init-like state on a non-new repository.
Without this ability, all of your git branches would have a common ancestor, your initial commit.  This is a common case, but in no way the only one.  For example, git allows you to track multiple independent projects as different branches in a single repository.
That's why your files are being reported as “changes to be committed”: in a git init state, the first commit isn't created yet, so all files are new to git.

A:

It's used by e.g. GitHub Pages, which stores a repo's website inside the repo but on a separate branch. There's no reason to store anything but the website's history on this branch.


Q:

Can javascript open a secondary window before the full document is loaded?

I am writing a CGI application which sometimes takes up to one minute to run, but not always.  In the cases I am able to predict the delay, I would like to open another window warning the user of the expected delay.  My first attempt was to have my CGI script add the line
    window.onload = function(){window.open('<URL FOR WINDOW WARNING OF DELAY>')}

to the javascript code embedded into the html document.  However the warning window is only opened when the html document is fully loaded, which unfortunately only happens after my slow process has finished running.  In other words, too late!
Is it possible to force Javascript to open a secondary window immediately, namely before the current html document is read in full?

A:

Yes you can, it's waiting because you're putting it in the window.onload handler, which, well... waits for the entire window (and its resources) to finish loading.
However, even if you do wait for the onload handler, the popup will be blocked by popup blockers. The only safe way to open a window is within a click event handler.
The better way would be to put some HTML immediately following the open  tag and remove it from window.onload

window.onload = function() {
    document.body.removeChild(document.getElementById('loader'));
}
#loader {
  text-align: center;
  position: absolute;
  top: 20px;
  left: 50px;
  width: 500px;
  height: 200px;
  padding-top: 120px;
  border: 2px solid firebrick;
  background-color: white;
  box-shadow: 0 0 5px 5px #eee;
}

 Please wait while page loads

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris eu convallis leo, a condimentum erat. Integer non blandit ligula, sed pretium ante. Cras convallis consequat lorem, tincidunt vehicula sapien dignissim ut. Fusce lacinia neque eu tortor gravida, a ornare eros mollis. Donec fringilla enim ut auctor iaculis. Fusce sed ipsum iaculis, pretium nunc aliquet, tempor ipsum. Ut ac purus sed massa finibus sollicitudin. Ut finibus sem vitae nibh interdum, et maximus mauris pretium. Sed imperdiet nulla non consequat ultrices. Praesent feugiat velit id lacinia faucibus. Aenean iaculis mi ac cursus tempus. Fusce interdum enim et leo hendrerit sollicitudin. Ut feugiat a tellus ac tincidunt. Integer eget convallis sem. Nullam eget dolor id augue volutpat efficitur. Nam at tortor nec purus cursus ullamcorper at sit amet mauris. Sed tristique, turpis ut commodo dictum, leo est bibendum enim, et convallis nunc nibh nec massa. Ut tempor ipsum sapien, ut aliquam libero volutpat et. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Nunc libero diam, porta a mattis eget, aliquet non urna. Nullam ex nisi, elementum tristique luctus eu, pharetra at leo. Nulla ac vestibulum nisl. Duis facilisis placerat augue non ornare. Proin tempor ultricies semper. Praesent odio dui, maximus nec erat sit amet, efficitur vestibulum metus. Phasellus in diam consequat, rhoncus quam nec, faucibus purus. Nulla nec scelerisque neque. Pellentesque pretium, dolor vel porta egestas, metus ex ullamcorper turpis, ac maximus est ipsum luctus nulla. Integer lobortis sapien id eros gravida maximus. Suspendisse potenti. Morbi ac volutpat elit, in pulvinar mauris. Aliquam enim est, lacinia id lacus vitae, interdum varius ex. Cras urna tortor, tristique sed nibh ac, vehicula ornare magna. Donec vel semper nisi, imperdiet aliquet diam.  Nullam eget pretium ipsum. Morbi semper at eros ac ornare. Quisque id enim sit amet magna imperdiet tristique ut eget quam. In egestas condimentum nisi vel consectetur. Nunc auctor tellus sed mi malesuada, sed iaculis nisi feugiat. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Phasellus dictum scelerisque elementum. Nam convallis, risus ac dapibus iaculis, arcu neque pulvinar sapien, sit amet auctor nisi felis quis nunc. Proin mattis metus sed mauris imperdiet, et dictum diam vestibulum. Vivamus ac mattis tortor. Phasellus felis lorem, posuere a magna non, tempus dignissim lacus. Nulla vitae euismod turpis. Mauris a nunc quis ligula placerat pulvinar. Donec et quam vitae orci sodales vulputate at ac risus. Quisque eleifend augue in elit dignissim, et aliquet dui ultricies. Duis eget auctor nunc, ac facilisis velit. Mauris lacus nibh, finibus a blandit sed, hendrerit nec turpis. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Proin nulla enim, tempor eu augue a, fringilla feugiat arcu. Proin molestie ex sit amet purus laoreet maximus quis in leo. Ut rhoncus metus nisi. Morbi in ipsum vitae erat sodales bibendum. Praesent vitae rhoncus odio. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In convallis tristique odio. Ut sit amet lorem sed enim tristique tincidunt. Nunc quis dictum tortor.    Vestibulum maximus dui malesuada, bibendum mi sed, finibus nunc. Aliquam erat volutpat. Sed semper risus nisi, non lobortis quam luctus a. Curabitur posuere felis eget erat aliquet imperdiet. Vestibulum mollis feugiat sapien quis ultrices. Vivamus quis ipsum eget nibh vehicula interdum sed nec justo. Pellentesque sagittis, lacus ac malesuada elementum, neque risus eleifend quam, at sollicitudin erat libero ac turpis. Vivamus eu lorem ut sapien fringilla facilisis. Mauris facilisis venenatis ex, nec dapibus ligula fringilla quis. Quisque tempus vehicula ante. Sed vel finibus arcu.  Proin in leo at neque pulvinar tincidunt. Morbi efficitur diam nec vulputate interdum. Nunc dapibus felis sollicitudin quam imperdiet sollicitudin. Maecenas eu lacus in sem tempus iaculis. Duis placerat semper nibh, nec malesuada nunc ullamcorper ac. Vestibulum consectetur elit felis, non hendrerit dolor ornare aliquam. Praesent at pretium erat. Duis id velit et velit rutrum efficitur eu ut enim. Phasellus eget molestie nisl, sit amet vulputate turpis. Maecenas id ullamcorper sem.   Aliquam ac quam quis purus pellentesque faucibus ac at tellus. Cras sollicitudin vulputate metus, nec tempus tortor. Donec in venenatis nibh. Vivamus maximus sem leo, nec aliquet quam bibendum in. Curabitur luctus, lectus in tempus pretium, nunc lorem lobortis metus, a mattis lectus odio id ante. Proin viverra sapien id felis vehicula, non condimentum ipsum pulvinar. Fusce vitae nisl dui. Nunc at aliquet ante.In non tellus in turpis malesuada tempor scelerisque eu dui. Vivamus sagittis porttitor dui, at lobortis massa commodo ut. Vestibulum ac elementum diam. Ut in egestas dolor. Aenean in ante elit. Etiam dictum nulla odio, sagittis pretium eros aliquam sit amet. Fusce venenatis hendrerit lacus, vitae semper quam molestie non. Aenean lacinia massa vitae felis ullamcorper auctor. Nulla sapien velit, sagittis ac sapien nec, varius pharetra erat. In ornare, arcu a vestibulum lacinia, lorem est molestie mi, eget dapibus dolor odio a mauris. Sed non nibh risus. Fusce facilisis mauris tristique, imperdiet sem quis, maximus turpis. In sit amet nibh venenatis, egestas dolor quis, sagittis mauris. Sed gravida, ex in gravida aliquet, sem nunc sollicitudin mi, sed vehicula turpis magna nec odio. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed feugiat massa et tempus lacinia. Duis consectetur ac libero nec hendrerit. Vivamus eu fringilla libero, euismod maximus felis. Nulla laoreet viverra magna nec auctor. Etiam dignissim sollicitudin tellus, non semper dui imperdiet vel. Pellentesque enim mi, imperdiet vitae suscipit vel, euismod ut lacus. Aliquam congue faucibus sapien, eu tempus erat aliquet at.


Q:

Why does PHP's foreach advance the pointer of its array (only) once?

This is a question of curiosity about the reasons behind the way foreach is implemented within PHP.
Consider:
$arr = array(1,2,3);
foreach ($arr as $x) echo current($arr) . PHP_EOL;

which will output:
2
2
2

I understand that foreach rewinds array pointers to the beginning; however, why does it then increment it only once? What is happening inside the magic box?? Is this just an (ugly) artefact?

Thanks @NickC -- for anyone else curious about zval and refcount, you can read up on the basics here

A:

Right before the first iteration the $array is "soft copied" for use in foreach. This means that no actual copy is done, but only the refcount of the zval of $array is increased to 2.
On the first iteration:

The value is fetched into $x.
The internal array pointer is moved to the next element, i.e. now points to 2.
current is called with $array passed by reference. Due to the reference PHP cannot share the zval with the loop anymore and it needs to be separated ("hard copied").

On the following iterations the $array zval thus isn't anymore related the the foreach zval anymore. Thus its array pointer isn't modified anymore and current always returns the same element.
By the way, I have written a small summary on foreach copying behavior. It might be of interest in the context, but it does not directly relate to the issue as it talks mostly about hard copying.

A:

See how interesting, if we change the code just a little bit:
$arr = array(1,2,3);
foreach ($arr as &$x) echo current($arr) . PHP_EOL;

We got this output:
2
3

Some interesting references:
http://nikic.github.com/2011/11/11/PHP-Internals-When-does-foreach-copy.html
http://blog.golemon.com/2007/01/youre-being-lied-to.html
Now, try this:
$arr = array(1,2,3);
foreach ($arr as $x) { $arr2 = $arr; echo current($arr2) . PHP_EOL; }

Output:
2
3
1

This is very curious indeed.
And what about this:
$arr = array(1,2,3);
foreach ($arr as $x) { $arr2 = $arr; echo current($arr) . ' / ' . current($arr2) . PHP_EOL; }
echo PHP_EOL;
foreach ($arr as $x) { $arr2 = $arr; echo current($arr2) . ' / ' . current($arr2) . PHP_EOL; }

Output:
2 / 2
2 / 2
2 / 2

2 / 2
3 / 3
1 / 1

It seems what happens is just as written in NickC answer, plus the fact that when passing an array as an argument to current function, as it is passed by reference, something inside there does modify the array passed as argument to it...


Q:

cannot convert int to string simple age program

I am having an odd problem with my program. I want to print out my first name, last name and age and I feel like there is a simple solution here that I am just not seeing.
Here is my code:
string firstname; //the data type that is named and initialised
string lastname;
string userAge;
int age;

//takes user input
Console.Write("please enter your first name - ");

//stores user input
firstname = Console.ReadLine();

Console.Write("please enter your last name - ");

lastname = Console.ReadLine();

Console.Write("please enter your age - ");

userAge = Console.ReadLine();

//this is a bit of useless code I was playing around with earlier
//age = Console.Readline();

userAge = Convert.ToInt32(age);

//prints user input to screen the 0 is the position
Console.WriteLine("Your name is {0} {1}", firstname,lastname + "and your age is",age);

//pauses the program for 1000 mlseconds so you can see what the result is
Thread.Sleep(2000);

A:

It's giving you that error because ToInt32 takes a string as an input and you're giving it an int. Instead, you should give it the string and get the int as a result:
userAge = Console.ReadLine();
age = Convert.ToInt32(userAge);

But really, you don't need to convert anything. Instead, keep everything as strings. Also, your use of WriteLine is a little misformed:
string firstname;
string lastname;
string userAge;

//takes user input
Console.Write("please enter your first name - ");

//stores user input
firstname = Console.ReadLine();

Console.Write("please enter your last name - ");

lastname = Console.ReadLine();

Console.Write("please enter your age - ");

userAge = Console.ReadLine();

//prints user input to screen the 0 is the position
Console.WriteLine("Your name is {0} {1} and your age is {2}.",
        firstname, lastname, userAge);

//pauses the program for 1000 mlseconds so you can see what the result is
Thread.Sleep(2000);


Q:

Problem overriding Devise::RegistrationsController

I've read similar articles like Override devise registrations controller , but Devise in my app doesn't override correctly.
I am using Devise 1.4.2 and Rails 3.0.9 on my Mac (OSX 10.6.8).
# app/controllers/registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
  def new
    debugger
  end

  def create
    debugger
  end
end

# config/routes.rb
devise_for :users, :controllers => {:registrations => "registrations"}

Then I started my local server with --debugger option (ruby-debug19 is installed) and when access to /users/sign_up, debugger doesn't trigger.
rails server --debugger

Started GET "/users/sign_up" for 127.0.0.1 at 2011-07-11 21:21:46 +0900
Processing by Devise::RegistrationsController#new as HTML
Rendered devise/shared/_links.erb (3.8ms)
Rendered devise/registrations/new.html.erb within layouts/application (20.4ms)

Updated: I checked my routings with "rake routes", but the routing for sign_up still remains as below.
user_registration POST /users(.:format) {
    :action=>"create", :controller=>"devise/registrations"}
new_user_registration GET /users/sign_up(.:format) {
    :action=>"new", :controller=>"devise/registrations"}

I want :controller to point "registrations" (without "devise/") when POST.
What am I missing?

A:

In your routes.rb file,
You can amend your devise routes in the following way:
devise_for :users, :controllers => { :registrations => 'registrations' }


Q:

What is going on with the JavaScript room?

Seriously, almost all of the flags I get are in the JavaScript room. Here is one. In case you are tired, it leads to the "Ask a question" screen. I don't care about these silly flags, really. But I wondered if there is something we can do to make the flags more pertinent and save them for when things really are obscene. If I am right and the majority of flags come from a certain place (and assuming most are dismissed) should this chat be closed?
Of course they could go to another chat and similar things happen. I'm not sure how to know what users or how often they are flagging but it seems to be like "the chat room who cried wolf". If nothing else, I would like to bring attention to those who are flagging there. If the chat is that bad then make it a gallery or stop visiting it.
Edit
OK, I don't really think the chat should be closed. This was a poorly-formed question from the beginning, because that wasn't my main point of the post. It was more to get a discussion about why it seems, at least to me, that most of the flags (at least lately) appear to come from there and if there is anything to be done about it.

A:

Should [a chat room with an anecdotally large number of odd flags] be closed?

No
If a room was generating a large number of valid flags, then yes, that's certainly something to look into.  However, you yourself show that the flags are not valid - they're usually users taking offense at not following the JS room rules.
Speaking of rules, those that break them don't really have an excuse.  Our bot sends a message to any user with rep between 20-2,000 with some friendly advice and a link to the rules.
We also have the ability to move to gallery whenever problem users arise, and use it instead of flagging.

A:

I am often in the C# chat room. I will visit the JavaScript room on occasion, to say hi, talk about Caprica, or perhaps with some complex or pedantic issue to discuss.
I have enough rep to see the flags, and what I can observe is that there really are not a high volume on average coming from any one place at all. It may seem like JavaScript generates a lot of flags, but break it down a little bit.
JavaScript is one of the largest chat rooms on the exchange, hosts a lot of drive-by student questions or help seekers, and still is not generating all of the flags. If you were to really look at this with a metric of flags per message, then the JavaScript room would probably rate very, very, very low on that metric.
Sometimes there are problematic users who will troll chat rooms. This happens to all rooms and is not any one room's fault. The flagging system is not perfect, and some people feel that spamming flags will speed the problem user into the moderator review.
Fact is, flagging will not generate moderator review. There is however a route to accomplishing that, and I think more chat users should take advantage of it.
First, click on the user actions arrow of the message from the problem user, and select "flag for moderator". Note that this will not go to the regular users, but to an actual site moderator.

Second, enter a message in detail explaining the problematic behavior.

But please, for those who are interesting in maintaining civility in chat, do not spam flags. It is just spam.

A:

The javascript chat room has basically groups: the "regulars", people who habitually hang out there (and people like me who are probably more like "semi-regular"), and the "transients" who just come in, get help (or at least try to), and leave.
Most of the flags, I suspect, come from this second group, the transients, people who come in once, ask a question, possibly don't get an answer, get angry, flag, leave.  Or some variation on this theme.  So neither gallery mode, nor telling people to "stop visiting" is really a solution to that problem.  They wouldn't be affected by gallery mode, and they likely do "stop visiting".
Sure, closing the room would stop the flags, but that'd be a major case of throwing the baby out with the bathwater, in my opinion.  It'd be destroying a community (the "regulars"), in order to deal with a problem that likely isn't being perpetuated by members of that community.  If we're having a problem with the flagging system lets fix the flagging system, not nuke the room that's a symptom of that problem.


Q:

can I get whether a field has been assigned with reflection in golang

I have a struct as below:
type Demo struct{
     A string
     B string
}

and I have a instance of it as below:
demo := Demo{A:"a"}

the field of A has been assigned value explicit but field B not.
Now, I want to know are there exist some method that I can get the field of Instance A which has been assigned value through reflection?
Here I want to get field A.

A:

It's not possible to determine if a field was explicitly assigned a value, but it is possible to determine if there's a field that's not equal to the field's zero value.
Loop through the fields. Return true if a field's value is not equal to the zero value for the field's type.
func hasNonZeroField(s interface{}) bool {
    v := reflect.ValueOf(s)
    if v.Kind() == reflect.Ptr {
        v = v.Elem()
    }
    t := v.Type()
    for i := 0; i < t.NumField(); i++ {
        sf := t.Field(i)
        fv := v.Field(i)
        switch sf.Type.Kind() {
        case reflect.Chan, reflect.Func, reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
            if !fv.IsNil() {
                return true
            }
        case reflect.Struct:
            if hasNonZeroField(fv.Interface()) {
                return true
            }
        // case reflect.Array:
        // TODO: call recursively for array elements
        default:
            if reflect.Zero(sf.Type).Interface() != fv.Interface() {
                return true
            }
        }
    }
    return false
}

Run it on the playground.


Q:

Выполнить функцию php по истечению времени

Ребят, пишу аукцион.
Как бы покупка должна отдаться по истечению какого-то времени, а отдавать ее должна какая-то функция, которая должна выполниться в момент истечения времени.
Я рассматривал варианты создать задачу CRON, но запускать ее каждую сикунду это нереально для сервера (мне кажется), второй вариант: запускать эту функцию "проверки" фоном при каждом действии пользователя, что тоже нагрузит сервер.
Что посоветуете?

A:

К каждому аукциону в базу пишите timestamp. И если время на серваке "перевалило" за timestamp то выводите его статус как закрытый. Аналогично при генерации ЛК (личном кабинете) юзеров кто делал ставки на этот ID аукциона, если сервертайм "перетёк" за timestamp и у этого юзера "самая высокая ставка" (любое нужное вам условие) => продано.
Ну и раз в сутки прогонять базу кроном (скажем часа в 4 утра от ЦА) на удаление(скрытие, выставление статуса) аукционам. Или вместо крона использовать MySQL Event Scheduler (http://habrahabr.ru/post/123391/)


Q:

How is Identity.EntityFramework OnModelCreating called

I am working on 2 similar projects - but I did not create either of them.
They both have the same local context, as follows:
using Microsoft.AspNet.Identity.EntityFramework;

    public class LocalContext :
        IdentityDbContext
            <ApplicationUser, ApplicationRole, int, ApplicationUserLogin, ApplicationUserRole, ApplicationUserClaim>
    {
     //.....

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            AddConfigurations(modelBuilder);
        }
    }

Searching the entire project for references to OnModelCreating returns the 2 instances mentioned above, plus the reference to this method in the namespace Microsoft.AspNet.Identity.EntityFramework
These projects are made using Onion architecture, and I am running the REST layer using Swagger.
The problem is that in one of the projects, OnModelCreating is called when I start the application (Which I would expect), whilst in the other it is called the first time a user makes an action.
Can anyone explain why this is?
I assume there is a setting somewhere that is triggering this call - but I cannot find it - as I said above I have searched the entire project, but cannot find anywhere that is calling this method.
As far as I can see all the references are the same between the 2 projects - can anyone help?

A:

It's called when your database context is initialized.
If you're using a database initializer in your startup code, it'll happen then:
Database.SetInitializer(new CreateDatabaseIfNotExists<MyDbContext>());

Otherwise it'll happen the first time you create an instance of it:
using (var context = new MyDbContext()) {
    ...
}

A:

The OnModelCreating method is typically called when you create the first instance of a derived context or use data access in your application.  The reason this is at different points in your applications is probably due to the fact that you call your data access layers in different points in the lifecycle.  I would think that in this case, one application creates a copy of the LocalContext at startup and the other doesn't create a context until a user accesses the data layer.
Take a look here for some detailed documentation and here for another SO question that touches on this topic.


Q:

Save a shapefile in a temporary file

I would like to add a line after the transformation of my shapefile in order to save it in a temporary file.
uploadShpfile <- reactive({
    if (!is.null(input$shp)) {
      inFile <- input$shp
      inFolder <- substr(inFile$datapath, 1, nchar(inFile$datapath) - 5)
      unzip(inFile$datapath, exdir = inFolder)
      shpDF <- input$shp
      pwd <- getwd()
      updir <- dirname(shpDF$datapath[1])
      setwd(updir)
      for (i in 1:nrow(shpDF)) {
        file.rename(shpDF$datapath[i], shpDF$name[i])
      }
      shpName <- shpDF$name[grep(x = shpDF$name, pattern = "*.shp")]
      shpPath <- paste(updir, shpName, sep = "/")
      setwd(pwd)
      shpFile <- readOGR(shpPath)
      shpFile <- spTransform(shpFile,CRS("+proj=longlat +datum=WGS84"))

Any ideas ?

A:

Assuming you want to save to temporary shapefile the last line could be something like:
shapefile(shpFile, tempfile(pattern = "", fileext = ".shp"))


Q:

remove redundant signals in pandas

I want to build correspondance between col1 and col2 with certain rule.
Label1 is like an on switch, and label2 is like an off switch. Once label1 is on, further operation on label1 will not re-open the switch until it is switched off by label2. Then label1 can switch on again.
For example, I have a following table:
index     label1     label2    note
1          F           T       label2 is invalid because not switch on yet
2          T           F       label1 switch on
3          F           F
4          T           F       useless action because it's on already
5          F           T       switch off
6          F           F
7          T           F       switch on
8          F           F
9          F           T       switch off
10         F           F
11         F           T       invalid off operation, not on

The correct output is something like:
label1ix   label2ix
2          5
7          9

What I tries is :
    df['label2ix'] = df.loc[df.label2==T, index] # find the label2==True index
    df['label2ix'].bfill(inplace=True) # backfill the column

    mask = (df['label1'] == T) # label1==True, then get the index and label2ix
    newdf = pd.Dataframe(df.loc[mask, ['index', 'label2ix']])

This is not correct because I have got is:
label1ix   label2ix    note
2          5           correct
4          5           wrong operation
7          9           correct

I am not sure how to filter out row 4.
I have got another idea,
df['label2ix'] = df.loc[df.label2==T, index] # find the label2==True index
df['label2ix'].bfill(inplace=True) # backfill the column

groups = df.groupby('label2ix')
firstlabel1 = groups['label1'].first()

But for this solution, I don't know how to get the first label1=T in each group.
And I am not sure if there is any more efficient way to do that? Grouping is usually slow.

A:

Not tested yet, but here are few things you can try:
Option 1: For the first approach, you can filter out the 4 by:
newdf.groupby('label2ix').min()

but this approach might not work with more general data.
Option 2: This might work better in general:
# copy all on and off switches to a common column
# 0 - off, 1 - on
df['state'] = np.select([df.label1=='T', df.label2=='T'], [1,0], default=np.nan)

# ffill will fill the na with the state before it
# until changed by a new switch
df['state'] = df['state'].ffill().fillna(0)

# mark the changes of states
df['change'] = df['state'].diff()

At this point, df will be:
    index label1 label2  state  change
0       1      F      T    0.0     NaN
1       2      T      F    1.0     1.0
2       3      F      F    1.0     0.0
3       4      T      F    1.0     0.0
4       5      F      T    0.0    -1.0
5       6      F      F    0.0     0.0
6       7      T      F    1.0     1.0
7       8      F      F    1.0     0.0
8       9      F      T    0.0    -1.0
9      10      F      F    0.0     0.0
10     11      F      T    0.0     0.0

which should be easy to track all the state changes:
switch_ons = df.loc[df['change'].eq(1), 'index']
switch_offs = df.loc[df['change'].eq(-1), 'index']

# return df
new_df = pd.DataFrame({'label1ix':switch_ons.values,
                       'label2ix':switch_offs.values})

and output:
   label1ix  label2ix
0         2         5
1         7         9


Q:

How to detect if ondraglistener is already finish? (android)

I need to stop this service after a listener is already activated by using stopSelf(); However the service ends even though there is no Drag event... How can i detect if there is a Drag event happend before I can call StopService?
           mainButton.setOnTouchListener(new MyTouchListener());
           vTopLeft.setOnDragListener(new MyDragListener());
           vTopRight.setOnDragListener(new MyDragListener());
           vBottomLeft.setOnDragListener(new MyDragListener());
           vBottomRight.setOnDragListener(new MyDragListener());
           Log.d("tok", "add mview");
           stopSelf(); ---> this should wait after draglistener is finish.

MyDragListener.java
Public class MyDragListener implements View.OnDragListener  {

@Override
public boolean onDrag(View v, DragEvent event) {
    String containerName = null;
    int ID = 0;
    int Dragaction = event.getAction();
    int gravity2 = 1234567879;

    switch (event.getAction()) {
        case DragEvent.ACTION_DRAG_STARTED:

            break;
        case DragEvent.ACTION_DRAG_ENTERED:
            break;
        case DragEvent.ACTION_DRAG_EXITED:
            break;
        case DragEvent.ACTION_DROP:

            View view = (View) event.getLocalState();

            ViewGroup owner = (ViewGroup) view.getParent();
            owner.removeView(view);
            owner.setVisibility(View.GONE);
            FrameLayout container = (FrameLayout) v;
            container.addView(view);

            LocationSerializable ls = new LocationSerializable();
            switch (v.getId()) {
                case R.id.topLeft:

                    gravity2 = Gravity.LEFT | Gravity.TOP;

                    ls.setGravity(gravity2);
                    break;

                case R.id.topRight:

                    gravity2 = Gravity.RIGHT | Gravity.TOP;
                    ls.setGravity(gravity2);
                    break;

                case R.id.bottomLeft:
                    gravity2= Gravity.BOTTOM | Gravity.LEFT;
                    ls.setGravity(gravity2);

                    break;
                case R.id.bottomRight:
                    gravity2 = Gravity.RIGHT | Gravity.BOTTOM;
                    ls.setGravity(gravity2);
                    break;

                default:
                    throw new RuntimeException("Unknown ID");
            }

            LinearLayout containerParent = (LinearLayout) v.getParent();

            LinearLayout conatainerGrandMother = (LinearLayout) containerParent.getParent();

            conatainerGrandMother.setVisibility(View.GONE);

        case DragEvent.ACTION_DRAG_ENDED:

        default:

            break;
    }
    return false;
    }
}

A:

Stop your service in  case DragEvent.ACTION_DRAG_ENDED:
below is a sample template.
 @Override
      public boolean onDrag(View v, DragEvent event) {
        int action = event.getAction();
        switch (event.getAction()) {
        case DragEvent.ACTION_DRAG_STARTED:
        // do nothing
          break;
        case DragEvent.ACTION_DRAG_ENTERED:
            break;
        case DragEvent.ACTION_DRAG_EXITED:

          break;
        case DragEvent.ACTION_DROP:
          // Dropped, reassign View to ViewGroup

          break;
        case DragEvent.ACTION_DRAG_ENDED:
         // option 1
          Context.stopService();
           // option 2
            // stopService(new Intent(Activity.this,MailService.class));
           //stopSelf();
            //  other alternative is
             //  v.getContext().stopService(new Intent(v.getContext(),DragDropButtonMainService.class));
          break;
        }
        return true;
      }

According to android docs

After the user releases the drag shadow, and after the system sends out (if necessary) a drag event with action type ACTION_DROP, the system sends out a drag event with action type ACTION_DRAG_ENDED to indicate that the drag operation is over.


Q:

Chrome extensions accessing Windows registry

I understood that this could've been done before using the NPAPI, but since it's gone is there like .. any other way to access the Windows' registry using a Chrome extension ?

A:

The answer should be no, since extension lives in the sandbox and you can only do that using plugin with NPAPI, which has been permanately removed in the latest chrome.
The answer could also be yes, you can use Native Messaging to exchange messages between extensions and native applications, then you can access the registry in the native app.


Q:

How many peers it MultiBit connected to? Can not send bitcoins

I have received bitcoins from an online wallet and I am now trying to send 0.05 BTC to another address. I have by now figured out that I need to set at least 0.0001 BTC as a sender fee (that error message was confusing, because it appears before has the opportunity to set that fee!).
I am now getting the error message “MultiBit must be online and connected to more than one peer to send bitcoin”. I can see from the status in the lower left corner that MultiBit is online, but I can not see the number of peers.

How can I check the number of peers?
Why is MultiBit not connected to more than one peer (if any)?
How long can it take to connect to more than one peer?

I am using MultiBit 0.5.14 with Ubuntu 13.10.

A:

You can hover over the "Online" indicator to see the number of peers.
It should only take a few seconds to find more peers. This is dependent on the Bitcoin network though. You can force MultiBit to attempt to connect to a whole new set of peers by restarting it.


Q:

Asp.net mvc paging mechanism

is there some elegant way, ideally with jquery plugin like pager 1 or pager 2 how to implement paging with asp.net mvc? I am trying to go over partial views, but so far unsucessfully. Where should I store the loaded grid data? And how to respond on the page selection with just a partial refresh?
Thanks in advance.

A:

Try this article out, looks pretty handy - he uses a custom Html extension method. Also, check this SO question.


Q:

Search Result Webpart showing "People who've written about"

We have SharePoint 2013 and I was tasked to investigate the following issue with Search Result Webpart.
If you do a people search we get the result, but above the result we see:
People who've written about {User Name Results} as shown below:

I have been asked to investigate why it is displaying this message? above the result item.

A:

Your query is tripping the out of the box "People Expertise Search" Query rule. You will find the definition in the SSA (or Site Collection) Query Rules under "Local People Results".


Q:

CSS - What does asterisk before class mean?

Whats the difference between .some_class{} and *.some_class{}.
Does it mean that the class is applied only on tags which are inside another tag or is there no difference at all?

A:

There is no difference- see here

The universal selector, written "*", matches the name of any element type. It matches any single element in the document tree.
If the universal selector is not the only component of a simple selector, the "*" may be omitted. For example:

*[lang=fr] and [lang=fr] are equivalent.
*.warning and .warning are equivalent.
*#myid and #myid are equivalent.

A:

There is no difference between them at all. If you don't specify an element type, like div or p, then whether you have * or not doesn't matter. Even if you leave it out, it's implied that you want to match any element so long as it has the class some_class. From the spec:

If a universal selector represented by * (i.e. without a namespace prefix) is not the only component of a sequence of simple selectors selectors or is immediately followed by a pseudo-element, then the * may be omitted and the universal selector's presence implied.

Examples:

*[hreflang|=en] and [hreflang|=en] are equivalent,
*.warning and .warning are equivalent,
*#myid and #myid are equivalent.

What you're describing in terms of elements being inside other elements only applies when * is separated from the class by a space, e.g. * .some_class. That would match an element with the class some_class only if it's inside another element (basically this means it will never match the root element).
And taking the above explanation about * being implied, this would make the selector with the space also equivalent to * *.some_class. Here you can see that two universal selectors are in use, separated by a combinator. The second one just happens to be optional because it's already qualified by the class selector (the first one is not optional because it exists on its own).


Q:

Why is there an asterisk after a function type declaration in C?

My question is in the title and is more of a syntax related question. Does anyone know what the * is doing in the function below? See here:
int* reat(int *n)
{
     int i, *array;
     do
     {
         printf("n="); scanf("%d", n);
     } while (*n < 1);
     array = (int *)malloc(*n * sizeof(int));
     for (i = 0; i < *n; i++)
     {
        printf("%d. broj: ", i + 1);
        scanf("%d", array + i);
     }
     return array;
}

A:

The syntax
int i, *array;

declares i to be a variable of type int and array to be a variable of type int*. This sort of declaration isn't particularly common, but is legal C code.
Hope this helps!


Q:

How do the 35mm Zeiss Loxia vs Sony Zeiss Sonnar compare for IQ for landscapes?

How do the Sony Zeiss Sonnar 35mm f/2.8 and Zeiss Loxia 35mm f/2 lenses compare  on the Sony a7? (I am interested more with image quality than ergonomics, build quality, price, etc.)
I am particularly curious about sharpness and detail preservation for large landscape prints. Also, good corners in the f/5.6 to f/14 range. Lastly, chromatic aberration around high contrast areas (like purple fringing around leaves in front of a bright sky).

A:

Here is an example of the Sony Zeiss 35mm f/2.8 on the A7ʀ at f/5.6:

And here's a crop of the extreme bottom left corner (right click -> "view image to see it at 100%"):

Sharpness in the corners is very impressive for a 36 megapixel sensor. Chromatic aberration is well handled by lightroom, I've not had any problems with it
I don't have the Loxia to compare it to but that's a lens geared towards a classic rendering and bokeh, I wouldn't expect it to match the Sony lens for landscape use, if you're after image quality stopped down then I would definitely go for the Sony Zeiss f/2.8 lens.


Q:

SELECT previous year data based on year column

I am trying to develop a SSRS report. I have taken sales values from a transactional table and grouped them by year, month and subcategory. I have created this as a view. Here is the view code:
SELECT b.FiscalYear AS Year,
       b.FiscalMonth AS Month,
       a.SubCategoryKey,
       MAX(a.SubCategoryDesc) AS SubCategoryDesc,
       SUM(CAST(a.Cost + a.FreightCost AS decimal(18, 2))) AS TotalCost,
       SUM(CAST(a.SalesAmount AS decimal(18, 2))) AS   TotalSales,
SUM(CAST(a.Weight AS decimal(18, 2))) AS Pounds, SUM(CAST(a.SalesAmount -(a.Cost + a.FreightCost) AS decimal(18, 2))) AS Margin
FROM dbo.GrossMargin_CorrectedCosts AS a
LEFT OUTER JOIN dbo.M_DateDim AS b ON a.InvoiceDate = b.Date
GROUP BY b.FiscalYear, b.FiscalMonth, a.SubCategoryKey

I am then left with a clean view that looks like this:
SELECT [Year]
  ,[Month]
  ,[SubCategoryKey]
  ,[SubCategoryDesc]
  ,[TotalCost]
  ,[TotalSales]
  ,[Pounds]
  ,[Margin]
  FROM [FinancialData].[dbo].[SubCategorySalesbyMonth_V]\

I'd now like to add additonal columns to this query. I am going to run this as a SSRS report and pass both Year and Month parameters. What I'd like to do is when 2017 is selected as the passed Year parameters, then I would like to show previous year values for TotalSales, TotalCost and Pounds.
Whereas the query would look something like this:
SELECT [Year]
  ,[Month]
  ,[SubCategoryKey]
  ,[SubCategoryDesc]
  ,[TotalCost]
  ,[TotalSales]
  ,[Pounds]
  ,[Margin]
  ,PreviousYearTotalSales
  ,PreviousYearTotalCost
  ,PreviousYearPounds
  FROM [FinancialData].[dbo].[SubCategorySalesbyMonth_V]

Essentially when a year and month is passed to the report, I'd like to show the previous years totalsales, totalcost and pounds for that given period minus one year. I am having a heck of time doing this.
I feel like I have tried everything but obviously not. Please help.

A:

Something that could work now that you have a view to work with is the following query.
SELECT CY.[Year]
,CY.[Month]
,CY.[SubCategoryKey]
,CY.[SubCategoryDesc]
,CY.[TotalCost]
,CY.[TotalSales]
,CY.[Pounds]
,CY.[Margin]
,PY.[TotalSales] AS PreviousYearTotalSales
,PY.[TotalCost] AS PreviousYearTotalCost
,PY.[Pounds] AS PreviousYearPounds
FROM [FinancialData].[dbo].[SubCategorySalesbyMonth_V] CY LEFT JOIN [FinancialData].[dbo].[SubCategorySalesbyMonth_V] PY
ON CY.[Year] - 1 = PY.[Year]
AND CY.[Month] = PY.[Month]
AND CY.[SubCategoryKey] = PY.[SubCategoryKey]
AND CY.[Month] = PY.[Month]

This is just a simple self left join to the same view, but the year from the current year (CY) is joining back to the prior year (PY), year - 1. It is a LEFT JOIN, so the prior year's values will be null if there isn't any prior year/month's data available.
Hope this helps.


Q:

Multi-touch cross platform java application (Windows, Mac, and Linux(Ubuntu)(possibly Android))

Am trying to add multi-touch to an existing cross platform java project. I have looked in to 2 ways. There was several other ways but they seemed to not be cross platform or needed special software.

JavaFx - Working gesturing/touchevent events on windows and osx but not functioning on Ubuntu 16.04.
MT4J - Looks to be discontinued and/or unsupported.

My conclusions for the above could be wrong and am willing to try them again given good feedback.
Is there anyway to achieving a cross platform multi-touch java application? Seems I may need to write some native code and add it through the JNI which seems like a lot of work. Any ideas on this line of thought?. Feed back is appreciated, Thanks.
Continuation 1.0:
I have kept investigating using JavaFX on linux mostly because the only drawback right now for using JavaFX is linux multitouch support. What I have found out is that JavaFx multitouch does work on Linux distributions that are for embedded systems(ex: Raspberry Pi, probably most to be honest). What I can gather from this is if OpenJFX can be compiled for the embedded system then the embedded version of OpenJFX uses the device drivers directly to get input(/dev/input/) instead of the X11/GTK. Since the Linux dists for the desktop use X11/GTK for there input into the desktop environment JavaFx is unable to get these events due to a lack of support.
I don't wish to use a link but here it is
https://wiki.openjdk.java.net/display/OpenJFX/Building+the+OpenJFX+embedded+stack+for+Linux+desktop
The above link, seems to me at-least, to be about compiling a version of the OpenJFX for x86 systems(should work x64) which uses the embedded systems way of getting device input. I'am able to compile this version but when I run it appears to crash the Desktop and sometimes it does leave the Java App up. When the Java App is left running touch events do work but this end result is just not acceptable because it is unpredictable and seems to crash the desktop manager(Requires a reboot of the desktop after this).
Continuation 1.1:
I looked into using TUIO but none of the sample programs worked. They say you need a TUIO enable device which might be a special standard/protocal my devices don't use. Pretty much just downloaded the TUIO demo and ran it on a touch screen with no luck.
I also thought about attaching xev to my java application window and streaming the results to a file to latter be read by the java application and parsed into java events. This seems pretty hacky and am not sure if it would even work. If someone would lay out the possibility of this working I may try it. But at this point it seems like way to much work.
Continuation 1.2:
Found this https://bugs.openjdk.java.net/browse/JDK-8090954
and thought it was interesting.
Posted the solution below.

A:

Recently there has been many cross platform project generators
React native, Cordova are some of those
I have used React Native .It uses javascript codes which are compiled down according to the platform
React native has support for Gesture Control programming
https://facebook.github.io/react-native/docs/gesture-responder-system.html

you can also interface the react portion of code with the existing JAVA code for the app which you have already written
https://facebook.github.io/react-native/docs/integration-with-existing-apps.html


Q:

Migrate DOMBuilder setEntityResolver method in xerces 2.7 to xerces 3.x

How can we migrate setEntityResolver(DOMEntityResolver* const handler) method in DOMBuilder of xerces 2.7 to xerces 3.x.
Thanks in advance

A:

After some research I am able to find the replacement for setEntityResolver(DOMEntityResolver* const handler) method in DOMBuilder in xerces c 2.7.
The equalent for it in xerces 3.x is :
Replace DOMBuilder with DOMLSParser.
then replace "setEntityResolver" by setting parameter as below.
void DOMLSParserImpl::setParameter(const XMLCh* name, const void* value)
Here "name" should be "XMLUni::fgDOMResourceResolver" and "value" is your handler.


Q:

I want to updatecomplex XML file attribute value on specific position

I want to update my XML on specific position. Please help. Today is my last date of project submission.
<?xml version="1.0" encoding="utf-8"?>
<A>
  <B>
    <C>
      <D>
        Item1
      </D>
      <E>
        <F type="id" text="Item type">
          <E>
          <G type="id" width="" text="Pen">
            <image name="Pen1" url="www.mysite.com"></image>
          </G>
          </E>
          <E>
            <G type="id" width="" text="Pencil">
              <image name="Pen1" url="www.mysite2.com"></image>
            </G>
          </E>

        </F>
      </E>
      <D>
        Item2
      </D>
      <E>
        <F type="id" text="Item type">
          <E>
            <G type="id" width="" text="Book">
              <image name="Pen1" url="www.mysite3.com"></image>
            </G>
          </E>
          <E>
            <G type="id" width="" text="Book2">
              <image name="Pen1" url="www.mysite4.com"></image>
            </G>
          </E>

        </F>
      </E>
    </C>
  </B>
</A>

previously i know the D element vaue, F,G attribute Text value and need to update image URL.
Kindly help, I can't search exact url.
I used
XmlDocument doc = new XmlDocument();
doc.Load(xmlPath);

XmlNodeList elemList = doc.GetElementsByTagName("F");
XmlNodeList subelemlist = doc.GetElementsByTagName("G");
for (int i = 0; i < elemList.Count; i++)
                        {
                            string attrVal = elemList[i].Attributes["text"].Value;
                            if (attrVal == "Pen")
                            {

                                for (int j = i - 1; j < subelemlist.Count; j++)
                                {
                                    string attrval2 = subelemlist[j].Attributes["URL"].Value;
                                    subelemlist[j].Attributes["URL"].Value = colURL;
                                    doc.Save(xmlPath);
                                    break;
                                }
                            }

                        }

A:

If I understand your requirements, you are looking for an element that has a text property with Pen value.And you want to change image element's URL.If so, you can do the following with LINQ to XML:
var xDoc = XDocument.Load(xmlPath);
var elements = xDoc.Descendants()
                   .Where(x => (string)x.Attribute("text") == "Pen");
                   .ToList();

foreach(var item in elements)
{
   var imageElement = item.Elements("image").FirstOrDefault();
   if(imageElement != null)
   {
       imageElement.Attribute("url").Value = newUrl; // change the url value
       xDoc.Save(xmlPath);
   }
}


Q:

How do I make .htaccess work on the current directory and not subdirectories?

I'm using mod rewrite to access my PHP files in the root directory of my website indirectly. Currently, I have something like this,
RewriteRule ^(blog|about|page3|etc)$ /$1.php [L]

But what I would like to use is
RewriteRule ^(.*)$ /$1.php [L]

So that I wouldn't have to update my .htaccess file whenever I wanna add a new page to my website. The problem with this however is that it affects my subdirectories too. Which makes CSS, javascript, images unaccessable because it redirects to "/dir/example.png.php".
So what is the best solution here?

A:

Try this rule:
RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI}.php -f
RewriteRule .* $0.php [L]

A:

Edit the .htaccess to this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /$1.php [L]

After starting the rewrite engine, it will first check to see if the requested file is an actual file on the system, or if it is actually a directory. If it is neither of those, it will execute the rule, which in this case is to try and find the file by appending .php and serving that up.
Subdirectories, images, CSS and the like will be fine because they will step out of the rewriting once they are found.


Q:

necessary conditions for a quadric surface to be ruled (over a field of char 2)

Given a quadric surface $Q$ over a field $F$ of characteristic $2$, assume it is irreducible and reduced, we say it is ruled, if $Q$ is birational to $C \times \mathbb{P}^1$ for some $C$.
A sufficient condition for such a quadric to be ruled is that there is a rational point (use the projection from this point).
My question is, is this also necessary?
People have studied ruledness of a quadric hypersurface over fields of characteristic other than $2$. Maybe there are also results in characteristic $2$. In that case, I would also be very interested in knowing a reference.

A:

The condition you state is not a necessary condition.  You may find much more about these types of questions in Manin's "Cubic Forms".
First of all, over a finite field every quadric hypersurface has a rational point by Chevalley's theorem (or you can probably reduce this case to Wedderburn's earlier theorem).  Thus, assume that the field is infinite.  Then, by Bertini's Theorem, for a sufficiently general hyperplane section $C$ of your surface, $C$ is a smooth plane conic.
For the numerical polynomial $P(n) = n+1$, computing Hilbert polynomials with respect to the restriction to $Q$ of $\mathcal{O}_{\mathbb{P}^3}(1)$, the Hilbert scheme $\text{Hilb}^P_{Q/F}$ is a finite, flat scheme over $C$ of degree $2$.  Of course $C$ is geometrically simply connected.  Thus, either the Hilbert scheme is isomorphic to two disjoint copies of $C$ (the "split" case), or the Hilbert scheme is isomorphic to $C\times_{\text{Spec}\ F}\text{Spec}\ E$ for a degree $2$ separable extension of $F$ (the "non-split case").
In the split case, $Q$ is isomorphic to the product surface $C\times C$ embedded into $\mathbb{P}^3$ by the complete linear system of the Cartier divisor $\Delta(C)\subset C\times C$. If the surface $Q$ has an $F$-point, then that $F$-point projects to an $F$-point of $C$.  Thus, for every smooth, geometrically integral curve $C$ over $F$ of arithmetic genus $0$ that has no $F$-point, $Q=C\times C$ is an example of a smooth quadric surface that has no $F$-point.  On the other hand, identifying $C$ with either one of the connected components of $\text{Hilb}^P_{Q/F}$, also $Q$ is isomorphic to $C\times \mathbb{P}^1$.
Edit. The OP contacted me.  There is a mistake in what I wrote above.  It is still correct that for every conic $C$ with no $F$-rational point, the surface $Q=C\times C$ is birational to $C\times \mathbb{P}^1$ yet admits no $F$-rational point.  However, for a singular quadric surface $Q$ and a smooth hyperplane section $C$, the Hilbert scheme $\text{Hilb}^P_{Q/F}$ may fail to be an étale double cover of $C$.  The Hilbert scheme may be geometrically nonreduced (everywhere).  So the answer above is quite incomplete: it does not address the non-split case, and it does not address the nonreduced case.


Q:

How to make ordinal tick labels adjust automatically in D3

As you can see in the example, the tick labels on an ordinal axis (scale) become crowded and illegible as the domain grows. How can I make them adjust automatically as they would on a linear axis?
(I suppose I could use a linear scale instead, but this question and the answer from Mike Bostock himself suggest that the ordinal scale is more appropriate for this type of data. After all, the domain is discrete and I'm making a modified bar chart, where a convenient padding setting is useful.)

var x0 = d3.scaleBand()
  .domain(d3.range(1,6))
  .range([0,200]);

var x = d3.scaleBand()
  .domain(d3.range(1,51))
  .range([0,200]);

var xLinear = d3.scaleLinear()
  .domain([1,50])
  .range([0,200]);

d3.select('svg').append('g')
  .attr('transform', 'translate(10,10)')
  .call(d3.axisBottom(x0));

d3.select('svg').append('g')
  .attr('transform', 'translate(10,50)')
  .call(d3.axisBottom(x));

d3.select('svg').append('g')
  .attr('transform', 'translate(10,100)')
  .call(d3.axisBottom(xLinear));
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width='300' height='150'></svg>

A:

This solution takes advantage of the very smart built-in function d3.ticks(), which deals with edge cases so we don't have to.

var dataSmall = d3.range(1,8),
    dataLarge = d3.range(1, 51);

var xS = d3.scaleBand()
  .domain(dataSmall)
  .rangeRound([0,200]);

var xL = d3.scaleBand()
  .domain(dataLarge)
  .rangeRound([0,200]);

function makeAxis(scale) {
  var n=5,
      data = scale.domain(),
      dataLength = data.length;

  return d3.axisBottom(scale).tickValues(
    dataLength > n ? d3.ticks(data[0], data[dataLength-1], n) : data);
}

d3.select('svg').append('g')
  .attr('transform', 'translate(10,10)')
  .call(makeAxis(xS));

d3.select('svg').append('g')
  .attr('transform', 'translate(10,50)')
  .call(makeAxis(xL));
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width='300' height='150'></svg>


Q:

iOS: Is there a way to check if an NSArray object contains a certain character?

I need a way to know if an array has the character "@" in one of its string objects. The following code obviously doesn't work because it checks if an object just has the @ sign instead of checking if an object contains the @ sign. For example, if the user has test@test.com my if statement won't detect it. I need to see if a user has an email or not. I tried researching on how to accomplish this on stackoverflow, but no luck. Any tips or suggestions will be appreciated.
if([answer containsObject:@"@"]){
  /// do function.
}

A:

You can check if an NSArray contains an object with containsObject.  If it's an array of characters represented as one-character strings, then the code is simple:
NSArray *array = @[@"a", @"b", @"c", @"d"];
BOOL contains = [array containsObject:@"c"];

There's no such thing as an NSArray of scalar types like 'c' char, since the NS collections contain only objects.  The nearest thing to an array of chars is an NSString, which has a variety of ways to tell you if a character is present.  The simplest looks like this:
NSString *string = @"test@test.com";
NSRange range = [string rangeOfString:@"c"];
BOOL contains = range.location != NSNotFound;

A:

You have to cycle through each NSString in the array and check if it contains the substring.
This custom method shows how:
//assumes all objects in the array are NSStrings
- (BOOL)array:(NSArray *)array containsSubstring:(NSString *)substring {

    BOOL containsSubstring = NO;

    for (NSString *string in array) {

        if ([string rangeOfString:substring].location != NSNotFound) {
            containsSubstring = YES;
            break;
        }
    }
    return containsSubstring;
}

Usage:
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:3];
[array addObject:@"hi"];
[array addObject:@"yo"];
[array addObject:@"test@test.com"];

BOOL containsSubstring = [self array:array containsSubstring:@"@"];


Q:

How To update and then insert all the record in database

I have a newbie problem.
I have a query date,prepared,approved,itemcode,itemname,brandname,totalquantity,quantity
When I input 10 on quantity the php alert me that I input then Follow by insert all that query
How to do this?
    <form method="post" name="increasing" action="<?php echo "increasing.php?id=$id"; ?>">

Increasing

Date	:	<input type="date" name="date" style="width: 180px;">

Prepared By	:
            <select name="pre" style="width: 180px;">
              <option value="">Prepared By</option>
             <?php foreach ($fullname as $fl): ?>

              <option><?=$fl?></option>
            <?php endforeach; ?>
          </select>

Approved By	:
            <select name="app" style="width: 180px;">
              <option value="">Approved By</option>
             <?php foreach ($fullname as $fl): ?>

              <option><?=$fl?></option>
            <?php endforeach; ?>
          </select>

Itemcode	:	<input type="text" name="itemcode" required="required"  disabled="disabled" value="<?php echo $itemcode; ?>">

Itemname	:	<input type="text" name="itemname" required="required" disabled="disabled" value="<?php echo $itemname; ?>"/>

Brandname	:	<input type="text" name="brandname" required="required" disabled="disabled"  value="<?php echo $brandname; ?>"/>

Total Quantity	:	<input type="text" name="brandname" readonly="readonly" value="<?php echo $quantity; ?>"/>

Quantity	:	<input type="number" name="quantity"   value=""/>

		<input type="hidden" name="quantity1" value="<?php echo $quantity; ?>">

		<input type="submit" name="submit" class="myButton" value="Save"/>

</form>

    if(isset($_POST['submit'])){

$id = $_GET['id'];
$old = $_POST['quantity'];
$new = $_POST['quantity1'];

$total = $old + $new;

$uiqry = $mysqli->prepare("UPDATE table_inventory SET quantity = ?  WHERE id = ?");

$uiqry->bind_param('ii', $total,$id);

$uiqry->execute();
$uiqry->close();

}

echo "";
echo "";

TIA.

A:

add this line in  of html

Html
<input type="text" name="date " value=""/>
<input type="text" name="prepared" value=""/>
<input type="text" name="approved"  value=""/>
<input type="text" name="itemname" value=""/>
<input type="text" name="itemcode" value=""/>
<input type="text" name="totalquantity" value=""/>
<input type="text" name="quantity" value=""/>

Jquery
$("input[name=quantity]").change(function(e){
if($(this).val() != "")
{
alert("You have added new data");

var date = $("input[name=date]").val();
var prepared= $("input[name=prepared]").val();
var approved= $("input[name=approved]").val();
var itemname= $("input[name=itemname]").val();
var itemcode= $("input[name=itemcode]").val();
var totalquantity= $("input[name=totalquantity]").val();
var quantity= $("input[name=quantity]").val();

// pass the values to insert using ajax like this
jQuery.post("datains.php", {

date :date ,
prepared:prepared,
approved:approved,
itemname:itemname,
itemcode:itemcode,
totalquantity:totalquantity,
quantity:quantity

},  function(data, textStatus){

if (data == 1)
{
alert("Data inserted");
location.reload();

}
else
{
alert("Data not inserted");
return false;
}
});

}

});

datains.php
// retrive passed values like this
$date= $_POST['date'];
$prepared= $_POST['prepared'];
$approved= $_POST['approved'];
$itemname= $_POST['itemname'];
$itemcode= $_POST['itemcode'];
$totalquantity= $_POST['totalquantity'];
$quantity= $_POST['quantity'];

$con = mysqli_connect("localhost","username","password","dbanme");

$query = //write insert query here;

$result = mysqli_query($con,$query) or die (mysqli_error($con));

if($result)
 echo "1";
else
echo "2";


Q:

Can I make threads wait for a lock and then jump over it once released?

Given is the following pseudo code. A function may be entered by multiple threads simultaneously. I want all threads to execute a() and c(), but b() must only be executed by those threads that were not locked when entering the synchronized block.
In other words: If a thread must wait for the lock, then I want it to wait until the lock is released and then jump over b() and continue with c() right away.
    public void code() {
        a() // check if page is present locally

        if (pageMissing) {
            synchronized (this) {
                page = b(); // get page over REST
            }
        }

        c() // access page
    }

How is this useful? Imagine b() calls an external REST function to update local data. When a thread enters, we want to be sure that the function is called and local data is updated, but once the blocking thread exits b() we know local data is current and we don't want to waste resources in having consecutive threads that were already waiting call the update function again.

A:

You can have a boolean flag (instance variable) that denotes whether b() has been called or not. All threads that enter the synchronized block will check this condition before calling b().
private boolean isDone = false;

public void code() {
    a();
    synchronized (this) {
        if (!isDone) {
            b();
            isDone = true;
        }
    }
    c();
}

Only the first thread that acquires the lock will call b(). After it succeeds, it will set the flag to true and will exit the block. All subsequent threads entering the block will fail on the if condition and hence will not invoke b().

If you do not want the other threads to wait on the synchronized block's lock and want to continue to call c(), you can remove the synchronized keyword and use an AtomicBoolean and use its compareAndSet
 private AtomicBoolean isDone = new AtomicBoolean(false);

 public void code() {
    a();
    if (isDone.compareAndSet(false, true)) {
       b();
    }
    c();
}

Javadoc of compareAndSet states

Atomically sets the value to the given updated value if the current value {@code ==} the expected value.
@return {@code true} if successful. False return indicates that the actual value was not equal to the expected value.

So, the first thread that calls compareAndSet while isDone is false will succeed. The others will get false as the return value and hence won't enter the block and can thus continue.

UPDATE:
From your comments

@user7 Yes, I am concerned with threads calling b() unnecessarily, but (see my other comment) I need those threads that arrive while b() runs to wait until it is finished before they continue with c()

Seems you need the first solution of mine.


Q:

Unset XML element function not working

This is what I have.
$filename= asql($_GET['filename']);
$fullfile = "xml/".$filename;
function delete_book_id($ids){
  $data = simplexml_load_file($fullfile);
  $data_count = count($data->item);
  for($i = 0; $i < $data_count; $i++)
  {
    //basically what you want to remove
    if(($data->item[$i]->id == $ids))
    {
      unset($data->item[$i]);
    }
  }
  file_put_contents($fullfile, $data->saveXML());
}

lets say $fullfile is xml/name.xml and the file exists in our folder. Where the variable is called in the function it should work right?
If I replace the variable in the function with xml/name.xml it will work, but using the variable causes the page to break and not reload nor will it remove the line it is supposed to unset. Will the function not accept variables, or am I missing something here?
I have also tried using "xml/".$filename in place of the variable in the function. No luck there either.

A:

$fullfile is defined outside of the function. It's undefined inside of it. Use global $fullfile; within function or define it there.


Q:

When to use 'self' in Ruby

This method:
  def format_stations_and_date
    from_station.titelize! if from_station.respond_to?(:titleize!)
    to_station.titleize! if to_station.respond_to?(:titleize!)
    if date.respond_to?(:to_date)
      date = date.to_date
    end
  end

Fails with this error when date is nil:
NoMethodError (You have a nil object when you didn't expect it!
The error occurred while evaluating nil.to_date):
  app/models/schedule.rb:87:in `format_stations_and_date'
  app/controllers/schedules_controller.rb:15:in `show'

However, if I change date = date.to_date to self.date = self.date.to_date, the method works correctly.
What's going on? In general, when do I have to write self?
Edit: It's not related to the question, but please note that there is no "titleize!" method.

A:

Whenever you want to invoke a setter method on self, you have to write self.foo = bar. If you just write foo = bar, the ruby parser recognizes that as a variable assignment and thinks of foo as a local variable from now on. For the parser to realize, that you want to invoke a setter method, and not assign a local variable, you have to write obj.foo = bar, so if the object is self, self.foo = bar

A:

You disambiguiate between the instance method name and a local variable using self (it is allowed to have both with the same name in the same scope). In other words, there will be a method name resolution only if there is no local or block variable of the same name in scope. Behold:
class Foo
  attr_accessor :boo
  def do_boo
    boo = 123
    puts "Locvar: #{boo} Method: #{self.boo}"
  end
end
Foo.new.do_boo

Here's why: imagine you have a module which implements a method. This method assigns something to it's internal local variable
"foo" which is used for some computation. If you skip the "self" part, the method will make a "foo=" method call on the object
whose class includes the module, which was not the intention of the author and can be downright disastrous.
class Foo
  def bar=(new_value_of_bar)
    set_off_nukes(new_value_of_bar / 3)
  end
end

module InnocentModule # written by a different author elsewhere
  def do_useful_stuff
    ...
    bar = Math.sin(something) # we're dead
  end
end
Foo.send(:include, InnocentModule)

Another crucial part where you have to use self is when invoking the Object#class method, because simply saying "class" means a class keyword for Ruby.


Q:

Should you rely on another header for the headers it includes?

Assuming that all headers are guarded, let's say you had an abstract data type.
#include "that.h"
#include "there.h"

class Foo {
 protected:
  // Functions that do stuff with varOne and varTwo
 private:
  that varOne;
  there varTwo;
 ...
};

Then in the classes that inherit from foo ( and thus include foo.h ), would you also bother including that and this? Normally what I do is include everything that a class needs, regardless of whether would already receive them from another include. Is this redundant?

A:

There is one downside to redundantly including header files that would otherwise have been included directly: it forces the compiler to reopen and reparse them. For example, in
a.h:
#ifndef __A_H
#define __A_H
// whatever
#endif

b.h:
#ifndef __B_H
#define __B_H
#include "a.h"
// whatever
#endif

c.cpp:
#include "a.h"
#include "b.h"
//whatever

a.h has to be opened and read twice -- although the #ifndef will make the preproc ignore a.h's contents in the second inclusion, it still has to at least load the file from disk and read its bytes from the #ifndef to the #endif.
This can slow down compilation.  It will not break your build or anything though, it'll just be an annoyance in really large projects, where compiles can take many minutes.
If you use #pragma once in your headers, there's a good chance an aware compiler will cache the filenames at a higher level, and ignore the second inclusion of a.h altogether. That too can speed up builds.


Q:

SQL to end users: pros and cons

Once upon a time, far far away in a distant galaxy I was a witness to a discussion between a couple of developers. The subject was if it's a good idea to give end users access to a production SQL server (MS SQL 2008) in order to give them ability to make their own reports against their own data.
It was a request from business people -- "Our clients want to make custom reports".
A guy who proposed this, claimed that:

He was able to give users "read-only access" through set of
permissions and make the system absolutely safe.
SQL initially
was an "end-user" language and may be so now.
Having permissions
to run SQL queries, users would be able to do what they want not
disturbing developers and support.

Other guys who were against this claimed:

It's pretty easy to crash MS SQL having even max. restricted access.
Exposing SQL and database structure to end users is not a good idea anyway; it's a bad design.
SQL is too complicated to non-programmers, and, therefore, it won't make their life easier.

What do you think about giving end users access to SQL?
Thank you in advance!

A:

You can make some things safer by not just limiting users to read-only access, but also by turning on the query governor cost limit.  That will attempt to do some cost analysis of the queries prior to running them, and if they exceed the predefined threshold it will refuse to run them.
Even better than this would be to have a cloned database available for querying.  This could be something as simple as a separate server running off of a backup of the production system.  Depending on how "live" your data needed to be, you could adjust the backup/restore interval accordingly.
As far as whether it's a good idea to expose the database to direct querying for non-programmers, that still depends on just how savvy the users are.  Could they be taught SQL?  It's really not that hard for simple things.


Q:

JavaScript conditions

If someone could point out what I'm doing wrong I'd be eternally grateful! I can't seem to get the right combination of parenthesis - how to I combine multiple conditions in one statement?? Obviously I don't expect anyone to modify the code below, I just want to show what I'm trying to achieve.
If someone can explain the logic to me that'd be great
Thanks
function ChangeButton()
{
if
((document.forms[0].IPR.value == "") && (document.forms[0].FNM1.value == "") && (document.forms[0].FNM1.value == "") && (document.forms[0].SURN.value == "") && (document.forms[0].GEND.value == "") && (document.forms[0].DOB.value == "") && (document.forms[0].CRIM.value == "") && (document.forms[0].ETHC.value == "") && (document.forms[0].DSBC.value == "") && (document.forms[0].MARK1.value == "") && (document.forms[0].NATC.value == "") && (document.forms[0].COBC.value == "") && (document.forms[0].COD.value == "") && (document.forms[0].FIVE.value == "") && (document.forms[0].PERM.value == "") && (document.forms[0].VISF.value == "") && (document.forms[0].USD.value == "") && (document.forms[0].HAD1.value == "") && (document.forms[0].HAD3.value == "") && (document.forms[0].HTEL.value == "") && (document.forms[0].HAEM.value == "") && (document.forms[0].FEES.value == "") && (document.forms[0].REF1TIT.value == "") && (document.forms[0].REF1ORG.value == "")     && (document.forms[0].REF1POS.value == "") && (document.forms[0].REF1AL1.value == "") && (document.forms[0].REF1AL3.value == "") && (document.forms[0].REF1AL5.value == "") && (document.forms[0].REF1EMA.value == "") && (document.forms[0].DISC.value == ""))
&&
((document.forms[0].PERM.value == "") && (document.forms[0].FIVE.value == "N"))
&&
((document.forms[0].AGNT.value == "") && (document.forms[0].USD.value == "Y"))
&&
((document.forms[0].CSTRT.value == "") && (document.forms[0].USD.value == "N") && (document.forms[0].CENDD.value == "") && (document.forms[0].CAD1.value == "") && (document.forms[0].CAD3.value == "") && (document.forms[0].CAD4.value == "") && (document.forms[0].CAPC.value == "") && (document.forms[0].CTEL.value == ""))
&&
((document.forms[0].AWDB.value == "") && (document.forms[0].FEES.value == "") && (document.forms[0].FEES.value == "Private Funds Self or Family") && (document.forms[0].AWDS.value == ""))
&&
((document.forms[0].RESEARCH.value == "Y") && (document.forms[0].RESSRT.value == "") && (document.forms[0].RESMOA.value == "") && (document.forms[0].RESAR.value == "") && (document.forms[0].RESDIS.value == ""))
{
document.getElementById('submitbutton').className = 'enabled';
}
else {
document.getElementById('submitbutton').className = 'disabled';
}
}

A:

I see
...&&...  document.forms[0].FIVE.value == ""
...&&... document.forms[0].FIVE.value == "N"

This never be true
EDIT
I think you must change approach, try something like this:
function ChangeButton()
{
    var frm = document.forms[0];
    var neverEmpty = ['field1','field2','field3'];
    var mustBe     = {field3:'Y', field4:'N'};

    var status = 'ok';

    for(var i = 0; i<neverEmpty.length; i++) {
        if(frm[neverEmpty[i]] == '') {
        status = 'ko';
        break;
    }
}

for(myField in mustBe) {
    if(frm[myfield] != mustBe[myField]) {
        status = 'ko';
        break;
    }
}
document.getElementById('submitbutton').className = status=='ok'? 'enabled' : 'disabled';

}


Q:

How to validate error messages for nested form group fields in angular

Hi i am new for angular and i am trying to implement form validations and using below code and my problem is nested form group fields i am getting errors in log TypeError: Cannot read property 'touched' of null can some one help me please..
.ts
 ngOnInit() {
    this.employeeForm = this.fb.group({
      fullName: ['',[Validators.required,Validators.minLength(2), Validators.maxLength(10)]],
      email: ['',[Validators.required,Validators.email]],
      skills: this.fb.group({
        skillName: ['',[Validators.required]],
        experienceInYears: ['',Validators.required],
        proficiency: ['']
      })
    });
  }

.html
<form class="form-horizontal" [formGroup]="employeeForm" (ngSubmit)="onSubmit()">

Create Employee

        Full Name

          <input id="fullName" type="text" class="form-control" formControlName="fullName">

              Full Name is required

              Full Name must be greater than 2 characters and less than 10 characters

        Email

          <input id="email" type="text" class="form-control" formControlName="email">

              Email is required

              Valid Email is required

    //**PROBLEM IN THIS BLOCK**

          skill Name

            <input type="text" class="form-control" formControlName="skillName">

                Skill is required

            <input type="text" class="form-control" formControlName="experienceInYears">

                Experience is required

    <button class="btn btn-primary" type="submit">Save</button>
    <button class="btn btn-primary" type="submit" (click)="onLoadDataClick()">Load Data</button>

A:

Be aware of the fact that, you have nested your form one level by folder called, 'skills'. Hence, you need to honor that by,
employeeForm.get('skills.skillName').touched


Q:

Bash script to edit excel files

I have multiple excel files in this format.
They are clock in and clock out date and time.

---------------------------------
| Name     | Time               |
---------------------------------
| Person A | 03-Jul-17 8:15 AM  |
| Person A | 03-Jul-17 10:32 AM |
| Person A | 03-Jul-17 1:56 PM  |
| Person A | 03-Jul-17 6:15 PM  |
| Person A | 04-Jul-17 8:29 AM  |
| Person A | 04-Jul-17 8:58 AM  |
| Person A | 04-Jul-17 9:43 AM  |
| Person A | 04-Jul-17 1:03 PM  |
| Person A | 04-Jul-17 2:17 PM  |
| Person A | 04-Jul-17 5:58 PM  |
.
.
.
| Person A | 31-Jul-17 7:45 AM  |
| Person A | 31-Jul-17 8:10 AM  |
| Person A | 31-Jul-17 3:26 PM  |
| Person A | 31-Jul-17 7:29 PM  |
---------------------------------

I would want to extract this data and save it as a new excel file in this format:

---------------------------------------------
| Name     | Date      | Time In | Time Out |
---------------------------------------------
| Person A | 03-Jul-17 | 8:15 AM | 6:15PM   |
| Person A | 04-Jul-17 | 8:29 AM | 5:58PM   |
.
.
.
| Person A | 31-Jul-17 | 7:45 AM | 7:29PM   |
---------------------------------------------

Basically it's to arrange the data one entry per date with the earliest time for that date as the Time In and the latest time for that date as the Time Out.
There are multiple excel files in this format, and doing it manually is going to take too long.
If you want to convert them to .csv first edit then convert them back to .xlsx, it's cool.
PS: Bounty of 200 rep up for grabs.

A:

I converted the files to csv and used a PHP script to parse the content creating it into how I actually wanted. The result was then saved in a new file then those files were converted back to xls then merged into one notebook.
The conversion and merging part was done manually. It's not the best solution but it's working for now.
Here's the script:

// get list of files from data directory
$files = array_diff(scandir('./data'), array('.', '..'));
foreach($files as $file):

    // get all data from the csv file and save in the $data array
    $csvFile = file('data/'.$file);
    $data = $list = [];
    foreach($csvFile as $line) {
        $data[] = str_getcsv($line);
    }
    unset($data[0]);

    // parse the data array and get the different sections: name. date and time
    foreach($data as $v) {
        $date = strtotime($v[1]);
        $list[date('d-m-Y',$date)][] = array(
            'name'=>$v[0],
            'date'=>date('d/m/Y',$date),
            'in'=>$date
        );
    }

    // create a new array and save parsed data in it with header columns
    $new = array(array('Name','Date','Time In','Time Out'));
    foreach($list as $k => $v) {
        $out = max(array_column($v, 'in'));
        $name = $v[0]['name'];
        $new[] = array(
            'name'=>ucwords(strtolower($name)),
            'date'=>$v[0]['date'],
            'in'=>date('h:i A', $v[0]['in']),
            'out'=>date('h:i A', $out)
        );
    }

    // The name of a new file in the new directory using this file name
    $filename = str_replace('.csv', '', basename($file));
    $fn = strtolower($filename.'-log.csv');

    // open the file and output the new array as CSV
    $out = fopen('new/'.$fn, 'w');
    foreach($new as $l) {
        fputcsv($out, $l, ",",'"');
    }
    fclose($out);

endforeach;


Q:

How to get input parameter in Razor?

Example
When editing item
/domain.com/app/item/detail/111
OR
/domain.com/app/item/detail/?Id=111

When creating a new item
/domain.com/app/item/detail/new
OR
/domain.com/app/item/detail/

A:

You can access query strings like this
@if(Request.QueryString["Id"] == "111")
{

foo bar

}

or
use ViewBag in your controller to give the information to the view
public ActionResult Detail(string Id)
{
    ViewBag.Id = Id;

    return View();
}

Then in your view

@ViewBag.Id


Q:

AWS API Method fails with 504 Error; Using Cognito and CORS

Summary:
I'll get into the weeds below, but essentially the end goal I'm aiming for is to retrieve a value from a AWS Lambda function and return it to the client side of my page. The page is using AWS Cognito to authenticate a user and once authenticated it posts to an API Gateway endpoint to retrieve data back from my Lambda function (The Lambda queries DynamoDB). This is the part I'm struggling with because I get a 504 (Timeout) error back.
I know my Lambda returns values correctly and that my API, theoretically, is implemented correctly, or at least that it works from the test section of the API Gateway Management Console.
Details:
I've spent quite a bit of time trying to figure out exactly where my error lies, and I believe it has something to do with the Cognito authentication or CORS. If I remove the authorization requirement from my API gateway method and don't send the authorization token, then I get the expected response back from the post. This leads me to believe that maybe the root of my issue is incorrectly implementing Cognito authorization on the Post method.
I'm using CORS because the site is hosted on an EC2, but is using AWS API Gateway for its RESTful routes.
Also, I use the Cognito javascript SDK to authenticate the user, then pass the authToken into the custom headers in my ajax.
Here's my ajax:
$.ajax({
    method: 'POST',
    url: _config.api.invokeUrl + '/getusersites',
    dataType: "json",
    crossDomain: true,
    cors: true,
    xhrFields: {
        withCredentials: true
    },
    headers: {
        Authorization: token
    },
    data: JSON.stringify(user),
    success: completeRequest,
    error: ajaxError
});

Now unless I'm misunderstanding, when I look at the headers in the Network tab of Chrome's DevTools, it appears that the post is failing on the preflight. Because when I look at that General section of that URL, it says:

Request Method: OPTIONS
Status Code: 504

(See update below for full headers)
And the body is:

{"message": "Endpoint request timed out"}

So that would lead me to believe that the Option request for CORS is timing out prior to the Post even being called.
I'm also getting the console error:

Failed to load (My API endpoint here): Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '(My origin domain)' is therefore not allowed access. The response had HTTP status code 504.

So to me that looks like the CORS preflight is failing to respond before the API times out.
I do not have Authorization enabled in the method execution for the Options method on my API resource, but I do have it enabled for the Post method. As I said previously, if I disable that then everything works as expected, only there's no Cognito authorization check.
So what am I doing wrong here? Is it a CORS issue? Auth issue? Both?
What I've tried:
I attempted to add the CORS headers to the Integration Response of my Post method. However, I believe this didn't make a difference because they would only be returned with a 200 (Success) code, and I'm getting the 504 code.
I thought perhaps there was a permissions issue with either my Lambda function or in my Cognito User Pool's authorizer. So I went into IAM and gave them both all the permissions they could possibly want. This didn't change the result.
I was working under the theory my ajax might be incorrectly set up, so I've tried a few different ways of implementing the parameters of the post, however the only one that works is if I disable authorization and don't send the custom header with the auth token.
I ensured that my API resources have CORS enabled and have been redeployed. If only it had been that simple.
I've googled enough to overheat a few google servers, but I'm out of ways to ask this question.
Final Thoughts:
If you've taken the time to read my novel, I appreciate it. If anyone has tried to do something similar or has any ideas of directions I could go next with this issue. I'm still learning how to handle all this AWS implementation, so I'm sure I've just made some silly mistake somewhere.
Thank you in advance for your replies.
>>>UPDATE:<<<
Per request, here are the full headers for the OPTION attempt. There is no POST because of the 504 error on the OPTION attempt.
General:

Request URL: https://(API endpoint).amazonaws.com/prod/getusersites
Request Method: OPTIONS
Status Code: 504
Remote Address: 52.84.11.37:443
Referrer Policy: no-referrer-when-downgrade

Response Headers:

content-length: 41
content-type: application/json
date: Wed, 04 Apr 2018 16:16:14 GMT
status: 504
via: 1.1 0a9f4502819b08c3a7919c963887be2b.cloudfront.net (CloudFront)
x-amz-apigw-id: E0wHvE3doAMFgrA=
x-amz-cf-id: pVgd6gNNtw-cYxKe4s9jdEnfU2rBle8cd9MyP34aduYi0_ds4YBRCA==
x-amzn-requestid: 6e014d82-3823-11e8-bc41-3f13ca287d3c
x-cache: Error from cloudfront

Request Header:

:authority: (API Endpoint)
:method: OPTIONS
:path: /prod/getusersites
:scheme: https
accept: /
accept-encoding: gzip, deflate, br
accept-language: en-US,en;q=0.9
access-control-request-headers: authorization
access-control-request-method: POST
cache-control: no-cache
origin: https://(Origin Domain)
pragma: no-cache
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36

A:

It's taken forever, but I finally figured out what was wrong.
The problem was how AWS set up the OPTIONS Integration Request when I implemented CORS through the AWS API Gateway Console.
By default, it sets up the Integration Request as HTTP, using the API invocation URL as the endpoint. For some reason, this was causing the OPTIONS preflight to time out and respond with 504. Still don't know why, likely had to do with the authentication.
Solution:
In the Integration Request section of my OPTIONS method I changed the Integration type from HTTP to MOCK.
Then, after saving that, I had to go to the Integration Response section of my OPTIONS method, expand the 200 HTTP status code, expand the Headers Mappings and reenter the values for my headers. The headers were still there, but the values had been removed. My final response headers looked like this:

Access-Control-Allow-Headers   'Content-Type,X-Amz-Date,Authorization,X-Api-Key,X-Amz-Security-Token'
Access-Control-Allow-Origin    'https://MyDomain.com'
Access-Control-Allow-Credentials   'true'
Access-Control-Allow-Methods   'DELETE,GET,HEAD,OPTIONS,PATCH,POST,PUT'

After setting those, I redeployed the API and It worked perfectly! Now I'm off to drink a bottle off champagne. :)


Q:

How to save an audio stream as a wav file using NodeJS

My aim is to record a radio stream coming from an Icecast server.
I am using the icecast node module to fetch the radio stream and then writing the wave file by piping the stream through the wav module.
Here is an example of my code:
const icecast = require('icecast');
const url = 'http://87.118.104.139/radiogibsonaac';
var wav = require('wav');

let ice, fileWriter;

ice = icecast.get(url, res => {
    fileWriter = new wav.FileWriter(__dirname+'/recording.wav', {
        channels: 1,
        sampleRate: 16000,
        bitDepth: 128
    });
    res.pipe(fileWriter);
});

setTimeout(()=>{
    fileWriter.end();
    ice.end();
},5000);

The stream is successully recorded to my disk as expected and I am able to listen to the file in VLC, but the wav file itself does not seem to be formed correctly.
When I try to use another tool to edit the file, it shows an error each time.
For example, I am trying to change the speed of the audio on this site and it does not recognise the file.
Also if I try to view the file info using the Sox CLI it displays:

sox FAIL formats: can't open input file `recording.wav': Sorry, don't understand .wav size

Does anybody know if I am missing a step in the process of writing the wav file to disk?

A:

Based on the stream URL, it looks like the stream is in AAC format, and you are trying to write that data directly to a WAV file, so you end up with a file with a WAV header but AAC audio data.
You would need to either write the stream to disk as AAC, and then do a conversion on the file, or transcode the stream on-the-fly before writing it to disk.


Q:

keep page 100% when zooming into iframe content on touch device

I have a page that displays a container div and next to it is an iframe that is displaying an model I made using "Three.js" which works perfectly. The problem I have is when I switch this over to my touch device and interact with the model(by zooming in), the whole page zooms in instead of the model itself. I've been researching and all the solutions i've found didn't fix my bug. Basically, all I want is for the model(inside the iframe) itself to zoom in/out when on touch device and not the whole screen. I believe the problem has to deal with th model itself because when I switch the model from a regular gltf file to a pointmaterial it works fine. Here is my code
HTML

text

text

Home | spanish

CSS
#width{

    width: 600px;

}
body{

    overflow: hidden;
}
body p {
    font-size: .875em;
    font-family: 'Open Sans';
}

h1,h2,h3,h4 {
    font-family:'Marcellus';
    font-size: 1.5em;
}

.feather {
  width: 16px;
  height: 16px;
  vertical-align: text-bottom;
}

/*sticky-footer*/

.footer {
    position: absolute;
    bottom:0%;
    margin-bottom:3%;
    width: calc(100% - 20px);
    height: 100px; /* Set the fixed height of the footer here */
    /*line-height: 60px; /* Vertically center the text there */
    /*padding: 20px;*/
    background-color: #F8F9FA;
}

/*
 * Sidebar
 */

.sidebar {
    position: fixed;
    top: 0;
    bottom: 0;
    left: 0;
    z-index: 100; /* Behind the navbar */
    padding-top: 10px;
    padding-right: 10px;
    padding-left: 10px;
    padding-bottom: 10px; /* Height of navbar */
    box-shadow: inset -1px 0 0 rgba(0, 0, 0, .1);
}

.sidebar-sticky {
  position: relative;
  top: 0;
  padding-bottom: 0px;
  height: calc(100% - 200px);
  /* height: 90%; */
  padding-top: .5rem;
  overflow-x: hidden;
  overflow-y: auto; /* Scrollable contents if viewport is shorter than content. */
}

A:

This is not really a ThreeJS question. What you're looking for is the CSS touch-action attribute to prevent pinch-zooming on touch devices. Try adding touch-action: none; to your iframe, and it will prevent the user from zooming in when pinching this iframe.
For more info, see the MDN documentation.


Q:

Connecting to a udp socket in Node.js

I'm writing a javascript/node.js program that receives the scores from a HL/Team Fortress 2 server, but I can't seem to receive the udp packets send by the game server. (I can receive udp packets transmitted by a UDP test tool)
I have found a python library that works but it uses socket.connect() before receiving data from the server.
Python snipplet (asyncore used):
self.create_socket(socket.AF_INET, socket.SOCK_DGRAM)
self.bind(('0.0.0.0', 17015))
self.connect((IP of server, 27015))

data = self.recv(1400)

But in node.js I can't seem to connect to a remote address.
My code so far:
var dgram = require('dgram')
var server = dgram.createSocket("udp4");
server.on('message', function (data, rinfo) {
    data = data.toString();
    if (data.startsWith('\xff\xff\xff\xff') && data.endsWith('\n\x00')) {
        console.log(data);
        Logparser(data);
    } else {
        console.log(data);
    }
});
server.bind(17015);

UDP packet captured with wireshark http://pastebin.com/W7i9CV2u

A:

You need to use the addMembership() method to join a multicast group, in UDP you don't connect to servers, a connection is never created and there is no guarantee that you will receive any/all packets. You join a multicast group and receive packets with that group-id that reach your network card, the python method name is misleading.
http://nodejs.org/api/dgram.html#dgram_socket_addmembership_multicastaddress_multicastinterface