Are non-tonic or dominant pedal points still effective?

Question: Pedal points are usually over scale degree 1 or 5, the former to seal the tonic in the listener's mind, and the latter to generate more tension than most other techniques in music.
It seems that there are other degrees that would work to generate tension, perhaps even more effectively than 5. Namely, scale degree 7(raised 7 in minor) would clash with virtually any chord(the objective of a pedal point) and would create said tension as it refuses to resolve to scale degree 1.
Are pedal points on scale degrees that are not 1 or 5, namely scale degree 7, still effective?
Comment: Possibly a duplicate- https://music.stackexchange.com/questions/111218/can-a-pedal-point-note-be-used-from-any-note Though I think that you're not just looking for a "yes" answer but rather some insight into how such a pedal point might appear in music.
Comment: You may find Wikipedia's [Pedal point](https://en.wikipedia.org/wiki/Pedal_point) article of value.
Comment: https://youtu.be/tR32h5jhPtU?t=349
Comment: Which pedal points have you tried? What effect did they have ?
Comment: I feel like IV or vi are used often enough, often to create an "unsettling" or foreboding sense under a major melody
Answer: Pedals other than tonic and dominant are not much used (in Common Practice styles at any rate) so I guess we can infer a general opinion that they're not so 'effective'.
You could use a non-diatonic pedal to create a discombobulating effect. 'Harmony' or just an 'Effect'?  'Composition' and 'Sound design' often overlap these days!
You might want to re-examine your opening statement: "Pedal points are usually over scale degree 1 or 5, the former to seal the tonic in the listener's mind, and the latter to generate more tension than most other techniques in music."   Do you agree that a dominant pedal is the strongest tool we have available for creating tension?
Comment: Note the keyword "most". I was referring to the fact that the dominant pedal point is effective to build tension, and that it was a prominent tool to do exactly that near the end of a composition. It was more of a logical conclusion considering it's ubiquity in western musical styles.


Child content types

Question: I need to create two content types (Call List and Call Announcements), in Call Announcements there are 5 fields, in Call List there are 12 fields but 5 of them are mutual with Call Announcements, I do not want to create 2 different content types (Call List, Call Announcements) because when the user create a node, he should be able to choose where the node is shown (in Call List, in Call Announcements, Both). (Call List and Call Announcements should be in the same database table)

How can I do these?
Answer: Have a look at the Conditional Fields module and use a taxonomy vocabulary with Call List and Call Announcements as items that users can select on node creation. Of course, add a term reference field to that vocabulary under "manage fields" for the parent content type.
Conditional Fields can hide/disable/show fields upon user choice (Call List or Call Announcements).
Comment: a. You should create a content type e.g. named Call b. create a taxonomy vocabulary called for example Call Tags c. for this vocabulary add two terms: Call List & Call Announcements. d. back to content type 'call' add a term reference field to Call Tags Vocab. e. create all other fields under node type Call. f. Install Conditional Fields module and read documentation at project page for further instructions. All the best.
Comment: Thanks you, but I am sorry, I did not understand I try to apply your instructions but could not achieve

Child content types


Remover menu navigation controller

Question: Como removo esse menu em cinza da minha webview acho que é alguma coisa relacionada ao navigation controller n tenho certeza
Answer: Essa barra se refere a NavigationBar que é exibida por padrão na NavigationController.
Para ocultar essa barra, você pode simplesmente chamar o método setNavigationBarHidden da sua NavigationController.
<code>self.setNavigationBarHidden(true, animated: true)
</code>
Lembrando que o self se refere a instância da sua NavigationController.
Documentação da Apple que fala sobre a NavigationController

Remover menu navigation controller


cookie issue with same domain same port but different path

