text:
Q: UNABLE_TO_LOCK_ROW during send email I have a code where I send email using single email message.
I am setting targetObjectId as a contact Id.
I am getting the following error:

System.EmailException: SendEmail failed. First exception on row 0; first error: UNABLE_TO_LOCK_ROW.

The record for which the error occurs is a Contact.
As per my research, if a record is under process, still we can query its value and use it. Why is this error occurring?
The error doesn't occur always, but is happening regularly.
Below is the method :
public static void sendEmail(List<Id> contactids)
{
    EmailTemplate et = [SELECT id FROM EmailTemplate WHERE developerName = 'XYZ'];
    if(et.Id!= Null)
    {
        List<SingleEmailMessage> emailList = new List<SingleEmailMessage>();
        OrgWideEmailAddress[] owea = [select Id from OrgWideEmailAddress where Address = 'abcd@xyz.com'];

        for(Id conId: contactids)
        {
            Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
            mail.setTargetObjectId(conId);
            mail.setTemplateId(et.Id);
            mail.setOrgWideEmailAddressId(owea.get(0).Id);
            emailList.add(mail);
        }
    }

    if(!emailList.isEmpty()){
        Messaging.sendEmail(emailList); // I am getting the Unable_To_Lock_Row error here
    }

}

A: The Salesforce Record Locking Cheat Sheet is incredibly useful for troubleshooting this type of issue.
It appears to me that what is happening is your Contact is being briefly locked as a result of inserting either a Task (which is the default behavior if you do not call setSaveAsActivity(false) and causes locking of the records for the Task's WhoId, WhatId, and the related Account) or an EmailMessage, if using Enhanced Email.
Because you're performing this email send in a future method, I am going to speculate that the code calling the future method is making updates to the Contact records. Because the future method is running concurrently with this code, which may be non-bulkified or require a lot of processing time, you're seeing collisions between the two locks that are required. That's the root cause of the row locking error - two parallel processes trying to modify the Contact or modify/insert a qualifying child object of Contact at the same time. The record locking cheat sheet helps clarify which child objects can cause this situation.
It's not obvious without understanding the context in which this code is being called what the best approach is to fix it. One approach could be to move the email sending code out of the future method and run it synchronously, after the other processing takes place, or to fire the future method at the very end of the original processing.


text:
Q: xubuntu 12.04 can't change desktop background/wallpaper permanently If I change the desktop background (wallpaper) via right-click on desktop => desktop settings => single image, and select another background image from the list, or add a photo of my own (via the "+" symbol), I can actually change the background image, but after logging out or restarting, the wallpaper is always reset to the original xubuntu 12.04 background.
So, basically, I can't find a way to permanently change the desktop background.
Any ideas?

A: Because of the way Xfce is built, if you change settings and do not save session, the changes are not saved. It is not automatic. Menu -> Log out -> save session must be checked.

A: I also encountered this problem but in Ubuntu 14.04.3: right-click on desktop>change desktop settings>add own image using + and "span" it across my two monitors. After logging out, then logging in again, I saw that the background was saved but not after restarting the computer.
I'm new in using Ubuntu but somehow know a bit about Linux and was able to set my first Ubuntu install yesterday (after deciding to leave Windows).
So, here's my guess: my wallpaper is not being found when I login because the image is in an internal hard disk drive that is probably not mounted upon login.
I copied my wallpaper from the unmounted HDD to somewhere inside my home folder (e.g. ~\Pictures\wallpapers\image.jpg) and set this image as my desktop background, and my problem was solved.
I hope this helps someone similar to my case. This is my first time posting in Ask Ubuntu, so I hope I'm not violating some rules such as necromancy. ^_^

redpajama_set_name: RedPajamaStackExchange


text:
Q: Web API DbGeography Hangs Forever I have an entity- GeoEntity- that has a DbGeography property. In my Web Api, I have a POST endpoint that allows you to add new GeoEntities.
Entity-
public class GeoEntity {

  [JsonProperty("point")]
  [NotMapped]
  public GeoPoint Point { get; set; }

  [JsonIgnore]
  public DbGeography Location {

    get
    {
      // Breakpoint A
      return DbGeography.FromText($"POINT({Point.Longitude} {Point.Latitude})", 4326);
    }

    set
    {
      Point.Latitutde = value.Latitide;
      Point.Longitude = value.Longitude;
    }

  }

}

public class GeoPoint {

  public double Latitude { get; set; }

  public double Longitude { get; set; }

}

API -
[HttpPost]
[Route("")]
public async Task<IHttpActionResult> Add(GeoEntity entity)
{
  // Breakpoint B
  var newGeo = _geoService.Add(entity);
  return Ok(newGeo);
}

When I send the following post body-
{
  "point": {
    "latitude": 10,
    "longitude": 10
  }
}

I get stuck on Breakpoint A. When I continue from that endpoint, I never arrive at Breakpoint B and the http request is stuck Pending forever.
If I try stepping over, nothing happens.
I've captured the FromText result to a temporary var x to make sure it wasn't getting stuck trying to parse- and sure enough- it is not getting stuck trying to parse. The DbGeography object is created just fine.
If I return null in that get: get { return null; } I do arrive at Breakpoint B. But obviously my data is lost.
Any ideas why returning an actual DbGeography object causes the request to hang forever while returning null does not?

A: Serializer trouble
Based on your question, the Breakpoint A should never even get hit in the first place, because you are explicitly telling your serializer to ignore it, where it is obviously not doing so.

It is very likely to be your serializer trying to serialize the property Location of type DbGeography.

Simply, your serializer is not ignoring it and trying to retrive the value to serialize it. Which is not your intent based on the decorator you have provided.
Note:
Depending on your serializer, you make need to use one of the following attributes/decorators
 // using System.Web.Extensions;
 // using System.Web.Script.Serialization;

 [IgnoreDataMember]
 [ScriptIgnore]
 [JsonIgnore]
 public DbGeography Location { ... }

Alternative is to use DataContract and DataMember
[DataContract]
public class Computer
{
    // included in JSON
    [DataMember]
    public GeoPoint Point { get; set; }

    // ignored
    public DbGeography Location { get; set; }
}

If for whatever reason you are trying to serialize it... Then you will need to verify that the implementation of DbGeography.FromText() and it's return type (DbGeography) is object is actually "serialize-able".


text:
Q: Sending mail without client Android public class MainActivity extends Activity implements View.OnClickListener {

    Session session=null;
    ProgressDialog pdialog=null;
    Context context=null;
    EditText reciep,sub,msg;
    String rec,subject,textMessage;
    Button login;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        context = this;

        login = (Button) findViewById(R.id.btn_submit);
        reciep = (EditText) findViewById(R.id.et_to);
        sub = (EditText) findViewById(R.id.et_sub);
        msg = (EditText) findViewById(R.id.et_text);

        login.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        rec=reciep.getText().toString();
        subject=sub.getText().toString();
        textMessage=msg.getText().toString();

        Properties props=new Properties();
        props.put("mail.smtp.host","smpt.gmail.com");
        props.put("mail.smtp.socketFactory.port","465");
        props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.auth","true");
        props.put("mail.smtp.port","465");
        props.put("mail.smtp.socketFactory.port", "465");
        props.put("mail.smtp.socketFactory.class",
                "javax.net.ssl.SSLSocketFactory");
        props.put("mail.smtp.socketFactory.fallback", "false");
        props.setProperty("mail.smtp.quitwait", "false");

       session=Session.getDefaultInstance(props,new Authenticator(){
           protected    PasswordAuthentication getPasswordAuthentication()
           {
               return new PasswordAuthentication("example@gmail.com","password");
           }
        });

        pdialog=ProgressDialog.show(context,"","Sending mail....",true);
        RetreiveFeedTask task=new RetreiveFeedTask();
        task.execute();
    }

        class RetreiveFeedTask extends AsyncTask<String,Void,String> {

            @Override
            protected String doInBackground(String... strings) {

                try{
                    Message message=new MimeMessage(session);
                    message.setFrom(new InternetAddress("example@gmail.com"));
                    message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(rec));
                    message.setSubject(subject);
                    message.setContent(textMessage,"text/html;charset=utf-8");
                    Transport.send(message);

                }catch (MessagingException e){
                    e.printStackTrace();
                }
                catch (Exception e){
                    e.printStackTrace();
                }

                return null;
            }

            @Override
        protected void onPostExecute(String result) {
            pdialog.dismiss();
            reciep.setText("");
            msg.setText("");
            sub.setText("");
            Toast.makeText(getApplicationContext(), "Message Sended", Toast.LENGTH_SHORT).show();
        }
    }

}

It shows a fatal exception. Can you help?
08-09 12:18:53.957 23203-23203/com.example.bathri.mail D/Dialog: show
08-09 12:18:53.979 23203-23323/com.example.bathri.mail E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #4
 Process: com.example.bathri.mail, PID: 23203
 java.lang.RuntimeException: An error occured while executing doInBackground()
     at android.os.AsyncTask$3.done(AsyncTask.java:304)
     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
     at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
     at java.lang.Thread.run(Thread.java:818)
  Caused by: java.lang.VerifyError: Rejecting class javax.mail.internet.MimeMessage because it failed compile-time verification (declaration of 'javax.mail.internet.MimeMessage' appears in /data/data/com.example.bathri.mail/files/instant-run/dex/slice-slice_4-classes.dex)
     at com.example.bathri.mail.MainActivity$RetreiveFeedTask.doInBackground(MainActivity.java:92)
     at com.example.bathri.mail.MainActivity$RetreiveFeedTask.doInBackground(MainActivity.java:85)
     at android.os.AsyncTask$2.call(AsyncTask.java:292)
     at java.util.concurrent.FutureTask.run(FutureTask.java:237)
     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
     at java.lang.Thread.run(Thread.java:818)


