Why can't I get to a shared folder from Windows

Question: I want to access a folder on my new Ubuntu 12.10 box from any machine on my network without the need to provide credentials.
My machine name is Ubuntu1
I have a 2TB disk that formatted NTFS that has media on it
The mount point is mount1
I have numerous folders on the disk and I want to share each of them individually
I have enabled folder1 and folder2 for sharing
I have enabled shared access, Allow others to create and delete files in this folder and guest access is allowed.
The folder icon now has arrows so I assume all is good.
From windows I can see under network
Ubuntu1>folder1
Ubuntu1>folder2
When I click to open the folder from windows I get the error "You cannot access \Ubuntu1\folder1
You do not have permission to access \Ubuntu1\folder1
I have them both on the same workgroup.
Your assistance would be appreciated
Comment: please read this one https://wiki.ubuntu.com/MountWindowsSharesPermanently
Comment: @user128296: That guide talks about mounting Windows shares on Ubuntu: Ron is trying to share folders from Ubuntu and mount them on Windows, which is quite different.
Comment: Check that the path you are trying to share is correct in case you have directly entered the configuration in the samba config file
Answer: Try running this command on your Ubuntu server:
sudo -u nobody ls "/path/to/my/share"

That will try to access your shared folder as user nobody.  If you see an error like this:
ls: cannot access /path/to/my/share: Permission denied

then your local permissions are the problem (or at least a part of it).

Samba uses Linux filesystem permissions to determine whether it should grant access to shared files; if permissions block access to the shared folder itself, Samba will refuse to allow other machines to connect to the share at all.  Guest access uses the nobody user (from group nogroup), so you should use the 'other user' file permissions to ensure that guests can access your shared folder.

It's important to check permissions on all the directories leading from / down to your shared folder too: if a user doesn't have execute permissions for a directory then they're prevented for accessing any paths below that point, including your share.  (I created the ls error message above by removing 'x' permissions from an intermediate directory.)
Let's say you wanted to share /mnt/external/ntfs-drive/folder.  You could add the 'x' permissions on all the parent directories with this command:
sudo chmod o+x /mnt /mnt/external /mnt/external/ntfs-drive

You also need to set read, write and execute permissions for the shared folder and any contents, but for parent directories execute permission is enough.
Comment: (Just in case it's not obvious to everyone else:)  If the Samba logs say `stat of /var/lib/samba/usershares/myshare failed. Permission denied` then you should **ignore** what that actually says, and instead try reading it as `stat of THE SHARED FOLDER NAMED BY /var/lib/usershares/myshare failed.  Permission denied`....
Comment: this solved my problem seeing an smb share on ubuntu 21.10 from macos 11.6.2. the permissions on `~` (`/home/login-name/`) are `drwxr-x---` but need to be `drwxr-x--x`. using the gui to share a directory inside `~` with guest access does not fix this, but your fix does. as for non-guest access, any idea why my ubuntu username/password are rejected when trying to connect? does something have to be set up in the samba serving config? also, i get file transfers of 8MB/s when i push to the server from the mac. when i pull from the mac on the server, i only get 3MB/s, any idea why?
Comment: filed a bug report here https://bugs.launchpad.net/ubuntu/+source/nautilus-share/+bug/1956419, https://gitlab.gnome.org/GNOME/nautilus/-/issues/2074
Answer: Samba needs you to authenticate as a valid user.
You either have to enable guest access or create a user with the same username/password combination on Windows...
Answer: I had the same problem where I could not share files even with the guest access enabled.  I also had the same stat permission denied errors in my log.  Apparently these errors are "normal" and are not the real problem.  In my case the problem was my home directory permissions.  My permissions were rwx for the user and no permissions for group or other.  Setting the execute bit for "other" users fixed the problem.  Something like this should do the trick:
sudo chmod o+x /home/your-home

Answer: Hi the answers already here are good and correct but they do not show that there is a very easy way to fix this using the Ubuntu GUI way.
Right click on your folder you want to share got to the sharing properties and choose,

Allow others to create and delete files in this folder

and

Guest Access (for people without a user account)

as this image shows.

or you can do as Falstaff has correctly said to create an account on Windows with the same user name and pass, or vice versa, create a unix account with the same user pass.
Comment: Sorry I am Lynx newbie and am not real comfortable with the terminal advice given I can't easily translate from the example to my system.
Comment: This is exactly how I changed permissions. I rebooted and have found these errors in log files  [2012/12/17 20:22:04.543567,  0] smbd/service.c:1055(make_connection_snum)
  canonicalize_connect_path failed for service Music, path /media/ron/wd2tb_bottom/Music
Comment: Other errors[2012/12/17 20:23:28.523873,  0] smbd/service.c:1055(make_connection_snum)
  canonicalize_connect_path failed for service AudioBooks, path /media/ron/wd2tb_bottom/AudioBooks
[2012/12/17 20:28:16.968188,  0] param/loadparm.c:9114(process_usershare_file)
  process_usershare_file: stat of /var/lib/samba/usershares/audiobooks failed. Permission denied
Comment: [2012/12/17 20:46:59.237641,  0] param/loadparm.c:6498(canonicalize_servicename)
  canonicalize_servicename: NULL source name!
Comment: 2012/12/17 22:41:21.644314,  0] lib/util.c:1117(smb_panic)
  PANIC (pid 3056): internal error
[2012/12/17 22:41:21.757819,  0] lib/util.c:1221(log_stack_trace)
  BACKTRACE: 23 stack frames:
   #0 smbd(log_stack_trace+0x29) [0xb718e8a9]
   #1 smbd(smb_panic+0x28) [0xb718e9a8]
   #2 smbd(+0x42daf2) [0xb717daf2]
   #3 [0xb6d2d400]
   ....
  smb_panic(): action returned status 0
[2012/12/17 22:41:22.052098,  0] lib/fault.c:372(dump_core)
  dumping core in /var/log/samba/cores/smbd
