Windows 11 can't install pygame?

Question: Yes, just as I said, my new laptop doesn't want to download pygame for me. It's running Windows 11, maybe it has something to do with it (?)
Anyways, here is what my lovely machine responded to a simple "pip install pygame":
C:\Users\User>pip install pygame
Collecting pygame
  Downloading pygame-2.1.2-cp310-cp310-win_amd64.whl (8.4 MB)
     ------ --------------------------------- 1.4/8.4 MB 23.1 kB/s eta 0:05:03
ERROR: Exception:
Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_vendor\urllib3\response.py", line 438, in _error_catcher
    yield
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_vendor\urllib3\response.py", line 519, in read
    data = self._fp.read(amt) if not fp_closed else b""
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 90, in read
    data = self.__fp.read(amt)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\http\client.py", line 465, in read
    s = self.fp.read(amt)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\socket.py", line 705, in readinto
    return self._sock.recv_into(b)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\ssl.py", line 1273, in recv_into
    return self.read(nbytes, buffer)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\ssl.py", line 1129, in read
    return self._sslobj.read(len, buffer)
TimeoutError: The read operation timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_internal\cli\base_command.py", line 167, in exc_logging_wrapper
    status = run_func(*args)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_internal\cli\req_command.py", line 205, in wrapper
    return func(self, options, args)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_internal\commands\install.py", line 339, in run
    requirement_set = resolver.resolve(
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_internal\resolution\resolvelib\resolver.py", line 94, in resolve
    result = self._result = resolver.resolve(
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 481, in resolve
    state = resolution.resolve(requirements, max_rounds=max_rounds)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 348, in resolve
    self._add_to_criteria(self.state.criteria, r, parent=None)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_vendor\resolvelib\resolvers.py", line 172, in _add_to_criteria
    if not criterion.candidates:
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_vendor\resolvelib\structs.py", line 151, in __bool__
    return bool(self._sequence)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 155, in __bool__
    return any(self)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 143, in <genexpr>
    return (c for c in iterator if id(c) not in self._incompatible_ids)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_internal\resolution\resolvelib\found_candidates.py", line 47, in _iter_built
    candidate = func()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_internal\resolution\resolvelib\factory.py", line 215, in _make_candidate_from_link
    self._link_candidate_cache[link] = LinkCandidate(
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_internal\resolution\resolvelib\candidates.py", line 288, in __init__
    super().__init__(
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_internal\resolution\resolvelib\candidates.py", line 158, in __init__
    self.dist = self._prepare()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_internal\resolution\resolvelib\candidates.py", line 227, in _prepare
    dist = self._prepare_distribution()
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_internal\resolution\resolvelib\candidates.py", line 299, in _prepare_distribution
    return preparer.prepare_linked_requirement(self._ireq, parallel_builds=True)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_internal\operations\prepare.py", line 487, in prepare_linked_requirement
    return self._prepare_linked_requirement(req, parallel_builds)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_internal\operations\prepare.py", line 532, in _prepare_linked_requirement
    local_file = unpack_url(
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_internal\operations\prepare.py", line 214, in unpack_url
    file = get_http_url(
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_internal\operations\prepare.py", line 94, in get_http_url
    from_path, content_type = download(link, temp_dir.path)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_internal\network\download.py", line 146, in __call__
    for chunk in chunks:
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_internal\cli\progress_bars.py", line 304, in _rich_progress_bar
    for chunk in iterable:
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_internal\network\utils.py", line 63, in response_chunks
    for chunk in response.raw.stream(
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_vendor\urllib3\response.py", line 576, in stream
    data = self.read(amt=amt, decode_content=decode_content)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_vendor\urllib3\response.py", line 512, in read
    with self._error_catcher():
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\contextlib.py", line 153, in __exit__
    self.gen.throw(typ, value, traceback)
  File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.1264.0_x64__qbz5n2kfra8p0\lib\site-packages\pip\_vendor\urllib3\response.py", line 443, in _error_catcher
    raise ReadTimeoutError(self._pool, None, "Read timed out.")
pip._vendor.urllib3.exceptions.ReadTimeoutError: HTTPSConnectionPool(host='files.pythonhosted.org', port=443): Read timed out.

Answer: Try this, As the last line says timeout you need to change the default time to something else.
pip --default-timeout=1200 install pygame

Answer: If your having trouble installing pygame on windows 11 use:
pip install pygame --pre

Windows 11 can't install pygame?


Context Menu Strip Control With and Without Selected Grid

Question: I really don't know what to search so I'll just ask this:
I have a context menu strip linked to a listview,
what I need is that when I right click to a highlighted variable in the grid list view, the menu for items will be displayed, and
when I right click to an empty grid, the grid settings will be displayed.
How can I achieve this?
Comment: In mouse down: `If myLV.SelectedItems.Count > 0 then ...display item menu Else ...display system menu End If`.  Note that the question changed in the comment...also the LV doesnt care which mouse button is pressed to select an item and making users deselect items to get at a different menu is cruel
Comment: sounds like there are *two* context menus involved, but please explain what a `highlighted variable in the grid list view` is or means
Comment: I mean selected Item, when I select and item in the list view and press right click it should display things like copy paste stuffs related to the item, and when there are no highlighted item the context menu should show menus for listview like, columns, rows..
Answer: I doubt the user will appreciate your approach; you plan to display 2 different menus from the same action - a click.  It may not be apparent how to get one menu or the other.  Further, it is not clear why the "Settings" or main menu would ever need to be hidden from them.
Rather than 2 menus, why not 1 menu with 2 submenus, to make it easy to find them?
Private Sub myLV_MouseUp(sender...
    If (e.Button = Windows.Forms.MouseButtons.Right) Then

        lvCMS.Items("ItemMenu").Enabled = (myLV.SelectedItems.Count > 0)

        ' show (may need if there ARE 2 menus)
        lvCMS.Show(myLV.PointToScreen(New Point(e.X, e.Y)))

    End If
End Sub

The LV will show an assigned menu on its own, but if you have 2, you may want/need to display it manually, which is shown.  By using the MouseUp event the LV has already reacted to MouseDn and changed the selected item.  The only thing that varies menu-wise is whether the ItemMenu is enabled or not.
Clicking on an empty area deselects an item.  Barring a button to do the same, it is hard to deselect an item because the empty area can get be almost nonexistent:

Only the orange-ish area is empty grid, add one more item to fill in the bottom and cause a scroll bar and there is none.  This is partly why a separate menu and special set of conditions may not be a good idea.


Plugin Un-install missing

Question: Moodle plugins come up with install & uninstall option when $plugin variable is specified in version.php.
I couldn't see uninstall option for my customized authentication plugin:
<code>$plugin->version   = 2015051100;
$plugin->requires  = 2015050500;
$plugin->component = 'auth_hotspot';
</code>
Once installation is done, When I run the plugin, Un-install option is missing. I even don't have an option to delete as it shows "missing from disk". (Moodle version: 2.9).
Appreciate your suggestions.
Answer: Moodle does not allow to uninstall the auth plugin if any user-created using that plugin.
You need to delete the user from Database or convert the user's authentication method to manual or others.
https://moodle.org/mod/forum/discuss.php?d=272751
Comment: Sry, I missed that, moodle does not delete the users from DB when you delete the user from moodle users list, You need to manually delete the user from DB. Convert the user's auth method is the best way for this issue.
Comment: Hello Prasanna, if I delete the users, even then I couldn't see uninstall option. Is there  additional way to uninstall the plugin.

Plugin Un-install missing


Probability of being in a random interval

Question: Consider an Erlang$(n,\lambda)$-distributed random variable $A$ and another Erlang$(1,1)$-distributed random variable $B$ (hence exponential(1)) such that $A$ and $B$ are independent.
How to compute $P(A<t<A+B)$?
Are the events $\{A<t\}$ and $\{t<A+B\}$ independent?
Comment: For any $t\gt 0$, the events $\{A<t\}$ and $\{t<A+B\}$ are not independent, and their complements are mutually exclusive
Comment: Could you give me a hint then how to compute $P(t<A+B\mid A<t)$?
Answer: For $t\ge 0$,
\begin{align}
\mathsf{P}(t\in [A,A+B])&=\int_0^\infty \mathsf{P}(t\in [A,A+b])\,e^{-b}\,db \\
&=\int_0^\infty \left(\int_{(t-b)\vee 0}^t \frac{\lambda^n a^{n-1}e^{-\lambda a}}{(n-1)!}\,da\right)e^{-b}\,db.
\end{align}
Comment: Thank you very much!


How Do I attach my deck to the house..or not?

Question: I removed the old deck and found out that the previous ledger board was just nailed to the house. See pictures attached. The wooden boards you see are also nailed to the house, and the ledger board was nailed to those...
https://i.stack.imgur.com/d9Lmg.jpg
Now that I don't see the house rim joist, how can I attach the deck to the house ?
Do I have to remove the house insulation ?
Do I build just a free standing deck ?
Thank you for your help !
Comment: Building a free-standing deck eliminates the problems of attaching a ledger board to the house.  But you need to provide more posts, footers, and a beam to run across the posts.
Comment: Do you have access to the floor joists behind that side of the house?  And if so, in what direction do those floor joists run?
Comment: Building free-standing might also make your permits process easier. Check with your local building dept.
Comment: Free standing can be a floating deck. If allowed in your area (IIRC years ago when I built mine, it was allowed in all states except NJ) there are likely limits on size and height. But if you can legally build a floating deck it can be a lot cheaper.
Comment: 1- The floor joists in the basement are parallel to the deck (if that is clear)
2- I am in quebec and no permit is required for a deck attached or not. and I am ok with using more material and puting in more work, if it saves me screwing things iup
Comment: @Nazim Haddadi - Are you familiar with Tension Ties?  They are used to tie a ledger board to the structure of the house.  Information on their use can be found in the Simpson catalogue, and that from other manufacturers.
Answer: I would cover the scar on the house with siding to match, after sealing any holes from fasteners.
Build a freestanding deck. No risk of water infiltration causing degradation to the home. Further, if you decide to change it or remove in the future, you have no work needed to the home.
Comment: You can put a ledger on without risking water damage if you flash it and tape the flashing correctly. Not a big deal.
Comment: Or not need it and not have to do any of that.
Comment: That's not the point, you're inferring that by installed a ledger to the building that you risk water damage which simply is not true.
Comment: Sorry but it is true.  Diligence will mitigate, but the possibility exists. Where as not attaching a ledger means no intrusions.  A hole not made does not need to be sealed.
Comment: Water trapped between a floating rim joist and siding that has nowhere to drain could cause rot as well. A pressure treated framing member with metal flashing and flashing tape works perfectly fine. Guess we will just have to agree to disagree.  Good day.
Comment: I never understood why the ledger is always set so thaat the top is even with the top of the deck joists. If you put a ledger on use a board that is taller than your joists. if the joists are 2x8 then use a 2x12 ledger. cut the top edge of the ledger at a 45 degree angle and allow it to stick up past the top of the deck boards. Flash the ledger and you will NEVER have any water penetration so long as the flashing is not rotted through. having a deck board cover the top of the ledger is a great way to make a trap for debris and water.


Django / Python how to get the full request header?

Question: I've been looking over what I can find about this and found something about denying access to specific user-agents but couldn't find how I can actually get the full request header. I am trying to make a customized analytics app so would like access to the full headers.. any info is appreciated.
Answer: All the headers are available in request.META. See the documentation.


"Cannot access a disposed context instance" in EF Core with Blazor Server

Question: I have these layers:

Repositories
Services
BlazorServer

In my BlazorServer, I have dependency injected IDbContextFactory, my repositories and services like below:
builder.Services.AddDbContextFactory<EstateDbContext>(OptionsHelper.ContextOptions(builder));
builder.Services.AddScoped<IRepository<Dealer>, EFRepository<Dealer, EstateDbContext>>();
builder.Services.AddScoped<IDealerService, DealerService>();

My repository example with GetTableAsync-method:
public sealed class EFRepository<T, TDbContext> : IRepository<T> where T : BaseEntity where TDbContext : DbContext
{
    private readonly IDbContextFactory<TDbContext> contextFactory;

    public EFRepository(IDbContextFactory<TDbContext> contextFactory)
    {
        this.contextFactory = contextFactory;
    }

    public async Task<IQueryable<T>> GetTableAsync(CancellationToken cancellationToken = default)
    {
        using TDbContext context = await contextFactory.CreateDbContextAsync(cancellationToken);
        DbSet<T> table = context.Set<T>();

        return table;
    }
}

And my Services-layer, example with Get a list of 'Dealer'-entity:
public sealed class DealerService : IDealerService
{
    private readonly IRepository<Dealer> dealerRepository;

    public DealerService(IRepository<Dealer> dealerRepository)
    {
        this.dealerRepository = dealerRepository;
    }

    public async Task<List<Dealer>?> GetDealersAsync(CancellationToken cancellationToken = default)
    {
        IQueryable<Dealer> dealerQuery = await dealerRepository.GetTableAsync(cancellationToken);
        List<Dealer> dealers = await dealerQuery.ToListAsync(cancellationToken);

        return dealers;
    }
}

Lastly, my Blazor Component:
@page "/dealers"
@inject IDealerService DealerService

Dealers

    @if (dealers is not null)
    {
        foreach (var dealer in dealers)
        {

@dealer.Name

        }
    }
    else
    {

Dealer is null

    }

@code {
    private List<Dealer>? dealers;

    protected override async Task OnInitializedAsync()
    {
        dealers = await DealerService.GetDealersAsync();
    }
}

I have awaited everything all the way to the application layer, but I still get exception, how do I fix this one:
Cannot access a disposed context instance. A common cause of this error is disposing a context instance that was resolved from dependency injection and then later trying to use the same context instance elsewhere in your application. This may occur if you are calling 'Dispose' on the context instance, or wrapping it in a using statement. If you are using dependency injection, you should let the dependency injection container take care of disposing context instances. Object name: 'EstateDbContext'. |

Note: I have narrowed down my logic in the code above to be as simple as possible.
EDIT: I found the issue, but don't know how to solve it: in Repository, the using-statement is used on GetTableAsync()-method, and after the method is finished, the context is disposed, and then it can't be used in Service-layer... which causes the exception. How would I go about sending a IQueryable to the service layer without it being disposed?
Comment: the problem may occur in asynchronous tasks. check if the methods that call DealerService return a task in the Blazor component
Comment: I triple checked, all methods that call DealerService return async Tasks. @Laaziv
Comment: you can delete
builder.Services.AddDbContextFactory
//AddService
builder.Services.AddTransient();
Comment: AddDbContextFactory shouldn't be deleted since it holds my connectionstring to my database.. @Laaziv
Comment: you can use a Service.AddDbContext the same way.
and for the Service used transient AddTransient();. @Zecret
Comment: Doing so will cause other problems which I have encountered before, because I am using Blazor Server and when loading multiple stuff from Database on the same context it will cause exceptions too. That's why I want to Dispose at method levels using DbContextFactory. @Laaziv
Comment: This is a big headache for Blazor Server with it's long-lived scopes. I dealt with it by creating my own Scope from `IServiceScopeFactory` and getting the `DbContext` via DI.
Answer: Your problem, as you've identified, is in your usage of IQueryable.
You solve the problem like this:
    public async ValueTask<IEnumerable<T>> GetTableAsync(CancellationToken cancellationToken = default)
    {
        using TDbContext context = await contextFactory.CreateDbContextAsync(cancellationToken);
        // can turn off tracking as you are only querying
        TDbContext.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;

        // get the IQueryable object
        IQueryable<T> query =  context.Set<T>();
        // At this point you can apply any filtering, sorting, paging,....

        // Materialize the query into a memory based IEnumerable object
        // this is an async operation
        var table = await query.ToListAsync();

        // return the object
        return table;
    }

Basically, you don't don't materialize your query before the DBContext goes out of scope.  An IQueryable object isn't a list in itself: it's a class that defines how to get a list from it's data source.  It's a unexecuted SQL query,  So when the DbContext goes out of scope at the end of the method, you sever the query from it's source.
In the above code, the query is materialized [run] by calling ToListAsync which gets the data from the database and stores in it a memory based object.  You then return it as an IEnumerable which is the memory based equivalent of IQueryable.  Lists implement IEnumerable.  It won't go out of scope and the GC destroy it until all references to it are released.
I've also changed the Task type to a ValueTask which is normally a little less "expensive" in resource usage.
If you want to know more about materialization and the differences between IQueryable and IEnumerable see this - What is the difference between IQueryable<T> and IEnumerable<T>? and many other articles.
Comment: No, you can stay generic.  You just need to move your paging, filtering and sorting operations down to the repository service.   Paging and sorting is relatively simple, but filtering has it's challenges if you are writing a WASM application with API calls.  It looks like you are building a Blazor Server application.  If so, see this article that describes how to builds a generic IRepository data pipeline - https://www.codeproject.com/Articles/5350000/A-Different-Repository-Pattern-Implementation
Comment: I currently use just one generic repository (EFRepository.cs) which holds 4 methods: GetTable, Create, Update & Delete. I usually pass IQueryable with GetTable-method to the service layer which is responsible to forming the Queryable with includes, paging, etc. for each Get methods. Does that mean I have to switch up my way of using repositories and instead create a repository for each domain entity I have which has methods for each use-case i.e. GetBookWithAuthor()?


How to Mute ongoing instance of SpeechSynthesisUtterance

Question: I am using SpeechSynthesisUtterance for text to speech in my browser. How can I mute and unmute the ongoing speech on button click?
Answer: You may change the SpeechSynthesisUtterance.volume property. For muting make SpeechSynthesisUtterance.volume = 0.
Comment: And to add that to unmute the default value is 1.
https://dvcs.w3.org/hg/speech-api/raw-file/tip/webspeechapi.html#dfn-utterancevolume
Answer: Actually, there is no way to mute the ongoing speech. You can cancel the running speech, mute the volume using SpeechSynthesisUtterance.volume property and restart the speech.


Unable to load caret package in R on R 3.1.0 on OSX 10.9

Question: I installed the R caret package using install.packages command and did library(caret). I am recieving the following error
>library(caret)
Loading required package: lattice
Loading required package: ggplot2
Error : .onLoad failed in loadNamespace() for 'tcltk', details:
call: dyn.load(file, DLLpath = DLLpath, ...)
error: unable to load shared object '/Library/Frameworks/R.framework/Versions/3.1/Resources/library/tcltk/libs/tcltk.so':
dlopen(/Library/Frameworks/R.framework/Versions/3.1/Resources/library/tcltk/libs/tcltk.so, 10): Library not loaded: /usr/local/lib/libtcl8.6.dylib
Referenced from: /Library/Frameworks/R.framework/Versions/3.1/Resources/library/tcltk/libs/tcltk.so
Reason: image not found
Error: package or namespace load failed for 'caret'

I searched other posts and also installed OSX tcltk package from http://cran.us.r-project.org/bin/macosx/tools/ but it still does not seem to work. I also installed tcltk2 package from R but still does not work.. Kindly help
Comment: How did you install R and the packages? Did you use the Mavericks binaries from CRAN or did you install from source?
Comment: I used straight forward `install.packages `
Comment: caret do not depends on tcltk, so I think that something else causing this. What `traceback()` says? Does `library(tcltk)` works?
Answer: I have met the same problem with the same error message but unfortunately, just reinstalling R1.3 didn't solve the problem for me.
To solve it, I had to install X-Quartz as explained here in the "Mac OS X Trouble-shooting" section and the problems related to tcltk.
Answer: Do this and it will resolve the problem
install.packages("quantreg")

Answer: What version of R are you using? Do you use Mavericks? You may need to update to a version which includes Mavericks updates.
http://cran.r-project.org/bin/macosx/
Comment: I am using R 3.1 on OSX Mavericks.. This problem does not seem to oocur on my macbook air which is also  running mavericks. Anyway will reinstall R and check
Comment: There are a few versions of R3.1, one is specific to Mavericks.
Comment: I had downloaded the Mavericks version. Anyways I deleted and re-installed R3.1 again on my system. I seems to work fine now
Answer: I had the same issue. Reinstalling Quartz solved the issue
Answer: Try this, worked for me.
install.packages("caret", dependencies = T)

Once that is done, run
install.packages("pbkrtest", dependencies = T)


How can I convert an image to audio using JavaScript?

Question: I'm looking to experiment with an idea and create a little web app that will allow me to select an image, convert it to audio and play it back (I understand it will not sound pleasant).
So my question is, could anyone suggest some examples or existing libraries that might help me out.
Other areas I'll explore are the use of Processing and MaxMSP but ideally, I'd like to later package what I make in the likes of Ionic - so web solutions are preferred.
Answer: German mathematician David Hilbert published what we call the Hilbert Curve which defines how to trace across each pixel in an image visiting each once and only once without skipping any pixels starting in one corner and ending in another.  This is how you can transform the 2D image into a 1D representation.
On this resulting line you have recorded the light intensity measurements per pixel ... now to synthesize audio from this image we map the spectrum of human hearing from low to highest frequencies onto this line ... atop each pixel point on the line you introduce a sine curve oscillator generating a constant single tone at a frequency appropriate to its position going left to right on your line ... synthesize audio from all of these oscillators simultaneously ... this is the sound of the image
Beautiful aspect is it goes equally well in reverse ... from an arbitrary audio to its image representation ... its not lost that streaming audio can get transformed into a video stream ... to do this without loosing information if you wish to go round robin (audio->video->audio->...) gets tricky as the simple method to collapse the RGBA of each pixel into a single light intensity value with the ambition to avoid losing information you really need a   multidimensional structure instead of a simple 1D line
Here is a video explaining this Hilbert Curve
Its a nice self contained idea which is computationally simple enough to perform in real-time for a decent image resolution at a respectable audio sample rate and bit depth ... I am actively working on this question and will report back my findings with a code repo
Regarding implementation details there are libraries to reveal the RGBA pixel values of a supplied image ... also short of writing your own Hilbert Curve algorithm it too has libraries ... once all of your frequency oscillators are humming away you will need to sample all of them simultaneously to synthesize one output sample as the aggregate curve height at a given sample point in time ... then to be able to hear the audio output I would use Web Audio API where you could feed its event loop memory buffer with your aggregate curve audio ... not a trivial approach yet very doable
The human brain is plastic enough to get trained to hear what others see such that the blind would use this to cast away their walking cane !!! what joy ...
Comment: The notes i've already taken, wee questions i've asked myself fit in with that video so well. I'm quite excited to dig deeper now, thanks for the recommendation.

If I make any progress, i'll keep you posted.
Comment: Thank you for the speedy response! This certainly sounds useful, i'll dive into this video and get back to you soon. More suggestions for exploration like this, more than welcome!
Comment: I dont really know where to start with javascript on this, but i can say its certainly do-able, ive done the first part of this task in php before Cycling each pixel and extracting colour values etc (falthough for a different purpose). Please post any results, ide love to see them.
Comment: @Scott Stensland Have you been able to do anything with this?


Replacing WIndows 8.1 within Ubuntu 14.04 LTS

Question: I am in the process of wiping my Windows 8.1 install and replace it with Ubuntu 14.04 LTS, but have the following queries pls, prior to doing anything:
1) Will I be able to install Ubuntu 14.04 LTS on my new Acer Aspire ES1-512 C32A laptop, which is a 64 bit OS, has 8GB RAM (upgraded it) and a 500GB HDD (7200rpm). Boot mode is set to: UEFI?
2) I have created a USB Flash drive install of Ubuntu using Universal Installer app - I believe it worked, even though it was stuck on 99% but when I pressed "Close" after 15 mins, it came back saying installation completed successfully - can I assumed this worked or can people suggest another installer ISO app?
3) When I restart my laptop and press the F2 key to enter BIOS mode, I switch over to Boot section and I  am presented with Boot Mode of UEFI  and then the option set boot sequence of drives, which would be my USB drive. My question is, what should the Boot Mode be when I go to change the boot order sequence - should it be UEFI or Legacy?
4) If/when I eventually wipe Windows 8.1 and replace with Ubuntu, is there any special I need to do from my end?
5)Will things like Wireless LAN | SD Card Reader| Touchpad  work straight off the bat or do I need to install specific drivers?
Have I missed any other crucial steps?
Furthermore, I actually have another laptop that I use for all things Windows 8.1 and so I want to dedicate this Acer laptop alone to just being a linux box. Am not interested in dual boot on Acer.
Thanks.
Comment: before you whipe, go install Vmware migration tools and make a virtual image of your windows8 machine. Youll have the option to compress it, so do that. Then once you have installed linux, you can still use your old OS simulaneously.
Answer: Many users find one application or game that they just cannot live without and then want to restore Windows & dual boot. Best to have good backups of efi partition and full Windows install.
How you boot install media UEFI or CSM/BIOS is how it installs. And then that is the setting you have to have in UEFI. Best to use UEFI.
Acer Aspire ES1-512-C39M Details on password and settings to enable trust on ubuntu entries
http://ubuntuforums.org/showthread.php?t=2256083&p=13203044#post13203044
http://acer--uk.custhelp.com/app/answers/detail/a_id/27071/~/how-to-enable-or-disable-secure-boot
Aspire E1-522 InsydeH20 Bios unlock -  7 min video
https://www.youtube.com/watch?v=7SkBFkzOW0A
Acer E1-531 UEFI menus.
http://www.tomshardware.com/forum/65627-63-body
Did live installer work in live mode? That tells best if it will work without added effort to install extra/special drivers.
Comment: Pls see my updated thread above re: not interested in dual boot - just a dedicated Linux box. Thanks.
Comment: Are you installing in UEFI or BIOS mode. This shows screens you may see:  https://help.ubuntu.com/community/UEFI and: https://help.ubuntu.com/community/DiskSpace and: http://askubuntu.com/questions/343268/how-to-use-manual-partitioning-during-installation
Comment: Will be installing in UEFI mode.
Answer:
first of all, you need to be sure that you have the 64 bit Ubuntu installer and not the 32 bit.
You can get it at

http://releases.ubuntu.com/14.04/
http://releases.ubuntu.com/14.04/ubuntu-14.04-desktop-amd64.iso

next, you have to make a live usb of ubuntu:

http://www.ubuntu.com/download/desktop/create-a-usb-stick-on-windows

then, change the IDE to your flash drive and boot from it
then, install Ubuntu alongside windows.
if you have problems with your partitioning, pick "try Ubuntu" in the beggining of your installation and open gparted partition editor. then, check and fix the windows partition.
if you get all this done, you should have grub and dual-boot on your computer

Note: if my answer solved your problem, dont forget to tick the check mark next to the answer.
ENJOY!
Comment: Thank you for your response. I definitely have the 64 bit version of Ubuntu, but I am not requiring dual boot. I want to dedicate this Acer laptop to being a 100% linux box - no MS Windows 8.1 required. Is this possible with the Ubuntu Installation process within Live USB - try Ubuntu before installing? Thanks.
Comment: in that case, since your windows partition is causing the problem, opn gparted(in try ubuntu mode), then delete the windows partition. and then you can install Ubuntu fully on your computer with the option " erase disk and install ubuntu
Comment: Hi - have actually done this but having issues with shim efi key component. See my other thread. Thanks.
Answer: i think you have to install ubuntu inside windows8.1 and make your PC dual boot
thats will help you to do any thing in both system
you can see here :
Dual-Boot Ubuntu 14.04 and Windows 8 "2014"
Answer: First Go to Installing Ubuntu Alongside a Pre-Installed Windows with UEFI and read everything very carefully. Even though the answers are for dualboot, you can choose to wipe Windows and replace it with Ubuntu at the time of installation.
To answer your questions...
1) Will I be able to install Ubuntu 14.04 LTS on my new Acer Aspire ES1-512 C32A laptop, which is a 64 bit OS, has 8GB RAM (upgraded it) and a 500GB HDD (7200rpm). Boot mode is set to: UEFI?
This is hard to say as computer manufacturers often use different internal components for different batches of the computer with same model number. The best thing to do is to boot from the Live USB you created and select "Try Ubuntu without installing". This option will not make any changes to your computer and you will be able to check if everything works or not.
2) I have created a USB Flash drive install of Ubuntu using Universal Installer app - I believe it worked, even though it was stuck on 99% but when I pressed "Close" after 15 mins, it came back saying installation completed successfully - can I assumed this worked or can people suggest another installer ISO app?
Try the Live USB without installing as mentioned above. If it does not work, try creating the Live USB again.
3) When I restart my laptop and press the F2 key to enter BIOS mode, I switch over to Boot section and I am presented with Boot Mode of UEFI and then the option set boot sequence of drives, which would be my USB drive. My question is, what should the Boot Mode be when I go to change the boot order sequence - should it be UEFI or Legacy?
For a system that just boots Ubuntu, it does not matter if you choose UEFI or Legacy. The installation program will use the appropriate process. If you intend to use UEFI, at the time you choose the Boot drive, make sure you choose the USB with UEFI.
4) If/when I eventually wipe Windows 8.1 and replace with Ubuntu, is there any special I need to do from my end?
If you select the option to replace Windows with Ubuntu during installation, it will erase everything in your hard drive including other partitions such as D:\. If you have data, music, photos, etc. in another partition, copy them in an external drive before you start. You may also choose "Something Else..." and manually select the partitions for Ubuntu. This requires some knowledge of the partition scheme used by Ubuntu.
5)Will things like Wireless LAN | SD Card Reader| Touchpad work straight off the bat or do I need to install specific drivers?
Most things should work. Ubuntu has most drivers already built in. The two exceptions are graphics cards and WiFi cards. Even for these opensource drivers are built-in. If your WiFi card needs a proprietary driver, you connect your computer by Ethernet during installation and check the appropriate box to install these additional drivers at the install time. This can be also done later by running the appropriate program that looks for and installs additional drivers if they are needed.
Hope this helps
Comment: Thanks for your answers. FYI, I am currently writing this comment using the "Try Ubuntu without installing" option and all seems to be working fine. WiFi, graphics card and touchpad. Not sure yet about SD card reader yet. Based on this, I am confident that Ubuntu 14.04 works on  my Acer Aspire ES1 512 laptop. If I install Ubuntu and overwrite my HDD with new Ubuntu, is there  anything else I need to do afterwards?
Comment: I will certainly do this after I have officially installed Ubuntu 14.04 on my laptop. Just want to keep it open until I know all works fine. Just want to keep running with the "Try Ubuntu without installing" option a bit more. Thanks.
Comment: Looks like I just found an issue with Live USB - my system doesn't seem to shutdown. Just shows me the Ubuntu Logo in centre of screen.
Comment: See http://askubuntu.com/search?q=%22not+shutdown%22 for possible solution. If not, ask a new question.
Comment: See http://askubuntu.com/questions/585134/what-should-i-do-straight-after-installing-ubuntu for what you may want to do after intalling Ubuntu.