text:
Q: Change of basis such that the line $\ell=\{tx:t\in\mathbf{R}\}$ passes through the origin and $(1,0,\ldots,0)$ Let $V$ be a vector space with $\dim V=n$, and let $x$ be a vector in $V$. Let $\ell=\{tx:t\in\mathbf{R}\}$. Denote $x=(x_1,\ldots,x_n)$. Assuming that the representation of the line $\ell$ is given with respect to the standard basis, I would like to find a change of basis from the standard basis $B$ to $B'$ such that $[x]_{B'}=(1,0,\ldots,0)$, i.e. the line $\ell$ is rotated such that it passes through the origin when $t=0$ and the unit vector $(1,0,\ldots,0)$ when $t=1$. I need help finding a new basis $B'$ that satisfies this condition.
My thoughts so far: The new basis $B'$ must contain the vector $x$; since any vector can be built as a unique linear combination of the basis vectors, we would then have:
$$[x]_{B'}=a_1x+\cdots=(1,0,\ldots,0)\implies a_1=1,a_i=0\,\forall i>1$$
Now the trouble is just finding $n-1$ other basis vectors all linearly independent from $x$, and I am not entirely sure how to go about this.
I am fairly new to linear algebra so my experience in this field is limited. Any hints on how to go about finding a suitable new basis $B'$? Thanks in advance.


text:
Q: Why is a folder in Mail favourites greyed out and how to reactivate it? In the favourites section of Mail (in screenshot at location (1)), a folder is greyed out. It cannot be selected, also nothing happens if I hover over it. What could be the reason? Please note, the folder was before in another section ("On my Mac", (2)), I probably moved it to the favourites section by accident. Also I cannot drag it back to any of the non-favourite sections.
Searching for this kind of problem was unfortunately not successful.


text:
Q: check a range with switch/case in fish shell Is something like this possible with fish? i.e.
switch $var
  case a-z
    do something
  case "*"
    do something else
end

case "*"works fine, but case a-zdoesn't trigger.
I also tried case [ a-z ] but no joy.

A: The fish shell has not, for some reason, implemented character sets. Assuming you're using the latest version, use the string command
if string match --quiet --regex '[a-z]' $var >/dev/null
    echo $var contains a letter
else
    echo $var has no letters
end

I'm using regex matching due to the minimal glob patterns in fish


text:
Q: How to determine which web service should be used alongside php to call the pastebin api? I want to develop an app using the api provided by pastebin.com , using php . What I am not able to figure out is which web service like SOAP , etc , should be used to do this work ?

A: The documentation says to submit a POST request, which means this is a REST-ful HTTP interface. No SOAP, no WSDLs, just HTTP like web browsers work.
All you need is some code capable of sending HTTP requests.
In PHP, the simplest one that comes with most installs is the cURL library.
Example of sending a POST is in the second comment of the manual page:
http://www.php.net/manual/en/function.curl-exec.php


text:
Q: Capturar evento "Save work item" no TFS - Visual Studio 2015 Bom dia pessoal. Tudo bem?
Eu utilizo o Visual Studio 2015 para acessar os Work Items do TFS e estou procurando uma ferramenta que armazene algumas informações especificas das atividades em uma planilha Excel e, ao finalizar um Work Item, envie um e-mail com formatação específica para alguns destinatários.
Dei uma pesquisada e vi que as configurações do TFS dão suporte para o envio de e-mail, isso só tem que ser configurado... Porém não achei nada que atenda a questão da planilha, então pensei em desenvolver um add-in que faça as duas coisas!
Alguém saberia me indicar alguma ferramenta que tenha essas funcionalidades ou o que eu poderia pesquisar para começas a desenvolver a minha própria?
Desde já agradeço.

A: Ao invés de armazenar informações específicas das atividades em uma planilha Excel, por que não armazenar nos próprios Work Items?
É possível customizá-los para adicionar campos e até mesmo alterar o workflow. Então é só disparar o envio de um email baseado nas informações. Você pode utilizar os web hooks e integrações, como você está em uma versão antiga, recomendo fazer o update para o 2018 Update 2 e utilizar várias features novas.

A: 1) Instalar o "TFS Office Integration Installer":
https://go.microsoft.com/fwlink/?LinkId=626605
2) No excel você pode se conectar em uma consulta do TFS:


text:
Q: Java Rendering 2D or 3D, what & how? I feel more comfortable when I have some task, dealing with Swing Rather than other topics.
Thus, When I read one of this case I'm a bit confused.
Preview: Click Here.
I recall this is about the java 2d topics, in which the shape (oval, line, etc) lessons are covered.
I'm thinking there must be a library for achieving the main result.

*

*But how about the coordinate for making a curve with the coordinate,
what's that different layer? -pic 1 on upper box

*What are the topics needed to render this image? -pic 1 & 2 both
boxes

*Is there any thread discussing about this matter, if so, which one?


text:
Q: Xamarin iOS: Hard coding a specific location in CLGeocoder Api I am trying to pass a specific address in my geolocation. But
CLGeocoder.GeocodeAddressAsync("46 Grosvenor Pl, London SW1X 7EQ, United Kingdom");
But I am getting Geocoding Error. Can anyone kindly confirm if the address format is right? I even tried with out postcode, but failing for the same reason.

A: Code:
Task.Run(async () =>
{
    var geoCoder = new CoreLocation.CLGeocoder();
    var placemarks = await geoCoder.GeocodeAddressAsync("46 Grosvenor Pl, London SW1X 7EQ, United Kingdom");
    foreach (var placemark in placemarks)
    {
        System.Diagnostics.Debug.WriteLine(placemark);
    }
});

Results:
46 Grosvenor Place<GEOMapItemStorage: 0x79bdf890> {
    placeData =     {
        component =         (
                        {
                "cache_control" = CACHEABLE;
                "start_index" = 0;
                status = "STATUS_SUCCESS";
                timestampFirstSeen = "485089873.024917";
                ttl = 2592000;
                type = "COMPONENT_TYPE_ENTITY";
                value =                 (
                                        {
                        entity =                         {
                            "is_disputed" = 0;
                            name =                             (
                                                                {
                                    locale = "en-US";
                                    "string_value" = "46 Grosvenor Place";
                                }
                            );
                            type = ADDRESS;
                        };
                    }
                );
                "values_available" = 1;
                version = 1;
                "version_domain" =                 (
                    apple,
                    fwdgeo,
                    GB
                );
            },
                        {
                "cache_control" = CACHEABLE;
                "start_index" = 0;
                status = "STATUS_SUCCESS";
                timestampFirstSeen = "485089873.024917";
                ttl = 2592000;
                type = "COMPONENT_TYPE_PLACE_INFO";
                value =                 (
                                        {
                        "place_info" =                         {
                            center =                             {
                                lat = "51.498251";
                                lng = "-0.1474483";
                            };
                            timezone =                             {
                                identifier = "Europe/London";
                            };
                        };
                    }
                );
                "values_available" = 1;
                version = 1;
                "version_domain" =                 (
                    apple,
                    fwdgeo,
                    GB
                );
            },
                        {
                "cache_control" = CACHEABLE;
                "start_index" = 0;
                status = "STATUS_SUCCESS";
                timestampFirstSeen = "485089873.024917";
                ttl = 2592000;
                type = "COMPONENT_TYPE_ROAD_ACCESS_INFO";
                value =                 (
                                        {
                        "access_info" =                         {
                            "road_access_point" =                             (
                                                                {
                                    drivingDirection = "ENTRY_EXIT";
                                    isApproximate = 1;
                                    location =                                     {
                                        lat = "51.4981067";
                                        lng = "-0.1472507";
                                    };
                                    walkingDirection = "ENTRY_EXIT";
                                }
                            );
                        };
                    }
                );
                "values_available" = 1;
                version = 1;
                "version_domain" =                 (
                    apple,
                    fwdgeo,
                    GB
                );
            },
                        {
                "cache_control" = CACHEABLE;
                "start_index" = 0;
                status = "STATUS_SUCCESS";
                timestampFirstSeen = "485089873.024917";
                ttl = 2592000;
                type = "COMPONENT_TYPE_BOUNDS";
                value =                 (
                                        {
                        bounds =                         {
                            "map_region" =                             {
                                eastLng = "-0.1469381274878062";
                                northLat = "51.49856860315036";
                                southLat = "51.49793339463645";
                                westLng = "-0.1479584796223861";
                            };
                        };
                    }
                );
                "values_available" = 1;
                version = 1;
                "version_domain" =                 (
                    apple,
                    fwdgeo,
                    GB
                );
            },
                        {
                "cache_control" = CACHEABLE;
                "start_index" = 0;
                status = "STATUS_SUCCESS";
                timestampFirstSeen = "485089873.024917";
                ttl = 2592000;
                type = "COMPONENT_TYPE_ADDRESS";
                value =                 (
                                        {
                        address =                         {
                            "known_accuracy" = POINT;
                            "localized_address" =                             (
                                                                {
                                    address =                                     {
                                        formattedAddressLine =                                         (
                                            "46 Grosvenor Place",
                                            London,
                                            "SW1X 7EQ",
                                            England
                                        );
                                        structuredAddress =                                         {
                                            administrativeArea = England;
                                            areaOfInterest =                                             (
                                                "Great Britain"
                                            );
                                            country = "United Kingdom";
                                            countryCode = GB;
                                            dependentLocality =                                             (
                                                Belgravia
                                            );
                                            fullThoroughfare = "46 Grosvenor Place";
                                            geoId =                                             (
                                            );
                                            locality = London;
                                            postCode = "SW1X 7EQ";
                                            subAdministrativeArea = London;
                                            subLocality = Belgravia;
                                            subThoroughfare = 46;
                                            thoroughfare = "Grosvenor Place";
                                        };
                                    };
                                    language = "en-US";
                                }
                            );
                        };
                    }
                );
                "values_available" = 1;
                version = 1;
                "version_domain" =                 (
                    apple,
                    fwdgeo,
                    GB
                );
            },
                        {
                "cache_control" = CACHEABLE;
                "start_index" = 0;
                status = "STATUS_SUCCESS";
                timestampFirstSeen = "485089873.024917";
                ttl = 2592000;
                type = "COMPONENT_TYPE_RATING";
                "values_available" = 0;
                version = 1;
                "version_domain" =                 (
                    apple,
                    fwdgeo,
                    GB
                );
            },
                        {
                "cache_control" = CACHEABLE;
                "start_index" = 0;
                status = "STATUS_SUCCESS";
                timestampFirstSeen = "485089873.024917";
                ttl = 2592000;
                type = "COMPONENT_TYPE_HOURS";
                "values_available" = 0;
                version = 1;
                "version_domain" =                 (
                    apple,
                    fwdgeo,
                    GB
                );
            },
                        {
                "cache_control" = UNCACHEABLE;
                status = "STATUS_FAILED";
                timestampFirstSeen = "485089873.024917";
                type = "COMPONENT_TYPE_TRANSIT_INFO";
            },
                        {
                "cache_control" = UNCACHEABLE;
                status = "STATUS_FAILED";
                timestampFirstSeen = "485089873.024917";
                type = "COMPONENT_TYPE_TRANSIT_SCHEDULE";
            },
                        {
                "cache_control" = CACHEABLE;
                "start_index" = 0;
                status = "STATUS_SUCCESS";
                timestampFirstSeen = "485089873.024917";
                ttl = 2592000;
                type = "COMPONENT_TYPE_FLYOVER";
                "values_available" = 0;
                version = 1;
                "version_domain" =                 (
                    apple,
                    fwdgeo,
                    GB
                );
            },
                        {
                "cache_control" = CACHEABLE;
                "start_index" = 0;
                status = "STATUS_SUCCESS";
                timestampFirstSeen = "485089873.024917";
                ttl = 2592000;
                type = "COMPONENT_TYPE_AMENITIES";
                "values_available" = 0;
                version = 1;
                "version_domain" =                 (
                    apple,
                    fwdgeo,
                    GB
                );
            },
                        {
                "cache_control" = CACHEABLE;
                "start_index" = 0;
                status = "STATUS_SUCCESS";
                timestampFirstSeen = "485089873.024917";
                ttl = 2592000;
                type = "COMPONENT_TYPE_STYLE_ATTRIBUTES";
                "values_available" = 0;
                version = 1;
                "version_domain" =                 (
                    apple,
                    fwdgeo,
                    GB
                );
            },
                        {
                "cache_control" = CACHEABLE;
                "start_index" = 0;
                status = "STATUS_SUCCESS";
                timestampFirstSeen = "485089873.024917";
                ttl = 2592000;
                type = "COMPONENT_TYPE_TRANSIT_INCIDENT";
                "values_available" = 0;
                version = 1;
                "version_domain" =                 (
                    apple,
                    fwdgeo,
                    GB
                );
            },
                        {
                "cache_control" = CACHEABLE;
                "start_index" = 0;
                status = "STATUS_SUCCESS";
                timestampFirstSeen = "485089873.024917";
                ttl = 2592000;
                type = "COMPONENT_TYPE_TEXT_BLOCK";
                "values_available" = 0;
                version = 1;
                "version_domain" =                 (
                    apple,
                    fwdgeo,
                    GB
                );
            },
                        {
                "cache_control" = CACHEABLE;
                "start_index" = 0;
                status = "STATUS_SUCCESS";
                timestampFirstSeen = "485089873.024917";
                ttl = 2592000;
                type = "COMPONENT_TYPE_FACTOID";
                "values_available" = 0;
                version = 1;
                "version_domain" =                 (
                    apple,
                    fwdgeo,
                    GB
                );
            },
                        {
                "cache_control" = CACHEABLE;
                "start_index" = 0;
                status = "STATUS_SUCCESS";
                timestampFirstSeen = "485089873.024917";
                ttl = 2592000;
                type = "COMPONENT_TYPE_TRANSIT_ATTRIBUTION";
                "values_available" = 0;
                version = 1;
                "version_domain" =                 (
                    apple,
                    fwdgeo,
                    GB
                );
            },
                        {
                "cache_control" = CACHEABLE;
                "start_index" = 0;
                status = "STATUS_SUCCESS";
                timestampFirstSeen = "485089873.024917";
                ttl = 2592000;
                type = "COMPONENT_TYPE_RESULT_SNIPPET";
                "values_available" = 0;
                version = 1;
                "version_domain" =                 (
                    apple,
                    fwdgeo,
                    GB
                );
            }
        );
        referenceFrame = WGS84;
        "result_provider_id" = 0;
    };
}
Thread finished: <Thread Pool> #4


