text:
Q: MySQLi and OOP PHP Error Parse error: syntax error, unexpected '$this' (T_VARIABLE), expecting function (T_FUNCTION) in C:\xampp\htdocs\Login-OOP\classes\class.user.php on line 28

The above is the error I get, my class.user.php is:
<?php
class Users {
    public $db;
    public function __construct() {
        $this->db = new mysqli("localhost", "root", "<removed for privacy>", "oop");
    }

    public function login($username, $password) {
        $stmt = $this->db->prepare("SELECT username, password FROM users WHERE username=$username AND password=$password");
        $stmt->bind_param('ss', $username, $password);
        $stmt->execute();
        $stmt->bind_result($username, $password);
        $stmt->store_result();
        if($stmt->num_rows == 1) {
            while($stmt->fetch()) {
                $_SESSION['username'] == $username;
                header("Location: home.php");
                exit;
            }
        }
        else {
            header("Location: index.php?e=invalidlogin");
            exit;
        }
        $stmt->close();
        $stmt->free_result();
    }
    $this->db->close();
}
?>

So, is there anything that can be done? I am trying to access my index.php so, if you need my index.php, here it is:
<?php
    session_start();

    include "classes/class.user.php";

    if(isset($_REQUEST['submit'])) {
        extract($_REQUEST);
        $login = $users->login($username, $password);
    }
?>
<!DOCTYPE html>
<head>
    <title>Login</title>
</head>
<body>
    <form method="POST" action="" name="submit">
        <input type="text" name="username">
        <input type="password" name="password">
        <input type="submit" name="submit" value="submit">
    </form>
</body>
</html>

I hope there is a solution for this error, I think this is a weird error. Can you suggest what has caused this error? Also if I am using any of my code in an in-secure way, please let me know to improve my habits.

A: Move this $this->db->close(); inside your  public function login($username, $password)
which is...
$stmt->free_result();
           }
           $this->db->close();
           }
         ?>

to
           $stmt->free_result();
           $this->db->close();
    }
}
?>

A: You have made mistake here. $this->db->close();
try to close database connection in destructor
public function __destruct()
{
    $this->db->close();
}


text:
Q: How can I export a component containing and function and then use that function in another component? I am exporting a component with functions but when I try to use its functions in another component it is throwing an undefined. I have imported it properly but I can't seem to use the functions.
import React from 'react';

export default class TeamStore extends React.Component {
    _state: {
        team: "None",
        loaded: false
    }

    getState() {
        return this._state.team;
    }

    addTeam(team) {
        this._state.team = team;
        this.onChange();
    }

    onChange() {}
}

import React from 'react';
import Jumbotron  from 'react-bootstrap/lib/Jumbotron';
import TeamStores from './TeamStore';

export default class JumbotronNews extends React.Component {
    getStateFromStore() {
        return  TeamStores.getState(); //this is the one throwing the error

    }

    constructor() {
        super();

        this.state = this.getStateFromStore();
    }

    componentDidMount() {
        TeamStore.onChange = this.onChange;
    }

    onChange() {
        this.setState(this.getStateFromStore());
    }

    render() {
        return (
                <Jumbotron>

{this.state.team}

                  </Jumbotron>
        )
    }

}

A: I see a few problems.

*

*You defined TeamStore as a class, but you're using it like a regular object that has functions defined on it. If you want to keep it as a class, you'll have to instantiate it first before calling the functions.

*You defined the TeamStore class as an extension of React.Component, but you're not using it as a React component.

*In your JumbotronNews file, you import TeamStore as TeamStores, but you use it componentDidMount as TeamStore.

A: What you want is called a Mixin , here is an example:
var SetIntervalMixin = {
  componentWillMount: function() {
    this.intervals = [];
  },
  setInterval: function() {
    this.intervals.push(setInterval.apply(null, arguments));
  },
  componentWillUnmount: function() {
    this.intervals.map(clearInterval);
  }
};

var TickTock = React.createClass({
  mixins: [SetIntervalMixin], // Use the mixin
  getInitialState: function() {
    return {seconds: 0};
  },
  componentDidMount: function() {
    this.setInterval(this.tick, 1000); // Call a method on the mixin
  },
  tick: function() {
    this.setState({seconds: this.state.seconds + 1});
  },
  render: function() {
    return (

        React has been running for {this.state.seconds} seconds.

    );
  }
});

Check Mixin on this page : https://facebook.github.io/react/docs/reusable-components.html
Also a different implementation based on ES6 is possible : https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750

redpajama_set_name: RedPajamaStackExchange


text:
Q: Upgrading from phpseclib 2 to 3 I inherited a project years ago and and we started randomly having issues with phpseclib 2.x not decrypting anymore just a few days ago and I'm pulling my hair out on this one. No code changed in our projects but the decrypt function literally stopped working, encryption is fine, but even in a test environment decrypting does nothing, and the errors are none or basically so vague they are useless. So, we went to 3.0 but the original developer of this project didn't use an initialization vector as it wasn't required in version 2, it is required in version 3.
My question is how do we decrypt using AES with no IV in version 3? I can't find anywhere in the documentation how to do this and phpseclib throws an error if I don't provide an IV.
So basically, before:
$aes = new AES();
$aes->setKey('secret_key');
$enc_data = $aes->encrypt('abcdefg');
$dec_data = $aes->decrypt($enc_data);

New version:
$aes = new AES('cbc'); //or whatever cipher
$aes->setIV('something');
$aes->setKey('secret_key');
$enc_data = $aes->encrypt('abcdefg');
$dec_data = $aes->decrypt($enc_data);

Now in 3.0, AES requires a cypher to be declared which looks like CBC was the default in 2, but I cannot see what to do if no IV was added in 2.0 and it needs to be added in 3.0. I have tried but can't add '', passing no argument at all, null, etc., so it's like if someone didn't use an initialization vector using version 2, they can't decrypt using 3...? I looked through the 2.0 documentation and it defaults to and empty string from what I can tell, I can't pass that in 3.0.
Has anyone run into this? Anyone have a good idea on how to fix it? I completely removed 2.0 from this server and re-added it and I still can't decrypt with it, I'm guessing some update in apache or php broke something but I can't reproduce it on my other servers.

A: In V2, CBC and a zero IV are used by default, i.e. an IV with 16 0x00 values. In V3, mode and IV must be explicitly specified.
The following codes therefore result in the same ciphertext:
With V2:
$key = hex2bin("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
$plaintext = "The quick brown fox jumps over the lazy dog";
$aes = new AES();
$aes->setKey($key);
$enc_data = $aes->encrypt($plaintext);
$dec_data = $aes->decrypt($enc_data);

print(bin2hex($enc_data) . PHP_EOL); // bce46469e2f7ab6b7ea767bd3252529a843ba24e890e567ef600c4a6e1051ffc2012305e362438463838fad4043c22a6
print($dec_data . PHP_EOL); // The quick brown fox jumps over the lazy dog

With V3:
$key = hex2bin("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
$iv = hex2bin("00000000000000000000000000000000");
$plaintext = "The quick brown fox jumps over the lazy dog";
$aes = new AES('cbc');
$aes->setKey($key);
$aes->setIV($iv);
$enc_data = $aes->encrypt($plaintext);
$dec_data = $aes->decrypt($enc_data);

print(bin2hex($enc_data) . PHP_EOL); // bce46469e2f7ab6b7ea767bd3252529a843ba24e890e567ef600c4a6e1051ffc2012305e362438463838fad4043c22a6
print($dec_data . PHP_EOL); // The quick brown fox jumps over the lazy dog

Note that a static IV, like a zero IV, is insecure.


text:
Q: Elastic Beanstalk over SSL on Cloudflare I am using ElasticBeanStalk on AWS as part of my Parse environment. The Elastic Beanstalk URL is myparseapp.elasticbeanstalk.com. When a user registers for an account on my site ("www.example.com"), Elastic Beanstalk works its magic.
That worked fine until I enabled SSL on the soon-to-be-production website and tested it. Registration fails, and I see this in the developer console:

parse.min.js:16 Mixed Content: The page at
  'https://www.example.com/register.html' was loaded over HTTPS, but
  requested an insecure XMLHttpRequest endpoint
  'http://myparseapp.elasticbeanstalk.com/parse/users'. This request has
  been blocked; the content must be served over HTTPS.

I understand why I'm receiving the error. I'm not clear on how to resolve it. Everything I read says "register your domain, get an SSL cert, attach a CNAME (www) using Route 53, apply it to the load balancer. Done."
Well... 1) I already have a domain which is used for my website. 2) My SSL is being served via Cloudflare, which is where SSL terminates. 3) Why would I assign the CNAME 'www' to Elastic Beanstalk when my www.example.com is my actual website? Wouldn't using the CNAME "www" break my site? 4) My Elastic Beanstalk instance isn't behind a load balancer.
Do I need to create a separate domain just for elastic beanstalk? That doesn't sound right. I could see making it a subdomain perhaps, such as parseapp.example.com.
Since I'm using Cloudflare (and I like it), I would prefer not to use Route 53 for this... but if it's my only choice, then so be it.
So, in summary, how do I access my Elastic Beanstalk app over SSL using Cloudflare?
Thank you in advance for any assistance.

A: Without looking at all your configuration in CloudFlare, here is how we setup our system for Parse with CloudFlare and AWS.
If Parse Server instance (on elasticbeanstalk) cannot handle HTTPS:

*

*Setup a subdomain parse.example.com with CloudFlare as a CNAME with an alias of myparseapp.elasticbeanstalk.com.

*Make sure the cloud icon is orange (turned on).

*Go to the Crypto tab in CloudFlare and make sure it is set to Flexible. Doing so will have all requests to any example.com domain go through CloudFlare which will use CloudFlare's SSL, but then CloudFlare will route that request to your elasticbeanstalk.com in either HTTP or HTTPS.

*Make sure your Parse Server URL is now set to https://parse.example.com/parse (as defined in your CNAME). This will make your Ajax request look like: https://parse.example.com/parse/users instead of the previous URL.

If you can setup SSL certificates on your instance, you can configure CloudFlare to provide you with Origin Certificates that you can install on your instance (see Crypto tab, under Origin Certificates). Those certificates are there to secure the connection between CloudFlare and the origin server, in your case ElasticBeanstalk. If you do this, then you should still follow the steps above, but instead of selecting Flexible on SSL, use Full.


text:
Q: z-index not bringing element to top I have a div which is a picture of a downwards arrow and when the user clicks it, it should decrement a number, however I cannot get the click to fire because it seems to be below another element.
To explain the html, it is two bootstrap grid system rows, but the downwards arrow image is in the top row, however, it is dropped down low, so the bottom row goes over top of it.
image:

Here is the css of the downwards arrow (it has a high z-index):
#down-arrow-icon {
  background: url("../../assets/images/home_page/down-arrow.svg") center no-repeat;
  background-size: 100%;
  width: 40px;
  height: 40px;
  z-index: 9999;
}

html:

      11

        KILOMETERS

OF

How do I make the downwards arrow be on top so that it registers the clicks?

A: z-index will work only for positioned elements (position:absolute, position:relative, or position:fixed).
Thus, add position:relative/absolute/fixed to your CSS.
ie, your new CSS would be like
#down-arrow-icon {
  background: url("../../assets/images/home_page/down-arrow.svg") center no-repeat;
  background-size: 100%;
  width: 40px;
  height: 40px;
  position:relative;
  z-index: 9999;
}

