text:
Q: Filter common dates between two arrays in Javascript So i have this project i am working on where i have an array of Javascript objects, and each object contains different entrys:
var array_of_objects = [{
    "timeline": [-765, ..., -18342],
    "Date": [2022-01-18 00:00:00:0000Z, ..., 2022-06-03 00:00:00:0000Z],
    ....
},
....
{
    "timeline": [-34, ..., 421],
    "Date": [2022-02-14 00:00:00:0000Z, ..., 2022-05-27 00:00:00:0000Z],
    ....
}]

And the dates go in a range from a starting day to an end day, and represent the dates corresponding to the values in timeline. Date and timeline array have the same length.
I have many of these objects and wish to compare them two at a time with some algorithm, but my problem is that the starting and end dates are different for each object.
My goal is to slice them so that they represent the overlapping date range of the two objects, so that the timeline array is sliced by the common dates between the two objects.
Meaning the output should be two arrays of the same length, containing the values of timeline sliced by the overlapping dates between the two objects.
I have absolutely no idea, i started with an extremely clunky if statement, but that just started looking ugly and only sometimes gave the right result. Does anybody have any ideas?


text:
Q: Why can't Internet Explorer run this simple jQuery? I'm running a really simple jQuery script to grab all emails selected by checkboxes in a table. The table looks like this:

                <input type="checkbox" value="MD5HASH" />

                First Name

                Email Address

My jQuery looks like this:
$("#submitButton").click(function() {
    var output = [];
    $("table tbody tr:has(input:checkbox:checked)").each(function() {
        var email = $('td.email', $(this)).text();
        if (validate(email) && output.indexOf(email) == -1)
            output.push(email);
    });

    $("#emails").val(output.join(", "));
});

function validate(email) {
    return /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/.test(email);
}

This fails miserably in IE, but works everywhere else.

*

*The table tbody tr:has(input:checkbox:checked) selector matches nothing.

*The call to validate throws a Object expected error.

WHY!? Isn't jQuery designed to be cross-browser and portable?

A: Internet Explorer (< 9) doesn't have Array.prototype.indexOf.  Try using jQuery's $.inArray instead (it's cross browser and will actually use Array.prototype.indexOf if it exists :-P).
if (validate(email) && $.inArray(email,output) == -1)
  output.push(email);

A: give the input a class and target it directly...

                <input class="emailchecked" type="checkbox" value="MD5HASH" />

                First Name

                Email Address

Then target the checked ones in your js like this:
$("#submitButton").click(function() {
    var output = [];
    $(".emailchecked ([checked='checked'])").each(function() {
        var email = $('td.email', $(this)).text();
        if (validate(email) && output.indexOf(email) == -1)
            output.push(email);
    });

    $("#emails").val(output.join(", "));
});

function validate(email) {
    return /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/.test(email);
}

A:

<input type="checkbox" value=""/>	one@gmail.com

<input type="checkbox" value=""/>	two@gmail.com

<input type="checkbox" value=""/>	three@gmail.com

<input type="checkbox" value=""/>	four@gmail.com

    <input id="btnSubmit" type="button" value="Submit"/>

Since you have three columns instead of two, just walk the DOM for that row.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Converting mp3 to caf file for iPhone I am experimenting with the sampling rate of the mp3 file to convert it into caf format.
afconvert -f caff -d LEI16@44100 ./fricatives_play_all.mp3 ./test.caf
 afconvert -f caff -d LEI16@22100 ./fricatives_play_all.mp3 ./test.caf
 afconvert -f caff -d LEI16@12000 ./fricatives_play_all.mp3 ./test.caf
 afconvert -f caff -d LEI16@20100 ./fricatives_play_all.mp3 ./test.caf
 afconvert -f caff -d LEI16@15100 ./fricatives_play_all.mp3 ./test.caf
 afconvert -f caff -d LEI16@14100 ./fricatives_play_all.mp3 ./test.caf
 afconvert -f caff -d LEI16@13100 ./fricatives_play_all.mp3 ./test.caf
 afconvert -f caff -d LEI16@44100 -c 1 ./fricatives_play_all.mp3 ./test.caf
 afconvert -f caff -d LEI16@13100 -c 1 ./fricatives_play_all.mp3 ./test.caf
 afconvert -f caff -d LEI16@22100 -c 1 ./test ./test2.caf
I have used different sampling rates as above for converting mp3 files
to caf files. For instance, for a 38.5 MB file :
Sampling Rate       Size
15,100                   72.6 MB
14,100                   67.8 MB
13,100                   63 MB
As you can see the file size reduces with the lower sampling rate but
the quality gradually decreases. If you could provide more insight
into this problem, I would really appreciate it.

A: If it's a stereo file, you could convert it to mono. You can also use the IMA-4:1 compression, which reduces the file size to 25%, but it does reduce the quality somewhat.


text:
Q: How to wire up an HttpTrigger to the Designer I'm new to Azure Functions.
I'm trying to write an Http Trigger that will not only "fail" bad json (that doesn't match my schema, I want to provide feedback to the caller with the invalid messages about the json they submitted.
Ok, so first I brought up VS2017.

Then I coded it up.  I can use PostMan to test it, it works fine during PostMan testing.
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

////using MyExceptionLibrary;

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;

using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Schema;

namespace MyNamespace.AzureFunctionsOne
{
    public static class MyFirstHttpTrigger
    {
        [FunctionName("MyFirstHttpTriggerFunctionName")]
        public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function MyFirstHttpTriggerFunctionName about to process a request.");

            try
            {

                string jsonSchemaText = @"{
                  'description': 'A person',
                  'type': 'object',
                  'properties':
                  {
                    'name': {'type':'string'},
                    'hobbies': {
                      'type': 'array',
                      'items': {'type':'string'}
                    }
                  }
                }";

                JSchema schema = JSchema.Parse(jsonSchemaText);

                var content = req.Content;
                string jsonContent = content.ReadAsStringAsync().Result;

                JObject jobj = JObject.Parse(jsonContent);

                IList<string> messages;
                bool valid = jobj.IsValid(schema, out messages);
                if (!valid)
                {
                    string errorMsg = string.Join(",", messages);
                    throw new ArgumentOutOfRangeException(string.Format("Bad Json. ({0})", errorMsg));
                }
            }
            catch (Exception ex)
            {
                string errorMsg = ex.Message; //// ExceptionHelper.GenerateFullFlatMessage(ex);
                log.Error(errorMsg);
                return req.CreateResponse(HttpStatusCode.BadRequest, errorMsg);
            }

            log.Info("C# HTTP trigger function MyFirstHttpTriggerFunctionName processed a request.");
            return req.CreateResponse(HttpStatusCode.OK);
        }
    }
}

I then "published" this azure function to the cloud.
My issue is now........how do I wire this into the Logic App Designer to be the trigger?
In the below, I'm able to add the generic-request-trigger.

In the below, I've also looked for ~my~ azure http trigger that I published, and no luck.

So I can't figure out how to get my custom Http-Trigger to be available in the Logic App designer so it can be the entry-point-trigger.
Am I missing some basic concept?
My end game is:
I want a third-party to POST some json to my azure-logic-app as an http-request. That should be the trigger.  But I only want the trigger to keep running if they submit valid json.  (This I know can be done via the generic request trigger).  My caveat (and thus my custom http-trigger) is that I want the third-party to get schema violation messages so they know what they did wrong.

A: If I understand this correctly, you have a workflow you want 3rd party to invoke via HTTP request, and when the request body isn't well formatted, you want to return a friendly error.
So you coded up an Azure Function that expose itself as a request endpoint, and does the validation.
If that's the case, you will just need to have the Azure Function to invoke Logic App after success validation, and pass the original payload to Logic App. So you can create the Logic App with a request trigger, save and get the Url, and have Function call that Url.


text: Q: How would I include a third party image gallery on my Cornerstone-based theme? I'm requested to add a new image gallery for our products page. I've found a few that I like, and I got really close to adding one using the advanced non-npm method. I tried Galleria, UniteGallery, and PhotoSwipe. Is there any way someone can walk me through installing it on Cornerstone (v1.5.3)? Cornerstone uses WebPack 1.14.


text:
Q: size of dynamically allocated array Is it true that a pointer assigned to the starting address of a dynamically allocated array does not have the information of the size of the array? So we have to use another variable to store its size for later processing the array through the pointer.
But when we free the dynamically allocated array, we don't specify the size, instead we just "free ptr" or "delete [] ptr". How could free or delete know the size of the array? Can we use the same scheme to avoid storing the size of the array in another variable?
Thanks!

A: The funny thing is that historically it was delete [20] arr; just as it is arr = new int[20]. However practice proved that the information on size can be painlessly stored by the allocator, and since most people using it then stored it anyway, it was added to the standard.
What is more funny, and little known, is the fact that this "extended delete syntax" is in fact supported by a few C++ compilers (despite being incorrect even in face of the C++98 standard), although none require it.
int* arr = new int[20];
delete [20] arr;

The sad part about this all however is, that there's no standard-conforming way to retrieve that passed size for your own use :-/

A: It is true that the array does not contain the size of the array, you have to store that information for later. When deleting an array through delete or free it is the pointer to the allocated memory you pass. The memory manager used (either by the system or your own custom from overriding new and delete) knows the memory area that is freed, and keeps track of it. Hope it makes sense.

A: Yes, it's true. This is part of why you should rarely try to deal with this directly, and use a standard container instead. About the only time it makes sense to deal with it is if you decide to implement a container yourself (in which case you'll normally track the size information in your container's implementation).

A: Yes, this is true.
delete knows the size of the memory chunk because new adds extra information to the chunk (usually before the area returned to the user), containing its size, along with other information. Note that this is all very much implementation specific and shouldn't be used by your code.
So to answer your last question: No - we can't use it - it's an implementation detail that's highly platform and compiler dependent.

For example, in the sample memory allocator demonstrated in K&R2, this is the "header" placed before each allocated chunk:
typedef long Align; /* for alignment to long boundary */

union header { /* block header */
  struct {
    union header *ptr; /* next block if on free list */
    unsigned size; /* size of this block */
  } s;

  Align x; /* force alignment of blocks */
};

typedef union header Header;