text:
Q: big query BadRequest: 400 Unrecognized name after running a query I'm running a BQ query using Python. I am trying to pull the listed columns. The date format is yyyy-mm-dd 00:00:00 so I changed it to the needed date format. It works fine but the issue I'm having is with my WHERE statement. What I am trying to do is to just pull the last 7 days of my data.
The error is the following:
BadRequest: 400 Unrecognized name: date at [4:10]
Could someone point me in the right direction of where the mistake is coming from?
query_job = client.query(f"""
   SELECT sku, sku_unit_count, entity_id, revenue, CAST(order_date AS DATE) as date,
   unique_code, refunds
   FROM tables.revenue
   WHERE date >= DATE_ADD(CURRENT_DATE(), INTERVAL -7 DAY)
   LIMIT 5; """)

A: Use below
query_job = client.query(f"""
   SELECT sku, sku_unit_count, entity_id, revenue, CAST(order_date AS DATE) as date,
   unique_code, refunds
   FROM tables.revenue
   WHERE CAST(order_date AS DATE) >= DATE_ADD(CURRENT_DATE(), INTERVAL -7 DAY)
   LIMIT 5; """)


text:
Q: Trying to count occurrences of a single character line by line in python I have a txt file that I am trying to count occurrences of specific characters line by line. This is the code I'm trying currently and the results I've received. When I use the same code without the file and add part of the data as a string I get the expected result.
Example piece of a line in the text file = "ADSFABASDFMMASDF"
from collections import Counter

file_handle = open("Input.txt", "r")

protein = file_handle.readlines()

#variable defining for rewrite

proteinout = ""

for line in protein :
        counted = Counter(protein)
        proteinout += line + str(counted["M"])

print (proteinout)

file_handle.close()

