UTF-16LE encoding and xerces2 Java

Question: I went through a few posts, like FileReader reads the file as a character stream and can be treated as whitespace if the document is handed as a stream of characters where the answers say the input source is actually a char stream, not a byte stream.
However, the suggested solution from 1 does not seem to apply to UTF-16LE. Although I use this code:
    try (final InputStream is = Files.newInputStream(filename.toPath(), StandardOpenOption.READ)) {
      DOMParser parser = new org.apache.xerces.parsers.DOMParser();
      parser.parse(new InputSource(is));
      return parser.getDocument();
    } catch (final SAXParseException saxEx) {
      LOG.debug("Unable to open [{}}] as InputSource.", absolutePath, saxEx);
    }

I still get org.xml.sax.SAXParseException: Content is not allowed in prolog..
I looked at Files.newInputStream, and it indeed uses a ChannelInputStream which will hand over bytes, not chars. I also tried to set the Encoding of the InputSource object, but with no luck.
I also checked that  there are not extra chars (except the BOM) before the <?xml part.
I also want to mention that this code works just fine with UTF-8.
// Edit:
I also tried DocumentBuilderFactory.newInstance().newDocumentBuilder().parse() and XmlInputStreamReader.next(), same results.
// Edit 2:
Tried using a buffered reader. Same results:
Unexpected character '뿯' (code 49135 / 0xbfef) in prolog; expected '<'
Thanks in advance.
Comment: What if you remove the BOM at the beginning (skipping the first two bytes)? `... { is.read(): is.read();`
Comment: Then I wouldn't be able to read UTF-8 without bom or ISO-8859-1. :(
Comment: The encoding is given or defaulted UTF-8 in ``. I have heard that in rare cases a BOM gave such a problem. But I do not remember specifics.
Comment: I cannot get even this far. I want to read that tag and attribute you refer to. But see my 2nd edit, it stops before that.
Comment: I double checked. The file is starting with the BOM 0xFF 0xFE. Maybe I need to wrap it into a BOMRemovingInputStream…
Comment: Shouldn't you set the character encoding on the input source before parsing (`inputSource.setEncoding("UTF-16");`) so it uses the BOM to determine whether it's LE or BE?
Comment: Yes and no. The XML libraries are mature enough to do this right now. The correct answer was "maven resource filtering". Since maven is set to UTF-8, my tests failed reading from the target/classes folder, but my input (from the src/test/resources-folder) was okay.
Answer: To get a bit farther some info gathering:
byte[] bytes = Files.readAllBytes(filename.toPath);
String xml = new String(bytes, StandardCharsets.UTF_16LE);
if (xml.startsWith("\uFEFF")) {
    LOG.info("Has BOM and is evidently UTF_16LE");
    xml = xml.substring(1);
}
if (!xml.contains("<?xml")) {
    LOG.info("Has no XML declaration");
}
String declaredEncoding = xml.replaceFirst("<?xml[^>]*encoding=[\"']([^\"']+)[\"']", "$1");
if (declaredEncoding == xml) {
    declaredEncoding = "UTF-8";
}
LOG.info("Declared as " + declaredEncoding);

try (final InputStream is = new ByteArrayInputStream(xml.getBytes(declaredEncoding))) {
  DOMParser parser = new org.apache.xerces.parsers.DOMParser();
  parser.parse(new InputSource(is));
  return parser.getDocument();
} catch (final SAXParseException saxEx) {
  LOG.debug("Unable to open [{}}] as InputSource.", absolutePath, saxEx);
}

