text:
Q: Java EE security - application clients I'm writing on a Java EE project which will have everything from 3-6 different clients. The project is open source, and I wonder what security mechanisms one could/should use. The problem is: Because it is open source, I would believe that it is possible for anyone with a user to write their own client (maybe not realistic, but truly possible) and make contact with the server/database. I've tried to go through all the scenarios of reading/writing different data to the database as different roles, and I conclude with that I have to have some security mechanism on a higher level than that (it is not enough to check if that account type is allowed to persist that entity with that ID and so on...). In some way I have to know that the client making contact is the correct client I wrote.  Could signing the Jar files solve this entire problem, or is there other ways to do it?
-Yngve

A: I really think that if restricting the available activities on the server side (based on role) is not sufficient, than you've got a bigger problem.  Even if a user doesn't write their own client, whatever mechanism you are using for your remote calls is likely to be vulnerable to being intercepted and manipulated.  The bottom line is that you should limit the possible calls that can be made against the server, and should treat each call to the server as potentially malicious.
Can you think of an example scenario in which there's a server action that a particular authenticated user would be allowed to take that would be fine if they're using your client but dangerous if they're not using your client?  If so I'd argue that you're relying too strongly on your client.
However, rather than just criticize I'd like to try to also offer some actual answers to your question as well.  I don't think signing your jar file will be sufficient if you're imagining a malicious user; in general, public-key cryptography may not help you much since the hypothetical malicious user who is reverse-engineering your source will have access to your public key and so can spoof whatever authentication you build in.
Ultimately there has to be someone in the system you trust, and so you have to figure out who that is and base your security around them.  For example, let's imagine that there may be many users at a particular company who you don't necessarily trust, and one admin who oversees them, who you do trust.  In that scenario you could set up your client so that the admin has to enter a special code at startup, and have that code be kept in memory and passed along with any request.  This way, even if the user reverse-engineers your code they won't have the admin code.  Of course, the calls from your client to your server will still be vulnerable to being intercepted and manipulated (not to mention that this requirement would be a royal pain in the neck to your users).
Bottom line: if your user's machine is calling your server, than your user is calling your server.  Don't trust your user.  Limit what they can do, no matter what client they're using.

A: Well the source may be available for anyone, but the configuration of the deployment and the database certainly isn't. When you deploy the application you can add users with roles. The easiest thing to do is to persist them in a database. Of course the contents of the table will only be accessible to the database administrator. The database administrator will configure the application so that it can access the required tables. When a user tries to log in, he/she must supply a username and password. The application will read the table to authenticate/authorize the user.
This type of security is the most common one. To be really secure you must pass the credentials over a secure path (HTTPS). For a greater degree of security you can use HTTPS client authentication. You do this by generating a public key for every client and signing this with the private key of the server. Then the client needs to send this signed key with every request.
EDIT: A user being able to write his/her own client doesn't make the application less secure. He/she will still not be able to access the application, if it is required to log in first. If the log in is successful, then a session (cookie) will be created and it would be passed with every request. Have a look at Spring security. It does have a rather steep learning curve, but if you do it once, then you can add security in any application at a number of minutes.


text:
Q: Cannot see changes in Magento 2 js and css I am new to magento 2 and I am creating extension for it.
But I am unable to see any js and css changes.
When i check on my source code my js file custom.js and css file custom.css is loaded properly but i am unable to see any of my changes.

I tried to clear cache and didn't get any result.
I cleared cache from backed and manually as well and disabled all
cache too.

