text:
Q: How to fastly select data from Oracle I have the following Oracle table:
GAMES
    id_game int
    id_user int
    dt_game DATE

Before creating a new record I must check that the same user has not inserted a game more than N times a day.
I'm actually selecting the number of games played today in this way:
select count(1) as num from GAMES
where id_user=ID_USER and
to_char(dt_game,'DD/MM/YYYY')=to_char(sysdate,'DD/MM/YYYY')

I don't like it very much. Is there a better way to do it?
Thanks in advance.

A: The date conversions are a bit pointless and prevent any index on that column being used; you could simplify that bit with dt_game > trunc(sysdate).

A: There is a problem (related to concurrency) with checking the table and counting the rows before inserting a new row.
Let us say the user currently has played 9 games and you want to limit the rows to 10..
if you open two different sessions, then the both of them will see the currently uncommitted value of 9 games and hence both the games are allowed, By the time the transaction is complete, the user would have played 11 games..which is against the rule that you are trying to enforce.

A: You can use a unique constraint to ensure that a fixed maximum number of records may be inserted for a particular day. For example, if N=5:
CREATE TABLE GAMES (
  id_game         NUMBER NOT NULL,
  id_user         NUMBER NOT NULL,
  dt_game         DATE   NOT NULL,
  user_game_count NUMBER NOT NULL,
  CONSTRAINT max_games_per_day
  CHECK (user_game_count BETWEEN 1 AND 5),
  CONSTRAINT dt_game_notime
  CHECK (dt_game = TRUNC(dt_game)),
  CONSTRAINT games_unique
  UNIQUE (id_user, dt_game, user_game_count),
);

The max_games_per_day constraint means that it can only take one of 5 different values. The dt_game_notime constraint means that we won't get various time values. The unique constraint, finally, ensures that for any particular date and user, they can only insert up to 5 rows.

A: In Oracle you can create a function based index on id_user, to_char(dt_game,'DD/MM/YYYY') to improve lookup performance.


text:
Q: AngularJs directive compile function and isolated scope My problem is demonstrated in the below plnkr
Plnkr
  <ntimes repeat=10 >

Hello World - 10 {{smsg}}

More text

    </ntimes>

Directive :
directive('ntimes', function() {
return {
    restrict: 'E',
    scope:{
      smsg: '='
    },
    compile: function(tElement, attrs) {
        var content = tElement.children();
        for (var i = 0; i < attrs.repeat - 1; i++) {
            tElement.append(content.clone());
        }
        tElement.replaceWith(tElement.children());

        return function(scope,elem,attr){
          scope.smsg='abc';
        }
    }
}
})

I have a compile function returning link function, and the directive scope is isolated. When I update scope variable in the link function, the page is not rendering the updated value.  I am expecting to see abc instead of xyz.
Please help

A: When using two-way-data-binding you have to make sure the variables are connected properly.
This means that in your directive you declare that the smsg scope variable will be two-way-data-binded with something else which will be declared in the DOM.
Now looking at the DOM this "link" is missing which provides you this error.To fix it you have to change your html to this <ntimes smsg="smsg" repeat=10 >
And when you do your new smsg will be equal to 'abc'.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Question about Azure Devops pipeline question about task conditions I've been trying to setup an Azure Devops pipeline for testing purposes and i'm struggling to understand why one of my tasks runs the script line despite being skipped.
Here's the pipeline yaml code:
## Example azure-pipelines.yml

## Event (branch to trigger the pipeline execution)
trigger:
  branches:
    include:
    - main
    exclude:
    - My-branch # Will not run

# Configures pipeline execution on pull requests
pr:
  branches:
    include:
    - main
    exclude:
    - My-branch # Will not run

# Environment variables created
variables:
- group: my-keys

## OS where the pipeline will run
pool:
  vmImage: 'ubuntu-latest'

# List of stages for your application
stages:
- stage: Test
  displayName: Application Testing
  # List of jobs the pipeline stage will run
  jobs:
  - job: MyJob
    displayName: Install packages and and publishes
    variables:
      # Sets the environment variable to cache the application packages
      npm_config_cache: $(Pipeline.Workspace)/.npm
    # List of steps for the job
    steps:
    - task: NodeTool@0
      inputs:
        versionSpec: '12.x'
      displayName: 'Install Node.js'
    - task: Cache@2
      displayName: Install and cache packages
      inputs:
        key: 'npm | "$(Agent.OS)" | package-lock.json'
        restoreKeys: |
          npm | "$(Agent.OS)"
        path: $(npm_config_cache)
    - script: npm ci
      condition: ne(variables.CACHE_RESTORED, 'true')
    - task: Npm@1
      displayName: Publish and auto accept
      condition: and(succeeded(), eq(variables['build.sourceBranch'], 'refs/heads/main'))
    - script: npx my-package  --with-token=${my-keys} --auto-publish-changes
    - task: Npm@1
      displayName: Publish
      condition: eq(variables['Build.Reason'], 'PullRequest')
    - script: npx my-package --with-token=${my-keys}
    - script: echo ${{variables['Build.Reason']}} ${{eq(variables['Build.Reason'], 'PullRequest')}}

A example, for instance when a push is made into the main branch it runs Publish and auto accept followed by the Publish, when it technically should only run the first one. One other thing that i saw was that when a pull request is incoming to one other branch rather than main it shouldn't trigger the script associated to Publish and auto accept but instead jump over that and run only the script in Publish, but instead it runs the scripts in both.
If anyone could provide some help with this i would appreciate it.
Thanks in advance

A: I think the problem is that you run 4 tasks instead of two
Take a look at NPM task syntax, it has no 'script' parameter
https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/package/npm?view=azure-devops
'script' task that you are using is indeed shortcut of another task 'CmdLine@2'
https://learn.microsoft.com/en-us/azure/devops/pipelines/tasks/utility/command-line?view=azure-devops&tabs=yaml
Firstly you run NPM task with specified condition, but it does nothing
task: Npm@1
  displayName: Publish and auto accept
  condition: and(succeeded(), eq(variables['build.sourceBranch'], 'refs/heads/main'))

Then you run script task without condition(so it will run always), this task does npm stuff
script: npx my-package  --with-token=${my-keys} --auto-publish-changes

Then you run again npm task without desired parameters but with conditions
task: Npm@1
  displayName: Publish
  condition: eq(variables['Build.Reason'], 'PullRequest')

And finally you run fourth task doing stuff, without conditions so it runs always.
script: npx my-package --with-token=${my-keys}

So as to fix this problem, you need to use Npm@1 task with parameters specified in provided documentation. Or just add conditions to your script tasks(CmdLine@2).
I think that below snippet should work
- task: CmdLine@2
  displayName: 'Publish and auto accept'
  condition: and(succeeded(), eq(variables['build.sourceBranch'], 'refs/heads/main'))
  inputs:
    script: 'npx my-package --with-token=${my-keys} --auto-publish-changes'

- task: CmdLine@2
  displayName: 'Publish'
  condition: eq(variables['Build.Reason'], 'PullRequest')
  inputs:
    script: 'npx my-package --with-token=${my-keys}'


text:
Q: Указатели и функция Как правильно разименовать эти указатели, почему пишет , что не получается операция записи?
#include <stdlib.h>
#include <conio.h>
#include <stdio.h>
#include <math.h>

long double* fn(float* z1, double* z2)
{
   long double* zz;
   zz = (log(--z1)/z2);
   return zz;
}

int main()
{
  float aa;
  double bb;
  long double* p1;
  float* p2=&aa;
  double* p3=&bb;

  aa = 10; bb = 15;

  p1 = fn(p2, p3);
  printf("fn=%.3f", p1);
  getch();
  return 0;
}

A: Разыменовывание указателя производится такой же звёздочкой. Это
zz = (log(--z1)/z2);
надо заменить на
zz = (log(--(*z1))/(*z2));

То есть, поскольку функция принимает не вещественные числа, а указатели на них, надо брать не значения указателей (т.е. числовые представления адресов, на которые они указывают), а то, что находится по этим адресам.
Функция у Вас тоже возвращает указатель. По идее, в переменную zz надо записать не число, которое возвращает выражение (log(--(*z1))/(*z2)), а адрес переменной, в которую это число будет записано. Только, скорее всего, как только Вы выйдете из этой функции и попробуете разыменовать этот указатель, Вы получите ошибку доступа к памяти, т.к. указатель будет указывать на фрейм стека, который после выхода из функции будет неиспользуемым.
A: Переменная zz внутри функции должна ссылаться на какой-то блок памяти, который нужно выделить функцией malloc. Чтобы присвоить значение переменной, а не указателю на нее, нужно использовать *zz=..., и точно так же чтобы получить значения z1 и z2.
Плюс для вывода long double лучше использовать %Lf, хотя на винде long double и double вроде не отличаются.
#include <stdlib.h>
#include <stdio.h>
#include <math.h>

long double* fn(float* z1, double* z2)
{
   long double *zz = (long double*)malloc(sizeof(*zz));
   *zz = (log(--*z1)/(*z2));
   return zz;
}

int main()
{
  float aa;
  double bb;
  long double* p1;
  float* p2=&aa;
  double* p3=&bb;

  aa = 10; bb = 15;

  p1 = fn(p2, p3);
  printf("fn= %.3Lf\n", (long double)*p1);
  free(p1);
  scanf("");
  return 0;
}


text:
Q: find_by on unsaved many to many association I have a model Payment which has many PaymentItems where each payment item is associated with an Item.
class Payment < ActiveRecord::Base
  has_many :payment_items, inverse_of: :payment
  has_many :items, through: :payment_items

  accepts_nested_attributes_for :payment_items, reject_if: ->(payment_item_attributes) { payment_item_attributes['item_id'].blank? }
  ...
end

class PaymentItem < ActiveRecord::Base
  belongs_to :tab_item, inverse_of: :payment_item
  belongs_to :payment, inverse_of: :payment_items

  ... validations ...
end

In my form for a payment, I'm using a fields_for method for each PaymentItem while iterating over available items.
= form_for @payment do |f|
  - @tab_items.each do |item|
    = f.fields_for :payment_items, @payment.payment_items.find_or_initialize_by(item_id: item.id) do |payment_item_form|
      %label
        = payment_item_form.check_box :item_id, item.id, nil
        = item.name

There is more nesting going on to collect more information for payment_item which has validations but if validations fail find_or_initialize_by method does not find items by item_id.
My question is: does find_by work on unpersisted nested models in case validation fails? My work around for now is to do something like:
@payment.payment_items.select {|i| i.tab_item_id == item.id } || @payment.payment_items.new(tab_item: item)

but it feels clunky.
Thanks for any help.


text:
Q: Not all the data on mongoose schema can be posted I have a mongoose schema as follows:
var myprojectsSchema = new Schema({

        pname: String,
        pnumber: String,
        plocation: String,
        pclient: String,
        clientabn: String,
        contname: String,
        contnumber: String,
        mobile: String,
        address: String,
        city: String,
        country: String,
        pocode: String,
        pdesc: String,
        punit: String,
        pqty: String,
        prate: String,
        pprice: String,

});

Myprojects  = mongoose.model("Myprojects", myprojectsSchema);

when I post the data from a form, not all the data can be seen on mongo database, I only can see the first 12 items on mongo database but not the last 5. please note i don't have the last 5 items on my form but still i should see them as "nill" on data, is it correct? (I have another schema exactly the same situation but can see all the items in schema)
below is the post route:
app.post("/myprojects", function(req,res){

var pname = req.body.pname;
var pnumber = req.body.pnumber;
var plocation = req.body.plocation;
var pclient = req.body.pclient;
var clientabn = req.body.clientabn;
var contname = req.body.contname;
var contnumber = req.body.contnumber;
var mobile = req.body.mobile;
var address = req.body.address;
var city = req.body.city;
var country = req.body.country;
var pocode = req.body.pocode;
var pdesc = req.body.pdesc;
var punit = req.body.punit;
var pqty= req.body.pqty;
var prate= req.body.prate;
var pprice= req.body.pprice;

 var newProject = {
    pname:pname,
    pnumber:pnumber,
    plocation:plocation,
    pclient:pclient,
    clientabn:clientabn,
    contname:contname,
    contnumber:contnumber,
    mobile:mobile,
    address:address,
    city:city,
    country:country,
    pocode:pocode,
    pdesc:pdesc,
    punit:punit,
    pqty:pqty,
    prate:prate,
    pprice:pprice,
 };

 Myprojects.create(newProject,function(err, newlycreated){
    if(err){console.log(err);}else{
        res.redirect("/myprojects");
    }
  });
});