Comment: @Ron, use Paul Whittaker's (https://askubuntu.com/users/12150/paul-whittaker) answer above (https://askubuntu.com/a/391709/911198) if the directory you're trying to share is in your home directory -- the gui doesn't seem to set the needed permission on your home directory, even still in 21.10!
Answer: As falstaff explained, you need to allow guest from your Ubuntu1 machine or create credentials.
I suggest you to have a look at this guide.
I used it to fix access from both sides (linux/windows clients) to access other SMB shares.
Comment: Welcome to Ask Ubuntu! Whilst this may theoretically answer the question, [it would be preferable](http://meta.stackexchange.com/q/8259) to include the essential parts of the answer here, and provide the link for reference.


What type of client server implementation is mongrel? concurrent or iterative?

Question: Do the mongrel server forks a new child when a request comes or it maintains a queue?
Answer: maintains a queue. No fork do.


Any procedure to find a normal operator that is not self adjoint?

Question: Is there a quick algorithm or tricks (that someone who is half way through Sheldon Axler's Linear Algebra Done Right would understand) to come up with a linear map that is normal but not self-adjoint (say for a simple operator over a 2 dimensional inner product space), that would be pretty handy to get some intuition quickly in an exam situation?
I ask because it always takes me a while to come up with an example, and usually its a very basic one. If any external condition was imposed on this map, I wouldn't be able to come up with one quickly enough.
Answer: Try a skew-adjoint operator, like $$\begin{pmatrix}0 & -1 \\ 1 & 0\end{pmatrix}$$
An easy way to remember this example is that if you identify $\mathbb{R}^2$ with $\mathbb{C}$, then this operator is multiplication by $\sqrt{-1}$.  (That is not a coincidence...)
Indeed, every normal operator (over the reals) can be written as the sum of a self-adjoint operator and a skew-adjoint operator which commute with each other.


Angular Viewchild InfoWindow behaves differently

Question: In my angular google map (not agm) project, the map page html file contains a info window component like this.
<map-info-window #myInfoWindow>

</map-info-window>

In ts file, I use @ViewChild to grab the info window. When marker is clicked, it calls the function openInfo(). Then this.myMapInfoWindow is opened.
@ViewChild(MapInfoWindow, { static: false }) myMapInfoWindow: MapInfoWindow;

openInfo(mk: MapMarker) {
   this.myMapInfoWindow.open(mk);
}

So far everything is good. Now, if I change the @ViewChild in the following way
@ViewChild('myInfoWindow') myMapInfoWindow: MapInfoWindow;

with or without { static: false }, then marker is clicked, in openInfo function, the statement
this.myMapInfoWindow.open(mk);

is failed with an error
TypeError: this.myMapInfoWindow.open is not a function

and info window is not opened.
Where am I wrong in @ViewChild with selector or why open is not a function now?
Thank you
Comment: can you provide a stackblitz?
Answer: According to Angular's Changelog one core change is:
"In Angular version 8, it's required that all @ViewChild and @ContentChild queries have a 'static' flag specifying whether the query is 'static' or 'dynamic'."
If you're working on latest version of angular. This might be the reason your code isn't working without the flag.
You can read more about this here:

https://angular.io/guide/static-query-migration
https://www.thecodecampus.de/blog/angular-viewchild-static-property-in-ng8/
Comment: thank you for your help. however, I have specifically explained in my post that "with or without { static: false }", I also tried static: true and it does not work.
Comment: Sorry, If you could provide a Stackblitz itwould be great. Also, is there anything in this.myMapInfoWindow when you call `this.myMapInfoWindow.open(mk);` ?


Is it bad practice to use same variable for two purpose in DTO

Question: @JsonRootName(value = "studentInfo")
@JsonInclude(value = Include.NON_EMPTY)
public class StudentInfo {
    private String student;
    @JsonProperty("address")
    private String address;

    @JsonProperty("studentName")
    public String getStudent() {
        return student;
    }

    @JsonProperty("studentUserId")
    public void setStudent(String student) {
        this.student = student;
    }
    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }
}

This is my Student class I'm using this object in my student related API as DTO.
Here I've used the student String variable in such a way that when POST/PUT/ API is called and studentUserId is passed it'll get set to student String variable but whenever StudentInfo object is returned as Response Entity then it'll return the actual name of Student which is stored in User table.
I just want to know that, the way I've used the student String variable and @JsonProperty for it, is correct way to use or its wrong practice?
Comment: Yes, it is bad practice. You should have a separate `userId` field in your class. Using the same field for different data is just bugs waiting to happen. It will also be really confusing when other people look at the class at a later time.
Comment: It is also a nightmare to write tests for that class if the semantics for a field depends on the context it is used in.
Answer: Not only a rule for a DTO but for all classes, programs and languages (basically in real non-academic life), when programming, each variable and attribute has it's own purpose and used only for this.
If you follow this rule you will follow also conventions about:

Naming  (each variable will have a decriptive and unique name)
Readability (not only you, also others will see and know how each variable is used for)
Maintanability (when something change -and yes, it will change-, you won't need to divide or make uglies workarounds to make change or fix the problem)
Testability it is a nightmare to write tests for class if the semantics for a field depends on the context it is used in. (@Fildor)

And some others. Anyway, this are just conventions and not mandatory rules, the syntax will be confusing but correct, thus you can use it. My recommendation is: don't! ;)
Comment: You are right. Not impossible, but very ugly and complicated. Given the scenario in the question: I'd have to write the test so it takes into account the context (used as response / used as query). Of course, one could argue that field is only tested for that it contains the actual value I give it, but there may be more to it. So I am speaking on a general basis. A better example would be a numerical field with bounds. Based on context, it may have different valid bounds which had to be tested taking the context into account. Makes for an ugly instable test ... at least in my humble opinion.
Comment: I'd like to add testability to that list.


x-ray: Read html from a file rather than a URL

Question: Code
const Xray = require('x-ray');

const xray = Xray();

// How do I read a file, rather than a URL?
const url = 'https://www.tel-o-fun.ga/';

xray(url, '.marker')((err, value) => {
  console.log(value);
});

My goal
I am using x-ray to scrape some date from a website. For testing and development purposes, I would like to parse data from a local file rather than a remote resource.
How do I load a local file into x-ray, instead of pointing it to a remote URL?
Answer: This example from the x-ray repo solved my problem. Simply pass an HTML string instead of a URL:
const path = require('path');
const Xray = require('x-ray');
const read = require('fs').readFileSync;

const html = read(path.resolve(__dirname, 'index.html'));
const xray = Xray();

xray(html, '.marker')((err, value) => {
  console.log(value);
});


How to Pass Functions as Parameters in Procedures in Delphi?

Question: Is it possible to pass an object function as a parameter in a procedure rather than passing the whole object?
I have a record definition with a function defined as a public class parameter such as:
    TMyRecord = record
      public
        class function New(const a, b: Integer): TMyRecord; static;
        function GiveMeAValue(inputValue: integer): Single;
      public
        a, b: Integer;
      end;

The function could be something like:
    function TMyRecord.GiveMeAValue(inputValue: Integer): Single;
    begin
      RESULT := inputValue/(self.a + self.b);
    end;

I then wish to define a procedure that calls on the class function GiveMeAValue but I don't want to pass it the whole record. Can I do something like this, for example:
    Procedure DoSomething(var1: Single; var2, var3: Integer, ?TMyRecord.GiveMeAValue?);
    begin
      var1 = ?TMyRecord.GiveMeAValue?(var2 + var3);
      //Do Some Other Stuff
    end;

If so then how would I correctly pass the function as a procedure parameter?
Answer: You can define a new type for the function like
TGiveMeAValue= function(inputValue: integer): Single of object;// this definition works fine for methods for records.

then define the method DoSomething
Procedure DoSomething(var1: Single; var2, var3: Integer;GiveMeAValue: TGiveMeAValue);
begin
  writeln(GiveMeAValue(var2 + var3));
end;

And use like so
var
  L : TMyRecord;
begin
    l.a:=4;
    l.b:=1;
    DoSomething(1, 20, 5, L.GiveMeAValue);
end;

Comment: Anon methods make code more flexible. However, they can be a performance headache. Don't reject them without timing, but if you uses anon methods in a bottleneck area of your program, you may suffer.
Comment: Alternatively, one can use Anonymous Methods. This could allow you to call any function you like inside the anonymous method.

http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/devcommon/anonymousmethods_xml.html
Comment: Good point.  I personally find the `procedure-or-function of object` syntax more readable than the `reference to procedure-or-function of object` syntax too. writing `procedure (a,b,c:Integer) begin ... end` inline begins to get ugly.
Comment: Your method reference uses 'Single of object' instead of just 'of object'. Are you just telling it to put the Self pointer in a Single?
Comment: @Noumenon, No, the `of object` means which  the function is a reference to a method of an instance object. You can find more info in the [Delphi DocWiki](http://docwiki.embarcadero.com/RADStudio/XE8/en/Procedural_Types)
Comment: I actually spent quite a while researching "of object" and method references before asking, but I never saw anyone inserting a numeric type like "Single" before the "of object". What does that mean?
Comment: *Single* is just the return type of the function.
Comment: If I declare `Procedure DoSomething(var1: Single; var2, var3: Integer;GiveMeAValue: TGiveMeAValue = nil);`, how can I check if the caller actually passed a callback function so I can safely call it? Something like `if GiveMeAValue <> nil then GiveMeAValue(..);`


How to clone a class instance and change just one field in Objective C or Swift?

Question: Scala provides a way to change just one property when copying an immutable object. Does Objective C or Swift for that matter have a equivalent or is there any library that adds similar functionality?

https://coderwall.com/p/8wofhq/update-property-value-of-immutable-object-while-maintaining-immutability

NOTE: This question is about only referencing a single property not about updating an array of objects.
Comment: No, neither Obj-C, Swift, C++ or Java has such an operation in their grammar. They don't even have the concept of immutability so such an operation doesn't really make sense in them.
Comment: It would be ideal if you'd pick one language or the other; if you truly don't care, then you're really asking about Cocoa (Touch), and should retag.
Comment: @JoshCaswell Fair enough. Will do next time.
Answer: There's nothing built in, but it's easy enough to write a method that does this, using KVC to set the value:
@implementation NSObject (WSSCopyMutating)

- (instancetype)WSSCopyChangingValue:(id)val forKey:(NSString *)key
{
    id newObj = [self copy];
    [newObj setValue:val forKey:key];

    return newObj;
}

@end

This requires that the class you're copying conforms to NSCopying. setValue:forKey: will find the field you've named regardless of its public visibility or writeability.
Comment: Thanks I found more info about this from @bbum in this question: http://stackoverflow.com/questions/1502708/why-does-a-readonly-property-still-allow-writing-with-kvc


I am using nodejs version 20.10.0, but I am getting error that says you are using node js 15.0.1

Question: I am trying to build nexjs app, but once I run npm run dev the cmd is giving me the following error
You are using Node.js 15.0.1. For Next.js, Node.js version >= v18.17.0 is required.

actually I am using nodejs v20.10.0
when I run node -v, it shows v20.10.0
I don't know why, can any one help me figure out?
Comment: I am not sure what is the issue here, but one possibility is that what you're seeing might not be the actual Node.js version. Sometimes, other programs or command line tools might override or the version. If you are not using the NVM then install NVM and fire command `nvm use v20.10.0`. And then try to run your nextjs app using `npm run dev`.
Comment: I downloaded the nodejs v20.10.0 from the nodejs website and installed it, I don't thinks that this is the problem
Comment: check: 1. if both the error and `node -v` command are run in same terminal or different. 2. restart terminal. Also paste screenshot here if still not solved
Answer: Here are a few steps you can take to troubleshoot and resolve this issue:-
1.Clear Node.js Cache:-
Sometimes, caching issues can cause discrepancies. Try clearing the Node.js cache with the following commands:-
> npm cache clean -f

2. Reinstall Dependencies:-
If you've made changes to the Node.js version or other configurations, consider reinstalling the project dependencies:
> rm -rf node_modules npm install

Also, Crosscheck Your Nodejs environment.


How to print an NUnit test run's XML file as a nice-looking report on the command line?

Question: I have a suite of NUnit tests.  When they finish, I get a TestResults.xml file.  This file is very large and dense; I'd like to be able to peruse a simple human-readable report of the underlying results.  I'm led to believe that the provided nunit-console program can do that, but I can't figure out how.
How can I print the information described by TestResults.xml with nunit-console?
Note that running the tests is not the problem; my problem is figuring out how to display the results on the command-line.  I can't change how the tests are run, but I can do whatever I want with the results file.
Comment: You can find various NUnit report generators on GitHub and other places. One example I was looking at the other day was `Ghpr.NUnit`, which generates a HTML/JS report. It requires some setup obviously, but after that it generates whenever you run tests using the `nunit-console`. The result is bit complex for my taste, and I'm still looking for a report generator that makes sense to me, but you might find it to be useful. You can view a sample report on the GitHub page. https://github.com/GHPReporter/Ghpr.NUnit
Answer: The Test Result file isn't intended to be human-readable, except when used for debugging. It's a source for all the data about a test run from which human-readable reports may be generated.
There are two ways to generate a report

As a part of the test run itself.
After the run is finished, using the test result xml file.

Reports generated as part of the test run require a report writing extension. You would write such an extension following the documentation to produce the report in whatever format you require, like text or html, and give it a unique tag likemyreport.
You would install your extension and could then run the console runner including an option like
 --result:somefile.html;format=myreport

As you may guess, creating your own extension is a relatively advanced use of NUnit.
Another option, if you are familiar with XSLT processing, is to use the built-in report format user, together with an XSLT transform. In that case, the option is something like
 --result:somefile.html;transform=mytransform.xslt

You can also produce a report after the run is finished using the XML output file. The NUnit console program is not used in this case. You must use some standard program for creating reports from NUnit output (or a generic program taking XSLT transforms) or write your own program.
Comment: Where can I find a pre-made XSLT or extension that'll make a report on the console?


How can I make mouse-overs provide more description?

Question: In WoL, mousing over an ability, armor, or damage showed all of the statistics for it. HotS seems to have disabled this by default and I've toggled what seem to be the relevant "Gameplay" commands in single player but haven't been able to solve the issue.
Answer: I believe it's the "Display Game tooltips" options under the "Gameplay" menu


DisplayMemberBinding for list of objects in wpf

Question: I'm have listView which show Name of book and first Author:
<ListView.View>
        <GridView>
            <GridViewColumn Header="Name" Width="Auto" DisplayMemberBinding="{Binding Name}" />
            <GridViewColumn Header="Author" Width="Auto" DisplayMemberBinding="{Binding Authors[0].Name}" />
        </GridView>
    </ListView.View>

But i need to show not only name first author, but all author in collection separated by commas. This is my Model:
public class Book : IModel
    {
        public Book()
        {
            Authors = new List<Author>();
            Tags = new List<string>();
        }
        public string Name { get; set; }
        public List<Author> Authors { get; set; }
        public string ISBN { get; set; }
        public int Pages { get; set; }
        public List<string> Tags { get; set; }
        public int PublicationYear { get; set; }
        public PublicationHouse PublicationHouse { get; set; }
    }

And code behind XAML:
public partial class BooksView : ListView
    {
        public BooksView()
        {
            InitializeComponent();
            ItemsSource = FilesManager.books.Values;
        }
    }

Comment: Use a Binding Converter that converts an `IEnumerable` to string, or add another property (probably to a view model class) that already contains the result string.
Answer: What about making a separate property?
 public string MyAuthors { get {return return String.Join(", ", Authors.ToArray());} }

I would also recommend to implement INotifyPropertyChanged to avoid further problem in your Data Binding.


whats the difference between cache & http cache "reverse proxy"

Question: am having a bit of difficulty understanding the difference between the normal cache "memory,file,db,etc.." and the http caching "reverse proxy".
Example.
lets say i have a page divided into 3 parts.

movies
games
apps

and when i retrieve those parts from the db, i cache each part in its own key & when a new data is entered to any of those parts i flush the cache and remake it including the new data, so now each part will only update if there is something new was added.
on the other hand the http caching have something call ESI which u can include page partials that have a different cache life span from the main page which is perfect but
why would i need to use it ?
or what is the advantage over the first method ?
Edit

this is slimier to what i was after but still, why would u use/continue to use the reverse proxy over the below ?

https://laracasts.com/series/russian-doll-caching-in-laravel
https://www.reddit.com/r/laravel/comments/3b16wr/caching_final_html_from_view/
https://github.com/laracasts/matryoshka
Answer: A reverse proxy cache has a few benefits:

Requests served by the proxy never hit your webserver. It's typically
cheaper/easier to scale out your proxy servers (e.g. by using
commercial providers like Akamai) than to scale out your
webserver(s).
This means you can survive traffic spikes and denial of
service attacks with much less stress.
It also means you can serve
traffic that's not close to your origin webserver much faster - if
your site serves a global audience, latency can have a big impact on
your perceived response time.
You can also take your webserver off line, e.g. for upgrades, without affecting your end users.

Drawbacks of reverse proxy caching:

It's an additional layer of architecture, which brings complexity, maintenance, administration etc.
It may also require additional costs (most sites have separate infrastructure for the reverse proxy servers, or use a commercial CDN provider).
Your solution design needs to manage cache invalidation between even more layers - this can easily become complex and error prone.
This, in turn, means that debugging and testing the solution can be very hard. If the QA team report an incorrect page, you need to be able to find out where the item was served from - reverse proxy, application cache, database?
Comment: dam, that sound more complicated than i thought, thanx.


Water cooler faucet handle broke

Question: After a decade of use, it looks like my water cooler is slowly falling apart.
I am not sure of the proper terminology here, but the handle/lever part of the faucet broke off.

Am I able to buy just the handle and install it (not the entire faucet)
If I have to install the entire faucet, is there a guide/manual somewhere? I couldn't scavenge anything relevant.
Is there a temporary workaround that I could do to still use the faucet?

Image of the damage (blue, center):
Answer: I've not found an image to match the handles in the photo. Without a model designation, it's challenging to zero in on the same product, but the images I've found indicate there are similarities in your product and the parts available.
My search terms were "sunbeam water cooler handles" and could be modified by adding your model number for best results. I was surprised to see that WalMart carries replacement parts, but that's likely to be online and not necessarily available in stores. Amazon also popped up in the search results.

It appears that you may be able to dismantle the nozzle just above the opening if parts are available for that segment, or you should be able to remove the entire assembly for replacement as well.

Water cooler faucet handle broke


Thymeleaf th:each + spring MVC

Question: I'm a beginner with thymeleaf and Spring MVC.
I try to make a loop with images, but I think my controller return me empty list because when I check on my page it doesn't show my html with th:each.
I make a lot of research and based my code on Spring mvc tutorial : http://www.thymeleaf.org/doc/articles/springmvcaccessdata.html
Here are my code I don't understand my mistake.. I give you all my code hoping you'll find where is my error. I think my error is in my crontroller.
I thank you a lot for your help!
First my java class
public class Sponsors {

    private String image;
    private String href;
    private String name;
    private String id;

    public Sponsors(String image,String href,String name,String id) {
        this.image = image;
        this.href = href;
        this.name = name;
        this.id = id;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }

    public String getHref() {
        return href;
    }

    public void setHref(String href) {
        this.href = href;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

Here it's just a test to fill an arraylist with some Sponsors
public class GetSponsorsList {

    private List<Sponsors> listSponsors = new ArrayList<Sponsors>();

    public GetSponsorsList() {
        listSponsors.add(new Sponsors("@{/images/logo-***.jpg}","@{/recherche?res=***}","****","****"));
        listSponsors.add(new Sponsors("@{/images/logo-***.jpg}","@{/recherche}","****","****"));
        listSponsors.add(new Sponsors("@{/images/logo-***.jpg}","@{/recherche}","*****","*****"));
        listSponsors.add(new Sponsors("@{/images/logo-***.jpg}","@{/recherche}","*****","*****"));
        listSponsors.add(new Sponsors("@{/images/logo-***.jpg}","@{/recherche}","*****","*****"));
    }

    public List<Sponsors> getListSponsors() {
        return listSponsors;
    }

    public void setListSponsors(List<Sponsors> listSponsors) {
        this.listSponsors = listSponsors;
    }
}

Here is my controller
@Controller
public class HomeSponsors extends AbstractController {

    @ModelAttribute("sponsorsList")
    public List<Sponsors> sponsorsList() {
        return new GetSponsorsList().getListSponsors();
    }
}

And last this is my html
<!DOCTYPE html>

  <meta charset="UTF-8"/>

...

...

Comment: Where is your request mapping for this page?
Comment: But I don't use th:href to print my tab. So why should I need a request mapping?
Comment: Try to add @ControllerAdvice annotation in the controller class and set the request mapping in the same controller. Model attribute is only available for requests inside the controller. Using controllerAdvice annotation you will make available for all requests. Hope that helps
Comment: Thanx I'll try this :D
Comment: @Controller
public class HomeSponsors extends AbstractController {

 @RequestMapping(value = "sponsorsList", method = RequestMethod.GET)
    public List messages() {
        return new GetSponsorsList().getListSponsors();
    }
}
Comment: I change my controller to this but it doesn't work. I try to input @ControllerAdvise but i can't find any help that I can understand :/
Answer: Edwyn,
What I mean is something like this:
@Controller
@ControllerAdvice
public class HomeSponsors extends AbstractController {

    @RequestMapping("/sponsorsPage")
    public String sponsorsPage(Model model) {
        return "sponsorsPage";
    }

    @ModelAttribute("sponsorsList")
    public List<Sponsors> sponsorsList() {
        return new GetSponsorsList().getListSponsors();
    }

}

Comment: `@ControllerAdvice` is for something completely different... Don't add that to a `@Controller`.
Comment: Sorry :/ I'll do it.
Comment: Thank you a lot kimy! It's working now!
I don't know Deinum but if I don't put it, my website doesn't work.
Comment: @M. Deinum It is necesary if you want the model attribute to take effect in all request mapping, even outside this controller
Comment: Then still don't add it to a `@Controller` it should be a separate component, especially not here because there is some `AbstractController` class with who knows what in there and you probably don't want to have that globally applied.

Thymeleaf th:each + spring MVC


QR code decoding & encoding in an android application

Question: I am working with android API v2.2.
I want in my application i can work with QR reader. means in a button click it open the camera and can able to read QR code.
Is it possible generate QR code through application?
How can i work with these? I dont have any idea.
Plz tell me what should used for this(is there any lib or api available for this) If yes then what should be the process.
Give me a sample example.
Thank you
Comment: try this also http://stackoverflow.com/search?q=%5Bandroid%5D+qr+code
Answer: Try the zxing library : http://code.google.com/p/zxing/
Comment: I am not getting. if possible plz describe me
Comment: There is a tutorial in the wiki on how to get started : http://code.google.com/p/zxing/wiki/GettingStarted
Answer: you can use either
zxing library : http://code.google.com/p/zxing/
or
ZBar bar code reader here http://sourceforge.net/projects/zbar/?source=dlp


use cypress to change angular proxy.conf.json headers

Question: Currently using Cypress 12.8 and Angular 15.2.  I have a proxy.conf.json file set up in an Angular project that sends requests for localhost:4200/api to server.com/path/to/api that sends a variable to the server in the header.  Something like:
headers: {
  foo: baz
}

The foo header is read by the api and depending on its value, different sets of data are returned.  Based on what the api returns, Angular displays different elements on the page.  So far so good.
But I want to run some Cypress tests and change baz to bar and foobar and rebar without having to stop the test and re-serve the app.  The docs make it sound like this should be possible, but what I have isn't working.
cy.intercept({pathname: '/testme', query: '*'}, (req) => {
      req.headers['foo'] = 'rebar'
}).visit('http://localhost:4200/testme');

The angular page displays with baz, which is what is in proxy.conf.json.
I think I just have dueling proxies going on.  Cypress intercepts the .visit('http://localhost:4200/test') command and sets foo=rebar, then passes control on to Angular, which uses the setting in its proxy and set foo=baz when it requests server.com/path/to/api.
So far the best solution I've come up with is to have multiple proxy.conf.json files, multiple configurations in my angular.json and then do concurrently "ng serve --configuration=rebar" "cypress open" run the tests for rebar, then repeat for bar and baz.
Any other ideas?
Thanks!
Answer: A couple of options come to mind.
From the Angular side, add Serve configurations. Add a non-proxy configuration to angular.json
{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "app": {
      ...
      "architect": {
        ...
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "configurations": {
            "production": {
              "browserTarget": "app:build:production",
              "proxyConfig": "src/proxy.conf.json"
            },
            "development": {
              "browserTarget": "app:build:development",
              "proxyConfig": "src/proxy.conf.json"
            },
            "qa": {
              "browserTarget": "app:build:qa"
            }
          },
          "defaultConfiguration": "development"
        },

In package.json
{
  "name": "app",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "start:qa": "ng serve --configuration=qa",

From the Cypress side, use mocks in the intercept to return the data you need for the test.
cy.intercept({pathname: '/testme', query: '*'}, (req) => {
  req.reply({something})
})

Comment: Thanks.  That was pretty much what I came up with too.  I was hoping for a way to avoid adding a bunch of different settings and fixtures for all of the different roles that I have to test.  3 wouldn't be too bad, but the client wants almost a dozen roles with slightly different settings and there's just no talking them out of it.  Going to have to increase their budget for all of that testing I guess.


How to print an Array of strings after passing it to another function

Question: After receiving a certain number of students and their names, the program stops after passing it to another function to print it. How do I change this?
#include <stdio.h>
#define MAX_STUDENT 1024

void print_name(char* surname,char* first_name,int n_students)
{
    int i,b=1;
    for(int i=0;i<n_students;i++)
    {
        printf("%d. %s, %s\n",b,first_name[i],surname[i]);
        b++;
    }
}
int main()
{
    int n_students,i,b=1;
    char surname[MAX_STUDENT][20],first_name[MAX_STUDENT][20];

    printf("number of students:");
    scanf("%d",&n_students);

    for(i=0;i<n_students;i++)
    {
        printf("%d. ",b);
        scanf("%19s %19s",&surname[i],&first_name[i]);
        b++;
    }
    print_name(surname,first_name,n_students);

    return 0;
}

Comment: @Jabberwocky i know but im only using what our professor has taught us yet and structs isnt one of them yet.
Comment: Slightly off topic: you should learn about structs.
Comment: mopheadkim, 1) Why not use all of the good answer of your 1 hour earlier question?  2) Save time, enable all compiler warnings.
Comment: @chux-ReinstateMonica i actually forgot to post that with a function so i asked again
Comment: mopheadkim, The prior one has the same unfixed problem as this one.  Many of your code problems with emit a warning when 1) all warnings are enabled, 2) using a good compiler. Faster then posting on SO.
Answer:
Match types between function arguments and what are passed. In main, you are passing 2D-arrays as arguments of print_name function , but the you are using character pointers as arguments in definition of print_name function
Remove & from arguments of scanf() to pass data having correct type and avoid undefined behavior.

#include <stdio.h>
#define MAX_STUDENT 1024

void print_name(char surname[][20],char first_name[][20],int n_students) /* fix 1 */
{
    int i,b=1;
    for(int i=0;i<n_students;i++)
    {
        printf("%d. %s, %s\n",b,first_name[i],surname[i]);
        b++;
    }
}
int main()
{
    int n_students,i,b=1;
    char surname[MAX_STUDENT][20],first_name[MAX_STUDENT][20];

    printf("number of students:");
    scanf("%d",&n_students); /* note: & here is necessary */

    for(i=0;i<n_students;i++)
    {
        printf("%d. ",b);
        scanf("%19s %19s",surname[i],first_name[i]); /* fix 2 */
        b++;
    }
    print_name(surname,first_name,n_students);

    return 0;
}


Recently exposed pipe seems to go nowhere in lawn

Question: Just noticed this pipe in my front lawn. Must have been recently exposed, possibly by the landscapers. Pipe is open and not clogged. Seems to have been buried and not go anywhere? Any idea what it is?
Comment: In some areas this is a way to drain the run off it fills that area and goes over the curb. Cutting the curb may not be allowed and even end up with large fines but allowing the water to flow over the curb was legal.
Comment: do you have smoke bombs? That can find the other end, but I suspect it connects to your gutter's downspouts.
Answer: It's a drain. What, exactly, it's draining is not obvious from the limited view of the picture, but it's carrying water from some higher point to this point, where it can (as Ed Beal notes) flow over the curb and into the street.
Grab an umbrella (and possibly a flashlight) and revisit it in or soon after a rain storm.
It may simply be removing excess water from part of the yard, or it may serve other purposes. But it's definitely a drain.
Comment: It probably should _not_ be covered, @erg0s4m. It will drain better this way.
Comment: Thank you. It probably does connect to the downspout. I'm debating whether it needs to be covered up again or not.


Retrieving data from GtkListStore

Question: I have a created a GUI with a tree view in Glade. This is the XML file:
<?xml version="1.0" encoding="UTF-8"?>
<interface>
  <requires lib="gtk+" version="2.24"/>

  <object class="GtkListStore" id="liststore1">
    <columns>

      <column type="gchararray"/>
    </columns>
  </object>
  <object class="GtkWindow" id="window1">
    <property name="can_focus">False</property>
    <child>
      <object class="GtkTreeView" id="treeview1">
        <property name="visible">True</property>
        <property name="can_focus">True</property>
        <property name="model">liststore1</property>
      </object>
    </child>
  </object>
</interface>

I am trying to set some data in the list and retrieve it with the following
code:
#include <gtk/gtk.h>

int main(int argc, char * argv[]) {
    GtkBuilder* gtkBuilder = gtk_builder_new();
    GtkWidget* mainwin;

    gtk_init(&argc, &argv);

    gtk_builder_add_from_file(gtkBuilder, "test.glade", NULL);

    mainwin = GTK_WIDGET(gtk_builder_get_object(gtkBuilder, "window1"));

    // set treeview data
    GtkTreeView *treeview = NULL;
    GtkTreeModel *model = NULL;
    GtkListStore *liststore = NULL;
    GtkTreeIter iter;
    gchar* data = "Hello World";
    gchar* item = NULL;

    treeview = GTK_TREE_VIEW(gtk_builder_get_object(gtkBuilder, "treeview1"));
    model = gtk_tree_view_get_model(treeview);
    liststore = GTK_LIST_STORE(model);

    gtk_list_store_append(liststore, &iter);
    gtk_list_store_set(liststore, &iter, 0, data, -1);

    gtk_tree_model_get(model, &iter, 0, item, -1);

    printf("item: %s\n", item);

    g_object_unref(G_OBJECT(gtkBuilder));

    g_signal_connect(mainwin, "destroy", G_CALLBACK(gtk_main_quit), NULL);

    gtk_widget_show(mainwin);
    gtk_main();
}

However, the data is neither displayed in the tree view nor can I retrieve the previously inserted data. I do not know whether the data was correctly inserted into the list and/or if I am just trying to receive it the wrong way.
Answer: From the gtk_tree_model_get () documentation:

Gets the value of one or more cells in the row referenced by iter .
  The variable argument list should contain integer column numbers, each
  column number followed by a place to store the value being retrieved.
  The list is terminated by a -1. For example, to get a value from
  column 0 with type G_TYPE_STRING, you would write: gtk_tree_model_get
  (model, iter, 0, &place_string_here, -1), where place_string_here is a
  gchararray to be filled with the string.

So, you should change in your code:
gtk_tree_model_get(model, &iter, 0, item, -1);

To:
gtk_tree_model_get(model, &iter, 0, &item, -1);

Also notice:

Returned values with type G_TYPE_OBJECT have to be unreferenced,
  values with type G_TYPE_STRING or G_TYPE_BOXED have to be freed. Other
  values are passed by value.

So, you will need to free item, e.g. g_free (item);, after use.
EDIT:
The treeview has no TreeViewColumn and neither a CellRendererText.
I've added those to your glade file:
<?xml version="1.0" encoding="UTF-8"?>

<interface>
  <requires lib="gtk+" version="3.0"/>
  <object class="GtkListStore" id="liststore1">
    <columns>

      <column type="gchararray"/>
    </columns>
  </object>
  <object class="GtkWindow" id="window1">
    <property name="can_focus">False</property>
    <child>
      <object class="GtkTreeView" id="treeview1">
        <property name="visible">True</property>
        <property name="can_focus">True</property>
        <property name="model">liststore1</property>
        <child internal-child="selection">
          <object class="GtkTreeSelection" id="treeview-selection1"/>
        </child>
        <child>
          <object class="GtkTreeViewColumn" id="treeviewcolumn1">
            <property name="title" translatable="yes">column</property>
            <child>
              <object class="GtkCellRendererText" id="cellrenderertext1">
                <property name="height">40</property>
              </object>
              <attributes>
                <attribute name="text">0</attribute>
              </attributes>
            </child>
          </object>
        </child>
      </object>
    </child>
  </object>
</interface>

It should work now:
Comment: Thanks, data retrieval works now. However, it still does not display anything in the `GtkTreeView` when I run the program. Is there anything else I need to do to display the data? Maybe in the Glade editor or programmatically?
Comment: oh i just focus on the printf... let me check @nautical ... I think you don't have a treeview column and cell renderer

Retrieving data from GtkListStore


Insertion of element in the array-

Question: I'm not so good with C so please help me in this project where I want the user to pick what operation he wants to perform, where I just completed the insertion part of it and here the code is giving the garbage values after the insertion. This is my code so far-
#include<stdio.h>
#include<stdlib.h>

int main(){
    int n, opt, i, insOpt, pos, newEle;
    printf("Enter the number of elements you want to store in the array: ");
    scanf("%d", &n);
    int* arr = (int*) malloc(n*sizeof(int));
    printf("Enter all %d elements you want to store in the array: ", n);
    for(i=0; i<n; i++){
        scanf("%d", &arr[i]);
    }

    options:
    printf("Enter the operation you want to perfrom: \n 1. Insertion \n 2. Deletion \n 3. Traversing \n 4. Searching \n 5. Sorting \n 6.Reverse of array \n");
    scanf("%d", &opt);
    switch (opt)
    {
    case 1:
        n++;
        int* newArr=(int*) realloc(arr, n*sizeof(int));
        for(i=0; i<n-1; i++){
            newArr[i] = arr[i];
        }
        free(arr);
        arr = newArr;
        printf("Pick where you want to insert: \n 1. Beginning \n 2. Middle \n 3. End \n 4. Position");
        scanf("%d", &insOpt);
        switch (insOpt)
        {
        case 1:
            pos=0;
            break;
        case 2:
            //
            break;
        case 3:
            pos=n;
            break;
        case 4:
            printf("Enter the position: ");
            scanf("%d", &pos);
            break;
        default:
            printf("Please pick between 1 to 4: ");
            break;
        }
        printf("Enter the element: ");
        scanf("%d", &newEle);
        for(i=n-1; i>=pos-1; i--){
            arr[i]=arr[i-1];
        }
        arr[pos-1] = newEle;
        printf("Array after insertion: ");
        for(i=0; i<n; i++){
            printf("%d ",arr[i]);
        }
        break;

    default:
        break;
    }

    return 0;
}

Now, when I try to insert the element at the beginning it gives me some random values after 8-

Array after insertion: 8 1512474568 5 1571285629 1432712575 3
Answer: For starters this code snippet
    for(i=0; i<n-1; i++){
        newArr[i] = arr[i];
    }
    free(arr);

does not make sense. The reallocated array already contains existent elements and the pointer arr in this case is invalid. So remove this code snippet.
If the user selected the end position then the value of pos shall be n - 1 instead of n. on the other hand, if the user selected the position in the beginning of the array then pos shall be equal to 0.
In this case the following for loop will look like
    for ( i=n-1; i != pos; i--){
        arr[i] = arr[i-1];
    }
    arr[pos] = newEle;

Comment: I saw a video about realloc(), maybe I got confused! Thank You for helping, I removed that code and it is working fine! :)

Insertion of element in the array-


When writing a startupbean (@Singleton @Startup @PostConstruct) is there anyway for me to get the ServletContext?

Question: So I am trying to create a task that fires off at regular intervals and I want it to get some things from the ServletContext:
<code>...
@Singleton
@Startup
public class InitTimers {
    @Resource
    private TimerService timerService;

    @PostConstruct
    public void initTimer() {
        ...
        // I want ServletContext here, how do I?
        ServletContext context = getServletContext();
        ...
    }

    @Timeout
    public void timeout(Timer timer) {
        ...
    }
}
</code>
Can an EJB 3.1 @Startup @Singleton access the ServletContext?
Answer: No, this is not possible.  I recommend moving the logic to a ServletContextListener contextInitialized method, and then call the singleton to do startup work as required.


NSIS How do I unhide a section when something returns a specific value?

Question: I have an installer created using the HM NIS Edit. And I want to be able to unhide the section called VDF if my check finds out its not installed. And hide it when it's installed and also don't execute that embed installer.
I hope I made myself clear.
This is the function:
<code>Function .onInit #Check's wether the installer is in your installation folder. onInit means that it checks for that even before the installer is initialized.
  ${If} ${FileExists} "$EXEDIR\VDF2012-18.104.22.168.Client.exe"
    MessageBox MB_OK "VDF found"

  ${Else}
    MessageBox MB_OK "The Visual DataFlex setup was not found in the installation folder. However the installation of $(^Name) will still continue."

  ${EndIf}
</code>
Answer: To hide a section you must change its name to a empty string.
To check/uncheck a section you should use the helper macros in sections.nsh.
<code>!include sections.nsh

Section "VDF" SID_VDF
#Install VDF
SectionEnd

Function .onInit
${IfNot} ${FileExists} "$EXEDIR\VDF2012-18.104.22.168.Client.exe"
  !insertmacro UnselectSection ${SID_VDF}
  SectionSetText ${SID_VDF} ""
${EndIf}
FunctionEnd
</code>
To unhide you would give it a non-empty name but it is usually less work to show it by default and hide when required...


I'm trying to take a record from, for example row 1 and insert it into row 3

Question: I have a field called RecordType that has three different records, 1, 2, 3. Each hold different records. I want to take the the balance from another field I have called Limit from RecordType 1 and insert it into RecordType 3 but I'm just unsure on how to do this. This will be going into a Crystal Report and I want to be able to suppress the RecordType 1 altogether.
I've tried a simple case statement but that's about it, I can't really think of any other ways to do it (I'm sure there's loads).
CASE
    WHEN FA.RecordType = 3 THEN
        FA.Limit
END AS LimitTest

Current results

Record Type
Limit

1
5,000,301

2
0

3
0

Expected Results

Record Type
Limit

2
0

3
5,000,301
Comment: what if Record type 1 also has some value like `1000`.
Comment: i mean what if Record type 1 and 3 both have some values, like in above case since type 3 has 0 so we assume to make it to `sum` or apply `max` or something like that, but what if type 1 has 5000 and type 3 has 1000 now what will be the result. You cannot just ignore the value in type 3
Comment: also record are limited to 3 type only?
Comment: @DarkRob Record Type 1 is a recurring Record Type and has multiple values.

It looks something like this:
RecordType | Limit
         1         | 5,000,301
         2         | 0
         3         | 0
         1         | 43,260,301
         2         | 0
         3         | 0
etc...
Comment: Sorry my formatting is terrible I'm not sure how to do it properly. But to answer your question no type 1 & 3 will never have the same value as 3 never has a value. I want to basically move the value from type 1 into type 3
Comment: then what is the problem in ans of @Gordon Linoff ?
Comment: It's not clear whether you are trying to `select` data for a report and, in the process, filter and alter some of the data. You also refer to inserting and updating and generally fiddling about in the original table. Do you want to change the contents of the table or extract and modify data for a report?
Answer: You seem to want to combine the limit for types 1 and 3.  You can do this with aggregation on an expression:
select (case when recordtype = 1 then 3 else recordtype end) as recordtype,
       sum(limit) as limit
from t
group by (case when recordtype = 1 then 3 else recordtype end);

Answer: You can try using sub-query and a Case statement in your select statement, for example:
SELECT [RecordType],
    (CASE [RECORDTYPE] WHEN 3 THEN
                        (SELECT LIMIT from Table_1 WHERE RECORDTYPE = 1)
                    ELSE LIMIT END) LimitTest
FROM TABLE_1 WHERE RECORDTYPE <> 1

Answer: You said:

Sorry my formatting is terrible I'm not sure how to do it properly. But to answer your question no type 1 & 3 will never have the same value as 3 never has a value. I want to basically move the value from type 1 into type 3

Which makes me think that this would be the simplest:
DELETE FROM table WHERE RecordType = 3
UPDATE table SET RecordType = 3 WHERE RecordType = 1

3 never has a value so let's get rid of them first, then 1 has the value but we want it to be 3 so just update all the 1s to be 3s instead
If you're not into deleting it, just mask it instead:
SELECT 3 as RecordType, Limit FROM table WHERE RecordType = 1

Answer: If you want to move value from type 1 to type 3 then do simple update in your query.
   update t set t.value= t1.value from table as t , table as t1 where t.recordtype=3 and t1.recordtype=1

or
   delete from table where recordtype = 3
   update recordtype set recordtype=1 where recordtype=3

This will work may be
Answer: SELECT
    IIF(A.RECORDTYPE = 1,3,A.RECORDTYPE) AS RECORDTYPE,
    A.LIMIT
FROM
(
    SELECT 1 RECORDTYPE,5000301 LIMIT UNION ALL
    SELECT 2 RECORDTYPE,0 LIMIT UNION ALL
    SELECT 3 RECORDTYPE,0 LIMIT
) A
WHERE A.RECORDTYPE IN (1,2)
ORDER BY RECORDTYPE

Check this if works for you.


Can OpenEBS support across AWS regions?

Question: Is there a way to use openebs across aws regions if I have a vpn, or vpc peering set up? I have seen that OpenEBS supports across AZs in a region but want to know whether I can take backup across region?
Answer: OpenEBS across zone is supported in AWS. You can go through integration section of openebs docs site.
Tried creating the zone using
<code>kops create cluster --name=<cluster_name>.k8s.local --vpc=<vpc_id> --zones=<zone1_name>,<zone2_name>,<zone3_name>
</code>
Post that regular installation of OpenEBS.

Can OpenEBS support across AWS regions?


Distribution of a maximum

Question: Randomly select $n$ numbers from ${\{1,2,\dots,m\}}$ without replacement, and order the chosen elements increasingly: $X_1 < X_2 < \dots < X_n$
And we can view each $X_i$ as a random variable, and we can get $\mathbb{E}(X_i) = \frac{(m+1)i}{n+1}$
And we can define $Y_i=|X_i-\mathbb{E}(X_i)|$ which is the distance of each variable to its corresponding expectation.
And we can also define $Z = \max_{1 \le i \le n} Y_i$
So what is the distribution of $Z$?
[Updated]
Any bound of $Z$ is helpful.
[Updated]
I have re-posted the question at Mathoverflow:
https://mathoverflow.net/questions/78822/distribution-of-a-maximum
People there gave some new ideas.
Comment: @MichaelHardy I've been guilty of using "randomly" to mean "uniformly distributed", although generally only for uniform distributions over a finite set.
Comment: @MartinSleziak This is the problem I think is interesting.
Comment: Is the choice of numbers done with replacement or without?
Comment: You haven't said what the distribution of the original randomly selected numbers is.  Often people say "randomly" when they mean "uniformly distributed", but I think that's on the sloppy side; I don't know that I've ever seen a probabilist or statistician do that.  Whether this is with or without replacement should also be made explicit.
Comment: I have updated that the selection is without replacement.
Comment: @ChrisTaylor withou replacement.
Answer: Yours is an interesting question to ask, but hardly simple to answer. The following is not an answer to your question, but is given to offer certain insight into the distribution.
I ran several simulations to get an idea about distribution of $Z$. I did that for $m=100$ and $m=50$ for different values of $1 \le n < m$.

The code used to simulate histograms is as follows:
<code>MathSE73091Histogram[m_Integer, n_Integer, samples_Integer,
  opts : OptionsPattern[ListPlot]] :=
 Module[{means = (m + 1)/(n + 1) Range[n], data, omega = Range[m]},
  data = Tally[
    Table[Max@Abs[Sort[RandomSample[omega, n]] - means], {samples}]];
  data[[All, 2]] /= Total[Part[data, All, 2]];
  ListPlot[data, opts]
  ]
</code>
Comment: what software do you use?
Comment: @FanZhang Sorry for not mentioning this in the post. I used _Mathematica_, v8.
Answer: This is a partial answer to an analogous problem. Assume the numbers are chosen independently and uniformly in the continuous interval $[0,m]$. Then, $\mathrm E(X_i)=x_i$ with $x_i=im/(n+1)$ for every $1\leqslant i\leqslant n$.
For small enough values of $z$, $[Z\leqslant z]$ is realized if and only if each interval $[x_i-z,x_i+z]$ contains exactly one value of the sample. More precisely, these intervals are disjoint for every $z\leqslant z_*=m/(2(n+1))$ and, for such values of $z$, $\mathrm P(Z\leqslant z)=n!(2z/m)^n$.
Thus, the density of the distribution of $Z$ on the interval $(0,z_*)$ is $f(z)=n!n(2/m)^nz^{n-1}$. The situation for larger values of $z$ is more complicated.
Answer: This answer addresses your update "Any bound of $Z$ is helpful."  It does not give the probability distribution of $Z$.
For fixed $m$ and $n$ with $n < m$, we have $$Z \leq n \left(\frac{m+1}{n+1}-1\right),$$ and for fixed $m$, where $n$ is allowed to range over all possible values from $1$ to $m$, we have $$Z \leq \left(\sqrt{m+1}-1\right)^2.$$

For the first inequality, let $m$ and $n$ be fixed with $n < m$.  So $\frac{m+1}{n+1} > 1$.  Thus the maximum possible value of $\left|X_i - \frac{(m+1)i}{n+1}\right|$ occurs for one of the extreme values in an extreme in the other direction sample.  In other words, the largest possible value of $Z$ occurs with $Y_n$ when the sample $\{1, 2, \ldots, n\}$ is chosen or with $Y_1$ when the sample $\{m-n+1, m-n+2, \ldots, m\}$ is chosen.  By symmetry, these two values should be equal, and that is the case: In the first sample, we have $Y_n = \left|n - \frac{(m+1)n}{n+1}\right| = n \left(\frac{m+1}{n+1}-1\right)$, and in the second sample we have $Y_1 = \left|m-n+1 - \frac{m+1}{n+1}\right| = (m+1)\left(1 - \frac{1}{n+1}\right) - n = n \left(\frac{m+1}{n+1}-1\right).$  Thus $Z \leq n \left(\frac{m+1}{n+1}-1\right).$
To see the second inequality, just use calculus to maximize the expression $f(n) = n\left(\frac{m+1}{n+1}-1\right)$.  We get that $f(n)$ is maximized when $n = \sqrt{m+1}-1$, and thus $Z \leq \left(\sqrt{m+1}-1\right)^2$.
As an illustration of this last result, consider the numerical work posted by Sasha.  The largest values of $Z$ occur on the plots for which $n$ is closest to $\sqrt{m+1}-1$.

Distribution of a maximum


Is an outlet with a switched neutral dangerous?

Question: I have a switch that control the outlet at my home. The outlet is located on the ceiling of a room. The switch opens/closes the neutral line (not hot).
How dangerous is this for a house? I plan to remove the outlet, and simply connect a light bulb.
The switch should still turn on/off the light but not sure if switching the neutral line on/off is a good idea.
Answer: It is against code but not necessarily all that dangerous. The classic problem is that when you are changing a light bulb, if hot is switched off then the socket is totally dead. If neutral is switched instead then hot is still present in the socket and a short from hot to ground will complete a circuit. Of course, similar problems can happen with a circuit where hot and neutral are reversed, which is often found in the wild (or at least in my old house...), so for anything beyond a simple light bulb replacement (which should be trivial and safe, as long as the bulb is not stuck or broken), the proper procedure is to turn off the breaker and not rely on the switch for safety.
However, it should be relatively easy to fix. There are some really wacky scenarios, but the two likely situations should be easy to fix. In both cases, replacing a receptacle with a hardwired light fixture makes no difference - the problem and solution are the same either way.
Existing Scenario 1: Power -> Receptacle -> Switch (aka Switch Loop)
Power hot and neutral go to receptacle box. Hot connects to the receptacle directly. Neutral connects to a wire going to the switch. Another wire comes back from the switch to the neutral connection of the receptacle.
In this case, changing how the wires are connected in the receptacle box will solve the problem.
Existing Scenario 2: Power -> Switch -> Receptacle
Power hot and neutral go to switch box. Switch is connected to neutral wire. Hot is connected to a hot wire going to the receptacle. The other connection on the switch is connected to a neutral wire going to the receptacle.
Similar to the first scenario, changing how the wires are connected in the switch box should solve the problem.
Answer: Here is where the danger lies:
If you or someone else decides to replace the plug with a light fixture, you might turn the switch off & go test the plug with a voltmeter.  You insert the probes into the slots and you get no voltage reading.  The average person would assume that means it is safe to handle the wires, but it isn't because all the switch disconnected is the neutral.
What you have at that point is a hot (black) wire that is still hot.  But also, if there is a load connected to the outlet (such as a lamp) the neutral on the outlet is also hot because it is no longer bonded to the neutral bar in the breaker panel.
That is a real danger, which is why the NEC does not allow it.
Situations like this are the reason you should always  test wires with a multimeter or probe type volt meter, then test them again with a non-contact voltage detector before handling them.  The non-contact detector detects the electromagnetic field produced by AC voltage.  It does not need a neutral.
I suggest getting an electrician to wire it properly.  If you are an electrician, but don't know for sure how to change the connections, a new question that includes details of the wires in each box will probably get you the information you need to make it right.
Regarding electricity, if you aren't sure, it's always best to ask first.


How to develop apps using PhoneGap or AdobeAir?

Question: I'm trying to understand how programs like PhoneGap and Adobe Air work, that allow you to 'write once and run anywhere' on mobile platforms. The way I understand it now is that you build your application as a web app using either HTML5, or flash, or I don't know what, and it takes in those files and converts them to the proper types for each mobile OS. Assuming this is correct, what I would like to know is, what the options for developing web apps that are able to be converted into apps are; and what the most popular platforms to use/learn flash, or html5, or JavaScript, or I have no idea what are.
I want to build a web app to deploy across multiple phone platforms, but I don't know where to start. Thanks for the help!
Answer: You use tools like PhoneGap to access native device API's through JavaScript. If you don't need access to these API's you can write a HTML5 app and install it using "Add to home screen" etc.
As HTML5 matures, more and more of the device API's are actually directly available through HTML5 (for instance GPS), so depending on what you want to do access it might be in/scheduled to be part of the Device API.
Write once and run anywhere
There are different frameworks that lets you deploy to multiple platforms through the device specific install process. These tools usually work in 2 ways. Run in an embedded browser, or compile to native code.
PhoneGap runs the HTML5 part of your app in an embedded browser. Other tools like MonoTouch actually cross-compiles to native code, so they run on the bare metal.
Cross platform using HTML5
There are plenty of frameworks you can use to make mobile apps with HTML5. These usually help make the app "feel native", and includes abstractions over device specific idioms that differ between the different devices.
Popular frameworks includes Sencha Touch, JQuery Mobile and a bunch of others.
If you want the users to install the app through the AppStore/Market etc. then a solution like PhoneGap is a good option. If you don't care about that you can write your app and add a meta tag like
<code><meta name="apple-mobile-web-app-capable" content="yes">
</code>
and when you add it to the home screen it'll look just like any other app and run in an embedded browser without the browser window etc. You can add offline capabilities using HTML5 and synch when users go on-line etc. all just using HTML5.
Have a look at the Sencha touch app gallery to see what is possible with this technology.


rebase - automatically continue if rerere resolved all conflicts

Question: Git rerere provides for reuse of previous conflict resolutions during rebase, and can even stage the resolved files by setting rerere.autoupdate = True (as detailed in another question).  However, even if all conflicts are resolved and all files staged, I still have to run git rebase --continue to continue the rebase operation.
How can I automatically continue if rerere has resolved all conflicts and staged all changes?
Comment: Another question has a nice answer http://stackoverflow.com/a/27513648/259946
Comment: I don't know if @frasertweedale meant the question this way, but I'm using `git rebase -i` in a script (with `GIT_SEQUENCE_EDITOR`).  So not automatically continuing/skipping resolved conflicts is a PITA, because either I have to do it manually or emulate the nicety of `if ! git rebase […]; then git rebase --abort; fi` with lots of `git reset`, `git cherry-pick`, etc. and thus lots of opportunities to mess up.
Answer: Rebase should use more the rerere-autoupdate from Git 2.14.x/2.15 onward (Q3 2017).
See commit f826fb7, commit 8d8cb4b, commit 6f0e577, commit 9b6d7a6, commit 5fb415b, commit fd4a3f4 (02 Aug 2017) by Phillip Wood (phillipwood).
(Merged by Junio C Hamano -- gitster -- in commit 1016495, 22 Aug 2017)
That is because now:

rebase: honor --rerere-autoupdate
Rebase accepts '--rerere-autoupdate' as an option but only honors it
  if '-m' is also given.
  Fix it for a non-interactive rebase by passing on the option to 'git am' and 'git cherry-pick'.
rebase -i: honor --rerere-autoupdate
Interactive rebase was ignoring '--rerere-autoupdate'.
  Fix this by reading it appropriate file when restoring the sequencer state for an interactive rebase and passing '--rerere-autoupdate' to merge and cherry-pick when rebasing with '--preserve-merges'.
Comment: Note that this does not work for `rebase --continue`, i.e. you already need to specify it for the initial rebase command.
Answer: No. Rebase or Merge does not automatically provide a provision for auto-commits when conflicts arise. You could understand more about git merge here in 'merging' heading. git config also does not provide an option for auto commits while rebasing. Note that you could choose not-to commit while merging.


How can I temporarily close an arched interior passageway?

Question: I need to close an opening and I am not sure the best way to do it.
The goals are

Low cost
Good sound insulation
Easy to take apart with minimal damage to the existing walls.

It doesn't have to look perfect

edit: my original thought was  to attach drywall panel to each side of the  opening (bout 7 inch apart) and to screw them to the preexisting frame without using additional studs. To remove, unscrew the screws, fill with mud and paint again. what do you think of this solution?
edit: task mostly done. I probably need to paint it or hide it behind a curtain. but is is up and block sounds pretty well. I used the two plywood system of the selected answer without  weather striping.
I have also cut the plywood to smaller pieces for easier handling
Comment: I have to ask: why?
Comment: Its temporary because we done own the place and want to return it in the same state as we got it. Its OK to cover the changes with some mud and paint, but it needs to look unchanged in the post rent inspection.
Comment: "It doesn't have to look perfect" and "It doesn't have to look good" are, in my opinion, two different things. You've said the former, but your own solution and most of the answers seem to be the latter. Can you clarify?
Comment: How temporary?  What does "not look good" mean?  If it looks like a construction site is that ok?  Or just a bad DIY plaster job?  Do you intend to paint it?  Does it need an openable door (for fire egress, etc?)
Comment: Also, its needs to have very good noise insulation, but visually, it just need to be good enough.
Comment: @GManNickG one example could be using a dressing room as a nursery.  Another could be an odd little bit of hallway as an office next to a TV room (examples picked because of the sound blocking requirement) I agree that it's good to know *why* because that may affect *how*.
Comment: To me it sounds like some sort of a musical instrument practice room.
Comment: @GManNickG The area beyond the opening is a room that has an additional entrance through the backyard. we are having some guests over and we want  them to enjoy a quite room.
Comment: @yigal: Gotcha. :) Mostly asking for the reason Chris mentioned - it's good to double-check it's not an X-Y problem.
Answer: I would take two sheets of plywood or similar material, cut slightly larger than the opening, place one on either side, and use a few big bolts & nuts driven through to pull the panels towards each other. The tension from the bolts will hold the contraption in place; some weatherstripping or the like on the edges will create a better seal and protect your walls. You can fill the inside cavity with fiberglass insulation and paint the wood the same color as your walls.
Comment: Exactly what I would suggest.  Perhaps a little tape or fabric on the edges of the boards to minimize damage to wall paint might be a good idea.
Comment: I might suggest a manufactured/"particle board" material rather than plywood, since the latter seems likely to warp under the tension or changes in humidity etc.
Comment: I am starting to lean towards this solution. which plywood should I pick for maximum noise insulation?
Comment: @yigal I would take R's suggestion and go with the thickest MDF or OSB you're comfortable with. The keys to sound insulation are creating an air-tight seal and putting as much mass in the way as possible; a thick tape or strip of rubber on the edges will help with the first part (like a gasket); putting soundproofing insulation in the cavity will help with the second. You could back the boards with mass-loaded vinyl, too, but that stuff's not cheap.
Comment: which bolt should i use? carriage bolt or hex bolt?

Also, the preexisting wall is  kinda thick - 7.5 inch,  adding 1.5 inch for the two panels and some extra for the nut means that i need 10 inch bolts. The only ones that I found are 1/2 inch thick and costs $2.3 each at home depot. - I need about 20. where do I get thinner, less expensive bolts?
Comment: @yigal: You probably want an intermediate wall to screw the plywood covers into. Something like itserwood's answer: https://diy.stackexchange.com/a/121460/7121. If you go the bolt route, you should only need four or five bolts, IMO. You can buy threaded rod and cut it, use a pair of nuts at each end to lock things together, per-rod.
Comment: @GManNickG  Threaded rod. Brilliant. The reason why I figured that I need about 20 bolts is that I cant possibly lift the whole 8' x 4' panels by myself and I thought to cut the 8' panel into four 2' x 4' panels and then use 4 bolts per panel pair. Also, note the moulding close to the floor, I need 5.5'' x 4'  panel with two bolts just for that.
Comment: @yigal: Makes sense. Consider also squeezing/sticking molding all the way around the opening so that everything is flush to the same plane, to minimize cuts.
Answer: One solution that might look reasonable is to get a bookshelf (IKEA Billy are cheap) larger than the opening and stand it against the opening. For better sound insulation I'd combine this with Robert's answer: put a sheet of ply on the other side of the opening and bolt it to the back of the bookshelf or screw bookshelf and ply to some intervening 2x4 + shim. The cavity can be filled with loose sound-insulating material.
Answer: For a clean, elegant appearance I would build a framed wall that fits inside that arched opening with 1/2" gap at sides and top. I'd sheath it with plywood or paneling to suit, and I'd insulate it with fiberglass.
Alternatively, sandwich 2" rigid foam between paneling using appropriate construction adhesive and weight it until the glue sets.
I'd then stand it in the opening and gently stuff 1" foam rope caulk into the gap--one bead from each room. Chances are, that alone will secure the temporary wall enough that you don't have to use screws or adhesives at all.
If you find that it's not secure enough, a couple shims set in silicone caulk on each side of the opening, and inside the rope beads, will hold it firmly and invisibly until you need to remove it.
Answer: Your solution sounds fine to me.  For sound insulation, you need mass - so if you have some spare bricks or concrete blocks:

put in one sheet of drywall
stack the bricks/blocks in the void (you don't need to fill it completely
and you don't need it to form a strong wall)
attach the other sheet of drywall.


Configuring one ear to call remote ejb3 on another ear in JBoss

Question: I am new to EJB3 and am missing something when it comes to accessing a @Remote @Stateless bean deployed as an ejb module inside an ear file.  I want to access a remote bean in lima.ear from soup.ear.
Here is what I am doing now (somewhat abbreviated):
<code>//deployed under lima.ear
@Remote
@Stateless
public interface LimaBean {
    String sayName();
}
</code>
I want to put LimaBean in the Soup:
<code>//deployed in soup.ear
@Stateless
public class Soup implements SoupLocal {

    @EJB
    private LimaBean limaBean;

    public String taste() {
        return limaBean.sayName();
    }

 }
</code>
When I start JBoss I get the following error:
java.lang.RuntimeException: could not resolve global JNDI name for @EJB for container Soup: reference class: com.example.LimaBean ejbLink:  not used by any EJBs
I have had a hard time finding out what this ejbLink is about, if that is the right path to go down.
If I deploy LimaBean as a jar file in jboss then everything works great!
I ran accross an article that had a section called "2.5.3. References between beans in different jars and different ears"
(http://jonas.ow2.org/doc/howto/jboss2_4-to-jonas3_0/html/x111.html)
Example of jboss.xml file for SB_BrowseRegions:
<code><jboss>
    <session>
        <ejb-name>SB_BrowseRegions</ejb-name>
        <ejb-ref>
            <ejb-ref-name>ejb/Region</ejb-ref-name>
            <jndi-name>protocol://serverName/directory/RegionHome</jndi-name>
        </ejb-ref>
    </session>
</jboss>
</code>
If I touch the soup.ear, after JBoss starts up then it deploys fine, so I am assuming I need to specify a dependency like the above article says.
But even after it deploys then I get an error when accessing the remote LimaBean:
Caused by: java.lang.IllegalArgumentException: Can not set com.soup.LimaBean field com.soup.Soup.limaBean to $Proxy147
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:146)
    at sun.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:150)
    at sun.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:63)
    at java.lang.reflect.Field.set(Field.java:657)
    at org.jboss.injection.JndiFieldInjector.inject(JndiFieldInjector.java:115)
    ... 49 more
I have tried a few things but, if anyone can point me in the right direction about this I would appreciate it.
Answer: It looks like the JNDI properties need to be set as if it were a remote client outside of the app server because of the ear isolation we have setup.
<code>    properties.put(Context.PROVIDER_URL, url);
    InitialContext ctx = new InitialContext(properties);
</code>
Just specify the URL for the InitialContext and that should do the trick.


What is the right viscosity of silicone grease for ceramic-discs in mixer faucet?

Question:
Hi.
What is the right viscosity of a silicone grease to lubricate between the ceramic-discs of single lever mixer faucet?
NLGI-00,NLGI 1,NLGI 2 etc.
Thanks.
Comment: Why do you feel you need to break open that unit and **"lubricate between the ceramic-discs that are located inside the plastic cartridge of a single lever mixer faucet."** ?  I would assume that if the manufacturer wanted you to do that they would have given you the instruction and  info to do it. ?  *Potable or Portable ?*
Comment: Silicone grease is silicone grease, if there were a special requirement, the manufacturer's documents and/or website would be the place to look. Some brands even use Teflon lubricants... the only thing that usually matters, is that it be an approved food grade lubricant.
Comment: Have you checked the manufacturer's documentation on what the proper product to use is?  That would be my starting point.
Comment: No,unfortunately,i couldn't achieve the manufacturer's documentation.I would like to know,in general,what should the viscosity be,when applying it between ceramic-discs?It doesn't matter which company made it.ceramic-discs made of ceramic in all brands.The question is what is the viscosity of the grease that should use in ceramic disc?
Comment: Hello, and welcome to Home Improvement. It's a little hard to understand your post; would you spend a little time fixing capitalization and sentences, and splitting it into a paragraph or two? And, you should probably [take our tour](//diy.stackexchange.com/tour) so you'll know how best to participate here.
Comment: When the handle of a mixer faucet becomes stiff,it usually because the grease between the ceramic discs washed-off and relubricate them solve the issue.You are all should know that(if you expert in that area).You can find alot of videos and sites how it's done,but they don't mention the viscosity of the grease.The viscosity of a silicone grease is important.Silicone grease isn't just silicone grease as lithium grease isn't just lithium grease.When you apply lithium grease to wheel bearing of a car you use NLGI-2 viscosity,so it's important.Can i get,please,an answer from a professional.
Comment: @xchcui "*When the handle of a mixer faucet becomes stiff,it usually because the grease between the ceramic discs washed-off and relubricate them solve the issue"* did a **professional** tell you that ?  If you want advice from a professional then you should call a professional.   I have never heard of anybody breaking open a sealed cartridge to lubricate the ceramic discs so if a professional tells you it's possible then listen to the professional. **If I were you I would call the manufacturer**.
Comment: I have never heard of this.  As far as I know, ceramic discs last a long time.  I have never had to do this on any of my taps.  The last time, a tap (disc/valve) failed was 2 months ago.  And the importer replaced it with a different tap, under warranty.  he had stopped importing the one we had because of problems.
Answer: The spec sheet for Molykote 7508 valve grease says viscosity is 30,000 to 85,000 mPas


What is the Record-Score Setter medal awarded for?

Question: While playing Rainmaker in Anarchy Battle, I noticed I'd won medals for both #1 Score Booster and Record-Score Setter in a single round. Presumably the Score Booster medal is for boosting the team score, so what is the Record-Score Setter medal for?
Comment: Score booster is an award for object score (Tower Control, Rainmaker, Clam Blitz) according to this [website](https://www.gamepur.com/guides/all-multiplayer-medals-in-splatoon-3-and-what-they-mean), I (and the website) don't know about record setter but I guess highest point you've achieved in the game or with a weapon?
Answer: Record-score Setter is awarded in Tower Control when you ride the tower closest to the enemy team's goal point. I'd assume that it is very similar in Rainmaker, being awarded when you bring the Rainmaker closest to the enemy base from your team.


Keep the choice made as constant in a shiny widget that exists inside a dynamic tabsetPanel()

Question: Im trying to create a shiny app in which the user displays or not a secret tab. The issue is that I want the radioButtons() inside the main panel to keep the choice that I give to it if I change it and return to the selected one if I choose to hide or display the secret tab.
library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      radioButtons("displaySecretTab", "Display Secret Tab", choices = c("Yes", "No"))
    ),
    mainPanel(
      uiOutput("tabsets")
    )
  )
)