Get value of TextBox in Panel in  in TemplateField in GridView

Question: I have a GridView with a TemplateField. Inside the ItemTemplate there are 2 TextBox's and then a
 with an Panel. In that Panel there's another TextBox.
How do I get the value of that last TextBox?
I have the index of the gridview's row, but I don't know how to get on from there.
(Data from DB is bound at page load).
<asp:ScriptManager runat="server"></asp:ScriptManager>
<asp:GridView ID="grv_Four_Rows" runat="server" AutoGenerateColumns="False"
    ShowHeader="False" CellPadding="3" CssClass="myGrid" DataKeyNames="Test1_First_Name">
    <RowStyle BackColor="#b5c7de" />
    <AlternatingRowStyle BackColor="#d1e0e0" />
    <Columns>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:TextBox ID="txbFirstName" runat="server" CssClass="myTextBox" ReadOnly="false" Text='<%# Eval("Test1_First_Name")%>'></asp:TextBox>
                <asp:TextBox ID="txbLastName" runat="server" CssClass="myTextBox" ReadOnly="true" Text='<%# Eval("Test1_Last_Name")%>'></asp:TextBox>

                    <asp:Panel ID="upp_2nd_row" runat="server" Visible="true">

                             Address:
                             <asp:TextBox ID="txbAddress" Width="200px" Font-Bold="true" runat="server" Text='<%# Eval("Test1_Address")%>' />

                             <asp:Button ID="btn_Edit_Details" runat="server" Text="Go" Font-Bold="true"
                                    OnClick="my_Update_details" CommandArgument='<%#DataBinder.Eval(Container, "DataItemIndex")%>' />

                    </asp:Panel>

            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

