text:
Q: YouTube Apps Script API only runnable by accounts without a YouTube channel? This is such a strange issue and there seems to be no documentation of it anywhere online.
Whenever I try to execute a script that requires authorization to access an API, the code will only continue executing after authorization if I choose to authorize it from a GMail account, but not a YouTube account.
The code literally does not execute after choosing to authorize it from a YouTube account.  Even a Logger.Log() call on Line 1 of the function will not trigger unless the code is authorized from a GMail account only.
When authorizing from a YouTube account, it will continually loop and request authorization forever without continuing.  When authorizing from a GMail account, the code doesn't work because it is requesting YouTube data.
The problem of course is that I'm trying to access Analytics data from my YouTube account, which the GMail account does not have.
Really hoping someone is able to provide insight into this.  I've tested in multiple browsers, different YouTube accounts, GMails, etc. and the issue persists.
It also happens with any code that requests YouTube's Analytics API.  Replicable with the sample code found here, pasted below: https://developers.google.com/youtube/analytics/v1/code_samples/apps-script#export_youtube_analytics_data_to_google_sheets
function spreadsheetAnalytics() {
  // Get the channel ID
  var myChannels = YouTube.Channels.list('id', {mine: true});
  var channel = myChannels.items[0];
  var channelId = channel.id;

  // Set the dates for our report
  var today = new Date();
  var oneMonthAgo = new Date();
  oneMonthAgo.setMonth(today.getMonth() - 1);
  var todayFormatted = Utilities.formatDate(today, 'UTC', 'yyyy-MM-dd')
  var oneMonthAgoFormatted = Utilities.formatDate(oneMonthAgo, 'UTC', 'yyyy-MM-dd');

  // The YouTubeAnalytics.Reports.query() function has four required parameters and one optional
  // parameter. The first parameter identifies the channel or content owner for which you are
  // retrieving data. The second and third parameters specify the start and end dates for the
  // report, respectively. The fourth parameter identifies the metrics that you are retrieving.
  // The fifth parameter is an object that contains any additional optional parameters
  // (dimensions, filters, sort, etc.) that you want to set.
  var analyticsResponse = YouTubeAnalytics.Reports.query(
    'channel==' + channelId,
    oneMonthAgoFormatted,
    todayFormatted,
    'views,likes,dislikes,shares',
    {
      dimensions: 'day',
      sort: '-day'
    });

  // Create a new Spreadsheet with rows and columns corresponding to our dates
  var ssName = 'YouTube channel report ' + oneMonthAgoFormatted + ' - ' + todayFormatted;
  var numRows = analyticsResponse.rows.length;
  var numCols = analyticsResponse.columnHeaders.length;

  // Add an extra row for column headers
  var ssNew = SpreadsheetApp.create(ssName, numRows + 1, numCols);

  // Get the first sheet
  var sheet = ssNew.getSheets()[0];

  // Get the range for the title columns
  // Remember, spreadsheets are 1-indexed, whereas arrays are 0-indexed
  var headersRange = sheet.getRange(1, 1, 1, numCols);
  var headers = [];

  // These column headers will correspond with the metrics requested
  // in the initial call: views, likes, dislikes, shares
  for(var i in analyticsResponse.columnHeaders) {
    var columnHeader = analyticsResponse.columnHeaders[i];
    var columnName = columnHeader.name;
    headers[i] = columnName;
  }
  // This takes a 2 dimensional array
  headersRange.setValues([headers]);

  // Bold and freeze the column names
  headersRange.setFontWeight('bold');
  sheet.setFrozenRows(1);

  // Get the data range and set the values
  var dataRange = sheet.getRange(2, 1, numRows, numCols);
  dataRange.setValues(analyticsResponse.rows);

  // Bold and freeze the dates
  var dateHeaders = sheet.getRange(1, 1, numRows, 1);
  dateHeaders.setFontWeight('bold');
  sheet.setFrozenColumns(1);

  // Include the headers in our range. The headers are used
  // to label the axes
  var range = sheet.getRange(1, 1, numRows, numCols);
  var chart = sheet.newChart()
                   .asColumnChart()
                   .setStacked()
                   .addRange(range)
                   .setPosition(4, 2, 10, 10)
                   .build();
  sheet.insertChart(chart);

}
youtube.gs

A: There is a related issue ticket which Google have marked as 'Wont't fix' which describes your problem:

If you are trying to use the YouTube API to get data about a YouTube Channel that you manage using the Google+ association system, it will get you stuck in an infinite loop. Google+ pages can "own" a YouTube channel, and the authorization will not work when trying to use one of those channels

Google do have a suggested workaround:

use the OAuth2 library to authorize access to the G+ page, and then use UrlFetchApp instead of the YouTube Advanced service to make requests to the API

As this is a problem I've also encountered I've published a detailed tutorial that uses the YouTube Data API. As the code you require also needs access via to the YouTube Analytics API there is some additional setup required detailed below and referencing the part in the tutorial:

*

*Add a YouTube Analytics library with id 1MWD64g7dq_ZhlN8HU_O6BRu5xNwywhp8V76utKowZEtcirEgO3t_JFFL (Part 1.4)

*Add additional scopes to getYouTubeService() for yt-analytics-monetary.readonly and yt-analytics.readonly (Part 2.2)
// Set the scope and additional Google-specific parameters.
.setScope(["https://www.googleapis.com/auth/youtube",
          "https://www.googleapis.com/auth/youtube.force-ssl",
          "https://www.googleapis.com/auth/youtube.readonly",
          "https://www.googleapis.com/auth/youtubepartner",
          "https://www.googleapis.com/auth/youtubepartner-channel-audit",
          "https://www.googleapis.com/auth/yt-analytics-monetary.readonly",
          "https://www.googleapis.com/auth/yt-analytics.readonly"])

*Enabling the YouTube Analytics API as well as the YouTube Data API (Part 3.4)
There is also some minor modification in your code sample as to enable the library autocomplete e.g. YouTube.Channels.list() becomes YouTube.channelsList() and YouTubeAnalytics.Reports.query() becomes YouTubeAnalytics.reportsQuery()
All these changes have been included in this example sheet. You'll still need to do all the setup of the console project outlined in the tutorial and in the auth.gs sheet (I've modified the example to run in @OnlyCurrentDoc to avoid app verification).
Note: when you run logRedirectUri() you need to authenticate with your Google Drive account and when copy the authentication url in a new browser tab select the YouTube account you want data for.

A: Make sure that you are using the right scope for this. To retrieve the information about a specific reporting job that has been scheduled for a channel or content owner, you must use the following authorization scopes:

*

*https://www.googleapis.com/auth/yt-analytics.readonly

*

*View YouTube Analytics reports for your YouTube content. This scope provides access to user activity metrics, like view counts and rating counts.

*https://www.googleapis.com/auth/yt-analytics-monetary.readonly

*

*View YouTube Analytics monetary reports for your YouTube content. This scope provides access to user activity metrics and to estimated revenue and ad performance metrics.

Check this link for more information.


text:
Q: How to move windows between dual monitors by using arrow buttons instead of dragging I had dual monitors at a previous job that had the ability to move windows from one screen to the other by the click of an arrow button at the top of the window. I just got dual monitors at my new job and my windows do not have the arrow buttons, I have to drag the windows if I want to move them. Is there a way to get the arrow buttons added to the windows of my computer so that i have the one-click capability to move them from screen to screen?

A: Win + Shift +  arrow key  moves the selected window from screen to screen in a multi-monitor configuration in Windows versions 7 and later.
This capability is built-in to Windows and does not require additional software.
The arrow buttons you mention are likely part of a piece of video controller software that comes with certain types of video cards, usually "workstation" class cards such as Matrox.

redpajama_set_name: RedPajamaStackExchange