A: step 1.
rm -rf pub/static/frontend/*
step 2.
rm -rf var/cache/*
step 3.
php bin/magento s:s:d -f
step 4.
php bin/magento indexer:reindex
The above step worked for me. I hope it will work for you also.

A: step 1. delete all folders under pub/static/frontend
step 2. delete cache folder under var/cache
Now open your command prompt and go to your root installation of magento 2
and fire the following commands
step 3. php bin/magento setup:static-content:deploy
step 4. php bin/magento indexer:reindex
The above step worked for me. I hope it will work for you also.
Let me know if you still facing any problem.

A: To work efficient it is possible to use the following command to do all tasks together:
rm -rf var/view_preprocessed; rm -rf pub/static/frontend/*; rm -rf var/cache/*; php bin/magento setup:static-content:deploy -f de_DE;

A: Even if Magento is in Dev mode, Nginx may set caching headers on Javascript and CSS files:
$ bin/magento deploy:mode:show
Current application mode: developer. (Note: Environment variables may override this value.)

See that Note? And sure enough:
$ curl -v 'https://foo.local/static/version51/adminhtml/Magento/backend/en_US/Dc_Foo/js/foo.js'
< HTTP/1.1 200 OK
< Server: nginx/1.21.6
< Date: Tue, 12 Jul 2022 12:00:07 GMT
< Content-Type: application/javascript; charset=utf-8
< Content-Length: 1082
< Last-Modified: Tue, 12 Jul 2022 05:57:18 GMT
< Connection: keep-alive
< ETag: "62cd0d3e-43a"
< Expires: Wed, 12 Jul 2023 12:00:07 GMT
< Cache-Control: max-age=31536000
< Cache-Control: public
< X-Frame-Options: SAMEORIGIN
< Accept-Ranges: bytes

Note the Expires header, set for one year in the future (answer written July 2022).
You can configure Nginx or Apache or any other server to not serve these headers, but my preferred method is to configure my browser to ignore caching when development tools are in use. In Chrome that can be accomplished by opening DevTools (F12), then clicking on the gear icon (⚙), then checking Preferences -> Network -> Disable cache while DevTools is open.

A: It may be because a core CSS rule has a priority over your css rule for the same DOM element. You should check it with a browser developer tools.

A: Require JS will cache the changes to your javascript files (even in developer mode). To disable caching, add the below to MyNamespace/MyModule/view/frontend/requirejs-config.js
var config = {
    urlArgs: "bust=" + (new Date()).getTime()
};

redpajama_set_name: RedPajamaStackExchange


text:
Q: Counting organizations which user has not contacted I am new at PostgreSQL. I have the following tables created in my schema:
User table:
CREATE TABLE public.users
(
    user_id integer NOT NULL DEFAULT nextval('users_user_id_seq'::regclass),
    first_name character varying(90) COLLATE pg_catalog."default" NOT NULL,
    last_name character varying(90) COLLATE pg_catalog."default" NOT NULL,
    email citext COLLATE pg_catalog."default" NOT NULL,
    user_password character varying(90) COLLATE pg_catalog."default" NOT NULL,
    bt_id integer,
    reset_password_token character varying COLLATE pg_catalog."default",
    bstage_id integer,
    CONSTRAINT users_pkey PRIMARY KEY (user_id),
    CONSTRAINT users_email_key UNIQUE (email),
    CONSTRAINT bstage_id FOREIGN KEY (bstage_id)
        REFERENCES public.business_stage (bstage_id) MATCH SIMPLE
        ON UPDATE NO ACTION
        ON DELETE CASCADE,
    CONSTRAINT bt_id FOREIGN KEY (bt_id)
        REFERENCES public.business_type (bt_id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE
        NOT VALID
)
WITH (
    OIDS = FALSE
)

Organization table:
CREATE TABLE public.organization
(
    org_id integer NOT NULL DEFAULT nextval('organization_org_id_seq'::regclass),
    name character varying(90) COLLATE pg_catalog."default" NOT NULL,
    description character varying(90) COLLATE pg_catalog."default" NOT NULL,
    email citext COLLATE pg_catalog."default" NOT NULL,
    phone_number character varying(11) COLLATE pg_catalog."default" NOT NULL,
    bt_id integer NOT NULL,
    bs_id integer NOT NULL,
    is_active boolean NOT NULL,
    org_link character varying COLLATE pg_catalog."default",
    CONSTRAINT organization_pkey PRIMARY KEY (org_id),
    CONSTRAINT bs_id FOREIGN KEY (bs_id)
        REFERENCES public.business_step (bs_id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE
        NOT VALID,
    CONSTRAINT bt_id FOREIGN KEY (bt_id)
        REFERENCES public.business_type (bt_id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE
        NOT VALID
)
WITH (
    OIDS = FALSE
)

And finally
Organization_rating table:
CREATE TABLE public.organization_rating
(
    rating integer NOT NULL,
    user_id integer NOT NULL,
    organization_id integer NOT NULL,
    rating_comment character varying(255) COLLATE pg_catalog."default",
    CONSTRAINT organization_rating_pkey PRIMARY KEY (user_id, organization_id),
    CONSTRAINT user_id FOREIGN KEY (user_id)
        REFERENCES public.users (user_id) MATCH SIMPLE
        ON UPDATE CASCADE
        ON DELETE CASCADE,
    CONSTRAINT stars CHECK (rating >= 1 AND rating < 5)
)
WITH (
    OIDS = FALSE
)

With this schema, an organization has a business type in which gives support to the user that also have that business type. After giving this support, the user can rate this organization with organization_rating. Following this logic, I would like to execute a query which gives me the percentage of the organizations that the user has contacted rated versus the organizations which the user still needs to rate. For example, lets say the user_id 1 rates the organization 1, which have the same business type as the user. 9 more organizations have the same business type, but the user has not rated these organizations. This query would return 10%.
I have the following query to count the organizations which the user has already contacted:
Select U.first_name, COUNT(R.rating)
From users as U INNER JOIN organization_rating as R on U.user_id = R.user_id
Inner join organization as O on O.org_id = R.organization_id
Where O.bt_id = 1 AND R.user_id != 62
Group by U.first_name;

How can I count the organizations which have not been contacted by this user, and the percentage of contacted vs still to be contacted?
If you could also refer me to some sites which can help me learn more of PostgreSQL and the different functions, I would appreciate it. Thank you in advance!

A: You can cross join the uses and organizations to get all possible combinations, then bring the bridge table with a left join. The last step is conditional aggregation:
SELECT u.first_name,
    COUNT(*) FILTER (WHERE r.user_id IS NULL) as cnt_not_contacted,
    AVG((r.user_id IS NOT NULL)::int) as avg_contacted
FROM users u
CROSS JOIN organization o
LEFT JOIN organization_rating r ON u.user_id = r.user_id AND o.org_id = r.organization_id
WHERE o.bt_id = 1 AND u.user_id <> 62
GROUP BY u.user_id


text:
Q: How to create Toast Notification with custom icon and custom app name? I'm trying to create a Windows Toast Notification with .Net C#. While this, I would like to change the notification icon and the app name in the attribution area (header) of the notification.
I'm able to place a notification with a custom "App name" like shown here:

I do this with this code:
var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);

var stringElements = toastXml.GetElementsByTagName("text");
stringElements[0].AppendChild(toastXml.CreateTextNode("Title"));
stringElements[1].AppendChild(toastXml.CreateTextNode("Message"));

ToastNotification toast = new(toastXml);
ToastNotificationManager.CreateToastNotifier("App name").Show(toast);

But I don't find a solution, how to place an icon left from "App name".
The solution can't be to modify the toast on a different way, since it only changes the visual or action elements. But not the attribute area:

How can I show an icon in the attribute area?

A: To set the icon in the attribution area you can set it directly.
var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);

var stringElements = toastXml.GetElementsByTagName("text");
stringElements[0].AppendChild(toastXml.CreateTextNode("Title"));
stringElements[1].AppendChild(toastXml.CreateTextNode("Message"));

ToastNotification toast = new(toastXml);
// here you set your icon
toast.attribution.icon = new ToastImageSource("path to your image");
ToastNotificationManager.CreateToastNotifier("App name").Show(toast);

To set the icon in the title you can change the created toast.
var toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastText02);

var stringElements = toastXml.GetElementsByTagName("text");
stringElements[0].AppendChild(toastXml.CreateTextNode("Title"));
stringElements[1].AppendChild(toastXml.CreateTextNode("Message"));

ToastNotification toast = new(toastXml);
// Here you can change the visual element of the toast
// don't know which image will be correct. Can't test at the moment
toast.Visual.TileLarge.HintRemoveMargin = true;
toast.Visual.TileSmall.HintRemoveMargin = true;
toast.Visual.TileMedium.HintRemoveMargin = true;
toast.Visual.TileLarge.Branding = ToastBranding.Logo;
toast.Visual.TileSmall.Branding = ToastBranding.Logo;
toast.Visual.TileMedium.Branding = ToastBranding.Logo;
toast.Visual.TileLarge.AppLogoOverride = new ToastAppLogo();
toast.Visual.TileSmall.AppLogoOverride = new ToastAppLogo();
toast.Visual.TileMedium.AppLogoOverride = new ToastAppLogo();
toast.Visual.TileLarge.AppLogoOverride.Crop = new ToastAppLogoCrop(0, 0, 1, 1);
toast.Visual.TileSmall.AppLogoOverride.Crop = new ToastAppLogoCrop(0, 0, 1, 1);
toast.Visual.TileMedium.AppLogoOverride.Crop = new ToastAppLogoCrop(0, 0, 1, 1);
toast.Visual.TileLarge.AppLogoOverride.Source = new ToastImageSource("file:///C:/path/to/your/icon");
toast.Visual.TileSmall.AppLogoOverride.Source = new ToastImageSource("file:///C:/path/to/your/icon");
toast.Visual.TileMedium.AppLogoOverride.Source = new ToastImageSource("file:///C:/path/to/your/icon");

ToastNotificationManager.CreateToastNotifier("App name").Show(toast);

Additionally you can set an appLogoOverlay which is displayed in the title area
// get hte ToastGeneric toast content
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastGeneric);

// here you get the visual element of the toast
XmlNodeList toastVisualElements = toastXml.GetElementsByTagName("visual");

// to add an icon you need app logo overlay
XmlElement appLogoOverlay = toastXml.CreateElement("appLogoOverlay");
// here you set the source of the overlay
appLogoOverlay.SetAttribute("src", "path to your icon");
// here you can add style attributes
appLogoOverlay.SetAttribute("hint-crop", "circle");
toastVisualElements[0].AppendChild(appLogoOverlay);

var stringElements = toastXml.GetElementsByTagName("text");
stringElements[0].AppendChild(toastXml.CreateTextNode("Title"));
stringElements[1].AppendChild(toastXml.CreateTextNode("Message"));

ToastNotification toast = new(toastXml);
ToastNotificationManager.CreateToastNotifier("App name").Show(toast);


text:
Q: Just Installed Ubuntu - Mostly empty screen that doesn't respond to mouse clicks or keyboard I installed (twice) Ubuntu x64 11.10 and it does boot (most of the time, sometimes it gets stuck with this problem My fresh installation doesn't load. (PulseAudio problem))
The little startup sound plays, I see a background, and a toolbar left and a thinner grey one top. There's three buttons on the left one, nothing on the top. I can move the mouse cursor but no key press or mouse (left or right click) anywhere does anything. I don't know what's going wrong with it or what to search for to find a solution. I'm hoping someone has an idea from this description.
The hardware is relatively modern so quite possibly it needs some drivers or configuration changes:
intel DX79T0 motherboard
i7 6-core
ATI Radeon 6950
What steps should I try to resolve this?

A: I got around it by changing .dmrc Session=ubuntu to Session=gnome-2d
I then installed the proprietary driver for my Radeon card and restored Session=ubuntu and it worked after that.

A: Try yo install am early version, if it works, then upgrade to latest version, also you can try a x86 version


text:
Q: How to scale feature by column? I believe i have to scale my features differently. Is there an easy way to scale my features by column?
ie.
samples[:, 0] = preprocessing.MaxAbsScaler().fit_transform([:, 0])
samples[:, 1] = preprocessing.StandardScaler().fit_transform([:, 1])

Is there an easy way to do this?

A: samples["column1"] = preprocessing.MaxAbsScaler().fit_transform(samples["column1"])
samples["column2"] = preprocessing.StandardScaler().fit_transform(samples["column2"])

You can do it like this if you want to scale columns differently.


text:
Q: Convert .pt to .pth? I've been trying to compile my custom trained YoloV5 model using SageMaker Neo.
The compilation gives an error :
ClientError: InputConfiguration: No pth file found for PyTorch model.
Please make sure the framework you select is correct.

The weights are a .pt file.
Is there a way to convert the .pt file to .pth?

A: There is no difference between both file extensions. If SageMaker is only looking for a file with a .pth extension, then you can simply rename your file from filename.pt to filename.pth.


text:
Q: How to calculate the minimal and maximal distance between these two objects? Suppose that an object $\mathcal{O}$ travels on the $xy$ plane following a path with respect to the time $t$ of the form $\mathcal{O}(t)=(2\cos(t), 2\sin (t))$ and another object $\tilde{\mathcal{O}}$ at the same time follows the path $\tilde{\mathcal{O}}(t)=(2\cos (t+\delta)+1, \sin(t+\delta))$, $t \in \Bbb R$, where $\delta$ is a real number.  I need to know how to calculate the minimal and maximal distance between these two objects as a function of $\delta$. I aready made a graph of the two paths, but I need to calculate this distance analytically. I calculated
$$||\mathcal{O}(t)-\tilde{\mathcal{O}}(t)||=\sqrt{9+8[\cos(t)\cos(t+\delta)-\sin(t)\sin(t+\delta)]+4[\cos(t)-\cos(t+\delta)]},$$
but I don't what else to do. Actually, I don't know if this is the correct and/or easiest way to solve this problem. I'd appreciate any ideas to solve this. Thanks in andvance. I leave you the graph of the paths:

A: First of all notice that if $f(t)$ is always positive, then finding the maximum and minimum of $\sqrt{f(t)}$ is the same as finding them for $f(x)$. This is obviously your case, where
$$f(t) = \big(1+2\cos(t+\delta)-2\cos(t)\big)^2+\big(\sin(t+\delta)-\sin(t)\big)^2$$
Now find the extrema as usual, by solving
$$\frac{\partial}{\partial t}f(t) = 0$$
and then checking the second derivative to determine which are maxima and which are minima.


text:
Q: Storing HTML5 Geolocation information in MySQL I've been experimenting with a simple project that essentially just stores the number of visits to the sites, along with the latitude / longitude of the user (it's mainly for people visiting via the iPhones Safari browser).
I've managed to store the 'clicks' to the page via PHP / MySQL, and I can display the users lat / long via the navigator.geolocation object in Javascript, but I have no idea how I can then store that (I'm fairly new at this!).
I appreciated that JavaScript is client-side and PHP is server-side, so I presume I need to somehow pass the returned values of my Javascript back to the PHP code somehow?
Thanks for any advice!

A: I've not used the navigator.geolocation object, but you should be able to send what it returns to an external page using AJAX.
<script>
var data = 'something-here'; // the result of your geolocation call
$.ajax({
    type: 'POST',
    url: 'http://yourdomain.com/storeLatLngInDb.php',
    data: data
});
</script>

The above is an example written on top of the jQuery framework.

A: You presume well. You can either put them in hidden fields in a form and ask user to press the button to send data to serve, or you can initiate AJAX call.


text:
Q: HTML body tags within Powershell I am new to Powershell and HTML. I am using Powershell code within an HTML file to display AD passwords expiry criteria and finally send it as an email. The email getting generated is having the header and footer displayed properly but the middle portion of the code which queries the AD is not showing any rows in the HTML table.
I am suspecting there is something wrong in my use of $body +=     but this is how some of the documentation has suggested. Also when I individually run the Powershell commandlets I can see that records are being returned.
Can someone please suggest where I could be going wrong?
 #Remove Digital Signature Check
Set-ExecutionPolicy Unrestricted

 import-module activedirectory
# $ErrorActionPreference = 'SilentlyContinue'

$MailParams = @{
To = @("iq@mail.com")
From = "iq@mail.com"
Subject = "HTML Table"
SmtpServer = "mail.server.com"
}

 try {

        $body =
        "

                Attention IT Group:

                    <td colspan=2 style='width:100.0%; border:solid #1F4E79 1.0pt; background:#1F4E79; padding:0cm 5.4pt 0cm 5.4pt'

                                Password Expirations for Service Accounts

"
# **** Need Code for Expire within < 1 Day ******
        $body +=    Get-ADUser -Filter {Enabled -eq $True}  -SearchBase "OU=Service Accounts,OU=SG1,OU=TAW,DC=wt,DC=ad,DC=cit,DC=com" `
                 -Properties * |
                 Sort-Object -Descending -Property  @{Expression={($_.PasswordLastSet.AddDays(365) - [DateTime]::Now).Days}}|
                # sort-object -Descending -property SamAccountName |
                 Where-Object{($_.PasswordLastSet.AddDays(365) - [DateTime]::Now).Days -le  1 }|
    Select-Object -property `
           @{Name="LogonName";Expression={$_.SamAccountName}} ,
            @{Name="PasswordExpiration";Expression={$_.PasswordLastSet.AddDays(365).ToString("dd-MMM-yyyy")}}  |
    convertto-HTML -Fragment

# **** Need Code for Expire within 7 Days ( 2 - 7 Days) ******
        $body +=   Get-ADUser -Filter {Enabled -eq $True}  -SearchBase "OU=Service Accounts,OU=SG1,OU=TAW,DC=wt,DC=ad,DC=cit,DC=com" `
                 -Properties * |
                 Sort-Object -Descending -Property  @{Expression={($_.PasswordLastSet.AddDays(365) - [DateTime]::Now).Days}}|
                # sort-object -Descending -property SamAccountName |
                 Where-Object{($_.PasswordLastSet.AddDays(365) - [DateTime]::Now).Days -in (2,7) }|
    Select-Object -property `
           @{Name="LogonName";Expression={$_.SamAccountName}} ,
            @{Name="PasswordExpiration";Expression={$_.PasswordLastSet.AddDays(365).ToString("dd-MMM-yyyy")}}  |
    convertto-HTML -Fragment

# **** Need Code for Expire within 7 Days ( 8 - 15 Days) ******
        $body +=   Get-ADUser -Filter {Enabled -eq $True}  -SearchBase "OU=Service Accounts,OU=SG1,OU=TAW,DC=wt,DC=ad,DC=cit,DC=com" `
                 -Properties * |
                 Sort-Object -Descending -Property  @{Expression={($_.PasswordLastSet.AddDays(365) - [DateTime]::Now).Days}}|
                # sort-object -Descending -property SamAccountName |
                 Where-Object{($_.PasswordLastSet.AddDays(365) - [DateTime]::Now).Days -in (8,15) }|
    Select-Object -property `
           @{Name="LogonName";Expression={$_.SamAccountName}} ,
            @{Name="PasswordExpiration";Expression={$_.PasswordLastSet.AddDays(365).ToString("dd-MMM-yyyy")}}  |
    convertto-HTML -Fragment

# **** Need Code for Expire within 7 Days (16- 30  Days) ******
        $body +=  Get-ADUser -Filter {Enabled -eq $True}  -SearchBase "OU=Service Accounts,OU=SG1,OU=TAW,DC=wt,DC=ad,DC=cit,DC=com" `
                 -Properties * |
                 Sort-Object -Descending -Property  @{Expression={($_.PasswordLastSet.AddDays(365) - [DateTime]::Now).Days}}|
                # sort-object -Descending -property SamAccountName |
                 Where-Object{($_.PasswordLastSet.AddDays(365) - [DateTime]::Now).Days -in (16,30) }|
    Select-Object -property `
           @{Name="LogonName";Expression={$_.SamAccountName}} ,
            @{Name="PasswordExpiration";Expression={$_.PasswordLastSet.AddDays(365).ToString("dd-MMM-yyyy")}}  |
    convertto-HTML -Fragment

#*****   Footer of Email****
    $body += "

                     Management team

             "
    $MailParams.body = $body

}

catch {
write-output "No records found for one of the criteria"
}

Send-MailMessage @MailParams -BodyAsHtml

A: This won't be the full answer, and I'm basically repeating what people have already said. Especially the comment to not call Get-ADUser three times.

*

*Your Get-Aduser should be filtered with a query - don't return every enabled account and then use a Where clause. I assume you want accounts with password last set date up to 30 days before what will be the 1 year anniversary of the password date? Grab all of those and then use your Where clause on the results.

*Separate the code where you're generating your AD report from the code where you generate the HTML. And separate that from the code where you construct the mail message. You currently have three different processes jumbled together, and this makes troubleshooting more complex.

*Output your fragments as HTML files and test individually. Outlook is really picky about the HTML it renders and
 and  can be a drama. Of course they work in Outlook, but sometimes some combination doesn't work. I keep it as simple as possible.

Here's an example of how the AD filter and subsequent slicing could work.
$1year = (get-date).AddDays(-365)
$30days = (get-date).AddDays(-334)
$tomorrow = (get-date).AddDays(-364)
$15days = (get-date).AddDays(-350)

# Get all the users that will be included in the report - one AD query
$users = get-aduser -filter 'passwordlastset -gt $1year -and passwordlastset -lt $30days -and enabled -eq "True"' `
    -properties passwordlastset -searchbase "OU=myOU,DC=example,DC=com"

# break down the user list into the report categories
$expTomorrow = $users | where {$_.passwordLastSet -le $tomorrow} |
    sort -Property passwordlastset -Descending |select -property `
        @{Name="LogonName";Expression={$_.SamAccountName}},
        @{Name="PasswordExpiration";Expression={$_.PasswordLastSet.AddDays(365).ToString("dd-MMM-yyyy")}}
$exp15Days = $users | where {$_.passwordLastSet -gt $tomorrow -and $_.passwordLastSet -le $15days} |
    sort -Property passwordlastset -Descending | select -property `
        @{Name="LogonName";Expression={$_.SamAccountName}},
        @{Name="PasswordExpiration";Expression={$_.PasswordLastSet.AddDays(365).ToString("dd-MMM-yyyy")}}
$expOver15Days = $users | where {$_.passwordLastSet -gt $15days} |
    sort -Property passwordlastset -Descending | select -property `
         @{Name="LogonName";Expression={$_.SamAccountName}},
         @{Name="PasswordExpiration";Expression={$_.PasswordLastSet.AddDays(365).ToString("dd-MMM-yyyy")}}

# assemble body
$preHTML = @'
...
'@
$postHTML = @'
...
'@

$body = $preHTML
$body += [fragment1]
$body += ...

# Send message
Send-MailMessage ...

With the three collections of users for your report, you can check the output of each of those individually to see if they look correct.
For your testing, do the Convertto-HTML -fragment on some collection examples, wrap them inside a really basic HTML header, output to file, and see how they look in the browser.
Once that looks good, create a codeblock to assemble the entire body into the $body variable. Remember that some of those user collections might be empty, so you'll need to append to $body so it doesn't error on an empty collection (obviously test that).
I agree with the comment not to wrap the body in yet another table. Just do a simple paragraph with a text style for your heading. Leave out the  tags unless you're actually styling the text. Once again, check how it renders in the browser when output as a simple HTML file.
Then your Send-MailMessage can be in its own codeblock. It makes it a lot easier to see where something's going wrong.


text:
Q: Calculating radius using tangent point and center point I got 2 coordinates which are given to me, they can be random. One is a tangent point coordinate and the other is center point coordinate.
I would like to get the radius of the circle using these 2 points. How would I do that? Is there a formula or something I have forgotten about?

A: Given the centre $(x_1,y_1)$ and a point on the circumference of the circle $(x_2,y_2)$ then using the general form of a circle in the Cartesian plane$$(x-x_1)^2+(y-y_1)^2=r^2$$
and calculating the radius using the distance formula
$$r=\sqrt{(x_2-x_1)^2+(y_2-y_1)^2}$$
we would get
$$(x-x_1)^2+(y-y_1)^2=(x_2-x_1)^2+(y_2-y_1)^2$$
which can be expanded and simplified if required.


text:
Q: How to fix this question:ERROR: Command errored out with exit status 1: command: /usr/bin/python /usr/local/
*

*Python:3.7

*Raspbian GNU/Linux 10 (buster)

*Pip:latest

I cant install Pyqt5 by "pip install PyQt5" or "pip3 install PyQt5"
" Using cached PyQt5-5.15.4.tar.gz (3.3 MB)
  Installing build dependencies ... done
  Getting requirements to build wheel ... done
    Preparing wheel metadata ... error
    ERROR: Command errored out with exit status 1:
     command: /usr/bin/python /usr/local/lib/python3.7/site-packages/pip/_vendor/pep517/_in_process.py prepare_metadata_for_build_wheel /tmp/tmp12utc_07
         cwd: /tmp/pip-install-isn1q135/pyqt5_3ec1cc0700174738991a9fc21489ab73
    Complete output (37 lines):
    Querying qmake about your Qt installation...
    /usr/bin/qmake -query
    Traceback (most recent call last):
      File "/usr/local/lib/python3.7/site-packages/pip/_vendor/pep517/_in_process.py", line 126, in prepare_metadata_for_build_wheel
        hook = backend.prepare_metadata_for_build_wheel
    AttributeError: module 'sipbuild.api' has no attribute 'prepare_metadata_for_build_wheel'

    During handling of the above exception, another exception occurred:

    Traceback (most recent call last):
      File "/usr/local/lib/python3.7/site-packages/pip/_vendor/pep517/_in_process.py", line 280, in <module>
        main()
      File "/usr/local/lib/python3.7/site-packages/pip/_vendor/pep517/_in_process.py", line 263, in main
        json_out['return_val'] = hook(**hook_input['kwargs'])
      File "/usr/local/lib/python3.7/site-packages/pip/_vendor/pep517/_in_process.py", line 131, in prepare_metadata_for_build_wheel
        config_settings)
      File "/usr/local/lib/python3.7/site-packages/pip/_vendor/pep517/_in_process.py", line 159, in _get_wheel_metadata_from_wheel
        whl_basename = backend.build_wheel(metadata_directory, config_settings)
      File "/tmp/pip-build-env-9qtio6u7/overlay/lib/python3.7/site-packages/sipbuild/api.py", line 51, in build_wheel
        project = AbstractProject.bootstrap('pep517')
      File "/tmp/pip-build-env-9qtio6u7/overlay/lib/python3.7/site-packages/sipbuild/abstract_project.py", line 83, in bootstrap
        project.setup(pyproject, tool, tool_description)
      File "/tmp/pip-build-env-9qtio6u7/overlay/lib/python3.7/site-packages/sipbuild/project.py", line 481, in setup
        self.apply_user_defaults(tool)
      File "project.py", line 63, in apply_user_defaults
        super().apply_user_defaults(tool)
      File "/tmp/pip-build-env-9qtio6u7/overlay/lib/python3.7/site-packages/pyqtbuild/project.py", line 70, in apply_user_defaults
        super().apply_user_defaults(tool)
      File "/tmp/pip-build-env-9qtio6u7/overlay/lib/python3.7/site-packages/sipbuild/project.py", line 227, in apply_user_defaults
        self.builder.apply_user_defaults(tool)
      File "/tmp/pip-build-env-9qtio6u7/overlay/lib/python3.7/site-packages/pyqtbuild/builder.py", line 75, in apply_user_defaults
        self._get_qt_configuration()
      File "/tmp/pip-build-env-9qtio6u7/overlay/lib/python3.7/site-packages/pyqtbuild/builder.py", line 484, in _get_qt_configuration
        for line in project.read_command_pipe([self.qmake, '-query']):
      File "/tmp/pip-build-env-9qtio6u7/overlay/lib/python3.7/site-packages/sipbuild/project.py", line 445, in read_command_pipe
        "'{0}' failed returning {1}".format(cmd, pipe.returncode))
    sipbuild.exceptions.UserException
    ----------------------------------------
WARNING: Discarding https://files.pythonhosted.org/packages/8e/a4/d5e4bf99dd50134c88b95e926d7b81aad2473b47fde5e3e4eac2c69a8942/PyQt5-5.15.4.tar.gz#sha256=2a69597e0dd11caabe75fae133feca66387819fc9bc050f547e5551bce97e5be (from https://pypi.org/simple/pyqt5/) (requires-python:>=3.6). Command errored out with exit status 1: /usr/bin/python /usr/local/lib/python3.7/site-packages/pip/_vendor/pep517/_in_process.py prepare_metadata_for_build_wheel /tmp/tmp12utc_07 Check the logs for full command output.

I dont kown how to do ...


text:
Q: Understanding clones borrow I'm fairly new to rust, and still learning the rust ownership model. I'm working on a piece of code where I hold a reference to a point in the data structure. I want to store multiple copies of this data structure, where on each copy the reference point hold different values. I (tried to) solve this by creating a mutable reference to the point inside the data structure, and after each update of the reference create a clone of the original data structure.
I was able to create this simple example that is analogue to what i'm trying to do and produces the same error.
fn main() {
    let mut v = vec![1, 1, 1];
    let mut c = Vec::new();

    for i in &mut v {
        *i += 1;
        c.push(v.clone());
    }

    println!("{:?}", v);
}

which produces the following error
error[E0502]: cannot borrow `v` as immutable because it is also borrowed as mutable
   --> src/main.rs:107:16
    |
105 |     for i in &mut v {
    |              ------
    |              |
    |              mutable borrow occurs here
    |              mutable borrow later used here
106 |         *i += 1;
107 |         c.push(v.clone());
    |                ^ immutable borrow occurs here

With some help of the handy rust book i was able to interpret the error message. I believe this tells me that I cannot have both a mutable, and an immutable reference that are alive at the same time. What is (or is there) an rust-idiomatic method of iteratively creating duplicates of a data structure and updating a reference within said data structure?
Edit:
The example above might be too minified and not highlight the actual problem I'm having. What would be the rust-idiomatic way to write something like the example below.
#[derive(Clone, Debug)]
enum Tree {
    Leaf,
    Node { l: Box<Tree>, r: Box<Tree>, },
}

fn main() {
    let mut tree = Tree::Node {
      l: Box::new(Tree::Node { l: Box::new(Tree::Leaf), r: Box::new(Tree::Leaf), }),
      r: Box::new(Tree::Node { l: Box::new(Tree::Leaf), r: Box::new(Tree::Leaf), }),
    };
    let augmenting_trees = vec![
        Tree::Node { l: Box::new(Tree::Leaf), r: Box::new(Tree::Leaf), },
        Tree::Node { l: Box::new(Tree::Node { l: Box::new(Tree::Leaf), r: Box::new(Tree::Leaf), }), r: Box::new(Tree::Leaf), },
        Tree::Node { l: Box::new(Tree::Leaf), r: Box::new(Tree::Node { l: Box::new(Tree::Leaf), r: Box::new(Tree::Leaf), }), },
    ];

    let mut trees: Vec<Tree> = Vec::new();
    let leaf = find_some_leaf_in_tree(&mut tree);
    for augmenting_tree in augmenting_trees {
        *leaf = augmenting_tree;
        trees.push(tree.clone());
    }

    println!("trees: {:?}", trees);
}

fn find_some_leaf_in_tree<'a>(tree: &'a mut Tree) -> &'a mut Tree {
    match tree {
        Tree::Leaf => tree,
        Tree::Node { l, .. } => find_some_leaf_in_tree(l),
    }
}

A:
What is (or is there) an rust-idiomatic method of iteratively creating duplicates of a data structure and updating a reference within said data structure?

The general answer is "don't use a reference for the purpose you're trying to use a reference". In this case, you have a vector, so use indices instead of references:
fn main() {
    let mut v = vec![1, 1, 1];
    let mut c = Vec::new();

    for i in 0..v.len() {
        v[i] += 1;
        c.push(v.clone());
    }

    dbg!(v, c);
}

Note that this doesn't mean you can't use references at all. For example, the code could be written in terms of a mutable reference to v instead:
fn modify_and_snapshot(v: &mut Vec<u32>) -> Vec<Vec<u32>> {
    let mut c = Vec::new();
    for i in 0..v.len() {
        v[i] += 1;
        c.push(v.clone());
    }
    c
}

fn main() {
    let mut v = vec![1, 1, 1];
    let c = modify_and_snapshot(&mut v);
    dbg!(v, c);
}

The necessary condition is that when you want to snapshot v, you don't have a mutable reference to less than all of v — you can own the whole vector or you can have a mutable reference to the whole vector, but you can't do anything with the whole of the vector while a mutable reference to part of it exists.


text:
Q: I am using apache shiro under camel and I cannot map groups to roles with ldap/active directory I am using shiro with camel. I can authenticate an user with activedirectory (ldap) but I am not able to map user groups in roles to user permissions. And camel needs absolutely permissions to work.
Here is my config.ini:
[main]
authcStrategy = org.apache.shiro.authc.pam.FirstSuccessfulStrategy
securityManager.authenticator.authenticationStrategy = $authcStrategy

activeDirectoryRealm = org.apache.shiro.realm.activedirectory.ActiveDirectoryRealm
activeDirectoryRealm.systemUsername=cn=padl,cn=Users,dc=comune,dc=prato,dc=local
activeDirectoryRealm.systemPassword=xxxxxxxxxxxxxxxxxxxxxxx
activeDirectoryRealm.url = ldap://172.16.1.98:389
activeDirectoryRealm.groupRolesMap = "CN=menu_ufficiomobile_ania,OU=Menu,OU=Gruppi,OU=ComuneDiPrato,DC=comune,DC=prato,DC=local":"menu_ufficiomobile_ania"

securityManager.realms = $activeDirectoryRealm
[users]

test = test,menu_ufficiomobile_passicarrabili, menu_ufficiomobile_rubati,menu_ufficiomobile_ordinanze, menu_ufficiomobile_ztl, menu_ufficiomobile_cciaa,  menu_ufficiomobile_ania, menu_ufficiomobile_anagrafe, menu_ufficiomobile_mctc, menu_ufficiomobile_pra

[roles]

menu_ufficiomobile_anagrafe = prato:anagrafe
menu_ufficiomobile_mctc = prato:mctc
menu_ufficiomobile_pra = prato:pra
menu_ufficiomobile_ania = prato:ania
menu_ufficiomobile_cciaa = prato:cacomm
menu_ufficiomobile_ztl = prato:ztl
menu_ufficiomobile_ordinanze = prato:ordinanze
menu_ufficiomobile_rubati = prato:rubati
menu_ufficiomobile_passicarrabili = prato:permessi

My security injection code:
ShiroSecurityToken shiroSecurityToken = new ShiroSecurityToken(qr.getUserName(),qr.getPassword());
ShiroSecurityTokenInjector shiroSecurityTokenInjector = new ShiroSecurityTokenInjector(shiroSecurityToken, passPhrase);
arg0.getIn().setHeader("SHIRO_SECURITY_TOKEN", shiroSecurityTokenInjector.encrypt());

And the routing code that uses permissions:
from("seda:interrogaANIA").threads(1)
 .setHeader("db", constant(Database.ANIA)).policy(aniaS)
 .to("bean:interrogaANIA?method=interrogaBancaDati")
 .to("seda:prefilter");

Thanks,
Mario

A: So, a realm in shiro provides 3 things:

*

*Authenticate users

*Map users to roles

*Map users to permissions

What it does not do is provide arbitrary role->permission mapping.  For this, you would need to set a RolePermissionResolver on your active directory realm.  Looking at the IniRealm (which is what gets created by the [users] and [roles] section in your ini file), there doesn't appear to be an easy way to use it as a RolePermissionResolver.  I was able to throw together an adapter class that should work reasonably well.
package org.apache.shiro.samples.web;

import java.util.Collection;
import java.util.Collections;

import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.SimpleRole;
import org.apache.shiro.authz.permission.RolePermissionResolver;
import org.apache.shiro.config.Ini;
import org.apache.shiro.realm.text.IniRealm;

public class IniRealmRolePermissionResolver implements RolePermissionResolver {
        private LocalIniRealm realm;

        public Collection<Permission> resolvePermissionsInRole(final String roleString) {
                final SimpleRole role = this.realm.getRole(roleString);
                return role == null ? Collections.<Permission>emptySet() : role.getPermissions();
        }

        public void setIni(final IniRealm ini) {
                this.realm = new LocalIniRealm();
                this.realm.setIni(ini.getIni());
                this.realm.init();
        }

        private static class LocalIniRealm extends IniRealm {
                @Override
                protected SimpleRole getRole(final String rolename) {
                        return super
                                        .getRole(rolename);
                }
        }
}

This should be usable with this addition to your ini file:
rolePermissionResolver = org.apache.shiro.samples.web.IniRealmRolePermissionResolver
rolePermissionResolver.ini = $iniRealm
activeDirectoryRealm.rolePermissionResolver = $rolePermissionResolver

If you don't really need the ini mapping, you can use the same concept, but greatly simplify things.
package org.apache.shiro.samples.web;

import org.apache.shiro.authz.Permission;
import org.apache.shiro.authz.permission.*;

import java.util.Collection;
import java.util.Collections;

public class SimpleRolePermissionResolver implements RolePermissionResolver, PermissionResolverAware {

    private PermissionResolver permissionResolver = new WildcardPermissionResolver();

    public void setPermissionResolver(PermissionResolver permissionResolver) {
        this.permissionResolver = permissionResolver;
    }

    public Collection<Permission> resolvePermissionsInRole(String roleString) {
        return Collections.<Permission>singleton(permissionResolver.resolvePermission(roleString));
    }
}

And then your ini configuration changes a bit as well:
rolePermissionResolver = org.apache.shiro.samples.web.SimpleRolePermissionResolver
activeDirectoryRealm.rolePermissionResolver = $rolePermissionResolver


text:
Q: How to launch instance with more storage in AWS? I'm running instances in AWS using following:
input := &ec2.RunInstancesInput{
    // .... assign parameters
}
reservation, err := ec2session.RunInstancesWithContext(ctx, input)

I'd like to supply storage size of the storage volume, just as it can be specified in the AWS Console in the 'Add Storage' tab.
However, I can't configure RunInstancesInput for initial storage size, so it launches with whatever default size for the instance type.
I can attach another volume later, but I want to specify initial volume size.
Is it possible, and how to do it?

A: As it was already suggested in comments, you should add BlockDeviceMapping into your request. Here is an example of how to do it in Java.
private static BlockDeviceMapping blockDeviceMapping(int systemDiskSizeInGb)
{
    EbsBlockDevice ebs = new EbsBlockDevice()
            .withVolumeSize(systemDiskSizeInGb)
            .withVolumeType(VolumeType.Gp2);
    return new BlockDeviceMapping()
            .withDeviceName("/dev/sda1")
            .withEbs(ebs);
}

private static RunInstancesRequest buildInstanceRequest(String imageId, int systemDiskSizeInGb)
{
    return new RunInstancesRequest()
            .withImageId(imageId)
            .withBlockDeviceMappings(ImmutableSet.of(blockDeviceMapping(systemDiskSizeInGb)));
}

RunInstancesResult result = this.ec2Client.runInstances(request);


text:
Q: Detect unsaved data using angularjs I'm a newbie to AngularJs, so this might be trivial.
Are there any inbuilt AngularJs directive to detect unsaved data in a form.
If not then how to go about writing one.
Any pointers would be appreciated.
html code is
<input type="text" runat="server" />

And my angular js controller code is
    function MyCtrl1($scope) {
      // code to do stuff
}MyCtrl1.$inject = ['$scope'];

I am trying to write a directive to detect unsaved data, and I'm guessing its to be written in the above controller.Correct me if wrong.

A: AngularJS sets the CSS classes ng-pristine and ng-dirty on any input field you've used ng-model on, and your FormController has the properties $pristine and $dirty which you can check to see if the form is dirty or not. So yes, it's possible.
Could you provide some code that shows what you're trying to do? That would make it easier to help you.
EDIT
Here's a simple example of how to detect a pristine/dirty state, and how to revert to a pristine state:
<!doctype html>

    <form name="myForm" ng-controller="Ctrl">
        myModel.text: <input name="input" ng-model="myModel.text">

myModel.text = {{myModel.text}}

$pristine = {{myForm.$pristine}}

$dirty = {{myForm.$dirty}}

        <button ng-click="revert()">Set pristine</button>
    </form>

A: Monitoring pristine/dirty state is a good place to start, but if you want to provide user with the best possible usability, you will have to compare current form data with initial form data to detect any changes. If form is dirty it still doesn't mean that it has changed data.
I've created a very small and useful module to solve this exact problem. With it you can keep your controller code as simple as possible. It adds modified property to every model and even form controller automatically and you can reset entire form by just calling a provided reset() method, so you can concentrate on your application's business logic instead of detecting changes manually.
Please see the Demo.
You can find a distribution package as well as a source code here:
https://github.com/betsol/angular-input-modified (it's also available via Bower)
If you will need any help with using this library - you can contact me personally. I will be glad to help. Cheers!

A: This is what I did in my Controller.
When I get the form data for modification, first I save its string representation to a scope variable like this:
$scope.originalData = JSON.stringify($scope.data);

Then I create a state change listener:
 var $locationChangeStartUnbind = $scope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
    if ($scope.originalData !== JSON.stringify($scope.data)) {
        //Show alert and prevent state change
    } else {
        //DO NOTHING THERE IS NO CHANGES IN THE FORM
    }
});

Then I clear the listener on scope destroy:
$scope.$on('$destroy', function () {
    window.onbeforeunload = null;
    $locationChangeStartUnbind();
});

Hope this helps.

A: Try this directive that works with ui-router
https://github.com/facultymatt/angular-unsavedChanges


text:
Q: How To make a Form and Div have a max width of child elements I was wondering How To make a Form and Div have a max width of child elements. Eg in this example both the form and the outerDiv stretch the full width of the page. I would like the form and outerDiv to have a width of 200px.
This becomes a problem when I have this page in an iframe, because the width of the page is larger than the iframe I get a horizontal scroll bar.

<form name="myForm" method="post" action="#"  >

        Both the form and outer div stretch 100%. I am wondering how I
        would get them to wrap tightly around the inner div.

</form>

Thanks for your time and help.

A: To make a block display like an inline element you can use
display: inline-block;

A: I believe the "proper" way is to make them inline elements:
style="display: inline;"

divs are block elements and fill their container,
spans are inline elements and shrink to fit their contents.
You can either use spans as containers or just add the above style to your divs.
Good luck!

A: To prevent scrollbars for #outerDiv you could set a max-width and overflow properties:
#outerDiv {
  max-width: 300px;
  overflow: hidden;
}

In this way, you assure no scroll bars, and I'm assuming the width of the iframe is never wider than 300 pixels. Also be sure to set frameborder="0" on the iframe and check the margins on the body of the included html.


text:
Q: Laravel API Based ionic application not working on android but its working fine on browser This is my code. its perfectly works on browser. But it doesn't works at mobile. Please help me to solve this problem. I am using laravel api to get json output.
import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders, HttpErrorResponse } from '@angular/common/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/timeout';

@Injectable()
export class AccessProviders  {
    server: string = 'https://sriex.com/api/';
    constructor(
        public http: HttpClient,
    ){

    }
    postData(body,file,user_token){
        let type = "application/json; charset=UTF-8";
        let token = "Bearer "+user_token;
        let headers = new HttpHeaders({ 'Content-Type': type,'Authorization': token});
        let options = {
            headers: headers
        }
        return this.http.post(this.server+file,JSON.stringify(body),options).map(res => res);
       // return this.http.post(this.server + file,JSON.stringify(body),options)
        //.timeout(59000)
        //.map(res => res);
    }
}


text:
Q: Emacs Lisp: Multiple comment-start values Is it possible to have multiple comment-start strings in an Emacs major mode? I am looking at some VB code, which has both single-quote comments and "REM" comments.

A: Yes. C and C++ mode do, for example.
See the Elisp manual, node Syntax Class Table. This is the relevant part for comment syntax:

Comment starters: <
Comment enders: >
Characters used in various languages to delimit comments.  Human
       text has no comment characters.  In Lisp, the semicolon (;)
       starts a comment and a newline or formfeed ends one.

(You will need to read more about specifying syntax classes, to configure your own comment behavior.)
FYI, I found this node of the manual by using i in the manual: i comment TAB.


text:
Q: Two tangent circles and parallel lines I have problems in solving the following problem:
Consider two circles which have only one point $A$ in common, i.e. which are tangent to each other. Now consider two lines through A, such that the lines meet the circles at further points $B,C,D,E$. I want to prove that the lines $DE$ and $BC$ are parallel lines ($D,E$ being points on one circle and $B,C$ on the other).
I tried to use theorems like the inscribed angle theorem, but I was not succesfull so far. Does someone know how to solve this problem?
If it is possible, I only want to use geometric arguments, and not analytical arguments. Does this result have any name?
Best wishes

A: Hint:
Let $M,N$ two points on the common tangent at opposite sides with respect to $A$, than $\angle DAM = \angle DEA$ because they subtend the same arc $DA$ ( $\angle DAM$ is a ''limit'' angle, being  the side $AM$ tangent, but, if you don't like the concept of ''limit'' angle, you can proof the same claim as a consequence of the tangent-secant theorem.).
In the same manner $\angle BAN=\angle BCA$.
Now note that $\angle DAM$ and $\angle BAN$ are opposed, and .....
I don't know if this result has a special name.

A:
Let the common tangent $L$ be drawn.
Then, by the Alternate Segment Theorem:
$$\angle DEA =\angle (DA,L)$$
And similarly:
$$\angle CBA=\angle (CA,L)$$
But the latter are equal as they are vertically opposite.
Therefore it follows that the angles
Intercepted by $BE$ are equal and thus, the lines are parallel.

This is a special limiting case of the Reim's Theorem, which states that lines through the points of intersection of two circles cut the circle in points that form two parallel segments.
This is not a well-known theorem by the way.


text:
Q: function not working and nothing is happening I am trying to insert a data or record inside firebase realtime database.
I am using firebase 9.14.0. Upon clicking the button there are no errors or prompts. What's the problem?
Here is my code:
var crops = document.getElementById('cropName').value;
var cropDetails = document.getElementById('cropInformation').value;

function insertData(){
 set(ref(database, "Crops/"),{
    CropName: crops,
    CropDetails: cropDetails
 })
 .then(()=>{
    alert ("successfully inserted");
 })
 .catch((error)=>{
    alert ("unsucessful, error");
 });
}

addCrop.addEventListener('click', insertData);

I checked if I am connected with firebase, I am. And I am expecting to get my data inserted to their realtime database, but nothing is happening.


text:
Q: Performing statistics or simple pie chart in QGIS? Does anyone know how to perform pie charts based on table values within QGIS and include them in the print outs?

A: Giovanni is right. I outline the process here: http://darrencope.com/2011/11/01/qgis-diagrams-pie-charts-for-symbols/

To create a diagram symbol, go to the properties for the layer in question, and click the "Diagrams" tab at the top, then check off "Display Diagrams" and set Diagram type to "Pie Chart." You can also use "Text Diagram" but that's another post!
You can set either a fixed size, or scale the size of the charts to an attribute value range. This is useful if you are wanting to use the size of the symbol to indicate a value, and the 'slices' to indicate percentages. In my case, I set the size to '23' and set it to scale between 0 and 30mm. This is arbitrary in my case, but you can play with it using your own data to see what works best for you.
At the bottom under "Attributes," select each attribute you want to form a 'slice' of the pie, and click the '+' on the right. Then select the next value, and click '+.'  Repeat until you are finished adding all values. In my case, I added attributes A, B, C, and D. I didn't want to use the ID, so I left it out. You can set individual colours for each 'slice' here by double clicking the colour in the table. Here's what my settings looked like:

A: Open the vector attributes and use the tool you'll find in the "diagram" tab.


text:
Q: How to execute a method passed as parameter to function I want to write my own function in JavaScript which takes a callback method as a parameter and executes it after the completion, I don't know how to invoke a method in my method which is passed as an argument. Like Reflection.
example code
function myfunction(param1, callbackfunction)
{
    //do processing here
    //how to invoke callbackfunction at this point?
}

//this is the function call to myfunction
myfunction("hello", function(){
   //call back method implementation here
});

A: function myfunction(param1, callbackfunction)
{
    //do processing here
   callbackfunction(); // or if you want scoped call, callbackfunction.call(scope)
}

A: You can just call it as a normal function:
function myfunction(param1, callbackfunction)
{
    //do processing here
    callbackfunction();
}

The only extra thing is to mention context.  If you want to be able to use the this keyword within your callback, you'll have to assign it. This is frequently desirable behaviour. For instance:
function myfunction(param1, callbackfunction)
{
    //do processing here
    callbackfunction.call(param1);
}

In the callback, you can now access param1 as this.  See Function.call.

A: I too came into same scenario where I have to call the function sent as parameter to another function.
I Tried
mainfunction('callThisFunction');

First Approach
function mainFuntion(functionName)
{
    functionName();
}

But ends up in errors. So I tried
Second Approach
functionName.call().

Still no use. So I tried
Third Approach
this[functionName]();

which worked like a champ. So This is to just add one more way of calling. May be there may be problem with my First and Second approaches, but instead googling more and spending time I went for Third Approach.

A: All the examples here seem to show how to declare it, but not how to use it. I think that's also why @Kiran had so many issues.
The trick is to declare the function which uses a callback:
function doThisFirst(someParameter, myCallbackFunction) {
    // Do stuff first
    alert('Doing stuff...');

    // Now call the function passed in
    myCallbackFunction(someParameter);
}

The someParameter bit can be omitted if not required.
You can then use the callback as follows:
doThisFirst(1, myOtherFunction1);
doThisFirst(2, myOtherFunction2);

function myOtherFunction1(inputParam) {
    alert('myOtherFunction1: ' + inputParam);
}

function myOtherFunction2(inputParam) {
    alert('myOtherFunction2: ' + inputParam);
}

Note how the callback function is passed in and declared without quotes or brackets.

*

*If you use doThisFirst(1, 'myOtherFunction1'); it will fail.

*If you use doThisFirst(1, myOtherFunction3()); (I know there's no parameter input in this case) then it will call myOtherFunction3 first so you get unintended side effects.

A: object[functionName]();
object: refers to the name of the object.
functionName: is a variable whose value we will use to call a function.
by putting the variable used to refer to the function name inside the [] and the () outside the bracket we can dynamically call the object's function using the variable. Dot notation does not work because it thinks that 'functionName' is the actual name of the function and not the value that 'functionName' holds. This drove me crazy for a little bit, until I came across this site. I am glad stackoverflow.com exists <3

A: Another way is to declare your function as anonymous function and save it in a variable:
var aFunction = function () {
};

After that you can pass aFunction as argument myfunction and call it normally.
function myfunction(callbackfunction) {
    callbackfunction();
}

myfunction(aFunction);

However, as other answers have pointed out, is not necessary, since you can directly use the function name. I will keep the answer as is, because of the discussion that follows in the comments.

A: I will do something like this
var callbackfunction = function(param1, param2){
console.log(param1 + ' ' + param2)
}

myfunction = function(_function, _params){
_function(_params['firstParam'], _params['secondParam']);
}

Into the main code block, It is possible pass parameters
myfunction(callbackfunction, {firstParam: 'hello', secondParam: 'good bye'});

A: callbackfunction = () => {}
callbackfunction2(){
}
function myfunction1(callbackfunction) {
    callbackfunction();
}
//Exe
myfunction1(callbackfunction);
myfunction1(callbackfunction2.bind(this));

A: Super basic implementation for my use case based on some excellent answers and resources above:
/** Returns the name of type member in a type-safe manner. **(UNTESTED)** e.g.:
*
* ```typescript
* nameof<Apple>(apple => apple.colour); // Returns 'colour'
* nameof<Apple>(x => x.colour); // Returns 'colour'
* ```
*/
export function nameof<T>(func?: (obj: T) => any): string {
 const lambda = ' => ';
 const funcStr = func.toString();

 const indexOfLambda = funcStr.indexOf(lambda);
 const member = funcStr.replace(funcStr.substring(0, indexOfLambda) + '.', '').replace(funcStr.substring(0, indexOfLambda) + lambda, '');

 return member;
}