A: Please apply position: relative for z-index to work
#down-arrow-icon {
  background: url("../../assets/images/home_page/down-arrow.svg") center no-repeat;
  background-size: 100%;
  width: 40px;
  height: 40px;
  position: relative
  z-index: 9999;
}


text:
Q: Oracle DB LIKE query on NULL values This question is about Oracle DB. I want to know how Oracle DB query LIKE clause works on NULL values.
Select * From table_name where column_name like 'text%'

In above query, how the Oracle db treat to rows with null value for column 'column_name'? Also how about 'NOT LIKE'.
Also, I observed that rows having NULL values are not selected for the following query.
Select * From table_name where column_name NOT LIKE 'text%'  .

I don't know why rows having NULL values for the column are not in results even though they are null and hence not like 'text%' .

A: NULL values basically fail all comparisons.  The general idea is that NULL means "I don't know what the value is".  So, when you use like with the pattern 'text%', the answer is "I don't know what the value is".  It is NULL.
And if you use not like, the answer is the same "I don't know what the result is".
That is how NULLs work.  Even with like and not like.  Even with Oracle.

A: First one,
  When you search for column_name like 'text%', db search for string that starts with "text" not other string, it doesn't matter what will come after the text. It could be anything like text123,text stack etc.
Second one,
  When you search for NOT LIKE 'text%', db search for all the columns that should not be started with text, it the column value have text it will not be in the result. it is like "atext", it will be appear in the search results.
So in both condition NULL values never match so they don't come in the results.
Hope it will help.

A: Try this,
SELECT *
FROM table_name
WHERE NVL(column_name,1) NOT LIKE NVL('',2) -- '' OR NULL you can use

A: Try this,
SELECT *
FROM table_name
WHERE NVL(column_name,1) NOT LIKE NVL('',2) -- '' OR NULL you can use


text:
Q: Jetpack Compose nested theming preview Let's consider the following @Composable functions:
@Composable
fun WelcomeScreen() {
    ...
    ButtonTheme {
        Button(...) {...}
    }
}

@Composable
@Preview
fun MockWelcome() {
    AppTheme {
        WelcomeScreen { }
    }
}

@Composable
@Preview
fun MockDarkWelcome() {
    AppTheme(darkTheme = true) {
        WelcomeScreen { }
    }
}

And theme (note: AppTheme follows the same logic):
@Composable
fun ButtonTheme(darkTheme: Boolean = isSystemInDarkTheme(), content: @Composable () -> Unit) {
    MaterialTheme(
        ...
        colors = if (darkTheme) darkButtonColorPalette else lightButtonColorPalette,
    )
}

The preview window will show both WelcomeScreen versions correctly but the dark version will not show the button in the dark theme.
Running the app everything is OK, this it's only a preview "problem".
So, my question is: is this intended behaviour, a bug, or a misconfiguration?
Full code here: https://github.com/GuilhE/JetpackChallenge

A: If you join together the previews and screen together you effectively have something like this:
AppTheme(darkTheme = true) {
    ButtonTheme {
        Button(...) {...}
    }
}

So the ButtonTheme will always be used no matter what theme you use in preview - the preview theme is overridden always.
To make the previews work as you want you'd need to abstract ButtonTheme outside of WelcomeScreen so something like this:
@Composable
fun MyApp() {
    ...
    MyTheme {
        WelcomeScreen()
    }
}

@Composable
fun WelcomeScreen() {
    ...
    Button(...) {...}
}

@Composable
@Preview
fun MockWelcome() {
    AppTheme {
        WelcomeScreen { }
    }
}

@Composable
@Preview
fun MockDarkWelcome() {
    AppTheme(darkTheme = true) {
        WelcomeScreen { }
    }
}


text:
Q: In Erlang is there any way that a message sender can wait on a response? In Erlang is there any way that a message sender can wait on a response, so it only continues execution once the message has been processed?
And I mean something like this:
Actor ! DoSomething
Continue to this next line of code when DoSomething has been processed

I know a callback can be made by sending the Pid of the sender, but is there any other way to wait?

A: You could use a receive block:
http://www.erlang.org/doc/reference_manual/expressions.html#id2270724
Reading from the doc:

receive never fails. Execution is
  suspended, possibly indefinitely,
  until a message arrives that does
  match one of the patterns and with a
  true guard sequence.

In other words, send a message and wait for a reply.

A: If the receiving process is a gen_server, you can use gen_server:call.  E.g.:
gen_server:call(Pid, Message),
% At this point, we know that the other process has answered.

A: First thing to understand is that Erlang was built to deal with asynchronous message passing. As such, the only way to have synchronous message passing is to implement something akin to an acknowledgement.
Imagine two processes, P1 and P2. P1 might run the following code:
%% process P1 takes the Pid of P2 as a parameter
%% and a Message to pass on to P2
p1(P2, Message) ->
    P2 ! {self(), Message},
    receive
        {P2, ok}
    after 5000 -> % this section is optional, times out after 5s
        exit("P2 didn't process this!") % this kills P1
    end.

P2, on its side might just run the following:
p2() ->
    receive
        {From, Message} ->
            io:format("P2 received message ~p~n",[Message]),
            %% processing is done!
            From ! {self(), ok}
    end.

So then you might spawn p2 as a new process. This one will sit waiting for any message. When you then call p1, it sends a message to P2, which then processes it (io:format/2) and replies to P1. Because P1 was waiting for a reply, no additional code was run inside that process.
That's the basic and only way to implement blocking calls. The suggestions to use gen_server:call roughly implement what I've just shown. It's hidden from the programmer, though.

A: No, there is only asynchronous message passing.
If you want to be a little philosophical then it is very difficult to automatically define when a message has been processed. Is it when the message has arrived at the process, been received but not yet acted upon or at sometime when it has been acted upon by the receiving process. It is similar to getting automatic notification when someone has "read" my mail. Yes, they have seen it but they have really read it?

A: Just depends on the situations jldupont. If a web browser makes a request to webmachine for some long running erlang resource, there's no way to use a cast to fulfill that request.


text:
Q: Use a shell script to replace text with pwd file.txt
...
<LOCAL_PATH_TO_REPO>/src/java/example.java
...

^A longer file but this pretty much explains what I am trying to do.
script.sh
dir=$(pwd)
# replace <LOCAL_PATH_TO_REPO> with dir

I tried using the sed command but it did not work for some reason. Any ideas on how to do this?

A: Your error means you have backslashes in the variable text.
The simplest solution is to change the delimiter to the one that does not occur in the variable text.
If there are no commas use a comma:
sed -i "s,LOCAL_PATH_TO_REPO,$PWD," file.yml

The -i flag introduces changes into the input file (works for GNU sed).


text:
Q: Using 2 NumericUpDown fields to maintain Dimensions aspect ratio I have two NumericUpDown text fields. They are used for Image Dimensions. I've done it before but I don't remember how I did it. I've looked at over 20 related questions on here but they're not really the same question. The logic and math is totally different than what I need.
Basically, numericUpDown1 is for Width and numericUpDown2 is for Height. When the numericUpDown1 value is changed (either by using arrows or typing), numericUpDown2 must auto change as well, while maintaining the correct aspect ratio.
How can I do this? I'm really lost.

A: If the aspect ratio is simply defined like this: Width/Height, you should implement both the ValueChanged events of the two NumericUpDown controls: in the event for the numericUpDown1 (for width) you should set the new height value by dividing the numericUpDown1.Value by the aspect ratio; in the other event you should multiply numericUpDown2.Value by the aspect ratio in order to get the new width.

A: *

*Keep the original values, as the base for the calculation. This will prevent rounding errors.

*Set a flag to indicate that you are adjusting the other control(s) from your code, and they should not react to their events. So you don't end up in an endless loop.


text:
Q: Determining probability of association between elements in a large number of paired sets Please excuse me if this is the wrong place to ask (new here)...

I am trying to come up with a quantitative method for determining the association between two elements in different sets - something like a probability.
I have a large list of pairs of sets of unique first names and unique last names. The first set in each pair contains a list of first names. The second set in each pair contains a list of last names.
Each pair of sets is related, but not guaranteed to be exhaustive, i.e. every first name in the first set may not have its corresponding last name and vice versa - every last name in the second set may not have its corresponding first name. However, we can add the assumption that for every first name there exists only one last name if that helps simplify the problem. We can also assume that my list of sets is exhaustive over the space of first name, last name pairings - i.e. the union of all of the lists of first names covers the entire space of first names and the union of all of the lists of last names covers the entire space of last names.
I would like to develop a model returning the probability that a given last name belongs to or is associated with a given first name.
A simple example:
set-pair-1: [(john, jacob, amelia) --> (smith, jones)]
set-pair-2: [(john, amelia) --> (jones)]
set-pair-3: [(jacob, amelia) --> (robertson, smith, jones)]
set-pair-4: [(john, jacob) --> (smith, robertson)]
Attempted solution:
Working under the assumption that this list of set pairs is exhaustive over the entire space of first name, last name pairs:
From set-pair-1 we know that john, jacob and amelia could have the last name smith or jones.
(john --> (smith, jones), jacob --> (smith, jones), amelia --> (smith, jones))
From set-pair-2 we gain additional information that john or amelia could have the last name jones.
(john --> (smith, jones, jones), amelia --> (smith, jones, jones))
From set-pair-3 we gain the additional information that jacob and amelia could have the last name robertson, as well as another observation that their last names could be smith or jones.
(jacob --> (smith, jones, robertson, smith, jones), amelia --> (smith, jones, jones, robertson, smith, jones))
Finally, from set-pair-4 we get additional information that john and jacob could have the last name smith or robertson.
(jacob --> (smith, jones, robertson, smith, jones, smith, robertson), john --> (smith, jones, jones, smith, robertson))

This leaves us with the possible relations:
jacob --> (smith, jones, robertson, smith, jones, smith, robertson)
john --> (smith, jones, jones, smith, robertson)
amelia --> (smith, jones, jones, robertson, smith, jones)

I reason that since robertson is most likely to appear in association with jacob, jacob's last name is probably robertson.
Similiarly, since jones is most likely to appear in association with amelia, I guess that amelia's last name is probably jones.
And since there's only one unknown pair left, I assume that john's last name is smith.
Questions:

*

*Is there a way to generalize this logic?

*Is my logic correct?

*How can I add probabilities for when there's no clear answer?


text:
Q: Django: How to set default language in admin on login I'm saving an user's default language in his user profile and on login I want to set the admin's default language to it.
One possibility I was thinking of is using a middleware, but I think if I do it on process_request I will not see an user object there since this is processed AFTER the middleware, so I could only set it after the next request!
Any solutions are highly appreciated!

A: The sad thing is Django doesn't send any signals on Login/Logout (apparently there's a ticket open for that at http://code.djangoproject.com/ticket/5612).
But looking around I found a rather simple and elegant solution for implementing signals on login/logout without touching Django's code: http://charlesleifer.com/blog/hooking-into-djangos-login-and-logout-two-approaches/

A: You can do follow:
In templates/admin/login.html
<script type="text/javascript">
            $(function(){
                $.ajax({
                    type : 'POST',
                    url : "{% url 'setLangueDefault' %}",
                    dataType : 'JSON',
                    success : function(data) {
                        //
                    }
                });
            });
        </script>

