text:
Q: woocommerce cart coupon price without tax to display I want woocommerce to display price in cart without tax, reduced by using a coupon.
I want to have:

*

*price without tax

*coupon value

*price without tax reduced by coupon

*tax

*price with tax

Can anybody help me please?
I was trying to play wit this code:
add_action( 'woocommerce_cart_calculate_fees','new_customers_discount', 10, 1 );
function new_customers_discount( $wc_cart ) {
    if ( is_admin() && ! defined('DOING_AJAX') ) // We exit

// Only for logged in users
if ($woocommerce->cart->applied_coupons)  // We exit

// Only for new customers without orders
if ( wc_get_customer_order_count( get_current_user_id() ) != 10000 ) return;  // We exit

// Calculation
$discount = $wc_cart->cart_contents_total - $coupon ;

$wc_cart->add_fee( __( 'Netto po rabacie', 'woocommerce')."", $discount);
echo '

' . $wc_cart->add_fee( __( 'TEST', 'woocommerce')."", -$discount ) . ' zł netto

';

but no luck. I am not a programmer. :)

A: I got it, but i want to change the order. I want to move the nett price on top of VAT
add_action( 'woocommerce_cart_totals_before_order_total', 'bbloomer_wc_discount_total_30', 10, 1 );
add_action( 'woocommerce_review_order_before_order_total', 'bbloomer_wc_discount_total_30', 10, 1 );
function bbloomer_wc_discount_total_30() {

global $woocommerce;

$discount_total = 0;

foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values) {

$_product = $values['data'];

    if ( $_product->get_regular_price() ) {
    $regular_price = $_product->get_regular_price();
    $sale_price = $_product->get_sale_price();
    $discount = ($regular_price - $coupon) ;
    $discount_total += $discount;
    }

}

if ( $discount_total > 0 ) {
echo '

'. __( 'Razem netto', 'woocommerce' ) .'
'
. wc_price( $discount_total - $woocommerce->cart->discount_cart ) .'

';
}

}


text:
Q: R no longer accepting timezones in the format GMT+n/GMT-n ?timezones states "Most platforms support time zones of the form GMT+n and GMT-n, which assume at a fixed offset from UTC (hence no DST)."
I have old code from earlier this year where I use tz="GMT-8". Only changes to my computer have been updating to R version "R version 3.2.2 (2015-08-14)" and migrating my library from an old user account by adding a line of code to my Rprofile located in "C:\Program Files\R\R-3.2.2\library\base\R". Just to be detailed code was .libPaths(c("C:/Users/XXXX XXXX/Documents/R/win-library/3.2",.Library.site)). Why might my system suddenly not accept this tz format? What system setting can I change to resolve this?
Working example below.
tdat<-c("11/19/2014 12:45", "11/19/2014 13:00", "11/19/2014 13:15",
"11/19/2014 13:30", "11/19/2014 13:45", "11/19/2014 14:00", "11/19/2014 14:15",
"11/19/2014 14:30", "11/19/2014 14:45", "11/19/2014 15:00")

as.POSIXct(strptime(tdat,"%m/%d/%Y %H:%M",tz="GMT-8"))

Warning messages:
1: In strptime(tdat, "%m/%d/%Y %H:%M", tz = "GMT-8") :
  unknown timezone 'GMT-8'
2: In as.POSIXct.POSIXlt(strptime(tdat, "%m/%d/%Y %H:%M", tz = "GMT-8")) :
  unknown timezone 'GMT-8'
3: In as.POSIXlt.POSIXct(x, tz) : unknown timezone 'GMT-8'

A: If your platform is using the standard tzdb time zones, then you can indeed specify fixed whole-hour zones in the form: Etc/GMT+8.
However, be aware:

*

*The sign is inverted from what you probably expect.  Etc/GMT-8 is in China.  Etc/GMT+8 is in America.

*There are plenty of real world time zones that use half-hour or 45-minute offsets, which cannot be represented in this form.

*This does not account for daylight saving time, or other historical changes in time zones.
Therefore, the better idea is to use named time zones, as found here.
For example, for US Pacific Time, use America/Los_Angeles, as it correctly accounts for daylight saving time, alternating between UTC-8 and UTC-7 .

redpajama_set_name: RedPajamaStackExchange


text:
Q: Invite Facebook friends? I would like to add a function to let the possibility to users to invite their Facebook friends.
My problem is that there is no documentation (https://developers.facebook.com/docs/app-invites/ios)
The website is down and I don't have any information. Is it still possible to do that in an app?


text:
Q: Error al instalar Android SDK en Macbook M1 Reciente instalando Android estudio en la parte de la descarga de los paquetes, me salió el siguiente error, alguna solución?
An error occurred while trying to compute required packages.

A: Investigando encontre esta respuesta Link de la respuesta
Basicamente nos descargamos IntelliJ IDEA Community:
Link de descarga
Creamos un nuevo proyecto

Damos click en instalar SDK

Siguiente, Siguiente, Siguiente

Una vez terminado, abrimos android studio y empezará a descargar los componentes

Listo, android funcionando.


text:
Q: Changing "key" and "values" into "name" and "children" using nest() UPDATE:
 Solved thanks To @AmeliaBR, that answered my specific question here  after I asked it.

*

*This fiddle shows the adaptation of the solution to my specific problem.

My question was:

*

*I'm looking for something like this without changing the structure of the functions I want to use.

*This works great if you have defined parents inside the structure, but I can't get access to it.
What I ideally would do is to also do it work efficiently, and I think that in order to do so nest() might be a good answer.
I want to change
"key": "keyname", "values":"a value"

into
"name": "keyname", "children":"a value"

And in the leaf node change (if possible making the rest of useless data dissapear)
 "value": "a value"

into
"size": "a value"

I got a bit sad when I read this:
"I don't see any other method than going trough all elements recursively and changing names, which requires copying and deleting each field. However you can always use the source code of nest() as inspiration."
Can you beat that guy with your knowledge?


text:
Q: Определенное слово + цифра php регулярка $dannie = "Длина: 100 м
Длина 100 метров
Длина 100м";

Нужна регулярка которая будет находить определенное слово (в данном случае длина), и получать цифру идущую за ней, и на этом поиск прекращала, а не шла дальше и цепляла все остальные цифры. Почему то так не срабатывает. Почему не могу понять:
$str = preg_match_all("/([Длина:]+\d)/ui", $dannie, $out);
echo $dlina_result = implode(', ', $out[0]);

Пример: http://sandbox.onlinephpfunctions.com/code/b4efb8e5baba773d4c88e175d9ec8b105a5cd05d

A: Используйте
$dannie = "Длина: 100 м
Длина 100 метров
Длина 100м";
if (preg_match_all('~Длина:\s*\K\d+(?:[.,]\d+)?~u', $dannie, $matches)) {
    echo implode(', ', $matches[0]);
}

Пример работы кода онлайн. См. также демо регулярного выражения.
Подробности

*

*Длина: - буквальный текст

*\s* - 0 и более пробельных символов

*\K - оператор, удаляющий весь найденный текст из текущего совпадения

*\d+ - 1 и более цифр

*(?:[.,]\d+)? - 1 или 0 повторов последовательности:

*

*[.,]  - точка или запятая

*\d+ - 1 и более цифр

A: Если я правильно понял, что двоеточие относится к маске и число отделено пробелами, то так:
preg_match_all("/(?<=Длина:)\s*(\d+)/ui", $dannie, $out);
echo $out[0][0];

A: Регулярка длина\D*(\d+)/i, брать первую группу:

var s = `Длина: 100 м
Длина 100 метров
Длина 100м`

console.log(s.match(/длина\D*(\d+)/i)[1])


text:
Q: Using Entity Framework 6 to delete from a junction table but leave the record in the lookup table I have 2 tables, 1 main table, 1 junction table and 1 lookup table. It's a 1-to-many-to-1 relationship. I'm looking for a way to delete all the entries from the junction table only, without removing the lookup value.
An example of my tables are below
Record table

*

*id

*name

Junction table

*

*recordid

*lookupid

Lookups table

*

*lookupid

*lookupname

Currently I'm passing in an updated model and I'm trying to delete all the junction records before reading the new chosen values. So far everything I've tried deletes out the record from the lookup table as well.
 foreach (var lookup in recordFromDB.Lookups.ToList()) {
     _context.Lookups.Remove(DesignSoftware);
 }

A: Try this - just using the .Clear() method on the navigation property should remove any navigation (a.k.a. "junction") entries - but not the actual Lookups entries:
recordFromDB.Lookups.Clear();
YourContext.SaveChanges();


text:
Q: Unity 2019.3.0f1 one sided meshes with baked lightmap dark I am using unity 2019.3.0f1, with HDRP. I have made a simple room mesh, that has only one sided walls, facing inwards. Turning the room static, having it generate lightmap uv, and setting the light static makes it completely black, when scene lightning is used. I've attached some images. I tried turning backface tolerance to 0, but it did not help.
Without lights (scene lightning not used)
With lights (scene lightning used).
Any help is appreciated :).

A: So my original answer was untrue, unfortunately. Turns out, when I created the mask, I've set green to 0, setting ambient occlusion to 0. Because of this, it handled everything occluded (from ambience). Setting ambient occlusion to 1 manually (and adding full green on every mask afterwards) fixes the issue.


text:
Q: Attachments using C# to Sharepoint I have been trying to add new list items with attachments to my list .
The list items are added fine, however I cannot figure out how to attach files to those items
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ConsoleApplication3.TestReference;
using System.IO;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            MVSDataContext dc = new MVSDataContext(
                new Uri("https:xxx_vti_bin/ListData.svc"));
            dc.Credentials = System.Net.CredentialCache.DefaultCredentials;

            TestListItem newItem = new TestListItem { Title = "test6" };
            dc.AddToTestList(newItem);
            dc.SaveChanges();

            /* up to this point everything works fine and i am able to add a new list item */

            FileStream fStream = File.OpenRead("C:\\xxxxx.xlsx");
            string fileName = fStream.Name.Substring(3);
            byte[] contents = new byte[fStream.Length];
            fStream.Read(contents, 0, (int)fStream.Length);
            fStream.Close();

            /* the file read  successfuly . Now I should use `contents` to upload the file */

            newItem.Attachments.Add(fStream.Name, contents); /* This line does not compile */

            dc.SaveChanges();

            }
        }
    }
}

I also tried approach from here
DirectoryInfo  attachmentDirectory = new DirectoryInfo(@"C:\xxx");
            FileInfo[] attachments = attachmentDirectory.GetFiles();
            foreach (FileInfo attachment in attachments)
            {
                FileStream fs = new FileStream(attachment.FullName, FileMode.Open, FileAccess.Read);

                // Create a byte array of file stream length
                byte[] ImageData = new byte[fs.Length];

                //Read block of bytes from stream into the byte array
                fs.Read(ImageData, 0, System.Convert.ToInt32(fs.Length));

                //Close the File Stream
                fs.Close();

                newItem.Attachments.Add(attachment.Name, ImageData);

            }

However got the same error
How can I make an attachment to a list item ?