<asp:Label ID="lblMessage1" runat="server" BackColor="Yellow" Font-Bold="true"></asp:Label>

C# Code behind:
    protected void my_Update_details(object sender, EventArgs e)
    {
        string my_row_index = (sender as Button).CommandArgument;
        lblMessage1.Text = "Row Index: " + my_row_index;
    }

When I click the "Go" button in any row, the my_Update_details event is fired. All it does is, it displays the gridview's current row's index, and the value is correct.
But in the my_Update_details I also want to pick the values of the textbox's, and that's where I'm stuck (user is supposed to change their values and the 'Go' button should update the DB).  In the following example I clicked the button in the 4th row and it correctly displays the index as 3 :
Answer: So this is how it works: first I rack my brains for a couple of days, then I post a question in SO, then - after 2 minutes I find a solution...
All I did was add a line in the my_Update_details method (the second line) :
    protected void my_Update_details(object sender, EventArgs e)
    {
        string my_row_index = (sender as Button).CommandArgument;
        TextBox AAAAAA = (TextBox)grv_Four_Rows.Rows[Convert.ToInt32(my_row_index)].Cells[0].FindControl("txbAddress");
        lblMessage1.Text = "Address: " + AAAAAA.Text;
        lblMessage2.Text = "Row Index: " + my_row_index;
    }