text:
Q: Expo.io using React Native - "Super expression must be either null or a function" Code:
    import React from 'react'
import { Text, View, StyleSheet } from 'react-native';

export default class App extends React.Component(){
  render(){
    return(
     <View> </View>
    )
  }
}

Why is this returning an error? I am using version 42.00 on Expo.io and my browser is fully updated.

A: You've accidentally added () after React.Component. It should be likeso:
import React from 'react'
import { Text, View, StyleSheet } from 'react-native';

export default class App extends React.Component {
  render(){
    return(
     <View> </View>
    )
  }
}


text:
Q: Sinusoidal wave output from a GPIO I think the question is not particularly MCU/board specified but I will be trying it on STM32F4-DISC board.
I was thinking of how to output a nice sinewave from a normal GPIO output pin, but I was not able to find a proper methodology. I am asking for a method of thinking, a guide rather than the complete solution.
Just give me an overview of the process.
If possible of course.
Thanks in advance.

A: Only dedicated DAC outputs could do this directly but for many purposes you could use a timer output pin in compare mode to generate pulse width modulation (PWM) and vary that in a sinusoidal fashion.  If the you then filter it (sometimes with nothing more than some series resistance and capacitance to ground) you can end up with a reasonable approximation to a sine wave for many purposes.
The greater the difference in frequency between the PWM repetition rate, and the desired sine wave frequency, the better the result you can achieve.
With either a DAC or PWM, you probably want to implement a Direct Digital Synthesizer to produce the amplitude values, at least if you need to vary the frequency or it is not a nice fraction of an available clock.  The DDS algorithm is described in this existing EESE answer (describing an audio application, but the technique is general)

