How To Get Value of Row Table Appended

Question: i have some problems in my code... I am using html and jquery..
i want to alert value of idPredefineDetail that was appended before... here's my code:

<input type="checkbox" name="chkPredefineDetail" ><input type="hidden" name="idPredefineDetail" value="1">	<input type="text" name="txtCodePredefineDetail" value="ab"  size="10">	<input type="text" name="txtDescriptionPredefineDetail" id="txtdesk" size="50">	<button class="upPredefine"></button><button class="downPredefine"></button><button class="removeStdInsBtn"></button>

<input type="checkbox" name="chkPredefineDetail"  ><input type="hidden" name="idPredefineDetail" value="2">	<input type="text" name="txtCodePredefineDetail" value="ac"  size="10">	<input type="text" name="txtDescriptionPredefineDetail" id="txtdesk" size="50">	<button class="upPredefine"></button><button class="downPredefine"></button><button class="removeStdInsBtn"></button>

When i clicked button remove removeStdInsBtn.. i am using the code below:
 $('#tablePreDefineDetail tr button.removeStdInsBtn').click(function(e){
    var obj=$(this);
    e.preventDefault();
     $("#dialog-confirm").dialog({
          buttons : {
            "Confirm" : function() {

               var idPredefineDetail=$(this).parent().parent().children("input[name=idPredefineDetail]").val();
               alert(idPredefineDetail);
               $(this).dialog("close");
            },
            "Cancel" : function() {
              $(this).dialog("close");
            }
          }
        });

        $('#dialog-confirm').dialog('open');
 });

anybody help me??
Comment: Don't have duplicate IDs... change `id="rowPreDefineDetail"` to `class="rowPreDefineDetail"`.
Comment: U'd better tell us what's the prob.
Comment: @walio if i alert the value of idPredefineDetail.. the result shown undefined... i don't know how to get it..
Answer: You didn't post all your html, but as a first guess, I'd suggest using closest to traverse up the DOM tree.
var idPredefineDetail=$(this).closest( "#dialog-confirm" ).children("input[name=idPredefineDetail]").val();

Answer: You can use a combo of closest and find .
Try this:
$('#tablePreDefineDetail tr button.removeStdInsBtn').click(function(e){
    var obj=$(this);
    e.preventDefault();
     $("#dialog-confirm").dialog({
          buttons : {
            "Confirm" : function() {

               var idPredefineDetail=obj.closest("tr").find("input[name=idPredefineDetail]").val();
               alert(idPredefineDetail);
               $(this).dialog("close");
            },
            "Cancel" : function() {
              $(this).dialog("close");
            }
          }
        });

        $('#dialog-confirm').dialog('open');
 });

Comment: In Confirm handler you are using $(this) which refers to the dialog and not the button. You should use obj instead since it is still in scope.
Answer: I believe the $(this) is actually pointing to #dialog-confirm. You should use the obj variable that you set at the start of the click callback function. You also didn't go back far enough, you need another parent() call.
var idPredefineDetail=obj.parent().parent().parent().children("input[name=idPredefineDetail]").val();
alert(idPredefineDetail);
$(this).dialog("close");

Answer: well here i want to modify the below mentioned code which was originally posted by Cybernate
$('#tablePreDefineDetail tr button.removeStdInsBtn').click(function(e){   var obj=$(this);
e.preventDefault();
 $("#dialog-confirm").dialog({
      buttons : {
        "Confirm" : function() {
           var idPredefineDetail=obj.attr("id");
           alert(idPredefineDetail);
           $(this).dialog("close");
        },
        "Cancel" : function() {

          $(this).dialog("close");
        }

      }

    });

    $('#dialog-confirm').dialog('open');

});
for example i have a hyperlink like this.
clickme
when i click this link the value which i access is id='clickit' as obj.attr("id"); is used.
so we can place a required value in id, or in name or in another tag property and later we can easily acces it...

How To Get Value of Row Table Appended


How to Implement a general Save() Function in a Base Class

Question: As an assessment, I received the following Testcase so I can implement the code behind:
[TestCase]
public void ProgrammerTest()
{
    var address = new Address("56 Main St", "Mesa", "AZ", "38574");
    var customer = new Customer("John", "Doe", address);
    var company = new Company("Google", address);

    Assert.IsNullOrEmpty(customer.Id);
    customer.Save();
    Assert.IsNotNullOrEmpty(customer.Id);

    Assert.IsNullOrEmpty(company.Id);
    company.Save();
    Assert.IsNotNullOrEmpty(company.Id);

    Customer savedCustomer = Customer.Find(customer.Id);
    Assert.IsNotNull(savedCustomer);
    Assert.AreSame(customer.Address, address);
    Assert.AreEqual(savedCustomer.Address, address);
    Assert.AreEqual(customer.Id, savedCustomer.Id);
    Assert.AreEqual(customer.FirstName, savedCustomer.FirstName);
    Assert.AreEqual(customer.LastName, savedCustomer.LastName);
    Assert.AreEqual(customer, savedCustomer);
    Assert.AreNotSame(customer, savedCustomer);

    Company savedCompany = Company.Find(company.Id);
    Assert.IsNotNull(savedCompany);
    Assert.AreSame(company.Address, address);
    Assert.AreEqual(savedCompany.Address, address);
    Assert.AreEqual(company.Id, savedCompany.Id);
    Assert.AreEqual(company.Name, savedCompany.Name);
    Assert.AreEqual(company, savedCompany);
    Assert.AreNotSame(company, savedCompany);

    customer.Delete();
    Assert.IsNullOrEmpty(customer.Id);
    Assert.IsNull(Customer.Find(customer.Id));

    company.Delete();
    Assert.IsNullOrEmpty(company.Id);
    Assert.IsNull(Company.Find(company.Id));
}

The requirements are:

In C# create a single class that when subclassed allows this sample test code to run using only the file system for storage, no pre-built database allowed; use files.
Create all classes required to compile and pass the test case; you may not modify the test. The test is not wrong, it's not a trick.
The Id, Save, Delete, and Find methods must be in the super class only; subclasses must not implement these methods themselves.

Here are a class example I could extract from the test cases:
public abstract class MyBase
{
    public abstract void Save();
    public abstract void Delete();
}

public class Company : MyBase
{
    public string Id { get; set; }
    public string Name { get; set; }
    public Address Address { get; set; }

    public Company(string name, Address address)
    {
        this.Name = name;
        this.Address = address;
    }

    internal static Company Find(string id)
    {
        throw new NotImplementedException();
    }

    public override void Delete()
    {
       throw new NotImplementedException();
    }

    public override void Save()
    {
        object company = new List<Company>();

        if (company != null)
        {
            // serialize JSON to a string and then write string to a file
            File.WriteAllText(@"c:\company.json", JsonConvert.SerializeObject(company));
        }
    }
}

I have experience creating TestCases for a given code, but not the other way out and I could extract the Classes from it but, how can I implement the methods Save(), Delete(), Find(customer.Id) as Generic Types without passing the populated data classes? I know I could do something like void Save(object obj) and implement the passed object on the Base, but the testcase just calls like customer.Save()... So, how can I do this?
Thanks in advance for any input!
Answer: I would assume the intent is to use some kind of serialization to produce a copy of the object.
Json
If using json.net you should be able to use name-handling to include the actual object type in the serialized message:
JsonSerializerSettings settings = new JsonSerializerSettings
{
    TypeNameHandling = TypeNameHandling.All
};

string strJson = JsonConvert.SerializeObject(instance, settings);

From how to deserialize JSON into IEnumerable with Newtonsoft JSON.NET
Protobuf
You could also use a protobuf.net with ProtoInclude to allow it to serialize subtypes:
[ProtoContract]
[ProtoInclude(7, typeof(SomeDerivedType))]
class SomeBaseType {...}

[ProtoContract]
class SomeDerivedType {...}

Then the base-type should just be able to serialize this to a memory-stream and deserialize it again, store the copy in a static list, and let the find method search the list.
Protected virtual/abstract members
Another approach would be to just add protected virtual methods to the sub-types to do all the actual work of creating an identical object. The task only specified that the Save method needs to be on the base type, not that it needs to do the actual work without help from the sub-type.
Note that I would not recommend the practices from that assignment due to several issues:

The simplest way to pass the test is with static mutable fields, and these are generally not recommended.
Using serialization to produce deep copies might be appropriate in some cases, but I would generally recommend against it. Reason is that not all types would be expected to be serializable, and that deep copies might be expected to be fairly cheep to construct.
The instructions suggest that writing to files are expected. Unit tests should in general avoid writing to disk since disk is comparably slow, and unit tests need to run fast to be useful.
I find it fairly rare for copies to be needed. In many cases, immutable objects are easier to use, and does not need to be copied.
The test seem rather nonsensical overall. If I saw that in the wild it would trigger quite a few WTFs.


Is there a way to show different Amazon affiliate link based on visitor locations?