In frontend/urls.py
urlpatterns = patterns('frontend.views',
    ...
    url(r'^set-language-default/$', views.setLangueDefault, name='setLangueDefault'),
    ....

)
In frontend/views.py
from django.conf import settings
...
def setLangueDefault(request):
    language = settings.LANGUAGE_CODE
    if hasattr(request, 'session'):
        if 'django_language' in request.session:
            language = request.session['django_language']
    if language:
        request.session['django_language'] = language
    if request.is_ajax():
        message = {'status' : 0, 'info' : 'done'}
        return JsonResponse(json.dumps(message))
    return HttpResponseRedirect('/')

Note config default language in settings.py
Exp: LANGUAGE_CODE = 'vi'


text:
Q: Can i create rows in different tables all in one query? I'm trying to create multiple rows at the same time, each row implements previous rows Primary key. Is there a way i can make all this happen in one query instead of creating multiple query's for doing it, like shown in code sample?
public void CreateMessage(int profileId, String text, int chatId)
    {
        string stmt = "INSERT INTO Activity (profileID, timeStamp) OUTPUT INSERTED.activityID values (" + profileId + ", '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "')";
        SqlDataReader reader = new SqlCommand(stmt, con).ExecuteReader();
        reader.Read();

        stmt = "INSERT INTO Text(activityID, message) OUTPUT INSERTED.textID values(" + Int32.Parse(reader["activityID"].ToString()) + ", (select cast('" + text + "' as varbinary(max))))";
        reader.Close();
        reader = new SqlCommand(stmt, con).ExecuteReader();
        reader.Read();

        stmt = "INSERT INTO Message (textID, chatID) values (" + Int32.Parse(reader["textID"].ToString()) + ", " + chatId + ")";
        reader.Close();
        new SqlCommand(stmt, con).ExecuteNonQuery();
    }

A: SqlDataReader is used to read data in a secuential way. You retrieve data from a select or a stored procedure call and read a record at a time.
If you want to execute a block of commands you could use a transaction in your code, check SQlConnection.BeginTransaction, or delegate that task to the database using a stored procedure (which internally should use a transaction).

A: Normally you could just put a semicolon between statements and send multiple commands in as one string. However, you're using the results of one statement in the next. This means that you MUST run each statement one at a time and read the results before executing the next.
You can do that in c# or in an SQL stored procedure. In either case you can use transactions to ensure all get written at once.

A: It is possible the only thing you had to do is enter a ; between the different insert lines, see example below:
public void CreateMessage(int profileId, String text, int chatId)
    {
        string stmt = "INSERT INTO Activity (profileID, timeStamp) OUTPUT INSERTED.activityID values (" + profileId + ", '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "')";
        SqlDataReader reader = new SqlCommand(stmt, con).ExecuteReader();
        reader.Read();

        stmt = "INSERT INTO Text(activityID, message) OUTPUT INSERTED.textID values(" + Int32.Parse(reader["activityID"].ToString()) + ", (select cast('" + text + "' as varbinary(max))))";
        reader.Close();
        reader = new SqlCommand(stmt, con).ExecuteReader();
        reader.Read();

        stmt = "INSERT INTO Message (textID, chatID) values (" + Int32.Parse(reader["textID"].ToString()) + ", " + chatId + ")";
        reader.Close();
        new SqlCommand(stmt, con).ExecuteNonQuery();
    }

will become
    public void CreateMessage(int profileId, String text, int chatId)
        {
            string stmt = "INSERT INTO Activity (profileID, timeStamp) OUTPUT INSERTED.activityID values (" + profileId + ", '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff") + "');
INSERT INTO Message (textID, chatID) values (" + Int32.Parse(reader["textID"].ToString()) + ", " + chatId + ");
INSERT INTO Text(activityID, message) OUTPUT INSERTED.textID values(" + Int32.Parse(reader["activityID"].ToString()) + ", (select cast('" + text + "' as varbinary(max))))";
            SqlDataReader reader = new SqlCommand(stmt, con).ExecuteReader();
            reader.Read();
        }

I hope this will solve your problem, If i'am wrong say it! Good Luck

A: It is better to wrap this code in a stored procedure, but it is possible without it. Pay attention to the transaction, it is necessary to preserve the integrity of the data.
        public void CreateMessage(int profileId, String text, int chatId)
        {
            string stmt = string.Format(
@"DECLARE @profileId int;
DECLARE @text nvarchar(4000);
DECLARE @chatId int;
DECLARE @id int;

SELECT
    @profileId = {0},
    @chatId = {1},
    @text = N'",
                profileId.ToString(), chatId.ToString());

            stmt += text;
            stmt +=
@"';

BEGIN TRAN;

INSERT INTO Activity (profileID, timeStamp) VALUES(@profileId, getdate());
IF @@ERROR = 0
    SET @id = @@IDENTITY;
ELSE
    GOTO on_roll_back;

INSERT INTO Text (activityID, message) values(@id, (select cast(@text as varbinary(max))));
IF @@ERROR = 0
    SET @id = @@IDENTITY;
ELSE
    GOTO on_roll_back;

INSERT INTO Message (textID, chatID) values (@id, @chatId);
IF @@ERROR = 0 BEGIN
    COMMIT TRAN;
    GOTO on_finish;
END;

on_roll_back:
ROLLBACK TRAN;

on_finish:";

            using (SqlCommand cmd = conn.CreateCommand())
            {
                cmd.CommandText = stmt;
                cmd.ExecuteNonQuery();
            }
        }


text:
Q: How to implement adobe analytics in Next Js (React )? I have given the requirement to add adobe analytics in the react js application that I have built.
Please apologize me that I don't have any basic idea/ understanding on how to implement it, So help from experts would be very helpful for me.
Requirement is that I need to implement the adobe analytics in the next js with typescript project that I have built in..
I could find only google analytics sample here in official documentation but not adobe..

The complete sample working application code here...

Index.tsx:
import React from "react";
import Container from "@material-ui/core/Container";
import Typography from "@material-ui/core/Typography";
import Box from "@material-ui/core/Box";
import Link from "../src/Link";

export default function Index() {
  return (
    <Container maxWidth="sm">
      <Box my={4}>
        <Typography variant="h4" component="h1" gutterBottom>
          Next.js with TypeScript example
        </Typography>
        <Link href="/about" color="secondary">
          Go to the about page
        </Link>
      </Box>
    </Container>
  );
}

From the source code given in the link, please help me where should I start and how exactly should I need to implement Adobe Analytics?
I found the link for SSR here,  https://docs.adobe.com/content/help/en/experience-manager-65/developing/headless/spas/spa-ssr.html but it doesn't provide necessary details about implementation inside code.
Raised a query here: https://github.com/zeit/next.js/discussions/10679 but I couldn't get the appropriate help from anyone..
As like the question title indicates, I am in the need of adobe analytics implementation and strictly not google analytics..
I humble request, please provide the solution by forking the above codesandbox with working condition.

A: Step 1:
Download the AppMeasurement.js file. It is not available for guest user but should be available for logged in paid user.  from here
More on how to download the file is available here.
Step 2:
Define the configuration variables in the AppMeasurement.js file. The complete details are here but I will reproduce here for convenience.
Change the userID and trackingServer.
var s_account = "examplersid"; // Change this
var s=s_gi(s_account); // Instantiation
s.trackingServer = "example.omtrdc.net"; // Change this

// Page Level variables

s.pageName = "Example page";
s.eVar1 = "Example eVar";
s.events = "event1";

Step 3:
Then add them to your <head> of the document. You can do this by adding it to the _document.js file. Or include it per page using the Next.js next/head module. The following is the code to include it in the <Head> module of Next.js. (Ensure that the path of AppMeasurement.js is appropriate for each page.)
import Head from 'next/head';

export default () => {
....
  <Head><script src="AppMeasurement.js"></script></Head>
....

}

I have myself not used Adobe Analytics considering it to be a paid service. But have worked with several other JS based analytics platforms. I think the above procedure should work. Let me know if face any issue.
References :

*

*JS Implementation

*Inserting the code

*More about adding JSX to header

*https://docs.adobe.com/content/help/en/analytics/implementation/other/dtm/t-analytics-deploy.html

*https://docs.adobe.com/content/help/en/analytics/implementation/launch/overview.html

A: If you're server side rendering wouldn't it be possible to just drop a one liner from Adobe post render?
"Adobe Experience Platform Launch: The standardized and recommended method to implement Adobe Analytics. Place a loader tag on each page, and use Launch's interface to determine how each variable is defined" from Adobes documentation https://experienceleague.adobe.com/docs/analytics/implementation/home.html#key-analytics-implementation-articles
Ideally you don't want to spend time intertwining the nextJS code with Adobe and just use a separate tool to capture the events
How would you implement Adobe on a static page?

A: Your best resource will be the examples directory in nextjs repository.
Check the Google Analytics implementation and you can get a basic idea on how to do it.
But summarizing, you need to:
1) Add analytics script to Head component in _document.js Page
<Head>
{/* Global Site Tag (gtag.js) - Google Analytics */}
  <script
    async
    src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
  />
  <script
    dangerouslySetInnerHTML={{
      __html: `
    window.dataLayer = window.dataLayer || [];
    function gtag(){dataLayer.push(arguments);}
    gtag('js', new Date());
    gtag('config', '${GA_TRACKING_ID}', {
      page_path: window.location.pathname,
    });
  `,
    }}
  />
</Head>

2) Listen for page change event on _app.js Page, and manually trigger the action with your analytics lib api.
Router.events.on('routeChangeComplete', url => gtag.pageview(url))

p.s.: If you don't have custom _app and _document pages you may need to create them


text:
Q: Calculating a similarity score based on both nominal and scale variables I'm currently writing my master thesis on the importance of deep-level similarities between a mentor and mentee for the mentorship effectiveness.
In order to test this, I've had 5 respondents evaluate 8 mentee profiles each to indicate their expected mentorship effectiveness on a scale of 1 to 7.
My main problem lies in calculating a similarity score as the independent variable. This is because the similarity between the respondent and the mentee profile is based on 6 variables: 5 personality characterstics and one cognitive style characterstic.
The personality characterstics are measured on an interval scale for the respondents and on a nominal scale for the mentee profiles (either 'high' or 'low')
The cognitive style characteristic is measured on an nominal scale for both the respondent and the mentee profile ('thinking' or 'feeling').
Do you have advice for me on how to calculate a similarity score?


text:
Q: Set videoview position in constraint layout main_acitivity.xml
<?xml version="1.0" encoding="utf-8"?>
    <!--suppress ALL -->
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@color/black"
        android:id="@+id/main"
        tools:context=".MainActivity"
        android:layout_gravity="center"
        android:gravity="center">

    <VideoView
        android:id="@+id/videoView1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:gravity="center"
        />
</androidx.constraintlayout.widget.ConstraintLayout>

Then in java I do the next
vv = (VideoView) findViewById(R.id.videoView1);

ConstraintLayout.LayoutParams pararams = (ConstraintLayout.LayoutParams) vv.getLayoutParams();
int ch=vv.getHeight();
pararams.height = vv.getWidth();

vv.setLayoutParams(pararams);

HOW TO MAKE ELEMENT VERTICALLY CENTERED AFTER THAT? I did vv.setY, I did margins, I tried do stuff with xml - nothing work, video either in the top or stretched through all window
Currently :

I need :

A: Try to add below properties
<VideoView
    android:id="@+id/videoView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"/>

I hope this can help you!

