text:
Q: Why is SQLite adding unused disk space to "free-list" after deleting a lot of data in a database? The SQLite FAQ states the following:

(12) I deleted a lot of data but the database file did not get any
  smaller. Is this a bug?
No. When you delete information from an SQLite database, the unused
  disk space is added to an internal "free-list" and is reused the next
  time you insert data. The disk space is not lost. But neither is it
  returned to the operating system.

Can you explain to me the motives behind that decision (as opposite to returning free space to the OS immediately)? What are the pros and cons of such decision (including non-obvious ones)?

A: As Phil wrote, freeing pages from the free-list would require that pages are moved around (and that all references to those pages are adjusted).
When data is deleted, it is very likely that some other data will be inserted afterwards, and that data can then just use the pages in the free-list. Returning those pages to the OS only to allocate new ones afterwards would be inefficient, and will increase fragmentation (both of the database file on disk, and of the objects in the database file). But if you really want SQLite to do that, you can enable it with PRAGMA auto_vacuum.
In practice, deleting lots of data usually doesn't happen during normal operation, and if you know that you will not insert new data after deleting, you can run the VACUUM command manually.


text:
Q: Spark/PySpark collect_set with a binary column Some test data, with two columns: the first binary (using alphanumeric bytes in this example), the second an integer:
from pyspark.sql.types import *
from pyspark.sql import functions as F

df = spark.createDataFrame([
    (bytearray(b'0001'), 1),
    (bytearray(b'0001'), 1),
    (bytearray(b'0001'), 2),
    (bytearray(b'0002'), 2)
],
schema=StructType([
    StructField("bin", BinaryType()),
    StructField("number", IntegerType())
]))

Using collect_set to group by the integer column and then remove duplicates doesn't work, because byte arrays don't support hashing. Hence:
(
    df
    .groupBy('number')
    .agg(F.collect_set("bin").alias('bin_array'))
    .show()
)

+------+------------+
|number|   bin_array|
+------+------------+
|     1|[0001, 0001]|
|     2|[0001, 0002]|
+------+------------+