Most practical table based synthesizers use a fixed playback sample
  rate, and a fractional phase increment and accumulator register.
Essentially, calculate the phase increment per sample period for your
  desired output frequency, and pre-multiply by a large power of two,
  say 1024 or even higher - with an ARM MCU you might as well just
  multiply it by 2^16.
Each cycle add this phase increment to an accumulator register.
The accumulator will be wider (have more precision) than the address
  input into your wave lookup table, so simply ignore the lower bits and
  use only as many upper bits as your lookup table has address bits. So
  you might be calculating time with 32-bit accuracy, but only using the
  upper 16 bits to look up samples in a 65536 element table.
The result is that while the index time of a given sample is
  approximate, the cumulative time has many bits of accuracy. This
  easily gets you sub-Hz resolution, without the need to alter a timer
  or DAC clock at all. And that's important, because typically the
  cleanup circuitry in a DAC and following its output is designed for
  only a small number of sample rate(s).
Note that if your lookup table contains a sine or other waveform with
  symmetry, you can probably shrink its size - for a sine you really
  only need to store a quarter of a wave, as you can get the other three
  quadrants by inverting phase or amplitude.

A: You would

*

*create one cycle of appropriate analog values in a buffer

*use the values in the buffer to adjust the duty cycle on a PWM output on a GPIO, stepping through the buffer