and now I get:

which is exctly what I needed : to get the value that's in the txbAddress textbox.
Hope it will help someone in the future....


Automatically link function names to api.drupal.org

Question: Is it possible to automatically turn core function names into links to api.drupal.org? For instance: 'hook_node_load' would become 'hook_node_load'.
If it's possible at all, would you consider it helpful?
We would at least need figure out how to handle common words that match function names by coincidence. For instance, we don't need to link 'theme' to http://api.drupal.org/api/drupal/includes--theme.inc/function/theme/7 everywhere.
Comment: Possible duplicate: http://meta.drupal.stackexchange.com/questions/319/markdown-for-drupal-api-reference
Comment: Sorry I didn't find that one before I posted this. It's not an exact duplicate, but definitely related.
Comment: Yea, just thought would be worth showing both for the sake of discussion
Answer: This is a good idea, although an existing JavaScript library that parses function names would be a stronger selling point to Stack Exchange. Other Stack Exchange sites already use the MathJax library.
I think the generic name for Drupal function use case can be solved by always referring to functions as (for example) theme() or hook_node_load().
Comment: You're right, the brackets should be enough to differentiate between a word and a function name. Using an existing library is always a good idea, but I wouldn't know which library.


How to handle large selection sets when paging

Question: I'm working on a document management platform. Users can upload documents to the web app, edit their meta-data, and execute tasks (e.g. send the documents to their recipients by e-mail).
Our users need to be able to select any number of documents from a search result. They can pick documents one by one, or click a "Select all" button. We could be talking about thousands or tens of thousands documents to be selected.
When searching for documents, we display paged results in a Datatables table. This means that when making a selection of documents for a task, we need to stock the selection set somewhere, since the Datatable only has knowledge of the rows that are being currently displayed. Currently, we stock the documents' GUIDS in a hidden page element.
This is proving to be insufficient, because we're facing problems with this approach:
- When selecting all documents, there might be a concurrency issue. What if more documents are uploaded that fit the current search criteria, between the time a user makes a search and plans a task? This could lead to the unintended processing of documents.
- If you send all GUIDs to the client when they choose "Select all" (to avoid the concurrency issue above), the list might be too large to send as a JSON object.
- The opposite might also happen: what if the list on the client's side is too large to send to the server?
My question is: what is a better approach to stocking and processing large user selection sets?
Answer: I've found out you can compress response data in ASP.Net, making use of GZip or Deflate.
Thanks to this, I was able to send large data sets, no problem.


Mach O Link Error- linker command failed with exit code 1 (use -v to see invocation)