server <- function(input, output, session) {
  output$tabsets<-renderUI({
    if(input$displaySecretTab=="Yes"){
      tabsetPanel(
        id="tabs",
        tabPanel("tab 1",
                 radioButtons("ftype", "Choose file type", choices = c("CSV" = "csv", "Excel (.xlsx)" = "xlsx", "Excel (.xls)" = "xls"), selected = "csv")),
        tabPanel("secret"))

    }
    else{
      tabsetPanel(
        id="tabs",
        tabPanel("tab 1",
                 radioButtons("ftype", "Choose file type", choices = c("CSV" = "csv", "Excel (.xlsx)" = "xlsx", "Excel (.xls)" = "xls"), selected = "csv")),
      )
    }
  })
}

shinyApp(ui, server)

Comment: firmo23> See also `showTab`/`hideTab`, if you don't want to loose the contents of the secret tab, if there's any.
Answer: I would use insertTab/removeTab:
library(shiny)

ui <- fluidPage(
  sidebarLayout(
    sidebarPanel(
      radioButtons("displaySecretTab", "Display Secret Tab", choices = c("Yes", "No"))
    ),
    mainPanel(
      tabsetPanel(
        id="tabs",
        tabPanel("tab 1",
                 radioButtons("ftype", "Choose file type", choices = c("CSV" = "csv", "Excel (.xlsx)" = "xlsx", "Excel (.xls)" = "xls"), selected = "csv")),
      )
    )
  )
)