*filter the PWM signal with an RC circuit

Of course, "nice" can mean a lot of things.  For the highest quality, use a fast PWM carrier freq, and make sure your buffer makes use of the full resolution of the PWM duty cycle control.
STM32F4's tend to have Digital to Analog converters, which can do the job directly.
You might find http://www.ti.com/lit/an/spraa88a/spraa88a.pdf of use

A: Only pins capable for that on STM32F4 would be the DAC output pins.


text:
Q: Powerpivot average, only show a range of rows I have done an average price calculation for apples. See example
In the new column "testar", I only want to show the year 1990 - 1994 (yellow cells), since the other years are not specified in my formula.
Formula I used for average calculation was:
=CALCULATE (
AVERAGEX (Datasrc; Datasrc[C_P2] );
DATESBETWEEN(Datasrc[Year];"1990-01-01";"1994-01-01")
)

Any ideas or advice how to do that?

A: You'll need to test the values of Datasrc[Year] in an IF().
Here's a sample using a dummy dataset I have.
Testar =
IF(
    MAX( DimDate[Year] ) > 2010
        && MAX( DimDate[Year] ) < 2014
    ,[SumAmt]
)

We're testing MAX() DimDate[Year]. On any given pivot row, only one year is in context, so max is the year on that pivot row.
The measure you used calculates the average in the context of the 5 years you've defined, overriding whatever the current filter context is.
Additionally, AVERAGEX() is unnecessary in this situation; you can use AVERAGE( Datasrc[C_P2] ).

