2020-10-31

Finding definitions of modules which are parameters

Suppose i have the following code in python:

module dbm_adapter

def insert_in_database():
   doSomething

module B:
import dbm_adapter

def myfunc(dbm_adapater):
LINE 10    dbm_adapter.insert_in_database()

myfunc(dbm_adapter)

When i got line 10 and i click on isnert_in_database, my IDE be it emacs using lsp for example can't find the function. Is it possible to jump to that definition with lsp?



from Recent Questions - Stack Overflow https://ift.tt/3e91Ave
https://ift.tt/eA8V8J

Div Elements Not Showing Properly

I have been having this problem for a couple of weeks now. I have this code

div{
    margin: 0;
    padding: 0;
    border: 5px outset black;
    text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="index.css">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <div>
        <p>testing</p>
    </div>
</body>
</html>

and it is doing this: Weird CSS

I have looked at tutorials, searched on Stack Overflow, and even when I run it in the code snippet, it works. What am I doing wrong!?!?



from Recent Questions - Stack Overflow https://ift.tt/2HGOMAA
https://ift.tt/34IQY39

How to run CSS animation of two keyframes continuously

I would like to run my animation consisting of two keyframes to mimic the motion of a closing garage door, but the animation stops after one execution. Adding animation-iteration-count: 10; just flashes the 'door', doesn't rerun the whole animation. What could be the issue? Thank you in advance!

.house {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 200px;
    height: 150px;
}

.house .front {
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 5.2em;
    height: 4em;
    border-left: 0.5em solid grey;
    border-right: 0.5em solid grey;
}

.house .front .gable {
    position: absolute;
    top: -3.5em;
    left: 50%;
    width: 0;
    height: 0;
    transform: translateX(-50%);
    border-left: 3.1em solid transparent;
    border-right: 3.1em solid transparent;
    border-bottom: 3.5em solid grey;
}

.house .front .door {
    position: absolute;
    bottom: 0;
    left: 50%;
    transform: translateX(-50%);
    width: 4.2em;
    height: 0.4em;
    background: grey;
    border-radius: 2px 2px 0 0;
    overflow: hidden;
}

.house .front .door:before {
    content: '';
    display: block;
    width: 40%;
    height: 100%;
    position: absolute;
    top: 0;
    left: 0;
    background: black;
}

.house .front #d1 {
    transform: translateX(-50%) translateY(-80%);
}

.house .front #d2 {
    transform: translateX(-50%) translateY(-300%);
}

.house .front #d3 {
    transform: translateX(-50%) translateY(-540%);
}

.house .front #d4 {
    transform: translateX(-50%) translateY(-800%);
}

.house .front .doors .door {
    animation-name: hide, up;
    animation-duration: 1.6s;
    animation-timing-function: ease-in;
    animation-iteration-count: 1;
    opacity: 1;
}

.house .front .doors #d4 {
    animation-delay: 0s, 0s;
}

.house .front .doors #d3 {
    animation-delay: 0s, 0.3s;
}

.house .front .doors #d2 {
    animation-delay: 0s, 0.6s;
}

.house .front .doors #d1 {
    animation-delay: 0s, 0.9s;
}

@keyframes hide
{ 
    from { opacity: 0; } to { opacity: 0 }
}
@keyframes up
{ 
    0% { opacity: 0; }
    1% { opacity: 1; }
    100% { opacity: 1; } 
} 
<div class="house">
    <div class="front">
        <div class="gable"></div>
        <div class="doors">
            <div id="d1" class="door"></div>
            <div id="d2" class="door"></div>
            <div id="d3" class="door"></div>
            <div id="d4"class="door"></div>            
        </div>
    </div>
</div>

sorry for this part, but SO wouldn't let me post this question unless more text is added.



from Recent Questions - Stack Overflow https://ift.tt/34KL3uu
https://ift.tt/eA8V8J

Flask: detect calling view and redirect accordingly

In a Flask application I've a template showing a list of short notices to the user. I've enclosed this part in a Blueprint called board. The user can click a link to accept a notice. The application records the acceptance to a database and shows the list of notices with the total number of acceptances updated.

THE PROBLEM: the user can also click a notice to see a detailed view of it. He can accept the notice also in the detailed view. The application records the acceptance and shows the same detailed view updated. I want to manage this view in the same Blueprint since most of the code is in common.

WHAT WORKS FINE:

I've two separate endpoints for notices list acceptance and detailed view acceptance.

  • Here's the template for the list "calling" the accept function:
<p> 
   <a class="action" href="">accept</a> 
</p>

and the code taking care of it:

@bp.route("/<int:id>/accept")
@login_required
def accept(id):

    """ Commit acceptance to dbase (omitted) """

    # Redirect to board.index
    return redirect(url_for("board.index"))
  • Here's the template for the detailed view "calling" the view_accept function:
<p>   
   <a class="action" href="">accept</a> 
</p>

and the code taking care of it:

@bp.route("/<int:id>/detailed/accept")
@login_required
def view_accept(id):

    """ Commit acceptance to dbase (omitted) """
    """ Exactly the same as before """

    # Redirect to board.detailed
    return redirect(url_for("board.detailed", id=id))

THE QUESTION: Can I just use one function detecting which template generated the "call" and redirecting to the correct view? Or is the previous approach the correct one? Do I miss something?

request.path and siblings don't seem to work:

@bp.route("/<int:id>/accept")
@bp.route("/<int:id>/detailed/accept")
@login_required
def accept(id):
    """ ...omitted """

    # request.path / request.url_rule / request.endpoint always give the same route
    # (/<int:id>/detailed/accept) regardless of which view generate the call


    # Redirect to board.index or ("board.detailed", id=id) 

Thanks.



from Recent Questions - Stack Overflow https://ift.tt/3jESJSZ
https://ift.tt/eA8V8J

React/JS How to get the value of last index of props.data which is an object

I have an application that passes array object to a child component and the child component can access the data via "props.data" whose format is as follows:

....

246: {key: 3510, date: "10/27/2020", name: "Canada", total_cases: 222887, cases_today: 2674, …}
247: {key: 3522, date: "10/28/2020", name: "Canada", total_cases: 225586, cases_today: 2699, …}
248: {key: 3540, date: "10/29/2020", name: "Canada", total_cases: 228542, cases_today: 2956, …}
249: {key: 3566, date: "10/30/2020", name: "Canada", total_cases: 231999, cases_today: 3457, …}
length: 250
__proto__: Array(0)

I want to get only the last value of total_cases and it shows an error that it's undefined when I tried "props.data[props.data.length-1].total_cases" Any idea what would cause this error? Thank you for your time!



from Recent Questions - Stack Overflow https://ift.tt/37VJdIZ
https://ift.tt/eA8V8J

Plotting two dataframes into one bar chart, distinguish their values

I am confusing myself with the following task and I hope someone can point me to the right direction. I have two datasets, one with data from January 2019 and another one with data from January 2020.

df1

ID     Date
5177   2019-01-31
5178   2019-01-31
5179   2019-01-31
5180   2019-01-31
5181   2019-01-31
5182   2019-01-31
5183   2019-01-31
5184   2019-01-30
5185   2019-01-30
5186   2019-01-30

df2

ID     Date
2918   2020-01-31
2919   2020-01-31
2920   2020-01-31
2921   2020-01-31
2922   2020-01-31
2923   2020-01-31
2924   2020-01-31
2925   2020-01-31
2926   2020-01-30
2927   2020-01-30

I tried to plot them as line charts as follows:

df1.groupby('Date').size().plot()
df2.groupby('Date').size().plot()

plt.xticks(rotation=90)
plt.show() 

but the output is not good as the results as shown in two different areas of the chart (one is 2019 and another one is 2020). So what I have been trying to do is to plot these data as bar charts, putting bars close to each other I order to easily compare the frequency of data day by day through months.

I have tried as follows:

df1.groupby(['Date'])['Date'].size().plot(kind='bar')
df2.groupby(['Date'])['Date'].size().plot(kind='bar')

but this does not distinguish between values from df1 and values from df2 (also, bars are in the same colour).

What I would like to have is a chart with on the x-axis the date (only days, as months are the same and I know which year I am comparing). With different colour, I would need to plot data from 1 and data from 2 (the legend will tell which df1/2 is).

Can you please tell me how to plot data to get the expected output?

Thanks



from Recent Questions - Stack Overflow https://ift.tt/34J5wQo
https://ift.tt/eA8V8J

TestCafe EC2 Network logs

We are "successfully" running our gherkin-testcafe build on ec2 headless against chromium. The final issue we are dealing with is that at a certain point in the test a CTA button is showing ...loading instead of Add to Bag, presumably because a service call that gets the status of the product, out of stock, in stock, no longer carry, etc. is failing. The tests work locally of course and we have the luxury of debugging locally opening chrome's dev env and inspecting the network calls etc. But all we can do on the ec2 is take a video and see where it fails. Is there a way to view the logs of all the calls being made by testcafe's proxy browser so we can confirm which one is failing and why? We are using.
const rlogger = RequestLogger(/.*/, { logRequestHeaders: true, logResponseHeaders: true });

to log our headers but not getting very explicit reasons why calls are not working.



from Recent Questions - Stack Overflow https://ift.tt/31XkYXb
https://ift.tt/eA8V8J

how to count combinations of 1 and 2 adding to equal x number? in java [closed]

please help I'm new in java there is N floors given, you can jump 1 or 2 floors once the program should be counting the variants of going on N floor



from Recent Questions - Stack Overflow https://ift.tt/37WQUPl
https://ift.tt/eA8V8J

why is drawing a bitmap on a canvas then moving it duplicating it? android, java

I'm trying to update the position of this bitmap, but it keeps duplicating it, then moving it.

private void draw() {
    if (getHolder().getSurface().isValid()) {
        canvas = getHolder().lockCanvas();

        canvas.drawBitmap(backgroundStar.starBitmap, backgroundStar.getCurX(), 
        backgroundStar.getCurY(), paint);

        getHolder().unlockCanvasAndPost(canvas);
    }
}

my update function is called after the draw,

private void update() {
    backgroundStar.setCurY(backgroundStar.getCurY() + backgroundStar.getSpeed());
}

this is the background star constructor, i left out the getters and setters

public BackgroundStar(int curX, int curY, int speed, Resources res) {
    CurX = curX;
    CurY = curY;
    this.speed = speed;

    starBitmap = BitmapFactory.decodeResource(res, R.drawable.star);
    starBitmap = Bitmap.createScaledBitmap(stareBitmap, 20,20, false);
}


from Recent Questions - Stack Overflow https://ift.tt/2JmuPzo
https://ift.tt/eA8V8J

TestCafe loop over elements and check if class exists within Set

I have a table with a column of icons. Each Icon has a class of "test" and then "test" + [some rating]. The rating could be A, B, C, XX, YY. I'd like to select the group of icons and loop over them, pop off the last class (the one with the rating) and then expect that my Set of classConsts contains the class in question. I've done a bunch of research but can only find examples of interacting with each of the elements, I'm not sure what I'm doing wrong when trying to check the classes on each instead. Any help is appreciated, thanks.