Question: When I try building for archiving for my app in Xcode (version 4.5) I get an error that says:
<code>ld: file is universal (3 slices) but does not contain a(n) armv7s slice: /Users/[myrealname]/Downloads/[myappname]/BT_Objects/TwitterOAuth/SAOAuthTwitterEngine/libOAuth.a for architecture armv7s
</code>
clang: error: linker command failed with exit code 1 (use -v to see invocation)
It then says under it:
<code>(null): File is universal (3 slices) but does not contain a(n) armv7s slice: /Users/shakerite/Downloads/shakeritetestnotrealone_v15_iOS/BT_Objects/TwitterOAuth/SAOAuthTwitterEngine/libOAuth.a for architecture armv7s
</code>
Does anyone know how to solve this?
Comment: possible duplicate of [file is universal (3 slices) but does not contain a(n) armv7s slice error for static libraries on iOS, anyway to bypass?](http://stackoverflow.com/questions/12402092/file-is-universal-3-slices-but-does-not-contain-an-armv7s-slice-error-for-st)
Answer: I received a very similar message just the other day when I tried running my app on my iPad after several successful attempts on the simulator.  I found out that under the build settings I had to make "build active architecture only" to yes.  Then my app would compile on my device. Hope this helps.
Comment: @shak77, the Build Active Architecture Only is under targets and then build settings.  However, you do need to pick All instead of Basic!  It is at the top of the build setting pane on the left.
Comment: Hi Douglas, I don't see where it says "build active architecture only." Is it under build settings for the target or the project?
Comment: @shak77,  glad to hear.  Don't forget to accept the answer, so the question will be closed!  I am glad that I could help.
Comment: Thanks.....a lot..i got similar Error.....but thanks to @Douglas...Really Much Helpful..and saved my lot of hours..+1 from my side for this
Comment: This works! Anyway if you do not have separate build targets for different devices, it wold be wise to change in the project settings rather than target settings
Answer: Yeah, I had this same exact problem. Click on your project in xcode. Then, click on the target. Go to build settings and look for valid architectures. Delete armv7s from the list of valid architectures and just leave armv7.
Let me know if you have any questions!
Comment: I'll make sure to try this when I get on my computer with the app. Thanks so much.
Comment: Make sure your changing 'Valid Architectures' and not 'Architectures'
Comment: @ttarules,  This is Douglas.  I just wanted to one up you, because I just got a new device and got the Mach O error.  So I followed my answer and got no where.  So I tried yours out and it worked great.  Thanks for the help.
Answer: here I provide you one temporary solution that can solve this error hope its help you,

go to Project->Build Settings->Build Active Architecture Only->yes

thats it.
Comment: -1 : your solution is a duplicate of what @Douglas has posted an year ago.


What determines which part of the "Hyrule Theme" is played in Ocarina of Time?

Question: Recently, I replayed Ocarina of Time on my Nintendo 64.
The first time you exit Kokiri Forest and walk out into the big world outside of it, the theme of Hyrule Field sounds very good as you move toward the town. It gives you a sense of an epic adventure beginning and makes one's skin shiver in a good way.
After beating the game, I'm now trying to recreate that experience, to be able to show it to somebody else. So I loaded up my save file, moved back in time to child Link and made sure the time was "day". Then I saved. Now, I exit Kokiri Forest and walk out on Hyrule Field, but even though I have made several attempts, I just can't get it to play the "proper" Hyrule Theme. It uses different "variations" which don't sound as good at all. I think they are different parts of the same longer theme, picked according to some unknown logic.
The time it takes Link to walk across Hyrule Field is roughly how long it takes for a day-night cycle, so the music stops before it ever gets to the good part. (Assuming that I'm right in my guess about what is going on.)
Is the first time you walk out "special" to the game? Or is it entirely random? Is it only random once you've heard the good version at least once? I actually never noticed this before.
Also, this is not some glorified music memory that I'm getting all mixed up in my head, because I recently heard it with my own ears, straight from my Nintendo 64. It definitely doesn't sound the same when I try it now.
The best part, which I'm trying to hear, goes like this: "du-du-du-du-du-DU-du-du-du, du, du-du-du-du-du-du-DU-du-du, du-du". It can be heard (after a few seconds) here:

Why is not the good version playing for me now? Is there anything I can do to make sure that the good one/part is playing when I show the game to somebody who has never experienced it and I really want to highlight how magical it sounded to my young ears back in the day?
Comment: Could it be that the developers chose to use it only for that initial time you step into the field?
Answer: As you suspect, the Hyrule Field theme consists of several segments, which are played randomly. This is confirmed in an interview with the game's composer:

Kondo:
When I first heard the plan for Ocarina of Time, I thought, "This is going to be a really big game!" There was this big field in the centre, and you needed to ride a horse to reach the other side!
Iwata:
Yes, Hyrule Field was big enough that you were thankful for your horse!
Kondo:
But if you went to all these dungeons and came back and the same old music was playing…
Iwata:
You'd get sick of it.
Kondo:
Right. I wanted to avoid players going to a dungeon and coming back to find the same song droning on. I thought about what I could do to have different music playing whenever you listened to it, and eventually I created several eight-measure "components" to play randomly.
Iwata:
They shared a certain chord progression, so the music could shuffle them around.
Kondo:
Right. Each group of eight measures ended with a chord that would lead nicely into whichever group started next. It sounded natural even when you played them randomly.
Iwata:
How many of those "components" did you make?
Kondo:
About 20. They're in battles, too.
Iwata:
So even if the general atmosphere of the music is the same, it sounds different each time.

They also mention in a different point in the interview how there are three types of segment (the regular one, getting into a battle, and just standing still):

Yokota:
Getting back to Ocarina of Time, the music was different every time you went out to a dungeon on an adventure and came back to Hyrule Field, the main setting of the game. The general feeling of the music itself didn't change that much, but the melodies came along at a different tempo. And even if it was the same song, if you were fighting an enemy, the tune would become more thrilling. Then, when the battle was over, it would return to the usual majestic music*. When Link stood still, it would grow quiet*. The music was constantly changing.
Iwata:
It didn't always play the exact same music.
Yokota:
Right. In the land of Hyrule, the music changed between three patterns, normal, battle and quiet.
Iwata:
Back then when there were still strict restrictions in the amount of memory that you could allocate to sound, it was common to stream pre-created music tracks. But by taking advantage of the ROM cartridge of the Nintendo 64 system, it was possible for the music tracks to be combined and generated depending on the situation. That is why in Ocarina of Time, music was constantly changing throughout the entire game. But even though Kondo-san did that for the sound on Hyrule Field, I doubt many people back then noticed and could talk about it.
Kondo:
Not many people noticed.

*(The interview includes some video examples for "majestic music" and "grow quiet").
As such, recreating exactly the segments you wanted in game would be tricky; you'd need to be performing the right action for the part you wanted to be able to appear, and then get lucky with the randomness. Your best bet might be to play on an emulator (such as using the Switch Online version) and to take a save state before that first walk out onto Hyrule Field - then you can reload the save state and play from there when you want to show it off.
Comment: Thanks for the information. I just wish they would've specifically mentioned that the best part is always played the first time, because I think such must be the case. As for emulators, that would ruin the whole atmosphere as they completely destroy how the game looks, sounds and feels. But maybe it could be done with some "code" when played on an EverDrive...


query parameter validation with Jersey

Question: I'm using Jersey in Java for a simple web server. I'm trying to handle with url query parameters, like
<code>/path?value1=X&value2=Y&value3=Z
</code>
I was able to extract the query value by using the @QueryParam annotation like
<code>@GET
@Produces(MediaType.APPLICATION_XML)
@Path("/path")
public String getUpdate(@QueryParam("All") List<String> allParam,
        @QueryParam(value = "value1") String value1,
        @QueryParam(value = "value2") String value2,
        @QueryParam(value = "value3") String value3) {
        ...
}
</code>
Now my problem is I need to validate the input. I'm mainly trying to make sure that value1, value2 and value3 follow a specific format. I also want to make sure that those parameters are not empty.
I checked out the Bean Validation documentation for Jersey, but it seemed hard to follow. This is probably because I'm still somewhat new to Jersey framework.
So how can I set up query parameter validations? Are there easier to follow resources/examples I could be directed to? Thanks
Answer: As @VA31 linked, you can use bean validation like this, if your jersey is latest enough.
<code>@GET
@Produces(MediaType.APPLICATION_XML)
@Path("/path")
public Response getUpdate(
    @QueryParam("value1")
    @NotNull
    @Size(min = 1, max = 255)
    @Pattern(regexp = "\\d+")
    String value1,
    @QueryParam("value2")
    @Min(52)
    @Max(53)
    int value2,
    @QueryParam("value3")
    @NotNull
    Integer value3) {

}
</code>
Comment: @PratikSinghal Yes it does! `400` will be responded with counterintuitive message.
Comment: Will jersey give a bad request, if the required validation turns out to be false ?

query parameter validation with Jersey


How to pass JsonObject in HttpURLConnection via POST Method in Android?

Question: When I use GET method then run successfully. my codes be below :
HttpURLConnection http = null;
        URL url;
        try {
            url = new URL(URLPREFIX + "login?user=" + "username" + "&pwd="
                    + "password");
            Log.e(TAG, "Login url :" + url.toString());
            HttpsURLConnection https = (HttpsURLConnection) url
                    .openConnection();
            reader = new BufferedReader(new InputStreamReader(
                    http.getInputStream()));
            Log.e(TAG, "reader :" + reader.toString());
            StringBuilder sb = new StringBuilder();
            String line = null;
            // Read Server Response
            while ((line = reader.readLine()) != null) {
                // Append server response in string
                sb.append(line + "\n");
            }
            Log.e(TAG, "sb :" + sb.toString());
            JSONObject job = new JSONObject(sb.toString());
            Log.e(TAG, "job :" + job.toString());
            mSuccess = job.getInt("Status");
            if (mSuccess == 1) {

            } else if (mSuccess == 0) {

            } else if (mSuccess == 2) {

            } else {

            }

        } catch (MalformedURLException e) {
            Log.e(TAG, "MalformedURLException" + e.toString());
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            Log.e(TAG, "IOException" + e.toString());
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (JSONException e) {
            Log.e(TAG, "JSONException" + e.toString());
            e.printStackTrace();
        } finally {
            try {

                reader.close();
            } catch (Exception ex) {
            }
        }

But i don't know how to manipulate POST method. Suppose
    url :https/example.com/folder/something
    parameters  : JsonObject. such as
    {
    "foldername" : "imageFolder",
    "jsonArray"  : ["abc","sdsf","sfsd"],
    "location"   : "Dhaka"
    }

how to manipulate when used post method. Please help me anybody. I a lot of time kill behind of this code. But output of my try is zero. Please help me.
Comment: What do you mean `manipulate`? You want send or get json object?
Comment: send json object into server.
Answer: private static HttpResponse sendRequest(String url, String stringParams, Header[] headers)

            if(stringParams!=null) {
        Log.d(TAG, "sending request with the given params:" + stringParams);
    }
    HttpResponse response = null;
    HttpRequestBase request = null;
    DefaultHttpClient client = new DefaultHttpClient();

    HttpEntity entity =getHttpEntity(stringParams);
        request = new HttpPost(url);
        if (entity != null) {
            ((HttpPost) request).setEntity(entity);
        }

    Log.d(TAG, "request to url: " + url);
    if (headers != null) {
        Log.d(TAG, "adding headers: " + headers);
        request.setHeaders(headers);
    } else {
        Log.d(TAG, "no headers to add");
    }
    try{
        response = client.execute(request);
    } catch (Exception e) {
        Log.w(TAG, "exception", e);
        throw e;
    } finally {
        client.shutdown();
    }
    return response;
}

private static HttpEntity getHttpEntity(String stringEntity) {
        HttpEntity entity = null;
        try {
            entity = new StringEntity(stringEntity, HTTP.UTF_8);
            ((StringEntity) entity).setContentType("application/json;charset=UTF-8");
            ((StringEntity) entity).setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));

        } catch (Exception e) {
            Log.d(TAG, "error creating entity: " + stringEntity);
        }
        return entity;
    }