server <- function(input, output, session) {
  observeEvent(input$displaySecretTab, {
    if(input$displaySecretTab=="Yes"){
      insertTab(
        "tabs",
        tabPanel("secret")
      )
    } else {
      removeTab("tabs", "secret")
    }
  })
}

shinyApp(ui, server)


What is the reason that a boolean operation between two almost identical 3D triangular meshes fails?

Question: I have been trying to detect defects on "before-and-after" meshes, by finding the boolean difference between them, to no avail.
I tried these two Python libraries(algorithms run in C++) but their boolean operations would produce error or never finish:

PyVista(VTK wrapper) : https://docs.pyvista.org
Pymesh : https://pymesh.readthedocs.io

More specifically, some testing and findings that I had:

The libraries would operate normally in any other case of boolean operations between two different meshes.
The 2 almost-identical meshes I wanted to use were clean and water-tight. I even used an example shape which I subtracted from itself. It crashed too.
These 2 similar meshes are originating from the same mesh, but with a small difference, like a dent or some noise. I tried to introduce stronger noise or bigger changes, but it still would not work if the 2 meshes had their biggest part identical.
by enlarging 1 of the 2 meshes by more than 0.1%, or by transforming/moving(see attached picture) it by a similar amount, the algorithm starts working. But by that point, the shapes are too different to be useful.

