text:
Q: Animated ImageView go to Origin back I want to center an ImageView. I am using this so far:
 private void moveViewToScreenCenter(View view, RelativeLayout relativeLayout) {
        DisplayMetrics dm = new DisplayMetrics();
        windowManager.getDefaultDisplay().getMetrics(dm);
        int statusBarOffset = dm.heightPixels - relativeLayout.getMeasuredHeight();

        int originalPos[] = new int[2];
        view.getLocationOnScreen(originalPos);

        int xDest = dm.widthPixels / 2;
        xDest -= (view.getMeasuredWidth() / 2);
        int yDest = dm.heightPixels / 2 - (view.getMeasuredHeight() / 2) - statusBarOffset;

        TranslateAnimation anim = new TranslateAnimation(0, xDest - originalPos[0], 0, yDest - originalPos[1]);
        anim.setDuration(1000);
        anim.setFillAfter(true);
        view.startAnimation(anim);
    }

Now, when the animation ends, the view should go to its origin. How can I do this?

A: switch this:

anim.setFillAfter(true);

with this:

anim.setFillAfter(false);


text:
Q: Example of a non-closed cocomplete symmetric monoidal category Background
By a cocomplete symmetric monoidal category $C$ I mean a symmetric monoidal category whose underlying category is cocomplete and such that $- \otimes X : C \to C$ is cocontinuous for all $X \in C$. Recall that the internal hom $\underline{\mathrm{hom}}(X,-)$ is defined, if it exists, as a right adjoint of $- \otimes X$, and that $C$ is called closed if internal homs exist for all $X \in C$. According to the General Adjoint Functor Theorem, this reduces just to a size condition: For all $X,Y \in C$ there should be a set of morphisms $(Z_i \otimes X \to Y)_{i \in I}$, such that any other morphism $Z \otimes X \to Y$ factors as $Z \otimes X \to Z_i \otimes X \to Y$ for some $i \in I$ and $Z \to Z_i$.
Questions
Q1. What is a nice example of a cocomplete symmetric monoidal category which is not closed?
A standard example for a cartesian category which is not closed is $\mathsf{Top}$; but $-\times \mathbb{Q}$ doesn't preserve coequalizers so that this doesn't answer the question (similar problems with other standard examples). If Q1 is too easy, what about cartesian categories?
Q2. What is a nice example of a cocomplete category with products, such that $-\times X$ is cocontinuous for all $X$, but has no right adjoint in general?
A weaker question would be:
Q3. What is a nice example of a cocomplete symmetric monoidal category whose underlying category is not locally presentable?
Again the standard examples of non-locally presentable categories which I have found in the literature don't fit here.

A: Here is an amusing example which addresses Q2: take the universe $V$ of sets in a model of ZFC, as a class partially ordered by inclusion of sets. Consider a partially ordered class to be a category in the usual way. Of course, by Cantor's theorem, there is no terminal object in this category, but anyway we can freely adjoin one; let $V_+$ denote the result. Notice that cartesian products are given by taking intersections.
The category $V_+$ is small cocomplete since we can take small unions, and of course intersections $- \cap X$ distribute over unions, so we get a cocomplete cartesian monoidal category. But I claim that unless $X$ is the top element (that we freely adjoined), there is no exponential $Y^X$ for any strict subset $Y \subset X$. Indeed, if $Z = Y^X$, then $Z$ would have to be the largest set such that $Z \cap X \subseteq Y$. But there is no such largest set, since to any such set we could add more elements which do not belong to $X$ to get a larger set $Z'$, and we'd still have $Z' \cap X \subseteq Y$!

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is E[X|Y>c] where Y=X+Z, and X, Z are normally distributed rvs? Suppose X, Z are normally distributed random variables and independent ($X$ follows $N(\mu,\sigma^{2})$ and $Z$ follows $N(0,\sigma_{z}^{2})$), and that Y=X+Z.
What is E[X|Y>c], where c is just a constant - how do you derive this?


text:
Q: Force Body Diagrams of object sliding down ramp So I think I am confusing myself about forces. I know that when something is sliding down a ramp that it will have the force of gravity, normal force and force of friction acting on it.
But for an example, what if I had a toy cart and added a chocolate bar to it. When it is sliding down the ramp, the forces acting on it will be the force of gravity, normal force, friction but would there be an applied force on the toy cart from the chocolate bar?
Or would I just treat this still as "one system" and make it so that when I am calculating the forces I increase the mass to take into account the chocolate bar? Or would I have to put an applied force downwards?

A: You can treat it as one system. Since the weight of the bar and the car are downwards, you can add them.

A: You can do either.
If the chocolate bar is not moving relative to the cart and you don't care how much force is between the cart and the chocolate bar, then you can treat them as a single system.
If you do care about the forces or the chocolate bar is sliding around within the cart, then you'd have to model the system with two separate independent masses. The cart would have a normal and fiction force from the ramp, a normal and friction force from the chocolate, and gravity. The chocolate would have the normal and friction force from the cart (equal and opposite to the cart's from the chocolate as per newtons third law) and gravity.
This is true in general for multiple bodies, as long as they move together and you don't care about internal forces you can model it as one solid body. That's why you don't have to model each half of the cart or even each molecule of the cart separately. If however you were worried about the cart breaking then you'd want to model those internal forces to see if it would break.

A: For sure the object you will put in cart will act as one body until and unless they both have same velocity or I say that they both move relatively and this is possible if both have contact with each other. And if you want to take internal forces then you have to work on that but besides everything of what you ask the answer is simple that you have to take that as single body.
Example-
Let us say one block sliding down and for the sake of question and imagination let us take one small section of (red portion in image) as chocolate bar. So by seeing the FBD we can recognize that it will act as one body (as the red section is already a part of that block) will work as one system and it will act just same in your Cart example due to which the mass of the system increases.


text:
Q: string to time with python import requests
import bs4

root_url = 'url here'

response = requests.get(root_url)
soup = bs4.BeautifulSoup(response.content)
hora = soup.select('span.match-time')[0].get_text()

return - 20:45
I need to convert the string variable "hora" to datetime zone UTC
Update:
 from_zone = tz.gettz('UTC')
to_zone = tz.gettz('America/Montevideo')
utc = dt_obj.replace(tzinfo=from_zone)
central = utc.astimezone(to_zone)

print(central)

return 1900-01-01 15:45:00-03:45
time difference is 3 hours not 3:45.
What is the matter?
Thankyou

A: See Python'sdatetime library (datetime)
You're going to particularly need to use datetime.strptime to parse 20:45. You'll also need pytz (pip install pytz) to get UTC timezone.
     import pytz
     import datetime

     udt = datetime.datetime.strptime(hora, '%H:%M').time().replace(tzinfo=pytz.UTC)

This is assuming the time you're reading is already in UTC.

A: datetime.time(*map(int,hora_string.split(":")))

but you would need to know the timezone it is in in order to change it ...
you could also use the dateutil library
import dateutil.parser as p
print p.parse("16:45")

but this will attach todays date to the time , which may not be desireable

A: from datetime import datetime as dt

hora = "20:45"
the_time = dt.strptime(hora, "%H:%M").time()

This will return a datetime.time() object.

A: To convert UTC time to a given timezone, you need to know both date and time (utc offset may be different at a different date/time):
>>> from datetime import datetime
>>> import pytz
>>> input_time = datetime.strptime('20:45', '%H:%M').time()
>>> utc_dt = datetime.combine(datetime.utcnow(), input_time)
>>> tz = pytz.timezone('America/Montevideo')
>>> str(utc_dt.replace(tzinfo=pytz.utc).astimezone(tz))
'2015-01-24 18:45:00-02:00'

Note: the current offset is 2 hours, not 3. Uruguay observes DST from October till March.