Question: I'm trying to get an Amazon affiliate link set up that directs the visitor to their local store, rather than being fixed to one particular store. I know I could set up individual links for each country and let the user choose the right one, but ideally I only want to show the one Amazon link.
Essentially what I'm looking for is a Drupal version of this Amazon Affiliate Link Localizer Wordpress plugin, or a combination of modules/tweaks that will let me do the same thing.
Comment: It looks like the Amazon Affiliate Link Localizer is mostly javascript and a standalone php script (that responds to ajax calls). It probably wouldn't be very much work to adapt it to work as a Drupal module.
Answer: I wrote that plugin, so should be able to help!
There is a Javascript-only version of the Amazon Link Localiser. I don't know Drupal, but I can't see any reason why you wouldn't be able to use this - you'd just insert the JavaScript link into your template.
Cheers
Pete
Comment: OK, try the link again, I've now fixed the error if Google can't get a location.
Comment: I tried your code but it breaks some other JavaScript elements on the page. What could cause this conflict?
Comment: Pete, I've tried setting that up, and it seems like it should work,  but I'm getting a JS error. It can't read the `address` property because `location` is null. Any suggestions?
Comment: Update: Looks like it was because Google doesn't have a location for my IP. Will your script localise links that already contain affiliate links? Would be nice to fall back to an affiliate URL rather than a plain Amazon link.
Comment: Sorry, the Javascript-only version isn't as up-to-date as the Wordpress version so there's an old bug in there. As you've found, if Google can't get a location it'll give an error. I'll add the fix to this tonight if I get a chance.
Comment: Working a treat. Time to spend an evening tweaking and playing with it now!
Answer: You can easily use client side JavaScript to check the PCs time zone setting and then set different links accordingly. There is an examples of how to do this at http://www.tomcoote.net/code-examples.html
Answer: If you don't want Javascript or a custom Plugin, I'd suggest to have a look at A-FWD.
It's a web site that lets you build a custom link that will forward the user based on the IP.


Textbook for graduate analysis over a general complete valued field?

Question: At my university, the standard sequence of first-year graduate analysis courses is taken by students who plan to go into analysis, differential equations, and applied math. These students know why they have to learn analysis. The first-year graduate analysis courses are also taken by students who plan to go into algebraic topology, algebraic number theory, and algebraic geometry. These students sometimes are disinterested in learning classical analysis (over the real or complex numbers), because their perspective is not yet broad enough to see the fundamental importance of analysis and/or how it is related to the subjects they plan to specialize in. My efforts to explain to these students why they ought to care about analysis have generally not been successful.
My colleagues and I are considering the possibility of running our first-year graduate analysis courses as courses in analysis over a general complete valued field. Over the archimedean fields, we would recover classical analysis over the real and complex numbers; over the non-archimedean fields, we would recover many cases of interest to the students who plan to study algebra, particularly analysis over p-adic fields. We hope the resulting courses would be of interest and of use to all our students. But it is not yet clear to us that this idea makes sense; perhaps some topics (e.g. integration theory) are simply too different in the non-archimedean case to treat them, at this level, alongside the classical treatment.
There are many good references on functional analysis which work over non-archimedean fields, or which allow the base complete valued field to be archimedean or non-archimedean. However, I do not know of a graduate analysis textbook (not just functional analysis, but rather roughly the contents of a standard first year of graduate analysis) which works over a general complete valued field. Do you know of any such textbook? Thanks.
Comment: I think most graduate students find graduate measure/integration theory more than sufficiently challenging working with the concrete cases of $\Bbb R$ and $\Bbb C$. Sometimes generalizing too soon makes for terrible pedagogy. But it's an interesting twist.
Answer: If by analysis you meant functional analysis, then the book that comes to my mind is Functional Analysis and
Valuation Theory (1971) by L. Narici, E. Beckenstein, and G. Bachman. The preface of that book states:
"...Generally it would be accurate to say that we have tried to present functional analysis over arbitrary valued fields, and to best benefit from the book, the reader should be familiar with some classical functional analysis and some valuation theory"
It might be worth your time to take a look at it.


Allowing the user to choose a new font from a list on iOS