One hacky option is to embed the binary array in a struct and then unwrap them all again afterwards, but I suspect this will result in a huge number of allocations and be very expensive (haven't actually profiled it though):
def unstruct_array(input):
    return [x.bin for x in input]

unstruct_array_udf = F.udf(unstruct_array, ArrayType(BinaryType()))

(
    df
    .withColumn("bin", F.struct("bin"))
    .groupBy('number')
    .agg(F.collect_set("bin").alias('bin_array'))
    .withColumn('bin_array', unstruct_array_udf('bin_array'))
    .show()
)

+------+------------+
|number|   bin_array|
+------+------------+
|     1|      [0001]|
|     2|[0001, 0002]|
+------+------------+

If I try lots of Google search terms around binary types and Spark, there are various answers that say you should wrap arrays if you need hashing. Suggestions include a custom wrapper or by calling Scala's toSeq that creates a Scala WrappedArray. For instance:
ReduceByKey with a byte array as the key
How to use byte array as key in RDD?
So, options include:

*

*Mapping the underlying RDD to make the binary field a WrappedArray. Not sure how to do that in Python?

*Creating a Python wrapper for the array, and then somehow hashing the underlying Java array in Python? Though not sure that has any advantage over using a struct?

*I could wrap in a struct and then never unwrap, which would be a bit more efficient processing-wise, but would then presumably make parquet files bigger and more expensive to parse in all downstream tasks

A: Here is a hack that will probably be more efficient that wrapping and unwrapping. You could simply call the distinct method beforehand.
df.show()
+-------------+------+
|          bin|number|
+-------------+------+
|[30 30 30 31]|     1|
|[30 30 30 31]|     1|
|[30 30 30 31]|     2|
|[30 30 30 32]|     2|
+-------------+------+

df.distinct().show()
+-------------+------+
|          bin|number|
+-------------+------+
|[30 30 30 31]|     1|
|[30 30 30 31]|     2|
|[30 30 30 32]|     2|
+-------------+------+

Note that I probably do not use the same version of Spark as yours (mine is 2.2.1) for the display of binary arrays seems different.
Then, for the collect_set, it simply boils down to:
df.distinct().groupBy("number").agg(F.collect_set("bin"))

redpajama_set_name: RedPajamaStackExchange


text:
Q: Async WebClient not truly Async? I have created an Asynchronous WebClient request inside a class as follows:
public class Downstream
    {
        public bool StartDownstream()
        {
            WebClient client = new WebClient();

            client.Headers.Add("user-agent", "Mozilla/4.0 [...]");
            client.Headers.Add("Content-Type","application/x-www-form-urlencoded");
            try
            {

                byte[] postArray = Encoding.UTF8.GetBytes("somevar=foo&someothervar=bar");
                Uri uri = new Uri("http://www.examplesite.com/somepage.php");

                client.UploadDataCompleted +=
                new UploadDataCompletedEventHandler(client_UploadDataCompleted);
                client.UploadDataAsync(uri, postArray);
            }
            catch (WebException e)
            {
                MessageBox.Show("A regular Web Exception");
            }
            catch (NotSupportedException ne)
            {
                MessageBox.Show("A super Web Exception");
            }
            return true;
        }

        void client_UploadDataCompleted(object sender, UploadDataCompletedEventArgs e)
        {
            MessageBox.Show("The WebClient request completed");
        }
    }

I then create a new instance of the class and run the method here:
Downstream Downstream1 = new Downstream();
Downstream1.StartDownstream();

When I do so, the thread that the form is running on seems to hang until the WebClient gets a response back. Why is this? I have used the UploadDataAsync method so should it not be Asynchronous?
Edit:
This is my call stack:
    [External Code]
>   Arcturus.exe!Arcturus.Downstream.StartDownstream() Line 36 + 0x18 bytes C#
    Arcturus.exe!Arcturus.MainWindow.btnLogin_Click(object sender, System.Windows.RoutedEventArgs e) Line 111 + 0x12 bytes  C#
    [External Code]

This is all that happens when I run my application, just hanging on the StartDownstream() and client.UploadDataAsync(uri, postArray); methods.

A: My problem I had was to do with the WebClient using the same thread as the UI, regardless of it being Async or not. I decided to use a BackgroundWorker instead.
Thanks for the answers!

A: Just a guess, does your main form have the STAThread attribute set on it? If you application doesn't have any COM calls then you can safely remove this attribute. Perhaps it may force UploadDataAsync to run in the same thread as the main form, thus blocking it.

A: First, you need to use await keyword before client.UploadDataAsync(uri, postArray). Therefore it should be " await client.UploadDataAsync(uri, postArray); "
Second, since you use await keyword in your method, you need to write async beginning of your method declaration and Task instead of bool. Therefore it should be async public Task StartDownstream(){..}
After these two steps, since your StardDownstream method async you also should await it.
Use it like await Downstream1.StartDownstream();
If I have any mistake, let me know because I am new to this topic.


text:
Q: Error: Invalid HTML for md-menu: Expected the menu to contain a `md-menu-content` element I am trying angular material menu
 <md-menu class="address-menu" layout="row " layout-align="end-center " flex="10 ">
       <md-button  ng-click="vm.openMenu($mdOpenMenu, $event);vm.showAddressMenu(cartItemDetails)" class="address-menu-icon">
           more_vert
       </md-button>
      <apt-address-menu ng-if="itemDetails.showAddressMenu " details="itemDetails "></apt-address-menu>
</md-menu>

here I am trying to make a directive for md-menu-content like below:
<md-menu-content width="4">
<md-menu-item >
    <md-button translate="ADDRESS_MENU.DUPLICATE"></md-button>
</md-menu-item>
<md-menu-item ng-click="vm.showShippingLocations()">
    <md-button translate="ADDRESS_MENU.CHANGE_ADDRESS"></md-button>
</md-menu-item>
<md-menu-item ng-click="vm.changeDefaultAddress()">
    <md-button translate="ADDRESS_MENU.DEFAULT_ADDRESS"></md-button>
</md-menu-item>
<md-menu-item >
    <md-button translate="ADDRESS_MENU.DELETE_CART"></md-button>
</md-menu-item>

But while doing so,
I am getting the error:
Error: Invalid HTML for md-menu: Expected the menu to contain a `md-menu-content` element.

Any help would be appreciated.

A: The md-menu directive will require some elements in the DOM when it compiles, at least in 1.1.4.
Specifically it needs a md-menu-content right under the md-menu element.
This is why md-menu-content cannot be put in a template of a directive of your own, because the DOM will look like this:
<md-menu>
<my-directive> <- Not md-menu-content
***here starts your directive***
<md-menu-content>
***code of your directive***
</md-menu-content>
***here ends your directive***
</my-directive>
<md-menu>

Fortunately it does not need the md-menu-item to be right under the md-menu-content, so what you could do is wrap only the md-menu-item inside your directive.
This should work:
AptAddressMenu directive template
<md-menu-item >
    <md-button translate="ADDRESS_MENU.DUPLICATE"></md-button>
</md-menu-item>
<md-menu-item ng-click="vm.showShippingLocations()">
    <md-button translate="ADDRESS_MENU.CHANGE_ADDRESS"></md-button>
</md-menu-item>
<md-menu-item ng-click="vm.changeDefaultAddress()">
    <md-button translate="ADDRESS_MENU.DEFAULT_ADDRESS"></md-button>
</md-menu-item>
<md-menu-item >
    <md-button translate="ADDRESS_MENU.DELETE_CART"></md-button>
</md-menu-item>

Parent
<md-menu class="address-menu" layout="row " layout-align="end-center " flex="10 ">
       <md-button  ng-click="vm.openMenu($mdOpenMenu, $event);vm.showAddressMenu(cartItemDetails)" class="address-menu-icon">
           more_vert
       </md-button>
<md-menu-content>
      <apt-address-menu ng-if="itemDetails.showAddressMenu " details="itemDetails "></apt-address-menu>
</md-menu-content>
</md-menu>


text:
Q: Nesting conditions on OpenSearch We recently migrated to Open Search, we are recreating our db logic inside OS, and in most scenarios we have been successful.
There is one use case that we are struggling heavily to achieve.
The original query has nested conditions like this :
WHERE
    (
        (
            NOT D2.DOCTYPE IN ('Text','Log','Query')
            AND D2.ATTRIBUTE1 LIKE @DocNumber
        )
        OR (
            D2.DOCTYPE IN ('Novel','Comedy')
            AND D2.ATTRIBUTE2 LIKE @DocNumber
        )
        OR (
            D2.DOCTYPE = 'Science-text'
            AND D2.ATTRIBUTE3 LIKE @DocNumber
        )
        OR (
            D2.DOCTYPE IN ('Fiction', 'Romance')
            AND D2.ATTRIBUTE4 LIKE @DocNumber
        )
    )
    AND (
            @Revision = ''
            AND D2.RFLAG = 'C'
    )

I have read the documentation of boolean queries (https://opensearch.org/docs/latest/opensearch/query-dsl/bool/) inside OP and I know its possible to achieve this query, but for the life of me I have not been able to achieve it.
The closest I have been to achieve the query is this :
{
  "query": {
    "bool": {
      "minimum_should_match": 1,
      "should": [
        {
          "bool": {
            "should": [
              {
                "bool": {
                  "must_not": [
                    {
                      "wildcard": {
                        "DOCUMENTTYPE": {
                          "value": "Text"
                        }
                      }
                    },
                    {
                      "wildcard": {
                        "DOCUMENTTYPE": {
                          "value": "Log"
                        }
                      }
                    },
                    {
                      "wildcard": {
                        "DOCUMENTTYPE": {
                          "value": "Query"
                        }
                      }
                    }
                  ]
                }
              },
              {
                "bool": {
                  "must": [
                    {
                      "wildcard": {
                        "DOCUMENTNUMBER": {
                          "value": "12%"
                        }
                      }
                    }
                  ]
                }
              }
            ]
          }
        },
        {
          "bool": {
            "should": [
              {
                "bool": {
                  "should": [
                    {
                      "wildcard": {
                        "DOCUMENTTYPE": {
                          "value": "Novel"
                        }
                      }
                    },
                    {
                      "wildcard": {
                        "DOCUMENTTYPE": {
                          "value": "Comedy"
                        }
                      }
                    }
                  ]
                }
              },
              {
                "bool": {
                  "must": [
                    {
                      "wildcard": {
                        "DESCRIPTIOn": {
                          "value": "12%"
                        }
                      }
                    }
                  ]
                }
              }
            ]
          }
        },
        {
          "bool": {
            "should": [
              {
                "bool": {
                  "should": [
                    {
                      "wildcard": {
                        "DOCUMENTTYPE": {
                          "value": "Science-Text"
                        }
                      }
                    }
                  ]
                }
              },
              {
                "bool": {
                  "must": [
                    {
                      "wildcard": {
                        "ATTRIBUTE3": {
                          "value": "12%"
                        }
                      }
                    }
                  ]
                }
              }
            ]
          }
        },
        {
          "bool": {
            "should": [
              {
                "bool": {
                  "should": [
                    {
                      "wildcard": {
                        "DOCUMENTTYPE": {
                          "value": "Fiction"
                        }
                      }
                    },
                    {
                      "wildcard": {
                        "DOCUMENTTYPE": {
                          "value": "Romance"
                        }
                      }
                    }
                  ]
                }
              },
            ]
          }
        }
      ],
      "must": [
        {
          "wildcard": {
            "RFLAG": {
              "value": "C"
            }
          }
        }
      ]
    }
  }
}

But this query ALWAYS bring the total amount of data inside my index.
What am I doing wrong ?


text:
Q: Custom JSON response format in Phoenix Phoenix seems to have an unconventional way of serializing JSON (it's new to me anyway). For example, let's say I have a table with two columns - id, and name. In nearly every other web framework the response to the show endpoint would return JSON that looks like this:
{
    "id": 1,
    "name": "foo"
}

Using the Phoenix generators the response looks like this:
{
    "data":
    {
        "id": 1,
        "name": "foo"
    }
}

I'm seeing similar issues with POSTs, I need to post {"company": { "name": "foo" } } instead of { "name": "foo" }.
I have two questions:

*

*Is there an advantage to serializing JSON this way that I'm unaware of?

*Is there a way to handle JSON serialization in the "normal" way as described above?

A: *

*I think that comes down to personal preference.

*You can change it of course.
In the generated view, change it from
def render("show.json", %{id: id, name: name}) do
  %{
    data: %{
      id: id,
      name: name
    }
  }
end

to
def render("show.json", %{id: id, name: name}) do
  %{
    id: id,
    name: name
  }
end

And in your controller function which accepts JSON from:
def create(conn, %{"company" => %{"name" => name}}) do
  ...
end

to
def create(conn, %{"name" => name}) do
  ...
end

Your generated functions might look different but I think you get the point.

A: Posting diffs of Phoenix 1.3.0 generated code so that it might help others:
Controller changes
-  def create(conn, %{"company" => company_params}) do
+  def create(conn, company_params) do

-  def update(conn, %{"id" => id, "company" => company_params}) do
-    company = Repo.get!(Company, id)
+  def update(conn, company_params) do
+    company = Repo.get!(Company, conn.path_params["id"])

View changes
   def render("index.json", %{companies: companies}) do
-    %{data: render_many(companies, ConstructApi.CompanyView, "company.json")}
+    render_many(companies, ConstructApi.CompanyView, "company.json")
   end

   def render("show.json", %{company: company}) do
-    %{data: render_one(company, ConstructApi.CompanyView, "company.json")}
+    render_one(company, ConstructApi.CompanyView, "company.json")
   end


text:
Q: Eclipse - how to create on-class-created template I watched the question about Eclipse -> Java -> Templates and how to create template to decrease code time development but I couldn't find how to:

*

*generate template on Java class created

*generate the template for some special Java classes which extend javax.swing.JPanel
for example how to generate code like :
public class AClass extends JPanel {

    public AClass(){this.aMethod();}
    private void aMethod(){}
}

...on Java class created?
EDIT :
I try to invoke template code generation on new java source file created (see image)

I tried to edit the preferences -> Java -> code templates constructor body (see image) but I am not sure how to insert method invoke into constructor body :(

I tried to input this.aMethod(); into the edit text area but this doesn't generate constructor body as : public AClass(){this.aMethod();}

A: for question A :
You can edit template through eclipse preferences :
Java code style > Code template

For question B :
You would have to create a custom new file wizard (a little overkill maybe...)
you can find a simple tutorial on vogella :
http://www.vogella.com/tutorials/EclipseWizards/article.html


text:
Q: Iron-ajax can't read json file I'm using a Polymer app initialized with the Polymer Starter Kit in my first view. I want to read a JSON file inside a <paper-listbox>, and create a <paper-item> for each array element:
Here's the code for my <paper-listbox>:
<paper-listbox>
    <iron-ajax auto url="/listActivities.json" handle-as="json" last-response="{{activities}}" id="ajaxLoader"></iron-ajax>
    <template is="dom-repeat" items="{{activities}}">
        <paper-icon-item>
            <iron-icon icon="star" item-icon></iron-icon>
            <paper-item-body two-line>

{{item.label}}

Unit game number : {{item.unitGames.length}}

            </paper-item-body>
        </paper-icon-item>
    </template>
  </paper-listbox>

Here's my JSON file:
[
{
    "_id":"58dbcb30dc0b2a01553c59a9",
    "staticMedia":"58d52d626575de2207193fac",
    "label":"myfirstgame",
    "__v":0,
    "unitGames":["58dbcaa5dc0b2a01553c59a8"]
},
{
    "_id":"58dd1d3edc0b2a01553c59af",
    "staticMedia":"58d12091241b0868bfb29a3b",
    "label":"Jeu à l'IUT",
    "__v":0,
    "unitGames":["58dd1b61dc0b2a01553c59ab"]
},
{
    "_id":"58dd23e14704644b4ab307e6",
    "staticMedia":"58d12091241b0868bfb29a3b",
    "label":"IUT",
    "__v":0,
    "unitGames":["58dd23ba4704644b4ab307e4"]
},
{
    "_id":"58e008d67d08713351f0af13",
    "staticMedia":"58d52d626575de2207193fac",
    "label":"Test POI clue",
    "__v":0,
    "unitGames":["58e008b97d08713351f0af12"]
},
{
    "_id":"58e10d2d7d08713351f0af22",
    "label":"Prunus MLG",
    "__v":0,
    "unitGames":["58e10d167d08713351f0af21"]
}
]

The app doesn't need every part of my JSON file (only needs label and unitGames). When I run the app, it shows nothing after the title of the view. How do I fix this?

A: It's possible that you're missing one or more HTML imports required for the component:
<link rel="import" href="../iron-ajax/iron-ajax.html">
<link rel="import" href="../iron-icon/iron-icon.html">
<link rel="import" href="../iron-icons/iron-icons.html">
<link rel="import" href="../paper-listbox/paper-listbox.html">
<link rel="import" href="../paper-item/paper-item.html">
<link rel="import" href="../paper-item/paper-icon-item.html">
<link rel="import" href="../paper-item/paper-item-body.html">

With the imports above and your listActivities.json, this plunker demo produces:

A: The problem came from the url path to my JSON file, the "/" before the name of the file wasn't needed as the file was on the same folder as my-view1.html.


text:
Q: Crystal Reports for Visual Studio 2010 Error I am trying to run a crystal report from my web application which was built using ASP.NET 4.0 and Visual Studio 2010. I have installed the following from the SAP site (http://www.businessobjects.com/jump/xi/crvs2010/us2_default.asp)
1) SAP Crystal Reports, version for Visual Studio 2010 - Standard EXE installation package which installs the software into the Visual Studio IDE.
2) SAP Crystal Reports runtime engine for .NET Framework 4 (64-bit)
I have a page called Reports.aspx in which I have a crystal report viewer control
 <CR:CrystalReportViewer ID="rptViewer" runat="server" AutoDataBind="true" />

In the Reports.aspx.cs file I have the following code:
protected override void OnPreRender(EventArgs e)
{
    ReportDocument report = new ReportDocument();
    var path = Server.MapPath("Reports/Sample.rpt");
    report.Load(path);
    report.SetDatabaseLogon("username", "password", "servername", "databasename");
    rptViewer.ReportSource = report;
}

On the report.Load(path) line I get the following error:
Unsupported Operation. A document processed by the JRC engine cannot be opened in the C++ stack.
How can I fix this?

A: You will need to modify two properties in the .rpt files:

*

*Build Action is set to "Embedded Resource" by default. Change it to "Content".

*Copy to Output is set to "Do not copy" by default. Change it to "Copy always".

Rebuild, Build deployment package and Publish. Done!

A: NOTE: Below, the term "WebSite" refers to actual web site nodes in IIS, NOT a virtual directory within a web site.
Problem Root Cause: There is no "aspnet_client" folder accessible by the application.
This can happen for several reasons:

*

*Since the SAP CR installer appears to install the aspnet_client folder in the ...\inetpub\wwwroot\ folder, if your Web Site physical path is NOT ...\inetpub\wwwroot, your application will not have access to the aspnet_client folder.

*If the aspnet_client folder was moved or deleted from to the top level of your web site's physical path, your IIS application will not have access to the folder.

Problem Solution (For Windows Server 2008 R2)

*

*Go to the IIS manager on your server

*Expand the tree view node for the WebSite running your application

*Look at the level immediately under the web site node and ensure you see a "aspnet_client" folder.

*If you do see the folder, then perhaps this root cause is not the cause of your problem.

*If you do NOT see the folder, search the server's hard drive for it and COPY it to the Web Site's Physical path.

*Right mouse button click on the Web Site node and click Refresh from the popup Menu

*You should now see the aspnet_client folder at the level directly under your web site node and the reports in the application should work.

A: I ran into this when I converted a web site to a web application.  The report would run fine on my dev machine, but not on the server.  Then I realized the rpt file was missing on the server!
By default the report files were considered embedded resources and were not copied when the web application was published.  I just changed them individually, republished the site, and all was well again.

A: I have also had a report load failure if I have mistakenly left the report file open in crystal reports designer.

A: This error is a real treat, and seems to have many possible antecedents.  Fortunately I only wasted a day on my particular variation:
ReportDocument.Load() also makes a local temp copy.  (This may only be in the case of a load from a network drive location, I didn't test this in the case of a local load.)
If the user context under which the load occurs does not have authority to create the temp file locally, Load will fail with the same very unhelpful error.

Also, I ended up diagnosing this with Process Monitor.  It may be helpful for you as well.

A: I also got into the same problem my problem was report path was not valid, May be you have same problem , check  Server.MapPath("Reports/Sample.rpt") returning valid path ?

A: make sure the report is in app_code folder
initialize a new instance of it instead of initializing a reportdocument and loading the report in it.
Sample report = new Sample();

this worked for me

A: Please make sure your report rpt files are in their original folder. I got the same error first, after I "published" my MVC web site to IIS. I didn't realize that "Publish" didn't put rpt files in the package.

A: *

*Re-install the "Crystal report engine" to the server

*Build Action set to "Content".
It perfectly worked for me..!


text:
Q: startx gives the error "Could not resolve keysym XF86 KeyboardError" I installed Arch Linux following this tutorial. After installing gnome and configuring .xinitrc, running
startx

gave the error - "Could not resolve keysym XF86 KeyboardError"  and exited. But
sudo startx

gave some different error and showed three terminals with a clock on top right.
systemctl start gdm.service

gives the error "Something went wrong" with a "Log Out" button
Log File
Arch Version - 2018.07.01
While installing
xorg-server-utils

was not found.
What I have tried  -
export XAUTHORITY=/home/subham/.Xauthority

This gives the error - "timeout in locking authority" followed by a black screen and then the error "No protocol specifies..xinit: giving upxinit: unable to connect to X server: Resource temporary unavailable"
Setting XAUTHORITY back to ""  doesn't change the error.


text:
Q: How to match an object with specific shape and cut it out from image? Well, I have a problem with finding a solution to this one. I want to match specific shape of object on image and cut it out. Object is not in the same place all the time. There are small differences.. also it can be smaller than the one which is compared with. Another problem is the background which has similar pixel intensivity and segmentation doesn't work as it should(it takes all the object pixels and some from the background). I need to get rid of those pixels which are not the object pixels. That's why I would like to match with the "template" and cut out the exact shape of it with no background. Is it possible?

I've tried few segmentation methods but it doesn't work. Those pixels above the object have similar intensivity to those which are object pixels. I've tried morphology operations but it doesn't work either.


text:
Q: Javafx Image placeholder I'm creating an asset sharing application. The application loads tiles from data coming from my server. The users can download and upload assets from/to the server. An asset can have or not an image with it. The tiles use the asset image as background and or a default one if none is found on the server.
The asset itself is named with a hash, and if an image is provided, the image file is named the same, with a "png" extension, making it easy to find the images without DB queries or more work.
When the app loads, it gets the data from the server and loads the images on background.
I know there is a way to check if an image exists using the html return codes like
public static boolean urlExists(String url)
{
    try
    {
        HttpsURLConnection.setFollowRedirects(false);
        HttpsURLConnection con = (HttpsURLConnection) new URL(url).openConnection();
        con.setRequestMethod("HEAD");
        return (con.getResponseCode() == HttpsURLConnection.HTTP_OK);
    }
    catch (Exception e)
    {
        e.printStackTrace();
        return false;
    }
}

But that can take time, slowing down my loading process, as I load about 500 assets on launch.
So I thought, hey, just provide the url to the image constructor, anyway, if the url doesn't exist, we don't get an error, but an empty image....
tileBackground.setImage(getObj().getImageURL());

Problem, if that image is empty, I'd still like to display a placeholder...
I have tried to use Image.isError() / image.errorProperty() / image.exceptionProperty() but even if the url doesn't exist, these don't show it. So I thought, let^s make it this way:
Image image = new Image(MainApp.class.getResourceAsStream("view/img/default-tile-icon.png"));
ImageView tileBackground= new ImageView(image);
getObj()._image.progressProperty().addListener((observable, oldValue, newValue) -> {
        if (newValue.intValue() == 1) {
            tileBackground.setImage(getObj().getImage());
        }
    });

So technically, set a default image for every tile, and when the object finishes loading the image, set it as the tile background... But non existing url image do load as well up to 100%...
Who would have a nicer idea to display a default image when the image doesn't display, without url checking that consumes a lot of time?


text:
Q: How do I read arbitrary bytes from a zlib stream? I would like to read the output of a zlib stream's inflate() into a buffer one byte at a time, so that I can parse out single lines.
Is there a way to specify the number of bytes that inflate() returns, so that I can watch for newlines?

A: When you call inflate() you pass a pointer to a z_stream_s structure. z_stream_s::avail_out member variable of that structure is exactly for specifying the size of the output buffer.

A: That would probably give horrible performance, since the inflate() function might have some start up costs.
I would suggest just going with a reasonable output buffer size, and then iterating through the buffer after each call to inflate(), collecting all complete lines found. Of course there will very likely be a "tail", i.e. an incomplete line, that you will need to keep track of for the next round.


text:
Q: How to access a specific table in a Word document I have a docx document with 10 tables. I want to access table 3, 4, 8 and 9 to color the content of the table. How can I access a specific table via VBA?
I know this code will access all tables, but instead of all, I just want to use my code on specific tables:
Dim oTbl As Word.Table
For Each oTbl In ActiveDocument.Tables

The code right now will color a table, which is in my focus:
Sub colourSelectedTable()

Dim c As Word.Cell

If Selection.Information(wdWithInTable) Then
  For Each c In Selection.Tables(1).Range.Cells

    If InStr(c.Range.Text, Chr(37)) > 0 And Val(c.Range.Text) >= 110 Then
    c.Shading.BackgroundPatternColor = rgb(255,124,103)

    ElseIf InStr(c.Range.Text, Chr(37)) > 0 And Val(c.Range.Text) < 0 Then
    c.Shading.BackgroundPatternColor = rgb(255,124,103)

    ElseIf InStr(c.Range.Text, Chr(37)) > 0 And Val(c.Range.Text) <= 100 Then
    c.Shading.BackgroundPatternColor = rgb(136,241,142)

    ElseIf InStr(c.Range.Text, Chr(37)) > 0 And Val(c.Range.Text) > 100 And Val(c.Range.Text) < 110 Then
    c.Shading.BackgroundPatternColor = rgb(255,227,132)

    ElseIf Val(c.Range.Text) = "Good" Then
    c.Shading.BackgroundPatternColor = rgb(136,241,142)

    ElseIf Val(c.Range.Text) = "Fair" Then
    c.Shading.BackgroundPatternColor = rgb(255,227,132)

    ElseIf Val(c.Range.Text) = "Satisfactory" Then
    c.Shading.BackgroundPatternColor = rgb(255,227,132)

    ElseIf Val(c.Range.Text) = "Not Satisfactory" Then
    c.Shading.BackgroundPatternColor = rgb(255,124,103)

  End If

  Next
  End If
  End Sub

A: Most collections like Tables, Paragraphs, etc. can be accessed by number : Document.Tables(1)
Dim i As Long, c As Word.Cell, doc As Document
Set doc = ActiveDocument

For i = 1 To doc.Tables.Count
    If i = 3 Or i = 4 Or i = 8 Or i = 9 Then
        For Each c In doc.Tables(i).Range.Cells
            ' your code here
        Next
    End If
Next


text:
Q: Interpolation polynomials and Vandermonde Matrices I'm looking for a polynomial of degree $5$ such that: $p(-1)=1, p'(-1)=1, p(0)=3, p'(1)=2, p(2)=1, p'(2) = 4$
I want to show that there is no such polynomial by showing that the Vandermonde matrix associated to the system has a determinant equal to $0$.
Now I know that the Vandermonde matrix associated to the system is:
$ \left( \begin{array}{ccc}
1 & -1 & 1 & -1 & 1 & -1 \\
0 & 1 & -2 & 3 & -4 & 5 \\
1 & 0 & 0 & 0 & 0 & 0 \\
0 & 1 & 2 & 3 & 4 & 5 \\
1 & 2 & 4 & 8 & 16 & 32 \\
0 & 1 & 4 & 12 & 32 & 86 \end{array} \right) $
The determinant is indeed $0$ (an therefore no such polynomial exists) But I don't understand how we came up with those coefficients.

A: The general form of a degree $5$ polynomial is $p(x) = a_0 + a_1 x + a_2 x^2 + a_3x^3 + a_4 x^4 + a_5 x^5$. Now consider the equation $p(-1) = 1$, which is equivalent to
$$
a_0 - a_1 + a_2 - a_3 + a_4 - a_5 = 1 \iff (1,-1,1,-1,1,-1)\cdot(a_0,a_1,a_2,a_3,a_4,a_5) = 1.
$$
So the variables of the linear system are the coefficients of $p$, and the first row of the matrix corresponds to the vector $(1,x,x^2,x^3,x^4,x^5)$ at $x = -1$. You can use the same reasoning with the remaining equations to obtain the remaining rows of the matrix.


text:
Q: jQuery select value inside neighbourhood TD I want to get value inside span with id 'TargetSpan' when user clicks on Input with ID of 'test'
I tried this code but it returns null.

$('.PrintReport').click(function (e) {
            alert($(this).parent().find('td:eq(2)').html());

        });

0

<input id=test type="image"  class="PrintReport" >

0

<input id=test2 type="image"  class="PrintReport" >

A: .parent() will return the parent td; try parent().parent() or .closest("tr")

A: I guess this is what you are looking for and of course this solution relative to your HTML mark-up and might not work if you change your mark-up.
$('.PrintReport').click(function() {
  alert($(this).parent().prev().prev().find('.Price').html());
});

this is another solution but you have to give every TargetSpan and Test id's with a number suffix like TargetSpan1, TargetSpan2, test1, test2
$('.PrintReport').click(function() {
  var id = this.id.replace('test', '');
  alert($(this).closest('tr').find('TargetSpan' + id).html());
});

A: Why don't you just select it by the id?
$('#TargetSpan').html()

A: If you continue to use the id conventions in your example, this will ALWAYS work, regardless of td order.
$('.PrintReport').click(function (e) {
    alert($('#TargetSpan' + $(this).attr('id').replace(/\D/g,'')).html());
});


text:
Q: An audio error has occurred, player will skip forward in 2 seconds I added the music player plugin to my own blog and recently opened it to find that the music player is not working with the following prompt:
An audio error has occurred, the player jumps forward in 2 seconds.
Please tell me what the problem is and how to solve it, thanks a lot!


text:
Q: How can I redirect viewers who are blocked from social networking to an alternative page I've looked at this Check if Facebook is blocked then redirect to try and help me solve this problem.
I have a web page that has an iframe in that contains my tumblr page. What I want is if someone is at work and social networking is blocked it won't try and load the tumblr in the src of the iframe but load my own page tumblr.htm instead.
so I got this far and realise I don't know what I'm doing really.
function isSiteOnline(url,callback) {
// try to load favicon
var timer = setTimeout(function(){
    // timeout after 5 seconds
    callback(false);
},5000)

var img = document.createElement("img");
img.onload = function() {
    clearTimeout(timer);
    callback(true);
}

img.onerror = function() {
    clearTimeout(timer);
    callback(false);
}

img.src = url+"/favicon.ico";
}

isSiteOnline("http://www.tumblr.com",function(found){
if(found) {
    // site is online
window.location.href = 'http://my_page.tumblr.com/';
}
else {
    // site is offline (or favicon not found, or server is too slow)
window.location.href = 'tumblr.htm';
}
}

Would this work and what would I put in the src of the iframe tag? would it be src="isSiteOnline" ? and that's where the problem is there are several others on one page (twitter etc.) so I'm fighting a losing battle through lack of experience. Can anyone help?


text:
Q: The import org.apache.axis2.AxisFault cannot be resolved. What dependency installs necessary AxisFault? Tried adding a dependency for a recently installed project. Uses
import org.apache.axis2.AxisFault;

Dependency is:
<!-- https://mvnrepository.com/artifact/org.apache.axis2.wso2/axis2 -->
<dependency>
    <groupId>org.apache.axis2.wso2</groupId>
    <artifactId>axis2</artifactId>
    <version>1.6.1-wso2v54</version>
</dependency>

Error message is
Missing artifact org.apache.axis2.wso2:axis2:jar:1.6.1-wso2v54
In any case I can't find out where this import comes from. Googled it and none of those dependencies worked. Tried:
<!-- https://mvnrepository.com/artifact/org.apache.axis2/axis2 -->
<dependency>
    <groupId>org.apache.axis2</groupId>
    <artifactId>axis2</artifactId>
    <version>1.7.9</version>
    <type>pom</type>
</dependency>

<!-- https://mvnrepository.com/artifact/org.apache.axis/axis -->
<dependency>
    <groupId>org.apache.axis</groupId>
    <artifactId>axis</artifactId>
    <version>1.4</version>
</dependency>

Still nothing.
pom file is:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<!--
<parent>
    <groupId>org.orgname.maven</groupId>
    <artifactId>ORGNAME-Parent</artifactId>
    <version>2.0</version>
</parent>
 -->
<name>PDM-ProjectName</name>
<groupId>org.orgname.apps.pdm</groupId>
<artifactId>ProjectName</artifactId>
<version>2.0.2-SNAPSHOT</version>
<packaging>war</packaging>
<description>static web-based 'reports' to provide a view of Windchill data</description>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <junit.version>4.8.2</junit.version>
    <log4j.version>1.2.17</log4j.version>
    <slf4j.version>1.6.1</slf4j.version>
</properties>
<dependencies>
    <!-- https://mvnrepository.com/artifact/org.apache.xmlbeans/xmlbeans -->
    <dependency>
        <groupId>org.apache.xmlbeans</groupId>
        <artifactId>xmlbeans</artifactId>
        <version>2.6.0</version>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.axis2/axis2 -->
    <dependency>
        <groupId>org.apache.axis2</groupId>
        <artifactId>axis2</artifactId>
        <version>1.7.9</version>
        <type>pom</type>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.apache.axis/axis -->
    <dependency>
        <groupId>org.apache.axis</groupId>
        <artifactId>axis</artifactId>
        <version>1.4</version>
    </dependency>

                        <!-- https://mvnrepository.com/artifact/org.apache.axis2.wso2/axis2 -->
<dependency>
<groupId>org.apache.axis2.wso2</groupId>
<artifactId>axis2</artifactId>
<version>1.6.1-wso2v54</version>
</dependency>

    <dependency>
        <groupId>org.orgname.utils</groupId>
        <artifactId>ess-proxies</artifactId>
        <version>3.5-RELEASE</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>${log4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>${slf4j.version}</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>${slf4j.version}</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>${junit.version}</version>
    </dependency>
    <dependency>
        <groupId>commons-httpclient</groupId>
        <artifactId>commons-httpclient</artifactId>
        <version>3.1</version>
    </dependency>
    <dependency>
        <groupId>javax.mail</groupId>
        <artifactId>mail</artifactId>
        <version>1.4</version>
    </dependency>
    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-lang3</artifactId>
        <version>3.1</version>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.0.1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>
<build>
    <sourceDirectory>src/main/java</sourceDirectory>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <excludes>
                <exclude>**/*.java</exclude>
            </excludes>
        </resource>
    </resources>
    <plugins>
        <plugin>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.8</source>
                <target>1.8</target>
            </configuration>
        </plugin>
        <plugin>
            <artifactId>maven-war-plugin</artifactId>
            <version>2.3</version>
            <configuration>
                <warSourceDirectory>WebContent</warSourceDirectory>
                <failOnMissingWebXml>false</failOnMissingWebXml>
            </configuration>
        </plugin>
    </plugins>
</build>
</project>

I really think this is just a problem with the dependency, as a simple import isn't working right, and I'm having trouble finding the right dependency to work that has the right file AxisFault in its packages. For some reason though axis2 doesn't contain the right things I need. If someone grabs the same dependencies I do, do they see
import org.apache.axis2.AxisFault;

working correctly, not giving an error message? I'm a bit lost, any help would be appreciated.

A: I got it!
Answer was here:
https://jar-download.com/artifacts/org.apache.axis2/axis2-kernel/1.7.7/source-code/org/apache/axis2/AxisFault.java
<dependency>
    <groupId>org.apache.axis2</groupId>
    <artifactId>axis2-kernel</artifactId>
    <version>1.7.7</version>
</dependency>


text:
Q: jquery $.ajax() with IE I have been searching high and low on the internet for an answer to this question and I think there is something I am missing. I am reading in a gallery of photos from an xml document via jquery $.ajax() and I am having trouble with IE7. The function I am using works fine in all the other browsers I've tested.
I have read a ton on setting the correct dataType and contentType for IE, but I'm beginning to question whether or not that is the issue. I have tried a ton of combinations of different dataTypes and contentTypes and none of them seem to do the trick. I am wondering if there may be an issue with my xml or with the way my function is reading the xml, because with the function set the way it currently is, everything runs through in IE7, but none of the images are added to the DOM.
    var dataType;
if ($.browser.msie) { dataType = 'text' } else { dataType = 'html' };

$.ajax({
   type: 'GET',
   url: 'images/gallery-images/gallery-images.xml',
   dataType: dataType,
   success: function(parseXML){

   $(parseXML).find('section').each(function(){

    var $section = $(this),
        photos = $section.find('photo'),
        photoContainer = $('

', { id : $section.attr('id'), 'class' : 'gallery-section' });

    photos.each(function(){

        var photo = $(this),
        imageurl = photo.attr('imageurl'),
        title = photo.find('title').text(),
        description = photo.find('description').html(),
        kind = photo.find('description').attr('type');
        icon = photo.find('icon').attr('source');
            iconClass = photo.find('icon').attr('class');

        var photoWrapper = $('

'),
            imageElem = $('', { 'src' : imageurl, 'class' : 'gallery-photo' }),
            photoInfo = $('

', { 'class' : 'photo-info ' + kind }),
            iconInsert = $('', { 'src' : icon, 'class' : iconClass }),
            header = $('

', { text: title }),
            photoDescription = $('

', { html: description });

        photoInfo.append(iconInsert).append(header).append(photoDescription);
        photoWrapper.append(imageElem).append(photoInfo);
        photoContainer.append(photoWrapper);

    });
        $('#photo-viewer-inner').append(photoContainer);
    });
    var videos = '

';
        $('#photo-viewer-inner').append(videos);
        $('#videos').load('images/gallery-images/videos.html #video-inner');

That is the code I am using to extract the data from my xml. Like I said, everything, including this and everything after this, seems to run fine in IE7, but the images are never loaded.
I am stumped, hoping to find some help here.

A: There's nothing I recognise as an IE7-snarl but here are a few suggestions:

*

*Classes - Try setting classes with class="..." or .addClass('...') as opposed to a prop in a map, eg. photoInfo = $('

').addClass(kind).

*Declarations - icon and iconClass are both missing a var (the previous line ends with semicolon).

*Duplicate ids? - Avoid a possibly duplicated id in the videos div with eg. var videos = $('

').appendTo($('#photo-viewer-inner')).load('images/gallery-images/videos.html#video-inner');. Note also I removed a space from the URL.


text:
Q: show picture file on pi3b I'm trying to show a picture file (in this example icon.png) on the screen using dispmanx (bcm_host.h) and OpenCV.
the code im using:
/*
Copyright (c) 2012, Broadcom Europe Ltd
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright
      notice, this list of conditions and the following disclaimer in the
      documentation and/or other materials provided with the distribution.
    * Neither the name of the copyright holder nor the
      names of its contributors may be used to endorse or promote products
      derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <iostream>
#include <memory>
#include <cstdlib>
#include <cassert>
#include <vector>

#include "bcm_host.h"

#include <opencv2/core/core.hpp>

#include <opencv2/highgui/highgui.hpp>

#ifndef ALIGN_UP
#define ALIGN_UP(x,y) ((x + (y)-1) & ~((y)-1))
#endif

class Rect {
    static int rectCount;
    static DISPMANX_DISPLAY_HANDLE_T   display;
    static DISPMANX_MODEINFO_T         info;
    static DISPMANX_RESOURCE_HANDLE_T  resource;
    void                              *image;
    static DISPMANX_UPDATE_HANDLE_T    update;
    DISPMANX_ELEMENT_HANDLE_T          element;
    uint32_t                           vc_image_ptr;
    VC_RECT_T       src_rect;
    VC_RECT_T       dst_rect;
    VC_DISPMANX_ALPHA_T alpha;
    int x, y;
    int width, height;
    int pitch;
    int aligned_height;
    VC_IMAGE_TYPE_T type;

public:
    Rect(int x, int y, int width, int height, unsigned char* data):x(x),y(y),width(width),height(height) {
        if(display == 0) {
            bcm_host_init();
            display = vc_dispmanx_display_open(1);
            int ret = vc_dispmanx_display_get_info(display, &info);
            assert(ret == 0);
            std::cout << "Display:  " << info.width << " x " << info.height << std::endl;
        }
//        pitch = ALIGN_UP(width*2, 32);
        pitch = ALIGN_UP(width*3, 32);
        aligned_height = ALIGN_UP(height, 16);
//        type = VC_IMAGE_RGB565;
//        type = VC_IMAGE_BGRX8888;
        type = VC_IMAGE_BGR888;
//        image = calloc(1, pitch * height);

    image=data;

    assert(image);

   }

    int getCount() { return rectCount; }

    void beforeDraw() {
        resource = vc_dispmanx_resource_create(type,
                                               width,
                                               height,
                                               &vc_image_ptr);
        assert(resource);
        update = vc_dispmanx_update_start(0);
        assert(update);
    }

    void draw(int layer) {
        VC_DISPMANX_ALPHA_T alpha = {
                        DISPMANX_FLAGS_ALPHA_FROM_SOURCE,
                        120, /*alpha 0->255*/
                        0
        };

        vc_dispmanx_rect_set(&dst_rect, 0, 0, width, height);
        int ret = vc_dispmanx_resource_write_data(resource,
                      type,
                      pitch,
                      image,
                      &dst_rect);
        assert(ret == 0);

        vc_dispmanx_rect_set(&src_rect, 0, 0, width << 16, height << 16);

        vc_dispmanx_rect_set(&dst_rect, x, y, width, height);

        element = vc_dispmanx_element_add(update,
                      display,
                      layer,        // layer
                      &dst_rect,
                      resource,
                      &src_rect,
                      DISPMANX_PROTECTION_NONE,
                      &alpha,
                      NULL,        // clamp
                      DISPMANX_NO_ROTATE);
    }

    void afterDraw() {
        int ret = vc_dispmanx_update_submit_sync(update);
        assert(ret == 0);
    }

    ~Rect() {
        update = vc_dispmanx_update_start(0);
        assert(update);
        int ret = vc_dispmanx_element_remove(update, element);
        assert(ret == 0);
        ret = vc_dispmanx_update_submit_sync(update);
        assert(ret == 0);
        rectCount--;
        if(rectCount == 0) {
            std::cout << "No more rectangles" << std::endl;
            ret = vc_dispmanx_resource_delete(resource);
            assert(ret == 0);
            ret = vc_dispmanx_display_close(display);
            assert(ret == 0);
            display = 0;
        }
    }

};

DISPMANX_DISPLAY_HANDLE_T Rect::display = 0;
int Rect::rectCount = 0;
DISPMANX_MODEINFO_T Rect::info;
DISPMANX_RESOURCE_HANDLE_T Rect::resource;
DISPMANX_UPDATE_HANDLE_T Rect::update;

int main(void)
{

    std::vector<std::shared_ptr<Rect>> rects;

    cv::Mat img = cv::imread("/home/pi/myDispmanx/t.png" , cv::IMREAD_COLOR);
//    cv::Mat img = cv::imread("/home/pi/myDispmanx/t.png" , CV_LOAD_IMAGE_COLOR);

    int width = img.size().width;
    int height = img.size().height;
    int i=0;

    std::cout << "image width:  " << width << std::endl;
    std::cout << "image height:  " << height << std::endl;

    std::shared_ptr<Rect> r = std::make_shared<Rect>(0, 0, width, height, img.data);

    r->beforeDraw();

    r->draw(i+5);

    rects.push_back(r);

    rects[0]->afterDraw();

    sleep(2);
    return 0;
}

I'm running the code above on a pi3b (Raspbian os).
The code is error free on compilation(using g++).
however when I run the code in some cases I get "segmentation error" or  double free or corruption (out): 0x01a2f480 (<===probably some memory address)
these errors change from one to another when I change the .png file.
(still couldn't manage to figure out the reason of each case)
with a little knowledge I have on programming I believe I should be getting the same result no matter which .png file i'm using?
can anybody elaborate?
P.S I must add in one case I had a very blurry picture as an output.
EDIT: Code updated, got rid of the errors but still getting a distorted projection of the picture in some occasions. e.g: cat.png
Notice: the width and height are set considering the dimensions of the picture.

A: It is a little hard to go through such a big code, it is better to write a small sample where your error occur, to give expected behaviour and some sample images that show the problem (I mean like the blurry one not the error) . My recommendation is to use a debugger and check the output of different parts of your code to see if you get what you are expecting.
I could spot one error though:
image = calloc(1, pitch * height);

image=data;

This will allocate the data and put in image such pointer. Then you replace your pointer with the pointer to the data of OpenCV. Then you do:
free(image);

but this pointer points to the data of the cv::Mat that will try to delete it later on, so it will have double free error. To copy the data of a pointer use something like std::memcpy


text:
Q: How to download file using dropbox I'm trying to build an app that gives my users right to download file from my dropbox storage.
So I've got next quesions:
1) I was following the dropbox tutorial and it says:

If the Dropbox app is installed, the SDK will switch to it so the user
  doesn't have to sign in, and it will fallback to the browser if not.

If I run my app, it will open a browser with dropbox web site. Is there any way to avoid that?
2) Is it possible to download file by file name only? Can I just set url for my storage and file name without randomized url?

A: You can use the dropbox public folder for downloading the file that you want. You just have to put the file in that folder and then copy the url.
Then on you java you just have to put the code to download from a URL.
This is how I have done in my program and it doesn't open any browser.
A good thing about the URL in Public folder, is that it doesn't change if the filename doesn't change, so you can update your file and the URL will be the same

A: You can simply use client to download file by name
    DbxEntry.File md;
    File file = new File("destination.file");
    OutputStream out = new FileOutputStream(file);
    try {
        md = client.getFile("/path/to/target.file", null, out);
    } finally {
        out.close();
    }

Here null indicates that you want to receive the latest revision of file. And "/path/to/target.file" is path to file on your dropbox, like "/Public/001.jpg".
Also md can be used to retrieve some metadata about this file, like its size, name, revision, etc.


text:
Q: Covert object into array How can I convert an object into an array of objects and add key and value?
My current object
{   "0": "Ann_B", "1": "Billy_P", "2": "Carly_C", "3": "David_L"   }

I want it to be
[
    {  "value": "Ann_B_Aii", "name": "Ann B Aii",   },
    {  "value": "Billy_P", "name": "Billy P"  },
    {  "value": "Carly_C", "name": "Carly C"  },
    {  "value": "David_L", "name": "David L"  },
]

I used Object.entries and replace _ to space

A: You could take the values and iterate by getting new objects.

var data = { 0: "Ann_B", 1: "Billy_P", 2: "Carly_C", 3: "David_L" },
    result = Object.values(data).map(v => ({ id: v, name: v.replace(/_/g, ' ') }));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: You can use Object.values() and .map() methods:

let data = {
  "0": "Ann_B",
  "1": "Billy_P",
  "2": "Carly_C",
  "3": "David_L"
};

let result = Object.values(data)
                   .map(v => ({id: v, name: v.replace(/_/g, ' ')}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A: Try this (I assume that d contains your input object; working example HERE)
Object.values(d).map(v=>({value:v,name:v.replace(/_/g,' ')}));


text:
Q: Text not being put in same position through loop I have a loop that iterates through an array of day names, and creates a Text for each, which are then spread around a circle. The problem is that the text changes position with each iteration - appearing to get lower, then higher again. Below is the code I use:
struct LabelPositionTest: View {

private var sectorAngle: Double = Double(360/7)
private var dayNameArray: Array<String> = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
private var viewWidth: CGFloat = 180
private var viewHeight: CGFloat = 100

var body: some View {
    GeometryReader
    {   selectorWheelGeometry in
            ForEach((0...6), id: \.self) {i in
            ZStack(alignment: .trailing)
            {
                if dayNameArray.count > i
                {
                    Rectangle()
                        .foregroundColor(.red)
                    Text(dayNameArray[i])
                        .rotationEffect(Angle.degrees(90))
                        .foregroundColor(.black)
                }
            }
            .frame(width: selectorWheelGeometry.size.width/2.25, height: viewHeight)
            .rotationEffect(Angle.degrees(Double((i-1)*(360/7))+(90 + (0.5 * sectorAngle))), anchor: .leading)
            .position(x: selectorWheelGeometry.size.width/2 + (selectorWheelGeometry.size.width/2.25)/2, y: selectorWheelGeometry.size.height/2)
        }
    }
}
}

A: When working with this kind of rotated view, I have found that the easiest way to fix errors is to create the base view first, and then position and rotate the base view as a unit. Often, I will create this unit as a separate view, but your example was simple enough that I just created the Rectangle() and overlayed the Text(). One other thing I did was to switch the dimensions on the Rectangle(). Essentially, you had a Rectangle() lying on its side, and then you rotated the text to try to match the Rectangle(). I stood the Rectangle() up and overlayed the text in a normal orientation with a top alignment and some .padding().
The reason your labels weren't in the same place was that they were all rotated before positioning. If you show your code in preview, and then highlight the Text(), you will see the Text() view outlines are all different sizes. That accounts for the misplaced labels. The placement as per above, resolves this issue.
The commented code is below:
struct LabelPositionTest: View {

    private var sectorAngle: Double {
        Double(360/dayNameArray.count)
    }
    private var dayNameArray: Array<String> = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"]
    private var viewWidth: CGFloat = 100

    var body: some View {
        GeometryReader { selectorWheelGeometry in
            ZStack {
                // A much safer way of obtaining the index of an array in a ForEach is to zip the array
                // and its indices together, and then iterate off the array. This prevents out of bounds
                // errors, and, if the array elements are Identifiable, still allows you to use .move()
                // and .delete. The id: \.0 simply tells the ForEach to iterate on the first element in the zip
                ForEach(Array(zip(dayNameArray, dayNameArray.indices)), id: \.0) { day, index in
                    Rectangle()
                        .foregroundColor(.red)
                        .overlay(
                            Text(day)
                                .foregroundColor(.black)
                                .padding(.top),
                            alignment: .top
                        )
                        .frame(width: viewWidth, height: selectorWheelGeometry.size.width/2.25)
                        // You already had sectorAngle defined, so I just used that. I also removed
                        // the extra 90 degree rotation. You can put that back in if you don't want a
                        // top start. This was just simplification for the answer.
                        .rotationEffect(Angle.degrees(Double(index) * sectorAngle), anchor: .bottom)
                }
            }
            .frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .center)
        }
    }
}

A: ForEach constant range syntax for 7 days is:
ForEach(0..<7) { i in

Your constant vars should be lets.


text:
Q: how to convert gps north and gps west to lat/long in objective c I got these values from server:
<gps_n>34.22.123</gps_n>
<gps_w>81.59.345</gps_w>

I would like to convert these values to latitude/longitude in Objective C. Would you please give me a guide to do this?
Thanks

A: The formula for both lat/long (n/w) is:

Degrees+(minutes/60)+(seconds/3600)

From this page:
http://webmaster10.com/ldr/lat-long-conversion.html

A: The example you have given, already are latitude/longitude coordinates. There are many such lat,lon formats, what you want are lat/long coordinates in decimal degrees, probably with a sign to denote N/S or E/W.
Use the formula above:  (Degrees+(minutes/60)+(seconds/3600))
 and multiply latitude with -1 when S is given.
Multiply longitude by -1 when "W" is given.


text:
Q: Sprite Render with Pattern Texture ... Unity2D I want to add a pattern Texture to the sprite Render.

Anyone can help with that thanks

A: You can accomplish that by writing a custom shader.
Create a new shader and add the code from down below. After that, create a material with the newly created shader, add a texture that you want to use for the pattern and add the material to your SpriteRenderer component.
Shader source code
Shader "Custom/TexturePattern"
{
    Properties
    {
        [PerRendererData] _MainTex("Sprite Texture", 2D) = "white" {}
        _PatternTex("Pattern Texture", 2D) = "white" {}
        _Color("Tint", Color) = (1,1,1,1)
        [MaterialToggle] PixelSnap("Pixel snap", Float) = 0
    }

        SubShader
        {
            Tags
            {
                "Queue" = "Transparent"
                "IgnoreProjector" = "True"
                "RenderType" = "Transparent"
                "PreviewType" = "Plane"
                "CanUseSpriteAtlas" = "True"
            }

            Cull Off
            Lighting Off
            ZWrite Off
            Blend One OneMinusSrcAlpha

            Pass
            {
            CGPROGRAM
                #pragma vertex vert
                #pragma fragment frag
                #pragma multi_compile _ PIXELSNAP_ON
                #include "UnityCG.cginc"

                struct appdata_t
                {
                    float4 vertex   : POSITION;
                    float4 color    : COLOR;
                    float2 texcoord : TEXCOORD0;
                };

                struct v2f
                {
                    float4 vertex   : SV_POSITION;
                    fixed4 color : COLOR;
                    float2 texcoord  : TEXCOORD0;
                };

                fixed4 _Color;

                v2f vert(appdata_t IN)
                {
                    v2f OUT;
                    OUT.vertex = UnityObjectToClipPos(IN.vertex);
                    OUT.texcoord = IN.texcoord;
                    OUT.color = IN.color * _Color;
                    #ifdef PIXELSNAP_ON
                    OUT.vertex = UnityPixelSnap(OUT.vertex);
                    #endif

                    return OUT;
                }

                sampler2D _MainTex;
                sampler2D _PatternTex;
                sampler2D _AlphaTex;
                float _AlphaSplitEnabled;

                fixed4 SampleSpriteTexture(float2 uv)
                {
                    fixed4 color = tex2D(_MainTex, uv);
                    fixed4 patternColor = tex2D(_PatternTex, uv);

                    color.r = patternColor.r;
                    color.g = patternColor.g;
                    color.b = patternColor.b;

    #if UNITY_TEXTURE_ALPHASPLIT_ALLOWED
                    if (_AlphaSplitEnabled)
                        color.a = tex2D(_AlphaTex, uv).r;
    #endif

                    return color;
                }

                fixed4 frag(v2f IN) : SV_Target
                {
                    fixed4 c = SampleSpriteTexture(IN.texcoord) * IN.color;
                    c.rgb *= c.a;
                    return c;
                }
            ENDCG
            }
        }
}

End result


text:
Q: object stream to canvas My aim is to have a picture drawn on one device to be duplicated onto another, I have managed to send the coordinates of the path to a networking thread but am unable to handle these on the second device. how would i draw a path on the second device using coordinates from the stream in as real time as possible. Currently i have a threaded connection:
public class connecting implements Runnable{

    Socket sock;
    ObjectInputStream ois;

    @Override
    public void run() {

        try{
            sock = new Socket("10.42.34.46", 1337);
            InputStream is = sock.getInputStream();
            ois = new ObjectInputStream(new BufferedInputStream(is));

        }catch(IOException ex){
            ex.printStackTrace();
        }

        while(true){
            com.DrawTastic.Drawring serverDraw = null;

            serverDraw =   (com.DrawTastic.Drawring) ois.readObject();

            float mX =  serverDraw.getMx();
            float mY = serverDraw.getMy();

        }
    }

}

how would i get the float variables to continuously draw into this onDraw method in another thread
@Override
    public void onDraw(Canvas canvas) {

        connecting ncoords = new connecting();
        mPath.lineTo(mX, mY);

        canvas.drawPath(mPath, mPaint);
        canvas.drawColor(Color.WHITE);

        canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
        canvas.drawPath(mPath, mPaint);
    }
}

A: This is the most basic tutorial about client/server programming in Java. Let's start with naming

*

*client is the device interacting with real touch events

*server device is listening to events brought in by the client

The client implements onTouchEvent(MotionEvent) and writes x and y coordinates to its socket's OutputStream. Even if you want it as realtime as possible, you may need to store the events (x, y and timestamp) locally and transmit them at certain time intervals. Like every other blocking operation, this will run on a separate thread than the main application thread. This is a pseudo implementation
ClientActivity
  thread:
    while activity_is_running:
      sleep 100
      socket.write list_of_events

  onCreate(): start_background_thread
  onViewTouched(): thread.add_event

The server will have a ServerSocket listening for events. Every time an event is received it will draw. Note that in order to access the drawing thread from the background thread which the socket is listening on, you may use a Handler. A Handler is simply a way to run some code on a specific thread. You only need to declare a Handler instance variable for your ServerActivity and instantiate it in onCreate: this way the Handler will be bound to the application main thread, which is also the UI thread.
ServerActivity
  thread:
    while activity_is_running:
      handler.draw socket.get_event_from_input_stream

  onCreate():
    handler: new Handler()
    start_background_thread

The last part is how to remember already drawn things, both on the client and on the server side. This is because each call to onDraw will give you a clean bitmap, so you must either store each event in a list and draw from that list, or you can keep a cache of already drawn things (see this paste)


text:
Q: Error (0x80070002) when dll is not in the same path from registration First, the question is similar to Deploying .NET COM dll, getting error (0x80070002) but it didn't answer my problem.
I have build a dll (.net4) that I use with VBA in Excel / Word.
Principle:

*

*I register the dll with regasm.exe from a temporary folder (no problem)
RegAsm.exe `C:\temp\install\mydll.dll` /codebase

*When Excel / Word load, the document (excel or word) load the dll in references
Call ThisWorkbook.VBProject.References.AddFromFile("C:\working\anyfolder\mydll.tlb")

The folderpath can change depending the user (he create documents where he wants), and he can send documents to other users (if the dll is not in the folder, the document works in a degraded mode.
All of this works fine.
My problem: Recently I decided to improve the installation of this dll. When the installation finish I add a clean of the installation folder (C:\temp\install). But after doing that, when I try to use my dll in Excel / Word I have the error 0x80070002 File not found, even if the dll is in the folder of use (it's the same version of the dll I register)
What I know: I understood that he want the dll in the installation folder.
What I want:

*

*Is there a way, after registration with regasm, to delete dll from installation folder and only use the one in the folder of documents (and move the dll from folder to folder depending needs).

*Should I take a look at the GAC ? (I read the GAC wasn't needed if the dll is in the same folder as the document)

I read regasm documentation but found no information about it
If any other information is needed to anwser this, don't hesitate to ask.
Thanks a lot
update
To solve my problem, during the installation I add an installation to the GAC
(new Publish()).GacInstall("C:\temp\install\mydll.dll")

Publish needs a reference to System.EnterpriseServices

A: The COM DLL needs to be present in the folder it was registered from all the time. You can use it in any application, but the Windows system needs to be able to find the DLL.
Your specific problem sounds like you should look into Office addin development.

There are little exceptions like Microsoft Dynamics NAV 5 that also require the DLL be present in the same folder as the application's executable, but I guess that's just a flaw in design and shouldn't normally be the case (in Dynamics: If you use the COM class both from the classic client and an application server, the COM-DLL needs to be present both in the classic-folder and the application server folder).


text:
Q: Stop a program but not exit it? I'm trying to write a simple program for school with if else statements. I want script to stop after the first question, if it doesn't meet the criteria, without closing the program. Here is what I have so far:
age=int(input("How old are you? ")) #add a line to skip the other two inputs if not old enough
#registered = input("Are you a registered voter? yes/no ").lower()[:1]
#precinct   = input("Are you in your registered precinct? yes/no ").lower()[:1]

if age >= 18:
    print("You are old enough to vote. ") #Determines if old enough to vote.

else:
    print("You are not old enough to vote. ")

registered = input("Are you a registered voter? yes/no ").lower()[:1]

if registered == 'y':
    print("You are registered to vote. ")

else:
    print("Do you have documentation showing your permanent address? ")

precinct   = input("Are you in your registered precinct? yes/no ").lower()[:1]

if precinct == 'y':
    print("You are in your precinct and can vote. ")

else:
    print("You must be in your precinct to be able to vote. ")

if age >= 18 and registered == 'y' and precinct == 'y':
    print("Congratulations you may vote! ")

else:
    print("Sorry you may not vote. ")

A: You can add an empty input() to make the program pause without exiting. It requires pushing enter to advance the program.
age = int(input("How old are you? "))

if age >= 18:
    print("You are old enough to vote. ") #Determines if old enough to vote.
else:
    print("You are not old enough to vote. ")
    input()  # Program is paused until enter is pressed


text:
Q: Search in 1) Post, 2) Products (woocommerce) and 3) Custom post type or Taxonomy type on a single page I was hoping to make changes in the search.php file, where I want to display search results from Post, Products and Custom Taxonomy on the same page in three different section. Can anybody help me to achieve this?
Thanks,
S

A: I believe you cannot achieve it in the same loop. Instead, you should have three loops, each setting WP_Query criteria differently (setting WP_Query arguments to filter for Post, Products and Custom Taxonomy). Howevery, you want to save initial search parameters in variable(s), so you could apply them to those three different loops as other parts of arguments array. More details you can find in lower part of this page: https://wordpress.org/support/article/creating-a-search-page/


text:
Q: Why won't my loop stop; seemingly despite boolean expression So my program runs and draws a row of diamonds starting at the top right. It then moves down a  row and repeats. It SHOULD stop at 4 rows (due to canvas size) but it won't!
First for statement draws a diamond. Second for statement moves to the next diamond. Repeat 7 times.
The third for statement (and this is where I'm assuming the issue is..) moves down a row and repeats the first two.
all of which runs perfectly! Right up until it doesn't STOP!
It just keeps repeating indefinitely!
import Media.*;
import static java.lang.Math.*;

public class DiamondTiles2 {

private TurtleDisplayer display;
private Turtle            steve;

public DiamondTiles2 (){

display = new TurtleDisplayer();
steve = new Turtle();
display.placeTurtle(steve);

steve.setSpeed(15);
steve.forward(140);             // Moves Steve to the furthest right he needs to be
steve.left(PI/2);
steve.forward((float)1.5*(40*sqrt(3.0)));  // Moves Steve to the top (up 1.5 times the height of a diamond)
steve.left(PI/6);
steve.penDown();

for (int j=1 ; j<=7 ; j++){  //Diamond Drawing
  steve.forward(40);
  steve.left(2*PI/3);
  steve.forward(40);
  steve.left(PI/3);
  steve.forward(40);
  steve.left(2*PI/3);
  steve.forward(40);
  steve.left(PI/3);
  for (int i=1 ; i<=1 ; i++){ //Move to Next Diamond
    steve.penUp();
    steve.left(PI/3);
    steve.forward(40);
    steve.right(PI/3);
    steve.penDown();
    for (int k=1 ; (j>=7)&&(k<=4) ; j=j-7 , k++){ //Move to next row
      steve.penUp();
      steve.right(7*PI/6);
      steve.forward((float)40*(sqrt(3.0)));
      steve.left(PI/2);
      steve.forward(280);
      steve.left(2*PI/3);
      steve.penDown();
    }
  }
}
display.close();
};
public static void main ( String[] args ) { DiamondTiles2 d = new DiamondTiles2(); };
}

The way I'm seeing it: the last for loop SHOULD start as k==1 and then increase k by one each time. and it SHOULDN'T repeat past 4 because of
for (int k=1 ; (j>=7)&&**(k<=4)** ; j=j-7 , k++)

please help! :)
EDIT: Okay, so j is definitely the problem... to explain WHY I'm resetting J:
When I didn't reset 7 at seven it would draw the first row and then it would infinitely loop the step that Moves to a new row. So it would stop drawing and just move "Down, Right, Down, Right, Down, Right... etc.
Adding j=j-7 fixed that issue but started this new one..
Which i THOUGHT would be fixed because of k<=4 NOT being true... any reason it seems to be "ignoring" that Boolean?
EDIT2:
Fixed: Changed the last for statement to this IF statement:
 if ((j>=7)&&(x<=3)){ //Move to next row
      steve.penUp();
      steve.right(7*PI/6);
      steve.forward((float)40*(sqrt(3.0)));
      steve.left(PI/2);
      steve.forward(280);
      steve.left(2*PI/3);
      steve.penDown();
      j=j-7;
      x=x+1;

Thank you to everyone who helped me! Amazing response on this site!

A: Is it possible that the j=j-7 in the line you referenced isn't screwing up your intention in the first for loop on j?

A: You increment j in your outermost loop and you reset j in the innermost loop. That seems like asking for trouble. The innermost loop guarantees that j will never be 7 or more, and therefore the outermost loop will never terminate.
I would refactor so that you don't modify j other than in the outer for statement.
I would also recommend stepping through with a debugger to see what's going on.

A: It looks like the problem is j=j-7 - your loop will only stop if j is greater than or equal to 7 and k is less than 4. Because j is decremented by 7 on each iteration, your condition can never be met.

A: It doesn't repeat past 4... in that loop.  The issue is that the innermost loop is being run an infinite number of times, so it's looping from 1-4 and then from 1-4 and then from 1-4, etc.
Why is that loop being run an infinite number of times?
It seems that your terminators in the innermost & outermost loops are at odds.  Since you subtract 7 from j in the innermost loop every time it increases beyond 7, and the outermost loop will run so long as j is less than or equal to 7, j never is allowed to become large enough for the outermost loop to terminate.  This means that the innermost loop is run over and over and over again (because the outermost loop in endless), 1-4, 1-4, 1-4...


text:
Q: How to print names in output in python code? I have written python code where i want to print name. Can you please help me to correct this?
def unique_names(names1, names2):
    return None

names1 = ["Ava", "Emma", "Olivia"]
names2 = ["Olivia", "Sophia", "Emma"]
print(unique_names(names1, names2))

desired Output:
[Ava, Emma, Olivia, Sophia]

A: convert each list into sets then union them the result it will be set of unique values and convert the result to list again.
def unique_names(names1, names2):
   return list(set(names1).union(set(names2)))

names1 = ["Ava", "Emma", "Olivia"]
names2 = ["Olivia", "Sophia", "Emma"]
print(unique_names(names1, names2))

Result:
['Olivia', 'Emma', 'Sophia', 'Ava']

For more information about sets read the following documentation

A: I tried to solve it manually: (As I knew how to solve the problem but not familiar to python):
def unique_names(names1, names2):
    newArr = []
        # Iterate in the 1st list
    for m in names1:

        # Iterate in the 2nd list
        for n in names2:
            # if there is a match
            if m == n and len(names2) != 0 :
                names2.remove(n)

    newArr = names1 + names2
    print(newArr)

names1 = ["Ava", "Emma", "Olivia"]
names2 = ["Olivia", "Sophia", "Emma"]
unique_names(names1, names2)

A: I tried to solve by removing the duplicate in the list as i learned from W3Schools
basically i am adding the names1 and names2 and creating a new dictionary with no repeating names.
def unique_names(names1, names2):
    new_Arr = []
    new_Arr = list(dict.fromkeys(names1 + names2))
    return new_Arr

names1 = ["Ava", "Emma", "Olivia"]
names2 = ["Olivia", "Sophia", "Emma"]
print(unique_names(names1, names2))

and i got the respected out put

A: def unique_names(names1, names2):
    l = []
    for elem in names1:
        l.append(elem)
        for elem1 in names2:
            l.append(elem1)
        return sorted(l)
    names1 = ["Ava", "Emma", "Olivia"]
    names2 = ["Olivia", "Sophia", "Emma"]

print(unique_names(names1, names2))


text:
Q: v-if toggles for all items instead of the only clicked item I am listing from loop my items in html, I am trying to add an accordion effect to display info about the items, whenever I am toggling this, it changes all items to active instead of the one I clicked on.
I am facing the same issue, whenever I have a lot of input boxes and I want to edit one of them, it triggers the edit option for all the inputs instead of the only one.
 div(v-for="review of list" :key="review.id")
    .flex
      p {{ review.name }}
      box-icon.ml-auto(type="solid" name="down-arrow-circle" @click="toggle()" v-if="!toggled")
      box-icon.ml-auto(type="solid" name="up-arrow-circle" @click="toggle()" v-if="toggled")
    .info(v-if="toggled")
      p test

 const toggled = ref(false)
        function toggle() {
          toggled.value = !toggled.value
        }

        return { list, toggle, toggled }
    },

A: Use an array or object for toggled data.  If using an object, the key should be the item id, and use Vue.set to set it initially to maintain reactivity.
If using an array, use the item id to indicate a set value.
div(v-for="review of list" :key="review.id")
    .flex
      p {{ review.name }}
      box-icon.ml-auto(type="solid" name="down-arrow-circle" @click="toggle(review)" v-if="!toggled.includes(review.id)")
      box-icon.ml-auto(type="solid" name="up-arrow-circle" @click="toggle(review)" v-if="toggled.included(review.id)")
    .info(v-if="toggled.includes.review.id)")
      p test

const toggled = ref([])

        function toggle(review) {
          const idx = toggled.value.findIndex(r=>r === review.id)
          if (idx === -1) toggled.value.push(review.id)
          else toggled.value.splice(idx, 1)
        }

        return { list, toggle, toggled }
    },


text:
Q: Shutdown a TThreadPoolServer in python I want to know how to shutdown a TThreadPoolServer properly.
Right now I use the following python code:
try:
    # Other settings
    transport = TSocket.TServerSocket(port=server_port)
    server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory)
    print("Starting server...")
    server.serve()
except (SystemExit, KeyboardInterrupt):
    transport.close()
    print("Done.!")
    exit(0)

After the server is started using terminal, I press control-c, "Done.!" is printed on the screen, but it doesn't exit and go back to command line. Can anybody help with this?
If I use TSimpleServer, it will terminated and go back to command line.

A: Don't you need to .stop() the server?


text:
Q: Can not get values from a form in javascript I'm trying to get the values of the different inputs of this form:
<form class="form-horizontal" role="form" id="form_newCours">

            Matiere:

                <input type="text" class="form-control" id="discipline" placeholder="Matiere">

            Date:

                        <input type="text" class="form-control" id="datetimepicker"/>

                <input type="checkbox" id="creneau_regulier"> Ce creneau regulier

              <button type="submit" class="btn btn-default" id="btn-newCours">Ajouter</button>

 </form>

And I have this JS code where I try to get the values of the inputs:
$('#btn-newCours').on('click', function(e) {

    // this will stop the form from submitting normally and let you handle it yourself with the following code:
    e.preventDefault();

    // YK: Bellow is my code
    var jsonString = JSON.stringify($('#form_newCours').serializeObject());
    console.log($('#form_newCours').serialize());
    $.ajax({
      type: "POST",
      data: jsonString,
      url: "/cours/",
      contentType: "application/json"
    });
  });

The function is called, but the variable jsonString is empty. I'm not so familiar with JS, but can the additionnal div between the form and input cause problems ?
Edit:
P.S. I'm using a plugin for serializeObject().

A: You should add name attribute to your inputs.

A: Add name attribute to your inputs
<form class="form-horizontal" role="form" id="form_newCours">

            Matiere:

                <input type="text" class="form-control" id="discipline" placeholder="Matiere" name="discipline">

            Date:

                        <input type="text" class="form-control" id="datetimepicker" name="datetimepicker"/>

                <input type="checkbox" id="creneau_regulier" name="creneau_regulier"> Ce creneau regulier

              <button type="submit" class="btn btn-default" id="btn-newCours">Ajouter</button>

 </form>

Note : If you are using jquery-serialize-object Plugin, you can replace
var jsonString = JSON.stringify($('#form_newCours').serializeObject());

with
var jsonString = $('#form_newCours').serializeJSON();


text:
Q: Cassandra claims "A node with address X already exists" when restarting that same node So I'm running cassandra in kubernetes. Every once in a while, one of them will fall over or run out of disk or.. look. Things happen to people.
This is the status I found in the ring this morning.
root@cassandra-cluster-arm-az-a-3:/# nodetool status
Datacenter: eu-central-1-arm
============================
Status=Up/Down
|/ State=Normal/Leaving/Joining/Moving
--  Address          Load       Tokens       Owns (effective)  Host ID                               Rack
DN  192.168.132.73   1.08 TiB   256          28.3%             b583b2c7-c5a4-4f9e-90a9-eddc4f56b8b2  eu-central-1-arm-az-a
UN  192.168.206.106  1.11 TiB   256          29.7%             2f653ab5-b97c-4756-84b5-841eedae9419  eu-central-1-arm-az-b
UN  192.168.179.26   1.15 TiB   256          31.2%             f79153d2-01f9-4687-a4b4-989f0696e68b  eu-central-1-arm-az-a
DN  192.168.182.250  1.1 TiB    256          29.1%             e23ca25b-2a21-467a-b518-16375439b834  eu-central-1-arm-az-a
UN  192.168.179.237  1.09 TiB   256          29.0%             6eb40e00-d829-491d-a1a8-c3668b3fa6d7  eu-central-1-arm-az-a
UN  192.168.228.174  1.17 TiB   256          32.6%             cbdd095d-502f-4720-a937-8314200dd8f1  eu-central-1-arm-az-b
UN  192.168.247.177  1.24 TiB   256          33.0%             0d0fc344-aaf9-4cb7-9298-2025e89c672b  eu-central-1-arm-az-b
UN  192.168.234.100  1.12 TiB   256          30.0%             3971e56c-cde3-4507-bc40-2dbe5c9ff549  eu-central-1-arm-az-b
UN  192.168.147.148  1.1 TiB    256          29.2%             abfe9961-c737-4d8f-935e-1043111cd170  eu-central-1-arm-az-a
UN  192.168.193.117  1.07 TiB   256          27.9%             85b5d818-fc9c-48cb-ac82-2e8f2d82c9b3  eu-central-1-arm-az-b

I log onto 192.168.182.250 and run nodetool status on it. Yeah. It's stuck and can't contact any of the other nodes. I kill the process and kubernetes restarts the node. Upon startup, I end up in a crashloop of these:
ERROR [main] 2022-05-17 07:01:56,176 CassandraDaemon.java:708 - Exception encountered during startup
java.lang.RuntimeException: A node with address /192.168.182.250 already exists, cancelling join. Use cassandra.replace_address if you want to replace this node.
at org.apache.cassandra.service.StorageService.checkForEndpointCollision(StorageService.java:558) ~[apache-cassandra-3.11.2.jar:3.11.2]
at org.apache.cassandra.service.StorageService.prepareToJoin(StorageService.java:807) ~[apache-cassandra-3.11.2.jar:3.11.2]
at org.apache.cassandra.service.StorageService.initServer(StorageService.java:667) ~[apache-cassandra-3.11.2.jar:3.11.2]
at org.apache.cassandra.service.StorageService.initServer(StorageService.java:613) ~[apache-cassandra-3.11.2.jar:3.11.2]
at org.apache.cassandra.service.CassandraDaemon.setup(CassandraDaemon.java:379) [apache-cassandra-3.11.2.jar:3.11.2]
at org.apache.cassandra.service.CassandraDaemon.activate(CassandraDaemon.java:602) [apache-cassandra-3.11.2.jar:3.11.2]
at org.apache.cassandra.service.CassandraDaemon.main(CassandraDaemon.java:691) [apache-cassandra-3.11.2.jar:3.11.2]
INFO [StorageServiceShutdownHook] 2022-05-17 07:01:56,180 HintsService.java:220 - Paused hints dispatch
WARN [StorageServiceShutdownHook] 2022-05-17 07:01:56,183 Gossiper.java:1548 - No local state, state is in silent shutdown, or node hasn't joined, not announcing shutdown
INFO [StorageServiceShutdownHook] 2022-05-17 07:01:56,183 MessagingService.java:984 - Waiting for messaging service to quiesce
INFO [ACCEPT-/192.168.182.250] 2022-05-17 07:01:56,185 MessagingService.java:1338 - MessagingService has terminated the accept() thread
INFO [StorageServiceShutdownHook] 2022-05-17 07:01:56,574 HintsService.java:220 - Paused hints dispatch
192.168.182.250
Starting Cassandra on 192.168.182.250

The node, having IP 192.168.182.250, cannot join because "A node with address /192.168.182.250 already exists".
.. Why though?
Note. These Cassandras are running on an AWS, ARM nodes, with persistent volumes attached.
Full(-ish) startup log https://gist.github.com/zoomix/2e95b9350da97a2e1f5bc1913045826a

A: There's a good chance that in your Kubernetes setup that you're adding a pod with the same IP address but not reusing the persistent volume so there's no data/ directories on it with data from the pod which failed/ran out of disk.
When this happens, the cluster thinks you're adding a new node with the same IP and it won't allow you because another node in the cluster with the same IP already exists.
Our recommendation is to use persistent volumes (PV) so that when replacing a failed pod, the same PV gets mounted to the new pod and thus the node's local metadata (data in the node's system.local table) is preserved. If Cassandra is able to check the contents of the system.local table on startup, then it knows that it is the same node re-joining the cluster.
In case you weren't already aware, we've created K8ssandra.io -- our opinionated deployment of Apache Cassandra on Kubernetes (fully open-source and free) using the cass-operator and with all the admin tools already bundled in:

*

*Reaper for automated repairs

*Medusa for backups and restores

*Metrics Collector for monitoring with Prometheus + Grafana

*Traefik templates for k8s cluster ingress

*Stargate.io - a data gateway for connecting to Cassandra using REST API, GraphQL API, JSON/Doc API and gRPC API

Cheers!


text:
Q: Function to add 3 rows together in OpenOffice Calc then drag function down for 195,000 rows I have a spreadsheet with 195,000 rows, There are 3 columns with different numbers in in the 4th column (D1) I enter =A1+B1+C1 and it comes up with the answer, But I can only drag down the AutoSum feature slowly.
Is there a way to automate it so I can have the Autosum for all columns in D so it'd be D1 : D195000?

A: Here is a simple trick you can do: Write your type on the first cell (D1) and anything to the last one (D198K - use the Navigator tool (F5) to go there fast). Then, copy the cell from the first cell, and press Ctrl + Shift + End (selection till the last cell that contains data) and then make a Paste.
This should paste the type to the selected shells, applying the type in analogy to each cell - unless you have used $ in the type for a cell row and/or column, in order to preserve a cell.
You could simply follow this logic in order to create your own function in OpenOffice Calc.


text:
Q: having issues converting mongodb data to json in dart server side I am trying to get a list of friends from the database and send it to the client using shelf_router. I am able to get the data but it is not parsed correctly, so the client does not recognize it as a json object. When I print friendsList to console it is formatted like this:
[{username: dave@one.com, sent: 2021-05-17 22:16:37.752Z}, {username: josh@one.com, sent: 2021-05-17 22:18:39.183Z}, {username: adam@one.com, sent: 2021-05-17 22:29:18.051Z}, {username: mike@one.com, sent: 2021-05-17 22:32:35.713Z}, {username: rob@one.com, sent: 2021-05-17 22:34:29.328Z}, {username: larry@one.com, sent: 2021-05-17 23:20:32.737Z}]
Here is the code I am currently using:
 router.get('/', (Request req) async {
  final authDetails = req.context['authDetails'] as JWT;
  final user = await store.findOne(
      where.eq('_id', ObjectId.fromHexString(authDetails.subject)));

  var friendsList = user['friends'];

  print(friendsList);

  return Response.ok(json.encode(friendsList.toString(), headers: {
    'Content-Type': 'application/json',
  });
});

Right now, they are showing up like map objects but I gotta have them all in one json object so the client side can understand the data. Thanks in advance


text:
Q: Using multer in memory buffer with GraphicsMagick I'm trying to resize an image uploaded in memory, using multer over express to get the file. While I can access req.files.picture.buffer and it shows some content, when I pass the buffer to GM I receive a ENOENT. The code is as follows:
var buffer = req.files.picture.buffer

gm(buffer)
  .options({imageMagick: true})
  .resize(300)
  .toBuffer('PNG', function (err, buffer) {
    if (err) return handle(err);
      console.log('done!');
  });

return res.sendStatus(200);

Either using toBuffer or write as the output I get the same ENOENT. Am I missing something?

A: According to the gm Buffer example, you also need to supply a filename for the data. Example: gm(buffer, 'foo.jpg')

A: There was some problem with my Linux setup and ImageMagick was not available to Node.js. After re-configuring the machine the code works without changes.


text:
Q: jqGrid colModel dynamic Searchoptions Is it possible to have a dynamic (not hard coded) search filter values for the jqGrid column?
So in the example such as:
 $('#my-grid').jqGrid({
            datatype: 'json',
            loadonce: true,
            jsonReader: common.jqgrid.jsonReader('Workorder'),
            mtype: 'POST',
            colNames: ['Project', 'PO Number', 'Type', 'Folder'],
            colModel: [
                { name: 'Project', index: 'Project', width: 80, sortable: false, search:false},
                { name: 'PONumber', index: 'PONumber', width: 60, sortable: false, search: true },
                { name: 'Type', index: 'Type', width: 60, sortable: false, search: true},
                { name: 'Folder', index: 'Folder', width: 60, sortable: false, search: false },
                           ],
            scroll: true,
                   });

I would like the type to have a drop down filter with values that are array of distinct values from the data subset coming back.
How would I achieve this?
Edit
Is the jqGrid data accessible directly? I am looking for something like
Data.Cols[2].Distinct that will give me the distinct array of values from column 3(in this case). Is this possible?
Edit 2
This is the code:
onLoadComplete: function (data) {
        var $this = $('#gridReport');

        if ($this.jqGrid("getGridParam", "datatype") === "json") {

            // first loading from the server
            // one can construct now DISTINCT for 'Type' column and
            // set searchoptions.value
            $this.jqGrid("setColProp", "Type", {
                stype: "select",
                searchoptions: {
                    value: buildSearchSelect(getUniqueNames("Type")),
                    sopt: ["eq", "ne"]

                }
            });
        }
    },

A: I'm not sure that I understand you correctly. Probably you want to use advanced searching dialog with dropdown (stype: 'select') with different values of the 3-d column of the grid? I would recommend you to read the answer which shows the main idea how one can set searchoptions.value dynamically. You use loadonce: true. So you can call setColProp inside of loadComplete at the first loading of data from the server. You can include additional testing for the value of datatype. At the loading from the server the value is "json". Later it will be changed to "local". So the code could be about the following:
loadComplete: function () {
    var $this = $(this);

    if ($this.jqGrid("getGridParam", "datatype") === "json") {
        // first loading from the server
        // one can construct now DISTINCT for 'Type' column and
        // set searchoptions.value
        $this.jqGrid("setColProp", "Type", {
            stype: "select",
            searchoptions: {
                value: buildSearchSelect(getUniqueNames("Type")),
                sopt: ["eq", "ne"]
            }
        });
    }
}

A: This is how I ended up doing it, I ended up using jquery to populate the drop down directly, as jqgrid filters were not available at any point (if they are, I would love to see a documented example):
 onLoadComplete: function (data) {

        if ($('#mygrid').jqGrid("getGridParam", "datatype") === "json") {

            //get the distinct types from the data set coming back
            var length = data.length;
            var types = [];

            for (var i = 0; i < length; i++) {
                types.push(data[i]['Type']);
            }

            var uniqueTypes = getUnique(types);

            $('#gridId select[name="Type"]').empty().html('<option value="">All</option>');

            for (var i = 0; i < uniqueTypes.length; i++) {
                  $('#gridId select[name="Type"]').append($('<option value="' + uniqueTypes[i] + '">' + uniqueTypes[i] + '</option>'));
            }
        }


text:
Q: htaccess multiple conditions and rewrites I am trying to process the following:

*

*All urls go to www.mydomain.com/index.php

*GET paramaters are still processed

*Removal of .php
So if I have: www.mydomain.com/test.php?a=1
I want to check here for the existence of file app/controllers/test.php and pass the string app/controllers/text.php to ./index.php and remove .php from test.php
or
If I have: www.mydomain.com/dir1/test.php?a=1
I want to check here for the existence of file app/dir1/controllers/test.php
and pass the string app/dir1/controllers/text.php to ./index.php and remove .php from test.php
or
If I have: www.mydomain.com/dir1/dir2/dir3/test.php?a=1
I want to check here for the existence of file app/dir1/dir2/dir3/controllers/test.php and pass the string app/dir1/dir2/dir3/controllers/text.php to ./index.php and remove .php from test.php
As you can see sub dir needs to be dynamic so DIR and FILE check is necessary.
So.. If it php file test.php exists at any directory level

*

*Remove .php from browser url and send param to www.mydomain.com/index.php, so that I can pickup the path to the file but the browser never sees file extension

If it doesn't exist (this part I already have working)
I want to proceed and run what I already have in my htaccess.
Which will assume index.php at directory path and redirect to a 404 if not found
I would expect it to look something like this:
Options +FollowSymlinks
RewriteEngine On

#Rewrite Conditions to detect actual file at path adding app/controllers
#to front of url string as this shouldn't be viewable
# -- CODE I AM STUCK WORKING OUT --
# [L] to prevent proceeding with htaccess if condition met and rewrite done

# Existing code below to run if above not found
#RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
#RewriteRule ^(.*)$ ./index.php?p=$1 [L,NC,QSA]

Thanks
D

A: To get the .php stripped from the URL itself, you need a redirect:
RewriteRule (.*)\.php$ $1 [QSA,R=301]

Now to apply your actual logic, I think this should work:
RewriteRule (.*)/([^/]+)$ index.php?file=app/$1/controllers/$2.php [QSA]

You will then have to have PHP check if( file_exists($_GET['file'])), because your condition is too complex to check in .htaccess (inserting that controllers/ into the path to check)