A: Create four Guidelines using constraint layout with percentage 25% from TOP , 25% from BOTTOM , 25% from RIGHT , 25% from BOTTOM and then create your VIdeoview
You can adjust percentage as per the requirement then according to the screen size it will arrange accordingly.
<VideoView
android:id="@+id/videoView1"
android:layout_width="0dp"
android:layout_height="0dp"
app:layout_constraintTop_toBottomOf="@id/guidelinetop"
app:layout_constraintBottom_toTopOf="@id/guidelinebottom"
app:layout_constraintLeft_toRightOf="@id/guidelineleft"
app:layout_constraintRight_toLeftOf="@id/guidelineright"/>

A: Use this code
<?xml version="1.0" encoding="utf-8"?>

    <!--suppress ALL -->
    <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/black"
    android:id="@+id/main"
    tools:context=".MainActivity"
    android:layout_gravity="center"
    android:gravity="center"
   android:background="#000000">

    <VideoView
        android:id="@+id/videoView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_gravity="center"
        android:gravity="center"
        />
    </androidx.constraintlayout.widget.ConstraintLayout>


text:
Q: SSL issue with multiple virtual hosts on apache I'm trying to renew the certificate for a second web serviced identified by a virtual host, call it "mysubdomain2.mydomain2.com".
I've generated all the required files (mysubdomain2.crt  mysubdomain2.mydomain.com.key  ca.pem  sub.class1.server.ca.pem).
Note that I recently successfully renewed the certificate for mysubdomain1.crt.
Here's the virtual host entry in apache:
<VirtualHost *:443>
  ServerName mysubdomain2.mydomain.com
  ServerAdmin myname@mycomp.com

   SSLEngine on
   SSLProtocol all -SSLv2
   SSLCipherSuite ALL:!ADH:!EXPORT:!SSLv2:RC4+RSA:+HIGH:+MEDIUM

   SSLCertificateFile /disk2/certificates/ssl/mysubdomain2.crt
   SSLCertificateKeyFile /disk2/certificates/ssl/mysubdomain.mydomain.com.key
   SSLCertificateChainFile /disk2/certificates/ssl/sub.class1.server.ca.pem
   SSLCACertificateFile /disk2/certificates/startssl/ca.pem
   SSLOptions StrictRequire
   SetEnvIf User-Agent ".*MSIE.*" nokeepalive ssl-unclean-shutdown

   CustomLog /var/log/apache2/ssl_request_log "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"

#</VirtualHost>

But when I restart apache, it shuts down with this error message:
"caught SIGTERM, shutting down
[Tue Jan 13 13:59:16 2015] [warn] Init: Name-based SSL virtual hosts only work for clients with TLS server name indication support (RFC 4366)
[Tue Jan 13 13:59:17 2015] [warn] Init: Name-based SSL virtual hosts only work for clients with TLS server name indication support (RFC 4366)
[Tue Jan 13 13:59:17 2015] [notice] Apache/2.2.16 (Ubuntu) PHP/5.3.3-1ubuntu9.5 with Suhosin-Patch mod_ssl/2.2.16 OpenSSL/0.9.8o configured -- resuming normal operations

Additionally, from this link:
https://wiki.apache.org/httpd/NameBasedSSLVHostsWithSNI

it's clear that this installation of apache has SNI installed. It seems that apache should at least start, as these are supposed to be just warning messages.
The problem SNI is supposed to solve is that without it, the host name doesn't get communicated until after the SSL connection is established, meaning that apache doesn't know which certificate to use.
But, at this point, it's simply not starting at all. I'm thinking to try regenerating the certificate and key and pem files, but I was pretty careful doing that in the first place. I'd like to understand what the real problem is.

A: I must have done something wrong when decrypting the secret key. I tried it again, and everything was fine.


text:
Q: Why am I getting 404 /N2/Api/Context.ashx I'm using the NuGet N2CMS package. I've tried version 2.9.6.8 and 2.9.6.14( and .16)
This is a fresh setup/install. When finishing the setup and navigating to /N2 I'm getting a 404 Not Found from the following:
/N2/API/Context.ash?mode=full

You can see my question on their GitHub here.
Anyone experience this, or have a fix?

A: bherila from the N2CMS team, was able to help me. It turns out that some of the Nuget Packages do not work out of the box; one of which is the standalone N2CMS package.
I was able to get a new project working using the N2CMS.NoZip (management UI) and N2CMS.MVC packages.
Even with these, you will still need to create and decorate a RootPage and StartPage to get past installation. You can see how I created those in the link I posted in my question


text:
Q: Using CFSavecontent to generate an Excel table doesn't write images to the Excel file I am generating a Excel file in ColdFusion, using cfsavecontent. Now I want to add an image to the excel file. The code below doesn't work, resulting in a broken image.
<cfsavecontent variable="adc" >
   <cfoutput >

   </cfoutput>

<cfsavecontent>

A: Excel is very forgiving; writing an html table to a file, giving it an xlsx extension and telling Excel to open it will more or less work. But you can't do anything fancy, like embed an img tag and expect it work.
Coldfusion does have the capability to write proper xlsx files in the native format, and you can add an image if you do it that way. I recommend you read through https://helpx.adobe.com/coldfusion/cfml-reference/coldfusion-functions/functions-by-category/spreadsheet-functions.html for how to do that.


text:
Q: Table in header sheet I am creating an engineering analysis report format and I want to include a table of information about details of the project in the header.
I understand that I have to edit the format in Format -> Edit Stylesheet. But, what code I have to write to get a table like this:

I am a new in Mathematica.
Thanks in advance.

A: This is just a partial, exploratory answer to get feedback. This is the start of an approach that just generates the header, which could then be copy-pasted to some other context where the report lives.
FieldLabel[label_] := Style[label, Bold, 12];
FieldValue[value_] := Style[value, 14, FontFamily -> "Arial"];
Field[label_, value_, width_] :=
  Grid[
    {{FieldLabel[label]}, {FieldValue[value]}},
    Alignment -> {Left, Center, {2, 1} -> Center}, ItemSize -> width];
Grid[
  {{TBD, Field["Job", "1529085", 20], TBD},
   {SpanFromAbove, Field["Project", "West Bridgeport", 20], TBD},
   {SpanFromAbove, Field["Client", "Com-Ex Consultants, LLC", 20], TBD}},
  Dividers -> All]

Considerations:

*

*This demonstrates a way to generate the output programmatically with consistent/pre-defined styling. You can tweak the styling however you like. This let's you reuse this header "template".

*If your report is actually in Mathematica, then consider just creating the header as a cell.

*Otherwise, what is the context for your report?

*Or, asking another way, what format will this eventually need to be in?

*If this is heading in the right direction, I'll update to flesh out more of the content.

Update
I'm inferring from the comment from OP that there is a Mathematica notebook that constitutes the report and that what is wanted is for a customer header to be shown when the notebook is printed.
Here is one way you can do that (there will probably be some nitpicky issues to figure out as you go along):

*

*Execute the code I posted above