The below code blows up when i call mrArray.nth saying it's not a function (sorry its a bit messy, had to change some variable names around)

test('Sers are verified', async t => {
    const IconArr = Selector('#testtable .test');
    var count = await IconArr().count;
    var myArray = await IconArr();

    const classConsts = ["testClassA", "testClassB", "testClassC", "testClassXX", "testClassYY"]

    let mySet = new Set(classConsts);

    for(let i = 1; i <= count; i++){
        mySet.has(myArray.nth(i).classNames.pop());
        await t.expect(mySet.has(i.classNames.pop())).eql(true)
    
    };
});


from Recent Questions - Stack Overflow https://ift.tt/37RxFGO
https://ift.tt/eA8V8J

Issue with JTextField not displaying correctly

I'm working on a school assignment creating a Social Media timeline. I'm working on the implementation of searching the time by specific user-specified things. My issue is when I am creating my JTextFields, they are not displaying with a width larger than 1 character.

Here is an example of how I am creating and adding the JTextField to a JPanel:

        JTextField hashtagField = new JTextField(20);
        hashtagField.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                hashtagField.setText("");
                hashtagField.removeFocusListener(this);
            }
        });
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.LINE_END;
        hashtagPanel.add(new JLabel("Enter a hashtag: "), gbc);
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.LINE_START;
        hashtagPanel.add(hashtagField, gbc);       
        actionsPanel.add(hashtagPanel, HASHTAG_ID);

I have tried to remove the FocusListener from the code, but that does not fix the issue.

Also, here is an example of what the code is producing:Output

EDIT: I noticed that changing the setResizable(boolean visibility) method's parameter to true fixes this, but I don't want to allow the user to resize the frame.



from Recent Questions - Stack Overflow https://ift.tt/34K2mvm
https://ift.tt/34GQHgT

How do you add ads into react native?

I've tried everything but I can't make it work. Tried AdMob (google) but it says I have to add some JAVA code and it's not compatible with my Javascript react native code. Tried firebase and it had lots of errors as well. I can't find a solution, everything is broken or outdated

How does everyone do it?



from Recent Questions - Stack Overflow https://ift.tt/37VjQHp
https://ift.tt/eA8V8J

Trouble understanding Functions in C

I am working through a programming assignment. I had the key validation working within main but decided to try to make it a separate function. I do not understand functions very well yet so I am unable to see where I am going wrong. Whenever I run the program, I always just get "Key is Valid" even when I know it's not. As I said, the program was running fine in main.

#include <cs50.h>
#include <ctype.h>
#include <stdio.h>
#include <string.h>

int validate (int c, string v[]); //prototpe validate function

int main (int argc, string argv[])
{
    int validate (int argc, string argv[]); //run validate for argc and argv

    printf("Key is valid\n"); //if valid, print message

}

int validate (int c, string v[])
{
    //Validate that only one Command Line Argument was entered
    if (c != 2) //Check the number if entered commands at execution
    {
        //If more than one, print error message
        printf("Key must be the only Command Line Argument\n");
        return 1; //Return false
    }

    //Validate that Key length is 26 characters
    if (strlen(v[1]) != 26) //Don't forget null 0
    {
        printf("Key must contain exactly 26 characters\n");
        return 1; //Return false
    }

    //Validate that all Key characters are alphabetic
    for (int i = 0, n = strlen(v[1]); i < n; i++)
    {
        //Check each element of the array
        if (isalpha(v[1][i]))
        {
            continue; //Continue if alphabetic
        }
        else
        {
            //if non-alphabetic, print error code
            printf("Key must contain only alphabetic characters\n");
            return 1; //Return false
        }
    }

    //Validate that each Key character is unique
    for (int x = 0, z = strlen(v[1]) - 1; x < z; x++)
    {
        //Create a second loop to compare every element to the first before incrementing the first
        for (int y = x + 1; y < z; y++)
        {
            //Cast array elements to int, check if each element equals next element in array
            if (v[1][x] == v[1][y])
            {
                printf("Key must contain exactly 26 unique characters\n");
                return 1;
            }
        }
    }

    return 0; //Key is valid, so return true
}


from Recent Questions - Stack Overflow https://ift.tt/3eavJKF
https://ift.tt/eA8V8J

All body content moves up and below the navigation (HTML & CSS)

I've tried a few suggestions like removing overflow from the body, adding a z-index to header and padding-top but nothing seems to work.

It worked fine at first but then I implemented a lot of Lorem Ipsum text. All the content just slides up and below the navbar. I've attached a JS fiddle to explain.

I tried the whole body overflow and tried the fixed/relative header positions. Nothing works.

Any input would seriously be appreciated A LOT.

I would love some help in how can I make the nav stick but not really stay fixed when I scroll down.

And of course, how to make the contents not overflow horizontally.

Please help!

CSS

html,
body {
  position: absolute;
  width: 100%;
  top: 0;
  min-height: 100vh;
  font-family: sans-serif;
  margin: 0 !important;
  padding: 0 !important;
}



ul {
  box-sizing: border-box;


}

#logo {
  max-width: 15%;
}




.menu-wrapper {
  background-color: white;
}

.header {
  z-index: 1000;
  width: 100%;
  margin: 1.2em;
  position: fixed;
  background-color: black;


}






#about {
  position: absolute;
  max-width: 100%;
  top: 49%;
  left: 50%;
  transform: translate(-50%, -50%);
  border: 5px solid purple;
  padding: 20px;
  text-align: center;
  justify-content: center;
}

.about-par {
  font-size: 1em;
}



.header ul {
  padding: 0;
  list-style: none;
  overflow: hidden;
  margin-right: 2em;

}

.header li a {
  display: block;
  color: blue;
  text-decoration: none;
  font-size: 1em;
}

.header li a:hover,
.header .menu-btn:hover {
  color: black;
}

.header li a:active,
.header .menu-btn: active,
  {
  color: blue;
}

.header li a:active {
  color: blue;
}

.header .logo {
  color: black;
  display: block;
  float: left;
  font-size: 1.1em;
  padding: 12px;
  margin-left: 1em;
  text-decoration: none;
}

.header .menu {
  clear: both;
  max-height: 0;
  transition: max-height 0.2s ease-out;
}

/* menu icon */
.header .menu-icon {
  cursor: pointer;
  display: inline-block;
  float: right;
  padding: 28px 40px;
  position: relative;
  user-select: none;
}

.header .menu-icon .navicon {
  display: block;
  height: 2px;
  position: relative;
  transition: background 0.2s ease-out;
  width: 18px;
}

.header .menu-icon .navicon:before,
.header .menu-icon .navicon:after {
  background: black;
  content: "";
  display: block;
  height: 100%;
  position: absolute;
  transition: all 0.2s ease-out;
  width: 100%;
}

.header .menu-icon .navicon:before {
  top: 5px;

}

.header .menu-icon: before {
  background: transparent;
}

.header .menu-icon .navicon:after {
  top: -5px;

}

/* menu btn */
.header .menu-btn {
  display: none;
}

.header .menu-btn:checked~.menu {
  max-height: 340px;
  background-color: black;
}

.header .menu-btn:checked~.menu-icon .navicon {
  background: transparent;
}

.header .menu-btn:checked~.menu-icon .navicon:before {
  transform: rotate(-45deg);
}

.header .menu-btn:checked~.menu-icon .navicon:after {
  transform: rotate(45deg);

}

.header .menu-btn:checked~.menu-icon:not(.steps) .navicon:before,
.header .menu-btn:checked~.menu-icon:not(.steps) .navicon:after {
  top: 0;
}

/* Responsive */
@media only screen and (max-width: 768px) {
  .header li a {
    padding: 15px;
    border-bottom: 1px dotted #ddd;
    color: white;
  }

  .header li a:hover {
    padding: 15px;
    border-bottom: 1px dotted #ddd;
    color: blue;




  }


}

@media only screen and (min-width: 768px) {
  .menu-wrapper {
    width: 100%;
  }


  .header li {
    float: left;
  }

  .header .logo {
    line-height: 1;
  }

  .header li a {
    color: blue;
    padding: 0px 30px;
    border-right: 1px solid rgba(255, 255, 255, 0.2);

  }

  .header .menu {
    clear: none;
    float: right;
    max-height: none;

  }

  .header .menu-icon {
    display: none;

  }
}

HTML

<!DOCTYPE html>