To reproduce the error with Pyvista with an example shape from their website:
<code>import pyvista as pv
mesh_knot = pv.read("knot.ply")
mesh_knot2 = pv.read("knot.ply")
mesh =  mesh_knot.boolean_difference(mesh_knot2)
mesh.plot(eye_dome_lighting=True)
</code>
To conclude, has anyone any idea why this would happen? Do you think that there is a way to bypass the problem if no solution is found? Any other ideas of how I should approach my initial problem?
Answer: Without debugging the routines with the offending data, it's impossible to say conclusively. However given the examples you have given it sounds like the libraries are falling foul of the coplanar triangle cases when evaluating the meshes. This is certainly an Achilles heel of many CSG implementations out there (far to many in my experience). In many cases, both theory and implementations seem to fail to address these coplanar cases in many CSG libs.
Certainly the fact that it crashes or fails to produce the desired result implies that the libraries you use are buggy or incomplete in this regard.

The libraries would operate normally in any other case of Boolean operations between two different meshes.

When there are no coplanar triangles between manifolds, the result is well defined and since CSG operations use triangle/triangle intersections fundamentally, if the case of coplanar triangle intersections is not accounted for, everything should be fine and dandy when there are no coplanar triangle tests between meshes. Of course this is not what you require, but makes sense that this operates normally in these scenarios.