you need to convert your jsonObject to string, to use this method, just call jsonObject.toString();


Is it okay that I taped over ventilation outlets?

Question: I live in a building where I have no control over ventilation, it is very loud and annoying, the smell from othe people rooms and cooking is coming inside my room, together with the awful amount of dust. I taped over both ventilation outlets, the one that sucks the air from the room and the one that puts air inside the room. Is this okay for the ventilation system, that is apparently connected for all the units in the building?
Answer:
the smell from other people rooms and cooking is coming inside my room

And any airborne viruses...
The ventilation system isn't supposed to suck air from other people's appartments and blow it into yours. If it does, then something is absolutely wrong with the system. Maybe the fan that's supposed to suck outside air and blow it in is out of order.
If it smells like cooking, then maybe someone in the building plugged the outlet of their kitchen hood into the wrong pipe, so instead of going outside, it goes to everyone else's appartments.
You can try talking with whoever manages the building.
But taping over the vents won't break anything. Just remember to open the windows once in a while, especially if you air dry some clothes, otherwise without ventilation it'll get damp and moldy.
Comment: Most residential hvac systems have return air and don't use fresh air.  I imagine a lot of older buildings do the same thing where they don't have a heat exchanger - some of the return air would be sucked out of the building as combustion air at the return point assuming the hvac is using combustion.
Comment: It is actually a completely new building, but it's a student residence and I guess they were going for the cheapest option possible, especially because I have no control over switching it on/off. I do open windows and doors very often. Thank you for your answer!
Answer: This happens a lot in older building that utilize ductless vent, relying on the space between joists to vent air. Taping them up will not cause any damage to the system.
You might want to think about getting a window fan, window AC or portable AC unit. Running these would give you a pressure increase that could cancel the air flowing into your unit from these vent if you untaped them. If you kept them taped up, you'd get some fresh, filtered air (with the AC units) and just fresh air with the fan.
Comment: My only concern was not to cause damage, otherwise I am completely fine without it and I open my windows often ane air is always fresh. Thank you for your answer!


Remove duplicate pattern (dutch number and postal code) REGEX

Question: I would like to remove duplicates with regex in python but I'm struggling a bit.
text= 'H. Gerhardstraat 77 1502 CC 77 1502 CC Zaandam'
text = re.sub(r'\b(\d{,4})\s(\d{4})\s([A-Za-z]){2}\b', r'\1', text)

print(text)

I would like to get 'H. Gerhardstraat 77 1502 CC Zaandam'
I now get this :
'H. Gerhardstraat 77 77 Zaandam'
Answer: Use the forth argument count of re.sub(pattern, repl, string, count=0, flags=0) as follows:
text= 'H. Gerhardstraat 77 1502 CC 77 1502 CC Zaandam'
pattern = r'(\d{0,4}\s\d{4}\s[A-Za-z]{2}\s+)'
count  = len(re.findall(pattern, text))

if count > 1:
    text = re.sub(pattern, '', text, count -1)

Comment: This also removes the pattern when its not duplicate.
Comment: @user773674 It was just an example code which removes only 1 duplicate from the whatever number of duplicates are present in the text (if just one, then it will be removed as expected). You could just extend this to whatever used case you have. Anyhow please find updated snippet.
Answer: try this :
import re

c = re.compile(r'([\w\.]+)(?!.*\1)')
text = 'H. Gerhardstraat 77 1502 CC 77 1502 CC Zaandam'

print(' '.join(c.findall(text)))

output :
H. Gerhardstraat 77 1502 CC Zaandam

Link to Demo
Explanation : We match every words including period with [\w\.]+ only if there isn't any same word later using negative lookahead assertion. \1 here points to ([\w\.]+) group.
This way we only get the last occurrence of the words in the list.


How to change hostname

Question: I have updated my system's hostname in /etc/hostname file as master. I have also mapped my /etc/hosts file like
<ip> master

Still, when I type $ hostname, I get a different hostname.
I basically want to change my hostname from the default one to "master".
What file am I missing out?
Comment: What is `` the placeholder for? It should be 127.0.1.1
Comment: Your host name is by default your machine name. If you have Apache installed, it can be typed into the url bar. So mine is Hairy14, and I see my locally hosted website. Why do you need to change it?
Comment: I am working on hadoop with ec2 instances. I would want to change my instance names to master and slaves for easy tracking while working on the terminal
Comment: Just use localhost
Answer: The problem is that you should have:
127.0.0.1   localhost
127.0.1.1   master

in your /etch/hosts file, not a real ip address.
Simply run the command sudo hostname your-new-name
If that doesn't work, can you not use localhost instead of master?
Comment: I changed my host file as you said and reconnected to the instance. Still when I type $hostname, I get "ip-" which was my default hostname.

How to change hostname


Vivado / Vitis HLS - "WARNING: Port "xy" has no fanin or fanout and is left dangling."

Question: Often I get the error message

WARNING: [RTGEN 206-101] Port 'xy' has no fanin or fanout and is left dangling. Please use C simulation to confirm this function argument can be read from or written to.

C simulation and synthesis passes. What is the general reason ports are sometimes left dangling? How can I debug it? And is it important to resolve them?
Answer: That warning usually comes if some ports, i.e. function arguments, are never utilized in your C/C++ code. It might happens that the compiler/Vivado HLS simply optimizes away parts of the code where the arguments/ports are never accessed or never reached.
This last condition might actually help finding spots of a buggy algorithm. For instance: an if-else statement can be resolved in only one branch always being executed, thus leaving out the arguments processed in the other branch (and therefore generating dangling ports).
In general the warning causes the generated RTL to still have the defined ports, but just having them unconnected to anything.
They are usually not an issue in later generation steps, since they might be further optimized away and removed (during synthesis or optimization, before generating the bitstream).


Executing processes with python by subprocess library

Question: i've just created a software in python which should schedule several commands from shell. (ps: i'm working on linux)
By the way, i've created the following function to launch processes:
def exec_command(cmd):
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True, preexec_fn=os.setsid)
pid = process.pid
print '----------launched process with PID: ', pid
return pid

After this i use the pid to check if the process goes on zombie's state and in that case a kill it.
Sometime everything works just fine but there is a case in which the process launched doesn't do anything.
The process i'm talking about is:    sh /home/ubuntu/programs/data-integration/kitchen.sh -file=/home/ubuntu/TrasformazioneAVM/JobAVM.kjb -level=Basic -param:processName=avm
If i launch it by shell everything works perfectly but if i do it with my function i can see the process on the system monitor (or by shell with the "top" command) but nothing appens (i check the memory usage and cpu usage which is usually really high but not in this case).
Any body has any ideas ?
Comment: can you please write the output of print cmd
Comment: What do you mean whit "print CMD" ?
Comment: i mean are you giving cmd as a list or a string
Comment: This is the string: sh /home/ubuntu/programs/data-integration/kitchen.sh -file=/home/ubuntu/TrasformazioneAVM/JobAVM.kjb -level=Basic -param:processName=avm
Comment: related: [How to hide output of subprocess in Python 2.7](http://stackoverflow.com/q/11269575/4279)
Answer: stdout=subprocess.PIPE

Here is the culprit. You're redirecting your child process output to a pipe, but you aren't reading from that pipe.
You can either read from it (if you need output that process creates), or remove redirection altogether.
Edit:
If you wish to redirect output to /dev/null, given the fact that you're launching your command through shell (shell=True) anyway, the simplest solution would be to append > /dev/null to cmd string. If it's also printing to stderr, then you need >/dev/null 2>&1.
A better solution, that doesn't require launching your command through shell, would be as follows:
If you're on Python 3.3 or higher, just pass subprocess.DEVNULL constant:
subprocess.Popen(cmd, stdout=subprocess.DEVNULL, shell=True, preexec_fn=os.setsid)

If not, or you want to maintain backward compatibility, just open /dev/null and pass it:
subprocess.Popen(cmd, stdout=open(os.devnull, "w"), shell=True, preexec_fn=os.setsid)

Comment: @user2637212 Do you need the output that program prints? If you just need to see it yourself, remove stdout argument (or set it to None). Output will be printed to your shell. If you don't need the output at all, you can redirect it to /dev/null by opening it for writing and passing resulting file object. If your python script needs to interpret output somehow (parse it, etc), it will be somewhat more difficult, and it's a completely different story.
Comment: I think that i have to create a pipe because when i launch the process many pids are generated and i when a kill one of these i want that all the proccesses connected die
Comment: @user2637212 you don't have to use pipes to do that. It's more like side-effect that child receives SIGPIPE and dies once it tries to write to pipe that's closed on the other end. You can use process groups, for example. Remember that pressing  ^C in console interrupts all children? It's implemented by sending SIGINT to entire process group. You can do that, too.
Comment: So what do you suggest to write instead of stdout=subprocess.PIPE ?
Comment: Ok, i set "stdout" to None and now everything works just fine. As you said it prints the output on my shell. I would like to redirect it to /dev/null. How can i do it ?
Answer: Try below
def exec_command(cmd):
    cmd = cmd.split()
    process = subprocess.Popen(cmd, stdout=subprocess.PIPE, preexec_fn=os.setsid)
    pid = process.pid
    print '----------launched process with PID: ', pid
    return pid

Comment: what was the response


Which one is easier and more expensive for a DIYer when building walls for a shower -Kerdi board or cement board?

Question: After buying cement boards for my shower walls (using a base for the shower ) I am having second thoughts about using cement boars after seeing how friable they are. Also after briefly looking at kerdi boards is seems easier to work with but I have the slight feeling that this is not for DIYers.
Also it might need more expensive accessories like screws, sealing paper or similar and I am not sure if the same water proof membrane (redguard) can be used for it or it needs some special for kerdi boards only membrane
Also it might need some special thinset
When it comes to price to cover a quarter of a 4x8 with kerdi seems to be double that the full sheet of cement board
Comment: Never used Kerdi, but have done several shower/tub surrounds with cement board.  Using cement board for this type of project is well within the skill set of the average DIYer, IMO.
Comment: yes I thought so but I feel the cement board is flimsy and fragile. Not sure if there are other options
Comment: I did cement board for my tub/shower surround nearly 30 years ago (before the internet had all the answers to life, the universe and everything). The hardest part I remember was cutting it - we went through tons of blades. I don't remember it being as fragile as you're indicating your is. Maybe quality has changed...
Comment: Also, you want the easier _and_ more expensive option? Based on Fredric's answer, it sounds like there isn't one - the more expensive option (Kerdi) is also more difficult.
Comment: It seems that I will have to live with the 'pleasure' to work with cement board
Comment: Kerdi waterproofing membrane over drywall and kerdi pan and drain.
Answer: Cement board is far cheaper and easier to work with, even considering the total cost of the solutions with waterproofing.
Cost - Cement boards vary in price a bit, but they don't include waterproofing so of course they're cheaper. Kerdi is a system with strict install instructions - more on that in the "ease of install" section.
Ease of install - Looking up install instructions or demos on YouTube will show the difference. As mentioned above, Kerdi is a whole system: wall boards, fasteners, fastener seals, edge/corner seals, plumbing penetration seals. It does a very good job but it's far from easy and this makes it expensive. It also has strict install instructions in order to qualify for its warranty and even if you're not interested in the warranty, you'll get best results by following its whole system to the letter anyway.
Cement board has its own quirks but is much simpler to install: keep it intact, cut to shape, use proper fastener schedule, tape seams and apply thinset, then cover with your choice of waterproofing (Redgard or similar brands).
Comment: Kerdi schlutter system is far easier to work with than cbu.
Comment: I disagree, but there's definitely a case to be made. Feel free to write your own answer. As a non-pro who's done 2 showers, a tub surround, a floor, and a kitchen backsplash, I would 100% rather do concrete than Kerdi. Pros who do Kerdi often might have some shortcuts to make it less work, but it's daunting. See https://youtu.be/9hPMWc22oK8 for an example


Computations question

Question: a) Determine the prime factorizations of 3850 and 4125
b) Find the value of d = gcd(3850,4125)
c) List all the positive divisors of d
This is what I have so far.
a) 3850: 11, 5, 5, 7, 2
4125: 11, 5, 5, 5, 3
b) gcd(3850,4125) = 11
c) How would I find this?
Comment: gcd$=11\cdot5^2=275$
Comment: gcd of 3850 and 4125 is 275?
Comment: @DanielValentine That would be correct.
Comment: If $m=\prod p_i^{r_m},n=\prod p_i^{r_n} $ gcd $$=\prod p_i^{\text{min}(r_m,r_n)}$$
Answer: This is what @lab trying to refer you:

Now pick the primes which are in common in two numbers with minimum powers. So you get $$\gcd(3850,~4125)=5^{\color{red}{2}}\times 11$$
Comment: If we pick the primes which are in common in two numbers with maximum powers we get $lcm(3850,4125)=2\times3\times5^3\times7\times11$.(+1)
Comment: so is my answer to part b 25*11 = 275?
Comment: How would I find all the positive divisors?
Comment: @DanielValentine: Do the same as the picture tells and then consider all multiplications of primes. I mean: $$1, 2, 5, 7, 2\times 5=10, 11, 2\times 7=14, 2\times 11=22, 5\times 5=25, 5\times 7=35, 2\times 5\times 5=50, 55, 70, 77, 110, 154, 175, 275, 350, 385, 550, 770, 1925, 3850$$
Comment: why would 7 be a possible divisor of d? which is 275
Comment: would the positive divisors just be 1, 5, 11, 25, 55, and 275?
Comment: @DanielValentine: It is wrong. :) In fact according to the definition of `gcd` $d$ divide both numbers. Does $7$ divides $d$ while $d$ is free of $7$?!
Comment: @DanielValentine: Yes they are for $d$. Not for two numbers.
Comment: I'm a bit confused. So my question tells me to list all the positive divisors of d, won't I just be looking at 275?
Comment: @DanielValentine: As you wrote it, your question tells you to list all the positive divisors of $d$ which is $1,5,11,25,55,275$.

Computations question


Is the "MOV" instruction in Assembly to allocate memory?

Question: I notice that MOV is supposed to copy and overwrite data to and from registers, but if there's no present data in any other register, does MOV move a certain sized byte(s) from RAM to the register to temporarily hold it, or how does this work exactly?
To clarify my question, say I use:
MOV AL, 0x10;