size is the size of the allocated block (that's then used by free, or delete).


text:
Q: excel - .Copy() twice I have a workbook that consists of 6 worksheets. I want to save sheet 2 & 3
    With Excel
            .SheetsInNewWorkbook = 6
            .Workbooks.Add()
            ....

            .Worksheets(2).Copy()
            filename = "1.txt"
            .ActiveWorkbook.SaveAs(filename, -4158)
            .Worksheets(3).Copy()
            filename = "2.txt"
            .ActiveWorkbook.SaveAs(filename, -4158)
    End With

Upon copying the 2nd time, my application crash and return this error: Invalid index. (Exception from HRESULT: 0x8002000B (DISP_E_BADINDEX)). I noticed the error was due to trying to "Copy" the 2nd time, so how should I copy twice in this case?

A: Try this:
With Excel
    Dim sourceWB As Workbook = .Workbooks.Add()
    '~~> Rest of your code here
    .
    .
    .
    sourceWB.Worksheets(2).Copy
    .ActiveWorkbook.SaveAs("C:\blah\test1.txt", -4158)
    sourceWB.Worksheets(3).Copy
    .ActiveWorkbook.SaveAs("C:\blah\test2.txt", -4158)
End With

A: Not sure why, but .Worksheets(2).Copy() will open another workbook "Book2" in this case, therefore need to close it.
.DisplayAlerts = False
.ActiveWorkbook().Close()

Upon closing the copied worksheet then copy again.
.Worksheets(3).Copy()
filename = "2.txt"
.ActiveWorkbook.SaveAs(filename, -4158)

The full code will be
.Worksheets(2).Copy()
filename = "1.txt"
.ActiveWorkbook.SaveAs(filename, -4158)
.DisplayAlerts = False
.ActiveWorkbook().Close()
.Worksheets(3).Copy()
filename = "2.txt"
.ActiveWorkbook.SaveAs(filename, -4158)


text:
Q: Postgres Where And being ignored? I'm trying to chain multiple WHERE AND statements in Postgres, however it seems they're being ignored.
My query is
SELECT id, title, tags, selected_preview_image, items, uid
            FROM  fb_designs r, json_array_elements(r.items#>'{listings}') obj
            WHERE  obj->>'active' = 'false' OR obj->>'active' = 'true'
            AND title LIKE '%hoot%'
            AND tags @> '{"123"}'
            GROUP BY id

However as you can see in the below output, its ignored the title and the tags query

Can anyone help?

A: Surround the ORed condition with parentheses
WHERE
    (obj->>'active' = 'false' OR obj->>'active' = 'true')
    AND title LIKE '%hoot%'
    AND tags @> '{"123"}'

Or better yet, use IN:
WHERE
    obj->>'active' IN ('false', 'true')
    AND title LIKE '%hoot%'
    AND tags @> '{"123"}'

Rationale: OR has lower prescendence than AND.
So this:
obj->>'active' = 'false'
OR obj->>'active' = 'true'
AND title LIKE '%hoot%'
AND tags @> '{"123"}'

Is actually equivalent to:
obj->>'active' = 'false'
OR (
    obj->>'active' = 'true'
    AND title LIKE '%hoot%'
    AND tags @> '{"123"}'
)

As you can see, with the above expression, any record that has obj->>'active' = 'false' will pass through.


text:
Q: adding horizontal scroll to posts automatically where can I add div style="overflow-x:auto;" code to turn posts automatically horizontally scrollable? when it sees **table **? Thank you in advance.
i dont know so I am asking


text:
Q: Hibernate throws queries even on cache hits I'm not sure if it's a real problem or it's only a matter of configuration but I can see on my log console how hibernate hits (or at least throws the select query) even on cache hits.
I've checked the cache is properly working on Ehcache monitor and it registers 100% of hits for a certain request. But I always see the queries in the log.
All entities are anotated as shown:
@Entity
@Cacheable
@Cache(usage = READ_WRITE)
@Table(name = "city")
//@NamedQuery(name = "city.findById", query = "from City where ID = :id")
public class City extends Audit implements Serializable {

My ehcache.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
    dynamicConfig="true" monitoring="autodetect">

    <!-- Location of persistent caches on disk -->
    <diskStore path="java.io.tmpdir/MxlServiceLayer" />

    <cacheManagerPeerListenerFactory
        class="org.terracotta.ehcachedx.monitor.probe.ProbePeerListenerFactory"
        properties="monitorAddress=localhost, monitorPort=9889, memoryMeasurement=true" />
    <defaultCache eternal="false" maxElementsInMemory="1000"
        overflowToDisk="false" diskPersistent="false" timeToIdleSeconds="0"
        timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU" statistics="true" />
    <cache name="authToken" eternal="false" maxElementsInMemory="100"
        overflowToDisk="false" diskPersistent="true" timeToIdleSeconds="0"
        timeToLiveSeconds="31536000" memoryStoreEvictionPolicy="LRU"
        statistics="true" />
</ehcache>

And what I see in my over and over again...

Hibernate: select city0_.ID as ID2_, city0_.CREATED as CREATED2_,
  city0_.CREATOR as CREATOR2_, city0_.MODIFIED as MODIFIED2_,
  city0_.MODIFIER as MODIFIER2_, city0_.NAME as NAME2_, city0_.state_fk
  as state7_2_ from city city0_ where State_fk=?

Is hibernate really hitting the DB? Can anyone explain this to me, please?
I'm using:

JPA 2.0 in Spring Data JPA 1.2.0
Ehcache 2.6.0
Spring 3.2.1

A: What you enabled is the second-level cache. This cache caches the state of the entities, and indexes them by their ID. It's like a Map<ID, EntityState>. This cache is only used if you get the entity by ID:

*

*by calling session.get()

*by calling session.load()

*by navigating through a XxxToOne association targeting the entity

Your query doesn't fall into this category: it looks for your entity by one of its fields, and not by its ID.
For the rest, Hibernate can't execute arbitrary SQL queries against the cache, and even if it could, the cache only contains a subset of the table, so it has to query the database.
You can however, cache the result of queries as well. You'll need to enable the query cache to do so, and to mark your query as cacheable. You can also cache an association (which seems like the reason for this query: it's looking for all the cities of a given state). You'll have to annotate the association with @Cache.
Read the documentation.


text:
Q: Use Swift 2.2 in Xcode 8? Is it possible to use Swift 2.2 in Xcode 8?
From Xcode 8 release notes:

"Xcode 8 supports switching toolchains, such as those from swift.org,
  without relaunching Xcode. (23135507)"

I have been trying to find swift 2.2 toolchain on swift.org website but couldn't. Have any one success in configuring Xcode 8 to work with swift 2.2

A: It is not possible to use Swift2.2 in XCode8, and it is also not possible to use Swift2.3 or Swift3 in XCode3.
The best solution i found is to create a single project file that will compile for both iOS 9 (Xcode 7) and iOS 10 (Xcode 8), and that will support Swift2.2 and Swift2.3 (very similar).

A: If you want to continue to use Swift 2 in Xcode 8, then use Swift 2.3 by enabling the Use Legacy Swift Language Version build setting (SWIFT_VERSION = 2.3).

A: Using Swift 2.3 in Xcode 8 by That Thing in Swift provides a good introduction to using Swift 2.3 in Xcode 8.
The following is quoted from the article:

There's a single build setting that will let you continue building
  your Swift projects with a Swift version that's mostly similar in
  syntax to your existing projects from Xcode 7: Use Legacy Swift
  Language Version
Just drop into your project's build settings and search for legacy
  swift to find the correct build setting, then switch the setting to
  YES to opt-in to Swift 2.3 rather than Swift 3 in Xcode 8.

A: As one of possible solutions to this problem I could suggest to install two versions of Xcode (7.3.1 and 8, for example) side by side.
To accomplish this you should:

*

*Download suitable dmg file from Downloads for Apple Developers. Use search to find Xcode.

*Double click this file to see familiar "Drag to install Xcode in your Applications folder" window. But drag this somewhere else for a moment. Desktop would be good. Rename it to Xcode \number of version\ (like Xcode 7.3.1) and then drag it to Applications folder.

That's it.

A: It is not possible to use Swift2.2 in XCode8 by setting Use Legacy Swift Language Version to Yes in Build Settings.


text:
Q: Create virtual port from another mac I have 2 Macintoshes.
In the first Macintosh I have put in the USB port a device (like a iPod, Arduino, other) and I would like to connect from the second Macintosh to the device on the first.
The two Macintosh are on a LAN.
How can I do that?

A: You will not be able to do this with default osx resources, but there is a lot of programs that will allow you to share usb over the network
for example this one


text:
Q: Simplifying a characteristic equation when one eigenvalue is known This is either trivial, or difficult; if the former I should be embarrassed to ask it.  Anyway... I have a 4x4 matrix of non-zero integer values, for which the determinant is zero.  Given that therefore (at least) one eigenvalue is zero, is there a way of producing a third degree polynomial for the other eigenvalues without having to go through the rigmarole of computing $\det(A-\lambda I)$ in full?
So far the best thing I can do is this: since $\det(A)=0$ there is a linear combination $\sum a_iR_i=0$ where $R_i$ are the rows and $a_i$ are not all zero.  Applying that to the rows of $\det(A-\lambda I)$ will produce a row all of whose elements are multiples of $\lambda$, which can thus be factored out of the determinant leaving a single row consisting only of integer values.  Expanding this determinant using the standard Laplace expansion will produce a cubic polynomial.  Still seems like a lot of work, though...

A: Let $\{e_1,e_2,e_3,e_4\}$ be the canonical basis of $\mathbb{R}^4$.
Find the eigenvector associated to $0$. Let $v_1=(a,b,c,d)$ be this eigenvector. If $a\neq 0$ then $\{v_1,e_2,e_3,e_4\}$ is a basis of $\mathbb{R}^4$.
Let $V\in M_{4\times 4}=(v_1,e_2,e_3,e_4)=\left(\begin{array}{cccc}
a & 0 & 0 & 0 \\
b & 1 & 0 & 0 \\
c & 0 & 1 & 0 \\
d & 0 & 0 & 1
\end{array}\right)$. Notice that $V^{-1}=\left(\begin{array}{cccc}
1 & 0 & 0 & 0 \\
-\dfrac{b}{a} & 1 & 0 & 0 \\
-\dfrac{c}{a} & 0 & 1 & 0 \\
-\dfrac{d}{a} & 0 & 0 & 1
\end{array}\right)$.
Notice that  $V^{-1}AV=\left(\begin{array}{cccc}
1 & 0 & 0 & 0 \\
-\dfrac{b}{a} & 1 & 0 & 0 \\
-\dfrac{c}{a} & 0 & 1 & 0 \\
-\dfrac{d}{a} & 0 & 0 & 1
\end{array}\right)\left(\begin{array}{cccc}
0 & a_{12} & a_{13} & a_{14} \\
0 & a_{22} & a_{23} & a_{24} \\
0 & a_{32} & a_{33} & a_{34} \\
0 & a_{42} & a_{43} & a_{44}
\end{array}\right)=\left(\begin{array}{cccc}
0 & b_{12} & b_{13} & b_{14} \\
0 & b_{22} & b_{23} & b_{24} \\
0 & b_{32} & b_{33} & b_{34} \\
0 & b_{42} & b_{43} & b_{44}
\end{array}\right)$.
Finally, the required polynomial is $\det(B-\lambda Id)$, where $B=\left(\begin{array}{ccc}
b_{22} & b_{23} & b_{24} \\
b_{32} & b_{33} & b_{34} \\
b_{42} & b_{43} & b_{44}
\end{array}\right)$.
If $a=0$ and $b\neq 0$, put $v_1$ in the second column of $V$ and $e_1$ in the first and so on.


text:
Q: https and DNS over https... VPN still needed? Does using DNS over https + https web pages give equivalent privacy to using a VPN?
The DNS service also needs to be trusted (e.g. that they only keep certain logs, for so many days not keeping identifiable info etc...). Is it more or less easy to verify a DNS providers claims, as compared to a VPN provider? And... is it more critical if one or the other turns out not to be trustworthy?
Can a ISP log which sites are visited if you are using DNS over https?

A: No, it is not equivalent, and yes, an ISP can see what sites you visit.
The privacy is not equivalent, but it is complimentary. Combined, they give good privacy.
Your ISP can see the IP addresses you send data to. With a VPN (or, for that matter, Tor Browser), they only see you send data to the VPN provider (or the Tor network).
If you use unencrypted DNS lookups, the IP addresses of the sites you visit can be logged, even if you use a VPN. Someone could be snooping in on your traffic. I suspect it's not always legal for an ISP to do so, but they could. They would then see what IP addresses you're looking up, even if they can't see that you're actually visiting those addresses.
If you have encrypted traffic and DNS lookups, and use a VPN, your ISP (or someone else with access to the traffic from your machines) cannot easily see what you're doing.


text:
Q: windows phone 7 does not receive scripts and js files on https Can't solve a problem that I have regarding windows phone jquery mobile https and asp.net mvc 2. I have a asp.net mvc 2 app that resides on my localhost. Some pages require https connection, so when I use my windows phone to browse through pages everything is fine (jquery mobile renders fine) until I accept the https message and go to the https page then it showes all html content with no javascript and css (white background with black text, jquery mobile not working, hidden divs now visible and so on). Seems like windows phone is blocking the files on https in this particular scenatio. Quite strange problem, especially that everything works on Iphone. Iphone renders everything just fine whether its http or https.
I'm not gonna try to paste any code since I don't event know where to start, and the app is too large to paste code snippets. Just wanted to know if anyone had similar problem, or has any idea how to overcome this issue.
Thanks.
EDIT: by searching through forums I stumbled upon problem of self signed certificate on the server and accesing pages with windows phone, dont know if this is the exact problem tho

A: I think I found solution to my problem, as I thought I need to add the same self signed certificate to my phone that I generated on the server. It is not necessary on the iphone, but for some reason Windows Phone requiers it.


text:
Q: Setting Default Ubuntu eth port Background:
I have a desktop computer running Ubuntu 12.04.
I have installed DRBL to handle DHCP server and Clonezilla Server.
I have a network card in my desktop with 2 ports in it.
These 2 ports are bonded together and are used by DRBL.
There is a 3rd port integrated in the motherboard.
I want to use this 3rd port for internet.
DRBL knows that this is set for internet.
EDIT: "Ubuntu Network-Manager has stopped recognising the connections (device not managed)." - I have now uninstalled Network-Manager.
It use to say that eth1 was default (first port in the network card)
I want eth0 to be default as that is the Internet port.
Question:
How do I make eth0 as the default port without using Network-Manager?

A: The way to use network manager for default network assignment is by checking the 'Use this connection only for resources on its network' option in editing IPv4 routes on all connections you do NOT want to be the default.
To do this without Network manager simply edit connections that you don't want to be default and add the following at the end of each corresponding file in /etc/NetworkManager/system-connections/YourConnection
never-default=true

this line should be added under IPv4 section.
NOTE: Replace YourConnection with the corresponding Connection name. You can see available options via
ls /etc/NetworkManager/system-connections/


text:
Q: Sending data from android to php using http This my android code I used to send to my php file in website. also modified android manifest file.
        ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(7);
        nameValuePairs.add(new BasicNameValuePair("number", "5556"));
        nameValuePairs.add(new BasicNameValuePair("password",password));
        nameValuePairs.add(new BasicNameValuePair("token",token));

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://futuretime.in/post.php");
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
        HttpResponse response = httpclient.execute(httppost);

This is my php script for receiving data from android.
But my problem is when I printed data in php it is not showing any value.
        <?php
          $number= $_POST['number'];
          $password = $_POST['password'];
          $token   = $_POST['token'];
          echo $number;
        ?>

A: you can try use Ion https://github.com/koush/ion ,is a great library for make http request.
is a simple example .check the project site for more examples and wiki.
    Ion.with(getContext(), "https://koush.clockworkmod.com/test/echo")
   .setBodyParameter("goop", "noop")
   .setBodyParameter("foo", "bar")
   .asString()
   .setCallback(...)


text:
Q: Nginx reverse proxy redirect subdomain to a dynamic port without updating settings I want to setup nginx as reverse proxy server to handle wildcard subdomains. The subdomain should be linked to there own port. How can this be setup without updating nginx settings for every wildcard subdomain.
Example:
A user creates request a demo version of an application. A subdomain is defined for the user and a docker container with de application is started on a random port. De new url has to go through the nginx server and get routed to the right container. All this withouh restarting the nginx server.


text:
Q: sparse matrix parallel to the full matrix syntax of A(ind,ind)=1 in Matlab In Matlab I can populate all combinations of elements in a full matrix by doing the following:
A=zeros(5);
ind=[1 4 5];
A(ind,ind)=1

 A =
     1     0     0     1     1
     0     0     0     0     0
     0     0     0     0     0
     1     0     0     1     1
     1     0     0     1     1

How can I accomplish that when my matrix A is sparse? (say A=zeros(1e6) and I only want ~1000 elements to be 1 etc...)

A: You can use the sparse command, as follows:
% create a 5x5 sparse matrix A, with 1's at A(ind,ind)
[row,col] = meshgrid(ind,ind); % form indexing combinations
row = row(:); % rearrange matrices to column vectors
col = col(:);
A = sparse(row, col, 1, 5, 5);

While it is possible to index sparse matrices using the conventional A(1,2) = 1 style, generally this is not a good idea. MATLAB sparse matrices are stored very differently to full matrices behind the scenes and do not support efficient dynamic indexing of this kind.
To get good performance sparse matrices should be built in one go using the sparse(i,j,x,m,n) syntax.


text:
Q: Difference between Microsoft.VSTS.Scheduling.DueDate and Microsoft.VSTS.Scheduling.FinishDate of a work item I wonder the difference between using the field Microsoft.VSTS.Scheduling.DueDate or Microsoft.VSTS.Scheduling.FinishDate while customizing a work item in Team Foundation Server.

A: You can find both fields in the Work Item Field Reference. The DueDate is a field which users enter in the UI of Team Explorer or Web Access. The FinishDate is the Automatically calculated end-date if you have Project or Project Server integration enabled on your project.


text:
Q: component factory krypton myexe.exe has stopped well i am working with Component.Factory.Toolkit.dll this works in my machine which i have installed component factory, but when I copy the Bin folder in ohter pc then this does not work and InitializeComponent(); is not execute! a simple windows form using this  toolkit cant start if I execute in other machine.Do i need to install component.factory.toolkit in this pc?
Now i have connect to a remote equipe, i call the exe from my machine  since this new pc, and i got the same error
"exe has stopped"
how can i execute it? i dont want to install the tookit in every PC need uses this application.

A: You dont have to install Krypton toolkit on ever PC, Just include ComponentFactory.Krypton.Toolkit.dll with your Setup/Bin file(s).
Also here is an Answer to a simliar question


text:
Q: NSLog incorrect encoding I've got a problem with the following code:
NSString *strValue=@"你好";
char temp[200];
strcpy(temp, [strValue UTF8String]);
printf("%s", temp);
NSLog(@"%s", temp);

in the first line of the codes, two Chinese characters are double quoted. The problem is printf function can display the Chinese characters properly, but NSLog can't.

Thanks to all. I figured out a solution for this problem. Foundation uses UTF-16 by default, so in order to use NSLog to output the c string in the example, I have to use cStringUsingEncoding to get UTF-16 c string and use %S to replace %s.

NSString *strValue=@"你好";
char temp[200];
strcpy(temp, [strValue UTF8String]);
printf("%s", temp);
strcpy(temp, [strValue cStringUsingEncoding:NSUTF16LittleEndianStringEncoding]);
NSLog(@"%S", temp);

A: My guess is that NSLog assumes a different encoding for 8-bit C-strings than UTF-8, and it may be one that doesn't support Chinese characters.  Awkward as it is, you might try this:
NSLog(@"%@", [NSString stringWithCString: temp encoding: NSUTF8StringEncoding]);

A: I know you are probably looking for an answer that will help you understand what's going on.
But this is what you could do to solve your problem right now:
NSLog(@"%@", strValue);

A: NSLog's %s format specifier is in the system encoding, which seems to always be MacRoman and not unicode, so it can only display characters in MacRoman encoding. Your best option with NSLog is just to use the native object format specifier %@ and pass the NSString directly instead of converting it to a C String. If you only have a C string and you want to use NSLog to display a message instead of printf or asl, you will have to do something like Don suggests in order to convert the string to an NSString object first.
So, all of these should display the expected string:
NSString *str = @"你好";
const char *cstr = [str UTF8String];
NSLog(@"%@", str);
printf("%s\n", cstr);
NSLog(@"%@", [NSString stringWithUTF8String:cstr]);

If you do decide to use asl, note that while it accepts strings in UTF8 format and passes the correct encoding to the syslog daemon (so it will show up properly in the console), it encodes the string for visual encoding when displaying to the terminal or logging to a file handle, so non-ASCII values will be displayed as escaped character sequences.

A:     #   define NSLogUTF8(a,b) NSLog(a,[NSString stringWithCString:[[NSString stringWithFormat:@"%@",b] cStringUsingEncoding:NSUTF8StringEncoding] encoding:NSNonLossyASCIIStringEncoding])

#define NSLogUTF8Ex(a,b) NSLog(a,[MLTool utf8toNString:[NSString stringWithFormat:@"%@",b]])

+(NSString*)utf8toNString:(NSString*)str{
    NSString* strT= [str stringByReplacingOccurrencesOfString:@"\\U" withString:@"\\u"];
    //NSString *strT = [strTemp mutableCopy];
    CFStringRef transform = CFSTR("Any-Hex/Java");
    CFStringTransform((__bridge CFMutableStringRef)strT, NULL, transform, YES);

    return strT;
}


text:
Q: String should be in middle in JTable cell, Not by left This is my table:

I like that 61 and 29 and 2013/09/20 be in the middle of cell, Not in the left side!
How can do it?

A: You can do this, which sets the horizontal alignment for each column by overriding the renderer.
DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
renderer.setHorizontalAlignment(JLabel.CENTER);
for(int i = 0; i < columnCount; i++){
    table.getColumnModel().getColumn(i).setCellRenderer(render);
}


text:
Q: Writing High-Speed I2S to SD Card I've been struggling with finding a solution for the following in a personal hobby project of mine for the last six months and really starting to run out of ideas. I've been trying to create a modification of sorts for a Sony XDR-F1HD HD Radio, which is a radio that's famously good at picking out distant signals. As part of the HD radio feature, the main module exposes the digitized RF baseband with a pair of I2S lines carrying the digital samples. I'd like to piggyback off of these lines and write the raw samples to an SD card.
The Problem
The interface I'd like to capture consists of the I2S word select and bit clock lines as well as a pair of I2S data lines each carrying one channel of PCM samples. The bit clock runs at 10.4 MHz and the word select line runs at 325 kHz. Since each I2S data line is carrying one channel, this gives a sample rate of 650,000 samples/sec at 16 bits/sample. With two channels of this, the effective data rate is 20.8 megabit/sec or 2.6 MB/s. Additionally, the bit clock and word select clock is generated by the module, so whatever I use to capture must work as a "rx slave" device and not generate the clock itself.
Here is a timing diagram I modified to show how this works.
I'd like to take this parallel I2S stream and continuously stream it onto an SD card's filesystem as a file so it could be read as a two channel, 16 bits/sample, 650 ksps audio file on a computer later. Any modern decent SD card should be able to handle 2.6 MB/s pretty easily over SDIO, but likely not via SPI. I'm looking for a microprocessor or chip of some sort (that I'll refer to as a controller from here) that could accomplish this task. Ideally I'd be able to send the controller a command via i2c or something similar to "start recording to " and another command to "stop recording". I'd also like the controller to support at least a FAT32 filesystem, although I'd be more ideal to have a (Windows) filesystem that can handle files >2 GB. It's also come to my attention that SD cards can sometimes stall for up to 250ms at a time, so whatever controller I go with would need to be able to buffer 250ms (0.65 MB) of data in RAM as it's waiting to be written.
What I've Tried
First, I tried purchasing an ESP32 microprocessor to use. Unfortunately, while the datasheet claims it supports bit clocks up to 80 MHz, that apparently only applies in master mode where the ESP32 is generating the clock and not in slave mode where it needs to lock onto the external clock as is required for this project. Otherwise, it'll drop bits and just read in junk. This is unfortunate, as I've found that the ESP32 has a fast enough SD card interface to accomplish this data rate if it could only clock in the bits fast enough. Additionally, it doesn't seem to have any support for the strange "parallel" I2S I have.
Next, I purchased a Raspberry Pi Pico and ran into essentially the opposite problem. With some cleverly crafted PIO (programmable IO) assembly code I was able to pretty easily capture the signal. However, it can't write to an SD card nearly fast enough, so I can only really capture as much that'll fit into RAM. Since I need recording to be continuous, this doesn't work for me. However, I was at least able to run an FFT using fftw3 (which ran surprisingly well!) and confirm that the data over these I2S lines is what I'm after.
Additionally, I tried a full size Raspberry Pi (which isn't really ideal for this project) but the GPIO isn't quite fast enough for my needs. It has the RAM and SDIO speed for it, but I couldn't find a way to clock in bits fast enough. I'd also like this to be as "bare metal" as possible so I'd like to avoid running on top of an OS if I don't have to.
Summary
In summary, I'm looking to find a microcontroller or chip of some sort that'll help me accomplish the following:

*

*Continuously capture the 16-bit PCM samples sent via a parallel I2S interface running at 20.8 megabit/sec (2.6 MB/s), clocked in from an external bit/word select clock, onto an SD card

*The data must be written onto a file on the SD card through a filesystem like FAT32, although ideally something like ExFAT or NTFS that supports files >2 GB (although segmented files would be fine too)

*The microcontroller or chip must be able to buffer a bit of the signal to avoid dropping samples while the SD card stalls occasionally

*This is just a personally hobby project, not something I'm planning on manufacturing at scale, so whatever I use has to be at least a bit affordable (no $500+ dev boards please, haha)

*I'd appreciate a pretty "fat free" solution that doesn't require booting into an OS or something like that

I have programming experience so I'd be happy to write the software myself, I just need to find hardware that'll be capable of such a thing. I don't have any experience with hardware language for something like an FPGA though, so I'd have no clue what to do if I needed one of those. I really liked the "programmable IO" feature on the Raspberry Pi Pico, so maybe I'm looking for something like that but with a lot more RAM and an SDIO interface?
Thanks, I really appreciate it. I've been banging my head against this problem for months and months, haha.


text:
Q: ReactJS - why is my nested element not rendering? I'm trying to render a nested component friendPanel from within my App component. It is compiling but upon loading, is not showing the friendPanel's array. I'm a reactJS newbie, so please bear with me. How should I render the friendPanel from within the App component?
The relevant parts of my code are below:
class friendPanel extends Component {
  render(props) {
    return (

        {props.friends.map( friend =>

{friend.name}

        )}

    );
  }
}

class App extends Component {
  state = {
    name: 'Bob McBobberson',
    friendList: [
      {id: 1, name: "Sandra"},
      {id: 2, name: "Tammy"},
      {id: 3, name: "Fernando"}
    ],
  }

  render() {
    return (
      <MuiThemeProvider theme={theme}>

Welcome {this.state.name}

          <friendPanel friends={this.state.friendList} />

      </MuiThemeProvider>
    );
  }
}

export default App;

Thank you in advance for any help!

A: You should capitalize FriendPanel or React will treat it as plain old HTML.
See: ReactJS component names must begin with capital letters?

A: Try this:
class FriendPanel extends Component {   //fixed - Component name should start with an upper-case letter
  render() {   // removed the unnecessary props parameter
    return (

        {this.props.friends.map( friend =>  //fixed - in ReactJS, this is the way we get data from props

{friend.name}

        )}

    );
  }
}

class App extends Component {
  state = {
    name: 'Bob McBobberson',
    friendList: [
      {id: 1, name: "Sandra"},
      {id: 2, name: "Tammy"},
      {id: 3, name: "Fernando"}
    ],
  }

  render() {
    return (
      <MuiThemeProvider theme={theme}>

Welcome {this.state.name}

          <FriendPanel friends={this.state.friendList} />   //fixed -  in JSX, the custom element must start with an upper-case or the compiler will treat this as regular html tag

      </MuiThemeProvider>
    );
  }
}


text:
Q: Poisson point process in "input" to another Process I have a Poisson point process with rate $\lambda$. I want to consider a new process that fires an event every time the Poisson point process finds 3 points. How this process can be described? What is the event rate and the variance of this process?
I put on evidence that the second process is not simply a Poisson point process with rate $\frac{\lambda}{3}$.

A: Denote this process by $X(t)$. The interarrival distribution has $\mathrm{Erlang}(3,\lambda)$ distribution with density $f_J(t) = \lambda\frac{(\lambda t)^2}2 e^{-\lambda t}$. The Laplace-Stieltjes transform of this distribution is
\begin{align}
\hat F(z) &= \mathbb E[e^{-zJ}]\\
&= \int_0^\infty e^{-zt}\lambda\frac{(\lambda t)^2}2 e^{-\lambda t}\mathsf dt\\
&= \frac{\lambda^3}{(\lambda+z)^3}.
\end{align}
Let $M(t) = \mathbb E[X(t)]$ be the renewal function. Then the Laplace-Stieltjes transform of $M$ is
\begin{align}
\hat M(z) = \frac{\hat F(z)}{1-\hat F(z)} = \frac{\frac{\lambda^3}{(\lambda+z)^3}}{1-\frac{\lambda ^3}{(\lambda +z)^3}} = \frac{\lambda ^3}{z^3+3 \lambda  z^2+3 \lambda ^2 z}.
\end{align}
Inversion yields
$$
M(t) = \frac{1}{3} \lambda  \left(1-e^{-\frac{1}{2} (3 \lambda  t)} \left(\sqrt{3} \sin \left(\frac{1}{2} \sqrt{3} \lambda  t\right)+\cos \left(\frac{1}{2} \sqrt{3} \lambda  t\right)\right)\right).
$$
From this question we can derive the variance of a renewal process from the renewal function:
\begin{align}
\operatorname{Var}(X(t)) &= 2\int_0^t M(t-s)\ \mathsf d M(s) + M(t) - M(t)^2\\
&=2\int_0^t \frac{\lambda ^3}{3 \lambda ^2 (t-s)+3 \lambda  (t-s)^2+(t-s)^3}\left(-\frac{3 \lambda ^3}{(\lambda +s)^4}\right)\ \mathsf ds\\
&\quad+\frac{1}{3} \lambda  \left(1-e^{-\frac{1}{2} (3 \lambda  t)} \left(\sqrt{3} \sin \left(\frac{1}{2} \sqrt{3} \lambda  t\right)+\cos \left(\frac{1}{2} \sqrt{3} \lambda  t\right)\right)\right)\\
&\quad - \left(\frac{1}{3} \lambda  \left(1-e^{-\frac{1}{2} (3 \lambda  t)} \left(\sqrt{3} \sin \left(\frac{1}{2} \sqrt{3} \lambda  t\right)+\cos \left(\frac{1}{2} \sqrt{3} \lambda  t\right)\right)\right)\right)^2.
\end{align}
Unfortunately, I can't get Mathematica to evaluate the integral. There isn't likely to be a nice closed form for this one.


text:
Q: How do you reset the Google AppEngine Datastore Quota Exceeded condition? If you have a application that exceeds that Datastore quota of 1 Gig (Master/Slave configuration) How do you clear the condition?
I have an application called "parking-helper" and it has a Total Stored Data 100% used message.
But I've deleted 99% of the data (a few days ago) cleared the indexes,
vacuumed the indexes and cleared the memcache and also waited for at
least 2 reset cycles and yet the datastore still says 100% used.
The datastore admin shows that the datastore does not add up to more than a
meg.
I know that memcache and indexes count also.  It would be nice to see the sizes of these in the Datastore Admin view (but currently we cannot see these values).  But I believe I cleared them also.
How can I reset this application without the drastic measure of deleting and re-creating which means I'd have to pick another application id and re-create all the other data.
Thanks,
Ralph

A: It's usually just a matter of waiting. And it looks like your quota is under 100% now.


text:
Q: displayed another field in front-office and back-office prestashop I would like to display a "Function" field in the front-office and back-office of prestashop but I can't. Thanks to my code, I added the field "Function" in my registration form, it is persisted in database and we can modify it in database too, but it is not displayed in front-office nor in back-office. Its value is not filled in the $value variable of the form-field.tpl and I don't see how to fix it
My module :
<?php
if (!defined('_PS_VERSION_')) {
    exit;
}
use PrestaShop\PrestaShop\Adapter\Presenter\Object\ObjectPresenter;

require_once dirname(__FILE__) . '/classes/CustomerFonction.php';

class AddJob extends Module
{
    public function __construct()
    {
        $this->name = 'addjob';
        $this->tab = 'others';
        $this->version = '1.0.0';
        $this->author = 'advisa';
        $this->need_instance = 0;
        $this->ps_versions_compliancy = [
            'min' => '1.6',
            'max' => '1.7.99',
        ];
        $this->bootstrap = true;

        parent::__construct();

        $this->displayName = $this->l('AddJob');
        $this->description = $this->l('Add job in registration form');
    }
    public function install()
    {
        return parent::install() &&
            $this->installSql() &&
            $this->registerHook('additionalCustomerFormFields') &&
            $this->registerHook('actionCustomerAccountAdd') &&
            $this->registerHook('actionCustomerAccountUpdate') &&
            $this->registerHook('actionAdminCustomersFormModifier') &&
            $this->registerHook('displayCustomerAccount');

    }
    public function uninstall()
    {
        return (
        parent::uninstall()
        );
    }
    /*
    public function installSql()
    {
        $sqlInstall = "ALTER TABLE " . _DB_PREFIX_ . "customer "
            . "ADD fonction VARCHAR(255) NULL";

        return Db::getInstance()->execute($sqlInstall);
    } */
    public function installSql()
                {
                    $sqlQuery = array();
                    $sqlQuery[] = 'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'addjob_addfonction` (
                        `id_addfonction` INT(10) PRIMARY KEY NOT NULL AUTO_INCREMENT,
                        `id_customer` INT(10),
                        `fonction` VARCHAR(255)
                    )';

                    $db = Db::getInstance();
                    foreach ($sqlQuery as $query) {
                        if (!$db->execute($query)) {
                            return false;
                        }
                    }
                    return true;
                }

    public function hookAdditionalCustomerFormFields($param)
    {
        $field = array();
        $field['fonction'] = (new FormField())
                ->setName('fonction')
                ->setType('text')
                //->setRequired(true)
                ->setLabel($this->l('Fonction'));
        if($this->context->customer->id !== null){
            $data = new CustomerFonction($this->context->customer->id);
            $field['fonction']->setValue($data->fonction ?? '');
        }
        return $field;
    }

    public function hookActionCustomerAccountAdd($param)
    {
        $customeField = new CustomerFonction();
        $customeField->id_customer = $param['newCustomer']->id;
        $customeField->fonction = Tools::getValue('fonction', '');

        $customeField->add();

    }
    public function hookActionCustomerAccountUpdate($param)
    {
        $customerId = $this->context->customer->id;
        $customerField = new CustomerFonction($customerId);
        $customerField->id_customer = $customerId;
        $customerField->fonction = Tools::getValue('fonction', '');

        $customerField->save();
    }
    public function hookActionAdminCustomersFormModifier($params) {

        $params['fields'][0]['form']['input'][] = [
            'type' => 'text',
            'label' => $this->l('fonction'),
            'name' => 'fonction',
            'class' => 'input fixed-width-xxl',
            'hint' => $this->l('fonction')
        ];

        //Définition de la valeur du champ supplémentaire
        $params['fields_value']['fonction'] = $params['object']->fonction;
    }
    public function displayCustomerAccount($param)
    {
        $this->context->smarty->assign([
            'fonction' => Tools::getValue('fonction')
        ]);
            return '/themes/classic/templates/_partials/form-field.tpl';
    }
}

and here is my class extends ObjectModel
<?php

class CustomerFonction extends ObjectModel
{
    public $id_addfonction;
    public $id_customer;
    public $fonction;

    public static $definition = [
        'table' => 'addjob_addfonction',
        'primary' => 'id_addfonction',
        'multilang' => false,
        'fields' => [
            'id_customer' => ['type' => self::TYPE_INT],
            'fonction' => ['type'=>self::TYPE_STRING, 'size'=> 255],
        ],
    ];
    public static function getFonctionByCustomer($id_customer): ?string
    {
        $sql = new DbQuery();
        $sql->select('fonction');
        $sql->from('addjob_fonction');
        $sql->where('id_customer = ' . $id_customer);
        return Db::getInstance()->getValue($sql);
    }

Can someone help me please :) ?

A: You need to register these new extra hooks

*

*validateCustomerFormFields

*actionObjectCustomerUpdateAfter

*actionObjectCustomerAddAfter

*actionAfterCreateCustomerFormHandler

*actionAfterUpdateCustomerFormHandler
like you did in your question above

$this->registerHook('validateCustomerFormFields');

*

*validateCustomerFormFields
Is used to validate the form fields.

public function hookValidateCustomerFormFields($params)
{
      $myfields = $params['fields'];
      // example check if fonction is empty
       if($myfields[0]->getValue() ==''){
          $myfields[0]->addError(
              $this->l('fonction is empty')
          );
       }
      return array($myfields);

}

*actionObjectCustomerUpdateAfter
This hook is called when customer updates his/her identity form

public function actionObjectCustomerUpdateAfter($params)
    {
            $id_customer = (int)$params['object']->id;
           $fonction= trim(Tools::getValue('fonction'));
             Db::getInstance()->update('customer', array(fonction=>pSQL($fonction) ), ' id_customer ='.(int) $id_customer);

    }

*actionObjectCustomerAddAfter
This hook is called when customer creates account.

public function actionObjectCustomerAddAfter($params)
    {
        $id_customer = (int)$params['object']->id;
        $fonction= trim(Tools::getValue('fonction'));
        Db::getInstance()->update('customer', array(fonction=>pSQL($fonction) ), ' id_customer ='.(int) $id_customer);
    }

*actionAfterCreateCustomerFormHandler
This hook is called when customer account is created

public function hookActionAfterCreateCustomerFormHandler($params)
    {
       $id_customer =  $params['id'];
       $formcontent =  $params['form_data']; // this is an array of form fields and values.
       // You can update your the fonction field this way
      Db::getInstance()->update('customer', array(fonction=>$formcontent['fonction']), ' id_customer ='.(int) $id_customer);

    }

*actionAfterUpdateCustomerFormHandler
This hook is called when customer account is updated.

public function hookActionAfterUpdateCustomerFormHandler($params)
    {
    $id_customer =  $params['id'];
    $formcontent =  $params['form_data']; // this is an array of form fields and values.
    You can update your the fonction field this way
    Db::getInstance()->update('customer', array(fonction=>$formcontent['fonction']), ' id_customer ='.(int) $id_customer);
    }

You do no need to include these hooks if all you want to do is add additional fields to the customer form

*

*actionCustomerAccountAdd

*actionCustomerAccountUpdate

*displayCustomerAccount


text:
Q: How to convert Model to JSON When I naively use Jackson to convert to JSON i receive this exception:

Caused by: com.fasterxml.jackson.databind.exc.InvalidDefinitionException: No serializer found for class org.apache.cayenne.access.DefaultDataRowStoreFactory and no properties discovered to create BeanSerializer

Edit: I'd like to do something like this:
ObjectContext context = cayenneRuntime.newContext();

List<User> users = ObjectSelect.query(User.class).select(context);
JsonObject json = Json.mapper.convertValue(obj, Map.class)

Are there any existing solutions? Thanks

A: Considering that in a general case Cayenne gives you not just objects, but a virtual graph of objects, serialization to JSON becomes a more quirky topic than it initially appears.
The short answer: you'd have manually build JSON for whatever subgraph of your object graph.
While not a direct answer, it may be worth mentioning that Agrest framework (ex. LinkRest) supports rule-based serialization of Cayenne object graphs to JSON. But it is not a standalone component. I.e. it will only work if you use it for your REST services.


text:
Q: Algorithms of compare multiple fields I have a table info
CREATE TABLE `info` (
   `id` int(11) NOT NULL DEFAULT '0',
   `name` varchar(50) NOT NULL,
   `email` varchar(50) NOT NULL,
   `phone` varchar(50) NOT NULL,
   PRIMARY KEY (`id`)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8

The comparable fields are name, email and phone.
My compare rule is: any two of the three fields equal then the two records equal.
So my question is what is the most efficient way of implements this feature.
P.S. I can add extra fields if needs.

A: MySQL returns 1 for true and 0 for false.
Select * From info
WHERE (name = 'name') + (email = 'email') + (phone = 'phone') > 1


text:
Q: can i print a setter value (sysout) or do i have to use only getters in order to get an output ? (java) I have just recently learned about setter , getters and this.(somthing).
I having quite a hard time undersatnding when to use getters and when to use setters .
Another thing , can i use setter method to print out ?
For Example :
 class workerId {
private int workerAge;
private String workerName;
private int workerIde;

public void setWorkerAge(int newAge) {
    newAge = workerAge;
}

public void setWorkerName(String newName) {
    newName = workerName;
}

public int setIde(int ide) {
    ide = workerIde;
    return ide;

 }
}

public class App {

public static void main(String[] args) {
    workerId worker1 = new workerId();
    worker1.setWorkerAge(41);
    worker1.setWorkerName("dan ");
    worker1.setIde(318574524);

    System.out.println(worker1.setIde());

    }

}

the system out print shows an error and i didnt understand why , is it because only getters can be used in the sysout command ?

A: No offense intended, but your setters are all wrong. You should assign your properties to the values passed in the setter, not setting the value again. So your code should look like this:
class workerId {
  private int workerAge;
  private String workerName;
  private int workerIde;

  public void setWorkerAge(int newAge) {
    workerAge = newAge;
  }

  public void setWorkerName(String newName) {
    workerName = newName;
  }

  public int setIde(int ide) {
    workerIde = ide;
  }
}

If you need getters, it should look like this:
class workerId {
  private int workerAge;
  private String workerName;
  private int workerIde;

  public void setWorkerAge(int newAge) {
    workerAge = newAge;
  }

  public void setWorkerName(String newName) {
    workerName = newName;
  }

  public int setIde(int ide) {
    workerIde = ide;
  }
  public int getIde() {
    return workerIde;
  }
}

Then you can print, e.g. System.out.println(worker1.getIde());

A: You should be using a getter method to get the values.
class workerId {
private int workerAge;
private String workerName;
private int workerIde;

    public void setWorkerAge(int newAge) {
        workerAge = newAge;
    }

    public void setWorkerName(String newName) {
         workerName=newName;
    }
    public int getIde() {
    return workerIde;
    }

    public void setIde(int ide) {
        workerIde = ide;

     }
    }

    public class App {

    public static void main(String[] args) {
        workerId worker1 = new workerId();
        worker1.setWorkerAge(41);
        worker1.setWorkerName("dan ");
        worker1.setIde(318574524);

        System.out.println(worker1.getIde());

        }

    }

A:     class workerId {
    private int workerAge;
    private String workerName;
    private int workerIde;

    public void setWorkerAge(int newAge) {
        this.workerAge = newAge;
    }

    public void setWorkerName(String newName) {
        this.workerName = newName;
    }

    public int setIde(int ide) {
        this.workerIde = ide;
        return this.workerIde;

     }
    }

    public class Car {

    public static void main(String[] args) {
        workerId worker1 = new workerId();
        worker1.setWorkerAge(41);
        worker1.setWorkerName("dan ");
        worker1.setIde(318574524);

    System.out.println(worker1.setIde(56));
    }

}


text:
Q: How to read $x^n-1$ and $x^{n-1}$? Now, it may sound absurd, but I would like to know (if exists), how to read $(x^{n-1})$ and $(x^n-1)$ distinctly and practice this it in everyday Mathematics.
As of now, I read $(x^{n-1})$ as, "x whole raised to power n-1" and $(x^n-1)$ as " x raised to n whole minus 1".
Similar confusing scenarios are also welcome.
Thank you.

A: To read aloud I would say, "x to the power, pause, n minus 1", and "x to the power n, pause, minus 1". The position of the pause is used to communicate the implied brackets. If this is not clear enough, then "x to the power open bracket n minus 1 close bracket".

A: For $x^{n-1}$, $``x$ whole raised to $n-1"$ looks great.
For $x^n - 1$, I'd suggest $``1$ less than $x^n"$

A: For $x^{n-1}$: $x$ raised to the difference of $n$ and $1$. And for $x^n-1$: The difference of $x$, raised to $n$, and $1$.


text:
Q: Spring and JSR 303 Validation. How to validate only some properties? let's assume we have a signup form. When some input of the form is changed, I want to validate its value on the fly by using the ajax call to the server. Is there a chance to validate only some particular property of the bean by using the JSR 303 validation?
The signup form handler validates the received bean just fine, but I want to find out the way to check the property before submit the whole bean.
The straight forward approach is just to create a server-side method to receive the property name and value and based on the name check the value, but I hope there is a way to use already defined constraints for the bean.
For example, the user entered the email address and moved forward to the next property. The client makes a call and the server method checks if the provided email is already exist. If so, it returns an error and I do show it up on the client side. I believe it may make the signup process more flexible and user friendly
Any comments are really appreciated.

A: The jsr-303 Validator does have a method right on it to validate just one property:
<T> java.util.Set<ConstraintViolation<T>> validateProperty(T object,
                                                           java.lang.String propertyName,
                                                           java.lang.Class<?>... groups)

You just need to inject the validator so that you can use it directly, rather than relying on Spring to call it automatically via putting @Valid on a method parameter.


text:
Q: include_path gets ignored? Or Recently my ISP added imap functionality to my webserver. After the installation they recompiled PHP. But the hostingclients on my server are including from a specific hostingaccount on the server. By adding an extra include_path to the CMS folder the websites are able to communicate with the CMS and database. The strange thing is that after recompiling PHP the 'client-accounts' can't include my CMS files anymore. I'm prompted with the traditional error 'failed to open stream'.
I've tried to add the includepath in the php.ini, but as i expected without any result. Do you have any idea why the include_path is getting ignored/excluded/overruled? Are there perhaps other settings in php.ini which need to be set?
P.s. my server is configured without suPHP (I've been told by my ISP).

A: It's solved by the ISP now. Open basedir restrections were the problem. I turned them off and now it works again :)


text:
Q: 0 opacity in css and what to use jquery mouseenter to change opacity and size I want to create a div and set the opacity to 0 with css(background, color, border) so completely invisible and the whole thing will only work if js enabled. There is another div next to it, and want to use jQuery to change the opacity to 1 and change it size. If possible with fadeIn fadeOut.
So far I didn't get far, still couldn't even change the opacity, although a researched it.
$(document).ready(function(){
    $("#showCaseWD").hover(function(){
        $("#wdShow").css({color:rgba(0,0,0,1.0)});
    });
});

A: You're close.. You'll have to use a css transition if you don't want the opacity change to be abrupt. css 'color' refers to the colour of the text inside the div. So if you want to change the opacity of the whole div, just use css 'opacity' property.
#wdShow {
    opacity: 0;
    transition: 0.2s opacity ease;
}

$(document).ready(function(){
    $("#showCaseWD").on('mouseenter', function() {
        $("#wdShow").css('opacity', '1');
    });
});

A: $(document).ready(function(){

    $('#wdShow'){
      'opacity':0.8,
      'transition':'0.3s opacity linear'
    });

    $("#showCaseWD").hover(function(){
        $("#wdShow").css({
           'background-color':'rgb(0,0,0,1.0)'
    });

});

A: Try this: http://jsfiddle.net/1xopc6bq/1/.
$("#showCaseWD").mouseenter

To make a div invisible you can use opacity, background-color: rgba(0,0,0,0); or visibility:hidden;
Also I recommend to read http://www.w3schools.com/css/css_display_visibility.asp


text:
Q: PHP and XSLTProcessor Misbehavior Simple question: Why is a PHP function called from an XSL Stylesheet just returning the last argument passed:
foo.xsl:
<xsl:template match="/">
    <xsl:value-of select="php:function('date','c')" />
</xsl:template>

PHP:
...
$xsl = new XSLTProcessor();
$xsl->registerPHPFunctions();
$xsl->importStylesheet($fooStylesheet);
echo $xsl->transformToXML($myXML);

I Get the output
c

and if I call <xsl:value-of select="php:function('date')" /> I just get date as my output. Seems strange to me.
Version info:
PHP 5.3.2
libxslt Version 1.1.26
libxslt compiled against libxml Version 2.7.6
EXSLT   enabled
libexslt Version    1.1.26

A: You need the PHP xmlns in your <stylesheet> root tag:
<stylesheet xmlns:php="http://php.net/xsl">


text:
Q: Hide a
* item class

I want to hide this bit:
Kατηγορίες
 as seen in the code below (also see here https://poiimata.com/poets/):

Kατηγορίες

    Robert Frost

    Shlain

I tried using
.categories {
  display:none;
}

but the result was to hide all items below that one (the whole list).

A: That happen because you've an invalid HTML code in :

Kατηγορίες

_________________________________^^^^

The browser will evaluate your code to the below format, that why all your li's become hidden :

Kατηγορίες

Robert Frost

Shlain

Instead it should be :

Kατηγορίες

Robert Frost

Shlain

Snippet:

.categories {
  display: none;
}

Kατηγορίες

Robert Frost

Shlain

A: It appears you just have an error in your HTML. You use an incorrect closing tag and therefore hide the entire thing.

Kατηγορίες

    Robert Frost

    Shlain

Try instead:

Kατηγορίες

    Robert Frost

    Shlain

and change CSS to
.categories:first-child {
 display:none;
}

That's just one way of accomplishing it. There are quite a few different angles you can take.

A: Since li contains tags that you do not need to hide, you need to masked the hidden text. for example like this:

.categories {
  font-size: .1%;
}

.categories ul {
  font-size: 100000%;
}

if only child elements is not a bug...


text:
Q: How can I show dynamically-updated content in a Bootstrap popover? I have a Bootstrap 4.7 popover as follows. This works ok without the popover. However if I insert the id="countdown" in data-content the result is not shown. How do you fix this? Thanks a lot. PS: endTime value is just a reference, the real value is near Date().getTime().

var myfunc = setInterval(function() {
  var endTime = 6666666666
  var currentTime = new Date().getTime() / 1000 | 0
  var seconds = endTime - currentTime

  // output
  document.getElementById("countdown").innerHTML = seconds + "s "

  // when countdown is over
  if (remaining < 0) {
    clearInterval(myfunc);
    document.getElementById("countdown").innerHTML = ""
  }
}, 1000);
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">

<div class="myinfo" data-container="body" data-toggle="popover" data-html="true" data-placement="top" data-trigger="hover" data-content='Submit Time:
                          '>Div content


text:
Q: Output JS and HTML to different locations using Gulp Usemin I'm using gulp-usemin to combine my JS files (with uglify)
I have a folder structure as follows:
Top
  |- Web
      |- Scripts
         |- App
             |- script1.js
             |- script2.js
         |- Vendor (folder)
         |- CompiledScripts
             |- useminFile1.js
      |- Areas
          |- Area1
              |- index.html

All the usecases for gulp-usemin designate copying everything to a dist folder, which I cannot do.
The goal is to rewrite the index.html file to it's current location, but to write the combined JS files to 'Top/Web/Scripts/CompiledScripts'. I've tried various combinations but I can only get JS OR html in the correct place, never both.
I've put the basic task below. This will output the re-written index file in the correct location, but not the compiled JS files (will be in same directory as the html file, put at the path in the html block).
gulp.src('./Top/Web/Areas/Area1/index.html')
    .pipe(usemin({
        path: './Top/Web/',
        assetsDir: './Top/Web/',
        js: [
            uglify()
        ]
    }))
    .pipe( gulp.dest( './Top/Web/Areas/Area1/' ) );

HTML Block. Needs to have absolute path to scripts
<!-- build:js /Scripts/CompiledModules/Libraries/test.js -->
    <script src="/Scripts/Vendor/Bower/lodash/dist/lodash.js"></script>
    <script src="/Scripts/Vendor/Bower/jquery/jquery.js"></script>
<!-- endbuild -->

Any help would be greatly appreciated. Trying more combinations as we speak

A: Since you have:
.pipe( gulp.dest( './Top/Web/Areas/Area1/' ) );

You need to use:
<!-- build:js ../../Scripts/CompiledScripts/vendor.min.js -->


text:
Q: How to improve this SQL performance? I made a query shown as below. The purpose is for a quick search for the orders. User inputs one keyword, system returns orders whose property matches that keyword. E.g. keyword = "pan", any order record related to "pan" should be returned, like order's country="Japan",or description = "This is a pan." or order's customer's name = "Pan", or there is a product named "pan" in the order.
ORDER_TABLE, ORDER_DESCRIPTION, ORDER_COUNTRY, these tables are one to one relationship. But ORDER_TABLE and ORDER_PRODUCT is one to many (10-100) relationship. 'ORDER_TABLE' has over 300,000 rows, so is ORDER_DESCRIPTION, ORDER_COUNTRY. ORDER_PRODUCT has about 1500,000 rows.
But it is extremely slow since database stores huge data.
SELECT ot.id, od.description, oc.country_name
    FROM       ORDER_TABLE ot
    LEFT JOIN  ORDER_DESCRIPTION od ON ot.id = od.id
    LEFT JOIN  ORDER_COUNTRY oc     ON ot.id = oc.id
    LEFT JOIN  ORDER_PRODUCT op     ON ot.id = op.id
    WHERE ot.delete!='Y' AND od.delete!='Y' AND ot.create_date >= SYSDATE - 90
    AND
    (
        ot.id like '%KEYWORD%'
        OR UPPER(od.description) LIKE '%KEYWORD%'
        OR UPPER(ot.version) LIKE '%KEYWORD%'
        OR UPPER(oc.country_name) LIKE '%KEYWORD%'
        ...(many columns are used to match that keyword)
        OR UPPER(op.product_name) LIKE '%KEYWORD%'
    )
    GROUP BY (...)
    ORDER BY ot.id

This query is extremely slow. Usually it takes 35sec to process. Any idea to improve it? I heard that multiple join is not a good idea. So I tried to use nested subquery, but no big improvement.
Thanks.

A: Try using the AND checks in where clause directly in join
SELECT ot.id, od.description, oc.country_name
FROM ORDER_TABLE ot
    LEFT JOIN  ORDER_DESCRIPTION od ON ot.id = od.id AND ot.delete!='Y' AND od.delete!='Y' AND ot.create_date >= SYSDATE - 90
    LEFT JOIN  ORDER_COUNTRY oc     ON ot.id = oc.id
    LEFT JOIN  ORDER_PRODUCT op     ON ot.id = op.id
    WHERE
    (
        ot.id like '%KEYWORD%'
        OR UPPER(od.description) LIKE '%KEYWORD%'
        OR UPPER(ot.version) LIKE '%KEYWORD%'
    OR UPPER(oc.country_name) LIKE '%KEYWORD%'
    ...(many columns are used to match that keyword)
    OR UPPER(op.product_name) LIKE '%KEYWORD%'
)
GROUP BY (...)
ORDER BY ot.id


text:
Q: Make synchronous post request from react to flask to get dict Context:
I'm building a app that can plot graph structures in electron with react. My backend is some Matlab code that can perform analysis on the graph struct. I'm using flask as the middle man communicating between them.
In the GUI i have a button that should be able to load the data that is provided in a excel file to the GUI. This should be done by a post request that uses a matlab script to load the data from the excel file and then returns this to javascript.
I have tried using something like this:

fetch('http://localhost:5000/getGriddata', {
method : 'POST',
headers : {
'Content-Type' : 'application/json'
},

          body : JSON.stringify(fileObj.path)

      }).then(response => response.json())
      .then(data => setGriddata(data))
      .catch(error => console.log(error));

The problem is that this code won't wait for the flask function to be finished. The flask function takes about 10 seconds depending on the graph size. Therefor i want to make this call in sync with my javascript code so that after the request, i can assure that the new griddata is defined.
Question:
Is there some way to ensure this when using fetch?
Do i need to find a different way of connecting to flask, if so what would that be?

A: Solution:
Instead of using the fetch api, another post brought me to the XMLHttpRequest. This works synchronously if the parameter is set to false.

With this my code looks like this:
var request = new XMLHttpRequest();
request.open("POST",'http://localhost:5000/getGriddata',false);
request.setRequestHeader('content-type', 'application/json');
request.send(JSON.stringify(fileObj.path));
console.log(request.response)
console.log(request.responseText)
setGriddata(JSON.parse(request.responseText))

A: Instead of using callbacks, try using async/await
const fetchGridData = async () => {
    try {
        const response = await fetch('http://localhost:5000/getGriddata', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(fileObj.path)
        });

        const result = await response.json();

        setGriddata(result)
    } catch(error) {
        console.error("fetchGridData =>", error)
    }
}


text:
Q: How to write SQL query for aggregate total value for a particular condition vote table
PK_ID  ob_type  ob_id  VOTE   user_id  VOTED_ON
    1      100      1     1   NISHANT  02/08/10
    2      100      1     1      DEVI  02/08/10
    3      100      1     1  VIRENDRA  02/08/10
    4      100      1     0       XYZ  02/08/10
    5      200      1     1     XCXCX  02/08/10
    6      200      1     1       CXC  03/02/11
    7      200      1     0      XCCX  03/02/11
    8      200      1     0      XCCX  03/02/11
    9      300      1     1    XCCXXC  03/02/11
   10      300      1     1      XCCX  03/02/11
   11      300      1     1        SD  02/08/10
   12      300      1     0   XCCXXCC  02/08/10
   13      400      4     0    CXXCXC  02/08/10
   14      400      4     0      XCCX  03/02/11
   15      400      4     0       CXC  03/02/11
   16      400      1     1       CXC  03/02/11

here I want to calculate total no of vote on a particular object type and id.
  SELECT
     COUNT (ALL  [PK_ID]) AS [TOTAL_VOTE],
     COALESCE (
         ( SELECT
               [IS_THUMBS_UP]
           FROM
               [votetable]
           WHERE
               [ob_type] = 400 AND
               [ob_id] = 4 AND
               [FK_VOTED_BY] = Nishant ),-1) AS [MY_VOTING]
  FROM
     [votetable]
  WHERE
     [ob_type] = 400 AND
     [ob_id]  = 4

Here it give result
total vote = 4
and my vote = 0
but here total voting is -2 (bcz 3 false(0) and 1 true)
So how do I get the correct value.

A: I suggest (SQLServer syntax) :
select sum(case [VOTE] when 1 then 1 else -1 end) as total_votes,
       sum((case [VOTE] when 1 then 1 else -1 end) *
           (case when [user_id] = @username then 1 else 0) as user_votes
from [votetable]
where [ob_type] = @obtype and [ob_id] = @obid

@username, @obtype and @obid are variables with the desired user's name, object type and object ID.


text:
Q: SQL Query Generated by Rails #find method There is an Article model with id, title, created_at, and updated_at columns in the database and no additional logic in the model.  In the Rails console, the find method generates the following query:
Article.find(1)
# Article Load (2.8ms)  SELECT  "articles".* FROM "articles"  WHERE "articles"."id" = ? LIMIT 1  [["id", 1]]

I was surprised to find that this query raises a syntax error when it's run in the rails db console:
$ rails db
sqlite> SELECT  "articles".* FROM "articles"  WHERE "articles"."id" = ? LIMIT 1  [["id", 1]];
Error: near "[["id", 1]": syntax error

I was also surprised to see LIMIT 1 in the query.  The primary key must be unique, so isn't it obvious that only one result will be returned?
Recap of my questions:

*

*Why isn't the find method generating 'valid' SQL (i.e. SQL that
can be pasted in the Rails db console and work)

*Why is LIMIT included in the find query.

A: *

*The SQL is not wrong. Rails is showing you what is being injected at the end. It is essentially converting that SQL statement to this:
SELECT  "articles".* FROM "articles"  WHERE "articles"."id" = 1 LIMIT 1

*With find, you are only looking for a single row with the primary key you give. Ruby ensures that what is found should only be a single row. Since you have an article id with one, it will return that data.
http://guides.rubyonrails.org/active_record_querying.html#retrieving-a-single-object

A:
Why isn't the find method generating 'valid' SQL (i.e. SQL that can be pasted in the Rails db console and work)

The key thing is the output which you are seeing is not for copying and pasting into database console. It is just there so it will give you some sense what it is going inside. I guess if you map the values appropriately it will be good then. Also, if you are interested in finding the sql of a give ActiveRecord object, you can call to_sql in it.

Why is LIMIT included in the find query

The find method takes any number of arguments. since, you passed one argument, It is rails responsibility to give you back 1 record. It might be the cases that the id may appear more than one time so just to avoid all such bad scenarios they are appending limit 1.
If you pass multiple arguments say find(1,2,3) it won't append limit clause, since in this case you are getting Array instead of model.


text:
Q: roots argument in shinyFileChoose() is not reactive to input I'm trying to use shinyFileChoose() in one of my applications, the problem is, the top-level directory where I need to let users search is fairly large and has thousands of subdirectories, thus slowing down the app.
One obvious (to me) solution is to get a list of the 2-level subdirectories, let user select a subdirectory simply in a selectInput(), then feed this subdirectory as the root for shinyFileChoose(). Reproducible example using your machine's home directory below:
library(shiny)
library(shinyFiles)

allinhome <- list.files("~")

ui <- fluidPage(
  selectInput("2LevelFolder",
              "Select a folder in home directory.",
              choices = allinhome),

  shinyFiles::shinyFilesButton("chooseFile",
                               "Explore and choose file",
                               "This is the title",
                               multiple = TRUE),

  verbatimTextOutput("path")

)

server <- function(input, output, session) {

  volumes <- reactive(paste0("~/", input$`2LevelFolder`))
  shinyFiles::shinyFileChoose(input = input, "chooseFile",
                              roots = c(chosenFolder = volumes()),
                              session = session)

  output$path <- renderPrint({
    input$chooseFile
  })
}

shinyApp(ui, server)

The problem I then ran into is, the roots is set to the the reactive volumes() only the 1st time. That is, when the shinyFilesButton ("chooseFiles") was clicked for the 1st time, the root was set correctly to whichever the 2-level subdirectory points to; however, if I changed the value selected in selectInput(), click the shinyFilesButton again, the root was not updated.
Please advise if this behavior is expected or if I've missed something. Thanks you very much!
> sessionInfo()
R version 3.6.1 (2019-07-05)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Mojave 10.14.5

Matrix products: default
BLAS:   /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] shinyFiles_0.7.3 shiny_1.3.2

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.2      crayon_1.3.4    digest_0.6.20   later_0.8.0     mime_0.7        R6_2.4.0        xtable_1.8-4
 [8] jsonlite_1.6    magrittr_1.5    pillar_1.4.2    rlang_0.4.0     rstudioapi_0.10 fs_1.3.1        promises_1.0.1
[15] tools_3.6.1     httpuv_1.5.2    compiler_3.6.1  pkgconfig_2.0.2 htmltools_0.3.6 tibble_2.1.3

A: You can do:
  shinyFiles::shinyFileChoose(input = input, "chooseFile",
                              roots = exprToFunction(c(chosenFolder = volumes())),
                              session = session)


text:
Q: AngularJS: pass parameter between controllers What i am trying to do:
I have a ListView (or rather an accordion) which contains several items (for simplicity lets assume those have a unique id and a name). For each item i want to include a link to a a detail-view to show and edit the properties (except for the id) of that item.
Googling for this returns several results like for example: Passing data between controllers in Angular JS?
and from what i understand the suggested solutions include:
ng-init: (see Can you pass parameters to an AngularJS controller on creation?)
I could initialize a parameter for each item in my List using ng-init inside of the ng-repeat. However by now the angular-documentation advise against this:

The only appropriate use of ngInit for aliasing special properties of ngRepeat, as seen in the demo below. Besides this case, you should use controllers rather than ngInit to initialize values on a scope.

service:
It is suggested to use services to share global variables between controllers. I am already doing that by using a service to hold my list of items and use calls to the service to add/delete or change the items. I also implemented a getItem(id) method which i would like to call from the controller of my detail-view. But to do that i need to know the id of the item first!
passing values via $routeParams
The Angular Phonecat Tutorial solves a similar problem by passing parameters via the $routeParams. While this would work, this means I have to include the id of my item in the link to the detail-view. A user could easily change the link and end up in a detail view for a completely different item. If possible, i would rather not expose the internal id in the link to my detail-view!

This seems like a quite common requirement. Is there any best-practice that i am missing?

A: You have two real alternatives (that you have identified):

*

*Use a service

*Pass the information as part of a url

Both are technically correct and viable but my preference from a semantic and state point of view would be to use a url.
Since you are supplying a clickable link it makes sense that you are linking to something that is linkable (i.e. an item or state that can be identified by a unique url). If you believe an open accordion item to be more an item of state (as opposed to a page) then you could look into ui-router: https://github.com/angular-ui/ui-router
I'm not sure why you are averse to having item IDs in the url. After all anyone that's interested can see any information in the UI with developer tools. If you don't want database schema information in the UI then there are various methods of ID obfuscation to address this.


text:
Q: Making domain data available to WCF behavior In my application, I have a value ("BusinessUnit") which I want to add into every request to a web-service. One way of doing this would be to write a WCF behaviour, which would insert the value for me.
However, the one part I am not clear on is how I can get this value from my application and into the behaviour.
To illustrate my question, here is how I might implement it.
public object BeforeSendRequest(ref Message request, IClientChannel channel)
{
    string businessUnit = //How do I set this to a value known by the client?
    MessageHeader<string> header =
        new MessageHeader<string>(businessUnit);
    request.Headers.Add(
        header.GetUntypedHeader("Business Unit", "http://mywebsite.com"));
}

Any ideas?

A: If this value is the same for all calls, then you can consider using a static variable for it. If it varies per call, you can use the operation context to add it (and even skipping the behavior), as shown below
ServiceClient client = new ServiceClient(...);
using (new OperationContextScope(client.InnerChannel))
{
    MessageHeader<string> header = new MessageHeader<string>(businessUnit);
    OperationContext.Current.OutgoingMessageHeaders.Add(header.GetUntypedHeader("Business Unit", "http://mywebsite.com"));
    client.MakeServiceCall();
}

If it's something that varies per group of calls, you can consider passing it to the behavior when you create the client, and then the behavior can pass it to the inspector it creates:
ServiceClient client = new ServiceClient(...);
client.Endpoint.Behaviors.Add(new MyBehavior(businessUnit));
client.MakeServiceCall1();
client.MakeServiceCall2();
client.MakeServiceCall3();


text:
Q: Apache PHP script to Start Tomcat Server in Linux I made a php script to start Tomcat Server (catalina.sh start) thats works well from command line in Linux. It was run as ROOT with a different set of ENV.
However, I would like to do the same from the Web, Please note due to security issues, this script would only be accesible via localhost (for administration only), so we ironed out the security issue.
Problem is, Tomcat is not starting (we could confirm that from the logs, nothing was initiated). We coded lots of Echo around catalina.sh and its providing the right echo output.
Im sure theres an easier way to do this. Any Ideas?
The PHP script does the following:

*

*Changes Dir to th Tomcat Bin

*Starts Catalina.sh Script vis startup.sh

OUTPUT FROM COMMAND LINE PRINT ENV:

ORBIT_SOCKETDIR=/tmp/orbit-root
HOSTNAME=localhost.localdomain
SHELL=/bin/bash
TERM=xterm
HISTSIZE=1000
XDG_SESSION_COOKIE=c111d8f81ff89709b78252c50000000d-1338310776.433586-1797694621
GTK_RC_FILES=/etc/gtk/gtkrc:/root/.gtkrc-1.2-gnome2
WINDOWID=73400323
QTDIR=/usr/lib/qt-3.3
QTINC=/usr/lib/qt-3.3/include
USER=root
LS_COLORS=rs=0:di=01;34:ln=01;36:mh=00:pi=40;33:so=01;35:do=01;35:bd=40;33;01:cd=40;33;01:or=40;31;01:mi=01;05;37;41:su=37;41:sg=30;43:ca=30;41:tw=30;42:ow=34;42:st=37;44:ex=01;32:*.tar=01;31:*.tgz=01;31:*.arj=01;31:*.taz=01;31:*.lzh=01;31:*.lzma=01;31:*.tlz=01;31:*.txz=01;31:*.zip=01;31:*.z=01;31:*.Z=01;31:*.dz=01;31:*.gz=01;31:*.lz=01;31:*.xz=01;31:*.bz2=01;31:*.tbz=01;31:*.tbz2=01;31:*.bz=01;31:*.tz=01;31:*.deb=01;31:*.rpm=01;31:*.jar=01;31:*.rar=01;31:*.ace=01;31:*.zoo=01;31:*.cpio=01;31:*.7z=01;31:*.rz=01;31:*.jpg=01;35:*.jpeg=01;35:*.gif=01;35:*.bmp=01;35:*.pbm=01;35:*.pgm=01;35:*.ppm=01;35:*.tga=01;35:*.xbm=01;35:*.xpm=01;35:*.tif=01;35:*.tiff=01;35:*.png=01;35:*.svg=01;35:*.svgz=01;35:*.mng=01;35:*.pcx=01;35:*.mov=01;35:*.mpg=01;35:*.mpeg=01;35:*.m2v=01;35:*.mkv=01;35:*.ogm=01;35:*.mp4=01;35:*.m4v=01;35:*.mp4v=01;35:*.vob=01;35:*.qt=01;35:*.nuv=01;35:*.wmv=01;35:*.asf=01;35:*.rm=01;35:*.rmvb=01;35:*.flc=01;35:*.avi=01;35:*.fli=01;35:*.flv=01;35:*.gl=01;35:*.dl=01;35:*.xcf=01;35:*.xwd=01;35:*.yuv=01;35:*.cgm=01;35:*.emf=01;35:*.axv=01;35:*.anx=01;35:*.ogv=01;35:*.ogx=01;35:*.aac=01;36:*.au=01;36:*.flac=01;36:*.mid=01;36:*.midi=01;36:*.mka=01;36:*.mp3=01;36:*.mpc=01;36:*.ogg=01;36:*.ra=01;36:*.wav=01;36:*.axa=01;36:*.oga=01;36:*.spx=01;36:*.xspf=01;36:
SSH_AUTH_SOCK=/tmp/keyring-bsFAQz/socket.ssh
GNOME_KEYRING_SOCKET=/tmp/keyring-bsFAQz/socket
USERNAME=root
SESSION_MANAGER=local/unix:@/tmp/.ICE-unix/1788,unix/unix:/tmp/.ICE-unix/1788
PATH=/usr/lib/qt-3.3/bin:/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin:/root/bin
MAIL=/var/spool/mail/root
DESKTOP_SESSION=gnome
PWD=/programs/tomcat/bin
GDM_KEYBOARD_LAYOUT=us
GNOME_KEYRING_PID=1779
LANG=en_US.UTF-8
GDM_LANG=en_US.UTF-8
GDMSESSION=gnome
HISTCONTROL=ignoredups
SSH_ASKPASS=/usr/libexec/openssh/gnome-ssh-askpass
SHLVL=3
HOME=/root
GNOME_DESKTOP_SESSION_ID=this-is-deprecated
LOGNAME=root
QTLIB=/usr/lib/qt-3.3/lib
DBUS_SESSION_BUS_ADDRESS=unix:abstract=/tmp/dbus-9HtQtRhCr9,guid=e1755bf07ea8a916f0a4e3f70000001c
LESSOPEN=|/usr/bin/lesspipe.sh %s
WINDOWPATH=1
DISPLAY=:0.0
G_BROKEN_FILENAMES=1
COLORTERM=gnome-terminal
XAUTHORITY=/var/run/gdm/auth-for-root-IT2DiY/database
_=/usr/bin/printenv

OUTPUT FROM APACHE PRINT ENV:

TERM=xterm
PATH=/sbin:/usr/sbin:/bin:/usr/bin
PWD=/programs/tomcat/bin
LANG=C
SHLVL=4
_=/usr/bin/printenv

A: try using exec()
exec('full path to your script')


text:
Q: Priority of kernel modules and SCHED_RR threads I have an embedded Linux platform (the Beagleboard, running Angstrom Linux) with two devices connected:

*

*a Laser range finder (Hokuyo UTM 30) connected via USB

*a custom external board connected via SPI

We have a written a Linux kernel module which is responsible for the SPI data transfer. It has an IRQ handler in which spi_async is called which in turn causes an async callback method to be called.
My C++ application consists of three threads:

*

*a main thread for data processing

*a laser polling thread

*an SPI polling thread

I am experiencing problems which seem to be caused by how the modules described above interact.

*

*When I switch off the USB device (laser range finder) I receive all SPI messages correctly (1 message every 3ms, message length divided by data rate is <1ms), independent from thread scheduling

*When I switch on the USB device and I run my program with normal thread scheduling (SCHED_OTHER, priority 0, no nice level set) about 1% of the messages is "lost" because the callback method of spi_async is running when the next IRQ occurs (I could handle this case differently in order not to loose the messages, so this is not a big issue.)

*With the USB device turned on and I run the program with SCHED_RR and

*

*priority = 10 for main thread

*priority = 10 for SPI reading thread

*priority = 4 for USB/Laser polling thread

then I am loosing 40% of the messages because the IRQ is triggered again before the spi-callback method is called! (I could still maybe find a workaround, but the problem is that I need fast response times which can no longer be reached in this case). I need to use the thread scheduling and the laser device so I am looking for a way to solve this case.
Question 1:
My assumption was that IRQ handlers and the callbacks triggered by spi_async in kernel space have higher priority than any thread running in user space (no matter if SCHED_RR or SCHED_OTHER). This would mean that turning to SCHED_RR in my application shouldn't slow down SPI transfer, but this seems very wrong. Is it?
Question 2:
How can I determine what happens here? Which debugging aids exist? (Or maybe you don't need any further information?) The main question for me is: why do I experience the problems only when the laser device is turned on. Could the USB driver consume so much time?
----- EDIT:
I have made the following observation:
The spi_async's callback calls wake_up_interruptible(&mydata->readq); (with wait_queue_head_t readq;). From the user space (my app) I call a function which results in poll_wait(file, &mydata->readq, wait); When the poll returns the user space calls read().

*

*When my application runs with SCHED_OTHER I can see that the callback method first finishes before the read() method in my kernel module is entered.

*When my application runs with SCHED_RR read is entered before exiting the callback.

This seems to proof that the priority of the user space threads is higher than the callback method's context's priority. Is there any way to change this behaviour and still have SCHED_RR for my application's threads?

A: Not all kernel thread have an RT priority. Imagine a periodically waking up thread that needs to do some background work is waking up. You don't want this thread to preemt your RT thread. So I guess your first assumption is wrong.
Based on your other questions :

*

*your main processing loop receives SPI data through a queue

*the spi processing thread feeds the main processing queue

It seems your main processing thread get in the way of the spi driver thread responsible for the spi data transfer.
Here is what happens :

*

*an IRQ is fired

*spi_async is called, which means a data transfer is queued, that will be picked up by a thread created by the spi master driver.

*spi master thread compete with your main processing thread, the laser thread, but this kernel thread has not RT priority, so it looses every time one of the RR thread is running.

What you can do is going back to normal scheduling, while playing with the various CONFIG_PREEMPT_ options. Or mess with the spi master driver, to ensure that any delayed work is queued with enough priority. Or even not queued at all.


text:
Q: Is it okay to free multiple dynamically allocated memories at once? During my school assignments, I just got curious if it really frees as I expect.
#include "stdio.h"
#include "stdlib.h"

void main(){
    int* menu1 = (int*)malloc(sizeof(int));
    int* menu2 = (int*)malloc(sizeof(int));
    int* menu3 = (int*)malloc(sizeof(int));
    int* menu4 = (int*)malloc(sizeof(int));
    int* menu5 = (int*)malloc(sizeof(int));

    free(menu1,menu2,menu3,menu4,menu5);
    system("pause");
}

It still runs in VS2017, but I'm not sure that it's freed correctly.

A: for each pointer you have, you allocated memory separately. By memory allocation, the system allocates a bit more that requested in order to safe some control information which should be used for different internal purposes and also later for deallocation.
Since each allocated memory knows only about itself and not about other allocated pieces of memory, you cannot free all together.
The function free expects only one argument (one pointer). Please see 7.22.3.3 in C standard.
GCC doesn't compile this code.

A: No.
https://linux.die.net/man/3/free
void free(void *ptr);

I code does not compile:
error: too many arguments to function 'free'
  free(menu1,menu2,menu3,menu4,menu5);

A: Your code does not compile, because the function free() expects one argument, but you passed more than that; 5 to be exact.
You could make it compile by enclosing the arguments in parentheses:
free((menu1, menu2, menu3, menu4, menu5));

This allows all the arguments to be evaluated by using the comma operator, but only the last one will be used by the function free(). That is, only menu5 will be freed, and the rest won't.
You must call free() on each argument separately to release memory appropriately:
free(menu1);
free(menu2);
...
free(menu5);

A: The code as is, will not compile:
  free(menu1,menu2,menu3,menu4,menu5); /* error: too many arguments to function 'free' */

The function free is defined in header <stdlib.h> and takes only one parameter:
void free( void* ptr );

Parameters:
 `ptr` -    pointer to the memory to deallocate

Return value:
(none)
Function deallocates the space previously allocated by malloc(), calloc(), aligned_alloc, (since C11) or realloc().
If ptr is a null pointer, the function does nothing.
References:
C11 standard (ISO/IEC 9899:2011):
7.22.3.3 The free function (p: 348)

C99 standard (ISO/IEC 9899:1999):
7.20.3.2 The free function (p: 313)

C89/C90 standard (ISO/IEC 9899:1990):
4.10.3.2 The free function

A: If this compiles you are using an olde compiler. What you are showing is a common error in C code.
What happens in this case the generated code looks something like this:
PUSH  menu5 ; which probably looks more like "menu5(SP)"
PUSH  menu4
PUSH  menu3
PUSH  menu2
PUSH  menu1
CALL _free

free () only expects one argument and it finds an argument: menu1. The extra arguments simply get ignored.
What would cause even bigger problems is to not pass enough arguments to a function. In that case the function being called would use random garbage on the stack as the argument. Something like
 fprintf (fp)

in rarely executed logging code could give you a crash.


text:
Q: Protractor: The path to the driver executable must be set by the webdriver.ie.driver I have a problem running automated tests for IE. When I'm trying to start my tests using the command: protractor myConfig.js I'm getting the following error:
> UnknownError: The path to the driver executable must be set by the
> webdriver.ie. driver system property

I already copied the IEDriver manually but I don't know how to change the webdriver.ie.driver path.

A: Try to install and/or update protractors internet explorer manager with command
webdriver-manager update --ie

Then restart protractor and it should work!


text:
Q: Reducing Redmine's memory usage - Low Hanging Fruit I am running a Redmine instance with Passenger and Nginx. With only a handful of issues in the database, Redmine consumes over 80mb of RAM.
Can anyone share tips for reducing Redmine's memory usage. The Redmine instance is used by 3 people and I am willing to sacrifice on speed.

A: There are not really and low hanging fruits. And if there were, we would've already included and activated them by default.
80 MB RSS (as opposed to virtual size which can be much more) is actually pretty good. In normal operation, it will use between 70 and 120 MB RSS per process (depending on the deployment model, rather few on passenger).
As andrea suggested, you can reduce your overall memory footprint by about one third when you use REE (Ruby Enterprise Edition, which is also free). But this saving can only achieved when you run more than one process (each requiring the above memory). REE achieves this saving by optimizing Ruby for a technique called Copy on Write, so that additional application processes take less memory.
So I'm sorry, your (hypothetical) 128 MB vServer will probably not suffice. For a small installation, you might be able to squeeze a minimal installation into 256MB, but it only starts to be anything but a complete pain in the ass at 512 MB (including database).
That's because of how Rails applications work in contrast to things like PHP. They require a running application server instance. That instance is typically able to answer one request at a time, using about the same amount of memory all the time. So your memory consumption is roughly equivalent to the number of application processes you run, independent of actual load. But if you tune your system properly, you can get quite a number of reqs/s out of one process.

A: May be i am replying very late but i got stuck in the same issue and I found a link to optimize ruby/rails memory usage, which works for me
http://community.webfaction.com/questions/2476/how-can-i-reduce-my-rubyrails-memory-usage-when-running-redmine
It may be helpful for someone else.