Question: I have a situation where my web application will respond with cookie Rules=abcdefg for each request.
Request 1:
http : //hostname:8080/teja/axftyo (for this request I am setting cookie path as below, response from server)
Set-Cookie: Rules=HCE0F290B77137721C2F6107DD4B62F28;Path="/teja/axftyo"
Request 2:
http : //hostname:8080/teja/bcdefg
I assume that for request 2 Rules cookie should not be sent, but still the browser is sending this cookie in to the server.
How can I achieve the functionality of browser sending different cookies based on the path (/bcdefg) rather by my application name /teja
Thank you.
Comment: You can't. Cookies are sent depending on the path, not on the page. It's part of the implementation of HTTP and you can't change it.
Comment: @ThoriumBR Cookies are sent depending on the path, not on the page. Can you elaboarate
Answer: Cookie paths only work on a directory level. /dir/a and /dir/b are considered to be in the same scope for cookies.
/dir/a/ and /dir/b/, on the other hand, are distinguishable, so you could consider adding trailing slashes to your URLs.
Comment: HI , i tired adding the extra slashes , but still the browser is sending the cookie . I have verified this with fiddler. This is the path which server responded " RULES=HDD55C0B2525E9F969F957E5BB9C2FEFB;  Path=/prweb/PRServlet/pbdorj4V2aBoI4ScEONLsEaxdEWiqDby*/" , Request 2 is GET /prweb/PRServlet/beEBp4uRVTogorRwSwWqbAuSszhTv2W2svU1posaO4A[*/!STANDARD HTTP/1.1, the recieved cookie for previous request is being sent to the server though the path is different
Comment: Both requests are using path */prweb/PRServlet/*. The page are different, but they are hosted on the same folder, so they share the same _Cookie Path_.
Comment: @ThoriumBR But if you observe paths after PRServlet is different right?? Should browser will not take that into account while sending cookie. If no, apart from creating a new cookie , how can i make it work with the old cookie itself? "/prweb/PRServlet/pbdorj4V2aBoI4ScEONLsEaxdEWiqDby*/ "                                                   "/prweb/PRServlet/beEBp4uRVTogorRwSwWqbAuSszhTv2W2svU1posaO4A[*/"
Comment: You can create some structures using redirection to deal with this situation, but why do you need to not send the cookies anyway? It's your server, your pages, so how sending different cookies will be a problem? Ignoring the extra cookie is way easier than to create a whole structure to avoid sending two cookies. What exactly are you building?


IIS Digest repeatedly asking for authentication

Question: I have a development copy of an ASP.NET intranet site checked out and running on my local machine.  We're using digest authentication to allow users to log in using their active directory accounts.
On my development copy only, Digest sometimes will repeatedly prompt for login information usually ~9 times per page request.  After repeatedly logging in (or it also works to cancel out of 8 out of the 9 prompts), I can use the site as normal.
I cannot pinpoint what is triggering the issue.  Sometimes this problem triggers upon the next page request, sometimes after I edited/saved/refreshed a page, and sometimes it doesn't happen at all.
Each prompt triggers several logon (Event ID 4624 & 4672) security events in the Events Viewer.  Shortly after each burst of logon events, I'll see a burst of logoff events (Event ID 4634)
A co-worker who has a nearly an identical setup (Windows 7, IIS 7) is not experiencing the issue.  Our production copy (that is running on a different server) also does not experience the issue.  We've tried to compare our settings in IIS, not really finding any differences.
I'm using chrome but I've experienced the issue in other browsers.
Answer: The question is 11 years old, but still not solved.
The actual problem is wrong MD5-sess implementation in Chrome and Firefox.
The only correct implementation can be found in (already abandoned) IE.
IIS is the only popular web server with support for MD5-sess and MD5-sess is always used with recent IIS versions if Digest Authentication is enabled.
According to RFC 2617 (and RFC 7616) the first part of hash code (H(A1)) for MD5-sess must be calculated with the server nonce and the first client cnonce. The H(A1) should not be changed until new server nonce is received, even if client uses another cnonce.
According to Chrome and Firefox source code, browsers ignore this requirement and always recalculate H(A1) with new cnonce. As the result, the first request with the first cnonce is valid and accepted by IIS, but the second and following requests with the same nonce and different cnonce have invalid response hash and rejected by IIS. This force browsers to request the username and password again for every element located on URL with Digest Authorization. As soon as all elements on the page become cached, browser stops asking for password re-enter.
The more info is here.
Looks like IIS with Digest Auth is used very unfrequently and this is why this problem is not noticed (and not fixed) for years.
MS Edge is based on Chromium code and has the same problem.
Comment: In my experience Digest was not used frequently in areas where TLS certificates are pervasive. And this isn't really an issue with Microsoft's implementation, because Microsoft essentially end-of-lifed the technology when they recommended disabling it. The key takeaway is in a Microsoft environment this is a critical security risk.This has been discussed on Security Stack Exchange. https://security.stackexchange.com/questions/152935/why-is-there-no-adoption-of-rfc-7616-http-digest-auth
Comment: ` IIS with Digest Auth is used very unfrequently`. I would say never. Digest authentication is a critical security risk and most organizations disabled it years ago. It's a dead technology.   "This update prevents every Microsoft SSP in LSASS, besides WDigest, from storing the user's clear-text password."  WDigest stores passwords in clear text in LSASS and the only way to prevent this is to disable WDigest." https://techcommunity.microsoft.com/t5/core-infrastructure-and-security/the-importance-of-kb2871997-and-kb2928120-for-credential/ba-p/258478
Comment: The mentioned problems are problems in MS's implementation of Digest Auth. Digest Auth allow storing hashed passwords (with different hashes for every realm). SHA-256 is allowed as an alternative to insecure MD5. While Microsoft's implementation `WDigest` is problematic and has security problems, Digest Auth is still usable in general.
This question has been asked originally 11 years ago, when WDigest was used more frequently.
Answer: If this app is for internal use only I would recommend using integrated auth rather then digest.  For apps without built in web-form auth like yours, 99% are integrated (AD auth pass through) or basic auth over SSL.
Also, Digest doesn't always work with AD and depends on settings in AD and in each user.  Google things like "digest auth active directory" or "digest reversible encryption" so see the issues people have with it.
Other things to look at are NTFS permissions on files/folders, and if anonymous is enabled (it shouldn't be).
Answer: Do you have a (caching/non-caching) web proxy between your machine and the server ?
I saw the same problem with Sharepoint authentication, the solution we took was to get rid of the ISA Firewall/Proxy through a rule allowing clients to bypass it for the Sharepoint site.
That solved the problem but we didn't investigate the root cause.


ASP.NET application on "IIS 8.5" on "Windows Server 2012 R2" performs poorly compared with "IIS 7.5" on a "Windows Server 2008 R2"

Question: We have the same ASP.NET application running on a couple of servers:

one instance runs under IIS 8.5 on Windows Server *2012* R2
two instances run under IIS 7.5 on Windows Server *2008* R2

What bugs me is that the newer machine seems to perform worse than both of the older machines!

On the 2012 box, a window of about 80 minutes shows an average 37% CPU usage (Processor time), and 8 Requests/sec on average.
On the 2008 box, in the same time frame, I see 32.5% CPU usage and 12.5 Requests/sec:

What's more, the CPU on the 2012 box (Intel Core i7-4770 @ 3.40GHz) is actually supposed to be faster than the one on the 2008 boxes (Intel Xeon E3-1230 @ 3.20GHz):

Adding to my lack of comprehension of this performance difference is the fact, that the 2012 instance only runs the one ASP.NET application, whereas both of the 2008 servers fulfill other tasks as well: one runs the DB server that is accessed by all three application instances, the other runs quite a few other ASP.NET applications under the same IIS instance.
QUESTION:
Can anyone shed some light on what could be the culprit of the better equipped server falling so far behind in terms of ASP.NET application performance?
Comment: You need to perfmon more counters than just the processor usage.  There are several issues that could manifest as higher CPU time but the processor is not the problem.  Also, what is the power plan set to?
Comment: @GregAskew: Please add an answer with your hint to check the Power Plan - it was set to **Balanced**! After setting it to **High Performance** the PerfMon graph changed its look entirely :-)
Answer: I believe this has been covered in several places, but the Balanced power plan can cause excessive transitions between performance states.  This results in exceptionally poor performance, and affects both physicals and virtuals.
Change the power plan to High Performance to use the hardware to its limits.
Slow Performance on Windows Server 2008 R2 when using the "Balanced" Power Plan:
https://support.microsoft.com/en-us/kb/2207548
https://sqlserverperformance.wordpress.com/2010/09/28/windows-power-plans-and-cpu-performance/
http://www.brentozar.com/archive/2010/10/sql-server-on-powersaving-cpus-not-so-fast/
EDIT by @oliver:
Switching to the High Performance power plan resulted in these PerfMon stats:


correctly override __new__ in python3

Question:
So I am trying to override __new__ and let it exist as a factory to create
derived instances. After some reading on SO, I am under the impression that I should be calling __new__ on the derived instance as well.
BaseThing
class BaseThing:
    def __init(self, name, **kwargs):
        self.name = name

    # methods to be derived

ThingFactory
class Thing(BaseThing):
    def __new__(cls, name, **kwargs):
        if name == 'A':
           return A.__new__(name, **kwargs)
        if name == 'B':
           return B.__new__(name, **kwargs)

    def __init__(self, *args, **kwargs):
        super().__init__(name, **kwargs)

   # methods to be implemented by concrete class (same as those in base)

A
class A(BaseThing):
    def __init__(self, name, **kwargs):
       super().__init__(name, **kwargs)

B
class B(BaseThing):
    def __init__(self, name, **kwargs):
       super().__init__(name, **kwargs)

what I am expecting was that it'd just work.
>>> a = Thing('A')

gives me TypeError: object.__new__(X): X is not a type object (str)
I am bit confused by this; when I just return a concrete instance of derived classes, it just worked. i.e.
def __new__(cls, name, **kwargs):
        if name == 'A':
           return A(name)
        if name == 'B':
           return B(name)

I don't think this is the correct way to return in __new__; it may duplicate the calls to __init__.
when I am checking signatures of __new__ in object it seems be this one:
@staticmethod # known case of __new__
def __new__(cls, *more): # known special case of object.__new__
    """ Create and return a new object.  See help(type) for accurate signature. """
    pass

I didn't expect this was the one; I'd expect it came with args and kwargs as well. I must have done something wrong here.
it seems to me that I need to inherit object directly in my base but could  anyone explain the correct way of doing it?
Comment: You seem to have assigned something to `X`.
Comment: Your thing factory doesn't need to be a subclass of `Thing`; a regular function like `def thing_factory(name, *args, **kwargs): if name == "A": return A(*args, **kwargs) ...` would suffice.
Comment: @user2357112 updated the question.
Comment: Where  'A' is coming from: `return A.__new__(name, **kwargs)` ? As error explains, 'A' is not an object.
Comment: It doesn't look like you actually tried to run any code version you posted. This code wouldn't have produced the error you claim, and it even contains obvious syntactical errors like `return return A(name)`. Posting code that doesn't reproduce your error tends to attract downvotes.
Comment: @ElisByberi ok yes, I guess that's a further evidence proving I am calling __new__ wrong. thanks
Comment: @stucash Why do you need to call new? It is called whenever you create a new class object!
Comment: @user2357112 thanks for that, but I guess that'd be something once you pointed out I could easily rectify. and for not running this codes, I guess it's yes and no, I won't argue this. I'll take this blame. I do have live codes which is far more complex so I could only create same skeleton here.
Comment: @stucash Test your code before coming here. You are welcome! Come prepared next time! :-)
Comment: @ElisByberi it's half learning to be honest; making correct use of `__new__` we could implement the factory pattern in a different way for it looks a bit nicer..
Comment: @ElisByberi yep will defo do that, now at least I think the downvote is not wrong. thanks for helping out!
Comment: @stucash This will help you for next time: https://stackoverflow.com/questions/674304/why-is-init-always-called-after-new
Comment: @user2357112 thanks for letting me, I genuinely appreciated it.
Answer: You're calling __new__ wrong. If you want your __new__ to create an instance of a subclass, you don't call the subclass's __new__; you call the superclass's __new__ as usual, but pass it the subclass as the first argument:
instance = super().__new__(A)

I can't guarantee that this will be enough to fix your problems, since the code you've posted wouldn't reproduce the error you claim; it has other problems that would have caused a different error first (infinite recursion). Particularly, if A and B don't really descend from Thing, that needs different handling.
Comment: thanks and I have actually fixed circula dependency by using this implementation, but with returning instances directly.  calling `__new__` wrong I guess might be my real problem; I am going to try it and update it later.. peculiar that you didn't get the same error.
Comment: Sincere apologies, I have corrected the codes now. if you run them you should be able to reproduce the error.

correctly override __new__ in python3


Como pegar o caminho do diretório

Question: Estou usando WinForm e tentando salvar uma string com o SaveFileDialog mas não consigo passar o diretório escolhido no SaveFileDialog para a função do System.IO.File.WriteAllLines;
        private void saveCategoriesToolStripMenuItem_Click(object sender, EventArgs e)
    {

        string[] SaveString = new string[100];
        SaveFileDialog SFD = new SaveFileDialog();
        SFD.Filter = "Categories Files (.ctg)|*.ctg";
        SFD.Title = "Save a Categories file";
        SFD.ShowDialog();

         if (SFD.FileName == "")
        {
            MessageBox.Show("Enter a name for the file", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
        else
        {
            SaveString[0] = tamanho.ToString();
            for(int i=1;i<=tamanho;i++)
            {
                SaveString[i] = "\"" + KeysValues[i] + "\",\"" + CategoriesValues[i] + "\"";
            }
            SFD.DefaultExt = ".ctg";
            System.IO.File.WriteAllLines(, SaveString);
        }

Answer: Caio, o que você procura é a classe FileInfo, podendo ser usado da seguinte forma
FileInfo fileInfo = new FileInfo(SFD.FileName);

System.IO.File.WriteAllLines(fileInfo.DirectoryName, SaveString);

Nesse caso o fileInfo.DirectoryName retorna o diretório do arquivo selecionado pelo SaveFileDialog

Como pegar o caminho do diretório


How to get logged in user's email in Flutter using Firebase

Question: I want to get the email of the logged in user in a Flutter app which uses Firebase for authentication.
I can get the current user by
final user = await _auth.currentUser();

But if I try this to get the mail
final mailID = await _auth.currentUser().email.toString();

I get the following error:
The getter 'email' isn't defined for the type 'Future<FirebaseUser>'.
Try importing the library that defines 'email', correcting the name to the name of an existing getter, or defining a getter or field named 'email'.

How to get the logged in user's email in this case?
Answer: Get the user before trying to get the email. code below
<FirebaseUser> user = await _auth.currentUser();
final mailID = user.email;

Comment: Ohh yea.
You have to `await` `_auth.currentUser()` but if you write it in one line you're just trying to get the email from a `Future`
Comment: Thank you, but any explanation as to why this happens? I mean why not in one command?
Answer: it's working for me.
import 'package:firebase_auth/firebase_auth.dart';

FirebaseAuth auth = FirebaseAuth.instance;

FirebaseAuth.instance
    .authStateChanges()
    .listen((User? user) {
  if (user == null) {
    print('User is currently signed out!');
  } else {
    print('User is signed in!');
  }
 });


Does OpenTest support Implicit Waits?

Question: Does OpenTest support specifying implicit waits for element location or page loading?
Answer: You don't need to use implicit waits in OpenTest. All keywords know how to wait for the UI elements they interact with. Behind the scenes, OpenTest uses explicit waits, which you can customize, when necessary, by setting the explicitWaitSec argument for a test action (the default is 10 seconds). For example:
- description: Verify that element is visible
  action: org.getopentest.selenium.AssertElementVisible
  args:
    locator: { id: my_element }
    explicitWaitSec: 20

Does OpenTest support Implicit Waits?


Integrate Webform.html.twig into existing template

Question: I am attempting to add a webform field into an existing content type which has an associated twig template.  I can add the webform field to a new content type and/or use the default webform content type and the form displays without an issue.  If I add the webform to an existing content type the form does not display.  I tried adding the content from webform.html.twig to the existing content types template but it is still not displaying the form.  I know I am missing something simple here.  I can supply a few screenshots and or the twig files if that would be helpful
thank you for your patience.  I have had the debugging turned on for quite some time now the development version of our site.  The inspect screen appears to suggests the problem with displaying the webform field is in the page.html.twig which I have attached.  Interestingly, I tried adding a few other random fields to the page content type and they do not display either so I am fairly certain now that there is a problem with the twig template.
{#
/**
 * @file
 * Default theme implementation to display a page.
 *
 * @see academyhealth.info.yml
 * @see template_preprocess_page()
 * @see html.html.twig
 *
 * @ingroup themeable
 */
#}

    AcademyHealth
    <button class="header__menu-button"> Menu</button>

       Close

        {{ page.main_navigation }}

        {{ page.utility_navigation }}

          {{ page.search }}

  {#
    A block titled content will be set if pages are extending this template, so
    print that instead of just printing page.content. The templates that extend
    this template, call page.content and place it appropriately.
  #}
  {% set _block_content = block('content') %}

  {% if _block_content is not empty %}
    {{ _block_content|raw }}
  {% else %}
    {{ page.content }}
  {% endif %}

      AcademyHealth

Connect with Us

      {{ page.footer_social_media }}

Navigate AcademyHealth

      {{ page.footer_menu }}

Extras

      {{ page.footer_extras }}

      {{ academyhealth_address_line }} | {{ academyhealth_address_line_2 }} | Tel: {{ academyhealth_phone_number }} | Fax: {{ academyhealth_fax_number }}

Comment: Welcome to Drupal Answers. When you ask a question, it usually helps to add the "7" or "8" tag so we know which Drupal version you're asking about. In fact, you can still edit your question and add it. In this case I'm going to guess 8 because you said "twig".
Comment: In a site setup that I would consider "normal", I don't see how this could be a problem with blocks or the page template. In other words: If this is not a problem with the configuration of your view mode (which, as you have checked, it is not) or the node template (which you say it is not), then I'm running out of plausible options. That could also mean your question is so specific to your site and custom code, that it is beyond the scope of Drupal Answers.
Answer: Conceptually, you shouldn't be thinking about it as including templates in other templates. Other CMS'es are more "template based" so to speak, but Drupal isn't. Building your content types and pages in Drupal means telling Drupal (through configuration or in code) how to construct its render arrays. From there on, Drupal will figure out which templates to use and how to merge the resulting HTML of one template into another template.
So that's the theory... now what's the problem in your case? The most obvious reason I can think of, is that you added the field, but did not yet configure it to be displayed. To do so, make sure Field UI module is enabled and then go the "Manage Display" page of your content type. The URL will look like /admin/structure/types/manage/[type]/display where "[type]" is the machine name of your content type. If you see your field in the "disabled" part of the form, drag it upwards to make it enabled and save the form. (This is an example of the "through configuration" method I mentioned earlier.)
If the above does not solve your problem, please add more details to your original question.
Comment: Thank you and I apologize you are correct I am using Drupal 8.5.4.  I had already confirmed that the webform field is listed in the enabled section of the Manage Form Display and under the various views under the custom display settings.  If I use the webform included content type the webform displays as expected.  If I change the theme to the default seven the page with the webform field will display the webform and other fields correctly.  Using our theme the page will display all of the content with the exception of the webform field (which it just seems to ignore) correctly
Comment: So you tried if it does work in a different theme - excellent! That is a great way to determine if the problem is in your configuration or in your theme. Obviously it's in your theme. Maybe you can add the code of your custom node template to the original question? If you are not sure which template is used, follow [these instructions](https://www.drupal.org/node/2358785) to find out.
Comment: Based on your earlier comment I also wonder if this couldn't have something to do with the region blocks.  I looked at the ones for defined for content and there doesn't seem to be restriction on the webform content type but I may not be looking at the correct information


Automation of Jira and Jira Issue Updater Plugin

Question: I have the following task: To automate issue converting from Resolved to Integrated if build is successfull.
I have Jira v.6 and Jenkins.
I installed Jira(wiki.jenkins-ci.org/display/JENKINS/JIRA+Plugin) and Jira Issue Updater Plugin (wiki.jenkins-ci.org/display/JENKINS/Jira+Issue+Updater+Plugin) in Jenkin
I configured this plugin(Jira Issue Updater Plugin) for needed job with task to change from Open to Resolved.
Jira SOAP URL - https://MyJiraUrl/rpc/soap/jirasoapservice-v2
Jira Username - myusername
Jira Password - mypassword
JQL for selecting issues to be updated - project=MyProjectKeyNameFromJira and issue=MyIssueName and status= Open
Name of the workflow action to be executed - Resolved
Fail this build if JQL returns error - Checked
When I run this build I have the following error
Jira could not execute your JQL, 'project=MyProjectKeyNameFromJira  and issue=MyIssueName and status= Open': com.atlassian.jira.rpc.exception.RemoteValidationException:
Query validation failed: The value 'MyProjectKeyNameFromJira' does not exist for the field 'project'. An issue with key 'MyIssueName' does not exist for field 'issue'.
Build step 'Jira Issue Updater' marked build as failure
If I try this JQL in Jira - it works.
I have Jira Standalone installation type with version 6.1
What I do incorrect?
Comment: Are you using JIRA Server or JIRA Cloud (formerly JIRA OnDemand)? And in case of the former, which JIRA Server version?
Comment: The SOAP support has been deprecated. Please use the REST version instead.
Comment: If you change the search to use matching "~" instead of the "=" on the issue, does that work?
Answer: This means the user doesn't have permissions.  Atlassian does this on purpose to confuse hackers.  I'm not sure whether you're allowed to use expletives on this site but I'd use a whole heap to describe them for doing this.
Note: that this often means you're either doing this as an anonymous user or the user you are doing this as doesn't have permissions.  You can check the later by trying to enter the JQL in the Advanced Search while logged in as the user you want.
The first case might occur if, for example, you're using the dict options in the python jira lib.  It allows you to set the basic_auth key but doesn't use it!!! (instead you have to pass the basic_auth as a keyword argument).


How to load an extension in Guile 2.0?

Question: I'm trying to load the Graphviz extension for Guile 2.0. This line of scheme code, suggested by Graphviz's documentation, works in Guile 1.8:
(load-extension "/usr/lib/graphviz/guile/libgv_guile.so" "SWIG_init")

However, it will fail in Guile 2.0 with the following error:
scheme@(guile-user)> (load-extension "/usr/lib/graphviz/guile/libgv_guile.so" "SWIG_init")
ERROR: In procedure load-extension:
ERROR: In procedure dynamic-link: file: "/usr/lib/graphviz/guile/libgv_guile.so", message: "file not found"

Entering a new prompt.  Type `,bt' for a backtrace or `,q' to continue.

I've tried using the following alternative paths as well:
/usr/lib/graphviz/guile/libgv_guile
libgv_guile

Same results. How do I do that?
Answer: The problem was that my distribution's Graphviz packages were compiled against Guile 1.8, and those two versions of Guile are not ABI compatible.
Compiling Graphviz linking against Guile 2.0 (with Guile 2.0's headers) solved it.
Answer: (load-extension "/usr/lib/graphviz/guile/libgv_guile.so" "SWIG_init")

It works for me : up to date Archlinux 64 bits, guile 2.09 and graphviz 2.30.1-7
Your error message says "File not found".
Check that the file exists and you have enough permissions.
Comment: The file exists and it works in Guile 1.8, so it is surely not a problem of this nature

How to load an extension in Guile 2.0?


volume between a sphere and cone

Question: I'm having some problems finding the volume between a sphere of radius 5 and the cone $z = -\sqrt{x^2 + y^2}$.
the bounds I got for spherical coordinates are
$0$ to $2\pi$ for $\theta$,
$3\pi/4$ to $\pi$ for $\phi$,
$0$ to $5$ for $r$, however I'm not sure if these are correct. My thought process is that if you let say $x$ or $y = 0$ in the equation for a cone, you get an inverted modulus graph which is where I got the bounds for $\phi$.
For cylindrical coordinates I got bounds of $0$ to $2\pi$ for $\theta$, $0$ to $5$ for $r$ and $0$ to $\sqrt{25-r^2}$ for $z$ and after evaluating the triple integral I got a volume of $125/3$.
Could someone run me through their thought process and show me where I went wrong?
Answer: For spherical coordinates, your bounds look fine.
For cylindrical coordinates, though, you have $0\le r\le 5$; that is wrong. $r$ ranges from $0$ to the value that $r$ takes along the circle of intersection of the cone and the sphere.
I got $\frac{125}{3}(2-\sqrt{2})\pi$ for the value of the integral.

volume between a sphere and cone


How can I apply CSS on all buttons which are present in that page?

Question: I have created a CSS style class:
.btn {
  color:#050;
  font: bold 84% 'trebuchet ms',helvetica,sans-serif;
  background-color:#fed;
  border:1px solid;
  border-color: #696 #363 #363 #696;
}

How can I apply this CSS style class to all buttons which are present in the page without adding class="btn" to every button?
Answer: If your buttons are <input type="button"> or submit, then this should do it:
input[type="button"], input[type="submit"] {
    color:#050;
    font: bold 84% 'trebuchet ms',helvetica,sans-serif;
    background-color:#fed;
    border:1px solid;
    border-color: #696 #363 #363 #696;
}

Otherwise, if your buttons are <button>:
button {
    color:#050;
    font: old 84% 'trebuchet ms',helvetica,sans-serif;
    background-color:#fed;
    border:1px solid;
    border-color: #696 #363 #363 #696;
}

To grab all three kinds of buttons:
button, input[type="button"], input[type="submit"] {
    color:#050;
    font: bold 84% 'trebuchet ms',helvetica,sans-serif;
    background-color:#fed;
    border:1px solid;
    border-color: #696 #363 #363 #696;
}

Comment: i'm using asp.net so its like
Comment: How to add Hover in this Scss?
Answer: button{
  color:#050;
  font: bold 84% 'trebuchet ms',helvetica,sans-serif;
  background-color:#fed;
  border:1px solid;
  border-color: #696 #363 #363 #696;
}

OR
input[type="button"]{
  color:#050;
  font: bold 84% 'trebuchet ms',helvetica,sans-serif;
  background-color:#fed;
  border:1px solid;
  border-color: #696 #363 #363 #696;
}

Comment: The second example is **not** CSS3. The attribute selector already exists in CSS2.1. It was only expanded in CSS3. http://www.w3.org/TR/CSS2/selector.html#attribute-selectors
Comment: IMO, this item deserves to be marked as the answer; IOW, I think it deserves a green check mark.
Answer: input[type=submit], input[type=button], button {
   ...
}

Comment: Always add a description to what the code does to make your answer more helpful
Answer: If you don't want to explicitly set all the styles, but want to use the styles already defined in some pre-existing class (for example the bootstrap btn-default class), you could do something like this:

In my case this was what I was looking for, although I'm sure there is some sort of caveat about doing it this way, or you'd expect it was something doable directly from CSS.
Answer: just a note
input[type="button"]

isn't going to work on old browsers like IE6. If that's a problem you will unfortunately need to add your class to each item.


How to prove three vectors are in same plane?

Question: I know that three vectors lie on the same plane if and only if u.(v×w)=0.
(VxW) gives us a vector which is perpendicular to the plane.But if u vector is on another plane which plane is parallel to (VxW) plane still we get u.(V×W)=0.Then how can i be sure about that three vectors are in same plane?
Comment: Vectors are not generally "in the plane". Vectors begin at the origin and offer only directions and magnitudes.
Comment: Vectors are *not* arrows floating through space. Unfortunately, the only ultimately valid definition of vector is: "an element of a vector space"
Comment: Three vectors are in te same plane if one of them is combinaison of two others.
Answer: Hint: Assume that $u$ and $v$ are not proportional (or else there's nothing to do), and write $w$ as a linear combination of $u$, $v$ and $u\times v$. Check the coefficient in front of $u\times v$ is precisely $u\cdot (v\times w)$.
Answer: If you're dealing with a three-dimensional Euclidean vector space -- the kind of vector space where it makes sense to say $V\times W$ is perpendicular to $V$ and $W$ -- then a vector is just a direction and distance (or length) in three dimensions.
If a vector $u$ is parallel to a vector $u'$, in the same direction as $u'$, and is the same length as $u'$, then $u = u'.$
So what is this vector $u$ that is parallel to the plane of $v$ and $w$ but is not in the plane of $v$ and $w$?
You may think that the vector $u$ can be outside the $v, w$ plane if you put its starting point outside the $v, w$ plane. But "starting point" is not a distinguishing property of vectors in this vector space. Only direction and length can make two vectors different.


How to find the remainder of dividing polynomial $x^{2016}-x^{2015}-1$ with $x^2+1$

Question:
What is the remainder of dividing polynomial
  $$P(x)=x^{2016}-x^{2015}-1$$
  with $x^2+1$?

So what I thought of doing is just dividing them the "school" way:
$(x^{2016}-x^{2015}-1)\div(x^2+1)=x^{2014}-x^{2013}-x^{2012}+x^{2011}\cdots$
But the problem is that this way it just goes on and on, and I can see that it should end up with $x$ as a remainder, but what's the way I can prove that, without knowing that it ends up in $x$?
The other way I thought of solving this is by maybe presenting that:
$P(x)\div(x^2+1)=Q(x)+y$,
so for $P(i)$
$i^{2016}-i^{2015}-1=y$,
where $i^2=-1$, and this way I get
$y=-i$
but that seems incorrect, since I can see that the regular division would end up to $x$.
Comment: Here's a broad hint: you know that $x^2\equiv -1\pmod {x^2+1}$; this means that $x^4\equiv 1\pmod{x^2+1}$. Can you continue from there?
Comment: Aleksa, I think you mean to correct the typo to read $P(x)=Q(x)(x^2+1)+y$. If you leave it as it currently is, you should correct it to $P(x)/(x^2+1)=Q(x)+\frac{y}{x^2+1}$. (Please note that this formulation is still invalid, but it is more in line with your approach.)
Comment: @Clayton I'll leave it as it is, since it's a mistake I made in the first place. Anyone reading the whole post with answers will see that it's incorrect.
Answer: Your approach works except that it is not fully general: because $x^2+1$ is quadratic, the quotient-remainder form should be
$$
   P(x) = Q(x)(x^2+1) + ax+b
$$
for some unknown $a$ and $b$.
Now we can set $P(i) = Q(i)(0) + ai + b$, getting one equation for $a$ and $b$. We can also set $P(-i) = Q(i)(0) + a(-i) + b$, getting another equation, because $x^2+1$ is $0$ when $x=i$ or when $x=-i$.
Solving for $a$ and $b$, you should get $a=1$ and $b=0$.
Comment: We don't need to solve any equations since $\,P(i) = ai+b\,$ implies the remainder $= ax+b,\,$ see my answer.
Comment: @BillDubuque This is true in the special case of division by $x^2+1$ when the coefficients of $P$ are real; in this case, if $P(i) = ai+b$, we know that $P(-i) = P(\overline{i}) = \overline{P(i)} = a(-i)+b$, so in general the remainder is $ax+b$. But in some more general case, we would need to solve the equations.
Comment: The idea works *much* more generally, e.g. using roots of  an  irreducible polynomial. This will be clear when one studies ring theory.
Comment: @BillDubuque I am familiar with the ring theory, thank you. This means that I know when the idea applies and when it does not. However, the asker of the question may not know when the idea applies and when it does not, so you do not need to condescend to me just because I have tried to give an answer that does not require ring theory.
Comment: Generally my answers and comments are targeted as widely as possible, i.e. not at you but anyone who may be reading (hence I wrote "when *one* studies", not "when *you* study").  Also, keep in mind that it is usually not easy to infer the knowledge level of an answerer from a single answer.
Answer: The remainder of $P(x)$ with $Q(x)$ stays invariant if we add or subtract a multiple (which can be a polynomial) of $Q(x)$ from $P(x)$. So, we can evaluate the remainder in the analogous way as we would do in case if ordinary numbers using modular arithmetic.
We thus need to do the computations modulo $Q(x) = x^2 + 1$. Since:
$$x^2 = -1 \bmod Q(x)$$
we have:
$$x^{2016} = 1 \bmod Q(x)$$
$$x^{2015} = x^3 \bmod Q(x) = -x \bmod Q(x)$$
Therefore:
$$x^{2016} - x^{2015} - 1 = x \bmod Q(x)$$
Answer: $\!\bmod\, x^{\large 2}\!+\!1\!:\,\ x^{\large 2}\equiv -1\,\Rightarrow\, \color{#0a0}{x^{\large 3}\equiv -x}\,\Rightarrow\,\color{#c00}{x^{\large 4}\equiv 1}\,\Rightarrow\, x^{\large\color{#c00}4q+r} = (\color{#c00}{x^{\large 4}})^{\large q} x^{\large r} \equiv\, x^{\large r}$
$\begin{align}{\rm Therefore}\ \ \ \qquad x^{\large\color{#c00} 4n}\! - x^{\large \color{#c00}4k\color{#0a0}{+3}} &-\, 1\\
\equiv\quad\  1\ \  \,-\,\ \ \color{#0a0}{\large x^3} &-\, 1\, \equiv\, \color{#0a0}x\ \end{align}$
Remark $ $ Above $x$ like $i$ is a square root of $-1$. If you know a little ring theory you know how to say this much more precisely $\,\Bbb Z[x]/(x^2+1)\cong \Bbb Z[i],\,$ so replacing $x$ by $i$ above gives an isomorphic calculation in the Gaussian integers. So we can use numbers to deduce results about polynomials!
Comment: I am always surprised how few people seem to get this way of looking at things.
Answer: Okay so I got where I messed up.
for $P(i)$
$i^{2016}-i^{2015}-1=y\\1-(-i)-1=y\\y=i$
And since I did it for $P(i)$, it should be
$y=x$,
which means that the remainder of dividing those polynomials is $x$, which seems correct.
Correct me on this if I'm wrong somewhere.
Comment: I don't think this idea works since you end up with $P(i)/0=0+y$. You're using that $x^2+1=0$ on the right-hand side but not on the left-hand side (which causes a division by $0$).
Comment: @Clayton Yes but in this case I just say that $x^{2016}-x^{2015}-1=Q(x)(x^2+1)+y$, there is no division in this case.
Comment: @Aleksa: If you write the formula correctly, I agree. But if you look at your original post, you have $P(x)/(x^2+1)=Q(x)(x^2+1)+y$. See Misha's correction for an approach similar to this
Comment: It could be that $y=x$, or that $y=i$ no matter what $x$ is, or that $y=2x-i$. There is no way to know without a second equation.
Comment: @Clayton Perhaps then you should say "you made a typo" not "your math is all wrong".
Comment: @MishaLavrov: I didn't catch the typo when I wrote my comment. I based Aleksa's approach off of her math in the original post. And for what it's worth, I didn't say, "Your math is all wrong." I tried to be polite and explain that I didn't think the approach worked and gave a reason as to why I didn't think it worked (again, this latter part is based off of what is shown in the original post, typo or not).
Comment: @Clayton The idea can be made rigorous - see my answer.
Comment: Thanks, @BillDubuque. Isn't your method the same as Count Iblis, though? I mentioned to Aleksa to have a look at Misha's answer only because it followed a similar line of reasoning without relying on congruence classes (although I think your approach is cleaner, just perhaps outside the scope of Aleksa's current course).
Comment: @Clayton Yes, I didn't notice that. They do both use modular methods


regex condition that returns only if a " [word]" does not trail at the end

Question: I'm new at regex, and somebody helpfully showed me the following a few minutes ago:
(?:^|(?<=\D))\d{4}-\d{1,5}(?=\D|$)

Now I would like to deploy its findings only if the strings it's looking for are not immediately trailed by a space and the word "Dog"
E.g., it would return a value if "2013-29883" is encountered, but not if "2013-29883 Dog" is encountered.
Thank you for any help.
Comment: what language are you using? what environment? what version? what are you trying to accomplish?
Comment: http://www.regular-expressions.info/lookaround.html
Comment: Python.  (And I saw regular-expressions.info mentioned quite a few times here, and have visited it and gotten some other valuable search/iteration information from the site, but I'm just not that up to speed on this parsing syntax yet.)
Answer: The regex can be shortened by quite a few characters:
(?<!\d)\d{4}-\d{1,5}(?!\d)

And so that it doesn't match 2013-29883 followed by Dog, use another negative lookahead:
(?<!\d)\d{4}-\d{1,5}(?!\d)(?! Dog)

Answer: if it is in c# then you can use Regex class:
     string pattern = "(?:^|(?<=\D))\d{4}-\d{1,5}(?=\D|$)";

     if(Regex.IsMatch(input, pattern))
     {
        // Your code of a match
     }

Comment: Thank you.  I use C# for other stuff, but this one is a Python job.


pass varible in collection resource laravel api

Question: i have this function
public function activityAutoDeposit(GoalRequest $request)
{
    $goal = Goal::find($request->input('goal_id'));
    if($goal->user_id != auth()->id()) {
        return $this->responseData([], 'forbidden card', true);
    }
    $schedule_deposit = DB::table('rules')
        ->join('cards', 'rules.card_id', '=', 'cards.id')
        ->join('rules_schedule_deposits', 'rules.id', '=', 'rules_schedule_deposits.rule_id')
        ->select('rules_schedule_deposits.*')
        ->where('table', '=', 'rules_schedule_deposits')
        ->where('cards.user_id', '=', auth()->id())
        ->get();

    return $this->responseData(AutoDepositResource::collection($schedule_deposit ,$goal->distribution->percentage ));
}

i want to pass the varible $goal->distribution->percentage to the resource collection .. i wrote in AutoDepositResource class this constructor
public $att;

public function __construct($resource , $att)
{
    #parent::__construct($resource);
    $this->resource = $resource;
    $this->att = $att;
}

but the value i get 0 , 1 ,2 +++ .. i did not recive the correct value
Answer: JsonResource does not support multiple parameters. Use single resource parameter.
public function activityAutoDeposit(GoalRequest $request)
{
    $resource = (object) [
        'schedule_deposit' => $schedule_deposit,
        'goal_distribution_percentage' => $goal->distribution->percentage,
    ];

    return $this->responseData(
        AutoDepositResource::collection($resource)
    );
}

class AutoDepositResource extends JsonResource
{
    public function toArray($request)
    {
        return [
            'schedule_deposit' => $this->schedule_deposit,
            'goal_distribution_percentage' => $this->goal_distribution_percentage,
        ];
    }
}


Can the system of equations be extracted from its solution?

Question: While I was solving the secondary school exam of 2014 I came across a question that states:
After solving those equations: $a_{1}x + b_{1}y = c_{1}$ and $a_{2}x + b_{2}y = c_{2}$, we found that x = $\frac{-7}{\begin{vmatrix}
  3 & 1 \\
  1 & -2
 \end{vmatrix}}$ and y = $\frac{-21}{\begin{vmatrix}
  3 & 1 \\
  1 & -2
 \end{vmatrix}}$, then $c_{1} = .....$ and $c_{2} = .....$
The answer is $c_{1} = 6$ and $c_{2} = -5$ in the ministry's model answers on its website with no steps available ,but it was probably solved by Cramer's rule.
Is this answer right and does $c_{1}$ and $c_{2}$ have only one value?
Answer: Presumably the denominator $\left|\matrix{3 & 1\cr 1 & -2}\right|$ indicates that the coefficient matrix $\pmatrix{a_1 & b_1\cr a_2 & b_2} = \pmatrix{3 & 1\cr 1 & -2}$.  Then we have
$$ \pmatrix{c_1 \cr c_2} = \pmatrix{3 & 1\cr 1 & -2} \pmatrix{x\cr y\cr} = \pmatrix{3 & 1\cr 1 & -2} \pmatrix{1\cr 3\cr} = \pmatrix{6\cr -5\cr}$$
agreeing with the ministry's answer.
Comment: Is this mathematically correct? can I deduce the matrix from the determinant? As much as I know the determinant represents only a value,so there's infinity determinants with the same value that could be the coefficient matrix. for example: $\begin{vmatrix}
  -3 & -2 \\
  1 & 3
 \end{vmatrix}$
Comment: You are perfectly right. It is a case where one has to think to the simplest solution ("Occam's razor"), trying to think as the person who has given the problem. Solve it, then make your remark.
Comment: so this answer is as they thought of :D. I was wondering if it's a correct answer "mathematically " @JeanMarie
Comment: That's it. And the ministry is right, by definition.
Comment: The assumption is that they are not trying to fool you: by putting that determinant in the denominator, they are indicating that the solution process involved expressions with that determinant in the denominator.  Of course there are lots of other matrices with the same determinant, but when solving a system of linear equations the most likely reason for evaluating expressions with a determinant in the denominator is that you are using Cramer's rule and the determinant comes directly from the coefficient matrix.
Answer: In view of the main determinant:
$$\begin{vmatrix}3 & 1\\1 & -2\end{vmatrix}$$
one may infer that the system is
$$\begin{cases}3x_1+x_2&=&c_1\\1x_1-2x_2&=&c_2\end{cases}$$
Using Cramer's rule (https://en.wikipedia.org/wiki/Cramer's_rule), the two numerators can be written under the form:
$$\begin{vmatrix}c_1 & 1\\c_2 & -2\end{vmatrix}=-7 \ \ \text{and} \ \ \begin{vmatrix}3 & c_1\\1 & c_2\end{vmatrix}=-21$$
This can be transformed into a linear system:
$$\begin{cases}-2c_1-c_2&=&-7\\-c_1+3c_2&=&-21\end{cases}$$
Solving this system gives $c_1=6$ and $c_2=-5$, as indicated.
Comment: the main determinant = $\begin{vmatrix}
  3 & 1 \\
  1 & -2
 \end{vmatrix}$ = $\begin{vmatrix}
  a_{1} & b_{1} \\
  a_{2} & b_{2}
 \end{vmatrix}$.does this mean that $a_{1} = 3$ , $a_{2} = 1$, $b_{1} = 1$ and $b_{2} = -2$?If we put $a_{1}$, $a_{2}$, $b_{1}$ and $b_{2}$ with the values -1, 1, 1, 6 respectively the determinant will be the same value and x and y wouldn't change but $c_{1}$ and $c_{2}$ would have different value.
Comment: See my remark above : you have seen that I have used the very diplomatic "one may infer that..." and my colleague has said "Presumably"...
Comment: before that step you presumed that
x = $\frac{-7}{\begin{vmatrix}
  3 & 1 \\
  1 & -2
 \end{vmatrix}} = \frac{det(A_{1})}{det(A)}$ means that $det(A) = \begin{vmatrix}
  3 & 1 \\
  1 & -2
 \end{vmatrix}$.it's something like saying $\frac{1}{2} = \frac{2}{4}$ means 1 = 2 and 2 = 4.
Comment: and after that you said $\begin{vmatrix}
  3 & 1 \\
  1 & -2
 \end{vmatrix} = \begin{vmatrix}
  a_{1} & b_{1} \\
  a_{2} & b_{2}
 \end{vmatrix}$ means $a_{1} , b_{1} ,  a_{2}, b_{2}$ equals 3, 1, 1, -2.this is also like saying $\begin{vmatrix}
  1 & 1 \\
  1 & 1
 \end{vmatrix} = \begin{vmatrix}
  0 & 0 \\
  2 & 2
 \end{vmatrix}$ means 0 = 1 and 1 = 2.this doesn't seem quite right.


How to get value from HashTable and call the function from this object?

Question: I created Class Disk
Disk disk1 = new Disk();

Hashtable myCatalog = new Hashtable();

try
{
    myCatalog.Add("Disk1", disk1);
}
catch
{
    Console.WriteLine("An element with Key = \"Disk1\" already exists.");
}

Disk  valueColl = (Disk)myCatalog.Values;
        valueColl.

And here I have a problem.
How I can use this method ShowCompositions();
Comment: Sidenote: `Hashtable` dates from the earliest days of .NET.  There's almost certainly a better type to use now, perhaps `Dictionary`.
Comment: myCatalog["Disk1"].ShowCompensation() ... or if you want all, use foreach on myCatalog.Values
Answer: Values is a ICollection containing the values in the Hashtable.
You could do this.
Disk  valueColl = (Disk)myCatalog["Disk1"]; // access element with `Key`
valueColl.ShowCompositions(); // this will work

On other note as @jamesthorpe highlighted in comments , try using Dictionary over Hashtable, it has added advantages.
Answer: Easiest way
Hashtable hashtable = new Hashtable();
        foreach (DictionaryEntry entry in hashtable)
        {
            Console.WriteLine("{0}, {1}", entry.Key, entry.Value);
        }

Comment: Add value in hash table like hashtable[1] = "One";
            hashtable[2] = "Two";
            hashtable[13] = "Thirteen";


Show custom error on Finish page in Inno Setup based on the exit code from a custom script

Question: I am using following Inno Setup code to run a PowerShell script and redirect its output to custom progress page:
Create a button on Inno Setup custom wizard page to interrupt an program executed from the installer
What I want is to show custom error messages on Finish page based on the errors thrown by PowerShell script instead of default Finish page with default message.
I have configured the PowerShell script to give specific error codes in case of specific failures. I have used something like this:
Write-Output $Error.Exception.Message
Exit 1000

Here 1000 is custom error code when script exits.
Is it possible to display custom error message on Finish page of Inno Setup based on the error code as shown above?
Answer: To retrieve the exit code, use GetExitCodeProcess:
function GetExitCodeProcess(Process: THandle; var ExitCode: Cardinal): Boolean;
  external 'firstname.lastname@example.com stdcall';

somewhere after the process completes. In your case, it's somewhere after the while not Completed do loop completes:
var
  ExitCode: Cardinal;

GetExitCodeProcess(ExecInfo.hProcess, ExitCode);

Then use the ExitCode to create or modify the labels on WizardForm.FinishedPage.


Prove that a function between two topological spaces is a homeomorphism

Question: Is the complement of the closed unit disk in the plane homeomorphic with $\mathbb R^2\setminus \{(0,0)\} $ ?
My question is about the above, somebody has defined a function and its fine. But for proving that the function is homeomorphism we need to show that $f(U)$ is open if and only if $U$ is open.($f$ here means that function.)
I do not know how to prove "$f(U)$ is open if and only if $U$ is open".
Thank for your time.
Comment: Also note that in polar coordinates (which are valid in $\mathbb R^2\smallsetminus \{0\}$, your function is given by $(r,\theta)\mapsto (r+1,\theta)$, which has a very easy to define inverse.
Comment: It is maybe better to find the inverse, and show that it is continuos as well
Comment: If you have already shown it is a bijection, then your work in showing it is a surjection may give you a clue into how to construct an inverse. If you want to show it is a homeomorphism, and you have already shown it is a bijection, it suffices to that any $\epsilon$-ball in $\mathbb R^2-\{0\}$ gets mapped to an open set in $\mathbb R^2-D^2$.
Comment: I got that @Chris, Thanks.
Comment: I could find that inverse which is $(x,y) \mapsto (x,y)(1-1/(\sqrt{x^2+y^2}))$, but I still can not show that every open ball will mapped to an open set. @Chris
Comment: If you have the inverse, and it's continuous then you are done
Comment: Is it Ok to proof the continuity of inverse or the main function with metric space tools? I mean using epsilon-delta or equivalently limitation notation. @Chris
Comment: Absolutely, epsilon delta is equivalent to inverse image of every open is open
Comment: great, Thank you!
Answer: The accepted answer to the linked question says that
$$h : \mathbb R^2 \setminus \{ (0,0) \} \to \mathbb R^2 \setminus D^2, h(x) = x + \frac{x}{\lVert x \rVert} = \frac{\lVert x \rVert + 1}{\lVert x \rVert}x \tag{1}$$
is a homeomorphism. The map $h$ is well-defined since
$$\lVert h(x)\rVert = \frac{\lVert x \rVert + 1}{\lVert x \rVert} \lVert x  \rVert = \lVert x  \rVert +1  > 1 \tag{2}$$
Clearly $h$ is continuous.
Of course one can try to show directly that $h$ is a bijection and an open map, but is more efficient find an inverse for $h$. Looking at $(1)$ suggests that
$$g: \mathbb R^2 \setminus D^2 \to \mathbb R^2 \setminus \{ (0,0) \}, g(y) = \frac{\lVert y \rVert - 1}{\lVert y \rVert}y \tag{3} $$
is the right candidate. The map $g$ is well-defined since $\lVert g(y) \rVert = \frac{\lVert y \rVert - 1}{\lVert y \rVert} \lVert y  \rVert = \lVert y  \rVert - 1  > 0$. Clearly $g$ is continuous.
Using $(2)$ we get
$$g(h(x)) = \frac{\lVert h(x) \rVert - 1}{\lVert h(x) \rVert}h(x) = \frac{\lVert x \rVert}{\lVert x \rVert + 1}\frac{\lVert x \rVert + 1}{\lVert x \rVert}x = x$$
which means $g \circ h = id$. Similarly we get $h \circ g = id$.
This proves that $h$ and $g$ are homeomorphisms which are inverse to each other.


simple custom video player for ios

Question: I am developing an app in which I wanna show the tutorial on how to use the app. For that need a custom video player which should look simple with a single play/pause button, a seeker and a stop button.
                    I have tried some video players like "videoplayerkit". To use this videoplayerkit I have to install cocoapods(libpods.a).  It would be very helpful if anyone help me with a custom third party video player that satisfies my need. In short I need something like this in the picture below
Comment: Looks like you want `MPMoviePlayerViewController`. Not sure about the "video-cloud player" thought.
Comment: Check this [tutorial](http://www.engage-encore.com/index.php/2010/11/08/video-player-ipad-iphone/). This may help you.
Comment: Thank you for your response. I dont wanna use ios's default video player. That is why I asked for a custom one
Answer: You can try out an example app I created if you would like to see an example of a custom movie player, the Xcode project is at AVSync. This movie player looks exactly like the default iOS movie player, but you can have a look at the code to see how a custom set of controls can be made to control a movie player underneath. This example sits on top on a custom movie library, but the basic idea of creating your own controls and having them submit actions is the same no matter how you implement it.

simple custom video player for ios


I want to create a view with filters filters

Question: I want to create a view with Better Exposed filters, filters exactly like in
http://www.shopmgd.com/gold-jewellery.html. I am new to drupal, so somebody please help How can i do dis? I am using drupal 7.
Comment: Check out this tutorial https://www.youtube.com/watch?v=2JP0_CxW1_I it should get you going.
Comment: I had tried the tutorial before, my problem is i'm struggling to bring format options in one block region(sidebar) and the formatted display in content region. can you please help me out
Comment: You need to expose your filters in a block and place it in a region, check out this tutorial http://s1l.org/views-3-exposed-filters-block You should edit your question also as you don't really specify what you need help with.
Answer: Not sure how to close this question but I'll add my comments as answer so that Jumma can approve and close it.
You need to expose your filters using the Better Exposed filters module, see this tutorial.
To place your exposed filter in one region and the result of the view in another region you need to expose your filters in a block. See this tutorial learn how to do that.


Task Schedular VBScript to generate a Message Pop-up

Question: I need to create a task made in Vb Script for  Windows Vista & Windows 7 that will show a message pop-up to the user. That task will run every Monday and Friday at 9am. The message window should contain 2 button (Yes/No). For Yes->Open a web-link and No->Exit.
I found some information on internet but that is all about starting a program like Notepad.
Example: http://msdn.microsoft.com/en-us/library/aa394601%28v=vs.85%29.aspx.
I am not able to find how to generate a message popup along with buttons.
Can anyone help ? Thanks.
Comment: Start your research here http://msdn.microsoft.com/en-us/library/sfw6660x%28v=vs.84%29.aspx and here http://msdn.microsoft.com/en-us/library/d5fk67ky%28v=vs.84%29.aspx (follow the link to .Exec). Avoid WMI if you can.
Comment: Thanks Horner, I have made the VBS file which is running perfectly. I just now want to schedule it.  I want to avoid doing the manual work because this VBS needs to be scheduled in the machines of my team mates. I dont want all of them to assign this VBS in the task schduler from GUI. Thats why now I need to choose WMI. I hope you understand.
Comment: Hi Horner, How can I use EXEC method to run a task even after the system restart ?
Answer: <code>choice = msgbox( " That task will run every Monday and Friday at 9am ", 3, "test ")
</code>
this should give you " yes, no and cancel " options.
Comment: Hi Timrau, How can I use this message in VBScript ?
And also how can I apply action on YES,No and Cancel buttons ?


PasswordDeriveBytes (System.Security.Cryptography) fails if disposed

Question: The usage of the PasswordDeriveBytes class in a using block (which disposes it, because it implements IDisposable) creates a problem if the class is used a second time. This is the code:
public class AES
{
    protected static CryptoData localCryptoData;

    static AES()
    {
        localCryptoData = new CryptoData();
    }

    public static string Encrypt(CryptoData cryptoData)
    {
        using (PasswordDeriveBytes pass = new PasswordDeriveBytes(cryptoData.Password, cryptoData.Salt, "SHA1", 2))
        using (RijndaelManaged symmetricKey = new RijndaelManaged())
        {
            byte[] keyBytes = pass.GetBytes(cryptoData.KeySize / 8);
            symmetricKey.Padding = PaddingMode.PKCS7;
            symmetricKey.Mode = CipherMode.CBC;

            using (ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, cryptoData.InitVector))
            using (MemoryStream memoryStream = new MemoryStream())
            using (CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
            {
                cryptoStream.Write(cryptoData.ByteText, 0, cryptoData.ByteText.Length);
                cryptoStream.FlushFinalBlock();
                return Convert.ToBase64String(memoryStream.ToArray());
            }
        }
    }

    public static string Decrypt(CryptoData cryptoData)
    {
        using (PasswordDeriveBytes pass = new PasswordDeriveBytes(cryptoData.Password, cryptoData.Salt, "SHA1", 2))
        using (RijndaelManaged symmetricKey = new RijndaelManaged())
        {
            byte[] cipherTextBytes = Convert.FromBase64String(cryptoData.Text);
            byte[] keyBytes = pass.GetBytes(cryptoData.KeySize / 8);
            symmetricKey.Padding = PaddingMode.PKCS7;
            symmetricKey.Mode = CipherMode.CBC;

            using (ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, cryptoData.InitVector))
            using (MemoryStream memoryStream = new MemoryStream(cipherTextBytes))
            using (CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read))
            {
                byte[] textBytes = new byte[cipherTextBytes.Length];
                int count = cryptoStream.Read(textBytes, 0, textBytes.Length); //throws CryptographicException - Padding is invalid and cannot be removed.
                return Encoding.UTF8.GetString(textBytes, 0, count);
            }
        }
    }

If this class is used in this manner:
AES.Encrypt(cryptoData);
 AES.Decrypt(cryptoData);
Ths first use gives you a correct AES encrypted string, but if fails with an exception when trying to decrypt the same string. The problem lies in the assigning of the first parameter (The password to derive the key from) from the PasswordDeriveBytes class, when this password is given through a Byte array. If it is given as a string (because of the overload) it works ok.
The helper CryptoData class:
public class CryptoData
{
    private string text;
    public string Text
    {
        get { return text; }
        set
        {
            text = value;

            if (value != null)
            {
                ByteText = Encoding.ASCII.GetBytes(value);
            }
            else
            {
                ByteText = null;
            }
        }
    }

    public byte[] ByteText { get; private set; }
    public byte[] Password { get; set; }
    public int KeySize { get; set; }
    public byte[] InitVector { get; set; }
    public byte[] Salt { get; set; }
}

If you just change this row in the methods:
using (PasswordDeriveBytes pass = new PasswordDeriveBytes(cryptoData.Password,
      cryptoData.Salt, "SHA1", 2))

into
using (PasswordDeriveBytes pass = new PasswordDeriveBytes("somePassword",
         cryptoData.Salt, "SHA1", 2))

everything works fine. The problem is, the instance of PasswordDeriveBytes does not get the byte array for password the second time used, because of the using statement. If a string has been passed, instead of a byte array, it works.
Edit: After reviewing it closer, it seems that there is a problem in the default property setter for the password parameter. It gets the pointer of the array, and that is why it is disposing it. It should make a value.clone() of the array, as is the case with the salt array.  It's a definite bug.
Am I right, or am I doing something wrong?
Edit:
*Change the first line in AES.Encrypt() and AES.Decrypt methods with this and it works: *
 using (PasswordDeriveBytes pass = new PasswordDeriveBytes(
        (byte[])cryptoData.Password.Clone(),
        cryptoData.Salt, "SHA1", 2))

Comment: Note that `PasswordDeriveBytes` has many, many things wrong with it. You should use `Rfc2898DeriveBytes` instead. If you use it, use it for max of 20 bytes. You also seem to generate a random IV implicitly, and then forget about it.
Comment: Please read and understand the code. Nobody uses the same object twice. There are different methods.
Comment: Can you post the exception details, including stack-trace?
Comment: @Ramhou - you're totally off track. When the array contains Value types (bytes) there is no shallow/deep copy. The workaround simply uses a copy of the password array to be used & zeroed.
Comment: You're right, I could verify this. Weird.
Comment: @Ramhound - can you expand on that? The holder of the array does not seem to matter here. The issue is that the Password class zeroes one of its params.
Comment: @Ramhound - it's not a bug in my code, it's a bug in the PasswordDeriveBytes class. If it were my bug, then the salt that I use (which is also a byte array) should also be nullified like it is done with the password array. Another thing, an object is by convention passed by value, and a class using an input parameter isn't allowed to change this parameter directly. It can use it, but must not change it. Ergo, the salt array stays unchanged, the password array is changed. <- A Bug.
Comment: You can't use an object after it has been disposed.
Comment: "It gets the pointer of the array, and that is why it is disposing it. " - You cannot dispose an array, and it seems very unlikely it would alter anything inside the array.
Comment: @Henk well, dispose is a wrong word for the array, but it actualy clears the array with Array.Clear(), which makes it all zeroes.
Comment: This happens in the dispose method of the PasswordDeriveBytes, and that is why I said it was disposing it.
Comment: The reason you ran into this problem is you were not using a reference to the `cryptoData` the reason cryptoData.Password.Clone() works is you send a cloned reference to the array.**"It's a definite bug.**" - I agree the bug was in your code.
Comment: @HenkHolterman - Its just something I noticed.
Answer: This is certainly counter-intuitive and undocumented behavior, although whether or not it is a bug could possibly be debated. Basically, when you pass the password byte array to the constructor, the PasswordDeriveBytes instance is taking ownership of that array. This is similar to the way StreamReader takes ownership of the Stream which is passed to it, and will Dispose it when it is Disposed (this behavior was also criticized on similar grounds, which led to the addition of a boolean parameter to the StreamReader constructor in .NET 4.0 which can prevent the underlying stream from being Disposed).
Cloning the byte array before you pass it in is probably your best option.


Web cam on RDS 2012 r2 clients?

Question: My RDS clients (Win 8.1) needs to use Web Cam (in Lync) on their Win2012R2 RDS (Session Host).
How do I set this up?
I've found several of articles online, but they are all for Win2008R2. Is it still by using RemoteFX?
Thanks
Answer: First of all, yes you still use RemoteFX and USB Device Redirection.  There have been some nice improvements for both of these in 2012, one of which is the isolation feature.  That should help your users do what they need to with their webcams.
See this for how to setup RemoteFX
See this for USB Device Redirection
Make sure you note that Appendix A (from the USB Device Redirection Guide) does indeed say that 2012 redirection includes Webcams, but it is for LAN only.  Just FYI on that.
Please let me know if you get hung up along the way when setting this up and I'd be glad to help.

Web cam on RDS 2012 r2 clients?


Show that this probability distribution is an exponential family

Question: We define a probability distribution on the non-negative integers 0,1,2,...,as having point probabilities $$P_\eta(k)=G(k,\rho)\left(\frac{1}{\rho+\eta}\right)^{\rho}\left(\frac{\eta}{\rho+ \eta}\right)^k$$ for $\eta, \rho>0$. A explicit expression for $G(k,\rho)$ is not needed just that $\sum_{k=0}^{\infty}p_{\eta}(k)=1$.
I have to show that this is an exponential family and find cumulant function.
I have tried by converters and doing exponential and log tricks to get the expression:
$$f(x) = \exp{\left(\frac{\theta x- b(\theta)}{a(\phi)} + c(x,\theta)\right)}$$
(where c is cumulant function), but have not succeeded. Can anyone help me?
Comment: At https://stats.stackexchange.com/questions/519578/is-poisson-lindley-an-exponential-family-if-not-why/519715#519715 I provide a general procedure to solve problems of this nature, along with a worked example that is close to yours.
Answer: Showing the probability distribution is an exponential family: The notation is a bit different from what I'm used to, but this looks similar to the Negative Binomial distribution
with parameters $ (\rho,\eta) $; that is,
$$ f(k;\rho,\eta)=G(k,\rho)\biggl(\frac{1}{\rho+\eta}\biggr)^{\!\rho}\biggl(\frac{\eta}{\rho+\eta}\biggr)^{\!k},\; k=0,1,\ldots, $$
where $\rho,\eta>0$.
Note that
\begin{align*}
    f(k;\rho,\eta)
    &=\exp\Bigl\{\ln\bigl(f(k;\rho,\eta)\bigr)\Bigr\}\\
    &=\exp\Biggl\{\ln\biggl(G(k,\rho)\biggl(\frac{1}{\rho+\eta}\biggr)^{\!\rho}\biggl(\frac{\eta}{\rho+\eta}\biggr)^{\!k}\biggr)\Biggr\}\\
&=\exp\Biggl\{\ln\bigl(G(k,\rho)\bigr)+\rho\ln\biggl(\frac{1}{\rho+\eta}\biggr)+k\ln\biggl(\frac{\eta}{\rho+\eta}\biggr)\Biggr\}.
\end{align*}
Now, define
\begin{align*}
\theta&=\ln\biggl(\frac{\eta}{\rho+\eta}\biggr)\implies \eta=-\frac{e^{\theta}\rho}{e^{\theta}-1}\\
b(\theta)&=-\rho\ln\biggl(\frac{1}{\rho+\eta}\biggr)=-\rho\ln\Biggl(\frac{1}{\rho-\frac{e^{\theta}\rho}{e^{\theta}-1}}\Biggr)=-\rho\ln\biggl(\frac{1-e^\theta}{\rho}\biggr)\\
a(\phi)&=1\\
c(k;\phi)&=\ln\bigr(G(k,\rho)\bigl).
\end{align*}
Therefore, we have shown that this is a member of the exponential family, that is,
$$f(y;\theta,\phi)=\exp\biggl\{\frac{y\theta-b(\theta)}{a(\phi)}+c(y;\phi)\biggr\}.$$


A better visualization for comparison?

Question: How can I fill with a color in one side of the diagonal of the following graph (only one triangle area) in R? I have used abline(0,1) for drawing the diagonal line. However, as we can see the the diagonal line is not perfect in the left-bottom corner. Could someone help me to draw a perfect diagonal line that starts exactly from the left-bottom corner, please.
Comment: Are you sure you really meant to change the title to include "Time Series"? The question at hand has nothing intrinsically to do with time series data (unlike your other [question](http://stats.stackexchange.com/q/14898/1036)).
Comment: @Andy: You are right. I have removed the word time-series.
Answer: I'm not entirely sure if this is what you had in mind, but it could be a start:
x    <- runif(40, 0.2, 0.9)  # x coordinates
y    <- runif(40, 0.2, 0.9)  # y coordinates
lims <- c(0.1, 1)            # axis limits for x and y

With the plot() arguments xaxs="i" and yaxs="i", the axes start and end exactly at the given axis limits. The diagonal line will then be placed where you wanted it. With type="n", the plot is initially empty, so we can add the triangle polygon, and then plot the data points over it.
plot(x, y, type="n", xlim=lims, ylim=lims, xaxs="i", yaxs="i")
polygon(c(lims, rev(lims)), c(lims, 0, 0), col="yellow")  # lower right triangle
abline(0, 1)
points(x, y, pch=20, col="blue")

If you want the data points themselves to have different colors depending on which triangle they lie in, you first have to do a suitable logical comparison to identify these points. In your case, it's just all points with a y-coordinate bigger than the x-coordinate.
below <- y < x            # points in lower right triangle
plot(x, y, type="n", xlim=lims, ylim=lims, xaxs="i", yaxs="i")
points(x[below], y[below], pch=16, col="red")
polygon(c(lims, rev(lims)), c(lims, 1, 1), col="yellow")  # upper left triangle
abline(0, 1)
points(x[!below], y[!below], pch=20, col="blue")

Comment: Thanks for this nice idea. However, I am unable to get the second figure with the code you have provided. Is code for the second graph fine? If not, could you please port correct code.
Comment: @kkp Strange, did you run the first three lines defining `x`, `y`, and `lims` before continuing with the second example?
Comment: You are right. I missed a couple of lines. Thanks for your time.

A better visualization for comparison?


Create pcolormesh from 1D array

Question: I have a 1D array C = [1.0, 1.0, 0.93, 0.6, 0.28, 0.42, 0.53, 0.5, 0.42, 0.45] and want to display it visually with Matplotlib. I tried using pcolormesh, but it only seems to work with 2d arrays like C2D = [C[5:], C[:5]]. This 2D array creates the following plot:

However, what I want is something like this:
Answer: Simply turn you 1D list into a 2D matrix with just one row:
plt.pcolormesh([C])

Create pcolormesh from 1D array


Ajuda escapar caracteres especiais php

Question: Estou tendo dificuldade em salvar caracteres especiais. Estou desenvolvendo um sistema onde o professor precisa escrever uma observação em um textarea. Estou usando o código abaixo, para salva/atualizar o campo observação:
$.ajax({
 url: '<?php echo site_url('accountant/update_planning/'); ?>' + id +
 '/' + encodeURI(observation) + '/' + status,
  success: function (response)
     {
       buttonSend.innerHTML = 'Salvar';
            $.notify({
                title: 'Sucesso!',
                message: 'O planejamento foi atualizado com sucesso.'
            }, { type: 'success' });
        },
        error: function (response)
        {
            buttonSend.innerHTML = 'Salvar';
            $.notify({
                title: 'Erro!',
                message: 'Ocorreu um erro ao atualizar o planejamento.'
            }, { type: 'danger' });
        }
    });

O problema é o seguinte: Ao usar a função encodeuri, ela não deixa escapar (A-Z a-z 0-9 ; , / ? : @ & = + $ - _ . ! ~ * ' ( ) #)
Ao usar a função escape(observation), ela não deixar escapar os acentos.
Então o que eu preciso, é que escape aceite os acentos e o caracteres como (, ! ; / ? :)
Como contornar esse problema?
Comment: Você pode capturar os dados usando base64encode, base64decode... tem isso em [javascript](https://www.devpleno.com/como-converter-uma-string-em-base64-em-javascript-navegador-e-nodejs/).
Answer: Você usou a função errada, encondeURI é para escapar em URI "inteiras", exemplo:

var uri = 'https://pt.stackoverflow.com/?q=[javascript] á é ? #teste a b c ó ú';
var resultado = encodeURI(uri);
console.log(resultado);

Para usar em strings "normais" use o encodeURIComponent assim:
url: '<?php echo site_url('accountant/update_planning/'); ?>' + id +
'/' + encodeURIComponent(observation) + '/' + status,

Comment: Grato, pela explicação e ajuda.
Answer: Vou fazer um exemplo que utiliza base64encode/base64decode ok:
var Base64 = {

    _keyStr: "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    encode: function(input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output + this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) + this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    decode: function(input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    _utf8_encode: function(string) {
        string = string.replace(/\r\n/g, "\n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if ((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    _utf8_decode: function(utftext) {
        var string = "";
        var i = 0, c1 = 0, c2 = 0, c3 = 0, c = 0;

        while (i < utftext.length) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            } else if ((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i + 1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            } else {
                c2 = utftext.charCodeAt(i + 1);
                c3 = utftext.charCodeAt(i + 2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}

Faça o encode:
var observation = Base64.encode(observation);

Ficaria assim:
$.ajax({
 url: '<?php echo site_url('accountant/update_planning/'); ?>' + id +
 '/' +  observation + '/' + status,
  success: function (response)
     {
       buttonSend.innerHTML = 'Salvar';
            $.notify({
                title: 'Sucesso!',
                message: 'O planejamento foi atualizado com sucesso.'
            }, { type: 'success' });
        },
        error: function (response)
        {
            buttonSend.innerHTML = 'Salvar';
            $.notify({
                title: 'Erro!',
                message: 'Ocorreu um erro ao atualizar o planejamento.'
            }, { type: 'danger' });
        }
    });

No lado servidor não sei como você está capturando, porque você não acrescentou na pergunta, então vou simular que fosse assim:
$observation = base64_decode($_POST['observation']);

Answer: ola amigo pode ser problema no momento da criação do banco verifica como esta o encoding UTF-8 geralmente e o padrão, se estiver enviando em outro formato que não condiz com o do banco  pode ocorre este erro.
por exemplo os browser atuais só enviam em UTF-8...
Comment: "os browser atuais só enviam em UTF-8", como assim? Qual a fonte desta informação?
Comment: Anderson Carlos talvez tenha expressado mal, geralmente get/post os browser trata de enviar ultilizando charset ISO-8859-1, tem que ter esta observação pra ñ ter conflitos no lado do servidor.. não entendi foi "Quando você tiver reputação suficiente, você vai poder deixar comentários em qualquer post" se faz necessário ter quantos pontos pra ajudar o amigo em duvida? o  outro amigo colocou "No lado servidor não sei como você está capturando, porque você não acrescentou na pergunta, então vou simular que fosse assim" foi esta a minha pergunta que poderia ser de solução também!!

Ajuda escapar caracteres especiais php


Pass query string to Webform text field

Question: I have a webform (www.mysite.com/myform) ad I want to be able to pass a URL string to a text field in the webform when a user visits the page and submits it. For instance, the URL provided to "customer A" might be www.mysite.com/myform?customer_name=customera and the URL provided to "customer B" might be www.mysite.com/myform?customer_name=customerb. I would like for the value of the text field "Customer Name" to be auto-populated with "customera" or "customerb" depending on the URL used to access the webform page.
Is this possible? If so, how can I accomplish this?
Going a bit deeper... if this is possible, is it also possible to pass two strings via the URL so that two separate fields are auto-populated? For instance, www.mysite.com/myform?customername=customera?customer_type=lead would auto-populate "Customer Name" with "customera" and would auto-populate "Customer Type" with "lead".
Thanks!
Answer: You can set a default value for each field on your webform.  The default value you would use would be
For Webform v3 and under:
<code>%get[customer_name]
</code>
For Webform v4+:
<code>[current-page:query:customer_name]
</code>
To get a first and last name you could do something like:
URL:
<code>http://mysite.com/myform?first_name=John&last_name=Doe
</code>
First Name Default Value:
<code>%get[first_name]                 //webform <= v3
[current-page:query:first_name]  //webform >= v4
</code>
Last Name Default Value:
<code>%get[last_name]                 //webform <= v3
[current-page:query:last_name]  //webform >= v4
</code>
Comment: Patrick, thanks for your answer. I followed your instructions, but now the two form fields on the live site simply show the %get[key] text in the field instead of the values from the URL string. Any idea why that would happen? It's almost like it is not respective the token. I should also say that I am using Webform 7.x-4.0-alpha6, in case that has any bearing on anything.
Comment: @hockey2112 Webform v4 uses a different approach, you would use [current-page:query:first_name] and [current-page:query:last_name] instead of the %get[] defaults

Pass query string to Webform text field


How to debug this C program?

Question: What did I do wrong?
I haven't used string library function in this code. I just used index position of the string to solve this code. But when I submit it in URI, it's showing wrong answer.
Problem:

Code:
#include <stdio.h>

int main()
{
    int c, i, x;
    char s[10], r[10];
    scanf("%d", &x);

    for(i = 0, c = 0; i < x; i++){
        scanf("%s%s", s, r);
        c++;
        if(s[4] == 'a' && r[0] == 'l' || s[4] == 'a' && r[0] == 't'){
            printf("Caso #%d: Bazinga!\n", c);
        }
        else if(s[0] == 'l' && r[4] == 'a' || s[0] == 't' && r[4] == 'a'){
            printf("Caso #%d: Raj trapaceou!\n", c);
        }

        else if(s[0] == 'p' && r[4] == 'a' || s[0] == 'p' && r[0] == 's'){
            printf("Caso #%d: Bazinga!\n", c);
        }
        else if(s[4] == 'a' && r[0] == 'p' || s[0] == 's' && r[0] == 'p'){
            printf("Caso #%d: Raj trapaceou!\n", c);
        }

        else if(s[0] == 't' && r[0] == 'p' || s[0] == 't' && r[0] == 'l'){
            printf("Caso #%d: Bazinga!\n", c);
        }
        else if(s[0] == 'p' && r[0] == 't' || s[0] == 'l' && r[0] == 't'){
            printf("Caso #%d: Raj trapaceou!\n", c);
        }

        else if(s[0] == 'l' && r[0] == 's' || s[0] == 'l' && r[0] == 'p'){
            printf("Caso #%d: Bazinga!\n", c);
        }
        else if(s[0] == 's' && r[0] == 'l' || s[0] == 'p' && r[0] == 'l'){
            printf("Caso #%d: Raj trapaceou!\n", c);
        }

        else if(s[0] == 's' && r[0] == 't' || s[0] == 's' && r[4] == 'a'){
            printf("Caso #%d: Bazinga!\n", c);
        }
        else if(s[0] == 't' && r[0] == 's' || s[4] == 'a' && r[0] == 's'){
            printf("Caso #%d: Raj trapaceou!\n", c);
        }
        else if(s[4] == 'a' && r[4] == 'a' || s[0] == 'p' && r[0] == 'p' || s[0] == 't' && r[0] == 't' || s[0] == 'l' && r[0] == 'l' || s[0] == 's' && r[0] == 's'){
            printf("Caso #%d: De novo!\n", c);
        }

    }
}

Comment: Please include the sample input, expected output and actual output.
Answer: Why don't you use the index [2] of s and r:
d: pedra
p: papel
s: tesoura
g: legarto
o: spock

Then the response would be
novo:

s[2] == r[2]

bazinga:

s[2] == 's' && r[2] == 'p'
s[2] == 'p' && r[2] == 'd'
s[2] == 'd' && r[2] == 'g'
s[2] == 'g' && r[2] == 'o'
s[2] == 'o' && r[2] == 's'
s[2] == 's' && r[2] == 'g'
s[2] == 'g' && r[2] == 'p'
s[2] == 'p' && r[2] == 'o'
s[2] == 'o' && r[2] == 'd'
s[2] == 'd' && r[2] == 's'

trapaceou: otherwise.

Comment: Thank you so much. Now the code is accepted.
But could you please explain why the previous one was not accepted??
I didn't find any problem. What was the problem actually?
Comment: To be honest, i don't know, simply intuition, i saw unecessary complexity, just brought it down to a simpler version. I trusted your statement, that it didn't work and didn't debug your code, sorry.

How to debug this C program?


Change submit button value

Question: It may take a long time to complete the call.php and get the return value, how can I change the submit button's value to "Processing … " while the call.php is being executed?
Submit button with id "submit_btn", there is no change to the script
$('#submit_btn').val('Processing …')
AJAX code
$(document).ready(function(){
    $('#form1').submit(function(e) {
        e.preventDefault();
        $('#submit_btn').val('Processing ...');
      $.ajax({
        cache: false,
        type: "POST",
        dataType: "json",
            data: $('#form1').serialize(),
        url: $('#form1').attr('action'),
        complete: function (HttpRequest, textStatus) {
                $('#submit_btn').val('Create');
      }});
      return false;
  });
});

HTML
<form action="call.php" method="POST" id="form1" name="form1">
        <input type="text" name="campname" id="campname">
        <textarea id="longdesc" name="longdesc"></textarea>
        <input type="text" name="vercode" id="vercode" />
        <input type="submit" value="Create" id="submit_btn" />
</form>

Answer: I'm not very sure, but why don't try to change the value with jQuery on click?
Something like:
$('#submit_btn').click(function(){
   $(this).val("your value")
})

... or just change in your code the submit with click :)
--------------EDIT(based on the author code)----------------
The value of the button don't change because the jquery you use style the basic submit input by applying a span over it. So on click You will have to change the text in this span.
Here is a DEMO
Comment: The click function would not work well here. If a user pressed the enter button to submit the form, this would never change the value of the button.
Comment: @Justin - ah, I have to ckeck that but if it is not working then you can use the Enter key event...but it is too lame...The Ajax beforeSend option is maybe the best solution the author could get.
Comment: @Justin - I made a demo - http://jsfiddle.net/6zjCZ/1/. The enter button change the value too :)
Comment: NoSense's solution is work when only work with 1.10.2/jquery.min.js, thanks a lot.

After I apply jquery.mobile-1.3.2.min.css and jquery.mobile-1.3.2.min.js, then the value of submit button cannot be change.

Demo on http://jsfiddle.net/yckelvin/Uw9A6/
Comment: I've changed my answer :)
Comment: Thanks NoSense, you guide me the way to do the troubleshooting.
Answer: For simple form from single HTML file,  $('#submit_btn').val('Processing …').button('refresh'); is work but NOT in multiple jQuery page.
HTML
<form action="test.php" method="POST" id="form1" name="form1">
    <fieldset>
        <input type="text" name="field1" id="field1" />
        <input type="button" value="Button" name="btn01" id="btn01" />
        <input type="submit" value="Submit" id="submit_btn" />
    </fieldset>
</form>

AJAX
$(document).ready(function () {

    $('#form1').submit(function (e) {
        e.preventDefault();
        $('#submit_btn').val('Processing …').button('refresh');
        $.ajax({
            type: "POST",
            dataType: "json",
            data: $('#form1').serialize(),
            url: $('#form1').attr('action'),
            complete: function (HttpRequest, textStatus) {
                $('#submit_btn').val('Submit').button('refresh');
            }
        });
        return false;
    });
});

Demo page: http://jsfiddle.net/yckelvin/C6kzr/
For multiple jQuery page, $('#submit_btn').prev().text("Processing …") must be used instead.
HTML

   Menu

Goto Form Page

Close

        <form action="test.php" method="POST" id="form1" name="form1">
            <fieldset>
                <input type="text" name="field1" id="field1" />
                <input type="button" value="Button" name="btn01" id="btn01" />
                <input type="submit" value="Submit" id="submit_btn" />
            </fieldset>
        </form>

AJAX
$(document).ready(function () {

    $('#form1').submit(function (e) {
        e.preventDefault();
        $('#submit_btn').prev().text("Processing ...").delay( 1000 );
        $.ajax({
            type: "POST",
            dataType: "json",
            data: $('#form1').serialize(),
            url: $('#form1').attr('action'),
            complete: function (HttpRequest, textStatus) {
                $('#submit_btn').prev().text('Submit');
            }
        });
        return false;
    });
});

Demo page: http://jsfiddle.net/yckelvin/V5mSv/
Comment: It's similar to my code except the delay part which I advice you not to use(because you can't relay on the user's internet speed :D) and check the @r3mus answer with the beforeSend option. Cheers!
Comment: Yes, you are right, the delay I use here just for delay the change of the text to the button. It is too fast to change back to 'Submit' without delay.
Answer: Use $ajax's beforeSend option:
$.ajax({
    cache: false,
    type: "POST",
    beforeSend: function() { ... },
    ...

Answer: $(document).ready(function(){
    $('#submit_btn').click(function(e) {
        e.preventDefault();
        $(this).val('Processing ...'); // this did the trices
      $.ajax({
        cache: false,
        type: "POST",
        dataType: "json",
            data: $('#form1').serialize(),
        url: $('#form1').attr('action'),
        complete: function (HttpRequest, textStatus) {
                $('#submit_btn').val('Create');
      }});
      return false;
  });
});

WORKING DEMO
Answer: For my this was the one that worked in a page with many forms with the same name and id
$(this).find("#submit").val("Saved");

Change submit button value


sequelize problema comrelções

Question: Olá, tenho algumas tabelas no mysql, criei os models usando o sequelize-auto e as associações manualmente. O problema é que quando tento incluir essas relações me depara com o erro SequelizeEagerLoadingError: tbl_contato_visitas is not associated to tbl_visitas!
a estrutura das tabelas é 1 pra n, ou seja uma visita pode ter n contato e um contato apenas uma visita.
tabela visitas

module.exports = function (sequelize, DataTypes) {
  return sequelize.define('tbl_visitas', {
    id_visitas: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    km: {
      type: DataTypes.STRING(45),
      allowNull: true
    },
    km_total: {
      type: DataTypes.STRING(45),
      allowNull: true
    },
    deslocamento: {
      type: DataTypes.STRING(45),
      allowNull: true
    },
    saida: {
      type: DataTypes.STRING(45),
      allowNull: true
    },
    retorno: {
      type: DataTypes.STRING(45),
      allowNull: true
    }
  }, {
    tableName: 'tbl_visitas',
    classMethods: {
      associate: function (models) {
        models.tbl_visitas.belongsToMany(models.tbl_contato_visitas, );
      }
    }
  });
};

Tabela contato

/* jshint indent: 2 */

module.exports = function (sequelize, DataTypes) {
  return sequelize.define('tbl_contato_visitas', {
    id: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      primaryKey: true,
      autoIncrement: true
    },
    id_visitas: {
      type: DataTypes.INTEGER(11),
      allowNull: false,
      references: {
        model: 'tbl_visitas',
        key: 'id_visitas'
      }
    },
    nome: {
      type: DataTypes.STRING(50),
      allowNull: true
    },
    telefone_1: {
      type: DataTypes.STRING(30),
      allowNull: true
    },
    telefone_2: {
      type: DataTypes.STRING(30),
      allowNull: true
    },
    email: {
      type: DataTypes.STRING(50),
      allowNull: true
    }
  }, {
    tableName: 'tbl_contato_visitas',
    classMethods: {
      associate: function (models) {
        models.tbl_contato_visitas.belongsTo(models.tbl_visitas, {
          foreignKey: 'id_visitas',
          targetKey: 'id_visitas'
        });
      }
    }

  });
};

onde tento usar

const express = require('express'),
    router = express.Router();
const {
    tbl_visitas,
    tbl_locais_visitas,
    tbl_contato_visitas
} = require('../../models');

router.get('/:id', (req, res) => {
    tbl_visitas.findByPk(req.params.id, {
        include: [tbl_contato_visitas]
    }).then((result) => {
        res.json(result)
    }).catch((err) => {
        res.json(String(err))
    });
});

module.exports = router
Answer: Resolvi, adicionando as relações no arquivo que faço as buscas.

tbl_visitas.hasMany(tbl_contato_visitas, {
    foreignKey: 'id_visitas',
    // targetKey: 'id_visitas'
});
tbl_contato_visitas.belongsTo(tbl_visitas, {
    foreignKey: 'id_visitas',
    targetKey: 'id_visitas'
});

sequelize problema comrelções


Statistical methodology for a 3 arms clinical trial

Question: I am struggling to finalise a statistical framework/methodology that would be best suited to analyse a 3 arm clinical trail data.
The problem is as follows, I have two clinical trails, parallel designs, 3 arms (placebo, drug 100mg, drug 200mg. It has a primary efficacy point is proportion of responders at week 12 and secondary endpoints at week 12, 28, and 52.The data also includes several demographic and baseline characteristics. I need to have a framework that would better characterize profile of those patients that respond better to 200mg dosage Vs 100mg.
I can either analyse these datasets separately or pool them together but I am not sure what will be the benefits or drawbacks. In addition, does anyone knows a package in R that could perform this kind of test.
I am new to the world of clinical trails so please guide me or direct me to a resource that would be a good starting place.
Answer: There's a whole literature about "best practices". Effectively your problem is one of multiple hypotheses. The overarching objective is to propose a testing framework that conserves the nominal 0.05 (or other) alpha testing level. Probably the best and most authoritative reference on the subject comes from the American FDA (https://www.fda.gov/regulatory-information/search-fda-guidance-documents/multiple-endpoints-clinical-trials-guidance-industry).
Some studies run analyses like the above in a formal phase II study. You can design and power and the study in several ways. One possibility is to sequentially test the hypothesis that either 100mg or 200mg is superior to placebo - if you believe that 100mg is a minimally effective dose, then using a Holm procedure, test whether 200mg is superior to 100mg. Or you can do dose adaptation, to overenroll 100mg and 200mg dose levels and use an interim analysis to drop the less effective arm. You can test 100mg vs placebo and 200mg vs placebo as coprimary or separate hypotheses, so it's patient or physician's choice of dose level.
The software is far from the most important thing here. What's important is that you formally translate the investigator's question of interest into a formal hypothesis.
Comment: Thank you for your reply. In your opinion, will Dunnett's test for multiple comparisons, which compares each treatment with a control (Placebo) or with another established drug will work in this case?


Adding virtual host to nginx using IP and folder

Question: I want to test this website for which I don't have a domain yet, and wanted to be able to access it via something like this:
http://18.104.22.168/testsite
I thought that on my testsite.conf file I could just do this:
server {
        listen 80;
        server_name 220.127.116.11/testsite;

        access_log /var/log/nginx/testsite.com.access.log;
        access_log /var/log/nginx/testsite.com.error.log;

        root /var/www/testsite;
        index   index.php;

        location / {
                try_files $uri $uri/ /index.php?$args;
        }

        location ~ \.php$ {
                try_files $uri =404;
                include fastcgi_params;
                fastcgi_pass 127.0.0.1:9000;
        }
}

but it doesn't work... can anyone point me to the right direction?
Thanks
Answer: Read the documentation !
The server_name directive must not contain an URI part as it matches against the HTTP Host header.
Adapt your path and you location block to match /test instead of /.
Comment: And where do I put the log commands? inside the location block? Imagine I might want to have more than one rules like this. Thanks
Comment: @JoaoLeal Why do you want to duplicate this ? Just set [`access_log`](http://nginx.org/en/docs/http/ngx_http_log_module.html#access_log) in the http block scope and [`error_log`](http://nginx.org/en/docs/ngx_core_module.html#error_log) in the main block scope (in nginx.conf).