In such a case, where is the "10" digit data that is moved to the 8-bit register?
Is this moved from RAM to AL as eight bits to hold, or is the "10" byte just a scratchpad number that is not in memory?
I don't understand this, and it would be amazing if someone could straighten this out.
My problem is that I need to know where and how much memory is used, and how and what exactly is addressing it(and tutorials don't make clear of this).
Comment: It's in the instruction itself.
Comment: Perhaps the missing concept is that MOV isn't a single instruction. There are tons of them, one moves 10 to AL, another moves 42 to BX, etc.
Comment: You don't really "allocate" memory in ASM in the traditional sense. The memory is all there.
Comment: @GManNickG  Could you clarify that a little more? So you're saying that the RAM is accessed by the instruction itself, and not moved? I don't get it.
Comment: can you tell us why you need to know this. please give more context
Answer: Guessing at the mental block: it is important to understand that RAM both contains code and data.  The value 0x10 comes from code.  It was encoded into the machine code instruction by the assembler.  That code got loaded into RAM by the operating system when it started executing your code.
Notable is that it is not a variable, the instruction will always load 0x10, regardless of the state of your program.  Other parts of RAM store the data that you declared in your assembly program.  Like the .data and .stack sections.  But is not otherwise used by this particular instruction.
Adding to the possible confusion:  it doesn't have to be in RAM.  On embedded systems without an operating system or boot drive, the code is often burned into ROM instead.  The processor doesn't otherwise care about it, it just reads bytes from a memory bus, using the EIP register (the instruction pointer) to tell the memory sub-system what bytes it needs.
Answer: your code lives in RAM ie, the bytes that represent MOV AL, 0x10;,  the 0x10 is part of the instruction, its not stored seperately.  Typically it wont be coming from RAM at the point of execution but a instruction pipeline on the CPU,  The CPU fetches instructions from RAM into its pipelines as it see's fit.
for a great free online book on assembly try http://cs.smith.edu/~thiebaut/ArtOfAssembly/artofasm.html
chapter 4 deals with memory addressing  http://cs.smith.edu/~thiebaut/ArtOfAssembly/CH04/CH04-1.html
there are a lot of concepts to get your head around, memory addressing in all its forms and how to work with the CPU architecture can seem daunting at first, but will slowly start making sense as you try stuff out.
Comment: I still really don't understand how that makes sense ... the instruction is stored in RAM, but how do you move the data to the processor to work with it? And when it's "in" the processor, how do you know when and what is concurrently in RAM, or moved between the devices interchangeably between instructions in parallel?
Comment: well, for instructions like the one you have shown, it doesn't involve accessing RAM for data purposes,  the instruction contains all the necessary parts.   For addressing memory so that you can store data or retrieve data, generally you have an allocated chunk of memory ( how you get that depends on whether this is running on an OS, or is embedded, or something else).  You load an addressing register with the start of that chunk, and then use a mov with an index, like mov     al, [eax][ebx]
Comment: where eax would hold the base memory address of the chunk,  and ebx would hold an index into that chunk where you want to access the data
Answer: I suppose that the primary memory in your device/machine is RAM. So basically your application would be exists there at run-time (after you run that application from hard disk for example, it will be load into the device memory). By the way, all of the binary-instructions which are executable for the processor are in RAM now.
To simplify that, let say processor will start reading the memory from the very first cells, like 0, will try to understand what to do with that, and after finishing will move on to the next one which is 1 in this case and so on.
Now let say mov al, 0x10 is equal to 0xAABB in our imaginary processor. At the physical memory, 0xAA is stored at the cell number 20 and 0xBB at 21. Our processor is still busy to reading the stream. When it reaches the memory at 20, it would load the binary value that is 0xAA in this case. By the way, in our processor's documentation it means Fill up the AL with the Following data. The Following data in our case is 0xBB, so the processor will do that.
As you can see:

here, in our example, everything exists in the RAM (at run-time) including executable instructions, data, etc.
CPU reads it from RAM and will try to do whatever is supposed/necessary to do by that
As you may noticed that mov al, 0x10 wasn't allocate at the run-time, but it was all hard-coded by the compiler, and stored into an executable file (for example)
So, that imaginary 0xBB is exists on the RAM, but you can't change it at the run-time. Again keep it in mind that it wasn't also created at the run-time, it was just loaded into the RAM, at run-time

I hope it helps you understand that better.
Answer: assembly instruction
mov al, 0x10

is equal to 0xb010 in binary
mov al, 0xff

is equal to 0xb0ff
if you are on windows
you can click start - run - debug
and in a debug window, write
a
[Enter]
mov al, ff
[Enter]
[Enter]

it change
mov al, ff
to binary
and then you can see 0xb0ff
by..
u 100
[Enter]

a
mov al, ff

means 'assemble' mov al, ff and save to current location(may be 0x100)
u 100 means 'unassemble' location 0x100
Comment: the file contains 0xb0ff and loaded on ram when you execute it. and cpu read ram and execute 0xb0ff.


How can I create network plot in one column based on another column?

Question: I want to create network plot in one column based on another column.
Here an example of what my data frame looks like:

## project-ID ## ## Area-ID ##
     1                2
     1                3
     1                5
     2                4
     2                2
     2                3

so the network plot will show the relation between AreaID, I didn't found any idea that will help me.
Answer: We can convert the data.frame to an igraph object, and plot the graph.
# Sample data
df <- read.table(text =
    "project-ID Area-ID
     1                2
     1                3
     1                5
     2                4
     2                2
     2                3", header = T)

# Convert data.frame to igraph and plot
library(igraph);
ig <- graph_from_data_frame(df);
plot(ig);

Many resources involving plotting and analysing networks/graphs using igraph can be found online, e.g. here, here, here, ...


How to find the lowest value and the corresponding date SQL-Server 2014

Question: I have the sample data See the SQL Fiddle. I want to find the lowest value from the value column and the date of lowest value from the uploaded-date column. I tried the following query and it is not properly working and showing all values.
SELECT
    username,
    MIN(Value1) AS MinValue1,
    CASE
        WHEN value1 = MIN(value1) THEN uploaded_date
    END
    AS MinDate
FROM
    test

GROUP BY
    username

Answer: You could use the RANK window function to find the minimal value for each username:
SELECT username, value1, uploaded_date
FROM   (SELECT username, value1, uploaded_date,
               RANK() OVER (PARTITION BY username ORDER BY value1 ASC) AS rk
        FROM   test) t
WHERE  rk = 1

SQLFIddle
Comment: Thanks, It is working like a charm. I will accept your answer in 5 minutes. Any suggestions why my approach is not working? or how that can be aggregated.
Comment: Your original query is mixing aggregate and non-aggregate terms, which is not allowed. The other two answers demonstrate ways to separate the aggregate terms from the row terms with a subquery, while mine uses window functions instead.
Answer: SELECT test. username,value1,MIN(uploaded_date  )FROM
(Select MIN(value1) MinValue1,username from test group by username ) A
INNER JOIN
test
ON A.MinValue1 = test.Value1
AND A.username = test.username
GROUP BY
test. username,value1

Your query did not work because you were using the columns in the select list so the Group by clause will group all distinct values into each row
Comment: Can you please update the query because there is a small bug. In the case when user enter same value for value1 it shows all the values. Can you please update it to make only one row (first one).
Answer: i hope this will help you
  ;with CTE as(
    SELECT username,
      MIN(Value1) AS MinValue1
  FROM
      test
  GROUP BY
    username
  )

  select c.username,MinValue1,dt.uploaded_date from CTE c
  cross apply(select top 1 uploaded_date from test where value1=c.MinValue1 and username=c.username order by uploaded_date desc) dt

Answer: select Value1, update_date from test order by Value1 limit 1


MySql - Select between date together with other datatype

Question: I want to select varchar within date. I already tried code below but it will ignore date selection. It will select outside(and inside) the date range.
    SELECT *
    FROM register
    WHERE company LIKE '%abc%' OR address LIKE '%def%'
    AND Timestamp
    BETWEEN  '2011-8-1 10:00:00'
    AND  '2011-8-31 10:00:00'

If I just leave the date itself, yes it works
    SELECT *
    FROM register
    WHERE Timestamp
    BETWEEN  '2011-8-1 10:00:00'
    AND  '2011-8-31 10:00:00'

I just want select varchar WITHIN selected date. How?
Answer: That's because of operators OR and AND precendence.
Wrap your whole OR part with parenthesis
    SELECT *
    FROM register
    WHERE (company LIKE '%abc%' OR address LIKE '%def%')
    AND Timestamp
    BETWEEN  '2011-8-1 10:00:00'
    AND  '2011-8-31 10:00:00'


How to provide an "easy to understand" UI to display/hide checked items?

Question: I have a tree where the user can check/uncheck each item. Since there's many items, I would like to provide a way to filter the tree to display:
<code>all items
only selected items
only unselected items
</code>
Today, I have three radio buttons:

download bmml source – Wireframes created with Balsamiq Mockups
From user's feedback, the behaviour of those buttons seems not obvious.
Do you have a better way to provide this feature, is there some patterns around that?
Comment: Could you provide a screenshot of your user interface? Maybe the lack of understanding is due to false positioning and relation with other elements.
Answer: Could you implement a dropdown? Something like the following:

When the dropdown is closed, only the active choice will be visible, hopefully causing less confusion.
Comment: Titling the drop down "Filter" might also help the user to understand it's purpose
Comment: @AndrewMartin +1, good addition. I used "Display" because it was the language used in the question, but that language may also contribute to user confusion.
Answer: Radio buttons imply an OR condition, meaning you're choosing A or B or C.  In your case, choosing A is the same as choosing B and C, which may be what's leading to the confusion.
A better option may be two checkboxes where any combination of the two may be chosen:
[] Display selected items
[] Display unselected items
Answer: I'd suggest a filter with the checkboxes like so:

download bmml source – Wireframes created with Balsamiq Mockups
The "display all" option seems redundant, and could possibly have the effect of making it seem like "all" consists of more than selected and unselected.  The dropdown has the same problem. Most users already associate checkboxes with multiple options that are not mutually exclusive.
Instead, all items would be displayed when either both checkboxes are checked, or when both are unchecked—the equivalent of no filter.

How to provide an “easy to understand” UI to display/hide checked items?


OpenGL: Purpose of transform matrix in Vertex shader where transform*vertex

Question: I'm trying to understand OpenGL by using Processing OpenGL ES.
If I have an example Cube to render.
I've read that a vertex shader will be run once for each Vertex. The fragment shader will be run (at least) once for each pixel.
In a vertex shader I have:
#define PROCESSING_COLOR_SHADER

uniform mat4 transform;

attribute vec4 vertex;
attribute vec4 color;

varying vec4 col;

void main(){

    gl_Position = vertex;

    col = color;
}

In a fragment shader I have:
gl_FragColor = col;

When ran, it creates a simple painted cube of the colour defined in the Processing sketch. However, if I change the vertex shader to...
gl_Position = vertex

(instead of transform*vertex) it draws a wireframe cube in exactly the same place. What exactly does the transform matrix do?
Answer: The transform matrix will be a uniform which is easier to update and upload to the gpu (just a single glUniform call) than applying the transform to all vertices on the cpu and uploading the new vertices. Especially with large models.
Comment: Altough it could be used to other things
Answer: The transform matrix allows you to translate, rotate or resize your model. From the model's point of view, its vertices always are at the same position. But if you multiply the vertices with, let us say a translation matrix, they all get moved. Seen from the model's origin, they are still at the same position. But in world space, your whole model has moved.
The reason that changing the code did nothing to how the cube was presented to you lies in your transformation matrix not applying any changes to the cube's model data.
If you choose a different transformation matrix, things will look differently.


Made huge mistake when updating, nothing seems to work

Question: I recently tried to update my old song laptop to 12.4 to make it more useable, but I accidentally closed the computer without thinking while it was installing packages. Now I've turned it back on and all I get is a black screen with a line of settings - file, edit,view, go, bookmarks, help. I can't connect to the internet, the only thing I can do is change the background colour from black to blue or purple. I'm not very tech savvy so please use fairly simple language. Is there anything I can do?
Answer: Try to get access to a terminal by pressing Ctrl+Alt+F1.  If it works, log in and try the following commands to continue an interrupted update:
sudo dpkg --configure -a
sudo apt-get -f install
sudo apt-get update
sudo apt-get upgrade

If you don't have Internet, here's something else you can try:
First, boot an Ubuntu live CD and click the "Try Ubuntu" option.  When you get to a desktop, connect to a wifi network.  Then open a terminal and type:
sudo mount /dev/<sdaX> /mnt

sudo mount --bind /dev /mnt/dev

sudo mount --bind /proc /mnt/proc

sudo mount --bind /sys /mnt/sys

sudo chroot /mnt

apt-get update

apt-get upgrade

Note that instead of /dev/sdaX in the first command, type whatever partition Ubuntu is installed in.  If you don't know, install gparted from the software center, open it, and figure it out from the partition sizes.
If nothing works and you just want to back up and reinstall, then from the Live CD session open the file browser, and on the left hand side you should be able to see your hard disk and access all your files.  From there, you can copy your home folder to a flash drive/external HDD.
Comment: It says to enter a sudo password, but I don't think I have one... What do I do?
Comment: @user270189 your sudo password is the same as your account password.
Comment: Wait, no. I just did the update command but some index files failed to download and have been ignored. Should I repeat the command?
Comment: @user270189 I would suggest that you proceed with the upgrade command, and post back if you still encounter problems.  At this point it seems like the failed index files may be an unrelated issue.
Comment: I did that, but it says 'need to get 4.9.1/849 MB of archives and asks to free 27.5 MB of dusk space, I responded yes and it said to use apt-update. I tried it again and it just went through the same thing. Is this a disk problem? Memory trouble?
Comment: Is this computer normally connected to the internet with a wired connection, or with wireless?
Comment: @user270189 Ok, is it possible to connect this computer to the internet with a wired connection?  Typically, when Ubuntu is in a partially working state like this, it will not connect to wifi but will easily connect to a wired network.  An internet connection is required for this operation to work.
Comment: @user270189 Without Internet, the only other possibility I'm aware of is to upgrade using an alternate install ISO, but it requires a bit more terminal work.  Instructions: http://linuxpoison.blogspot.com/2011/06/how-to-upgrade-ubuntu-using-alternate.html  Otherwise, I think you'll have to back up your files and clean install.
Comment: @user270189 I edited and added another possible solution, so try that first.
Comment: Ugh, I hate to have this long discussion in the comments section but it doesn't seem like you can use chat yet.  Anyway, here are instructions on creating a CD: https://help.ubuntu.com/community/BurningIsoHowto