text:
Q: ICollection<> inside ICollection<> in Razor - can't retrieve the model names I'm wondering how to resolve the problem. I'm developing an ASP.NET MVC app
I have a models
public class SearcherString
{
    public int ID { get; set; }
    public string Description { get; set; }
    public virtual ICollection<Path> Path { get; set;
    public SearcherString()
    {
        Path = new List<Path>();
    }
}

public class Path
{
    public int ID { get; set; }
    public int CategoryID { get; set; }
    public string CategoryName { get; set; }
}

I'm passing it in my Controller (I'm writing my model into my database and then I'm retrieving it)
public ActionResult Index()
{
    return View(db.SearchersString.ToList()
}

And I have a View with:
@model IEnumerable<App.Models.SearcherString>

The problem is in my View, I can't display the names from Path model
  (CategoryID, CategoryName)

I tried to do:

            @Html.DisplayNameFor(model => model.Description)

        @foreach (var item in Model)
        {
            foreach (var path in item.Path)
            {

                    @Html.DisplayName(path.CategoryID.ToString())

                    @Html.DisplayName(path.CategoryName)

            }
        }

    @foreach (var item in Model)
    {

                @Html.DisplayFor(modelItem => item.Description)

            @foreach (var path in item.Path)
            {

                    @Html.DisplayFor(modelItem => path.CategoryID)

                    @Html.DisplayFor(modelItem => path.CategoryName)

            }

                @Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
                @Html.ActionLink("Details", "Details", new { id = item.ID }) |
                @Html.ActionLink("Delete", "Delete", new { id = item.ID })

    }

But I have only:

Could someone help me with this problem?

Edit:

Is there a way to change the Html.DisplayName to Html.DisplayNameFor here?
@Html.DisplayName(path.CategoryID.ToString())

A: You should include navigation property to your query:
public ActionResult Index()
{
    return View(db.SearchersString.Include(c=>c.Path).ToList()
}

A: Your Model is incorrect.
public SearcherString()
{
    Path = new List<Path>();
}

This is not a property. This is treated as a Method, a special one. And it is a constructor. That Creates a Path object That is EMPTY.
If you want to have a one to many relationship. You would have to use the property for this and add a property of ID.
public int PathID {get; set;}
public virtual Path Path{get; set;}

Now you have a lazy loading property that will automatically save the ID property of the Path class into your SearchString model property PathID.
to get the PathID, you will specifically need to call the include function if you're using EntityFramework, which most likely the case.
public ActionResult Index(){

  return View(db.SearchersString.Include(c=>c.Path).ToList();
}


text:
Q: Compare Date with Timestamp in oracle 11g stored procedure I'm very confused from this problem. We use Oracle DB with stored procedures, these are called from C#.
This is problematic part of stored procedure:
  IF pi_from_date IS NOT NULL THEN
       where_part := where_part || 'and created_on >= ''' ||  pi_from_date || '''';
   END IF;
   IF pi_to_date IS NOT NULL THEN
       where_part := where_part || 'and created_on <= ''' ||  pi_to_date || '''';
   END IF;

pi_from_date and pi_to_date are IN parameters type of DATE. credated_on is column type of TIMESTAMP. I call this procedure from C# code and use C# type DateTime for pi_to_date and pi_from_date.
It isn't working. I don't get any results, but in DB are some records. I tried functions like TO_DATE, TO_CHAR, but nothing is working. Sometimes I get error:

SQL Error: ORA-00904: "APR": invalid identifier

Could you help me how to solve this problem, please?
Thanks.
EDIT:
Here is C# code:
var parameters = new OracleDynamicParameters();
parameters.Add("pi_from_date", filterData.From); //DateTime.Now.AddMonths(-1);
parameters.Add("pi_to_date", filterData.To); //DateTime.Now.AddMonths(1);

var payments = conn.Query<Payment>("TEST_PCG.find_proc", parameters, commandType: commandType.StoredProcedure);

In DB are records with date 1.8.2013.
Stored procedure:
PROCEDURE find_proc ( pi_from_date           IN DATE,
                          pi_to_date             IN DATE,
                          items_ret              OUT sys_refcursor)
AS
  stmt varchar2(32767);
  where_part varchar2(32767);
BEGIN
  -- select statement part
   stmt := 'SELECT * FROM (SELECT a.*, rownum r__ FROM (SELECT * FROM Payment WHERE 1=1 ';

   -- where statement part
   IF pi_from_date IS NOT NULL THEN
       where_part := where_part || 'and created_on >= ''' ||  pi_from_date || '''';
   END IF;
   IF pi_to_date IS NOT NULL THEN
       where_part := where_part || 'and created_on <= ''' ||  pi_to_date || '''';
   END IF;
   stmt := stmt || where_part;

   -- get ref cursor from query
   OPEN items_ret FOR stmt;
END find_proc;

A: Your Dynamic SQL considers your date value as a string, and depending on your machine, C# would convert the date into different formats of string (e.g. dd/mm/yyyy, DD-MM-YYYY..etc) so you need to specify that as well. If you have to use D-SQL then your where clause should convert the date value you are passing to a date using TO_DATE and have the same date format that you are converting to in C#


text:
Q: PHP increment integer onClick I've already searched for different ways to do this but no luck with fixing my problem.
My code looks basically like this:
<?php
   $attnum = 1;
?>

<button type="button" onClick="<?php $attnum++ ?>">+</button>

att<?php echo "$attnum" ?>:

When the page loads it have already added 1 on $attnum. I only want to add on $attnum when the button is pressed. What have I done wrong?
Thanks

A: If you want to do it server side, you can do it like this:
<?php
   session_start();
   // Page was not reloaded via a button press
   if (!isset($_POST['add'])) {
       $_SESSION['attnum'] = 1; // Reset counter
   }
?>

<form method='post'>
<input name='add' type="submit" value='+'>

att<?php echo $_SESSION['attnum']++ ?>:

</form>

If you want to do it client side, do it like this:
<button id='add' type="button">+</button>

att1:

A: You are mixing up HTML (client side) and PHP (server side).
If you want to increment a server variable in PHP whenever a user clicks the button, you have to notify the server, for instance using ajax call.

A: I implemented this by using Javascript, check this fiddle:
HTML:
<button id="button" type="button">+</button>

att1:

Javascript:
var button = document.getElementById('button');
var attnum = 1;
button.addEventListener('click', function(){
    document.getElementById('att').innerHTML = ++attnum;
});

https://jsfiddle.net/a79bb31b/9/

A: create a function using javascript instead and call it in the onClick attribute of the button.
HTML:
<button type="button" onClick='add()'>+</button>

att  :

add script tag somewhere (I put it in the bottom part usually):

A: Try Like this

<button type="button" onClick="funct('<?php $attnum++ ?>')">+</button>

att<?php echo "$attnum" ?>:

and create a new javascript function


text:
Q: How to use php to remove an XML element I'm still really new to using simpleXML with PHP.  I'm trying to use simpleXML to remove a segment from a sitemap XML document.
The document looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>http://www.test.com/</loc>
        <priority>1.0</priority>
    </url>
    <url>
        <loc>http://www.test.com/test.html</loc>
        <priority>0.6</priority>
    </url>
</urlset>

I would like to provide a specific <loc> web address, search the xml document for that address, then remove the parent <url> element that contains the web address i'm searching for.
Below is the code I though would work but I can't get it to work.

 $xml = simplexml_load_file('path-to-my-sitemap.xml');
 $addressToRemove = "http://www.test.com/test.html";
 $remove = simplexml_load_string("<url><loc>$addressToRemove</loc><priority>0.6</priority></url>");

 xml_remove($xml, $remove);

 $str = $xml->asXML();

 echo $str;
 ?>

 function xml_remove(SimpleXMLElement $xml, SimpleXMLElement $removeFrom) {
     $mainDom = dom_import_simplexml($xml);
     $removeFromDom = dom_import_simplexml($removeFrom);
     $mainDom->removeChild($removeFromDom);
 }

After running my script it should output:
<?xml version="1.0" encoding="UTF-8"?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
    <url>
        <loc>http://www.test.com/</loc>
        <priority>1.0</priority>
    </url>
</urlset>

Does anyone know what i'm doing wrong here?


text:
Q: How to run postgres in docker as non-root user? I know that running docker containers as root is not secure, so I would like to change they way I run them. I have a container running postgres, which up till now was run as root (default). However, when I add this line to my docker-compose file:
user: ${CURRENT_UID}

Where CURRENT_UID is:
export CURRENT_UID=$(id -u):$(id -g)

I get the following error in the container logs:
initdb: error: could not change permissions of directory "/var/lib/postgresql/data": Operation not permitted

fixing permissions on existing directory /var/lib/postgresql/data ... chmod: changing permissions of '/var/lib/postgresql/data': Operation not permitted

chmod: changing permissions of '/var/run/postgresql': Operation not permitted

The situation is the same when running the pg-admin container, with the error message:
PermissionError: [Errno 13] Permission denied: '/var/log/pgadmin'

The errors make sense of course, I am non root, yet postgres requires root access.
Does it mean it is impossible to run as non root?

A:
Does it mean it is impossible to run as non root?

In fact, the postgres service already runs as a non-root user. The startup process for the postgres container is effectively:

*

*Create necessary directories and set appropriate ownership

*Switch to the postgres user

*Start postgres

So if you start up the postgres image, even without specifying a user:
docker run -e POSTGRES_PASSWORD=secret postgres:14

You will find that it's running as the postgres user:
# ps -fe
UID          PID    PPID  C STIME TTY          TIME CMD
postgres       1       0  0 16:11 ?        00:00:00 postgres
postgres      56       1  0 16:11 ?        00:00:00 postgres: checkpointer
postgres      57       1  0 16:11 ?        00:00:00 postgres: background writer
postgres      58       1  0 16:11 ?        00:00:00 postgres: walwriter
postgres      59       1  0 16:11 ?        00:00:00 postgres: autovacuum launcher
postgres      60       1  0 16:11 ?        00:00:00 postgres: stats collector
postgres      61       1  0 16:11 ?        00:00:00 postgres: logical replication launcher

It is entirely possible to start the image as a non-root user as well, but in this case you have to ensure that the necessary directories exist and have appropriate ownership. In an environment like Kubernetes/OpenShift the container orchestration system will take care of this for you when mounting a volume, but when using plain Docker (or docker-compose) you have to take care of it yourself.
Here's one way of doing it:

*

*Have an "initialization container" take care of setting volume permissions

*Start postgres only after the initialization container has finished

version: "3.9"

services:
  postgres-init:
    image: postgres:14
    volumes:
      - "postgres_data:/data"
    entrypoint:
      - sh
      - -c
      - |
        chown -R 2000:2000 /data

  postgres:
    depends_on:
      postgres-init:
        condition: service_completed_successfully

    image: postgres:14
    environment:
      POSTGRES_PASSWORD: "secret"
      PGDATA: /pgdata
    volumes:
      - "postgres_data:/pgdata"
    user: "2000"

volumes:
  postgres_data:


text:
Q: Mismatch in IOS useragent We have received today an useragent looking like this:
Mozilla/5.0 (iPhone; CPU iPhone OS 11_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E216 Myapp/10.2.0.3 (iPad4,4; iOS 11.3; gzip)
According to what i know from the mozilla specs the system details tell us it's and iphone and the platform details tell us it's an ipad?
Did somebody encounter this scenario before, and knows if we should detect it as an iphone or an ipad?
specs mozilla: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
As far as it concerns me it's an iphone, but am not 100% sure if i'm interpreting it correctly?

A: We figured out after time, that we are simply hitting fraud scenario's that try to pass both checks. So the fraudsters tries if it matches on one of both conditions. Topic closed.


text:
Q: Git: turn a directory with repos into a repo with submodules I'm developing my project in a directory "software". The project is divided into subdirectories:
software
  |
  +-- common_forms
  |     +-- .git
  +-- common_utils
  |     +-- .git
  +-- gui_app
  |     +-- .git
  + ...
  ... and so on.

Each subdirectory is a git repo; the master directory "software" is not a repo, just a root for the repos.
Now I want to turn the master directory "software" into a repo, and include those repositories as master repo's submodules. How can I do it not destroying the existing structure of directories and repos?

A: Let me add one word—sort of redundant, but important for emphasis—here:

Each subdirectory is already a git repo; the master directory "software" is not a repo, just a root for the repos.

In this case, just enter the software directory, run git init to create a .git directory / repository with this as its top level working tree, and use git submodule add for each of the various submodules.  See the git submodule documentation for specifics of git submodule add.  Then git add the .gitmodules file and commit, to make the initial commit.
Note that the repository argument to each git submodule add command can be the same as the path argument.  This affects what winds up in the .gitmodules file, which—once you make a commit in the superproject you've just created—is now available for future clones of this superproject.
That is, in the future, someone—let's give him or her a name, e.g., Pat—will run:
git clone $URL [<path>]

to clone the submodule from some URL (for now I'm assuming it's in $URL, though Pat might type in a literal string rather than use a variable).  Then Pat will cd into the clone and run, e.g., git submodule update --init.
Pat's clone here needs to have instructions for git submodule init or git submodule update --init.  These instructions tell Git what all the submodules are and how to git clone each one.  That is, rather than Pat having to, now, run one git clone for each submodule, Pat's git submodule update --init allows Pat's Git to read, from the .gitmodules file, the URLs and path names needed for each of these git clone operations.
A path-relative pseudo-URL, such as ./common_forms, turns into a URL-relative URL.  That is, since Pat cloned $URL to make the superproject, the .gitmodules URL ./common_forms turns into the URL ${URL}/common_forms.  If this is the right URL, everything is good.
On the other hand, suppose you plan to push the superproject to host1.example.com/supers/superproj.git but all the submodules will live at URLs like host2.example.com/subs/common_forms.git.  Then when you create the .gitmodules file—or before committing it, at least—you should make sure that the URL that will be stored in the .gitmodules file is host2.example.com/subs/common_forms or host2.example.com/subs/common_forms.git.  That way Pat will still be able to run git submodule update --init.
(It makes the most sense to arrange for the repository hosting to mirror the superproject-and-submodule layout, when that is possible, but it's not always possible.)


text:
Q: error of scala and spark version mismatch in Java maven code from IntelliJ I am trying to run Java/Scala (maven project) from IntelliJ (community 2019.2) on Mackbook pro.
My java:
  Java 12.0.2 2019-07-16
  Java(TM) SE Runtime Environment (build 12.0.2+10)
  Java HotSpot(TM) 64-Bit Server VM (build 12.0.2+10, mixed mode, sharing)

my code:
  SparkConf conf = new SparkConf().setAppName("test").setMaster("local"); // error !

  JavaSparkContext sc = new JavaSparkContext(conf);

My pom:
  <properties>
    <scala.version>2.11.12</scala.version>
    <scala.binary.version>2.11.12</scala.binary.version>
    <java.version>12</java.version>
    <maven.javadoc.skip>true</maven.javadoc.skip>
</properties>

 <dependency>
        <groupId>org.scala-lang</groupId>
        <artifactId>scala-xml</artifactId>
        <version>2.11.0-M4</version>
    </dependency>

  <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_2.11</artifactId>
        <version>2.4.5</version>
        <scope>compile</scope>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.module</groupId>
        <artifactId>jackson-module-scala_2.11</artifactId>
        <version>2.4.5</version>
    </dependency>

  <dependency>
        <groupId>org.apache.hadoop</groupId>
        <artifactId>hadoop-common</artifactId>
        <version>2.7.0</version>
        <scope>compile</scope>
    </dependency>

My scala and spark are all 2.11, why I still got the error :
 Exception in thread "main" java.lang.NoSuchMethodError:
 scala.Predef$.$conforms()Lscala/Predef$$less$colon$less;

Based on
 https://stackoverflow.com/questions/43845831/nosuchmethoderror-scala-predef-conformslscala-predeflesscolonless

I should not have this version mismatch ?
thanks
UPDATE
I have installed java11 based on
https://medium.com/w-logs/installing-java-11-on-macos-with-homebrew-7f73c1e9fadf
but, I got the same error.
 /Library/Java/JavaVirtualMachines/openjdk-11.0.2.jdk/Contents/Home/bin/java -agentlib:jdwp=transport=dt_socket,address=...

 Exception in thread "main" java.lang.NoSuchMethodError: scala.Predef$.$conforms()Lscala/Predef$$less$colon$less;

thanks

A: Java 12 is compatible with Java 13. And Java 13 is compatible with Scala versions 2.13.1 and 2.12.9. If possible, use at most Java 11 (which is compatible with Scala versions 2.13.0, 2.12.4, 2.11.12, 2.10.7 so you should be fine with your 2.11.12.
Nonetheless, it seems that Spark 3.0 is going to support JDK9+ SPARK-24417

Also: please change scala.binary.version in your pom.xml, it should be
<scala.binary.version>2.11</scala.binary.version>

instead of
<scala.binary.version>2.11.12</scala.binary.version>

With that change you can call dependencies without explicit Scala version, that is instead of
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-core_2.11</artifactId>
    <version>2.4.5</version>
    <scope>compile</scope>
</dependency>

you can say
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-core_${scala.binary.version}</artifactId>
    <version>2.4.5</version>
    <scope>compile</scope>
</dependency>


text:
Q: Configure keepalived for services (NodePort) on kubernates I have a k8s cluster which contains 2 nodes. And in the cluster I deployed 2 pods for the same application. Due to some reason I have to deploy a service (NodePort IP) for each pod, so totally I have 2 services the application, for example the service NodePort IP is 192.142.1.11 and 192.142.1.12. And use these 2 ips I can access the application from any node.
Now I am going to use keepalived to set up HA for the application. So:

*

*What's the best practice to install the keepalived service? On each k8s node or deploy it as pod?

*How to configure the interface in the keepalived.conf file? You know the NodePort ips are configured on kube-ipvs0 interface created by k8s and its status is down. Seems it cannot be used as the interface in keepalived.conf. Should I use the Node external interface if I start keepalived service on each node?

Thanks for your help.

A: If your final goal is masters HA / users  service load balancing in on-prem environment, then you can take a look on this two project:
Kubevip: can do both (HA masters + LoadBalancer type for user workload).
Metallb:
user workload LoadBalancer


text:
Q: df.to_html() shows in flask html source code, but not a browser's interpretation of that code. How to fix? I hope it will be easy but I cannot render a Dataframe.to_html() in flask. How to do it?
It renders me a code on my webpage but not a table. Screenshot is below.
I have a dictionary. Key is df_html and value is a html code from pandas DataFrame:
results = {
"df_html": df.to_html(index=False, classes='table table-stripped', header=True, escape=False)
}

Then I render it in my route method like this:
return render_template("results.html", results_dict=results)

then in results.html I have this code (jinja, flask):
{% for table in results_dict.df_html %}
 {{ table|safe }}
{% endfor %}

An it outputs to me a html code (source code). How to fix it and make it show a normal html table? Should I add some tags around jinja-flask code?
Update: For some reason each symbol is spaced in this html code generated by pandas
Image Link: https://tinypic.host/i/DIlab

A: The problem is your for loop.  df.to_html returns a single string, not a list of strings.  So, what you're doing there is iterating through that string character by character.  Replace that whole thing with:
{{ results_dict.df_html }}


text:
Q: NUL character and static character arrays/string literals in C I understand that strings are terminated by a NUL '\0' byte in C.
However, what I can't figure out is why a 0 in a string literal acts differently than a 0 in an char array created on the stack. When checking for NUL terminators in a literal, the zeros in the middle of the array are not treated as such.
For example:
#include <stdio.h>
#include <string.h>
#include <sys/types.h>

int main()
{

    /* here, one would expect strlen to evaluate to 2 */
    char *confusion = "11001";
    size_t len = strlen(confusion);
    printf("length = %zu\n", len); /* why is this == 5, as opposed to 2? */

    /* why is the entire segment printed here, instead of the first two bytes?*/
    char *p = confusion;
    while (*p != '\0')
        putchar(*p++);
    putchar('\n');

    /* this evaluates to true ... OK */
    if ((char)0 == '\0')
        printf("is null\n");

    /* and if we do this ... */
    char s[6];
    s[0] = 1;
    s[1] = 1;
    s[2] = 0;
    s[3] = 0;
    s[4] = 1;
    s[5] = '\0';

    len = strlen(s); /* len == 2, as expected. */
    printf("length = %zu\n", len);

    return 0;
}

output:
 length = 5
 11001
 is null
 length = 2

Why does this occur?

A: The variable 'confusion' is a pointer to char of a literal string.
So the memory looks something like
 [11001\0]

So when you print the variable 'confusion', it will print everything until first null character which is represented by \0.
Zeroes in 11001 are not null, they are literal zeroes since it is surrounded with double quotes.
However, in your char array assignment for variable 's', you are assigning a decimal value 0 to
char variable.  When you do that, ASCII decimal value of 0 which is ASCII character value of NULL character gets assigned to it.  So the the character array looks something like in the memory
  [happyface, happyface, NULL]

ASCII character happyface has ASCII decimal value of 1.
So when you print, it will print everything up to first NULL and thus
the strlen is 2.
The trick here is understanding what really gets assigned to a character variable when a decimal value is assigned to it.
Try this code:
 #include <stdio.h>

 int
 main(void)
{
    char c = 0;

    printf( "%c\n", c );  //Prints the ASCII character which is NULL.
    printf( "%d\n", c );  //Prints the decimal value.

    return 0;

}

A: '0' and 0 are not the same value. (The first one is 48, usually, although technically the precise value is implementation-defined and it is considered very bad style to write 48 to refer to the character '0'.)
If a '0' terminated a character string, you wouldn't be able to put zeros in strings, which would be a bit... limiting.

A: You can view an ASCII Table (e.g. http://www.asciitable.com/) to check the exact value of character '0' and null


text:
Q: edge triggered interrupts? what are they? Can someone tell me what level and edge triggered interrupts are? Or give me a link to an article with a simple explanation?

A: So here's a signal line in a quiescent state (special ASCII oscilloscope reenactment):
-------------------------------------------------------------

That represents one copper wire carrying one voltage with no variations over some period of time.  In digital electronics, that voltage is either 0v or 5v, a.k.a. 0 (zero) or 1 (one).
Let's say that wire is normally kept at 0v (zero volts).  If I send a pulse down that line, that means I apply a higher voltage, say, 5v (five volts).  On an oscilloscope, the transition from low to high looks like this.  That part where the transition happens is an edge.
                                 -------------------------- +5v
                                 |
0v -------------------------------

                                 ^
                                 |
                                edge

So in edge-triggered interrupts, there's a wire connecting the CPU and some device that's normally kept, say, at 0v.  When the device wants to get the CPU's attention, it sends an interrupt: it puts power to that wire.  The CPU detects the new high voltage on the wire and triggers an interrupt handler to deal with it.  Then the device stops putting power on the wire, and the voltage heads back down to 0v.

A: Two seconds with a search engine pointed me at Wikipedia:

An edge-triggered interrupt is a class
  of interrupts that are signalled by a
  level transition on the interrupt
  line, either a falling edge (1 to 0)
  or a rising edge (0 to 1). A device
  wishing to signal an interrupt drives
  a pulse onto the line and then
  releases the line to its quiescent
  state.


text:
Q: How to deploy the code on heroku from assembla I want to deploy push code from assembla to heroku when some one has pushed the code on assembla then I want it should automatically deploy on heroku.
Please suggest me how can I do that.

A: **disclaimer, I work for Assembla
The problem with deploying directly to Heroku from Assembla is that you will have to include your credentials, theoretically it is possible with a post-receive hook, but I would advise against this and Assembla would most likely reject the post-receive hook submission unless you know a way to work around the authentication problem.
However, you can accomplish this with the SSH tool, which will deploy from a server that you provide. So you would need to have a plan that includes the SSH tool, then a server that the SSH tool can connect to and run a script that pulls your repo and then pushes out to Heroku. You can put the SSH tool job to run "on commit" and it will automatically run this job for you.


text:
Q: Is there a name for the rule $a \div (b \times c) = a \div b \div c$? Edit, because I should have looked it up before I posted the question:
Is there a name for the rule $a \div (b \div c) = a \div b \times c$  ? I ran across this in Liping Ma's book, Knowing and Teaching Mathematics, and I have searched the internet for a name for this rule to no avail. It is not the distributive law, but it is rather similar. Thank you!
From Ma's book, p. 59 discussing "dividing by a number is equivalent to multiplying by its reciprocal":
"We can use the knowledge that students have learned to prove the rule that dividing by a fraction is equivalent to multiplying by its reciprocal. They have learned the commutative law. They have learned how to take off and add parentheses. They have also learned that a fraction is equivalent to to the result of a division, for example, $ \frac{1}{2} = 1 \div 2 $  . Now, using these, we can rewrite the equation this way:
$ 1\frac{3}{4} \div \frac{1}{2} \to $

$1\frac{3}{4} \div (1 \div 2) \to $

$1\frac{3}{4} \div 1 \times 2 \to  $ (This is the step my question is about.)

$1\frac{3}{4} \times 2 \div 1 \to $ (and I'd like an explicit explanation of this step, too.)

$1\frac{3}{4} \times 2\to$
$1\frac{3}{4} \times (2 \div 1) \to $

A: I suppose that $a,b,c$ are rational (or real) numbers. In this case your starting expression is equivalent to:
$$
\dfrac{a}{b\times c}=a\times \dfrac{1}{b}\times \dfrac{1}{c}=\left(a \times \dfrac{1}{b} \right)\times \dfrac{1}{c}=\dfrac{a \times \dfrac{1}{b}}{c}=\dfrac{ \dfrac{a}{b}}{c}
$$
so you can see that this property does not need a special name since it is simply the application of the definition of inverse and of associativity for the product.

A: In the same way as subtraction should be thought of as adding by the additive inverse, it is better to think of division as multiplication by the multiplicative inverse to avoid any potential confusion.
That is to say, $a-b-c = a+(-b) + (-c)$ and $a\div b\div c = a\times b^{-1}\times c^{-1}=a\times \frac{1}{b}\times \frac{1}{c}$
As for why $a\times \frac{1}{b}\times \frac{1}{c}= \frac{a}{b\times c}$, this is an immediate consequence of how multiplication is defined for rational numbers (and fractions in general) and so likely doesn't have a name.
The definition of multiplication of two fractions is $\frac{a}{b}\times \frac{c}{d} := \frac{a\times c}{b\times d}$, so you have $(\frac{a}{1}\times \frac{1}{b})\times\frac{1}{c} = \frac{a}{b}\times\frac{1}{c}=\frac{a}{b\times c}$
You go on to say "but in fraction form..." implying you think something looks different about the case where the numbers are fractions instead, but I see no difference.  The application of the rule is exactly the same in both scenarios.

A: Never thought about this. My work with quadratic forms gives many expressions in one line, with a selection of plus and minus signs. It never bothered me, if there is a plus sign it gets added, and all those with minus signs get subtracted. I think most people do that. So,
$$ s + t - u - v + w - x - y + z = (s + t + w + z) - (u + v + x + y)  $$
The analogous usage with multiplication and division signs would be
 $$ s \cdot t \div u  \div  v  \cdot  w  \div  x  \div  y  \cdot  z = \frac{s  t  w  z}{ u  v  x  y}  $$
but I can hardly imagine anyone writing the thing on the left hand side and expecting to be understood. In a single line, we could write $s  t  w  z/( u  v  x  y)$ instead.
Go Figure.

A: Well the concept of inverses is fundamental so you eventually have to get it across whether or not you use the inverse notation.
$\newcommand{\box}[1]{~\boxed{#1}~}$
$x \box{\times a} \box{\div a} = x$ for any $a \ne 0$ because $\box{\div a}$ exactly undoes $\box{\times a}$. $\box{\div 0}$ is not allowed simply because it is impossible to undo $\box{\times 0}$.
Also we can think of numbers as what we use to represent amounts of something, so "$a$" actually stands for "$\box{\times a}$". For example when we say "$3$ apples" we mean "apple$\box{\times 3}$". So actually what we have is $\box{\times a} \box{\div a} = \box{\times 1}$. It turns out that undoing multiplying amounts is itself undoable, so we have $\box{\div a} \box{\times a} = \box{\times 1}$ as well. Both of these are for $a \ne 0$.
Now as stated we should take "$\box{\div a}$" to mean "undo $\box{\times a}$", but it may not be obvious that this has an important implication for the question at hand as well. What is "$\box{\div (b \div c)}$"? It means precisely "undo $\box{\times (b \div c)}$" = "undo $(\box{\times b} \box{\div c})$". How to undo? Clearly "$\box{\times c} \box{\div b}$". Thus we immediately get $\box{\div (b \div c)} = \box{\times c} \box{\div b}$, which explains the original question fully.
One implicit notion used above is that we define "$\box{\times (ab)}$" to mean "$\box{\times a} \box{\times b}$". Think carefully about this. It means that the product of $a,b$ is defined as the combined action of ( multiplying by $a$ ) and ( multiplying by $b$ ). In the above we used this interpretation when we went from "$\box{\times (b \div c)}$" to "$\box{\times b} \box{\div c}$".

A: But if you really don't want to touch inverses at all, and stick to dividing by only real-world quantities (positive with physical units), then another way is that "$a \div ( b \div c )$" can represent "$a \text{ cake} \div ( b \text{ cake} \div c \text{ people})$, which is "number of people we can feed when $a$ cake is divided into pieces of the size that each of $c$ people would get for a fair division of $b$ cake". Example usage would be when we know that 2 cakes divided by 5 people gives each one a decent meal, and so if we have 3 cakes we can feed $3 \div ( 2 \div 5 )$ people. Clearly it is the same if we first took the ratio of cake, $3 \div 2$, and then multiplied by $5$, the number of people we could feed using $2$ cakes. Feeling hungry now?

A: The set of all nonzero real numbers with $\times$ is a commutative group. Dividing by a number can be defined as multiplying by its multiplicative inverse. So from those properties, we can derive that $\forall a \in \mathbb{R} - \text{{0}}\forall b \in \mathbb{R} - \text{{0}}\forall c \in \mathbb{R} - \text{{0}} a \div (b \times c) = a \div (c \times b) = a \times (c \times b)^{-1} = a \times (b^{-1} \times c^{-1}) = (a \times b^{-1}) \times c^{-1} = (a \div b) \times c^{-1} = (a \div b) \div c$. Here I'm using the operation ^-1 to denote taking the inverse of the number using the operation included in the group, not to denote real number exponentation although it turns out to get the same result as the other meaning of that notation. For high level mathematicans who are good at thinking of how to write the type of proof I just wrote, once you know that a set with a certain operation is a commutative group, it's so easy to derive that result. That's probably why mathematicians never decided the result that that holds for all commutative groups needs to be written as a theorem that they say was carefully checked by experts to be true. It's also easy to show that for real numbers, when ever one expression is defined, the other expression is also defined and equal to it even when you don't restrict $a$ to being nonzero.


text:
Q: dynamic changing max range and document.getElementById I have a range slider and I want the max range to be set dynamically from the html text of a div with class="aaa". unfortunately it doesn't not work. And maybe I have some error in the var = zzz that sets the max value..
Here's my code

var  zzz = document.getElementById('aaa').val();
document.getElementById('slider1').max = zzz;

const $mutuo = $("#mutuo"),
  $rata = $("#rata"),
  $anni = $("#anni"),
  $slider1 = $("#slider1"),
  $slider2 = $("#slider2"),
  $max = $("#aaa").html();

function showAmount1(newAmount){
    document.getElementById('mutuo').innerHTML = newAmount;
    $mutuo.val($("#mutuo").innerHTML);
    update();
}

function showAmount2(newAmount){

    document.getElementById('anni').innerHTML = newAmount;
    $anni.val($("#anni").innerHTML);
    update();
}

  function update() {
  let interesseannuo = 1.60,
    C = $mutuo.html(),
    anni = $anni.html(),
    i = interesseannuo / 12 / 100,
    n = anni * 12,
    rata = C * i / (1 - Math.pow(1 + i, -n));

  $rata.html(rata.toFixed(2) + " €");
}
update();

123456

Totale mutuo (€)

     <input type="range" min="0" max="" value="" step="10" onchange="showAmount1(this.value)" id="slider1"/>

10000

Durata mutuo (anni)

    <input type="range" min="10" max="30" value="10" step="5" onchange="showAmount2(this.value)" id="slider2">

10

La tua rata

A: val() is used in jQuery, For javascript you need to use value
In javascript if you want the input value then use
document.getElementById('aaa').value

Instead of
document.getElementById('aaa').val()

If you want text of element you can use
document.getElementById('aaa').innerHTML

OR
document.getElementById('aaa').innerText

var zzz = document.getElementById('aaa').innerText;
document.getElementById('slider1').max = zzz;

const $mutuo = $("#mutuo"),
        $rata = $("#rata"),
        $anni = $("#anni"),
        $slider1 = $("#slider1"),
        $slider2 = $("#slider2"),
        $max = $("#aaa").html();

function showAmount1(newAmount) {
 document.getElementById('mutuo').innerHTML = newAmount;
 $mutuo.val($("#mutuo").innerHTML);
 update();
}

function showAmount2(newAmount) {
 document.getElementById('anni').innerHTML = newAmount;
 $anni.val($("#anni").innerHTML);
 update();
}

function update() {
 let interesseannuo = 1.60,
         C = $mutuo.html(),
         anni = $anni.html(),
         i = interesseannuo / 12 / 100,
         n = anni * 12,
         rata = C * i / (1 - Math.pow(1 + i, -n));

 $rata.html(rata.toFixed(2) + " €");
}
update();

123456

Totale mutuo (€)

     <input type="range" min="0" max="" value="" step="10" onchange="showAmount1(this.value)" id="slider1"/>

10000

Durata mutuo (anni)

    <input type="range" min="10" max="30" value="10" step="5" onchange="showAmount2(this.value)" id="slider2">

10

La tua rata

A: val() function only fetches the value of input elements. In order to get the text of  other elements, you need to use innerHTML or innerText. Just replace
var  zzz = document.getElementById('aaa').val();

with
var  zzz = document.getElementById('aaa').innerText;

It should work.


text:
Q: Populating dropdown list from database I am trying to populate my dropdown list on a form with data from a database, i have tried the following but to no success it gives me an error saying unexpected ; i have tried removing but still getting errors?
 echo form::label('myproduct', 'My Product:');
         echo form::select('form[myproduct]', $sql = mysql_query("SELECT description FROM claim_incentive"); while ($row = mysql_fetch_array($sql))
            {echo "<option value=\"1\">" . $row['description'] . "</option>"; }

I think i could be putting the code in the wrong place as i have two php files, one is the controller, my code below:
public function action_claimincentive() {
                    $this->template->content = View::factory('crm/uk/claim_incentive_form');
                    $this->template->content->thanks = false;
                    $this->template->content->val = '';
                    $this->template->content->post = '';

                        if ($this->request->post('form')) {
                                    $post = $this->request->post('form');

                                    $stmt = DB::query(Database::INSERT, 'INSERT INTO `claim_incentive_form_data` (`User Reference`, `Claimant Postcode`, `Purchase Order No.`, `Claimant Email Address`, `Storename`, `Storetown`, `Date of Sale`, `Date of Delivery`, `Acknowledgement No.`, `Product`)
                                                                        VALUES (:userreference, :claimantpostcode, :orderno, :email, :storename, :storetown, :dateofsale, :dateofdelivery, :acknowledgementno, :product)');
                                    $stmt->param(':userreference', $post['userreference']);
                                    $stmt->param(':claimantpostcode', $post['claimantpostcode']);
                                    $stmt->param(':orderno', $post['orderno']);
                                    $stmt->param(':email', $post['email']);
                                    $stmt->param(':storename', $post['storename']);
                                    $stmt->param(':storetown', $post['storetown']);
                                    $stmt->param(':dateofsale', $post['dateofsale']);
                                    $stmt->param(':dateofdelivery', $post['dateofdelivery']);
                                    $stmt->param(':acknowledgementno', $post['acknowledgementno']);
                                    $stmt->param(':product', $post['product']);
                                        try {
                                                $stmt->execute();
                                                $this->template->content->post = $post;
                                                $this->template->content->thanks = true;
                                                } catch (Exception $e) {
                                                    FB::error($e);
                                                }

                    }
                }

And the other is the actual form, see part of it below:
echo form::label('dateofdelivery', 'Date of Delivery:');
         echo form::input('form[dateofdelivery]', $val, array('class'=>'input', 'id'=>'dateofdelivery'));

         echo form::label('acknowledgementno', 'Acknowledgement No:');
         echo form::input('form[acknowledgementno]', $val, array('class'=>'input', 'id'=>'acknowledgementno'));

         echo form::label('product', 'Product:');
         echo form::select('form[product]', array(
                                            '' => 'Please select from the list',
                                            'In store' => 'In store',
                                            'Word of mouth' => 'Word of mouth',
                                            'Television' => 'Television',
                                            'Newspaper' => 'Newspaper',
                                            'Magazine' => 'Magazine',
                                            'Internet' => 'Internet',
                                            'Google Reasearch' => 'Google Reasearch',
                                            'Radio' => 'Radio',
                                            'Medical Recommendation' => 'Medical Recommendation',
                            ), '', array('class="select"', 'id'=>'product'));

        echo form::submit('btnSubmit', 'Submit', array('id'=>'btnSubmit', 'class'=>'button'));
        echo '
';
        echo '

';

        echo form::close();

A: You have some errors in your markup, let's see:
In this line you have some errors:
echo form::select('form[myproduct]', $sql = mysql_query("SELECT description FROM claim_incentive");

You are opening two parenthesis but only closing one should be something like:
echo form::select('form[myproduct]', $sql = mysql_query("SELECT description FROM claim_incentive"));

It's not necessary to assign the sql variable inside the method, any way I don't know which kind of framework are you using, so I am only noticing syntax errors.


text:
Q: ModuleNotFoundError: No module named 'pygame.locals'; 'pygame' is not a package So this problem is a bit strange for me. I wrote this piece of code to see if pygame works correctly.
import pygame,sys
from pygame.locals import *

pygame.init()
DISPLAYSURF = pygame.display.set_mode((400,300))
pygame.display.set_caption("Hello World")
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()

    pygame.display.update()

I saved this file as pygame.py and when I typed:
-python pygame.py

on the cmd it says:
 ModuleNotFoundError: No module named 'pygame.locals'; 'pygame' is not a package

And if I type -python to the shell and then type import pygame it works like a charm.
So In summary: If I want to execute pygame.py, it does not see the module,
but it sees the module after typing python and import pygame (works without error).
The operating system is Windows.

A: Naming the file pygame.py makes the computer think of the file when importing, not the package. That is why it says pygame is not a package because pygame is the file.


text: Q: MinGW doesn't give warning when using gets( ) I used -Wall -Werror flags and still MinGW is not able to produce a warning when I am using the gets( ) function? Please tell me which flags should I use so that MinGW produces a warning?


text:
Q: routing in MVC (html) at controller public function clothdelete($id){

session_start();
$uid = $_SESSION['id'];

$cloth = new \App\Models\Owner();
$deleteclothes = $cloth->deleteclothes($id);
$clothes = $cloth->viewall($uid);

$data = ['clothes'=> $clothes,'success' => 'item successfully deleted!!'];
View::renderTemplate('Owner/index.html',$data);}

This is how I route in my system. There is no any problem in this code. The problem is when ever this controller is called, it deletes item(cloth with id) and route to Owner.index.html page with successful message.
So after I reach in index.html if I refresh this page the controller is called again and tries to perform delete action. When I refresh this page, the clothdelete($id) controller is called again and again.
How can I stop this? Using header might be an option but I don't know how to apply this in my code.

A: Make the delete (in your controller) a POST request vs. a GET request, then call delete within a form.  GET must be idempotent and safe.


text:
Q: How to return different format of records from a single PL/pgSQL function? I am a frontend developer but I started to write backend stuff. I have spent quite some amount of time trying to figure out how to solve this. I really need some help.
Here are the simplified definitions and relations of two tables:
Relationship between tables
CREATE TABLE IF NOT EXISTS items (
    item_id       uuid          NOT NULL DEFAULT gen_random_uuid() ,
    parent_id     uuid                   DEFAULT NULL              ,
    parent_table  parent_tables NOT NULL
);

CREATE TABLE IF NOT EXISTS collections (
    collection_id uuid          NOT NULL DEFAULT gen_random_uuid() ,
    parent_id     uuid                   DEFAULT NULL
);

Our product is an online document collaboration tool, page can have nested pages.
I have a piece of PostgreSQL code for getting all of its ancestor records for given item_ids.
WITH RECURSIVE ancestors AS (
    SELECT *
    FROM items
    WHERE item_id in ( ${itemIds} )

    UNION

    SELECT i.*
    FROM items i
    INNER JOIN ancestors a ON a.parent_id = i.item_id
)
SELECT * FROM ancestors

It works fine for nesting regular pages, But if I am going to support nesting collection pages, which means some items' parent_id might refer to "collection" table's collection_id, this code will not work anymore. According to my limited experience, I don't think pure SQL code can solve it. I think writing a PL/pgSQL function might be a solution, but I need to get all ancestor records to given itemIds, which means returning a mix of items and collections records.
So how to return different format of records from a single PL/pgSQL function? I did some research but haven't found any example.

A: You can make it work by returning a superset as row: comprised of item and collection. One of both will be NULL for each result row.
WITH RECURSIVE ancestors AS (
   SELECT 0 AS lvl, i.parent_id, i.parent_table, i AS _item, NULL::collections AS _coll
   FROM   items i
   WHERE  item_id IN ( ${itemIds} )

   UNION ALL -- !
   SELECT lvl + 1, COALESCE(i.parent_id, c.parent_id), COALESCE(i.parent_table, 'i'), i, c
   FROM   ancestors        a
   LEFT   JOIN items       i ON a.parent_table = 'i' AND i.item_id = a.parent_id
   LEFT   JOIN collections c ON a.parent_table = 'c' AND c.collection_id = a.parent_id
   WHERE  a.parent_id IS NOT NULL
   )
SELECT lvl, _item, _coll
FROM   ancestors
--     ORDER BY ?

db<>fiddle here
UNION ALL, not UNION.
Assuming a collection's parent is always an item, while an item can go either way.
We need LEFT JOIN on both potential parent tables to stay in the race.
I added an optional lvl to keep track of the level of hierarchy.
About decomposing row types:

*

*Combine postgres function with query

*Record returned from function has columns concatenated


text:
Q: Jquery Mobile - swipe left get row id Im using Query mobile to swipe left which works and brings me up an alert window that states, you swiped. but I get no id in the alert.

    $(function(){
    // Bind the swipeleftHandler callback function to the swipe event on div.box
    $(".row").on( "swipeleft", swipeleftHandler );
    // Callback function references the event target and adds the 'swipeleft' class to it
    function swipeleftHandler( e ){
        $id =  e.target.id;
        alert( 'You swiped ' + $id  );
    }
    });

<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-mobile/1.4.5/jquery.mobile.min.css" rel="stylesheet"/>

        Date/Time
        Alert
        Acknowledged By

        01/01/2017 3:41

            Device: Server

            Component: CPU

            Alert: 100%

        Bill Jones

        01/01/2017 4:41

            Device: Switch 02

            Component: Port 10

            Alert: Down

        Fred Smith

A: try $id = $(this).attr('id'); instead of $id =  e.target.id;.
it should work


text:
Q: php - how to shorten a string outputed? im using php
if i have an uknown length of a string being outputted how can i limit it to only 16 characters to be outputted?

A: the function is called substr.
string substr ( string $string , int $start [, int $length ] )

so:
return substr($mystring,0,16);

should do it.

A: The above methods, mentioning substr would help you. But, in case if your string contains multibyte characters (non-english characters), mb_substr should be used, which is a safe multi-byte substring function.

A: I personally like this one if it is a blog or something:
<?php

if(strlen($string) > 16) {
echo substr($string,0,16) . "...";
}else{
echo $string;
}

?>

This way it won't truncate the string if its below 16 characters. Otherwise, it will add an ellipsis.

A: Could you provide the code that you're using now?  I'm going to go off the basis that you have a function returning a string of an unknown length.  All you have to do is use the substr function.
$shorterString = substr( some_function(), 0, 16 );

A: substr($input_string, 0, 16)

A: You can use substr function like this.
$text = "I am pretty long text.";
echo $text;                        //outputs I am pretty long text.
echo substr($text, 0, 16);         //outputs I am pretty long

A: use substr
 echo substr( $str,0, 16 )

A:
$str = "More than 16 characters of
  text in this string.";
print substr( $str,0, 16 );


text:
Q: How many necklaces can be formed with $6$ identical diamonds and $3$ identical pearls
Find number of ways to make a necklace (or a garland) consisting of $6$ identical diamonds and $3$ identical pearls.

I got the correct answer $7$ by taking different cases but when I applied the formula for arrangement, i.e. $$\frac{(6+3-1)!}{6!3!2}$$ I get a value which is not an integer. I divided by $6!$ and $3!$ because the diamonds and pearls are identical. Further I divided by $2$ since a necklace can be viewed from two sides.
Why am I getting a wrong answer?

A: Necklaces are invariant under rotation, while bracelets are invariant under rotation and reflection.  You seem to be counting bracelets rather than necklaces.
If we arrange six indistinguishable diamonds and three indistinguishable pearls in a row, there are $\binom{9}{3}$ ways to select the positions of the pearls.  We can join the ends of the row together to form a circle.  Since there are nine objects, it would appear that there are nine linear arrangements which correspond to the same circular arrangement, once for each of the nine places we could cut the circle to obtain a linear arrangement, which would give
$$\frac{1}{9}\binom{9}{3}$$
necklaces.  However, this is not quite right because we can only divide by $9$ if each of the nine linear arrangements is distinct.  As Ned pointed out in the comments, this is not true since there are only three distinct linear arrangements corresponding to the necklace in which each pair of pearls is separated by exactly two diamonds.  Those linear arrangements are PDDPDDPDD, DPDDPDDPD, and PPDPPDPPD. Hence, dividing by $9$ counts that symmetrical necklace $1/3$ times.  We want to count it once, so we must add $2/3$ to the total.  Hence, there are
$$\frac{1}{9}\binom{9}{3} + \frac{2}{3} = 10$$
distinct necklaces that can be formed with six indistinguishable diamonds and three indistinguishable pearls.  They are shown below.

As Ned pointed out in the comments, you cannot simply divide the number of necklaces by $2$ to obtain the number of bracelets since some bracelets are their own reflections, so you would be counting each symmetrical bracelet $1/2$ times rather than once.
Notice that the four necklaces in the top row are symmetrical with respect to the vertical axis drawn through the top pearl.  Thus, each of these four necklaces is its own reflection.  Each necklace which is its own reflection produces one bracelet.
On the other hand, reflecting each necklace in the second row in this axis produces a different necklace, namely the necklace in the third row in the corresponding column.  Each pair of necklaces which can be obtained by reflection from each other corresponds to a single bracelet.
Hence, the number of bracelets which can be formed using six indistinguishable diamonds and three indistinguishable pearls is
$$4 + \frac{6}{2} = 4 + 3 = 7$$

A: There are  two possibilities  here, rotational symmetry  (necklace) or
dihedral  symmetry (bracelet). This is the OEIS naming convention. For the
first one  we have  the cycle index of the cyclic group:
$$Z(C_n) = \frac{1}{n} \sum_{d|n} \varphi(d) a_d^{n/d}.$$
For second one we have the cycle index of the dihedral group
$$Z(D_n) =
\frac{1}{2} Z(C_n) +
\begin{cases}
\frac{1}{2} a_1 a_2^{(n-1)/2} & n \text{ odd} \\
\frac{1}{4} \left( a_1^2 a_2^{n/2-1} + a_2^{n/2} \right)
& n \text{ even.}
\end{cases}$$
We get for $n=9$ the cycle indices
$$Z(C_9) = 1/9\,{a_{{1}}}^{9}+2/9\,{a_{{3}}}^{3}+2/3\,a_{{9}}$$
and
$$Z(D_9) =
1/18\,{a_{{1}}}^{9}+1/9\,{a_{{3}}}^{3}+1/3\,a_{{9}}
+1/2\,a_{{1}}{a_{{2}}}^{4}.$$
Then by the Polya Enumeration Theorem we require
$$[D^6 P^3] Z(C_9; D+P)$$
and
$$[D^6 P^3] Z(D_9; D+P).$$
We thus get for the first case
$$\frac{1}{9} {9\choose 6} + \frac{2}{9} {3\choose 2}
= 10$$
and the second one
$$\frac{1}{2} 10 + \frac{1}{2} [D^6 P^3] (D+P) (D^2+P^2)^4
\\ = 5
+ \frac{1}{2} [D^6 P^2] (D^2+P^2)^4
+ \frac{1}{2} [D^5 P^3] (D^2+P^2)^4
\\ = 5 + [D^3 P] (D+P)^4 = 5 + \frac{1}{2} {4\choose 3} = 7.$$


text:
Q: Calculate MAE, MSE and R2 metrics for a DNNRegressor model I have a DNNRegressor model and I want to calculate some metrics to understand how well my model is predicting. How can I calculate the mean absolute error (MAE), mean squared error (MSE) and the R squared coefficient?
So far I only have the loss so can someone help me calculate MAE, MSE and R2?
# Imports
import itertools
import pandas as pd
import tensorflow as tf
import numpy as np

import sklearn
from sklearn import preprocessing
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
import seaborn as sns
from matplotlib import pyplot as plt

from sklearn.metrics import r2_score

import statsmodels.api as sm

COLUMNS = ['Prot', 'Gra', 'Cen', 'Sal', 'TVN', 'Velocidad_Prensa']
FEATURES = ['Prot', 'Gra', 'Cen', 'Sal', 'TVN']
LABEL = ['Velocidad_Prensa']

def get_input_fn(data_set, num_epochs=None, shuffle=True):
  return tf.compat.v1.estimator.inputs.pandas_input_fn(
      x=pd.DataFrame({k: data_set[k].values for k in FEATURES}),
      y=pd.Series(data_set[LABEL].values),
      num_epochs=num_epochs,
      shuffle=shuffle)

training_set = pd.read_csv("prensa train.csv", skipinitialspace=True, skiprows=1, names=COLUMNS)
test_set = pd.read_csv("prensa eval.csv", skipinitialspace=True, skiprows=1, names=COLUMNS)
training_set.head()

# Model

feature_cols = [tf.feature_column.numeric_column(k) for k in FEATURES]

regressor = tf.estimator.DNNRegressor(feature_columns=feature_cols,
                                          activation_fn = tf.nn.relu, hidden_units=[200, 100, 50, 25, 12])

# Reset the index of training
training_set.reset_index(drop = True, inplace =True)
def input_fn(data_set, pred = False):

    if pred == False:

        feature_cols = {k: tf.constant(data_set[k].values) for k in FEATURES}
        labels = tf.constant(data_set[LABEL].values)

        return feature_cols, labels

    if pred == True:
        feature_cols = {k: tf.constant(data_set[k].values) for k in FEATURES}

        return feature_cols

# Deep Neural Network Regressor with the training set which contain the data split by train test split
regressor.train(input_fn=lambda: input_fn(training_set), steps=2000)

# Evaluation on the test set created by train_test_split
ev = regressor.evaluate(input_fn=lambda: input_fn(test_set), steps=1)

# Display the score on the testing set
loss_score1 = ev["loss"]
print("Final Loss on the testing set: {0:f}".format(loss_score1))

def input_fn(features, batch_size=256):
  return tf.data.Dataset.from_tensor_slices(dict(features)).batch(batch_size)

features = ['Prot', 'Gra', 'Cen', 'Sal','TVN']
predict = {}

print("Ingresar características químicas de la materia prima")
for feature in features:
  valid = True
  while valid:
    val = input(feature + ": ")
    if not val.isdigit(): valid = False

  predict[feature] = [float(val)]

predictions = regressor.predict(input_fn=lambda: input_fn(predict))

for pred_dict in predictions:
    print(pred_dict)

A: sklearn.metrics has dedicated scoring methods for each of the metrics you are asking for.
Just to the following:
# Import metrics
from sklearn import metrics

# Make predictions
predictions = regressor.predict(input_fn=lambda: input_fn(predict))

# Calculate MAE, MSE, R2
print('MAE:', metrics.mean_absolute_error(y_true, predictions))
print('MSE:', metrics.mean_squared_error(y_true, predictions))
print('R2:', metrics.r2_score(y_true, predictions))


text:
Q: I have problems with an array in kotlin Hello I want to make a query I have two variables
var dataObjectProduct = ArrayMap<String, String>()
var dataObjectProducts = mutableListOf<String>()

Then in a function I load it as follows
dataObjectProduct.set("idProduct", tvIdProduct?.text.toString())
                dataObjectProduct.set("nameProduct", tvNameProduct?.text.toString())
                dataObjectProduct.set("AmountProduct", txtAmountProduct?.text.toString())
                dataObjectProduct.set("PriceProduct", tvPriceProduct?.text.toString())
                dataObjectProduct.set("TotalProduct", totalLine.toString())
                dataObjectProducts.add(dataObjectProduct.toString())

In another function I occupy to obtain the result I am doing it in the following way:
fun viewListsProducts(v: View){
        val dlProductsSale =
            LayoutInflater.from(this).inflate(R.layout.tr_list_sale_products_layout_as, null)
        tvIdProductSale = dlProductsSale.findViewById(R.id.tvIdSaleProduct)
        tvNameProductSale = dlProductsSale.findViewById(R.id.tvNameSaleProduct)
        tvPriceProductSale = dlProductsSale.findViewById(R.id.tvPriceSaleProduct)
        tvAmountProductSale = dlProductsSale.findViewById(R.id.tvAmountSaleProduct)
        tvTotalProductSale = dlProductsSale.findViewById(R.id.tvTotalSaleProduct)
        for (table in dataObjectProducts){
           var product = JSONObject(table)

            tvIdProductSale.text = "1"
            tvNameProductSale.text = product.getJSONObject("idProduct").toString()
        }

        val dlBuilder = AlertDialog.Builder(this).setView(dlProductsSale)
            .setTitle("Productos a Facturar")
            .setNegativeButton("Cancelar", { dialogInterface: DialogInterface, i: Int -> })
            .setCancelable(false)
        dlBuilder.show()

    }

but it's giving me an error I don't know how to proceed can you give me a hand?
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: ******************, PID: 22161
    java.lang.IllegalStateException: Could not execute method for android:onClick
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:446)
        at android.view.View.performClick(View.java:7862)
        at android.widget.TextView.performClick(TextView.java:15004)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1217)
        at android.view.View.performClickInternal(View.java:7831)
        at android.view.View.access$3600(View.java:879)
        at android.view.View$PerformClick.run(View.java:29359)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:237)
        at android.app.ActivityThread.main(ActivityThread.java:8167)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:441)
        at android.view.View.performClick(View.java:7862)
        at android.widget.TextView.performClick(TextView.java:15004)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1217)
        at android.view.View.performClickInternal(View.java:7831)
        at android.view.View.access$3600(View.java:879)
        at android.view.View$PerformClick.run(View.java:29359)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:237)
        at android.app.ActivityThread.main(ActivityThread.java:8167)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
     Caused by: org.json.JSONException: Unterminated object at character 58 of {PriceProduct=1000, idProduct=8029, nameProduct=PRODUCTO GENERICO, TotalProduct=2000.0, AmountProduct=2}
        at org.json.JSONTokener.syntaxError(JSONTokener.java:460)
        at org.json.JSONTokener.readObject(JSONTokener.java:403)
        at org.json.JSONTokener.nextValue(JSONTokener.java:104)
        at org.json.JSONObject.<init>(JSONObject.java:164)
        at org.json.JSONObject.<init>(JSONObject.java:181)
        at ***********************************.SelectProductsInvoice_as.viewListsProducts(SelectProductsInvoice_as.kt:146)
        at java.lang.reflect.Method.invoke(Native Method)
        at androidx.appcompat.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:441)
        at android.view.View.performClick(View.java:7862)
        at android.widget.TextView.performClick(TextView.java:15004)
        at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1217)
        at android.view.View.performClickInternal(View.java:7831)
        at android.view.View.access$3600(View.java:879)
        at android.view.View$PerformClick.run(View.java:29359)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:237)
        at android.app.ActivityThread.main(ActivityThread.java:8167)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)

XD you're right sorry here is the error that I get

A: See your stacktrace? It's divided into sections, there's a header for each one that summarises it. If you just read those, it tells you what the error is, then the thing that caused that error, then the thing which caused that, etc:
java.lang.IllegalStateException: Could not execute method for android:onClick
Caused by: java.lang.reflect.InvocationTargetException
Caused by: org.json.JSONException: Unterminated object at character 58 of {PriceProduct=1000, idProduct=8029, nameProduct=PRODUCTO GENERICO, TotalProduct=2000.0, AmountProduct=2}

So your onClick method failed, because there was some reflection error, and that happened because there was a JSONException (i.e. some big problem relating to JSON)
You can look into the calls in that section to see exactly where the problem appears - but you don't need to, that JSONException line explains what the problem is - you've got an "unterminated object" at character 58 of that data it printed. So it thinks you didn't close the object properly - without bothering to count to character 58, I'm gonna assume it's probably because of this:
nameProduct=PRODUCTO GENERICO

That should be in quotes, right? If it hits that space, it thinks it's the end of the object, that's why it's complaining. So it's a problem with your JSON
Hope that helps! Once you learn how to read stacktraces they can give you a lot of help tracking problems down - they can even tell you exactly what the issue is sometimes, so always check if there's a useful message, or even a warning in the logs


text:
Q: Couldn't connect to google.com or its subdomains For about 10 minutes, none of my devices connected to the Internet could connect to www.google.com, its subdomains and other Google-owned sites (e.g. youtube.com). Sites with Google Analytics installed would time out on me too.
In Terminal I typed in ping www.google.com and got this message:
Request timeout for icmp_seq 0
Request timeout for icmp_seq 1
Request timeout for icmp_seq 2

..etc..
I flushed my cache using dscacheutil -flushcache, and I don't know if it worked or not because Google suddenly responded again but very slowly. I renewed my DHCP license through System Preferences and enabled my firewall (again, not sure if it effected it). Google worked again after 5 minutes, but I'm worried what this could have been about after reading this thread on Apple's support forum:
https://discussions.apple.com/thread/3660038?start=0&tstart=0
However, NONE of my devices worked (Android/Windows/Mac), so I'm really at loss here.
I am not connected to any university. This is a home connection on Mediacom.

A: It seems others on social networks are reporting Google has been down for them. So this might be just a temporary glitch in services that you happened to see for a sort period; especially since you say all your devices behave the same, I don't think you have anything to worry about in terms of malicious intent. To be safe, you could always check your Hosts file and have a look over your router's admin page to make sure you have adequate security in place, are using WPA2 with a good password and are using HTTPS to the router's admin page.


text:
Q: How to test if a job has been queued? I wrote this code to test, if a job has been queued after submitting a result.
The chain of happenings is, that an event triggers a listener and the listener dispatches the job.
public function test_certificate_can_be_created_after_submitting_test_result()
    {

        $user = User::factory()->create();
        $test = Test::factory()->create();

        $response = $this->actingAs($user)
            ->put(route('tests.update', $test->id), [
                'result' => 'positive',
                'result_time' => '2021-01-01 12:00:00',
            ]);

        Event::fake([
            TestResultSubmitted::class,
        ]);
        Queue::fake();

        event(new TestResultSubmitted($test));
        Event::assertDispatched(TestResultSubmitted::class);
        Event::assertListening(
            TestResultSubmitted::class,
            ListenersCreateCertificate::class
        );

        Queue::assertPushed(CreateCertificate::class);

        $response->assertStatus(302);
    }

The event is just an event as it was created by php artisan make:Event TestResultSubmitted.
The Listener has just one line in the handle() function:
JobsCreateCertificate::dispatch($event->test);

The JobsCreateCertificate is empty atm. The only change I made is, that it implements ShouldQueue`.
The test result is:
The expected [App\Jobs\CreateCertificate] job was not pushed.
When I add a dd(1) into the handle() function of a job, the result of the test is 1. So the handle function is triggered.


text:
Q: Drawing line segment connecting two points on ggplot I have a point plot with two different points on each category and I want to create a line segment joining the two points on each row.
items %>%
  group_by(category) %>%
  summarise(med_buy_price = mean(buy_value, na.rm = TRUE),
            med_sell_price = mean(sell_value, na.rm = TRUE)) %>%
  pivot_longer(cols = c("med_buy_price", "med_sell_price"),
               names_to = "measure",
               values_to = "value") %>%
  ggplot(aes(x = value, y = category)) +
  geom_point(aes(color = measure), size = 3)

A: For creating a line segment, you need to have start and endpoints for the segment. Thus, you can stay with the wide format, so no pivot_longer needed.
Then create individual geom_point for sell and buy value and a geom_segment combining both points.
This code will work:
library(ggplot2)
library(dplyr)
library(tibble)
library(tidyr)

items <- tribble(
  ~category, ~buy_value, ~sell_value,
  "Wallpaper", 2000, 5200,
  "Usables", 500, 12500,
  "Umbrellas", 200, 1800
)

items %>%
  group_by(category) %>%
  summarise(med_buy_price = mean(buy_value, na.rm = TRUE),
            med_sell_price = mean(sell_value, na.rm = TRUE)) %>%
  ggplot() +
  geom_point(aes(x = med_buy_price, y = category), size = 3, color = "red")+
  geom_point(aes(x = med_sell_price, y = category), size = 3, color = "green")+
  geom_segment(aes(x = med_buy_price, xend = med_sell_price, y = category, yend = category))

A: If you do not insist on using geom_point you could try geom_errorbar which simplifies thing a little bit
items %>%
  group_by(category) %>%
  summarise(med_buy_price = mean(buy_value, na.rm = TRUE),
            med_sell_price = mean(sell_value, na.rm = TRUE)) %>%
  ggplot(aes(xmin=med_buy_price,xmax=med_sell_price, y = category)) +
  geom_errorbar(width=0.1)


text:
Q: How to specify named subfolders in htaccess? I have a folder structure like this /img/products/{product name}/ and then the sub folders hi, low, and thumb.
I want to use htacess to force-download any files in a 'hi' or 'low' subfolder (but not 'thumb').
I was hoping something like this would work:
<FilesMatch "\(.*)(\/hi|\/low)(.*)">
ForceType applicaton/octet-stream
</FilesMatch>

Now I'm not great with regex, but that seems to work in regex testers against paths like
/img/products/active/low/something.jpg
However it's not working on the site.
Any suggestions?
Thanks
Pete

A: This probably should have been a ServerFault question based on what I think that you're trying to do, but since you actually can't do what you're trying to do (the way I think you're trying to do it), I'll provide two alternatives; one that likely won't work, and another that involves a PHP script (which should hopefully be alright for you, since your question history shows you asking something about PHP before).
The Problem:
First, what I think you're trying to do, so you can correct me if I'm wrong:
# Apply ForceType to anything that's in a path that matches this
<FilesMatch "img/products/[^/]+/(hi|low)/[^/]+$">
    ForceType applicaton/octet-stream
</FilesMatch>

However, this won't work, because FilesMatch only examines the filename, under the assumption that you could either appropriately place the .htaccess file, or combine the directive with a Directory statement in the server or virtual server configuration.
In your case though, this isn't possible (Well, I assume anyway, maybe you do have access to the necessary configurations, but since your question is tagged .htaccess I'm guessing probably not), given that copying a .htaccess file to every folder isn't realistic.
The Solutions:
As it turns out, mod_rewrite, along with performing all sorts of voodoo in the way of filename resolution, also gives you extensions of other Apache functionality that you would not necessarily have been able to use otherwise. Case in point, we can set the MIME type using the T flag, making the easiest solution this:
RewriteEngine On

# Force the MIME-type, but don't actually perform a rewrite
RewriteRule ^img/products/[^/]+/(hi|low)/[^/]+$ - [T=application/octet-stream]

This actually works pretty well, but chances are good that your Apache installation thinks that it knows better than you, and includes a mimes.types file in the main configuration that maps the jpg extension to image/jpeg. This value takes precedence over the RewriteRule, making it ineffective in that case.
The other solution is to create a small script that acts as the go-between, passing the appropriate headers and image data from the server to the client. You would then use mod_rewrite to pass the request on to that script:
RewriteEngine On

# For an added bit of sanity, make the test pattern even more restrictive
RewriteRule ^img/products/[A-Za-z._-]+/(hi|low)/[A-Za-z._-]\.[A-Za-z]+$ imageDownloader.php

As for the script itself, to keep this answer from getting ridiculously long, I suggest taking a look at this answer or one of the other questions on this topic, keeping in mind that it's imperative that you screen the filenames that can be downloaded for reasons of security. Note that you would be able to get the original request path from $_SERVER['REQUEST_URI'], and could use that to locate the proper image.


text:
Q: Display date in the column depending on certain conditions While running the below code, I am getting the error:

Subquery returned more than 1 value. This is not permitted when the
  subquery follows =, !=, <, <= , >, >= or when the subquery is used as
  an expression

when I add the last bit of code (see after union)
(select top 1 convert(varchar,PaymentDate,103) from tblUTRDetail where CCN_No=CR.CCN_NO and CR.Claim_Status='Y' order by PaymentDate desc
union all
select top 1 convert(varchar,CreatedDate,103) from tblOpenCloseTrans where S_NO=CR.S_NO and OpenCloseType='C' and CR.Claim_Status='C' order by CreatedDate desc
union all
select top 1 convert(varchar,GENERATED_DATE,103) from tbldeficiencyletterTrans where S_NO=CR.S_NO and DEFICIENT_REPUDATION_FLAG='NC' and CR.Claim_Status='NC' order by GENERATED_DATE desc
union all
select top 1 convert(varchar,GENERATED_DATE,103) from tbldeficiencyletterTrans where S_NO=CR.S_NO and DEFICIENT_REPUDATION_FLAG='R' and CR.Claim_Status='RC' order by GENERATED_DATE desc
union
(select GENERATED_DATE from  (Select s_no, convert (varchar,(GENERATED_DATE),103)as GENERATED_DATE ,row_number()
over(partition by s_no order by s_no asc )as rw from tblDeficiencyLetterTrans b
where DEFICIENT_REPUDATION_FLAG='NC' and s_no=CR.S_NO) T where rw=1)
)
as SETTLEMENT_DATE,

A: Your query looks like this:
SELECT *

,(select 1 union all select 2
union all select 3
union all select 3
union (select 4)) as SETTLEMENT_DATE
FROM sys.tables

You are selecting some columns values and the for one of them you can return up to 4 values for one column SETTLEMENT_DATE.
So, you can have multiple values where one value is expected and this is what the error is saying to you. You have to options:

*

*if you want to see all values, just give a separated name to each column like this
SELECT *

,select 1 as SETTLEMENT_DATE1
,
select 2 as SETTLEMENT_DATE2
,
select 3 as SETTLEMENT_DATE3
,
select 3 as SETTLEMENT_DATE4
,
(select 4) as SETTLEMENT_DATE5
FROM sys.tables

*add more logic to return only one value each time from this sub-query
(
    SELECT TOP 1 date
    FROM
    (

        (select top 1 convert(varchar,PaymentDate,103) from tblUTRDetail where CCN_No=CR.CCN_NO and CR.Claim_Status='Y' order by PaymentDate desc
        union all
        select top 1 convert(varchar,CreatedDate,103) from tblOpenCloseTrans where S_NO=CR.S_NO and OpenCloseType='C' and CR.Claim_Status='C' order by CreatedDate desc
        union all
        select top 1 convert(varchar,GENERATED_DATE,103) from tbldeficiencyletterTrans where S_NO=CR.S_NO and DEFICIENT_REPUDATION_FLAG='NC' and CR.Claim_Status='NC' order by GENERATED_DATE desc
        union all
        select top 1 convert(varchar,GENERATED_DATE,103) from tbldeficiencyletterTrans where S_NO=CR.S_NO and DEFICIENT_REPUDATION_FLAG='R' and CR.Claim_Status='RC' order by GENERATED_DATE desc
        union
        (select GENERATED_DATE from  (Select s_no, convert (varchar,(GENERATED_DATE),103)as GENERATED_DATE ,row_number()
        over(partition by s_no order by s_no asc )as rw from tblDeficiencyLetterTrans b
        where DEFICIENT_REPUDATION_FLAG='NC' and s_no=CR.S_NO) T where rw=1)
        )
    )  DS (date)
    ORDER BY date
)
as SETTLEMENT_DATE,

A: create table #tempT (Material varchar(10),yyyyww  int,item_type  varchar(10),TPT int    )
-------------Insert---------------
insert into #tempT values('E123'    ,    201919 , 'Assembly'  , 7)
insert into #tempT values('E123'    ,    201919 , 'Assembly'  , 6)
insert into #tempT values('E123'    ,    201919 , 'Assembly'  , 7)
insert into #tempT values('E123'    ,    201919 , 'Assembly'  , 7)
insert into #tempT values('E123'    ,    201919 , 'FG'        , 2)
insert into #tempT values('E123'    ,    201919 , 'FG'        , 2)
insert into #tempT values('E123'    ,    201919 , 'FG'        , 1)
insert into #tempT values('E123'    ,    201919 , 'TEST'      , 7)
insert into #tempT values('E123'    ,    201919 , 'TEST'      , 4)

------------Output-------------
select Material ,ceiling(((sum((MaxTPT)))/7.00)+1)MaxTPT
 from(select Material,item_type,case when item_type='Assembly' then max(TPT)
when item_type='fg' then max(TPT)
when item_type='TEST' then max(TPT) end MaxTPT from #tempT
group by Material,item_type)a`enter code here`
group by Material


text:
Q: Crash on MediaController.show() i've a problem with mediacontroller, this part of code works perfecty on different devices as Acer Liquid (gingerbread), Archos 43 (froyo) e Archos 32 (froyo)...
VideoView videoView = (VideoView) findViewById(R.id.videoView1);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);
File filevideo = new File(Environment.getExternalStorageDirectory() + "/edizionitsm/firenze/map_" + map_n + "/",filename + "_" + language + ".mp4");
Uri video = Uri.fromFile(filevideo);
videoView.setMediaController(mediaController);
videoView.setVideoURI(video);
videoView.start();

...but on a Point of View Pro Tab2 (gingerbread) it crash at the beginning of the activity.
11-09 14:12:59.640: E/AndroidRuntime(31433): FATAL EXCEPTION: main
11-09 14:12:59.640: E/AndroidRuntime(31433): java.lang.RuntimeException: Unable to start activity ComponentInfo{edizionitsm.archeoplayer/edizionitsm.archeoplayer.Player}: java.lang.NullPointerException
11-09 14:12:59.640: E/AndroidRuntime(31433):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
11-09 14:12:59.640: E/AndroidRuntime(31433):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
11-09 14:12:59.640: E/AndroidRuntime(31433):    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
11-09 14:12:59.640: E/AndroidRuntime(31433):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
11-09 14:12:59.640: E/AndroidRuntime(31433):    at android.os.Handler.dispatchMessage(Handler.java:99)
11-09 14:12:59.640: E/AndroidRuntime(31433):    at android.os.Looper.loop(Looper.java:123)
11-09 14:12:59.640: E/AndroidRuntime(31433):    at android.app.ActivityThread.main(ActivityThread.java:3683)
11-09 14:12:59.640: E/AndroidRuntime(31433):    at java.lang.reflect.Method.invokeNative(Native Method)
11-09 14:12:59.640: E/AndroidRuntime(31433):    at java.lang.reflect.Method.invoke(Method.java:507)
11-09 14:12:59.640: E/AndroidRuntime(31433):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-09 14:12:59.640: E/AndroidRuntime(31433):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-09 14:12:59.640: E/AndroidRuntime(31433):    at dalvik.system.NativeStart.main(Native Method)
11-09 14:12:59.640: E/AndroidRuntime(31433): Caused by: java.lang.NullPointerException
11-09 14:12:59.640: E/AndroidRuntime(31433):    at android.widget.MediaController.disableUnsupportedButtons(MediaController.java:640)
11-09 14:12:59.640: E/AndroidRuntime(31433):    at android.widget.MediaController.show(MediaController.java:674)
11-09 14:12:59.640: E/AndroidRuntime(31433):    at android.widget.MediaController.show(MediaController.java:631)
11-09 14:12:59.640: E/AndroidRuntime(31433):    at android.widget.VideoView.start(VideoView.java:962)
11-09 14:12:59.640: E/AndroidRuntime(31433):    at edizionitsm.archeoplayer.Player.onCreate(Player.java:48)
11-09 14:12:59.640: E/AndroidRuntime(31433):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
11-09 14:12:59.640: E/AndroidRuntime(31433):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
11-09 14:12:59.640: E/AndroidRuntime(31433):    ... 11 more

the problem is in the function show() of mediacontroller class. How can i resolve it?
Thank you.

A: I had a similar problem on 3.1 Honeycomb and used setMediaPlayer to resolve it.  Try your code in this order with setMediaPlayer.
VideoView videoView = (VideoView) findViewById(R.id.videoView1);
MediaController mediaController = new MediaController(this);
mediaController.setAnchorView(videoView);

mediaController.setMediaPlayer(videoView);

File filevideo = new File(Environment.getExternalStorageDirectory() + "/edizionitsm/firenze/map_" + map_n + "/",filename + "_" + language + ".mp4");
Uri video = Uri.fromFile(filevideo);
videoView.setMediaController(mediaController);
videoView.setVideoURI(video);
videoView.start();


text:
Q: MYSQL combining results into single item for display I'm currently having an issue where I run a query on multiple tables getting the results, but they are all being considered independent. I've tried a couple ways of combining them, but because my SQL knowledge is limited I can't seem to get what I want to happen.
    SELECT DISTINCT t.*, s.quantity, s.rrp, ts.thumbnail, ts.bigpic, t.rating
                FROM tyres t
                INNER JOIN stocklevels s
                ON t.stockcode = s.stockcode
                LEFT JOIN tyre_treads ts
                ON t.treadid = ts.recid
                LEFT JOIN reseller r
                ON s.city=r.recid
                WHERE s.quantity> 0 AND s.rrp > 0

I've tried adding GROUP BY t.recid and a couple other basic solutions but this doesn't seem to work. I've added a couple images which might help.

As you can see the bottom Toyo tyres are the same, just with varying cities and quantities.
Here they are on the website.

I'm wanting to combine they so that they say minimum 6 in stock and shows only once on the site.

A: As long as there is at least one column in your SQK resukt, which contains different values  (like city in your example for "the same" tire, group by won't work. You must adapt your SQL statement in a way, that it only picks columns with the same values. Especially, you should remove the t.* from your sql and name all columns (You then will not need the distinct anymore).
Then, you sum over quantity to get the combined value for this column as wanted.
SELECT r.recid, sum(s.quantity), s.rrp, ts.thumbnail, ts.bigpic, t.rating
            FROM tyres t
            INNER JOIN stocklevels s
            ON t.stockcode = s.stockcode
            LEFT JOIN tyre_treads ts
            ON t.treadid = ts.recid
            LEFT JOIN reseller r
            ON s.city=r.recid
            WHERE s.quantity> 0 AND s.rrp > 0
            GROUP BY recid