Question: I have a text field where I would like the user to be able to set the font from a drop down box. I can't seem to find any documentation related to doing anything like this, but it seems like something that should be fairly trivial so I assume I'm just using poor search terms or something.
I can obviously build the drop down box myself, but I have no idea how to get a list of all available fonts prefrably including my own custom fonts.
Comment: I'm not sure why my answer was down-voted, but I'd definitely suggest you check it out.
Answer: You can create an array of fonts to populate your drop-down list like so:
self.fontNameList = [[NSMutableArray alloc] init];
NSArray *familyNames = [UIFont familyNames];
for (NSString *familyName in familyNames) {
    NSArray *fontNames = [UIFont fontNamesForFamilyName:familyName];
    for (NSString *fontName in fontNames) {
       [self.fontNameList addObject:fontName];
    }
}
// And optionally, to arrange them in alphabetical order...
[self.fontNameList sortUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

This should find all your fonts, custom and otherwise.
Then assuming you're using a UITableView for your drop-down menu where each row contains a font name, once an index is selected you can set the font in your UITableViewDelegate's didSelectRowAtIndexPath: method like so:
UIFont *currentFont = [UIFont fontWithName:[self.fontNameList objectAtIndex:indexPath.row] size:12];

I've set the size to 12 in this case, but you can set it to whatever variable float value or default constant float you desire.
Comment: This seems like a solid solution, I would also like to know why it's being down voted.
Comment: @Tiddly Just checked and this code works. Yeah, I tend to get some suspicious downvotes several times a day after two guys on the site didn't like a question I gave a *month* ago haha... It doesn't bother me personally (I'm not here for "points"), but it's not so great for others if they see my answer right after it's been downvoted for the wrong reasons then don't look into it further.
Answer: Fist get the font families with familyNames then get all the fonts for the different family names with fontNamesForFamilyName.
Show the names and react on the users selection by setting the selected font.


Prove that $Re+Rf=Re\oplus R(f-fe)$

Question:
Let $e,f$ be idempotent elements of a ring $R$. Prove that $Re+Rf=Re\oplus R(f-fe)$.

This post solves the first part of my question. How should we prove the second part, that $e,f$ are orthogonal?
Help me. Thanks a lot.
Answer: First of all, it is a good idea to say what you have tried and how far you have come in your attempts. That way it is easir to provide a better answer.
That being said, here are some hints: You need to show two things. First, that $e$ and $f-fe$ spans $Re + Rf$, and secondly that $e$ and $f-fe$ are orthogonal.
For the first, notice that we certainly have a containment $\supseteq$. The opposite inclusion is also straight-forward.
Secondly, what happens if you multiply $e \cdot (f-fe)$?
Comment: What does "$e$ and $f-fe$ are orthogonal" mean?
Comment: @user110834: Only that they multiply to zero.
Comment: $e(f-fe)=ef-efe=ef(1-e)$ What should I do then?
Comment: It's $(f-fe)e=0$.

Prove that $Re+Rf=Re\oplus R(f-fe)$


ckEditor showing standard version in prod environment although I have updated it to full version

Question: I have updated my CKEditor 4.3.3 to full edition from composer.phar install command. And it shows full version in my CMSCreate edit pages. But it only works in dev mode not in prod mode. I don't know how it loads the standard version in prod environment. Please help. My composer.json is:
<code>{
    "name" : "--",
    "version" : "--",
    "license" : "proprietary",
    "type" : "project",
    "description" : "-- propriatary project built on: The \"Symfony CMF Standard Edition\" distribution",
    "authors" : [{
            "name" : "--",
            "homepage" : "--"
        }, {
            "name" : "--",
            "homepage" : "--"
        }, {
            "name" : "--",
            "homepage" : "--"
        }
    ],
    "autoload" : {
        "psr-0" : {
            "" : "src/"
        }
    },
    "minimum-stability" : "stable",
    "require" : {
        "php" : ">=5.3.3",
        "symfony/symfony" : "2.3.6",
        "twig/extensions" : "1.0.*",
        "symfony/monolog-bundle" : "2.3.*",
        "symfony/assetic-bundle" : "2.3.*",
        "sensio/distribution-bundle" : "2.3.*",
        "symfony-cmf/symfony-cmf" : "1.0.*",
        "symfony-cmf/simple-cms-bundle" : "1.0.*",
        "symfony-cmf/create-bundle" : "1.0.*",
        "symfony/security-bundle" : "2.3.*",
        "jackalope/jackalope-doctrine-dbal" : "1.0.*",
        "doctrine/doctrine-bundle" : "1.2.*",
        "doctrine/data-fixtures" : "1.0.*",
        "doctrine/migrations": "dev-master",
        "doctrine/doctrine-migrations-bundle": "dev-master",
        "lunetics/locale-bundle" : "2.2.*",
        "liip/doctrine-cache-bundle" : "1.0.*",
        "incenteev/composer-parameter-handler" : "~2.0",
        "liip/imagine-bundle" : "~0.12",
        "wjzijderveld/check-bundles" : "1.0.*@dev",
        "sonata-project/core-bundle": "~2.2@dev",
        "sonata-project/admin-bundle" : "dev-master",
        "sonata-project/doctrine-phpcr-admin-bundle" : "dev-master",
        "sonata-project/doctrine-orm-admin-bundle" : "dev-master",
        "symfony/swiftmailer-bundle" : "dev-master",
        "sonata-project/easy-extends-bundle" : "dev-master",
        "sonata-project/user-bundle" : "dev-master",
        "friendsofsymfony/user-bundle" : "v1.3.3",
        "gedmo/doctrine-extensions" : "dev-master",
        "sonata-project/block-bundle" : "dev-master",
        "whiteoctober/breadcrumbs-bundle" : "dev-master",
        "setasign/fpdi" : "1.4.2",
        "tecnick.com/tcpdf" : "6.0.052"
    },
    "require-dev" : {
        "liip/functional-test-bundle" : "1.0.*"
    },
    "scripts" : {
        "post-install-cmd" : [
            "WillemJan\\CheckBundles\\Composer\\CheckBundles::postPackageUpdate",
            "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
            "Symfony\\Cmf\\Bundle\\CreateBundle\\Composer\\ScriptHandler::downloadCreateAndCkeditor",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets"
        ],
        "post-update-cmd" : [
            "WillemJan\\CheckBundles\\Composer\\CheckBundles::postPackageUpdate",
            "Incenteev\\ParameterHandler\\ScriptHandler::buildParameters",
            "Symfony\\Cmf\\Bundle\\CreateBundle\\Composer\\ScriptHandler::downloadCreateAndCkeditor",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile"
        ]
    },
    "config" : {
        "bin-dir" : "bin"
    },
    "extra" : {
               "ckeditor-directory": "vendor/symfony-cmf/create-bundle/Symfony/Cmf/Bundle/CreateBundle/Resources/public/vendor/ckeditor",
                   "ckeditor-repository": "https://github.com/ckeditor/ckeditor-releases.git",
                   "ckeditor-commit": "0b7c3f1f5c0a9d14657cedf56a3735a2c57a38ac",
            "checkbundles-ignore" : [
            "Liip\\FunctionalTestBundle\\LiipFunctionalTestBundle",
            "Sensio\\Bundle\\DistributionBundle\\SensioDistributionBundle",
            "Sonata\\BlockBundle\\SonataBlockBundle",
            "Symfony\\Cmf\\Bundle\\BlockBundle\\CmfBlockBundle"
        ],
        "symfony-app-dir" : "app",
        "symfony-web-dir" : "web",
        "incenteev-parameters" : {
            "file" : "app/config/parameters.yml",
            "keep-outdated": true
        },
        "branch-alias" : {
            "dev-master" : "1.0-dev"
        }
    }
}
</code>
Any help will be really appriciated.
Comment: did you clear your cache? `php app/console cache:clear --env=prod`
Comment: Yes, I have cleared:(
Answer: After running
<code>Assetic dump
app/console assetic:dump
</code>
resolved the issue.


Strange behavior with title field

Question: I have a strange behavior (or at least this is what I think) I have two form elements. Both are required, in the first (First Name) I want to have a required field so I use '#required' => TRUE and '#required' => TRUE in the second I don't use this properties to says that the field is required, I just add this line to the title '*'. The problem is that the output of the first element is "First name " (with space at the end) and in the second element the output is "Last name" (without space at the end). See the code and the picture with the output code.
Is this a normal behavior or I missing something here?
  $form['general']['group-1']['prenom'] = array(
    '#prefix' => '
',
    '#title' => t('First name'),
    '#id' => 'cf-1',
    '#type' => 'textfield',
    '#required' => TRUE,
    '#attributes' => array('required' => 'required'),
    '#suffix' => '
',
  );

  $form['general']['group-1']['nom'] = array(
    '#prefix' => '
',
    '#title' => t('Last name') . '*',
    '#id' => 'cf-2',
    '#type' => 'textfield',
    '#suffix' => '
',
  );

The HTML code:
Answer: Works as designed imho.
The markup of the first is generated by the form element/Drupal. By default Drupal has a space between the field title and the asterisk. That's just how it was designed.
The second time you tell the form what to add - exactly what to add. Drupal wont add a space for you, as you may not always want a space between your custom wrapper and the title. (In most cases you probably don't.)
If it is important to remove the space you can overwrite theme_form_element() in your theme. Check the mid to late replies (starting with kkatusic) in this thread: How to remove asterisks from required fields?
Is there a reason why you would want to mark a field required if it isn't a required field?
Comment: Well, if it is important to remove the space you can overwrite theme_form_element() in your theme. Check the mid to late replies (starting with kkatusic) in this thread: https://www.drupal.org/node/141790
Comment: This is just an example. But the really reason is because I need to make some validations with javascript so I put the asterisk for indicate that the field is required. Thanks for your answer.

Strange behavior with title field


Creating IIS Rewrite Rules

Question: I'm having a hard time converting old .htaccess rewrite rules to new IIS ones so I was wondering if anyone could point me in the right direction. Below are some example URLs I would like rewriting.
<code>http://example.org.uk/about/

Rewrites to

http://example.org.uk/about/about.html

-----------

http://example.org.uk/blog/events/

Rewrites to

http://example.org.uk/blog/events.html

-----------

http://example.org.uk/blog/2010/11/foo-bar

Rewrites to

http://example.org.uk/blog/2010/11/foo-bar.html
</code>
The directories and file names are generic and could be anything.  Any help would be greatly appreciated.
Answer: Gotchas:
Match URL only matches after the slash that trails the host - (.*) is common, and becomes {R:1} if you want to reuse the capture.
Host/domain name matches are done using {HTTP_HOST} in a condition. Conditions become {C:#}; multiple conditions can be confusing/complicated, I'm not sure how the numbering works precisely there.
Append querystring is usually a good option.
Looks like you want to preserve your host header, and rewrite host in response headers. The former is a applicationHost.config setting, or an appcmd change; the latter is in the GUI, or again can be touched in the .config file by hand, or using appcmd.

Creating IIS Rewrite Rules


Can not see all columns of data table because browser is not showing horizontal scroll bar

Question: I have implement a data table using bootstrap with approximately 38 columns. All columns are being shown in browser of eclipse, eclipse is showing horizontal scroll bar in browser. But in chrome or any other browser it is not showing horizontal scroll bar.
Comment: Please provide some code (html, css)
Comment: Without any code its almost impossible to guess what is going wrong. That being said if there is no horizontal scrollbar then you might have `overflow: hidden` set on a parent element. You will need to remove that for the scrollbar to appear.
Comment: Thanks for your quick response. We have found the answer and changed the script in jsp file.
Answer: Changed script with this now it is working:


error in compilation in codeforces

Question: can anyone help me in this
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
#define ll long long int
struct points{
ll a;
ll b;
};
int cos(points x , points y)
{
    return x.b<y.b;
}
int main()
{
   ll n,r,avg,i,j,k;
   points pt[100005];
   cin>>n>>r>>avg;
   for(i=0;i<n;i++)
   {
       cin>>pt[i].a>>pt[i].b;
   }
   sort(pt,pt+n,cos);
   ll sum=avg*n;
   for(i=0;i<n;i++)sum-=pt[i].a;
   if(sum<=0)cout<<"0\n";
   else
   {

   ll ans=0;
   for(i=0;i<n;i++)
   {
       if(sum==0)break;
       else
       {
           if(sum>r-pt[i].a)
           {
               ans=ans+pt[i].b*(r-pt[i].a);
               sum=sum-(r-pt[i].a);
           }
           else
           {
               ans=ans+sum*pt[i].b;
               sum-=sum;
           }
       }
   }
   cout<<ans<<endl;
   }
    return 0;
}

when im compiling in my system its working fine and getting the correct output but when i'm submitting in codeforces under GNUC++ 11 im getting compllation error? can u help me
Comment: So what is the error?
Comment: It might help if you wrote *what error you're getting*
Comment: Could you please provide more details about what's the compilation error?
Comment: You do know that the `pt` array is about 1.5 MEGA byte? Are you sure that Codeforce allow such large stacks?
Answer: Your compare function, cos(), collides with function in standard <cmath>. Rename it and it will compile.

error in compilation in codeforces


Better to know diatonic chords by pattern or by name?

Question: Let's say a given key is given like: A major.
Is it better to know how to play the diatonic chords in your given instrument (like piano or guitar) by pattern. For example, in piano I could just know the scale. Then I could just pick out the I IV V etc of the scale, just by moving my fingers around without knowing (or bothering to know) what the names of the chords I'm playing. All I know is I'm playing the "V" as an example.
-OR-
Is it better to memorize the diatonic chords of each scale by name. So the diatonic chords in A major would be: A major, D major, E major, B minor, C#minor, F#minor, G#dim. and then play these chords on the given instrument?
Comment: Are you sure this is an accurate dichotomy? It's hard for me to imagine someone knowing "this is V of A" without being able to make the connection to "this is an E major chord."
Comment: Well all I need to know is where the A note is. Then I know what the scale sounds like (just do re me fa so..) from there so I know the fingering, then I can pick the IV the V or whatever just by counting. and then I can play V because I just know the sound of a major chord, or the iii cause I know the sound of a minor chord. but I never take the time to care or figure out what chord I'm playing. like what the name of it, so I wasn't sure if I should or not.
Comment: @foreyez So you have enough time to do all the steps in (1) "know  where the A note is" (2) "know what the scale sounds like" (3) "pick the IV the V or whatever just by counting" (4) "play V because I just know the sound of a major chord" - I'm not surprised you "never take the time to care or figure out what chord I'm playing" if you are doing all that for every chord! Do you read English by counting out the alphabet from the beginning, to figure out each letter??? In any case, you shouldn't be aiming to play individual chords, but *chord progressions,* if you want to make real progress.
Answer: That's like asking whether it is better to know words by sound or spelling.
You don't really get to pick one and forego the other if you are seriously working with music.
Comment: In laying out your example for the key of A major you have demonstrated an ability to, as @user40262 would put it,  seriously work with music (as opposed to, seriously avoid working with music), so the time spent in assimilating this information for all keys will be well worthwhile. And after all, you are already 1/12th the way there.
Answer: There's a lot of difference in the 'patterns' between piano and guitar! On guitar, I find I'm changing chords automatically as I listen to what will probably come next - there's really no time to think 'I'm on F#m, and C#7 is coming next, where can I play it?' And that's probably easier on guitar, with not so many chord shapes to consider.
On piano, the same thing happens with the more familiar keys, but there's a lot more choice with voicings and patterns generally, and two lots of fingers to deal with as well! gain, the academic side really needs to be put away, and the fingers go straight to the next chord, i.e. if it's an A triad, root position, and the following is C#m, then I'd probably just drop r.h. thumb down to G#, leaving the others where they are, but not necessarily be thinking 'this is going to be C#m'. I reckon it's a bit of both, dependent on one's prowess on the instrument, and familiarity with both the key and the song.
Comment: yeah your example with the guitar is what I mean. so you do it by ear. so same with when you jam with people, you don't consciously think about the chord names I assume..
Comment: and if you don't consciously think about them.. then I imagine it  would be hard to remember the names of them. Like if someone were to ask you out of the blue to name them? Because I don't. and I'm not sure if I should commit the effort to know them all by name.
Comment: Don't need to actually quote names at that moment, but am well aware of what chord it is called, so, it's a bit of both...In the heat of the moment, the name is inconsequential though.
Answer: Disregarding needing to know the underlying scales of chords, it's better to know chords by name than by pattern/harmonic function if you plan on reading a lot of lead sheets. Lead sheets are often filled with chords labelled stuff like "C-Ab7-Bb9-C7-E7b5" with no regard for whether any of them are I, bVII, or are involved in a deceptive cadence.


Non Gaussian ARMA and invertibility of the process

Question: There are many ARMA(p,q) processes, with different parameter values, associated with the same auto-correlation function. If this processes are also Gaussian, this implies they follow same exact distribution.
So, for a set of data points, there are usually multiple parameter values associated with the same (maximum) likelihood. Only one of this processes is also invertible, we choose that particular estimate restricting the parameter space to that of invertible processes (making the model identifiable).
If the processes are not Gaussian, it is still true that there are multiple processes with different parameters all having the same auto-correlation function, but, I don't think this implies they follow the same distribution as before.
So, for a set of data points, I wouldn't expect to have multiple points in the parameter space with the same maximum likelihood. Is this correct?
Restricting the parameter space was useful with Gaussian processes since it was a way of  choosing the invertible representation of the process among all those having the same maximum likelihood. Now, with non-Gaussian processes, the possibly unique maximum likelihood estimate could be an invertible process or not. If it isn't, we can't actually choose an invertible representation with the same maximum likelihood.
In this case, is it a problem to have a process that isn't invertible?
Answer: Yes, for non-Gaussian white noise, the distribution of the data may be different for an invertible model and its non-invertible counterpart(s).  For example, consider the invertible MA(1) model
$$
y_t = w_t + \frac12 w_{t-1} \tag{1}
$$
where the white noise process $w_t \sim U(-1,1)$ and the non-invertible model
$$
y_t = w_t + 2 w_{t-1} \tag{1}
$$
where $w_t \sim U(-1/2,1/2)$.  Although these processes have the same autocovariance functions the joint distribution of for instance $y_1,y_2$ are different as demonstrated by the following simulation.
<code>n <- 1e+4
par(mfrow=c(1,2))
# Invertible version
s <- .5
w0 <- runif(n,-s,s)
w1 <- runif(n,-s,s)
w2 <- runif(n,-s,s)
y1 <- w1 + .5*w0
y2 <- w2 + .5*w1
plot(y1,y2,pch=".")
# Non-invertible counterpart
s <- .25
w0 <- runif(n,-s,s)
w1 <- runif(n,-s,s)
w2 <- runif(n,-s,s)
y1 <- w1 + 2*w0
y2 <- w2 + 2*w1
plot(y1,y2,pch=".")
</code>

Given enough data, you should thus in principle be able to distinguish between models such as (1) and (2) and relying on (2) e.g. for prediction would of course be perfectly fine.   But the exact likelihood seems rather hard to compute.  Also, depending on the exact distribution of the white noise, the difference between the resulting joint distributions of the data may be much less obvious than in this toy example.  But, yes, this sort of thing is something people have looked into.
Comment: @JarleTufto thank you! this example shows really well what I was kind of thinking about when writing the question. So, would you say that invertibility is necessary only for Gaussian processes, with the main goal of assuring identifiability?
Comment: @JarleTufto Would you also kindly take a look at this related question I wrote later? (https://stats.stackexchange.com/q/557948/318559) the book by Box and Jenkins seems to make a big deal about invertibility and I don't get why...
Comment: So is it a problem to have a process that isn't invertible?
Comment: @RichardHardy No, such non-Guassian, non-invertible models seems to be in wide use if you look into the literature.
Comment: Thank you, that was helpful!


Cordova build failed not sure why it is happening

Question: All of my version are i think right but the build always fail please help me
i am sure that the java is perfect but not to sure about the android sdk
My gradle version Gradle 6.4
My adb version Android Debug Bridge version 1.0.41
Version 31.0.3-7562133
<code>C:\Cordova\Hello>cordova build android
Checking Java JDK and Android SDK versions
ANDROID_SDK_ROOT=G:\Android sdk (cordova)\platform-tools_r31.0.3-windows\platform-tools (recommended setting)
ANDROID_HOME=C:\Android (DEPRECATED)
Using Android SDK: G:\Android sdk (cordova)\platform-tools_r31.0.3-windows\platform-tools
Subproject Path: CordovaLib
Subproject Path: app
Starting a Gradle Daemon (subsequent builds will be faster)

FAILURE: Build completed with 2 failures.

1: Task failed with an exception.
-----------
* Where:
Script 'C:\Cordova\Hello\platforms\android\CordovaLib\cordova.gradle' line: 64

* What went wrong:
A problem occurred evaluating project ':app'.
> No installed build tools found. Install the Android build tools version 19.1.0 or higher.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
==============================================================================

2: Task failed with an exception.
-----------
* What went wrong:
A problem occurred configuring project ':app'.
> compileSdkVersion is not specified. Please add it to build.gradle

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
==============================================================================

* Get more help at https://help.gradle.org

BUILD FAILED in 6s
Command failed with exit code 1: C:\Cordova\Hello\platforms\android\gradlew cdvBuildDebug -b C:\Cordova\Hello\platforms\android\build.gradle
</code>
Answer: This needs to be fixed in Android Studio. Open the SDK Manager, then go to the "SDK tools" tab and check "show package details". " Android SDK build tools " will be there. Check the box next to the Android SDK build tools 19.1.0 (or whatever number your error code is referencing) and hit 'Apply' to install.


How to prove by induction that a string is a member of a recursively defined language?

Question: If I have a recursively defined language L, for example:

The empty string is in L.
For any string x in L, the string 0x is also in L.
For any strings x and y in L, the string 1x1y is also in L.
These are the only strings in L.

How do I go about proving that every string which is in the set of strings {0, 1} with an even number of 1s is in L?
Comment: Thank you for waiting until after the homework deadline to ask this question.
Answer: A string $s$ with an even number of ones can have a prefix of a digit zero: $s=0p$.
Thanks to the rule 2, $(s\in L) \Leftarrow(p\in L)$, hence you can drop any leading zeros from a string and test the remaining part.
Then you have a string $p$ with an even number of ones and no leading zeros. So either $p$ is empty or it starts with $1$. If it's empty you're done (the empty string belongs to $L$ by the first rule).
Otherwise, let $m$ be a part between the first and the last one, and $n$ be the part (possibly empty) following the last one:
$$p=1m1n$$
By the rule 3, $p\in L$ if both $m$ and $n$ belong to $L$.
However, as the second chosen one was the last one in $p$, the string $n$ must be empty or contain zeros only. An empty string belongs to the language by the rule 1, and zeros-only string can be reduced (as before) to an empty string by rule 2, hence $n\in L$.
The only remaining test is whether $m\in L$. But $m$ is a part of $p$ with two extreme ones (and possibly some zeros) dropped, so the same reasoning applies recursively.
Eventually we get to a base case of an empty string, or a zeros-only string, which can be reduced to an empty string, which is in $L$ — hence all preceding strings are in $L$, too, including the starting string $s$.
Answer: Proof by infinite descent: Let $M$ be the set of strings that have an even number of $1$s but that are not in $L$. Let $n > 0$ be the length of the shortest string in $M$. Any string in $M$ that is not in $L$ can made into a shorter string in $M$ either by removing the initial $0$, or by removing the initial $1$ and any other $1$. Applied to a string of length $n$, this procedure gives a string of length $n-1$ or $n-2$ that is also in $M$, contradiction.


javascript pick random line from a textarea

Question: I'm trying to get a javascript pick a random line from a textarea. Sorry, big noob here.
Currently my code looks like this, and I'm quite sure there are silly mistakes in it. I'm just kinda stuck. First, how do I connect this function to the textarea? Secondly, how do I even output the result?
I think I've done too much there with making it two functions. I don't mind making it smaller somehow.

    Enter all of the names on a seperate line.

<textarea id="textarea" placeholder="Enter names here..."></textarea>

The winner is:

<button onclick="randomSelect()">Click me</button>

Answer:

function randomSelect() {
  const winnerEl = document.getElementById("winner");
  winnerEl.innerHTML = "";
  const candidates = document.getElementById("textarea").value;
  if (candidates) {
    const names = candidates.split(/\n/);
    if (names.length > 0) {
      const max = names.length - 1;
      const winnerIndex = getRandomInt(0, max);
      winnerEl.innerHTML = names[winnerIndex];
    }
  }
}

function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

    Enter all of the names on a seperate line.

<textarea id="textarea" placeholder="Enter names here..."></textarea>

The winner is:

<button onclick="randomSelect()">Click me</button>

Answer: Your codes should look like bellow:

  Enter all of the names on a seperate line.

 <textarea id="textarea" placeholder="Enter names here..."></textarea>

The winner is:

<button onclick="randonSelect()">Click me</button>

You just forgotten to get the element from which you are getting the value.
But you did well.
Comment: Thanks! This helped a lot! (:
Answer: Inside your randomSelect() function access your text area and value that is stored in it.
Thus add the following line
    const input = document.getElementById("textarea").value;


How to compile multiple angularjs files into single application file

Question: I recently started using angularjs and at the moment I am working on developing someone else's code. The whole application is divided into multiple files, but at the end they are used from single application.js file.
I have a file looking like this:
//= require (some path)
//= require (some path)
angular.element(document).ready(function () {
    angular
        .bootstrap(document, [
            (multiple routes)
        ]);
});

Seems like I need to compile this file to generate a new, bigger file for whole app. I can't figure how, though.
Comment: Is there a gulp or grunt file attached to the project? There could be a task to run that will concatenate all javascript files into one.
Comment: There is none, but there is a chance it was not added to the repository. Thanks for the sugggestion, I will check that.
Comment: If there isn't a gulp or grunt file available it isn't that difficult to set one up that would grab all the javascript files from your project and combine them. I don't particularly recommend that as there are ways of doing lazy loading controllers/files on demand to reduce bandwidth but that might be a little bit more advanced.
Answer: There are multiple ways to do this, you could pick an existing library like:

Uglify: traditional way to concatenate, minify and "uglify" JS sources into a single ".min.js" file. This is useful if you want to concatenate all js files in a whole directory structure more than using explicit relative requires.
Browserify: uses CommonJS's require to generate a single file wisely resolving dependencies. Looks more like the way you are looking to implement your app! Note that the require calls are resolved server (NodeJs) side.
RequireJS: specific require for browsers, means that your code would only run client-side.
Comment: I came up with browserify already, but (correct me if I am wrong) code above is not written they way browserify requires it to be written. I am trying to find exact tool the code was combined into this larger file.

"//= require js/lib.js" seems a bit confusing for me.
Comment: I understand better your problem now. No popular JS framework use the `//= require` syntax. I guess this has been commented and that the developer was using RequireJS, I'm adding the suggestion to my post.
Comment: Whole project is pretty messy and barely documented - I was bit confused by that. I was thinking about it being commented, but couldn't  get it all right. I will get a look at RequireJS, thanks.
Comment: Don't forget the AngularJS specifics here! Read this: https://stackoverflow.com/questions/18782324/angularjs-minify-best-practice
Answer: I wanted to just make this a comment to your original post, but it was too long. This isn't a definitive answer, so I apologize. Based on another post, (Google Closure Compiler Includes) I suspect they may have been using Google's Closure compiler, and using the require statements to trigger the Closure compiler's dependency analysis.
Apparently the compiler can translate the RequireJS 'require' statements into goog.require statements to establish ordering dependencies between the javascript files. So you may want to look at the monolithic file and see if there's any signs it went through the Closure compiler.


requestFiltering equivalent in IIS 6.0

Question: What is the equivalent of this in IIS 6.0 (The web.config code below works in IIS 7.5)
<system.webServer>
    <security>
      <requestFiltering>
        <requestLimits maxQueryString="xxx"/>
      </requestFiltering>
    </security>
  </system.webServer>

Answer: URLScan is the tool for IIS 6,
http://www.iis.net/learn/extensions/working-with-urlscan/common-urlscan-scenarios
Answer: Please see the answer to this question:  Increase file upload size limit in iis6
Anything in <system.webServer> is used by IIS 7 and above; IIS 6 does not know what to do with those configurations.  Stick to attributes in the <system.web> element for IIS versions below 7.

requestFiltering equivalent in IIS 6.0


Show that the Sylow 11-subgroup of a group of order 990 is normal

Question: The SmallGroups library in the program GAP reveals that each of the thirty groups of order 990 has a normal subgroup of order 11. But I would like to prove this fact directly, without reliance on a computer. The alternative to a single subgroup of order 11 is that there are 45 of them but I see no immediate way to rule that out....
Comment: If you show that $n_3=1$ first, I think that the result follows easily because the groups of order $3 \cdot 11$ are cyclic.
Comment: All groups of order 990 also have a normal Sylow 3-subgroup.  Proving that by hand also seems rather difficult to me.
Answer: Every finite group $G$ of order $2m$, where $m$ is odd, has a subgroup of order $m$ which, since it has index $2$ in $G$, is normal in $G$ (see this for instance). Thus a group of order $990$ has a normal subgroup $H$ of order $495=3^2 \cdot 5 \cdot 11$. Now focus on $H$. (Note that $n_3(H) \in \{1, 55\}$, $n_5(H) \in \{1, 11\}$ and $n_{11}(H) \in \{1, 45\}$.)
Comment: Let me know if you want me to finish the argument. You just have to play around a little with the possibilities.
Comment: Thanks!  I see two parts to work through -- the first is the claim on $2m$, $m$ odd (thanks for the link) and the second is the claim about $n_{11}(H).$  I am pretty sure I can do the second, since I had already spent a lot of time working through $N(P)$ of order 22, etc., without the advantage of this big normal subgroup.  (I now recall seeing the $2m$ claim elsewhere, but not in a standard textbook environment.)
Answer: Following on the hints from the first answer provided (thanks!) and attempting to work through this in my own words... here is my argument:
(1) Left multiplication provides an action of the group $G$ on itself and in this action, each nonidentity element is a permutation (in $S_{990}$) which fixes no points.
(2) An element of order two exists (Cauchy/Sylow) and such an element must be a product of 495 transpositions, thus an odd permutation.
(3) The intersection of the image of $G$ in $S_{990}$ thus intersects $A_{990}$ in a proper subgroup $H$ of order 495.
(4) If the Sylow 11-subgroup of $H$ is not normal then it has 45 conjugates, giving $45\cdot 10 = 450$ elements of order 11. This forces a unique Sylow 5-subgroup $K$.
(5) $H/K$, a group of order 99, has a unique Sylow 11-subgroup $P/K$.
(6) Any Sylow 11-subgroup of $H$ must be mapped onto $P/K$ by the natural homomorphism and it is not possible for the 5-1 natural map to send all 45 subgroups of $H$ to $P/K.$
The contradiction in (6) shows that the assumption in (4) is invalid and so the Sylow 11-subgroup of $H$ is unique.  Since any Sylow 11-subgroup of $G$ is a subgroup of $H$, then $G$ has only one Sylow 11-subgroup.
Comment: This argument, based on the existence of $H$, also shows why the Sylow 3-subgroup is unique.  By removing the factor 2 in 990, a lot of extraneous choices collapse.


Solidity Import Multiple Declarations

Question: I need to use external contracts (AAVE) so to call their methods I import them. Nevertheless, this import conflicts with the previous ERC20 Declaration and I have the next error:
<code>browser/Project.sol:10:1: DeclarationError: Identifier already declared. import "https://github.com/aave/protocol-v2/blob/master/contracts/interfaces/IAToken.sol"; ^----------------------------------------------------------------------------------------^ https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v3.3.0/contracts/token/ERC20/IERC20.sol:8:1: The previous declaration is here: interface IERC20 { ^ (Relevant source part starts here and spans across multiple lines).
</code>
Answer: You can remove the second import and still use the IERC20 interface as it is already imported by the first import.

Solidity Import Multiple Declarations


event hubs receive slow

Question: I am testing Azure event hubs from a single machine.
I have an event hub with max allowed partitions (32).
What I have found is that writing to the hub is very fast - basically in the order of 1000 msgs / sec. However when I try to pull the data out, I don't get nearly the same throughput. Pulling out 1000 msgs takes something like a minute.
I have tried both the Direct approach with 32 parallel receivers and the EventHost approach. Both are roughly the same in terms of speed.
I have left all settings as default.
Is it because I am using a single machine for pulling the data out? Note that writing from the same machine is not a problem.
Update: Here is the code that I am using for pulling data from Event Hubs (direct version):
<code>let startDirectPump
    stream
    eventHubConnectionString
    storageConnectionString
    fPost =
    let tag = "startEventHubPump"
    let client = EventHubClient.CreateFromConnectionString(eventHubConnectionString,stream)
    let cg = client.GetDefaultConsumerGroup()
    let runtimeInfo = client.GetRuntimeInformation()
    let pCount = runtimeInfo.PartitionCount
    let receivers =
        [for p in 0..pCount - 1 ->
            cg.CreateReceiver(runtimeInfo.PartitionIds.[p],System.DateTime.UtcNow)
            ]
    let tasks =
        receivers
        |> List.map (fun r ->
            async {
                try
                    while not r.IsClosed do
                        let! e = r.ReceiveAsync() |> Async.AwaitTask
                        if e <> null then
                            fPost e
                with ex ->
                    do! Async.Sleep 5000
                    Logging.logex "eh receive" ex
            })
    tasks |> Async.Parallel |> Async.Ignore |> Async.Start
    client
</code>
Comment: were you able to resolve it? I ran into the same issue as yours, I'm using a python SDK
Answer: If your goal is to pump data into Storm, there is actually integration being done to provide an adapter for getting EventHub data into Storm. Please see code @ https://github.com/hdinsight/hdinsight-storm-examples/tree/master/lib
As for figuring out the latency problem there is a number of things you may want to try:

Enable ServiceBus performance counter to see the receive latency. You can follow the example @ https://code.msdn.microsoft.com/windowsazure/Service-Bus-Messaging-7a0a0761
Your code is using DateTimeUtc as the checkpoint marker. I wonder if you can try using offset as the marker instead to see if there is a perf improvement (using datetime as marker will require a translation on the service side).
Make sure your client is running at the same Azure region as the EventHub.

Thanks
-Eric Lam (MSFT)
Answer: what are you using to measure the speed? Are you storing the data in database and checking there if all the data has been received? This problem may be somewhere else, may be in your database insertion. Some time it takes time when it tries to take lease on partitions initially. You can try sending more message once it warmed up. And check if still takes the same time.
Comment: I am using the wall clock for now. The difference is clearly noticeable. For now I am just dumping messages to the console as simple strings. I don't believe that this would be the bottleneck. I will run a longer test to see if it makes a difference.
Comment: I have not looked under the covers but could it be that the throughput is limited because of a single AMQP connection / single machine. Don't know if 32 partitions means that 32 connections are opened - one for each partition?
Comment: @fwaris, Have you figure out the root cause for this?
Comment: We faced similar kind of issue. Network latency could be a culprit here. You can try with 'short messages'. Another way could to to try out in Azure environment, like running your code on a worker role.
Comment: Unfortunately I was not able to determine the root cause. The messages are very short (about 200 char json). I don't believe that network latency is an issue as we are on the corporate network. Also tried Azure site.

At this point, my belief is that to get higher throughput you have to use multiple concurrent connections possibly from different machines. We may have to look for alternatives such as Kafka to get around this issue.
Comment: That should not be the case. We are working on similar kind of piece. We can easily receive 1000 msg per small messages. In case of bigger message, we could not receive them in this pace. But when we tested on Azure worker role, our receiving rate increased dramatically. Of course, it cannot go beyond 2 MB per second in case you are using 1 throughput unit.
Comment: thanks for info. I have tried azure website - not a worker role - but did not see any substantial increase. The code is very straightforward so not sure where the issue lies. Our goal is to pump data into Apache Storm so for now are using web sockets directly.
Comment: thanks i will try apache kafka, I do not like hearing about slow cloud latency, but it doesn't surprise me.
Answer: I've used the same approach as you did and couldn't receive any events / data. After some time, I found about EventProcessorHost which is a bit more verbose, but works just fine.
Answer: increasing the throughput unit will help you .

event hubs receive slow


how to delete a previous message if we get new message in django channels

Question: I want to broadcast the only latest message of Django-channel layer in a specific room. Right now I have created specific room names for specific users. Now I just want to send them only latest message or note, I don't want to show all the previous messages. Right now all the previous message are showing to user side.
<code>    # chat/consumers.py
import json
from channels.generic.websocket import AsyncWebsocketConsumer

class ProjectConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        parameter = self.scope['url_route']['kwargs']["project_key"]
        print("url_parameter ",parameter)

        self.room_name = parameter

        # Join room group
        await self.channel_layer.group_add(
            self.room_name,
            self.channel_name
        )

        await self.accept()

    async def disconnect(self, close_code):
        # Leave room group
        await self.channel_layer.group_discard(
            self.room_name,
            self.channel_name
        )

    # Receive message from WebSocket
    async def receive(self, text_data):
        text_data_json = json.loads(text_data)

        instance_user = text_data_json['instance_user']
        sender = text_data_json['sender']
        receiver =  text_data_json['receiver']
        message = text_data_json['message']

        object = {
            'sender':sender,
            'receiver':receiver,
            'message':message,
        }
        # Send message to room group
        await self.channel_layer.group_send(
            self.room_name,
            {
                'type': 'sent', #function name as an event type
                'object': object #function parameters as an event object
            }
        )

    # Receive message from room group
    async def sent(self, event):

        sender = event['object']["sender"]
        receiver = event['object']["receiver"]
        message = event['object']["message"]

        # Send message to WebSocket
        await self.send(text_data=json.dumps({
            'sender':sender,
            'receiver':receiver,
            'message':message,
        }))
</code>
Answer: Channel_layer broadcasts only the available message, you are probably appending the message to a DOM element in your front-end
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Nao estou conseguindo C. Porfavor me ajudem!

Question: Estou querendo fazer um caixa eletrônico somente com notas de 10, com limite de 1000 cédulas. Porém, tem que me mostrar quantas cédulas saíram no caixa e quanto sobrou para retirar e que seja possível sacar quantas vezes quiser até que as notas acabem. No entanto, quando eu coloco o valor que quero sacar o programa não mostra a quantidade de cédulas retiradas e quando eu respondo qualquer coisa o programa encerra, sendo que ele só poderia ser fechado quando eu respondesse "N".
#include<stdio.h>
main()
{
char R[1];
int S, SQ, Nc, Vt;
   Nc=1000;
   Vt=10000;
    while(R!="N" || Nc>0)
    {
    printf("limite:%d",Vt);
    printf("\nDigite quanto deseja sacar:");
    scanf("%d",&S);
    SQ=S/10;
    if ((S<0) || (S>Vt) || (S%10!=0))
    printf("Valor invalido");
    printf("\nDeseja realizar outro saque? [S/N]");
    scanf("%s",&R);
    break;
    if ((S%10==0) && (S<Vt))
    printf("%d nota(s) de 10.", SQ);
    printf("Deseja realizar outro saque? [S/N]");
    scanf("%s",&R);
    Vt=Vt-S;
    Nc=Nc-SQ;
    break;
    if (Nc == 0)
    printf("Sem notas");
    break;
}
}

Comment: Nós que perguntamos: onde está o erro? O que está ocorrando?
Comment: Acabei de fazer a alteração, porém o programa continua fechando após eu colocar o valor de saque.
Comment: Ok, então agora vale apena você [Edit] a pergunta e colocar o novo código corrigido e talvez adicionar mais informações como:  **O que esta ocorrendo**, **Mostra algum erro**, **Passos para o erro ocorrer**, ...  Isso vai ajudar a comunidade a identificar e te explicar o que esta acontecendo =D -- não esqueça de dar uma olhada no nosso [Tour]
Comment: Me parece relacionada: https://pt.stackoverflow.com/q/386706/3774
Comment: O programa excuta, porém depois que respondemos quanto desejamos sacar o programa encera.
Comment: Talvez esse seja o problema `if (Nc = 0)` mais uma comparação `=` ao invés de `==`
Comment: acerte a indentação de seu código, para facilitar o entendimento de outras pessoas
Answer: O erro que você está tendo é:
segmentation fault (core dumped)
Esse erro é causado nessa linha:
scanf("%d",S);
Faltou o "&":
scanf("%d",&S);
Se você fizesse a pergunta informando esse erro, e onde está ocorrendo, com certeza vários usuários identificariam o erro na mesma hora!
Comment: Inclusive, existe um erro de lógica: no `while(R!="N" || Nc>0)` deveria ser `&&`, caso contrário seu programa só irá parar quando o usuário digitar 'N' E o Nc for menor ou igual a 0
Comment: Concertei esse erro, mas o programa ele inicia, eu coloco o valor que quero sacar, porém ele não fala quantas cédulas foram retiradas e quando eu aperto para continuar ele encerra o programa, sendo que só era para encerrar quando eu colocasse "N" como resposta.
Comment: Consertou qual erro?
Que erro está ocorrendo agora?
Answer: Seu código não foi postado completo.
Ou você declara sua variável R com um único caractere e faz a comparação utilizando aspas simples:
char R;
...
while(R!='N' || Nc>0) {
...
scanf("%c",&R);

ou declara como uma string, isto é um array de caracteres que deve ter um tamanho mínimo de 2 para comportar o caractere terminador '\0'. Neste caso você precisará utilizar a função strcmp de <string.h> e não utilizar o & no scanf.
char R[2];
...
while(strcmp(R, "N") != 0 || Nc>0) {
...
    scanf("%s",R);

Note que não tem sentido você colocar comandos na sequencia de um break; pois eles não serão executados.


Tkinter Root Window Disappeared after Withdraw()

Question: I am writing a program that opens a file using the file browser and stores it as a path in a variable. I want to hide the root window until after the file path has been selected. However after I call the root.withdraw() method
I have tried calling root.deiconify() after the file path method and also root.iconify() I have also tried using the Toplevel method however it seems the window has completely vanished from the screen and the taskbar.
root = tk.Tk()
root.winfo_toplevel()
root.withdraw()

filePath = filedialog.askopenfilename(initialdir="~/", title="Select file")

root.update()

fileSize = os.path.getsize(filePath)
print("File selected: " + filePath)
print("\nfile is: " + str(fileSize) + " bytes\n")

#.............................................................
root.deiconify()
button1 = (root, text="SHA256", command=SHA256(filePath))
button1.pack()

fileType = input("specify checksum type: " + "(ex. md5, sha1, sha256)" + "\n")

if fileType.lower() == "md5":
    message = MD5(filePath)
    print("MD5:\n" + message + "\n")
elif fileType.lower() == "sha256":
    message = SHA256(filePath)
    print("SHA256:\n" + message + "\n")
elif fileType.lower() == "sha1":
    message = SHA1(filePath)
    print("SHA1:\n" + message + "\n")

elif fileType.lower() not in hashTypes:
    print("Invalid file type \n\n")

No errors are being shown the root window has simply vanished and cannot be recalled into view.
Comment: Is this all of the code? I don't see where you're calling `mainloop` anywhere.
Answer: Those two together:
root.update()
root.deiconify()

are the correct way to bring back root after withdraw call. You probably have a problem that your program don't have a main loop- bind some button to root.destroy and call root.mainloop() at the end.


Prove that $ \{0,1\}^{|A|} $ is finite

Question: If I want to prove that a set $ \{0,1\}^{|A|} $ is finite for $ A$  finite set in a rigorous formal way, induction is innevitable?
because my idea was to claim that by definition of $ |A^{B}| $, it follows that $ |\{0,1\}^{|A|}|=2^{n}\in\mathbb{N} $ and therefore $ 2^{n}<\aleph_{0} $.
Is this proof wrong? I have to use induction in order to prove this claim?
If someone with experience of checking exams could tell me if he would accept this proof, this would be very helpful. Thanks.
Answer: Your proof seems correct. But if you want to use induction... go ahead, use induction on the size of $A$.
Assume $ \{0,1\}^{|A|} $ is finite and is of size M. What is then the size of the set $ \{0,1\}^{|B|} $ where B is any set which has 1 element more than $A$?
Comment: Then you may want to argue with the professor. Then you will understand if there's a flaw in your proof or not. Maybe you assumed something which is obvious but not really proven. But he cannot just say: "this is the only way" without explaining why. You should argue with him and find out.
Comment: Actually I do not want to use induction. But my proffesor gave me 3/10 for this proof, and claimed that there is no other way to prove it rather than induction over the size of A. But I just cant understand why. $ 2^{|A|} $ is a natural number. every natural number is smaller than $ \aleph_{0} $ and therefore the set is finite
Comment: I did, the answer I got was "this is an argument over the natural numbers, you have to prove by induction that it holds for any natural number, saying $ 2^{n} $ is finite is just assuming what you were suppose to prove "

Prove that $ \{0,1\}^{|A|} $ is finite


How detailed is penalty kick encroachment in football

Question: The laws of the game prohibit encroaching on a penalty kick whether it is an attacking player or defending player.  The keeper is supposed to remain on the line until the kick is taken but in practice this is a loose interpretation; movement off the line is common.
My question is: if another player (besides the keeper and penalty taker) has a foot on/over the line of the 18 yard box or the arc, what grounds are there for a retake or an indirect kick out?  Is it a similar loose interpretation which goes unpunished or shall it be referenced as an offside play or simply an infringement?
Answer: In answer to your first question, let's consider how it should be called.
From Law 14 - The Penalty Kick, Section 1 - Procedure:

The defending goalkeeper must remain on the goal line, facing the kicker, between the goalposts until the ball has been kicked.
The players other than the kicker and goalkeeper must be:

at least 9.15 m (10 yds) from the penalty mark
behind the penalty mark
inside the field of play
outside the penalty area

After the players have taken positions in accordance with this Law, the referee signals for the penalty kick to be taken.

Now, if encroachment as defined above occurs, Law 14 - The Penalty Kick, Section 2 - Offences and Sanctions states that:

Once the referee has signalled for a penalty kick to be taken, the kick must be taken. If, before the ball is in play, one of the following occurs:

the player taking the penalty kick or a team-mate offends:

if the ball enters the goal, the kick is retaken
if the ball does not enter the goal, the referee stops play and restarts with an indirect free kick

...

the goalkeeper or a team-mate offends:

if the ball enters the goal, a goal is awarded
if the ball does not enter the goal, the kick is retaken; the goalkeeper is cautioned if responsible for the offence

a player of both teams offends the Laws of the Game, the kick is retaken unless a player commits a more serious offence (e.g. illegal feinting); if both the goalkeeper and kicker commit an offence at the same time:

if the kick is missed or saved, the kick is retaken and both players cautioned
if the kick is scored, the goal is disallowed, the kicker is cautioned and play restarts with an indirect free kick to the defending team

A summary of the outcomes for encroachment (and other penalty kick infringements) is also included in Law 14 - The Penalty Kick, Section 3 - Summary Table.
As for your second question, with the 2016 rewrite of the Laws of the Game, referees were explicitly given broad discretion. In Law 5 - The Referee, Section 2 - Decisions of the Referee, it states:

Decisions will be made to the best of the referee`s ability according to the Laws of the Game and the 'spirit of the game' and will be based on the opinion of the referee who has the discretion to take appropriate action within the framework of the Laws of the Game.

The other big change in 2016 was the requirement to caution the goalkeeper for unsporting behaviour if a retake is required due to them leaving their goal line before the kick is taken.
Whether it was intended or not by IFAB, the combination of these two changes have led to referees only taking action when there is blatant encroachment. The alternative, i.e. strict enforcement, would dictate that the goalkeeper would be sent-off for being millimetres off their line for a saved / missed penalty kick twice in a match. This is clearly a disproportionate punishment.
Finally, here's an example of a referee having a penalty kick retaken multiple times for encroachment by both the goalkeeper and outfield players. In my opinion, at the time when this occurred in 2004, he would have been correct. However, by 2017 standards, none of the kicks required referee intervention.
Also, here's a better quality video of a different incident, with replays showing the encroachment. At the time, in 2005, the first two of these calls were probably correct, but to be consistent, the third kick should have been retaken, as a Brazilian defender (in yellow) entered the penalty area before the kick was taken and it was missed.
However, applying 2017 standards, I believe that only the blatant goalkeeper infringement on the second kick should have been retaken. In 2017, this would also require the goalkeeper to be cautioned, but this seems proportionate, given that he was one to one-and-a-half metres off his line before the kick was taken.
Comment: +1 for a splendid answer. I used to be a ref as well, and I know the troubles caused by inconsistency. In addition to your answer, I would like to add that "the rule (and interpretation of the rule) is written so that it punishes the offender, and not the 'victim'." It's a good rule, it's just that refs need to be more consistent :)
Comment: @Qvist I think the best part about it as that it offers immediate restitution to the team that has suffered from the encroachment. However, I do think that goalkeeper needing to remain on the line is very difficult and this causes a lot of retakes. It's very hard to remain perfectly still and only move laterally when making a save. I think there would be a lot less retakes if the goalkeeper was allowed to be on, or up to a metre behind the line. However, as I mentioned in the answer, players moving into the penalty area or arc early really have no excuse.
Comment: I couldn't agree with you more! As long as the GK doesn't gain a clear advantage, it should be ignored really.
Comment: Three years on and this answer hasn't aged particularly well. I'll make an effort to update it at some point if possible.
Comment: Great answer except that you missed (in the 2nd video) that on the 2nd and 3rd penalty there was a defender entering the penalty area - before the kick was taken, that is not allowed unless the result of the penalty is a goal. So both these penalties should acctually have been retaken.


Simple sequence a(n)

Question: what is a sequence a(n) such that the nth entry of a(n) is {0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3,...,a(n)}, with the first entry pertaining to n=0, the second to n=1, ans
I attempted to use mathematica's FindSequenceFunction command:
FindSequenceFunction[{0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3}, n]
which did not return a functional answer.
Comment: $\text{floor}\lfloor x/7 \rfloor$?
Comment: What are restrictions on $a_n$? There are infinitely many sequences which start like this - you must have some criteria for picking out a given one.
Answer: I'm guessing:
$$
a_n=\begin{cases}
\lfloor\frac{n}{7}\rfloor\ \text {if}\ n<28\\
42\ \text{else}
\end{cases}
$$
As Sten pointed out in a comment there are infinitely many sequences that start like yours, this is just one.
Answer: Could be the obvious A132270(n-1), or A054896(n)
Comment: does there exist no closed form representation as a function of n?
Comment: For A132270(n-1), $$(n-3)/7 + \sum_r \dfrac{r^5+2 r^4+3 r^3+4 r^2+5 r-1}{49 r^{n+1}}$$ where the sum is over the roots $r$ of $X^6 + X^5 + X^4 + X^3 + X^2 + X + 1$.

Simple sequence a(n)


Synology volumes vs shared folders

Question: What is the benefit of making more than 1 volume on disk group on Synology DiskStation? Or, in another words, what is the benefit of organising data into a) many volumes vs b) many shared folders on one volume? I'm interested in any considerations in: access, administration, maintenance and backup context.
Answer: In terms of resiliency and maintenance, it seems to me the number of volumes would be beneficial in case of High Availabilty (HA) system design due to replication. Let's say you have 2 or more volumes on 2x Synology hosts configured on HA shared storage and face drive failure on a single host. It would take less to replicate each volume across hosts (restore and bring HA volume online), instead of a case of single volume, where, obviously, it takes more time to get a single volume replicated.
For a single node, shared folders on a single volume would be beneficial due to I/O performance. In the case, the data on each shared folder would be available with speed of overall storage performance, reads and writes would be performed from the whole storage array.
Comment: Many thanks for enlightment. I've also found that HyperBackup warns while creating backup task with destination on the same volume as data while does not warn when destination is on different volume than data, although both volumes are on the same disk group. Do you know what's the difference in terms of backup safety while this is still the same disk group?

Synology volumes vs shared folders


audit_log_user_command(): Connection refused when using sudo, what's wrong?

Question: i ssh to my remote centos sever as hugemeow, then i run sudo ls, then error happens:
[hugemeow@home ~]$ sudo ls
**audit_log_user_command(): Connection refused**
httpd

hugemeow is in /etc/sudoers, with the config as the follows:
hugemeow ALL=(ALL)     ALL

what's wrong with the msg showned above?
Comment: `rpm -qa| grep sudo`?
Answer: The error you're seeing isn't important; it means that sudo is trying to connect to a local auditd server but that one isn't running.  You'll note that the sudo command worked anyway, despite the error.  This message should be suppressed in newer versions of sudo (according to Fedora bug 401201, this was fixed back in 2010).
In theory, making sure that auditd is running on your system should make the error go away.


Feasibility of Linear Mixed Effects Models (aka. MLM) after Unflattering Visual Inspection

Question: Is it still of utility to run a full-blown LME modelling procedure when the visual inspections between the predictors and outcome variable are characterless?
I have been arguing that it makes little sense to invest more time and effort in using LME in such a case, since the goal is to discover which predictors have significant effects on the outcome but visually eyeballing the pairwise scatter plots indicates otherwise.
In greater detail, I have two predictors W and G and an outcome S2 in a longitudinal dataset; the time variable is called ACAGE, which is the individuals' ages. I am interested to see whether any of the two predictors influence S2 significantly.
I produced the scatter plots of mean S2 over ACAGE against W of individuals. In addition, instead of averaging S2 over ACAGE, I faceted by ACAGE in a second group of plots. I did the same also for G. Here is an example where S2 values constitute the y-axis and W the x-axis (I cannot show too much due to data privacy):

None of the plots showed patterns/candidate relationships between the independent and dependent variables. I am wondering whether it is wise to proceed to LME in this case, and I think it is not.
Notes:

I have 484 subjects and 9 items
The subjects and items are crossed, not nested
The "best" model itself is still unspecified, but it is along the lines of S2 ~ G * W + (G*W | subject_id) + (G*W | item_id)
Comment: What pairwise scatter plots have you inspected?  Please provide more details about all the variables in your dataset.
Comment: I will edit the question accordingly
Comment: And what would be your proposed linear mixed model formula ?
Comment: I would build it gradually in a taxonomy of models, but to answer you and "keep it maximal", it's along the lines of `S ~ G * W + (G*W | subject_id) + (G*W | item_id)`. I hope this answers your question.
Comment: So are subjects cossed with items ? Why isn't `ACAGE` in the formula ?
Comment: Subjects are indeed nested within items (I used `lmer` `R` notation). As to `ACAGE`, the time-invariant predictors `W` and `G` are of more interest towards the final goal of the analysis, but I'm not severely against including it as well
Comment: So why are you doing different plots foe each value of ACAGE  ?
Comment: A very fair question, I should've been more elaborate in the question but I didn't feel it was necessary. The first idea was to average `S2` over `ACAGE` for visual inspection, but then I was worried about the Simpson's Paradox since `S2` itself was calculated using another mean, so I faceted by `ACAGE` as well. Long story short, I didn't see encouraging patterns in the scatter plots in all cases, hence why I questioned proceeding to LME. I may have missed the point of your inquiries, if so it would help if you explain it more. Thank you!
Comment: Sorry I said subjects and items are nested while they are *crossed*
Comment: No problem. That makes more sense. And how many subjects and items are there ?
Comment: I couldn't edit the "nested" comment understandably. 484 subjects and 9 items.
Answer: After some discussion in the comments, I don't think you can discard the idea of fitting a mixed model based on the plots that you have described.
The study design is reasonably complex and the proposed model:
S ~ G * W + (G*W | subject_id) + (G*W | item_id)

...is likewise quite complex. In order to discard the idea of fitting a mixed model you would need to establish that there is very little variation of the outcome within subjects and items. To destermine this from plots alone would mean plotting the outcome against covariates for every subject. Since you have 484 subjects, this is not really feasible. With 9 items it is feasible, but still, it is hard to see how you would determine that there is no variation, simply from inspecting such plots.
The best way forward in this situation is to fit the proposed model and if any of the variance components are close to zero, then consider removing them. The random structure of the proposed model is quite complex so it would not be surprising if it led to a singular fit. If so then you can follow the procedure in this answer:
How to simplify a singular random structure when reported correlations are not near +1/-1
Comment: Thanks, I updated the question to summarise the comments for convenience. I can confirm the singular fit occurs, so +1 for the additional resource.


Why would just adding a product to cart create a payment with method type "unknown" and credit card of "4111--------1111"

Question: We have the Payment Method Example module turned OFF. And, we only have one payment type set up (Authorize.net) in the Enabled Payment Method Rules.
Yet, when we add just one product to the cart and click submit (without going to checkout, so without filling in any payment fields) we can go to orders/shopping cart and see that a payment with the following fields has been added to the order in process:
Date: "6/25/2015" (even though today is 6/22/2016)
Method: "Unknown"
Remote ID "-"
Result Message: -    Number: 4111--------1111  Expiration: 06/2015
Amount: $1,788 (which is $4.00 less than the total for this particular order. Note that this amount will vary, though.)
This causes the following Authorize.net issues:
1) In the above example, Authoize.net comes in and accepts a transition for $4.00. The order balance is then zero, based on the above $1,788 "unknown" payment plus the $4.00 from Authorize.net.
OR
2) Authorize.net comes back with the below error when the "Unknown" method payment is larger than the actual order:
REJECTED: A valid amount is required.
AVS response: AVS not applicable for this transaction
CVV match: -
If it helps, here are the rules that fired on the product submit page:
Commerce Pricing Attributes (default)
Calculate taxes: Sales tax (default)
Calculate taxes: VAT (default)
Reset the cart order status on product add or remove (default)
Add to Cart message (overridden)
Redirect after product add to Cart (custom) - a page redirect after submit
So - I need some help to debug/fix this:
1) Is there anything obvious I should look at? I have analyzed the setup of all modules, rules, etc.
2) How would what looks like an example payment type be added before even going to any checkout page - when we have the Payment Method Example module turned OFF.
3) And, since there is no error message - where do I even begin to debug this (I am a novice)?
4) Will Devel help? It seems you need some code added to a module. How do I figure out what module, what code, and where to add the code?
Thanks! Any help you can give would be highly appreciated!
Comment: Were there any uncompleted test orders made by your user account still in the database? Sometimes Commerce attempts to link these to your basket and gets it wrong.
Comment: If I recall right, that credit card number is a test number that fits the auto card number validator but is not a real card.  Sounds like you have a test harness active somewhere.  1) go through _all_ the rules that are on the site, even if they should not be firing.  2) grep your doc root `grep -nr "4111" ./*`
Comment: Thanks Alfred! I deleted all orders/shopping carts that were created before we went live (ie - when the Payment Method Example might have been turned on). But - I am still seeing the unknown payment being applied when a product is added. I will start analyzing the rules now... Thanks again!
Answer: Fixed it!
When you delete an order on the order page, the associated payment does NOT get deleted. And, once the order is deleted, there is no way to delete the payment in Drupal commerce, since you only have a view of the orders.
Then, when you create a new order, the order number you deleted can get 'reused'. So, the old payment is then associated with this new order. That is why we saw the errant payments on the new orders.
So, I fixed this issue by going into the database and manually deleting all of the errant example payments in the commerce_payment_transaction table. So far, so good….
Bottom line: NEVER delete an order once live. Or, minimally, always delete the order's payment FIRST, then the order.
Comment: Note - this issue should be resolved in the future once the patch is created that disallows the deletion of orders if they have payments. See https://www.drupal.org/node/1208896


Scaling Cumulative Probability Distribution function values

Question: We have a cumulative probability distribution function (cdf), we want to scale it down for using it in anomaly detection. The mapping should look like this.
CDF value: 0.1   ...  0.5    ...  0.9  ...  0.99  ... 0.999 ... 0.9999 ........
Mapped to: 0.001 ...  0.002  ...  0.01 ...  0.2   ... 0.3   ... 0.5 ........
So CDF greater than 0.9 is relevant and then the values should start increasing rapidly. The mapped scale is between 0 to 1, with 0.2 being strong anomaly and 1 being extreme anomaly.
Is there any standard function to scale CDF values, in above described manner?
Also is this a standard Statistics approach, or this approach is used in Anomaly Detection? (Any references will be helpful)
Comment: How about polynomal mappings? $x\mapsto x^2$ comes to mind as the most usual, but increasing the exponent will make it increasingly sharp. Your values are quite extreme so maybe $x^{20}$ provides a good scaling.
Comment: It gives a good approximation but not exactly the same thing, as you can see 0.999 and 0.9999 have high difference in their mapping values. Using simple polynomial mappings, can't help it.
Comment: Roots, maybe? Think of $1-\sqrt[n]{1-x}$ will not even be differentiable at $1$.
Comment: This seems to be plausible solution (not exact kind of results though), but are there any standard approaches for this?
Also, are there any references where people use this for anomaly detection?
Comment: I guess most of the time you'll just highlight significance levels of a certain magnitude. Not an expert on the subject, though.
Comment: Yes, but what we also want is to justify why we chose a certain scale/function, will be writing a research paper. So, what i don't know if this is standard approach in statistics or anomaly detection.
Answer: As for your question about anomaly detection, you can use any threshold on CDF to declare an anomaly, despite what the CDF is, and you can apply any arbitrary non-negative increasing transformation to your CDF. So your proposed framework doesn't really add anything new to the concept of "anomaly detection." You're just changing around some thresholds for detection from one CDF to the next, leaving the set of finally declared "anomalies" intact. And frankly, 0.2 is quite an unusually low threshold to declare an anomaly anyway, at least in practice, so you might want a different pair of transformation/threshold assuming this is something you still want to do and sell to your audience.
Comment: This is just a part of problem statement, I am not adding anything new to anomaly detection.
I can apply certain function such as root etc., but I want to know is there any standard approach for it, so that I can justify why I choose a certain function.
Comment: @RamanGoyal What I'm saying is that you can use your original CDF for anomaly detection, with suitable threshold, without doing any transformation. Changing the CDF monotonically just changes what anomaly threshold you want, and doesn't "justify" the anomaly detection in any way unless you can show that you originally had a distorted CDF and can show how to "fix" it so that thresholds retain their intended meaning. CDF value of 0.99 means 1% chance of being occurring by chance, assuming your CDF is correct.
Comment: Well I need to change them because there are multiple attributes, and then I need to combine them.
Also, the problem with using original CDF is that if value of 499 is 0.999, then value for 500 is 0.9999 and value for 500000 is 0.99999, what I essentially want is to distinguish them on a broader scale.