The 2 almost-identical meshes I wanted to use were clean and water-tight. I even used an example shape which I subtracted from itself. It crashed too.

This is certainly not correct and I would say a bug. A crash implies something is very wrong and either the coplanar triangle support is buggy, limited, or simply not implemented at all.
I suspect the latter unless you can get a result out with something simple such as diff'ing one cube from another... if you can get a result in some sandboxed cases, then it could be any of the former possibilities.
To see if your CSG routines can handle the coplanar cases, subtracting one cube from another should produce nothing (which as you said it fails). You could also attempt to subtract one cube from another which has a single face coplanar. e.g. Two cubes, both of length length. One positioned at x - length should produce a cube which is a closed manifold. i.e. Cube A (1x1x1) positioned at 0,0,0... and cube B (1x1x1) positioned at 1,0,0.

These 2 similar meshes are originating from the same mesh, but with a small difference, like a dent or some noise. I tried to introduce stronger noise or bigger changes, but it still would not work if the 2 meshes had their biggest part identical.

Probably just one triangle in a mesh is coplanar to another triangle in the other mesh which you are operating on, and thus failing. This may be a way to test by creating two meshes with only one triangle from each mesh being coplanar to another in the other mesh. If this fails then It might indicate that this corner case of coplanar intersection is not catered for at all. As said above, if it does work, then this may point to buggy behaviour at much higher level when dealing with coplanar triangles.

