text:
Q: Could not mock oracledb.getConnection() in jest unit test for nodejs typescript class that use oracledb npm This is nodejs typescript class to execute query or getConnection using oracledb npm.
I could not mock oraclebd getConnection in jest unit test.
How to write unit test for executeQuery. It shows test coverage to be done on finally block all statement.
I written unit test but

import { Inject, Injectable } from '@nestjs/common';
import * as oracledb from 'oracledb';
import { ORACLE_DB_OPTIONS } from '../constant';
import { OracleDBOptions } from '../interface';
import { PromInstanceCounter, PromMethodCounter } from '@digikare/nestjs-prom';

@PromInstanceCounter
@Injectable()
export class OracleDBService {
  constructor(
    @Inject(ORACLE_DB_OPTIONS)
    private readonly oracleDbOptions: OracleDBOptions[],
  ) { }

  @PromMethodCounter()
 async executeQuery(
    dbName: string,
    query: string,
    bindValue: any[] = [],
  ) {
    let localConnection: any;
    try {
      const oracleDbOption = this.oracleDbOptions.filter(
        x => x.name === dbName,
      );
      if (!oracleDbOption) {
        throw Error('Connection string does not exist');
      }
      localConnection = await oracledb.getConnection({
        user: oracleDbOption[0].user,
        password: oracleDbOption[0].password,
        connectString: oracleDbOption[0].connectString,
      });
      const result = await localConnection.execute(query, bindValue);
      await localConnection.close();
      return result;
    } finally {
      if (localConnection) {
        try {
          await localConnection.close();
        } catch (err) {
          console.log('Error when closing the database connection: ', err);
        }
      }
    }
  }
  @PromMethodCounter()
  async getConnection(dbName: string) {
    const oracleDbOption = this.oracleDbOptions.filter(x => x.name === dbName);
    if (!oracleDbOption) {
      throw Error('Connection string does not exist');
    }

    const localConnection = await oracledb.getConnection({
      user: oracleDbOption[0].user,
      password: oracleDbOption[0].password,
      connectString: oracleDbOption[0].connectString,
    });

    return localConnection;
  }
}

Written Unit Test for getConnection() method.

describe('OracleDbService', () => {
  let oracleDBService: OracleDBService;

  let oracleDBOptions = [
    {
      name: 'rfdest',
      user: 'rfdest',
      password: 'rfdest',
      connectString: 'alsyntstb.ohlogistics.com:1521/syntstb',
    },
    {
      name: 'DOCGENDEV',
      user: 'DOCGENDEV',
      password: 'DocGen$dev18',
      connectString: 'alsynwebd.ohlogistics.com/synwebd_maint',
    },
  ];

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [
        OracleDBService,
        {
          provide: ORACLE_DB_OPTIONS,
          useValue: oracleDBOptions,
        },
      ],
    }).compile();

    oracleDBService = module.get<OracleDBService>(OracleDBService);
  });

  it('should be defined', () => {
    expect(oracleDBService).toBeDefined();
  });
  it('getConnection success', () => {
    jest.fn(getConnection).mockReturnValue({
      execute: function() {},
      close: function() {},
    });
    oracleDBService.getConnection('rfdest').then(resolve => {
      expect(resolve).not.toBeNull();
    });
  });
  it('getConnection throw error', () => {
    jest.fn(getConnection).mockReturnValue({
      execute: function() {},
      close: function() {},
    });
    oracleDBService
      .getConnection('')
      .then(resolve => {
        expect(resolve).not.toBeNull();
      })
      .catch(reject => {
        expect(reject).not.toBeNull();
      });
  });
});


text:
Q: How to get exact value of choice field in django I have a choice field in Django model:
COMMITTEE_STATUS = (
    ("p", "Pending"),
    ("a", "Active"),
    ("c", "Completed"),
)

But the issue is when I am accessing these data in template I am getting p,a and c instead of actual pedning, active and complete

A: It's because first value is actually stored in database, the other is just for humans. You have to do additional thing to get second value. According to Django docs use this:
{{ yourobject.get_yourfield_display }}

A: {{your_variable_name.get_fieldname_display}}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cakephp what does $this->request->params['pass'][0] mean? Hi I need help in this line of code, I already searched in the docs I found $this->request->params['pass'][0] but I can't understand what's it's use
What does $this->request->params['pass'][0] mean?
Can anyone please help me into this?

A: http://book.cakephp.org/2.0/en/controllers/request-response.html
$this->request->params['pass']

represents the passed parameters within a url
Example:  your request url localhost/calendars/view/recent/mark
Both recent and mark are passed arguments to CalendarsController::view()
$this->request->params['pass'] is an array valued array ([0]=>recent [1]=>mark)
So, in the above example
$this->request->params['pass'][0] = "recent"


text:
Q: How do I install the Moksha window manager on 15.04? I have Xubuntu 15.04 running through VirtualBox and in an effort to minimize the resources it uses further I was considering switching to Bodhi Linux's Moksha window manager. I have tried adding the Bodhi repo (deb http://packages.bodhilinux.com/bodhi trusty main) to my /etc/apt/sources.list file but as Bodhi is based on LTS releases of Ubuntu I encountered some issues with attempting to install Moksha this way. So instead I cloned the Moksha GitHub repository and checked-out the latest release (0.1.0) with:
git clone https://github.com/JeffHoogland/moksha
git fetch -p
git checkout 0.1.0
git remote add upstream https://github.com/JeffHoogland/moksha

With the last line really just serving to make it easier for me to update this repo when newer releases become available. I then ran sudo apt-get build-dep e17 as I know that Moksha is forked from Enlightenment 17 and hence its dependencies are similar. After this I proceeded to compile and install Moksha from this source code by following the instructions in the INSTALL file, namely:
./configure
make
sudo make install

I received no error messages from this at all and everything, from my point of view, ran smoothly. Then I rebooted with sudo reboot, so I could try out Moksha but at the lightdm login screen no Moksha option appeared in the list of available session types.
In attempting to follow Muru's suggestions in the comments I copy-pasted $MOKSHA_BUILD_PATH/data/xsession/enlightenment.desktop to /usr/share/xsessions/moksha.desktop (with sudo mv) and I then rebooted and logged in using the Moksha session option that appeared but I was left with a black screen. I then switched to tty1 using Ctrl+Alt+F1 and logged in and ran /usr/local/bin/enlightenment_start (which should have started Mokshra) and I received an error message (which I can't copy here as tty1 doesn't allow me to use clipboard in it). Is there a way I could get this error message while running a Xfce session (as then I could copy-paste it here)? I have tried running /usr/local/bin/enlightenment_start while in Xfce but the error it gave was complaining that another window manager was active and because of this it could not launch.


text:
Q: Highcharts stacked area filtering I'm getting a bug in my stacked area implementation when a user filters to a specific line.
In the image linked below, you'll see we're tracking two trends. When I turn off the "Dialup" trend, the orange area should remain where it is. Instead, it moves up to fill the entire area. Likewise, if I were to turn off the orange "Broadband" trend, the green dialup area fills the entire area below it, rather than falling to the baseline as it should.

(stackoverflow will not allow me to post images yet.)
You can see the value in the tooltip remains accurate.
Could anyone provide some insight into what may be causing this? In case this may be a factor, the chart is generated based on a table of data using Highcharts.visualize().

A: I can see that you're using Highcharts 3.0.0. According to this, there was a bug in this version of Highcharts. If you upgrade Highcharts to the latest version, it should work as intended.


text:
Q: How to solve "Time Machine did not finish backing up because some files were unavailable. Backups will resume when your Mac is unlocked." My Time Machine hasn't been able to backup properly for a couple of weeks now and I got this error:

"Time Machine did not finish backing up because some files were unavailable. Backups will resume when your Mac is unlocked."

Does anyone know what that means? I have never seen it and don't know what is mean by "when your Mac is unlocked." What is locked though?
This is an M1 Pro 14 Inch 2021 running Monterey 12.0.1
My last backup was October 16, so that's more than a month ago and I don't know if that extended period of time has to do with anything. Usually I backup every 1-2 weeks, but I've been busy lately.
Thank you very much


text:
Q: display element multiple times I'm trying to display a little box multiple times with jquery. I goal is something like a for loop

 .box_counter {
   float: left;
   width: 10px;
   height: 10px;
   margin: 40px 0px 0px 250px;
   background-color: black;
 }

So like (pseudo code)
for (index != total)
  push.box_counter
  index++

JSFIDDLE

A: Create the elements in the loop. Example:
for (var i = 0; i < 10; i++) {
  $(document.body).append($('').addClass('box_counter'));
}

Demo: http://jsfiddle.net/WUYfW/2/

A: Simply clone the element, and add the copy after it in the DOM JSFIDDLE
$(function() {
    var total = 20;

    for (var i=0; i<total; i++) {
        $boxCntr = $(".box_counter").first().clone(true);
        $(".box_counter").last().after($boxCntr);
    }
});


text:
Q: R markdown ! Extra alignment tab has been changed to \cr. error occured In R markdown I want to make the table with 2 rows and 8 columns.
\begin{table}[ht]
\begin{tabular}{c|c|c|c|c|c|c|c}
\hline
variable & N & Mean & Std.Dev & SE Mean & 95% cI & T & P \\
Y & 25 & 92.5805 & ? & 0.4673 & (91.6160, ?) & ? & 0.002 \\
\hline
\end{tabular}
\end{table}

I entered this command and it returns this error message.
! Extra alignment tab has been changed to \cr.
<recently read> \endtemplate

l.101 Y & 25 & 92.5805 &

pandoc.exe: Error producing PDF
error: pandoc document conversion failed with error 43

I guess I entered tabular right and nothing to be calculated.
They' are just texts and numbers.
I tried to search similar questions and compare the examples codes.
But I don't know how to solve it.

A: Specify your tablar correctly with extra vertical bars | at the beginning and at the end. In addition escape the percent sign with a backslash \%, otherwise it has a meaning as a program code.
\begin{table}[ht]
\begin{tabular}{|c|c|c|c|c|c|c|c|}
 \hline
 variable & N & Mean & Std.Dev & SE Mean & 95\% cI & T & P \\
 Y & 25 & 92.5805 & ? & 0.4673 & (91.6160, ?) & ? & 0.002 \\
 \hline
\end{tabular}
\end{table}

Hope this would work for you?

A: I encountered the same error when omitting a justification argument for one of the aligned columns. In this example, I want to left justify two equations using an array rather than a table:
\begin{array}{l}
\hat{z} =& \frac{\beta_0}{1 - \beta_z} \\
\hat{z}' =& \beta_0+\beta_z\left(\frac{\beta_0}{1-\beta_z}\right).
\end{array}