Here is the TestListItem class
      //------------------------------------------------------------------------------
    // <auto-generated>
    //     This code was generated by a tool.
    //     Runtime Version:4.0.30319.18052
    //
    //     Changes to this file may cause incorrect behavior and will be lost if
    //     the code is regenerated.
    // </auto-generated>
    //------------------------------------------------------------------------------

    // Original file name:
    // Generation date: 1/30/2014 11:00:30 AM
    namespace ConsoleApplication3.TestReference
    {

        /// <summary>
        /// There are no comments for MVSDataContext in the schema.
        /// </summary>
        public partial

 class MVSDataContext : global::System.Data.Services.Client.DataServiceContext
    {
        /// <summary>
        /// Initialize a new MVSDataContext object.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        public MVSDataContext(global::System.Uri serviceRoot) :
                base(serviceRoot)
        {
            this.ResolveName = new global::System.Func<global::System.Type, string>(this.ResolveNameFromType);
            this.ResolveType = new global::System.Func<string, global::System.Type>(this.ResolveTypeFromName);
            this.OnContextCreated();
        }
        partial void OnContextCreated();
        /// <summary>
        /// Since the namespace configured for this service reference
        /// in Visual Studio is different from the one indicated in the
        /// server schema, use type-mappers to map between the two.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        protected global::System.Type ResolveTypeFromName(string typeName)
        {
            if (typeName.StartsWith("Microsoft.SharePoint.DataService", global::System.StringComparison.Ordinal))
            {
                return this.GetType().Assembly.GetType(string.Concat("ConsoleApplication3.TestReference", typeName.Substring(32)), false);
            }
            return null;
        }
        /// <summary>
        /// Since the namespace configured for this service reference
        /// in Visual Studio is different from the one indicated in the
        /// server schema, use type-mappers to map between the two.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        protected string ResolveNameFromType(global::System.Type clientType)
        {
            if (clientType.Namespace.Equals("ConsoleApplication3.TestReference", global::System.StringComparison.Ordinal))
            {
                return string.Concat("Microsoft.SharePoint.DataService.", clientType.Name);
            }
            return null;
        }
        /// <summary>
        /// There are no comments for Attachments in the schema.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        public global::System.Data.Services.Client.DataServiceQuery<AttachmentsItem> Attachments
        {
            get
            {
                if ((this._Attachments == null))
                {
                    this._Attachments = base.CreateQuery<AttachmentsItem>("Attachments");
                }
                return this._Attachments;
            }
        }
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        private global::System.Data.Services.Client.DataServiceQuery<AttachmentsItem> _Attachments;
        /// <summary>
        /// There are no comments for MasterPageGallery in the schema.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        public global::System.Data.Services.Client.DataServiceQuery<MasterPageGalleryItem> MasterPageGallery
        {
            get
            {
                if ((this._MasterPageGallery == null))
                {
                    this._MasterPageGallery = base.CreateQuery<MasterPageGalleryItem>("MasterPageGallery");
                }
                return this._MasterPageGallery;
            }
        }
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        private global::System.Data.Services.Client.DataServiceQuery<MasterPageGalleryItem> _MasterPageGallery;
        /// <summary>
        /// There are no comments for MasterPageGalleryCompatibleUIVersionS in the schema.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        public global::System.Data.Services.Client.DataServiceQuery<MasterPageGalleryCompatibleUIVersionSValue> MasterPageGalleryCompatibleUIVersionS
        {
            get
            {
                if ((this._MasterPageGalleryCompatibleUIVersionS == null))
                {
                    this._MasterPageGalleryCompatibleUIVersionS = base.CreateQuery<MasterPageGalleryCompatibleUIVersionSValue>("MasterPageGalleryCompatibleUIVersionS");
                }
                return this._MasterPageGalleryCompatibleUIVersionS;
            }
        }
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        private global::System.Data.Services.Client.DataServiceQuery<MasterPageGalleryCompatibleUIVersionSValue> _MasterPageGalleryCompatibleUIVersionS;
        /// <summary>
        /// There are no comments for TestList in the schema.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        public global::System.Data.Services.Client.DataServiceQuery<TestListItem> TestList
        {
            get
            {
                if ((this._TestList == null))
                {
                    this._TestList = base.CreateQuery<TestListItem>("TestList");
                }
                return this._TestList;
            }
        }
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        private global::System.Data.Services.Client.DataServiceQuery<TestListItem> _TestList;
        /// <summary>
        /// There are no comments for UserInformationList in the schema.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        public global::System.Data.Services.Client.DataServiceQuery<UserInformationListItem> UserInformationList
        {
            get
            {
                if ((this._UserInformationList == null))
                {
                    this._UserInformationList = base.CreateQuery<UserInformationListItem>("UserInformationList");
                }
                return this._UserInformationList;
            }
        }
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        private global::System.Data.Services.Client.DataServiceQuery<UserInformationListItem> _UserInformationList;
        /// <summary>
        /// There are no comments for Attachments in the schema.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        public void AddToAttachments(AttachmentsItem attachmentsItem)
        {
            base.AddObject("Attachments", attachmentsItem);
        }
        /// <summary>
        /// There are no comments for MasterPageGallery in the schema.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        public void AddToMasterPageGallery(MasterPageGalleryItem masterPageGalleryItem)
        {
            base.AddObject("MasterPageGallery", masterPageGalleryItem);
        }
        /// <summary>
        /// There are no comments for MasterPageGalleryCompatibleUIVersionS in the schema.
        /// </summary>
        [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Data.Services.Design", "1.0.0")]
        public void AddToMasterPageGalleryCompatibleUIVersionS(MasterPageGalleryCompatibleUIVersionSValue masterPageGalleryCompatibleUIVersionSValue)
        {
            base.AddObject("MasterPageGalleryCompatibleUIVersionS", masterPageGalleryCompatibleUIVersionSValue);
        }
        /// <summary>
        /// There are no comments for TestList in the schema.
        /// </summary>
..............

A: Have you got the code for TestListItem? It looks pretty clearly like Add requires 2 arguments to be passed into it.
You need to add the byte stream for the file you want to add - see here
    foreach (FileInfo attachment in attachments)
    {
        FileStream fs = new FileStream(attachment.FullName , FileMode.Open,FileAccess.Read);

        // Create a byte array of file stream length
        byte[] ImageData = new byte[fs.Length];

        //Read block of bytes from stream into the byte array
        fs.Read(ImageData,0,System.Convert.ToInt32(fs.Length));

        //Close the File Stream
        fs.Close();

        item.Attachments.Add(attachment.Name, ImageData);

    }

A: Call the Method AddQueryOption instead of Add:
        newItem.Attachments.Add(fStream.Name, contents); /* This line does not compile */

        newItem.Attachments.AddQueryOption(fStream.Name, contents); /* This line does compile */

A: Hope this helps other users.
The problem here is that the SharePoint Client Object Model does not create the item's sub-folder under the Attachments folder.
To solve this you should use the "/_vti_bin/lists.asmx" web service by adding a Web Service Reference, please follow this link  in case you need indications to achieve it.
using FR.WssODataCore.ListsWebService;
Once you added the reference to your service you can just use this code snippet:
var listsServiceClient = new Lists
{
    Credentials = defaultContext.Credentials,
    Url = siteCollectionUrl + "/_vti_bin/lists.asmx"
};
listsServiceClient.AddAttachment(currentListName, listItemId, fileName, fileContent);

Where siteCollectionUrl is your service's url like http://yourSite.ext/webName, and defaultContext is an instance of Microsoft.SharePoint.Client which I've used to complete other actions.
Please, note that you need a reference to your web service reference that contains the Lists object
using MyServiceNameSpace.ListsWebService;

In this way, I was able to use both the ListData.svc and Lists.asmx endpoints by combining the operations, using the .asmx service only to upload the attachment.
Here another good resource.


text:
Q: Absolute maximum for $f(x,y) = 4x^2 + 5y$ Suppose you have a region $R$ that satisfies $4x^2+y^2\leq 4$ What is the absolute maximum of the function $f(x,y) = 4x^2 + 5y$ on $R$?
The correct answer is $10$
First, I calculated the critical points in $R$:
$$f_x = 8x$$
$$8x= 0$$
$$x=0$$
$$f_y = 5$$
$$5 \ne  0$$
Given the fact that there are no points where both $f_x$ and $f_y$ equal $0$, doesn't that mean there are no critical points in $R$, indicating no maximum value? I don't know if I have to check the boundary in this case, since the region is circular? I am not allowed to use Lagrange Multipliers.
Any insight into how to solve these types of problems would help.

A: The function $f(x)=x$ also has an absolute maximum on $[-1,1]$, even though there is no point at which $f'(x)=0$.
Remember, the zeroes of the partial derivatives only give you candidates for the critical points in the interior of the domain of $f$. On the border (where a maximum can also be reached sometimes), you can use Lagrange multipliers to calculate the max.
Alternatively, your particular function is fairly simple, so you can do without Lagrange. You have, on the border, $4x^2+y^2=4$, which means you can express $x^2$ as a funciton of $y$, and insert that into $f(x,y)$ to get a function of only $y$, and you can calculate the maximum of $f$ on the border quite easily.

A: When the function is defined by a simple expression ad-hoc methods are recommended. You can find the maximum  without using any theorems. $f(x,y) \leq 5y+4-y^{2}$ and $y$ is subject to the condition $-2\leq y \leq 2$. This gives $f(x,y)\leq 10$ and this value is attained when $x=0,y=2$.

A: You proved that there are no critical points in the interior of $R$. In order to see what happens at the boundary of $R$, you can use the method of Lagrange multipliers, which leads you to the system:$$\left\{\begin{array}{l}8x=8\lambda x\\5=8\lambda y\\4x^2+y^2=4.\end{array}\right.$$Otherwise, you can reduce this to a $1$-dimensional problem: find the maximum of$$(4\cos\theta)^2+5\times4\sin\theta,$$with $\theta\in[0,2\pi]$. It is perhaps better to keep in mind that $\cos^2\theta+\sin^2\theta=1$.

A: We have: $4x^2 + 5y \le 4-y^2+5y =10 -y^2+5y-6=10 -(y-2)(y-3)\le 10$ since $y \le 2$.


text:
Q: change title of a modal window how can I change the title of a modal window open through the command using?
ExecuteOrDelayUntilScriptLoaded(function () { openModalWindow('.....')},\"sp.js\");

I would like the person to see: loading ...
and at the end of the loading to then show the true title of the page.

This solution sets the title of the modal window, I would like to change the title after the window has been opened.

A: Hi you can find the same question here:
Pass parameters in ExecuteOrDelayuntilScriptLoaded in Javascript client Object model
To make changes to the title like so in JavaScript:
var win = window.open();

win.document.title="......Change Me......";

A: I don't know how you plan on loading your modal dialog, but usually you can just do as below:
var options = SP.UI.$create_DialogOptions();
options.url = "url to the page";
options.title = "Modal Dialog Title Here";

SP.UI.ModalDialog.showModalDialog(options);

Which then would make yours look something like this:
var options = SP.UI.$create_DialogOptions();
options.url = "url to the page";
options.title = "Modal Dialog Title Here";

ExecuteOrDelayUntilScriptLoaded(function () { SP.UI.ModalDialog.showModalDialog(options);},"sp.js");

A: Simonw pass the title like so:
<a href="#" onclick="openDialog('Test.aspx?ID={@ID}','{$title}'); return true "/>

<script type="text/javascript">
function openDialog(FormPath,Title) {
    var options = {
        url: FormPath,
        width: 950,
        height: 800,
        title: Title,
        allowMaximize:'true'

    };
    SP.UI.ModalDialog.showModalDialog(options);
}
</script>

Hope this helps


text:
Q: Building a Java EE app on Mac OS X Snow Leopard for Glassfish 3 I'm having a bit of a problem building a Java Enterprise Edition web application on Mac OS X 10.6.2 using Ant 1.7.1, Glassfish v3 and Java EE 6.
The problem is that the build process does not find the Java EE libraries which fair enough as I don't think Apple supply them with the default Java installation but I know they exist in the Glassfish distribution.
Which jars are the correct ones to build against (I'm assuming javaee.jar is a general jar which references all the other needed jars) and what should I be putting in my ant build.xml file?
Any help is very much appreciated.

A: You need to have the javaee.jar in your ant classpath, but be aware: do not copy the javaee.jar to the webapp (WEB-INF/lib folder)!

A: I would encourage you to get and use NetBeans or GlassFish Tools Bundle For Eclipse to start working with Java EE 6 and GlassFish v3... (read my profile to find out why).
If you are determined to avoid using either of these IDEs, then I would recommend that you download the Java EE 6 SDK, to get started.  The SDK includes a number of different samples that can be built and deployed using Ant.  (Use -verbose to learn the 'secrets')


text:
Q: Match attributes (with spatial join) weighted by length of line feature in polygon in ArcGIS I have line features (streets) and polygons (air quality raster). I need to transfer the air quality attributes into the lines. However, some lines are part of two or more polygons (e.g. the selected feature below).

I am looking for a way to transfer the attributes of the polygons onto the lines weighted by the length of the part of a line feature within each polygon.
The tool Spatial join only allows for a simple average in its merge rules (mean) giving equal weights for both parts of the selected line in the picture above.
An alternative idea was to split line features at intersections with polygon boundaries and have the air quality attributes assigned to the two or more new features. In a second step, I could then unsplit those split features using an ID. Lastly, I could use the field calculator to calculate a new weighted average air quality field, like:
Air Quality = (Shape_Length A * Air Quality A) + (Shape_Length B * Air Quality B)/(Shape_Length A + Shape_Length B)
I am using ArcGIS Desktop 10.5.


text:
Q: how to load modal when click a link without refresh I have index page with some  modal box.
these modal cause page become  very untidy and bad effect when page loaded.
Now this is my question,how can i load that modal when click that link without refresh,i do not have any modal in index page at first,by click i include that modal?
I use laravel 4 framework,some guys say it is possible by event in laravel,is it?


text:
Q: Retrieve Identity Verification Image for Recipient Our business has a requirement to retrieve and store an image of the recipient's ID (government issued or passport) after envelope completion. I've been unable to locate any API methods that allow us to do that.
Is there anyway to do this using the C# SDK/API? If you can't do it via the API, what is the easiest way to manually do this?

A: You can use the ID Evidence API to do this.
Here is the developer endpont to call:
https://proof-d.docusign.net/api/v1.0/events/{entityType}/{entityId}/{eventId}/media/{mediaId}

You can also follow the How to retrieve ID Evidence media articl.e


text:
Q: is there an example of a canvasJS graph where each point on a graph has a tick and label on the X axis? I cannot seem to find an example where every single point in a set of data had its own tick and label on a graph. when I load in my data, CanvasJS gives me intervals as my x axis. the actual points are placed inbetween these intervals. If i add more data, the intervals dont change. I am looking for an example of how to make it so each point is represented.
I would also like the xaxis to look as identical to this formatting as possible

I have read some documentation here but I am struggling to make it work for me. My X axis values look like this: 119604384477647324 but are in Miliseconds.
any help would be appreciated. I have a presentation soon and I am hard stuck. thank you!

A: Passing label instead of x-value in datapoint seems to work fine.

var chart = new CanvasJS.Chart("chartContainer", {
      title: {
        text: "Custom Labels on X Axis "
      },
      data: [{
        type: "column",
        dataPoints: [
        { y: 71, label: "cat 1"},
        { y: 55, label: "cat 2"},
        { y: 50, label: "cat 3"},
        { y: 65, label: "cat 4"},
        { y: 95, label: "cat 5"},
        { y: 68, label: "cat 6"},
        { y: 28, label: "cat 7"},
        { y: 34, label: "cat 8"},
        { y: 14, label: "cat 9"}
        ]
     }]
});

chart.render();
<script type="text/javascript" src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 300px; width: 100%;">


text:
Q: What I did wrong in finding the radius of convergence for this problem? I'm asked to find the radius of convergence for summation from n = 1 to $\infty$ of $\sum n!x^n/(4n^n)$. I used the ratio test because of the factorial, and I eventually got a whole bunch of cancellations that just left me with $|x|$, and so if $|x| < 1$, $R=1$, but this answer is apparently wrong. I redid the problem a couple times very slowly, but I kept getting the same answer. Did I make a mistake somewhere, or am I using the wrong approach?
Edit: here is my approach
$$\lim\left|\frac{(n+1)n!x^nx}{4(n+1)^n(n+1)} \frac{4n^n}{n!x^n}\right|$$
The (n+1) terms cancel, the n! terms cancel, the 4's cancel, the n^n's cancel, the x^n terms cancel, leaving |x|

A: I'm not sure what you did where you wrote "here is my approach" (though I think there are several mistakes...), but it seems to be pretty direct:
$$a_n:=\frac{n!}{4n^n}\implies\frac{a_{n+1}}{a_n}=\frac{(n+1)!}{4(n+1)^{n+1}}\cdot\frac{4n^n}{n!}=\frac{n^n}{(n+1)^n}=\frac1{\left(1+\frac1n\right)^n}\xrightarrow[n\to\infty]{}\frac1e$$
and thus the convergence radis is $\;R=e\;$ and we have convergence for
$$\frac{|x|}e<1\iff |x|<e\iff -e<x<e$$

A: It's actually not hard to show that $(n+1)^n\geq 2n^n$ for $n\geq 1$.
The first two terms of $(n+1)^k$ are $n^k + k\cdot n^{k-1}$. So $(n+1)^k\geq n^k+k\cdot n^{k-1}$ when $n\geq 0$ and $k\geq 1$.
When $k=n$, then $(n+1)^n\geq n^n+n\cdot n^{n-1}=2n^n$.
This in turn means that $\left(\frac{n}{n+1}\right)^n\leq \frac{1}{2}$ for all $n\geq 1$. In particular, the limit cannot be $1$, so you cannot "cancel" $n^n$ and $(n+1)^n$.
In fact, $$\left(\frac{n}{n+1}\right)^n\to e^{-1}.$$


text:
Q: Run a Powershell command as an Administrator - Commands themself won't load using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Diagnostics;

namespace WindowsFormsApplication
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            var newProcessInfo = new System.Diagnostics.ProcessStartInfo();
            newProcessInfo.FileName = @"C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe";
            newProcessInfo.Verb = "runas";
            System.Diagnostics.Process.Start(newProcessInfo);
            newProcessInfo.Arguments = @"sfc /scannow";
        }
    }
}

So my code works up to a point.  you click the windows form application button and it will run windows Powershell in 64bit as an administrator but won't run a .ps1 script "c:\path\script.ps1" or the command directly written out like the "sfc /scannow" above.
I was reading that the powershell commands won't work sometimes if the "Set-ExecutionPolicy Unrestricted" isn't loaded somewhere in the beginning of the code.
Please help!  I have been looking everywhere for an answer.

A: First of all, you need to specify the Arguments property before you start the process:
var newProcessInfo = new System.Diagnostics.ProcessStartInfo();
newProcessInfo.FileName = @"C:\Windows\SysWOW64\WindowsPowerShell\v1.0\powershell.exe";
newProcessInfo.Verb = "runas";
newProcessInfo.Arguments = @"sfc /scannow";
System.Diagnostics.Process.Start(newProcessInfo);

Second, you'll need to tell PowerShell that sfc /scannow is a command, and not command line switches.
On the command line you would do powershell.exe -Command "sfc /scannow", so the correct Arguments value in your case would be
newProcessInfo.Arguments = @"-Command ""sfc /scannow""";

("" is the escape sequence for " in verbatim string literals)
For .ps1 files, use the -File switch:
newProcessInfo.Arguments = @"-File ""C:\my\script.ps1""";

If you don't know the execution policy on the target system, you can bypass it without affecting the machine-wide policy with -ExecutionPolicy Bypass:
newProcessInfo.Arguments = @"–ExecutionPolicy Bypass -File ""C:\my\script.ps1""";


text:
Q: Optional.ofNullable doesn't seem to work if my inner objects are null? I have a nested class structure that I use to deserialize my data:
Class A has a single property that is an object of Class B (say b)
Class B has a single property that is an object of Class C (say c)
Class C has a single property that is an object of Class D (say d)
Class D has a single property that is a a string (say e)

I have data that looks like
Map<String, List<Map<String, Map<String, Map<String, Map<String, String>>>>>> input =
                ImmutableMap.of("Key",
                        ImmutableList.of(ImmutableMap.of("a",
                                ImmutableMap.of("b",
                                        ImmutableMap.of("c",
                                                ImmutableMap.of("d", "e"))))));

I want to parse this multilevel map and put the result into a map
Map<String, String> result = new HashMap<>();

At the end, I expect result map to contain this at the end: ["key", "e"]
I have this code that works if the map contain all the intermediate keys a, b, c and d
mapping.entrySet()
            .stream()
            .map(l -> l.getValue().stream()
                    .map(Optional::ofNullable)
                    .map(opta -> opta.map(A::getB))
                    .map(optb -> optb.map(B::getC))
                    .map(optc -> optc.map(C::getD))
                    .map(optd -> optd.map(D::getE))
                    .map(optv -> optv.orElse("default"))
                    .map(m -> result.put(l.getKey(), m))
                    .count())
            .count();

but for example say if  the input is
Map<String, List<Map<String, Map<String, Map<String, Map<String, String>>>>>> input =
                    ImmutableMap.of("Key",
                        ImmutableList.of(ImmutableMap.of("a",
                                ImmutableMap.of("b",null))));

then my code fails:
java.lang.NullPointerException: null value in entry: b=null

Why is my Optional.isNullable not working?

A: You are using ImmutableMap, and ImmutableMap does not like null key or value: https://guava.dev/releases/23.0/api/docs/com/google/common/collect/ImmutableMap.html#of-K-V-

public static <K,V> ImmutableMap<K,V> of(K k1, V v1)
Returns an immutable map containing a single entry. This map behaves
  and performs comparably to Collections.singletonMap(K, V) but will
  not accept a null key or value. It is preferable mainly for
  consistency and maintainability of your code.

The message is produced by this method: https://github.com/google/guava/blob/82b3e9806dc3422e51ecb9400d8f50404b083dde/guava/src/com/google/common/collect/CollectPreconditions.java#L28
  static void checkEntryNotNull(Object key, Object value) {
    if (key == null) {
      throw new NullPointerException("null key in entry: null=" + value);
    } else if (value == null) {
      throw new NullPointerException("null value in entry: " + key + "=null");
    }
  }

On the other hand, I think you should use specialized rather than map... I'm pretty sure that such kind of type is giving headache to your team or other reader:
Map<String, List<Map<String, Map<String, Map<String, Map<String, String>>>>>>


text:
Q: Use Google Earth Engine to read MODIS NDVI into python I'm trying to adapt this example for my needs: https://mygeoblog.com/2017/10/06/from-gee-to-numpy-to-geotiff/
The difference is that I'm using the MODIS NDVI image collection.
# define the image
img = ee.ImageCollection('MODIS/MCD43A4_006_NDVI').filterDate(date_start, date_end)

median_data = img.median()

# get the lat lon and add the ndvi
latlon = ee.Image.pixelLonLat().addBands(median_data)

# apply reducer to list
latlon = latlon.reduceRegion(
  reducer=ee.Reducer.toList(),
  geometry=area,
  scale=10000);

# get data into three different arrays
data = np.array((ee.Array(latlon.get("NDVI")).getInfo()))
lats = np.array((ee.Array(latlon.get("latitude")).getInfo()))
lons = np.array((ee.Array(latlon.get("longitude")).getInfo()))

I thought I understood the example but my data, lats and lons arrays are coming out different sizes which is obviously incorrect.
In [2]: data.shape
Out[2]: (21005,)

In [3]: lats.shape
Out[3]: (21051,)

In [4]: lons.shape
Out[4]: (21051,)

Any ideas what I'm doing wrong?

A: This works for me:
import ee
import numpy as np

ee.Initialize()

date_start = ee.Date('2004-05-01')
end_date = ee.Date('2004-06-12')

area = ee.FeatureCollection(r'users/bcoerver/gadm36_PSE_0')

# define the image
img = ee.ImageCollection('MODIS/MCD43A4_006_NDVI').filterDate(date_start, end_date)

median_data = img.median()

# get the lat lon and add the ndvi
latlon = ee.Image.pixelLonLat().addBands(median_data)

# apply reducer to list
latlon = latlon.reduceRegion(
  reducer=ee.Reducer.toList(),
  geometry=area,
  scale=100);

# get data into three different arrays
data = np.array((ee.Array(latlon.get("NDVI")).getInfo()))
lats = np.array((ee.Array(latlon.get("latitude")).getInfo()))
lons = np.array((ee.Array(latlon.get("longitude")).getInfo()))

output:
lons.size
Out[17]: 734995

lats.size
Out[18]: 734995

data.size
Out[19]: 734995

But maybe you can specify which dates and area you are using?


text:
Q: Hide drawer navigation header I'm trying to hide Drawer Header on react native application. Currently,using react-navigation ^1.5.12.
* I want to delete grey header
enter image description here
My code look like this.
Router.js
const HomeStack = DrawerNavigator({
  Home: { screen: Home },
  Message: { screen: Message },
  History: { screen: History },
  Settings: { screen: Settings },
}, {
  contentComponent: DrawerMenu,
  drawerWidth: 240,
  // Explicitly set the default screen to use
  initialRouteName: 'Home',
});

export default const MainStack = StackNavigator({
  LoggedInHome: { screen: HomeStack },
  Notification: { screen: Notification },
}, {
  // Explicitly set the default screen to use
  initialRouteName: 'Home',
});

I added header: null on each screen also.
DrawerMenu.js
export default class DrawerMenu extends React.Component {
  static navigationOptions = {
    header: null
  }

  navigateToScreen = (route) => () => {
    const navigateAction = NavigationActions.navigate({
      routeName: route
    });
    this.props.navigation.dispatch(navigateAction);
  }

  render() {
    return (
      <View>
        <TouchableOpacity
          onPress={this.navigateToScreen('Home', { isStatusBarHidden: false })}
        >
          <Text>Home</Text>
        </TouchableOpacity>
...

A: you should try it like this:
  Home: {
navigationOptions: ({ navigation }) => ({
  header: null,
}),

A: You should set the navigation options in your drawer's instantiation :
const HomeStack = DrawerNavigator({
  Home: {
    screen: Home,
    navigationOptions: { header: null }
  },
  ...


text:
Q: Why do C++20 ranges not provide only pipe syntax? I understand that question sounds weird, so here is a bit of context.
Recently I was disappointed to learn that map reduce in C++20 ranges does not work as one would expect i.e.
const double val = data | transform(...) | accumulate (...);

does not work, you must write it this unnatural way:
const double val = accumulate(data | transform(...));

Details can be found here and here, but it boils down to the fact that accumulate can not disambiguate between 2 different usecases.
So this got me thinking:
If C++20 required that you must use pipe for using ranges, aka you can not write
vector<int> v;
sort(v);

but you must write
vector<int> v
v|sort();

would that would solve problem of ambiguity?
And if so although unnatural to people using std::sort and other STL algorithms I wonder if in the long run that would be a better design choice.
Note:
If this question is too vague feel free to vote to close, but I feel that this is a legitimate design question that can be answered in relatively unbiased way, especially if my understanding of the problem is wrong.

A: You need to differentiate between range algorithms and range adaptors. Algorithms are functions that perform a generic operation on a range of values. Adaptors are functions which create range views that modify the presentation of a range. Adaptors are chained by the | operator; algorithms are just regular functions.
Sometimes, the same conceptual thing can have an algorithm and adapter form. transform exists as both an algorithm and an adapter. The former stores the transformation into an output range; the latter creates a view range of the input that lazily computes the transformation as requested.
These are different tasks for different needs and uses.
Also, note that there is no sort adapter in C++20. A sort adapter would have to create a view range that somehow mixed around the elements in the source range. It would have to allocate storage for the new sequence of values (even if it's just sorting iterators/pointers/indices to the values). And the sorting would have to be done at construction time, so there would be no lazy operation taking place.
This is also why accumulate doesn't work that way. It's not a matter of "ambiguity"; it's a matter of the fundamental nature of the operation. Accumulation computes a value from a range; it does not compute a new range from an existing one. That's the work of an algorithm, not an adapter.
Some tasks are useful in algorithm form. Some tasks are useful in adapter form (you find very few zip-like algorithms). Some tasks are useful in both. But because these are two separate concepts for different purposes, they have different ways of invoking them.

A:
would that would solve problem of ambiguity?

Yes.
If there's only one way to write something, that one way must be the only possible interpretation. If an algorithm "call" can only ever be a partial call to the algorithm that must be completed with a | operation with a range on the left hand side, then you'd never even have the question of if the algorithm call is partial or total. It's just always partial.
No ambiguity in that sense.
But if you went that route though, you end up with things like:
auto sum = accumulate("hello"s);

Which doesn't actually sum the chars in that string and actually is placeholder that is waiting on a range to accumulate over with the initial value "hello"s.


text:
Q: How to push a mysql result's fields up to become the property of a class How can I push a mysql result result's fields up to become the property of a class?
For instance, this is my result,
   object(ArticleModel)[4]
      public 'item' =>
        object(stdClass)[7]
          public 'article_id' => string '4' (length=1)
          public 'parent_id' => string '4' (length=1)
          public 'template_id' => string '4' (length=1)
          public 'type' => string 'page' (length=4)
          public 'url' => string 'home' (length=4)
          public 'title' => string 'Home' (length=4)
          ... and so on...

I want it to be like this,
object(stdClass)[7]
  public 'article_id' => string '4' (length=1)
  public 'parent_id' => string '4' (length=1)
  public 'template_id' => string '4' (length=1)
  public 'type' => string 'page' (length=4)
  public 'url' => string 'home' (length=4)
  public 'title' => string 'Home' (length=4)
  ... and so on...

Model, Mapper, Service below are the classes how I get to the result above (
    object(ArticleModel)[4]public 'item' => [...]
).
model,
class ArticleModel
{
    // It is not ideal if I have to set the property manually.
    public $article_id;
    public $title;
    public $url;
    ... and so on...
}

mapper,
class ArticleMapper
{
    private $Database;

    public function __construct(Database $pdo)
    {
        $this->Database = $pdo;
    }

    public function getRow($article_id)
    {
        $sql = "
            SELECT *
            FROM article AS p
            WHERE article_id = ?
        ";

        $this->item = $this->Database->fetchRowObject($sql, $article_id);

        return $this;
    }

    public function addContent()
    {
        ...
    }

    public function mapRow(ArticleModel $ArticleModel, $article_id)
    {
       $ArticleModel->item = $this->getRow($article_id)->item;
    }
}

service,
class ArticleService
{
    public function __construct(Database $pdo)
    {
        $this->Database = $pdo;
    }

    public function fetchRow($article_id)
    {
        $ArticleModel = new ArticleModel();
        $ArticleMapper = new ArticleMapper($this->Database);
        $ArticleMapper->mapRow($ArticleModel,$article_id);
        return $ArticleModel;
    }
}

view/ controller,
// Instance of Database.
$Database = new Database(DSN,DB_USER,DB_PASS);

// Make connection.
$Database->connect();

$ArticleService = new ArticleService($Database);
$article = $ArticleService->fetchRow(4);

var_dump($article);

result,
object(ArticleModel)[4]
  public 'item' =>
    object(stdClass)[7]
      public 'article_id' => string '4' (length=1)
      public 'parent_id' => string '4' (length=1)
      public 'template_id' => string '4' (length=1)
      public 'type' => string 'page' (length=4)
      public 'url' => string 'home' (length=4)
      public 'title' => string 'Home' (length=4)
      ... and so on...

I am following this slideshare example to make my example above.


text:
Q: predict train_generator from vgg16 to compare the true value vs prediction value I've 20 classes and 2907 observations in my train dataset of dog from imagenet.
I want to compare my predictions and the true value of label because of overfitting problems.
I try :
X_train, y_train = next(train_generator)
preds = net_final.predict(X_train, batch_size=BATCH_SIZE, verbose=0)
print(train_generator.n)
print(len(X_train))
pred_labels = np.argmax(preds, axis=1)
true_labels = np.argmax(y_train, axis=1)
print (pred_labels)
print (true_labels)

The problem is : train_generator.n equals 2907
and len(X_train) equals 50.
How can i recover the true label to compare to my predictions?
I'm a french student and i'm sure i make some errors in english and in python of course ;) i apologize.
Thanks for your response


text:
Q: Unexpected output from Get-ACL | Select Access Unexpected output from Get-ACL | Select Access
If I do not Select the Access property, then the contents are displayed as I desire.  e.g. BUILTIN\Administrators Allow  FullControl.
But if I Select the Access property, some sort of object type (System.Security.AccessControl.FileSystemAccessRule) gets displayed instead:
PS C:\tmp> Get-Acl .\test | Format-List

Path   : Microsoft.PowerShell.Core\FileSystem::C:\tmp\test
Owner  : EXAMPLE\sjobs
Group  : EXAMPLE\Domain Users
Access : BUILTIN\Administrators Allow  FullControl
         BUILTIN\Administrators Allow  268435456
         NT AUTHORITY\SYSTEM Allow  FullControl
         NT AUTHORITY\SYSTEM Allow  268435456
         BUILTIN\Users Allow  ReadAndExecute, Synchronize
         NT AUTHORITY\Authenticated Users Allow  Modify, Synchronize
         NT AUTHORITY\Authenticated Users Allow  -536805376
Audit  :
Sddl   : REDACTED

PS C:\tmp> Get-Acl .\test | Select Access | Format-List

Access : {System.Security.AccessControl.FileSystemAccessRule, System.Security.AccessControl.FileSystemAccessRule,
     System.Security.AccessControl.FileSystemAccessRule, System.Security.AccessControl.FileSystemAccessRule...}

I'm more familiar with bash than PowerShell.  But I understand that PowerShell tends to pass objects instead of strings.
Why do these two display Access differently?
More importantly, how do I display only the Access property as I desire?

A: If you look at the object type, it gives some clues.
PS C:\Users\jacob> $acl = get-acl

PS C:\Users\jacob> $acl.GetType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    DirectorySecurity                        System.Security.AccessControl.FileSystemSecurity

PS C:\Users\jacob> ($acl | select access).getType()

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     False    PSCustomObject                           System.Object

With PSCustomObject you can access the property values using .psobject.Properties.value or . notation.
So if we isolate the acesss object $access = $acl | select access and then access the property values we get the information we're after.
PS C:\Users\jacob> $access.PSObject.Properties.Value

FileSystemRights  : FullControl
AccessControlType : Allow
IdentityReference : NT AUTHORITY\SYSTEM
IsInherited       : False
InheritanceFlags  : ContainerInherit, ObjectInherit
PropagationFlags  : None

FileSystemRights  : FullControl
AccessControlType : Allow
IdentityReference : BUILTIN\Administrators
IsInherited       : False
InheritanceFlags  : ContainerInherit, ObjectInherit
PropagationFlags  : None

FileSystemRights  : FullControl
AccessControlType : Allow
IdentityReference : SURFACE\jacob
IsInherited       : False
InheritanceFlags  : ContainerInherit, ObjectInherit
PropagationFlags  : None

In one line:
get-acl .\test | select access | % { $_.PSObject.Properties.Value }

Or we can trim it down to
get-acl .\test | select access | % { $_.Access }

Or finally:
(get-acl .\test | select access).access


text:
Q: .Net Maui: How to read/write (get/set) a global object from any content page (MVVM) I'm sure that I'm missing some deep or obvious concept here :)
So I have a page now that can setup various Bluetooth sensors and get data from a heart rate monitor, speedometer and cadence sensor. (Using Plugin.BLE)
So I do all of that in a ViewModel for a ContentPage called BluetoothPage.
I want to display the data I get in a different ContentPage called DisplayPage.
I have created a simple class (model) that can hold the data I want:
namespace TSDZ2Monitor.Models;

public partial class BluetoothData : ObservableObject
{
  //Heart rate raw data
  public int HRM { get; set; }
  public double HRR { get; set; }

  //SPD raw data
  public int SPDWheelRevolutions { get; set; }
  public double SPDWheelEventTime { get; set; }

  //CAD raw data
  public int CADCrankRevolutions { get; set; }
  public double CADCrankEventTime { get; set; }

}

So, how do I get the data from my Bluetooth page to my Display page?
I suspect I need to use an object based on my model and populate it with data in my Bluetooth viewmodel (easy...ish)?
But how can my Display page see this data as it happens?
When I tried working with ReactNative this sort of thing was a nightmare (State!)
Or am I being a bit simple in the head here :lol
Workaround: I could save the data to some local storage or sqlite as per https://learn.microsoft.com/en-us/learn/dotnet-maui/store-local-data/2-compare-storage-options - is that the way to do it, or can it be done with the object?
G.
Edit: I think I could also use the MessagingService https://learn.microsoft.com/en-us/dotnet/maui/fundamentals/messagingcenter and https://codemilltech.com/messing-with-xamarin-forms-messaging-center/ if I can figure out how to use them in MVVM context.
Also What is the difference between using MessagingCenter and standard .NET event handlers for informing interested parties of changes?

A: So it seems that using the MessagingCenter was a way to go.
Following the guidance in  https://codemilltech.com/messing-with-xamarin-forms-messaging-center/
I created a MessagingMarker class:
namespace TSDZ2Monitor.Classes;

public class MessagingMarker
{
}

That's all.
In the ViewModel where I wanted to send an object from, I did
MessagingCenter.Send(new MessagingMarker(), "BTDataUpdate", btd);

where btd was an instance of a class I created to hold my data: Here is a simplified model:
namespace TSDZ2Monitor.Models;

public partial class BluetoothData : ObservableObject
{
  //Heart rate raw data
  private int hRM;
  public int HRM  //heart rate
  {
    get => hRM;
    set => SetProperty(ref hRM, value);
  }
  private double hRR; //heartrate R-R value
  public double HRR
  {
    get => hRR;
    set => SetProperty(ref hRR, value);
  }

  private double wheelRPM;
  public double WheelRPM
  {
    get => wheelRPM;
    set => SetProperty(ref wheelRPM, value);
  }

  private double cadence;
  public double Cadence
  {
    get => cadence;
    set => SetProperty(ref cadence, value);
  }

}

In the constructor of the ViewModel for the sending page (probably best somewhere else?)
 public BluetoothData btd = new();

This is not used in the XAML for this ViewModel
In my receiving ViewModel
I also created an instance of the BluetoothData class, but this is used in the XAML bindings
  [ObservableProperty]
  private BluetoothData bTData;

and in the constructor of the ViewModel I had
    BTData = new BluetoothData();

    MessagingCenter.Subscribe<MessagingMarker, BluetoothData>(this, "BTDataUpdate", (sender, arg) =>
    {
      //Debug.WriteLine($"Message received {arg}");
      BTData.HRM                   = arg.HRM;
      BTData.HRR                   = arg.HRR;
      BTData.WheelRPM              = arg.WheelRPM;
      BTData.Cadence               = arg.Cadence;
    });

Well it works, don't know what the impact on performance might be, but it seems pretty responsive.
To my way of thinking though a more idea solution is to create a global instance of any class that any ViewModel can access.

A: I had need to also do this -- in my case, reference an ObservableCollection<State> States from multiple pages.  Sharing this as another possible solution:
I created a class with the ObservableCollection as a static member which is populated once upon first use:
public class Filter
{
    ...
    public static ObservableCollection<State> StateSelections { get; } = new();
    ...
    public Filter(DataService dataService) : base()
    {
        this.dataService = dataService;

        PopulateData();
    }

    public async Task PopulateData()
    {
        // Populate the available selections
        await LoadStates();
    }

    public async Task LoadStates()
    {
        if (StateSelections?.Count > 0)
            return;
        ...
    }
}

For each page that uses the collection, its VM has a reference to an instance of the class:
public partial class ParkListVM : BaseVM
{
    ...
    public Filter Filter { get; set; }
    ...

    public void PopulateData()
    {
        if (ParkListVM.Filter is null)
            ParkListVM.Filter = new Filter(dataService);
        ...
    }
}

And the page has a reference to the static collection for display:
<ContentPage
    xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
    xmlns:vm="clr-namespace:NationalParks.ViewModels"
    xmlns:model="clr-namespace:NationalParks.Models"
    x:DataType="vm:ParkListVM"
    x:Class="NationalParks.Views.ParkListPage"
    Title="{Binding Title}">
    <ContentPage.Resources>
        <model:Filter x:Key="Filter"/>
    </ContentPage.Resources>
    ...
    <CollectionView ItemsSource="{Binding Source={x:Static model:Filter.StateSelections}}"
                    SelectionMode="Multiple"
                    SelectedItems="{Binding SelectedStates}">
        <CollectionView.ItemTemplate>
            <DataTemplate x:DataType="model:State">
                <VerticalStackLayout>
                    <Label Style="{StaticResource LabelMedium}" Text="{Binding Name}" />
                </VerticalStackLayout>
            </DataTemplate>
        </CollectionView.ItemTemplate>
    </CollectionView>
    ...
</ContentPage>


text:
Q: Why isn't transliteration from Urdu to Latin working properly in icu4c? I'm trying to convert this line of Urdu to Latin, and then converting the Latin characters to ASCII (by removing the accents, etc) but it seems to be missing some characters.
Why are there non latin characters ("ہ", "ے", etc) still there?
$ uconv -x 'Any-Latin'
دفعہ 1: تمام انسان آزاد اور حقوق و عزت کے اعتبار سے برابر پیدا ہوۓ ہیں۔ انہیں ضمیر اور عقل ودیعت ہوئی ہے۔ اس لئے انہیں ایک دوسرے کے ساتھ بھائی چارے کا سلوک کرنا چاہئے

dfʿہ 1: tmạm ạnsạn ậzạd ạwr ḥqwq w ʿzt ḵے ạʿtbạr sے brạbr py̰dạ ہwے̉ ہy̰ں۔ ạnہy̰ں ḍmy̰r ạwr ʿql wdy̰ʿt ہwỷy̰ ہے۔ ạs lỷے ạnہy̰ں ạy̰ḵ dwsrے ḵے sạtھ bھạỷy̰ cẖạrے ḵạ slwḵ ḵrnạ cẖạہỷے

Why is the transliterator Any-ASCII not converting to ASCII?
$ uconv -x 'Any-Latin; Latin-ASCII'
دفعہ 1: تمام انسان آزاد اور حقوق و عزت کے اعتبار سے برابر پیدا ہوۓ ہیں۔ انہیں ضمیر اور عقل ودیعت ہوئی ہے۔ اس لئے انہیں ایک دوسرے کے ساتھ بھائی چارے کا سلوک کرنا چاہئے

dfʿہ 1: tmam ansan azad awr hqwq w ʿzt kے aʿtbar sے brabr pyda ہwے̉ ہyں۔ anہyں dmyr awr ʿql wdyʿt ہwyy ہے۔ as lyے anہyں ayk dwsrے kے satھ bھayy charے ka slwk krna chaہyے
$ uconv -x 'Any-Latin; Latin-ASCII' -t latin1
دفعہ 1: تمام انسان آزاد اور حقوق و عزت کے اعتبار سے برابر پیدا ہوۓ ہیں۔ انہیں ضمیر اور عقل ودیعت ہوئی ہے۔ اس لئے انہیں ایک دوسرے کے ساتھ بھائی چارے کا سلوک کرنا چاہئے

Conversion from Unicode to codepage failed at output byte position 2. Unicode: 02bf Error: Invalid character found

A: You can see what those characters are with this command:
uconv -x 'Any-Latin; Latin-ASCII' --to-callback escape-c -t ascii

*

*-t ascii   : convert the output to actual ASCII. Not just latin1.

*--to-callback escape-c :  anything that wasn't convertable, goes through the 'escape' callback

which gives us this result:
df\u02BF\u06C1 1: tmam ansan azad awr hqwq w \u02BFzt k\u06D2 a\u02BFtbar s\u06D2 brabr pyda \u06C1w\u06D2\u0309 \u06C1y\u06BA\u06D4 an\u06C1y\u06BA dmyr awr \u02BFql wdy\u02BFt \u06C1wyy \u06C1\u06D2\u06D4 as ly\u06D2 an\u06C1y\u06BA ayk dwsr\u06D2 k\u06D2 sat\u06BE b\u06BEayy char\u06D2 ka slwk krna cha\u06C1y\u06D2
So, U+06C1 HEH GOAL for instance isn't transliterated.  You could file a CLDR ticket.
Actually, there's already this one:  http://unicode.org/cldr/trac/ticket/4387
Once there's an Urdu-Latin transliteration, then you can use ur-Latin instead of just Any-Latin.  That way Urdu specific rules are used and not just Arabic script rules.
I'd follow up on ticket 4387 if I were you.


text:
Q: ASM: Check if no key is pressed I got a mission from school to build a snake game in assembly.
I have done all the game, but I can't figure a way to do one thing - make the snake countinue moving in the same dirction while no key is pressed.
Currently, after each step, my code call this code to get the next key:
mov ah,1h
int 21h ; store at al
But this code wait until the user will press something, so he is not good for that case.
Is someone know a code that after some time, if no key is pressed, countinue the code?
Thanks in addition :)

A: Try this :
  mov  ah, 0Bh  ;CHECK IF ANY KEY WAS PRESSED.
  int  21h      ;RESULT IN AL : ==0:NO KEY, !=0:KEY.
  cmp  al, 0
  je   JUMP_TO_MOVE_SNAKE
;GET PRESSED KEY.
  mov ah,1h
  int 21h
JUMP_TO_MOVE_SNAKE:
  ...

Service 0Bh doesn't stop the execution of the code, so you can know when a key is pressed or when it is not.

A: Have the interrupt set a variable. Use a timer to clear it right after it is read. Use the variable to determine which code to execute: straight/left/right


text:
Q: How to make a n-dimention list with one dimention lists with a loop I'm learning python and I have been trying to make an automatic list of lists. For example:
The next list, which I have to split to get a list of separated letters, and then join them again to make a two lists of separated letters
lists=[['a,b,c,h'],['d,e,f,g']]

print('list length', len(lists))
splited=[]

splited1=lists[0][0].split(',')
print(splited1)  #['a', 'b', 'c', 'h']

splited2=lists[1][0].split(',')
print(splited2)  #['d', 'e', 'f', 'g']

listcomb=[splited1,splited2]

print(listcomb) #[['a', 'b', 'c', 'h'], ['d', 'e', 'f', 'g']]

This is what I want to get, a list that have 2 lists, but in the case I have to get more lists inside that list i want to make it automatic with a for loop.
My try, but it didn't work
listcomb2=zip(splited1,splited2)
print(listcomb2)

sepcomb = list()
print(type(sepcomb))
for x in range(len(lists)):
    sep=lists[x][0].split(',')
    sepcomb[x]=[sep]
print(sepcomb)

I'm having problems with splitting the letters and then joining them in a new list. Pls help

A: You can simply do  the following:
final=[splinted1]+[splinted2]

Or a better way directly from the lists variable would be:
final=[value[0].split(',') for value in lists]

A: Make some tweak in your code. As we can see lenght of sepcomb is 0 so use append method to avoid this problem. As sepcomb[x]=[sep] is is assignment to x-index but it x index doesn't exist so, it will raise error
change:
for x in range(len(lists)):
    sep=lists[x][0].split(',')
    sepcomb[x]=[sep]

to
for x in range(len(lists)):
    sep=lists[x][0].split(',')
    sepcomb.append(sep)

Method-2
sepcomb = list(i[0].split(',') for i in lists)

A: Here you go:
lists = [['a,b,c,h'],['d,e,f,g']]

listcomb = []
for each in lists:
    splited = each[0].split(',')
    listcomb.append(splited)
print(listcomb)


text:
Q: Web app fetching background geolocation using service worker and push notification I am looking for a solution to fetch geolocation periodically (every 1 minute) on mobile browser. I did some research and came to know that fetching geolocation in background (when phone is locked or webapp not active) is impossible. In foreground it works ok.
I am making a web app where I fetch user location and send it to my server. All works ok, until the point where user locks his/her phone. I tried many things for workarounds:

*

*setInterval to get geolocation, works fine in foreground but fails in background

*converted my web app into Android using cordova, but same problem existed

*used https://github.com/mauron85/cordova-plugin-background-geolocation this plugin for android

*

*works good in both foreground and background

*but the same plugin does not work in iPhone (I did not tested it, I searched in Google before moving ahead)

*Its not good to release my app with just one platform (android) support, thus this workaround also failed for me.

*I also considered using serviceworkers for my web app but it seems issue persist for background
https://github.com/w3c/ServiceWorker/issues/745
I have another solution in mind, but before investing time in it, I wish to know if someone has tried it already.
I learnt about Push notifications:

*

*Web app client registers to Push notification

*It sends
subscriber object to my server

*My server using this object sends
message to Push notification server

*Push notification server
sends messages to my web app client

*My web app client wakes up my
service worker for a brief period to show the notification message

*As per google documentation:

Note: In the current implementation
  of Chrome, whenever we receive a push message and we don't have our
  site visible in the browser we must display a notification. That is,
  we can't do it silently without the user knowing. If we don't
  display a notification the browser automatically creates one to let
  the user know that the app is doing work in the background.

I won't mind showing a permanent notification to users until my app is running. I am ready for this trade-off.
Now, my question is, at step 5, when I wake up the service worker **is there a chance I call my main.js (main web app) which might be running in background **, will fetch the geolocation and update it to my server?
Has someone tried this solution already with success or failure, please inform.

A: Can you try Page visibility Api, which listens for visibilitychange of a browser tab is hidden or switched to other tab (in case of browser). For mobiles, it's just a try.
src : https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API
or You can look into this answer too..
Detecting when screen is locked


text:
Q: How do I save models as a vector with a loop? So I have this assignment where I have to create 3 different models (r). I can do them individually without a problem. However I want to take it a step further and to create a function that trains all of them with a for loop. (I know I could create a function that trained the 3 models each time. I am not looking for other solutions to the problem, I want to do it this way (or in a similar fashion) because now I have 3 models but imagine if I wanted to train 20!
I tried creating a list to store all three models, but i keep having some warnings.

library(caret)
library(readr)
library(rstudioapi)
library(e1071)
library(dplyr)
library(rpart)

TrainingFunction <- function(method,formula,data,tune) {
 fitcontrol <-  trainControl(method = "repeatedcv", repeats = 4)

 if(method == "rf") {Model <- train(formula, data = data,method = method, trcontrol = fitcontrol , tunelenght = tune)}
 else if (method == "knn"){
   preObj <- preProcess(data[, c(13,14,15)], method=c("center", "scale"))
   data <- predict(preObj, data)
   Model <- train(formula, data = data,method = method, trcontrol = fitcontrol , tunelenght = tune)
 }
 else if (method == "svm"){Model <- svm(formula, data = data,cost=1000 , gamma = 0.001)}
   Model
 }

So this is a training function I created, and it works, but now I want to train all three at once !
So I tried this:
methods <- c("rf","knn","svm")
Models <- vector(mode = "list" , length = length(methods))
for(i in 1:length(methods))
{Models[i] <- TrainingFunction(methods[i],Volume~.,List$trainingSet,5)}

This are the warnings :
Warning messages:
1: In Models[i] <- TrainingFunction(methods[i], Volume ~ ., List$trainingSet,  :
  number of items to replace is not a multiple of replacement length
2: In Models[i] <- TrainingFunction(methods[i], Volume ~ ., List$trainingSet,  :
  number of items to replace is not a multiple of replacement length
3: In svm.default(x, y, scale = scale, ..., na.action = na.action) :
  Variable(s) 'ProductType.GameConsole' constant. Cannot scale data.
4: In Models[i] <- TrainingFunction(methods[i], Volume ~ ., List$trainingSet,  :
  number of items to replace is not a multiple of replacement length

When I do Models the output is this :

[[1]]
[1] "rf"

[[2]]
[1] "knn"

[[3]]
svm(formula = formula, data = data, cost = 1000, gamma = 0.001)

A: I think the problem comes from this line:
{Models[i] <- TrainingFunction(methods[i],Volume~.,List$trainingSet,5)}

If you want to assign your model to the i-th place of the list, you should do it with a double bracket, like this:
{Models[[i]] <- TrainingFunction(methods[i],Volume~.,List$trainingSet,5)}

Another alternative would be use lapply instead of an explicit loop, so you avoid that problem altogether:
train_from_method <- function(methods) {TrainingFunction(methods,Volume~.,List$trainingSet,5)}
Models <- lapply(species_vector, train_from_method)

A: Consider switch to avoid the many if and else especially if extending to 20 models. Then use lapply to build a list without initialization or iterative assignment:
TrainingFunction <- function(method, formula, data, tune) {
 fitcontrol <-  trainControl(method = "repeatedcv", repeats = 4)

 Model <- switch(method,
     "rf" = train(formula, data = data, method = method,
                  trcontrol = fitcontrol, tunelength = tune)
     "knn" = {
          preObj <- preProcess(data[,c(13,14,15)],
                               method=c("center", "scale"))
          data <- predict(preObj, data)
          train(formula, data = data, method = method,
                trcontrol = fitcontrol, tunelength = tune)
          }
     "svm" = svm(formula, data = data, cost = 1000, gamma = 0.001)
 )
}

methods <- c("rf","knn","svm")

Model_list <-lapply(methods, function(m)
    TrainingFunction(m, Volume~., List$trainingSet, 5))


text:
Q: Don't understand the difference between $P(a \le X \le b)$ and $P(X\in B)$ By def, $P(a \le X \le b)=\int_a^b f_X(x) dx$ and $P(X\in B)=\int_B f_X(x) dx$.
I think I understand $P(a \le X \le b)$ well enough: it tells you that if $X$ is the random variable that maps the height of someone to $x$, then $P(a \le X \le b)$ asks what's the probability of someone's height, or $x$, being between $a$ and $b$.
$P(X\in B)$ is a lot more confusing. My textbook, Tsitsiklis' Intro to Probability and Statistics, said this is 'the PDF of $X$ for every subset $B$ of the real line'.
I have no idea what that is supposed to mean. Is it just the probability of $x$ being a real number?
The integral also doesn't make much sense to me. I can understand what $\int_a^b$ means - the area under the function between $x=a$ and $x=b$. But $\int_B$ only gives the lower bound...I am sure it doesn't mean the area from $B$ to infinite...so what does it mean?

A: $B$ in the statement $P(X\in B)$ is a subset of $\mathbb R$.
In fact, you can rewrite $P(a\leq X\leq B)$ as $$P(X\in [a, b])$$ in which case you can use the second definition to get, $$P(X\in [a, b]) = \int_{[a,b]}f_X(x)dx$$
and, "luckily", measure theory also tells you that
$$\int_{[a,b]}f_X(x)dx = \int_a^bf_X(x)dx$$
so the two definitions are compatible.


text:
Q: SharePoint Online - How to redirect a URL? SharePoint Online- We recently migrated a site from an old location to a new location. Users have the link(URL) to our old site. How can i redirect the users to the new location(new URL) when the try to access the Old URL?
Thanks

A: You "could" add a CEWP to the homepage to insert some javascript to redirect them automatically.
<script>
window.location.href = "https://sharepointtenant.sharepoint.com/";
</script>

Ideally, if you were coming from onprem, you could add this javascript to the 404 error page and turn off all the sites so that the 404 page will redirect them.


text:
Q: Batch Rename Shapfiles in subfolders in R I know this should be something easy, but I'm really struggling with it so figured I'd ask here. I have a group of shapefiles by state for 7 states, and am trying to batch rename them all. Within the "places" folder are state folders entitled the state name ("Iowa","Kansas" etc...). Within each of those folders is a basically gibberish name for the shapefiles ("gz_2010_53_160_00_500k" for the .shp, .prj etc... files). I'd like to rename each of them with the state name so that the shapefile path is basically ("places/Iowa/Iowa.shp" or dbf or prj...). Below was my attempt.
setwd("~/Dropbox/places")
files<-list.files(getwd(),pattern="", recursive=T)
sapply(files,function(x) {
    state<-strsplit(x,"/")[[1]][1]#extract state name
    file_type<-str_sub(files[1],start=-4) #get file type (.shp etc...)
    file.rename(x,paste(state,"/",file_type,sep=""))
})

The output of files looks something like this (only first 3 shown):
dput(files[1:3])
c("Iowa/gz_2010_19_160_00_500k.dbf", "Iowa/gz_2010_19_160_00_500k.prj",
"Iowa/gz_2010_19_160_00_500k.shp")

When I ran this, each of the filenames spit out in the console and said "TRUE" beneath them. When I looked at the folders, all of the files were gone! Clearly I had done something wrong.
I know this is likely a simple question, but please let me know how I can do this. I really seem to struggle with navigating through directories...


text:
Q: Sending data using Javascript I want to know how to send data using Javascript. This is what I tried so far:
$('A').on("click", function(){
    $.ajax({
        type:"POST",
        url: "/cccc",
        data: {user: 'a'},
        success: function(response){
            alert(response);
        },
        error: function(data)
        {
            alert(data.responseText);
        },
});

I've tried above ajax function but nothing happens.

Also i curious that if there is more simple function like
$('A').on("click", function(){
   post('/cccc', make_params(a:'a')
});

Hope someone can answer above 2 questions!
Thanks!

A: Of course if you use jQuery library, it will work:
$('some_selector').on('click', function(){
    $.post(
       '/cccc',
       {
           user: 'a'
       },
       function(response){
           alert(response);
       }
    }
});


text:
Q: Visual Studio build events I't trying to configure my solution in Visual Studio 2017 for cleanup after builds etc. I'm interested if there is a full list of commands/events for using in pre/post build events section. Is there any?

A: According to this page, there are PreBuild, PreLink, and PostBuild events.  These can be declared inline (which VS does):
<ItemGroup>
  <PostBuildEvent>rd /s /q obj</PostBuildEvent>
<ItemGroup>

The docs demonstrate it split up into separate Commands and Messages, but this didn't work for me in a C# project.  I'm not sure if this is a C++ only feature.
<ItemGroup>
  <PostBuildEvent>
    <Command>rd /s /q obj<Command>
    <Message>Cleanup intermediate output directory</Message>
  </PostBuildEvent>
<ItemGroup>

Additionally, you can augment the build pipeline by adding new MSBuild targets.  These can be configured to run before or after any specific target in the pipeline (there are many by default).  Documentation for that is here, especially the section titled BeforeTargets and AfterTargets.


text:
Q: Change the key in a PHP array I want to change the key of my array in php.
Here an exemple :
array (size=5)
  0 =>
    array (size=2)
      'iden' => string '01' (length=8)
      'don' => string '17' (length=2)
  1 =>
    array (size=2)
      'iden' => string '02' (length=8)
      'don' => string '17' (length=2)
  2 =>
    array (size=2)
      'iden' => string '03' (length=8)
      'don' => string '17' (length=2)

And I want to change my array like this :
array (size=5)
  0 =>
    array (size=2)
      0 => string '01' (length=8)
      1 => string '17' (length=2)
  1 =>
    array (size=2)
      0 => string '02' (length=8)
      1 => string '17' (length=2)
  2 =>
    array (size=2)
      0 => string '03' (length=8)
      1 => string '17' (length=2)

Thanks in advance

A: You can use the array_values function to remove named keys:
foreach($array as &$item) {
    $item = array_values($item);
}
unset($item); // Remove reference

Note the & in the foreach. This creates a reference in the $item variable to the corresponding array element which means you can edit it in your loop.
If you want, you can also write this in a single line using array_map:
$array = array_map("array_values", $array);


text:
Q: Showing the time remaining between two Date columns as a perentage I've got two columns 'Contract Commencement Date' and 'Contract End Date' and I'm trying to show the time remaining as a percentage in a third column.
Using Flow I've got a field to show todays date, and I'm using some JSON to colour code the field but I'm not getting the correct percentage. I've set the Percentage Test column up as calculated field with the following formula: =TodayDate-[Contract Commencement Date] as a percentage. Where am I going wrong

A: Assuming your TodayDate column is updated automatically every day (which should then also re-trigger your calculated field), then your formula should correctly calculate the total number of days that have elapsed since the Start of the Contract.  I will point that this means if the [Contract Commencement Date] is in the future, then your formula would return a negative number.  You can avoid that by changing the calculation to MIN(0, TodayDate-[Contract Commencement Date]).  However, this still only gives you total elapsed days, not a percentage.
If you want a percentage,  you want to divide the total days elapsed by the total number of days in the contract  The total days in the contact would be ([Contract End Date]-[Contract Commencement Date]), so your total formula would be:
=MIN(0, TodayDate-[Contract Commencement Date])/([Contract End Date]-[Contract Commencement Date])


text:
Q: How to rewind a CSV by one line? I am looping through a CSV to get product data. There are some lines that are variants of products and have a line of their own, e.g.:
sku, base_sku, name, desc, attribute
, 123, "product name", "long description here", Colour
abc,123,,,Red
xyz,123,,,Blue
novar,novar,"No variant product", "description here",

The main product has a base_sku. All variants will have a specific sku, linked to a product by the base_sku. If a product has no variants, then the product has a sku and base_sku of the same value.
Anyway, I am looping through the CSV using:
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {

Then I'm doing a check for variants and doing another while loop to get all variants:
while (($varient = fgetcsv($handle, 1000, ",")) !== FALSE){

During this while loop I am checking if the sku and base_sku are the same, and if they are break out of the while loop. Now I want to rewind the file pointer by one line so that when the first while loops it will read the correct line.
At the moment I have tried:
fseek($handle,-1,SEEK_CUR);

Which, I misunderstood at the time, is sending the file pointer back per character, not per line.
How do I get the file pointer to go back by one line?

A: There does not appear to be a way to do this so I have converted my code a little to work with arrays:
$rows = array();
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    $rows[] = $data;
}

foreach ($rows as $data) {

Then I use the array functions next() and prev()

A: you can save the previous position with the function ftell()
http://php.net/manual/en/function.ftell.php
then you can go back to that position
with the function fseek()
so you code would look something like this
$prev_line=null;

while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
  $prev_line=ftell($handle);
  while (($varient = fgetcsv($handle, 1000, ",")) !== FALSE){
    if($varient['sku']==$varient['base_sku']){
        fseek($handle, $prev_line, SEEK_SET);
        break;
    }
  }
}

so your pointer will be in the previous location as it was before it entered the second while loop


text:
Q: Keeping Python Interpreter always on [Windows] I run several custom python scripts on my Windows machine all the time. I also use batch files to link to these python scripts so I can easily control them from Run/Command Prompt:
(As an example I have a command which converts one file to another(like html to tex) using the corresponding available modules, so I don't need to remember them. Like the command Directory> python converter.py -C:/{Path to File} -tex -pdf converts the tex file to the pdf without me intervening further and gives a message box at the end. I also have a batch file(named pizza.bat all it does is give a command to run this python file by going to its directory and basically taking care of all the long steps I want to avoid) in system 32 so I can run this directly from the windows run without going to the directory pizza -C:{File Path} -tex -pdf. Obviously there are heavy modules that need to be imported. I need to know if there is a way I can import these modules and keep the python interpreter always running. Basically my python interpreter never shuts down. This should speed up my tasks.
The reason I gave an entire explanation about what I do is basically because if this makes any difference and if yes how to deal it.
Any advice is appreciated.
Thank you in advance.


text:
Q: How can I change the preference for what program opens a type of link in OS X? I recently upgraded Thunderbird to version 5, and I installed the plugin that allows the calendar tab to read/update webcal calendars.
Previous to the update, I had a Basecamp milestone calendar, a few Google calendars, and my Facebook event calendar plugged into Thunderbird.
When the upgrade completed, I got a pop-up asking me how I wanted to handle the opening of webcal/ical links, and I (without paying attention) selected iCal and chose the "Always use this..." option.
Now iCal opens every 10 minutes or so and asks me what to do with the links, which is extremely annoying. I tried just adding those calendars to iCal and hoping it wouldn't open anymore, but to no avail.
I know I can change the default application on files by right clicking, but as far as I know I can't save a webcal link as a file that can be right clicked.
I'm thinking I need access to some preference list. I don't know where to look for this, and all of my searches take me to the, "Right click, Get Info, change the application it opens with" answer. I'm comfortable in Terminal, but I'm not sure where to start looking.
Has anyone seen this before? Any known solutions?
Note: I'm using Mac OS X 10.6.8

A: An option would be to use RCDefaultApp. Download it, and install the Preference Pane by double-clicking the .prefpane file.
Then, go to URLs → webcal and select the application you want.

If the above doesn't work (for whatever reason):
You might also be able to remove the entry from the Launch Services associations. It's basically the same as what the app above does. The relevant entries are in ~/Library/Preferences/com.apple.LaunchServices.plist. You can open this file with some editor like TextWrangler or the Preference List Editor shipped with Xcode.
What I could find was something like this:
<dict>
    <key>LSHandlerRoleAll</key>
    <string>com.apple.ical</string>
    <key>LSHandlerURLScheme</key>
    <string>webcal</string>
</dict>

You could try to delete it, save the file and rebuild the launch services database.


text:
Q: Restrict AWS Codedeploy submiter user to approve his/her own deploy trigger We have a case,
Multiple people in a role can trigger and approve aws codedeploy. But we want to restrict user to start deployment and approve it all by him/her self.
What we want is kind of like github PR, where PR submitter can not approved the same PR.
How can we configure that in aws codedeploy?


text:
Q: Errors were encountered while processing: libnvidia-compute-450-server:amd64 How can I get rid of this package?
$ sudo dpkg --purge $(dpkg -l | grep libnvidia | awk '{print $2}')
dpkg: dependency problems prevent removal of libnvidia-compute-450-server:amd64:
 libcuinj64-10.1:amd64 depends on libcuda1 (>= 418.39) | libnvidia-tesla-cuda1 (>= 418.39) | libcuda.so.1 (>= 418.39) | libcuda-10.1-1; however:
  Package libcuda1 is not installed.
  Package libnvidia-compute-450-server:amd64 which provides libcuda1 is to be removed.
  Package libnvidia-tesla-cuda1 is not installed.
  Package libcuda.so.1 is not installed.
  Package libcuda-10.1-1 is not installed.
  Package libnvidia-compute-450-server:amd64 which provides libcuda-10.1-1 is to be removed.
 libcuinj64-10.1:amd64 depends on libcuda1 (>= 418.39) | libnvidia-tesla-cuda1 (>= 418.39) | libcuda.so.1 (>= 418.39) | libcuda-10.1-1; however:
  Package libcuda1 is not installed.
  Package libnvidia-compute-450-server:amd64 which provides libcuda1 is to be removed.
  Package libnvidia-tesla-cuda1 is not installed.
  Package libcuda.so.1 is not installed.
  Package libcuda-10.1-1 is not installed.
  Package libnvidia-compute-450-server:amd64 which provides libcuda-10.1-1 is to be removed.

dpkg: error processing package libnvidia-compute-450-server:amd64 (--purge):
 dependency problems - not removing
Errors were encountered while processing:
 libnvidia-compute-450-server:amd64

A: Thanks to pavlos in Ubuntu IRC channel:
Initially, I did:
$ sudo dpkg --purge $(dpkg -l | grep nvidia | awk '{print $2}')

and
$ sudo dpkg --purge $(dpkg -l | grep libnvidia | awk '{print $2}')

Not everything was removed then:
$ sudo dpkg --purge $(dpkg -l | grep cuda | awk '{print $2}')

$ sudo dpkg --purge libcuinj64-10.1:amd64

Then, again,
$ sudo dpkg --purge $(dpkg -l | grep nvidia | awk '{print $2}')

and
$ sudo dpkg --purge $(dpkg -l | grep libnvidia | awk '{print $2}')


text:
Q: Closure confusion, share global variable between function     var data = null;

    socket.on('screen1', function (data) {

        data = data;
        console.log(data) // has something
    });

    $approve.click(function(){
        console.log(data) //null
        socket.emit('screen2', data);

    });

For some reason I can't put click event into socket.on because it's listening to the server. But I want its callback which is the data.I tried to do data = data and expect my click callback is able to get the data but it's still null.

A: Your local variable takes precedence over the global variable:
socket.on('screen1', function (data) { // <-- local variable "data"
    data = data;  // <-- both these "data" are the same variable!!
});

To access the global variable "data" rename the local variable to something else:
socket.on('screen1', function (d) {
    // Here I have no idea what your intention is. If I am
    // confused consider how the compiler is supposed to read
    // your mind.

    // You either wanted to do:
    d = data;

    // or data = d;

    // I cannot guess and neither can the compiler.
});


text: Q: How to combine rows properly? I am coming to a problem where I have 5 rows from my database, all I need to do is combine those 5 rows into one object. I was wondering if there is a way to combine 5 rows into one?


text:
Q: Laravel 8: Recuperar dados Usuário Logado Ola,
eu não uso uma tabela padrão de usuários sugerida no Laravel, pois eu estou criando um frontend em um banco de dados já existe.
Todo o processo do login está funcionando corretamente, com verificação de usuário de senha. Mas o meu problema é que quando ele chama o menu eu não consigo recuperar os dados do usuário que foi logado no sistema. No menu quando eu coloco dd(auth()->user()) ele retorna null.
Queria saber o que falta no meu código para eu conseguir recuperar os dados do login do usuário.
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Repositories\UserRepository;
use App\Validators\UserValidator;
use Illuminate\Support\Facades\Auth;
use Exception;
Use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    private $repository;
    private $validator;

    public function __construct(UserRepository $repository, UserValidator $validator)
    {
        $this->repository = $repository;
        $this->validator  = $validator;
    }

    public function index()
    {
        return view('user.dashboard');
    }

    public function auth(Request $request)
    {

        $data = [
            'U_NAME'    => $request->get('username'),
            'PASSWORD4' => $request->get('password')
        ];
        try
        {
            if(env('PASSWORD_HASH'))
            {
                Auth::attempt($data, false);
            }
            else
            {
                DB::enableQueryLog();
                $user = $this->repository->findwhere(['USER_CODE' => $request->get('username')])->first();
                if(!$user)
                {
                    return redirect()->route('user.login')->withErrors(['Usuário Inválido']);
                }
                if((trim($user->PASSWORD4)) != (trim($request->get('password'))))
                {
                    return redirect()->route('user.login')->withErrors(['Senha Incorreta']);
                }
                Auth::login($user);
            }
            return redirect()->route('user.dashboard');
        }
        catch (Exception $e)
        {
            return $e->getMessage();
        }
    }
}

A: Eu consegui resolver fazendo colocando as informações na session, abaixo a nova classe com a alteração
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Repositories\UserRepository;
use App\Validators\UserValidator;
use Illuminate\Support\Facades\Auth;
use Exception;
Use Illuminate\Support\Facades\DB;

class DashboardController extends Controller
{
    private $repository;
    private $validator;

    public function __construct(UserRepository $repository, UserValidator $validator)
    {
        $this->repository = $repository;
        $this->validator  = $validator;
    }

    public function index()
    {
        return view('user.dashboard');
    }

    public function auth(Request $request)
    {
        $data = [
            'U_NAME'    => $request->get('username'),
            'PASSWORD4' => $request->get('password')
        ];
        try
        {
            if(env('PASSWORD_HASH'))
            {
                Auth::attempt($data, false);
            }
            else
            {
                DB::enableQueryLog();
                $user = $this->repository->findwhere(['USER_CODE' => $request->get('username')])->first();
                if(!$user)
                {
                    return redirect()->route('user.login')->withErrors(['Usuário Inválido']);
                }
                if((trim($user->PASSWORD4)) != (trim($request->get('password'))))
                {
                    return redirect()->route('user.login')->withErrors(['Senha Incorreta']);
                }
                Auth::login($user);
            }
                $request->session()->put('USER_CODE', $user->USER_CODE);
                $request->session()->put('U_NAME',    $user->U_NAME);
                $request->session()->put('SUPERUSER', $user->SUPERUSER);
                return redirect()->route('user.dashboard');
        }
        catch (Exception $e)
        {
            return $e->getMessage();
        }
    }
}


text:
Q: tar exclude error-output on specific paths Is it possible to ignore error-messages like: /etc/some-tool/some-log: file changed as we read it on the same way you can use exclude to exclude files?
I'm using tar to do system-backups, redirecting stdout and stderr into log-files. I Got some direcotires which contain log-files. Simply don't want to have the same error-lines (like shown above) every day in my result file.
So far couldn't find a command on man tar which could help me.

A: I wrote a script which analyzes the output log and decides if it's an error or not. Ignoring warnings on a global scope is not what I was looking for. Took me some time but it's the safest method imo.


text:
Q: How to load form with one value pre filled? I'm using using Django forms to collect information from users. But when I change between pages I want to use one of the value from url to be displayed in a from in the next page.
Example.
I  have url for checking out a book like
http://127.0.0.1:8000/checkout/780374157067
780374157067 is the ibn of the book
Next page has a form where I get the ISBN and card id of the user. How to fill the form with the ISBN and show the form to user. rather than the user giving the ISBN again.

ISBN Filed should be pre filled with thw isbn in URL.
HTML :
<div class ="col-md-3">
        <form method='POST' action=''>{%csrf_token%}
           {{template_form | crispy}}
           <input class="btn btn-lg btn-primary" type='submit'
                   value='Submit'/>
        </form>
</div>

Forms.py
class loansform(forms.Form):
    Isbn = forms.IntegerField()
    Card_id = forms.IntegerField()
    def clean_Isbn(self):
        isbn = self.cleaned_data.get("Isbn")
        isbn_string = str(isbn)
        if len(isbn_string) != 13:
            raise forms.ValidationError("Enter a valid ISBN-13")
        return isbn

views.py
template_form = loansform();

A: in your view you can put intial data in form first get paramter from url then :
data = {'isbn': 154646486,}
form = Myform(initial=data)

in urls.py:
url(r'^checkout/(?P<isbn>\d+)/$',check_page)

view example :
def check_page(request, isbn):
     data = {'isbn': isbn,}
     form = Myform(initial=data)
     template = 'mytem.html'
     context = {'form': form,}
     return render(request, template, context)

A: Say you've got url like
url(r'^checkout/(?P<isbn>\d+)/$')

In your view, when you instantiate form class, provide initial data to it like this.
form = YourFormClass(initial={'isbn': kwargs['isbn']})

kwargs contain url parameters, so you can get isbn from url.


text:
Q: Как повернуть спрайт не от нижнего левого угла? Переписал на си функцию glm::rotate, теперь хочу сделать так, чтобы можно было повернуть изображение относительно другой координаты, а не координаты левого нижнего угла рисунка. Так можно вообще? Я думал что надо что нибудь с cos и sin угол умножить на координаты, но изображение только уменшается и увеличивается.

A: Поворот в 2D относительно заданной точки CX, CY можно описать, как отметил Герман Борисов, с помощью последовательности переноса (чтобы центр вращения сместился в начало координат), поворота координат, и обратного переноса. В компактном виде формулы будут такие:
X_New = CX + (X - CX) * Cos(Fi) - (Y - CY) * Sin(Fi)
Y_New = CY + (X - CX) * Sin(Fi) + (Y - CY) * Cos(Fi)


text:
Q: Dovecot Authentication failed if trying login with @domain When I try to test my IMAP server functionality using telnet I encounter the following error.
If during the test i omit the @domain.ex everything works fine(as you can see below);
a login user password
a OK [CAPABILITY IMAP4rev1 LITERAL+ SASL-IR LOGIN-REFERRALS ID ENABLE IDLE SORT
SORT=DISPLAY THREAD=REFERENCES THREAD=REFS THREAD=ORDEREDSUBJECT MULTIAPPEND URL-PARTIAL
CATENATE UNSELECT CHILDREN NAMESPACE UIDPLUS LIST-EXTENDED I18NLEVEL=1 CONDSTORE QRESYNC
ESEARCH ESORT SEARCHRES WITHIN CONTEXT=SEARCH LIST-STATUS SPECIAL-USE BINARY MOVE] Logged in

if I try using username@domain.ex. I receive the following error:
a login user@domain.ex
a NO [AUTHENTICATIONFAILED] Authentication failed.

Someone knows where i'm mistaking ?
Thanks in advance.


text:
Q: Discord.py play local files on multiple server I have recently been writing a Discord bot recently which plays local mp3 files. The function I've used to play the files looks like this.
conn.play(discord.FFmpegPCMAudio("path/to/file"))
while conn.is_playing():
    time.sleep(0.1)
await conn.disconnect()

Now I was thinking about setting up the bot for multiple servers. My problem is that if I want to play two different sounds on two different servers at the same time, the bot is currently only able to play them sequentially and not simultaneously. I thought about having multiple python instances for each server but it looks kind of hard to manage for N server N python instances. It's ok for me to have multiple mp3 files  for each server so I don't lock any files. But using multiple python programs looks a bit complicated. Is there any easier solution?

A: Your problem arises from the use of time.sleep(). discord.py is an asynchronous library, which means that it handles being able to perform multiple functionalities at the same time to ensure that a bot is not blocked during its use, but adding a synchronous call like time.sleep() makes it stop its operations while that call lasts. As you are calling time.sleep() for the time the mp3 is playing, it is doing a synchronous operation in that function.
When you are working with asynchronous libraries it is best to look for the asynchronous version of other utilities as well so you do not fall into the temptation of using a blocking synchronous call within an asynchronous operation. In this case I recommend you to use await asyncio.sleep(0.1) for your purpose. You will need to import asyncio as well to use that function.
References:

*

*asynchronous vs synchronous

*asyncio

*asyncio.sleep()