file_handle = open(output.txt", "w")

file_handle.write(proteinout)

file_handle.close()

Input:
Data1
Data2
Data3

Expected Output:
Data1 12
Data2 25
Data3 38

Actual Output:
Data1 0
Data2 0
Data3 0


text:
Q: How to alter a table in SQLite after running a pragma I am attempting to check a database that already exist and querying through a table to see how many columns it has by calling this.
    if(res.toString().contains('Orchestration_Time')){
      await _database.execute('PRAGMA table_info(Orchestration_Time)'
    );

after this bit of code runs I need a way to use the information I get back to then determine if I should alter the table or not
'ALTER TABLE Orchestration_Time ADD COLUMN dashboard_area TEXT;'

but I cannot figure out how to access the data that the PRAGMA statement returns.
I'd like to wrap it in an 'if' statement and run the alter table if the PRAGMA is less than 5.


text:
Q: Is it possible to retrieve the last file of a folder in C language without using popen? it's been a long time since I touched C. I'm trying to get the name of the last file created in a folder. In a daemon I get the live file number with scandir, however I can not get the timestamp of the files in the dirent.
Do you have an idea ? I do not want to use popen () and a bash command.
(thank you for your answers and sorry for the approximate english)
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <cjson/cJSON.h>
#include <curl/curl.h>
#include <dirent.h>
#include <errno.h>
#include <time.h>

int main(int argc, char *argv[] ){

  int pid = fork();
  if (pid < 0){
      perror("Echec lors du clonage.");
      exit(-1);
   }
    else if (pid > 0){
          printf("Service lancé sur le PID : %d \n", pid);
          exit(0);
      }

      time_t debut, fin, difference;
      int numOfFiles = 0, oldNumOfFiles = 0, i  = 0;
      char *path = "/home/ackbar/Documents/watchmen/testfolder";
      debut = time (NULL);

      while(1 == 1){
          i++;
          struct dirent **fileListTemp;
          int numOfFiles = scandir(path, &fileListTemp, NULL, alphasort);

          if((numOfFiles > oldNumOfFiles) && (oldNumOfFiles == 0)){
            printf("first -\n");
            oldNumOfFiles  = numOfFiles;
          }
          else if(numOfFiles < oldNumOfFiles){
            printf("delete -\n");
            oldNumOfFiles  = numOfFiles;

          }
          else if(numOfFiles > oldNumOfFiles){

              printf("%d -- add %d\n", oldNumOfFiles, numOfFiles);
              oldNumOfFiles  = numOfFiles;
          }

          fin = time (NULL);
          difference = difftime (fin, debut);
          if((int)difference > 120){
            printf("fin\n");
            break;
          }

   }
}


text:
Q: How to get an agent user capability in TFS Build task? I've declared a user capability named "MyCapability" in a TFS 2015 build agent with a path as value. How can I get this value in the powershell script of my build task ?
$env:MyCapability and $MyCapability don't work.

A: You cannot access the capabilities from PowerShell through a variable unfortunately.
You could use the Rest Client to connect back to TFS and read the Build Agent as well as the Build Definition to read out the configured values. This will require access to the OAuth token, which can be configured through a checkbox on the Build Definition's configuration page.


text:
Q: How to display the inventory quantity of a specific variable on the product page? I am creating a form, and I would like to display the amount of inventory remaining for a variable product in a normal text field created with Jet-Engine within the same product or product page.
I have tried adding

*

*_product_attributes

*_stock

*_stock_status

*instock

but none of them show the value.
How do I tell the instock to show the remaining amount of inventory of the variation_id.
I don't know if I should create an add_filter or an add_action and associate it with a custom field to be replaced by the new instock_variation_id value.
I have installed JSM's Show Post Metadata plugin which shows all the product fields but it does not show the fields that each variable has, I have 7 variables of a single product.
Could you help me to find the solution?

*

*I am using Elementor Pro

*The theme is Hello from Elementor

*JetWooBuilder as a customization layer for WooCommerce

A: Place the following function in your functions.php
//This hook will return stock qty under the variation selection
add_action('woocommerce_after_variations_table','show_variation_stock_qty');
function show_variation_stock_qty() {
    global $product;
    foreach ( $product->get_available_variations() as $key ) {
        $variation = wc_get_product( $key['variation_id'] );
        $stock = $variation->get_availability();
        $stock_string = $stock['availability'] ? $stock['availability'] : __( 'In stock', 'woocommerce' );
        $attr_string = array();
        foreach ( $key['attributes'] as $attr_name => $attr_value ) {
            $attr_string[] = $attr_value;
        }
        echo '<br/>' . implode( ', ', $attr_string ) . ': ' . $stock_string;
    }
}

This will return something like:
blue: 6 in stock
red: 9 in stock
green: 4 in stock


text:
Q: ICICI IMPS payment api not working on postman I checked the ICICI IMPS api in postman, but it throws

Error while sending request: 'Failed to execute' set request header on XMLhttprequest, API key is not a valid HTTP header field name

It's working on icici developer portal, I used the same params and headers in postman.
API url: https://developerapi.icicibank.com:8443
Params:
{
  "localTxnDtTime": "20200121160503",
  "beneAccNo": "057001510618",
  "beneIFSC": "ICIC0000570",
  "amount": "1",
  "tranRefNo": "17df6a44e57f436492f66f6",
  "paymentRef": "FTTransferP2A",
  "senderName": "APIGATEWAY",
  "mobile": "7588215033",
  "retailerCode": "rcode",
  "passCode": "d1118d6f9fe94696b4b1e1a0980bb396",
  "bcID": "IBCOri00058"
}

Header values:
API key: xxxxxxx,
Priority:000000

A: I think the APIs mentioned in the developer portal are just for documentation and reference purposes. They'll share the documentation on how to send the requests. In order to hit their APIs, your IP needs to whitelisted by them and then they'll share some credentials like API key, passCode and bcID. Only after that you'll be able to hit their APIs and test. Also, your requests need to end to end encrypted using the ICICI public key (which will be shared by the ICICI team) and agreed upon encryption algorithm.


text:
Q: D3.nest() is finished Hi I'm trying to use nest()in D3.js like this.
var data = d3.nest()
  .key(function(d){
    return d.ledgerID;
  })
  .rollup(function(v){

    return {
      debit: d3.sum(v, function(b){
        return b.debit;
      }),
      credit: d3.sum(v, function(b){
        return b.credit;
      }),
    }

  })
  .entries(transactionEntries)

And then directly after run a loop on data
like this
    var data = d3.nest()
        .key(function(d){
            return d.ledgerID;
        })
        .rollup(function(v){

            return {
                debit: d3.sum(v, function(b){
                    return b.deb;
                }),
                credit: d3.sum(v, function(b){
                    return b.cre;
                }),

            }
        })
        .entries(transactionEntries)

     for(var i = 0; i < data.length; i++){
           console.log(data[i]);
     }

But it seems like the loop starts before nest()is completely finished which seems possible to me, so my first thought was if there is a callback or something like that I can use when nest() is finished?
Or am I going about this the wrong way?


text:
Q: Using family sharing, can a child account do in-app purchases without approval? I recently added my son to our "iTunes family"; I have set his Apple ID up as a child account and have checked the "Ask to Buy: require approval from parent for all purchases ..." checkbox.
Yet today I received an app store invoice for an in-app purchase my son made in one of the games he plays. Do in-app purchases not fall under the "require approval from parent" rule?
(I know that I can prevent in-app purchases by configuring "Restrictions" on his iPad, but that is not the point)

A: In app purchases do fall under the same rule, however if your Apple ID is signed into, say a family computer, he could approve it himself on that device.


text:
Q: Glue PySpark Error: pyWriteDynamicFrame. org.apache.parquet.column.values.dictionary.PlainValuesDictionary$PlainLongDictionary I have been over 2 days debugging and trying to figure out what's going on, without success. AWS Support has not been able to help me here either, so let me explain.
I have a table called provisioned.customer which is defined on Glue. This table is on provisioned database.

I have another 2 tables, curated.customer_consents and curated.customer with their respective schemas:

I have set all data types to string for easing the process.
Now I have a Glue job 3.0 with PySpark, and the following code:
# more imports...
import pyspark.sql.types as T
from awsglue.dynamicframe import DynamicFrame
from pyspark.sql import functions as F

def fudf(val):
    return functools.reduce(lambda x, y: x+y, val)

flattenUdf = F.udf(fudf, T.StringType())

customer_df = spark.read.table('curated.customer')
core_customer_consents_df = spark.read.table('curated.core_customer_consents')

core_customer_consents_df = core_customer_consents_df.groupBy("tscid").agg(F.collect_list('purpose').alias('__purposes__'))

merged = customer_df.join(core_customer_consents_df, ['tscid'], how='inner')
merged = merged.select("*", flattenUdf("__purposes__").alias("cirrus_purposes"))
merged = merged.select([c for c in merged.columns if c not in {'__purposes__'}])
logger.info(merged)

glueContext.write_dynamic_frame.from_catalog(
    frame=DynamicFrame.fromDF(merged, glueContext, "a"),
    database = 'provisioned',
    table_name = 'customer',
    transformation_ctx = "datasource0",
)

This is the output of the logger.info:
2022-06-15 08:35:26 INFO logger: DataFrame[tscid: string, first_name: string, last_name: string, gender: string, birthdate: string, qualification: string, country: string, estimated_annual_earning: string, cirrus_purposes: string]

But after executing this, I face the following issue:
An error occurred while calling o149.pyWriteDynamicFrame. org.apache.parquet.column.values.dictionary.PlainValuesDictionary$PlainLongDictionary

But I have checked schema matching and they are exactly the same (see logger.info output) and even in the same column order. Also in my local this does generate the data frame accordingly. So I don't know what's really going on.
Have you faced this? Thank you in advance.

A: I have found the problem. I was generating from CSV using pyarrow parquet files. Column estimated_annual_earning was being generated as long. So whenever I was reading it, apparently no issues due to the lazy nature, but it gave this error when the action (insert) was called, due to a mismatch between data type when reading curated.customer.
Solution: generate parquet with the same data types as what you have in your glue metastore.


text:
Q: How to toggle an item's status with JavaScript in Ruby on Rails in index view I have a model in Ruby on Rails (Rails 3) that has a "status" value. The status can either be on or off. In my index view for this model, I show the status for each item (just basic text showing either "on" or "off"). I want users to be able to click on this status field for each item and then it must toggle, without having to re-render the page. So it basically acts like a type of on/off switch.
When I toggle the on/off switch for the specific object, I need to call a controller action to perform some actions. Then I also need to update the view to change "on" to "off" or "off" to "on".
JavaScript would be the way to go, I suppose. I'm not sure if I'll need ajax as well. I have been looking for tutorials with a very basic step-by-step explanation of how to add JavaScript to my Ruby on Rails application. I am a complete newbie to JavaScript in RoR. Most of the tutorials I found assumes a basic background knowledge of JQuery/Protocol/Ajax/Javascript or it goes off on tangents.
Can someone perhaps recommend a good, basic and uncluttered tutorial for getting started with JavaScript in Ruby on Rails and/or give a basic outline as to how the mentioned functionality can be implemented?

A: Two ways to go.
The Rails way: the view helper form_for has an option :remote => true that will perform an ajax request.
Let say your model is called Car, and @car an instance of an existing object, you could do:
= form_for @car, :remote => true do |f|
  = f.hidden_field :status, true
  = f.submit_tag "On"

= form_for @car, :remote => true do |f|
  = f.hidden_field :status, false
  = f.submit_tag "Off"

Everything here is convention, so it would go to your cars#update action, where you would return Javascript to show / hide your forms. In that way you could toggle the On / Off forms with a jQuery show() and hide() methods.
http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-form_for
The plain jQuery way: use the same form but without the :remote => true option. The controller is the same as well, you will just return JSON instead (with a value saying if the update has been successful or not). Add your own javascript ($.ajax) on the client to update the object and toggle the html forms.
I tend to use the second option because I hate to return Javascript from the controller. I like to have all my Javascript related to one event in the same place.

A: First step.
In your controller action, have that action be able to respond to ajax like
class DocumentsController < ApplicationController
    respond_to :html, :js, :json
    def edit
        @document = current_user.documents.find(params[:id])
        respond_with @document, location: root_path
    end

Then you will create a *.js.erb file in your appropiate views controller, in this case in my app/views/documents and i'd call it edit.js.erb
Now in your js.erb file you will have some query that will manipulate that dom eleemnt you want.
Like when I call the edit action in my views, whether through a link or button or whatever, it will trigger the js.erb file.
This is one way.
Another way to do it (the rails way) is to add some jQuery action observers in your app/assets/javascript folder. These are static and are named *.js.coffee
These jQuery actions are probably the way you want to use it if the user is manipulating. Just add the jQuery for that dom element and it will be compiled and loaded into assets pipeline.
And there are many tutorials to learn how to do this, I recommend looking for up to date things as the ways to do all this changes in rails every 6 months.


text:
Q: redirect from domain in same folder to another domain this is the similar question but it's not working. I need help.
going from olddomain.com/samefolder to newdomain.com/samefolder. They are both in the same structure/server (i.e. somepath/olddomain and somepath/newdomain). I cant write to the somepath root but I can write in roots of olddomain and newdomain.
I only want this to work for one specific folder.


text:
Q: Not able to sort table view data in ascending order I have an table view which will populate some data. Now I need to sort my table view data in ascending order.
var SearchedobjectArray = [Objects]()

struct Objects {
    var looId : String!
    var looName : String
    var looImageUrl:String!
    var looCategoryType:String!
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier:"cell", for: indexPath) as? MyLooCell{
        cell.looImage.setShowActivityIndicator(true)
        cell.looImage.setIndicatorStyle(.gray)
        let imageURL = SearchedobjectArray[indexPath.row].looImageUrl

        if (imageURL?.isEmpty)! {
            let imageUrl = self.getDefaultImageForCategory(categoryName: SearchedobjectArray[indexPath.row].looCategoryType)
            cell.looImage.image = UIImage(named: imageUrl)
        } else {
            cell.looImage.sd_setImage(with: URL(string: SearchedobjectArray[indexPath.row].looImageUrl))
        }
        cell.looName.text = SearchedobjectArray[indexPath.row].looName
        let looCatType = SearchedobjectArray[indexPath.row].looCategoryType
    } else {
        return UITableViewCell()
    }
}

I tried with : let array = SearchedobjectArray.sorted(by: )
But I am not sure how can I sort this data with ascending order a to z. I tried with other sorted() also but not able to achieve.

A: When data is fetched in an array then you can simply sort the array on looName basis using the following code.
SearchedobjectArray = SearchedobjectArray.sorted(by: { $0.looName > $1.looName})
tableView.reloadData()

A: You need to sort your array of objects and then tableView.reloadData().  Here's a Playground example of how to sort your array:
import Cocoa

struct Objects {
    var looId : String!
    var looName : String
    var looImageUrl:String!
    var looCategoryType:String!
}

var SearchedobjectArray = [Objects]()

let c = Objects(looId: "Chase", looName: "Chase", looImageUrl: "Chase", looCategoryType: "Chase")
SearchedobjectArray.append(c)

let b = Objects(looId: "Bree", looName: "Bree", looImageUrl: "Bree", looCategoryType: "Bree")
SearchedobjectArray.append(b)

let a = Objects(looId: "Adam", looName: "Adam", looImageUrl: "Adam", looCategoryType: "Adam")
SearchedobjectArray.append(a)

print("Before sorting")
print(SearchedobjectArray)

// The real sorting is happening here...I guessed you wanted to sort by looName
SearchedobjectArray = SearchedobjectArray.sorted(by: { $0.looName < $1.looName })
print("After sorting")
print(SearchedobjectArray)


text:
Q: Magento 2: Any concern to share generated folder across containers? We are running Magento on Kubernetes, so every time we have some more traffic new pods/containers scale up and down multiple times a day.
We are seeing some weird things happening and it seems like the generated folder should be shared across containers.
We build the image used to bring the containers up, but it only contains the generated/metadata folder as we run di:compile as part of the docker image build.
We run the setup:upgrade on a separate container that we call post-deploy.
We are thinking about sharing the generated folder on EFS, is there any concern with this?
Thanks.

A: It seems like there wouldn't have any issue sharing the generated folder across containers, but for now we have decided to NOT share the generated folder.
We already run setup:di:compile when creating the docker image and that does the job to generated all files.
During our post-deploy we run setup:upgrade --keep-generated. When running --keep-generated it will maintain the generated files, but it will update the database schema.
The error we were seeing was due to permission issues with the generated folder.
The group didn't have write permission to the folder, we fix the permission before  running setup:di:compile and then fix it again to lock it up after the command is complete.


text:
Q: Fixed array initialization without implementing Copy or Default trait i want to make a 2D fixed size array that is going to be initialized in a for loop. This is the sample code (The Cell struct can not implement Copy or Default trait for some reason):
let mut cells: [[Cell; 20]; 20];
for i in 0..20 {
    for j in 0..20 {
        cells[i][j] = Cell::new(some_value_based_on_i_and_j);
    }
}

but then compiler gives this error:

use of possibly-uninitialized variable
So in order to assure the compiler that my array is fully initialized for at least 1 time; i change it to something like this:
let mut cells: [[Cell; 20]; 20] = [[Cell::new(default_value); 20]; 20];
for i in 0..20 {
    for j in 0..20 {
        cells[i][j] = Cell::new(some_value_based_on_i_and_j);
    }
}

(in fact i want to listen to the compiler and initialize all of the indices of my array with a default value like this pattern and then do my previous job):
 let a = [-12, 100] // means -> [default_value, repetition_or_also_length_of_the_array]

Then the compiler gives this error:

the trait bound [maze_maker::Cell; 20]: std::marker::Copy is not satisfied
the trait std::marker::Copy is not implemented for [maze_maker::Cell; 20]
note: the Copy trait is required because the repeated element will be copied
What should i do ): ?