*Click on the output cell (just so that's where focus is)

*Do Shift-Command-E (I'm on a Mac, I'm not sure if the command is the same on other platforms, but it's the "Show Expression" command in the Cell menu). This will show you the raw cell expression.

*Select the entire cell expression and copy it to the clipboard

*Open the option inspector (Shift-Command-O on mac)

*Set the scope to be your notebook that needs the header

*Find the PageHeaders option (you can search for it)

*Click on the value, select everything that's there, and delete it.

*Type this literally (this is just for convenience to make things easier to see): {{None,None,None},{None,None,None}}

*Now, replace the second "None" in each sublist and copy-replace it with the cell expression you have on the clipboard.

Now you can test by doing a print preview. I've never done a header this complicated, so there will probably be a lot of tweaking necessary. You'll also have to work in a CounterBox for the page number.


text:
Q: Specified cast is not valid? I have a table created in ASP.net and I want to populate the table with information from the database once the page has been loaded. I'm getting an error that the specified cast is not valid. What am I doing wrong?  Heres my code
public string getData()
{
        string htmlStr = "";

        SqlConnection conn = new SqlConnection(connString);
        SqlCommand command = conn.CreateCommand();
        command.CommandText = "SELECT * from INFO";
        conn.Open();
        SqlDataReader reader = command.ExecuteReader();

        while (reader.Read())
        {
            DateTime Date = reader.GetDateTime(0);
            DateTime Time = reader.GetDateTime(1);
            htmlStr += "
" + Date + "	"  + Time + "
";
        }

        conn.Close();

        return htmlStr;
}

INFO

                     Date
                     Time

                    <%=getData()%>

This is my error:

It is throwing the exception on this line from the above code:
DateTime Date = reader.GetDateTime(0);

A: From your comment:

this line DateTime Date = reader.GetDateTime(0); was throwing the exception

The first column is not a valid DateTime. Most likely, you have multiple columns in your table, and you're retrieving them all by running this query:
SELECT * from INFO

Replace it with a query that retrieves only the two columns you're interested in:
SELECT YOUR_DATE_COLUMN, YOUR_TIME_COLUMN from INFO

Then try reading the values again:
var Date = reader.GetDateTime(0);
var Time = reader.GetTimeSpan(1);  // equivalent to time(7) from your database

Or:
var Date = Convert.ToDateTime(reader["YOUR_DATE_COLUMN"]);
var Time = (TimeSpan)reader["YOUR_TIME_COLUMN"];

A: htmlStr is string then You need to Date and Time variables to string
while (reader.Read())
                {
                    DateTime Date = reader.GetDateTime(0);
                    DateTime Time = reader.GetDateTime(1);
                    htmlStr += "
" + Date.ToString() + "	"  +
                    Time.ToString() + "
";
                }

A: Try this:
public void LoadData()
        {
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Stocks;Integrated Security=True;Pooling=False");
            SqlDataAdapter sda = new SqlDataAdapter("Select * From [Stocks].[dbo].[product]", con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            DataGridView1.Rows.Clear();

        foreach (DataRow item in dt.Rows)
        {
            int n = DataGridView1.Rows.Add();
            DataGridView1.Rows[n].Cells[0].Value = item["ProductCode"].ToString();
            DataGridView1.Rows[n].Cells[1].Value = item["Productname"].ToString();
            DataGridView1.Rows[n].Cells[2].Value = item["qty"].ToString();
            if ((bool)item["productstatus"])
            {
                DataGridView1.Rows[n].Cells[3].Value = "Active";
            }
            else
            {
                DataGridView1.Rows[n].Cells[3].Value = "Deactive";
            }


text:
Q: "Invalid CFML construct found" in Framework/1 core file I downloaded Framework/1 from RIAforge and browsed to it.
I'm getting the following error:

Invalid CFML construct found on line 46 at column 81.
ColdFusion was looking at the following text:
[
The CFML compiler was processing:
   A script statement beginning with public on line 46, column 9.

The error occurred in C:\inetpub\wwwroot\FW1\org\corfield\framework.cfc: line 46
44 :   }
45 :
46 :   public void function addRoute(

I'm using cf9.0.0.25.1028

A: Framework/1's newest version, 2.x requires ColdFusion 9.0.1 at a minimum, which you don't have (thanks for posting your exact version - great question asking skills!). Just update your server and you will be set.
If you need ColdFusion 8 and 9.0.0 suppport, FW/1 version 1.2 is still a great piece of software and will work on your existing server.


text:
Q: Staging function and printing results to cells VBA Essentially I have an array A = Array(1, 2, 3, 4, 5) what I want to do is, with the use of Rnd(), circle around this loop depending on the value of the random numbers.
Basically start at 0 Mod 5 get a random number. If the random number is less than 0.5 then I stay at 0 Mod 5, however if the random number is greater than or eual to 0.5 then I move to 1 Mod 5, then because it's passed to the next stage 'it gets to roll again', so I pass a new random number to it, to see if it can get to 2 Mod 5.
My aim is to run this 10,000 times and collect the results in the A column in a spreadsheet and then plot a scattergraph to see how it works.
Now I created a function
Function looper(R, i)
If R < 0.5 Then
    j = i
Else
    j = i + 1
End If
If j = i Then
    Exit Function
Else
    newR = Rnd()
    j = looper(newR, j)
End If
End Function

Coupled with the sub
Sub loopy()
A = Array(1, 2, 3, 4, 5)
Randomize
R = Rnd()
k = looper(R, 1)
Cells(1, 1).Value = A(k Mod 5)

However it only ever returns the value 1.
I'm pretty sure I'm doing something fundamentally wrong, either with my logic, or how I'm attempting to put my logic into VBA code.

A: Are you trying to analyse and/or crack an online roulette logic? ;)
Your looper function is designed to always return 1.
Even if the random number is greater than 0.5 you are calling the function recursively - so, in easy words, it repeats until the new random number is smaller than 0.5 and if it is then it returns 1.

So I rewrote this for you and this code will print out the results of how many random numbers greater than 0.5 can I get in a row - in column A.
It prints the number of stages it passes
Option Explicit

Sub roulette()
    Dim ws As Worksheet, nextRow&, i&, max&
    Set ws = Sheets(1): ws.Cells.ClearContents
    For max = 1 To 10001
        nextRow = ws.Range("A" & Rows.Count).End(xlUp).Row + 1
        ws.Range("A" & max).Value = getStage
    Next max
End Sub

Function crack() As Boolean
    Dim x#: Randomize: x = Rnd()
    If x >= 0.5 Then crack = True
End Function

Function getStage() As Long
    Dim cnt&
    While crack: cnt = cnt + 1: Wend: getStage = cnt
End Function

A: Okay, so I changed my function
Function looper(i)
R = Rnd()
If R < 0.5 Then
    looper = i
Else
    looper = i + 1
End If
End Function

and altered my sub
Sub loopy()
A = Array(1, 2, 3, 4, 5)
Cells(1, 1).Value = "Number"
For i = 2 To 10001
    k = 1
    j = 1
    While k = j
        j = looper(k)
        k = k + 1
    Wend
    Cells(i, 1).Value = A(j Mod 5)
Next i
End Sub

This gives me what I want. I'm now hoping however, that some bright spark can conceieve of a better method that doesn't involve a While loop that I've always been taught should be avoided wherever possible.


text:
Q: Replace only specified occurrences of string - Python Regex I am playing around with re module in python, what i am stuck at is I want to replace only specified occurrences of the string.
for example
import re
string = "aabbaabbaabbabbaabbaa"
#I want to replace only 3rd time 'bb' appeared in the string with white space
string = re.sub("bb"," ",string,3)   #if iI do this all first 3 occurrences got replaced
print(string)

output
aa aa aa aabbaabbaa

any idea how to to replace only 3rd occurrence
so the output would look like This
aabbaabbaa aabbaabbaa

A: This may not be the perfect way but it is a solution:
string = re.sub('bb',' ',string, 3)
string = re.sub(' ','bb',string,2)

This is just an alternative solution I can think of.

A: Modify the regex so it only matches the third occurrence?
re.sub(r'(.*?bb.*?bb.*?)bb', r'\1 ', string, 1)

This could be extended to a large number of repetitions like r'(.*?(bb.*?){9999})bb'


text:
Q: Ubuntu 18.04: No wifi adapter found I bought a new laptop Lenovo S540 and tried dual booting it with windows 10 and Ubuntu 18.04. The dual boot went fine and after I updated the Ubuntu system my wifi icon got disappeared from top-right menu and in settings, it shows "No wifi adapter found"

I already tried some of the methods posted online but none of them worked till now.

lspci -knn | grep Net -A3; rfkill list

    00:14.3 Network controller [0280]: Intel Corporation Device [8086:02f0]
    Subsystem: Intel Corporation Device [8086:0034]
    Kernel driver in use: iwlwifi
    Kernel modules: iwlwifi, wl
0: ideapad_wlan: Wireless LAN
    Soft blocked: no
    Hard blocked: no
1: ideapad_bluetooth: Bluetooth
    Soft blocked: yes
    Hard blocked: no
2: hci0: Bluetooth
    Soft blocked: yes
    Hard blocked: no

dmesg | grep iwl

[   13.689174] iwlwifi 0000:00:14.3: TLV_FW_FSEQ_VERSION: FSEQ Version: 43.2.23.17
[   13.689176] iwlwifi 0000:00:14.3: Found debug destination: EXTERNAL_DRAM
[   13.689176] iwlwifi 0000:00:14.3: Found debug configuration: 0
[   13.689312] iwlwifi 0000:00:14.3: loaded firmware version 48.13675109.0 op_mode iwlmvm
[   14.968566] iwlwifi 0000:00:14.3: Detected Intel(R) Wireless-AC 9560, REV=0x354
[   14.975120] iwlwifi 0000:00:14.3: Applying debug destination EXTERNAL_DRAM
[   14.975404] iwlwifi 0000:00:14.3: Allocated 0x00400000 bytes for firmware monitor.
[   15.997193] iwlwifi 0000:00:14.3: Collecting data: trigger 15 fired.
[   15.997299] iwlwifi 0000:00:14.3: Start IWL Error Log Dump:
[   15.997334] iwlwifi 0000:00:14.3: Status: 0x00000000, count: -288669377
[   15.997335] iwlwifi 0000:00:14.3: Loaded firmware version: 48.13675109.0
[   15.997337] iwlwifi 0000:00:14.3: 0xB71F968D | ADVANCED_SYSASSERT
[   15.997337] iwlwifi 0000:00:14.3: 0x3381040B | trm_hw_status0
[   15.997338] iwlwifi 0000:00:14.3: 0x96318858 | trm_hw_status1
[   15.997339] iwlwifi 0000:00:14.3: 0x4B7695B8 | branchlink2
[   15.997340] iwlwifi 0000:00:14.3: 0x0EC5D74B | interruptlink1
[   15.997340] iwlwifi 0000:00:14.3: 0x24F3781B | interruptlink2
[   15.997341] iwlwifi 0000:00:14.3: 0x45C27942 | data1
[   15.997342] iwlwifi 0000:00:14.3: 0xBED7FD4A | data2
[   15.997342] iwlwifi 0000:00:14.3: 0xACB7D7AE | data3
[   15.997343] iwlwifi 0000:00:14.3: 0xBBD9DEF8 | beacon time
[   15.997344] iwlwifi 0000:00:14.3: 0x10005892 | tsf low
[   15.997345] iwlwifi 0000:00:14.3: 0xEBFDFD6E | tsf hi
[   15.997345] iwlwifi 0000:00:14.3: 0x4427F2FF | time gp1
[   15.997346] iwlwifi 0000:00:14.3: 0xBF08186D | time gp2
[   15.997347] iwlwifi 0000:00:14.3: 0xE083784A | uCode revision type
[   15.997348] iwlwifi 0000:00:14.3: 0x7FCEEDBF | uCode version major
[   15.997348] iwlwifi 0000:00:14.3: 0x194E69AB | uCode version minor
[   15.997349] iwlwifi 0000:00:14.3: 0xEBE01001 | hw version
[   15.997350] iwlwifi 0000:00:14.3: 0x82AA091E | board version
[   15.997350] iwlwifi 0000:00:14.3: 0xAC414028 | hcmd
[   15.997351] iwlwifi 0000:00:14.3: 0xF9477BC5 | isr0
[   15.997352] iwlwifi 0000:00:14.3: 0x56D95F01 | isr1
[   15.997353] iwlwifi 0000:00:14.3: 0xA440F2D5 | isr2
[   15.997353] iwlwifi 0000:00:14.3: 0x1676709A | isr3
[   15.997354] iwlwifi 0000:00:14.3: 0xEEE47AF2 | isr4
[   15.997355] iwlwifi 0000:00:14.3: 0x6C57755C | last cmd Id
[   15.997355] iwlwifi 0000:00:14.3: 0x3197F314 | wait_event
[   15.997356] iwlwifi 0000:00:14.3: 0x9898FBC2 | l2p_control
[   15.997357] iwlwifi 0000:00:14.3: 0x5FB6BBA3 | l2p_duration
[   15.997357] iwlwifi 0000:00:14.3: 0x72BA6AAF | l2p_mhvalid
[   15.997358] iwlwifi 0000:00:14.3: 0x1925B308 | l2p_addr_match
[   15.997359] iwlwifi 0000:00:14.3: 0xF6C84A9D | lmpm_pmg_sel
[   15.997359] iwlwifi 0000:00:14.3: 0xFB58FAE6 | timestamp
[   15.997360] iwlwifi 0000:00:14.3: 0x3D7AF30E | flow_handler
[   15.997392] iwlwifi 0000:00:14.3: Start IWL Error Log Dump:
[   15.997393] iwlwifi 0000:00:14.3: Status: 0x00000000, count: 7
[   15.997393] iwlwifi 0000:00:14.3: 0x201013F1 | ADVANCED_SYSASSERT
[   15.997394] iwlwifi 0000:00:14.3: 0x00000000 | umac branchlink1
[   15.997395] iwlwifi 0000:00:14.3: 0xC008CF5C | umac branchlink2
[   15.997396] iwlwifi 0000:00:14.3: 0x00000000 | umac interruptlink1
[   15.997396] iwlwifi 0000:00:14.3: 0x00000000 | umac interruptlink2
[   15.997397] iwlwifi 0000:00:14.3: 0x00000003 | umac data1
[   15.997398] iwlwifi 0000:00:14.3: 0x20000302 | umac data2
[   15.997398] iwlwifi 0000:00:14.3: 0x01300202 | umac data3
[   15.997399] iwlwifi 0000:00:14.3: 0x00000030 | umac major
[   15.997400] iwlwifi 0000:00:14.3: 0x13675109 | umac minor
[   15.997401] iwlwifi 0000:00:14.3: 0x00005C9C | frame pointer
[   15.997401] iwlwifi 0000:00:14.3: 0xC0887F58 | stack pointer
[   15.997402] iwlwifi 0000:00:14.3: 0x00000000 | last host cmd
[   15.997403] iwlwifi 0000:00:14.3: 0x00000000 | isr status reg
[   15.997419] iwlwifi 0000:00:14.3: Fseq Registers:
[   15.997421] iwlwifi 0000:00:14.3: 0x00000003 | FSEQ_ERROR_CODE
[   15.997423] iwlwifi 0000:00:14.3: 0x00260000 | FSEQ_TOP_INIT_VERSION
[   15.997426] iwlwifi 0000:00:14.3: 0x00000000 | FSEQ_CNVIO_INIT_VERSION
[   15.997428] iwlwifi 0000:00:14.3: 0x0000A384 | FSEQ_OTP_VERSION
[   15.997430] iwlwifi 0000:00:14.3: 0x71047F37 | FSEQ_TOP_CONTENT_VERSION
[   15.997432] iwlwifi 0000:00:14.3: 0x4552414E | FSEQ_ALIVE_TOKEN
[   15.997435] iwlwifi 0000:00:14.3: 0x20000302 | FSEQ_CNVI_ID
[   15.997437] iwlwifi 0000:00:14.3: 0x01300202 | FSEQ_CNVR_ID
[   15.997439] iwlwifi 0000:00:14.3: 0x20000302 | CNVI_AUX_MISC_CHIP
[   15.997443] iwlwifi 0000:00:14.3: 0x01300202 | CNVR_AUX_MISC_CHIP
[   15.997448] iwlwifi 0000:00:14.3: 0x0000485B | CNVR_SCU_SD_REGS_SD_REG_DIG_DCDC_VTRIM
[   15.997482] iwlwifi 0000:00:14.3: 0xA5A5A5A2 | CNVR_SCU_SD_REGS_SD_REG_ACTIVE_VDIG_MIRROR
[   15.997510] iwlwifi 0000:00:14.3: SecBoot CPU1 Status: 0x5c0f, CPU2 Status: 0x3
[   15.997511] iwlwifi 0000:00:14.3: Failed to start RT ucode: -110
[   15.997513] iwlwifi 0000:00:14.3: Firmware not running - cannot dump error
[   16.009256] iwlwifi 0000:00:14.3: Failed to run INIT ucode: -110

uname -a

Linux sandy 5.3.0-62-generic #56~18.04.1-Ubuntu SMP Wed Jun 24 16:17:03 UTC 2020 x86_64 x86_64 x86_64 GNU/Linux

dkms status

bcmwl, 6.30.223.271+bdcom, 5.3.0-62-generic, x86_64: installed
nvidia, 440.100, 5.3.0-62-generic, x86_64: installed


text:
Q: Using weather api nextjs I want to create a small weather api, for that I am using the page weatherapi.com, I can get the name of the city and the temperature but the url of the image I cannot add it to the src of the  element of Next.js.
This is the component i am creating:
import React from 'react'
import Image from 'next/image'
import styles from '../../../styles/Home.module.css'
import tpo from '../../../public/weather/64x64/day/113.png'

class Meteorologia extends React.Component{
   constructor(props){
     super(props);
     this.state = {ciudad: "",icon: "",grdos: ""};
   }

   cargarDatos = ()=>{
     const apikey = "codigo de la api de weatherapi.com";
     let ciudad = "Santiago";
     let ruta = `https://api.weatherapi.com/v1/current.json?key=${apikey}&q=${ciudad}&aqi=no`;

     fetch(ruta).then(response => response.json()).then(datos =>{
       const {location,current} = datos;
       const icono = "https:"+current.condition.icon;
       this.setState({ciudad: location.name,icon: icono,grdos: current.temp_c+"°"});
     });
   }

   render(){
     return(

{this.state.ciudad}

{this.state.grdos}

            <Image className={styles.imag} id="imaT" src={this.state.icon} alt="image temp"/>

     );
   }
}
export default Meteorologia;

I can use the name of the city and the temperature but not the url of the image.
This is the error that is generated:
Error: Image is missing required "src" property. Make sure you pass "src" in props to the next/image component. Received: {}


text:
Q: Extract max distance for IDs that visited multiple (lat,lon) I have a table with this format :

User
lat
lon

u1
x1
y1

u1
x2
y2

u1
x3
y3

u2
x4
y4

u2
x5
y5

u2
x6
y6

u3
x7
y7

u3
x8
y8

What I'd like to do is have a table where for each user I have the distance between the farthest 2 points they've been to.

User
max_dist_km

u1
15.2

u2
23.7

u3
8.3

The naive way is to loop over users, create the distance matrix for each user and extract the max distance. This wouldn't be scalable with a huge set of users.
Is there a more efficient and elegant way to proceed ?

A: Summary
Implemented a fast algorithm which works in linear time

*

*US Cities Dataset (30, 409 records): 0.103 seconds

*Animal tracking dataset (89,867 records): 0.325 seconds

*Timings on 10+ year old windows desktop (i7 920 CPU @ 2.67GHz)

Approach
Has linear complexity i.e. O(N)

*

*N is the total number of lats/lons (i.e. counting across all user)

Perform the following steps:

*

*Group latitude/longitude data by user

*Repeat steps 3-7 for each user

*Map latitudes/longitudes points to x, y, z coordinates using spherical earth approximation

*Find the two furthest points as follows:

*

*Initialize P1 to the center of mass of the points

*Repeat the following 3 times (once is normally enough but multiple times handles corner cases):

*

*Set P0 = P1

*Set P1 = the point in points at maximum distance from P0

*P0 and P1 are the furthest two points in x, y, z

*Use indexes of P0 & P1 to lookup latitude/longitude from original lat/log data

*Calculate the distance between P0 & P1 using Haversine

*Update results with the current user's distance

*Return results for all users as a data frame

Code
import numpy as np

def lat_lon_to_xyz(lat, lon):
    '''
        Convert latitude/longitude to x, y, z in Earth centered coordinates (assuming spherical earth)

        lat, lon are in degrees radian

        Source: https://stackoverflow.com/questions/1185408/converting-from-longitude-latitude-to-cartesian-coordinates
    '''
    lat_radians = np.deg2rad(lat)
    lon_radians = np.deg2rad(lon)

    R = 1  # use unit sphere rather than 6371 radius of earth in km
    x = R * np.cos(lat_radians) * np.cos(lon_radians)
    y = R * np.cos(lat_radians) * np.sin(lon_radians)
    z = R *np.sin(lat_radians)

    return np.array([x, y, z])

def furthest_points_spadsman(points):
    '''
        Based upon the following technique which scales linearly with the number of points

        - Initialize P1 to the center of mass of the points
        - Repeat the following 3 times (once is normally enough but multiple times handles corner cases):
          - Set P0 = P1
          - Set P1 = the point in points with maximum distance from P0
          - P0 and P1 are the furthest two points in x, y, z

        Technique from following reference.
        Reference: https://stackoverflow.com/q/16865291/
    '''
    # Initialize to mean
    p_1 = np.mean(points, axis = 0)

    for _ in range(3): # Iterating mitigates corner cases
        p_0 = p_1
        # Point in points furthest distance from p_0
        # note: can use squared distance since monotonical
        p_1 = points[np.argmax(np.sum(np.square(points - p_0), axis = -1))]

    return p_0, p_1

def haversine(point1, point2):
    '''
        Data in point1 and point2 are latitude/longitude pairs,
        with first number is the latitude (north-south),
        and the second number is the longitude (east-west)

        Source: https://medium.com/@petehouston/calculate-distance-of-two-locations-on-earth-using-python-1501b1944d97
    '''
    R = 6371  # Earth radius in km

    point1 = np.deg2rad(point1)
    point2 = np.deg2rad(point2)

    delta = point2 - point1

    a = (np.sin(delta[0] / 2) ** 2 +
         np.cos(point1[0]) * np.cos(point2[0]) * np.sin(delta[1] / 2) ** 2)

    return 2 * R * np.arcsin(np.sqrt(a))

def process(df, user = 'user', lat_field ='lat', lon_field = 'lon'):
    '''
        Generates the Dataframe containing the maximum distance by user of a set of points

        The process works as following steps.
        1.  Group latitude/longitude data by user
        2.  Repeat steps 3-7 for each user
        3.  Map latitudes/longitudes points to x, y, z coordinates using spherical earth approximation)
        4.  Find two furthest points as follows:
            i. calculate the center of mass M of the points
            ii. find the point P0 that has the maximum distance to M
            iii. find the point P1 that has the maximum distance to P0
            iv. P0 and P1 are the furthest two points in x, y, z
        5. Use indexes of P0 & P1 to lookup latitude/longitude from original lat/log data
        6. Calcualte distance between P0 & P1 using Haversine
        7. Update results
        8. Return results as a dataframe

         Process based upon following references:
         a. https://stackoverflow.com/questions/16865291/greatest-distance-between-set-of-longitude-latitude-points/16870359#16870359
         b. https://medium.com/@petehouston/calculate-distance-of-two-locations-on-earth-using-python-1501b1944d97

    '''
    results = []                              # holds list of tuples of (user, distance)
    for user_, g in df.groupby(user):            # Step 1--Group latitude/longitude data by user
        # Step 2--Repeat steps 2-4 for each user
        points_lat_lon = g[[lat_field, lon_field]].to_numpy()

        # Step 3--map latitudes/longitudes points to x, y, z coordinates
        points_xyz = lat_lon_to_xyz(points_lat_lon[:, 0], points_lat_lon[:, 1]).transpose()

        # Step 4--Find two furthest points
        # Find two furthest points in xyz (using spherical earth aproximation)
        p_0, p_1 = furthest_points_spadsman(points_xyz)

        # Step 5--Use indexes of P0 & P1 to lookup latitude/longitude from original lat/log data
        # Index of p_0 and p_1 in points_xyz (so we also corresponds to the index in points_lat_lon)
        index_0 = np.where(np.prod(points_xyz == p_0, axis = -1))[0][0]
        index_1 = np.where(np.prod(points_xyz == p_1, axis = -1))[0][0]

        lat_lon_0 = points_lat_lon[index_0, :]
        lat_lon_1 = points_lat_lon[index_1, :]

        # Step 6--Calcualte distance between P0 & P1 using Haversine
        distance = haversine(lat_lon_0, lat_lon_1)

        # Step 7--update results
        results.append((user_, distance))

    # Step 8--Return results as a dataframe
    return pd.DataFrame(results, columns = [user, 'Max_Distance_km'])

Tests
Test 1
Description
Computed maximum distance between cities in the United States

*

*Used state id as user

*Total 30, 409 records (multiple records per city and state)

*Each record included state id, lat, long

*Processing time for 30, 409 records: 0.104 seconds on 10+ year old windows desktop (i7 920 CPU @ 2.67GHz)

Dataset

*

*Downloaded from this site: simplemaps

*Contains many cities per state

*Used state id as user (i.e. found max distances between cities by state)

Test Code
from time import time
import pandas as pd

# CSV file downloadable from https://simplemaps.com/data/us-cities
# Datafile with 30, 409 records
cities = pd.read_csv('simplemaps_uscities_basicv1.75/uscities.csv')

t0 = time()
result = process(cities, user = 'state_id', lat_field = 'lat', lon_field = 'lng')
print(f'Processing time: {time()-t0:.3f} seconds')
print(f'Results:\n{result}')

Output
Processing time: 0.104 seconds
Results:
   state_id  Max_Distance_km
0        AK      3586.855864
1        AL       569.292071
2        AR       492.544129
3        AZ       712.434590
4        CA      1321.284443
5        CO       697.572158
6        CT       182.286421
7        DC         0.000000
8        DE       156.778146
9        FL       936.595405
10       GA       589.700716
11       HI       574.129490
12       IA       538.297210
13       ID       825.044994
14       IL       622.014829
15       IN       496.787181
16       KS       682.563079
17       KY       633.576282
18       LA       601.891459
19       MA       301.815349
20       MD       397.753918
21       ME       509.556000
22       MI       743.578849
23       MN       751.324104
24       MO       707.260076
25       MS       534.872877
26       MT       961.640222
27       NC       778.308918
28       ND       582.080515
29       NE       763.370612
30       NH       249.275265
31       NJ       259.273945
32       NM       747.581138
33       NV       807.834661
34       NY       641.785757
35       OH       471.708115
36       OK       826.431505
37       OR       649.340103
38       PA       508.693319
39       PR       205.710138
40       RI        81.539958
41       SC       435.894534
42       SD       688.135798
43       TN       751.286457
44       TX      1240.972424
45       UT       611.262766
46       VA       729.361836
47       VT       285.877877
48       WA       616.073484
49       WI       570.813035
50       WV       441.834382
51       WY       682.873519

Test 2
Description
Find furthest distances traveled by animals in animal tracking data.

*

*126 different animal tags (e.g. users)

*89, 867  data records

*Processed in 0.325 seconds

Dataset

*

*Movebank is an online database of animal tracking data hosted by the Max Planck Institute of Animal Behavior.

*Used Movebank dataset from Kaggle.

*Data Source
Test Code
from time import time
import pandas as pd

# Data downloaded from above kaggle link
df = pd.read_csv('migration_original.csv/migration_original.csv')

t0 = time()
result = process(df, user = 'individual-local-identifier', lat_field = 'location-lat', lon_field = 'location-long')
print(f'Processing time: {time()-t0:.3f} seconds')
print(f'Results:\n{result}')

Output
Processing time: 0.325 seconds
Results:
    individual-local-identifier  Max_Distance_km
0                        91732A      7073.629785
1                        91733A        65.788571
2                        91734A      3446.277830
3                        91735A       231.789762
4                        91737A      5484.820693
..                          ...              ...
121                      91920A      2535.920902
122                      91921A        26.698255
123                      91924A        14.518173
124                      91929A         0.806871
125                      91930A        10.427890

[126 rows x 2 columns]

References

*

*Greatest distance between set of longitude/latitude points

*Calculate distance of two locations on Earth using Python
Acknowledgements

*

*Thanks to @MangoNrFiv whose comments helped improve the implementation and testing.

A: Are you OK with cartesian distance instead of great-circle distance? They should be very similar for nearby points on the scale you're describing.
If so, convert lat/lon to ECEF (earth centered earth fixed) cartesian coordinates as described on page 4 of this paper. Then, for each user's set of ECEF position vectors, the distance between the two furthest points is given in O(n) time by Megiddo's 1983 smallest enclosing sphere algorithm.
Also, Welzl's algorithm could probably be applied in spheroidal coordinates if great-circle distance is necessary, but that seems a rather large undertaking.
Edit: More strictly speaking, the diameter of the enclosing sphere provides an upper bound on the distance between the two furthest points, and the distance between the two furthest of the set of points on the sphere provides a lower bound.
If only two points lie on the sphere, these must be antipodal and are necessarily the furthest apart. Otherwise, the search space of possible pairs can then be narrowed by removing any points which are not far enough from the sphere's center to be part of the maximally separated pair (based on the lower bound previously determined), but the reduced space must then be evaluated by another method.

A: On this answer one will find two potential options:

*

*Option 1, using a function that I created on my answer here. On that answer one will find additional methods that one could use.

*Option 2, using a different function.
For testing purposes, even though I recommend testing with data as close to what one will be using as possible, I will take the example proposed by @Qdr
import pandas as pd
import numpy as np
import random as rn

data = [[rn.randint(1, 10), rn.randint(1, 10)] for x in range(9)]
users = ['user1', 'user2', 'user3'] * 3
rn.shuffle(users)

df1 = pd.DataFrame(data, columns=['x', 'y'], index=users)

Option 1
In order to measure the distance between two points (represented by geographic coordinates), as I referred above, one can use one of the function I shared here, where we will find a better explanation.
The function is called haversine, and is inspired by the haversine formula.
def haversine(lon1, lat1, lon2, lat2):
    """
    Calculate the great-circle distance (in km) between two points
    using their longitude and latitude (in degrees).
    """
    # Radius of the Earth
    r = 6371.0

    # Convert degrees to radians
    # First point
    lat1 = radians(lat1)
    lon1 = radians(lon1)

    # Second Point
    lat2 = radians(lat2)
    lon2 = radians(lon2)

    # Haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = sin(dlat / 2)**2 + cos(lat1) * cos(lat2) * sin(dlon / 2)**2
    c = 2 * atan2(sqrt(a), sqrt(1 - a))
    return r * c

As one wants the max distance, let's create a function that uses the previous one
def max_distance(lat1, lon1, lat2, lon2):
    # Calculate distance between two points
    distance = haversine(lon1, lat1, lon2, lat2)
    # Return max distance
    return np.max(distance)

Finally, one can create a new dataframe, df2.
[In]: df2 = df1.groupby(df1.index).apply(lambda x: pd.Series({'max_distance': max_distance(x['x'].iloc[0], x['y'].iloc[0], x['x'].iloc[1], x['y'].iloc[1])}))

[Out]:       max_distance
user1    866.714728
user2    867.428750
user3    247.358878

Option 2
Depending on one's requirements, the following function can also be used to , assuming one wants to calculate the max distance between two points, the following function does the work
def max_distance(lat1, lon1, lat2, lon2):
    # Calculate distance between two points
    distance = np.sqrt((lat1 - lat2)**2 + (lon1 - lon2)**2)
    # Return max distance
    return np.max(distance)

In order to create the new dataframe, grouped by users (in this example it is the index of the dataframe df1), with a column named max_dist_km that will have the max distance between two points for a given user (using the previous function), the following should do the work
df2 = df1.groupby(df1.index).apply(lambda x: pd.Series({'max_distance': max_distance(x['x'].iloc[0], x['y'].iloc[0], x['x'].iloc[1], x['y'].iloc[1])}))

A: you could use distance_matrix in scipy
first create dataframe with random values and 3 users
import pandas as pd
from scipy.spatial import distance_matrix
import random as rn

data = [[rn.randint(1, 10), rn.randint(1, 10)] for x in range(9)]
users = ['user1', 'user2', 'user3'] * 3
rn.shuffle(users)

df = pd.DataFrame(data, columns=['x', 'y'], index=users)
df

x
y

user2
9
7

user2
5
4

user3
3
10

user1
8
3

user1
5
7

user1
8
5

user2
10
2

user3
3
9

user3
2
2

then groupby and apply distance_matrix
df.groupby(df.index).apply(lambda x: distance_matrix(x, x).max())

output:
user1    5.000000
user2    5.385165
user3    8.062258
dtype: float64

A: This approach is using pandas groupby, in combination with sklearn spatial function. It is fairly fast (about same as @DarrylG).
We define a custom groupby function, using Convex Hull to extract edge points within a group, and calculate the max distance, using Distance Metric Haversine.
The idea is that the maximum distance can sharply be approximated by only consider the edges of the Convex Hull. There are edge-cases where this falls short due to abusing it for lat/long pairs.

import pandas as pd
import numpy as np

from sklearn.metrics import DistanceMetric
from scipy.spatial import ConvexHull

from math import radians

dist = DistanceMetric.get_metric('haversine')

def max_distance_within_group(df):

    EARTH_RADIUS = 6371.009

    group_gps = df[['location-lat','location-long']].values

    if len(group_gps) > 10:
        """
            If more than 10 point, lets create a convex-hull,
            and only use the edge points.
        """
        convex_hull_idx = ConvexHull(group_gps)
        group_gps = group_gps[convex_hull_idx.vertices]

    haversine_distances = dist.pairwise(np.radians(group_gps))
    haversine_distances *= EARTH_RADIUS

    return np.max(haversine_distances)

I use the same 2nd test case of @DarrylG so you can compare speed if you like. Our speeds are so similar than I can't tell which is faster.
migration = pd.read_csv('work/migration_original.csv')

And apply
migration.groupby('individual-local-identifier').apply( max_distance_within_group )

which returns
individual-local-identifier
91732A    7073.639777
91733A      65.788664
91734A    3446.282699
91735A     231.790090
91737A    5484.828441
             ...
91920A    2535.924485
91921A      26.698292
91924A      14.518194
91929A       0.806872
91930A      10.427905
Length: 126, dtype: float64


text:
Q: How to create shadow password from a C program Function crypt() returns a string like TyVkFBglLfEGw, when on my Ubuntu machine all passwords are in form like
$6$Ty8Ew9/O$V/ck4Apc7VOOqobhenO5.f6ccsVdCpQy5H6fyuNzCaDG.LxFnUWKHOobkpRQQtl.1cFG8BLAdfWjNbLiSxKXF/
I think my machine uses SHA512 algorithm. How can I create hashed strings like in /etc/shadow file from a C program?

A: If you read the man page for crypt; specifically the piece about Glibc notes, it mentions the following:
The glibc2 version of this function supports additional encryption
algorithms.

If salt is a character string starting with the characters "$id$"
followed by a string terminated by "$":

      $id$salt$encrypted

then instead of using the DES machine, id identifies the encryption
   method used and this then determines how the rest of the password
   string is interpreted.  The following values of id are supported:
      ID  | Method
      ─────────────────────────────────────────────────────────
      1   | MD5
      2a  | Blowfish (not in mainline glibc; added in some
          | Linux distributions)
      5   | SHA-256 (since glibc 2.7)
      6   | SHA-512 (since glibc 2.7)

So $5$salt$encrypted is an SHA-256 encoded password and
   $6$salt$encrypted is an SHA-512 encoded one.
this means that you should pass in a string as salt that contains the string $6$salt to get it to generate a sha-512 crypt e.g.
char *salt = "$6$pt4wu5ns";
char *password = "muppet show";

printf("%s\n", crypt(password, salt));

A: Here's a website on how to implement the sha1 algorithm.
http://bradconte.com/sha1_c
Normally I would describe the algorithm, but really there;s nothing to it, just mix up the bits with a complex series of adds and shifts. The tricky bit is getting it to exactly conform to everyone else;s sha1 code.


text:
Q: How do I get it to be redirected to login when http response has status 401 due to an expired signature of the token? The following code listens for http responses to an api that includes the 401 status because a token has expired. In the case that status 401 is given, it should redirect to login
import { Injectable } from "@angular/core";
import {
    HttpInterceptor,
    HttpRequest,
    HttpHandler,
    HttpEvent,
    HttpErrorResponse,
} from "@angular/common/http";
import { Observable } from "rxjs";
import { tap } from "rxjs/operators";
import { Router } from "@angular/router";
import { Store } from "@ngrx/store";
import * as fromApp from "@app/system/store/app.reducers";
import * as loginActions from "@app/core/modules/login/store/auth.actions";

@Injectable()
export class AuthSignatureExpiredInterceptor implements HttpInterceptor {
    constructor(
        private store: Store<fromApp.AppState>,
        private router: Router
    ) {}

    intercept(
        request: HttpRequest<any>,
        next: HttpHandler
    ): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(
            tap(
                (event: HttpEvent<any>) => {},
                (err: any) => {
                    if (err instanceof HttpErrorResponse) {
                        if (err.status === 401) {
                            this.store.dispatch(loginActions.logout());
                            this.router.navigateByUrl("/login");
                        }
                    }
                }
            )
        );
    }
}

The behavior that I experience is the following, if after the token has expired I refresh the browser then the user is properly redirected to the login page. But if I only move between the different internal links of the site I am not redirected, I must press f5 to force being sent to the login page
How can I ensure that this behavior also occurs when navigating between different links within the site?
How do I get it to be redirected to login when http response has status 401 due to an expired signature of the token?

A: Store the fact that the token has expired via your interceptor. Or remove the record from storage via the interceptor on 401 eg:
Create session record initially on intercept if authentication is valid, e.g:
sessionStorage.setItem('auth_token', myToken);

Then remove on intercept if not valid:
sessionStorage.removeItem('auth_token');

Then you can use Angular route guards to control access per route by implementing CanActivate interface (or for all child routes with CanActivateChild). See Medium route guard article for how to set up a route guard which can check if the token does not exist or is expired.


text:
Q: configured apache to host pyramid app, but restarts dont show changes I have a pyramid application that I want to host using Apache. I started off by sucessfully getting a blank application to run - I used pyramid's starter scaffold to create a basic app then I configured apache and made sure I could see the app in my browser. It worked great - I got a nice 'welcome to pyramid' page.
Then I swapped out the code of the starter application for code that is actually useful and reloaded apache. Refreshing the page gets me back to 'welcome to pyramid'. restarting apache has the same effect.
No matter what I do Apache is running old code. How do I fix this? How do I get apache to run my actual application?
FYI...
pyramid.wsgi
from pyramid.paster import get_app, setup_logging
ini_path = '/home/criticalid/critical_env/pyramidapp/production.ini'
setup_logging(ini_path)
application = get_app(ini_path, 'main')

/etc/apache2/sites-enabled/pyramid
<VirtualHost *:80>
       <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
    WSGIApplicationGroup %{GLOBAL}
    WSGIPassAuthorization On
    WSGIScriptAlias /criticalid /home/criticalid/critical_env/pyramid.wsgi

    <Directory /home/criticalid/critical_env>
        Order allow,deny
        Allow from all
    </Directory>

WSGIDaemonProcess pyramid user=criticalid group=criticalid threads=4 \
   python-path=/home/criticalid/critical_env/lib/python2.7/site-packages

ErrorLog ${APACHE_LOG_DIR}/error.log
        # Possible values include: debug, info, notice, warn, error, crit,
        # alert, emerg.
        LogLevel warn
        CustomLog ${APACHE_LOG_DIR}/access.log combined

</VirtualHost>

A: my gosh. The fix is buried in the fact that I used:
setup.py install

This works a little differently...
setup.py develop


text:
Q: How can I construct this concept for my gallery? Basically, I am trying to create a concept that I have designed into actual code, but I have gotten stuck. I want to construct this creation. I have made the gallery with the pictures, but I am having some troubles producing the spacing, color underneath the picture, and caption. If I add a caption, all the images get spread out to where I don't what them to be. Could anyone please help me in creating this? All I need is the spacing, color, and caption to work, since the gallery itself is responsive. Any help is appreciated. Thanks. Here is my code so far. Click the "Full Page" link on the snippet.

.intro {
    margin-top: 70px;
    text-align: center;
    margin-bottom: 40px;
  }

  .gallery_container-all {
    width: 95%;
    margin: 20px auto;
    height: auto;
    margin-bottom: 40px;
  }
  #outside{
      background-color: lightcyan;
  }
  .gallery_container {
    width: calc(33% - 6px);
    overflow: hidden;
    height: fit-content;
    margin: 3px;
    padding: 0;
    display: inline-block;
    position: relative;
    float: none;
    border-radius: 5px;
    background-color: black;
  }

  img {
    width: 100%;
    transition-duration: 0.3s;
    max-width: 100%;
    display: block;
    overflow: hidden;
    cursor: pointer;
  }

  .gallery_title {
    position: absolute;
    display: block;
    cursor: pointer;
    top: 35%;
    display: none;
    left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%);
    font-weight: bold;
    font-size: 1.6em;
    transition-duration: 0.3s;
  }

  .gallery_text {
    position: absolute;
    top: 70%;
    cursor: pointer;
    max-width: 80%;
    text-align: center;
    left: 50%;
    font-size: 1em;
    display: none;
    margin-right: -50%;
    transition-duration: 0.3s;
    transform: translate(-50%, -50%);
  }

  .gallery_container:hover img {
    transform: scale(1.2);
    transition-duration: 0.3s;
    opacity: 0.5;
  }

  .gallery_container:hover span {
    color: white;
    display: block;
    transition-duration: 0.3s;
  }

  @media only screen and (max-width: 800px) {
  .intro {
      margin-top: 40px;
  }
  .gallery_container {
      width: 100%;
      margin-left: auto;
      margin-right: auto;
  }
}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <title>repl.it</title>
    <link href="style.css" rel="stylesheet" type="text/css" />

Earth

Here are some pictures of Earth

A: This should do the work.

.intro {
  margin-top: 70px;
  text-align: center;
  margin-bottom: 40px;
}

.gallery_container-all {
  width: 95%;
  margin: 20px auto;
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  grid-template-rows: repeat(2, 1fr);
  gap: 50px;
}

#outside {
  background-color: lightcyan;
}

.gallery_container {
  width: 60%;
  overflow: hidden;
  border-radius: 5px;
}

.gallery_container:nth-last-of-type(2n + 1) {
  justify-self: end;
}

img {
  width: 100%;
  transition-duration: 0.3s;
  max-width: 100%;
  display: block;
  overflow: hidden;
  cursor: pointer;
}

img:hover {
  transform: scale(1.2);
  transition-duration: 0.3s;
  opacity: 0.9;
}

.content {
  position: relative;
  z-index: 50;
  padding-top: 60px;
  background-color: lightcyan;
}

.content h3 {
  margin: 0;
  text-align: center;
}

.content h3::before {
  content: "";
  position: absolute;
  background-color: orangered;
  border-radius: 500px;
  width: 150px;
  height: 20px;
  top: 30px;
  left: 50%;
  transform: translateX(-50%);
}

@media only screen and (max-width: 1000px) {
  .gallery_container {
    width: 100%;
  }
}

Earth

Here are some pictures of Earth

Caption

Caption

Caption

Caption


text:
Q: iPhone SDK update existing conatct in phone book I am able to create new contact using ABAddressBookRef. Is it posible to automatically update a particular contact with some values in database?
Thanks

A: Yes, you can update a particular record from the addressbook. For that you need to know the person's recordID and pass it to the following you will get the existing person's record. Then set the values for the properties. If you want to change any value then first remove earlier and then set the new one. For person's recordID if u are storing the person's record in the same application then at that time you can keep the IDs in an array. In my application I was showing the addressbook records in tableview so while fetching them I had stored their recordIds in an array. You can refer the code below:
ABAddressBookRef ab = ABAddressBookCreate();
ABRecordRef newPerson = ABAddressBookGetPersonWithRecordID(ab, id);
if(newPerson != NULL){
    if(![firstName.text isEqual:firstname]){
        ABRecordRemoveValue(newPerson, kABPersonFirstNameProperty,nil);
        ABRecordSetValue(newPerson, kABPersonFirstNameProperty,      firstName.text,nil);
    }
   }
ABAddressBookSave(ab,nil);


text:
Q: why {%extends %} , {%block body_block%},{%endblock%} seen in webpage in browser? enter image description here here {%extends %} and {%block body_block%},{%endblock %} are seen but they shouldn't .How to fix this?

A: {%extends %} means that you are using Django's template extending. So you need a base.html file to extends from. For example, you could create a file base.html like this:

        <title>XXX</title>

        {% block body_block %}
        {% endblock %}

then, in your original file, change like this:
{% extends 'base.html' %}
{% block body_block %}

Hello ClassBased View

{% endblock %}

then the 'body_block' part will fill in the '{% body_block %}' part of base.html.  See more here


text:
Q: VB Retrieve file directory path from a process I've worked with VBA for a few years, but I'm switching to VB to utilize more powerful coding practices.
I have the following VB code to attach an Excel workbook to an open instance:
Dim FullFilePath as String = "C:\Temp"
Dim WrkBk = as Excel.Workbook
WrkBk = System.Runtime.InteropServices.Marshal.BindToMoniker(FullFilePath)

This seems to require the workbook's directory path.
I have the following code to cycle through Excel processes.
FileName = "ABCD.xlsm"

For Each P As Process In System.Diagnostics.Process.GetProcessesByName("EXCEL")
    With P
        If .MainWindowTitle.ToLower.Contains(FileName.ToLower) Then

            'don't know the code to get the directory where the p process is located

            WrkBk = System.Runtime.InteropServices.Marshal.BindToMoniker(FilePath)

            Exit For
        End If
    End With
Next

The path to ABCD.xlsm is not always the same for my application. Everything I've googled for getting a directory of the process returns the EXCEL.EXE path or returns the path of the vb project's working directory. I really need it to return something like: "C:\Temp\Tools\ABCD.xlsm" so I can attach WrkBk to the process.
Any Ideas? Is there an easier way to do this?

A: Dim xl As Excel.Application
xl = GetObject(, "Excel.Application")
For Each wb As Excel.Workbook In xl.Workbooks
  MsgBox(wb.FullName)
Next wb
xl = Nothing

A: I finally found it.
Windows API....
Private Delegate Function EnumWindowsProc(ByVal hwnd As IntPtr, ByVal lParam As IntPtr) As Boolean
Private Declare Function EnumChildWindows Lib "user32.dll" (ByVal hWndParent As IntPtr, ByVal lpEnumFunc As EnumWindowsProc, ByVal lParam As IntPtr) As Boolean
Private Declare Function GetClassName Lib "user32.dll" Alias "GetClassNameA" (ByVal hwnd As IntPtr, ByVal lpClassName As String, ByVal nMaxCount As Int32) As Int32
Private Const MAX_TITLE As Int32 = 256
Private Const S_OK As Int32 = &H0

Private Function GetClassName(ByVal hwnd As IntPtr) As String
    Dim name As New String(" "c, MAX_TITLE)
    Dim len = GetClassName(hwnd, name, MAX_TITLE)
    If len = 0 Then Return Nothing
    Return name.Remove(len)
End Function

Private Declare Function AccessibleObjectFromWindow Lib "OLEACC.dll" (ByVal hwnd As IntPtr, ByVal dwId As Int32, ByVal riid As Byte(), ByRef ppvObject As IntPtr) As Integer
Private Const OBJID_NATIVEOM As Int32 = &HFFFFFFF0
Private IID_IDispatch As New Guid("{00020400-0000-0000-C000-000000000046}")

function...
Function EnumCWindows(ByVal hwnd As IntPtr, ByVal lParam As IntPtr) As Boolean
    Dim name = GetClassName(hwnd)
    If name = "EXCEL7" OrElse name = "EXCEL10" Then
        Dim ptr As IntPtr
        If AccessibleObjectFromWindow(hwnd, OBJID_NATIVEOM, IID_IDispatch.ToByteArray(), ptr) = S_OK Then
            Dim win = CType(Marshal.GetObjectForIUnknown(ptr), Excel.Window)
            Dim sheet = CType(win.ActiveSheet, Excel.Worksheet)
            Dim book = CType(sheet.Parent, Excel.Workbook)
            If book.FullName.ToLower.Contains("wpp tools") Then
                FoundTheFile = True
                WPPFilePath = book.FullName
                Exit Function
            End If
        End If
    End If
    Return True
End Function

then in your code....
For Each p In Process.GetProcesses
    If p.ProcessName = "EXCEL" Then
        EnumChildWindows(p.MainWindowHandle, AddressOf EnumCWindows, IntPtr.Zero)
        If FoundTheFile = True Then Exit For
    End If
Next
If FoundTheFile = False Then
    MsgBox("Targeted file was not found.", MsgBoxStyle.OkOnly, "File Find Error")
    End
End If

I hope this can help someone else as I've searched for a week now!