Postgresql function to create table with dynamic table name?

Question: Let's say I have several users, each with their own set of contacts. Users get to select which 3rd parties have access to their contacts.
I could maybe create 1 large contact table and have an 'owner' column so that I can identify which contacts belong to which users. However, I'd then need to maintain row-level permissions so that I can restrict which 3rd parties do/don't have access to specific user contacts.
Instead, I think (and I could be mistaken here) it makes more sense to have a contact table for each user, e.g.: contact_e878df81_eba1_4a61_b592_30ac7100362a. I could then manage permissions in a separate table.
To create these 'dynamic contact tables', I have the following function:
CREATE OR REPLACE FUNCTION create_contact_table(IN tbl_name text) RETURNS INT AS $$
DECLARE
    table_name text;
BEGIN
    table_name = tbl_name;
    create table IF NOT EXISTS table_name
    (
        id serial  not null
            constraint test_pkey
                primary key,
        firstname varchar not null,
        lastname varchar not null,
        age int not null,
        address varchar not null,
        email varchar not null,
        created timestamp default CURRENT_TIMESTAMP
    );
    alter table table_name
        owner to postgres;
    RETURN 1;
END ;

$$ LANGUAGE plpgsql;

When I execute the function (create_contact_table(contact_e878df81_eba1_4a61_b592_30ac7100362a), the table is created, but the name of the table is table_name...
Why is that? How can I fix it so that the table name is correct?
Comment: "*it makes more sense to have a contact table for each user*" - no, absolutely not. In fact it's a terrible idea.
Comment: No, it's better to have a single table for all owners. Row-level permissions are typically used in controlled environment with a few users at most. But... you seems to be designing an app for many simultaneous users.
Comment: You need [dynamic SQL](https://www.postgresql.org/docs/current/plpgsql-statements.html#PLPGSQL-STATEMENTS-EXECUTING-DYN)
Comment: @TheImpaler You meant table-level permissions, right?
Comment: "*I could then manage permissions in a separate table*" - you can still do that, if you want, when using row-level security policies.
Comment: @Bergi No, I meant row-level security. That is typically done by crafting a view filtering by the "current user" and forbidding access to the underlying tables.
Comment: @TheImpaler You mean one view per user, and each user gets a postgres role? I don't see how that's different from having a table per user. When you said "row-level permissions", I thought you meant [row security policies](https://www.postgresql.org/docs/current/ddl-rowsecurity.html), that are defined for a single table and actually *do* work well for many users.
Comment: @Bergi No, it's a single view in the database. However, the filtering condition in the `WHERE` clause includes a predicate with the "current user", with the form `WHERE my_table.username = CURRENT_USER`. That way, each separate account sees different rows.
Answer: You can do it only using dynamic SQL, for example:
CREATE OR REPLACE FUNCTION create_contact_table(tbl_name text)
 RETURNS boolean
 LANGUAGE plpgsql
AS $function$
declare
    v_sql text;
    t1 text;
begin

    v_sql = '
    create table %I
    (
        id serial  not null
            constraint test_pkey
                primary key,
        firstname varchar not null,
        lastname varchar not null,
        age int not null,
        address varchar not null,
        email varchar not null,
        created timestamp default CURRENT_TIMESTAMP
    );
    ';

    raise notice 'SQL:: %', v_sql;

    EXECUTE format(v_sql, tbl_name);

    return true;

END;
$function$
;


CSS changes are not reflected in Joomla website

Question: I have a site built around Joomla, It was working fine from the time it was built. But from few days back the css changes in any of the css files are not reflecting in the site. I am able to see all the other UI changes except CSS. I have cleared he cache and checked from different ISP but no result. Can anyone suggest me how to resolve this.
Thanks in advance.
Comment: Please check if your template has caching or css compression enabled. Please try also to clear your joomla and browser cache.
Comment: Try to force refresh your browser ...
http://www.wikihow.com/Force-Refresh-in-Your-Internet-Browser
Comment: Thanks for your replies Mousa and emmanuel! I tried these options but no result. Can you please suggest me any other ideas.
Comment: make sure you use the right .css file. I know joomla has a lot, also I remember something like an `override.css` file, in which you can override css from another file.
Comment: Thanks Goosebumbs! you may be right but I do not have this kind of file in my template.
Comment: Hi guys, did anyone experience this sort of problem before?
Comment: I experienced this once and it was my HOsting service that was caching my css files related question : http://stackoverflow.com/questions/20192908/joomla-3-2-working-with-css-files you can try changing the name of the css file (also in index.php of your template)
Comment: if you're using chrome, pressing `Ctrl + Shift+ R` did it for me - as others have said, chrome/etc may cache old versions of the css and hence not update it automatically/view the changes.
Answer: I think you are using a Template which uses LESS instead of CSS. If so, see if there are any folder inside "/public_html/templates/your_template/less/" exists or not.
If it exists then you have to create (if it is already not there) a css file named "custom.css"
inside "/public_html/templates/your_template/css/" folder and write your CSS code inside this file.
Joomla will pickup this "custom.css" file at last and your changes will be reflected.
Answer: Sorry for late reply but I found the answer. It is due to enabling CloudFlare in my hosting account. When I reached to my Hosting support they disabled the CloudFlare and everything started working fine and I am able to see all the CSS changes.


The weak law of large numbers from the central limit theorem.

Question: I could not derive the weak law of large numbers from the central limit theorem for i.i.d. random variables with $0 < \operatorname{Var}(X) < \infty$.
The central limit theorem gives
$$\frac{\sum X_i - n\cdot E(X_1)}{\sqrt{\operatorname{Var}(X_i)n})} \to N(0,1)$$
Now I want to show
$$\lim P\left(\middle|\frac{\sum X_i - E(X_1)}{n}\middle| \geq \epsilon\right) = 0 \quad\forall \epsilon>0$$
I know that the cdf converges pointwise. It should be really easy as it is intuitively clear that it should hold, but I can't find the correct way to write and pin it down.
Comment: One can prove the wlln [using Chebyshev's inequality](http://en.wikipedia.org/wiki/Law_of_large_numbers#Proof_using_Chebyshev.27s_inequality), and one doesn't need any nontrivial information about the shape of the distribution.
Comment: Yes. But it is asked for how to derive it from the much stronger central limit theorem..
Comment: I understand the question. What I don't understand is why the CLT should be of much use here.
Answer: For every positive $t$, consider the events $A_n^t=[|S_n-nE[X]|\geqslant t\sqrt{n\mathrm{var}(X)}]$ and $B_n^t=[|S_n-nE[X]|\geqslant nt]$. Then:

The CLT says that $P[A_n^t]\to P[|Z|\geqslant t]$ when $n\to\infty$, for every positive $t$, where $Z$ is standard normal.
The WLLN says that $P[B_n^t]\to0$ when $n\to\infty$, for every positive $t$.
For every positive $t$ and $s$, there exists some finite $N$ such that $B_n^t\subseteq A_n^s$ for every $n$ large enough (can you show this?).

With these elementary facts in mind, assume that 1. holds, that is, that the CLT is valid and consider some positive $t$ and $\varepsilon$. Then:

There exists some finite $s$ such that $P[|Z|\geqslant s]\leqslant\varepsilon$.
By 1., this implies that $P[A_n^s]\leqslant2\varepsilon$ for every $n$ large enough, say $n\geqslant N_1$.
By 3., $P[B_n^t]\leqslant P[A_n^s]$ for every $n$ large enough, say $n\geqslant N_2$.

Thus, for every $n\geqslant\max(N_1,N_2)$, $P[B_n^t]\leqslant2\varepsilon$. Since $\varepsilon$ is arbitrary, this is the WLLN.


Installing 3 Gang Smart Switch

Question: I am installing 3 Kasa Tp link smart switches in one box. After installing, two fixtures work and one fixture just blinks on and off constantly. Original installation had a dimmer on this switch with only two black lines coming out of the dimmer. I swapped a kasa smart dimmer and a regular smart switch and they both have that blinking problem while the other two switches work fine.
I will attach a very rudimentary drawing lol. Since originally the line going to the dining room light didn't have a neutral I just tied in with the neutral line on the other lines.
Thank you everyone for any help.
Answer: You can't do that
The dining room, and kitchen, circuits are old-school switch loops.  They only bring always-hot and switched-hot to the box.
You are poaching neutral from a different cable potentially on a different circuit or even different phase.  Can't do it.
You can't attach the smart-switch wires to anything except wires in that same cable.  All related wires must be in the same cable or conduit, NEC 300.3.  There are several reasons, but one relates to the current imbalance it causes, resulting in EMFs not canceling each other out as they normally would.
That means you will need to either go with a different smart switch, or use a smart module up at the lamp itself if power enters there.
As far as the blinking problem, it might be tangled up in this, but it might also be a problem of the light or bulb not being dimmer-ready. Try swapping an old-school incandescent in there and see if that fixes it; if so it's the bulb.
Comment: Thank you for your response. All of the lines in that box are on the same circuit. I also made sure I put a dimmable bulb in the fixture. I have to look into EMF's - that's all new to me lol. I just thought it would be ok to piggy back in the other neutrals.

Most likely will just replace all 3 switches with a smart switch that does not require a neutral.
Comment: So I got a dimmer that doesn't require a neutral. Installed that. And now the kitchen light is blinking. I am so confused. The kitchen light has been working until I went to put it in that dimmer.
Comment: @ArthurTobin It's possible that LED won't play nice with any dimmer, and will need to be changed to one that does.

Installing 3 Gang Smart Switch


How to use final variable within forEach method

Question: final List<String> categoryCodeProductTypes = new ArrayList<>();
List<Uda> uda4 = udas.stream()
                     .filter(a -> a.getCode().equals(Uda_Code))
                     .collect(Collectors.toList());
uda4.stream()
    .forEach(a -> {
                   final String categoryCodeProductType = "";
                   categoryCodeProductTypes.add(categoryCodeProductType);
                   a.getReferences()
                    .stream()
                    .forEach(b -> {
                                   categoryCodeProductType = categoryCodeProductType.concat(b.getCode());
                                  });
                  });
return categoryCodeProductTypes;

I get error in categoryCodeProductType = categoryCodeProductType.concat(b.getCode()); saying remove final keyword but I can't. Is there any other way we can fix this?
Comment: Why can't you remove the `final` keyword?
Comment: Ada and Dave, variables used inside a closure in Java must be effectively `final`. I'm guessing OP tried without the `final` keyword, saw an error that said "This variable must be `final`", and rolled with it without understanding what the `final` keyword does.
Comment: Use a different variable? Don't use a string, rather a string buffer (or whatever the current string buffer-y hotness is in Java these days)?
Comment: I'm struggling to understand the nature of this question: if it's your code, why can't you remove it? If it's not, is it some sort of pop quiz? (Hint: they say it's always the red wire but it isn't.)
Comment: Not exactly a duplicate, but read [Variable used in lambda expression should be final or effectively final](https://stackoverflow.com/questions/34865383/variable-used-in-lambda-expression-should-be-final-or-effectively-final). The concept is explained, some answers have workarounds as well.
Comment: @Ada if i remove final i will get error categoryCodeProductTypes.add(categoryCodeProductType); asking for initialize the variable.
Comment: also i will get error in  categoryCodeProductType.concat(b.getCode()); this line saying the variable must be final
Answer: You can't reassign a final variable. And you can only use effectively-final variables (that is, final variables or those that could've been declared as such) inside of closures. So if you want to mutate a string inside of a closure, you'll need to use a mutable string type like StringBuilder.
final StringBuilder myStringBuilder = new StringBuilder();
someStream.forEach(value -> {
    myStringBuilder.append(value.getCode());
});
final String result = myStringBuilder.toString();

We never actually reassign the variable myStringBuilder, so it can still be final. But we can mutate it in-place. This is also more efficient than continually allocating new strings for concatenation, as StringBuilder will use a mutable buffer internally and save on copying.
Comment: @MohammedMuntazim `myStringBuilder().toString()` can be invoked at any time to get the current String value in that builder.
Comment: if i am using StringBuilder i cant use add() .that is the problem here
Answer: Class Uda has method getReferences which returns something that can be streamed, for example some kind of collection.
You want to concatenate the code of each element (in the collection returned by method getReferences) into a single string and then you want to collect all those strings into a List.
If the above summary is correct, then consider the below [uncompiled and untested] code:
uda4.stream()
    .map(a -> a.getReferences()
               .stream()
               .map(b -> b.getCode())
               .collect(Collectors.joining()))
    .collect(Collectors.toList());

Basically, the map method returns a stream of strings where each string is the concatenation of all the codes in the collection returned by method getReferences. All that remains is to collect all the strings, that the map method produces, to a List.
Note that I cannot compile nor test the above code as you did not provide a reproducible example.
Answer: You adding categoryCodeProductTypes.add(categoryCodeProductType);
And two lines below you are loosing ability to modify this object by reassigning attempt.
Dont use .forEach instead of iterator with no reason. You will see for yourself why this code is inappropriate by results it will produce.
That's closest to your approach:
    class Main {

    @Getter
    static class A {
        List references;
    }

    @Getter
    static class B {
        String code;
    }

    public static void main(String[] args) {
        final List<StringBuilder> categoryCodeProductTypes = new ArrayList<>();
        var uda4 = List.of(new A());
        uda4.forEach(a -> {
            final StringBuilder builder = new StringBuilder();
            categoryCodeProductTypes.add(builder);
            a.getReferences().forEach(b -> builder.append(b.getCode()));
        });
        List<String> result = categoryCodeProductTypes.stream().map(StringBuilder::toString).toList();
    }
}

It's not the best way of mapping the data. Converting into intermediate controlled objects piece by piece is much better than trying to do it on the fly at one time.


How to compile jade mixin to javascript to be used in client

Question: I have some mixins needed by both server and client(dynamic rendering). I'm using Express, Grunt, if that's of any interest.
Just for example, see the following mixin:
mixin book(data)
  .header data.title
  .description data.description

The documentation says we could pre-compile jade template to javascript. But jade --client --no-debug book.jade just gives the following output:
function template(locals) {
  var buf = [];
  var jade_mixins = {};
  var jade_interp;

  ;return buf.join("");
}

It's quite confused. I'v found that some others met the same problem, but no solution or even futher explanation is given.

how to using jade Mixin in Javascript?
How to use jade mixins on client side
Compile mixin to JS in JADE

So, is it really possible to share mixins between server and client? If possible, how?
Answer: This seemed to work:
mixins/userItem.jade
mixin userItem(user)
    .user= user.name

+userItem(user)

That way your template gets compiled correctly using jade --client --no-debug mixins/userItem.jade.
This will work like expected. template({ user: { name: 'foo' }) returns
foo

AND you can also use your mixin in you server-side rendering:
users.jade
include ./mixins/userItem

extends layout

block content
    each user in users
        +userItem(user)

server.js
render('users', { users: [{ name: 'foo' }] });

Comment: what if we get the `users` by AJAX?


Weird behaviour (bug?) in car::bcPower

Question: Consider the dataset Kort:
structure(list(V1 = c(-0.03, 0.22, -0.11, -0.01, 0.25, 0.29,
-0.74, 0.23, 0.39, -0.04, 0.18, 0.19, 0.4, 0.21, 0.21, -0.01,
-0.05, 0.02, -0.12, 0.37, -0.07, 0.51, 0.39, 0.14, 0.02, 0.73,
-0.25, 0.44, 0.29), V2 = c(35.39, 34.33, 32.74, 34.72, 33.07,
30.9, 29.89, 31.17, 31.62, 33.13, 30.64, 33.31, 33.61, 34.16,
30.06, 30.06, 31.18, 25.57, 30.52, 32.43, 31.54, 29.6, 34.66,
31.74, 27.22, 41, 32.02, 37.96, 29.25), V3 = c(37.24, 36.77,
37.21, 41.16, 40.3, 42.16, 40.77, 39.59, 37, 38.32, 34.6, 38.1,
36.07, 39.2, 36.97, 38.28, 38.72, 46.81, 39.63, 36, 45.33, 38.72,
36.2, 40.94, 37.7, 42.44, 37.92, 39.87, 37.15), V4 = c(-36L,
-18L, -2L, 20L, 37L, 39L, -7L, 31L, -23L, 32L, 73L, 10L, 14L,
18L, 126L, 98L, 13L, 14L, 15L, 37L, 66L, 3L, -50L, 9L, 6L, -20L,
4L, -26L, -2L), V5 = c(12.4, 10.5, 2.8, 9.5, 9.4, 10.7, 7.5,
14.8, 10.9, 13.5, 11.5, 11.8, 13.6, 8.6, 13.6, 13.1, 14.3, 11.3,
16.1, 14.5, 8.4, 15.4, 13.4, 14, 18.8, 17.4, 16.4, 16, 17.7),
    V6 = c(27424L, 25597L, 20968L, 24730L, 25423L, 25801L, 23681L,
    29527L, 26228L, 28262L, 27363L, 27134L, 27542L, 24647L, 28260L,
    27922L, 29054L, 25650L, 30096L, 29103L, 24112L, 30035L, 28771L,
    27818L, 32455L, 29722L, 30508L, 29896L, 31961L), V7 = c(68.8,
    70.4, 61.6, 73.5, 71.8, 76.5, 72.7, 75.3, 71.7, 75, 72.9,
    73.3, 73.7, 69, 72.7, 74.2, 73.4, 71.2, 76.4, 73, 62.5, 76,
    73.7, 74.7, 74.3, 74.8, 74.6, 74.4, 74.4), V8 = c(8.1, 6.8,
    11, 5.3, 6.3, 4.1, 5.5, 4, 5.9, 4.3, 5.5, 5.4, 4.2, 8.1,
    5.2, 4.8, 4.4, 8.2, 3.8, 5.9, 12.9, 4.3, 5.2, 5, 3.6, 3.8,
    4.6, 4.3, 4.5), V9 = c(0.38, 0.15, 0.16, 0.08, 0.12, 0.05,
    0.07, 0.04, 0.08, 0.07, 0.13, 0.08, 0.08, 0.26, 0.05, 0.14,
    0.05, 0.26, 0.03, 0.18, 0.26, 0.04, 0.04, 0.14, 0.05, 0,
    0.02, 0.02, 0.1), V10 = c(9.8, 9.9, 19.4, 7, 9.2, 3, 8.5,
    1.1, 3, 2.3, 5.1, 5.6, 1, 22.3, 4.4, 6.2, 2.2, 5.3, 1.5,
    5, 18.7, 1.5, 3, 8.9, 1.6, 0, 5.1, 2.1, 3.6), V11 = c(6.3,
    7.5, 5.5, 10.2, 5, 9.6, 9.3, 4.8, 4.3, 4.6, 4.1, 5.7, 6.4,
    4, 7.2, 4.7, 4.2, 4.5, 7.6, 5.3, 6.2, 4.1, 4.9, 4.1, 5.1,
    3.3, 5.4, 5, 5.6), V12 = c(153605L, 152867L, 115972L, 140341L,
    139245L, 167038L, 143239L, 179712L, 135273L, 167487L, 160738L,
    160648L, 154717L, 118800L, 168954L, 148412L, 147637L, 142615L,
    210838L, 161840L, 114310L, 182670L, 160293L, 147747L, 192889L,
    191077L, 164107L, 202051L, 192945L)), .Names = c("V1", "V2",
"V3", "V4", "V5", "V6", "V7", "V8", "V9", "V10", "V11", "V12"
), class = "data.frame", row.names = c(NA, -29L))

Where the response is:
Kort$V12
 [1] 153605 152867 115972 140341 139245 167038 143239 179712 135273 167487
[11] 160738 160648 154717 118800 168954 148412 147637 142615 210838 161840
[21] 114310 182670 160293 147747 192889 191077 164107 202051 192945

Doing a box-cox transform, using car::boxcox
boxcox(V12~.,data=Kort,lambda=seq(-4,4,4/10))

yields an optimal parameter of -2. Transforming the response using
car::bcPower
TVP<-bcPower(Kort$V12,lambda=-2)

turns TVP into a vector of constants:
TVP
 [1] 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5
[20] 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5 0.5

but box cox transform should be a continuous map!
Answer: I don't think this is a bug, there's simply a limit to how many decimal places are printed out. The help file suggests that the calculation is (U^(lambda)-1)/lambda which is pretty close to 1/2 where U is large. You can see that TVP is being calculated correctly with
TVP-0.5
# [1] -2.119138e-11 -2.139650e-11 -3.717610e-11 ...

or
options(digits=20)
TVP
# [1] 0.49999999997880861802 0.49999999997860350431 0.49999999996282390446 ...

Weird behaviour (bug?) in car::bcPower


Is Desktop Sharing possible in Gnome 22.04? (With screen locking and disconnecting the screen)

Question: I'd like to be able to login to my remote Ubuntu 22.04 and see the Desktop as shown on that machine. (I know how to create a vncserver with a separate desktop instance).
Built-in Remote Desktop
When I try with the built-in Remote Desktop

it works as long as the user is logged in, the screen isn't locked, and there is a physical screen attached. Requiring the user to be logged in is fine for me, but screen not locked means I can't login remotely after a while, and the "physical screen attached" requirement means I it only works when my KVM switch has the Ubuntu machine active, which also doesn't work for me.
Otherwise I get one of these error messages:
Failed to record monitor: GDBus.Error:org.freedesktop.DBus.Error.Failed: Unknown monitor

Failed to start remote desktop session: GDBus.Error:org.freedesktop.DBus.Error.AccessDenied: Session creation inhibited

But I want to be able to log in and see my desktop when the screen is locked and the monitor disconnected (due to the KVM).
The screen locked situation can be handled by this gnome extension: Allow Locked Remote Desktop - GNOME Shell Extensions, so now only the monitor disconnected issue remains, and for that, I've posted this issue: Failed to record monitor: GDBus.Error:org.freedesktop.DBus.Error.Failed: Unknown Monitor (using KVM switch) (#171) · Issues · GNOME / gnome-remote-desktop · GitLab.
x11vnc and x0vncserver
So I tried with x11vnc and x0vncserver. And they have different problems as outlined in: Why do both x11vnc and x0vncserver fail in similar ways in Gnome Ubuntu 22.04?
The real question
But this question is: Is there any easy way to get sharing of the "real" desktop with Gnome under 22.04 that works even if the screen locks and/or the monitor gets disconnected due to the KVM switch, ideally under Wayland (since that is where we're heading).
Is the situation better in future Ubuntu releases?
What about xrdp?
xrdp won't work for me, because as I state in the very first sentence:

...and see the Desktop as shown on that machine

xrdp only works if the user is not logged in locally (which I always am).
Related questions
These questions don't address my requirements of seeing the local already-logged-in desktop and that works with the monitor being disconnected due to the KVM switch:

Maintaining RDP connection to Ubuntu after Ubuntu Screen times out (goes black) Here the solution is to install "Allow Locked Remote Desktop" which I already mention. It doesn't tackle the "physical screen attached" requirement.
Connect when Remote Desktop is on login screen or screen locked (without autologin) Here the answer is either "Allow Locked Remote Desktop" or xrdp (both covered above).
Ubuntu 22.04 remote desktop headless? Answer suggests using xrdp (covered above).
Comment: Does this answer your question? [Maintaining RDP connection to Ubuntu after Ubuntu Screen times out (goes black)](https://askubuntu.com/questions/1453957/maintaining-rdp-connection-to-ubuntu-after-ubuntu-screen-times-out-goes-black)
Comment: Also see the [Original answer section](https://askubuntu.com/questions/1411504/connect-when-remote-desktop-is-on-login-screen-or-screen-locked-without-autolog/1428784#1428784) of this question.
Comment: See [Ubuntu 22.04 remote desktop headless?](https://askubuntu.com/questions/1407444/ubuntu-22-04-remote-desktop-headless)
Comment: @user68186: I have now explicitly listed these quesions and answers and why they don't address my needs.
Comment: This answered my misgivings, so I retracted my vote to close this question as a duplicate.
Answer: So "Built-in Remote Desktop" does not have support for when the monitor is disconnected (see issue#171 that I mentioned above).
And it turns out that the x11vnc and x0vncserver issues are also about the disconnected monitor.
I plan on working around this problem with an EDID Emulator. I've ordered this one. It hopefully lets the computer think the display is still attached. And then next time I update the KVM switch, get one with a built-in EDID emulator. I'll try to remember to update this thread when the EDID emulator arrives and I've tried it out.
That should allow me to use both the built in remote desktop and x11vnc and x0vncserver. We'll see...
Comment: Please comment to me with @karel here if you update this thread when the EDID emulator arrives and you've tried it out.


Advanced Wars - Change Main (Assistant) Name

Question: In Advanced Wars there is the main guy (you) not the COs but they refer to you as an assistant. You set this when you first buy the game. I've bought this game used and now everybody is calling me TOM. Can I change this somehow?
Answer: I don't think you can do it without restarting your whole game.  However, if you press L + Select + Right directly after turning on your GBA, the delete data option shows up allowing you to delete the data.
GameFAQs Advance Wars cheats
Comment: This is the only way. I bought my copy used and *hated* the name the previous owner used. I now have a piece of paper taped to the back of the cartridge with this key combination.


How to open a apple maps application with directions from my ios application

Question: My aim is to open a map application from ios application with directions, I am able to open maps application but it is not showing directions, i have written the code as follows
 NSString *mystr=[[NSString alloc] initWithFormat:@"http://maps.apple.com/maps?saddr=Current+Location&daddr=Newyork"];
            NSURL *myurl=[[NSURL alloc] initWithString:mystr];
            [[UIApplication sharedApplication] openURL:myurl];

Can any one please help me how figure out how to pass parameters to this url and any other?
Comment: please look at this link http://stackoverflow.com/questions/7605879/iphone-app-show-direction-using-map
Answer: CLLocationCoordinate2D coordinate =    CLLocationCoordinate2DMake(self.location.latitude,self.location.longitude);

//create MKMapItem out of coordinates
MKPlacemark* placeMark = [[MKPlacemark alloc] initWithCoordinate:coordinate addressDictionary:nil];
MKMapItem* destination =  [[MKMapItem alloc] initWithPlacemark:placeMark];
if([destination respondsToSelector:@selector(openInMapsWithLaunchOptions:)])
{
    //using iOS6 native maps app
    if(_mode == 1)
    {
        [destination openInMapsWithLaunchOptions:@{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeWalking}];

    }
    if(_mode == 2)
    {
        [destination openInMapsWithLaunchOptions:@{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeDriving}];

    }
    if(_mode == 3)
    {
        [destination openInMapsWithLaunchOptions:@{MKLaunchOptionsDirectionsModeKey:MKLaunchOptionsDirectionsModeTransit}];

    }

} else{

    //using iOS 5 which has the Google Maps application
    NSString* url = [NSString stringWithFormat: @"http://maps.google.com/maps?saddr=Current+Location&daddr=%f,%f", self.location.latitude, self.location.longitude];
    [[UIApplication sharedApplication] openURL: [NSURL URLWithString: url]];
}

Comment: Where is the `_mode` variable coming from?
Comment: Your own variable to choose what you want :)
Answer: If you mean taking the user to the maps application based on two points, then you can do it like this:
Create an NSURL that looks like this:
NSURL *URL = [NSURL URLWithString:@"http://maps.google.com/maps?saddr=%f,%f&daddr=%f,%f"];

You plug in your starting address and destination (in lat. and long.) appropriately.
Tell your application to open the URL
[[UIApplication sharedApplication] openURL:URL];

It should take you to the maps application automatically!


Android raw query problem

Question: I have a database which has a column of dates in milliseconds. I'm trying to perform a query which allows me to retrieve only the dates that are greater than the current system time and in ascending order.
This is what I have done, but it doesn't seem to work, help would be most appreciative.
<code>    long lowestDate = 0;
    long currentTime = System.currentTimeMillis();
    String CT = Long.toString(currentTime);
    String[] args = {CT};
    mDb = mDbHelper.getReadableDatabase();
    String mySQL =   " select dt"
                   + " from reminders"
                   + " where dt > " + args[0]
                   + " orderby dt Asc ";
    Cursor c1 = mDb.rawQuery(mySQL, null);
</code>
Comment: In what way doesn't it work? Is it crashing, are you getting an error message, is the result not what you expect?
Answer: <code>String mySQL =   " select dt"
                   + " from reminders"
                   + " where dt > " + System.currentTimeMillis()
                   + " order by dt Asc ";
</code>
"Order by" not "orderby",  long to string cast is automatic.
Answer: <code> long lowestDate = 0;
    long currentTime = System.currentTimeMillis();
    String CT = Long.toString(currentTime);
    String[] args = {CT};
    mDb = mDbHelper.getReadableDatabase();
    String mySQL =   " select dt"
                   + " from reminders"
                   + " where dt > '" + args[0]
                   + "' orderby dt Asc ";
    Cursor c1 = mDb.rawQuery(mySQL, null);
</code>
try this
Answer: Try
<code> String mySQL =   "select dt"
                       + " from reminders"
                       + " where dt > '" + args[0]
                       + "' orderby dt Asc";
</code>

Android raw query problem


Change column layout on mobile

Question: I have a nav menu that consists of 3 columns each 33% wide. On mobile I want each column to be 100% wide AND rearrange the columns so that the middle column sits above all other columns.
Its much easier to see what I am trying to achieve by viewing the below example. Do you know how I could rearrange the middle column so it sits above all other columns when the screen width is <500px? If there is a css solution that would be great, I believe I could achieve this in Javascript easily I'd just prefer CSS2/CSS3 ideas if its possible.

.col-1 {
  background-color: #eee;
  text-align: center;
}
.col-2 {
  background-color: #ccc;
  text-align: center;
}
.col-3 {
  background-color: #aaa;
  text-align: center;
}
.title {
  text-align: center;
  margin-top: 75px;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pure/2.0.3/pure-min.css">
<link rel="stylesheet" href="https://email@example.com/build/grids-responsive-min.css">

Desktop Look

Link

Link

        Brand

Link

Link

Desired Mobile Look

        Brand

Link

Link

Link

Link

Answer: You can use order property on flex items depending on device size.
here I have used order: -1; on .col-2 .
Browser compatibility

.col-1 {
  background-color: #eee;
  text-align: center;
}

.col-2 {
  background-color: #ccc;
  text-align: center;
  order: -1;
}

.col-3 {
  background-color: #aaa;
  text-align: center;
}

.title {
  text-align: center;
  margin-top: 75px;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pure/2.0.3/pure-min.css">
<link rel="stylesheet" href="https://email@example.com/build/grids-responsive-min.css">

Desktop Look

Link

Link

        Brand

Link

Link

Comment: thanks, do you know if flex and order are CSS2 or CSS3?
Comment: as far as I know they belongs to CSS 3
Answer: This can be done using order
I have created a separate class and added css code to it, since its not a good practice to write css on default purecss code.

.col-1 {
  background-color: #eee;
  text-align: center;
}

.col-2 {
  background-color: #ccc;
  text-align: center;
}

.col-3 {
  background-color: #aaa;
  text-align: center;
}

.title {
  text-align: center;
  margin-top: 75px;
}

@media(max-width: 768px) {
  .top_menu {
    display: flex;

  }
  .top_menu-middle {
    order: 0;
  }
  .top_menu-left {
    order: 1;
  }
  .top_menu-right {
    order: 2;
  }
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pure/2.0.3/pure-min.css">
<link rel="stylesheet" href="https://firstname.lastname@example.com/build/grids-responsive-min.css">

Desktop Look

Link

Link

      Brand

Link

Link

Desired Mobile Look

      Brand

Link

Link

Link

Link

Answer:
On mobile I want each column to be 100% wide

You simply need to update css from:

 ...

 ...

 ...

To:

 ...

 ...

 ...

Now, the elements within this grid will be width: 100% on small screens, but will shrink to become width: 33.33% on medium-sized screens and above.

AND rearrange the columns so that the middle column sits above all other columns.

For you can use order on .col-2 column like:
@media screen and (max-width: 767px) {
  .col-2 {
    order: -1;
  }
}

Working Demo:

.col-1 {
  background-color: #eee;
  text-align: center;
}
.col-2 {
  background-color: #ccc;
  text-align: center;
}
@media screen and (max-width: 767px) {
  .col-2 {
    order: -1;
  }
}

.col-3 {
  background-color: #aaa;
  text-align: center;
}
.title {
  text-align: center;
  margin-top: 75px;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pure/2.0.3/pure-min.css">
<link rel="stylesheet" href="https://email@example.com/build/grids-responsive-min.css">

Desktop Look

Link

Link

        Brand

Link

Link

Desired Mobile Look

        Brand

Link

Link

Link

Link

Answer: You can use a media query to set the width and order of the flex items.

.col-1 {
  background-color: #eee;
  text-align: center;
}
.col-2 {
  background-color: #ccc;
  text-align: center;
}
.col-3 {
  background-color: #aaa;
  text-align: center;
}
.title {
  text-align: center;
  margin-top: 75px;
}

@media only screen and (max-width: 500px) {
  /* Using specificity to force 100% width */
  .col-1.pure-u-1-3, .col-2.pure-u-1-3, .col-3.pure-u-1-3 {
    width: 100%;
  }
  .col-1 {
    order: 2;
  }
  .col-2 {
    order: 1;
  }
  .col-3 {
    order: 3;
  }
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pure/2.0.3/pure-min.css">
<link rel="stylesheet" href="https://firstname.lastname@example.com/build/grids-responsive-min.css">

Desktop Look

Link

Link

        Brand

Link

Link

Change column layout on mobile


Failed to open VScode within Samba Share

Question: In my Ubuntu system: Linux aldebaran 5.8.0-50-generic #56~20.04.1-Ubuntu SMP Mon Apr 12 21:46:35 UTC 2021 x86_64 x86_64 x86_64 GNU/Linux
Normally I go to the directory where the C++ source is located and start VS Code with
user-prompt> code .

On locally stored projects this works fine.
But not within a mounted cifs volume from my NAS. I immediately get:
cannot stat path of the current working directory: Permission denied

The directory is perfectly readable or writable by all other commands and bash scripts, but only VS Code has problems.
Starting with "sudo" make no difference. Same error.
Any idea ?
Answer: It is probably because you installed a snap version of vscode.
uninstall vscode with :
sudo snap remove code

and try installing it with the deb package on https://code.visualstudio.com/
using :
sudo apt install ./VS_CODE_FILENAME.deb

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: code \\YOUR_SERVER_IP\Folder_Name

or
open vscode -> file -> open folder -> \\YOUR_SERVER_IP\Folder_Name
Refer to the image reference.
enter image description here
enter image description here
Comment: Why should this work ? And the other way around not ? I will try tomorrow, but even if it runs this way it leaves questions.
Comment: Using the full path from \\servername\path\to\mount seems to work for me. The network mount (V:\ for me) was giving me "file is a directory". This seems like a bug in either windows or VSCode because I would expect these to work exactly the same but... it worked for me.
Comment: Further update: this still has bugs when trying to rename a file it's complaining about being unable to create the parent directory (which... it doesn't need to do I'm just trying to rename the child file) so I'm abandoning trying to use VSCode with samba.
Comment: Did you run it with administrator privileges?
Have you ever created a folder in File Explorer after connecting to Samba?
Did you log in to the root account and proceed with the Samba ID/password?
I think the remote area lacks authority.


Is the SO tag ordering a good representation of programming language popularity?

Question: Is the SO tag ordering a good representation of programming language popularity?
My first guess would be that it's not and that it's largely populated by fans of Jeff (who would probably be .Net biased) and fans of Joel (who may be more C/C++ biased among others).
Is there a way to get unbiased programming language popularity stats?
Comment: "unbiased programming language popularity stats" would rather depend on your definitions of unbiased, language, programming and popularity, to point at four nouns that may be open to interpretation. :)
Comment: How do you rate popularity of a programming language anyway?.. Amount of developers who like the language, amount of jobs available in the field..

That said no SO is most likely not a particularly unbiased source for that information.
Comment: Duplicate of quite a few questions including http://stackoverflow.com/questions/499331
Comment: I'm voting to close this question as off-topic because this question is arguably more appropriate for Meta.
Answer: I'm the creator of LangPop.com, which measures a number of metrics to try and gauge popularity.  My philosophy is to simply try and measure a lot of different things and let people see the results, and judge for themselves.  All of the metrics have flaws, biases and advantages, too.
In terms of SO tags, besides C#, they look fairly accurate, but there's a huge C# bias, so for the time being I don't think I will include SO in the LangPop results.  I am keeping an eye on it, though.  Another example of something I'm keeping my eye on, but that is still way too biased is GitHub, which has a huge number of Ruby projects.
Answer: Stackoverflow is an extremely biased sample, and the tags counts may further distort the figures. Because Joel Spolsky is a primary marketing tool for SO, and he favors Microsoft technology, it's greatly over-represented here. The bias is then amplified as people interested in other platforms sense that this site isn't for them and stop participating.
The Tiobe survey is widely cited as a means of gauging language popularity. Like any survey, it has flaws, but at least it was intended for the purpose of measuring popularity.
Answer: There are two good sites that track these sorts of things...
LangPop
TIOBE
Although I wish they showed C# right up there with Java, I'm not that surprised that most places are still using Java, or people are searching for Java, or there are lots of Java jobs. I don't have any particular reason to think they are being unfairly biased.
Answer: It may not be a good representation, apart form the reason you have posted, it would also be that certain techonolgies are new and there is very little help available elsewhere and would end up more on SO.
Certain techonologies are quite stable and hence hence the questions would be less, you would always have expert nearby, or some dedicated communities/forum sites like the ones for Oracle or Microsoft products.
Answer: I would expect that SO tag ordering is a very, very rough guide to language popularity.  Figure +/- a factor or 2 or 3, the tags with large numbers on them may reflect general reality.  The tags with smaller numbers, however, may be more fully represented in other arenas.
Once a forum starts show a preference, people will be attracted to that forum more or less depending on how that preference matches their.  Thus, there's a selection effect in addition to the ones you mentioned.  There are many places to find help, but some languages have better resources preexisting on the network.
It is truly difficult to get unbiased programming language popularity stats.  I suppose you could look at resumes to see what people advertise they know, but this is influenced by what they think will get someone to hire them.  You could look at jobs advertised, but this also has biases.  If people who know one language change jobs twice as often as people who know another language, then you'll see more jobs offered for the former, all other things being equal.
Answer: I think it will vary pretty heavily depending on how you define "popularity", but there probably will be no such thing as an "unbiased" representation.
Language popularity will vary greatly depending on which field/population you observe : Php is likely to be vastly used (if not neccesarily popular) by web developpers, Game developpers will probably tell you that C++ and Flash/AS are the be-all and end-all of programming, Windows developpers are probably widely adopting C# at the moment, ...
It might be possible to observe tendencies by looking ie at Job offers, Blogs, Forums, Stack Overflow, but you won't get much more than a tendency, and nothing really general enough to be of any use I think.
Answer: ohloh.net has some pretty good metrics. It reads from version control repositories for a bunch of projects and provides graphs.
Compare languages at Ohloh


SQL - SELECT Statement

Question: I have a simple SQL command that i need help with.
SELECT "01 Tickets within SLA in January: " as "Category",count(tickets.id) as "Total"     FROM tickets
  WHERE (created_at>=date('2013-01-01 00:00:00')) AND (created_at<=date('2013-01-31     23:59:00')) AND (closed_at<due_at)
union
 SELECT "02 Tickets within SLA in February: " as "Category",count(tickets.id) as "Total"     from tickets
  WHERE (created_at>=date('2013-02-01 00:00:00')) AND (created_at<=date('2013-02-31     23:59:00')) AND (closed_at<due_at)
union
  SELECT "03 Tickets within SLA in March: " as "Category",count(tickets.id) as "Total"     from tickets
  WHERE (created_at>=date('2013-03-01 00:00:00')) AND (created_at<=date('2013-03-31     23:59:00')) AND (closed_at<due_at)
union
  SELECT "04 Tickets within SLA in April: " as "Category",count(tickets.id) as "Total"     from tickets
  WHERE (created_at>=date('2013-04-01 00:00:00')) AND (created_at<=date('2013-04-31     23:59:00')) AND (closed_at<due_at)
union
  SELECT "05 Tickets within SLA in May: " as "Category",count(tickets.id) as "Total" from     tickets
  WHERE (created_at>=date('2013-05-01 00:00:00')) AND (created_at<=date('2013-05-31     23:59:00')) AND (closed_at<due_at)
union
 SELECT "06 Tickets within SLA in June: " as "Category",count(tickets.id) as "Total" from     tickets
  WHERE (created_at>=date('2013-06-01 00:00:00')) AND (created_at<=date('2013-06-31     23:59:00')) AND (closed_at<due_at)
union
  SELECT "07 Tickets within SLA in July: " as "Category",count(tickets.id) as "Total" from     tickets
  WHERE (created_at>=date('2013-07-01 00:00:00')) AND (created_at<=date('2013-07-31    23:59:00')) AND (closed_at<due_at)

 ORDER by Category

This query returns a value for each one, which is fine. However i want to return count(tickets.id) before i apply the "AND (closed_at

So it would return something like this.
Category                          Total  Total Tickets
01 Tickets within SLA in January:   131     400
02 Tickets within SLA in February:  132     500
03 Tickets within SLA in March:      87     100
04 Tickets within SLA in April:     121      99

Hope this makes sense.
Thanks
Comment: You should only need one SQL statement for this, using a GROUP BY on a  calculated month column.
Answer: Don't try and format your results in the SQL - this should be done in your presentation layer.  You can make the query MUCH simpler by simply grouping by the year and month of the date, then using this information to make your results:
SELECT YEAR(date), MONTH(date), count(tickets.id), SUM(CASE WHEN closed_at < due_at THEN 1 ELSE 0 END) as matching
from     tickets
GROUP BY YEAR(date), MONTH(date)
ORDER BY category

Comment: . . YOu need to move the `where` conditional to something like `sum(case when closed_at < due_at then 1 else 0 end)` to actually answer the question.
Answer: Here's how you count tickets matching a more specific condition while also counting total tickets:
 SELECT "01 Tickets within SLA in January: " as "Category",
        SUM(closed_at<due_at) as "Total",
        COUNT(tickets.id) as "Total Tickets"
 FROM tickets
 WHERE created_at BETWEEN '2013-01-01 00:00:00' AND '2013-01-31 23:59:00'

You can repeat this for each month, or use grouping as suggested elsewhere.
Answer: SELECT CONCAT(MONTH(created_at), ' Tickets within SLA in ', MONTHNAME(created_at)) `Category`
      ,SUM(closed_at<due_at) `Total`
      ,count(tickets.id) `Total Tickets`
  FROM tickets
 where created_at>=date('2013-01-01') AND created_at<date('2013-08-01')
 GROUP BY MONTH(created_at), MONTHNAME(created_at)
 ORDER by `Category`;

Note: For the sake of precision and sanity, it is infinitely better to use the form

WHERE ADATE >= {start} AND ADATE < {next-start}

which is absolutely unambiguous in a mathematical sense and leaves no nanoseconds prior to {next-start} left out.

SQL - SELECT Statement


After user Sign In, why Devise redirect to sign_in view instead of specified path?

Question: I have a problem with Devise redirect. By default after user sign in and sign up it will be redirect toroot_path. I want to change that path to playlists_path.
Every time I run my test, it fails and it goes to users/sign_in path, I don't' know why. I have tired different solution found on Stackoverflow and Github, but nothing works. May be the solution is obvious and I can't see it, or my test is not written well. Strangely enough sign_up_spec pass, but sign_in_spec fails every-time. I need another eye and help.
UPDATE***
Based on "sevenseacat" comments, I have updated my test below, but still get same result.
routes
Rails.application.routes.draw do
    devise_for :users
  root to: 'homes#index'
  resources :playlists, only: [:index, :new]
end

sessions#new
<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>

registrations#new
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>

Application_controller  Where Devise advice :) to change the redirect after user sign in
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
    def after_sign_in_path_for(user)
     playlists_path
    end
end

spec_helper.rb
FactoryGirl.define do
    sequence(:email) { |n| "email@example.com" }

    factory :user do
      email
      password 'password'
      password_confirmation { |u| u.password }
  end
end

spec/factories/users.rb
ENV["RAILS_ENV"] ||= 'test'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
# require 'rspec/autorun'
require 'capybara/rspec'
require 'database_cleaner'

Dir[Rails.root.join("spec/support/**/*.rb")].each { |f| require f }

ActiveRecord::Migration.check_pending! if defined?(ActiveRecord::Migration)

RSpec.configure do |config|
  config.include Capybara::DSL
  config.include FactoryGirl::Syntax::Methods
  config.include Devise::TestHelpers, type: :controller
  config.infer_base_class_for_anonymous_controllers = false
  config.order = "random"

  config.before(:suite) do
    DatabaseCleaner.strategy = :transaction
    DatabaseCleaner.clean_with(:truncation)
  end

  config.before(:each) do
    DatabaseCleaner.start
  end

  config.after(:each) do
    DatabaseCleaner.clean
  end
end

spec/features/sign_up_spec.rb This spec is good and pass
require 'spec_helper'
feature "Sign up as a user" do

  scenario "with an email address" do
    user = FactoryGirl.build(:user)
    visit root_path
    click_link "Create Account"

    fill_in "Email", with: user.email
    fill_in "Password", with: user.password
    fill_in "Password confirmation", with: user.password_confirmation
    click_button "Sign up"

    expect(current_path).to eq playlists_path
    expect(page).to have_css '.alert',          text: 'Welcome! You have signed up successfully.'
    expect(page).to have_link 'Sign out',       href: destroy_user_session_path
    expect(page).to have_link 'Edit profile',   href: edit_user_registration_path
  end
end

spec/features/sign_in_spec.rb This spec is no good and fails
require 'spec_helper'
feature "Sign in as a user" do

  scenario "with an email address and password" do
    user = FactoryGirl.create(:user)
    visit root_path
    click_link "Sign in"

    fill_in "Email", with: user.email
    fill_in "Password", with: user.password
    click_button "Sign in"

    expect(current_path).to eq playlists_path
    expect(page).to have_css '.alert',          text: 'Signed in successfully.'
    expect(page).to have_link 'Sign out',       href: destroy_user_session_path
    expect(page).to have_link 'Edit profile',   href: edit_user_registration_path
  end
end

When i run rspec spec/features/sign_in_spec.rb, it fails:
Failures:

  1) Sign in as a user with an email address and password
     Failure/Error: expect(current_path).to eq playlists_path

       expected: "/playlists"
            got: "/users/sign_in"

       (compared using ==)
     # ./spec/features/signin_spec.rb:11:in `block (2 levels) in <top (required)>'

The weird thing is, although my sign_in_spec fails but when I run the app, it works well and after Sign In and Sign Up the redirect to playlists_path
Why devise doing that weird redirect OR why my test fails?
Answer: Does that user exist in the sign in spec? Likely, you will need to create the user with that email and password in the setup for that spec.
Specs are generally run in isolation and the data is all removed between tests - if you are relying on data to be present when running a spec, you need to set it up in the spec.
Answer: By executing these operation:
bundle exec rake db:drop RAILS_ENV=test
bundle exec rake db:create RAILS_ENV=test
bundle exec rake db:schema:load RAILS_ENV=test

and change
user = FactoryGirl.create(:user)
to
user = FactoryGirl.build(:user)
my test is passed.


Ubuntu ZFS - backing up whole system before upgrading to 22.04?

Question: I have Ubuntu 20.04 with ZFS installed and I want to upgrade to 22.04.
I would very much like to avoid breaking my system, because it's important enough for it to keep running. My data is already backed up, that's not a problem, but just re-installing and setting up everything requires a lot of time to be to my liking.
How should I go about backing up whole system, and in case of breakage restoring it?

Should I use ZFS snapshots? And how?
Or should I use Clonezilla?
Something else?

Thanks
Comment: I generally use snapshots as it allows for relatively simple rollbacks when things fail. That said, I've never done a rollback of an entire LTS upgrade
Answer: For something as big as a system upgrade, I would make an image of the entire drive:

(With power off) Attach large-enough drive to system.
Boot using live USB or similar
Using "Disks" utility, create disk image on backup drive.

(I'm pretty sure it's just a front-end for dd, but it's a nice easy-to-use front end.)
Comment: I used Clonezilla to clone whole disk to USB storage.
Comment: Clonezilla is good, too.  Just so long as you have something you can go back to if things go sideways.
Answer: I use some variation of the below to back up a whole disk
dd if=/dev/sdX conv=sync,noerror status=progress bs=64k | gzip -c > backup_image.img.gz
You can use a different compression program other than gzip if you want.  You may also want to fill empty space with zeros or use sparse command in dd to make the compressions really work (you can google how to do this).  Put the backup image and copy to an external drive or non-system drive.
Just reverse the two arguments to restore (after you have unzipped your image)
dd if=path/to/backup-backup.img of=/dev/sdX


Service to service communication with authentication

Question: I am creating a service (web api) which is interacting with another service. I need to authenticate with this external service using IdentityServer.
I just wanted to confirm that for this it doesn't make sense to implement the refresh token since a webcontroller is constructed on a per request basis?
Answer: I changed the implementation to be run as a singleton to improve performance of not always having to authenticate everytime I do a call (big performance hit) therefore the token needs to be actually renewed


$\text {dom}(R)$ and $\text {ran}(R)$ exists for any definition of order pair.

Question: Suppose that we define, for any sets $x,y$, a set $(x,y)$ with the propertie that $$(x,y)=(x',y')\rightarrow x=x'\wedge y=y'(*)$$
Let $R$ be a set. I want to show that the classes $\{x:\exists y((x,y))\in R\}$ and $\{y:\exists x((x,y)\in R)\}$ exists.
My attempt:
Let $A:=\{z\in R: \exists v,w(z=(v,w))\}$ (this exists by separation axiom). Now take $\phi(z,u)\equiv\exists x,y(z=(x,y))\rightarrow u=x$.
It is easy to show that for each $z\in A$ exists an unique $u$ such that $\phi(z,u)$. So, by replacement axiom exists a set $B$ such that $\forall z\in A\exists u\in B\phi(z,u)$.
So, by separation axiom exists the set $\{x\in B:\exists z\in A\phi(z,x)\}=\{x:\exists y((x,y))\in R\}$ (In the same way we proof the existence of the another set).
My doubt is that I don't use $(*)$ or I don't see where I did. So, I don't know if my proof is right.
Edit: The only axioms that I can use are: extensionality, separation, pairing, union and replacement.
Comment: @MauroALLEGRANZA But $R$ is an arbitrary set.
Comment: So $A$ is the subset (maybe empty) of $R$ made of *pairs* ?
Comment: @MauroALLEGRANZA Yes it is
Comment: An you do not assume any "usual" def of ordered pair, like e.g. [Kuratowski's one](https://en.wikipedia.org/wiki/Ordered_pair#Defining_the_ordered_pair_using_set_theory). In which case you are assuming implicitly the axiom that : for any sets $x,y$ the *pair* $(x,y)$ exists.
Comment: @MauroALLEGRANZA The idea is to show that $dom R$ and $ran R$ can be defined independent of definition of $(x,y)$
Comment: @Gödel Let me point out that you implicitly assume (and use) that the map $\langle x, y \rangle \mapsto (x,y)$ is definable. And you have to assume that. It's not enough that for every $x,y$ $(x,y)$ exists. (You could cook up an example such that $\{ (n,n) \mid n < \omega \}$ is a real that doesn't exist in $L$, even though, for every $n < \omega$, $(n,n) \in L$.)
Comment: @StefanMesken What do you mean by $\langle x,y \rangle$? Is it a particular definition of order pair?
Comment: @Gödel Let's just say it's the Kuratowski pairing of $x,y$ (it doesn't really matter but since you used $(,)$ for your new pairing, I needed to distinguish them). To put it in other words: You need that there is a paramater free formula $\phi$ such that $(x,y) = z \iff \phi(x,y,z)$ is provable in your background theory.
Comment: Then, you suggest to me drop this construction? @StefanMesken
Comment: @Gödel No, I just think you should be aware of this implicit additional assumption.
Comment: @StefanMesken If I´m fine, the only tool that I need to justify the "additional assumption" is pair, separation and  replacement axioms. It is right?
Answer: Definition. Let $x$ and $y$ be sets. The ordered pair $x$ comma $y$, denoted $(x,y)$, is $\rule{50pt}{0.4pt}$.
Here $\rule{50pt}{0.4pt}$ represents any definition used.
Remark. Let $x$, $y$, $u$, $v$ be sets. Then $(x,y)=(u,v)$ if and only if $x=u$ and $y=v$.
Here it is assumed that the above remark can be proven, and is the assumption $\color{blue}{(*)}$ you mention.
Proposition. Let $R$ be a set. Then $\{x:(\exists y)[(x,y)\in R]\}$ is a set.
Proof.
Define the formula $\varphi$ with free variables $\check{p}$ and $\check{x}$ by
$$\varphi(\check{p},\check{x}):=(\exists y)[(\check{x},y)=\check{p}].$$
By the axiom of replacement, $\{x:(\exists p\in A)[\varphi(p,x)]\}$ is a set. Indeed,
$$\varphi:p\mapsto x$$ satisfies $(\forall a)[a\in A\:\Rightarrow\:(\exists!b)[\varphi(a,b)]]$ by $\color{blue}{(*)}$. That is to say $\varphi$ is a class function. Here $A=\{z\in R:(\exists a)(\exists b)[z=(a,b)]\}$.
$\square$
This proposition and proof can be modified to prove the range is a set as well.


Rendering same form repeated in Symfony for bulk insert

Question: I been trying all day to do multiple insert for the same form based on a number and i couldn't go any where with it. I hope someone here would be help me out...
am using admin generator on 1.4 doctrine. I have a form which i generated with only two fields. what am trying to do is, based on a number inserted the form will be repeated x number of times.
In the generator file I added a partial which placed a text field in the beginning of the form with default value of 1. If I choose 2 the form below gets duplicated twice..
Here is what i did to my form.. In action
class prizesActions extends autoPrizesActions

{
  public function executeNew(sfWebRequest $request)
  {
$this->form = $this->configuration->getForm(null, array('n' => 5));
$this->prizes = $this->form->getObject();

}
}
and in the PrizesForm, I wrote the following
class PrizesForm extends BasePrizesForm

{
 public function configure()
  {
    $array = $this->getOptions();
    for ($i = 0; $i < $array['n']; $i++) {
    $this->setWidgets(array(
      'id'         => new sfWidgetFormInputHidden(),
      'prize_no'   => new sfWidgetFormInputText(),
      'prize'      => new sfWidgetFormInputText(),
      'created_at' => new sfWidgetFormDateTime(),
      'updated_at' => new sfWidgetFormDateTime(),
    ));

    $this->setValidators(array(
      'id'         => new sfValidatorDoctrineChoice(array('model' => $this->getModelName(), 'column' => 'id', 'required' => false)),
      'prize_no'   => new sfValidatorInteger(array('required' => false)),
      'prize'      => new sfValidatorString(array('max_length' => 200, 'required' => false)),
      'created_at' => new sfValidatorDateTime(),
      'updated_at' => new sfValidatorDateTime(),
    ));

    $this->widgetSchema->setNameFormat('prizes['.$i.'][%s]');

    $this->errorSchema = new sfValidatorErrorSchema($this->validatorSchema);
}

unset(  $this['updated_at'],
        $this['created_at']
        );

}
}
I think the loop is working but its over writing the widgets at every entry and i cannot find other method to append instead. Any ideas?
Thanks,
Comment: I am a bit confused at what you are trying to do? Based on the number you are inserting are you trying to insert X number of copies of that form?
Comment: Yes, I have a form which I want to repeat x number of times based on database variable will be retrieved when the page is loaded.
Comment: Can you please format your code correctly?
Comment: @develop7: I tried but it i cannot get it to format correctly :(
Answer: Did you try embedForm()? Code below should give you an idea.
class PrizesForm extends BasePrizesForm
{
  public function configure()
  {
    $this->setWidgets(array(
      'id'         => new sfWidgetFormInputHidden(),
      'prize_no'   => new sfWidgetFormInputText(),
      'prize'      => new sfWidgetFormInputText(),
      'created_at' => new sfWidgetFormDateTime(),
      'updated_at' => new sfWidgetFormDateTime(),
    ));

    $this->setValidators(array(
      'id'         => new sfValidatorDoctrineChoice(array('model' => $this->getModelName(), 'column' => 'id', 'required' => false)),
      'prize_no'   => new sfValidatorInteger(array('required' => false)),
      'prize'      => new sfValidatorString(array('max_length' => 200, 'required' => false)),
      'created_at' => new sfValidatorDateTime(),
      'updated_at' => new sfValidatorDateTime(),
    ));

    $this->widgetSchema->setNameFormat('prizes[%s]');
  }
}

class PrizesGroupForm extends sfForm
{
  public function configure()
  {
    $array = $this->getOptions();

    for ($i = 0; $i < $array['n']; $i++)
    {
      $this->embedForm('prizes_' . $i, new PrizesForm());
    }

    $this->widgetSchema->setNameFormat('prizes_group[%s]');
  }
}


html5 pattern validation for file not working

Question: I searched in Google there has no option for validate file by using URL pattern.
I also have tried in my site. But pattern for file not working. Check my code -
<input type="file" class="form-control" id="mp3file_name" name="mp3file_name"  pattern="([^\s]+(\.(?i)(mp3))$)" accept="audio/mpeg, audio/mp3" required="required" />

Attribute accept working fine but I need to validate If I will  uploading other files except mp3
Comment: you can use javascript function along with button to validate..
Answer: Remove the pattern and just use:

<input type="file" class="form-control" id="mp3file_name" name="mp3file_name" accept="audio/mpeg, audio/mp3" required="required" />

Also as said by Mave:

The accept attribute is incredibly useful. It is a hint to browsers to only show files that are allowed for the current input. While it can typically be overridden by users, it helps narrow down the results for users by default, so they can get exactly what they're looking for without having to sift through a hundred different file types.
Comment: Your code accepted all files like `.doc`, `.zip` etc.
Comment: @Chinu What browser are you using? It doesn't allow me to add anything other than `.mpg` and `.mp3`!
Comment: Click on browse bottom and select `All Files ('*')` then choose any other file
Comment: I am using `mozilla firefox version - 39.0.3`
Comment: ^ That I don't think you can stop. It is a feature of all platforms.
Comment: I am using Chrome. And what you say is normal expected behaviour that you need to handle in server side by reading the MIME type.
Comment: I know i can validate in server side. But Just want to know is there any option for validate file extension in url pattern? I am using popup. once page refresh then popup will disappear
Comment: Nopes. You can't do that buddy! `:(`
Answer: Please see File input 'accept' attribute - is it useful?:

The accept attribute is incredibly useful. It is a hint to browsers to only show files that are allowed for the current input. While it can typically be overridden by users, it helps narrow down the results for users by default, so they can get exactly what they're looking for without having to sift through a hundred different file types.

You can make it easier for users to browse through their files, but ultimately you have no control over it, as it is user input. Make sure you check the file in whatever language you receive the form in.


Webots displaying processed numpy image (OpenCV Python)

Question: I am trying to simulate a line follower with Pioneer 3AT in Webots. This is the first step towards my application involving swarm robotics. I have placed camera. However, I am not able to display image processed with OpenCV in the simulation display (in realtime). For now, I am planning to just threshold the lane and display using the display node as mentioned in https://www.cyberbotics.com/doc/reference/display.
However, I am not able to get this up and running. The question is how do I display the processed numpy image array in the webots display?
Code that I currently have:
camera = Camera("camera")
camera.enable(TIME_STEP);
display = Display("display")

while (robot.step(timestep) != -1):
    cameraData = camera.getImage();
    image = np.frombuffer(cameraData, np.uint8).reshape((camera.getHeight(), camera.getWidth(), 4))

Now, how do I display the image in display?
I tried imageNew, imagePaste etc. However, I am getting plenty of C/C++ errors via SWIG and I am not able to find any relevant examples too. (The Webots simulator comes with only one example that uses display city.wbt and that uses a static image. I am not sure if that could be used. But, the summarised code of that example which is in C is as below.)
// speedometer
WbDeviceTag display;
int display_width = 0;
int display_height = 0;
WbImageRef speedometer_image = NULL;

// initialize display (speedometer)
if (enable_display) {
    display = wb_robot_get_device("display");
    speedometer_image = wb_display_image_load(display, "speedometer.png");
}

// display background
wb_display_image_paste(display, speedometer_image, 0, 0, false);

P.S.: I have spent more than 4 hours on this and I am not able to find any solution for this. There appears to be a similar question on Qt (I am not using Qt). But, that question has gone unanswered: Ploting an image with 'imshow' of opencv in webots.
Any help will be greatly appreciated as I am planning to opensource my entire project.
EDIT 1: I tried the following as per the following note for Java. But, I am getting a blank display screen. No luck after 10 hours of efforts.

Note [Java]: The Display.imageNew function can display the image returned by the Camera.getImage function directly if the pixel format argument is set to ARGB.

display.imageNew(cameraData, display.ARGB, camera.getHeight(), camera.getWidth())
Answer: I figured out an "official way" to get this up and running. However, I do not like this solution as it is not integrated directly into the simulator (and the simulations become too slow when used with this method). For now, I am accepting this answer. However, I will accept any other answer that integrates neatly into Webots.
cv2.startWindowThread()
cv2.namedWindow("preview")

while (robot.step(timestep) != -1):
    cv2.imshow("preview", image)
    cv2.waitKey(TIME_STEP)

Source: https://cyberbotics.com/forum?message=7950
Answer: You will find more example of Display device in Webots that might help you (they are in C/C++ but you should be able to apply similar mechanisms for Python):

projects/samples/devices/display: various example showing how to use the Display device (https://cyberbotics.com/doc/guide/samples-devices#display-wbt).
projects/samples/howto/vision: uses opencv and displays the result in a Display device (https://cyberbotics.com/doc/guide/samples-howto#vision-wbt).

In python you shoul dbe able to display an OpenCV image into the display with something similar to:
    imageRef = display.imageNew(camera.getImage().tolist(), Display.RGB)
    display.imagePaste(imageRef, 0, 0)

Comment: Could you please post a minimal working solution? I had through that before. But, I am getting SWIG errors when I try to access display memory. It looks like the C/C++ version uses `memcpy` which can't be replicated directly in Python (without digging into Webots source code).
Comment: I added an example (not tested) in the answer.
Comment: I am getting similar errors (that I used to get before) https://pastebin.com/erT8uLrT
Comment: @PrasadRaghavendra here is a tested solution:
`imageRef = display.imageNew(frame.tolist(), Display.RGB)`. @DavidMansolino please update the code
Comment: Hi @DarkoLukić thank you for the tested solution. I assume `frame = camera.getImage()` right?
Comment: Yes, that is correct. There is a problem only in the first line, the second is fine


Extract substring as number from string typescript

Question: This is the format of the string:

I want to extract the Revision number from the name. I tried using Substring() but I need a generic solution that could extract out Revision number from any name in this format.
This is how the name is being set is the backend:

Thanks in advance.
Comment: So the "Revision" word can be translated? You're left with the parenthesis and the number to recognize the pattern, isn't it a bit too fragile? That being said I've provided an answer.
Answer: You could use a regex with a capturing group like this:

const input = 'Access2 - changed - (Revision 2)';

const regex = /^.*\(\w+\s(\d+)\)$/;

const [, revision] = regex.exec(input);

console.log(revision);
Comment: May I please know what does the regex group target?
Comment: the capturing group (unescaped parenthesis) surrounds the decimals that you need to retrieve, the result is an array with the full match, then the capturing group match. It retrieves the revision number when the input string is in the form of `any characters(anyletters 123)` where `123` can be one or more decimals
Answer: You can try this
const [,revisionNumber] = value.match(/Revision (\d)/)

Comment: Won't it throw exception when value is an empty string?
Comment: It will, to prevent that you can add `|| []` at the end of the line, then revisionNumber will simply be undefined


cannot calibrate touchscreen

Question: I installed 11.04 on a WeTab (although wetab os is now gonne, only 11.04 now). I use the eGalax Inc. USB TouchController device driver. I want to calibrate the screen using Touchscreen Settings, but I get the following errir message:
"Unable to start calibration. Exclusive access to the pointer could not be obtained"
This is annoying because the calibration is slightly wrong, meaning I can't reach the right of the screen including shut down/log out etc.
Is there a fix for this, or a way to manually change the calibration settings?
Comment: i've given up in 11.04 for now. it isn't ready for my device, much better on a netbook without touchscreen
Answer: hey dude iv been having a similar issue....
to fix this i installed xinput-calibrator
 sudo apt-get install xinput-calibrator

you can then run it from System > Administration > Calibrate Touch-screen
after you have calibrated it will show a terminal output that looks similar to this
   Warning: multiple calibratable devices found, calibrating last one (eGalax INC. USB TouchController)
    use --device to select another one.
Calibrating EVDEV driver for "eGalax INC. USB TouchController" id=12
    current calibration values (from XInput): min_x=0, max_x=4095 and min_y=0, max_y=4095

Doing dynamic recalibration:
    Setting new calibration data: 77, 3935, 115, 3984

--> Making the calibration permanent <--
  copy the snippet below into '/etc/X11/xorg.conf.d/99-calibration.conf'
Section "InputClass"
    Identifier  "calibration"
    MatchProduct    "eGalax INC. USB TouchController"
    Option  "Calibration"   "77 3935 115 3984"
EndSection

ignore most of this the only bit you need is
Option  "Calibration"   "77 3935 115 3984"

in terminal type
sudo nano /usr/share/X11/xorg.conf.d/10-evdev.conf

and add the Calibration option to your touch-screen section
Section "InputClass"
        Identifier "evdev touchscreen catchall"
        MatchIsTouchscreen "on"
        MatchDevicePath "/dev/input/event*"
        Driver "evdev"
        Option "Calibration" "77 3935 115 3984"
EndSection

for the /etc/X11/xorg.conf.d/99-calibration.conf  simple instruction can be found on  http://gnometechblog.weebly.com/1/post/2012/03/first-post.html
Comment: hey, thanks for posting the answer. i don't have 11.04 installed at the moment but will try your method if I put it back in the future.

cannot calibrate touchscreen


How do you customize a NodeJS deployment to Elastic Beanstalk?

Question: I have a web application written with NodeJS for the webserver and Angular on the frontend.
The structure is like this
musicapp
   |-- server
   |     |--- src/
   |     |--- node_modules/
   |     |--- package.json
   |--- client
         |--- src/
         |--- node_modules/
         |--- package.json

When I deploy to Elastic Beanstalk using eb deploy nothing happens, and I've realized it must be because the default action for Elastic Beanstalk is to call npm install and npm start but in my case, that doesn't do anything when called on the root.
So my question is, how do I tell Elastic Beanstalk: upon deploy, cd to client and call npm install, npm run build and then cd to server and call npm install, npm start ?
I can't find anything in the EB documentation that explains how one might do this.
Answer: In your root folder create a dir called .ebextensions and inside that folder create a file called 01_npm.config (for example).
In that yaml file you can specify commands by:
container_commands:
  01_client:
    command: "cd ./server && npm install && npm run build"
    leader_only: true
  02_server:
    command: "cd ./client && npm install && npm run build"
    leader_only: true

Elastic Beanstalk will execute those commands when you run eb  deploy automatically.
For more information see:
https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/customize-containers-ec2.html
Comment: This is helpful, thanks, though I think these are YAML files rather than JSON.


How do I return my ActionResult to the proper view?

Question: I have a MVC 3 web application (more like a sub-application, really) that does not rely on ASPNET for authentication because that is already being used in another area of the app and we are using a different type of credentialing. At any rate, I decided to create my own authentication system with its own SQL table, which is working fine on one form in the app. Now, I am trying to roll it into the shared layout, calling a "Login" action in the home controller. The problem I am having is how to return from that Login action back to wherever the user is. When I try "return View();" it understandably tries to return to a Home/Login view, which doesn't exist. How do I return from this Action to wherever I was before the action? All views use the shared layout, so I'm hoping this is fairly simple!
public class HomeController : Controller
{

 .....

    private DataModel db = new DataModel();

    //
    // GET: /Home/

    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Login()
    {

        string un = Request["form_un"];
        string pc = Request["form_pc"];
        int usercount = db.JobBoardUsers.Where(u => u.userid.Equals(un) && u.passcode.Equals(pc)).Select(u => new AccountModel() { uid = u.id }).Count();
        usercount = db.JobBoardUsers.Where(u => u.userid.Equals(un) && u.passcode.Equals(pc)).Count();
        if (usercount > 0)
        {
            HttpContext.Session["IsSignedIn"] = true;
            HttpContext.Session["IsSignedInId"] = un;
        }
        return View();
    }

Comment: Do you explicitly go to the `Login` view (i.e. are you calling this action or does the server redirect the unauthenticated user)? Depending on your logic, you could use `Request.Path` to determine the targeted address. Or even `Request.UrlReferrer`.
Comment: It is explicit. The action on the login form is "Home/Login". The app is fully usable without authenticating (login provides some additional features, like remembering the user's information), so I would not want to automatically redirect to the login page.
Answer: Instead of return View(), You need to use return RedirectToAction or return Redirect method.
You may get the previous page in your login action using different methods
1) pass the current pages url to login action method as a parameter and use that for redirecting after successful authentication
2)Use the Request object to get the UrlReferrer property value and use that as the page to be redirected.
Chek this blog post where they explains how they did it in nerddinner.
Comment: Thank you, I went with #2 and it works perfectly. I would have figured MVC had a more convoluted standard for doing this like it seems to with everything else.


How to configure Let's Encrypt certificates for Service Fabric?

Question: Does Service Fabric support the Let's Encrypt certificates?
I want to use Let's Encrypt certificates and automate the process of renewing them.
Is there any tool available already which can help to add the Let's Encrypt certs to Service Fabric?
Any help would be appreciated.
Thanks,
Avinash
Comment: there was a powershell module or something like that to work with Lets encrypt and iis. not sure if that helps
Comment: There's a feature request for this: https://feedback.azure.com/forums/293901-service-fabric/suggestions/33847168-let-s-encrypt-certificates-for-service-fabric
Answer: This is the best I've found so far: https://www.troyhunt.com/everything-you-need-to-know-about-loading-a-free-lets-encrypt-certificate-into-an-azure-website/
Sorry I'm not just adding the content here, as it's long, and the screenshots are pretty useful
If you find something that's one click, let me know - I wish Azure directly just supported as it's somewhat of a pain.
Comment: This doesn't help. Service Fabric is a Microservice Orchestrator like Kubernetes. The cluster deployment script should have a way to interact with Lets Encrypt. Currently, there is no guidance on how to use Let's Encrypt in ARM templates used to create the cluster.


How does tensorflow implement the embedding_column?

Question: I'm learning tensorflow's wide_n_deep_tutorial these days, and I'm a little bit confused with the tf.contrib.layers.embedding_column. I wonder how does tensorflow implement the embedding column?
For example, suppose I have an sparse input with dimension 1000 and I want to embed it into a dense feature with dimension 10. Does it hold a fully connected network with 1000*10 params and train using BP to update the params? Or does it use some other techniques like FM to map the 1000 dim vector to a 10 dim vector?
Answer: There are 3 combiner in the embedding_column function:
"sum": do not normalize
"mean": do l1 normalization
"sqrtn": do l2 normalization. see more tf.embedding_lookup_sparse
There are not using FM to modulate/transform the dimensions.


complete and inherited metric question

Question: Let $(X,d)$ be complete, $S\subseteq X$.
Want to show that $(S, d|_{S\times S})$ is complete if and only if $S$ is closed in $(X,d)$.
Can anyone give me any hints? Thank you all.
Comment: If $S$ is complete consider a limit point of $S$ and a sequence of points from $S$ that converge to it. If $S$ is closed, consider a Cauchy sequence in $S$ and the point in $X$ that it converges to.
Comment: @chilangoincomprendido Assume $S$ is complete, then $\exists (x_n)$ Cauchy s.t. $(x_n)\rightarrow k\in X$. But I did not see the connection.
Answer: Suppose $S$ is complete. Assume $S$ is not closed, then $Clsr(S)\setminus S\neq\emptyset$. Choose $x\in Clsr(S)\setminus S\neq\emptyset$, then for every $n\in\mathbb{N}$, we have $(B(x,\frac{1}{n})\setminus\{x\})\cap S\neq \emptyset$, so we can choose $x_n\in (B(x,\frac{1}{n})\setminus\{x\})\cap S$. Obviously $(x_n)$ is a Cauchy sequence in $S$ with $x_n\to x$, but $x\notin S$ which means $S$ is not complete, contradiction.
Conversely suppose $S$ is closed. Assume $S$ is not complete. Let $(x_n)$ be a Cauchy sequence in $S$ which does not converge in $S$. Then since $X$ is complete, there exists $x\in X\setminus S$ such that $x_n\to x$. This means for every $\epsilon>0$, $B(x,\epsilon)$ contains a tail of the sequence, and thus has non-empty intersection with $S$. This implies $x\in Clsr(S)$, and therefore $S\neq Clsr(S)$ and this means $S$ is not closed, contradiction.

complete and inherited metric question


Using session while sending set of AJAX requests

Question: In my Rails application I make set of AJAX calls at once and that causes sending the same session cookie for each request.
The problem is that rails sets new session cookie in every response and therefore it expects that cookie value in the request after.
I'm looking for server-side solution because I don't want to chain those requests (they are time consuming).
Is it possible to change this behavior? And what security risks would come with it?
(I'm using Rails 4.1.0)
Many thanks
Answer: If the user doesn't already have a session cookie then there is nothing you can do.
If you can guarantee that the user already has a session (for example, if you require users to be logged in) then you may be able to do this with a server side session store.
With a server side session store the session cookie just contains an identifier - even if your overlapping ajax requests change values in the session they will not change the session cookie. In general this is better security wise: for example, old sessions can't be replayed after the user has logged out. Rails switched to the cookie store by default for performance reasons: no external data store needs to be accessed (however it does slightly increase the amount of data sent on each request)
Switching to a serverside session store isn't enough though and still leaves you open to race conditions. It is very easy to end up with a sequence along the lines of

Request A loads session
Request B loads session
Request B completes, saves session
Request A saves session and overwrites the session changes made by B

You need a session store that will attempt to merge any changes it has made with any changes that may have occurred from other requests.
I wrote such a session store  some time ago. I haven't updated it for rails 4, since it isn't something i need anymore but you may be able to (or at least find inspiration in it)
Comment: Good answer, thanks! I looked into it and found suitable gem for this. https://github.com/rails/activerecord-session_store
...
I think there's no reason to concern about the condition you mentioned at the very beginning because session is set after the first request and after that come those AJAX calls (with session_id already defined).
Comment: The session store I linked to was written because active record store (that used to be part of rails) exhibited race conditions the way we were using it. That may have changed, but do check
Comment: Luckily I don't have to worry about it in my project because only one of those requests writes to session. So the problem was really only in the sequence of calls. But you're right other readers should consider this.


Can a pair of pointers to different functions taking different types of parameters be compatible?

Question: Can we put a function address of a particular signature into a function pointer which is defined to have some other signature and use it seamlessly?
For example, the following code
#include <stdio.h>

void print_n(int *pn) {
    printf("%d\n", *pn);
}

void print_n_wrapper(void *p) {
    print_n(p);
}

int main(void) {
    int n = 123;
    void (*f)(void *) = print_n_wrapper;
    f(&n);
    f = print_n;
    f(&n);
    return 0;
}

gets compiled and runs fine in my machine. Am I invoking undefined behavior somehow?
Comment: Yes you are invoking UB. Those pointer types are not compatible.
Comment: It work find, but compiler tells you`warning: assignment from incompatible pointer type`
Answer: Yes, it is undefined behaviour.
Quoting C11, chapter §184.108.40.206, Pointers, (emphasis mine)

A pointer to a function of one type may be converted to a pointer to a function of another
  type and back again; the result shall compare equal to the original pointer. If a converted
  pointer is used to call a function whose type is not compatible with the referenced type,
  the behavior is undefined.

and regarding the "function whose type is not compatible" part, the definition of compatibility goes like

For two function types to be compatible, both shall specify compatible return types.(146)
  Moreover, the parameter type lists, if both are present, shall agree in the number of
  parameters and in use of the ellipsis terminator; corresponding parameters shall have
  compatible types.

That means, void * and int * should have been the same types, but they are not. So, the functions are also not of compatible type.
Comment: OP is asking whether his two different function types are *compatible* , so your answer should go into what it means for function types to be compatible
Answer: The call to print_n(p) in print_n_wrapper is defined since all you're doing is converting a void* which was originally an int* to an int*
The assignment f = print_n; will give you trouble. Although the assignment is defined, the behaviour on the subsequent call f(&n) is undefined.


SQLite - remove row with a lowest id

Question: How can I remove a row from a table that has lowest rowid?
Thank you.
Answer: DELETE FROM
  MyTable
WHERE
  Id = (SELECT MIN(Id) FROM MyTable);

Answer: In most cases like this, rowid is an indexed column. If that is the case the much faster solution is:
DELETE FROM
  tablename
WHERE
  rowid= (SELECT rowid FROM tablename order by rowid limit 1)

If rowid is NOT indexed then:
DELETE FROM
  tablename
WHERE
  rowid= (SELECT MIN(rowid) FROM tablename)

I'd still test the first one as it will often be faster, even if rowid is not indexed.
Answer: DELETE FROM
  tablename
WHERE
  rowid= (SELECT MIN(rowid) FROM tablename)

SQLite - remove row with a lowest id


How do I get the length of an MP3 from its URL?

Question: If I know the URL of an MP3 file, what is the easiest/fastest way to get its length, bitrate, size, etc?
How can I download just the ID3 tag part of the MP3 to get these details?
Comment: Length of the file in bytes of playing time of the audio in seconds?
Answer: You will need to look at the ID3 tags in the mp3 file.
Unless you keep track of the metadata you want somewhere else.
To specifically get the Track length of the file you will need to look into the ID3 metadata tag for sure, specifically the 'TRCK' frame of the tag.
To only download the ID3 Tag part, you must first download the ID3 header part of the file.
This website contains very specific information about the ID3 Tag format.  You will need to look at the version number of the ID3 Tag and then, based on that, you will need to find the information regarding how long the ID3 Tag is.  Then, you must download the WHOLE tag because the frames are not in any specific order.
Then you should be able to use a third party library to find the TRCK frame and its data.
Answer: Here is how you get file size, but how do you get bitrate and track length?
<code>import java.io.*;
import java.net.*;

public class FileSizeFromURL {
public static final void main(String[] args) {
URL url;
URLConnection conn;
int size;

if(args.length != 1) {
  System.out.println("Usage: FileSizeFromURL ");
  return;
  }

try {
  url = new URL(args[0]);
  conn = url.openConnection();
  size = conn.getContentLength();
  if(size < 0)
     System.out.println("Could not determine file size.");
  else
    System.out.println(args[0] + "\nSize: " + size);
  conn.getInputStream().close();
  }
catch(Exception e) {
  e.printStackTrace();
  }
}
}
</code>
Comment: try the suggestions made in the other answers?
Comment: It would probably be best for performance to do this as a HEAD request rather than GET. See eg. HttpURLConnection.setRequestMethod. http://java.sun.com/j2se/1.4.2/docs/api/java/net/HttpURLConnection.html#setRequestMethod(java.lang.String)
Answer:
what is the easiest/fastest way to get its length, bitrate, size, etc?

File size you can get with an HTTP HEAD request. If by 'length' you mean playing time in seconds, you cannot get this without fetching the entire file. You can guess, by fetching the first few MP3 frames, looking at their bitrate, and assuming that the rest of the file has the same bitrate, but given the popularity of Variable Bit-Rate encoding the likelihood this will be close to accurate is quite low.
ID3 tags can in theory contain information that might allow you to guess the length better, in the ASPI and ETCO tags. But in practice these are very rarely present.

How can I download just the ID3 tag part of the MP3 to get these details?

For ID3v2 tags, grab the start of the file. (It's possible for ID3v2 frames to be elsewhere, but in practice they're always there.) You can't tell how long the tag is going to be in advance. For text-only tags you're likely to find the information you want in the first 512-1024 bytes. Unfortunately more and more MP3s have embedded 'album art' pictures, which can be much longer; try to pick an ID3 library that will gracefully ignore truncated ID3 information.
ID3v1 tags are located at the end of the file. Again you can't tell how long they're going to be. And of course you don't know in advance whether the file has ID3v1 tags, ID3v2 tags, both or neither. Generally these days ID3v2 is a better bet though.
To read part of a file through HTTP you need the Range header. This too is not supported everywhere.
In summary, there are enough problems with this that the best option may well be giving up and just fetching the whole file.
Answer: I am answering this question a year+ after it was asked but I do have some info to add for those happening by at a later time.  I answered a similar question about getting the image dimensions from an image on a remote server without downloading the whole image.  See that discussion at the following URL:
Get image dimensions with Curl
You could definitely use the same technique to pull info out of the ID3 tags without downloading the whole MP3 from a remote server.
I hope that helps for future passers-by.
Answer: You cannot get this information from the URL alone.
You'll have to load the first few K of content and use an mp3 library to decode the header and get the values.
Answer: That data is encoded in the id3 tag, so you need to download at least that much of the file, which is at the beginning so you're in luck.
Alternatively you can look at the content-length header value in the http response header to know the length, if the server tells you which it may not.


How to run graphical python program on Ubuntu server?

Question: I am working on face recognition project on Ubuntu 18.04 remote server. I don't know how to install the desktop(GUI) version. I can run face recognition program without the cv2.imshow part. How can I display the results in graphical mode?
Answer: I'm assuming you are accessing the server remotely. If so (or if you can) see below.
For development you may want to look at using jupyter notebook. It runs on the server and you can access it from a web browser on another computer. You can wright you code or scripts in it and save/load programs there. The main thing is that over the remote browser session you can get images to appear so it may serve your needs. I've quite liked the tool from my use.

The Jupyter Notebook is an open-source web application that allows you to create and share documents that contain live code, equations, visualizations and narrative text.

jupyter


Tkinter Bugs wrt adding mulitple buttons to menu bar

Question: Attempting to create a menu box but I am having trouble adding multiple buttons, there is only a "Quit" button visible when I run the code, please assist xx
class Menu(Frame):
    def __init__(self, master = None):
        Frame.__init__(self, master)

        self.master = master

        self.init_menu()

    def init_menu(self):
        self.master.title("DUNGEON MENU")

        self.pack(expand = True, fill=BOTH)
        quitB = Button(self, text = "Quit", fg = "red", command = self.client_exit)
        quitB.grid(row = 0, column = 3, padx = 120)
    def client_exit(self):
        exit()

        lootB = Button(self, text = "Loot", command = None)
        lootB.grid(row = 1, column = 3, padx = 120)

root = Tk()
root.geometry("300x300")
app = Menu(root)
root.mainloop()
button.pack()```

Answer: I have created a working version from your code. You can find my finding in the below code as comments.
I am not totally sure what your expectation about your code. Now the "Quit" and "Loot" buttons are visible on the Frame and if you click to "Quit" button, the program will be end (Loot button does nothing).
Code:
from tkinter import Frame, BOTH, Button, Tk

class Menu(Frame):
    def __init__(self, master=None):
        Frame.__init__(self, master)

        self.master = master

        self.init_menu()
        # You have to call the "client_exit" method to rendering the "Loot" button to Frame.
        self.client_exit()

    def init_menu(self):
        self.master.title("DUNGEON MENU")

        self.pack(expand=True, fill=BOTH)
        # Destroy the master if you click to the "Quit" button.
        quitB = Button(self, text="Quit", fg="red", command=lambda: self.master.destroy())
        quitB.grid(row=0, column=0, padx=120)

    def client_exit(self):
        # exit() # This exit is not needed because it breaks the program running.
        # You can define the call-back of button in "command" parameter of Button object.
        lootB = Button(self, text="Loot", command=None)
        lootB.grid(row=1, column=0, padx=120)

root = Tk()
root.geometry("300x300")
app = Menu(root)
root.mainloop()
# button.pack() # It does not have effect. You cannot define widgets after "mainloop"

Output:
>>> python3 test.py


Passing Variables into a class once as setup vs passing it multiple times? C#

Question: Right, so I'm looking for a performance impact/code style answer here so this might not be the right place to ask.
I've got a DataRow 'reader' set up from a Database result and then I extract the values into an object. Since for each variable I want to check for null values and return a 'failure' value if it is null I have to perform the check:
try
{
    if (reader[property] != DBNull.Value)
    {
        var = reader[property];
    }
    else
    {
        var = failureValue;
    }
}
catch (ArgumentException e)
{
     // DISPLAY ERROR ABOUT NO VALUE CALLED Property
     var = failureValue;
}
catch (Exception e)
{
    // DISPLAY GENERIC ERROR ABOUT VALUE
    var = failureValue;
}

In my current situation I perform that check 47 times in one class so I moved the code into a method and then called it. Its important to note I put it in a superclass for my data access classes so every one could use it.
My question now, when I created this method I originally passed in the full DataRow 'reader' every time the method was called. Should I make a static variable within the superclass and set it when I set up the 'reader'? Thereby, allowing the method to access a static variable within itself and not having to perform the passing of the full reader every time? Or is it slower to change it over like this thread suggests?
EDIT: As both the first answer and comment have questioned, the variable does need to be static as the superclass is never initialised itself, just inherited from.
Comment: Pass what your method needs to fulfill its task. Pass via initialization (e.g. constructor) if the complete class needs the dependency. In your case its absolulety fine to pass the same reader on every call, it does not have any performance-impacts - even *if* they were so little, you might have other problems than those nano-seconds. You could of course also add a property which you set once before any call to the method, doesn´t need to be `static`.
Comment: So if i were to do: setReader(reader) and then call that before any call to the extract method, that would be acceptable?
Answer: From a performance-perspective it makes no difference at all (maybe some nano-seconds, but you won´t care for that) if you pass the reader again and again or store it locally into a variable. In contrast to what´s said in the post you´ve mentioned there is no difference on where an object is stored between decalaring it in a method or in the class itself. If it is stored on the stack or heap is determined by other means.
However from an API-perspective you should ask yourself if the dependency (in your case the reader) is needed for all members (or at least a few) of your class or just one single. I suggest passing the dependencies where you really need them.
Another appraoch is to set the dependency by a setter before calling your method the first time:
var instance = new MyType();
instance.SetReader(reader);
for(int i = 0; i < 100; i++) instance.DoSomething();

As per your EDIT: only because your base-class isn´t instantiated doesn´t mean all it´s members should be static. Actually your base-class is instantiated, whenever you create a new instance of one of its child-classes (which cab be converted to the base-class though). So you can just use a usual instance-member that is inherited by all deriving classes.
You may have a look at dependecy injection.
Answer: You should pass instances rather than using a class-level, static variable.
The reason is because you want to maintain tight control over the scope and thus lifetime of your variables.  You don't want them to exist any longer than they need to or be available outside of the scope within which they're needed.
Lets leave aside for the moment the fact that a data reader -- e.g. SqlDataReader -- implements the disposable pattern; you would still be making your application unnecessarily complicated.  It may not seem to matter that much for a small application with relatively few classes, methods, and variables, but small applications have a habit of growing into larger, more-complex ones.
As I alluded to above, data readers like SqlDataReader implement IDisposable, which means that the way you are supposed to use instances of them is within a using statement:
using (var reader = command.ExecuteReader())
{
    // ... do stuff
}

That way, the reader is guaranteed to be disposed and garbage collected before the block exits, even in the event of an exception.  What's important to note is that the variable reader only exists within the scope of the using block.  Narrower scope means not only is it easier to read your code and know what's happening where and when, but it also guarantees that your variables will be garbage collected when they are no longer needed.
Think about it: if you had a static, class-level variable, when would it be garbage collected?  Not until the application exits.  That is very hard to debug in cases where you're having memory issues.
Comment: Thanks for the advice, currently I'm using a web service to return me a new DataTable from a query and then I'm iterating over the rows using dataTable.row[i] and then passing that to the method. When i exit the method to return me the data, the datatable is available for garbage collection, only the last row may be left when passed to the superclass. i could get around this by adding a clearReader() method to null out the reference and allow full garbage collection?