A: The array_init crate may help you here, it lets you create an array either by giving it a function it will call repeatedly, or by collecting an iterator.

A: If you don't mind temporary allocation, you can make use of the fact that Vec<T> implements TryInto<[T; N]>, returning a run-time error if the length of the Vec doesn't fit the size of the array. It's not particularly elegant, but requires no unsafe:
let cells: [[Cell<usize>; 20]; 20] = (0..20)
    .map(|i| {
        (0..20)
            .map(|j| Cell::new(i + j))
            .collect::<Vec<_>>()
            .try_into()
            .unwrap()
    })
    .collect::<Vec<_>>()
    .try_into()
    .unwrap();

If you're ok with external crates, you can adapt the above to use arrayvec to avoid allocation:
let cells: [[Cell<usize>; 20]; 20] = (0..20)
    .map(|i| {
        (0..20)
            .map(|j| Cell::new(i + j))
            .collect::<ArrayVec<_, 20>>()
            .into_inner()
            .unwrap()
    })
    .collect::<ArrayVec<_, 20>>()
    .into_inner()
    .unwrap();

On the other hand, if you're already using external crates, then the array_init crate recommended by the other answer might be a better fit.


text:
Q: Lucene custom analyzer I am making search job site using Lucene, and coped with such problem. I need to search C#, .net so i need to use WhiteSpaceAnalyzer, but if i use it search will be case sensetive.
How can i make this case insensative? Now I see only one solution is to make own Analyzer. But i am new in Lucene, can you please help me with some sample of code for this. I made something that i think must work but it is not. Look
public sealed class NewWhitespaceAnalyzer : Analyzer
    {
        public override TokenStream TokenStream(System.String fieldName, System.IO.TextReader reader)
        {
            return new LowerCaseFilter(new WhitespaceTokenizer(reader));
        }

        public override TokenStream ReusableTokenStream(System.String fieldName, System.IO.TextReader reader)
        {
            Tokenizer tokenizer = (Tokenizer)GetPreviousTokenStream();
            if (tokenizer == null)
            {
                tokenizer = new WhitespaceTokenizer(reader);
                SetPreviousTokenStream(tokenizer);
            }
            else
                tokenizer.Reset(reader);
            return tokenizer;
        }
    }

If you would see mistake here please correct me.
If you have any other suggestions, you are wlcome.
Thanks for any help,
Dima.

A: Try this:
public sealed class NewWhitespaceAnalyzer : Analyzer
{
    public override TokenStream TokenStream(System.String fieldName, System.IO.TextReader reader)
    {
        return new LowerCaseFilter(new WhitespaceTokenizer(reader));
    }

    public override TokenStream ReusableTokenStream(System.String fieldName, System.IO.TextReader reader)
    {
        SavedStreams streams = (SavedStreams) GetPreviousTokenStream();
        if (streams == null)
        {
            streams = new SavedStreams();
            SetPreviousTokenStream(streams);
            streams.tokenStream = new WhiteSpaceTokenizer(reader);
            streams.filteredTokenStream = new LowerCaseFilter(streams.tokenStream);
        }
        else
        {
            streams.tokenStream.Reset(reader);
        }
        return streams.filteredTokenStream;
    }
}

A: There are 2 points:

*

*use LowerCaseFilter also in the ReusableTokenStream method.

*don't forget to use this custom Analyzer in both the query parsing and the document indexing.
enjoy.


text:
Q: Implementing a custom non-mapped property on entities I am currently developping an application which object model and persistence layer is built using the Entity Framework model designer.
One of the requirements I have is to provide a status to my entities that could let me know whenever they are in a "dirty" state (modified), when the status change occurs and, most important, working in a disconnected mode. So I started modifying the T4 template to add a IsDirty boolean property upon generation of those entities, added an event that is fired whenever IsDirty changes and added this.IsDirty = true in the xxxChanged methods of all scalar properties.
Everything works great when the entity is not attached to its context but when attached, whenever a property is changed, thus changing the IsDirty value to false, I receive this exception:

The property 'IsDirty' does not have a valid entity mapping on the
  entity object. For more information, see the Entity Framework
  documentation.

So what am I doing wrong here? I don't want this property to be mapped in my database as it is just an object status that only matters when the object is "alive". Is there an attribute I should use to decorate the IsDirty property? Or should I derive EntityObject and implement the status mechanism? Or maybe you have any better advice on how to implement this?
Thanks.

Edit: I am using Entity Framework 4.0 with EDM designer.
Here is the piece of code generated into every base entity:
private bool isDirty;
public event EventHandler DirtyStatusChanged;

public bool IsDirty
{
    get
    {
        return this.isDirty;
    }

    internal set
    {
        if (this.isDirty != value)
        {
            ReportPropertyChanging("IsDirty");
            this.isDirty = value;
            ReportPropertyChanged("IsDirty");
            ReportDirtyStatusChanged();
        }
    }
}

protected void ReportDirtyStatusChanged()
{
    var handler = this.DirtyStatusChanged;

    if(handler != null)
    {
        handler(this, EventArgs.Empty);
    }
}

A: I finally found the error myself. The problem lied inside my property setter. Instead of calling ReportPropertyChanged/ing I should have called OnPropertyChanged/ing.
ReportPropertyChanged/ing implies for the context to search for changes between the original and the current entity value but as this property is just a status object that has no mapping to a store, the concept of original value makes no sense, thus making the context failing to find a correct mapping for this property.
Using OnPropertyChanged/ing just fixed it.


text:
Q: CSS not behaving, 2 columns and 1 row spanning both columns I never have any luck with CSS. I have a dialog which is displayed when the user clicks a button. In this div there is an image, and 2 other divs (containing more elements).
It should all look like the following.

The second columns which contained "Applied Filters" should be on the right of the image, and span the width between the end of the image, and the end of the main container. But instead, it has gone under the image.
See JSFiddle here
Here is the HTML:

Applied Filters

dsadsa

CSS:
.filter_dialog {
    background-color:#333333;
    border:solid 1px #666666;
    display:inline-block;
    margin:0 auto;
    border-radius:15px;
}
.filter_dialog img {
    border-radius:15px 15px 0px 0px;
    float:left;
}
.applied_filters {
    float:left;
    background-color:#1a1a1a;
    width:100%;
}
.filters {
    background-color:#1a1a1a;
    height:8em;
    width:100%;
    border-radius:0px 0px 15px 15px;
    display:inline-block;
}

A: You'll need to set a fixed width on the two filters divs. I'd suggest wrapping them in one div with the fixed width, set to float: right, and then float the image left.

A: You'll need to define widths on the .filter-image and .applied-filter DIVs.  See this JSFiddle for an example:

applied

options

A: 100% width means 100% width of the nearest relative/absolute positioned PARENT so no that is not the way to do it.
Solutions:
A) The width of the "Applied Filters" and the image-width are always the same => add it a proper width so it could fit next to each other. could be done like:
img{ max-width: 75% } /*or proper px*/
.filterClass{ width: 24%; } /*or proper px*/

B) The image size is not fixed => use a javascript framework like jQuery to count the current image size and change the .filterClass's width like $('.filterClass').css('width', countedWidth);


text:
Q: Is there a way to have a rule in one object that references properties from a different object? I could not find any examples of this so I'm assuming it's not possible, but want to confirm.
I have a main schema that references other schemas:
https://www.jsonschemavalidator.net/s/4aLvXa4I
{
  "$defs": {
    "mainSchema": {
      "$id": "https://example.com/person.schema.json",
      "$schema": "https://json-schema.org/draft/2020-12/schema",
      "additionalProperties": false,
      "type": "object",
      "properties": {
        "objectOne": {
          "$ref": "#/$defs/objectOne"
        },
        "objectTwo": {
          "$ref": "#/$defs/objectTwo"
        }
      }
    },
    "objectOne": {
      "type": "object",
      "properties": {
        "checkThisValue": {
          "type": "string",
          "enum": [
            "one",
            "two",
            "three"
          ]
        }
      }
    },
    "objectTwo": {
      "type": "object",
      "properties": {
        "whenSettingThisValue": {
          "type": "string",
          "enum": [
            "A",
            "B",
            "C"
          ]
        }
      }
    }
  },
  "$ref": "#/$defs/mainSchema"
}

I want to define this rule:
IF objectOne.checkThisValue == one
THEN objectTwo.whenSettingThisValue MUST == A
Same for two=>B and three=>C

Is this possible somehow? How do I reference objectOne properties inside of objectTwo?
Edit
I tried to create an if rule for objectTwo that references objectOne here, but my syntax is wrong because it's not working. whenSettingThisValue is set to C and it's saying valid when it should be invalid: https://www.jsonschemavalidator.net/s/NNjEIhWW
    "objectTwo": {
      "type": "object",
      "properties": {
        "whenSettingThisValue": {
          "type": "string",
          "enum": [
            "A",
            "B",
            "C"
          ]
        }
      },
      "if": {
        "properties": {
          "objectOne": {
            "checkThisValue": {
              "const": "one"
            }
          }
        }
      },
      "then": {
        "properties": {
          "objectTwo": {
            "whenSettingThisValue": {
              "const": "A"
            }
          }
        }
      }
    }
  },