<html lang="en">

  <head>


    <script src="script.js"></script>

    <link href="style.css" rel="stylesheet">
    <meta charset="utf-8">

    <link href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" rel="stylesheet">


    <meta name="viewport" content="initial-scale=1, width=device-width shrink-to-fit=no">



    <title>Hello! </title>

  </head>

  <body>

    <div class="empty"></div>
    <div class="all">
      <div class="menu-wrapper">
        <header class="header">
          <a href="#home">Logo</a>
          <input class="menu-btn" type="checkbox" id="menu-btn" />
          <label class="menu-icon" for="menu-btn"><span class="navicon"></span></label>
          <ul class="menu">
            <li><a href="#">Home</a></li>
            <li><a href="about.html">About Us</a></li>
            <li><a href="#">More</a></li>
            <li><a href="#">More2</a></li>
          </ul>
        </header>
      </div>
    </div>

    <div class="row">
      <div class="container-fluid" id="about">
        <h5>Text</h5>
        <div class="col-lg-12">
          <article>
            <p class="about-par">
              Pellentesque in ipsum id orci porta dapibus. Cras ultricies ligula sed magna dictum porta. Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Proin eget tortor risus. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Vivamus suscipit tortor eget felis porttitor volutpat. Proin eget tortor risus. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
              <br>Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec velit neque, auctor sit amet aliquam vel, ullamcorper sit amet ligula. Pellentesque in ipsum id orci porta dapibus. Vivamus suscipit tortor eget felis porttitor volutpat. Proin eget tortor risus. Vivamus suscipit tortor eget felis porttitor volutpat.
              <br>
              Donec sollicitudin molestie malesuada. Nulla quis lorem ut libero malesuada feugiat. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur aliquet quam id dui posuere blandit. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus.
              <br>Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Donec sollicitudin molestie malesuada. Vivamus suscipit tortor eget felis porttitor volutpat. Vivamus suscipit tortor eget felis porttitor volutpat. Curabitur aliquet quam id dui posuere blandit. Nulla porttitor accumsan tincidunt. Nulla quis lorem ut libero malesuada feugiat. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec velit neque, auctor sit amet aliquam vel, ullamcorper sit amet ligula. Donec sollicitudin molestie malesuada.
              <br>
              Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Cras ultricies ligula sed magna dictum porta. Proin eget tortor risus. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Donec sollicitudin molestie malesuada. Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem. Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Cras ultricies ligula sed magna dictum porta.
              <br>Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec velit neque, auctor sit amet aliquam vel, ullamcorper sit amet ligula. Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Quisque velit nisi, pretium ut lacinia in, elementum id enim.
              <br>
              Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Nulla porttitor accumsan tincidunt. Curabitur aliquet quam id dui posuere blandit. Cras ultricies ligula sed magna dictum porta. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Cras ultricies ligula sed magna dictum porta. Proin eget tortor risus. Praesent sapien massa, convallis a pellentesque nec, egestas non nisi. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Donec velit neque, auctor sit amet aliquam vel, ullamcorper sit amet ligula. Nulla porttitor accumsan tincidunt. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Vestibulum ac diam sit amet quam vehicula elementum sed sit amet dui. Curabitur arcu erat, accumsan id imperdiet et, porttitor at sem. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus.
              <br>
              Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Vivamus suscipit tortor eget felis porttitor volutpat. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Donec sollicitudin molestie malesuada. Cras ultricies ligula sed magna dictum porta. Vivamus suscipit tortor eget felis porttitor volutpat. Donec rutrum congue leo eget malesuada.
              <br>Sed porttitor lectus nibh. Curabitur aliquet quam id dui posuere blandit. Pellentesque in ipsum id orci porta dapibus. Proin eget tortor risus. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Nulla quis lorem ut libero malesuada feugiat. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
              <br>
              Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Vivamus suscipit tortor eget felis porttitor volutpat. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Donec sollicitudin molestie malesuada. Cras ultricies ligula sed magna dictum porta. Vivamus suscipit tortor eget felis porttitor volutpat. Donec rutrum congue leo eget malesuada.
              <br>Sed porttitor lectus nibh. Curabitur aliquet quam id dui posuere blandit. Pellentesque in ipsum id orci porta dapibus. Proin eget tortor risus. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Nulla quis lorem ut libero malesuada feugiat. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
              <br>
              Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Vivamus suscipit tortor eget felis porttitor volutpat. Quisque velit nisi, pretium ut lacinia in, elementum id enim. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Donec sollicitudin molestie malesuada. Cras ultricies ligula sed magna dictum porta. Vivamus suscipit tortor eget felis porttitor volutpat. Donec rutrum congue leo eget malesuada.
              <br>Sed porttitor lectus nibh. Curabitur aliquet quam id dui posuere blandit. Pellentesque in ipsum id orci porta dapibus. Proin eget tortor risus. Vivamus magna justo, lacinia eget consectetur sed, convallis at tellus. Mauris blandit aliquet elit, eget tincidunt nibh pulvinar a. Nulla quis lorem ut libero malesuada feugiat. Lorem ipsum dolor sit amet, consectetur adipiscing elit.
            </p>
          </article>


        </div>
      </div>
    </div>









  </body>

</html>

JSFIDDLE https://jsfiddle.net/janie2000/pf3L4y1d/5/

Thank you so much.



from Recent Questions - Stack Overflow https://ift.tt/37TUZni
https://ift.tt/eA8V8J

How do I write a program that asks for user input and uses it to form new variables which I use to calculate something in java [closed]

How do I write a program that asks for user input and uses it to form new variables which I use to calculate something in java. It also keeps on repeating until the user tells it to stop.

Actual Question:

Write a program that calculates miles per gallon for a list of cars. the data for each car consists of initial odometer reading, final odometer reading, and number of gallons of gas. The user signals that there are no more cars by entering a negative initial odometer reading.

Example of how it should look like in the end)

Miles Per Gallon Program

Initial miles: 15000
Final miles: 15250
Gallons: 10
Miles per Gallon: 25.0

Initial miles: 107000
Finals miles: 107450
Gallons: 15
Miles per Gallon: 30.0

Initial miles: -1
bye


from Recent Questions - Stack Overflow https://ift.tt/2GimOKG
https://ift.tt/eA8V8J

discord bot not responding to event

The code is very simple, the bot is just simply not responding when I type hello into the discord channel. The bot has been added properly, and is showing as online.

Main.java

import events.HelloEvent;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDABuilder;

import javax.security.auth.login.LoginException;

public class Main {
    public static void main(String[] args) throws LoginException {
        JDABuilder builder = new JDABuilder("key");
        builder.addEventListeners(new HelloEvent());
        JDA api = builder.build();
    }
}

HelloEvent.java

package events;

import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent;
import net.dv8tion.jda.api.hooks.ListenerAdapter;


public class HelloEvent extends ListenerAdapter {

    @Override
    public void onGuildMessageReceived(GuildMessageReceivedEvent event) {
        String messageSent = event.getMessage().getContentRaw();
        if(messageSent.equalsIgnoreCase("hello")) {
            event.getChannel().sendMessage("what's up my dude").queue();
        }
    }
}


from Recent Questions - Stack Overflow https://ift.tt/3oQ44Un
https://ift.tt/eA8V8J

How can I verify a Python method was called with parameters including a DataFrames?

I'm using MagicMock to verify that a method was called with specific arguments:

ClassToMock.method_to_mock = MagicMock(name='method_to_mock')
ClassToMock.method_that_creates_data_frame_and_passes_to_mocking_method()
ClassToMock.method_to_mock.assert_called_with('test_parameter_value', self.get_test_data_frame())

Where self.get_test_data_frame() is a pre-defined DataFrame that is the expected result of the call.

When I print out the DataFrame passed to the mocking method and the the test DataFrame I can see that they look equal when printed:

enter image description here

but the test output does not think they are equal:

File "C:\python3.6\lib\unittest\mock.py", line 812, in assert_called_with if expected != actual: File "C:\python3.6\lib\unittest\mock.py", line 2055, in eq return (other_args, other_kwargs) == (self_args, self_kwargs) File "C:\python3.6\lib\site-packages\pandas\core\generic.py", line 1330, in nonzero f"The truth value of a {type(self).name} is ambiguous. " ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

From reading other issues I think it is because the MagicMock tries to call == but Pandas require .equals() to check for equality. Does anyone know of an alternative approach?



from Recent Questions - Stack Overflow https://ift.tt/35UTd2O
https://ift.tt/34K2qLC

How to update an Amazon S3 Bucket Policy via the AWS CLI?

I have a requirement to add a new line "arn:aws:sts::1262767:assumed-role/EC2-support-services" to an Amazon S3 bucket policy.

Something like this:

Before:

{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Sid":"AddCannedAcl",
      "Effect":"Allow",
    "Principal": {"AWS": ["arn:aws:iam::111122223333:root","arn:aws:iam::444455556666:root"]},
      "Action":["s3:PutObject","s3:PutObjectAcl"],
      "Resource":"arn:aws:s3:::awsexamplebucket1/*",
      "Condition":{
     "StringNotLike": {
        "aws:arn": [
          "arn:aws:sts::1262767:assumed-role/GR_COF_AWS_Prod_Support/*"
        ]
      }       
     }
   
    }
  ]
}

After:

{
  "Version":"2012-10-17",
  "Statement":[
    {
      "Sid":"AddCannedAcl",
      "Effect":"Allow",
    "Principal": {"AWS": ["arn:aws:iam::111122223333:root","arn:aws:iam::444455556666:root"]},
      "Action":["s3:PutObject","s3:PutObjectAcl"],
      "Resource":"arn:aws:s3:::awsexamplebucket1/*",
      "Condition":{
     "StringNotLike": {
        "aws:arn": [
          "arn:aws:sts::1262767:assumed-role/GR_COF_AWS_Prod_Support/*",
           "arn:aws:sts::1262767:assumed-role/EC2-support-services"
        ]
      }       
     }
   
    }
  ]
}

What is the AWS CLI command I need to use to add this line?



from Recent Questions - Stack Overflow https://ift.tt/31ZnyMb
https://ift.tt/eA8V8J

How i can write the dynamo query

I have created a table and inserted values

{
 "programname": {
 "S": "progressive"
  },
 "statecode": {
  "S": "TX"
 },
"ziprule": {
 "M": {
  "reason": {
    "S": "This policy is not eligible since the property address is in zip list"
  },
  "response": {
    "S": "No"
  },
  "zip": {
    "L": [
      {
        "S": "682040"
      },
      {
        "S": "682041"
      },
      {
        "S": "682042"
      },
      {
        "S": "682043"
      },
      {
        "S": "682044"
      },
      {
        "S": "682045"
      },
      {
        "S": "682046"
      },
      {
        "S": "682047"
      },
      {
        "S": "682048"
      },
      {
        "S": "682049"
       }
      ]
     }
    }
    }
  }

I need to check the following zip (682045)in the zip list.Can i get the result in a single query or i need to write the code for json array iteration for finding the zip. Please help me to write a query for this.is there any better way to design the dynamo DB



from Recent Questions - Stack Overflow https://ift.tt/2TFVV6k
https://ift.tt/eA8V8J

How to implement Web OTP Api in React?

I am trying to use Web Otp APi using docs from https://web.dev/web-otp/. But it is not working. Can anyone tell me how to execute it in reactjs.



from Recent Questions - Stack Overflow https://ift.tt/2HSgw4B
https://ift.tt/eA8V8J

MySQL - Get MAX value per category, joining three tables

EDIT

Setting mysql config to this to match live server worked, I got error #1055 when not including selected columns in the GROUP BY statement

sql_mode=STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION

New query:

SELECT
*,
    c.name AS coin_name,
    c.coin_symbol AS coin_symbol,
    p.name AS platform_name,
    o.apy as apy,
    o.apy_note1 as apy_note1,
    o.apy_note2 as apy_note2,
    o.compounding_freq as compounding_freq,
    o.payout_freq as payout_freq,
    o.id as offer_id,
    
    
    MAX(apy) max_apy
FROM
    offers o
    INNER JOIN coins c
        ON c.id = o.coin_id
    INNER JOIN platforms p
        ON p.id = o.platform_id 
WHERE MATCH (c.name, c.coin_symbol) AGAINST ("'.$search_param.'" IN BOOLEAN MODE)
GROUP BY
    coin_name

Long time lurker, first time poster.

I have these three tables, and I'd like to get the maximum apy from the offers table, per coin while also displaying the platform name, showing only the highest apy for each coin.

Any help would be greatly appreciated.

Expected result:

+--------------+-------------+---------------+-----+
| coin_name    | coin_symbol | platform_name | apy |
+--------------+-------------+---------------+-----+
| Bitcoin      | BTC         | Platform 1    | 5%  |
+--------------+-------------+---------------+-----+
| Crypto.com   | CRO         | Platform 3    | 6%  |
+--------------+-------------+---------------+-----+
| Bitcoin Cash | BCH         | Platform 8    | 1%  |

Truncated tables:

CREATE TABLE `coins` (
`id` int(11) NOT NULL,
`name` varchar(128) NOT NULL,
`coin_symbol` varchar(200) NOT NULL,
`description` varchar(2000) DEFAULT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `platforms` (
`id` int(11) NOT NULL,
`name` varchar(200) DEFAULT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE `offers` (
`id` int(11) NOT NULL,
`platform_id` int(11) DEFAULT NULL,
`coin_id` int(11) DEFAULT NULL,
`apy` varchar(10) NOT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

The query which gives duplicate coins

 SELECT
c.name AS coin_name,
c.coin_symbol AS coin_symbol,
p.name AS platform_name,
o.apy as apy,


MAX(apy) max_apy
FROM
offers o
INNER JOIN coins c
    ON c.id = o.coin_id
INNER JOIN platforms p
    ON p.id = o.platform_id

WHERE MATCH (c.name, c.coin_symbol) AGAINST ("bch,atom,cel,bnb,btc%" IN BOOLEAN MODE)

GROUP BY
coin_name, platform_name, coin_symbol, apy
ORDER BY `max_apy`  ASC

I'm thinking the "GROUP BY" clause is causing the issue, do I need to perform a subquery to group by coins first?



from Recent Questions - Stack Overflow https://ift.tt/3kFwiyA
https://ift.tt/eA8V8J

Having trouble with parsing specific data from log file

I have an assignment in which the main task is to report suspicious activities within a log file. There are several other problems I have to address, but the one that I want to focus on the most is "suspicious activities" (if I can get a grasp on this then more than likely I'll have a lightbulb to help guide me on the rest). The way this is supposed to be achieved is to keep up a count for whenever a user logins between 12:00 am to 5:00 am. Once a user has been marked for being suspicious, the users' name, their email, and the domain name should be present as output information.

I have never worked with log files before and this is my first dealing with one using Python 3 (specifically PyCharm). So far it has proven challenging because I don't know where exactly to start this assignment. I originally planned to use regular expressions to match specific text in the log file and dictionaries for keys, but I wasn't sure if this was the correct frame of mind in tackling this assignment.

Here is the sample log: Sample Behavior

And here is a piece of the user log file userlog.log

I apologize if my post comes off as a bit confusing, this is the very first time I have used Stack overflow. My goal is to gather thoughts and ideas of how I should tackle this assignment one step at a time. Thanks for any ideas or thoughts as well. Edit: below is a piece of the user log file pasted.

2020-05-23 00:44:42 login mailserver.local melaina.gabeline@yahoo.com.mx
2020-05-15 10:54:11 logout mailserver.local sevan.stephco@miho-nakayama.com
2020-05-07 11:25:24 login myworkstation.local breena.benassi@gmx.net
2020-05-14 16:31:34 logout webserver.local arti.karshner@mail2perry.com
2020-05-12 17:02:10 login mailserver.local queen.ham@quiklinks.com
2020-05-30 23:01:30 logout mailserver.local maryelizabeth.stassen@freesurf.fr
2020-05-11 15:04:32 logout myworkstation.local lupe.gave@freesurf.fr
2020-05-26 13:51:35 logout mailserver.local tarrin.evanoff@blacksburg.net
2020-05-15 02:21:39 logout mailserver.local maryelizabeth.stassen@freesurf.fr
2020-05-05 14:16:13 login mailserver.local aprilmarie.ulatowski@freesurf.fr
2020-05-21 03:53:37 login mailserver.local tarrin.naysmith@mail2champaign.com
2020-05-05 06:17:09 login webserver.local melaina.gabeline@yahoo.com.mx
2020-05-24 18:24:49 logout myworkstation.local kira.pay@mail2zambia.com



from Recent Questions - Stack Overflow https://ift.tt/37TUWb6
https://ift.tt/eA8V8J

How to add a link to open a file without a Win10 security warning in iTextSharp v5

When creating a new PDF file using iTextSharp I am able to create a link in the document using the .SetAnchor method that navigates to the specified URL when clicked, such as

anchor.SetAnchor(...some URL...);

However, all I really want the click to do is open or execute a specified file on my local Win10 machine, and this also works if I merely specify the file instead of a URL, such as

anchor.SetAnchor("notepad.exe");

The issue is that I must use iTextSharp to create many of versions of the PDF file, with each version having a different file name itself as well as a different name for the file the link opens. Although I have no problem getting this to work, the annoyance is that whenever I click the link in a new version I get a "Security Warning" popup from Windows wanting to know if the "connection" should be allowed.

Because the warning mentions a "connection" I get the feeling there may be a method something like SetAnchor that will produce a link specifically intended for opening files rather than URLs and that will not result in a Security Warning each time the name of the file the link represents is changed. If so, what is it? If not, is there some other reasonable approach to avoid the security warning? This is all being used on my local machine so I know there are no security issues with the PDFs or the files being opened.



from Recent Questions - Stack Overflow https://ift.tt/3kycn4r
https://ift.tt/eA8V8J

2020-10-30

Google Sheets: Hide protected rows

I'm working with Google Sheets. Just want to know if there is a way for the user to hide a protected rows so that whenever he/she is going to print something, all the range rows that are empty will not be visible. An owner can do that, but the user can't. Thanks!



from Recent Questions - Stack Overflow https://ift.tt/2HPO041
https://ift.tt/eA8V8J

Change component html template for each unit test in Angular

Is there a way to change the component html template for each test?

I created a component in my unit test and I want the component's html template to be different in other test.

I tried to use TestBed.overrideComponent (As shown in the code) but I got the error:

"Cannot override component metadata when the test module has already been instantiated."

@Component({
    template: `<div> <span *directive="let letter from ['x','y','z']"> </span> </div>`
})

class TestComponent {
    isEnabled: any;
}

describe('Directive', () => {

    let fixture: ComponentFixture<TestComponent>;
    let element: DebugElement;
    let component: TestComponent;

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [TestComponent, Directive],
        });
    });

    it('should do something with the initial component template', () =>{ ... });

    it('should do something with another template', () => {
        fixture = TestBed.overrideComponent(TestComponent, {
            set: {
                template: `<div> <span *directive="let letter from ['a','b','c'] enabled:isEnabled "> </span> </div>`
            }
        })
            .createComponent(TestComponent);
        component = fixture.componentInstance;
        component.isEnabled = true;
        fixture.detectChanges();
        ...
    });

});


from Recent Questions - Stack Overflow https://ift.tt/3kSStkE
https://ift.tt/eA8V8J

Catch event before redirect to external url

I mean that when client click any link on my site and those links are Redirected to external url( not to open new window/tab ).

My purpose: Handling something after clicking.(before going to other url) such as: call api or handle something

note: I dont want to use beforeunload or alert or confirm

Please help me, Thank you.!!



from Recent Questions - Stack Overflow https://ift.tt/2HNCF44
https://ift.tt/eA8V8J

How to use react hooks in this code? come three js"

hello I'm starting with thrrejs on react and found this example on the internet and I would like to know how I can rewrite it using hooks, I tried using useRef (null) but it gave an error, if anyone knows please let me know.

import React, { Component } from "react";
import ReactDOM from "react-dom";
import * as THREE from "three";
class App extends Component {
  componentDidMount() {
    var scene = new THREE.Scene();
    var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
    var renderer = new THREE.WebGLRenderer();
    renderer.setSize( window.innerWidth, window.innerHeight );
    // document.body.appendChild( renderer.domElement );
    // use ref as a mount point of the Three.js scene instead of the document.body
    this.mount.appendChild( renderer.domElement );
    var geometry = new THREE.BoxGeometry( 1, 1, 1 );
    var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
    var cube = new THREE.Mesh( geometry, material );
    scene.add( cube );
    camera.position.z = 5;
    var animate = function () {
      requestAnimationFrame( animate );
      cube.rotation.x += 0.01;
      cube.rotation.y += 0.01;
      renderer.render( scene, camera );
    };
    animate();
  }
  render() {
    return (
      <div ref={ref => (this.mount = ref)} />
    )
  }
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);



from Recent Questions - Stack Overflow https://ift.tt/31WKrzT
https://ift.tt/eA8V8J

Android: publish private apps for enterprise customers

I see that on PlayStore I can publish a private app to my customers if they has a OrganizationId. I don't understand the role of "Play Custom App Publishing API","Android Management API ". Is possible to develop a private enterprise store based on playstore ? I'm confused.. The world of private app for enterprise is soo few documented



from Recent Questions - Stack Overflow https://ift.tt/35JTllv
https://ift.tt/eA8V8J

lme function for mixed models for dichotomous variables: Singularity in backsolve at level 0, block 1

I am adjusting a fixed effects model considering some covariates. Regarding the specification of the model, two of these covariates are nested and have fixed effects. See that the following error below is happening.

data: https://drive.google.com/file/d/1hKfYpcgAV4gdDPHXv_4EQpiO0Y31_ZVo/view?usp=sharing

library(nlme)
library(lme4)

dados$VarCat=as.factor(dados$VarCat)
dados$VarX5=as.factor(dados$VarX5)
dados$VarX6=as.factor(dados$VarX6)

modelANew <- lme(log(Resp)~log(VarX1)+log(VarX2)+(VarX3)+(VarX4)+VarX5/VarX6 ,random = ~1|VarCat, 
                 dados, method="REML")

Error in MEEM(object, conLin, control$niterEM) : 
  Singularity in backsolve at level 0, block 1

Variable X6 is a dichotomous variable. This seems to me to be interfering with the convergence or estimation of the model. How can I solve?



from Recent Questions - Stack Overflow https://ift.tt/2TAW0Z3
https://ift.tt/eA8V8J

Keep comments in .scss with webpack SCSS loader

Using this webpack config to load scss file, I am trying to keep comments in my scss file in development mode and remove it in production mode.

{
  test: /\.(scss|sass|css)$/,
  exclude: /node_modules/,
  use: [
    {
      loader: MiniCssExtractPlugin.loader,
    },
    {
      loader: 'css-loader',
    },
    {
      loader: 'sass-loader',
      options: {
        sassOptions: {
          outputStyle: 'expanded',
        },
      },
    },
  ],
},

Here is an example test.scss file:

$block: ".test-";

#{$block} {
  // Comments
  &class {
    width: 100%;
    height: 100%;
  }
}

The webpack output for the css is:

.test-class {
    width: 100%;
    height: 100%;
}

As you can see my comments disappeared. However, I would like to keep the comments in development mode and delete them in production. How could I achieve this?



from Recent Questions - Stack Overflow https://ift.tt/31TTNfT
https://ift.tt/eA8V8J

Need help creating a URL rewrite from an SEO friendly URL

I hope you can help me. I'm trying to create a URL rewrite, redirect, or combination of the two in a .htaccess file, but I don't know how. It's kinda hard to find anything definitive on URL rewrites.

Basically, I want the user to be able to type in a SEO friendly URL (just one level) and have that sent to a page where I can do a $_GET['data'] and do a mysql query and serve up a web page. I don't want the URL the user sees to change though so I'm not sure if I need to redirect it back to the SEO friendly or if it can just stay the same SEO friendly version.

Here's my example:

The user would type in this URL: www.mysite.com/cars

somehow, that would be either redirected or rewritten as: www.mysite.com/getpage.php?page=cars