For which we see the same error:
! Extra alignment tab has been changed to \cr.
<recently read> \endtemplate

Indeed the principle of the issue is the same as for \tabular, however adding vertical bars | will not fix the problem. Only by adding the missing l in \begin{array}{l} (which becomes \begin{array}{ll}) resolved the error.


text:
Q: How to debug in [Clozure] Common Lisp? I'm using CCL on Mac (1.8.1 -- the latest available at this writing), and wondering if there's any sort of debugging tutorial available.
The thing I'm particularly interested in is setting a breakpoint somewhere in my code, then poking & prodding various values, then stepping over the next line of code, checking more values, etc.
EDIT:
I've read the debugging section of the CCL manual (18.3 and thereabouts), but can't quite make sense of it.  I'm coming from a C/Java/etc. background and IDE-based source level debuggers, with just a little exposure to gdb.
So I guess what I'm looking for is an introduction/tutorial that walks me through a few of the simpler steps.
(I'm new to Lisp (and CCL, of course) so, if I'm asking completely the wrong question or going about things completely the wrong way, feel free to let me know.)
Thanks!

A: I am sure a CCL user might point you to the Debugging section in the CCL manual, but, in fact, the ANSI Common Lisp standard includes excellent debugging facilities, including break and step you asked about (except for step's granularity is not based on a line of code but rather a form).
In fact, the whole Condition System is worth examining.
There are a few tutorials too.
The most important thing to remember that the debugging tools give you the normal Lisp REPL (Read-Eval-Print Loop) where you can do just about anything you can do with the initial REPL: define functions and variables, examine the existing variable (including those defined in the functions in which the debugger was entered) et al. Additionally, you might be able to issue additional commands, like step and next (often abbreviated :s and :n) in the stepper or continue (often abbreviated :c) in a continuable error.
One difference you need to watch for is that in gdb you examine a variable x using print x (abbreviated p x) while in Lisp you just type x and it is evaluated.
Here are some simple examples:
Step
Here ? gives help on available commands; try help or :h if your lisp barfs.
> (defun factorial (n) (if (zerop n) 1 (* n (factorial (1- n)))))
FACTORIAL
> (step (factorial 3))
step 1 --> (FACTORIAL 3)
Step 1 > ?

Commands may be abbreviated as shown in the second column.
COMMAND        ABBR     DESCRIPTION
Help           :h, ?    print this command list
Error          :e       print the last error message
Inspect        :i       inspect the last error
Abort          :a       abort to the next recent input loop
Unwind         :uw      abort to the next recent input loop
Reset          :re      toggle *PACKAGE* and *READTABLE* between the
                          local bindings and the sane values
Quit           :q       quit to the top-level input loop
Where          :w       inspect this frame
Up             :u       go up one frame, inspect it
Top            :t       go to top frame, inspect it
Down           :d       go down one frame, inspect it
Bottom         :b       go to bottom (most recent) frame, inspect it
Mode mode      :m       set stack mode for Backtrace: 1=all the stack elements
             2=all the frames                         3=only lexical frames
             4=only EVAL and APPLY frames (default)   5=only APPLY frames
Frame-limit n  :fl      set the frame-limit for Backtrace. This many frames
                          will be printed in a backtrace at most.
Backtrace [mode [limit]] :bt  inspect the stack
Break+         :br+     set breakpoint in EVAL frame
Break-         :br-     disable breakpoint in EVAL frame
Redo           :rd      re-evaluate form in EVAL frame
Return value   :rt      leave EVAL frame, prescribing the return values
Step           :s       step into form: evaluate this form in single step mode
Next           :n       step over form: evaluate this form at once
Over           :o       step over this level: evaluate at once up to the next return
Continue       :c       switch off single step mode, continue evaluation
-- Step-until :su, Next-until :nu, Over-until :ou, Continue-until :cu --
           same as above, specify a condition when to stop
Step 1 > :s
step 2 --> 3
Step 2 > :n
step 2 ==> value: 3
step 2 --> (IF (ZEROP N) 1 (* N (FACTORIAL #)))
Step 2 > :s
step 3 --> (ZEROP N)
Step 3 > :n
step 3 ==> value: NIL
step 3 --> (* N (FACTORIAL (1- N)))
Step 3 > :s
step 4 --> N
Step 4 > :n
step 4 ==> value: 3
step 4 --> (FACTORIAL (1- N))
Step 4 > :s
step 5 --> (1- N)
Step 5 > :n
step 5 ==> value: 2
step 5 --> (IF (ZEROP N) 1 (* N (FACTORIAL #)))
Step 5 > :c
step 5 ==> value: 2
step 4 ==> value: 2
step 3 ==> value: 6
step 2 ==> value: 6
step 1 ==> value: 6
6

Note that the prompt inside the stepper is step <level> where level is the nesting level.
Break
> (defun assert-0 (x) (unless (eql x 0) (break "Bad x: ~S" x)) 0)
ASSERT-0
> (assert-0 0)
0
> (assert-0 'assert-0)

** - Continuable Error
Bad x: ASSERT-0
If you continue (by typing 'continue'): Return from BREAK loop
The following restarts are also available:
ABORT          :R1      Abort main loop
Break 1 > x
ASSERT-0
Break 1 > :c
0

Here the prompt is Break <level>.
Assert
> (defun my+1 (x) (assert (numberp x) (x) "must be a number: ~S" x) (1+ x))
MY+1
> (my+1 5)
6
> (my+1 'my+1)

** - Continuable Error
must be a number: MY+1
If you continue (by typing 'continue'): Input a new value for X.
The following restarts are also available:
ABORT          :R1      Abort main loop
Break 1 > :c
New X> 'foo

** - Continuable Error
must be a number: FOO
If you continue (by typing 'continue'): Input a new value for X.
The following restarts are also available:
ABORT          :R1      Abort main loop
Break 1 > :c
New X> 6
7

assert uses the same prompt as break.

A: The simple answer you are looking for is given by juanitofatas. Unfortunately CCL does not support step and hence is weak in debugging. Until now the best implementation to debug is CLISP.

A: in ccl, you can use cl-stepper:step instead of cl:step.
(ql:quickload "com.informatimago.common-lisp.lisp.stepper")


text:
Q: Use an object's string.contains method within a switch statement? Basically something along the lines of:
switch (string.contains(x))
{
    case(x = "asdf"):
        break;
    case(x = "jkl"):
        break;
    case(x = "qwerty"):
        break;
}

edit: Sorry guys, what I'd ideally like is to have the switch statement check the string for several different values, and depending on which of the values it finds inside the string, execute the appropriate code.

A: You can't do this unfortunately, however you can apply "functional pattern matching".  Read up here on how to do it:
http://codebetter.com/matthewpodwysocki/2008/09/16/functional-c-pattern-matching/

A: You mean this, as far as I could figure it out:
if (string.Contains(x))
{
    switch (x)
    {
        case "asdf":
            break;
        case "jkl":
            break;
        case "qwerty":
            break;
    }
}

A: The Contains(string s) method returns a boolean, so it is not permissible in the switch statement.

A: The switch keyword has some magic (a lookup table), since it can never throw an exception.
You can rewrite it just as succinctly as:
if (x.Contains("asdf"))
{}
else if (x.Contains("jkl"))
{}
else if (x.Contains("qwerty"))
{}

A: Have you tried this:

    switch (true)
    {
        case string.Contains("asdf"):
            break;
        case string.Contains("jkl"):
            break;
        case string.Contains("qwerty"):
            break;
    }


text:
Q: Enlarging interlinear space to avoid cluttered text at specific lines I am using the mtpro2 typefaces in a document and I have noticed that where a superscript appears on the vertical relative to a subscript in the line immediately above, the vertical space between the top of the former and the bottom of the latter is, at least to my taste, too small. There is no collision indeed but the text becomes too cluttered and unless the page is magnified it looks like there is actually glyph collision. Other than that, line spacing is just fine.
I wonder if it is possible to somehow inform the system to set a larger interline space at those points without having to enlarge the space everywhere.
EDIT:
I have found that this is not an effect of the typeface but rather of my usage of a command of my own. Check in the below MWE that the leading between the first two lines is larger than between the last two lines, where I use my own
commands. With the mtpro2 typeface there is almost a glyph collision.
I have found that by switching the location of the token '^' according to the definion of the command \trianglesubx (see below), the leading is fine. What is the reason?
\documentclass{memoir}

\usepackage{xparse,amsfonts}

\DeclareDocumentCommand\trianglesub
  { s O{N} O{o} }
  { \bigtriangleup^{\IfBooleanT{#1}{#3}}_{#2} }

\DeclareDocumentCommand\vsuper
  { m m }
  {\mathbb{#1}^{#2}}

\DeclareDocumentCommand\trianglesubx
  { s O{N} O{o} }
  { \bigtriangleup\IfBooleanT{#1}{^{#3}}_{#2} }

\begin{document}
\noindent$\bigtriangleup_{N}$\\$\mathbb{R}^{N}$

\noindent$\trianglesub[N]$\\$\vsuper{R}{N}$

\noindent$\trianglesubx[N]$\\$\vsuper{R}{N}$
\end{document}

A: You have provided no example, but the linespacing is specified separately by your documentclass in its definition of \normalsize, \small etc, so you need to modify those settings, the details depending on the original definitions.
As a quick fix that would apply to any documentclass you could use
\renewcommand\baselinestretch{1.1}
\selectfont

To increase baselines by 10%
For example the standard classes at 10pt define normalsize via
\renewcommand\normalsize{%
   \@setfontsize\normalsize\@xpt\@xiipt
%                                ^^^^^^
   \abovedisplayskip 10\p@ \@plus2\p@ \@minus5\p@
   \abovedisplayshortskip \z@ \@plus3\p@
   \belowdisplayshortskip 6\p@ \@plus3\p@ \@minus3\p@
   \belowdisplayskip \abovedisplayskip
   \let\@listi\@listI}

where the marked argument specifies that at \normalsize a 12pt baseline is used.


text:
Q: Determine which project I'm in and which are available I think I'm connected to BigQuery via ODBC:
isql -v BigQuery
+---------------------------------------+
| Connected!                            |
|                                       |
| sql-statement                         |
| help [tablename]                      |
| quit                                  |
|                                       |
+---------------------------------------+

My odbc.ini file looks similar to this:
[ODBC]
Trace=yes
TraceFile=/root/odbc.error

[BigQuery]
# 1 = User Authentication
Email=someemail@blah.iam.gserviceaccount.com
KeyFilePath=/service.json
Driver=/opt/simba/driver/lib/libgooglebigqueryodbc_sb64.so
OAuthMechanism=0
Catalog=someproject

With this ODBC connection, I assumed I would connect to project someproject. However, when I try to query a table I get:
SQL> select * from `someproject.ua.ua_user_daily` limit 10;
[37000][Simba][BigQuery] (100) Error interacting with REST API: Access Denied: Project someproject: User does not have bigquery.jobs.create permission in project someproject.
[ISQL]ERROR: Could not SQLPrepare

I wanted to know which projects are therefore available to me within the SQL terminal, but I could not find any command to do this.
How can I test my connection by looking at what projects I do have access to?

A: The Problem you are facing deals with roles, you need to grant the role bigquery.jobs.create to the service account.
You can also add the role bigquery.user or bigquery.jobUser these two roles contain inside the role bigquery.jobs.create. Check all BigQuery roles that you can grant.
Additionally, if you want to use the same Service Account around multiple GCP projects see this post to see how you need to set it up.
You can Run the following Command in Cloud SDK to see which projects does your service account have access to:
gcloud projects list --impersonate-service-account=<your-service-account-email-address>

This command requires Cloud Resource Manager API to be enabled and resourcemanager.projects.list permission in your Service Account.


text:
Q: Conditional in model quick question. I struggle with writing a conditional in model. If I use code below I get desired .png file, but I'd like to specify that
if tripName == 'russia' than do the condition. However when I add that line code goes immediately to the else. Any ideas?
Updated code!
tripImages = (
    ("Russia"),
    ("Italy"),
    ("France"),
)

class Trip(models.Model):

tripName = models.CharField(max_length=64)
tripLogo = models.ImageField(default="default_trip.png", upload_to='trip_pics')

def save(self, *args, **kwargs):
    super().save(*args, **kwargs)

    if self.tripName in tripImages:
        self.tripLogo = '{}.png'.format(self.tripName.lower())
    else:
        pass

    tripImg = Image.open(self.tripLogo)
    print(self.tripLogo)

    if tripImg.height > 300 or tripImg.width > 300:
        output_size = (300, 300)
        tripImg.thumbnail(output_size)
        tripImg.save()

Here is my code print is added whether this function does anything, and it seems that yes. The name is changed, but the image is not swapped. Any ideas?

A: I would suggest that you implement this condition by overriding the save() method for the Django model.
Check this stackoverflow answer
Well to make it little more straightforward
class Trip(models.Model):
tripName = models.CharField(max_length=64)
    tripLogo = models.ImageField(upload_to='trip_pics')

def save(self, *args, **kwargs):
    tripName = getattr(self, 'tripName')
    if tripName in tripImages:
        self.tripLogo = "{}.png".format(tripName.lower())
    else:
        self.tripLogo = "default_trip"
    super(Model, self).save(*args, **kwargs)

A: How do you test that the name is changed? You have to be sure about that otherwise the if block will be skipped.


text:
Q: VHDL: How to assign a default value to a procedure parameter? I have some existing code that is making use of a procedure for a bus functional model. I am going to add new functionality that will require me to add a new parameter into this procedure. I want, in order to keep the code backward compatible, the procedure to have a default value. In this way, if that parameter is omitted when the procedure is called, the testbench program will still work.
Is it possible to assign a default value for inputs into a procedure in VHDL?

A: Yes.  You simply initialize it with ":= value" following the type.  You can do this for any subprogram (procedure or function).  For example:
  impure function NewID (
    Name          : String ;
    ParentID      : AlertLogIDType          := OSVVM_SCOREBOARD_ALERTLOG_ID ;
    ReportMode    : AlertLogReportModeType  := ENABLED ;
    Search        : NameSearchType          := NAME_AND_PARENT_ELSE_PRIVATE ;
    PrintParent   : AlertLogPrintParentType := PRINT_NAME_AND_PARENT
  ) return ScoreboardIDType ;


text:
Q: Почему при запуске рассылки выдается проблема: Chat not found? @dp.message_handler(commands=['sendall'])
async def sendall(message: types.Message):
   if message.chat.type == 'private':
        text = message.text[9:]
        users = db.get_users()
        for row in users:
            try:
                await bot.send_message(row[0], text )
                if int(row[1]) !=1:
                    db.set_active(row[0], 1)
            except Exception as e:
                print(e)
                db.set_active(row[0], 0)

        await bot.send_message(message.from_user.id,"Успешная рассылка")

Не понимаю почему такая ошибка, боту ранее отправлялись сообщения.


text:
Q: CloudFormation refusing to create AWS::KMS::Key with least privilege Endeavouring to apply the principle of least privilege to a CMK I'm creating, the goal is to create a CloudFormation template that can be used via StackSets to the entire organisation. As a result, I want a key that can be used (kms:Encrypt, kms:Decrypt etc.) for general encryption tasks in the account, but that cannot be modified by principals in the account (specifically kms:PutKeyPolicy but not only).
I have a working policy lifted from a hand crafted key. The CloudFormation template works fine, the StackSet initiates the resource creation.
But only when I don't restrict the account principal with any conditions, which removes the least privilege principle. The CreateKey and PutKeyPolicy API calls both have an option BypassPolicyLockoutSafetyCheck for those of us idiotic enough to think they know better! Except CloudFormation doesn't expose that for AWS::KMS::Key :(
So unless I basically leave the key policy wide open, I get the following error in the Stack:

Resource handler returned message: "The new key policy will not allow you to update the key policy in the future. (Service: Kms, Status Code: 400, Request ID: xxxx, Extended Request ID: null)" (RequestToken: xxxx, HandlerErrorCode: InvalidRequest)

I've tried a variety of options for the principal, with the Condition removed (as below) the key is created, with it in no joy.
- Sid: AllowUpdatesByCloudFormation
          Effect: Allow
          Principal:
            AWS: !Sub "arn:aws:iam::${AWS::AccountId}:root"
          Action:
          - kms:Describe*
          - kms:List*
          - kms:PutKeyPolicy
          - kms:CreateAlias
          - kms:UpdateAlias
          - kms:UpdateKeyDescription
          - kms:EnableKey
          - kms:DisableKey
          - kms:EnableKeyRotation
          - kms:DisableKeyRotation
          - kms:GetKey*
          - kms:DeleteAlias
          - kms:TagResource
          - kms:UntagResource
          - kms:ScheduleKeyDeletion
          - kms:CancelKeyDeletion
          Resource: '*'
          # Condition:
          #   StringEquals:
          #     "aws:PrincipalAccount": !Sub ${AWS::AccountId}
          #     "kms:ViaService": !Sub "cloudformation.${AWS::Region}.amazonaws.com"

I've tried with different principal settings, including AWS: "*" and a few different Service options, and different settings on the Condition. I've tried with and without the region in the service name. I must be missing something, but I've lost a few hours scratching my head over this one.
Web searches, AWS forum searches have turned up nothing, so I'm hoping the good bhurgers of StackOverflow can guide me - and future me's searching for the same help :)
It doesn't seem possible to link to the table section on the AWS KMS API page for the condition keys on CreateKey or PutKeyPolicy but I don't think I've missed a trick with those?
Thanks in advance - Robert.

A: Try giving the root user all kms permissions - (kms:*)
The principle of least privilege still applies when giving root all access.
That will enable IAM User permissions.
Add additional policies to each role or user or user group.
Add a policy for key administration.
Add a policy for usage.
That is where you can fine tune your access.
Try working with this key policy and tweak it.
This is a key I use for RDS encryption in a cfn stack.
(Yes!  I know that policies should be applied to user groups, not users directly for best practices... but this is inside a sandbox environment I have access to from 'aCloud guru')
  KeyPolicy:
    Id: key-consolepolicy-3
    Version: "2012-10-17"
    Statement:
      - Sid: Enable IAM User Permissions
        Effect: Allow
        Principal:
          AWS: !Sub "arn:aws:iam::${AWS::AccountId}:root"
        Action: kms:*
        Resource: '*'
      - Sid: Allow access for Key Administrators
        Effect: Allow
        Principal:
          AWS:
            - !Sub "arn:aws:iam::${AWS::AccountId}:role/admin"
            - !Sub "arn:aws:iam::${AWS::AccountId}:user/cloud_user"
        Action:
          - kms:Create*
          - kms:Describe*
          - kms:Enable*
          - kms:List*
          - kms:Put*
          - kms:Update*
          - kms:Revoke*
          - kms:Disable*
          - kms:Get*
          - kms:Delete*
          - kms:TagResource
          - kms:UntagResource
          - kms:ScheduleKeyDeletion
          - kms:CancelKeyDeletion
        Resource: '*'
      - Sid: Allow use of the key
        Effect: Allow
        Principal:
          AWS: !Sub "arn:aws:iam::${AWS::AccountId}:role/aws-service-role/rds.amazonaws.com/AWSServiceRoleForRDS"
        Action:
          - kms:Encrypt
          - kms:Decrypt
          - kms:ReEncrypt*
          - kms:GenerateDataKey*
          - kms:DescribeKey
        Resource: '*'
      - Sid: Allow attachment of persistent resources
        Effect: Allow
        Principal:
          AWS: !Sub "arn:aws:iam::${AWS::AccountId}:role/aws-service-role/rds.amazonaws.com/AWSServiceRoleForRDS"
        Action:
          - kms:CreateGrant
          - kms:ListGrants
          - kms:RevokeGrant
        Resource: '*'
        Condition:
          Bool:
            kms:GrantIsForAWSResource: "true"


text:
Q: How to set this dynamic range in vba? Here are 3 worksheets.

Case:
I want to sum the days for each person. The result is displayed on worksheet-report.
The days information is stored in worksheet-day. The day is not fixed. The range of the days is dynamic which should be according to
row: that person row in worksheet-day
column :Worksheets("button").Cells(1, 2 ) to Worksheets("button").Cells(2, 2)

For example :
Worksheets("button").Cells(1, 2 ) 'store 3

Worksheets("button").Cells(2, 2 )  'store 5

In column A of worksheet-report ,the sum of day of Peter ,Tom ,Mary should be calculated .The result should be displayed on column B correspondingly .
Then ,their sum of the days should be searched in worksheet-day and add up the total within the range (D:F 'because the value in worksheet("button"))
The result should be :
Peter: 2
Tom:   3
Mary:  3

Lastly,this result displayed on worksheet-report column B correspondingly .

Here is my code:
Sub gg()
row = Worksheets("report").Range("A" & Rows.Count).End(xlUp).row
Row2 = Worksheets("day").Range("A" & Rows.Count).End(xlUp).row
Dim rng As Range  'the range for sum
Dim row999 As Integer 'store the selected row index

For k = 2 To Row2 'check and store appropriate row
    If Worksheets("report").Cells(1, k).Value = Worksheets("day").Cells(1, k).Value Then
        row999 = ActiveCell.row
    End If
Next k

rng = Range(Cells(Worksheets("button").Cells(1, 2), row999), Cells(Worksheets("button").Cells(2, 2), row999))

For j = 2 To row  'do the sum
    Worksheets("report").Cells(2, i) = Application.WorksheetFunction.Sum(rng)
Next j
End Sub

I guess the rng is inaccurate here.
rng = Range(Cells(Worksheets("button").Cells(1, 2), row999), Cells(Worksheets("button").Cells(2, 2), row999))

A: The first parameter passed to Cells is the row, and the second parameter is the column.
You should also qualify which worksheet the range is on.
So your line saying:
rng = Range(Cells(Worksheets("button").Cells(1, 2), row999), Cells(Worksheets("button").Cells(2, 2), row999))

should say
rng = Worksheets("day").Range(Cells(row999, Worksheets("button").Cells(1, 2)), _
                              Cells(row999, Worksheets("button").Cells(2, 2)))

However, you have a lot of other errors in your code.  I believe what you want is:
Sub gg()
    Dim lastrowReport As Long
    Dim lastrowDay As Long
    Dim rowReport As Long
    Dim rowDay As Long
    lastrowReport = Worksheets("report").Range("A" & Rows.Count).End(xlUp).row
    lastrowDay = Worksheets("day").Range("A" & Rows.Count).End(xlUp).row
    Dim rng As Range  'the range for sum

    For rowReport = 2 To lastrowReport ' loop through each of the rows on the report
        For rowDay = 2 To lastrowDay   ' find the entry for this person on the days sheet
            If Worksheets("report").Cells(rowReport, 1).Value = Worksheets("day").Cells(rowDay, 1).Value Then
                set rng = Worksheets("day").Range(Worksheets("day").Cells(rowDay, Worksheets("button").Cells(1, 2)), _
                                                  Worksheets("day").Cells(rowDay, Worksheets("button").Cells(2, 2)))
                Worksheets("report").Cells(rowReport, 2) = Application.WorksheetFunction.Sum(rng)
                Exit For
            End If
        Next
    Next

End Sub

A: The problem that you are having is that the names do not match.  Tom is uppercase on Report and lower case on day.  Mary has an extra space on the Day worksheet "mary ".
Try to use shorter variable names when possible so that you can read each line of code without having to scan back and forth with your eyes.
Sub ProcessDays()
    Dim day1 As Integer, day2 As Integer
    Dim i As Integer, j As Integer
    Dim name1 As String, name2 As String

    With Worksheets("button")
        day1 = .Cells(1, 2)
        day2 = .Cells(2, 2)
    End With

    With Worksheets("day")

        For i = 2 To Worksheets("report").Range("A" & Rows.Count).End(xlUp).Row
            For j = 2 To .Range("A" & Rows.Count).End(xlUp).Row
                name1 = UCase(Trim(Worksheets("report").Cells(i, 1)))
                name2 = UCase(Trim(.Cells(j, 1)))

                If name1 = name2 Then

                    Set rng = .Range(.Cells(j, day1), .Cells(j, day2))

                    Worksheets("report").Cells(i, 2) = WorksheetFunction.Sum(rng)

                End If
            Next
        Next

    End With

End Sub


text:
Q: How to write instant queries in prometheus adapter to get custom metric value from prometheus operator? I want to continuously monitor a custom metric(of metricType Gauge) implemented in java usinf prometheus and autoscale the kubernetes pod based on that value. The value is exposed in the prometheus dashboard and I can able to access in the rest - http://localhost:9090/api/v1/query?query= . The tutorials are available only for series query (for prometheus adapter) and I want to implement instant query in prometheus adapter to monitor this metric, because if I use series query, I get a custom metric value in milli"s instead of integers. Current prometheus-adapter.yaml configuration.
rules:
  default: false
  custom:
  - seriesQuery: '{__name__=~"<custom-metric>"}'
    resources: { template: "<<.Resource>>" }
    name:
      matches: "custom-metric"
      as: "custom-metric"
prometheus:
  url: http://prom-demo-prometheus-opera-prometheus<namespace>
  port: port

Can anyone let me know how to implement this?
Thanks in advance!


text:
Q: How to create a single table from multiple tables on Google Sheets? I want to combine a large number of tables from different tabs into a master table in a new tab, and calculate the number of rows from each source table.
The tables contain the same table structure

Consider the following inputs -
Table A (in Sheet1)      Table B (in Sheet2)   Table C (in Sheet3)
----------------         -------------         -------------
a11 a12 a13              b11 b12 b13           c11 c12 c13
a21 a22 a23              b21 b22 b23
a31 a32 a33

- Value a11 is in cell 'Sheet1!A2' and value b11 is in cell 'Sheet2!A2' and so on
- All rows below Table A,B,C are empty

I would like resultant tables like this -
Result Table 1           Result Table 2
---------------          ---------------
a11 a12 a13              Sheet1 3
a21 a22 a23              Sheet2 2
a31 a32 a33              Sheet3 1
b11 b12 b13
b21 b22 b23
c11 c12 c13

I have around 30 input tables in 30 sheets that are updated daily.
Any Sheets formula or script that can create the master table?

A: A simple Google search would direct you to something like this. Adjusting that to your usecase would result in something like the code below:
={RANGE_SHEET_1; RANGE_SHEET_2; RANGE_SHEET_3}

Same goes for the amount of rows in a sheet


text:
Q: Proguard Obfuscation causing dex compliation to throw Exceptions I have an android app that I am only trying to obfuscate with Proguard(hence, I have the -dontoptimize -dontshrink -dontpreverify flags). When I build with Proguard, proguard itself does not throw any errors, but then dex throws the following exception:
Exception in thread "pool-1-thread-1" com.android.dx.cf.code.SimException: com.android.dx.rop.cst.CstMethodRef cannot be cast to com.android.dx.rop.cst.CstInterfaceMethodRef
at com.android.dx.cf.code.BytecodeArray.parseInstruction(BytecodeArray.java:810)
...
at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.ClassCastException: com.android.dx.rop.cst.CstMethodRef cannot be     cast to com.android.dx.rop.cst.CstInterfaceMethodRef

and the app crashes immediately from a NullPointerException.
I'm building in Android Studio, with the latest version of Proguard, on the default proguard file and some additional -keep options and -dontwarn options. Any ideas what is causing this? Thanks!

A: I hit a similar problemin Android Studio.  It struck when doing the 'dex' to convert an external Jar to dalvik:
Error:Android Pre Dex: [SOX.jar]
com.android.dx.rop.cst.CstInterfaceMethodRef cannot
be cast to com.android.dx.rop.cst.CstMethodRef

and then some obscure references to strings being processed.  Upgraded everything to no avail.
I eventually figured out that one of the methods being called to do some minor string processing had been placed in an interface.  Which worked happily for mainstream java, but evidently not for dex.  When the method was moved out of the interface and back into one of the many classes, dex did not barf.
My suggestion would then be to carefully review the code looking for newer or advanced language features that dex might barf on.  Not a lot of help, I know, this bug stalled all my android development for 2 months.

A: This can occur if you are using java 1.8+ level API in Android Studio and/or:

*

*building with an incompatible gradle configuration (sourceVersion/targetVersion are invalid)

*building using 1.8 API that isn't currently available on Android

*you're using illegal class-casts or reflection that may not be detected before dex time (unresolved as of this posting)

You can substitute 1.7 and 1.8 for "older" and "newer", the exact API version shouldn't really matter.
I suggest stripping out libraries and suspect code until you get a successful build. In my case, it was casting to a class like this:
Class<E> klass = (Class<E>) Class.forname(...).asSubclass(...) ... ;

Which built fine (with an occasional warning--another bug), but threw the obscure error you are receiving at dex time. Removing it solved the issue.
I also noticed that switching the language level down a version and then back (1.8 -> 1.7 -> 1.8) and applying and exiting the settings after each change generated a set of new warnings that were previously missing.


text:
Q: Find rows with like in oracle I am trying to write a procedure that would find a record with the matched LIKE keyword, this is what i've got:
CREATE OR REPLACE procedure proc_search_tracks_name(q IN tracks.track_name%TYPE)
AS
results tracks%rowtype;
BEGIN
  SELECT * INTO results FROM tracks WHERE track_name LIKE '%' + q + '%';
  dbms_output.put_line(results.track_id || ' ' || results.track_name);
END proc_search_tracks_name;

/
declare
Begin
 proc_search_tracks_name('Love');
end;
/

But for some reason i get the ORA-01722: invalid number error, what am i doing wrong?

A: You are using SQL Server syntax for concatenating strings.  Try this:
SELECT * INTO results FROM tracks WHERE track_name LIKE '%' || q || '%';

If you have multiple rows, then you have a problem with into.  You can limit it to one row.
I think this will work
SELECT * INTO results FROM tracks WHERE track_name LIKE '%' || q || '%' WHERE rownum = 1;


text:
Q: Can I create default types for missing template member types? If I have an algorithm with template parameters, something like
struct DemoParameters
{
    typedef float Price;
    typedef std :: list <Price> Prices;
}

template <typename Parameters>
void foo (int arg)
{
    typename Parameters :: Prices prices = ...;
    // blah
}

foo <DemoParameters> (123);

Is there a way I can write foo so that if something is missing from Parameters I can supply a default. For example
struct PartialParameters
{
     typedef float Price;
     // Prices is missing
}

template <typename Parameters>
void foo (int arg)
{
    Prices_type<Parameters>::type prices = ...;
}

foo<DemoParameters>    (123); // will use list<Price>
foo<PartialParameters> (123); // will use vector<Price>

Where Prices_type<Parameters>::type is Parameters::Prices if Prices is a member of Parameters, or std::vector<Parameters::Price> otherwise.
Is this possible?

A: This is named SFINAE :
#include <iostream>

struct Foo {
    using Type = int;
};
struct Bar {
};

template <typename T, typename Default >
struct TypeOrDefault {
    template <typename U>
    static auto call( int ) -> typename U::Type;

    template <typename U>
    static auto call(...) -> Default;

    using type = decltype( call<T>( 1 ) );
};

int main() {
    std::cout << std::is_same<int,typename TypeOrDefault<Foo,float>::type > ::value << std::endl;
    std::cout << std::is_same<int,typename TypeOrDefault<Bar,float>::type > ::value << std::endl;
}

The example above give to the type type member of TypeOrDefault int for Foo and float for Bar.
you can also simplify the syntax on use with a template alias.
template < typename T, typename Default >
using TypeOrDefaultType = typename TypeOrDefault<T,Default>::type;

then
int main() {
        std::cout << std::is_same<int,TypeOrDefaultType<Foo,float> > ::value << std::endl;
        std::cout << std::is_same<int,TypeOrDefaultType<Bar,float> > ::value << std::endl;
    }

A: You may do something like this (Tag dispatching and SFINAE):
template <typename T> struct has_Prices
{
private:
    template <typename U> static std::uint8_t check(typename U::Prices*);
    template <typename U> static std::uint16_t check(...);
public:
    static const bool value = sizeof(check<T>(0)) == sizeof(std::uint8_t);
};

template <typename T, bool = has_Prices<T>::value> struct Prices_type;

template <typename T>
struct Prices_type<T, true>
{
    typedef typename T::Prices type;
};

template <typename T, bool>
struct Prices_type
{
    typedef std::vector<typename T::Price> type;
};

Test it:
struct DemoParameters
{
    typedef float Price;
    typedef std :: list <Price> Prices;
};

struct PartialParameters
{
     typedef float Price;
     // Prices is missing
};

static_assert(std::is_same<std::list<float>, Prices_type<DemoParameters>::type>::value, "");
static_assert(std::is_same<std::vector<float>, Prices_type<PartialParameters>::type>::value, "");


text:
Q: Types of Mathematical "Sameness" What types of mathematical "sameness" do we have?
From what I've gathered (through studies / this afternoon):

*

*Equality between numbers or sets (meaning $A\subset B \;\&\; B\subset A$)

*Homeomorphism between topological spaces (preserving topological properties)

*Homomorphism between two algebraic structures, preserving their respective properties

*Isomorphism in algebra, a bijective homomorphism (related question)

*Graph isomorphism (added separately because of its importance in graph theory, unlike in abstract algebra)

*Congruence in algebra (e.g. $a \equiv b \; (\text{mod } n)$)

*Same cardinality of sets when there exists a bijection between them

*Congruence (geometry) if one object can be translated into another through an isometry
I am aware that this question might be vague, ill-defined, or too broad since I am asking about objects which I do not yet perhaps know. There might be too many, it might not be clear whether two types are different in the light of this question. I'd simply like to learn more and clarify my existing knowledge. (Also, Math.SE community often gives excellent and eye-opening answers to sometimes even very confused questions - as long as the confusion does not only stem from lack of effort)
Thank you.
Note: I chose the odd title deliberately as to not to hint towards some more mathematical  meaning (e.g. equality).

A: Geometry has lots of notions of sameness.
Euclidean geometry says two things are the "same" if they are congruent.
Affine geometry says two things are the same if there is an affine transformation between them. (An affine transformation is the sort of "shearing" operation that converts a rectangle to a parallelogram, or a dilation, or an isometry, or a combination of those.) All triangles are affine-congruent. All ellipses are affine-congruent. Lengths are not preserved by affine transformations, but midpoints and collinearity are.
Projective geometry says two things are the same if there is a projective transformation between them. All conic sections are projective-congruent. All quadrilaterals are projective-congruent, IIRC.
This is basically the Kleinian view of geometry, which I learned from this textbook.

A: The notion of computational indistinguishability, whereby two objects are considered "the same" if no efficient (i.e., polynomial-time) algorithm can tell them apart, is central to modern cryptography. (The formal definition involves families of random variables and is a bit messy, this is something most if not all beginners in cryptography struggle with.)
In general, being able to distiguish the two objects under consideration results in "breaking" the proposed cryptographic system, but it is unreasonable to require that this be absolutely impossible because it would result in the impossibility of constructing a practical system satisfying the desired properties (or even of constructing such a system at all). Hence, by merely requiring them to be computationally indistinguishable (as opposed to identical), we accept that it could be possible for an adversary to break the system as long as the computational cost of doing so is (believed to be) sufficiently high to be out of reach of any physical entity. On the other hand, it allows for systems sufficiently practical to be used in practice, as we know them today.

A: This could be quite an open-ended question.
On the other hand, in the sense that "sameness" can often be expressed as an equivalence relation, we might consider various different kinds of "sameness" the "same".
But perhaps we can just each contribute one or two examples to the list and call that an "answer"?
There are at least two versions of the integral and differential calculus: standard analysis and non-standard analysis.
An application of the transfer principle relates these two kinds of analysis, showing that they are in some sense "the same"
despite their obvious (and formerly very controversial) differences.


text:
Q: Post-Production Model Monitoring? I am interested in model monitoring techniques. To be clear, for production of a statistical model, let's say GLM, with a set of covariates (continuous). The model will go into production (live scoring of data) soon.
I have used PSI in the past, with some success. It is at a high level. I have been thinking about using something more granular, perhaps control charts for the predictors. Is that the right approach?


text:
Q: model an abstract base class and subclasses in a database I have 4 subclasses: Video, Image, Note, and Form. Each one contains different types of data. For example, the Image class contains a path to the image file on disk and image properties, and the Form class contains the form field values. The common element between each item, however, is the GPS coordinates and heading, so I have the following abstract base class:
public abstract class Content
{
    public float? Latitude { get; set; }
    public float? Longitude { get; set; }
    public float? Heading { get; set; }
}

However, where I get hazy is on how to model this in a database. Currently I have a table called Events (for the sake of example, let's say an event is a birthday party) and 4 tables (Videos, Images, Notes, and Forms). Each table has a foreign key linking back to Events' primary key.
Using LINQ-to-SQL, I get 5 classes for each table. This is fine if I only want one type of data, for example Event.Images, but what I want to do is count the total number of 'contents' an Event has and get the GPS coordinates. I can wing the count easy enough by just using Event.Images.Count() + Event.Videos.Count() + ..., but I can't do the same for the GPS coordinates. Is there some way I can model the database so that I can use a base class for every item and still be able to get the individual strongly-typed item when I need to see its data?

A: There are three different patterns for this documented in Martin Fowler's Patterns of Enterprise Application Architecture, each with different trade-offs:

*

*Single Table Inheritance

*Class Table Inheritance

*Concrete Table Inheritance

A: That is one way to do it.
Generally speaking, there are two other ways:

*

*table per sub-class: instead of trying to share the baseclass in the database, just create separate tables for each one.

*table per hierarchy: put a superset of all the fields into a table, as well as a "discriminator" column, and store them in one place.
To figure out which is right, think about the usage patterns:

*

*if you generally treat them independently, and query independently, separate tables are a good way to go-- either what you have or table per subclass.

*if these are treated as heterogeneous collections, so you want to look at them as such, a single table can be easier

Also see what your tool supports most naturally. They all work.

A: Actually, this exact question gets asked an awful lot, and has been answered many times.  You probably have not searched using database terminology.
The problem is applying OO terminology and thinking in a non-object subject area; making an ordinary straight-forward task very complex and limited.
Martin Fowler's and Scott Ambler's books are not worth a dollar for the lot of them, details in this answer, starting at the 11 Dec 10 entry.


text:
Q: How to block the specific websites using proxy server? I need to block the social networking sites like facebook, twitter, etc within my office network. I tried some proxy server and enabled settings in browser like giving IP and port number. It works but any one can disable the settings easily in the browser, and have easy access.
How do I setup a proxy server to prevent non-administrative users to access these sites?


text:
Q: Nginx proxy pass EKS cluster I have a react app deployed in ingress-nginx service. My react app is wrapped in nginx with the following configuration
server {
  listen 80;

  gzip on;

  root /usr/share/nginx/html;
  index index.html index.html;

  location / {
    try_files $uri $uri/ /index.html;
  }

  location /api {
    rewrite /api/(.*) /$1 break;
    proxy_pass http://backend-app:80;
  }
}

I am using the proxy pass to connect to my backend as it does require this according to setup. My ingress setup is as follow
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: example-app-ingress
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/enable-access-log: "true"
    nginx.ingress.kubernetes.io/enable-cors: "true"
    nginx.ingress.kubernetes.io/http2-push-preload: "true"
    nginx.ingress.kubernetes.io/enable-owasp-core-rules: "true"
    ingress.kubernetes.io/force-ssl-redirect: "true"
    acme.cert-manager.io/http01-edit-in-place: "true"

spec:
  rules:
    - host: example.co
      http:
        paths:
          - path: /
            backend:
              serviceName: example-app
              servicePort: 80
    - host: "*.example.co"
      http:
        paths:
          - path: /
            backend:
              serviceName: example-app
              servicePort: 80
    - host: api.example.co
      http:
        paths:
          - path: /
            backend:
              serviceName: backend-app
              servicePort: 80

My backend-app is reachable, however, but my react app Nginx cannot proxy pass to the backend… This does work in minikube but not working in eks


text:
Q: Hyperledger Composer nodes I am new to Hyperledger and would like to build a proof-of-concept using Hyperledger Composer. I know Composer is a toolset to build Blockchain-Applications, which can be deployed on Hyperledger Fabric.
Still, I don't really understand the structure of Hyperledger Composer, so I have the following questions:

*

*Am I building an actual Blockchain using Hyperledger Composer or is it just simulated?

*Who are the peers or nodes using Composer? Are there several or just one and how can I choose them?

*I know Fabric uses several consensus mechanisms. As I can't define them using Composer what is the used consensus mechanism? Am I defining them using the Access Control?

I am sorry if the questions may seem stupid but I am new in this field and can't find the answers online.

A: No, you're not building a blockchain. The blockchain is created using Fabric. You're just developing and deploying your chaincode to the Fabric-based blockchain. Same for nodes and the consensus.
However, the blockchain is simulated when you run your Composer tests.

A: *

*You are basically defining and developing a blockchain network with composer. The bna file that is created with composer can be deployed locally or in a production environment (atleast that's the plan, not sure if composer is actually there yet because there's still not a v1 for composer)

*When you deploy a bna file locally, you're deploying your blockchain network onto docker containers in your local machine. You can run the ./startFabric.sh script and then do a docker ps  this will list your docker containers and what their purpose is (e.g peer, orderer etc). There are no peers or orderers in composer itself. That is all on fabric.

*Fabric uses the ordering service to maintain consensus. The ordering service is responsible for checking access control rules, cryptographic material, identities, consensus etc. If your environment has only 1 orderer then there isn't much to worry about consensus. But if you have more than 1 orderer then there are going to be issues. To solve these issues, and mantain consensus, an apache kafka implementation is used on the ordering service which basically distributes the requests across different orderers.

A: I would recommend following the tutorials for a hyperledger fabric's first network as Composer is very restrictive when it comes to customizing the network structure (ie adding more nodes and/or organisations)
Composer is good for writing up quick smart contracts and connecting it to an app for a demo as it is easy to test and generates an API for the chain code.
When running a Composer locally, it will run the 2 organisation 2 peer network outlined in fabric first network tutorial. It will then install the chain code you have written and generate an API for it.
As for your last point about the consensus mechanism I'm not to sure.


text:
Q: Magento 2. Custom text in place of Price is not working Properly In custom module I hide the Price and in the place of Price I tried to show Custom text it work perfectly but in some Categories it shows the custom text twice e.g men, Women. I can show the details in image and also going to upload the code as well thanks in Advance
In other categories it shows the "For any Quaries Contact US" only once as you can see in the image.

but in "Men" and "Women" categories they show it twice as you guys can see it in image now my code is

PME\Hideprice\Plugin

<?php

namespace PME\Hideprice\Plugin;

use PME\Hideprice\Helper\Data as Helper;

    class Price
    {

        public function __construct (
            Helper $helper,
            array $data = []
        ) {
                $this->helper = $helper;
        }

        function afterToHtml(\Magento\Catalog\Pricing\Render\FinalPriceBox $subject, $result) {
            // echo $this->helper->isCustomerLoggedIn(); exit;
            if($this->helper->getIsEnable())
            {
                if(!$this->helper->isCustomerLoggedIn())
                {
                    return "
For any Quaries Contact Us
";
                }
            }
            return $result;
        }

    }

etc\di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">

        <type name="Magento\Catalog\Pricing\Render\FinalPriceBox">
            <plugin name="price_hide" type="PME\Hideprice\Plugin\Price"/>
        </type>

</config>

A: Twice price issue of Configurable product like "Men" and "Women" categories. You want to hide price for guest user. Use below example it's working for me.

File path: magento/app/code/PME/Hideprice/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'PME_Hideprice',
    __DIR__
);

File path: magento/app/code/PME/Hideprice/etc/di.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Catalog\Pricing\Render\FinalPriceBox"
        type="PME\Hideprice\Pricing\Render\FinalPriceBox" />
    <preference for="Magento\ConfigurableProduct\Pricing\Render\FinalPriceBox"
        type="PME\Hideprice\Pricing\Render\FinalPriceBox" />
</config>

File path: magento/app/code/PME/Hideprice/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="PME_Hideprice" setup_version="1.0.0"/>
</config>

File path:
  magento/app/code/PME/Hideprice/Pricing/Render/FinalPriceBox.php

<?php
namespace PME\Hideprice\Pricing\Render;

use Magento\Catalog\Pricing\Price;
use Magento\Framework\Pricing\Render;
use Magento\Framework\Pricing\Render\PriceBox as BasePriceBox;
use Magento\Msrp\Pricing\Price\MsrpPrice;

class FinalPriceBox extends \Magento\Catalog\Pricing\Render\FinalPriceBox
{
    protected function wrapResult($html)
    {
     $result = '';
     $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
     $httpContext=$objectManager->get('Magento\Framework\App\Http\Context');
     $isLoggedIn = $httpContext->getValue(\Magento\Customer\Model\Context::CONTEXT_AUTH);

     if($isLoggedIn){
       $result = '
getData('css_classes') . '" ' .
        'data-role="priceBox" ' .
        'data-product-id="' . $this->getSaleableItem()->getId() . '"' .
        '>' . $html . '
';
     }else{
        $result = "
For any Quaries Contact Us
";
     }
    return $result;
    }

}

Hope it help!


text:
Q: Understanding Borel Sets- 2 What would be an example of a $\sigma$-algebra on some sample space $\Omega$ that is not the smallest $\sigma$-algebra on that space?
This is an extension of the question at Understanding Borel sets. I would've posted in the comments but I don't have the rep to do so.

A: For any space $X$, $\{\emptyset, X\}$ will be the smallest sigma algeba on $X$. So choose any other non-trivial sigma algebra, and it's not the smallest. For instance, the Borel sigma algebra on $\mathbb{R}$ is not the smallest sigma algebra on $\mathbb{R}$.
Your question seems to be asking what is meant by the smallest sigma algebra containing some specified collection of sets, though. Say we want a sigma algebra $\mathcal{F}$ on $X$ that contains all the sets in some collection $\mathcal{A}$ of subsets of $X$. Given any two sigma algebras $\mathcal{F}_1$ and $\mathcal{F}_2$ on $X$ such that $\mathcal{A}\subseteq \mathcal{F}_1$ and $\mathcal{A}\subseteq \mathcal{F}_2$, $\mathcal{F}_1\cap \mathcal{F}_2$ is also a sigma algebra on $X$ that contains $\mathcal{A}$ (check this!). So
$$\mathcal{F}:=\bigcap_{\text{sigma algebras } \mathcal{G}\supseteq\mathcal{A}} \mathcal{G}$$
is a sigma algebra on $X$ containing $\mathcal{A}$, and it is the smallest such. Why the smallest? Well if $\mathcal{F}'$ is any other such sigma algebra, it is one of the sigma algebras in the intersection defining $\mathcal{F}$, so $\mathcal{F}\subseteq \mathcal{F}'$.
As an exercise, you can convince yourself that the smallest sigma algebra on $X=[0,1]$ containing $[0,\frac{1}{2}]$ is $\mathcal{F}=\{\emptyset,[0,1],[0,\frac{1}{2}],(\frac{1}{2},1]\}$.

A: Start with a set $X \subset \mathbb{R}$ that is not a Borel set, and consider the $\sigma$-algebra it generates. The result is (by definition) a $\sigma$-algebra, but because it contains a set that is not Borel it cannot be the smallest.


text:
Q: Why jsonb-functions does not work on update when column is null? I have a table with a jsonb column, where the column default value is null. Now when I try to update this column with data first time using jsonb_set or jsonb_insert I get UPDATE 1 as a result but actually, the column stays null.
I made little test-case:
CREATE SCHEMA test;
CREATE TABLE test.books (
  book_id serial NOT NULL,
  data jsonb
);

INSERT INTO test.books (data) VALUES (null);
INSERT INTO test.books (data) VALUES ('{}');

Now I update both new records:
UPDATE test.books SET data = jsonb_set( data, '{zzz}', 'true', true) WHERE book_id = 1;
UPDATE test.books SET data = jsonb_set( data, '{zzz}', 'true', true) WHERE book_id = 2;

And result:
# select * from test.books;
 book_id |                data
---------+------------------------------------
       2 | {"zzz": true}
       1 |
(2 rows)

Even when the update yielded the same result for both updates, the first row remained untouched.
I looked into documentation but found nothing about such behavior. Why it does not work this way?
I am using Postgres 9.6

A: This is because jsonb_set() is defined as strict which means if any input parameter is null the result is null.
You will need to use coalesce() in your call to jsonb_set:
UPDATE books
   SET data = jsonb_set( coalesce(data, '{}'), '{zzz}', 'true', true)
WHERE book_id = 1;

Note that this is true for any of the parameters of the function.So jsonb_set(data, '{zzz}', null, true) would also yield null even if data is not null.

A: What worked for me to set a native JSON value of null within a JSONB variable was the following:
IF condition = 1 THEN
    response = jsonb_set(
                    jsonb_in => response::jsonb,
                    path => ('{response, data, my_key')::text[],
                    replacement => 'null'::jsonb,
                    create_if_missing => true
                );
END IF;


text:
Q: How to use OnBehalfOfContentOwner field while using youtube data API insert request? Context :
I am trying to upload videos to a youtube channel(Other-Y) linked to a google cloud project(say X).
I am not the owner of the channel. However, I have the manager access. I have client secret keys with me.
Steps followed :

*

*Generate refresh token using these gcp secret keys and with my own personal email(this email is linked to the gcp account).I am using oauth credentials.

*Now, while uploading, the video is getting uploaded to my own personal channel and not to the channel I am managing.

I have read about the OnBehalfOfContentOwner field and am trying to use that.
Questions :

*

*Is this upload possible using OnBehalfOfContentOwner field ?

*If yes, is there a way to know the exact value to be passed here ? Should it be user id of the channel owner in the youtube UI ?

Also, please let me know if there are any specific golang references for the same.
Thanks !


text:
Q: Simple model for friction in a pivot joint Consider a pendulum that is attached to its pivot point using a hinge or ball bearing joint. What is a simple but reasonable approximation for modelling friction in that joint?
Background: I'm deriving the equations of motion for the cart and pole system, whereby an inverted pendulum attached to a cart is maintained in an upright position by an external force that pushes the cart left-right accordingly. In existing research papers I have looked at which model this system with friction, the pivot joint friction is given as a function of angular velocity. This doesn't seem to correspond with the notion of rotational friction being the result of dry/sliding Coulomb friction within the joint - which would result in hinge friction being a function of the force being applied at the joint (and the coefficient of friction).
Assume the system is within a vacuum (the cart friction term I have seen in the literature is modelled with dry sliding friction only, so I want to maintain consistency with that choice).

A: you can use this equation for a friction torque in a spherical joint.
$$\tau_\mu=-\text{signum}( \dot{\theta})\,\mu\,|F_N|\,R$$
where
$\tau_\mu$ is the friction torque
$\mu$ friction coefficient
$F_N$ normal joint force
$R$ Joint radius
the "signum"  function is necessary, because the friction torque must operate always opposite to the angular velocity
Example Pendulum

for a pendulum is the normal force $F_N= m\,\left[\dot{\theta}^2+g\,\cos(\theta)\right]$
the equation of motions:
$$\ddot{\theta}+\frac{g}{L}\,\sin(\theta)-\tau_\mu=0$$
simulation results:


text:
Q: import com.android.build.OutputFile error in react-native First I run a new project
react-native init AwesomeProject --version 0.58.6

(0.59.1 has a bug, but I test this problrm with it)
with react-native run-android I can run it.
In android studio when I sync it, I get an error:
app/build.gradle:
import com.android.build.OutputFile

Error: Cannot resolve symbol 'build'

I use these versions:
ext {
    buildToolsVersion = "28.0.3"
    minSdkVersion = 16
    compileSdkVersion = 28
    targetSdkVersion = 27
    supportLibVersion = "28.0.0"
}
repositories {
    google()
    jcenter()
}
dependencies {
    classpath 'com.android.tools.build:gradle:3.2.1'

    // NOTE: Do not place your application dependencies here; they belong
    // in the individual module build.gradle files
}

A: I think in android studio you can import only android part.
Goto:  File -> Open -> choose the project -> select folder with name android.
Link given here
It worked for me.

A: Before running this command
react-native init AwesomeProject --version 0.58.6

Did you add the following to your System environmental variables ?
(1) ANDROID_HOME environment variable and
(2) platform-tools to Path
If not, make sure you add them. I have resolved this error by adding all necessary paths to my system environment variables as shown in the Images below and then I created a whole new project without any errors.
adding ANDROID_HOME environment variable:

adding platform-tools to Path:

Also check out this link :
https://reactnative.dev/docs/0.60/enviroment-setup
Make sure that you have installed all necessary packages and added all necessary paths as mentioned in this link.


text:
Q: Unable to merge dex Android - Studio 3.0 build error What I want to know
I have got the error to build my project after updating my Android Studio 3.0. This error said the Lorg/objectweb/asm/AnnotationWriter is duplicated. So I assume that I have to exclude the dependencies for the grade but I don't know how to find the library that uses this AnnotationWriter.
compile('com.googlecode.json-simple:json-simple:1.1.1') {
    exclude group: 'org.hamcrest', module: 'hamcrest-core'
}

I understand that there are several same posts on the StackOverflow but I still need help even though I tried almost everything that everyone commented.
Thank you.
This is what I tried

*

*Build -> Clean Project.

*Adding multiDexEnabled true(It's already added from the previous version)

*Update the compileSdkVersion, compileSdkVersion and supportLibVersion to 26

*Deleting .gradle and build folder then clean and Rebuild

*Updating Google Play Services to latest version(46)

*Added jumboMode true to dexOption in the gradle file.

*Replace complie to implementation, testCompiple to testImplementation and testImplementation to androidTestImplementation
Stack Trace
14:57:28.124 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]
14:57:28.124 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] FAILURE: Build failed with an exception.
14:57:28.124 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]
14:57:28.124 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] * What went wrong:
14:57:28.124 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
14:57:28.124 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] > com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
14:57:28.124 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]
14:57:28.124 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] * Exception is:
14:57:28.124 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.
14:57:28.124 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:100)
14:57:28.124 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:70)
14:57:28.124 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:63)
14:57:28.124 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.tasks.execution.ResolveTaskOutputCachingStateExecuter.execute(ResolveTaskOutputCachingStateExecuter.java:54)
14:57:28.125 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
14:57:28.125 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:88)
14:57:28.125 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.tasks.execution.ResolveTaskArtifactStateTaskExecuter.execute(ResolveTaskArtifactStateTaskExecuter.java:52)
14:57:28.125 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
14:57:28.125 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:54)
14:57:28.125 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
14:57:28.125 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:34)
14:57:28.125 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker$1.run(DefaultTaskGraphExecuter.java:248)
14:57:28.125 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
14:57:28.125 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
14:57:28.125 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
14:57:28.125 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
14:57:28.126 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:241)
14:57:28.126 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter$EventFiringTaskWorker.execute(DefaultTaskGraphExecuter.java:230)
14:57:28.126 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.processTask(DefaultTaskPlanExecutor.java:124)
14:57:28.126 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.access$200(DefaultTaskPlanExecutor.java:80)
14:57:28.126 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:105)
14:57:28.126 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker$1.execute(DefaultTaskPlanExecutor.java:99)
14:57:28.126 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.execute(DefaultTaskExecutionPlan.java:625)
14:57:28.126 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.execution.taskgraph.DefaultTaskExecutionPlan.executeWithTask(DefaultTaskExecutionPlan.java:580)
14:57:28.126 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$TaskExecutorWorker.run(DefaultTaskPlanExecutor.java:99)
14:57:28.126 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:63)
14:57:28.126 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:46)
14:57:28.126 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:55)
14:57:28.126 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] Caused by: java.lang.RuntimeException: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
14:57:28.126 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.builder.dexing.DxDexArchiveMerger.mergeMultidex(DxDexArchiveMerger.java:266)
14:57:28.126 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.builder.dexing.DxDexArchiveMerger.mergeDexArchives(DxDexArchiveMerger.java:133)
14:57:28.126 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.build.gradle.internal.transforms.DexMergerTransformCallable.call(DexMergerTransformCallable.java:97)
14:57:28.126 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.build.gradle.internal.transforms.ExternalLibsMergerTransform.transform(ExternalLibsMergerTransform.kt:121)
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:222)
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.build.gradle.internal.pipeline.TransformTask$2.call(TransformTask.java:218)
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.builder.profile.ThreadRecorder.record(ThreadRecorder.java:102)
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.build.gradle.internal.pipeline.TransformTask.transform(TransformTask.java:213)
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.internal.reflect.JavaMethod.invoke(JavaMethod.java:73)
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$IncrementalTaskAction.doExecute(DefaultTaskClassInfoStore.java:173)
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:134)
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.project.taskfactory.DefaultTaskClassInfoStore$StandardTaskAction.execute(DefaultTaskClassInfoStore.java:121)
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter$1.run(ExecuteActionsTaskExecuter.java:122)
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:336)
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.internal.progress.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:328)
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.internal.progress.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:197)
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.internal.progress.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:107)
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:111)
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:92)
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   ... 27 more
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] Caused by: com.android.builder.dexing.DexArchiveMergerException: Unable to merge dex
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:72)
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:36)
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   ... 46 more
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] Caused by: com.android.dex.DexException: Multiple dex files define Lorg/objectweb/asm/AnnotationWriter;
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:661)
14:57:28.127 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:616)
14:57:28.128 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:598)
14:57:28.128 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:171)
14:57:28.128 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.dx.merge.DexMerger.merge(DexMerger.java:198)
14:57:28.128 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   at com.android.builder.dexing.DexArchiveMergerCallable.call(DexArchiveMergerCallable.java:61)
14:57:28.128 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]   ... 47 more
14:57:28.128 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]
14:57:28.128 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter]
14:57:28.128 [ERROR] [org.gradle.internal.buildevents.BuildExceptionReporter] * Get more help at https://help.gradle.org
14:57:28.128 [ERROR] [org.gradle.internal.buildevents.BuildResultLogger]
14:57:28.128 [ERROR] [org.gradle.internal.buildevents.BuildResultLogger] BUILD FAILED in 3s