I also tried using a oneOf rule in mainSchema where both the subschemas are used, but it is not working either (this example should be invalid): https://www.jsonschemavalidator.net/s/WkmMasDC
"mainSchema": {
  "$id": "https://example.com/person.schema.json",
  "$schema": "https://json-schema.org/draft/2020-12/schema",
  "additionalProperties": false,
  "type": "object",
  "properties": {
    "objectOne": {
      "$ref": "#/$defs/objectOne"
    },
    "objectTwo": {
      "$ref": "#/$defs/objectTwo"
    }
  },
  "oneOf": [
    {
      "type": "object",
      "properties": {
        "objectOne": {
          "checkThisValue": {
            "const": "one"
          }
        },
        "objectTwo": {
          "whenSettingThisValue": {
            "const": "A"
          }
        }
      }
    }
  ]
},

Solution
Per answer my OneOf rule was malformed. This correctly checks a value in one object is set in response to another. I thought because I was referencing them in another schema with $ref I would have to do something special, but I don't.
https://www.jsonschemavalidator.net/s/HcVhrShk
  "oneOf": [
    {
      "type": "object",
      "properties": {
        "objectOne": {
          "properties": {
            "checkThisValue": {
              "const": "one"
            }
          }
        },
        "objectTwo": {
          "properties": {
            "whenSettingThisValue": {
              "const": "A"
            }
          }
        }
      }
    },
    {
      "type": "object",
      "properties": {
        "objectOne": {
          "properties": {
            "checkThisValue": {
              "const": "two"
            }
          }
        },
        "objectTwo": {
          "properties": {
            "whenSettingThisValue": {
              "const": "B"
            }
          }
        }
      }
    }
  ]
},

A: Yes you can. There is an if/then/else construct which takes schemas as its arguments, so you can define a rule "if property A exists with value X, then property B must exist with value Y" etc.
There are some examples here:
https://json-schema.org/understanding-json-schema/reference/conditionals.html#if-then-else
edit:
in your re-edit, change the oneOf clause to this:
  "oneOf": [
    {
      "type": "object",
      "properties": {
        "objectOne": {
          "properties": {
            "checkThisValue": {
              "const": "one"
            }
          }
        }
      }
    },
    {
      "type": "object",
      "properties": {
        "objectTwo": {
          "properties": {
            "whenSettingThisValue": {
              "const": "A"
            }
          }
        }
      }
    }
  ]


text:
Q: Kronecker-Weber does not apply Let $K=\mathbb{Q}(\sqrt{D})\neq \mathbb{Q}$. Show that $K$ has an abelian extension that is not contained in $K(\theta)$ for any root of unity $\theta$.
Hint: Find $u \in K $ such that $K(\sqrt{u})$ is not normal over $\mathbb{Q}$. If $\sqrt{u} \in K(\theta)$ for some root of unity $\theta$ then $K(\theta)$ is abelian over $\mathbb{Q}$ and every subfield is normal over $\mathbb{Q}$.
Suppose that $K$ has a abelian extension $L$  such that $L \subset K(\theta)$ for some root unity $\theta$.
If I put $u=\sqrt{D}$, then $L=K(\sqrt[4]{D})=\mathbb{Q}(\sqrt{D},\sqrt[4]{D} )$ is not normal over $\mathbb{Q}$. If $\sqrt[4]{D} \in K(\theta)$, then $L=K(\sqrt[4]{D}) \leqslant K(\theta) $, but $K(\theta)$ is normal over $\mathbb{Q}$ and any subfield of $K(\theta)$ is normal. This contradicts our assumption.
This is correct?
Thanks!

A: Set $u = a + b \sqrt{D}$.  We will show that we can choose $a,b \in \mathbb{Q}$ such that $L = K(\sqrt{u})$ is not normal over $\mathbb{Q}$.
Obviously we should not choose $u$ to be a square in $K$, so we can assume that [$L$:$\mathbb{Q}$]=4.
The conjugates of $\sqrt{u}$ are $\pm \sqrt{u}$ and $\pm \sqrt{u'}$, where $u' = a - b \sqrt{D}$.
If $L$ is normal, then $L$ contains $\sqrt{uu'}= \sqrt{a^2 - D b^2}$.  The extension $K_2 = \mathbb{Q}(\sqrt{a^2-Db^2})$ is in general different from $K = \mathbb{Q}(\sqrt{D})$ (they would only be equal for some special choices of $a$, $b$). Hence $L$ contains at least 2 distinct quadratic subextensions, and so the Galois group of $L$ is $C_2 \times C_2$, which means that $L$ contains exactly 3 quadratic subextensions: $K_1 = K$, $K_2 = \mathbb{Q}(\sqrt{a^2-Db^2})$, and a third one which we will call $K_3$.
Next, observe that the norms of $\sqrt{u}$ down to each of the $K_i$ are obtained by multiplying $\sqrt{u}$ by each of its other 3 conjugates (corresponding to the 3 non-identity elements of the Galois group).  These norms are:
$$\sqrt{u} \cdot -\sqrt{u} = -u = -(a+b \sqrt{D})$$
$$\sqrt{u} \cdot \sqrt{u'} = \sqrt{a^2 - Db^2}$$
$$\sqrt{u} \cdot -\sqrt{u'} = -\sqrt{a^2 - Db^2}$$
The first norm lies in $K_1$, the last 2 norms both lie in $K_2$, and none lie in $K_3$.  This is a contradiction.
(Essentially, what we have proven here is: If $\mathbb{Q}(\sqrt{a+b\sqrt{D}})$ is a normal extension of $\mathbb{Q}$ of degree 4, then its Galois group must be $C_4$.)


text:
Q: How do I group and add values from nested hashes and arrays with same key? I am trying to get the sum of points and average grade for each student inside this combination of hashes and arrays but all my attempts only return the general sum for all entries. Any ideas?
student_data =
  {"ST4"=>[{:student_id=>"ST4", :points=> 5, :grade=>5},
           {:student_id=>"ST4", :points=>10, :grade=>4},
           {:student_id=>"ST4", :points=>20, :grade=>5}],
   "ST1"=>[{:student_id=>"ST1", :points=>10, :grade=>3},
           {:student_id=>"ST1", :points=>30, :grade=>4},
           {:student_id=>"ST1", :points=>45, :grade=>2}],
   "ST2"=>[{:student_id=>"ST2", :points=>25, :grade=>5},
           {:student_id=>"ST2", :points=>15, :grade=>1},
           {:student_id=>"ST2", :points=>35, :grade=>3}],
   "ST3"=>[{:student_id=>"ST3", :points=> 5, :grade=>5},
           {:student_id=>"ST3", :points=>50, :grade=>2}]}

A: The desired hash can be obtained thusly.
student_data.transform_values do |arr|
  points, grades = arr.map { |h| h.values_at(:points, :grade) }.transpose
  { :points=>points.sum, :grades=>grades.sum.fdiv(grades.size) }
end
  #=> {"ST4"=>{:points=>35, :grades=>4.666666666666667},
  #    "ST1"=>{:points=>85, :grades=>3.0},
  #    "ST2"=>{:points=>75, :grades=>3.0},
  #    "ST3"=>{:points=>55, :grades=>3.5}}

The first value passed to the block is the value of the first key, 'ST4' and the block variable arr is assigned that value:
a = student_data.first
  #=> ["ST4",
  #    [{:student_id=>"ST4", :points=> 5, :grade=>5},
  #     {:student_id=>"ST4", :points=>10, :grade=>4},
  #     {:student_id=>"ST4", :points=>20, :grade=>5}]
  #   ]
arr = a.last
  #=> [{:student_id=>"ST4", :points=> 5, :grade=>5},
  #    {:student_id=>"ST4", :points=>10, :grade=>4},
  #    {:student_id=>"ST4", :points=>20, :grade=>5}]

The block calculations are as follows. The first value of arr passed by map to the inner block is
h = arr.first
  #=> {:student_id=>"ST4", :points=>5, :grade=>5}
h.values_at(:points, :grade)
  #=> [5, 5]

After the remaining two elements of arr are passed to the block we have
b = arr.map { |h| h.values_at(:points, :grade) }
  #=> [[5, 5], [10, 4], [20, 5]]

Then
points, grades = b.transpose
  #=> [[5, 10, 20], [5, 4, 5]]
points
  #=> [5, 10, 20]
grades
  #=> [5, 4, 5]

We now simply form the hash that is the value of 'ST4'.
c = points.sum
  #=> 35
d = grades.sum
  #=> 14
e = grades.size
  #=> 3
f = c.fdiv(d)
  #=> 4.666666666666667

The value of 'ST4' in student_data therefore maps to the hash
{ :points=>c, :grades=>f }
  #=> {:points=>35, :grades=>4.666666666666667}

The mappings of the remaining keys of student_data are computed similarly.
See Hash#transform_values, Enumerable#map, Hash#values_at, Array#transpose, Array#sum and Integer#fdiv.

A: Whatever you expect can be achieved as below,
student_data.values.map do |z|
  z.group_by { |x| x[:student_id] }.transform_values do |v|
    {
      points: v.map { |x| x[:points] }.sum, # sum of points
      grade: (v.map { |x| x[:grade] }.sum/v.count.to_f).round(2) # average of grades
    }
  end
end

As exact expected output format is not specified, obtained in following way,
=> [
  {"ST4"=>{:points=>35, :grade=>4.67}},
  {"ST1"=>{:points=>85, :grade=>3.0}},
  {"ST2"=>{:points=>75, :grade=>3.0}},
  {"ST3"=>{:points=>55, :grade=>3.5}}
]

A: For Ruby 2.6 using Object#then or Object#yield_self for Ruby 2.5
student_data.transform_values { |st| st
  .each_with_object(Hash.new(0)) { |h, hh|  hh[:sum_points] += h[:points]; hh[:sum_grade] += h[:grade]; hh[:count] += 1.0 }
  .then{ |hh| {tot_points: hh[:sum_points], avg_grade: hh[:sum_grade]/hh[:count] } }
}

How it works?
Given the array for each student:
st = [{:student_id=>"ST4", :points=> 5, :grade=>5}, {:student_id=>"ST4", :points=>10, :grade=>4}, {:student_id=>"ST4", :points=>20, :grade=>5}]

First build a hash adding and counting using Enumerable#each_with_object with a Hash#default set at zero (Hash.new(0))
step1 = st.each_with_object(Hash.new(0)) { |h, hh|  hh[:sum_points] += h[:points]; hh[:sum_grade] += h[:grade]; hh[:count] += 1.0 }
#=> {:sum_points=>35, :sum_grade=>14, :count=>3.0}

Then use then! (yield_self for Ruby 2.5)
step2 = step1.then{ |hh| {tot_points: hh[:sum_points], avg_grade: hh[:sum_grade]/hh[:count] }}
#=> {:tot_points=>35, :avg_grade=>4.666666666666667}

Put all together using Hash#transform_values as in the first snippet of code


text:
Q: MS Access Pulling last 12 digits of barcode I changed scan guns recently from a FedEx scan gun, to a Wasp scan gun. Now when I scan a FedEx label, it gives me a 24 character tracking, and I only need the last 12 digits. I will also be scanning UPS labels and they are alphanumeric. Is there any way to truncate all but the last 12 digits of an all numeric barcode scanned into a text box?
My current code has me leaving off the leading zeros, but if I could just get the last 12 digits, I wouldn't need that piece of code.
Current Code:
Dim strIn As String
Dim i As Integer
Dim iLen As Integer
strIn = Me.txt_Track.Value
iLen = Len(strIn)
For i = 1 To iLen
For i = 1 To iLen
    If InStr(strIn, "0") = 1 Then
        strIn = Mid(strIn, 2)
    End If
Next i
CurrentDb.Execute
            "INSERT INTO TrackNum_Table(TrackingNum_TrackNum) " & _
            "VALUES ('" & strIn & "')"

A: Right will do that:
Code = Right(strIn, 12)

A: This is how I resolved this.
Dim strIn As String
Dim strOut As String
strIn = Me.txt_Track.Value
Numeric = IsNumeric(strIn)
If Numeric = True Then
    strOut = Right(strIn, 12)
Else
    strOut = strIn
End If
CurrentDb.Execute _
            "INSERT INTO TrackNum_Table(TrackingNum_TrackNum) " & _
            "VALUES ('" & strOut & "')"


text:
Q: java.lang.ClassCastException: android.app.Application cannot be cast I'm following this Android-Checkout for in-app purchases. Just getting a feel for how it works. I have a pretty good idea how it all works but I get this problem.
This is my Sku Activity class and I get an error which corresponds with in the CheckoutApplication class
final Billing billing = CheckoutApplication.get(this).getmBilling();
    mCheckout = Checkout.forActivity(this, billing); //Line with error
    mCheckout.start();

//Separate class
//This is where the other error is

public static CheckoutApplication get(Activity activity)
{
    return (CheckoutApplication) activity.getAcitivty();
}

I'm not sure what is causing the error. Any help is welcome. Thanks

at
  com.purchases.inapppurchases.CheckoutApplication.get(CheckoutApplication.java:37)
                                                                                at
  com.purchases.inapppurchases.SkuActivity.onCreate(SkuActivity.java:68)

A: return (CheckoutApplication) activity.getAcitivty();

You are returning an Activity instead of an Application, this can't be cast successfully. Try returning and casting the actual application instead:
return (CheckoutApplication) activity.getApplication();

A: replace this
public static CheckoutApplication get(Activity activity)
{
    return (CheckoutApplication) activity.getAcitivty();
}

with
public static CheckoutApplication get(Activity activity)
{
    return (CheckoutApplication) activity.getApplication();
}


text:
Q: What happens if I use a callback method from an activity that is about to finish? I am doing an HTTP request from my InitActivity:
private void initUserById(int challengerId) {
        Call call = StaticGlobalContainer.api.getUser(challengerId);
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Response<User> response, Retrofit retrofit) {
                StaticGlobalContainer.currentUser = response.body();
                if (response.code() == 200) {
                    // 200
                    // User object returned from server
                    Log.i("Getting user by id", ACTIVITY_TAG+"_Success");
                } else {
                    // 404 or the response cannot be converted to User.
                    Log.e("Getting user by id", ACTIVITY_TAG+"_Error:" + response.errorBody());
                }

            }

            @Override
            public void onFailure(Throwable t) {
                Log.i("HttpRequest - Get user", ACTIVITY_TAG+"_Failure");
            }
        });
    }

This activity ends as soon as user presses a button to go to the next activity:
setUserIdBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                StaticGlobalContainer.CURRENT_USER_ID = userIdEditText.getText().toString();
                initUserById(Integer.parseInt(StaticGlobalContainer.CURRENT_USER_ID));
                startActivity(new Intent(InitActivity.this, MainMenuActivity.class));
                finish();
            }
        });