By enlarging 1 of the 2 meshes by more than 0.1%, or by transforming/moving(see attached picture) it by a similar amount, the algorithm starts working. But by that point, the shapes are too different to be useful.

I presume these libs work on floating point numbers, in which case this sounds like the FP equality tolerances are kicking in and evaluating 'almost' coplanar triangles as coplanar, and then subsequently failing to result in the CSG operation. Of course this is problematic for you if the tolerances are high since the input geometry is expected to be 'different enough' to not fall within these tolerances.
Unfortunately, there is nothing you can really do which I think you would find satisfactory since you are effectively at the mercy of the accuracy of the implementation.
If you suspect the libs can handle coplanar triangles between meshes, and its just failing in many cases, you might need to find out how you can kludge the input geometry to not fall foul of the shortcomings that may or may not be present for these corner cases in the implementations:

Remeshing the input geometry may help, although this may result is varying quality of input data in comparison to your measured data, which kind of defeats the purpose and will result in loss of accuracy wrt the original input meshes, but may at least give a result.
Re-tessellating triangles while retaining the mesh features may help. This involves inserting Steiner points into a given triangle and re-tessellating into more triangles. This will result in larger meshes (mem footprint, not geometrically speaking) but may help the routines to resolve coplanar intersections. Unlike the previous suggestion, It will retain the accuracy of the topology of the original meshes though.
Change the FP tolerance (if applicable) that the routines use which may allow you to keep meshes a similar size. However the problem is still there, but this may be satisfactory for your needs allowing you to not have to scale as much. Certainly from a visual standpoint this would be satisfactory I would have thought, however from a numerical point of view this may not be. However this does not fix the issue, rather attempt to circumvent it.