but the URL stays the same: www.mysite.com/cars

I'm pretty sure this is a URL rewrite or redirect or a combination of the two but I have no idea how to write the rewrite rules. I

Any assistance you can offer would be extremely helpful!

Thanks Keyogee



from Recent Questions - Stack Overflow https://ift.tt/2TFsOzW
https://ift.tt/eA8V8J

How do I pop the value returned from my array?

So I have a function,

def Multiples(OGvalue, count):
    multiples = []
    for i in range(count):
        multiples.append(i*OGvalue)
    multiples.pop(1), multiples.pop(0)
    return (multiples[randrange(len(multiples))])

that is being called elsewhere in my program. Now, I don't want to random value that is given to repeat, so I want to remove it from my array after it is used, how would I go about doing that?



from Recent Questions - Stack Overflow https://ift.tt/2HJhkZQ
https://ift.tt/eA8V8J

Page reading 2 different If-Statements as the same

I'm running into a pretty confusing situation here:

   if ((a.length = 0 || b === null)) {
        this.noNotif = true;
        console.log("1");
      }
      if (a.length > 0 || b === null) {
        this.newNotif = true;
        // this.noNotif = false;
        console.log("2");
      } else {
        if (a.length === b.length) {
          console.log("No New Notifications");
          this.noNotif = true;
        } else {
          console.log("New notifications");
          this.newNotif = true;
        }

Console logging a.length returns 0 and 'b' is null However, the issue is that somehow both of the first two if-statements' conditions are being met. noNotif and newNotif both display a Vue components and both are showing up currently.

Some background information about a & b

'a' is supposed to be data from an API that is fetched on page load. 'b' is supposed to be a localStorage object array

The first if-statement deals with a new user who has no API data or anything stored in LocalStorage

The second if-statement handles when the user does have data in the API, but nothing in LS yet.

The First nested if-statement is if the data from the API matches the LS data

The nested else-statement is if the API data is different (longer) than what's in LS



from Recent Questions - Stack Overflow https://ift.tt/31SBRC8
https://ift.tt/eA8V8J

How do I convert this scikit-learn section to pandas dataframe? [duplicate]

I am trying to convert this Python code section to pandas dataframe:

iris = datasets.load_iris()
x = iris.data
y = iris.target

I will like to import Iris data on my local machine instead of loading the data from Scikit library. Your kind suggestions would be highly appreciated.



from Recent Questions - Stack Overflow https://ift.tt/3mAW87e
https://ift.tt/eA8V8J

How to I find the person who has taught the most classes

I want to try and find the employee who has taught the most classes as the position Teacher. So in this I want to print out Nick, as he has taught the most classes as a Teacher.

However, I am getting the error:

ERROR: column "e.name" must appear in the GROUP BY clause or be used in an aggregate function Position: 24

CREATE TABLE employees (
  id integer primary key,
  name text
);

CREATE TABLE positions (
  id integer primary key,
  name text
);

CREATE TABLE teaches (
  id integer primary key,
  class text,
  employee integer,
  position integer,
  foreign key (employee) references employees(id),
  foreign key (position) references positions(id)
);

INSERT INTO employees (id, name) VALUES
(1, 'Clive'), (2, 'Johnny'), (3, 'Sam'), (4, 'Nick');

INSERT INTO positions (id, name) VALUES
(1, 'Assistant'), (2, 'Teacher'), (3, 'CEO'), (4, 'Manager');

INSERT INTO teaches (id, class, employee, position) VALUES
(1, 'Dancing', 1, 1), (2, 'Gardening', 1, 2),
(3, 'Dancing', 1, 2), (4, 'Baking', 4, 2),
(5, 'Gardening', 4, 2), (6, 'Gardening', 4, 2),
(7, 'Baseball', 4, 1), (8, 'Baseball', 2, 1),
(9, 'Baseball', 4, 2);

The SQL statement I am trying to use:

SELECT count(t.class), e.name
FROM positions p
JOIN teaches t
ON p.id = t.position
JOIN employees e
ON e.id = t.employee
WHERE p.name = 'Teacher'
GROUP BY t.employee;

I've been working on this on a sql fiddle: http://www.sqlfiddle.com/#!17/a8e19c/3



from Recent Questions - Stack Overflow https://ift.tt/32cbUxV
https://ift.tt/eA8V8J

compare two arrays and take values ​from the first array not contained in the second array

I have this array with 3 of size

[
  'decdbaf8-db89-4d4b-973a-e8edab55927c',
  'c553c2f7-eff6-476e-b718-2814a7fa5435',
  '8717092f-5820-474b-9dd9-165e2649180f'
]

and this array with size equals 2:

[
  {
    id: 'c553c2f7-eff6-476e-b718-2814a7fa5435',
    name: 'test',
    codReference: '15422aa',
    category_id: '7a026a80-f3d2-462a-ad5d-598e9eabf693',
    created_at: 2020-10-29T22:23:35.928Z,
    updated_at: 2020-10-29T22:23:35.928Z,
    deleted_at: null
  },
  {
    id: 'decdbaf8-db89-4d4b-973a-e8edab55927c',
    name: 'test',
    codReference: '2',
    category_id: '7a026a80-f3d2-462a-ad5d-598e9eabf693',
    created_at: 2020-10-29T22:23:37.784Z,
    updated_at: 2020-10-29T22:23:37.784Z,
    deleted_at: null
  }
]

I know that if I were to get only one item that is not contained in the array, I would just use: indexOf (value)> -1;

but how can I compare the two arrays and get only the values ​​of the first array that are not contained in the second array



from Recent Questions - Stack Overflow https://ift.tt/3jD2UaJ
https://ift.tt/eA8V8J

How to use Oracle JSON_VALUE

I'm working on a trigger.

declare
  v_time number(11, 0);
begin
for i in 0..1
loop
  select JSON_VALUE(body, '$.sections[0].capsules[0].timer.seconds') into v_time from bodycontent where contentid=1081438;
dbms_output.put_line(v_time);
end loop;
end;

However, index references do not become dynamic.

like JSON_VALUE(body, '$.sections[i].capsules[i].timer.seconds')

Is there any way I can do this?



from Recent Questions - Stack Overflow https://ift.tt/3mtzHRo
https://ift.tt/eA8V8J

Using Jupyter Notebooks in Pycharm 2020.2 Jupyter Notebooks venv installation error

I am trying to work on Jupyter Notebooks in Jetbrains Pycharm 2020.2 Professional Edition with a venv. When I try to install Jupyter Package it returns an error. An error message when I tried to install the Jupyter Package What can I do to resolve this error and successfully install the Jupyter package to my Pycharm 2020.2 venv so I can use the Jupyter notebook in Pycharm?

A picture of Pycharm saying I need to install the Jupyter Package to utilize the Jupyter Notebook's functionality



from Recent Questions - Stack Overflow https://ift.tt/3kHmF2l
https://ift.tt/eA8V8J

How do I pack a function from a static library into an .so file with fortran (MKL)

I'm trying to speed up an optimization routine using MKL's blas implementation in fortran. I need to have the result in a shared library so that it is accessible from a larger script. I can compile and link my code without any warnings, but the resulting .so file has an undefined reference to the blas routine I'm trying to call, namely dgemm.

relevant section of the fortran code:

subroutine sumsquares(params, Mx, flen, glen, numr, numcols, g, lambda, res)
 implicit none
 integer, intent(in):: flen, glen, numr, numcols
 real(8), dimension(flen, numcols) :: params
 real(8), dimension(flen, numcols) :: g
 real(8), dimension(flen, numcols) :: gc
 real(8), dimension(flen, glen) :: Mx 

 gc = -g
 call dgemm('N', 'N', flen, glen, numcols, 1, Mx, flen, params, numcols, 1, gc,flen)
 return
end subroutine sumsquares

and the corresponding makefile

FC=ifort
LD_LIBRARY_PATH=/opt/intel/composerxe-2011.1.107/compiler/lib/intel64:/opt/intel/composerxe-2011.1.107/mkl/lib/intel64
LIBRARY_PATH=/opt/intel/composerxe-2011.1.107/compiler/lib/intel64:/opt/intel/composerxe-2011.1.107/mkl/lib/intel64
INCLUDE=/opt/intel/composerxe-2011.1.107/mkl/include
FPATH=/opt/intel/composerxe-2011.1.107/mkl/include
CPATH=/opt/intel/composerxe-2011.1.107/mkl/include
FFLAGS=-i8 -I$(MKLROOT)/include/intel64/ilp64 -I$(MKLROOT)/include
LDFLAGS= -shared -nofor-main -fPIC
LINKLIBS=-fPIC -shared -L$(MKLROOT)/lib/intel64 $(MKLROOT)/lib/intel64/libmkl_blas95_ilp64.a -lmkl_rt -lpthread -lm

sumsquares: sumsquares.f90
    $(FC) $(FFLAGS) -c -fPIC /opt/intel/composerxe-2011.1.107/mkl/include/blas.f90 -o blas95.o
    $(FC) $(FFLAGS) -nofor-main -c -fPIC sumsquares.f90
    $(FC) $(LDFLAGS) sumsquares.o $(LINKLIBS) sumsquares.o

As I said, I can run make without any warnings, but when I run nm sumsquares.so | grep dgemm I see U dgemm_, and when I try to load the .so file, I crash with a segfault (while calling an unrelated subroutine, so I don't think it's related to this code). How do I get the linker to put in the relevant function into the so file?

Update

I am loading the so file in an R script by calling dyn.load in R as follows:

Variation 1:

dyn.load("/home/me/path/sumsquares.so")

Variation 2:

dyn.load("/opt/intel/composerxe-2011.1.107/mkl/lib/intel64/libmkl_rt.so")
dyn.load("/home/me/path/sumsquares.so")

Both variations lead to the same result, with a segfault.



from Recent Questions - Stack Overflow https://ift.tt/2HPNZgt
https://ift.tt/eA8V8J

Can I use python - aiohttp inside of a GCP cloud function? [closed]

I'm trying to route/divvy up some workload to other cloud functions they all take roughly about the same amount of time, but I have to invoke them synchronously. I tried setting this up, and I followed someone's advice when implementing it with Flask to instantiate my loop outside the flask context because it needs control of the main thread(to return too), and everything still seems to be executed synchronously, I just need to gather up some responses in an object. this simple I/O problem doesn't seem to work on GCP Cloud Functions. I've seen this link where it's asked if it's even possible. Thats just plain asynchio, so this should work. if someone has gotten this to work before could you share an example?

loop = asyncio.get_event_loop()
app = Flask(__name__)
CORS(app)

@app.route('/', methods=['POST'])
def calculations():
    async def threaded_calculation_request_operation(session, 
        calculation_meta_data) -> dict: reference in calculations if exists
        url = calculation_meta_data['endpoint_url']
        async with session.post(
            url=url,
            headers={'X-Access-Token': request.headers['X-Access-Token']},
            json=json_safe_response(calculation_meta_data) as response:
        return await response.json()


    async def session_controler():
        async with aiohttp.ClientSession() as session:
            finished_queue = []
            for calculation in calculations_to_perform_queue:
                response = await threaded_calculation_request_operation(session, calculation)
                finished_queue.append(response)
            return finished_queue

    all_returned_charts = loop.run_until_complete(session_controler())
    prccesed_response = processed_for_return(all_returned_charts)
    return prccesed_response, 200


from Recent Questions - Stack Overflow https://ift.tt/3e7wrrU
https://ift.tt/eA8V8J

I want to search a file to find a user name and print that person's name [closed]

I want to search a file by username to find a person and then print out their name. For example, FileName contains a list in the format First,Middle,Last,username: John,Tyler,Smith,johnts Rob,Danial,Wright,robdw Chris,Eric,Graham,chriseg

When I run ./findName.sh johnts it prints out: John,Tyler,Smith,johnts What do I need to do so that it would just print the name John Tyler Smith without the username johnts?

#1 /bin/bash
# findName.sh
searchFile="FileName"
if[[ $1 = "" ]]; then
echo "Command line arguments are not equal to 1"
exit 2
fi
grep -i $1 ${searchFile}
grep -i $1 ${searchFile}
if [[ $? = "1" ]]; then
echo "Sorry that person is not on the list"
fi


from Recent Questions - Stack Overflow https://ift.tt/2TyzhNe
https://ift.tt/eA8V8J

Why a click function of a web page element doesn't work (using Selenium module of Python)?

I am trying to automate a task which can save me thousands of clicks.

I searched a bit for available modules in Python and I have selected to work with Selenium.

I installed Firefox drivers and did some progress but I am stuck for a long time. I finally gave up, opened a Stack Overflow account and wanted to bring this problem into this helpful medium.

My code can successfully do some clicks, but I could not make the code click a button like element. I have to click such items so that page opens some new elements. (Hopefully I am going to click on these new elements to save some excels files automatically).

Here is the part which works as expected:

from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
import time

browser = webdriver.Firefox()
url =  "https://www.tbb.org.tr/tr/bankacilik/banka-ve-sektor-bilgileri/istatistiki-raporlar/59"
browser.get(url)
time.sleep(2)

bank_reports_element_xpath = "//*[@title=  'Tüm Raporlar']"
bank_reports_element = browser.find_element_by_xpath(bank_reports_element_xpath)
bank_reports_element.click()
time.sleep(2)

second_item = "//div[@data-catid = '52']"
finance_tables_element = browser.find_element_by_xpath(second_item)
finance_tables_element.click()

years_item = "//div[@class = 'years']"
years_element = finance_tables_element.find_element_by_xpath(years_item)
year_elements = years_element.find_elements_by_xpath("a")

There I would like to click on the years. a screenshot of the years that I can't click using Selenium

As an example, I get the element related to year 2004.

year2004 = year_elements[2]

Issuing a year2004.click() command gives an ElementNotInteractableException exception.

year2004.click()  # ElementNotInteractableException: Element could not be scrolled into view

Based on searching similar posts, I tried the following (executing the click via javascript). I got no error but it does not do anything. When I click the year2004 button with mouse, a list pops-up in the page. But when I run the below code, no list pops up in the page.

browser.implicitly_wait(4)
browser.execute_script("arguments[0].scrollIntoView();", year2004)
browser.execute_script("arguments[0].click()", year2004)

I tried also the following code. I get "TypeError: rect is undefined"

browser.implicitly_wait(4)
action = ActionChains(browser)
action.move_to_element(year2004)       # gives: TypeError: rect is undefined
action.click(on_element = year2004)    # gives: TypeError: rect is undefined
action.perform()

I tried using Chrome Driver and got similar results. The errors definitions were not exactly the same. Instead of the above "rect is undefined" error, Chrome error is like: "Javascript error: Failed to execute 'elementsFromPoints' on 'Document': Provided double value is non-finite"

I don't know if it is relevant but year2004.location dictionary has a 0 value for "x".

I would appreciate any answer,

Keep safe



from Recent Questions - Stack Overflow https://ift.tt/3jJhr4G
https://ift.tt/eA8V8J

Unpacking a vector into an array of a certain bit width

Suppose I have a vector of bits. I'd like to convert it into an array of n bit values, where n is a variable (not a parameter). Can I achieve this using the streaming operators? I tried this (right now I'm just trying a value of 3, but eventually '3' should be variable):

module tb;
  bit [51:0] vector = 'b111_110_101_100_011_010_001_000;
  byte vector_byte[];
  
  initial begin
    $displayb(vector);
    vector_byte = {<<3{vector}};
    foreach(vector_byte[i])
      $display("%0d = %0b", i, vector_byte[i]);
  end
endmodule

What I was expecting was:

vector_byte = '{'b000, 'b001, 'b010 ... 'b111};

However, the output I got was:

# vsim -voptargs=+acc=npr
# run -all
# 00000000000000000000000000000000111110101100011010001000
# 0 = 101
# 1 = 111001
# 2 = 1110111
# 3 = 0
# 4 = 0
# 5 = 0
# 6 = 0
# exit

Am I just using the streaming operators wrong?



from Recent Questions - Stack Overflow https://ift.tt/31UHHTI
https://ift.tt/eA8V8J

Match and replace words in char-vector

I have a vector with text lines in it, like this:

text<-c("Seat 1: 7e7389e3 ($2 in chips)","Seat 3: 6786517b ($1.67 in chips)","Seat 4: 878b0b52 ($2.16 in chips)","Seat 5: a822375 ($2.37 in chips)","Seat 6: 7a6252e6 ($2.51 in chips)")

And I have to replace some words with other words, that i have in a dataframe like this:

df<-data.frame(codigo=c("7e7389e3","6786517b","878b0b52","a822375","7a6252e6"),
name=c("lucas","alan","ivan","lucio","donald"))

So I would like to 1) Grab the first line of "text" 2) Check if there is any word to replace in df 3) Replace it 4) Do the same with the next "text" line and so on. In order to have something like this:

[1] "Seat 1: lucas ($2 in chips)"
[2] "Seat 3: alan ($1.67 in chips)"
[3] "Seat 4: ivan ($2.16 in chips)"
[4] "Seat 5: lucio ($2.37 in chips)"
[5] "Seat 6: donald ($2.51 in chips)"

There is any formula to do this?



from Recent Questions - Stack Overflow https://ift.tt/2HKacMU
https://ift.tt/eA8V8J

I can't import the js library script p5.js CDN error

Refused to load the script 'https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.1.9/p5.min.js'
because it violates the following Content Security Policy directive: "script-src 'self'
https://cdn.jsdelivr.net/npm/p5@1.1.4/lib/p5.min.js". Note that 'script-src-elem' was not
explicitly set, so 'script-src' is used as a fallback.

I got this error while trying to make some chrome extension right now. I try to use p5.js library. But I still got this error several time. What is the death over here! Could you help me, please



from Recent Questions - Stack Overflow https://ift.tt/2TDGprQ
https://ift.tt/eA8V8J

Using JavaScript to change css display properties for details element on toggle

I have two details element trees but there will be more than that in my project. I want to change the css display properties to none for every details element except the one I just opened. How can I do this? Thank you.

Here is my codepen testing area.

Here is the basic code:

var details1 = document.querySelector("details")

details1.addEventListener("toggle", function() {
  console.log('toggle');
  /*details1.firstChild.textContent = "done"
  I need something like:
  document.querySelector('#'+ details[i](but not the one we just toggled!)style.display = "none";*/
  
})
.details {
  display: in-line;
}
<p>
<details id="agriculture" class="details"><summary>Agriculture</summary>
                <details><summary>Picking & packing</summary></details>
                            <details><summary>Farm worker</summary></details>
                            <details><summary>Irrigationist</summary></details>
                            <details><summary>Tractor operator</summary></details>
                            <details><summary>Pig farmer</summary></details>
                            <details><summary>Station hand</summary></details>
            </details>

      <details id="construction" class="details"><summary>Construction</summary>
       <details><summary>Foreperson</summary></details>
                <details><summary>Plant and Machinery Operator</summary></details>
                                <details><summary>Concreter</summary></details>
                                <details><summary>Paver</summary></details>
                                <details><summary>Fencer</summary></details>
                                <details><summary>Surveyer</summary></details>
            </details>

</p>
edit:

I found a good example of how to use document.getElementsByClassName and I am trying it on my fork of the first codepen which is here.

That's makes them all vanish though. I need to either exlude the one I just toggled or then change it back display in-line again.

I also need to add an event listener to the toggle event for each details tree and this stackoverflow post looks like it help with that.



from Recent Questions - Stack Overflow https://ift.tt/2Ga95p2
https://ift.tt/eA8V8J

2020-10-29

Convert Array to object with custom keys in JavaScript