What happens, if there is a slight delay on the server and it won't respond before user presses the button?
Since activity has already ended, I would expect an exception, but isn't it handled somehow? Like that the activity wouldn't be disposed until callback has been made?
EDIT:
After some thinking, I assume that such callbacks as described above are one of the reason they invented ProgressBars, is that right?


text:
Q: Trying to pass Parameters to Crystal Reports I am trying to pass parameters from Visual Studio using VB.net to a Crystal report.
I am using the following code:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    If IsDate(MaskedTextBox1.Text) Then
        Dim report As New invoice4

        report.SetParameterValue(0, gCustId)
        report.SetParameterValue("CustID", gCustId)
        report.SetParameterValue("inputDate", MaskedTextBox1.Text)

        Try
            report.DataSourceConnections.Item(0).SetConnection("", "" & My.Settings.storeCS, False)
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try

        gReport = ""
        With removenotice
            .CrystalReportViewer1.ReportSource = report
            .ShowDialog()
        End With
    Else
        MsgBox("Please Enter a Valid Date")
    End If
End Sub

but every time I run it gives me a prompt for:
Pm-?CustID
Which when entered then gives me a "Field Not None"
So I try to replace the first ParameterValue:
report.SetParameterValue(0, gCustId)
with
report.SetParameterValue("Pm-?CustID", gCustId)
It then gives me the error:
Operation illegal on linked parameter.
If I click okay it still promts me for the CustID and inputDate and ultimately gives me the correct report.
Any suggestions?
Thanks

A: Are you sure you are linking it correctly to the sub-report? I'm getting the impression that it has something to do with passing the parameter down to a subreport.
Did you try running the report without this line: report.SetParameterValue(0, gCustId) ?


text:
Q: Deleting node from Linear Linked List recursively C++ I'm trying to write a function to delete a node any where in a linear linked list recursively but it's not working so far. Deleting at the beginning works but not in the middle. Here is my code
int remove(node* &head, char* data_to_delete)
{
  if(!head) return 0; // check if head is null

  if(!strcmp(head->data,data_to_delete)) //check if the first node is data
  { node* temp  = head->next;  //save head->next
    delete [] head->data;  //deallocate data
    delete head; //delete the node
    head = temp;  //connect the node
    return 1;
  }

  if(head->next && !strcmp(head->next->data,data_to_delete))//check if head->next is not null and head->next->data is equal to data
  {
      node* temp = head->next->next;
      delete [] head->next->data;
      delete head->next;
      head->next = temp;
      return 1;
  }
  remove(head->next, data_to_delete);
}

Also how would I modify this if I want to drag along a previous pointer instead of looking ahead? Thanks!!!!


text:
Q: Proving a theorem for all real numbers using mathematical induction For the sake of this question, let us consider the De Moivre theorem. As of now, I am able to prove
$(\cos(\theta)+i\sin(\theta))^{n} = \cos(n\theta)+i\sin(n\theta)$
for all integers(positive and negative).
Using the fact that the theorem holds good for integers, if I try to prove the theorem for $\frac{a+b}{2}$, where $a$ and $b$ are integers, will this prove the theorem for all real numbers?
Note: The intent of this question is NOT to prove the theorem for all real numbers, but to discuss whether proving a theorem for $\frac{a+b}{2}$ where $a$ and $b$ are integers is a valid method to prove for all real numbers

A: If this were a valid proof technique, you could use it to prove that all real numbers are rational: clearly all integers are rational, and if $\frac pq$ and $\frac rs$ are rational then so is
$$
\frac{\frac pq + \frac rs}2 = \frac{ps + rq}{2qs}.
$$
Therefore this is not a valid proof technique for proving something for all real numbers.

A: No it would not work as you suggested.
If you could prove the theorem for example for all rational numbers (more generally: any dense subset of the reals), then you could conclude that it holds for all real numbers by a continuity argument (the expressions occuring in the formula you gave as an example define continuous functions).
The problem you have is that expressions of the form $\frac{a+b}{2}$ where $a$ and $b$ are integers do not form a dense subset of the reals, so you cannot conclude that the formular holds for all real numbers.
Edit: Maybe I was a bit unclear: Of course the conclusion from the rationals to the reals is only possible if we want to prove a formular which depends continuously on the variable over which we are inducing. If that's not the case (as for example in Mees de Vries' answer) then this does not work. But as the OP explicitly gave an example where we actually have a formula depending continuously on the variable we are inducing I thought that this was actually the point he was interested in.


text:
Q: Unable to load JS file from a swift package unit test I am trying to load a Javascript file from within a Unit Test for a Swift Package I am working on and it is failing.
Here is what I have so far ...

*

*The sample files are located in MyPackage/Tests/MyPackageTests/Resources/Sample.js

*Within the Package.swift I have added the recources attribute to the .testTarget as follows:
import PackageDescription

let package = Package(
    name: "MyPackage",
    products: [
        .library(
            name: "MyPackage",
            targets: ["MyPackage"]),
    ],
    dependencies: [],
    targets: [
        .target(
            name: "MyPackage"
        ),

        .testTarget(
            name: "MyPackageTests",
            dependencies: ["MyPackage"],
            resources: [.process("Resources")] // <---- Here is where I declare the Resources
        ),

    ]
)

*In my test case I have the following code:

import XCTest
import JavaScriptCore

class JavaScriptCoreTest: XCTestCase {