A: Almost, thank you for your valuable input and put me in the right direction!!!, since my format of the year table is different and I want to have the average price listed I did a little different. I simply combined your formula with my average formula and got the result I wanted.
See final result here
Code used:
=IF(
    MAX( Datasrc[Year2] ) >= 1990
        && MAX( Datasrc[Year2] ) <= 1994
    ;
CALCULATE (
AVERAGEX (Datasrc; Datasrc[C_P2] );
DATESBETWEEN(Datasrc[Year];"1990-01-01";"1994-01-01")
)
)

The first part of the formula, takes out only the years I'm interested in.
The second part of the formula [CALCULATE(AVERAGEX....] calculates the average of the years I'm interested of.


text:
Q: writing a spelling test for java and can't get my code to work the word abstract keeps messing up the whole thing i have been looking for hour on how to fix my code to make it work.
i am writing a spelling text the shows the user a definition and make them spell the word.
in my if else statement, the word abstract keeps me from moving on. the code is really long so i will give you a little bit of it.
i left comments near the bottom.
class SpellingExam {
    static CinReader cn = new CinReader();

    public static void main(String[] args) {
        String name = "Tim";
        DateFormat df = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
        Date today = Calendar.getInstance().getTime();
        String theDate = df.format(today);
        String goodWords = "Method, String, Java";
        String content = name + "\r\n" + theDate + "\r\n" + goodWords;
        stringToFile( content, "Spelling exam for " + name + ".txt" );
    }

    private static void stringToFile( String content, String fileName ) {
        try {
            File file = new File( fileName );
            if ( !file.exists() ) {
                file.createNewFile( );
            }
            FileWriter fw = new FileWriter( file.getAbsoluteFile( ) );
            BufferedWriter bw = new BufferedWriter( fw );
            bw.write( content );
            bw.close( );
        }
        catch( IOException e ) {
            e.printStackTrace( );
        }
    }

    public static void question1() {
        System.out.println("A class with the abstract reserved word in its header. Abstract classes are distinguished by the fact that you may not directly construct objects from them using the new operator. An abstract class may have zero or more abstract methods.");
        char answer1 = cn.readChar();
        if("abstract") {
           /*
            * here is the main problem
            * the word abstract is highlighted
            * incompatible types is all it says
            */
            System.out.println("correct!");
            playerScore += 1;
        }
        else {
            System.out.println("incorrect...");
        }
    }
}

A: vijar's and Ale Zalazar's comments are correct.  There's no boolean condition for your if() statement to match.  You need to read the user's typed input and compare that input with the String you expect.


text:
Q: Internal network can't see mailserver on public ip address Mikrotik Please esxcuse my english as it is not my home language
I have mailserver in my network behind a mikrotik router and firewall
the problem that I'm having is that my mailserver is on a public ip address
and that im not able to connect to it internaly. I have no problem connecting from outside the network.  The only way I'm able to connect at this point is to assign the public ip to the mikrotik router and setup these two NAT rules
IP Address I have used are only examples
 - Internal Network = 172.162.30.0/12
 - Public IP mailserver = 42.20.16.18
 - Private IP mailserver = 172.162.30.65
 **Internal clients Note:** Source address is my whole network this has    a     massive affect on my internet speed because
 I think all traffic is being routed to mail server

 chain=srcnat action=src-nat to-addresses=42.20.16.18
  src-address=172.162.30.0/24 log=no log-prefix=""

For clients connecting from outside the network
   chain=dstnat action=dst-nat to-addresses=172.162.30.65
   dst-address=42.20.16.18 log=no log-prefix=""
I tried almost every solution out there this is my last resort
my main goal is that I physically can assign my public ip to the machine and connect internally without using the private ip.

A: There are two solutions to this problem.
Either you implement NAT Loopback or NAT Hairpin or NAT Reflection (it's the same thing with different names) or you modify your internal DNS so that your mailserver's hostname does not resolve to the public IP but to your local IP (only from inside your private network).
With your src-nat rule you are already doing the first solution (NAT Hairpin) which as you mentioned works. The problem with this approach is that all your connections to the mailserver are being changed to src-address 42.20.16.18 so the mailserver only logs this IP instead of each user's real internal IP.
The other approach is that you either use Mikrotik's DNS server or any other local DNS server of your choice. There you set up a dns record with the mailserver's hostname and you set it to resolve to the internal IP of the mailserver.
Then you must configure all your PCs on your network to use this dns server and when hitting your mailserver's hostname they will resolve the internal IP instead of the public allowing them to connect to it directly instead of having to go through the router via NAT.
For more information about NAT Hairpin you can check the official Mikrotik Documentation here and for more information about the Mikrotik's DNS Server you can check here

A: For those interested, I encountered an issue with this solution whenever I sent mail to somebody that receivers mail server would detect a different source ip, a source ip that is blacklisted I think that it has to do with the fact that my ISP has masquerading setup somewhere down the line. I don't know, my work around was I created the dst-st and src-nat again, I kept the dst-nat the same as before and just changed the src-nat source address from my whole network to just my mail servers private ip. This worked 100% see below
chain=srcnat action=src-nat to-addresses=42.20.16.18
src-address=172.162.30.65 log=no log-prefix=""
chain=dstnat action=dst-nat to-addresses=172.162.30.65 dst-address=42.20.16.18 log=no log-prefix=""


text:
Q: Accessing Database Tables on Remote Machine from Local Machine Using R Basically, I have a local laptop and a remote machine. My database is on the Remote machine which I access through Remote Desktop Connection.I can ofcourse run R tasks on the remote machine itself. Now I wonder if I can connect the remote machine from my local R and run the tasks on the remote machine while I still call these things in my local machine... that is I don't need to open R or type/source R codes on the remote machine.Can also live with typing R codes to access the Remote Database.Also saving the files on my Local machine.
Is there any other method to download those database tables on my local machine???


text:
Q: android providing different drawable resources for orientations I would like to provide different drawable resources for different orientations.  What is the proper folder name to provide a landscape and portrait version of a drawable? I looked through the android documentation and haven't seen anything like drawable-hdpi-land or drawable-hdpi-port.  Are these the proper names?

A: it's
drawable-land-hdpi etc,
see the documentation for the full order:
http://developer.android.com/guide/topics/resources/index.html


text:
Q: AWS TimeStream Python SDK: Cannot create a correct client object Based on AWS TimeStream SDK documentation for Python, I have the following code:
import boto3

def list_databases(self):
        print("Listing databases")
        try:
            result = self.client.list_databases(MaxResults=5)
            self._print_databases(result['Databases'])
            next_token = result.get('NextToken', None)
            while next_token:
                result = self.client.list_databases(NextToken=next_token, MaxResults=5)
                self._print_databases(result['Databases'])
                next_token = result.get('NextToken', None)
        except Exception as err:
            print("List databases failed:", err)

session = boto3.Session(profile_name='superuser', region_name='eu-west-1')
query_client = session.client('timestream-query')

list_databases(query_client)

The authentication for my user superuser seems to work fine, but the boto3 session used for my query_client does not have a client object:
Listing databases
List databases failed: 'TimestreamQuery' object has no attribute 'client'

What am I missing?

A: This argument name in this method is likely a mistake:
# this name is discouraged in non-OO code:
def list_databases(self):

self is typically used in object oriented python code, which is not the case here.
Rename it as follows:
# this is better:
def list_databases(client):

Then, remove any mention of self in the body of the function, for example:
# this is incorrect:
result = self.client.list_databases(MaxResults=5)

should be:
# this should work:
result = client.list_databases(MaxResults=5)


text:
Q: JApplet multiple pages application I want to build a JApplet application, consists of 5 pages. Given data in one page will be input for next page. Based on given data I have to show different options in next page.
I am completely new to applets, previously worked with web applications. I need something similar to MVC but should completely with applets (Swing JApplet). Is there any framework like struts to implement it?
Please give me some ideas.  How do I proceed?

A: For me it's something like wizard.
I would define a cutom model class storing data for each page and define 5 JPanels to represent the model's data for each step.
Then all the 5 panels should be placed in a container with CardLayout.
Moving to the next step reads current step data, stores the data in model and prepares the model's data for the next step.
After that card swapped and new step's panel is shown reflected prepared data from the model.


text:
Q: How to insert a list of objects using stored proc in ado.net Let's say I have this method
public static void LockPerformanceToDB(List<performance> listOfPerformances)
{
    //Do I need just to wrap this call with a loop? ...
    using(var con = new OpenConnection)
    {
       //I call the LockPerformanceToDB SPROC here ...
    }
}

I also have this procedure in the database:
CREATE PROCEDURE LockPerformancesToDB
    @UserId INT,
    @Comments VARCHAR(50),
    @TimeStamp DATETIME
AS
BEGIN
    INSERT INTO Performance
    (UserId, Comments, [TimeStamp])
    VALUES
    (@UserId, @Comments, @TimeStamp)
END

This sproc handles one insertion at time. As it's obvious that the list has several of the same performance objects. Is looping through each object of the list the solution?
I'd like to know whether there is a different solution besides looping and calling the sproc as many times as there are objects in the lisOfPerformances?
Thanks for helping

A: Why not use Table-Valued Parameters to pass multiple rows to the stored procedure.

Table-valued parameters are declared by using user-defined table types. You can use table-valued parameters to send multiple rows of data to a Transact-SQL statement or a routine, such as a stored procedure or function, without creating a temporary table or many parameters.

*

*Create the type
Create Type TVP_LockPerformancesToDB As Table(
 UserId int, Comments varchar(50), [TimeStamp] datetime)

*Create the stored procedure as
CREATE PROCEDURE LockPerformancesToDB2
@CommentInfo TVP_LockPerformancesToDB READONLY
AS
BEGIN
  INSERT INTO Performance
   (UserId, Comments, [TimeStamp])
    SELECT UserId, Comments, [TimeStamp]
  FROM @CommentInfo
END

*Then in your code
class Performance
{
    public int UserId { get; set; }
    public string Comments { get; set; }
    public DateTime TimeStamp { get; set; }
}

List<Performance> listOfPerformances = new List<Performance>() {
     new Performance{ UserId=1, Comments="First", TimeStamp=DateTime.Now},
     new Performance{ UserId=2, Comments="Second", TimeStamp=DateTime.Now},
     new Performance{ UserId=3, Comments="Third", TimeStamp=DateTime.Now}
 };

 SqlCommand cmd = new SqlCommand();
 var dt = new DataTable();
 dt.Columns.Add("UserId", typeof(Int32));
 dt.Columns.Add("Comments", typeof(string));
 dt.Columns.Add("TimeStamp", typeof(DateTime));
 for (int i = 0; i < listOfPerformances.Count; i++)
 {
    dt.Rows.Add(listOfPerformances[i].UserId, listOfPerformances[i].Comments, listOfPerformances[i].TimeStamp);
 }

 cmd.Connection = conn;
 cmd.CommandText = "LockPerformancesToDB2";
 cmd.CommandType = CommandType.StoredProcedure;
 cmd.Parameters.Add(new SqlParameter("CommentInfo", SqlDbType.Structured));
 cmd.Parameters["CommentInfo"].Value = dt;

 cmd.ExecuteNonQuery();


text:
Q: what does the letter acronym S mean? what does S mean when running mini tests?
*** Running FRONTEND component engine specs
Run options: --seed 1947

# Running:

...................................................S....S....S.................................S............S...............S

I google around but didn't find an answer.

A: This means that you've skipped a test, or six in this case.
If you want to read more about skipping tests, there's a good blog post here that goes into detail.


text:
Q: Oblate ellipsoids and latitude I've been reading Wikipedia and am having a bit of trouble.
https://en.wikipedia.org/wiki/Latitude
Geodetic latitude would clearly change if the Earth were squashed vertically.
But would places like London retain their original geocentric latitude if this happened?
Or would geocentric latitude change, too?
I made these two images.
The left image is of a perfect sphere. The right image is of an oblate ellipsoid with geodetic latitude lines. The height of the right ellipsoid is equal to sin(45) times the height of the left sphere.
The yellow dot on the left image marks Greenwich, England.
Where should the yellow dot go on the right image?

If someone could place the dot roughly, then I can then work backwards to answer my question.

A: To calculate the geodetic latitude of a point, we draw a line that passes through the point and is also perpendicular to the surface of the ellipsoid  (called a Normal), and evaluate the angle it forms with the equatorial plane.
In this image from the Wikipedia article, you can see this relationship between the point and its latitude. The line PN (extended to C on the equatorial plane) is the normal used as a reference for the calculation.
The geocentric latitude (which is much less common) is measured by drawing a line linking the point with the center , and then measuring the angle with the equatorial plane. If we squashed the Earth, all these angles would change indeed. If the Earth were a sphere, both geocentric and geodetic latitudes would be equal for any point, because the perpendicular line would always pass through the center. On the ellipsoid, they are equal only if the point is at the poles or on the equator.

A: There's no single "right answer" (to where the yellow dot goes).  It all
depends on what you want to preserve as you deform the ellipsoid.
Let's start with the continents drawn on the reference ellipsoid and you
want to exaggerate the flattening of the earth to emphasize the
ellipsoidal effects.

*

*If you squash everything vertically, you are preserving the parametric
latitude β.

*If you squash radially (by a factor that depends on latitude), you are
preserving the geocentric latitude θ.

*If you wish to preserve shapes, you should hold the conformal
latitude χ of points constant.

*If you wish to preserve areas, you should hold the authalic latitude
ξ of points constant.  This has my vote because it leads to the most
natural looking deformation.

*If you wish to preserve meridional distances, you should hold the
rectifying latitude μ of points constant.

*Holding the geographic latitude φ constant is probably the worst
choice because it leads to the bizarre result of everything being
concentrated near the equator in the limit of extreme flattening.
ADDENDUM
To illustrate the various possibilities, I show here textured ellipsoids for a case of large flattening: b/a = 1/4, f = 3/4.  In this sequence, the texture is mapped using φ, β, ξ, μ, χ, and θ, respectively:
 geographic φ
 parametric β
 authalic ξ
 rectifying μ
 conformal χ
 geocentric θ


text:
Q: Windows Authentication and Custom SQL Profile/Role membership How would it be best to use windows authentication with custom sql profile and role membership?  We currently grab windows.identity.name (domain/username) and look up information i sql server to retrieve profile and role information.  I would like to make things more efficient by utilizing membership providers.
How would I go about doing this?  We currently develop within corporate environment using mvc and webforms.

A: You can certainly use SqlRoleProvider with Windows authentication. Just configure and enable RoleManager in your Web.config.
Unfortunately, you'll need to manually call the aspnet_Users_CreateUser stored procedure to populate the aspnet_Users table with your users. (The username will be your domain name, e.g., MYDOMAIN\myusername).
With that in place, you can then use the RoleManager API to create roles and associate users to roles, then use User.IsInRole to test for role membership.


text:
Q: Change configuration parameters from command-line or programatically How can I change settings in pg_hba.conf and postgresql.conf either from the command-line or programatically (especially from fabric or fabtools)?
I already found set_config, but that does not seem to work for parameters which require a server restart. The parameters to change are listen_addresses in postgresql.conf and a new line in pg_hba.conf, so connections from our sub-network will be accepted.
This is needed to write deployment scripts using fabric. It is not an option to copy template-files which then override the existing *.conf files, because the database server might be shared with other applications which bring their own configuration parameters. Thus, the existing configuration must be altered, not replaced.

A: Here is the currently working solution, incorporating the hint from a_horse_with_no_name. I paste a snippet from our fabfile.py (it uses require from fabtools, and it runs against Ubuntu):
db_name = env.variables['DB_NAME']
db_user = env.variables['DB_USER']
db_pass = env.variables['DB_PASSWORD']

# Require a PostgreSQL server.
require.postgres.server(version="9.4")
require.postgres.user(db_user, db_pass)
require.postgres.database(db_name, db_user)

# Listen on all addresses - use firewall to block inadequate access.
sudo(''' psql -c "ALTER SYSTEM SET listen_addresses='*';" ''', user='postgres')

# Download the remote pg_hba.conf to a temp file
tmp = tempfile.NamedTemporaryFile()
with open(tmp.name, "w") as f:
    get("/etc/postgresql/9.4/main/pg_hba.conf", f, use_sudo=True)

# Define the necessary line in pg_hba.conf.
hba_line = "host    all     all     {DB_ACCEPT_IP}/0   md5".format(**env.variables)

# Search the hba_line in the existing pg_hba.conf
with open(tmp.name, "ra") as f:
    for line in f:
        if hba_line in line:
           found = True
           break
    else:
        found = False

# If it does not exist, append it and upload the modified pg_hba.conf to the remote machine.
if not found:
    with open(tmp.name, "a") as f:
        f.write(hba_line)
    put(f.name, "/etc/postgresql/9.4/main/pg_hba.conf", use_sudo=True)

# Restart the postgresql service, so the changes take effect.
sudo("service postgresql restart")

The aspect I don't like with this solution is that if I change DB_ACCEPT_IP, this will just append a new line and not remove the old one. I am sure a cleaner solution is possible.


text:
Q: Keep a modified version of a GitHub repository updated Over the last few days, I have been working on adding update validators to Mongoose. I consider this absolutely critical in the way I use mongodb; this is why I got myself a lot of sleep deprivation, and implemented it:
https://github.com/LearnBoost/mongoose/pull/1256
For reasons that are very legitimate (it's impossible to have 100% consistent validators as right now mongoose validators expect full access to the loaded doc, something that is impossible for an update), Aaron, the great Mongoose maintainer, might end up not accepting this upstream. See the discussion in the pull request if you are interested.
This is absolutely not a problem: Mongoose is Aaron's baby, and he obviously got a LOT of things right; at the same time... well, I do do need update validation.
I am hopeless with git, although I am getting the gist of it. Now, I cloned Mongoose's main repo so that I could submit my pull request:
https://github.com/mercmobily/mongoose
I am obviously using this one for development (since it has the goodies). The modifications are really quite localised (only a big chunk of code in model.js and two small localised chunks in query.js). But, I am worried because Mongoose is very actively developed and I don't really want to miss out on the latest cream.
So, the question: How can I keep my repository syncronised with the main one, on a day to day basis? Or maybe weekly basis? Merging my modifications should be straightforward, as they shouldn't affect Mongoose as a whole.
I hope I won't have to do it in the end, but I am preparing for the worst :D
Thanks!

A: The general way you keep up with changes in a remote repo is that you 1) add a new "remote" repo in your local git repo, 2) fetch updates for that new remote repo, and 3) merge/rebase your repo to these changes.
Check these articles out:
How to sync with a remote Git repository?
http://gitready.com/advanced/2009/02/11/pull-with-rebase.html