Dependencies tree
debugRuntimeClasspath - Resolved configuration for runtime for variant: debug
    +--- org.jacoco:org.jacoco.agent:0.7.4.201502262128
    +--- com.android.support:design:26.0.2
    |    +--- com.android.support:support-v4:26.0.2
    |    |    +--- com.android.support:support-compat:26.0.2
    |    |    |    \--- com.android.support:support-annotations:26.0.2 -> 26.1.0
    |    |    +--- com.android.support:support-media-compat:26.0.2
    |    |    |    +--- com.android.support:support-annotations:26.0.2 -> 26.1.0
    |    |    |    \--- com.android.support:support-compat:26.0.2 (*)
    |    |    +--- com.android.support:support-core-utils:26.0.2
    |    |    |    +--- com.android.support:support-annotations:26.0.2 -> 26.1.0
    |    |    |    \--- com.android.support:support-compat:26.0.2 (*)
    |    |    +--- com.android.support:support-core-ui:26.0.2
    |    |    |    +--- com.android.support:support-annotations:26.0.2 -> 26.1.0
    |    |    |    \--- com.android.support:support-compat:26.0.2 (*)
    |    |    \--- com.android.support:support-fragment:26.0.2
    |    |         +--- com.android.support:support-compat:26.0.2 (*)
    |    |         +--- com.android.support:support-core-ui:26.0.2 (*)
    |    |         \--- com.android.support:support-core-utils:26.0.2 (*)
    |    +--- com.android.support:appcompat-v7:26.0.2
    |    |    +--- com.android.support:support-annotations:26.0.2 -> 26.1.0
    |    |    +--- com.android.support:support-v4:26.0.2 (*)
    |    |    +--- com.android.support:support-vector-drawable:26.0.2
    |    |    |    +--- com.android.support:support-annotations:26.0.2 -> 26.1.0
    |    |    |    \--- com.android.support:support-compat:26.0.2 (*)
    |    |    \--- com.android.support:animated-vector-drawable:26.0.2
    |    |         +--- com.android.support:support-vector-drawable:26.0.2 (*)
    |    |         \--- com.android.support:support-core-ui:26.0.2 (*)
    |    +--- com.android.support:recyclerview-v7:26.0.2
    |    |    +--- com.android.support:support-annotations:26.0.2 -> 26.1.0
    |    |    +--- com.android.support:support-compat:26.0.2 (*)
    |    |    \--- com.android.support:support-core-ui:26.0.2 (*)
    |    \--- com.android.support:transition:26.0.2
    |         +--- com.android.support:support-annotations:26.0.2 -> 26.1.0
    |         \--- com.android.support:support-v4:26.0.2 (*)
    +--- com.android.support:appcompat-v7:26.0.2 (*)
    +--- com.squareup.retrofit2:retrofit:2.3.0
    |    \--- com.squareup.okhttp3:okhttp:3.8.0
    |         \--- com.squareup.okio:okio:1.13.0
    +--- com.squareup.retrofit2:retrofit-mock:2.3.0
    |    \--- com.squareup.retrofit2:retrofit:2.3.0 (*)
    +--- com.squareup.retrofit2:converter-gson:2.3.0
    |    +--- com.squareup.retrofit2:retrofit:2.3.0 (*)
    |    \--- com.google.code.gson:gson:2.7 -> 2.8.2
    +--- com.squareup.retrofit2:adapter-rxjava:2.3.0
    |    +--- com.squareup.retrofit2:retrofit:2.3.0 (*)
    |    \--- io.reactivex:rxjava:1.3.0
    +--- com.squareup.okhttp3:logging-interceptor:3.8.0
    |    \--- com.squareup.okhttp3:okhttp:3.8.0 (*)
    +--- io.reactivex:rxandroid:1.2.1
    |    \--- io.reactivex:rxjava:1.1.6 -> 1.3.0
    +--- io.reactivex:rxjava:1.1.6 -> 1.3.0
    +--- com.trello:rxlifecycle:1.0
    |    +--- io.reactivex:rxjava:1.2.1 -> 1.3.0
    |    \--- com.google.code.findbugs:jsr305:3.0.1
    +--- com.trello:rxlifecycle-android:1.0
    |    +--- com.trello:rxlifecycle:1.0 (*)
    |    \--- com.jakewharton.rxbinding:rxbinding:0.4.0
    |         +--- io.reactivex:rxandroid:1.1.0 -> 1.2.1 (*)
    |         +--- io.reactivex:rxjava:1.1.0 -> 1.3.0
    |         \--- com.android.support:support-annotations:23.1.0 -> 26.1.0
    +--- com.trello:rxlifecycle-components:1.0
    |    +--- com.trello:rxlifecycle-android:1.0 (*)
    |    +--- io.reactivex:rxjava:1.2.1 -> 1.3.0
    |    \--- com.android.support:appcompat-v7:25.0.0 -> 26.0.2 (*)
    +--- com.google.guava:guava:20.0
    +--- com.google.code.gson:gson:2.8.2
    +--- com.jayway.jsonpath:json-path:2.0.0
    |    +--- org.slf4j:slf4j-api:1.7.10
    |    \--- net.minidev:json-smart:2.1.1
    |         \--- net.minidev:asm:1.0.2
    |              \--- asm:asm:3.3.1
    +--- me.dm7.barcodescanner:zxing:1.9.8
    |    +--- me.dm7.barcodescanner:core:1.9.8
    |    |    \--- com.android.support:support-v4:25.3.1 -> 26.0.2 (*)
    |    \--- com.google.zxing:core:3.3.0
    +--- com.twilio:video-android:1.3.4
    |    +--- com.android.support:support-annotations:26.1.0
    |    \--- com.getkeepsafe.relinker:relinker:1.2.2
    +--- com.wang.avi:library:2.1.3
    +--- uk.co.chrisjenx:calligraphy:2.3.0
    |    \--- com.android.support:appcompat-v7:25.3.1 -> 26.0.2 (*)
    +--- com.jakewharton:butterknife:8.8.1
    |    +--- com.jakewharton:butterknife-annotations:8.8.1
    |    |    \--- com.android.support:support-annotations:25.3.0 -> 26.1.0
    |    +--- com.android.support:support-annotations:25.3.0 -> 26.1.0
    |    \--- com.android.support:support-compat:25.3.0 -> 26.0.2 (*)
    +--- com.daimajia.easing:library:2.1
    |    \--- com.android.support:appcompat-v7:25.1.1 -> 26.0.2 (*)
    +--- com.daimajia.androidanimations:library:2.3
    +--- com.microsoft.azure.mobile:mobile-center-analytics:0.12.0
    |    \--- com.microsoft.azure.mobile:mobile-center:0.12.0
    +--- com.microsoft.azure.mobile:mobile-center-crashes:0.12.0
    |    \--- com.microsoft.azure.mobile:mobile-center:0.12.0
    \--- net.danlew:android.joda:2.9.9
         \--- joda-time:joda-time:2.9.9