A: If no value is available for a property than that property is considered to be undefined. That's why you don't see that in mongodb.
you can use default value as follow:
pprice: {
   type: String,
   default: null
}


text: Q: Can a connection be moved or shared between indy components? Is it possible to transfer a connection between indy components in delphi: to have a client thread connect, and then make server's onexecute event process this connection, rather than the thread? If it is, some syntax hints pls. Thank you.


text:
Q: Getting many undefined calls when running , each function is saying that it is undefined I am getting undefined values everywhere, its very annoying. I believe it might be a problem the way Im setting up the input with const
const prod = new Product();
prod

or is it something else ? I believe have try to fix some functions, like return this for buy product and fixing my toLowerCase with a null.
var products = [];
class Product {
   constructor(productName, amount, cost) {
       this.productName = productName,
        this.amount = amount,
        this.cost = cost
   }

   buyProduct(product){
       products.push(product);
       return this;

   }
   deleteProduct(str){
       var found = products.find(function(element){
       })
       if(found)
       {
           if(found.amount>1)

           }
       }
   }

A: You are not returning this from all your methods, so you cannot chain all of them.

*

*sumPrice() only returns this if the item is found

*deleteProduct() does not return this

*sumTotal() neither

Also, your code was severely broken. Here is a list a fixes I made to make it work:

*

*Return this in all methods.

*use the same property name for amount and quantity

*use the same property name for item and productName

*use numbers instead of strings for amount and cost

*remove constructor, it was never called

*use let/const instead of var
I also changed the name of the Product class to ProductsStore since your class manages all your products and not only one, so I moved the products[] array inside the class and initialized it in the constructor.

class ProductsStore {
  constructor() {
    this.products = [];
  }

  buyProduct(product) {
    this.products.push(product);
    return this;
  }

  deleteProduct(str) {
    const found = this.products.find(el =>
      el.productName.toLowerCase() == str.toLowerCase())
    if (found) {
      if (found.amount > 1) {
        const foundIndex = this.products.findIndex(x => x.productName.toLowerCase() === str.toLowerCase());
        this.products[foundIndex].amount = found.amount - 1;
      } else {
        this.products.splice(this.products.findIndex(
          item => item.productName.toLowerCase() === str.toLowerCase()), 1)
      }
    }
    return this;
  }

  sumPrice(str, num) {
    const foundIndex = this.products.findIndex(x => (x.productName || '').toLowerCase() === str.toLowerCase());
    if (foundIndex >= 0) {
      this.products[foundIndex].cost = this.products[foundIndex].cost + num;
    }
    return this;
  }

  sumTotal() {
    this.total = 0;
    for (let obj of this.products) {
      this.total += obj.amount * obj.cost;
    }
    return this;
  }

  write() {
    let total = 0;
    for (let obj of this.products) {
      console.log('Item: ' + obj.productName + ' | Quantity:' + obj.amount + ' | Price:' + obj.cost);
      total += obj.amount * obj.cost;
    }
    console.log('$' + total);
  }
}

new ProductsStore()
  .buyProduct({ productName: 'jameson', amount: 1, cost: 0 })
  .buyProduct({ productName: 'bud light', amount: 3, cost: 0 })
  .buyProduct({ productName: 'corona', amount: 4, cost: 0 })
  .buyProduct({ productName: 'beer', amount: 1, cost: 0 })
  .sumPrice('tequila', 5.99)
  .deleteProduct('corona')
  .sumPrice('beer', 5.04)
  .sumTotal()
  .write();

A: You should return "this" from all of your methods.
Some methods aren't returning "this", like :
sumPrice():
if(foundIndex>=0)
   {
       products[foundIndex].cost = products[foundIndex].cost + num;
   }
return this;// this should be returned here.

deleteProduct() :
should return "this" at the end of the function.
sumTotal():
Instead of returning the total you should return this.
in the end, you should return a getter for the total.


text:
Q: Turn on viewstate for a single page I have a website created using VS2017 - it's based on Asp.Net 4.7.
All of my pages inherit from the main master page - it includes all the header stuff which I don't want to repeat over.
Most of my pages don't need viewstate but one page in particular does.
Ideally I'd like to enable viewstate as the exception, but I'm finding it pretty difficult to achieve.
Firstly, I disabled viewstate in web.config.
I then tried to re-enable viewstate for the page in both the web.config (using location) and on the aspx page itself. Both unsuccessful.
I've read a few articles that imply this behaviour could be down to the use of a master page, which seems to be confirms with the tests I've perfeormed.
If that is the case, It leaves my with two rather cumbersome options:

*

*disable viewstate on each page;

*remove the reliance on the master page and 'duplicate everything
within the page that requires viewstate.

However, I may have missed something, or misunderstood what I've already read.
So, before going down either of these routes, I'd appreciate it if anyone could advise as to whether there are any other solutions to this problem.
Thanks in advance.

A: I couldn't find a way to fix this issue that wasn't cumbersome.
However, I did come up with a solution. All of my web pages are stored in a database, so I appended a new column 'EnableViewState' and now enable it programatically on a page by page basis.


text:
Q: Toggle Menus using buttons in JS - But it shows both menus i want to toggle two menus offered by two buttons.the issue is when i click on button one, it shows the menu bound with button one but when i click the other, it shows both instead of hiding the first one and vice versa, on my login page. The menus are identified by the ids of; 'reqpwd' and 'signup' in html / JS. What is worng? also suggest improvement in code if possible. My JS code:
    <script>
  window.onload = function() {
  document.getElementById('reqpwd').style.display = 'none';
  document.getElementById('signup').style.display = 'none';
 };
function chk(elm) {
var signup_ = signup.id;
var reqpwd_ = reqpwd.id;
elm_ = elm.id;
if (elm_ == reqpwd_){
 hide(signup_);
 show(reqpwd_);
}
if (elm_== signup_){
 hide(reqpwd_);
show(signup_);
}
};

function show(abc) {
var menuBox  = document.getElementById(abc);
  if(menuBox.style.display == "none") { // if is menuBox displayed, hide it
    menuBox.style.display = "block";
} };

    function hide(abc){ // if is menuBox hidden, display it
var menuBox  = document.getElementById(abc);
if(menuBox.style.display == "block"){
    menuBox.style.display == "none";
    }
  };
</script>

A: Instead of menuBox.style.display == "none"; try using menuBox.style.visibility== "hidden";
Edit:
I have changed a few things in your code. Didn't make a whole lot of sense to me the way you're setting the styles on load (missing HTML), so I had to use IDs that made sense to me.
Edit:
Ok, my bad. I updated the code. I think the problem is on hide you're using double equals instead of single equals on menuBox.style.display == "none";. Thus the menu is never hiding.
https://codepen.io/juanferrer/pen/qmOmWa

A: Finally i have landed into something like this using the flag variable as a state indicator.. now the only requirement is to check toggle as well as disappear the relevant menu by the same button..i.e. if signup menu is already open, the signup or reset button should close it and vice versa.
window.onload = function() {
document.getElementById('regd').style.visibility = 'hidden'; //regisration msg
document.getElementById('rset').style.visibility = 'hidden'; //reset msg
document.getElementById('reqpwd').style.display = 'none';
document.getElementById('signup').style.display = 'none';
};
var flag = 0;

function chk(elm) {
var signup_ = signup.id;
var reqpwd_ = reqpwd.id;
elm_ = elm.id;

if (elm_ == reqpwd_ && flag === 0 || elm_ == reqpwd_ && flag == 2) {
    flag = 1;
    hide(signup_);
    show(reqpwd_);

}
if (elm_ == signup_ && flag === 0 || elm_ == signup_ && flag == 1) {
    flag = 2;
    show(signup_);
    hide(reqpwd_);

}
if (elm_ == reqpwd_ && flag == 1 || elm_ == signup_ && flag == 2) {
    hide(elm_);
    flag = 0;
}

};

function show(abc) {
var menuBox = document.getElementById(abc);
if (menuBox.style.display === "none") { // if is menuBox hidden, display it
    menuBox.style.display = "block";
}
};

function hide(abc) { // if is menuBox
var menuBox = document.getElementById(abc);
if (menuBox.style.display === "block") { //if displayed, hide it
    menuBox.style.display = "none";
}
};


text:
Q: Como criar uma view no mysql pegando dados de 3 tabelas e repetindo as colunas diferentes no resultado? Tenho as tabelas:
+----------Tabela-1--------+
id | nome   |  cnpj   | qtd1
1  | carlos | 0563233 |   4
+--------------------------+

+----------Tabela-2--------+
id | nome   |  cnpj   | qtd2
1  | carlos | 0563233 |   6
+--------------------------+

+----------Tabela-3--------+
id | nome   |  cnpj   | qtd3
1  | carlos | 0563233 |   8
+--------------------------+

Gostaria de fazer um comando sql para gerar uma única tabela colocando as colunas com nome diferentes uma do lado da outra, por exemplo:
+------------------------------------------------------------------+
 id  | nome   |    cnpj    | qtd1  | qtd2  |  qtd3
  1  | carlos | 0563233    |   4   |  6    |    8
+------------------------------------------------------------------+

Alguém pode me ajudar por favor?

A: Basta fazer o join entre as tabelas pelo campo que elas tem em comum
SELECT
  T1.id,
  T1.nome,
  T1.cnpj,
  T1.qtd1,
  T2.qtd2,
  T3.qtd3
FROM
  tabela1 T1
  INNER JOIN tabela2 T2 on (T1.id = T2.id)
  INNER JOIN tabela3 T3 on (T1.id = T3.id)

A: você pode usar também o LEFT JOIN
SELECT t1.id, t1.nome, t1.cnpj, t1.qtd1, t2.qtd2, t3.qtd3 FROM tabela1 t1 LEFT JOIN tabela2 t2 on (t1.id = t2.id) LEFT JOIN tabela3 t3 on (t1.id = t3.id)

ou ainda com o WHERE  para fazer a condição entre tabelas
SELECT t1.id, t1.nome, t1.cnpj, t1.qtd1, t2.qtd2, t3.qtd3 FROM tabela1 t1, tabela2 t2, tabela3 t3 WHERE t1.id = t2.id and t1.id = t3.id

A: Eu não usuario nem INNER JOIN nem WHERE, eu usaria de cara um LEFT JOIN (igual primeira resposta do @Flaviano Silva), porque, se as tabelas subsequentes não tiverem os dados da relação eu trago o valor da tabela1 e trabalho os outros valores com 0 ou qualquer de sua preferência.
SELECT
  T1.id,
  T1.nome,
  T1.cnpj,
  ifnull(T1.qtd1, 0) AS qtd1,
  ifnull(T2.qtd2, 0) AS qtd2,
  ifnull(T3.qtd3, 0) AS qtd3
FROM
  tabela1 T1
  LEFT JOIN tabela2 T2 on (T1.id = T2.id)
  LEFT JOIN tabela3 T3 on (T1.id = T3.id);

Exemplo: SQL Fiddle