Comment: (takes a deeeeeep breath) … MAVEN RESOURCE FILTERING. I was looking at the source all along, but when looking at the target you could see some extra bytes at the beginning o/t file. Very sorry to see this :(
Comment: I looked into the file with `xxd` and I know it is \uFFFE at the beginning.
Comment: bytes FF FE are in UTF-16LE actually the char `\uFEFF` aka the BOM ( a bit weird Unicode number)
Comment: Hey, an aside. As the BOM in UTF-8 bytes is `EF BB BF`  that would explain your edit-2:  0xbfef somewhat.
Comment: both IntelliJ  and `file` show  this is a UTF-16LE file. UTF16LE starts with `\uFFFE`. `\uFFFE` is not weired, according to Wikipedia it is the "no character" character. The 2nd edit used UTF-8 interpretation by accident, no change when I put back UTF16LE in again :(
Comment: Well I could always use https://github.com/gpakosz/UnicodeBOMInputStream
Comment: (Bytes FF FE is in UTF-16 little endian the number 0xfeff hence U+FEFF or in java `\uFEFF`.) The mere point I wanted to make: (1) the BOM sometimes seems to be problematic, maybe only for UTF-16LE. (2) The declared encoding must agree with the bytes for XML parsing.

UTF-16LE encoding and xerces2 Java


Default value parameter in pure virtual function

Question: I submitted some code as:
Abstract class:
virtual void someFunction(std::vector<someObject*> & iObject) = 0;
virtual void someFunction(std::vector<someObject*> & iObject, bool aSwitch) = 0;

The first function was existing, I added the second to avoid having a default value parameter in a pure method.
Header in the derived class:
virtual void someFunction(std::vector<someObject*> & iObject);
virtual void someFunction(std::vector<someObject*> & iObject, bool aSwitch = false);

Usage as expected:
someFunction(std::vector<someObject*> & Object);

or
someFunction(std::vector<someObject*> & Object, true);

someFunction as it was - already existed, I added the switch.
It works well but I'm confused.
I have a code reviewer saying I should include a default value in the pure virtual function to avoid the two function signatures.  I remember reading that default values in pure virtuals are not a good idea but I can't argue a valid point and the articles dont seem clear as to why.
Would it cause ambiguity if I added the default value and if so would I still need the default value in the derived virtual method?
Could I just add the default value in the pure virtual function and do away with the first function in the derived class header?  What is the best practice here?
Comment: Related question about [default parameters and virtual functions](https://stackoverflow.com/questions/18105523/virtual-functions-default-parameters)
Comment: Just rename as someFunction1 and someFunction2 to make life easier.
Comment: Legacy code - cant do that.
Comment: At least the reader would be confused as they would be unsure which one was intended to call. It could be relying on the compiler. So follow your code reviewer's comment.
Comment: Best practice is to not mix default values with virtual methods, because it has confusing semantics.
Comment: @1201ProgramAlarm that doesnt address pure virtuals, only virtuals.
Comment: Note `Derived d; d.someFunction(obj_vec);` is ambiguous!
Answer: Default arguments in general
The default arguments for functions are not bound to the function itself, but to the calling context:  defaults declared for for the function in the scope in which it is called will be used (See C++ standard, [dcl.fct.default]).  For example:
void f(int a=1);     // forward declaration with a default value for the compilation unit
void f(int a)        // definition
{
    cout<<a<<endl;
}
void g() {
    void f(int a=2);  // declaration in the scope of g
    f();
}
int main() {
    f();            // uses general default => 1
    g();            // uses default defined in g => 2
    return 0;
}

Default arguments for virtual functions
This logic applies to all functions, so also the pure virtual functions. The only thing, is that the function declaration (and its defaults) that is considered is the one of the object class known by the compiler.  So the same function of the same object may have different default arguments, depending on the object type used to invoke it. For example:
struct A {
    virtual void f(int a=1) = 0;
};
struct B:A {
    void f(int a) override ;
};
struct C:A {
    void f(int a=2) override ;
};

void B::f(int a)        // definition
{
    cout<<"B"<<a<<endl;
}
void C::f(int a)        // definition
{
    cout<<"C"<<a<<endl;
}

int main() {
    B b;
    C c;
    A *x=&c, *y=&b;    // points to the same objects but using a polymorphic pointer
    x->f();  // default value defined for A::f() but with the implementation of C ==> C1
    y->f();  // default value defined for A::f() but with the implementation of B ==> B1
//  b.f();  // default not defined for B::f() so cannot compile
    c.f();  // default value defined for C::f(); ==> C2
}

Good to know

Default arguments don't alter the signature of the function.  It's still the same function.
Different default arguments don't affect the ODR rule.  So you could use different default values in different compilation units, and it would still be the same function.
The default arguments are provided by the caller, not by the function itself
If different default arguments are defined for base and derived classes, you need to be extremely careful, since different defaults might be used depending on how you call the function.
Comment: @solarflare yes.  Whenever several defaults are used, there is a risk of confusion.  In practice, most often a single default is defined in the header. This way,  the use of the default is very predictable (and easier to maintain).  For virtual functions it is tricky.  As you see, defining the default for the pure virtual is not sufficient.  But in practice, you may define the default in the header of the abstract class, and define the same default for all the overrides of the function.
Comment: This is pretty confusing tbh


Slim Php Mysql Put method empty value,want to update 4 column,but only 1 column is updated but result indicate success

Question: My goal is to update 4 column in my table in a single query.But end up only 1 column is updated,the other 3 is not.
My query is like this
$stmt = $this->conn->prepare("UPDATE users_info SET profile_image_path = ?,user_bio = ? ,gender = ?,date_of_birth = ? WHERE user_id = ?");
$stmt->bind_param("sssii",$profile_image_upload_url,$user_bio,$gender,$date_of_birth,$user_id);
$result = $stmt->execute();
$stmt->close();
return $result;

Here is my code for the query call
//update to database
global $user_id;
$db = new DBhandler();
$update_result = $db->callForQueryFunction($user_id,$user_bio,$date_of_birth,$gender,$profile_image_string);
$response = array();

if($update_result){
    $response['error'] = false;
    $response['message'] ="sucess";
}else{
    $response['error'] = true;
    $response['message'] ="fail";
}

After I run in advanced rest client ,with the the following query

user_bio=hihi&gender=f&profile_image_string=somestringhere&date_of_birth=2015-08-16

After run the query,the result is always "success",but in Mysql table only profile_image_path column is updated,the rest 3 column user_bio,date_of_birth and gender all are not updated.
Here is my database structure

I work for hours still haven't figure it out what's wrong with the code or my database structure.
Update:
I tried with bind_param for s with $date_of_birth,but still no luck with it
$stmt->bind_param("ssssi",$profile_image_upload_url,$user_bio,$gender,$date_of_birth,$user_id);

UPDATE
I actually using this example from Androidhive,the sample code is as below
       /**
     * Updating existing task
     * method PUT
     * params task, status
     * url - /tasks/:id
     */

$app->put('/tasks/:id', 'authenticate', function($task_id) use($app) {
            // check for required params
            verifyRequiredParams(array('task', 'status'));

            global $user_id;
            $task = $app->request->put('task');
            $status = $app->request->put('status');

But I use the same method as below to grab the value,but after var_dump() all the value is NULL.Here is my code
$app->put('/updateuserdetails','authenticate',function ()use ($app){

$user_bio  = $app->request()->put('userbio');
$gender    =$app->request()->put('gender');
$date_of_birth = $app->request()->put('dob');
$profile_image_string = $app->request()->put('profilestring');

I try this as well.The value of user_bio,gender,date_of_birth are all still null.
$app->post('/updateuserdetails','authenticate',function ()use ($app){

$user_bio  = $app->request()->post('userbio');
$gender    =$app->request()->post('gender');
$date_of_birth = $app->request()->post('dob');
$profile_image_string = $app->request()->post('profilestring');

I just cant figure out what is going wrong here
Update
After I test it in Postman by send data with x-www-form-urlencoded it come out with this error,which I cant get any solution
Comment: @ken Figured as much :-)
Comment: Use var dump to ensure your variables have the value that you think they do:
```var_dump($user_bio);```
```var_dump($gender);```
```var_dump($date_of_birth);```
```var_dump($user_id);```
Comment: @GreensterRox I using `put` method,why is it become null??
Comment: @Ken maybe post the code that shows how you are assigning these variables?? Are you using globals? e.g. $_POST ? I don't think that 'HTTP PUT' content is available using $_POST or $_REQUEST for example.
Comment: @GreensterRox actually I using Slim Framework.With update to server it use `Put` method.Wait I edit the question
Comment: @GreensterRox I update the question,feel free to take a look
Comment: @Ken are you using Postman to simulate the request?
Comment: @GreensterRox ya...postman
Comment: @Ken Take a look at http://stackoverflow.com/questions/23761425/get-put-params-with-slim-php
Comment: @GreensterRox i try as well..but it have  `Uncaught exception 'InvalidArgumentException'` error.Sir,I updated the question
Comment: for date_of_birth use `s` its of type date which will be string not inetger.  $stmt->bind_param("ssssi",$profile_image_upload_url,$user_bio,$gender,$date_of_birth,$user_id);
Comment: @Naincy I try this before,but the column still havent update.
Comment: by the way, why did you tag your question with pdo?
Comment: @YourCommonSense I tot is about pdo?sorry
Comment: @GreensterRox sir `$var_dump` and then get the value at where?I use Advance Rest Client
Comment: @GreensterRox wow..You help me noted that the 3 value is also null.thanks
Answer: Try the following:
$stmt = $this->conn->prepare("UPDATE users_info SET profile_image_path = :image, user_bio = :bio, gender = :gender, date_of_birth = :dob WHERE user_id = :id");

$stmt->bindParam(":image", $profile_image_upload_url, PDO::PARAM_STR);
$stmt->bindParam(":bio", $user_bio, PDO::PARAM_STR);
$stmt->bindParam(":gender", $gender, PDO::PARAM_STR);
$stmt->bindParam(":dob", $date_of_birth, PDO::PARAM_STR);
$stmt->bindParam(":id", $user_id, PDO::PARAM_INT);

$result = $stmt->execute();

$stmt->close();

return $result;

Comment: dob should be PARAM_STR
Comment: @Naincy - just noticed the mistake. Has been corrected.


How to make page.html.twig based on Vocabulary?

Question: I want to make different page.html.twig according to different Vocabulary.
 I found this code:
function THEME_NAME_theme_suggestions_page_alter(&$suggestions, &$vars) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
    $term = Term::load($tid);
    $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
  }
}

in How do I theme a taxonomy term page?.
Code does not work:

Fatal error: Class 'Term' not found in...

Excuse me, what is the reason, I really need to customize the page.html.twig according to the vocabulary, you can help me?
Answer: Because you have not included the PHP code that contains the Class.
See Namespacing in PHP.
According to term.php the name space is Drupal\taxonomy\Entity.
So you need to add use [name space]\[class name]; at the top.
Therefore, it would be use Drupal\taxonomy\Entity\Term;.
Example:
<?php

use Drupal\taxonomy\Entity\Term;

function THEME_NAME_theme_suggestions_page_alter(&$suggestions, &$vars) {
  if (\Drupal::routeMatch()->getRouteName() == 'entity.taxonomy_term.canonical' && $tid = \Drupal::routeMatch()->getRawParameter('taxonomy_term')) {
    $term = Term::load($tid);
    $suggestions[] = 'page__taxonomy__' . $term->getVocabularyId();
  }
}

Comment: No Sssweat,The problem is solved, thank you very much!
Comment: Thank you very much for your answer, you are a good person, but still do not understand, can not directly code, thank you very much!
Comment: @LIUJIAHUI Did you get it to work? If not working, did you get any errors? or ???
Comment: Very sorry, I was the first time to submit a question, I do not know where to choose...
Comment: Don't sweat it, welcome to Drupal Answers `:)`
Comment: For Drupal 9 you should to replace `$term->getVocabularyId()` for `$term->bundle()`


How to simulate, if a customer will buy

Question: If customer 1 will buy a product with a probability of 0.6 and every following customer  0.7, how can I simulate a system with n customers?
The result should show which customers bought and which didn't.
Maybe use a uniform distribution between 0 and 1 and see if the value is below the probability?
Answer: Generate $n$ independent uniformly distributed random variables between 0 and 1. If each variable is below the corresponding threshold, record this as a purchase. If it is above the threshold, no purchase.
Answer: Let $i=1,...,n$ and $X_i =1$ is customer $i$ buys and $X_i=0$ if not. Let $X_i \sim Bernoulli(p_i)$ with $p_1=0.7$ and $p_i=0.6$ for $i>1$.
You can simulate it by constructing the vector $p = (p_1,...,p_n)$ then draw $U=(U_1,...,U_n)$ uniform [0,1] variables and for each $i$ let
$$X_i = I[U_i<p_i]$$
which will have the property of being 1 with probability $p_i$ following from $Pr(U_i \leq r) = \int_0^r dt = r$.
You can do this in R for example
<code>N <- 100
p <- c(0.7,rep(0.6,N-1))
x <- as.numeric(runif(N)<p)
</code>

How to simulate, if a customer will buy


Javascript mouse event, drag and drop an image item in the html page

Question: I am using MacBook Pro and mouse is touchpad. I do not use physical mouse.
I am now exercising Javascript events programming. I suppose to make a toolbar, then I could drag and drop image item using Javascript mouse event. I wrote codes as below. Currently, I only implement the ball image could listen to mouse event. My purpose is to select the ball, then a new ball image could be created and put to the place where mouse is moved and released. I could create multiple balls and moved to the body of html page wherever I want.
The following codes could not invoke mouseup events. And the ball sticks to the mouse and could not be released/unattached.
Any help and hints?
Thanks in advance!

<!doctype html>

  <meta charset="UTF-8">

Drag image item from toolbar

Answer: I have to say the truth, I wrote codes by reference a book. And I modify the codes and there are bugs. I use chatGPT finally fix my bugs.
There are two mistakes in original codes. onmouseup shall not be ball.onmouseup, and also this function should be inside onmousedown function.
<!doctype html>

  <meta charset="UTF-8">

Drag image item from toolbar


Deployment pitfalls for VSTO and ClickOnce

Question: I am using Visual Studio 2010 with an Excel Workbook 2007 VSTO project.
It is using .NET 4 and the VSTO4 runtime.
I am using ClickOnce to publish this.
The prerequisites I have set are .NET 4, VSTO runtime, and Windows installer.. I have not included the Primary Interop Assemblies.
I have set this to download from the same location as my application.
After publishing when I get a user who has only .NET installed on their machine.. and they try to open the Excel Workbook to see what happens, they get an error of "The common language runtime could not be loaded... Contact an administrator"
I also tried running the "setup.exe" for this user and even clicking directly on the VSTO4 runtime installer and I got the message of "Do not have the required administrator privileges"
Can anyone confirm to me that the only way I can use a ClickOnce project for Office is for the user to have Administrator access?
Comment: Thanks do you want to add that as an answer? so I can mark it as such.
Answer: You need Admin rights to install prerequisites like the VSTO run time. The actual Add-In does not require Admin rights.


Replace keyup event action with click event action

Question: http://jsfiddle.net/2q8Gn/23/
Rather than have computedPageLinks update via the search input keyup event, can anybody help me amend the above fiddle so computedPageLinks updates via a button click event and doesn't update when the search input loses focus?
Comment: It's not my work. I've changed the question slightly to better explain (hopefully)
Comment: Fair enough, I've put together an answer with an updated fiddle for demonstration.
Answer: Since your search results are based on the value of query changing, even if you remove the valueUpdate: 'keyup' setting, that computed function will still update when the input box is blurred.
You can break that behavior by moving the "searching" out of the computed observable and instead populating a "results" observable array when the click occurs.
So, add a "results" array:
self.results = ko.observableArray([]);

And then add a search function we can trigger on click that populates the results:
self.search = function() {
    // Did the user search for anything?
    if (!self.query()) {
        self.results([]);
        return;
    }
    // Do the "search"
    self.results(ko.utils.arrayFilter(self.pageLinks(), function(item) {
        return item.title.toLowerCase().indexOf(self.query().toLowerCase()) >= 0;
    }) || []);
};

Now you can remove the computed observable, and change your binding to use the results array:

To link it all up, first remove the valueUpdate setting on your <input> and add a <button> that triggers the search function on your model:
<input placeholder="Search…" type="search" name="q" data-bind="value: query" autocomplete="off" />
<button type="button" data-bind="click: search">Go</button>

Demo


Can the integral get small outside a set with finite measure?

Question: Let $(X, \mathcal{A}, \mu )$ be a measure space and let $ f : X \rightarrow \mathbb{\overline{R}}$ integrable.
I just proved the fact that for every $\epsilon > 0$ we find $\delta > 0$ so that for every $A \in \mathcal{A}$ with $\mu(A)<\delta$ $$ \int_{A} |f| d\mu <\epsilon $$ holds.
Now I'm wondering if we can prove a similiar statement:
Let $\epsilon>0$. Then there exists $A \in \mathcal{A}$ with $\mu(A) < \infty$ so that $$ \int_{X \setminus A} |f| d\mu <\epsilon $$
Is it possible to derive this statement directly from the one mentioned first?
Answer: Yes.  Let $A_n = \{x : |f(x)| \ge \frac{1}{n}\}$.  Note that if $f$ is integrable we must have $\mu(A_n) < \infty$ (Markov's inequality).  The sequence $|f| 1_{A_n}$ converges to $|f|$ pointwise and is dominated by the integrable function $|f|$, so we have $\int |f| 1_{A_n} \,d\mu\to \int |f|\,d\mu$.  Subtracting, $\int |f| (1 - 1_{A_n}) \,d\mu= \int_{X \setminus A_n} |f|\,d\mu \to 0$.  In particular, for any $\epsilon$, there exists $n$ sufficiently large that $\int_{X \setminus A_n} |f| < \epsilon$.
Note that we do not need to assume that $(X,\mu)$ is $\sigma$-finite.  (In fact, the support of $f$ is $\sigma$-finite even if $X$ itself is not.)
Answer: This is true.  Just apply monotone convergence or dominated convergence to $|f|$ times the indicator function on $[-n,n]$.
Comment: Notice that the measure space is arbitrary.


Criar um servidor de background

Question: É bem simples, esse código funciona, porém apenas uma vez, depois da primeira vez que ele é iniciado nenhuma outra requisição é atendida, como se depois dele rodar uma vez o StreamSocketListener parasse.

public void Run(IBackgroundTaskInstance taskInstance)
{
    var deferral = taskInstance.GetDeferral();
    var detalhes = taskInstance.TriggerDetails as SocketActivityTriggerDetails;
    if (detalhes.SocketInformation.SocketKind == SocketActivityKind.StreamSocketListener &&
        detalhes.Reason == SocketActivityTriggerReason.ConnectionAccepted)
    {
        var list = detalhes.SocketInformation.StreamSocketListener;
        list.ConnectionReceived += async (sender, args) =>
        {
            using (DataWriter escritor = new DataWriter(args.Socket.OutputStream))
            {
                escritor.WriteString("HTTP/1.1 200 OK\r\nContent-Length: 2\r\nConnection: close\r\n\r\nOK");
                await escritor.StoreAsync();
            }
        };
    }
    deferral.Complete();
}

O registro da tarefa de background é feito com esse código:

private void Registrar()
{
    var tasks = BackgroundTaskRegistration.AllTasks;
    int quant = tasks.Values.Count(x => x.Name == "SocketActivityBackgroundTask");
    if (quant == 1)
    {
        task = tasks.Values.Single(x => x.Name == "SocketActivityBackgroundTask");
    }
    else
    {
        var socketTaskBuilder = new BackgroundTaskBuilder();
        socketTaskBuilder.Name = "SocketActivityBackgroundTask";
        socketTaskBuilder.TaskEntryPoint = "SocketActivityBackgroundTask.SocketActivityTask";
        var trigger = new SocketActivityTrigger();
        socketTaskBuilder.SetTrigger(trigger);
        task = socketTaskBuilder.Register();
    }
}

private async Task Iniciar()
{
    var sockets = SocketActivityInformation.AllSockets;
    if (!sockets.Keys.Contains(socketId))
    {
        StreamSocketListener socket = new StreamSocketListener();
        socket.EnableTransferOwnership(task.TaskId, SocketActivityConnectedStandbyAction.DoNotWake);
        await socket.BindServiceNameAsync(serverPort);
        await Task.Delay(500);
        await socket.CancelIOAsync();
        socket.TransferOwnership(socketId);
    }
}

O registro funciona e a tarefa vai pra o background, mas ela só funciona uma vez, e esse é o atual problema, porque o anterior foi resolvido mas esse foi criado.
Comment: Será que não quer dizer "Criar um SERVIÇO" ?
Comment: Agora a pergunta está clara o suficiente?
Comment: É que eu uso o StreamSocketListener para hospedar uma página Web, então por isso chamo isso de servidor.
Comment: Coloque o código de como é feita a chamada/registro do servidor/serviço
Comment: @rubStackOverflow Pronto, precisa de mais algum detalhe?
Comment: Agora ficou mais fácil de entender e tentar identificar o problema.
Answer: Não é tão simples, segundo a documentação além do uso de deferrals quando uma função assíncrona é realizada, também é recomendado:
(Re-register your background tasks during app launch.) ´Desregistrar` e registrar novamente uma tarefa durante o inicio da aplicação, dentre outras recomendações.
foreach (var cur in BackgroundTaskRegistration.AllTasks)
{
   if (cur.Value.Name != name) continue;
   cur.Value.Unregister(true);
}

Como o processo necessita ficar em execução, aparentemente o uso do deferral.Complete(); , faz a tarefa parar de responder as solicitações SocketActivityTrigger.
Preparei um exemplo funcional com as implementações mostradas aqui, o código fonte está no final da resposta.
Obviamente o código necessita ser melhorado mas demonstra o funcionamento de uma aplicação simples UWP cliente/servidor baseado na comunicação via sockets

Código Fonte:
https://github.com/rubgithub/ClientServerSocketUWP

Referencias:

https://docs.microsoft.com/en-us/windows/uwp/launch-resume/guidelines-for-background-tasks
https://social.technet.microsoft.com/wiki/contents/articles/36500.uwp-linux-socket-communication-handling-communciation-in-the-backgroundtask.aspx
https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/WebSocket
Comment: Nossa, que resposta completa, amanhã analisarei essa solução que você me mandou, caso tudo dê certo (estou implorando a Deus para que dê certo), criarei uma branch em minha solução para aprimorar seu projeto.
Comment: Infelizmente sua solução não funciona como eu esperava, sequer eu posso me conectar ao servidor.
Comment: Acredito que para o problema proposto na pergunta funcione. Agora se estiver enfrentando outro tipo de problema ou estive tentando algo que não esteja dentro do escopo da pergunta sugiro fazer outra pergunta.
Comment: O problema é que eu não consigo fazer com que o seu projeto funcione, simplesmente não funciona. Eu não consigo fazer o servidor receber uma requisição pelo Edge de jeito nenhum :(
Comment: Acredito que o gatilho `SocketActivityTask` não é disparado em requisições `HTTP`, ao menos nos testes realizados aqui. Recomendo fazer novas pesquisas e, se for o caso, complementar a pergunta ou fazer uma nova pergunta.
Comment: Ele é sim, pra tanto que no projeto da pergunta ele é disparado, mas só uma vez, porque acontece um erro se eu chamar o TransferOwnership.
Comment: Como seria a chamada via browser? Seria `http://localhost:123` por exemplo?
Comment: Eu usaria meu celular, e seria http://192.168.0.102:1337
Comment: Então... Alguma ideia de como ajeitar seu projeto, eu até tentaria ajeitar aqui, mas vou instalar agora o VS 2017.
Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/55781/discussion-between-rubstackoverflow-and-jaedson-barbosa).

Criar um servidor de background


How to read a file that is in use by other process?

Question: I have an application that have a log system that create a file and keep it handle with a TFileStream, that is created with this way:
FFileStream := TFileStream.Create(FFilename, fmOpenWrite);
Ok. When I try to open this file with notepad, no problem, with notepad++ no problem. When I try to load the file with other application that I created it raise my an error that says the file is in used by other process.
I tried TStringList, LoadFromFile and TFileStream.Create(LFile, fmOpenRea);.
Some one knows how I can read this like the notepad and notepad++?
Tks.
Comment: you need to use the sharing flags. Pass in fmShareDenyWrite to the constructor.
Answer: Erik got there first but uses fmShareDenyNone which would allow other processes to write to the same file. If you only want to allow reading by other processes, use:
FFileStream := TFileStream.Create(FFilename, fmOpenWrite or fmShareDenyWrite);

Comment: Keep in mind that Notepad doesn't *keep* a file open. It opens it only long enough to copy it into memory or dump it to disk. While you're editing, Notepad does not retain any handle on the file
Comment: Ok, it runs if I set it on my server, but how notepad and notepad++ do it?
Comment: They do it be ensuring that they use sharing options that make it clear they only intend to read the file and will allow other processes to write it while they are doing so. In order to achieve this, they use `fmOpenRead or fmShareDenyNone`. More information on the sharing options can be found in the help and of course on MSDN as the file sharing options are part of the file system which in turn is part of the OS.
Comment: Basically you use the sharing options to tell the file system how you want to open the file and what you will allow others to do when you have it open. If the file is already in use by another process and the sharing options set by that process are incompatible with the ones requested by you, your open will fail. Same applies when you are the first to open a file and another process opens it with sharing options incompatible with yours.
Comment: Marjan, I didn't understand. If i don't set this write flag on server, I'm not able to access the file, no matter if on my third application I set fmShareDenyWrite, like I said in the topic. So to do this I need to modify both of applications, but if I use notepad or notepad++ it's not necessary.
Comment: If you don't specify a sharing option, the default is fmShareCompat which "is compatible with the way that FCB's (File Control Blocks) are opened" (quoted from the help). Don't know what that means exactly, but it does mean that Notepad and Notepad++ are using a method of opening that is compatible with read-only access and FCB's.
Comment: Ok I'll study a little more about the answers, but notepad++ are able to read and write the archive.
Comment: @SaCi: Good idea (the study :-) Notepad++ may be able to write when you don't specify a sharing option (and thus use fmShareCompat), but it shouldn't be able to do so when you use fmShareDenyWrite. Although that may depend on the Delphi version as there was a bug in D2009 with regard to sharing options (don't remember the details).
Answer: Use fmOpenWrite or fmShareDenyNone to enable sharing.
Answer: I am using Delphi7 and I was experiencing, that TFileStream sometimes fail to open a file for reading, while it is only locked for writing. (Before one would start nagging about the sharing parameters of the TFileStream class; I know about them, and set them right.) While I was not yet able to find out the reasons of this clearly buggy behavior, I found that it can be worked around by using some other means of file handling:
While the file can not be opened with TFileStream - even with the right sharing settings (yes, I know what I am doing) - it could easily be opened using the appropriate WinAPI calls: CreateFile/ReadFile/SetFilePointer/CloseHandle wrapped in the Windows unit.


Is there a way to do a tone knob like effect with an acoustic without audio effects?

Question: I'm talking about adding or taking away treble progressively as a note rings.
You can ring a string unmuted and then slowly add muting as it rings, to give the impression of the treble decaying.  Is there a way to do the opposite, start with a string muted (or use a bass string version of the note) and then make it start being trebly without re-sounding the note, and without taking away too much sustain too quickly?
Here is a simulation of the ramp up I made on a computer, followed by the ramp down effect which I just played by progressively muting: http://vocaroo.com/i/s0dcsg4IwFN0
Doesn't have to be exact, but any technique like this?
Things I've tried:
Playing the string muted, but then clattering a finger nail on it a little, to add some brightness.  It's really hard (basically impossible so far) to get enough control of this, and also not stop the note ringing.
Playing the string muted, but then trying to progressively add fret buzz for the brightness.  This is also really difficult to have any control over, and to not cause the note to stop sounding.
edit:
After more experimentation, you can half do it with a slide, or maybe if you had a ring on your finger.  If you very briefly tap a ringing string with the metal, you'll introduce some brightness that stays with the string as it decays.  It's not progressive though.  You've got a muted string sound, and then you tap it, and the brightness is instant.  Another drawback is that this will change the pitch.  Probably doing it in key and very fast is better.
Comment: (stuffy old grouch alert) This sort of effect is essentially synthesizer work, as a plucked instrument (guitar, harpsichord, etc) is designed to produce only one basic frequency-amplitude vs. time curve.   Pipe organs OTOH are built to allow all sorts of dynamics and overtone control.
Answer: To increase the treble after sounding the note, there's no easy way of doing that.
Interfering with the string after sounding it is about the only way I can think of doing this, and as you've found it's hard to control.
Other possibilities would include using a bow, or an e-bow device, but these would produce something unlike the normal guitar sound.  (And the e-bow would be an electronic effect.)
One idea I just had is to try covering the soundhole with a spare hand (or holding the instrument behind an obstruction like a pillow) and see if uncovering it as the note decays can add treble.  This might produce an audible difference for the audience depending on where they are seated...
Answer: Well, getting the harmonics back into the string is not all that feasible.  You can instead try to get the fundamental out (touch the string very lightly at a flageolet position).
Another possibility is getting the harmonics temporarily away from the body of the instrument as that is the main transmitter and then admit them.  And you don't want to dampen them in the mean time as much as reflect them, or there will be nothing to admit.  So maybe pressing something made of hard rubber rather close to the saddle?  You'd need to experiment to figure out just what may make a dent in the harmonics rather then the fundamental as well.  Basically the idea is like with a violin mute, just in reverse.
But I'd not put too much hope into that approach.
Answer: Two things I have done which effect tone brightness with some kind of sustain:
Rotate the guitar around the axis of the neck so that the sound hole turns away/toward the listener. I've done this for a sort of tremolo effect, but if done slowly, it might imitate a tone swell. You must get a lot of volume at the start to make it work.
Finger a chord on the neck then pat the strings with the flat of your fingers or palm so that the impact sets the string vibrating. This is not exactly what you asked for, because it re-sounds the strings. But, you can control the brightness of tone by changing the force of the patting and closeness to the bridge. It can create


navigation drawer opens by pulling down other web blocks

Question: navigation drawer opens by pulling down other web blocks. when it closes blocks come up. additionally  drawer menu has occupied more space of my web sites top space. unable to keep blocks near the navigation bar. A big empty space there.  But drawer menu works fine.  how to solve this issue?
HTML

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>My web</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">

MY WEB

    A
    B
    C
    D
    E
    F

   Sigiriya
            From Wikipedia, the free encyclopedia

                Location    Central Province, Sri Lanka
            Coordinates 07°57′25″N 80°45′35″ECoordinates: 07°57′25″N 80°45′35″E
            Elevation   349 metres[1]
            UNESCO World Heritage Site
            Official name: Ancient City of Sigiriya
            Type    Cultural
            Criteria    ii, iii, iv
            Designated  1982 (6th session)
            Reference no.   202
            UNESCO Region   Asia-Pacific
            Sigiriya is located in Sri LankaSigiriya
            Location of Sigiriya in Sri Lanka
            Sigiriya or Sinhagiri (Lion Rock Sinhala: සීගිරිය, Tamil: சிகிரியா / aசிங்ககிரி, pronounced see-gi-ri-yə) is an ancient rock fortress located in the northern Matale District near the town of Dambulla in the Central Province, Sri Lanka. The name refers to a site of historical and archaeological significance that is dominated by a massive column of rock nearly 200 metres (660 ft) high.[citation needed]

            According to the ancient Sri Lankan chronicle the Culavamsa, this site was selected by King Kashyapa (477 – 495 CE) for his new capital. He built his palace on the top of this rock and decorated its sides with colourful frescoes. On a small plateau about halfway up the side of this rock he built a gateway in the form of an enormous lion. The name of this place is derived from this structure — Sīnhāgiri, the Lion Rock (an etymology similar to Sinhapura, the Sanskrit name of Singapore, the Lion City).

            The capital and the royal palace was abandoned after the king's death. It was used as a Buddhist monastery until the 14th century.[2] Sigiriya today is a UNESCO listed World Heritage Site. It is one of the best preserved examples of ancient urban planning.[3]

CSS
header, nav {
 background-color: #06C;font-family:'Open Sans';
}

header {
  width: 100%;display:flex;align-items:center;
  height: 80px;color:#FFF;justify-content:flex-start;
} /* we use flex display to position the hamburger icon on the side of the AndroiCSS h2 element */

#hamburger {
  cursor: pointer;
} /* add the small hand cursor pointer to indicate this element is clickable; it triggers the jQuery on click */

header * {
  margin: 0 15px;
}

.fa-bars, header h2 {
  font-size: 28px!important;
}

header h2 {
  font-weight: 400!important;
}

nav {
  display: flex;flex-direction:column;width:0;align-items:center;
  transition: width 0.2s ease;
}

nav.open {
  width: 250px;
  height: 100%;
}

nav.close {
  width:0;
}

nav * {
  color: #FFF!important;font-family:'Open Sans';font-size:20px!important;margin-right:15px;
}

nav a {
  text-decoration:none!important;
  border-top:2px solid gray;width:100%;text-align:left;display:flex;align-items:center;justify-content:center;height:55px;
}

nav a:hover {
  background-color:rgba(0, 0, 0, 0.1);
} /* this changes the bg color on hover over the nav element */

Javascript
$("#hamburger").click(function(){
  $("nav").toggleClass('open', 'close');
});

$("a").click(function(){
  $("nav").toggleClass('open', 'close');
});

Comment: Would you be able to create this example as a Snippet? It would make it easier to see what is going on.
Comment: @aksl ok i will have a look at this issue
Answer: Just give an absolute positioning to your header and nav and add this code to your header and nav CSS:
header {
position:absolute;
top:0;left:0;
}

nav {
position:absolute;
top:80px /* which is the height of header... */
left:0;
}

also you can add a wrapping div to your text elements like this :

and then add this css code
.text-c {
  margin-top:150px;
}

working codepen https://codepen.io/larrytherabbit/pen/qBNZpjZ
Comment: glad i could help. dont hesitate if you are stuck again


A-frame set sphere color to variable

Question: I am trying to figure out a way to take a sphere in my scene and set the color of the sphere to a variable. How can I achieve this? I would also like it to update so for example, if a button is pressed and the variable changes to a different color then the sphere's color will change too.
Here is my markup for the sphere:

What I would like is to set the color of that sphere to a variable called color. How can I achieve this?
Comment: check [this](https://stackoverflow.com/questions/67524575/a-frame-set-jump-height-to-a-variable) thread
Answer: you can try something like this

    <button style="position:fixed;z-index:999" onclick="colorChange()">Color change</button>

once you click on the change button it randomly generates you a color and sets the color attribute with the randomly generated value

A-frame set sphere color to variable


CDN Fallback for Dependant Scripts

Question: If I am using the following scripts:

jQuery
jQuery Validation
jQuery Validation Unobtrusive
Bootstrap

Bootstrap and jQuery Validation require jQuery and jQuery Validation Unobtrusive requires jQuery Validation so we have interdependent scripts. The fallback scripts I have seen all look something like this:
<code>(window.jQuery || document.write('<script src="/bundles/jquery"><\/script>'));
($.validator || document.write('<script src="/bundles/jqueryval"><\/script>'));
($.validator.unobtrusive || document.write('<script src="/bundles/jqueryvalunobtrusive"><\/script>'));
($.fn.modal || document.write('<script src="/bundles/bootstrap"><\/script>'));
</code>
The problem is that if I am using the ajax.aspnetcdn.com CDN and it fails, then the first line will cause jQuery to be loaded locally but the next three lines of code will execute before that and error because $ is undefined.
Is there a standard way to handle these types of interdependent fall-back scripts? I have looked around and can't find a resource for handling this type of scenario.
UPDATE
I answered the question as best I can but I'm still looking for an answer on how people handle this.
Answer: It seems overkill to rely on yet another third party script but I have discovered Fallback.js and YepNope.js which may be able to handle this scenario. I am not sure about the performance implications of the everyday scenario where the CDN's just work. More info here.
I also had a go at writing my own implementations:
JavaScript Fallbacks
<code>(function (document, fallbacks) {

    var check = function (fallbacks, i) {
        if (i < fallbacks.length) {
            var fallback = fallbacks[i];
            if (fallback.test()) {
                check(fallbacks, i + 1);
            }
            else {
                var script = document.createElement("script");
                script.onload = function () {
                    check(fallbacks, i + 1);
                };
                script.src = fallback.src;
                document.getElementsByTagName("body")[0].appendChild(script);
            }
        }
    }
    check(fallbacks, 0);

})(document, [
    { test: function () { return window.Modernizr; }, src: "/js/modernizr.js" },
    { test: function () { return window.jQuery; }, src: "/js/jquery.js" },
    { test: function () { return $.validator; }, src: "/js/jquery-validate.js" },
    { test: function () { return $.validator.unobtrusive; }, src: "/js/jquery-validate-unobtrusive.js" },
    { test: function () { return $.fn.modal; }, src: "/js/bootstrap.js" },
    { test: function () { return window.Hammer && window.Hammer.VERSION; }, src: "/js/hammer.js" },
    { test: function () { return window.Zepto; }, src: "/js/bootstrap-touch-carousel.js" }
]);
</code>
CSS Fallbacks
The idea for using a meta tag was 'borrowed' from the new ASP.NET 5 MVC 6 framework.
<code>(function (document, fallbacks) {

    var metas = document.getElementsByTagName("meta");

    for (var i = 0; i < fallbacks.length; ++i) {
        var fallback = fallbacks[i];

        for (j = 0; j < metas.length; ++j) {
            var meta = metas[j];
            if (meta.getAttribute("name") == fallback.metaName) {
                if (!fallback.test(meta)) {
                    var link = document.createElement("link");
                    link.href = fallback.href;
                    link.rel = "stylesheet";
                    document.getElementsByTagName("head")[0].appendChild(link);
                }
                break;
            }
        }

    }

})(document, [
    {
        // metaName - The name of the meta tag that the test is performed on. The meta tag must have a class from the
        //            relevant stylesheet on it so it is styled and a test can be performed against it. E.g. for
        //            font awesome the <meta name="x-font-awesome-stylesheet-fallback-test" class="fa"> meta tag is
        //            added. The 'fa' class causes the font awesome style to be applied to it.
        metaName: "x-font-awesome-stylesheet-fallback-test",
        // test - The test to perform against the meta tag. Checks to see if the Font awesome styles loaded
        //        successfully by checking that the font-family of the meta tag is 'FontAwesome'.
        test: function (meta) { return meta.style.fontFamily === "FontAwesome"; },
        // href - The URL to the fallback stylesheet.
        href: "/css/font-awesome.css"
    }
]);
</code>

CDN Fallback for Dependant Scripts


Guitar support for Yamaha SLG200NW

Question: I bought a silent guitar Yamaha SLG200NW around 6 months ago. I like it very much. However, there is one thing that doesn't allow me to fully enjoy practising on that guitar. I cannot find a proper position. In classical position (on the left leg) the upper part of the guitar's frame pushes against my sternum bone making it hurt. In the position when the guitar is on the right leg, I have to bend too much even though I use a footstool in the most upper position, so now I have pain in my back. I also tried a strap, it didn't go very well eighter.
I tried to find a guitar support, but couldn't due to the very thin body frame of the guitar. The width of the bottom frame is 28mm, and the width of the horn is 21mm.
Does anybody use any guitar support while playing this guitar?
Answer:
Try playing with strap while standing. Might be more comfortable and make you slouch less than sitting position.

In addition to the footstool you can put guitar "cushion" or "pillow" support on your leg. They don't attach to the guitar, so should work with an instrument of any thickness.

It's rare, but some musicians use a guitar supports which stand on the ground, thus don't require you to support the instrument by yourself. I found this example link: https://vikingguitarstands.com/ but I have no knowledge of this specific company and their products.

Electric guitar support. I'm aware of this product: https://guitarscientist.com/performaxe/ but again, I have never used it, and I don't know if it would work with the frame of Yamaha Silent.

Guitar support for Yamaha SLG200NW


Transferring files between two windows PCs programatically

Question: I have a build server running windows 7 and an amazon test server running windows server 2012.
When I execute my build process which outputs a WAR file I then want to move this to a specific location on my test server for testing.  Currently I just drag and drop the WAR file onto my test server.  I want instead to be able to do this programatically via a powershell script.
I use TFS for my build process. Is this possible without having to install an FTP server on my test server?
Comment: Can you just network share the destination you want to move it to?
Comment: Or maybe: https://blog.ipswitch.com/use-powershell-copy-item-cmdlet-transfer-files-winrm
Comment: The two PCs are not on the same domain,  can I still copy files via shared folder?
Comment: Which version of TFS are you using? Can you access your test sever from build server?
Comment: Hey Cece,  yes ,  that worked,  thanks,  answer accepted :)
Answer: Your requirement can be achieved by adding Windows Machine File Copy task in your build definition. You can use this task to copy application files and other artifacts to remote machines:

If you want to use powershell script, you could refer to this blog:

If you are using the PowerShell 5.0, now the Copy-Item command
  supports copying files from one machine to another through -ToSession
  and -FromSession parameters. As the name suggests, the -ToSession
  parameter expects a session with the destination computer where the
  file will be copied. Check the following example:
<code>$Session = New-PSSession -ComputerName PowerShellAzureMachine -Credential $cred
Copy-Item -Path C:\temp\localfile.txt -Destination C:\localfile.txt -ToSession $session
</code>


Higher Test Scores but Higher Variance?

Question: I am tuning hyper-parameters using 5-fold cross-validated grid search for various multiclass classifiers, and I keep running into the same issue that I can't quite wrap my head around.
The hyper-parameter configurations achieving the highest "test score" often have extremely low training error - suggesting overfitting.

The table above shows my results for tuning a decision tree, the test score of the configuration shown in the top row is slightly higher, but the train score is much higher. Obviously in this case the test scores are so close together that I can use either, but sometimes the difference is larger.
Plotting learning curves for each of the two configurations shown above makes the difference in variance very noticeable:

I'm having a hard time understanding why this is happening, and also reasoning which classifier is "better". If lower variance is the goal, should I be choosing the classifier configuration that produces the best test score, where the difference in train/test score is within a limit?
P.S. The same behaviour is shown for the results of an SVM - very high C values massively overfit (1.0 train scores) but tend to have better test scores than the classifiers with lower C values.
Comment: See also https://datascience.stackexchange.com/q/66350/55122
Answer: Based on your screenshot 1, model depths are 10 and 20 and min sample split are 2 and 3.
If you have small number of columns (e.g. <10), it is likely that decision trees are not split further because it is already built-up before hit the depth restriction.  Hence max depth parameter has no effect on overfitting control.
Similarly, the min sample split is only 2 or 3, which means leaves will not be split further if obs number is less than 2 or 3.  Hence, your tree models put nearly each obs in each of leaves, which is over-fitted.  This may also be the reason that your training set score is about 0.99 when min sample split is 2 (assume this is the measure of accuracy that 1 means no errors).
No sure about the which model both plots are related to, hence I'd assume top plot is related to model 42.  After depth decreases to 10 and min sample split increase (a little bit) to 3, you can see that train score decreases while cross validated score increases which make more sense in terms of their moving direction. This is because better parameters chosen to control overfit.
Possible Solutions:

Decrease tree depths depending on number of variables and your current model (42 and 36) actual tree depth.
Increase min_sample_split to 20 or 30.  This is to make your classifier more general as oppose to fit to individual obs.
Try random forest method which builds lots of trees (lots of weak learners to strong learner).
Comment: Trees can split multiple times on each continuous feature, so the second paragraph here seems erroneous.

Higher Test Scores but Higher Variance?


Continuously shift "selected" vertices in a graph so that none get squished.

Question: Suppose that we are doing a computer simulation of a dwarf kingdom. There is an underground
labyrinth of some shape and size, inhabited by some number of dwarves. Every dwarf is arbitrarily
moving around, but at all times obeying two laws of dwarf physics:

The movement of dwarves must be continuous.
The amount of dwarves must remain constant.

Given a specific setting of dwarves in a labyrinth, what can I know of their locations at some
point in the future?

One formalization I can invent — follows:
$\textbf{definition}\quad$ Given a graph $G = (V, E)$ with some "selection" of vertices $S
\subset V$, $S' \subset V$ is a "shift" of $S$ if they can be put into 1:1 correspondence so
that the corresponding vertices are no more than 1 edge apart. $\square$
Then I ask whether we can enumerate all possible shifts of a given selection, and the number of
ways each shift may be attained. This would allow us to probabilistically precompute the outcome
of any number of shifts.
But I also see some analogy with, should I say, fluid dynamics: there are tangible, distinctly
painted particles floating around in a continuum, obeying the same laws of continuity and
preservation stated above — like some droplets of oil in a bowl of soup. Could this line of
reasoning lead a more educated person than myself to some interesting quantitative results?
Is there some deep generalization here waiting to be discovered?

P.S.   I have accepted an answer because it is actually an awesome solution to the problem in the formulation I had put forward. But I am still looking for some kind of unification with the continuous.
Comment: I don't see what your graph definition has to do with the dwarf movement. Presumably you want to have the dwarf at vertex $v$ travel continuously along edge $e$ to vertex $v'$ if $v'$ is the "shift" of $v$ and they are separated by edge $e$. But this is a much stricter kind of movement than you initially described.
Comment: @kccu I am not sure I see what kinds of movement you have in mind that are completely at odds with some plausible extension of the graph definition I offer.
Comment: Anything that's not a union of straight lines?
Comment: @kccu Edges may represent arbitrarily short segments of the ways in the labyrinth, thus giving us arbitrary approximation to the real situation. We can always cut an edge into smaller edges and simulate more precisely; we can have multiple parallel edges or weighted edges to represent the width of the hallways, and weighted vertices to represent the expanse of the halls. I do not argue that this is the best and only representation of a dwarf kingdom possible, it is just that I can see how to make it work. I welcome any other way to put this situation in computable terms.
Comment: Then you're talking about a huge graph, which is going to make computation and enumeration very difficult. Honestly this question is too broad for MSE. Without more assumptions, you can't say anything about the dwarves' future positions - anything is possible, and there is no way to say what is more or less likely since you have not made any assumptions about what is probable/improbable.
Comment: @kccu? Too broad? The question is a very concrete question about specific computation in graphs.
Answer: The problem boils down to enumerating perfect matchings in a bipartite graph.
For a set $S \subseteq V(G)$, construct an auxiliary bipartite graph - not quite a subgraph - as follows:

On one side ($A$), you have all the vertices in $S$.
On the other side ($B$), you have all the vertices of $G$ adjacent to $S$. If there are vertices of $S$ adjacent to $S$, they appear on this side, again.
Put an edge between the two sides whenever that edge appears in $G$.

We should have $|A| \le |B|$ if there is any way for the dwarves to successfully move. Of course, you may allow the dwarves to sit still (approximating continuous motion along a path that goes nowhere), in which case all of $S$ is contained in $B$ as well, and this is guaranteed to hold.
A possible transition of the dwarves is a matching in this bipartite graph that saturates the vertices in $A$. Many people thinking about these problems like perfect matchings, which saturate both sides; we can obtain this by adding $|B|-|A|$ artificial vertices to $A$, which are adjacent to all of $B$. The artificial vertices will get matched to vertices of $B$ that are not the destination of any dwarf.
Unfortunately, counting perfect matchings in a graph is hard in general. This is one of the #P-complete problems: the equivalent of NP-complete, for counting problems rather than for decision problems.
Fortunately, we can go through all the perfect matchings in a way that takes $O(|S|)$ time per matching. This paper suggests several ways to do it. The problem is difficult mainly because there could be exponentially many perfect matchings. If you happen to have a dwarven network where the number of shifts is small for each $S$, then enumerating the shifts will not take long.
Finally, if you want to predict the dwarves' short-term state, this is going to be very hard with this approach, because the number of possible $S$ grows very quickly. However, long-term, the stationary distribution is relatively easy to describe: the probability of the dwarves occupying a set $S$ will be proportional to the number of shifts out of $S$.
Comment: @DanielWagner The stationary distribution is a distribution over *states*, not over dwarves. It assigns to each state (a subset $S \subseteq V$) a probability.
Comment: This is awesome. How did you arrive to the last point, about the long-term state?
Comment: This is true of any symmetric random walk, where all transitions from a state are equally likely and where if you can go from $S$ to $S'$ then you can go from $S'$ back to $S$.
Comment: Can you advise me some literature where this is covered?
Comment: See for instance [these lecture notes](http://web.cs.iastate.edu/~pavan/633/lec7.pdf). Equation (1.11) is the claim I'm referring to.
Comment: N.B. The stationary distribution may never actually be reached. For example, consider the complete graph on two nodes; the stationary distribution has half a dwarf on each node, which obviously isn't actually achievable except by averaging over multiple time steps.
Comment: (We still should worry about periodicity. But if we take my suggestion and allow a dwarf to stay put from one time step to another, then we are aperiodic.)
Comment: Sure, stated more precisely, the stationary distribution is a 50-50 split between the states "the dwarf is on A" and "the dwarf is on B". But starting from any concrete (non-probabilistic) initial setup and taking random steps, the only two distributions we ever reach are "100% probability of the dwarf being on A" and "100% probability the dwarf being on node B"; we never reach the stationary distribution, nor even converge towards it.
Comment: @DanielWagner Right; I'm saying that if we allow dwarves to stay put as one possible transition, we do reach the stationary distribution. (And if we don't allow dwarves to stay put, then there are other cases which are more problematic: cases where the dwarves are getting squeezed into a small set and have nowhere to go.)


Strange PATH when use sudoers via ldap

Question: I have a working LDAP authentication environment. LDAP server is on ubuntu 12.04 machine while client are all centos 6.4 machines. Recently I configure sudoers in LDAP following this article http://www.malaya-digital.org/configure-ldap-for-sudo-support-in-ubuntu-server-11-04-64-bit/
Everything works fine except that the PATH is strange when using sudo to execute command.
Here are the PATH of sudo
# sudo printenv PATH
"/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

It seems that every commands listed in the PATH shown above can be executed, except which in /bin . For example
# sudo which node
/usr/local/bin/node

# sudo which zip
/usr/bin/zip

# sudo which ip
/sbin/ip

# sudo which ls
which: no ls in ("/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin") #WTF??

# sudo ls /
sudo: ls: command not found

However, when using full path to execute command in /bin, it works.
# sudo /bin/ls /
bin  boot  dev  etc  home  lib  lib64  lost+found  media  mnt  NFS  opt  proc  root  sbin  selinux  srv  sys  tmp  usr  var

I have read Problems with sudo in path and Troubleshooting sudoers via ldap, but find no clue of what's wrong.
The LDAP entry with PATH setting is as follow:
dn: cn=defaults,ou=SUDOers,dc=example.dc=com
objectClass: top
objectClass: sudoRole
cn: defaults
description: Default sudoOption's go here
sudoOrder: 1
sudoOption: env_reset
sudoOption: secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

Comment: Related: [Why are PATH variables different when running via sudo and su?](http://unix.stackexchange.com/q/8646/21471) at Unix
Answer: I came to the same problem today and I believe that the solution is simply to remove the double quotes from the secure_path option:
dn: cn=defaults,ou=SUDOers,dc=example.dc=com
objectClass: top
objectClass: sudoRole
cn: defaults
description: Default sudoOption's go here
sudoOrder: 1
sudoOption: env_reset
sudoOption: secure_path=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

By surrounding it by quotes, as you can see in the result of sudo printenv PATH, the PATH contains the quotes themselves.  This seems to correspond to one funny long path, in which directory names contain colons --- not what you want...
Your answer seems to circumvent the problem, probably because the colon at the end has the special meaning of appending some default path.  Try sudo printenv PATH to see what's going on --- it did not work in my case.
With the LDIF that I propose above, what you get is the right PATH:
$ sudo printenv PATH
/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

Comment: I've run into this problem as well today - this fixed it! Thanks! +1
Answer: I found the solution myself, though I do not know exact why.
It is quite simple, add ":" to the end of the secure_path in LDAP entry fixed all the problem.
secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:"

Comment: I believe that this answer does not work properly.  The colon at the end may be appending the default path.  I tried it and could not execute anything in `/usr/local/sbin`, which apparently is not in the default path.
Comment: What @nickie said. You might want to change the accepted answer accordingly.

Strange PATH when use sudoers via ldap


Does a run count on a passed ball on a third strike?

Question: Under the following scenario would the run count?
With a runner on third and 2 outs, the batter swings and misses the third strike and the catcher does not catch the ball. Further the runner on third crosses home plate before the batter is either tagged out or out via a putout at first base?
Does the general rule that a run doesn't count if the batter is out at first base apply or does it count because the runner is deemed to have scored because it is considered a stolen base?
Comment: It will be counted as a run
Comment: If the batter is tagged out, or the ball is thrown to first getting the runner out before he reaches the base, I don't believe the run would count, as it becomes a force play with the batter running to first.  But I could be wrong on that, so I won't post it as an answer.
Answer: The run does not count if the batter does not safely reach first.  It does count if the batter does safely reach first.
From the 2016 MLB Rulebook:

5.08 (4.09) How a Team Scores

(a) One run shall be scored each time a runner legally advances to
    and touches first, second, third and home base before three men
    are put out to end the inning.

EXCEPTION: A run is not scored if the runner
      advances to home base during a play in which the third
      out is made (1) by the batter-runner before he touches
      first base; (2) by any runner being forced out; or (3) by
      a preceding runner who is declared out because he
      failed to touch one of the bases.

And then how an out is made:

5.09 Making an Out

(a) (6.05) Retiring the Batter
A batter is out when:

...
(10) After a third strike or after he hits a fair ball, he or first
      base is tagged before he touches first base;

Note how they group "after a third strike" with "hits a fair ball".  (The normal third-strike scenario is covered earlier in the list, so it's clear that this is only a dropped third strike situation.)  A dropped third strike with two outs or with first base open is essentially identical to a ball in play as far as the rulebook is concerned.
In fact, a further example of this is made clear in the rules, which while not this case is quite similar and addresses the "stolen base" part of your question directly, in 5.09 (14):

(14) With two out, a runner on third base, and two strikes on
      the batter, the runner attempts to steal home base on a
      legal pitch and the ball touches the runner in the batter's
      strike zone. The umpire shall call "Strike Three," the batter
      is out and the run shall not count; before two are out,
      the umpire shall call "Strike Three," the ball is dead, and
      the run counts;

Similar to the scenario you ask about, the run does not count not because of the action of the runner (he's hit by a pitch, which is not something that makes you out) but because the batter is out.


How to understand "factor loadings" in PCA?

Question: I have seen that some people are talking about "factor loadings" in PCA. It is a topic that I do not manage to understand, despite some googling.
I managed to obtain some code that generates the following plot (for 9 different "elements"). But I cannot interpret the results.
Comment: Perhaps these existing Q&A might help you https://stats.stackexchange.com/questions/92499/how-to-interpret-pca-loadings?rq=1 and https://stats.stackexchange.com/questions/2691/making-sense-of-principal-component-analysis-eigenvectors-eigenvalues?noredirect=1&lq=1
Comment: These seem to be eigenvectors, not "loadings".
Answer: I believe your two plots are factor loadings given by PCA for the first two principal components.

The bar represents the magnitude for each variable "loaded" on the latent component
The bar also represent whether the loading is positive or negative

Based on the plots, I can see variable 4 and 6 are highly loaded on PC 1. Thus, we can say the variable 4 and 6 are similar on the PC 1. There must be something in the original data set that makes variable 4 and 6 similar. Note that all loadings on PC 1 are positive
We can also see variable 6 continues to dominate the PC 2. This is a variable you might find useful for modelling. A few variables are now negatively loaded on PC 2, but they are all less than 0.5.
Although variable 4 and 6 are highly loaded on the first PC, they are not exact copy of each other.
Variable 7, 8 and 9 might not be very important for your analysis because they have low factor loading on both plots.
When you do PCA, you should also get the variance explained by each PC.
Comment: When you say "factor loadings", do you mean "PCA eigenvectors"?


Finding the sum of $5$ angles given equivalent division of a side

Question: Let $ABC$ be an isosceles triangle with $AB = AC.$ Point $D$ lies on segment $AB$ so that $AD = AB/6.$ Points $E_1, E_2, E_3, E_4,$ and $E_5$ lie on segment $BC$, in this order from $B$ to $C$, and they divide it into six equal parts. Find $$\angle AE_1D + \angle AE_2D + \angle AE_3D + \angle AE_4D + \angle AE_5D$$ in terms of $\angle A$.

I have experimented with this problem using a Geogebra diagram and concluded that the answer was $\angle A / 2$, but I am completely unsure how to start on this problem since I can't find any useful common angles.
Answer: Note that, by symmetry, $$\angle AE_1C+\angle AE_5C=\pi$$ $$\angle AE_2C+\angle AE_4C=\pi$$ $$\angle AE_3C=\frac{\pi}{2}$$
Therefore $$\sum \angle AE_iC=\frac{5\pi}{2}.$$
Now notice that triangle $DBE_5$ is similar to triangle $ABC$. By the same argument as above we have:
$$\sum \angle DE_iC=\angle DE_5C+2\pi=3\pi-\angle C.$$
Thus $$\sum \angle AE_iD=\sum \angle DE_iC-\sum \angle AE_iC=\frac{\pi}{2}-\angle C=\frac{1}{2}\angle A.$$
Answer: For convenience, let $\alpha = \angle A$, $\beta = \angle B = \angle C = \frac{\pi - \beta}{2}$, $x = AD$, and $y = \frac{BC}{6}$.  We want to find $\epsilon_k = \angle AE_kD$ for $k \in \{1, 2, 3, 4, 5\}$.
Set up a coordinate system with $B = (0, 0)$ and $C = (6y, 0)$, and it follows that $A = (7x \cos \beta, 7x \sin \beta)$, $D = (6x \cos \beta, 6x \sin \beta)$, and $E_k = (ky, 0)$.  Then:

$DE_k = \sqrt{(6x \cos \beta - ky)^2 + (6x \sin \beta)^2} = \sqrt{36x^2 - 12kxy \cos \beta + k^2y^2}$

$AE_k = \sqrt{(7x \cos \beta - ky)^2 + (7x \sin \beta)^2} = \sqrt{49x^2 - 14kxy \cos \beta + k^2y^2}$

Knowing the lengths of all three sides of $\triangle AE_kD$ (the other side is just $x$), you can use the Law of Cosines to solve for $\cos \epsilon_k$.  However, when I attempted to do this, I got a bunch of tedious algebra, so maybe there's an "obvious" trick to make things simpler.


Pegar sql Hibernate

Question: Bom dia.
Estou com o seguinte problema, necessito pegar o sql executado pelo hibernate e salvar em uma string.
Porem não tenho ideia de como fazer isso, alguém poderia dar uma ajuda?
Comment: Você precisa que seja impressa no console ou precisa salvar mesmo numa variável? O que você precisa fazer com essa informação?
Comment: Necessito salvar em uma String. Pois depois tenho que gravar ela no banco, para um sistema de Log.
Comment: Já que é para logs recomendo usar log4j. Dá uma olhada no artigo: https://www.mkyong.com/hibernate/how-to-configure-log4j-in-hibernate-project/
Comment: Então eu usei o log4j e o p6spy, porem eles não atende minha necessidade. teria q pegar em tempo de execução o SQL.
Comment: Tá usando Query em todas as consultas do hibernate? Se tiver pode chamar o método getQueryString() para cada query.
Comment: Vai funcionar sim quando e um select, no meu caso tenho que pegar(update, insert e delete), porem estou usando a session para fazer isso (session.save(obj)).
Comment: Nesse caso não usaria o session, mas sim o query.executeUpdate(). Aí vale a mesma resposta que já postei. Agora tem que ver o impacto de utilizar dessa forma.
Comment: Obrigado, Giuliana deu certo :)
Answer: Utilizando org.hibernate.Query do Hibernate (que é a prática mais comum quando alguém desenvolve consultas usando Hibernate) é possível recuperar a string da query utilizando o método getQueryString():
org.hibernate.Query query = session.createQuery("from Entidade where id= :id ");
query.setParameter("id", "1");
String queryString = query.getQueryString();

Você só vai precisar persistir a variável queryString no teu banco de logs.
Referência: https://antoniogoncalves.org/2012/05/24/how-to-get-the-jpqlsql-string-from-a-criteriaquery-in-jpa/
Comment: Pode adicionar um exemplo para que o link seja apenas referencia?
Comment: Sim, vou adicionar aqui!
Answer: Você pode criar um appender específico para o log de SQLs gerados pelo Hibernate e fazer com que este log salve os SQLs em um arquivo específico. Um arquivo diferente será gerado por dia, graças ao DailyRollingFileAppender:
log4j.properties
log4j.logger.org.hibernate=INFO, hb
log4j.logger.org.hibernate.SQL=DEBUG
log4j.logger.org.hibernate.type=TRACE
log4j.logger.org.hibernate.tool.hbm2ddl=warn
log4j.logger.org.hibernate.hql=debug
log4j.logger.org.hibernate.jdbc=debug

log4j.appender.hb=org.apache.log4j.DailyRollingFileAppender
log4j.appender.hb.layout=org.apache.log4j.PatternLayout
log4j.appender.hb.Threshold=TRACE

log4j.appender.hb.RollingPolicy=org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.hb.RollingPolicy.FileNamePattern=log/sql-gerado-pelo-hibernate-%d{yyyy-MM-dd}.log

No seu persistence.xml ou hibernate.cfg.xml
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>

Altere log/sql-gerado-pelo-hibernate.log para o diretório e arquivo que desejar. Se quiser salvar na pasta /tmp (se estiver no Linux), pode usar /tmp/sql-gerado-pelo-hibernate.log.
Precisa testar o código acima (fiz baseado neste e neste).
Como é gerado um arquivo diferente por dia, você pode depois ler o arquivo do dia anterior, recuperar todo o conteúdo dele e salvar no banco de dados. Nesse meu exemplo você não estará lendo o arquivo ao mesmo tempo que o Log4j estará gravando. Você até pode tentar isto se quiser, mas precisará controlar na leitura do arquivo o que você já leu e não leu ainda, antes de salvar no banco de dados.

Pegar sql Hibernate


AngularJs directive naming conventions

Question: When angularJs directive is defined, we have to name it in form of 'camelCase' syntax but when we use it, we have to name it in form of 'camel-case'. Question is why this is required ?
I know that it is for avoiding naming conflicts(now/in future) but why we have to name it differently while defining and while using. Can't we define it directly in form of 'camel-case' ?
Answer: There are two reasons why it's important.
First of all, HTML attributes are not case sensitive, meaning that "someName" and "somename" is the same attribute. So the best style is to use "kebab-case" notation to separate words in attribute name. That's why we use "attribute-name" syntax for HTML attributes and tag names.
On the other hand, kebab-case names are not valid identifiers in Javascript so in order to use such names as Angular directives we would have to use verbose bracket notation. But since in Javascript world camelCase is standard de-facto for naming variables and object properties, Angular uses normalization (see source) to convert kebab-case names to camelCase, and vice versa.
Comment: Thanks a lot dfsq. Makes sense!
Comment: Now angularjs master branch is far from it was that time you made the reference. That's why now the reference actually gives nothing to a reader. To avoid this, please, make references to a repository not at master branch, but better at a specific commit state.
Answer: Directives must have camel case names (for instance, fooBarDirective) because AngularJS converts camel case directive names to hyphen case .For instance
<foo-bar-directive>

or
< ...  foo-bar-directive>

for use in HTML(which is case insensitive).

AngularJs directive naming conventions


convert lowercase to uppercase first character and make other chars stay lower

Question:  void correcter(string s, int j)
{
    string correct;
    for (; j < s.length(); j++)
    {
        if (int(s[j]) != 46){
            if (int(s[j]) >= 97 && int(s[j]) <= 122 && i == 0)
            {
                char a = int(s[j]) - 32;
                correct += a;
                i++;
            }
            else if (int(s[j]) >= 65 && int(s[j]) <= 90&&i==0)
            {
                char a = int(s[j]) + 32;
                correct += a;
                i++;
            }
            else if (int(s[j]) >= 65 && int(s[j]) <= 90)
            {
                char a = int(s[j]) + 32;
                correct += a;
                i++;

            }
            else
                correct += s[j];
        }
        else
        {
            correct += ". ";
            i = 0;
        }
    }
    cout << correct << endl;
}

question is to write a code that convert first character of string to uppercase and other stay as lowercase. after every "." make the words first char again upper and other parts in lower!
Input:

hellOWOrLD.hELLOWORLD.

Output:

Helloworld. Helloworld.

It should work like in the picture...
Comment: What's your question? FYI: Have a look at `std::tolower` and `std::toupper`.
Comment: well it can convert only firs or all  characters mine is to convert its first character plus to make other part of the word in lowercase as in example  input=> hellOWOrLD.hELLOWORLD. output=>Helloworld. Helloworld.
Answer: I would use isalpha(), toupper() and tolower()
EDIT:  To look for punctuation.
#include <iostream>
#include <cctype>
#include <string>

using namespace std;

void upperCase(string& line)  {
    bool firstCharacter = true;
    string punctuation=".?!";

    for(int i = 0; line[i] != '\0'; i++) {
      char c=line[i];
        if(isalpha(c)) {
            if (firstCharacter) {
                line[i] = toupper(c);
                firstCharacter = false;
            } else {
                line[i] = tolower(c);
            }
        } else if (punctuation.find(c)!=string::npos) {
          firstCharacter=true;
        }
    }
}

int main() {
    string str = "hello UNiverse?! World? Hello. Hello";
    upperCase(str);
    std::cout << str << '\n';
}

Comment: how about ". " if there are some it should seperate with some blank spaces and then make another words first letter in uppercase
Comment: Does this answer your question?
Comment: Yes it is , exactly woooow yahooo thank u Paul Bentley
Comment: not sure - I think you have to accept it?  I have not asked a question here yet.


Is is possible to use Outlook with an Exchange server that has limited publicly accessible resources?

Question: Does anyone know if it is possible to get outlook (partially) working with an exchange service with only makes Webmail and ActiveSync publicly accessible?
Thanks,
Sean W.
Answer: I don't believe this is possible. Outlook uses RPC over HTTP(s) for remote access. This requires a separate configuration on the Exchange server, its not part of OWA or ActiveSync. I don't think there are any full mail clients that work with Outlook Web Access or ActiveSync.
I do seem to remember a taskbar app that would notify you of new mail that it saw in OWA, but it wasn't a client, just a notifier.
What are you trying to do?
Comment: Oh well. It would just be nice not no need to fire up a VM with IE to get any decent functionality out of my school mail when I'm off-campus. Heck, my android phone with ActiveSync has a better feature set than OWA light.
Comment: Probably not helpful to you, but Exchange 2010 has a new version of OWA, called Outlook Web App. It actually doesn't suck in Firefox and Chrome.
Comment: Also, it sounds like your Exchange policies are pretty locked down, but it might be possible to set up a forwarding address within OWA. You could forward all your mail to Gmail, and configure Gmail to send as your school account. This would still show your Gmail address if the SMTP servers are not available, but might be better than "IE via VM"


Follow up question to: Why does logistic regression generate well-calibrated models?

Question: I've read all answers and comments here: Why does logistic regression produce well-calibrated models?
but still not clear about the answer.
Can someone please elaborate why the following equation means model is well calibrated?

The two sides of above equation are sum of products. I don't quite understand why we can take  off the equation and have

Thank you very much!
Comment: Welcome to CV. Please edit your question (specifically the title) to make it clear how this question differs from the linked question. Follow-up questions are fine, but now your title is identical to the original question, which attracts close votes.
Comment: Thank you for the advice. It's a follow up question to the linked one, but I don't know how to tag it to make it sounds like a follow up question...
Answer: The first equation applies to every column $x_j$ of the design matrix. In particular, it applies to the first column $x_0$, which is a vector of all ones. That's why the $x$'s drop out in the second equation.
Comment: Ah I see! I forgot there is a column of all 1s for the intercept. Thank you so much!


Big problema when use thymeleaf th:ref

Question: My th:ref don't generate a link.
Inativar

          Inativar

Answer: There is a typo it should be th:href instead of th:ref
Inativar

Comment: Oh god!!
It's realy !!
Thanks a lot !!

Big problema when use thymeleaf th:ref


How to check if my AngularJS controller is located inside a form

Question: I have a controller that I reuse in two different places, but I want the controller to be able to distinguish wether it is used in a page that edits the data or a page that just displays the data. The difference here is that on one page the controller is located inside an <... ng-form="someForm"> tag.
(Actually, it is a partial html file that gets included; the controller is inside that partial)
Is it possible to detect whether a controller is located inside a form? If so, how?
Answer: I couldn't find any shortcut way to fulfill your requirement, but one thing you can do is to define a variable in $rootScope to track controller's behavior. Each time a view loads with a controller it calls its define function in the javascript file.
So the idea is, in the $rootScope you'll define a flag whether your required controller is loaded or not. Then you can check the flag to know whether it has loaded or not. Also you can use $watch on the flag to get a notification when it was loaded. Let me know if any part is unclear.
Thanks.
Comment: I think you misunderstood, I don't want to check if the controller is loaded or not. I know it is loaded, but I want to know if it is inside a form or not.
Anyway, I would rather not mess with $rootScope. I'm looking for a solution that keeps the logic contained within the controller itself.
Comment: You can use a directive and then search for your controller name inside that directive's inner html. That way all your logic will keep as it is.
Answer: I found out that I could create a directive that optionally requires form (not ng-form) and that you can check whether it is present or not in the link function.
someAngularModule
    .directive('formAware', [function(){
        return {
            require: '^?form',
            template: '
{{isPartOfForm ? "Inside the form" : "Outside of the form"}}
',
            link: function(scope, element, attrs, formCtrl) {
                scope.isPartOfForm = (formCtrl !== null);
            }
        }
    }]);

The directive can be placed inside an ng-form (displaying the text "Inside the form"):

or without an ng-form (displaying the text "Outside of the form"):


Overwrite a specific field on a specific node

Question: We have a content-type of 'offices' locations. There is a View that pulls all of them together and that view is used on a contact page, a buy and a representative page. It's also used on job postings as a field 'location'.
Now they want to post a job with at "TBD" location. If I add a "TBD" node type, it will then display in all of the places where that view display 'offices' is pulled.
So I need to tell Drupal "On this job posting only, show "TBD" in the location Field. That's the ideal thing ... to rewrite that field on a specific job posting. In this case, the node is specifically 11071, if that helps?
Can I use a page-node-11071.tpl.php and some function there?
Comment: Do you have also a job content type? if that is true, how do you connect the new job, TDB location and the offices?
Comment: Jose- yes, I have a job-posting content type with a 'location' field of which is tied to a 'node-reference' (the actual content-type of offices). My issue is that if I add an office content-type, then the other pages will list that.
Answer: As I understand, you want a to display the same block which lists some node information in different pages and want to avoide listing some specific nodes in some specific pages. You can make use of views filter with 'Global: PHP' and have code similar to as below :
<code>
if (arg(0) == 'node') {// Set your condition here.
  if ($data->nid == NID_YOU_WANT_TO_RESTRICT) {// Set the NID you want to restrict
    return TRUE;
  }
}
</code>
Note : To consider multiple job postings in future, you just need to set the path condition accordingly.
Hope it helps
Answer: Instead of treating this one node in a special way (there will be more job postings in the future with location TBA), you could filter out the location by adding a filter in your views that pull locations.
In you views, under "Filter criteria" click add, choose the field type of your location, choose Operator "not equal to" and Value "TBA".
That should do the trick.
Comment: Thanks. After seeing this, it makes sense and I see my issue.. I was thinking the actual field was linked to the view... when it was a "node-reference" so seeing your answer schooled me!


While starting the jboss server with IBM Sterling V9.3 (ISCCS included), im getting the below error. please help me with it

Question: <code>ERROR [[/isccsdev]] Servlet /isccsdev threw load() exception
java.lang.IllegalStateException: Profile file final.profile.js not found
        at com.sterlingcommerce.ui.web.framework.servlets.SCUIInitializerServlet.initializeProfile(SCUIInitializerServlet.java
        at com.sterlingcommerce.ui.web.framework.servlets.SCUIInitializerServlet.initializeDojo(SCUIInitializerServlet.java:18
        at com.sterlingcommerce.ui.web.framework.servlets.SCUIInitializerServlet.init(SCUIInitializerServlet.java:144)
        at org.apache.catalina.core.StandardWrapper.loadServlet(StandardWrapper.java:1161)
        at org.apache.catalina.core.StandardWrapper.load(StandardWrapper.java:981)
        at org.apache.catalina.core.StandardContext.loadOnStartup(StandardContext.java:4071)
        at org.apache.catalina.core.StandardContext.start(StandardContext.java:4375)
        at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:790)
        at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:770)
        at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:553)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:296)
        at org.jboss.mx.server.RawDynamicInvoker.invoke(RawDynamicInvoker.java:164)
        at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
        at org.apache.catalina.core.StandardContext.init(StandardContext.java:5312)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:296)
        at org.jboss.mx.server.RawDynamicInvoker.invoke(RawDynamicInvoker.java:164)
        at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
        at org.jboss.web.tomcat.service.TomcatDeployer.performDeployInternal(TomcatDeployer.java:301)
        at org.jboss.web.tomcat.service.TomcatDeployer.performDeploy(TomcatDeployer.java:104)
        at org.jboss.web.AbstractWebDeployer.start(AbstractWebDeployer.java:375)
        at org.jboss.web.WebModule.startModule(WebModule.java:83)
        at org.jboss.web.WebModule.startService(WebModule.java:61)
        at org.jboss.system.ServiceMBeanSupport.jbossInternalStart(ServiceMBeanSupport.java:289)
        at org.jboss.system.ServiceMBeanSupport.jbossInternalLifecycle(ServiceMBeanSupport.java:245)
        at sun.reflect.GeneratedMethodAccessor3.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
        at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
        at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
        at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
        at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
        at org.jboss.system.ServiceController$ServiceProxy.invoke(ServiceController.java:978)
        at $Proxy0.start(Unknown Source)
        at org.jboss.system.ServiceController.start(ServiceController.java:417)
        at sun.reflect.GeneratedMethodAccessor9.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
        at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
        at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
        at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
        at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
        at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
        at $Proxy44.start(Unknown Source)
        at org.jboss.web.AbstractWebContainer.start(AbstractWebContainer.java:466)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
        at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
        at org.jboss.mx.interceptor.AbstractInterceptor.invoke(AbstractInterceptor.java:133)
        at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
        at org.jboss.mx.interceptor.ModelMBeanOperationInterceptor.invoke(ModelMBeanOperationInterceptor.java:142)
        at org.jboss.mx.interceptor.DynamicInterceptor.invoke(DynamicInterceptor.java:97)
        at org.jboss.system.InterceptorServiceMBeanSupport.invokeNext(InterceptorServiceMBeanSupport.java:238)
        at org.jboss.wsf.container.jboss42.DeployerInterceptor.start(DeployerInterceptor.java:87)
        at org.jboss.deployment.SubDeployerInterceptorSupport$XMBeanInterceptor.start(SubDeployerInterceptorSupport.java:188)
        at org.jboss.deployment.SubDeployerInterceptor.invoke(SubDeployerInterceptor.java:95)
        at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
        at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
        at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
        at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
        at $Proxy45.start(Unknown Source)
        at org.jboss.deployment.MainDeployer.start(MainDeployer.java:1025)
        at org.jboss.deployment.MainDeployer.start(MainDeployer.java:1015)
        at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:819)
        at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:782)
        at sun.reflect.GeneratedMethodAccessor21.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
        at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
        at org.jboss.mx.interceptor.AbstractInterceptor.invoke(AbstractInterceptor.java:133)
        at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
        at org.jboss.mx.interceptor.ModelMBeanOperationInterceptor.invoke(ModelMBeanOperationInterceptor.java:142)
        at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
        at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
        at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
        at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
        at $Proxy9.deploy(Unknown Source)
        at org.jboss.deployment.scanner.URLDeploymentScanner.deploy(URLDeploymentScanner.java:421)
        at org.jboss.deployment.scanner.URLDeploymentScanner.scan(URLDeploymentScanner.java:634)
        at org.jboss.deployment.scanner.AbstractDeploymentScanner$ScannerThread.doScan(AbstractDeploymentScanner.java:263)
        at org.jboss.deployment.scanner.AbstractDeploymentScanner.startService(AbstractDeploymentScanner.java:336)
        at org.jboss.system.ServiceMBeanSupport.jbossInternalStart(ServiceMBeanSupport.java:289)
        at org.jboss.system.ServiceMBeanSupport.jbossInternalLifecycle(ServiceMBeanSupport.java:245)
        at sun.reflect.GeneratedMethodAccessor3.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
        at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
        at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
        at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
        at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
        at org.jboss.system.ServiceController$ServiceProxy.invoke(ServiceController.java:978)
        at $Proxy0.start(Unknown Source)
        at org.jboss.system.ServiceController.start(ServiceController.java:417)
        at sun.reflect.GeneratedMethodAccessor9.invoke(Unknown Source)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
        at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
        at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
        at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
        at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
        at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
        at $Proxy4.start(Unknown Source)
        at org.jboss.deployment.SARDeployer.start(SARDeployer.java:304)
        at org.jboss.deployment.MainDeployer.start(MainDeployer.java:1025)
        at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:819)
        at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:782)
        at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:766)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
        at java.lang.reflect.Method.invoke(Method.java:597)
        at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
        at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
        at org.jboss.mx.interceptor.AbstractInterceptor.invoke(AbstractInterceptor.java:133)
        at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
        at org.jboss.mx.interceptor.ModelMBeanOperationInterceptor.invoke(ModelMBeanOperationInterceptor.java:142)
        at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
        at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
        at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
        at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
        at $Proxy5.deploy(Unknown Source)
        at org.jboss.system.server.ServerImpl.doStart(ServerImpl.java:482)
        at org.jboss.system.server.ServerImpl.start(ServerImpl.java:362)
        at org.jboss.Main.boot(Main.java:200)
        at org.jboss.Main$1.run(Main.java:508)
        at java.lang.Thread.run(Thread.java:662)
</code>
The server starts fine. But I am unable to hit the ISCCS url (:7002/isccs/isccs/login.do)
Thanks in Advance
Answer: This is caused due to the VM arguments used while building the ear or war file. Don't use -Ddevmode and -Duidevmode. Try building a war instead with the following command.
buildwar.cmd -Dwarfiles=isccs -Dappserver=jboss
For dev
buildwar.cmd -Dwarfiles=isccsdev -Dappserver=jboss
Comment: I also agree sreejiths comment.
Answer: You can also refer IBM knowledge centre for this:
http://www-01.ibm.com/support/knowledgecenter/SSYLSL_9.3.0/com.ibm.help.wcc.install.doc/t_CreatingTheEAROnJBoss.html
There they are mentioning what all options you should use while using a call centre application in sterling.
Especially the following line:
Note: Commerce Call Center supports the RPC encoded or document literal style and usage of invocation for Web services. When choosing style and usage for JBoss, pass the following in the ear command line:
-Djboss-java2wsdl-style=
It may help you.