A: Finally, I figured this out with below.
compile('com.jayway.jsonpath:json-path:2.0.0') {
exclude group: 'net.minidev', module: 'asm'
}


text:
Q: Counting unique elements when some are synonyms of each other I am trying to count the number of unique drugs in this list.
my_drugs=c('a', 'b', 'd', 'h', 'q')

I have the following dictionary,which gives me drug synonyms, but it is not set up so that the definitions are only for unique drugs:
dictionary <- read.table(header=TRUE, text="
  drug   names
  a    b;c;d;x
  x    b;c;q
  r    h;g;f
  l   m;n
")

So in this case, there are 2 unique drugs in the list (because a, either directly or indirectly, has synonyms b,d,q). Synonyms of synonyms count as synonyms.
My attempted approach was to first make a dictionary that only had unique drugs on the left side. To do this, I would cycle through the dictionary$drug, grep in dictionary$drug and dictionary$synonyms, take the union of those and replace drug$synonyms, and then delete the other rows from the dictionary.
bigdf=dictionary

  small_df=data.frame("drug"=NA,"names"=NA)

  for(i in 1:nrow(bigdf)){
    search_term=sprintf("*%s*",bigdf$drug[i])
    index=grep(search_term,bigdf$names)
    list=bigdf$names[index]
    list=Reduce(union,list)
    list=paste(list, collapse=";")

    if(!list==""){

    new_row=data.frame("drug"=bigdf$drug[index][1],"names"=list)
    small_df=rbind(small_df,new_row)
    #small_df
    bigdf=bigdf[-index,]
    #dim(bigdf)

    }
    else{
      new_row=data.frame("drug"=bigdf$drug[index][1],"names"="alreadycounted")
      small_df=rbind(small_df,new_row)
    }
  }

This did not work (some drugs were missing from small_df), and even if it had I'm not sure how I would have used my new dictionary to count the number of unique drugs in my list.
How can I count the number of unique drugs in my_drugs?
Thank you for your help, and let me know if this needs further clarification.
Data Set Size: 200 elements in my_drugs, 2000 rows in dictionary, each drug has 10-12 synonyms.

A: library(igraph)
df1 = unique(data.frame(do.call(
    rbind, apply(X = dictionary,
                 MARGIN = 1,
                 FUN = function(x) t(combn(unlist(strsplit(x, ";")), 2, sort))))))
g = graph.data.frame(df1)
g2 = delete.vertices(g, unique(V(g)$name)[!unique(V(g)$name) %in% my_drugs])
clusters(g2)$no
#[1] 2


text:
Q: Ansible - Create new dict based on matching items in list There is a list:
mylist: ['a_value', 'something_else']

There is a dict:
my_dict:
  a_value:
    something: true
  bar:
    foo: false
  something_else:
    placeholder: true

There is an Ansible task to set a fact for a new dict.
- name: "Create a new dict, when name(s) in the list match the key in the dict"
  set_fact:
    new_dict: "{{ new_dict | default({}) | combine({item.key: item.value}) }}"
  loop:
    - "{{ my_dict | dict2items }}"
    - "{{ my_list }}"
  when: my_list??? item

Q: How would I configure Ansible to create a new dict, when the name(s) match the key in the dict?
In this example, desired output:
new_dict:
  a_value:
    something: true
  something_else:
    placeholder: true

A: You complicated the task by adding my_list in the loop, creating yourself a list of list and making it more complex that it really was.
So, as a first step, you could corrected your logic and do:
- set_fact:
    new_dict: "{{ new_dict | default({}) | combine({item.key: item.value}) }}"
  loop: "{{ my_dict | dict2items }}"
  when: item.key in my_list
  vars:
    my_list: ['a_value', 'something_else']
    my_dict:
      a_value:
        something: true
      bar:
        foo: false
      something_else:
        placeholder: true

- debug:
    var: new_dict

Which gives:
TASK [set_fact] *************************************************************************
ok: [localhost] => (item={'key': 'a_value', 'value': {'something': True}})
skipping: [localhost] => (item={'key': 'bar', 'value': {'foo': False}})
ok: [localhost] => (item={'key': 'something_else', 'value': {'placeholder': True}})

TASK [debug] ****************************************************************************
ok: [localhost] =>
  new_dict:
    a_value:
      something: true
    something_else:
      placeholder: true

This said, there is a way shorter approach, using selectattr.
So, with this one-liner:
- debug:
    var: my_dict | dict2items | selectattr('key', 'in', my_list) | items2dict
  vars:
    my_list: ['a_value', 'something_else']
    my_dict:
      a_value:
        something: true
      bar:
        foo: false
      something_else:
        placeholder: true

We get:
TASK [debug] ****************************************************************************
ok: [localhost] =>
  my_dict | dict2items | selectattr('key', 'in', my_list) | items2dict:
    a_value:
      something: true
    something_else:
      placeholder: true

A: extract the values of the mylist items
from my_dict
  _values: "{{ mylist|map('extract', my_dict) }}"

gives
  _values:
  - something: true
  - placeholder: true

Then create new_dict
  new_dict: "{{ dict(mylist|zip(_values)) }}"

gives
  new_dict:
    a_value:
      something: true
    something_else:
      placeholder: true


text:
Q: Find Pair with Difference less than K with O(n) complexity on average I have an unsorted array of n positive numbers and a parameter k, I need to find out if there is a pair of numbers in the array that the difference between than is less than k and I need to do so in time complexity of O(n) on probable average and in space complexity of O(n).
I believe it requires the use of a universal hash table but I'm not sure how, any ideas?

A: This answer works even on unbounded integers and floats (doing some assumptions on the nicety of the hashmap you'll be using - the java implementation should work for instance):

*

*keep a hashmap<int, float> all_divided_values. For each key y,
if all_divided_values[y] exists, it will contain a value v that
is in the array such that floor(v/k) = y.

*For each value v in the original array A, if v/k is in  all_divided_values's keys, output (v, all_divided_values[v/k])
(they are distant by less than k). Else, store v in
all_divided_values[v/k]

*Once all_divided_values is filled, go through A again. For each v, test whether all_divided_values[v/k - 1] exists, and if so,
output the pair (v, all_divided_values[v/k - 1]) if and only if abs(v-all_divided_values[v/k - 1])<=k
Inserting in a hashmap is usually (with Java hashmap for instance) O(1) in average, so the total time is O(n). But please note that technically this could be false, for instance if your language's implementation does not have a nice strategy about the hashmap.

A: Simple solution:
1- Sort the array
2- Calculate the difference between consecutive elements
a) If the difference is smaller than k return that pair
b) If no consecutive number difference yields a value smaller than k, then your array has no pair of numbers such that the difference is smaller than k.
Sorting is O(nlogn), but if you have only Integers of limited size, you can use Counting sort, that is O(n)