text:
Q: Creating Dropdown list from sql database in PHP *The condition for "die" had been left out of my code by mistake when I copied it to the question. I put it back in.
I know this question might seem repetitive, but I have not found an answer in any of the other questions. I am trying to create a drop-down list based off a column in a database. I have tried two different ways and neither gave me correct results. Does anyone know a correct way of doing this?
The first way I saw in other StackOverflow answers (Fetching data from MySQL database to html drop-down list, Fetching data from MySQL database to html dropdown list). My code is below:
<?php
 $connect = mysql_connect('localhost', 'root');
 if ($connect == false)
   {
     die  ("Unable to connect to database
");
  }

$select = mysql_select_db('ViviansVacations');
if ($select == false)
   {
    die ("Unable to select database
");
  }
$query = "SELECT * FROM Destinations";
$result = mysql_query($query);
 ?>
 <select name="select1">
 <?php

while ($row = mysql_fetch_array($result))
{
echo "<option value='". $row['Europe'] ."'>" .$row['Europe'] ."</option>" ;
}
?>
</select>

NetBeans sends me an error saying that "Text not allowed in element 'select' in this context".
The second way I tried:
<?php
 $connect = mysql_connect('localhost', 'root');
  {
   die  ("Unable to connect to database
");
  }
  $select = mysql_select_db('ViviansVacations');
  {
   die ("Unable to select database
");
  }
  $query = "SELECT * FROM Destinations";
  $result = mysql_query($query);
?>
<select name="select1">
<?php
  while ($line = mysql_fetch_array($result))
  {
?>
 <option value="<?php echo $line['Europe'];?>"> <?php echo
 $line['field'];?> </option>
<?php
  }
?>
</select>

This code did not produce any errors. However, inside the form were the opening php lines followed by an empty drop down box:
"); } $select = mysql_select_db('ViviansVacations'); { die ("Unable to select database
"); } $query = "SELECT * FROM Destinations"; $result = mysql_query($query); ?>

A: So there are many problems with your approach. First of all you are using a deprecated mysql_* functions which is bad idea and second you are not debugging your database connection properly :
$connect = mysql_connect('localhost', 'root');
   {
     die  ("Unable to connect to database
");
  }

In above code the die statement will always execute stopping further execution.
Also make sure the database ViviansVacations and table Destinations and column Europe exists with correct names(Follow standards and try to use all small letters for database/table/column naming)
The correct mysqli_* approach is(tested locally and the select box forms correctly) :
<?php
$db = 'ViviansVacations';

$mysqli = new mysqli('localhost', 'root', '', $db);

if($mysqli->connect_error)
  die('Connect Error (' . mysqli_connect_errno() . ') '. mysqli_connect_error());

$query = "SELECT * FROM Destinations";
$result = mysqli_query($mysqli, $query);

?>

<select name="select1">
<?php
while ($row = mysqli_fetch_array($result)) {
    echo "<option value='" . $row['Europe'] . "'>" . $row['Europe'] . "</option>";
}
?>
</select>

A: There are couple of things, you to verify and correct.
First of all, your database connection code, that doesn't seems to be correct. I didn't see any condition on which you are suppose to invoke die.
$connect = mysql_connect('localhost', 'root');
{
die  ("Unable to connect to database
");
}

From the above code, below line will execute all the time
 die  ("Unable to connect to database
");

You should correct your database connection code to below :
$link = mysql_connect('localhost', 'mysql_user', 'mysql_password');
if (!$link) {
    die('Could not connect: ' . mysql_error());
}
echo 'Connected successfully';
mysql_close($link);

You can refer mysql_connect for the usage.
Also, verify your file extension is .php

A: Mainly your problem is database connection. Try this -
<?php
mysql_connect("localhost", "root", "") or
    die("Could not connect: " . mysql_error());
mysql_select_db("your_db");

$result = mysql_query("SELECT * FROM your_table");

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
    print_r($row);
    echo "
";
}

mysql_free_result($result);
?>

A: There could be few issues:

*

*Use mysqli_connect instead of mysql_connect because mysql is depreciated

*Make 3rd parameter as empty `mysqli_connect('localhost', 'root', '');//as per standards

*Debug your code for example: (print_r($connect), execute your query in phpmyadmin, print_r($result) and then in loop print_r($row).

At end, I am sure you will get your desired result and also you will know in detail that what was happening.

A: You might want to try to use this ..The dept_id and the description u have to change according to your database .Hope this will help you
 <?php
  $sql = mysql_query("SELECT dept_id ,description FROM department
  ORDER BY dept_id ASC");
  db_select($sql,"dept_id",$dept_id,"","-select Department-","","");
  ?>


text:
Q: Just how dangerous is sending SIGINT to resize2fs tasked with shrinking? I inherited an old PC-server (quad Pentium 4) that only had partitions for /, /boot and swap (RAID1 with 2 1T SATA disks), but needed to update the distro (from CentOS 6.9). I decided to create a new partition so that the one containing / could be formatted.
But I forgot to add the -p flag to resize2fs and now it's silently staring back at me and I can't tell how much longer it could take (it's been at it for 50+ hours). Now, I know that shrinking a filesystem can take a long time, but while I could wait for 100 hours, something like 800 hours is out of the question.
Here's what I'm thinking at the moment:

*

*Go ahead with the Ctrl+C && e2fsck.

*Mount the partition and manually delete 100G+ worth of data that serves us no purpose.

*Start from the top with resize2fs -p ...
But I haven't been able to find consensus on just how dangerous it is to send SIGINT to resize2fs.
I do have an extra backup of the important information, but would still like to do this without corrupting the filesystem. And yes, I'm aware it might be faster to just install the distro from scratch and restore my backup.
Update: I decided to interrupt it. And everything seems to be fine, but the question still stands. I'm still curious.

A: Definitely an interesting question and while your result was pretty good (and as I would hoped, since catching SIGINT is not exactly rocket science and pausing halfway merely relocating some data blocks doesn't seem hard either), there are enough non-success stories as well, like for example 10yo Debian bug https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=574292
But even though that bug is 10y old, I've just ran a mock e2fsck and resize2fs through strace and while the former installs a whole bunch of signal handlers including SIGINT and SIGTERM, resize2fs still does not.
So if anyone finds this question: Take the above as anecdotal evidence and continue to beware. :-) Note that the man page does mention a flag for creating an undo file in case of mistakes.
(And me, I just wish I ran this resize operation inside a screen session... but ok at least I do have -p)
edit
Wait, I just realised, why not SSH in, make an LVM snapshot and e2fsck that while the resize is still running? I did that 5× in a row during the "Relocating blocks" phase and although I get "contains a file system with errors, check forced" on every check, it never found any errors. Now of course don't ask me about data integrity.
edit
Pretty interesting response from tytso@ himself BTW at https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=574292#30


text:
Q: Get real size of background image of div using JavaScript So, I wanted to take the real size of a backgound image of a div, and searching in the site I found some great JavaScript code in this url: http://jsbin.com/olozu/2/edit.
However, it doesn't seem to work in my site and I can't find out why, though my code is identical to the above.
Here's my code (JS Bin)
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body onclick="picture()">
  <img id="topicinfo" src="http://pierre.chachatelier.fr/programmation/images/mozodojo-original-image.jpg"><
</body>
</html>

JavaScript:
function picture()
{
  var a=document.getElementById("topicinfo").height;
  alert(a);
}

If you click the image on the left, it shows 0 width 0 height.

A: You are trying to get information from the style attribute, but since you did not declare the image background inline, style is null. You have to get the computed style. See this thread here; the top answer provides a comprehensive explanation.
Read CSS property of an element using JavaScript
Another good resource:
http://javascript.info/tutorial/styles-and-classes-getcomputedstyle#getcomputedstyle-and-currentstyle
EDIT: More specifically, what you have to do is this:
var imageUrl = getComputedStyle(document.getElementById('topicinfo'));
var imageSrc = imageUrl.replace(/"/g,"")
                       .replace(/url\(|\)$/ig, "");

I still recommend looking at those resources though, as they provide a nice way to implement a function to make this sort of action easily repeatable.


text:
Q: Perl HTML::Treebuilder XPATH Table Tags with no ID/Name I want to extract some text which is present in a specific table cell in the HTML page.
Now, the problem is, this cell is present inside a table tag which has no ID/Name.
I am using HTML::TreeBuilder::XPath to extract the value using XPATH expressions.
Here is how the HTML content looks like:

Some Text
The Text I want comes here

This is how my XPATH expression looks like:
@nodes=$tree->findnodes(q{//table[8]/tr/td[2]/text()});
print $_->string_value."\n" foreach(@nodes); # corrected, thanks mirod.

It does not display the output.
I have used, table[8] above since this is the eight table tag in the HTML page (assuming the index starts from 1).
Also, I have used td[2] since I want the innerHTML between the second td tag.
Thanks.

A: What happens if you remove the text() at the end of the XPath query? I would think that calling string_value on the td itself would be enough.
Also method calls are not interpolated in strings, so you need to write print $_->string_value, "\n".
This will give you the text of the content, not the markup though. For that you would need to use as_HTML, and strip the outer tags (there is no method in HTML::Element that gives you the inner HTML):
#!/usr/bin/perl

use strict;
use warnings;

use HTML::TreeBuilder::XPath;

my $tree= HTML::TreeBuilder::XPath->new_from_content( <DATA>);

my @nodes=$tree->findnodes(q{//table[1]/tr/td[2]});
print $_->string_value, "\n" foreach(@nodes); # text
print $_->as_HTML, "\n" foreach(@nodes);      # outerHTML

__DATA__

Some Text
The Text I want comes here with nested content

A: The mirod approach should work for you.
But I recommend to use findvalues instead of findnodes if you need text  content.
Try to run this code and show output:
my @values=$tree->findvalues(q{//table[8]//tr[1]//td});
print $_, "\n" foreach(@values);


text:
Q: Users' can not access sites even with correct permissions We're running on SharePoint Online at our company and I can't seem to figure out why users are unable to access specific sites inside a site collection.
They have proper read permissions and are in the correct group, but are still getting access denied errors.  I removed all the unique permissions on the site and nothing should be preventing them from access this resource.  Even "Checking Permissions" on a users profile shows they should have access.  There are no webparts on the page with unique permissions as well.  They can only see a resource on this page when I added them to a full control owners group.
Any ideas?  I'm at a loss here.

A: I figured it out... The "Shared Documents" library had versionion set to only allow "users who can edit items" to see draft items in the library.  The document was edited, thus creating major versions.

A: If the permissions are correct, one possibility is the default page of the site might be checked-out or in draft state. That also result in Access Denied error.

A: remove the user completely from the site collection and then add the user again.


text:
Q: Restlet send "get" request to server and process response I would like to send a get request to a remote server using Restlet and receive the response (as Json).
Here is my starting point, please feel free to complete:
ClientResource cr = new ClientResource("https://"+url);

JsonRepresentation r = (JsonRepresentation) cr.get();

r.getJsonObject().get("MY_VALUE");

Restlet version 2.1.7
Json: {"title":"General Terms & Conditions","version":"20022014_001"}

A: In fact, you don't use the JsonRepresentation the right way. The method get of the class ClientResource doesn't return an element of such type. You must use it as described below:
ClientResource cr = new ClientResource("https://"+url);
Representation repr = cr.get();
JsonRepresentation jsonRepr = new JsonRepresentation(repr);

String value = jsonRepr.getJsonObject().get("MY_VALUE");

Hope it helps you,
Thierry


text:
Q: Freeze a random number in Ruby I'm trying to build something that will randomly pick two objects from a list in Ruby (using Rails) and then perform basic operations on those objects. My current set up involves randomly picking numbers at the start - using these numbers to get objects from the database and then rendering those objects to index. However, now I'm trying to edit these objects using AJAX I'm running into a problem.
It seems that, when I click on a link that the random number in being recalculated and is causing my AJAX function not to work.
I've included (what I believe is) all relevant code below but let me know if you need to see anything else to get to the bottom of this. I'm looking to get the titles of the old animals and (ideally their previous ratings and) their new ratings to appear at the bottom of the page.
Thanks,
Matt
controllers/static_pages.rb
class StaticPagesController < ApplicationController
respond_to :html, :js
before_filter :pickanimals

def pickanimals
    @allAnimals = Animal.all
    @random_no = rand(@allAnimals.length)
    @animal = @allAnimals[@random_no]
    @allAnimals.delete_at(@random_no)
    @newRandom = rand(@allAnimals.length)
    @animal2 = @allAnimals[@newRandom]
end

  def index
    respond_to do |format|
        format.html
        format.js
    end
end

  def help
  end

  def about
  end

  def contact
  end

def league
end

def voting
    @votedAnimal = Animal.find(params[:id])
    if @votedAnimal == @animal
        @animal.rating += 1
        @animal2.rating -= 1
    else
        @animal.rating -= 1
        @animal2.rating += 1
    end
    Animal.transaction do
        @animal.save!
        @animal2.save!
    end
    respond_to do |format|
        format.html { redirect_to root_path }
        format.js
    end
end
end

app/views/static_pages/index.html.erb

Animal Attack

 Who will win when nature collides?

 <%= @animal.name %>

<%= link_to image_tag(@animal.attachment.url(:large)), voting_path(@animal.id), :remote => true, :confirm => "Rating:  "+@animal.rating.to_s  %>

 <%= @animal2.name %>

<%= link_to image_tag(@animal2.attachment.url(:large)), voting_path(@animal2.id), :remote => true, :confirm => "Rating:  "+@animal2.rating.to_s  %>

routes.rb
AnimalAttack::Application.routes.draw do

resources :animals

root to: 'static_pages#index'
match '/help' => 'static_pages#help'
match '/about' => 'static_pages#about'
match '/contact' => 'static_pages#contact'
match '/league' => 'static_pages#league'
match '/voting/:id' => 'static_pages#voting'

end

rake routes
    animals GET    /animals(.:format)          animals#index
        POST   /animals(.:format)          animals#create
 new_animal GET    /animals/new(.:format)      animals#new
edit_animal GET    /animals/:id/edit(.:format) animals#edit
 animal GET    /animals/:id(.:format)      animals#show
        PUT    /animals/:id(.:format)      animals#update
        DELETE /animals/:id(.:format)      animals#destroy
   root        /                           static_pages#index
   help        /help(.:format)             static_pages#help
  about        /about(.:format)            static_pages#about
contact        /contact(.:format)          static_pages#contact
 league        /league(.:format)           static_pages#league
               /animals(.:format)          animals#new
               /voting/:id(.:format)       static_pages#voting

A: I'm guessing @animal is being re-assigned because of your :before_filter. Unless you tell it otherwise, it'll execute before all actions (thus reassigning @animal before every controller action). You probably want to limit it to just the methods that need a newly-regenerated random number. For example:
before_filter :pickanimals, :only => :index

Also. Do you know about Array#sample? It's a built-in way of picking a random element from an array. You might find it useful here:
@animal, @animal2 = @allAnimals.sample(2)

ADDITIONALLY
Relying on instance variables in the controller like this is a pretty fragile way of passing information between functions. If your controller needs to know the ids of two models to have counters on each incremented or decremented based on user selection, why not just use a form to send those two ids to this controller action? So far, you'll only need two fields: chosen_animal_id and reject_animal_id.


text:
Q: Azure DevOps unable to deploy to Azure Web App Am currently trying to deploy an app from a Release Pipeline under Azure DevOps owned by Company A to an Azure App hosted on Azure owned by Company B.
Keep on getting this error when attempting to release stop the Azure App:

Error: Failed to get resource ID for resource type
  'Microsoft.Web/Sites' and resource name 'AppName'. Error: Could not
  fetch access token for Managed Service Principal. Please configure
  Managed Service Identity (MSI) for virtual machine
  'https://aka.ms/azure-msi-docs'. Status code: 400, status message: Bad
  Request

Am at a loss on how to solve this.
What has been done so far:

*

*Web App is created in Azure of Company B

*User from DevOps Company A Account is added as Guest User in Company Azure AD

*User has Contributor rights on the Web App

*Managed Service Identity is set to "On" on Web App

*The subscription of Company B and Web Apps can be seen and selected when setting up the release in Azure DevOps.

Am quite sure that more needs to be in order for the release deployment to work, but after an intensive search, I was not able to find anything.
Hope anyone here can advise.

A: Managed to find the solution to the problem I encountered.
It was related to the access rights of the guest account on the Azure subscription.
First of all "Managed Service Identity" was not related to this issue.
These are the steps that were followed to connect the Azure DevOps of Company A to the Azure of Company B:

*

*Created Web App in Company B Azure

*Azure DevOp's account from Company A, was added as a "Guest User"
in the Azure of Company B

*The DevOp's account is given Contributor rights on both the Azure
Subscription, and the Web app.

*In Company A's DevOps, add a "Azure Resource Manager". Choose the
settings of Company B's Azure as "Service Principal Authentication"

*Upon saving Azure Resource Manager, you will be prompted to login.
You will need to login with the admin account of Company B's Azure.

A: I had this problem, and it was an MSI issue but not resolved by creating a VM as is suggested elsewhere on the internet. In my case, I had reset the MSI ID of the app service, which broke the service connection in DevOps (though DevOps didn't tell me this -_-).
It was resolved by removing and re-adding the service connection in DevOps, and re-selecting it in the release pipeline settings.


text:
Q: Code Coverage issues when deploying change set I'm attempting to deploy a change set from my Sandbox to the production environment. The change set includes 1 Custom Object, several dozen custom fields, a controller (Apex class), and a static resource (an image file). When deploying the inbound change set, I get code coverage errors relating to 2 triggers. There are no triggers in my change set, so I'm confused as to why I'm getting these errors on this specific operation.
The only reason I could see this happening is if the triggers already on the live server, independent of this change set, are written so that they lack the appropriate code coverage. However, wouldn't this error have popped up when the triggers were committed?
I'm only in charge of a small portion of our SalesForce instance, so I lack the scope of responsibilities necessary to start messing with these unrelated triggers. Is there anything I can do to get my change set deployed with this being the case?

A: Regardless of what Apex code you are deploying, if you are deploying any Apex code to production, tests will need to run.  Given the defaults, you require:

*

*At least 75% code coverage throughout all Apex code. (For details on how this is calculated, look here.

*Greater than 0% code coverage on all triggers.

Now, if you are in a pinch and you need to deploy quickly, you can opt to "Run Selected Tests".  If you do so, you will only need test coverage of the classes/triggers you are deploying.  However, each individual test will require 75% code coverage.  Documentation here.
However, unless there are special circumstances, I would strongly recommend against this.  If items you are deploying interact with other code in the org, skipping the tests for that code could cause you to overlook dangerous errors you may be introducing into the codebase.

A: There are no triggers in your change set, but is there test code for the apex controller? Salesforce requires 75% cumulative code coverage, which includes Apex controllers, so if the code coverage in your production org is just above 75% and your controller is untested it could drag the total code coverage down to below the threshold. It's also possible that the total is already below 75% in your production environment, possibly caused by an admin changing workflow rules, validation rules, or process builder processes without checking tests.

A: So I wasted almost an entire day on this, but seems like I figured it out. Our salesforce has Apex classes that have 0% code coverage and that's bringing our percentage down and not letting me deploy code that's >90% coverage. Here's the trick: When deploying, select Run specified tests and put a comma delimited list of your test class names in your change set. This way you're able to deploy your changeset with good test coverage!


text:
Q: How to set global option IDs for product options in Opencart 3? I'm using opencart 3. And I am using product options for all products. I suppose to write a javascript to hide/show three product options when selecting another product option in all products. The option id are different for every product. How to add global id/global class for options.
for product 1:
<input name="option[1118]" value="" id="input-option1118" class="form-control" style="display: none;" type="text">

for product 2:
<input name="option[1229]" value="1229" id="input-option1229" class="form-control" style="display: block;" type="text">

Javascript code
$('#product #input-option1228').on('click', function(e) {
        e.preventDefault();
var waistDiv = document.getElementById("option-1229");
var waistInput = document.getElementById("input-option1229");
var hipDiv = document.getElementById("option-1231");
var hipInput = document.getElementById("input-option1231");
var heightDiv = document.getElementById("option-1232");
var heightInput = document.getElementById("input-option1232");
document.getElementById("input-option1228").onchange = function(){
waistDiv.style.display = (this.selectedIndex == '1144') ? "none" : "block";
waistInput.style.display = (this.selectedIndex == '1144') ? "none" : "block";
hipDiv.style.display = (this.selectedIndex == '1144') ? "none" : "block";
hipInput.style.display = (this.selectedIndex == '1144') ? "none" : "block";
heightDiv.style.display = (this.selectedIndex == '1144') ? "none" : "block";
heightInput.style.display = (this.selectedIndex == '1144') ? "none" : "block";
}
});

A: This has been asked a few times here:
Opencart how to related 2 options in a product and
How to add sub options in Opencart?
Summary: use an extension that handles "dependent/related options".


text:
Q: javax.net.ssl.SSLHandshakeException: No subject alternative DNS name matching example.com found I'm using a rest service to fetch data. Twice in the past several months, I received the following error: javax.net.ssl.SSLHandshakeException: No subject alternative DNS name matching example.com found.
I've read several posts that says it's something to do with LDAPS but LDAPS has nothing to do with the server/service I'm using. The problem seems to happen for several seconds and disappears on its own.
I don't have access to that server and the support told me that they did nothing nor changed anything from their side.
Not sure if it's related, I updated my lets encrypt certificate few days ago and the problem happened for several seconds a day and a half after I restarted my tomcat/java with the new certificate.
Any idea what to look for? Thanks


text:
Q: Display mysql data in php function Ok i got a problem now i want to display a data from the database and display it through a function now how do i do that??
like i have fetched a row from the database and its name is $row_field['data']; and it is correct now i have assigned a variable to it like this $data = $row_field['data']; now if i call it in a function it shows undefined variable even after i assigned it global in the function like this
function fun(){
    global $data;
    echo $data;
}

but if i assign it a value like 1 or 2 or anything it gets displayed without any error why is that so??

A: Global is evil. I dont know what you are trying to do, but why dont you just do the query in the function itself?

A: If it displays if you assign it a value like 1 or 2 while still in the global scope, then I can only assume that your database did not return the result you thought it did.  Does the database value display if you echo it out outside of the function?

A: If you have a column named data and your php call was something like
$result = mysql_query("SELECT data FROM mytable");

while ($row_field = mysql_fetch_assoc($result, MYSQL_NUM)) {
    ...
}

Then you could replace ... with print $row_field['data'].
Else please provide a snippet of your code where you query the db and retrieve the result.

A: When learning php try to start with simple things. For example in order to get some data from a database follow the examples from php website.
<?php

$conn = mysql_connect("localhost", "mysql_user", "mysql_password");

if (!$conn) {
    echo "Unable to connect to DB: " . mysql_error();
    exit;
}

if (!mysql_select_db("mydbname")) {
    echo "Unable to select mydbname: " . mysql_error();
    exit;
}

$sql = "SELECT id as userid, fullname, userstatus
    FROM   sometable
    WHERE  userstatus = 1";

$result = mysql_query($sql);

if (!$result) {
    echo "Could not successfully run query ($sql) from DB: " . mysql_error();
    exit;
}

if (mysql_num_rows($result) == 0) {
    echo "No rows found, nothing to print so am exiting";
    exit;
}

// While a row of data exists, put that row in $row as an associative array
// Note: If you're expecting just one row, no need to use a loop
// Note: If you put extract($row); inside the following loop, you'll
//       then create $userid, $fullname, and $userstatus
while ($row = mysql_fetch_assoc($result)) {
    echo $row["userid"];
    echo $row["fullname"];
    echo $row["userstatus"];
}

mysql_free_result($result);

If all this goes well go a little further change a little the while loop.
$myArray = array();

while ($row = mysql_fetch_assoc($result)) {
    $myArray[] = $row;
}

mysql_free_result($result);

// now you can start playing with your data
echo $myArray[0];

Small steps...


text:
Q: Python Pandas apply booknames to id number? A dataframe (df1) with a list of 20 book names and id numbers..
id, book
1,  name1
2,  name2
3,  name3
4,  name4

I want to take these id#'s and apply the book names to another larger table column which uses the same book id #s.
I've tried this code but it doesn't work:
for index, row in df1.iterrows():
    df2[df2['id'] == row['id'], 'id'] = row['book']

Thank you


text:
Q: Parser for simple expression in Prolog parseExp( ExpToParse, Op(Operand1, Operand2)) :-
    operand(ExpToParse, Diff, Operand1),
    operator(Diff, Diff2, Op),
    operand(Diff2, _, Operand2).

operand([H|L], L, H).
operator(['+'|R], R, add).
operator(['-'|R], R, sub).
operator(['*'|R], R, mul).
operator(['/'|R], R, div).

I am trying to implement parser for simple expressions, I mean something like: 2 + 4 etc.
But, I got the compiler error in the first line:
Syntax error: Operator expected

I cannot understand. I want to the second argument of the first term (Operator(Operand1, Operand2)) will be unified to add( 2, 4). I mean:
parseExp( [2, '+', 4] , X ).
?- X = add(2,4)
I don't undersant why a compiler has a problem.
And the second issue:
I know about DCG but I don't use it now because I as you can see I have a problem with understanding difference list. So, you are welcome to say someting about my code in that context.
Thanks in advance :)

A: It is not allowed to write Op(Operand1, Operand2) like in:
parseExp( ExpToParse, Op(Operand1, Operand2)) :-
  ...

instead, use:
parseExp( ExpToParse, RES) :-
  ...,
  RES =.. [ Op, Operand1, Operand2 ]

in your example, that means change code to:
parseExp( ExpToParse, RES ) :-
    operand(ExpToParse, Diff, Operand1),
    operator(Diff, Diff2, Op),
    operand(Diff2, _, Operand2),
    RES =.. [Op,Operand1, Operand2].


text:
Q: Understand SharedPreferences Android In android I want to make a basic login and registration application. I am following this tutorial. The application works properly and runs. I am just trying to understand the code now and after many google searches I can not understand some of the code and was wondering if somebody could help me understand it.
Below I have posted the method I do not understand and in comments highlighted what I do not understand - any clarification is much appreciated, I have also commented the code to what I believe the code does, if any of it is incorrect please tell me, you can also view all of the code on the tutorial website.
I am mainly confused about how the sharedpreferences works I have followed his tutorial on sharedpreferences too I understand that but do not understand this. Thank you and sorry if the problem is very basic
   private void checkLogin(final String email, final String password) {

    // Tag used to cancel the request
    String tag_string_req = "req_login";

    // Dialog stating trying to login
    pDialog.setMessage("Logging in ...");
    showDialog();

    // Send the request over to the database to check details
    StringRequest strReq = new StringRequest(Method.POST,
            AppConfig.URL_LOGIN, new Response.Listener<String>() {

        // Do this once you get a response
        @Override
        public void onResponse(String response) {
            Log.d(loginName, "Login Response: " + response.toString());
            hideDialog();

            // Break the response up into individual things and store in variables
            try {
                JSONObject jObj = new JSONObject(response);
                boolean error = jObj.getBoolean("error");

                // Check for error node in json
                if (!error) {

                   // I DO NOT UNDERSTAND THIS!!! how does this bit work?
                        // it sets the shared preferences login to true correct?
                        // but how does it set it true to only this particular user?
                        // Because it doesnt store the email and password along with it
                        // and sets its tag "isLoggedIn" and then saves it to the shared
                        // preferences
                    session.setLogin(true);

                    // Now store the user in SQLite
                    String uid = jObj.getString("uid");

                    JSONObject user = jObj.getJSONObject("user");
                    String name = user.getString("name");
                    String email = user.getString("email");
                    String created_at = user
                            .getString("created_at");

                    //I DO NOT UNDERSTAND THIS!!! Why do you need to do this & does this
                    //affect the MySQL DB at all?
                    db.addUser(name, email, uid, created_at);

                    // I DO NOT UNDERSTAND THIS!!! Why do you need to write LoginActivity.this
                    // do you not just write MainActivity?
                    Intent intent = new Intent(LoginActivity.this,
                            MainActivity.class);
                    startActivity(intent);
                    finish();
                } else {
                    // Error in login. Get the error message
                    String errorMsg = jObj.getString("error_msg");
                    Toast.makeText(getApplicationContext(),
                            errorMsg, Toast.LENGTH_LONG).show();
                }
            } catch (JSONException e) {
                // JSON error
                e.printStackTrace();
                Toast.makeText(getApplicationContext(), "Json error: " + e.getMessage(), Toast.LENGTH_LONG).show();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(loginName, "Login Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_LONG).show();
            hideDialog();
        }
    }) {

        /***************************************************************/
        //I DO NOT UNDERSTAND THIS WHOLE METHOD WHY DO YOU DO THIS?!!!
        /***************************************************************/
        @Override
        protected Map<String, String> getParams() {
            // Posting parameters to login url
            Map<String, String> params = new HashMap<String, String>();
            params.put("email", email);
            params.put("password", password);

            return params;
        }

    };

    // FINALLY I ALSO DO NOT UNDERSTAND WHY YOU DO THIS! AND WHAT DOES IT DO
    AppController.getInstance().addToRequestQueue(strReq, tag_string_req);
}

A: This adds a user to an SQL database:
 db.addUser(name, email, uid, created_at);

There should be a class somewhere that defines the actual function, which then creates the query that actually interacts with the database.
The intent changes the activity (what is rendered on the screen and what logic is handled):
LoginActivity.this: the context in the current class - this can be simplified to just this, but it's a bit of syntactic sugar in Java that attempts to clarify which this is being referred to.
MainActivity.class: the target activity
 Intent intent = new Intent(LoginActivity.this,
                        MainActivity.class);

The difference between two activities can be explained with the content of a game. The menu is "LoginActivity.this" and "MainActivity.class" is the actual game content

As for shared preferences, the usage is pretty straight-forward:

To obtain shared preferences, use the following method In your
activity:
SharedPreferences prefs = this.getSharedPreferences(
  "com.example.app", Context.MODE_PRIVATE);

To read preferences:
String dateTimeKey = "com.example.app.datetime";

// use a default value using new Date()
long l = prefs.getLong(dateTimeKey, new Date().getTime());

To edit and save preferences
Date dt = getSomeDate();
prefs.edit().putLong(dateTimeKey, dt.getTime()).apply();

(Source, posted by naikus)
The internal mechanics aren't something you need to worry about - the thing you really need to know is that it's able to save your data in a way you can use that doesn't involve directly accessing files (which has become a maze since Android 10).

EDIT:
Based on what I saw at the tutorial, the entire thing is to check if the login information entered exists in the database. The getParams() method defines what goes into the form data


text:
Q: Block Finder - Like Function I have a large string (more than 255 char) called strBlockText. This string includes random text and block numbers. The block numbers should to be in the format ###Block####-## (IE: 245Block6533-56) but sometimes someone enters the wrong block number format in the text - for example ##Block####-## or ###Block###-## or ##Block###-##...etc.
**Note, this is for plain text only.
I want to write a function that will be able to state, "Wrong block number format identified." when the block number is fat fingered.
This is the text I'm using as a sample:

This is a Test that we need to figure out why this isn't working.
24Block1234-23 This is a Test that we need to figure out why this
isn't working.  245Block4234-14 This is a Test that we need to figure
out why this isn't working.  This is a Test that 245Block6533-56 we
need to figure out why this isn't working.

This is the code...that I feel should work but isn't:
Dim strBlockText As String
Dim strBlockCheck As String

If (((strBlockText Like "*##Block####-##*") or _
     (strBlockText Like "*###Block###-##*") or _
     (strBlockText Like "*##Block###-##*")) And _
 (Not strBlockText Like "*###Block####-##*")) Then

    strBlockCheck = "Wrong block number format identified."

Else

    strBlockCheck = "Block number format acceptable."

End If

Would it be better to use a regex for this instead of like?...is there a reason like isn't working?

A: Consider this Sub using RegExp object with late binding:
Sub testRegExp2(strS)
Dim regexOne As Object, Matches As Object, Match As Object
'Set regexOne = New RegExp
Set regexOne = CreateObject("VBScript.RegExp")
regexOne.Pattern = "[0-9]+Block[0-9]+-[0-9]+"
regexOne.Global = True
Set Matches = regexOne.Execute(strS)
For Each Match In Matches
    If Not Match Like "###Block####-##" Then
        Debug.Print "Wrong block number format identified: " & Match
    Else
        Debug.Print "Block number format acceptable: " & Match
    End If
Next
End Sub


text:
Q: useContext returning undefined values Facing this problem where my context returns undefined values, all it is returning is the initial state. Here in the transaction list im trying to call the function deleteTransaction I defined, but its giving error that it is undefined. Please tell me if im missing something or need to add something.
These are my dependecies, just in case.
"dependencies": {
"@testing-library/jest-dom": "^5.11.10",
"@testing-library/react": "^11.2.6",
"@testing-library/user-event": "^12.8.3",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "4.0.3",
"web-vitals": "^1.1.1"
},

GlobalState.js:
import React, { createContext, useReducer } from 'react'
import AppReducer from './AppReducer'

const initialState = {
transactions: [
    {id:1, text:"Flower", amount:-20},
    {id:2, text:"Salary", amount:300},
    {id:3, text:"Book", amount:-10},
    {id:4, text:"Camera", amount:150}
]
}

export const GlobalContext = createContext(initialState)

export const GlobalProvider = (props) => {
const [state, dispatch] = useReducer(AppReducer, initialState)

const deleteTransaction = (id) => {
    dispatch({type:'DELETE_TRANSACTION', payload:id})
}

return (<GlobalContext.Provider value={{transactions:state.transactions, deleteTransaction}}>
    {props.children}
</GlobalContext.Provider>)
}

AppReducer.js:
export default (state, action) => {
switch(action.type) {
    case 'DELETE_TRANSACTION':
        return {
            ...state,
            transactions: state.transactions.filter(transaction => transaction.id !== action.payload)
        }
    default:
        return state
}
}

TransactionList.js:
import React, { useContext } from 'react'
import { GlobalContext } from '../context/GlobalState'
import { Transaction } from './Transaction'

export const TransactionList = () => {

const { transactions } = useContext(GlobalContext)

return (
    <>

History

            {transactions.map(transaction => (
                <Transaction key={transaction.id} {...transaction} />
            ))}

    </>
)
}

Transaction.js:
import React, { useContext } from 'react'
import { GlobalContext } from '../context/GlobalState'

export const Transaction = ({id, text, amount}) => {

const {deleteTransaction} = useContext(GlobalContext)

const sign = amount < 0 ? "-" : "+"

return (

        <li className={amount < 0 ? "minus" : "plus"}>
            {text} {sign}${Math.abs(amount)}<button onClick={() =>
deleteTransaction(id)} className="delete-btn">x</button>

)
}

A: Issue
Your default context value is missing the deleteTransaction function.
const initialState = {
  transactions: [
    {id:1, text:"Flower", amount:-20},
    {id:2, text:"Salary", amount:300},
    {id:3, text:"Book", amount:-10},
    {id:4, text:"Camera", amount:150}
  ]
}

export const GlobalContext = createContext(initialState)

Solution
Define your context's default value shape to match what is used by components and ensure that Transaction has a GlobalContext.Provider above it in the React tree.
const defaultValue = {
  transactions: [],
  deleteTransaction: () => {}, // <-- add a deleteTransaction function
}

export const GlobalContext = createContext(defaultValue);

Updating Context from a Nested Component

It is often necessary to update the context from a component that is
nested somewhere deeply in the component tree. In this case you can
pass a function down through the context to allow consumers to update
the context.
theme-context.js
// Make sure the shape of the default value passed to
// createContext matches the shape that the consumers expect!
export const ThemeContext = React.createContext({
  theme: themes.dark,
  toggleTheme: () => {},
});


text:
Q: Connection of the curvature tensor on a geodesic and a Jacobi field Let $M$ be a Riemannian manifold equipped with the Levi-Civita connection $\nabla$, $\gamma : I \rightarrow M$ a geodesic of $M$ such that $0 \in I$. Let $Y,Z$ two Jacobi fields along $\gamma$ vanishing at $0$, that is
$$
\left\{
    \begin{array}{ll}
        \nabla^2_{\dot{\gamma}} Y + R(\dot{\gamma}, Y)\dot{\gamma} = 0,\quad Y(0) = 0 \\
        \nabla^2_{\dot{\gamma}} Z + R(\dot{\gamma}, Z)\dot{\gamma} = 0, \quad Z(0) = 0
    \end{array}
\right.
$$
where $R$ is the curvature tensor of $\nabla$.

Now I would like to show that $$\big\langle \nabla_{\dot{\gamma}}(R(\dot{\gamma}, Y)\dot{\gamma}), \nabla_{\dot{\gamma}} Z \big\rangle = \big\langle R(\dot{\gamma}, \nabla_{\dot{\gamma}}Y)\dot{\gamma}, \nabla_{\dot{\gamma}} Z \big\rangle$$
I tried to go back to the definition of $R$, or used the fact that $\partial_t\langle Y,Z \rangle = \langle \nabla_{\dot{\gamma}}Y,Z \rangle + \langle Y,\nabla_{\dot{\gamma}}Z \rangle$ for every vector fields along $\gamma$, but I didn't succeed. Do you have any idea how to proceed ?

A: Note that this equation holds at $t=0$. For any vector $V$, we have at $t=0$
$$
 \begin{align}
  \langle \nabla_{\dot\gamma} (R(\dot\gamma, Y)\dot\gamma), V\rangle
&= \frac{d}{dt}\langle  R(\dot\gamma, Y)\dot\gamma, V\rangle - \langle  R(\dot\gamma, Y)\dot\gamma, \nabla_{\dot\gamma}V\rangle \tag{1}\\
&=\frac{d}{dt}\langle  R(\dot\gamma, V)\dot\gamma, Y\rangle \tag{2}\\
&=\langle \nabla_{\dot\gamma} (R(\dot\gamma, V)\dot\gamma), Y\rangle+ \langle  R(\dot\gamma, V)\dot\gamma, \nabla_{\dot\gamma}Y\rangle \tag{3}\\
&= \langle  R(\dot\gamma, \nabla_{\dot\gamma}Y)\dot\gamma, V\rangle .\tag{4}
 \end{align}
$$
In $(1)$ we used $\langle  R(\dot\gamma, Y)\dot\gamma, \nabla_{\dot\gamma}V\rangle = 0$ since $Y(0)=0$. For the same reason, we know that $\langle \nabla_{\dot\gamma} (R(\dot\gamma, V)\dot\gamma), Y\rangle$ vanishes in $(3)$. In equations $(2)$ and $(4)$ we used the symmetry property $$\langle R(X,Y)Z,W\rangle = \langle R(Z,W)X,Y\rangle.$$
Setting $V = \nabla_{\dot\gamma}Z$ gives the equation.


text:
Q: How to solve 401 authorization error when trying to publish to GitHub packages from gradle This is my first attempt at publishing a package on GitHub.
I have set up my project's build.gradle according to the instructions - the relevant excerpt from the former being:
publishing {

    publications {
        mavenJava(MavenPublication) {
            artifactId = 'moss'
            from components.java
        }
    }

    repositories {
        maven {
            name = "GitHubPackages"
            url = "https://maven.pkg.github.com/hansi_b/moss"
            credentials {
                username = project.hasProperty("GITHUB_ACTOR") ? GITHUB_ACTOR : ""
                password = project.hasProperty("GITHUB_REPO_PAT") ? GITHUB_REPO_PAT : ""
            }
        }
    }
}

I am using

*

*my GitHub username as the username (in GITHUB_ACTOR) and

*a PAT with the necessary scopes (AFAICS: delete:packages, repo, write:packages) as the password.

Both are set in my ~/.gradle/gradle.properties, and they look right when I do a println from the publish task. I have verified that with the right user name and PAT, I can clone a repo from the command line.
However, when I issue gradle publish, the result is:
Execution failed for task ':publishGprPublicationToMavenRepository'.
> Failed to publish publication 'mavenJava' to repository 'GitHubPackages'
   > Could not PUT 'https://maven.pkg.github.com/hansi_b/moss/org/hansi_b/moss/0.2.0/moss-0.2.0.jar'. Received status code 401 from server: Unauthorized

I get the same error if I mess up either the username or the password on purpose.  I have retried publishing with a different, private repository, and failed in the same manner.
Is there any way to get further information on what is going wrong? Is there some piece of configuration I am missing?
I'd be grateful for any pointers.

A: I was in your exactly situation and I resolved removing quotes in my properties file, like that:
//Before
gpr.user="cappee"
gpr.key="key"

//After
gpr.user=cappee
gpr.key=key

I hope you can fix with this advice!


text: Q: Why is a torsion group called so? Torsion in physics is understood as a "twist". I can see that in a torsion group, all elements when acted upon itself a certain number of times will give itself. So I can see the idea of rotating back to itself. Are torsion groups used to represent "twists" in topology and/or geometry? Also in what context was torsion group first used historically?


text:
Q: Crash while converting html to string in UILabel in IOS I have Home Page/view where I display all the records (only title and date) in a listview.
When I click on any record I display complete information of record in another page.
Each and every record has a html string value which needs to be displayed.
To display html content I use UILabel control which gets displayed correctly.
But when Navigation is done back and forth between 2 pages/views it crashes.
The crash report is pointing to memory related to issues.
modifiedContent = [modifiedContent stringByAppendingString:[NSString stringWithFormat:@"<style>body{font-family: '%@'; font-size:%fpx;}</style>",@"Helvetica",17.0f]];

content.attributedText = [[NSAttributedString alloc] initWithData:[modifiedContent dataUsingEncoding:NSUnicodeStringEncoding]
                              options:@{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
                              NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)}
                              documentAttributes:nil
                              error:nil];

Is there a need to change the above code to handle memory leakage or is there a need of different encoding type.
It needs to be supported from IOS 7 to IOS Current Version
Below is the stack Trace
MyAppName(1098,0x39d7000) malloc: *** mach_vm_map(size=151552) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
MyAppName(1098,0x39d7000) malloc: *** mach_vm_map(size=151552) failed (error code=3)
*** error: can't allocate region
*** set a breakpoint in malloc_error_break to debug
2015-11-19 10:18:59.643 MyAppName[1098:436403] -[__NSCFType encodeWithCoder:]: unrecognized selector sent to instance 0x76954080
2015-11-19 10:18:59.646 MyAppName[1098:436403] -[NSCoder(CACoderAdditions) CA_encodeObject:forKey:conditional:]: ignoring exception -[__NSCFType encodeWithCoder:]: unrecognized selector sent to instance 0x76954080
2015-11-19 10:18:59.650 MyAppName[1098:436403] *** NSKeyedArchiver warning: replacing existing value for key ''; probable duplication of encoding keys in class hierarchy
2015-11-19 10:18:59.660 MyAppName[1098:436403] *** NSKeyedArchiver warning: replacing existing value for key ''; probable duplication of encoding keys in class hierarchy
2015-11-19 10:18:59.662 MyAppName[1098:436403] *** NSKeyedArchiver warning: replacing existing value for key ''; probable duplication of encoding keys in class hierarchy
2015-11-19 10:18:59.675 MyAppName[1098:436403] *** NSKeyedArchiver warning: replacing existing value for key ''; probable duplication of encoding keys in class hierarchy
2015-11-19 10:18:59.677 MyAppName[1098:436403] *** NSKeyedArchiver warning: replacing existing value for key ''; probable duplication of encoding keys in class hierarchy
2015-11-19 10:18:59.785 MyAppName[1098:436403] *** NSKeyedArchiver warning: replacing existing value for key ''; probable duplication of encoding keys in class hierarchy
(lldb)

A: Since you state that the code doesn't use ARC, you're leaking a NSAttributedString instance every time the quoted code is run. To fix this, you can do this (I'm using an unorthodox formatting here to make it slightly more readable here on SO; adapt it to your coding style, please):
NSAttributedString *attributed = [[NSAttributedString alloc]
    initWithData:[modifiedContent dataUsingEncoding:NSUTF8StringEncoding]
    options:@{
        NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,
        NSCharacterEncodingDocumentAttribute: @(NSUTF8StringEncoding)
    }
    documentAttributes:nil
    error:nil];
content.attributedText = attributed;
[attributed release];

(Also: use NSUTF8StringEncoding instead of NSUnicodeStringEncoding or at least be consistent which you're using; you've created data using one encoding but told in the options that it would be in another encoding.)


text:
Q: Output of "df -h" to while loop, for list of host I want to print disk space percentage, path and host for 100+ machines. I have created below script to do that. But it's just working for the first host not for the rest of all in the host list. I slimmed down the possibility of error is with executing raw SSH command. Pls suggest any alternative. Thanks.
#!/bin/bash
set -x
echo "starting..."

begin ()
{
threshold=60
while read host
 do
  finder
 done <hosts.txt
}

finder ()
{
ssh ops@$host 'df -h' | grep -o '[0-9]\+%'| grep -o '[0-9]\+'| while read percent
do
  if [ $percent -gt $threshold  ]
   then
   path=`ssh ops@$host 'df -h' | tr -s " " | grep -oE "$percent% /[a-z]\+|$percent% /" | cut -d " " -f2`
   echo "Alert! Time to wipe off! It is $percent% in \"$path\" at $host"
  else
   echo "Info: It is $percent in $path at $host"
 fi
done
}

begin

It gives me result like this: Alert! Time to wipe off! It is 61% in "/" at 192.168.8.31
my hosts.txt looks like below:
192.168.8.31
192.168.7.41
192.168.7.42
192.168.8.32

So, in the script I'm executing df -h in each host via ssh and for each line of the df -h command I'm checking with the threshold value. If the condition is true alerting the guys, if not, just informing. Pls help me to understand what went wrong ? thanks :)


text:
Q: PHP/MYSQL: Update Query where value is missing from WHERE clause I think I know the answer to this but want to get confirmation.
If you have a simple update query with a where clause and the value of the variable in the where clause is missing, does that mean every record gets updated?
//let's say $name is empty

UPDATE users SET name= 'Jason' WHERE userid = '$name'

is that the same as

UPDATE users SET name= 'Jason' WHERE userid = ''

Is the behavior that every record would get updated?
And, if so, is there anything you can put in the SQL to prevent this potential catastrophe?
Thanks for guidance.

A: Both queries will update all records where userid column is empty. But it doesn't means that rows with userid value which is equal to NULL will be affected. If you want to use WHERE against NULL column, read how to working with NULL values.

A: If the variable is empty, or without a value, or "", and on your table there is no record where userid is empty or null, then no record will be updated as the where-condition would favor no record, however if there is any record with empty userid, then the record will be updated with the values you provided to the respective columns.


text:
Q: Failed Heroku deploy: sh: 1: ng: not found Failed Heroku deploy. Been looking at other similar stack overflow posts and changing package.json file trying solutions that have worked for others with no luck. I am not sure if this is a port issue, or a package.json issue or something completely different. Any help, tips or advice is greatly appreciated!
Heroku logs:

2019-02-09T08:32:56.609533+00:00 heroku[web.1]: State changed from crashed to starting
2019-02-09T08:33:00.956199+00:00 heroku[web.1]: Starting process with command `npm start`
2019-02-09T08:33:03.430137+00:00 heroku[web.1]: State changed from starting to crashed
2019-02-09T08:33:03.257739+00:00 app[web.1]:
2019-02-09T08:33:03.257781+00:00 app[web.1]: > the-lottery-genie-mean@0.0.0 start /app
2019-02-09T08:33:03.257783+00:00 app[web.1]: > ng serve
2019-02-09T08:33:03.257784+00:00 app[web.1]:
2019-02-09T08:33:03.294426+00:00 app[web.1]: sh: 1: ng: not found
2019-02-09T08:33:03.304958+00:00 app[web.1]: npm ERR! file sh
2019-02-09T08:33:03.305986+00:00 app[web.1]: npm ERR! code ELIFECYCLE
2019-02-09T08:33:03.306367+00:00 app[web.1]: npm ERR! errno ENOENT
2019-02-09T08:33:03.309015+00:00 app[web.1]: npm ERR! syscall spawn
2019-02-09T08:33:03.310700+00:00 app[web.1]: npm ERR! the-lottery-genie-mean@0.0.0 start: `ng serve`
2019-02-09T08:33:03.310912+00:00 app[web.1]: npm ERR! spawn ENOENT
2019-02-09T08:33:03.311266+00:00 app[web.1]: npm ERR!
2019-02-09T08:33:03.311514+00:00 app[web.1]: npm ERR! Failed at the the-lottery-genie-mean@0.0.0 start script.
2019-02-09T08:33:03.314421+00:00 app[web.1]: npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
2019-02-09T08:33:03.324652+00:00 app[web.1]:
2019-02-09T08:33:03.324892+00:00 app[web.1]: npm ERR! A complete log of this run can be found in:
2019-02-09T08:33:03.325013+00:00 app[web.1]: npm ERR!     /app/.npm/_logs/2019-02-09T08_33_03_316Z-debug.log
2019-02-09T08:33:03.411224+00:00 heroku[web.1]: Process exited with status 1

package.json:

{
  "name": "the-lottery-genie-mean",
  "version": "0.0.0",
  "scripts": {
    "preinstall": "npm link @angular/cli ",
    "heroku-postbuild": "ng build --prod",
    "postinstall": "",
    "ng": "ng",
    "start": "node server.js",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/cli": "^7.1.4",
    "@angular/compiler-cli": "~7.0.0",
    "@angular/animations": "~7.0.0",
    "@angular/common": "~7.0.0",
    "@angular/compiler": "~7.0.0",
    "@angular/core": "~7.0.0",
    "@angular/forms": "~7.0.0",
    "@angular/http": "~7.0.0",
    "@angular/platform-browser": "~7.0.0",
    "@angular/platform-browser-dynamic": "~7.0.0",
    "@angular/router": "~7.0.0",
    "core-js": "^2.5.4",
    "json": "^9.0.6",
    "rxjs": "~6.3.3",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^0.13.1",
    "@angular/language-service": "~7.0.0",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.5.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "protractor": "~5.4.0",
    "ts-node": "~7.0.0",
    "tslint": "~5.11.0",
    "typescript": "~3.1.1"
  },
  "engines": {
    "node": "10.15.1",
    "npm": "6.4.1"
  }
}

server.js file
app.listen(PORT, '0.0.0.0', function () {
console.log("Node app is running at localhost:" + app.get('port'));

})

A: Did you check the debug log here /app/.npm/_logs/2019-02-09T08_33_03_316Z-debug.log ?
I suggest looking into the debug log first to get us more details to solve the problem.
UPDATE
Its an H10 error. "heroku[router]: at=error code=H10 desc="App crashed"
method=GET path="/favicon.ico" host=angular-lottery-genie.herokuapp.com
request_id=30e63a79-c395-4d2a-9987-938bcc350629 fwd="50.250.113.70" dyno=
connect= service= status=503 bytes= protocol=https"

Your app crashed. Here are some things you can do:
1.) Restart heroku. You should have heroku CLI installed. Here's the link: Heroku CLI Install . And run heroku restart on your terminal.
2.) Use port that Heroku dynamically sets which can be accessed usually at process.env.PORT, and set your desired port as backup:
app.listen(process.env.PORT || 3000, function(){
  console.log("Node app is running at localhost:" + app.get('port'));
});

3.) Try to check your node and npm version by typing in your terminal:
node --version
npm --version

And update the node and npm versions indicated under your package.json file:
"engines": {
  "node": "10.15.1",
  "npm": "6.4.1"
}

Another UPDATE for your questions:
npm ERR! enoent ENOENT: no such file or directory

These errors are usually related to corruption or incompatibility of packages. What you can do:
1.) Make sure no other instances of node are running in the backgound and retry your npm command.
2.) Delete the node_modules directory and package-lock.json (if you have any). Reinstall packages running npm install (or any command you're using to install the packages) in your terminal inside your project directory.
3.) Upgrade node to the latest version, delete node_modules directory and package-lock.json, and reinstall the packages.
4.) If npm still does not work for you, try yarn package manager (Yarn).
5.) If packages installation still fail, check the error logs file for a detailed report of the error.
Hope this helps!

A: You might need to add the devkit/builder, make sure its in the right sequence. I added it in bold so make sure if you are gonna copy paste to remove the asterix from the beginning and end.
"@angular/cli": "^7.1.4",
"@angular/compiler-cli": "~7.0.0",
"@angular/animations": "~7.0.0",
"@angular/common": "~7.0.0",
"@angular/compiler": "~7.0.0",
"@angular/core": "~7.0.0",
"@angular/forms": "~7.0.0",
"@angular/http": "~7.0.0",
"@angular/platform-browser": "~7.0.0",
"@angular/platform-browser-dynamic": "~7.0.0",
"@angular/router": "~7.0.0",
**"@angular-devkit/build-angular": "^0.13.1",
"@angular/language-service": "~7.0.0",**
"core-js": "^2.5.4",
"json": "^9.0.6",
"rxjs": "~6.3.3",
"zone.js": "~0.8.26"

A: In my experience, the deployment of an app that works locally is not always straightforward in Heroku. There are several cases like this in StackOverflow without a definitive solution, specially related to "'library' not found". For someone with a similar problem (trying to deploy AngularJS in Heroku) I would recommend check first functional tutorials like these:

*

*https://devcenter.heroku.com/articles/mean-apps-restful-api
Almost-Oficial documentation. It describes a more complex app but you can discard some things.

*https://medium.com/better-programming/how-to-deploy-your-angular-9-app-to-heroku-in-minutes-51d171c2f0d This guy shows a working Angular tutorial deployed in Heroku.

A: move some devDependencies to dependencies (angular 9 example)
 npm i @angular/cli @angular-devkit/build-angular @angular/compiler-cli typescript --save-prod

or set NPM_CONFIG_PRODUCTION to false
here is an answer to similar question


text:
Q: Multiple regression - moderation Best,
For my thesis I have to do a multiple regression analysis for a moderation.
My results show that model 1 (without interaction term) is significant, but model 2 (with interaction term) is not significant. Model 2 is also not significantly responsible for more variance.
But in an article I'm following for the interpretation, it seems that if model 2 is not significant, complete moderation occurs. And if model 2 is significant, there are also main effects. Is this correct?
So should model 2 not be significant for a potential moderation effect?
How would you interpret my result (in attachment) and which article do you follow?
The interpretation of the article I used:

*

*Fit a regression model (block 1) predicting the outcome variable Y from both the predictor variable X and the moderator variable M. Both effects as well as the model in general (R2) should be significant.

*Add the interaction effect to the previous model (block 2) and check for a significant R2
change as well as a significant effect by the new interaction term. If both are significant, then moderation is occurring.
=>  If the predictor and moderator are not significant with the interaction term added, then
complete moderation has occurred.
=>  If the predictor and moderator are significant with the interaction term added, then
moderation has occurred, however the main effects are also significant.


text:
Q: efficient way to check if at least one row contains a null value in a DataView? I need  to do a test in a DataView to check if at least one row contains one cell with a null value. What is the best way to do it in your opinion ?
Thanks in advance.

A: As SLaks mentioned, you're going to need to loop over the rows and the items in each row. You can do this with LINQ like this:
bool hasNull = view.Table.Rows.OfType<DataRow>()
    .Any(r => r.ItemArray.Any(o => o == DBNull.Value));

Or you can write the loop yourself, something like:
private bool HasEmptyItem(DataView view)
{
    foreach (DataRow row in view.Table.Rows)
    {
        foreach (DataColumn col in view.Table.Columns)
        {
            if (row[col] == DBNull.Value)
                return true;
        }
    }
    return false;
}

While the LINQ version is a lot more compact, it's still going to loop over the rows and columns, so take your pick.
Update:
Based on comments, here's a better sample based on what you're trying to do. This simply loops over the rows, and checks if a give column is null (make sure to use DBNull.Value with a DataTable), and if so, just sets it to false to prevent problems in your case. Just change IS_DEFAULT_COL to be the correct index.
const int IS_DEFAULT_COL = 1;
foreach (DataRow row in view.Table.Rows)
{
    if (row[IS_DEFAULT_COL] == DBNull.Value)
        row[IS_DEFAULT_COL] = false;
}

A: Without measuring, I would guess that the answer is a nested loop.


text:
Q: how to fetch data while selecting there id without reload page how to make live fetching data by express mysql and pug  ?
i have a data in mysql and i want in view page when i select column_id then  fetch column_name and when i select second column_id then fetch the second column_name .. all this possible working automatically without reloading page ?
select(name='column')
 each x in columns
  option(value=2) column2

if id already selected then fetch there name here ...
h1 you selected id of this name : column2


text:
Q: Recalculate checksum in SVN dump after manual changes As we are migrating with a project to a public source hosting, I wanted to remove some "personal" information from the SVN repository. I did fine so far with removing paths or revisions using svndumptool and svndumpfilter. However I want to remove some text from a particular file in the repository as well.
I removed the text manually by regex'ing the dump and that worked fine, but when I want to use the dump, I get a checksum mismatch. This is obviously because I changed the file but didn't update the checksum.
Is there any tool that recalculates the checksum for the files in a dump? Or is there a good editing tool for files (should allow regex replacements) inside a svn dump that also updates the checksum?

A: Okay, I didn't want to wait longer for answers, so I wrote a script myself, which I will share with you. It utilizes SvnDumpTool, or rather its library. To do custom actions you are required to edit the source (and know a bit python). A simple example is included and I think the abstraction the script provides is quite good.
Anyway, hope it is as useful for you as it was for me, although it took me quite a while to get it working like that:
SvnDumpToolEdit.py on Github.


text:
Q: Can a Thread sleep for less than half milli seconds in Java/ Other language? [Edit]: After getting answer I understood its not specific to Java, its related to OS scheduler as well, so adding other tags
Is it possible in Java to make a thread sleep for a nano seconds.
Of course after looking the Thread api where we can pass nano seconds as well in sleep method, the answer could be yes.
But I doubt after looking the implementation/ source of sleep method in Thread class, which is:
public static void sleep(long millis, int nanos)
throws InterruptedException {
    if (millis < 0) {
        throw new IllegalArgumentException("timeout value is negative");
    }

    if (nanos < 0 || nanos > 999999) {
        throw new IllegalArgumentException(
                            "nanosecond timeout value out of range");
    }

    if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
        millis++;
    }

    sleep(millis);
}

Now according to the logic it is increasing milli seconds by 1 if the passed nano seconds is more than half milli seconds. But this sounds illogical to me, lets say I have written a code where one of my thread is waiting for say some 40000 nano seconds (in practical scenario it might not be the case) which is less than half milli seconds that means my thread will not wait at all.
Can someone please comment on the same and why this design was decided to wait for milli seconds rather than nano seconds?
Also what would guarantee that the thread wakes up accurately?

A: You can use LockSupport's parkNanos
LockSupport.parkNanos(400_000);

however this is not the same as sleep (it is not interruptable) and all it does is pass the request to the OS. On Windows 8 for example, even parkNanos(1) might sleep for 1 milli-second.
As biziclop pointed out, there Javadoc mentions

The call spuriously (that is, for no reason) returns.

This happens rarely in my experience, but it does happen.

However, you are right that Thread.sleep() will always sleep for at least 1 ms.  On Win XP it might sleep for 16 ms (1/60th of a second)

Also what would guarantee that the thread wakes up accurately?

Using a real time operating system.
What I do, is don't go to sleep but rather busy wait.  This way I can stop for a give amount of time with more accuracy.  If you run your thread on an isolated CPU (In Linux) you can reduce the variation to about 10 micro-seconds
An example of busy waiting
long end = System.nanoTime() + delay;
while (System.nanoTime() < end) { /* busy waiting */ }

or if you want to be slightly more friendly
while (System.nanoTime() < end)
     Thread.yield();


text:
Q: Cache locality in Flink I have a stream of data, containing a key, that I need to mix and match with data associated with that key. Each key belongs to a partition, and each partition can be loaded from a database.
Data is quite big and only a few hundred out of hundreds of thousands partitions can fit in a single task manager.
My current approach is to use partitionCustom based on the key.partition and cache the partition data inside a RichMapFunction to mix and match without reloading the data of the partitions multiple times.
When the number of message rate on a same partition gets too high, I hit a hot-spot/performance bottleneck.
What tools do I have in Flink to improve the throughput in this case?
Are there ways to customize the scheduling and to optimize the job placements based on setup time on the machines, and maximum processing time history?

A: It sounds like (a) your DB-based data is also partitioned, and (b) you have skew in your keys, where one partition gets a lot more keys than other partitions.
Assuming the above is correct, and you've done code profiling on your "mix and match" code to make that reasonably efficient, then you're left with manual optimizations. For example, if you know that keys in partition X are much more common, you can put all of those keys in one partition, and then distribute the remaining keys amongst the other partitions.
Another approach is to add a "batcher" operator, which puts up to N keys for the same partition into a group (typically this also needs a timeout to flush, so data doesn't get stuck). If you can batch enough keys, then it might not be so bad to load the DB data on demand for the partition associated with each batch of keys.


text:
Q: PHP best practices to prevent session hijacking in authentication
Possible Duplicate:
Preventing session hijacking

I am coding up my login and authentication system for a PHP web application and looking for best practices to prevent session hijacking. The login page set's sessions:
$_SESSION['email_address'] = $_POST['email_address'];
$_SESSION['ip_address'] = $_SERVER['REMOTE_ADDR'];

Then in every page and action I check to make sure the session exists, and the ip address stored in the session matches the ip address in $_SERVER['REMOTE_ADDR'].
if(isset($_SESSION['email_address']) && isset($_SESSION['ip_address']) && $_SESSION['ip_address'] == $_SERVER['REMOTE_ADDR']) {
     //valid auth
}

Reading online though, some people say simply checking the ip address is NOT good enough. What else is needed? Also, there is talk of using session_regenerate_id(). How does that factor into my code? Do I call session_regenerate_id() on every page?
Thanks.

A: If you're coding your own login system, I hope you're extremely versed in all the security issues and don't rely on questions given to you by people online like this site.  $_SESSION is automatically a security risk on any shared server.  $_SESSION is available to ALL php processes running on the system.  If any of your clients end up running your software on a shared server, you will have to plan for that.
Its also extremely easy to code mistakes that create security holes.  You'd be better off using Yii or some framework that already provides strong authenatication measures.   Yii, for instance, is about as basic as you can get if you want to be able to boil it down to just giving you some login and security plugins to start.


text:
Q: Programmatically play video with sound on Safari and Mobile Chrome With the release of OSX High-Sierra*, one of the new features in Safari is that videos on websites will not auto play anymore and scripts can't start it either, just like on iOS. As a user, I like the feature, but as a developer it puts a problem before me: I have an in-browser HTML5 game that contains video. The videos do not get automatically played anymore unless the user changes their settings. This messes up the game flow.
My question is, can I somehow use the players' interaction with the game as a trigger for the video to start playing automatically, even if said activity is not directly linked to the video element?
I cannot use jQuery or other frameworks, because of a restraint that my employer has put on our development. The one exception is pixi.js which - among all other animations - we are also using to play our videos inside a pixi container.
*The same restriction also applies on Mobile Chrome.

A: Yes, you can bind on event that are not directly ones triggered on the video element:

btn.onclick = e => vid.play();
<button id="btn">play</button>

<video id="vid" src="https://dl.dropboxusercontent.com/s/bch2j17v6ny4ako/movie720p.mp4"></video>

So you can replace this button with any other splash screen requesting an user click, and you'll be granted access to play the video.
But to keep this ability, you must call at least once the video's play method inside the event handler itself.
Not working:

btn.onclick = e => {
  // won't work, we're not in the event handler anymore
  setTimeout(()=> vid.play().catch(console.error), 5000);
  }
<button id="btn">play</button>

<video id="vid" src="https://dl.dropboxusercontent.com/s/bch2j17v6ny4ako/movie720p.mp4"></video>

Proper fix:

btn.onclick = e => {
  vid.play().then(()=>vid.pause()); // grants full access to the video
  setTimeout(()=> vid.play().catch(console.error), 5000);
  }
<button id="btn">play</button>

<video id="vid" src="https://dl.dropboxusercontent.com/s/bch2j17v6ny4ako/movie720p.mp4"></video>

Ps: here is the list of trusted events as defined by the specs, I'm not sure if Safari limits itself to these, nor if it includes all of these.

Important note regarding Chrome and preparing multiple MediaElements
Chrome has a long-standing bug caused by the maximum simultaneous requests per host which does affect MediaElement playing in the page, limiting their number to 6.
This means that you can not use the method above to prepare more than 6 different MediaElements in your page.
At least two workarounds exist though:

*

*It seems that once a MediaElement has been marked as user-approved, it will keep this state, even though you change its src. So you could prepare a maximum of MediaElements and then change their src when needed.

*The Web Audio API, while also concerned by this user-gesture requirement can play any number of audio sources once allowed. So, thanks to the decodeAudioData() method, one could load all their audio resources as AudioBuffers, and even audio resources from videos medias, which images stream could just be displayed in a muted <video> element in parallel of the AudioBuffer.

A: In my case i was combining transparent video (with audio) with GSAP animation. The solution from Kaiido works perfectly!
First, on user interaction, start and pause the video:
videoPlayer.play().then(() => videoPlayer.pause());

After that you can play it whenever you want. Like this:
const tl = gsap.timeline();
tl.from('.element', {scale: 0, duration: 5);
tl.add(() => videoPlayer.play());

Video will play after the scale animation :).
Tested in Chrome, Safari on iPhone


text:
Q: JDBC Connection to Snowflake with Private key - without passphrase I'm working on a Java client based code that is tryint to connect to snowflake JDBC with a private key
I have searched online and found this links:
https://domohelp.domo.com/hc/en-us/articles/360042931854-Snowflake-Using-Key-Pair-Authentication-Connector
https://docs.snowflake.com/en/user-guide/jdbc-configure.html
and other links, all required to use passphrase
and my code
        Properties p = new Properties();
    p.setProperty(USER, jdbcDetails.username);
    String privateKey = jdbcDetails.getPrivateKey().replace("-----BEGIN ENCRYPTED PRIVATE KEY-----\n", "");
    privateKey = privateKey.replace("\n-----END ENCRYPTED PRIVATE KEY-----", "");
    String passphrase = "abcdefg";
    EncryptedPrivateKeyInfo pkInfo = new EncryptedPrivateKeyInfo(Base64.getMimeDecoder().decode(privateKey));
    PBEKeySpec keySpec = new PBEKeySpec(passphrase.toCharArray());
    SecretKeyFactory pbeKeyFactory = SecretKeyFactory.getInstance(pkInfo.getAlgName());
    PKCS8EncodedKeySpec encodedKeySpec = pkInfo.getKeySpec(pbeKeyFactory.generateSecret(keySpec));
    KeyFactory keyFactory = KeyFactory.getInstance("RSA");
    PrivateKey encryptedPrivateKey = keyFactory.generatePrivate(encodedKeySpec);
    p.put("privateKey", encryptedPrivateKey);
    return p;

It seems this code is valid for connection but after talking with our DBA
he told me that he is able to connect without spesify the passphrase
with this command:
snowsql -h a-b-c-d.snowflakecomputing.com -a abcd.AWS_US_EAST-1 -u username  -d  INTEGRATION_ENGINE    --private-key-path ~postgres/ADHOC/12345/rsa_key.p8 -q "select 1"

how can i connect using jdbc with a private key - and without passspharse ?

A: Its possible to create 2 types of users with encrypted private key and decrypted private key, this snippet build the private key object and needs to be added to properties
there are 2 instances of - pemObject one for encrypted which requires passPharase and one who dont
//    pemObject instanceof PKCS8EncryptedPrivateKeyInfo (encrypted private key)
// pemObject instanceof PrivateKeyInfo decypted private key
public class PrivateKeyReader {

    public static PrivateKey get(File file, String passPhrase)
    {
        try {
            PrivateKeyInfo privateKeyInfo = null;
            Security.addProvider(new BouncyCastleProvider());
            // Read an object from the private key file.
            final PEMParser pemParser = new PEMParser(new FileReader(file));
            final Object pemObject = pemParser.readObject();
            if (pemObject instanceof PKCS8EncryptedPrivateKeyInfo) {
                // Handle the case where the private key is encrypted.
                final PKCS8EncryptedPrivateKeyInfo encryptedPrivateKeyInfo = (PKCS8EncryptedPrivateKeyInfo) pemObject;
                final InputDecryptorProvider pkcs8Prov = new JceOpenSSLPKCS8DecryptorProviderBuilder().build(passPhrase.toCharArray());
                privateKeyInfo = encryptedPrivateKeyInfo.decryptPrivateKeyInfo(pkcs8Prov);
            } else if (pemObject instanceof PrivateKeyInfo) {
                // Handle the case where the private key is unencrypted.
                privateKeyInfo = (PrivateKeyInfo) pemObject;
            }
            pemParser.close();
            final JcaPEMKeyConverter converter = new JcaPEMKeyConverter().setProvider(BouncyCastleProvider.PROVIDER_NAME);
            return converter.getPrivateKey(privateKeyInfo);
        } catch (Exception ex){
            throw new RuntimeException(ex.getMessage(), ex);
        }
    }
}

in order to load it to the connection i used:
PrivateKey privateKey = PrivateKeyReader.get(tempPublicKeyFile, jdbcDetails.getDecryptedPassPhrase());
    p.put("privateKey", privateKey);


text:
Q: How to integrate baguetteBox.js in the BST WordPress Starter theme? I am trying to modify the starter WordPress theme BST for a personal project.
In it I want to have a custom page template with bootstrap elements. This page will show various images in the form of galleries.
I also need to import the baguetteBox.js plugin so that I can use its lightbox effect.
The pages have been created in html and they work. The custom page template is created and the design is the same as the html variant.
However when importing the scripts in WordPress (by using wp enque and wp register) the console cannot define baguetteBox. So I guess I am doing something wrong.
Here is the official guide on installing this Bootstrap plugin:
The enqueue code that I am using is placed in the bst-master/function/enqueues.php file:
For baguetteBox.min.js:
wp_register_script('baguetteBox-js', get_template_directory_uri() . '/js/baguetteBox.min.js', false, null, true, array('jquery'));
wp_enqueue_script('baguetteBox-js');

I have also tried without array('jquery') - no changes. I am also not sure where/how to place the "async" part (as recommended by the developers).
For baguetteBox.min.css:
wp_register_style('baguetteBox-css', get_template_directory_uri() . '/css/baguetteBox.min.css', false, null);
wp_enqueue_style('baguetteBox-css');

The problem is with the <script>baguetteBox.run('.tz-gallery', {filter: /.angelov.+\.(gif|jpe?g|png|webp)/i});</script> which I cannot figure out how and where to place so I just tried to add it inside the page template php file and also in the Insert Headers/Footers plugin.

A: So I figured out my own solution. First of all the classic (and recommended) way of adding scripts for WordPress was failing somehow. So I decided to place the script in the header.php file before the closing head tag and without async. I also moved the script in the js folder of the child theme.
It looks like this:
    <script src="<?php echo get_stylesheet_directory_uri();?>/js/baguetteBox.min.js"> </script>

Next I placed the below code in the custom page template file right after the final closing <div> tag:
    <script>baguetteBox.run('.tz-gallery', {filter:/.angelov.+\.(gif|jpe?g|png|webp)/i});</script>

And it all worked out like a charm.


text:
Q: Find an object in a library (here, it is the NavigationLayout of the Kivy library) I am learning Kivy and I'm not used to .kv, so I am trying to learn the "hard way" first.
Problem: there is not a lot of documentation for interaction with Kivy except .kv.
I'm stuck with the import of the NavigationLayout, I tried to find it on the official Github, but I failed !
from kivy.uix.boxlayout import BoxLayout
from kivymd.uix.toolbar import MDToolbar
from kivy.properties import ObjectProperty
from kivy.uix.screenmanager import ScreenManager, Screen
from kivymd.app import MDApp
#from kivy import road.to.navigationlayout import NavigationLayout

class App(MDApp):
    def build(self):
        screen_manager = ScreenManager()
        main_screen = Screen()
        main_box = BoxLayout()
        main_toolbar = MDToolbar()
        main_toolbar.title = "Hello there !"
        #navigation_layout = NavigationLayout()

        screen_manager.add_widget(main_screen)
        main_screen.add_widget(main_box)
        main_box.add_widget(main_toolbar)
        return screen_manager

App().run()

PS: If you have tips to find out where objects are situated in new libraries, I would be happy to heard them!

A: It was in the MDKivy library. (I found it with this other stack overflow post)
from kivymd.uix.navigationdrawer import NavigationLayout


text:
Q: PHP:Why printf("%.2f", 0.02) output 0.024?why is not 0.02? When the code is :
<?php printf("%.2f", 0.02);?>

output: 0.02

When the code is :
<?php var_dump(printf("%.2f", 0.02));?>

output: 0.02int(4)

When the code is :
<?=printf("%.2f", 0.02)?>

output: 0.024

<?=var_dump(printf("%.2f", 0.02))?>

output: 0.02int(4)

Why <?=printf("%.2f", 0.02)?> isn't outputing 0.02? Does <?=printf("%.2f", 0.02)?> correspond to <?php var_dump(printf("%.2f", 0.02));?>?

A: I think you've missed something important here. From the manual

Returns the length of the outputted string.

So, while printf outputs to the browser, it returns the length of 0.02, which is 4


text:
Q: PyPandoc including hypertargets when converting from html to latex i have been trying to convert the HTML string question_text_html(which is a mathematical question written in HTML ) in the code below to a latex string using pypandoc. but it keeps including the irrelevant strings like "\protect\hypertarget{MJX-...}....." in the converted string
import pypandoc
from selenium import webdriver

driver.get("https://nigerianscholars.com/past-questions/mathematics/?
    show_answers=yes")
question_blocks=driver.find_elements_by_class_name('question_block')
for question_block in question_blocks:
 question_text=question_block.find_element_by_class_name('question_text')
 question_text_html=question_text.get_attribute('innerHTML')
 question_latex=pypandoc.convert_text(question_text_html,'tex',format='html')
 print(f'Question Html is {question_text_html}')
 print(f'Question latex is {question_latex}')

it usually gives
 Question Html is
Differentiate <span class="mjx-chtml MathJax_CHTML" data-mathml='<math xmlns="http://www.w3.org/1998/Math/MathML"><mo stretchy="false">(</mo><mn>2</mn><mi>x</mi><mo>+</mo><mn>5</mn><msup><mo stretchy="false">)</mo><mn>2</mn></msup><mo stretchy="false">(</mo><mi>x</mi><mo>&#x2212;</mo><mn>4</mn><mo stretchy="false">)</mo></math>' id="MathJax-Element-1-Frame" role="presentation" style="font-size: 114%; position: relative;" tabindex="0">(2x+5)2(x−4)<math xmlns="http://www.w3.org/1998/Math/MathML"><mo stretchy="false">(</mo><mn>2</mn><mi>x</mi><mo>+</mo><mn>5</mn><msup><mo stretchy="false">)</mo><mn>2</mn></msup><mo stretchy="false">(</mo><mi>x</mi><mo>−</mo><mn>4</mn><mo stretchy="false">)</mo></math> with respect to x.

Question latex is Differentiate
{}\protect\hypertarget{MathJax-Element-1-Frame}{}{\protect\hypertarget{MJXc-Node-1}{}{\protect\hypertarget{MJXc-Node-2}{}{\protect\hypertarget{MJXc-Node-3}{}{{(}}\protect\hypertarget{MJXc-Node-4}{}{{2}}\protect\hypertarget{MJXc-Node-5}{}{{x}}\protect\hypertarget{MJXc-Node-6}{}{{+}}\protect\hypertarget{MJXc-Node-7}{}{{5}}\protect\hypertarget{MJXc-Node-8}{}{{\protect\hypertarget{MJXc-Node-9}{}{{)}}}{\protect\hypertarget{MJXc-Node-10}{}{{2}}}}\protect\hypertarget{MJXc-Node-11}{}{{(}}\protect\hypertarget{MJXc-Node-12}{}{{x}}\protect\hypertarget{MJXc-Node-13}{}{{−}}\protect\hypertarget{MJXc-Node-14}{}{{4}}\protect\hypertarget{MJXc-Node-15}{}{{)}}}}{\((2x + 5)^{2}(x - 4)\)}}\((2x+5)^2(x-4)\)
with respect to x.

How can i remove all the "\protect\hypertarget{MJXc-Node-10}" from the latex leaving only
Differentiate {\((2x + 5)^{2}(x - 4)\)}}\((2x+5)^2(x-4)\)
with respect to x.

A: With MathJax, the equation is actually there in TeX notation initially. The spans are created by MathJax Javascript for the equation layout in HTML. Currently, you let MathJax first render the equation, grab the rendered equation and then try to convert it back to the original TeX equation. It would be more straightforward to directly read the TeX equation without the indirection of Javascript rendering.
To achieve that, you would just need to disable Javascript in Selenium. For example with the Firefox driver this should do the trick:
from selenium.webdriver.firefox.options import Options
from selenium import webdriver

opts = Options()
opts.preferences.update({
    "javascript.enabled": False,
})
driver = webdriver.Firefox(options=opts)

Alternatively, if you need to process the rendered version with Javascript enabled for some reason, you could try to get hold of the content of the script element inside the
. It contains the full equation, but without TeX math markup:

......

This way you would not have to remove the spans. You would then need to enclose it in TeX math markup \(...\) for the PDF.


text:
Q: system of non-linear differential equations $x'=y^2$ and $y'=x^2$ I am working on Exercise 2.90 in Jeffrey M. Lee's book Manifolds and Differential Geometry. To solve it, I need to solve the following system of non-linear differential equations:
$$
\begin{array}{rcl}
\displaystyle \frac{dx}{dt}&=&y^{2} \\
\displaystyle \frac{dy}{dt}&=&x^{2}
\end{array}
$$
Integrating the second equation and substitution into the first equation gives me
$$
dx=\left(\int{}x^{2}\,dt\right)^{2}dt
$$
but I don't know where to go from there.

A: One approach is to guess at the form of solutions.  I tried exponentials and products and that didn't seem to work.  Polynomials went nowhere.  But then I tried power functions.  A solution is $$ x = \frac{-1}{t}, y = \frac{-1}{t}$$

A: Rather than guess, you can also look at $dy/dx = (dy/dt)/(dx/dt)$ which leads to
$$ \frac{dy}{dx} = \frac{x^2}{y^2} \implies y^2 dy = x^2 dx \implies y^3 = x^3 + C. $$


text:
Q: How to understand the "Limits Step Size" and "Dominates Error" in Dymola Dymola provides a function to analyze the numeric integration process, the main two results are "Limits Step Size" and "Dominates Error", I did some tests in my model, as showed in the following screenshot.
But I got a few questions when trying to analyze these data:

*

*How does the integrator choose the integral step size in Dymola?

*With "Limits Step Size", does this mean that the integrator has to use smaller step size so that integration of the corresponding variable could converge?

*With "Dominate Error", does this mean that the corresponding variable causes a critical error during the iteration?

A: *

*There are several different integrators in Dymola. Which step controller is used depends on what is most suitable for the chosen integrator. As has been previously noted the default integrator is Dassl which implements a BDF method. The logic for choosing step size is rather complex and it is intertwined with the integration order selection. In a nutshell, Dassl makes an estimate of the local error and then chooses step size and order to match the estimate with the user-provided tolerance. For details please refer to Numerical Solution of Initial-Value Problems in Differential-Algebraic Equations, although there may be adaptions made to the solver used in Dymola.

*"Limits step size" means that the error of this variable (and possibly also errors of other variables) was so large that the integrator had to discard the step and redo the step with a smaller step size.

*From the Dymola manual:

The number of times the variable dominates the error, i.e. has an
  integration error larger than any other state variable.

So, to answer your question: This does not mean a critical error (instead see "Limits step size" above). Rather, this just means that in this particular step the error of this state was the largest comparing over all states. The step may have been successful.

A: I know more about OpenModelica than Dymola, but i guess the following is generally true:

*

*The Dassl-Integrator (which is standard) uses the BDF-Method
(backwards differentiation formulae) and solves a nonlinear system
with newton to compute the state derivatives. Somewhere you can
provide a integrator tolerance (i guess default would be 10^-6). The
solver chooses the stepsize for newton such that it can respect that
error tolerance. I think this is approximated by looking at the
regularity of the jacobian. How close it is to singularity. Something something eigenvalues.

*Limits step size: The variable was the most constraining one. Not for convergence but for error tolerance. Plus the step size had to actually be lowered, i think otherwise it is not tracked here.

*Dominates error: This one is for convergence failures caused by this variable i think. It was furthest from the value where it should be. Usually something like full pivoting and small fiddling with values (in addition to lowering the step size) will be done here. About this last one i am not 100% sure though.