    func testParseJSFile() throws {
        let testBundle = Bundle(for: type(of: self))
        XCTAssertNotNil(testBundle)

        let file = "Sample"

        guard let url = testBundle.url(forResource: file, withExtension: "js") else {
            fatalError("Unable to find resource \(file)") // <--- ERROR HERE
        }

        guard let data = try? Data(contentsOf: url) else {
            fatalError("Failed to load \(file) from bundle.")
        }

        let js = String(decoding: data, as: UTF8.self)

        let ctx = JSContext()!
        ctx.evaluateScript(js)

        // Rest of test logic here

    }

For some reason I keep getting nil for the url.  Any thoughts on what I might be doing wrong here?
NOTE I did read this other answer on StackOverflow but it did not help me here.


text:
Q: How can I disable the "No Backups for x Days" from Time Machine? Since I updated to High Sierra, I frequently get the "No Backups for x Days" notification. I used to be able to make this go away by turning off Time Machine in the System Preferences until I needed it, but there is no way to turn Time Machine off anymore. How can I get rid of these notifications?

A: For macOS 12 and earlier (pre-Ventura):
In the Time Machine preferences, you have to right-click on the drive icon and then select "Stop Using {Drive Name} for Backup".

For macOS 13 and later:
In Time Machine settings page, select the drive icon and click the [-] button at the bottom of the list.

A: I suggest you get TimeMachineEditor and set your backup schedule to once a week or some time period you find more suitable. This app overrides the hourly backup default schedule of Time Machine and lets you define time periods to prohibit backups.


text:
Q: In SharePoint Modern Page Layout using Application Customizer, custom footer gets disappeared In SharePoint Modern Page Layout using Application Customizer, the middle/main content height was too small for the view-port, so tried to increase the middle/main content height through CSS, by doing so custom footer is getting disappeared.Refer here for SharePoint Modern Page
Could anyone advice how to achieve it.
Thanks in advance.

A: You could try to add ' position:fixed; 'to bottom css.
After you add this, you would need adjust other elements' CSS accordingly.
My test css:
position:fixed;
right:10px;
bottom:10px;

Updated:
Firstly, add display:none to bottom div css.
Secondly, add a script in code , determine the position of the scroll bar according to the scroll event of the div. When the scroll bar reaches the bottom, show bottom div.
Sample(you need to change the class):
$(function(){

          var nScrollHight = 0;
          var nScrollTop = 0;
          var nDivHight = $(".scrollRegion_dfa95bf5").height();
          $(".scrollRegion_dfa95bf5").scroll(function(){
            nScrollHight = $(this)[0].scrollHeight;
            nScrollTop = $(this)[0].scrollTop;
        var paddingBottom = parseInt( $(this).css('padding-bottom') ),paddingTop = parseInt( $(this).css('padding-top') );
            if(nScrollTop + paddingBottom + paddingTop + nDivHight >= nScrollHight){

              $("div[class^='bottom']").show()
            }else{
              $("div[class^='bottom'").hide()
            }

            });
        })

Test result:


text:
Q: How to give PowerShell WorkFlow access to previously imported modules I'm trying to introduce PowerShell workflow into some existing scripts to take advantage of the parallel running capability.
Currently in the WorkFlow I'm having to use:
Inline
{
   Import-Module My.Modules
   Execute-MyModulesCustomFunctionFromImportedModules -SomeVariable $Using:SomeVariableValue
}

Otherwise I get the error stating it can't find the custom function. There must be a better way to do this?

A: The article at http://www.powershellmagazine.com/2012/11/14/powershell-workflows/ confirms that having to import modules and then use them is just how it works - MS gets around this by creating WF activities for all its common PowerShell commands:

General workflow design strategy
It's important to understand that the entire contents of the workflow
  get translated into WF's own language, which only understands
  activities. With the exception of a few commands, Microsoft has
  provided WF activities that correspond to most of the core PowerShell
  cmdlets. That means most of PowerShell's built-in commands—the ones
  available before any modules have been imported—work fine.
That isn't the case with add-in modules, though. Further, because each
  workflow activity executes in a self-contained space, you can't even
  use Import-Module by itself in a workflow. You'd basically import a
  module, but it would then go away by the time you tried to run any of
  the module's commands.
The solution is to think of a workflow as a high-level task
  coordination mechanism. You're likely to have a number of
  InlineScript{} blocks within a workflow because the contents of those
  blocks execute as a single unit, in a single PowerShell session.
  Within an InlineScript{}, you can import a module and then run its
  commands. Each InlineScript{} block that you include runs
  independently, so think of each one as a standalone script file of
  sorts: Each should perform whatever setup tasks are necessary for it
  to run successfully.


text:
Q: how to change the position of the button in perl tk? $mw->Checkbutton(-text => "FAU_GEN1.1 ", -command => sub{faugen1=1} )->pack;

This command creates a check button at the centre. How do I shift it to a certain position ?

A: You need to look at the geometry manager methods.  Start with the User Guide, then you might want to check out grid, form, pack, and place.


text:
Q: how to use libreoffice flatpak headlessly I would like to use the libreoffice flatpak version to headlessly convert odt files to pdf.
So e.g.
libreoffice --headless --convert-to pdf ./somefile.odt

However, I want to use the flatpak version for this.

A: This:
flatpak run org.libreoffice.LibreOffice/x86_64/stable --headless --convert-to pdf ./somefile.odt

seems to work.
Hence, you can set an alias:
alias libreoffice="flatpak run org.libreoffice.LibreOffice/x86_64/stable"

and add it to your ~/.bashrc file and use libreoffice headlessly, like you are used to.


text:
Q: redirect to another page on click of submit button using backbone.js using Backbone.js after calling collection.create() i want to redirect my page to the link which is having currently added record's unique id. this link(means link on which my page is redirected) should also pass to Backbone.sync.

A: If I understand your question correctly (which is not easy), it seems to me you could mean something like adding
document.location.replace(<model>.id)

into your models initialize function. However, I dont understand what you mean by "this link should also pass to Backbone.sync. Please clarify your question (and work on your accept rate)


text:
Q: Does PySpark ML LogisticRegression weightCol implement a sampleWeight or classWeight? I'm defining a binary LogisticRegression pipeline in PySpark ML for a largely imbaalnced dataset.
lr = LogisticRegression(maxIter=10, regParam=0.001, weightCol="weight")

The API contains an option for weightCol='weight', which I want to use for my imbalanced dataset. The docs for Pyspark 2.3.0.

weightCol = Param(parent='undefined', name='weightCol', doc='weight column name. If this is not set or empty, we treat all instance weights as 1.0.')

Yes, very verbose...
Is this a sample weight, or a class weight?
I cannot find any information on this elsewhere in the documentation.

A: When the Spark documentation is vague, especially on the Python side, often your best bet is to go to the Scala source code:
https://github.com/apache/spark/blob/992447fb30ee9ebb3cf794f2d06f4d63a2d792db/mllib/src/main/scala/org/apache/spark/ml/classification/LogisticRegression.scala#L491
Without digging too much here, it looks like the weight is a Double column applied at the row-level, so I'm going with sample weight.


text:
Q: Can't install Ubuntu for dual boot could someone please advise me as to where I may be going wrong... (I may need a Step-By-Step guide)

*

*I have been trying to install Ubuntu alongside windows 10. I have first created a 20GB partition (unformatted) and have turned off Fast start.

*I have formatted a flashdrive with the Ubuntu 16.04.1 32bit and this seems to work fine.

*Problem... when I try to install Ubuntu, it finds the Windows 10 installation but only gives me the option to format the partition with Ubuntu (losing all contents)... !! how do I set it up to install alongside Windows??

Thank you all in advance.
Matt

A: You have to choose the option "Something else". Then, look for the partition you want to dedicate to Ubuntu. Choose to use it as ext4 partition, check the checkbox to format it, and choose to mount it at /.
You will get a warning that the data on the partition will be lost when formatting. Double-check that you chose the correct partition, then confirm.


text:
Q: Accessing instance variables from another class from a static method I have the following code:
    public static boolean isRelated(Animal first, Animal second){
    boolean result=false;
    if(first(parentA).equals(second(parentA)))
        result=true;

    return result;
}

basically, I need to be able to access the parent A instance variable that is in the Animal class from this static method.
I understand that, to access instance variables in a static method, you need to create an object but I already have 2 brought in.(Parent A and Parent B)
Could  you guys tell me what the problem here is?

A:  if(first(parentA).equals(second(parentA)))

basically, I need to be able to access the parent A instance variable that is in the Animal class from this static method.

That is not the correct syntax to access instance members
should be
 if(first.parentA.equals(second.parentA))

More over use setters and getters to access the data such that
public class Animal  {
    private String parentA;

 //  code

  public String getParentA() {
    return parentA;
  }

  public void setParentA(String parentA) {
    this.parentA = parentA;
  }
}

}

Then use the line if(first.getParentA().equals(second.getParentA()))

A: In order to access instance variable, you need to use an instance. You don't have to create it each time you need it, as long as you have one.
And for your code:
if(first.getParentA().equals(second.getParentA()))

In this case you need to make sure than first.getParentA() isn't null before comparing (or else you'll get NPE)

A: Static methods are created in method area, and is the first to be created. Instance variables are created in heap after static methods are created. Hence, accessing instance variables directly is not possible. Always make use of an object to access such variables.


text:
Q: FFMPEG virtual camera on Microsoft Teams I would like to stream my monitor as the webcam input.
I do this using sudo ffmpeg -f x11grab -r 15 -s 1280x1024 -i :0.0+0,0 -vcodec rawvideo -pix_fmt yuv420p -threads 0 -f v4l2 -vf 'hflip,scale=800:600' /dev/video0.
I use this virtual webcam on Microsoft Teams but when there are a lot of people in the conference the video gets cropped.
Is there a fix ?


text:
Q: How to set up a route to serve reactjs app? I'm trying to set up a route to serve my reactjs application.
I have my index.html and bundle.js in the public folder
/public/index.html
/public/bundle.js

I'm using go as my backend API, and also to serve my reactjs app.
I created a subroute for my app like:
r := mux.NewRouter()

app := r.Host("app.example.com").Subrouter()

So any request with app as the subdomain will be for my Reactjs app.
So now I have to serve every request regardless of the URL to my reactjs app.
Is path prefix what I need here?
I tried this:
app.PathPrefix("/").Handler(serveReact)

func serveReact(w http.ResponseWriter, r *http.Request) {
}

But I get this error:

cannot use serveReact (type func() http.Handler) as type http.Handler
  in argument to app.PathPrefix("/").Handler:   func() http.Handler does
  not implement http.Handler (missing ServeHTTP method)

A: Your http handler needs a ServeHTTP method. If you pass your function to http.HandlerFunc, that will be introduced for you:
app.PathPrefix("/").Handler(http.HandlerFunc(serveReact))

func serveReact(w http.ResponseWriter, r *http.Request) {
}

The HandlerFunc type is an adapter to allow the use of ordinary functions as HTTP handlers. If f is a function with the appropriate signature, HandlerFunc(f) is a Handler that calls f.

source
type HandlerFunc func(ResponseWriter, *Request)

// ServeHTTP calls f(w, r).
func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
    f(w, r)
}

Similarly, you could use the mux router HandlerFunc instead:
app.PathPrefix("/").HandlerFunc(serveReact)

func serveReact(w http.ResponseWriter, r *http.Request) {
}

This essentially performs both steps for you in a combined single step.