A: You can consider this way.
The problem can be modeled as this:-
consider each element (considering integer) now you convert them to a range (A[i]-K,A[i]+K)
Now you want to check if any of the two intervals overlap.
Interval intersection problem without any sorted ness is not solvable in O(n) (worst case). You need to sort them and then inn O(n) you can check if hey intersect.
Same goes for your logic. Sort it and find it.


text:
Q: Why is $U$ open if and only if $j^{-1}(U \cap A)= j^{-1}(U)$? Suppose $(X, \tau)$ is a topological space and $A \subseteq X$. Suppose $A$ has the initial topology on $A$ with respect to the inclusion function $j: A \to X$.
Now suppose $U$ is open $X$ $\iff$ $j^{-1}(U)$ is open in   $A\iff j^{-1}(U \cap A)= j^{-1}(U)$ is open in $A$
Why we have the second equivalence? The set $U=U \cap A$ are not equal.. Has someone a solution to this question?

A: $j^{-1}(U\cap A)=j^{-1}(U)\cap j^{-1}(A)=j^{-1}(U)\cap A=j^{-1}(U)$.


text:
Q: Model date Range Validator in mvc I use the below url code for date validation in mvc, but it is not showing the error.
"MVC Model Range Validator?"
any help?

A: Your comment in that question says (ErrorMessage="") which will give a blank error message and ergo you will not see a message. delete this statement to use the default or write your own.