text:
Q: setting env variable like "key=value as string array" in docker compose I want to change settings value in environment section.  like below...
environment:
  - GROUP__One=["Group A", "Group B", "Group C"]

but it not work. Are there any errors?

A: Unfortunately, you can't do that.
You can only set string environment value on docker compose file.
The way to resolve this is to do it inside your code.
For example:
environment:
  - GROUP__One=Group A,Group B,Group C

On your code, split the environment by ,
example on Go:
strings.Split(os.Getenv("GROUP__One", ","))

You can write the seperator other than ,


text:
Q: my database give ana null object reference in sqllite android. how can i solve this _____
java.lang.NullPointerException: Attempt to invoke virtual method 'long
com.example.carpetcatalog.DataBaza.insertYec_product(com.example.carpetcatalog.Models.YecProductForDB)'
on a null object reference
at com.example.carpetcatalog.MainActivity$4.onResponse(MainActivity.java:374)

public void networkCallbackForProduct() {
        Call<List<Yec_product>> productresponse = ApiClient.getRetrofit().create(ApiInterFace.class).getproductfromAPI();
        productresponse.enqueue(new Callback<List<Yec_product>>() {
            @Override
            public void onResponse(Call<List<Yec_product>> call, Response<List<Yec_product>> response) {
                if (!response.isSuccessful()) {
                    Toast.makeText(MainActivity.this, response.code(), Toast.LENGTH_SHORT).show();
                }
                List<Yec_product> productList = response.body();
                for (Yec_product product : productList) {
                    YecProductForDB yecProductForDB = new YecProductForDB(product.getId(), product.getCode(), product.getName(), product.getImage_url(), product.getPrice(), product.getQuality_id(), product.getRoom_id(), product.getChanged());
                  long natija=dataBaza.insertYec_product(yecProductForDB);
                  if (natija==-1){
                      Toast.makeText(MainActivity.this, "error insert baza product", Toast.LENGTH_SHORT).show();
                    finish();
                  }

                }
            }

            @Override
            public void onFailure(Call<List<Yec_product>> call, Throwable t) {
                Toast.makeText(MainActivity.this, "error" + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });

    }

Database classs*******************************


text:
Q: In if test the list contains only one specific string or multiple same specific string I have a list file as
mike
jack
jack
mike

sometimes is (no mike)
jack
jack

I would like to test whether this file only contains one mike or multiple mike's like following
if [list **only** contains one `mike` or multiple `mike`'s]
then
do something
else
echo jack(other's name) is using it
done

A: Solution in bash
You can use a while loop with read to read through the lines as
while read line;
do
   [ $line == "mike" ] && ((count=$count+1))
done < inputFile

The $count will contain the count of mike in the file.
$ echo $count
2

Solution in awk
$ awk '/mike/{count++}; END{print count}' input
2

A: find_mike () {
    mike_count=$(grep -c 'mike');
    if (( mike_count == 1 )); then
        printf 'I found only one mike.'
    elif (( mike_count > 1 )); then
        printf 'I found %d mikes.' "$mike_count"
    else
        printf '%s\n' "I have no idea where is mike";
    fi
}

Usage example:
$ find_mike < input_file.txt
I found 2 mikes

A: [ "$(sort inputfile | uniq)" = mike ]

sort the input, then remove all identical lines. You need to sort the input for uniq because it works only for consecutive identical lines.
Short form:
[ "$(sort --unique inputfile)" = mike ]

A: grep -xvq mike inputfile

*

*-x: match the whole line

*-v: invert the match

*-q: do not print anything; exit at first match

This command exits with 0 as soon as it finds something that is not mike. If the file is empty or contains only (any number of) mike lines, it exits with 1.
grep is very, very fast. And it stops as soon as possible parsing the input file.
You might want to invert the exit value by prefixing the command with an exclamation mark.


text:
Q: Existence of $\{a_n\}$ s.t $f(\vec{v})=\sum_{n \in \mathbb{N}} a_n v_n$ for continuous linear functions. disclaimer: this is a homework assignment, I'm looking for a hint or a word of advice, not a full solution.
Let $f: l^1 \to \mathbb{R}$ be a continuous, linear function. Prove that there exists a bounded sequence $\{a_n\}$ of real numbers such that $$f(\textbf{v})=\sum_{n \in \mathbb{N}}a_n v_n$$ for $\textbf{v} \in l^1$, and where $\textbf{v}=(v_1,v_2,...)$.
Okay, so the first thing I noticed was that the question is icognito hiding the fact that we can define a vector $\textbf{a}=(a_1,...)$ so that $$\sum_{n \in \mathbb{N}}a_n v_n=\langle\textbf{a},\textbf{v}\rangle$$
So in truth, we are trying to show that for all continuous linear functions $f: l^1 \to \mathbb{R}$ there exists a vector in $\textbf{a} \in l^1$ so that $f(\textbf{v})=\langle\textbf{a}, \textbf{v} \rangle$ for all $\textbf{v} \in l^1$.
Okay, so first of all, I need to show taht $f$ is bounded:
lemma: we show that if $f$ is a continuous linear function $l^1 \to \mathbb{R}$, it is bounded.
Let $\epsilon=1$. Then there exists $\delta>0$ so that $||\textbf{v}||_1< \delta \implies ||f(\textbf{v})||_2 \leq 1$.
Assume $\textbf{v}$ is non trivial. but then $$||\frac{\delta \textbf{v}}{||\vec{v}||_1}||_1=\delta$$ so by linearity we obtain that
$$||\frac{\delta f(\textbf{v})}{||\textbf{v}||}||_2 \leq 1 \implies ||f(\textbf{v})||_2 \leq \frac{1}{\delta} ||\vec{v}||.$$
q.e.d
Okay, so from here, I'm having trouble explicitly expressing the desired vector $\textbf{a}$. I know that if $f$ is a trivial linear function, then we are done, since we just choose the zero vector. Any hints would be appreciated.
Side note: do these results generalize? I haven't used anything about $l^1$ or $\mathbb{R}$ in particular so far (or have I w.o realizing it?)

A: This is not any different from the finite-dimensional case.
Let $\mathbf{e}_n$ be the sequence whose components are all zeros except the $n$th component being $1$. Then $\mathbf{v} = \sum_n v_n \mathbf{e}_n$. Can you use this to write $f(\mathbf{v})$ in a different form? Does this suggest what the $a_n$ are? Once you have this, proving the rest (e.g., boundedness) should not be difficult.


text:
Q: Google charts getting custom tooltips to work with an animation Well this is my code, it's broken.  I want to have absolute figures appear on mouse over, instead of percentages.  Google's guides do not have an example of this with an animation, their examples use data table methods rather than arrays.  I think I need to somehow tell Google that I have a third column which is a tooltip, at present it draws it as a bar.
     google.load("visualization", "1", {
   packages: ["corechart"]
 });
 google.setOnLoadCallback(init);

 function init() {
   var rowData1 = [
     ['key', 'Percentage', 'tooltip'],
     ['PLUS', 20.9, 3855],
     ['EDU', 18.4, 3400],
     ['GEO', 15.6, 2872],
     ['NO FLAG', 45.2, 8342]
   ];
   var rowData2 = [
     ['key', 'Percentage', 'tooltip'],
     ['PLUS', 54.2, 974],
     ['EDU', 6.7, 120],
     ['GEO', 39.2, 704],
     ['NO FLAG', 0.0, 0]
   ];

   // Create and populate the data tables.
   var data = [];
   data[0] = google.visualization.arrayToDataTable(rowData1);
   data[1] = google.visualization.arrayToDataTable(rowData2);

   var options = {
     // removes the key
     legend: {
       position: 'none'
     },
     // puts popup boxes on bar

     width: 600,
     height: 300,
     vAxis: {
       title: "vertical axis"
     },
     hAxis: {
       title: "horizontal axis"
     },
     seriesType: "bars",
     series: {
       5: {
         type: "line"
       }
     },
     animation: {
       duration: 1000,
       easing: 'out'
     },
   };
   var current = 0;
   // Create and draw the visualization.

   var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
   var button = document.getElementById('b1');

   function drawChart() {
     // Disabling the button while the chart is drawing.
     button.disabled = true;
     google.visualization.events.addListener(chart, 'ready',
       function() {
         button.disabled = false;
         button.value = 'Switch to ' + (current ? 'Tea' : 'Coffee');
       });
     options['title'] = 'Monthly ' + (current ? 'Coffee' : 'Tea') + ' Production by Country';
     // custom popup box request

     chart.draw(data[current], options);
   }
   drawChart();

   button.onclick = function() {
     current = 1 - current;
     drawChart();
   }
 }

I've tried converting the array data to DataTables and using
     if (current == 0) { chart.draw(dataTable1, options); }
     else{ chart.draw(dataTable2, options); }

To select which chart to draw, but this isn't working.  And it's less intelligible and inelegant, the dataTables need lots of properties set, so repetition.

A: need to define tooltip column with object notation...
var rowData1 = [
  ['key', 'Percentage', {role: 'tooltip'}],
  ['PLUS', 20.9, 3855],
  ['EDU', 18.4, 3400],
  ['GEO', 15.6, 2872],
  ['NO FLAG', 45.2, 8342]
];
var rowData2 = [
  ['key', 'Percentage', {role: 'tooltip'}],
  ['PLUS', 54.2, 974],
  ['EDU', 6.7, 120],
  ['GEO', 39.2, 704],
  ['NO FLAG', 0.0, 0]
];

A: Change google visualization Combo Chart series option as below:
series: {
       0: {
         type: "line"
       }
    }

Every data table column is considered as one series in google visualization Combo Chart.
Here
"Percentage" is line series no is 0
"tooltip" is bar series no is 1
Nothing wrong with google visualization Combo Chart.
After above change you will get below output:


text:
Q: Run Github application on Windows I don't know how to make use of this application from GitHub. Or in other words, how to make use of it on Windows.
It is a Opensource Application that helps to convert Infobase files.
https://github.com/imazen/folioxml
I am using Windows 10

A: The build server for this project has been migrated and gone offline so you cannot download a complete and compiled application jar.
If you are not familiar with code, then the easy answer is that you need to find someone who has compiled the jar file and has a link for you to download it (Be careful who you trust though), or try and contact the original author with the provided email address, but don't hold your breath for a 6y old project. I suggest looking for an alternate application/project.

The longer/better answer:
Github is simply a location to share the projects source code. The home page has all the details you need on how to run the application: https://github.com/imazen/folioxml
Specifically, see the section about running the command line app:
mvn clean compile assembly:single -U -B -fae
java -jar commandline/target/folioxml-commandline-jar-with-dependencies.jar -config core/folioxml/resources/test.yaml -export folio_help

To complete the above you would first download a copy of the source code and unzip it, or you could clone it using the github command line tools.
Then you would use the maven console to run the clean and compile command:
mvn clean compile assembly:single -U -B -fae

If there are any code issues you would need to fix them, and resolve any dependency issues. Once it has been compiled you can configure the YAML file as shown in the Yaml configuration reference section.
Lastly, you can launch the application using the java command, although you will need to alter the command to point to the actual location of the compiled file, and the location of the YAML file. The example given is:
java -jar commandline/target/folioxml-commandline-jar-with-dependencies.jar -config core/folioxml/resources/test.yaml -export folio_help