Given that the majority of the meshes will perhaps be similar, if the vertices are what are similar (i.e coplanar triangles have the SAME vertex values, although that screen shot you posted suggests otherwise) you could perhaps simply diff the meshes yourself, finding all the vertices that are not equal when comparing and then tessellating these. This is far more complex though as you would need to keep track of the edges around the different vertices (these edges will use vertices which are equal to others in the other mesh, so not a quick and dirty fix, rather a slightly different approach avoiding the libs you use) so that you can tessellate the different vertices into a meaningful manifold. I wouldn't recommend this as it is quite a specialised case, and may not be generalised enough for your needs.
Ultimately, if you can't circumvent the issue present with the current libs. You may have to find another. I certainly wasn't able to find many that matched my needs with a correct lic that was applicable to work, however I think there are certainly libs out there that would cater for this. Look for CAD libs as this is an important operation in many CAD programs.
A few years ago I spent some time testing and evaluating various different C++ CSG libs for our needs at work as we required a fairly robust implementation for production. While there were various success, they all failed at some point, and coplanar triangles were usually the culprit. It's quite frustrating as the answer is actually quite straight forward and simply requires the Boolean operation to be performed in 2D between the coplanar triangles and then testing if the resulting split triangles are within the 'other' triangle. Why this rather crucial point is missed in a lot of implementations and theory is beyond me.
/rant
Comment: I never said it's foolproof. It explains why you have such failure cases in many libraries - it's a tedious edge case that requires a disproportionate amount of code to deal with robustly.
Comment: Because it's tedious and solved by any epsilon offset.
Comment: @lightxbulb While this would be an easy fix for a lot of cases, unfortunately not all. Consider two cubes next to each other, not intersecting, with one face touching. If you were to union them and apply an offset to one of the cubes so there is no coplanar check, the resulting mesh would be two manifolds (when it should be one).
Comment: Also in the case of OP, a decision would have to be made in advanced about which mesh to offset, if the blue mesh was to be offset along it's triangle normals, this would result in an empty space (what is desired), if the blue mesh was offset the other way (normal inverse) then the result would be the orange mesh (not desired, it should be an empty space). Of course if you are well disciplined you could get away with in many cases, however there are always situations which this cannot fix. Also note offsetting would only really work if the two triangles are equal, and not just coplanar.
Comment: @lightxbulb Yes it is certainly an extra layer of complexity ontop of what would otherwise be quite an elegant algorithm. I agree in most cases simply offsetting is fine, if I was using it for a hobby project I certainly wouldn't haven't bothered going the extra mile, however unfortunately professionalism sometimes demands that extra bit from me and in this case for CSG I had to comply. Certainly in OP's case, it seems they require this extra complexity due to the nature of required precision of the input data... but yes agree if you can get away with it, best to save oneself the extra pain ;)


How to update my UIButton Background colour to specific colour code 0xff64b5f6

Question: I have a new spec for my app which requires the changing of the background buttons to specific colours provided as colour codes, ie: 0xff64b5f6.
I've been browsing and cannot find any alternative the doesn't use the redColor, blueColor etc.
I also tried using UIColorFromRGB(0xff64B5F6) which returns an integer instead of UIColor.
There must be a solution if anyone can help.
I'm using Xcode6 with IOS8.
Answer: Your color appears to have an alpha component as well as RGB, try the following macro:
<code>#define UIColorFromRGBA(rgbValue) \
[UIColor colorWithRed:((CGFloat)(((rgbValue) & 0xFF000000) >> 24))/255.0 \
                green:((CGFloat)(((rgbValue) & 0x00FF0000) >> 16))/255.0 \
                 blue:((CGFloat)(((rgbValue) & 0x0000FF00) >>  8))/255.0 \
                alpha:((CGFloat)(((rgbValue) & 0x000000FF) >>  0))/255.0]
</code>
You can re-order the statements based on whether your color is RGBA, or ARGB.
Answer: You could make your own:
<code>@implementation UIColor (HexCodes)

+ (UIColor *)colorFromHexRed:(Byte)red green:(Byte)green blue:(Byte)blue alpha:(Byte)alpha
{
    return [self colorWithRed:red / 255.0 green:green / 255.0 blue:blue / 255.0 alpha:alpha / 255.0];
}

@end
</code>
Then call it:
<code>UIColor *color = [UIColor colorFromHexRed:0xff green:0x64 blue:0xB5 alpha:0xF6];
</code>


how to impose that $y_i = 0 $ if $q_i> C$

Question: How Can I impose that $y_i = 0 $ if $q_i> C$
where C is  a constant
My problem is defined by those constraints:
$$x_i \in \{0 ; 1\}$$
$$q_i \in R^+_0$$
$$y_i \ge x_i - x_{i+1}$$
$$y_i \le x_{i}$$
$$y_i \le 1 - x_{i+1}$$
$y_i$ is defined to detect the transition $x_1=0 \rightarrow x_{i+1}=1$
$$x_i*q_{min} \le q_i \le x_i*q_{max}$$
$q_{min}$ and $q_{max}$ are constants.
Answer: Your constraint
$$q>C \Rightarrow y=0$$
can be rewritten as:
$$y=1 \Rightarrow q \le C$$
A standard formulation is:
$$
\begin{align}
&q \le C + M (1-y)\\
&y \in \{0,1\}
\end{align}
$$
where $M=q_{max}-C$.


Can I use javascript to change individual page css entries (as opposed to swapping stylesheets)?

Question: I know it's possible to change css attributes on elements on the current page:
$('.changeMyStyle').css("color", "#FF0000");

But this won't affect new elements added after the change is made.
I know it's possible to remove, add, or swap out css stylesheets to re-style a page after it's been loaded:
$('link.swappableStylesheet').attr('href', 'path/to/new/style.css');

But this is a poor solution for changing one or two attributes, especially to programmatically-determined values (such as changing color from a colorpicker).
I could probably grab a stylesheet's raw data, search it, and modify it:
var sheet= document.styleSheets[0];
var rules= 'cssRules' in sheet? sheet.cssRules : sheet.rules; // IE compatibility

rules[0].style.padding= '0.32em 2em';
// assumes the first entry in the first stylesheet is the one you want to modify.
// if it's not, you have to search to find the exact selector you're looking for
// and pray it's not in a slightly different order

But that's also a poor solution and requires IE-compatibility hacks.
This linked answer also suggests appending another


Admob not showing - issues?

Question: sorry for my language i cant speak/write fluently english but i have a problem.
I've done with m aplication but i dont get my admob and its not showing to my device, when i run to emulator its ok but when i install the application to my device before publishing to the market it dont shows up why here is my code:
My MainActivity.class
public class MainActivity extends Activity implements OnClickListener{

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        AdView adview = (AdView)findViewById(R.id.adView1);
        AdRequest re = new AdRequest();
        re.setTesting(true);
        adview.loadAd(re);

My Main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" android:background="@drawable/worldsbackground" >

<com.google.ads.AdView
android:id="@+id/adView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="My_Publisher_ID"
/>

and Manifest.xml
<activity android:name="com.google.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation"/>

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

Can Somebody help Me?
Thanks
Comment: I know this is pretty obvious, but do you have access to internet on your phone? :))
Comment: yes i have internet connection in my emulator its shows admob "success now you are ready to travel through the App Galaxy"
Answer: Your LinearLayout is using fill_parent which fill's up the whole screen and there is no space left on the screen
Comment: @Javo take another linerlayout inside your main layout and put your adView inside it
Comment: its shows me process has stopped unexpectedly. please try again.

Admob not showing - issues?