A: Todas as outras respostas partem do princípio que nas 3 tabelas cada pessoa tem sempre o mesmo ID. Isso é verdadeiro no exemplo postado, mas não tenho tanta certeza de que seja assim no banco de dados real. Por isso, sugiro também um LEFT JOIN, mas pelo campo CNPJ em vez do ID.
Adaptando a query do Harry Potter:
SELECT
  T1.id,
  T1.nome,
  T1.cnpj,
  ifnull(T1.qtd1, 0) AS qtd1,
  ifnull(T2.qtd2, 0) AS qtd2,
  ifnull(T3.qtd3, 0) AS qtd3
FROM
  tabela1 T1
  LEFT JOIN tabela2 T2 on (T1.cnpj = T2.cnpj)
  LEFT JOIN tabela3 T3 on (T1.cnpj = T3.cnpj);

A: Considerando que colocou "MySQL" como tag da sua pergunta e falou em "gerar uma única tabela colocando as colunas com nome diferentes uma do lado da outra", você pode usar os joins naturais que casam as colunas de mesmo nome para você, fazendo o que pediu:
select *
from Tabela1
natural left join Tabela2
natural left join Tabela3


text:
Q: Is there a way to instantiate a class without calling __init__? Is there a way to circumvent the constructor __init__ of a class in python?
Example:
class A(object):
    def __init__(self):
        print "FAILURE"

    def Print(self):
        print "YEHAA"

Now I would like to create an instance of A. It could look like this, however this syntax is not correct.
a = A
a.Print()

EDIT:
An even more complex example:
Suppose I have an object C, which purpose it is to store one single parameter and do some computations with it. The parameter, however, is not passed as such but it is embedded in a huge parameter file. It could look something like this:
class C(object):
    def __init__(self, ParameterFile):
        self._Parameter = self._ExtractParamterFile(ParameterFile)
    def _ExtractParamterFile(self, ParameterFile):
        #does some complex magic to extract the right parameter
        return the_extracted_parameter

Now I would like to dump and load an instance of that object C. However, when I load this object, I only have the single variable self._Parameter and I cannot call the constructor, because it is expecting the parameter file.
    @staticmethod
    def Load(file):
        f = open(file, "rb")
        oldObject = pickle.load(f)
        f.close()

        #somehow create newObject without calling __init__
        newObject._Parameter = oldObject._Parameter
        return newObject

In other words, it is not possible to create an instance without passing the parameter file. In my "real" case, however, it is not a parameter file but some huge junk of data I certainly not want to carry around in memory or even store it to disc.
And since I want to return an instance of C from the method Load I do somehow have to call the constructor.
OLD EDIT:
A more complex example, which explains why I am asking the question:
class B(object):
    def __init__(self, name, data):
        self._Name = name
        #do something with data, but do NOT save data in a variable

    @staticmethod
    def Load(self, file, newName):
        f = open(file, "rb")
        s = pickle.load(f)
        f.close()

        newS = B(???)
        newS._Name = newName
        return newS

As you can see, since data is not stored in a class variable I cannot pass it to __init__. Of course I could simply store it, but what if the data is a huge object, which I do not want to carry around in memory all the time or even save it to disc?

A: I was reading the Python cookbook and there's a section talking about this: the example is given using __new__ to bypass __init__()

>>> class A:
    def __init__(self,a):
        self.a = a

>>> test = A('a')
>>> test.a
'a'
>>> test_noinit = A.__new__(A)
>>> test_noinit.a
Traceback (most recent call last):
  File "", line 1, in
    test_noinit.a
AttributeError: 'A' object has no attribute 'a'
>>>

However I think this only works in Python3. Below is running under 2.7

>>> class A:
    def __init__(self,a):
        self.a = a

>>> test = A.__new__(A)

Traceback (most recent call last):
  File "", line 1, in
    test = A.__new__(A)
AttributeError: class A has no attribute '__new__'
>>>

A: You can circumvent __init__ by calling __new__ directly. Then you can create a object of the given type and call an alternative method for __init__. This is something that pickle would do.
However, first I'd like to stress very much that it is something that you shouldn't do and whatever you're trying to achieve, there are better ways to do it, some of which have been mentioned in the other answers. In particular, it's a bad idea to skip calling __init__.
When objects are created, more or less this happens:
a = A.__new__(A, *args, **kwargs)
a.__init__(*args, **kwargs)

You could skip the second step.
Here's why you shouldn't do this: The purpose of __init__ is to initialize the object, fill in all the fields and ensure that the __init__ methods of the parent classes are also called. With pickle it is an exception because it tries to store all the data associated with the object (including any fields/instance variables that are set for the object), and so anything that was set by __init__ the previous time would be restored by pickle, there's no need to call it again.
If you skip __init__ and use an alternative initializer, you'd have a sort of a code duplication - there would be two places where the instance variables are filled in, and it's easy to miss one of them in one of the initializers or accidentally make the two fill the fields act differently. This gives the possibility of subtle bugs that aren't that trivial to trace (you'd have to know which initializer was called), and the code will be more difficult to maintain. Not to mention that you'd be in an even bigger mess if you're using inheritance - the problems will go up the inheritance chain, because you'd have to use this alternative initializer everywhere up the chain.
Also by doing so you'd be more or less overriding Python's instance creation and making your own. Python already does that for you pretty well, no need to go reinventing it and it will confuse people using your code.
Here's what to best do instead: Use a single __init__ method that is to be called for all possible instantiations of the class that initializes all instance variables properly. For different modes of initialization use either of the two approaches:

*

*Support different signatures for __init__ that handle your cases by using optional arguments.

*Create several class methods that serve as alternative constructors. Make sure they all create instances of the class in the normal way (i.e. calling __init__), as shown by Roman Bodnarchuk, while performing additional work or whatever. It's best if they pass all the data to the class (and __init__ handles it), but if that's impossible or inconvenient, you can set some instance variables after the instance was created and __init__ is done initializing.