I have array which I want to convert to object . Like ['jonas','0302323','jonas84@gmail.com]. Now what I want to achieve I want to convert array into object and I want to assign custom keys into that object .

Expected Result : {name:'Jonas',phone:84394934,email:jonas84@gmail.com}. I am beginner to JS could somone please help me



from Recent Questions - Stack Overflow https://ift.tt/35BCl0w
https://ift.tt/eA8V8J

How can i add a new field to my table (collection)?

i have this picture, that is a table, i want to add a new field to my table

enter image description here

the structures is following as:

cities: colleges:fields:attributes

i want to put a new field, i was trying

const myNewField ={
 name: chair
 notebook: true
}
db.collection("cities").doc(city.id).update(myNewField).then(function() {
        console.log("Document successfully written!");
       });


from Recent Questions - Stack Overflow https://ift.tt/3jJLEAU
https://ift.tt/34DvQeu

Is there a way to transform data in Stata from a single observation (e.g. # of patients experiencing an event) into many observations?

I'm trying to efficiently use Stata to estimate standard errors around a proportion of patients experiencing an adverse event in a model we are adapting. An example dataset:

n = 74

a = 56

b = 18

Where n is the number of patients, a is the number of patients experiencing an event and b is the number not experiencing an event.

When the data is in this format, I note that using

ratio myratio: a/n

Returns a proportion (a/n) but does not estimate a linearized standard error. Manually converting the data into "long" format however fixes this issue. Long format being:

No. observations = n (74)

n = 1 for all observations

a = 1 if index <= 18 else 0

b = 1 if index > 18 else 0

It's been a while since I have used Stata, is there a quick way to do this? I can't even remember how to extend the length of the dataset to the number of samples N!



from Recent Questions - Stack Overflow https://ift.tt/2J8YRGA
https://ift.tt/eA8V8J

SIMD support at runtime

I was making a XCode obj-c application, and I decided to turn on AVX2, through XCode's Enable Vector Extensions option.

I started up my app, but it crashed.

After a few hours I figured out that the issue was my Mac actually didn't support AVX2 (third gen i7).

The thing is, I still expected it to work because I had commented out all of the lines of code that used AVX2 instructions.

That meant that there was NO avx2 code even IN my app, I just had AVX2 support on. I was under the assumption that AVX2 was not used until I actually called the functions?

My question is:

How do I get an app that was compiled with the AVX2 instruction set but had conditions at RUNTIME that checked if the machine supported AVX2, and if it didn't, then there would be NO AVX2 instructions activated?



from Recent Questions - Stack Overflow https://ift.tt/3kDc8VZ
https://ift.tt/eA8V8J

Vault wrapping token - number of usage

We are facing issue with fetching secrets from Hashicorp Vaullt. Client is actually using role_id and secret_id to auth in Vault. We also use wrapping function for secret_id, so once secret_id is fetched from Vault, it's wrapped and has to be unwrapped to get real secret_id. Now problem is that wrapping token obtained from Vault has number of usage 1. Meaning that secret_id can be unwrapped only once. When we try 2nd time to unwrap, it is failing. And reason is number of usace for such generated token which is 1 by default.

Key                 Value
---                 -----
accessor            LctZYfQyzJVleDb41l7mACu5
creation_time       1603924396
creation_ttl        240h
display_name        n/a
entity_id           n/a
expire_time         2020-11-07T22:33:16.378745728Z
explicit_max_ttl    240h
id                  s.ajjvwjfjtTedj7xaeGW1B1WL
issue_time          2020-10-28T22:33:16.378758503Z
meta                <nil>
num_uses            1
orphan              true
path                auth/approle/role/img/secret-id
policies            [response-wrapping]
renewable           false
ttl                 239h58m30s
type                service

This is making a lot of issues for us. Is there a way to increase, or set as unlimited number od wrap token usage?

Thank you!



from Recent Questions - Stack Overflow https://ift.tt/31TeHvE
https://ift.tt/eA8V8J

How comes the lifetime of a local variable inside a function be extended?

See the code below. v1 is local variable inside a function. Accordingly, after leaving this fucntion, this variable should be killed. Thus, the move constructor should run into problem in the main function. But actually the outcome is the opposite. In the main function, I can see the contents of v1.

#include <iostream>

#include <vector>

using namespace std;

void my_fn(vector<vector<int>> & v) {
    vector<int> v1 = {1, 2, 3};
    v.push_back(move(v1));
    cout << " " << endl;
}

int main(){
    vector<vector<int>>  v;
    my_fn(v);
    for(const auto & e:v)
        for (const auto e1: e)
            cout << e1 << endl;

    return 0;
}


from Recent Questions - Stack Overflow https://ift.tt/31TeGrA
https://ift.tt/eA8V8J

I need to sum values for previous periods

I need help creating a query to sum the hoursworkedtotal for each period and jobid. I want sum all values prior to the period. For example, FEB20 and jobid 3415 will show a sum of all hoursworkedtotal before FEB20. I have a period id, so that should make life easier.

Many thanks

enter image description here



from Recent Questions - Stack Overflow https://ift.tt/37RNqh0
https://ift.tt/2JgiBZ3

Blank pages when trying to do captcha

Hello i am learning php now and developing website for my education. I am facing problem if i try to add captcha image. I don't know where is the problem but instead of working captcha i get blank page. I even tried few already done captchas from github but get same problem i think the problem could be with fonts but i am not sure "ts probably my stupidity and i am doing something wrong :D" . Anyway if anyone can help me with it it would be great. code i tried to use:

captcha.php

<?php
class captcha {
private static $captcha = "__captcha__";
public static $font;
private static $width = 70;
private static $height = 70;
private static $font_size = 40;
private static $character_width = 40;
private static function session_exists() {
    return isset($_SESSION);
}
private static function set_font() {

    self::$font = self::$captcha;

    $AnonymousClippings ='there is inserted chars from font you can'
  self::$font = tempnam(sys_get_temp_dir(), self::$captcha);

    $handle = fopen(self::$font,"w+");
    fwrite($handle,base64_decode($AnonymousClippings));
    fclose($handle);

    return self::$font;
}

private static function get_random() {

    $type = rand(0,2);

    switch($type) {
        case 2:
            $random = chr(rand(65,90));
        break;
        case 1:
            $random = chr(rand(97,122));
        break;
        default:
            $random = rand(0,9);
    }

    return $random;
}

private static function generate_code($length) {

    $code = null;
    for($i = 0; $i < $length; $i++) {
        $code .= self::get_random();
    }

    if(self::session_exists()) {
        $_SESSION[self::$captcha] = $code;
    }

    self::$width = $length * self::$character_width;
    
    return $code;
}

private static function get_width() {
    return self::$width;
}
private static function get_height() {
    return self::$height;
}

public static function image() {

    $length = 6;

    $code = self::generate_code($length);

    self::set_font();

    ob_start();
    
    $image = imagecreatetruecolor(self::get_width(),self::get_height());

    $white = imagecolorallocate($image, 255, 255, 255);

    imagefilledrectangle($image, 0, 0, self::get_width(), self::get_height(), $white);

    for($dot = 0; $dot < 2000; $dot++) {
        $r = rand(0,255);
        $g = rand(0,255);
        $b = rand(0,255);

        $dot_color = imagecolorallocate($image, $r, $g, $b);

        $x1 = rand(0, self::get_width());
        $y1 = rand(0, self::get_height());
        $x2 = $x1 + 1;
        $y2 = $y1 + 1;

        imageline($image, $x1, $y1, $x2, $y2, $dot_color);
    }

    for($start = - $length; $start < 0; $start++) {
        $color = imagecolorallocate($image, rand(0,177), rand(0,177), rand(0,177));

        $character = substr($code, $start, 1);

        $x = ($start+6) * self::$character_width;
        $y = rand(self::get_height() - 20, self::get_height() - 10);

        imagettftext($image, self::$font_size, 0, $x, $y, $color, self::$font, $character);
        
    }
    
    imagepng($image);
    imagedestroy($image);
    
    $source = ob_get_contents();
    ob_end_clean();

    unlink(self::$font);

    return "data:image/png;base64,".base64_encode($source);

 }
public static function  get_code() {
    if(self::session_exists()) {
        return $_SESSION[self::$captcha];
    }

    return rand();
   }
 }

index.php file

<?php
 session_start();

 require_once("captcha.php");

  if(isset($_POST['rCaptcha'])) {
   echo captcha::image();
  exit;
}
 else if(isset($_POST["code"])) {
  if($_POST["code"] == captcha::get_code()) {
    echo "Good";
  }
    else {
           echo "Bad";
    }

 echo "<br/>";
    }

    ?>
   <script>
   function refreshCaptcha(target) {

  var req = new XMLHttpRequest();

  req.open("POST", window.location, true);
  req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");


   req.onreadystatechange = function() {
    if(req.readyState == 4 && req.status == 200) {
        target.src = req.responseText;
    }
   }

    req.send("rCaptcha=true");
  }
  </script>

  <form method="post" autocomplete="off">
   <fieldset>
    <legend>PHP Captcha</legend>
    
    <input type="text" name="code" placeholder="Captcha Code" /><br/>
    <img src="<?= captcha::image() ?>" onclick="refreshCaptcha(this)" 
    title="click to refresh" /><br/>
    <input type="submit" value="Check" /><br/>
    </fieldset>
   </form>


from Recent Questions - Stack Overflow https://ift.tt/37Pdppb
https://ift.tt/eA8V8J

Use multiple collections with MongoDB Kafka Connector

According with the documentation if you don't provide a value it will read from all collections

"name of the collection in the database to watch for changes. If not set then all collections will be watched."

I saw the connector source code and I confirmed this:

https://github.com/mongodb/mongo-kafka/blob/k133/src/main/java/com/mongodb/kafka/connect/source/MongoSourceTask.java#L462

However if the collection is not provided I got an error like this:

ERROR WorkerSourceTask{id=mongo-source-0} Task threw an uncaught and unrecoverable exception (org.apache.kafka.connect.runtime.WorkerTask:186)
org.apache.kafka.connect.errors.ConnectException: com.mongodb.MongoCommandException: Command failed with error 73 (InvalidNamespace): '{aggregate: 1} is not valid for '$changeStream'; a collection is required.' on server localhost:27018. The full response is {"operationTime": {"$timestamp": {"t": 1603928795, "i": 1}}, "ok": 0.0, "errmsg": "{aggregate: 1} is not valid for '$changeStream'; a collection is required.", "code": 73, "codeName": "InvalidNamespace", "$clusterTime": {"clusterTime": {"$timestamp": {"t": 1603928795, "i": 1}}, "signature": {"hash": {"$binary": "AAAAAAAAAAAAAAAAAAAAAAAAAAA=", "$type": "00"}, "keyId": {"$numberLong": "0"}}}}

This is my configuration file

name=mongo-source
connector.class=com.mongodb.kafka.connect.MongoSourceConnector
tasks.max=1

# Connection and source configuration
connection.uri=mongodb://localhost:27017,localhost:27018/order
database=order
collection=

topic.prefix=redemption
poll.max.batch.size=1000
poll.await.time.ms=5000

# Change stream options
pipeline=[]
batch.size=0
change.stream.full.document=updateLookup
collation=
copy.existing=true
errors.tolerance=all

If a collection is used, I'm able to use the connector and generate topics.

Seeing the logs it appears the connector is connecting to the db:

INFO Watching for database changes on 'order' (com.mongodb.kafka.connect.source.MongoSourceTask:620)

Source Code

else if (collection.isEmpty()) {
      LOGGER.info("Watching for database changes on '{}'", database);
      MongoDatabase db = mongoClient.getDatabase(database);
      changeStream = pipeline.map(db::watch).orElse(db.watch());
    } else

If I go to my mongo console, I'm having the following:

rs0:SECONDARY> db.watch()
2020-10-28T18:13:50.344-0600 E QUERY    [thread1] TypeError: db.watch is not a function :
@(shell):1:1
rs0:SECONDARY> db.watch
test.watch


from Recent Questions - Stack Overflow https://ift.tt/35MGGy4
https://ift.tt/eA8V8J

Pandas Groupby Multiindex for multiple columns [duplicate]

How do you switch the format of a dataframe from a standard single row to multi-index columns? I've tried playing with groupby but it doesn't seem efficient.

+------------+----------+--------+----------+--------+
|  Product   |   Item   | Region | In Stock | Colour |
+------------+----------+--------+----------+--------+
| Electronic | Phone    | Canada | Y        | Black  |
| Electronic | Computer | Canada | N        | Silver |
| Furniture  | Table    | Canada | Y        | Brown  |
| Furniture  | Chair    | Canada | Y        | Black  |
| Electronic | Phone    | USA    | Y        | Black  |
| Electronic | Computer | USA    | Y        | Black  |
| Furniture  | Table    | USA    | N        | Black  |
| Furniture  | Chair    | USA    | Y        | Black  |
| Furniture  | Couch    | USA    | Y        | Black  |
+------------+----------+--------+----------+--------+

to

+------------+----------+----------+--------+----------+--------+
|            |          |       Canada      |         USA       |
+  Product   +   Item   +----------+--------+----------+--------+
|            |          | In Stock | Colour | In Stock | Colour |
+------------+----------+----------+--------+----------+--------+
| Electronic | Phone    | Y        | Black  | Y        | Black  |
|            | Computer | N        | Silver | Y        | Black  |
| Furniture  | Table    | Y        | Brown  | N        | Black  |
|            | Chair    | Y        | Black  | Y        | Black  |
|            | Couch    |          |        | Y        | Black  |
+------------+----------+----------+--------+----------+--------+

Thanks!



from Recent Questions - Stack Overflow https://ift.tt/2Gbkbdy
https://ift.tt/eA8V8J

Copy-paste files to folders that have matching names using R

I am trying to copy files to various folders that have matching filenames.

Here's an extract of the filenames:

20201026_ABCD.txt
20201026_XYZ.txt
20201027_ABCD.txt
20201027_POR.txt
20201028_ABCD.txt
20201028_PQR.txt

I want to create folders that have just the date components from the files above. I have managed to get that far based on the code below:

setwd("C:/Projects/TEST")
        
library(stringr)
        
filenames<-list.files(path = "C:/Projects/TEST", pattern = NULL)
        
#create a variable that contains all the desired filenames
foldernames.unique<-unique(str_extract(filenames,"[0-9]{1,8}"))
    
#create folders based on this variable
foldernames.unique<-paste("dates/",foldernames.unique,sep='')
lapply(foldernames.unique,dir.create,recursive = TRUE)

Now, how do I copy 20201026_ABCD.txt and 20201026_XYZ.txt to the folder 20201026, so on and so forth?



from Recent Questions - Stack Overflow https://ift.tt/2HGSDNu
https://ift.tt/eA8V8J

Use cache by each HTTP Request

I have an AppleService with a cacheable method getApples

@Cacheable("getApples")
public List<Apple> getApples(){
  //fetches apples from external API
}

Then I have the following controller methods:

@GETMapping("/fruits")
getFruits(){
  fruitService.getFruits(); //that internally invokes appleService.getApples();
}


@POSTMapping()
postRequest(){
  aService; //that internally invokes appleService.getApples();
  anotherService; //that internally invokes appleService.getApples();

}

This Spring application is consumed by a frontend that first invokes the @GETMapping("/fruits") method to load info in the page. Later, when the user submits the post request it should first (in aService) make another call to the external API invoked in appleService.getApples() without using cache and the cache should only be used in the anotherService when this invokes appleService.getApples().

However what is happening is that after the getFruits request is invoked to load the page info, then it caches getApples method. And when the user submits the @POSTMapping() request it is using cache in both appleService.getApples() method calls in aService and anotherService.

So how can I use cache only by each http request and not keep cache between different http requests?



from Recent Questions - Stack Overflow https://ift.tt/3muI4fB
https://ift.tt/eA8V8J

Invalid initializer for array member

I'm trying to specify an attribute of a class as being a array of 5 position of the type Stock like follows:

#include "stdio.h"
#include "string"
#include "array"
#include "./stock.h"

#ifndef WALLET_H

class Wallet {
  public:
    Wallet(std::string name, Stock stocks[5]) : name_(name), stocks_(stocks) {}

    //! Calculate de wallet return
    float wallet_return(Stock *stock);

    //! Return the name of the wallet
    std::string get_name();

    //! Return all the stocks in the wallet
    Stock* get_stocks();

  private:
    std::string name_;
    Stock stocks_[5];
};

#endif

std::string Wallet::get_name() {
  return name_;
}

Stock* Wallet::get_stocks() {
  return stocks_;
}

But I keep getting the error invalid initializer for array member 'Stock Wallet::stocks_ [5]', referring to the constructor method.

What I'm I doing wrong?



from Recent Questions - Stack Overflow https://ift.tt/3oF4Mnk
https://ift.tt/eA8V8J

How to run linear regression of a masked array

I am trying to run a linear regression on two masked arrays. Unfortunately, linear regression ignores the masks and regresses all variables. My data has some -9999 values where values where our instrument did not measure any data. These -9999 values produce a line that does not fit the data at all.

My code is this:

from sklearn.linear_model import LinearRegression
import numpy as np
import matplotlib.pyplot as plt

x = np.array( [ 2.019, 1.908, 1.902, 1.924, 1.891, 1.882, 1.873, 1.875, 1.904,
            1.886, 1.891, 2.0, 1.902, 1.947,2.0280, 1.95, 2.342, 2.029,
            2.086, 2.132, 2.365, 2.169, 2.121, 2.192,2.23, -9999, -9999, -9999, -9999,
            1.888, 1.882, 2.367 ] ).reshape((-1,1))
 
y = np.array( [ 0.221, 0.377, 0.367, 0.375, 0.258, 0.16 , 0.2  , 0.811,
          0.330, 0.407, 0.421, -9999, 0.605, 0.509, 1.126, 0.821,
          0.759, 0.812, 0.686, 0.666, 1.035, 0.436, 0.753, 0.611,
          0.657, 0.335, 0.231, 0.185, 0.219, 0.268, 0.332, 0.729 ] )

    
model = LinearRegression().fit(x, y )

r_sq = model.score( x, y )

print( 'coefficient of determination:', r_sq)
print( 'intercept:', model.intercept_)
print( 'slope:', model.coef_)

x_line = np.linspace (x.min(), x.max(), 11000)
y_line = (model.coef_* x_line) + model.intercept_
fig, ax1 = plt.subplots( figsize = ( 10, 10) )
plt.scatter( x, y )
plt.plot( x_line, y_line )
plt.show()

Which gives us this scatter plot with the regression plotted. Note: most of the values are in the upper right hand corner...they're too close together to differentiate.

Is there a way to run the regression while ignoring the masked -9999 values?



from Recent Questions - Stack Overflow https://ift.tt/31TeQPI
https://ift.tt/eA8V8J

How is the C# Delegate Action written in F#?

How to implement a C# Action in F#?

I have the following code in C# code-behind:

public MainWindow()
        {
            InitializeComponent();
            ViewModel = new ViewModel();
            DataContext = ViewModel;
        }

        private void ListView_PreviewMouseLeftButtonUp(object _, MouseButtonEventArgs e)
        {
            _closeAdorner();
        
            // listView here equals object _  
            var listView = (ListView)e.Source;
            var grid = (Grid)listView.Parent;
            var selecteditem = (InnerRow)listView.SelectedItem;
            ViewModel.Visit = selecteditem;
            ViewModel.LastName = selecteditem.LastName;
        
            var adornerLayer = AdornerLayer.GetAdornerLayer(grid);
            if (adornerLayer == null)
                throw new ArgumentException("datagrid does not have have an adorner layer");

            var adorner = new DataGridAnnotationAdorner(grid);
            adornerLayer.Add(adorner);
        
           _closeAdorner = () => adornerLayer.Remove(adorner);
        }

I am attempting to translate this into F#:

let handlePreviewMouseLeftButtonUp (obj: obj) (a, c) =
      let e = (obj :?> MouseButtonEventArgs)
      let listView = e.Source :?> ListView   // This is the ListView control that was clicked.
      let grid = listView.Parent :?> Grid
          
      let selectedItem = c.InnerRows |> List.filter (fun r -> Some r.Id = c.SelectedInnerRow) |> List.head
    
      let adorner = DataGridAdorner(grid)

      let installAdorner =
        let adornerLayer = AdornerLayer.GetAdornerLayer(grid)
        if (adornerLayer.GetAdorners = []) then adornerLayer.Add(adorner) else adornerLayer.Remove(adorner)
 

The last line: if (adornerLayer.GetAdorners = []) then adornerLayer.Add(adorner) else adornerLayer.Remove(adorner)

clearly does not compile and is not correct. How is the C# _closeAdorner written to have the same function in F#?

Thank you.

TIA



from Recent Questions - Stack Overflow https://ift.tt/37OCocj
https://ift.tt/eA8V8J

Need to find no of logins each week MongoDB

I have two collections. I am trying to find the count of logins based upon a LoggedTime field. I would like to get the no of logins per week for past five weeks.

I have two collections.

collection 1 : Role
Fields : Role, UserName , loggedTime

collection 2 :mysite
Fields : userName ,userEmail ,name

In collection 1: eg :

{ 'Role' :"admin" 'UserName' : "abc.efg", 'loggedTime' : 2020-06-24T18:12:03.455Z, } In collection 2: eg:

{ 'userName' : "abc Mr, efg" , 'userEmail' : "abc.efg@company.com" , 'name' : 'orgname' }

Is there any way where we can have a new collection which has count of no of logins(based on loggedTime) per week by each orgname for past 5 weeks.

Basically trying to get result like collection 3: { name :'orgname', 'Logins current week':'no of logins' 'Logins previous week' : 'no of logins' 'Logins 3rd week' :'no of logins' 'Logins 4th week' :'no of logins' 'Logins 5th week': 'no of logins' }

Thanks in advance



from Recent Questions - Stack Overflow https://ift.tt/35DUomW
https://ift.tt/eA8V8J

Updating text on a label

Working through an Oreilly Tutorial on tkinter and the code provided in the tutorial doesn't work for me. The "Choose one" message doesn't show, instead it shows: PY_VAR0. When I click the hello button nothing happens. When I click the goodbye button the window closes as expected but no message is shown.

Of note, prior I had:

def say_hello(self):
  self.label.configure(text="Hello World!")

def say_goodbye(self):
  self.label.configure(text="Goodbye! \n (Closing in 2 seconds)")
  self.after(2000, self.destroy)

And received an attribute error: attributeerror: '_tkinter.tkapp' object has no attribute 'label' site:stackoverflow.com.

I am uncertain what is wrong as I have followed the example explicitly in both cases.

My code is below:

import tkinter as tk

class Window(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title('Hello Tkinter')
        self.label_text = tk.StringVar()
        self.label_text.set("Choose One")

        label = tk.Label(self, text=self.label_text)
        label.pack(fill=tk.BOTH, expand=1, padx=100, pady=30)

        hello_button = tk.Button(self, text='Say Hello',
                                 command=self.say_hello)
        hello_button.pack(side=tk.LEFT, padx=(20, 0), pady=(0, 20))

        goodbye_button = tk.Button(self, text ='Say Goodbye',
                                   command=self.say_goodbye)

        goodbye_button.pack(side=tk.RIGHT, padx=(0, 20), pady=(0, 20))


    def say_hello(self):
        self.label_text.set("Hello World!")

    def say_goodbye(self):
        self.label_text.set("Goodbye! \n (Closing in 2 seconds)")
        self.after(2000, self.destroy)


if __name__ == "__main__":
    window = Window()
    window.mainloop()



from Recent Questions - Stack Overflow https://ift.tt/31RgKAo
https://ift.tt/eA8V8J