If __init__ has an optional step (e.g. like processing that data argument, although you'd have to be more specific), you can either make it an optional argument or make a normal method that does the processing... or both.

A: Use classmethod decorator for your Load method:
class B(object):
    def __init__(self, name, data):
        self._Name = name
        #store data

    @classmethod
    def Load(cls, file, newName):
        f = open(file, "rb")
        s = pickle.load(f)
        f.close()

        return cls(newName, s)

So you can do:
loaded_obj = B.Load('filename.txt', 'foo')

Edit:
Anyway, if you still want to omit __init__ method, try __new__:
>>> class A(object):
...     def __init__(self):
...             print '__init__'
...
>>> A()
__init__
<__main__.A object at 0x800f1f710>
>>> a = A.__new__(A)
>>> a
<__main__.A object at 0x800f1fd50>

A: As I said in my comment you could change your __init__ method so that it allows creation without giving any values to its parameters:
def __init__(self, p0, p1, p2):
   # some logic

would become:
def __init__(self, p0=None, p1=None, p2=None):
   if p0 and p1 and p2:
       # some logic

or:
def __init__(self, p0=None, p1=None, p2=None, init=True):
    if init:
        # some logic

A: Taking your question literally I would use meta classes :
class MetaSkipInit(type):
    def __call__(cls):
        return cls.__new__(cls)

class B(object):
    __metaclass__ = MetaSkipInit

    def __init__(self):
        print "FAILURE"

    def Print(self):
        print "YEHAA"

b = B()
b.Print()

This can be useful e.g. for copying constructors without polluting the parameter list.
But to do this properly would be more work and care than my proposed hack.

A: Not really.  The purpose of __init__ is to instantiate an object, and by default it really doesn't do anything.  If the __init__ method is not doing what you want, and it's not your own code to change, you can choose to switch it out though.  For example, taking your class A, we could do the following to avoid calling that __init__ method:
def emptyinit(self):
    pass
A.__init__ = emptyinit
a = A()
a.Print()

This will dynamically switch out which __init__ method from the class, replacing it with an empty call.  Note that this is probably NOT a good thing to do, as it does not call the super class's __init__ method.
You could also subclass it to create your own class that does everything the same, except overriding the __init__ method to do what you want it to (perhaps nothing).
Perhaps, however, you simply wish to call the method from the class without instantiating an object.  If that is the case, you should look into the @classmethod and @staticmethod decorators.  They allow for just that type of behavior.
In your code you have put the @staticmethod decorator, which does not take a self argument.  Perhaps what may be better for the purpose would a @classmethod, which might look more like this:
@classmethod
def Load(cls, file, newName):
    # Get the data
    data = getdata()
    # Create an instance of B with the data
    return cls.B(newName, data)

UPDATE: Rosh's Excellent answer pointed out that you CAN avoid calling __init__ by implementing __new__, which I was actually unaware of (although it makes perfect sense).  Thanks Rosh!


text:
Q: Android custom seekbar not drawing in < 3.0 I've created a custom seekbar for an app. It works fine on all newer devices, but it doesn't appear in the UI when I try it on an older device, with android v 2.3 to be specific. It still works - when I touch the blank space where the seekbar should draw, I see the values changing in a linked TextView, but it just doesn't draw. I'm probably using a method which isnt supported in 2.3, but i cant figure out which. Does anybody have an idea? Here is the code:
    public class CustomSeekBar extends SeekBar {

    private Paint selected, unselected;
    private int halfSize = 15;
    private RectF position;
    private final Bitmap thumbImage = BitmapFactory.decodeResource(getResources(), R.drawable.img_fragment_settings_seekbar_thumb);

    public CustomSeekBar(Context context) {
        super(context);
        selected = new Paint(Paint.ANTI_ALIAS_FLAG);
        selected.setColor(Color.argb(0xFF, 0x29, 0x80, 0xb9));
        selected.setStyle(Style.FILL);
        unselected = new Paint(Paint.ANTI_ALIAS_FLAG);
        unselected.setColor(getContext().getResources().getColor(R.color.orange));
        selected.setStyle(Style.FILL);
        position = new RectF();
        this.setMax(12);
    }

    public CustomSeekBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        selected = new Paint(Paint.ANTI_ALIAS_FLAG);
        selected.setColor(Color.argb(0xFF, 0x29, 0x80, 0xb9));
        selected.setStyle(Style.FILL);
        unselected = new Paint(Paint.ANTI_ALIAS_FLAG);
        unselected.setColor(getContext().getResources().getColor(R.color.orange));
        selected.setStyle(Style.FILL);
        position = new RectF();
        this.setMax(12);
    }

    public CustomSeekBar(Context context, AttributeSet attrs) {
        super(context, attrs);
        selected = new Paint(Paint.ANTI_ALIAS_FLAG);
        selected.setColor(Color.argb(0xFF, 0x29, 0x80, 0xb9));
        selected.setStyle(Style.FILL);
        unselected = new Paint(Paint.ANTI_ALIAS_FLAG);
        unselected.setColor(getContext().getResources().getColor(R.color.orange));
        selected.setStyle(Style.FILL);
        position = new RectF();
        this.setMax(12);
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {
        float halfHeight = (canvas.getHeight())*.5f;
        position.set(
            0,
            halfHeight-2,
            getWidth(),
            halfHeight+2);

        canvas.drawRect(position, selected);

        if(getProgress() !=0 ){
            position.right = getWidth() * getProgress()/12;
            canvas.drawRect(position, unselected);
        }

        canvas.drawBitmap(thumbImage, (getWidth()- thumbImage.getWidth()) * getProgress()/12  , halfHeight - thumbImage.getHeight()/2, null);

        //super.onDraw(canvas);
        // this is intentional, I don't want to call super
    }

    public int getDotsSize() {
        return halfSize*2;
    }

    public void setDotsSize(int dotsSize) {
        this.halfSize = dotsSize/2;
    }

}
Then I simply insert it in XML:
                    <com.xxx.custom_views.CustomSeekBar
                    android:id="@+id/sb_set_interval"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginBottom="@dimen/fragment_settings_interactive_elements_bottom_margin"
                    android:layout_weight="1"
                    android:max="12"
                    android:progressDrawable="@drawable/seekbar_progerss"
                    android:thumb="@drawable/img_fragment_settings_seekbar_thumb" />

Thanks.


text:
Q: How does one fix a "Variable not in scope" error? Can you please help me understand the error and how to fix it?
comp = \x -> f(g(h(x)))

The error is

"Variable not in scope: f :: t0 -> t2"

for f, g and h, which they are just some functions not otherwise specified.

A: I suspect you're trying to build a function that composes 3 functions, much like how . composes 2 functions. To do that, you can't just make up names in the body and expect GHC to know what you meant by them. Instead, you need to bring them into scope somehow, like this: comp f g h = \x -> f(g(h(x)))


text:
Q: Filter Dataframe based on condition coming in request I have one dataframe that I need to filter based on condition receiving in request from UI.
request example:
{
"table": "abc",
"condition": "A=98 and C=73 and D='rendom_char'"
}

dataframe sample:

A
B
C
D

0
85
39
54
td

1
39
51
23
abc

2
98
17
73
def

3
98
52
73
def

4
85
52
21
rst

5
61
89
31
xvz

so suppose if I get condition from UI that "condition": "A=98 and C=73 and D='def'" or "condition": "A=98 and C=73"
output should be like :

A
B
C
D

2
98
17
73
def

3
98
52
73
def

The issue I'm facing is how to convert that string condition getting from UI into python form so that I can apply filter on datafram.

A: Use DataFrame.query with replace = to double =:
d = {"condition": "A=98 and C=73 and D='def'"}
print (df.query(d['condition'].replace('=','==')))
    A   B   C    D
2  98  17  73  def
3  98  52  73  def

d = {"condition": "A=85 and C=21"}
print (df.query(d['condition'].replace('=','==')))

    A   B   C    D
4  85  52  21  rst

A: Alternatively, you can query pandas dataframe in SQL fashion with pandasql:
import pandasql as psql
...

req = {"table": "abc", "condition": "A=98 and C=73 and D='def'"}
q = f"select * from df where {req['condition']}"

print(psql.sqldf(q, locals()))

    A   B   C    D
0  98  17  73  def
1  98  52  73  def


text:
Q: How can i implement cookies in wordpress? I've got a few lists filled with forms like this on my website:
    <Input type="checkbox"> Option 1
    <Input type="checkbox"> Option 2

And so on
How could i implement cookies with these? So that visitors to my website get their setting saved.


text:
Q: Exporting image from GEE to Google Cloud Bucket in PNG/JPEG format? The below lines of code shows the export of the image to the cloud. I am unable to convert my file to JPEG/PNG. I want my image to be saved in PNG/JPEG in the cloud.
    Export.image.toCloudStorage({
    image:  rgb.select(0,1,2),
    description: 'cog',
    bucket: 'sample_bucket',
    scale: 30,
    region:ft_bnd,
    fileFormat: 'png',
    formatOptions: {
    cloudOptimized: true
    },
    dimensions:256*256
    });

A: JPG or PNG are not supported for image export.

You can export images from Earth Engine in GeoTIFF or TFRecord format.

As per the GEE Exporting Data documentation.

A: Your question isn't clear because you haven't specified what's not working, but you can't specify a scale + region and dimensions.  Those options are mutually exclusive.


text:
Q: Why underfull message in Texmaker in \[...\] equations Why I am getting
   underfull hbox badness 10000 in paragraph at lines

Message even when  I am not using \\. After reading many questions on the same message, I eliminated all \\ that I used after line spacing and defined
   \usepackage{parskip}
    \setlength\parskip{\baselineskip}
    \parindent=0pt

before
            \begin{document}
and used a line gap whenever I wanted to skip base line.
Now I have two questions-

*

*I should use \\ whenever I want to get to next line within a proof and do not want to skip a line, or is there something else for it?

*After eliminating all \\ except at line break, I still see some messages where I am using \[\] inline equations. How can I eliminate them.

Below I am attaching a pic where it shows the badness message when I use inline. Another pic of preamble is attached too.
Error at Inline (line 90)-

Preamble-

Here is the code
\documentclass[12pt]{report}
\usepackage{epsfig,epic,eepic,units}
\usepackage{url}
\usepackage{longtable}
\usepackage{mathrsfs}
\usepackage{multirow}
\usepackage{bigstrut}
\usepackage{amssymb}
\usepackage{amsmath}
\usepackage{centernot}
\usepackage{graphicx}
\usepackage{floatrow}
\usepackage{braket}
\usepackage{parskip}
\setlength\parskip{\baselineskip}
\parindent=0pt
\begin{document}
In this section we will describe the structure of group algebras over finite cyclic groups and will state the Main result which describe the structure of group algebras over any finite abelian group.
\vspace{1mm}\\
Let \(G\) be the cycle group of order \(n\), i.e. \(G=\langle a:a^n=1 \rangle\), and K be a field such that char\((K)\) doesn't divide \(|G|\). \\
Then considering the map \(\phi: K[x]\to KG\) given by:
\[f(x)\to f(a)\]
It is clear that \(\phi\) is an epimorphism and thus
\[\frac{K[x]}{\text{ker}(\phi)}\cong KG\] where Ker\((\phi)=\{f\in K[x]: f(a)=0\}\). Now, as \(K[x]\) is a P.I.D and \(x^n-1\in \text{Ker}(\phi)\), it easily follows that \(\text{Ker}(\phi)=\langle x^n-1 \rangle\) and thus \[KG \cong \frac{K[x]}{\langle x^n-1 \rangle}\]
Now decomposing \(x^n-1\) as product of irreducible factor polynomials in \(K[x]\), say, \(x^n-1=f_1f_2 \dots f_t\), and as \((x^n-1,nx^{n-1})=1 \) implies \(x^n-1\) is separable and thus for every \(i\neq j, f_i \neq f_j\). So now we can use Chinese Remainder Theorem, and express
$KG\cong \frac{K[x]}{\langle f_1 \rangle} \oplus \frac{K[x]}{\langle f_2 \rangle} \dots \oplus \frac{K[x]}{\langle f_t \rangle}$
Now \(\frac{K[x]}{\langle f_i \rangle} \cong K(\zeta_i)\) where \(\zeta_i\) is a root of \(f_i\) for \(1\le i \le t\). Therefore,\\
\[KG \cong K(\zeta_1) \oplus \dots \oplus K(\zeta_t)\]
as \(\zeta_i's\) are roots of \(x^n-1\)  thus \(KG\) is isomorphic to a direct sum of \textit{cyclotomic extensions} of \(K\)\\
\textbf{Example-} Let \(G=C_5\) and \(K=\mathbb{Q}\). In this case
\[x^5-1=(x-1)(x^4+x^3+x^2+x+1)\]
and thus
\[\mathbb{Q}G\cong \mathbb{Q}\oplus \mathbb{Q}(\zeta)\]
where \(\zeta\) is a root of \(x^4+x^3+x^2+x+1\).\\
Notice that changing \(K=\mathbb{Q}\) to \(K=\mathbb{R}\) would similarly suggest that the group ring  \(\mathbb{R}C_5 \cong \mathbb{R}\oplus \mathbb{R}(\zeta)\) as \(x^4+x^3+x^2+x+1\) is irreducible over \(\mathbb{R}\) too.\\
Similarly considering \(x^4-1=(x+1)(x-1)(x^2+1)\) , we see that \(\mathbb{Q}C_4 \cong \mathbb{Q}\oplus \mathbb{Q}\oplus \mathbb{Q}(i)\).\\
\end{document}

A: You still had some double back-slashed where they should not be. In front of display math, for example. And some in-line math had to be broken over the line which could cause such errors.
You should not use double back-slashes at all. If you want to have a new paragraph, do a blank line (no matter, if you use parskip or parindent then). If you want to generate more breaks as you do here, you may put such stuff in align environments.
The nicest would be to stick to one paragraph style. And if there is not enough reason for a blank line, then there is maybe no reason for a new paragraph as well. Right now, you break after almost each sentence... why?
For stuff as the math in your example, you should have a look on theorems and examples as defined by amsthm.
Here is a quick (not complete) code review of yours:
% arara: pdflatex

\documentclass[12pt]{report}
\usepackage{amssymb}
\usepackage{mathtools}
\usepackage[parfill]{parskip}

\begin{document}
    In this section we will describe the structure of group algebras over finite cyclic groups and will state the Main result which describe the structure of group algebras over any finite abelian group.

    Let \(G\) be the cycle group of order \(n\), i.e. \(G=\langle a:a^n=1 \rangle\), and K be a field such that char\((K)\) doesn't divide \(|G|\).\\
    Then considering the map \(\phi: K[x]\to KG\) given by:
    \[f(x)\to f(a)\]

    It is clear that \(\phi\) is an epimorphism and thus
        \begin{align*}
            \frac{K[x]}{\text{ker}(\phi)}&\cong KG\\
            \shortintertext{where}
            (\phi)&=\{f\in K[x]: f(a)=0\}.\\
            \intertext{Now, as \(K[x]\) is a P.I.D and \(x^n-1\in \text{Ker}(\phi)\), it easily follows that}
            \text{Ker}(\phi)&=\langle x^n-1 \rangle\\
            \shortintertext{and thus}
            KG &\cong \frac{K[x]}{\langle x^n-1 \rangle}.
        \end{align*}
    Now decomposing \(x^n-1\) as product of irreducible factor polynomials in \(K[x]\), say, \(x^n-1=f_1f_2 \dots f_t\), and as \((x^n-1,nx^{n-1})=1 \) implies \(x^n-1\) is separable and thus for every \(i\neq j, f_i \neq f_j\). So now we can use Chinese Remainder Theorem, and express
    \[KG\cong \frac{K[x]}{\langle f_1 \rangle} \oplus \frac{K[x]}{\langle f_2 \rangle} \dots \oplus \frac{K[x]}{\langle f_t \rangle}.\]
    Now \(\frac{K[x]}{\langle f_i \rangle} \cong K(\zeta_i)\) where \(\zeta_i\) is a root of \(f_i\) for \(1\le i \le t\). Therefore,
    \[KG \cong K(\zeta_1) \oplus \dots \oplus K(\zeta_t)\]
    as \(\zeta_i's\) are roots of \(x^n-1\)  thus \(KG\) is isomorphic to a direct sum of \textit{cyclotomic extensions} of \(K\)

    \textbf{Example-} Let \(G=C_5\) and \(K=\mathbb{Q}\). In this case
    \begin{align*}
        x^5-1&=(x-1)(x^4+x^3+x^2+x+1\\
        \shortintertext{and thus}
        \mathbb{Q}G&\cong \mathbb{Q}\oplus \mathbb{Q}(\zeta)
    \end{align*}
    where \(\zeta\) is a root of \(x^4+x^3+x^2+x+1\).

    Notice that changing \(K=\mathbb{Q}\) to \(K=\mathbb{R}\) would similarly suggest that the group ring  \(\mathbb{R}C_5 \cong \mathbb{R}\oplus \mathbb{R}(\zeta)\) as \(x^4+x^3+x^2+x+1\) is irreducible over $\mathbb{R}$ too.
    Similarly considering \(x^4-1=(x+1)(x-1)(x^2+1)\) , we see that \[\mathbb{Q}C_4 \cong \mathbb{Q}\oplus \mathbb{Q}\oplus \mathbb{Q}(i).\]
\end{document}

A: In addition to replacing all remaining \\ (double backslash) instances with a simple blank line, I also recommend you

*

*replace all instances of : (colon) in math mode with \colon

*make use of pre-defined "math operators" such as \ker

*replace one or the other inline-math expression with a display-math construct. Most importantly, you should convert
\(KG\cong \frac{K[x]}{\langle f_1 \rangle} \oplus
\frac{K[x]}{\langle f_2 \rangle} \dots \oplus
\frac{K[x]}{\langle f_t \rangle}\)

to a display-math statement

*don't leave spaces between \) (closing inline math) and subsequent punctuation marks (such as ,, and .).

\documentclass[12pt]{report}
%% I've omitted all unneeded packages from this preamble
\usepackage{amssymb,amsmath}
\DeclareMathOperator{\chr}{char}
\usepackage{parskip}
\setlength\parskip{\baselineskip}

\begin{document}

In this section we will describe the structure of group algebras over finite cyclic
groups and state the main result, which describes the structure of group algebras
over any finite abelian group.

Let \(G\) be the cycle group of order \(n\), i.e.\ \(G=\langle a\colon a^n=1 \rangle\),
and \(K\) be a field such that \(\chr(K)\) doesn't divide \(|G|\).

Then consider the map \(\phi\colon K[x]\to KG\) given by
\[
f(x)\to f(a).
\]
It is clear that \(\phi\) is an epimorphism and thus
\[
\frac{K[x]}{\ker(\phi)}\cong KG,
\]
where \(\ker(\phi)=\{f\in K[x]\colon f(a)=0\}\). Now, as \(K[x]\) is a P.I.D
and \(x^n-1\in \ker(\phi)\), it easily follows that
\(\ker(\phi)=\langle x^n-1 \rangle\) and thus
\[
KG \cong \frac{K[x]}{\langle x^n-1 \rangle}\,.
\]

Now decomposing \(x^n-1\) as product of irreducible factor polynomials in \(K[x]\),
say, \(x^n-1=f_1f_2 \dotsm f_t\), and as \((x^n-1,nx^{n-1})=1 \) implies
\(x^n-1\) is separable and thus for every \(i\neq j, f_i \neq f_j\). So
now we can use Chinese Remainder Theorem and express
\[
KG\cong \frac{K[x]}{\langle f_1 \rangle} \oplus \frac{K[x]}{\langle f_2 \rangle}
\dots \oplus \frac{K[x]}{\langle f_t \rangle}\,.
\]

Now \(\frac{K[x]}{\langle f_i \rangle} \cong K(\zeta_i)\), where
\(\zeta_i\) is a root of \(f_i\) for \(1\le i \le t\). Therefore,
\[
KG \cong K(\zeta_1) \oplus \dots \oplus K(\zeta_t)\,,
\]
as the \(\zeta_i\)'s are roots of \(x^n-1\)  thus \(KG\) is isomorphic
to a direct sum of \textit{cyclotomic extensions} of \(K\).

\textbf{Example--}Let \(G=C_5\) and \(K=\mathbb{Q}\). In this case
\[
x^5-1=(x-1)(x^4+x^3+x^2+x+1)
\]
and thus
\[
\mathbb{Q}G\cong \mathbb{Q}\oplus \mathbb{Q}(\zeta),
\]
where \(\zeta\) is a root of \(x^4+x^3+x^2+x+1\).

Notice that changing \(K=\mathbb{Q}\) to \(K=\mathbb{R}\) would
similarly suggest that the group ring  \(\mathbb{R}C_5 \cong \mathbb{R}
\oplus \mathbb{R}(\zeta)\), as \(x^4+x^3+x^2+x+1\) is irreducible
over \(\mathbb{R}\) too.

Similarly considering \(x^4-1=(x+1)(x-1)(x^2+1)\), we see that
\[
\mathbb{Q}C_4 \cong \mathbb{Q}\oplus \mathbb{Q}\oplus \mathbb{Q}(i).
\]
\end{document}


text:
Q: Evaluating Functions on Zero Sets (of other functions) I have a highly non-trivial function, call it $f(x,y)$, in which I want to look at its zero set in the $(x,y)$ plane, and plot/evaluate a different function $g$ precisely along this zero set.  I have a nice way of doing this when the zero set of $f$ can be parameterized by $x$, i.e. $y(x)$, but in general, this zero set will not be nicely parameterized by $x$.
Is there a nice way to parameterize zero sets by some parameter $t$, like length along the curve, and then save values and plot $g(x(t),y(t))$?  Perhaps it might be helpful to take an easy example like
f[x_,y_]=x^2+y^2-4
g[x_,y_]=x^2-3*y^2
Unlike the case of the circle above, my zero set certainly does not have a nice, obvious parameterization, so instead perhaps someone can help me form a numerical recipe using the simple example above.
**If it helps, I can upload the case I actually have in mind, but it's rather messy and requires a lot of pre-amble.
Thanks in advance!

A: Plot3D[g[x, y], {x, -5, 5}, {y, -5, 5}, MeshFunctions -> {f[#, #2] &},
  Mesh -> {{{0, Directive[Thick, Red]}}}, BoxRatios->1]

Plot3D[g[x, y], {x, -5, 5}, {y, -5, 5}, PlotStyle -> None,
 BoundaryStyle -> None, MeshFunctions -> {f[#, #2] &},
 Mesh -> {{{0, Directive[Thick, Red]}}}, BoxRatios->1]

cp = ContourPlot[f[x, y] == 0, {x, -5, 5}, {y, -5, 5},  ContourStyle -> {Thick, Red}]

Graphics3D[cp[[1]] /. GraphicsComplex[coords_, rest___] :>
                        GraphicsComplex[{##, g[##]} & @@@ coords, rest],
  BoxRatios -> 1,  Axes -> True]

A: Can use NDSolve to parametrize numerically.
f[x_, y_] = x^2 + y^2 - 4;
g[x_, y_] = x^2 - 3*y^2;
pt = {2, 0};

xyvals = NDSolveValue[
  Flatten[{D[f[x[t], y[t]], t] == 0, x'[t]^2 + y'[t]^2 == 1,
    Thread[{x[0], y[0]} == pt]}], {x[t], y[t]}, {t, 0, 11}];

(If you want to see the better part of a circle, do ParametricPlot[xyvals, {t, 0, 11}, AspectRatio -> 1])
Now to plot g on this set, do:
Plot[g @@ xyvals, {t, 0, 11}]


text:
Q: Logging into a specific file in Tizen?
Before asking this question I searched a lot about Logging (the terminal Debug Log) into a file for Tizen Application. I figured out some other ways to implement using several alternatives a bit complex pathway for this problem. But I want something straightforward, simple and builtin for Tizen Applications.
So here is what I want -

*

*I will run a Tizen application written in C/C++. It will generate response logs on the terminal based on the several queries I ask to the app.

*I want to save those logs into a specific file like file_name.log .

*That file_name.log will be saved somewhere within my PC. Developer can change the location as my own.

Is there any command or an existing system for Tizen apps ?
Thank you in advance.

A: Read https://developer.tizen.org/development/guides/native-application/error-handling/system-logs about Tizen's built-in logging system.
As stated in the page, the logs can be also retrieved from the command line using sdb shell dlogutil [options...] [TAG], or simply sdb dlog [options...] [TAG]. So if you want to save the output as a file, simply do sdb dlog [-d] MY_APP > file_name.log. If this is not what you are searching for, please be more specific in your question.


text:
Q: Python: creating a group column in a Pandas dataframe based on an integer range of values For each range [0, 150] in the diff column, I want to create a group column that increases by 1 each time the range resets. When diff is negative, the range resets.
import pandas as pd
df = pd.DataFrame({'year': [2016, 2016, 2016, 2016, 2016, 2016, 2016],
                   'month' : [1, 1, 2, 3, 3, 3, 3],
                   'day': [23, 25, 1, 1, 7, 20, 30]})
df = pd.to_datetime(df)
df = pd.concat([df, pd.Series(data=[15, 35, 80, 5, 20, 45, 90])], axis=1)
df.columns = ['date', 'percentworn']
col_shift = ['percentworn']
df_shift = df.shift(1).loc[:, col_shift]
df_combined = df.join(df_shift, how='inner', rsuffix='_2')
df_combined.fillna(value=0,inplace=True)
df_combined['diff'] = df_combined['percentworn'] - df_combined['percentworn_2']

The grp columns should have 0, 0, 0, 1, 1, 1, 1. The code I tried was
def grping(df):
    df_ = df.copy(deep=True)
    i = 0
    if df_['diff'] >= 0:
        df_['grp'] = i
    else:
        i += 1
        df_['grp'] = i
    return df_
df_combined.apply(grping,axis=1)

I need to i += 1 persist after incrementing. How can I achieve this? Or is there a better way get the desired results?

A: IIUC you can test whether the 'diff' column is negative which produces a boolean array, then cast this to int and the call cumsum:
In [313]:
df_combined['group'] = (df_combined['diff'] < 0).astype(int).cumsum()
df_combined

Out[313]:
        date  percentworn  percentworn_2  diff  group
0 2016-01-23           15            0.0  15.0      0
1 2016-01-25           35           15.0  20.0      0
2 2016-02-01           80           35.0  45.0      0
3 2016-03-01            5           80.0 -75.0      1
4 2016-03-07           20            5.0  15.0      1
5 2016-03-20           45           20.0  25.0      1
6 2016-03-30           90           45.0  45.0      1

breaking the above down:
In [314]:
df_combined['diff'] < 0

Out[314]:
0    False
1    False
2    False
3     True
4    False
5    False
6    False
Name: diff, dtype: bool

In [316]:
(df_combined['diff'] < 0).astype(int)

Out[316]:
0    0
1    0
2    0
3    1
4    0
5    0
6    0
Name: diff, dtype: int32


text:
Q: how to get value of a #t=querystring in asp.net? I use Request.QueryString["var"] to pull the value of http://test.com/test.aspx?var=test into a string
the same thing doesn't work for test.aspx#var=test
how can I get it from that version of a querystring?

A: The Fragment Identifier (#) is client-side only, you can't get that from server side code.

A: #var=test is not q query string. That's part of the "URL Fragment". In a URL to a web page, it indicates which <a> tag to go to.

A: I don't think the part of the url after the # is passed to the web server directly. To access it you would need to do some javascript processing to pass it on.


text:
Q: Angular 2 digest fails at executing a function, or finding a change at an object's property I have absolutely no idea on what's going on; my two theories are already in the title. Thing is, this should be working, but somehow one of the core parts of Angular, the digest cycle, is failing hard.
What I want to do, and how I did it
A comments section that is instantiated in a parent view, when you click a button. Then the comments appear, and they behave similarly to Reddit's: you can upvote or downvote them. Pretty much the same! So I just added some  with the arrows, and the rating of the comments between them:

    <ion-row>
    <button class="nocolor" (click)="rateComment(comment, true)">
    <ion-icon large name="arrow-up" [color]="isRated(comment.rated, 1)"></ion-icon>
    </button>
    </ion-row>
     <ion-row>
     {{comment.rating}}
    </ion-row>
     <ion-row>
       <button class="nocolor" (click)="rateComment(comment, false)">
    <ion-icon large name="arrow-down" [color]="isRated(comment.rated, 2)"></ion-icon>
       </button>
    </ion-row>

As you can see, when I click in the icons, they execute the "rateComment" function, which is:
   rateComment(comment, liked){
     if (liked==true){
       comment.rating++;
       comment.rated=1;
       //register like
     }else{
       comment.rating--;
       comment.rated=-1;
       //register unlike
     }
   }

Ok, pretty straightforward. Now that the object's property is properly changed, we should somehow change the icon's color from the default gray-like color, to something more like amber. This works perfectly when the data is first represented: you see the voted comments with the proper arrow, proper colored. Great. But if you click in the arrow, the color doesn't change.
The function that chooses the color of the icon, which works good at start but fails when updating the view, is this one:
   isRated(value, component){
     if(component == 1 && value == 1){
       return 'amber';
     }else if(component == 2 && value == -1){
       return 'amber';
     }
   }

Basically, as you can see, the upper arrow uses 1 as component value and the down arrow uses 2, just to reuse the function.
So, what's the problem?
As I already said, the problem I'm having here, is that either the "isRated" function is not being executed in the digest's cycle, or that the change os the ion-icon color is not working, or the property change of the object does not trigger a view update. I just don't know what's going on; but something is failing hard and I can't find any error in my code.
EDIT: the "isRated" function executed, BUT with the old value, like if the new one doens't get registered in the object. This is odd, since it actually gets changed in the "rateComment" function.


text:
Q: Firebase Admin SDK Security for Cloud Functions I use Google Cloud Functions in my Flutter app with the Admin SDK. Therefore, I initialised the SDK without parameters like this:
import * as admin from 'firebase-admin';
admin.initializeApp();

I am wondering if I need to consider anything else for the setup to be secure. My understanding is that because the SDK is deployed in a Google environment, I don't need to create any security keys.
Is this correct, or could someone still access the database with the current setup?
I am sorry, my knowledge here is very basic. I am also not sure if the information I gave is sufficient for you to answer the question. Please let me know if there is anything else I need to consider.
Edit:
I followed this article: fireship.io/lessons/flutter-push-notifications-fcm-guide (s. bottom of page - Step 2: Send Messages with NodeJS (Backend) )

A: Since all the code that sends notifications is entirely on the backend, which is entirely under your control, there's nothing you need to do in your app other than ensure that the frontend is sending the correct data.


text:
Q: escape delimiter between date fileds while using sed I'm trying to remove delimiter | with in the quotes using sed on text which contains dates, nulls, strings with pipe delimiter. I used following sed its working fine but its removing delimiter between dates. Any help will be appreciated.
sed -E 's/(^|[^"|])\|($|[^"|])/\1 \2/g' <file>

Input:
"Southern|Palms"|"AA|None"|"4"|"Ken|Coast"|1/11/2019 00:00:00|30/4/2020 00:00:00|"TH"|

Returns:
"Southern Palms"|"AA None"|"4"|"Ken Coast"|1/11/2019 00:00:00 30/4/2020 00:00:00|"TH"|
Expected Output:
"Southern Palms"|"AA None"|"4"|"Ken Coast"|1/11/2019 00:00:00|30/4/2020 00:00:00|"TH"|

A: With GNU awk for FPAT:
$ awk -v FPAT='[^|]*|"[^"]+"' -v OFS='|' '{for (i=1;i<=NF;i++) gsub(/\|+/," ",$i)} 1' file
"Southern Palms"|"AA None"|"4"|"Ken Coast"|1/11/2019 00:00:00|30/4/2020 00:00:00|"TH"|

See What's the most robust way to efficiently parse CSV using awk?

A: How about:
sed -E 's/(\w+)\|(\w+)/\1 \2/g' testfile.txt

\w+\|\w+ matches pipe symbols between two words like this <word1>|<word2> and replaces it with the two words separated by a space like this <word1> <word2>
If you want to match the quotes use:
sed -E 's/("\w+)\|(\w+")/\1 \2/g' testfile.txt

That matches "<word1>|<word2>" and replaces it with "<word1> <word2>"


text:
Q: SocketServer keeps accepting same connection. Creating multiple threads for that same connection I'm creating a simple http server. I have a master thread that waits in a loop for a connection to be accepted. Once a connection is accepted, I create a new worker thread to handle the connection, passing the accepted socket as an argument. Once a connection is accepted, a new thread is created for it, however the master thread will loop again, create another socket with the same connection and create another duplicated thread.
Master thread waiting for connections.
public void run(){
    while(Tester.serverStatus != "quit"){
    try {
        Socket clientSocket = serverSocket.accept();
        new Thread(new Worker(clientSocket)).start();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
    try {
        this.stop();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return;
}

public void stop() throws IOException{
    serverSocket.close();
    return;

}

Worker thread pseudocode
            public void run(){
InputStream input = clientSocket.getInputStream();
//read from stream, validate request and setup the response in a byte array
input.close();

DataOutputStream output = new DataOutputStream(clientSocket.getOutputStream());
output.write(responseByteArray);
output.flush();
output.close();

clientSocket.close();
return;

}

Any ideas as to why the accept() method isn't being blocked after the first connection is accepted? It just keeps on creating duplicate Worker threads with the same Socket.
Thanks

A: What you describe is not possible.
You undoubtedly have some static variables somewhere that should be instance members of Worker, such as the input and/or output streams, and/or the socket itself.


text:
Q: resizable window frame in tkinter I created a window with tkinter for my programm but I want it to resize itself when the user resizes the window. Right now when I increase or decrease the size of the window the widgets stay at the same position and don't in-/decrease in size.
Here is my code:
import tkinter as tk

class Graphicaluserinterface(tk.Frame):

    def __init__(self,master=None):
        super().__init__(master)
        self.grid()
        self.check1 = tk.IntVar()
        self.fileopenname1 = tk.StringVar()
        self.entrystring = tk.IntVar()
        self.menubar = tk.Menu(self)
        self.create_widgets()

    def create_widgets(self):
        self.filemenu=tk.Menu(self.menubar,tearoff=0)
        self.menubar.add_cascade(label="File",menu=self.filemenu)
        self.filemenu.add_command(label="Exit",command = root.destroy)
        self.helpmenu=tk.Menu(self.menubar,tearoff=0)

        self.programmstart = tk.Button(self, text = "Start Program")
        self.programmstart.grid(row=10,column=8,sticky = "W")

        self.checkbutton1 = tk.Checkbutton(self, text = "Drehzahl und Drehmoment",variable=self.check1,onvalue=1,offvalue=0)
        self.checkbutton1.grid(row=0,column=0,columnspan=3,sticky = "W")

        self.leer1 = tk.Label(self,text="                               ") #erzeugt leere Zelle, sonst ist startbutton links
        self.leer1.grid(row=0,column=3,columnspan=5)
        self.leer2 = tk.Label(self,text="                               ")
        self.leer2.grid(row=5,column=8,rowspan=2)
        self.leer3 = tk.Label(self,text="                               ")
        self.leer3.grid(row=9,column=9)

        self.inputpathdisplay = tk.Label(self,textvariable=self.fileopenname1,bg="white",width=60)
        self.inputpathdisplay.grid(row=1,column=8,columnspan=3,sticky = "W")
        self.inputpathdisplaylabel = tk.Label(self,text="Inputfile")
        self.inputpathdisplaylabel.grid(row=0,column=8,columnspan=3)

root = tk.Tk()
app = Graphicaluserinterface(master=root)
app.master.title("Programm")
app.master.minsize(800,300)
root.config(menu=app.menubar)
app.mainloop()

A: You need to configure the weight on your grid's rows and columns. The following is a refactored version of your code that should act a little more as you were hoping. Please continue development from this code:
#! /usr/bin/env python3
import tkinter
from tkinter.constants import *

class GraphicalUserInterface(tkinter.Frame):

    @classmethod
    def main(cls):
        root = tkinter.Tk()
        root.title('Program')
        root.minsize(560, 105)
        gui = cls(root)
        gui.grid(row=0, column=0, sticky=NSEW)
        root.grid_rowconfigure(0, weight=1)
        root.grid_columnconfigure(0, weight=1)
        root['menu'] = gui.menubar
        cls.create_toplevel(root, 'First Toplevel')
        root.mainloop()

    @staticmethod
    def create_toplevel(root, window_title):
        window = tkinter.Toplevel(root)
        window.title(window_title)
        window.minsize(560, 105)

    def __init__(self, master=None):
        super().__init__(master)
        self.check_value = tkinter.BooleanVar()
        self.filename = tkinter.StringVar()
        self.menubar = tkinter.Menu(self)
        self.file_menu = tkinter.Menu(self.menubar, tearoff=FALSE)
        self.help_menu = tkinter.Menu(self.menubar, tearoff=FALSE)
        self.program_start = tkinter.Button(
            self, text='Start Program',
            command=lambda: self.create_toplevel(self.master, 'Another Window')
        )
        self.check_button = tkinter.Checkbutton(
            self, text='Speed & Torque', variable=self.check_value,
            onvalue=True, offvalue=False
        )
        self.input_path_display = tkinter.Label(
            self, textvariable=self.filename, bg='white', width=60
        )
        self.input_path_display_label = tkinter.Label(self, text='Input File')
        self.create_widgets()

    def create_widgets(self):
        self.menubar.add_cascade(label='File', menu=self.file_menu)
        self.file_menu.add_command(label='Exit', command=self.master.destroy)
        pad = dict(padx=5, pady=5)
        self.check_button.grid(row=0, column=0, **pad)
        self.input_path_display_label.grid(row=0, column=1, sticky=EW, **pad)
        self.input_path_display.grid(row=1, column=1, sticky=NSEW, **pad)
        self.program_start.grid(row=2, column=1, sticky=EW, **pad)
        self.grid_rowconfigure(1, weight=1)
        self.grid_columnconfigure(1, weight=1)

if __name__ == '__main__':
    GraphicalUserInterface.main()


text:
Q: AngularJS ngStorage $sessionStorage gives access denied in IE only When running on localhost (via Visual Studios) all is well, when moved to staging IE 11 (only, Chrome/FF both work fine) I am getting an Error:

Error: Access is denied.
at isStorageSupported
  (http://stage.mySite.com/Scripts/Frameworks/AngularJS/1.13.15/modules/ngStorage.js:53:21)
  at Anonymous function
  (http://stage.mySite.com/Scripts/Frameworks/AngularJS/1.13.15/modules/ngStorage.js:74:17)
  at invoke
  (http://stage.mySite.com/Scripts/Frameworks/AngularJS/1.13.15/angular.js:4203:7)
  at enforcedReturnValue
  (http://stage.mySite.com/Scripts/Frameworks/AngularJS/1.13.15/angular.js:4056:7)
  at invoke
  (http://stage.mySite.com/Scripts/Frameworks/AngularJS/1.13.15/angular.js:4203:7)
  at Anonymous function
  (http://stage.mySite.com/Scripts/Frameworks/AngularJS/1.13.15/angular.js:4021:13)
at getService (http://stage.mySite.com/Scripts/Frameworks/AngularJS/1.13.15/angular.js:4162:11)
at invoke
  (http://stage.mySite.com/Scripts/Frameworks/AngularJS/1.13.15/angular.js:4191:9)

(note I have already Googled this problem a number of ways...)

A: This problem was resolved by updating to the latest version of ngStorage (as 8/5/2015)


text:
Q: Calling two functions at the same time How can i call the 2 functions at the same time or perform a mathematical operation from their results? Every time i call these two functions, only the first function stores the data while the second function shows 0?
fname= input("Enter a file name: ")
try:
    openFile= open(fname, 'r')
except:
    print(fname, "is not found in the directory.")
    quit()

def linecount():
    line_count= 0
    for line in openFile:
        if line.startswith("X-DSPAM-Confidence: "):
            line_count= float(line_count+1)
    return(line_count)

def contents():
    spamContent= 0
    for content in openFile:
        if content.startswith("X-DSPAM-Confidence: "):
            contentconversion= float(content[20:26])
            spamContent= spamContent + contentconversion
    return(spamContent)

result= contents()/linecount()
print(result)


text:
Q: Rest client java.net.ConnectException: Connection timed out: connect Hi i have a Spring Rest Webservice deployed in the weblogic service. I have advance rest client of google chrome which work perfectly over https
I am trying to create to Client over https Client. I have ca certificate and client certificate. I created it from the below link
Accessing secure restful web services using jersey client But i am getting exception below
Exception in thread "main" com.sun.jersey.api.client.ClientHandlerException: java.net.ConnectException: Connection timed out: connect
        at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:155)
        at com.sun.jersey.api.client.Client.handle(Client.java:652)
        at com.sun.jersey.api.client.WebResource.handle(WebResource.java:682)
        at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74)
        at com.sun.jersey.api.client.WebResource$Builder.post(WebResource.java:570)
        at org.app.last.JerseyClient.get_JSON(JerseyClient.java:39)
        at org.app.last.JerseyClient.main(JerseyClient.java:239)
    Caused by: java.net.ConnectException: Connection timed out: connect
        at java.net.PlainSocketImpl.socketConnect(Native Method)
        at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:351)
        at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:213)
        at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:200)
        at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
        at java.net.Socket.connect(Socket.java:529)
        at com.sun.net.ssl.internal.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:564)
        at com.sun.net.ssl.internal.ssl.BaseSSLSocketImpl.connect(BaseSSLSocketImpl.java:141)
        at sun.net.NetworkClient.doConnect(NetworkClient.java:163)
        at sun.net.www.http.HttpClient.openServer(HttpClient.java:395)
        at sun.net.www.http.HttpClient.openServer(HttpClient.java:530)
        at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:272)
        at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:329)
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:172)
        at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:911)
        at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:158)
        at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1172)
        at java.net.HttpURLConnection.getResponseCode(HttpURLConnection.java:379)
        at sun.net.www.protocol.https.HttpsURLConnectionImpl.getResponseCode(HttpsURLConnectionImpl.java:318)
        at com.sun.jersey.client.urlconnection.URLConnectionClientHandler._invoke(URLConnectionClientHandler.java:253)
        at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:153)
        ... 6 more

A: It seems like you still have a problem with the proxy. and also you can have problem with the certificate

*

*check whether you're configuring the proxy properly

*Check whether your certificate is expired. if expired, request a new one

*Check with fiddler whether you're sending the certificate to server

A: Check your firewall settings to see if the outbound ports are blocked except for the browser. This happens occasionally depending on the company.
Outbound ports are by default opened, but this might have been changed by system administrators - see this answer.
Also the connection might be blocked at the level of your corporate proxy. For example in some companies you can only surf with one browser, and if you install and try to access the internet with another browser, you receive a message "It's only allowed to browser the internet with browser XX", or a timeout.
This works because the proxy checks for the User-Agent header.
Many proxies require authentication and only give access to authorized users. Chrome fils in your credentials automatically in some HTTP header while surfing, but your program does not do that.
To troubleshoot this, try the following possibilities:

*

*print the Url to the console with System.out.println and confirm that it's exactly the same as you type in Chrome

*use a non-browser based command line utility like curl or wget to check if you can access for example google and also the endpoint

*check your firewall settings

A: It is not a cert issue, else you would have seen SSL errors. Check your proxy settings. In Spring applications, you can add the following to the VM arguments to set your proxy: -Dhttp.proxyHost=your.proxy.net -Dhttp.proxyPort=8080

A: Add below property in your application.properies file in eureka server application:
eureka.server.peer-node-read-timeout-ms=6000

If it does not work, try to increase read time out.
This is working in my case.


text:
Q: Combine alias functions Using Graphite, I'm plotting some graph and the same with a time shift.
Eg:
aliasByNode(my.application.metric.$Continent.$DC.*, 4, 5, 3)
aliasByNode(timeShift(my.application.metric.$Continent.$DC.*, "7d"), 4, 5, 3)

But I'd like to be able to identify the graphs (they currently get the same name).
How to add a prefix or a suffix (or any marker) to a metric alias?
Eg:
-- EU.PAR.pokemonCaught
-- EU.PAR.pokemonCaught (last week)

A: Use regex with aliasSub  to grab whole ( (.*) ) metric and change it - add desired text ( \1 last week ). E.g.
aliasByNode(timeShift(my.application.metric.$Continent.$DC.*, "7d"), 4, 5, 3)

should look like
aliasSub(aliasByNode(timeShift(my.application.metric.$Continent.$DC.*, "7d"), 4, 5, 3), "(.*)", "\1 last week")

A: You could just use alias() to rename it however you like.


text:
Q: Cauchy's theorem with partially defined contour and function The Cauchy's theorem says if $f(z)$ is analytic on and inside the contour $C$, then,$$\oint_C f(z)dz=0$$ And if we split the contour into two segments $A$ and $B$, we may obtain $$\oint_C f(z)dz=\int_Af(z)dz +\int_Bf(z)dz=0$$ So, $$\int_Af(z)dz=-\int_Bf(z)dz$$ Here is the part making me curious. If we only know the value of $f(z)$ on the segment $A$, but are otherwise free to define $f(z)$ at any point that is not on $A$ (as long as it is analytic), we end up something very weird. The left hand side of Equation 3 is something definite, but since we can freely vary $B$ and define the value of $f(z)$ outside $A$, the right hand side looks very indefinite. And there can be numerous different combination of $f(z)$ and $B$ outside $A$. So it means no matter how we choose, we end up the same for the integral. Shall I accept this counter-intuitive result or I make something wrong in my reasoning? Thanks in advance!
Edit: I find Lourenco Entrudo`s reply is quite helpful in understanding these. And thanks everyone for helping!

A: The answer to your question is that it doesn't come up: If you know the values of $f$ on $A$ and $f$ is analytic then you are not free to choose the values on $B$. Since $A$ has a limit point in the domain, if $f_j$ are analytic and $f_1=f_2$ on $A$ then also $f_1=f_2$ on $B$.


text:
Q: Handle CCAvenue response in angular js 2.0 I am using angular js 2.0 as client side application which communicate with ASP.Net core to performer server calls. I am using ccavenue seamless integration kit where i am generating encrypted request using server call which contains "www.abc.com/success" as success URL. After clicking on buy button on www.abc.com site is redirecting to CCAvenue.com and perform transaction,After successful transaction from CCAvenue ,Site is redirecting to provided success URL(www.abc.com/success) where are getting "HTTP Error 405.0 - Method Not Allowed
The page you are looking for cannot be displayed because an invalid method (HTTP verb) is being used." error.
I am confused how to handle HTTP post response from CCAvenue in angular 2.0 application.

A: After publishing its plain HTML and at the end once you come to main site HTML cant identify routing mechanism. You need to implement some server-side page like PHP.

A: As we mentioned in the comments there is no angular way or 'client-side' way to fix this. Should be handled in the backend with .post and .get routes for the status of the payment.


text:
Q: How to refer to the n attribute in the lg element of TEI xml document in XSLT to create a LaTeX output (for using reledmac to make PDF) I want to ultimately print the verse number, e.g. §1, encoded in the XML as <lg n="1"> , in my pdf output. Here's an example of my XML document:
        <teiHeader>
            ...
        </teiHeader>
        <text>
            ...
            <body>
                <head>
                    ...
                </head>
                <div>
                    <lg n="1">
                        <l n="1">
                           verse one line one of the poem</l>
                        <l n="2">
                            verse one line two</l>
                        <l n="3">...ditto </l>
                        <l n="4">...ditto </l>
                    </lg>
                    <lg n="2">
                        <l n="1">...
                    </lg>
...

I am preparing a critical edition of a poem of this structure, and since I am a novice to XML, TEI, XSLT, and LaTeX, I cannot figure out how to reference the n="1" part in the xslt so that LaTeX prints it. I am trying to use the stylesheet posted on TEI Critical Apparatus Toolbox that transforms XML into LaTeX with the reledmac package (the link to the XSLT file is under "Advanced Customisation"). The relevant part seems to be these lines, though I don't understand how this works. I just want to tweak it so that my verse numbers, and perhaps even my line numbers, can be referenced and printed:
<!-- inserts linegroup into document-->
  <xsl:template match="tei:lg">

    <!-- lg is a pain because it can occur in p (or not), but in tex it generates a stanza structure which must never be inside a paragraph
    I've tried closing the parent paragraph and re-opening one, but it's not enough.
    If the lg are inside a quotation, for instance, we need to have some more complicated handling.
    -->

    <xsl:choose>
      <xsl:when test="not(ancestor::tei:rdg)">
        <xsl:if test="ancestor::tei:p and not(preceding-sibling::tei:lg)">
          <!-- In TEI an lg can occur within a p, while in LaTeX a stanza cannot occur within a pstart. The only solution I came up with was to close then re-open the current paragraph.
        Warning: this can create a problem in the .tex file when the lg occurs at the very beginning or end of the paragraph. -->
          <xsl:text>
                \pend </xsl:text>
        </xsl:if>
        <xsl:text>
        \stanza[ ] </xsl:text>

        <!-- this is not good; TODO: do better. -->
        <xsl:if test="ancestor::tei:cit">
          <xsl:if
            test="ancestor::tei:quote[position() = 1]/descendant::node()[name() = 'lg'][position() = 1] = self::node()">
            <xsl:text>\edlabel{cit_</xsl:text>
            <xsl:number select="ancestor::tei:quote[position() = 1]" level="any"/>
            <xsl:text>_start}</xsl:text>
          </xsl:if>
        </xsl:if>

      </xsl:when>
      <xsl:otherwise>
        <xsl:text> </xsl:text>
      </xsl:otherwise>
    </xsl:choose>

A: Inside of your template matching a tei:lg element you can select @n in XPath to select the attribute named n and in XSLT output e.g. <xsl:value-of select="@n"/> to output the attribute's value (e.g. 1).


text:
Q: Error : Failed to allocate memory: 1455 when try to run my app in eclipse emulator in 2560x1600 xhdpi When i create an emulator with specifications

when I try to run my project on it , I get error
[2014-01-04 20:27:47 - Emulator] Failed to allocate memory: 1455
[2014-01-04 20:27:47 - Emulator]
[2014-01-04 20:27:47 - Emulator] This application has requested the Runtime to terminate it in an unusual way.
[2014-01-04 20:27:47 - Emulator] Please contact the application's support team for more information.
my laptop has following specifications

Please help what configuration should I use to make it run !

A: Change RAM configuration to 128 or 64.


text:
Q: How to get the difference between two datetime columns in SQL I have two columns (Created and ResolutionDate) in a table with the datetime values

I need to get the difference between the columns created and resolutiondate to get the number of days it took to be resolved from created date.
And also I need to get the result only with the working days or network days i.e., Monday to Friday (not the weekends and holidays).
For example, if I take created:2015-09-22 and resolutiondate: 2015-09-30, then the result should be 6 days, because two days are saturday and sunday between the created and resolutiondate I choose.
Please let me know how can I work it out with SQL.

A: For calculating the difference between two dates in working days, you can use the following function. Be aware that this will only calculate without weekends, and if you have holidays in the middle, it will calculate them as ordinary days.
    public double GetBusinessDays(DateTime startD, DateTime endD)
    {
        double calcBusinessDays =  1 + ((endD - startD).TotalDays * 5 - (startD.DayOfWeek - endD.DayOfWeek) * 2) / 7;
        if ((int)endD.DayOfWeek == 6) calcBusinessDays--;
        if ((int)startD.DayOfWeek == 0) calcBusinessDays--;

        return calcBusinessDays;
    }

A: Perhaps something like this...  The Cross Apply portion could be a UDF
Declare @YourTable table (ID int,Created datetime, ResolutionDate datetime)
Insert Into @YourTable values
(1,'2015-09-22 13:35:38','2015-09-30 17:37:09'),
(2,'2016-02-28 12:55:22','2016-02-29 12:55:44'),
(3,'2015-09-22 13:30:31','2015-09-30 17:37:09')

Select A.*
      ,B.WorkingDays
 From  @YourTable A
 Cross Apply (
                Select WorkingDays=count(*)
                 From (Select Top (DateDiff(DD,A.Created,A.ResolutionDate)+1) D=DateAdd(DD,Row_Number() over (Order By (Select NULL))-1,cast(cast(A.Created as date) as datetime)) From master..spt_values N1) D
                 Where  D >= A.Created and D<= A.ResolutionDate
                   and  DatePart(DW,D) not in (7,1)
                   and  Cast(D as Date) Not In (Select Date From (Values
                                       ('2016-01-01','New Year''s Day'),
                                       ('2016-01-18','Martin Luther King, Jr,'),
                                       ('2016-02-15','Washington''s Birthday'),
                                       ('2016-03-25','Good Friday'),
                                       ('2016-05-30','Memorial Day'),
                                       ('2016-07-04','Independence Day'),
                                       ('2016-09-05','Labor Day'),
                                       ('2016-11-24','Thanksgiving'),
                                       ('2016-11-25','Black Friday'),
                                       ('2016-12-26','Christmas Day')
                                ) as H (Date,Name))
       ) B

Returns
ID  Created                   ResolutionDate            WorkingDays
1   2015-09-22 13:35:38.000   2015-09-30 17:37:09.000   6
2   2016-02-28 12:55:22.000   2016-02-29 12:55:44.000   1
3   2015-09-22 13:30:31.000   2015-09-30 17:37:09.000   6

A: If you need company dates then have a table with all company work days
select ticket.ID, count(companyWorkDay.dt)
from ticket
left join companyWorkDay
       on companyWorkDay.dt between ticket.created and ticket.resolution
group by ticket.ID

For the hassle of populating the table once you get a lot easier queries
You could write a query to enter the weekdays and then just remove the company holidays


text:
Q: Error when installing cocoapods - Host is down i had some problems installing a gem, so i tried updating cocoapods. I uninstalled it first, then tried installing it again with command sudo gem install cocoapods and gem install cocoapods. This won't work because i had following error:
error: ERROR:  While executing gem ... (Errno::EHOSTDOWN)
Host is down - sendto(2) for "8.8.8.8" port 53
This happens when i do gem install cocoapods and sudo gem install cocoapods. Any idea why this happens ? my connection to internet is ok. I already tried searching on the internet for possible solutions but couldn't find a similar one.

A: Never mind, i was using little snitch which blocked my incoming connection :)


text:
Q: Using Cauchy Inequality for Simple Inequality Let $-\infty<\alpha<\beta<+\infty$ and $g\in C^1[\alpha,\beta]\setminus\{0\}$
How do I use the Cauchy inequality to show that if
$$
2|g(x)|\leq \parallel g' \parallel_{L^1(\alpha , \beta)}
$$
it holds that
$$
2|g(x)|\leq |\beta-\alpha|^{1/2}\parallel g' \parallel_{L^2(\alpha , \beta)}
$$

A: For any $L^{2}$ function $h$ we have $(\int_{\alpha}^{\beta} |h|)^{2} =(\int_{\alpha}^{\beta} (1)(|h|))^{2} \leq \int_{\alpha}^{\beta} 1^{2} \int_{\alpha}^{\beta} |h|^{2}=(\beta-\alpha) \int_{\alpha}^{\beta} |h|^{2}$. Just take square root and put $h=g'$ in this.


text:
Q: Legacy Fortran FORMAT Edit Descriptor Syntax - Number Before Type? In a snippet of legacy FORTRAN code (actual compiler unknown, suspect it was circa FORTRAN-77), I found a statement like this:
100 FORMAT(5I7.2)

Which I interpret to mean:

*

*Integer

*Width 7 characters, of which

*2 characters are decimals (e.g., '12345.67')
What I can't find is an explanation of the leading '5'. I assume it means something to the effect of "repeating group," say--five groups of seven integers...etc.
Is this interpretation correct?

A: Fortran 2008 defines the I edit descriptor in Section 10.7.2.2.  The relevant paragraphs to your question are (excerpts):

1 The Iw and Iw .m edit descriptors indicate that the field to be edited occupies w positions, except when w is zero.
  When w is zero, the processor selects the field width. On input, w shall not be zero. The specified input/output
  list item shall be of type integer.
5 The output field for the Iw .m edit descriptor is the same as for the Iw edit descriptor, except that the digit-string
  consists of at least m digits. If necessary, sufficient leading zeros are included to achieve the minimum of m digits.

This means that I7.2 will be 7 digits wide and at least two digits will always be displayed, 0-padded.
The preceding 5 in the edit descriptor is a repeat specification (Fortran 2008 10.3.1 paragraph 1) and is a repeat count of the following edit descriptor.
Put together, 5I7.2 will output 5 integers, each 7 digits wide displaying a minimum of 2 digits being zero padded to two digits if necessary.


text:
Q: Cross apply no postgres? Eu tenho a seguinte situação
CROSS APPLY (select top 1 seq.id_prod,
                   seq.id_emp,
                   seq.localizacao,
                   seq.localizacao_modulo,
                   seq.localizacao_nivel,
                   seq.localizacao_rua,
                   seq.localizacao_vao,
                   qtde
            from eq_prod_qtde seq
            where seq.id_prod = p.id_prod
              and seq.id_emp = pc.id_emp) ES
CROSS APPLY (select sum(qtde)
                   qtde
            from eq_prod_qtde seq
            where seq.id_prod = p.id_prod) ES1

Porem estou tendo dificuldade em fazer esse mesmo processo para postgres.


text:
Q: Archive Large files to DVD - span? I have about 16GB of data that I'd like to burn onto DVDs. Many small files and a few large (one is 13GB).
I'm looking for a good option to get all that data spanned across a few DVDs. I realize one option could be to use 7zip to make multiple archives, each 4.7GB, but before I go that route I figured I'd ask here first. :-)
I tried the built-in backup app that comes with Windows 7, but it didn't seem to want to span DVD and crapped out when the first DVD filled.

A: You best option is really the split archives using 7zip. It's simple, easy, and will use up every last bit of each DVD (excluding overburning). This way you'll also gain a extra space if the content isn't already compressed.
On that note, if the content is already compressed you might want to turn off compression or use lower compression settings to save some CPU time since you won't gain much space from compressing compressed content.
I recently backed up 1.36 TB of media to many DVDs using 7zip.


text:
Q: How to increment an NSIndexPath I have a data situation where I want to use an index path. As I'm traversing the data I want to increment the last node of an NSIndexPath. The code I have so far is:
int nbrIndex = [indexPath length];
NSUInteger *indexArray = (NSUInteger *)calloc(sizeof(NSUInteger),nbrIndex);
[indexPath getIndexes:indexArray];
indexArray[nbrIndex - 1]++;
[indexPath release];
indexPath = [[NSIndexPath alloc] initWithIndexes:indexArray length:nbrIndex];
free(indexArray);

This feels a bit, well, clunky - Is there a better way to do it?

A: You can try this - perhaps equally clunky, but at least a bit shorter:
NSInteger newLast = [indexPath indexAtPosition:indexPath.length-1]+1;
indexPath = [[indexPath indexPathByRemovingLastIndex] indexPathByAddingIndex:newLast];

A: One line less this way:
indexPath = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:actualIndexPath.section];

A: Check my solution on Swift:
func incrementIndexPath(indexPath: NSIndexPath) -> NSIndexPath? {
    var nextIndexPath: NSIndexPath?
    let rowCount = numberOfRowsInSection(indexPath.section)
    let nextRow = indexPath.row + 1
    let currentSection = indexPath.section

    if nextRow < rowCount {
        nextIndexPath = NSIndexPath(forRow: nextRow, inSection: currentSection)
    }
    else {
        let nextSection = currentSection + 1
        if nextSection < numberOfSections {
            nextIndexPath = NSIndexPath(forRow: 0, inSection: nextSection)
        }
    }

    return nextIndexPath
}

A: A for loop in Swift 4 achieving similar results with an embedded UITableView, iterating through the for loop, filling the detail text of a cell with "Row Updated"
for i in 0 ..< 9 {
     let nextRow = (indexPath?.row)! + i
     let currentSection = indexPath?.section
     let nextIndexPath = NSIndexPath(row: nextRow, section: currentSection!)

     embeddedViewController.tableView.cellForRow(at: nextIndexPath as IndexPath)?.detailTextLabel?.text = "Row Updated"

     let myTV = embeddedViewController.tableView
     myTV?.cellForRow(at: nextIndexPath as IndexPath)?.backgroundColor = UIColor.red
     myTV?.deselectRow(at: nextIndexPath as IndexPath, animated: true)
}


text:
Q: Changing nvidia powermizer setting using laptop-mode-tools I have laptop-mode-tools 1.61. The config files at /etc/laptop-mode/ have two folders for making laptop-mode-tools to execute scripts, when it detects that it has been switched from AC to battery, and viceversa. I have nvidia propietary driver 310.14 and ubuntu 12.04. the powermizer setting of the nvidia driver is set to adaptative. I want to have it on adaptative when on battery, and on performance mode (no underclocking) when on AC.
As the powermizer setting is changed in runtime with a selection box, I think it's possible to achieve what I want.
I have searched the web for commands to change the nvidia powermizer settings on the fly, as with the GUI, but I only found permanent ways of changing it by touching the xorg.conf.
Is there a command to change the nvidia powermizer setting on the fly?


text:
Q: NTFS permissions equivalent to Linux "--x" (chmod 111) I want to  set folder with permissions such that restricted users could access file.txt (in folder) they have permissions to read by specifying full path but could not list the content of folder.
For example, in Linux, we could do it like this:
$ whoami
cychoi
$ mkdir folder && echo 'file content' > folder/file.txt
$ chmod 111 folder/
$ sudo ls -la folder/
total 12
d--x--x--x 2 cychoi cychoi 4096 Aug 18 21:52 .
drwx------ 3 cychoi cychoi 4096 Aug 18 21:52 ..
-rw------- 1 cychoi cychoi   13 Aug 18 21:52 file.txt
$ ls folder/
ls: cannot open directory folder/: Permission denied
$ cat folder/file.txt
file content
$

In Windows 7, I clear all permissions of folder except execute/traverse (Apply to "this folder only"). However, It fails to read the content of file.txt even full path is specified.
On the other hand, if read data/list directory is also set for folder, file.txt will be read successfully but folder content will be leaked to restricted users.
G:\ptest>whoami
user-pc\test

G:\ptest>runas /u:administrator "cmd /c icacls g:\ptest\folder\ /t & pause"
Enter the password for administrator:
Attempting to start cmd /c icacls g:\ptest\folder\ /t & pause as user "USER-PC\administrator" ...

g:\ptest\folder\ user-PC\test:(S,X)
                 BUILTIN\Administrators:(OI)(CI)(F)
                 NT AUTHORITY\SYSTEM:(OI)(CI)(F)
                 user-PC\cychoi:(OI)(CI)(F)

g:\ptest\folder\file.txt user-PC\test:(F)
                         BUILTIN\Administrators:(I)(F)
                         NT AUTHORITY\SYSTEM:(I)(F)
                         user-PC\cychoi:(I)(F)

G:\ptest>dir
 Volume in drive G is ?????
 Volume Serial Number is DEAD-BEEF

 Directory of G:\ptest

18/08/2015  21:59              .
18/08/2015  21:59              ..
18/08/2015  21:59              folder
               0 File(s)              0 bytes
               3 Dir(s)   4,779,642,880 bytes free

G:\ptest>dir folder
 Volume in drive G is ?????
 Volume Serial Number is DEAD-BEEF

 Directory of G:\ptest\folder

File Not Found

G:\ptest>type folder\file.txt
Access is denied.

G:\ptest>runas /u:administrator "cmd /c icacls g:\ptest\folder\ /grant test:(rd) & pause"
Enter the password for administrator:
Attempting to start cmd /c icacls g:\ptest\folder\ /grant test:(rd) & pause as user "USER-PC\administrator" ...

G:\ptest>runas /u:administrator "cmd /c icacls g:\ptest\folder\ & pause"
Enter the password for administrator:
Attempting to start cmd /c icacls g:\ptest\folder\ & pause as user "USER-PC\administrator" ...

g:\ptest\folder\ user-PC\test:(S,RD,X)
                 BUILTIN\Administrators:(OI)(CI)(F)
                 NT AUTHORITY\SYSTEM:(OI)(CI)(F)
                 user-PC\cychoi:(OI)(CI)(F)

G:\ptest>dir folder
 Volume in drive G is ?????
 Volume Serial Number is DEAD-BEEF

 Directory of G:\ptest\folder

18/08/2015  21:59              .
18/08/2015  21:59              ..
18/08/2015  21:59                12 file.txt
               1 File(s)             12 bytes
               2 Dir(s)   4,779,642,880 bytes free

G:\ptest>type folder\file.txt
file content
G:\ptest>

So, how can I achieve the same behaviour as in the Linux example I shown above?