text:
Q: Suspend on Ubuntu 18.04 Not Saving State Using uswsusp and s2ram I am unable to get the "Suspend" functionality to work correctly on Ubuntu 18.04. However the Hibernate functionality works as expected.
Problem description:
When I use Suspend from either the Power Menu or "sudo systemctl suspend" the behavior is:

*

*The machine goes into Sleep mode and the power button LED slowly blinks (breaths).

*When the laptop is restarted, the OS starts up, I see the usual login screen, but none of the applications that were running are restored.

What I have done so far:
$ sudo apt-get install uswsusp
$ sudo update-initramfs -u
$ sudo systemctl edit systemd-suspend.service

I pasted in the following lines into systemd-suspend.service:
[Service]
ExecStart=
ExecStartPre=-/bin/run-parts -v -a pre /usr/lib/systemd/system-sleep
ExecStart=/usr/sbin/s2ram
ExecStartPost=-/bin/run-parts -v --reverse -a post /usr/lib/systemd/system-sleep

*

*saved the file. It gets saved in /etc/systemd/system/

*run:
$ sudo systemctl daemon-reload

*Test it:
$ sudo systemctl suspend
The results are as described above, the laptop sleeps, however the saved session is not restored on restart.
I do know that the systemd-suspend.service script is being called. If I change the line ExecStart=/usr/sbin/s2ram to ExecStart=/usr/sbin/s2disk the laptop goes into Hibernate and restores the session.
Additional info:
In order to get Hibernate to work I changed grub:
sudoedit /etc/default/grub

changed this line:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
 to:
GRUB_CMDLINE_LINUX_DEFAULT="no_console_suspend initcall_debug resume=UUID=<string of hex> resume_offset=34816"

*

*then ran:
$ sudo update-grub
Kernel info:
lsb_release -a

Distributor ID: Ubuntu
Description:    Ubuntu 18.04.2 LTS
Release:    18.04
Codename:   bionic

uname -a
Linux <machinename> 4.18.0-21-generic #22~18.04.1-Ubuntu SMP Thu May 16 15:07:19 UTC 2019 x86_64 x86_64 x86_64 GNU/Linux

sudo s2ram -K
This kernel has KMS support.

Is there some step or configuration item that I'm missing?

A: After much searching for an answer and banging my head on the table I arrived at a solution on my own by cobbling together bits and pieces of information from various sources. This solution works on my Sony Vaio Model VPCEB15FM running Ubuntu 18.04, your mileage may differ.
Part of the problem with getting hibernate/suspend to work correctly was the way that Ubuntu loads and assigns /dev/sda2, /dev/sdb2, etc. since the drive assignment order sometimes changes from boot to boot.  So the first step is to identify the UUID of the swap partition. Since the UUID is constant it makes a much more reliable mount point.
The UUID can be gotten from:
sudo blkid

Look for the entry that says "swap"
/dev/sda2: UUID="5c555600-2e37-477d-62df-6013d61dc36" TYPE="swap" PARTUUID="2f501554-02"

Your UUID will be different than mine. Don't use mine, use yours.
If you're using a swap file instead of a swap partition then use the UUID of the main linux partition, and you will also need to know the offset to the swapfile.
To get the offset to the swap file:
sudo filefrag -v /swapfile

The output will look similar to this:
ext:     logical_offset:        physical_offset: length:   expected: flags:
   0:        0..   32767:      34816..     67583:  32768:
   1:    32768..   63487:      67584..     98303:  30720:
   2:    63488..   96255:     100352..    133119:  32768:      98304:

The offset you're after is the first "physical_offset", in this case it would be 34816.
Now you have the information you need to get started.
Modify /etc/default/grub
sudoedit /etc/default/grub

change the line:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

if using a swap partition to:
GRUB_CMDLINE_LINUX_DEFAULT="no_console_suspend initcall_debug resume=UUID=5c555600-2e37-477d-62df-6013d61dc36"

if using a swapfile to:
GRUB_CMDLINE_LINUX_DEFAULT="no_console_suspend initcall_debug resume=UUID=5c555600-2e37-477d-62df-6013d61dc36 resume_offset=34816"

Install uswsusp.
This installs the s2disk, s2ram, and s2both methods.
sudo apt-get install uswsusp

Set up systemd-hibernate.service and systemd-suspend.service.
These files are in /etc/systemd/system/ or will be created there if they don't already exist.
sudo systemctl edit systemd-hibernate.service

Paste in these lines:
[Service]
ExecStart=
ExecStartPre=-/bin/run-parts -v -a pre /lib/systemd/system-sleep
ExecStart=/usr/sbin/s2disk
ExecStartPost=-/bin/run-parts -v --reverse -a post /lib/systemd/system-sleep

Note: my system has a path to /lib/systemd/system-sleep, others might have a different location like /usr/lib/systemd/system-sleep.
sudo systemctl edit systemd-suspend.service

Paste in these lines:
[Service]
ExecStart=
ExecStartPre=-/bin/run-parts -v -a pre /lib/systemd/system-sleep
ExecStart=/usr/sbin/s2both
ExecStartPost=-/bin/run-parts -v --reverse -a post /lib/systemd/system-sleep

Note use s2both instead of s2ram in the "suspend" configuration. s2ram didn't work on my system, but s2both always does.
Ubuntu 18.04 and 20.04:
Edit /etc/uswsusp.conf.
Use the UUID and if using a swapfile the offset:
sudo nano /etc/uswsusp.conf

Modify to use your UUID, etc.
# /etc/uswsusp.conf(5) -- Configuration file for s2disk/s2both
resume device = UUID=5c555600-2e37-477d-62df-6013d61dc36
compress = y
# early writeout = y
# image size = 1741570539
# RSA key file = /etc/uswsusp.key
shutdown method = platform
# only needed if using a swapfile
# resume offset = 34816

Note: There is a man page for uswsusp.conf that fully describes all the parameters. There's a bunch of other settings, this is the minimum required. The commented lines were left in so you can see some of the other options.
Ubuntu 22.04:
Edit /etc/suspend.conf.
09-16-2022 /etc/uswsusp.conf file has been replaced by /etc/suspend.conf
See: https://wiki.archlinux.org/title/Uswsusp
sudo nano /etc/suspend.conf

Only the "resume device" line has changed from the instructions above, everything else can stay the same.
Use this line instead:
resume device = /dev/disk/by-label/swap

Edit /etc/initramfs-tools/conf.d/resume
sudo nano /etc/initramfs-tools/conf.d/resume

add this line:
RESUME=UUID=5c555600-2e37-477d-62df-6013d61dc3
Note:  if using a swapfile then the offset needs to be added.
add: resume offset = 34816 after the UUID
Okay, that should take care of the various configuration items.
Update grub and initramfs:
sudo update-grub
sudo update-initramfs -u  or update-initramfs -u -k all  to do all kernels

Restart Ubuntu.
After the reboot test the hibernate and suspend functionality. Hibernate can take several minutes to write the resume file to the swap and shutdown the machine. Don't Panic. Suspend is a bit faster.
Test it all out!
sudo systemctl hibernate
sudo systemctl suspend

What you should see:

*

*hibernate - shuts down system completely, will take several minutes. After restarting the computer and logging back in your applications should be resumed. Note: The resume process can take a few minutes and the machine may appear hung while resume takes place. Be patient.

*suspend - the system goes into "sleep" mode and the power light slowly blinks (breaths). Pressing the main power button wakes up the machine. You should see the login screen and your applications should be resumed.

Further steps:
You should be able to enter sleep/suspend mode from the power menu drop down. When you open the drop down press the Alt key. The Power Icon should change into the sleep icon.
A Hibernate menu option can be added too. There are already some good tutorials on that which can be found by searching for "ubuntu add hibernate power menu"


text:
Q: Should tables be used to align form elements in HTML or is this looked down upon? I like to follow standards and use table-less div based layouts. However using tables to align form fields/textareas and submit buttons is so much easier than using anything else. So is it acceptable from a strict standard perspective?
I see Google, Facebook among others use tables in their registration pages.

A: Tables are for tabular data, that's all. Period.

A: You can use
 lists, with a little CSS work. In some ways it's less convenient (because you have to size your "label" column manually, pretty much), but in the end the markup is a lot cleaner and it's easier to deal with overall.
With tables, you're forced to group fields according to the layout, and it's totally static once it's on the page. When you use more flexible markup (and smart CSS rules), you can group your form inputs based on their natural relationships.

A: Tables are prefectly fine to display tabular data.
Styleing a form(fields/textareas and submit buttons) however is best to be done using CSS.
Spend the time to really learn HTML and CSS and it will be worth it. Eventually it will be as easy as using a table once you fully understand CSS.

A: I take a pragmatic approach to these things. I avoid using tables for layout and use CSS if I can get away with it. I fall back to tables though, under some circumstances:

*

*I have to have the form layout correct on a lot of different browsers. CSS is easy to learn. But learning all of the idiosyncrasies of all CSS implementations and how to work around them, and how to have them work together, that can be a nightmare.

*There are some logical form layouts that simply cannot be expressed in CSS as it currently stands, but that CAN be expressed in tables. If you have to implement one of these layouts, you don't have much choice but to go with tables.

A: My position focuses more on web accessibility, and using tables for layout is not recommended by the W3C and it can be difficult for screen readers at times, especially when they are nested tables.
HTML should be used for structure and CSS for presentation. I'm currently battling another developer regarding eliminating layout tables unless it's absolutely needed. He insists that the forms require tables and do not work without them, but that's a crock. To me, it's just pure laziness since it means redesigning the entire website.
The formatting of web pages will eventually be done purely in CSS, so why work around it now and not doing it by following the standards? I used to hate CSS, but not I love the fact that applicable text of a page/site can be modified by just one little change within the style sheet. It saves a lot of time in the end.

A: Don't use tables for layouts.  Use tables to store data in a chart.  HTML is not a presentation language.  Presentation is what stylesheets are for.
Google's code is incompetent.  Its homepage is intentionally incompetent to conserve bandwidth by limiting characters in its HTML code.  Its other HTML code is incompetent, because it is written by incompetent people who don't care about the value of conversing their data to the end user.

A: I use tables for tabular data, but I also use them for data input forms, where there are a lot of data-entry fields.  While this may not be considered semantically correct by some, I just find that it is damned near impossible to get everything lined up correctly without using some major CSS gyrations and hacks.
I don't use tables for structural layout, but I will use them for aligning things if it's Just SimplerTM

A: By introducing tables into your HTML, you make the maintainability of your code and future use a little less valuable.  Browsers are constantly pushing towards an all CSS world and tables are GUARANTEED to always work for tabular data.  It's just a COINCIDENCE that tables are easy to use now for formatting.  The easiest way to look at it is like this:
Tables --> Tabular data and reporting
CSS --> Design and formatting (use  DIVs)
HTML --> Structure and data/text
While the tables may be easier now, think about how much maintenance it will create down the road, when browsers change their behavior with rendering tables.
Also think about mobile browsers, they tend to render tables differently.  A table layout may look awesome on a PC and completely fall apart on a mobile browser.
That being said, at the end of the day you have to use CSS to design the tables, so why not start with CSS and Divs.

A: Tables can ease the burden in certain forms.  I find pure CSS great for single-column forms, however often times I'm dealing with very complex forms with multiple columns and/or require notes, hints, indicators that make using just CSS difficult.  For most forms however, pure CSS is the best route to go.
Here's a great getting started with CSS forms tutorial:
http://www.webcredible.co.uk/user-friendly-resources/css/css-forms.shtml

A: What is the
 good for besides tabular data? One thing I like to use it for is 9-slice buttons, so you can easily give things irregular edges or rounded corners while maintaining a center area for content. The following dummy HTML should be easy enough to follow, bearing in mind that top, left, right, and bottom images will have their repeat-x and repeat-y styles set as appropriate to allow them to expand vertically or horizontally:

Some will think this heresy, but I think it's damned convenient. It's layout, but on a micro level. My position is, if it works, use it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Setting values to a specific element in an array of dictionary overrides all values in array I'm trying to assign a specific value to a specific location in an array of dictionaries.
the assignment overrides all values in array - why?
a = fill(Dict("example" => 0.),3)
a[1]["example"] = 1.
println(a)

'''
output is
[Dict("example" => 1.0), Dict("example" => 1.0), Dict("example" => 1.0)]

A: This is the expected behavior of fill and it's described in documentation.

If x is an object reference, all elements will refer to the same object

Use a Array comprehension
I suggest using array comprehension for this purpose.
julia> a = [Dict("example" => 0.) for _ in 1:3]
julia> a[1]["example"] = 1.
1.0
julia> println(a)
[Dict("example" => 1.0), Dict("example" => 0.0), Dict("example" => 0.0)]

Alternative map solution
If you really dislike list comprehensions you could use map to achieve the same solution by instantiating multiple instances of the same looking dictionary.
julia> b = map(x -> Dict("example" => 0.), 1:3)
3-element Vector{Dict{String, Float64}}:
 Dict("example" => 0.0)
 Dict("example" => 0.0)
 Dict("example" => 0.0)

julia> b[1]["example"] = 2.0
2.0

julia> println(b)
[Dict("example" => 2.0), Dict("example" => 0.0), Dict("example" => 0.0)]


text:
Q: Use multiple ORBs through different threads (multithreaded multi-orb client application) - how? This question is related to: Is it possible to have several ORB objects in the same process?
So, thanks to @BrianKelly I found information about the ORB identifier (even though there was no such information in all ORBACUS docs, that I have) and I successfully created a simple application, that connects to different CORBA servers and successfully executed several CORBA requests.
So far, so good.
Now, what I want to do, is to make this application multithreaded and to start a separate thread for the connection to the different servers. But ORB_init crashes.
Here's a very short code, that I use for testing:
#include <OB/CORBA.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* run( void * );

struct config { const char* nameservice; const char* id; const char* exe; };

const bool mt = true;

int main()
{
    config cfg1 = { "NameService=corbaloc::10.102.8.15:13069/NameService", "1", "test" };
    config cfg2 = { "NameService=corbaloc::192.168.1.99:13069/NameService", "2", "test" };

    if( mt )
    {
        pthread_t t1, t2;

        pthread_create( &t1, NULL, run, (void*)&cfg1 );
        pthread_create( &t2, NULL, run, (void*)&cfg2 );

        pthread_join( t1, NULL ); pthread_join( t2, NULL );
    }
    else
    {
        run( (void*)&cfg1 );
        run( (void*)&cfg2 );
    }

    printf( "SUCCESS!\n" );
    return 0;
}

void* run( void* arg )
{
    pthread_mutex_lock( &mutex );

    int argc = 2; char* argv[3];

    config* cfg = (config*)arg;
    argv[0] = (char*)cfg->exe;
    argv[1] = (char*)cfg->nameservice;
    argv[2] = NULL;

    CORBA::ORB_var m_varOrb = CORBA::ORB_init( argc, argv, cfg->id );

    pthread_mutex_unlock( &mutex );
    return NULL;
}

So, when mt is false, everything's fine, I can extend the code to create some server specific objects, to execute different requests, etc. But then mt is true, the second thread fails calling ORB_init. See the stack trace below.
I'm pretty sure that I'm missing something very simple and stupid, but what?
$ g++ -g3 -ggdb -Wall -Wshadow -march=i486
      -DUNIX -DLINUX -DPTHREADS -DMULTITHREAD -D_REENTRANT
      -I. -I/usr/local/include/OB/ -I/usr/local/include/JTC/
      -I/usr/include/OB/ -I/usr/include/JTC/ -L/usr/local/lib
      -lpthread -lm -lz -lrt -ldl -lOB -lJTC -lCosNaming
      test.cpp

Stacktrace:
#0  0x00566402 in __kernel_vsyscall ()
#1  0x0080dfd0 in raise () from /lib/i686/nosegneg/libc.so.6
#2  0x0080f9b1 in abort () from /lib/i686/nosegneg/libc.so.6
#3  0x03dc490b in ~RefCount
    (this=Could not find the frame base for "~RefCount".)
    at ../../include/OB/RefCount_Ts_Linux-x86-32.h:43
#4  0x03ef8965 in ORBInstance
    (this=Could not find the frame base for "ORBInstance".)
    at ORBInstance.cpp:276
#5  0x03f134fe in ORB_impl
    (this=Could not find the frame base for "ORB_impl".)
    at ORB_impl.cpp:281
#6  0x03f24740 in OBCORBA::ORB_init
    (ac=Could not find the frame base for
        "OBCORBA::ORB_init(int&, char**, OB::Properties*,
                           OB::Logger*, OB::Reactor*,
                           char const*, char const*)". )
    at ORB_init.cpp:994
#7  0x03f249d9 in CORBA::ORB_init
    (ac=Could not find the frame base for
         "CORBA::ORB_init(int&, char**, char const*, char const*)".)
    at ORB_init.cpp:1014
#8  0x0804895d in run (arg=0xbfe8b544) at test_server.cpp:45
#9  0x007334d2 in start_thread () from /lib/i686/nosegneg/libpthread.so.0
#10 0x008b848e in clone () from /lib/i686/nosegneg/libc.so.6

A: I found something like a workaround. Makes my code really ugly and not easy for support, but it's still something.
Here's what I did:

*

*add a mechanism (in my application), that will count the necessary threads, before starting them

*read, in advance, the configurations - I need to know the necessary parameters for the naming services (used in ORB_init)

*before starting any threads, a "manager" will execute just once ORB_init, but it will pass several times the -ORBInitRef parameter, with different values - one for each thread/connection

*after this is done, the threads are started, but instead of executing ORB_init, they directly execute resolve_initial_references and continue with the server specific things

Note: My example does not containt resolve_initial_references, because the crash is in ORB_init.

So, applying this "algorithm" for this "workaround" would look like:
#include <OB/CORBA.h>

void* run( void * );
CORBA::ORB_var varORB;

int main()
{
    /** The necessary configurations */
    //-------------------------------------v
    const char* nameservice1 = "NameService1=corbaloc::10.102.8.15:13069/NameService";
    const char* nameservice2 = "NameService2=corbaloc::192.168.1.99:13069/NameService";
    //-------------------------------------^

    /** INIT the ORB **/
    int argc = 5; char* argv[ 6 ];
    const char* initref = "-ORBInitRef";
    const char* exe = "test";

    argv[0] = (char*)exe;
    argv[1] = (char*)initref; argv[2] = (char*)nameservice1;
    argv[3] = (char*)initref; argv[4] = (char*)nameservice2;
    argv[5] = NULL;

    varORB = CORBA::ORB_init( argc, argv );

    pthread_t t1, t2;

    char ns_id1 = '1', ns_id2 = '2';
    pthread_create( &t1, NULL, run, (void*)&ns_id1 );
    pthread_create( &t2, NULL, run, (void*)&ns_id2 );

    pthread_join( t1, NULL ); pthread_join( t2, NULL );

    varORB->destroy();

    return 0;
}
void* run( void* arg )
{
    char nameservice[] = "NameServiceN";

    // set the right number of the nameservice
    nameservice[ 11 ] = *((char*)arg);

    varORB->resolve_initial_references( nameservice );

    // do some CORBA-specific stuff

    printf( "SUCCESS %c\n", *(char*)arg );
    return NULL;
}

NOTE
I still can't believe this is the only option. If you look at my code (in the question) carefully, you'll see, that:

*

*it IS possible to have multiple ORBs (see the case with mt == false)

*the call to ORB_init IS synchronized

*the ORB identifier IS implemented and it works fine (again with mt == false)

So, this is not actual answer to my question, it's kind of a workaround.
It doesn't make sense (at least to me) to be possible to create several ORBs in a single thread, but not in multiple threads.

A: The ORB will use different connections (and threads) to different servers every time - always. Receiving answers and incomming calls are also handled in different threads (if useful and/or needed).
I think you try try to solve things, that the ORB already has solved for you. It's a middleware, don't scare about threading and stuff. It's already done by CORBA experts.


text:
Q: Do operations on uniform variables get cached in GLSL? Let's say I have a very simple GLSL vertex shader:
uniform mat4 model;
uniform mat4 view;
uniform mat4 projection;

in vec3 position;
in vec3 color;

out vec3 vertexColor;

void main()
{
    mat4 mvp = projection * view * model;
    vertexColor = color;
    gl_Position = mvp * vec4(position, 1.0);
}

Is the variable mvp recalculated for every vertex, or is it precalculated and stored until the the uniform variables it depends on change?

A: Could a particular implementation cache that value? Sure. Will they?
I would not assume that they would. Such caching would be difficult to implement, since it requires evaluating such expressions before draw calls, based on uniform state, then uploading those expressions to the code.
If you have some state that is computed from multiple uniform values, and you believe that such computation would be a performance problem, you are the one who should compute it.


text:
Q: Directing non-www to www by NGINX did not work? I'm deploying a website with NGINX and Wordpress.
To redirect from non-www to www, I put some code to NGINX config:
if ($host = example.com) {
    return 301 https://www.$host$request_uri;
}

I checked with Curl:
curl http://example.com
Result:
HTTP/1.1 301 Moved Permanently
Server: nginx/1.14.0 (Ubuntu)
Date: Mon, 03 Jun 2019 16:19:28 GMT
Content-Type: text/html
Content-Length: 194
Connection: keep-alive
Location: https://www.example.com/

But browser address bar still shows: https://example.com/.
I have to change URL setting in Wordpress General from example.com to www.example.com, browser address bar will shows: https://www.example.com/ as what I expected.
So:
Why I have to redirect non-www to www in 2 places (in NGINX and Wordpress Setting)?


text:
Q: SentenceTransformer (SBERT): encode_multi_process(): difference between batch_size and chunk_size
*

*:param batch_size: Encode sentences with batch size

*:param chunk_size: Sentences are chunked and sent to the individual processes.

Assuming I have a few thousands sentences to encode on 4 CPU cores.
I believe I understand what batch_size means. A batch_size of 32 would mean that groups of 32 sentences would be sent together to be encoded (normal batch processing meaning for deep learning).
If I run 4 processes (4 CPU cores), batches of 32 sentences would be sent to each core to be encoded.
I don't see what "chunk_size" is for... or what it means in this context.
Thanks for any help, clarification, and your time...


text:
Q: How to select a file through a GUI in MATLAB I want to create a GUI such that an image file should get copied to the matlab workspace on clicking a button titled "selct image". It should prompt me to select a particular image from a given folder, then on clicking a button titled "Run", an m file (which I have written) should be run and display the output.
Can anyone help me in this regard?

A: Have a look at this:
http://www.mathworks.de/help/techdoc/ref/uigetfile.html
Creating GUIs in MATLAB is pretty straightforward. Type "guide" in the command line, graphically add your buttons, then fill the callback functions of those buttons with the code you need.

A: The entire answer might be a little long, but let`s try anyway
as previous posters recommended, use guide command to start designing a GUI.
Add some buttons. Right click on a button will provide you with a "button callback function", which is called whenever you press a button on a running GUI.
The important commands are:
BUTTON1: Read an image through a modal dialog in a GUI in Matlab
and put the image data into the variables X and map in base workspace
% --- Executes on button press in pushbutton1.
function pushbutton1_Callback(hObject, eventdata, handles)
disp('Load image button pressed ...')
%% Create a file dialog for images
[filename, user_cancelled] = imgetfile;
    if user_cancelled
            disp('User pressed cancel')
    else
            disp(['User selected ', filename])
    end

    %% Read the selected image into the variable
    disp('Reading the image into variable X');
    [X,map] = imread(filename);
    %% Copy X and map to base workspace, overwriting the content !!!
    assignin('base','X',X);
    assignin('base','map',map);
    %% Now you have X and map variables in the base workspace

BUTTON2: Run a custom command
do something on the X and map variables in the base workspace
% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)

%% Put your own code here to be called
disp('Run button pressed ...')
evalin('base', 'if exist(''X'', ''var''), disp(''image loaded into X''), else, disp(''image not loaded yet''), end');
% if exist('X', 'var'), disp('image loaded into X'), else, disp('image not loaded yet'), end)

Alternatively, you can create your own file dialogs in matlab:
%% Alternatively use the following for reading image files of your own choosing
[filename, pathname] = uigetfile({'*.jpg;*.png;*.gif;*.bmp', 'All Image Files (*.jpg, *.png, *.gif, *.bmp)'; ...
                '*.*',                   'All Files (*.*)'}, ...
                'Pick an image file');

%This code checks if the user pressed cancel on the dialog.
        if isequal(filename,0) || isequal(pathname,0)
             disp('User pressed cancel')
        else
             disp(['User selected ', fullfile(pathname, filename)])

        end

Here is the entire file working, just copy&paste:
    function varargout = guitutorial_export(varargin)
    % GUITUTORIAL_EXPORT M-file for guitutorial_export.fig
    %      GUITUTORIAL_EXPORT, by itself, creates a new GUITUTORIAL_EXPORT or raises the existing
    %      singleton*.
    %
    %      H = GUITUTORIAL_EXPORT returns the handle to a new GUITUTORIAL_EXPORT or the handle to
    %      the existing singleton*.
    %
    %      GUITUTORIAL_EXPORT('CALLBACK',hObject,eventData,handles,...) calls the local
    %      function named CALLBACK in GUITUTORIAL_EXPORT.M with the given input arguments.
    %
    %      GUITUTORIAL_EXPORT('Property','Value',...) creates a new GUITUTORIAL_EXPORT or raises the
    %      existing singleton*.  Starting from the left, property value pairs are
    %      applied to the GUI before guitutorial_export_OpeningFcn gets called.  An
    %      unrecognized property name or invalid value makes property application
    %      stop.  All inputs are passed to guitutorial_export_OpeningFcn via varargin.
    %
    %      *See GUI Options on GUIDE's Tools menu.  Choose "GUI allows only one
    %      instance to run (singleton)".
    %
    % See also: GUIDE, GUIDATA, GUIHANDLES

    % Edit the above text to modify the response to help guitutorial_export

    % Last Modified by GUIDE v2.5 01-Apr-2012 00:26:11

    % Begin initialization code - DO NOT EDIT
    gui_Singleton = 1;
    gui_State = struct('gui_Name',       mfilename, ...
                                         'gui_Singleton',  gui_Singleton, ...
                                         'gui_OpeningFcn', @guitutorial_export_OpeningFcn, ...
                                         'gui_OutputFcn',  @guitutorial_export_OutputFcn, ...
                                         'gui_LayoutFcn',  @guitutorial_export_LayoutFcn, ...
                                         'gui_Callback',   []);
    if nargin && ischar(varargin{1})
            gui_State.gui_Callback = str2func(varargin{1});
    end

    if nargout
            [varargout{1:nargout}] = gui_mainfcn(gui_State, varargin{:});
    else
            gui_mainfcn(gui_State, varargin{:});
    end
    % End initialization code - DO NOT EDIT

    % --- Executes just before guitutorial_export is made visible.
    function guitutorial_export_OpeningFcn(hObject, eventdata, handles, varargin)
    % This function has no output args, see OutputFcn.
    % hObject    handle to figure
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)
    % varargin   command line arguments to guitutorial_export (see VARARGIN)

    % Choose default command line output for guitutorial_export
    handles.output = hObject;

    % Update handles structure
    guidata(hObject, handles);

    % UIWAIT makes guitutorial_export wait for user response (see UIRESUME)
    % uiwait(handles.figure1);

    % --- Outputs from this function are returned to the command line.
    function varargout = guitutorial_export_OutputFcn(hObject, eventdata, handles)
    % varargout  cell array for returning output args (see VARARGOUT);
    % hObject    handle to figure
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)

    % Get default command line output from handles structure
    varargout{1} = handles.output;

    % --- Executes on button press in pushbutton1.
    function pushbutton1_Callback(hObject, eventdata, handles)
    % hObject    handle to pushbutton1 (see GCBO)
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)

    disp('Load image button pressed ...')

    %% Alternatively use the following for reading image files of your own choosing
    % [filename, pathname] = uigetfile({'*.jpg;*.png;*.gif;*.bmp', 'All Image Files (*.jpg, *.png, *.gif, *.bmp)'; ...
    %         '*.*',                   'All Files (*.*)'}, ...
    %         'Pick an image file');
    %
    % %This code checks if the user pressed cancel on the dialog.
    %     if isequal(filename,0) || isequal(pathname,0)
    %        disp('User pressed cancel')
    %     else
    %        disp(['User selected ', fullfile(pathname, filename)])
    %
    %       end

    [filename, user_cancelled] = imgetfile;
            if user_cancelled
                    disp('User pressed cancel')
            else
                    disp(['User selected ', filename])
            end

    %% Read the selected image into the variable
    disp('Reading the image into variable X');
    [X,map] = imread(filename);
    %% Copy X and map to base workspace, overwriting the content !!!
    assignin('base','X',X);
    assignin('base','map',map);
    %%

    % --- Executes on button press in pushbutton2.
    function pushbutton2_Callback(hObject, eventdata, handles)
    % hObject    handle to pushbutton2 (see GCBO)
    % eventdata  reserved - to be defined in a future version of MATLAB
    % handles    structure with handles and user data (see GUIDATA)

    %% Put your own code here to be called
    disp('Run button pressed ...')
    evalin('base', 'if exist(''X'', ''var''), disp(''image loaded into X''), else, disp(''image not loaded yet''), end');
    % if exist('X', 'var'), disp('image loaded into X'), else, disp('image not loaded yet'), end)

    % --- Creates and returns a handle to the GUI figure.
    function h1 = guitutorial_export_LayoutFcn(policy)
    % policy - create a new figure or use a singleton. 'new' or 'reuse'.

    persistent hsingleton;
    if strcmpi(policy, 'reuse') & ishandle(hsingleton)
            h1 = hsingleton;
            return;
    end

    appdata = [];
    appdata.GUIDEOptions = struct(...
            'active_h', [], ...
            'taginfo', struct(...
            'figure', 2, ...
            'pushbutton', 3), ...
            'override', 0, ...
            'release', 13, ...
            'resize', 'none', ...
            'accessibility', 'callback', ...
            'mfile', 1, ...
            'callbacks', 1, ...
            'singleton', 1, ...
            'syscolorfig', 1, ...
            'blocking', 0, ...
            'lastSavedFile', '/home/mosi/Documents/MATLAB/guitutorial_export.m', ...
            'lastFilename', '/home/mosi/Documents/MATLAB/guitutorial.fig');
    appdata.lastValidTag = 'figure1';
    appdata.GUIDELayoutEditor = [];
    appdata.initTags = struct(...
            'handle', [], ...
            'tag', 'figure1');

    h1 = figure(...
    'Units','characters',...
    'Color',[0.701960784313725 0.701960784313725 0.701960784313725],...
    'Colormap',[0 0 0.5625;0 0 0.625;0 0 0.6875;0 0 0.75;0 0 0.8125;0 0 0.875;0 0 0.9375;0 0 1;0 0.0625 1;0 0.125 1;0 0.1875 1;0 0.25 1;0 0.3125 1;0 0.375 1;0 0.4375 1;0 0.5 1;0 0.5625 1;0 0.625 1;0 0.6875 1;0 0.75 1;0 0.8125 1;0 0.875 1;0 0.9375 1;0 1 1;0.0625 1 1;0.125 1 0.9375;0.1875 1 0.875;0.25 1 0.8125;0.3125 1 0.75;0.375 1 0.6875;0.4375 1 0.625;0.5 1 0.5625;0.5625 1 0.5;0.625 1 0.4375;0.6875 1 0.375;0.75 1 0.3125;0.8125 1 0.25;0.875 1 0.1875;0.9375 1 0.125;1 1 0.0625;1 1 0;1 0.9375 0;1 0.875 0;1 0.8125 0;1 0.75 0;1 0.6875 0;1 0.625 0;1 0.5625 0;1 0.5 0;1 0.4375 0;1 0.375 0;1 0.3125 0;1 0.25 0;1 0.1875 0;1 0.125 0;1 0.0625 0;1 0 0;0.9375 0 0;0.875 0 0;0.8125 0 0;0.75 0 0;0.6875 0 0;0.625 0 0;0.5625 0 0],...
    'IntegerHandle','off',...
    'InvertHardcopy',get(0,'defaultfigureInvertHardcopy'),...
    'MenuBar','none',...
    'Name','guitutorial',...
    'NumberTitle','off',...
    'PaperPosition',get(0,'defaultfigurePaperPosition'),...
    'Position',[103.833333333333 29.1333333333333 112 32.3333333333333],...
    'Resize','off',...
    'HandleVisibility','callback',...
    'Tag','figure1',...
    'UserData',[],...
    'Visible','on',...
    'CreateFcn', {@local_CreateFcn, blanks(0), appdata} );

    appdata = [];
    appdata.lastValidTag = 'pushbutton1';

    h2 = uicontrol(...
    'Parent',h1,...
    'Units','characters',...
    'Callback',@(hObject,eventdata)guitutorial_export('pushbutton1_Callback',hObject,eventdata,guidata(hObject)),...
    'Position',[8.16666666666667 27.5333333333333 25.1666666666667 1.4],...
    'String','Select image',...
    'Tag','pushbutton1',...
    'CreateFcn', {@local_CreateFcn, blanks(0), appdata} );

    appdata = [];
    appdata.lastValidTag = 'pushbutton2';

    h3 = uicontrol(...
    'Parent',h1,...
    'Units','characters',...
    'Callback',@(hObject,eventdata)guitutorial_export('pushbutton2_Callback',hObject,eventdata,guidata(hObject)),...
    'Position',[8.16666666666667 24.8 11.6666666666667 1.4],...
    'String','Run',...
    'Tag','pushbutton2',...
    'CreateFcn', {@local_CreateFcn, blanks(0), appdata} );

    hsingleton = h1;

    % --- Set application data first then calling the CreateFcn.
    function local_CreateFcn(hObject, eventdata, createfcn, appdata)

    if ~isempty(appdata)
         names = fieldnames(appdata);
         for i=1:length(names)
                 name = char(names(i));
                 setappdata(hObject, name, getfield(appdata,name));
         end
    end

    if ~isempty(createfcn)
         if isa(createfcn,'function_handle')
                 createfcn(hObject, eventdata);
         else
                 eval(createfcn);
         end
    end

    % --- Handles default GUIDE GUI creation and callback dispatch
    function varargout = gui_mainfcn(gui_State, varargin)

    gui_StateFields =  {'gui_Name'
            'gui_Singleton'
            'gui_OpeningFcn'
            'gui_OutputFcn'
            'gui_LayoutFcn'
            'gui_Callback'};
    gui_Mfile = '';
    for i=1:length(gui_StateFields)
            if ~isfield(gui_State, gui_StateFields{i})
                    error('MATLAB:gui_mainfcn:FieldNotFound', 'Could not find field %s in the gui_State struct in GUI M-file %s', gui_StateFields{i}, gui_Mfile);
            elseif isequal(gui_StateFields{i}, 'gui_Name')
                    gui_Mfile = [gui_State.(gui_StateFields{i}), '.m'];
            end
    end

    numargin = length(varargin);

    if numargin == 0
            % GUITUTORIAL_EXPORT
            % create the GUI only if we are not in the process of loading it
            % already
            gui_Create = true;
    elseif local_isInvokeActiveXCallback(gui_State, varargin{:})
            % GUITUTORIAL_EXPORT(ACTIVEX,...)
            vin{1} = gui_State.gui_Name;
            vin{2} = [get(varargin{1}.Peer, 'Tag'), '_', varargin{end}];
            vin{3} = varargin{1};
            vin{4} = varargin{end-1};
            vin{5} = guidata(varargin{1}.Peer);
            feval(vin{:});
            return;
    elseif local_isInvokeHGCallback(gui_State, varargin{:})
            % GUITUTORIAL_EXPORT('CALLBACK',hObject,eventData,handles,...)
            gui_Create = false;
    else
            % GUITUTORIAL_EXPORT(...)
            % create the GUI and hand varargin to the openingfcn
            gui_Create = true;
    end

    if ~gui_Create
            % In design time, we need to mark all components possibly created in
            % the coming callback evaluation as non-serializable. This way, they
            % will not be brought into GUIDE and not be saved in the figure file
            % when running/saving the GUI from GUIDE.
            designEval = false;
            if (numargin>1 && ishghandle(varargin{2}))
                    fig = varargin{2};
                    while ~isempty(fig) && ~isa(handle(fig),'figure')
                            fig = get(fig,'parent');
                    end

                    designEval = isappdata(0,'CreatingGUIDEFigure') || isprop(fig,'__GUIDEFigure');
            end

            if designEval
                    beforeChildren = findall(fig);
            end

            % evaluate the callback now
            varargin{1} = gui_State.gui_Callback;
            if nargout
                    [varargout{1:nargout}] = feval(varargin{:});
            else
                    feval(varargin{:});
            end

            % Set serializable of objects created in the above callback to off in
            % design time. Need to check whether figure handle is still valid in
            % case the figure is deleted during the callback dispatching.
            if designEval && ishandle(fig)
                    set(setdiff(findall(fig),beforeChildren), 'Serializable','off');
            end
    else
            if gui_State.gui_Singleton
                    gui_SingletonOpt = 'reuse';
            else
                    gui_SingletonOpt = 'new';
            end

            % Check user passing 'visible' P/V pair first so that its value can be
            % used by oepnfig to prevent flickering
            gui_Visible = 'auto';
            gui_VisibleInput = '';
            for index=1:2:length(varargin)
                    if length(varargin) == index || ~ischar(varargin{index})
                            break;
                    end

                    % Recognize 'visible' P/V pair
                    len1 = min(length('visible'),length(varargin{index}));
                    len2 = min(length('off'),length(varargin{index+1}));
                    if ischar(varargin{index+1}) && strncmpi(varargin{index},'visible',len1) && len2 > 1
                            if strncmpi(varargin{index+1},'off',len2)
                                    gui_Visible = 'invisible';
                                    gui_VisibleInput = 'off';
                            elseif strncmpi(varargin{index+1},'on',len2)
                                    gui_Visible = 'visible';
                                    gui_VisibleInput = 'on';
                            end
                    end
            end

            % Open fig file with stored settings.  Note: This executes all component
            % specific CreateFunctions with an empty HANDLES structure.

            % Do feval on layout code in m-file if it exists
            gui_Exported = ~isempty(gui_State.gui_LayoutFcn);
            % this application data is used to indicate the running mode of a GUIDE
            % GUI to distinguish it from the design mode of the GUI in GUIDE. it is
            % only used by actxproxy at this time.
            setappdata(0,genvarname(['OpenGuiWhenRunning_', gui_State.gui_Name]),1);
            if gui_Exported
                    gui_hFigure = feval(gui_State.gui_LayoutFcn, gui_SingletonOpt);

                    % make figure invisible here so that the visibility of figure is
                    % consistent in OpeningFcn in the exported GUI case
                    if isempty(gui_VisibleInput)
                            gui_VisibleInput = get(gui_hFigure,'Visible');
                    end
                    set(gui_hFigure,'Visible','off')

                    % openfig (called by local_openfig below) does this for guis without
                    % the LayoutFcn. Be sure to do it here so guis show up on screen.
                    movegui(gui_hFigure,'onscreen');
            else
                    gui_hFigure = local_openfig(gui_State.gui_Name, gui_SingletonOpt, gui_Visible);
                    % If the figure has InGUIInitialization it was not completely created
                    % on the last pass.  Delete this handle and try again.
                    if isappdata(gui_hFigure, 'InGUIInitialization')
                            delete(gui_hFigure);
                            gui_hFigure = local_openfig(gui_State.gui_Name, gui_SingletonOpt, gui_Visible);
                    end
            end
            if isappdata(0, genvarname(['OpenGuiWhenRunning_', gui_State.gui_Name]))
                    rmappdata(0,genvarname(['OpenGuiWhenRunning_', gui_State.gui_Name]));
            end

            % Set flag to indicate starting GUI initialization
            setappdata(gui_hFigure,'InGUIInitialization',1);

            % Fetch GUIDE Application options
            gui_Options = getappdata(gui_hFigure,'GUIDEOptions');
            % Singleton setting in the GUI M-file takes priority if different
            gui_Options.singleton = gui_State.gui_Singleton;

            if ~isappdata(gui_hFigure,'GUIOnScreen')
                    % Adjust background color
                    if gui_Options.syscolorfig
                            set(gui_hFigure,'Color', get(0,'DefaultUicontrolBackgroundColor'));
                    end

                    % Generate HANDLES structure and store with GUIDATA. If there is
                    % user set GUI data already, keep that also.
                    data = guidata(gui_hFigure);
                    handles = guihandles(gui_hFigure);
                    if ~isempty(handles)
                            if isempty(data)
                                    data = handles;
                            else
                                    names = fieldnames(handles);
                                    for k=1:length(names)
                                            data.(char(names(k)))=handles.(char(names(k)));
                                    end
                            end
                    end
                    guidata(gui_hFigure, data);
            end

            % Apply input P/V pairs other than 'visible'
            for index=1:2:length(varargin)
                    if length(varargin) == index || ~ischar(varargin{index})
                            break;
                    end

                    len1 = min(length('visible'),length(varargin{index}));
                    if ~strncmpi(varargin{index},'visible',len1)
                            try set(gui_hFigure, varargin{index}, varargin{index+1}), catch break, end
                    end
            end

            % If handle visibility is set to 'callback', turn it on until finished
            % with OpeningFcn
            gui_HandleVisibility = get(gui_hFigure,'HandleVisibility');
            if strcmp(gui_HandleVisibility, 'callback')
                    set(gui_hFigure,'HandleVisibility', 'on');
            end

            feval(gui_State.gui_OpeningFcn, gui_hFigure, [], guidata(gui_hFigure), varargin{:});

            if isscalar(gui_hFigure) && ishandle(gui_hFigure)
                    % Handle the default callbacks of predefined toolbar tools in this
                    % GUI, if any
                    guidemfile('restoreToolbarToolPredefinedCallback',gui_hFigure);

                    % Update handle visibility
                    set(gui_hFigure,'HandleVisibility', gui_HandleVisibility);

                    % Call openfig again to pick up the saved visibility or apply the
                    % one passed in from the P/V pairs
                    if ~gui_Exported
                            gui_hFigure = local_openfig(gui_State.gui_Name, 'reuse',gui_Visible);
                    elseif ~isempty(gui_VisibleInput)
                            set(gui_hFigure,'Visible',gui_VisibleInput);
                    end
                    if strcmpi(get(gui_hFigure, 'Visible'), 'on')
                            figure(gui_hFigure);

                            if gui_Options.singleton
                                    setappdata(gui_hFigure,'GUIOnScreen', 1);
                            end
                    end

                    % Done with GUI initialization
                    if isappdata(gui_hFigure,'InGUIInitialization')
                            rmappdata(gui_hFigure,'InGUIInitialization');
                    end

                    % If handle visibility is set to 'callback', turn it on until
                    % finished with OutputFcn
                    gui_HandleVisibility = get(gui_hFigure,'HandleVisibility');
                    if strcmp(gui_HandleVisibility, 'callback')
                            set(gui_hFigure,'HandleVisibility', 'on');
                    end
                    gui_Handles = guidata(gui_hFigure);
            else
                    gui_Handles = [];
            end

            if nargout
                    [varargout{1:nargout}] = feval(gui_State.gui_OutputFcn, gui_hFigure, [], gui_Handles);
            else
                    feval(gui_State.gui_OutputFcn, gui_hFigure, [], gui_Handles);
            end

            if isscalar(gui_hFigure) && ishandle(gui_hFigure)
                    set(gui_hFigure,'HandleVisibility', gui_HandleVisibility);
            end
    end

    function gui_hFigure = local_openfig(name, singleton, visible)

    % openfig with three arguments was new from R13. Try to call that first, if
    % failed, try the old openfig.
    if nargin('openfig') == 2
            % OPENFIG did not accept 3rd input argument until R13,
            % toggle default figure visible to prevent the figure
            % from showing up too soon.
            gui_OldDefaultVisible = get(0,'defaultFigureVisible');
            set(0,'defaultFigureVisible','off');
            gui_hFigure = openfig(name, singleton);
            set(0,'defaultFigureVisible',gui_OldDefaultVisible);
    else
            gui_hFigure = openfig(name, singleton, visible);
    end

    function result = local_isInvokeActiveXCallback(gui_State, varargin)

    try
            result = ispc && iscom(varargin{1}) ...
                             && isequal(varargin{1},gcbo);
    catch
            result = false;
    end

    function result = local_isInvokeHGCallback(gui_State, varargin)

    try
            fhandle = functions(gui_State.gui_Callback);
            result = ~isempty(findstr(gui_State.gui_Name,fhandle.file)) || ...
                             (ischar(varargin{1}) ...
                             && isequal(ishandle(varargin{2}), 1) ...
                             && (~isempty(strfind(varargin{1},[get(varargin{2}, 'Tag'), '_'])) || ...
                                    ~isempty(strfind(varargin{1}, '_CreateFcn'))) );
    catch
            result = false;
    end

A: You should use the GUIDE function to get you started.
http://www.mathworks.com/help/techdoc/ref/guide.html
All of the features you have listed are available through this tool.  One of the most critical items in order to 'connect' you GUI features together is learn how to pass data between functions.  By default GUIDE has a function call back that contains a Matlab structure named "handles" (you can change this to whatever you want.  Try simply passing a few values between functions to get started.


text:
Q: On the Ekedahl-Barron $F$ conjecture Let $(X,F)$ a one-dimensional folication over a smooth variety $X$ over $\mathbb{Z}$ . Let $(X_p,F_p)$ the modulus $p$ reduction of $(X,F)$. We assume that $(X_p,F_p)$ is a foliation in positive characteristic, for almost every prime $p$. The Ekedahl- Barron $F$-conjecture says that with it hypothesis, the leaves of $(X,F)$ are algebraic curves.
Let $L$ be a very ample line bundle on $X$. Let $P$ a non-singular point of $(X,F)$. Let $C$ a leave of $(X,F)$ that contain $P$.
In https://drive.google.com/open?id=1_SNpE8FxC8BmO0n6sin8Ali8bKhtrL73 I have shown that if there existe a colection of $F_p$-invariant curves $C_p$ with genus $g_p$ for every prime $p$ then:
$$\chi(C,L)(n)\leq \limsup_{p \text{  prime}} (g_p+h^0(X,L))n$$
Were $\chi(C,L)(n)$ is the Hilbert- Samuel polynomial. It means that if $g_p$ is bounded for every $p$ then the leaves of $C$ are algebraic curves. It can prove it conjecture. My question is:
_ Is this inequality well known?.
_ There exist a way to bound the $g_p$'s?.
_ There exist more references about the Ekedahl-Barron $F$-Conjecture?.


text:
Q: Query rows that have same column value and return one result for each duplicate I am using this query to return duplicate email addresses in a table:
SELECT DISTINCT * FROM `customers`
WHERE email IN ( SELECT email FROM `customers` GROUP BY email HAVING COUNT(id) > 1)

Sample Output:
TonyLoden - tloden@outlook.com
TonyLoden - tloden@outlook.com
MikeH3llgarth - mike.hallgarth@gmail.com
MikeH3llgarth - mike.hallgarth@gmail.com

How can I modify the query to return only ONE result for each duplicate found?
Meaning, instead I would like it to return:
TonyLoden - tloden@outlook.com
MikeH3llgarth - mike.hallgarth@gmail.com


text:
Q: KDE Plasma5 widgets by default Configuration
Kubuntu 18.04
KDE PLasma5 as desktop environment
Problem
Is it possible to configure default plasma widgets for new user? So when I create new user on workstation it have preconfigured widgets by default. Or maybe is it possible to install/enable widget for user from CLI.

A: Take a look at
~/.config/plasma-org.kde.plasma.desktop-appletsrc

All widgets settings are stored there. You can create a new user, define what do you want, exit session and copy this file to /etc/skel (for new users) or copy it to ~/.config of existing users.
You can also create a complete theme for your users. You can see detailed instructions here: https://userbase.kde.org/Plasma/Create_a_Look_and_Feel_Package.


text:
Q: Error and unexpected behavior with TCP connection I am wanting my TCP server and client to "talk" to each other depending on what the other says. But when I run, it seems to go through one iteration, but then both the server and client seem to just "hang" there. Once I kill it on the client side, I end up getting a broken pipe error.
Can anyone interpret what I am doing wrong here?
SERVER code snippet:
while(feof(file_ptr) == 0)
{
    fscanf(file_ptr, "%s", supplies);
    printf("%s\n", supplies);

    //SEND supplies to all clients (currently just one client)

    n = write(newsockfd, supplies, strlen(supplies));

    if (n < 0)
    {
        error("ERROR writing to socket");
    }

    //Receive a request from client that they can use supply

    bzero(buffer,2);
    n = read(newsockfd,buffer,2);

    if (n < 0)
    {
        error("ERROR reading from socket");
    }

    printf("Who is using supply? %s\n", buffer);

    if(strcmp(buffer, "A"))
    {
        aRounds++;
    }

    while(done != 1)
    {
        //WAIT loop until message CO is received from client
        bzero(buffer,2);
        n = read(newsockfd,buffer,2);

        if (n < 0)
        {
            error("ERROR reading from socket");
        }

        printf("Done? %s\n", buffer);

        if(strcmp(buffer, "CO"))
        {
            done = 1;
        }
    }

    done = 0;
}

fclose(file_ptr);
n = write(newsockfd, "DN", 2);

CLIENT code snippet:
while(noSupplies != 1)
{
    //RECEIVE MSG from server about supplies
    bzero(buffer,2);
    n = read(sockfd,buffer,2);

    if (n < 0)
    {
        error("ERROR reading from socket");
    }

    printf("%s\n",buffer);

    if(strcmp(buffer, "BC") == 0 || strcmp(buffer, "CB") == 0)
    {
        //SEND server msg that you are using supply

        n = write(sockfd,"A", 1);
        if (n < 0)
        {
            error("ERROR writing to socket");
        }

        printf("Client A has received components %s during round %d.\n", buffer, round);

        n = write(sockfd,"CO", 2);
        if (n < 0)
        {
            error("ERROR writing to socket");
        }

    }
    else if(strcmp(buffer, "DN"))
    {
        noSupplies = 1;
    }

    round++;
}

I get the following from the server (before killing):
BC
Who is smoking? A
Done smoking? CO

And the following from the client (before killing):
BC
Client A has received components BC during round 1.

Then after killing from the client.. I get the following from the server:
BC
Who is using supply? A
Done? CO
Done?
CB
Who is using supply?
Done?
CB
Who is using supply?
Done?
BC
Broken pipe

Does anyone understand what I am doing wrong? (looking for code fix!)
Just an FYI.. I will be changing the server code eventually to handle listening to mulitple clients (TCP) but one hurdle at a time right? :S
Thanks!

A: Not sure if this is all of your problem, but
bzero(buffer, 2);
n = read(socket, buffer, 2);

...
printf("%s", buffer);

is not correct, since if the read actually did get 2 bytes and neither of them were 0 then buffer may not be a null terminated string (unless there is something earlier that made that so).
Several calls to strcmp should also always fail for the same reason -- the read in string is not 0 terminated so strcmp thinks that it keeps on going and therefore is not the same as the compared to string, even if the first letters are the same.
edit
 n = read(socket, buffer, 2);
 if (n<0) {
     die_horrible_death();
 }
 buffer[n] = 0; // since arrays are 0 indexed this should be after last read character
 printf("I just read: \"%s\"\n", buffer);

A: Your server code writes only once something to the client, at the beginning. Later, in the loop - it just reads.
OTOH your client reads and writes in the loop.
Since you're working with sockets in a blocking mode - this means that your client eventually will become blocked in a call to recv.
P.S.
No offenses - but you have a lot to learn.

*

*TCP is a tunnel. When your server sends 2 bytes of data in a single call to send/write - there's no guarantee your client will read this within a single call to recv.

*Hence - reading and parsing always must be done in a sort of a loop.

*You can't write a really robust client/server with ability to timeout/interrupt on demand using only blocking I/O.

*Learn, learn, learn


text:
Q: Logistic regression (GLM) output: apa.reg.table I have been working with logistic regression and would like to run out that reports
several models ("blocks") so I can compare them.
I found apa.reg.table which creates exactly the kind of output I would like to see, but, alas,
when I run glm models, I get error messages. No such error messages when I run a regression. I am especially interested in comparing these block models by the percentage change, which runs fine in a regular regression.
Questions:

*

*Is there any way I can run apa.reg.table with a logistic regression?

*If not, does anyone know of any packages or techniques that can be used to help me reach my objectives?

...In researching the problem, I ran the iris database:
data(iris)

...and then ran a series of four successive logistic regressions:
#Logistic regression models
MODEL_A<-glm(species~sepal.len, data=iris,, family=binomial())
MODEL_B<-glm(species~sepal.len+sepal.wid, data=iris, family=binomial())
MODEL_C<-glm(species~sepal.len+sepal.wid+petal.len, data=iris, family=binomial())
MODEL_D<-glm(species~sepal.len+sepal.wid+petal.len+petal.wid, data=iris, family=binomial())

apa.reg.table(MODEL_A,MODEL_B,MODEL_C,MODEL_D)

...but I receive the following error messages:
#Error in if (F.value < 0) stop("Your 'F.value' is not correctly specified.") :
# argument is of length zero
#In addition: Warning messages:
#1: Unknown or uninitialised column: 'r.squared'.
#2: Unknown or uninitialised column: 'p.value'.

...it runs fine in a regular regression analysis:
#regression models:
MODEL_B2<-lm(sepal.len~sepal.wid, data=iris)
MODEL_C2<-lm(sepal.len~sepal.wid+petal.len, data=iris)
MODEL_D2<-lm(sepal.len~sepal.wid+petal.len+petal.wid, data=iris)

#create table with regression models--no error messages:
apa.reg.table(MODEL_B2,MODEL_C2,MODEL_D2)

Any help would be greatly appreciated.

A: You can try using broom:
library(broom)

colnames(iris) =c("sepal.len","sepal.wid","petal.len","petal.wid","species")

MODEL_A<-glm(species~sepal.len, data=iris,, family=binomial())
MODEL_B<-glm(species~sepal.len+sepal.wid, data=iris, family=binomial())
MODEL_C<-glm(species~sepal.len+sepal.wid+petal.len, data=iris, family=binomial())
MODEL_D<-glm(species~sepal.len+sepal.wid+petal.len+petal.wid, data=iris, family=binomial())

You can have them in a list:
lapply(list(MODEL_A,MODEL_B,MODEL_C,MODEL_D),tidy)

Or:
library(dplyr)
library(purrr)

res = tibble(name=c("MODEL_A","MODEL_B","MODEL_C","MODEL_D"),
models=list(MODEL_A,MODEL_BMODEL_C,MODEL_D)) %>%
mutate(coef=map(models,tidy),stats=map(models,glance))

`
then:
res %>% unnest(coef)

res %>% unnest(stats)


text:
Q: Form Update Database Model Record's Relationship I want to know how to up date a model's relationship using a frontend form. I looked at the documents and found:

Alternatively you may set the relationship using the primary key, this
  is useful when working with HTML forms.

// Assign to author with ID of 3
$post->author = 3;

// Assign comments with IDs of 1, 2 and 3
$post->comments = [1, 2, 3];

$post->save();

the backend form to update the relationship works fine. This is my code and where I am getting ID as a value but it doesn't seem to affect the relationship field. Help would be great thanks!
    $project = new Projects();
    $project->name = Input::get('name');
    $project->price = Input::get('price');
    $project->work = Input::get('work');
    $project->client = Input::get('client');
    $project->slug = $slug;
    $project->save();
    Flash::success('Estimate Added!');
    return Redirect::refresh();

This is the Pivot Table:
public function up()
    {
        Schema::create('brandon_invoice_ip', function($table)
        {
            $table->engine = 'InnoDB';
            $table->integer('invoices_id');
            $table->integer('projects_id');
            $table->primary(['invoices_id','projects_id']);
        });
    }

    public function down()
    {
        Schema::dropIfExists('brandon_invoice_ip');
    }
}

Here is the model relationship:
public $hasOne = [
        'client' => 'Brandon\Invoice\Models\Clients'
    ];

This is the front end form: The values are correct according to their ID.

    Client

        <select class="uk-select" name="client">
          <option value="1">Brandon</option>
          <option value="2">Sanitary Ostomy System</option>
        </select>

Image of the relationship in the builder.

A: After you set the client using:
$project->client = Input::get('client');

You need to save the changes using:
$project->save();

Assuming your tables and models have been setup correctly, the above should work. If it does not, you need to post the structure of your tables and the rest of your code.

A: I think you need to add belongsTo relationship instead of hasOne
public $belongsTo = [
    'client' => 'Brandon\Invoice\Models\Clients'
];


text:
Q: Visual Studio Professional 2010 .csproj cannot be opened I am more In to Java, iOS, Linux. I did so little development with Microsoft products.
I am trying to run an existing project developed by another team on Microsoft visual studio.
The project is originality developed by Microsoft Visual Studio 2010
It is complaining that .csproj cannot be opened
I have noticed that so many ask this question in order to solve this based on the solution given, I try the following:

*

*run it on Microsoft Visual Studio 2012 premium

*run it on Microsoft Visual Studio 2010

*run it on Microsoft Visual Studio 2010 Professional

*installed service pack 1

*installed asp.net MVC 4

*re-applied service pack 1

*installed ASP.NET MVC 3 Tools Update

*installed webmatrix

Still the same problem.
I don't know why all this craps are needed to run one project. It looks for me intentional complication.
any one any other solution?
attached the beginning of the file as an image file.


text:
Q: Setup Android Studio SDK with Unity I have recently downloaded Android Studio with its SDK and set custom path for SDK download and its get completed.
My Android Studio correctly detected downloaded SDK and setup running fine with this.
But when I try to set path in Unity its not able to set, again and again same location related popup get opened.
Please see below image file:

Why path not get set that I don't know!! Upto now I used Android SDK with Eclipse so all things work good with me. But after upgrading to Android Studio I can't able to SDK path.
Please give me some help so I can able to export Android build.
Same problem running with Windows platform too.

A: You don't have Android SDK Tools in your folder.
Download Android SDK Tools and insert it in your sdk folder.


text:
Q: Java: Accessing original class of an item inside an array list Let's assume I have the following classes:
public class AnSuperClass { ... }

and
public class AnBetterClass extends AnSuperClass { ... }

Also I have the following ArrayList:
private final ArrayList<AnSuperClass> theList;

and I put some object of type AnBetterClass and AnSuperClass in it like so:
theList.add(new AnBetterClass());
theList.add(new AnSuperClass());

If I iterate over the list: how do I know which one of the two classes I have? The following query will always return false:
boolean foundOther = false;
for(AnSuperClass asc: theList)
    if(!(asc instanceof AnSuperClass))
        foundOther = true;
return foundOther;

Help desirable
P.S. Annotation do not work either.

A: You can use getClass() method
    ArrayList<AnSuperClass> theList = new ArrayList<>();
    theList.add(new AnBetterClass());
    theList.add(new AnSuperClass());
    for(AnSuperClass asc: theList)
        System.out.println(asc.getClass());

that prints out
class pck.AnBetterClass
class pck.AnSuperClass


text:
Q: Is there any physically relevant example of constructing series solution about infinity of an ordinary differential equation? I was reading about how to test if a given second order ordinary differential equation has singularity at infinity from Arfken and Weber. I understood the steps mathematically but I could not find its physical application. Can anybody please give an example (relevant in physics) of constructing a series solution in such a case about infinity, in particular if infinity is a regular singular point?
Second, what does it mean to develop a series solution about "infinity"? I guess infinity is not very well-defined and unique like other points on finite axis, like x=0. So how to make sense of such a series?

A: I will try to provide examples where a solutions of physical problems are expansions about $\infty$. They are not necessarily solutions to a second-order differential equation.

Mechanics:
Consider a cylinder of mass M, area A and length $L_0$. Situate it vertically on the ground,  (that is, one end touching the ground, the other end in the air). Suppose that the cylinder (like every solid object) has elasticity, that is, spring constant, equal to K. Now, if the cylinder is infinitely rigid, that is, if K is equal to infinity, the length of the cylinder will not change due to the gravitation, and will be equal to $L_0$. That is, gravity will not make it shrink, since K is infinity.
But what if the cylinder is rigid, but some elasticity (like every real solid)? Then we expect the length to become less than L, we expect it to shrink a bit. So, we seek a solution in the form: $L=L_0 - \frac{1}{k} f_1(M,g,A,L_0)$, where $f_1$ is the first-order correction in terms of $\frac{1}{K}$. You can continue to find the next corrections in powers of $\frac{1}{K}$.

Electrostatics: This time in electrostatics. You can certainly find the electric field above the center of a plane with uniform surface density $\sigma$. It is $\frac{\sigma}{  2 \epsilon}$. Now, suppose that instead of the infinite plane, which physically does not exist, we have a circular disk of radius $R$, ans we try to find the electric field on its axis, at distance $h$ from the center. You can easily calculate the result, which is $\frac{\sigma}{2\epsilon} \bigg[ 1-\frac{h}{h^2+R^2}\bigg]$. Since $R$ is large, you can Taylor-expand this in terms of $\frac{h}{R}$. The result is $\frac{\sigma}{  2 \epsilon} -\frac{\sigma}{  2 \epsilon} \frac{h}{R}+ \frac{\sigma}{  4  \epsilon} \frac{h^3}{R^3} + \ldots $. This is an expansion about $R=\infty$.

thermodynamics:  almost every occurrence of the term 'finite size effects' in thermodynamics, in phase transitions and in the field of complex networks would give you corrections (which are basically truncated expansions) in powers of the inverse of system size.

Finally, I think I can contrive an illustrative example of second order ordinary differential equations where there is a singularity at $\infty$. Suppose there is a block  long rectangular block  of mass M, on the ground, with no friction between the block and the ground. Suppose we place a mass $m$ on the block, with friction $\mu$ between the blocks. Suppose that $M$ is large, that is, $m \ll M$. Now we pull the upper mass with constant force $F$. Find the velocity of the block (not the upper mass) as a function of time. If you write down equations of motion, you will see that for $M=\infty$, there is a singularity, easily removable, and the speed (or position) of the block is zero for $M=\infty$, and the corrections are of order $\frac{1}{M}$.


text:
Q: How to pass username of the logged in user to the navbar I want my navbar to display the username of the logged user, so i tried this:
app.get('/*', function(req, res){
  if(req.isAuthenticated()){
    User.find({'username': req.user.username}, function(err, usuario){
     res.render("partials/header", {
       usuario: usuario,
     });
   });
  }else{
    res.redirect('/login')
  }
})

This piece of code is how i take the info from MongoDB and pass to the view (i'm using EJS)
But this redirects all the routes of my application to render the view of the navbar.
I pass the document of the MongoDB in the User.find() function, but i need to specify a route in the app.get() and if i specify a route, the username will only display in the navbar of said route.
I know it is redirecting the pages because of the '/*'.
HTML:

      <button class="navbar-toggler" id='botao-fechador2' type="button">

      </button>

              Cadastro

Produto

              Logística

Produtos

Entrada de Produtos

              Usuário

Novo Usuário

Usuários Ativos

<%= usuario[0].username %>

Is there a better way to do this? Or do i need to user User.find() in every route of my app.js to pass the user info to the view of the navbar?
(Sorry for any language mistakes)


text:
Q: Installing Ubuntu Studio aside Ubuntu 13.04 I was just wondering if I could install Ubuntu Studio without getting rid of Ubuntu 13.04? I'm not looking to dual boot, just want to see if its possible to install Studio on top of 13.04.
Thanks in advance

A: Ubuntu Studio, as it name describes, is a Ubuntu version but focused to the multimedia purposes. To do that task, it uses a Real Time (kind of Low Latency) Linux kernel.
The main differences between this kernel and the usual is that uses less time to response to a multimedia actions (in music is crucial to play and listen the sound that you are making in less than 10ms), but the overall performance is worse than the generic kernel (here an example: http://sevencapitalsins.wordpress.com/2007/08/10/low-latency-kernel-wtf)
Then, if you want Ubuntu and Ubuntu Studio, both in the same SO (you don't want dual boot), you can install one OS (Ubuntu for example) and install all the packages of the other flavour over it like this:
sudo apt-get update && sudo apt-get install ubuntustudio-desktop ubuntustudio-audio ubuntustudio-audio-plugins ubuntustudio-graphics ubuntustudio-video

From https://help.ubuntu.com/community/Ubuntu%20Studio%20Upgrade%20from%20Ubuntu
As a conclusion, you could have both operative systems installed as a one OS but you are able to work only with one kernel, the generic or the low-latency one (depending if you need performance or multimedia purposes), and you need to reboot when you want to change to the other (the same scene as if you have a dual boot system).

A: Probably you just want the applications and the settings that Ubuntu Studio comes with, and not the desktop.
In that case do:
sudo apt-get update && sudo apt-get install linux-lowlatency ubuntustudio-audio

If you want other than audio applications, just install those too. You can find all of them by doing:
apt-cache search ubuntustudio

Finally, you'll want to make sure the user is in audio group:
sudo usermod -a -G audio $USER

..and that audio group is handed realtime privilege. Make sure the file:
/etc/security/limits.d/audio.conf

is not named:
/etc/security/limits.d/audio.conf.disabled

If it is, rename it. Reboot, enjoy!


text:
Q: How can I discern which files in my public html folder are used by which domain? I inherited two websites on the same host server and several thousand files/directories that are not being used by those websites. I want to remove those files that are not used. I have tried using developer tools on Chrome and looking at the network tab to see what is served to a browser when navigating to those websites but there some files that are never passed to the client. Does anyone know a way to do this efficiently?

A: Keep a list of all the files that you have.
Now write a crawler that will crawl over both the websites and each file that is crawled over, remove it from the initial list.
The list of files that you have now are the ones that are not used by any of those websites.


text:
Q: Show that integrated track length in electromagnetic shower is proportional to $E_0$ I would like to show that the integrated track length in an electromagnetic shower is proportional to $E_0$. The energy spectrum of the shower is modeled by, $E(t)=\frac{E_0}{2^t}$, where $t$ refers to the time it takes for the particle to traverse a single radiation length, $x_0$. That is, the distance it travels before splitting into two secondaries. It is also known that the shower terminates at $E=E_c$.
The integrated track length should therefore simply be the radiation length, $x_0$ multiplied by the total number of particles traversing this length until $t_{max}=t_{c}$, where $t_{max}=\log_2(E_0/E_c)$. We therefore have that, $$T_{int}=x_0\int_0^{t_{max}}2^t\,dt=\frac{x_0}{\ln(2)}(\frac{E_0}{E_c}-1).$$
Evidently, this is not exactly proportional to $E_0$, differing by a constant, $-\frac{x_0}{\ln(2)}$. I feel as if there is something wrong with my bounds of integration, though I'm not exactly certain what. Any help would be appreciated.

A: Your approach is correct. Yes, we must sum over all track lengths. However, using an integral to achieve this merely gives an approximation. As per my comment above, daughter particles are only produced at discrete times, $t_0+n$, where $n$ is an integer, until, $t_0+n=t_{max}$. That is to say, we do not produce particles at $t_0+0.5=0.5$. In truth, therefore, we really should be taking a sum, not an integral.
Regardless, the integral still works well enough for our purposes. We have (as you have correctly stated), $$T_{int}=x_0\int_0^{t_{max}}2^t\,dt=\frac{x_0}{\ln(2)}(\frac{E_0}{E_c}-1).$$
Again, you are correct that the proportionality differs by a constant. However, consider what it means for $E_0$ to equal $E_c$, which is the termination energy. Simply, no shower will occur, for $E_0\approx E_c$, and so, we can argue that $1=\frac{E_c}{E_c}\ll \frac{E_0}{E_c}$, such that the $1$ is negligible, and that $$T_{int}=\frac{x_0}{E_c\cdot\ln(2)}E_0,$$
which is certainly proportional to $E_0$.


text:
Q: How PSExec runs application as SYSTEM user? I wondered how psexec.exe by sysinternals executes a process as a SYSTEM user.
I need to run a tool under a SYSTEM process, but I don't really know how to do that without registering it as a service.
Does anyone have an idea ?
p.s. I would really prefer to do it with WINAPI (C++). Thanks! :-)
Thanks!

A: psexec operates by creating a phantom, behind-the-scenes Windows service named "psexesvc" that is then removed after the operation completes.
Details are here: http://www.windowsecurity.com/articles/PsExec-Nasty-Things-It-Can-Do.html
Perhaps your tool could call psexec to run a process?


text:
Q: How can I group RadioButtons without a GroupBox in VB.NET? I want to group RadioButtons, but I don't want to use the visible control GroupBox. Is there something like the Java ButtonGroup in VB.NET?

A: Use the Panel control.

A: Check out the RadioButtonList
<asp:RadioButtonList id=RadioButtonList1 runat="server">
      <asp:ListItem>Item 1</asp:ListItem>
      <asp:ListItem>Item 2</asp:ListItem>
      <asp:ListItem>Item 3</asp:ListItem>
      <asp:ListItem>Item 4</asp:ListItem>
      <asp:ListItem>Item 5</asp:ListItem>
      <asp:ListItem>Item 6</asp:ListItem>
</asp:RadioButtonList>

Hope this helps.

A: I'm not sure if you could alter an asp:RadioButtonList Here


text:
Q: Oracle ODBC how to check default connection attributes I have an application that connect to Oracle DB using oracle-instantclient11.2-odbc-11.2.0.4.0-1 driver in unix.
The odbc.ini is setting only the below attributes;

*

*Driver

*DSN

*ServerName

*UserID

*Password

when I test connection failure with network drop to the remote db server while executing query, it takes 17 minutes for application to detect the network drop and exit executing the query.
Query timeout or connection timeout not specified for the application.
Where can I find the default settings values that sets the connection_timeout/lock_timeout for oracle odbc connection in unix.
I'm also unsure which default setting would be triggering the above behavior.


text:
Q: C++: Pass string literal or variable to function I have a function f that takes a string as input. I usually want to provide a string literal, e.g., f("hello"). However, I want to implement another function g that builds upon f:
std::string f(const std::string&& x) {
  return x + " world";
}

std::string g(const std::string&& x) {
  std::string res = f(x);  // problem: rvalue reference to std::string cannot bind to lvalue of type std::string
  res += "!";
  return res;
}

int main() {
  std::string res_a = f("hello");
  std::string res_b = g("world");
  return 0;
}

How can I achieve this in C++11/14 in a way that I can use f with string literals as well as variables?

A: A generic way of solving the problem of a function taking both l-value and r-value references is to use templated functions like so-
template <typename T>
T f(T&& val) {
}

template <typename T>
T g(T&& val) {
  T some_val = f(std::forward<T>(val));
}

std::foward<T>(val) forwards an l-value as an l-value and an r-value as an r-value, just as its name implies.
By templating the function, you ensure that this logic works for any type and not just strings.

A: The traditional way to take a read-only parameter is by const lvalue reference.
std::string f(const std::string& x)

This rule of thumb applies to many types, not just std::string. The primary exceptions are types that are not bigger than a pointer (e.g. a char).
It's rather unusual for a function to have a const rvalue reference. As you discovered, that adds difficulty when trying to pass a variable as the argument. A non-const rvalue reference has value, but a const rvalue reference is inferior to a const lvaue reference in most cases. See also Do rvalue references to const have any use?


text:
Q: No valid kits found in QT I am trying to create my first project using the QT.
Here is the problem I am getting into:

I am using Windows, so, the first solution from here does not apply to me.
What should I do to create a basic project in QT? It seems so painful to do that.
I think that the problem might is that I did not install QT itself, but just a QT creator. But when I try to install the latest version of QT from over here its size is more than 7Gb and when I come 30% over the installation it just closes and deletes the folder in which I try to install it.

A: A Qt kit is detected by Qt Creator by its respective qmake. You Qt Creator simply can't find a qmake. If you have installed Qt properly all you need to do it is to add the location of qmake to the PATH variable.
The size of the download (7GB) of Qt seems rather odd. If your installation has failed (according to your post it does when the installer hits 30%), needless to say you cannot expect to have a functioning Qt hence Qt Creator will also not be useful in this situation.


text:
Q: CoffeeScript Encapsulation and Variable Access Trying to understand how CoffeeScript instance and class variable works I came with this code (and the results are in the comments).
class A
  x: 1
  @y: 2

  constructor: (@z) ->
    #console.log "const x", x #ReferenceError: x is not defined
    console.log "constructor y", @y #undefined
    console.log "constructor z", @z # = 3 for A and 6 for B

  get: () ->
    #console.log "get x", x #ReferenceError: x is not defined
    console.log "get y", @y #undefined
    console.log "get z", @z # = 3 for A and 6 for B

  get2: () =>
    #console.log "get2 x", x #ReferenceError: x is not defined
    console.log "get2 y", @y #undefined
    console.log "get2 z", @z # = 3 for A and 6 for B

  @get3: () ->
    #console.log "get3 x", x #ReferenceError: x is not defined
    console.log "get3 y", @y # = 2
    console.log "get3 z", @z #undefined

  @get4: () =>
    #console.log "get4 x", x #ReferenceError: x is not defined
    console.log "get4 y", @y # = 2
    console.log "get4 z", @z #undefined

class B extends A
  constructor: (@w) ->
    super(@w)

console.log '------A------'
i = new A 3
console.log "i.x", i.x # = 1
console.log "i.y", i.y #undefined
console.log "i.z", i.z # = 6
i.get()
i.get2()
A.get3()
A.get4()
console.log '------B------'
i = new B 6
console.log "i.x", i.x # = 1
console.log "i.y", i.y #undefined
console.log "i.z", i.z # = 6
console.log "i.w", i.w # = 6
i.get()
i.get2()
B.get3()
B.get4()
console.log '------------'

There are some strange things happening here:

*

*x var
I was expecting to access it from any method but x var can't be accessed from any method or constructor (ReferenceError). I'm only able to access it from a instance of A or B (i.x). Why is that?

*@y var
I was expecting to get @y var value from any method but it has no value in most of places (undefined value, not a ReferenceError exception). @y has value only on @get3 and @get4 (instance methods?). If it is defined, why I can't get its value?

*@y and @z var
Both @y and @z are instance variables, but because @z was initialized in the constructor, it has a differentiated behavior. @y is valid on @get3 and @get4 and @z is valid on get and get2. Again, what is happening here?
The thing is that I'm really confused by these behaviors. Is this code correct? So, should I learn more about JS generated by CS?
Tks

A: To respond to your questions:

*

*x = 1 within the class body would create a variable named x within the scope body. But x: 1 within the class body defines a property x on the prototype. If you change console.log x to console.log @x, then you'll get 1.

*Within the class body, @ points to the class itself. Within the constructor (and in methods called as instance.method), it points to the particular instance. Change console.log @y to console.log A.y, and you'll get 2. (You can also use @constructor to get a reference to the class from the instance, because in JavaScript, the class actually is the constructor function.)

*Since @ in the constructor points to the instance, you're setting the instance's z property to the given value.

And yes, I do recommend understanding the underlying JavaScript—I know it's a bit odd for @ to have so many different meanings, but it makes a lot of sense once you understand JavaScript's this (one of the trickier parts of the language, to be sure). Incidentally, my book has a lot more info on this.

A: In function bodies, @ refers to this and in class definitions, @ refers to the class itself rather than the prototype.
So in the example above, the definition of @y refers to A.y, and not A.prototype.y. It's tricky to refer to it because of the way this is bound in the various ways of defining methods. You can access it using @y from methods named @get because in this case this always refers to A.
The definition of x refers to A.prototype.x and so from your get methods you should access it via @x in get1 and get2.
As a basic guide, try not to use @ outside of function bodies and everything will make a lot more sense:
class A
  constructor: (@a) ->
  b: 2
  tryStuff: =>
    console.log(@a) #will log whatever you initialized in the constructor
    console.log(@b) #will log 2

EDIT: you could consider methods defined as @something to be static methods of that class, so you can call them with classname.something() but as static methods, they can't access any instance variables.


text:
Q: Why did the matter in the early universe not stick together due to gravity? (Feel free to correct any mistaken assumptions I have)
The overall question I have is: given that the early universe started as an incredibly dense ball of matter and energy, why didn't that mass stick together in one huge "blob" due to gravity instead of becoming, as it is, "homogeneous and isotropic"?
One explanation I can think of is that the universe is constantly expanding. But if the expansion rate in the early universe was sufficient to tear apart this hugely dense ball of matter which must have been undergoing massive gravity, and the expansion rate is constantly increasing, why doesn't that same expansion force continue to tear apart stars and planets today?
Another possible factor is that heat in the early universe must have also been large, and heat tends to push atoms apart (not sure if this is true of subatomic particles). If this is the fundamental reason, we would expect to see an equilibrium reached between the expansionary force of heat, and the contractionary force of gravity, and (I reason), the universe would be composed of one big "galaxy" instead of, as it is, many galaxies quite separated from each other.
So what is the explanation for the current structure of the universe? Thanks.

A: Atoms themselves didn't form until well after the Big Bang. The Big Bang Nucleosynthesis (BBN) is when most nuclei formed and that happened somewhere between 10 seconds and 20 minutes after the Big Bang (that's a long time relative to how quickly everything was happening back then). That would be when ions formed, neutral atoms didn't make an appearance until a few hundred thousand years later. Matter and other things with mass didn't form until after inflation ended. By that time, the universe had expanded so much that only the smallest regions of it were able to see and interact with each other. Because it expanded so rapidly, the range over which gravity could act was extremely small. When BBN started, at around 10 seconds, gravity could only influence things that were about as far away as 10 times the distance to the Moon. If Earth was around back then, it wouldn't even know of the Sun's existence, much less feel a gravitational pull towards it. By the time BBN ended, gravity's range would be enough to allow all the planets out to Mars to orbit the Sun. At this point, the universe was still expanding very fast as well.
So the reason why matter was able to avoid being all in one enormous clump is that it simply didn't feel the gravitational pull of other matter until it was too late to form a clump.
To be fair, even if all matter felt the pull of all other matter right from the beginning, the matter in the universe was distributed fairly homogeneously. This means there wouldn't be a net pull in any direction. There were inhomogeneities; perturbations in the density of matter. These would naturally tend to fall together with the smaller scale over-densities clumping first.
In reality, because of how fast the universe was expanding and how long it took for gravity to extend its influence over neighbouring regions, what we see is a combination of what I described above. The limited range of gravity and the rapid expansion prevented matter from any extensive falling together in very early times. As expansion slowed and gravity's reach extended outwards, we observe that matter formed structures; first on the smallest scales and later on larger scales. These structures were seeded by the over-densities.

A: First, the early universe was incredibly hot. Second, Gravity is the weakest force. Third, when we talk about the early universe, we analyse things up to the point that gravity is not important. Why? Because we don't have a quantum theory of gravity. Forth, you need to think of the early universe as an infinite dense soup of particles. It is homogenous and it would not clump in one point to form one galaxy. The reason galaxies form is because there were fluctuations in this homogeneity.
On a side note, I would personally worry that the electric force between the charges is much stronger than gravity, hence they would annihilate and we would only have radiation today!

A: The error is to imagine that the incredibly dense ball of matter was located in a larger universe.  At that era, the incredibly dense ball filled the whole universe.  It was, to a good approximation, already homogeneous and isotropic.  If you believe in inflation, it made things even more so, but it wasn't a small blob in a large universe.


text:
Q: Ordinal scale's rangeRoundBands() I'm building a bar chart that will have a varied number of data points. All the examples I've seen use an ordinal scale for the x axis, then call rangeRoundBands() to get the width for the bars.
I'm getting the error "Uncaught TypeError: Cannot read property '1' of undefined" when I try to called .rangeRoundBands() and as far as I can tell I'm setting the scale up properly.
http://jsfiddle.net/rLzbbec0/1/
var globOb = {
bar: {
    height: 390,
    width: 675,
    innerHeight: 300,
    innerWidth: 615,
    margin: {
        bottom: 70,
        left: 40,
        right: 20,
        top: 20
    }
},
barData: [
    { task: "meetingsTask", val: 2.5    },
    { task: "reportsTask", val: 3 },
    { task: "emailsTask", val: 2 },
    { task: "planningTask", val: 1.5 },
    { task: "clientsTask", val: 4 },
    { task: "dataAnalysisTask", val: 3 }
]};

//Set X Scale
var xScale = d3.scale.ordinal()
    .rangeRoundBands([0, globOb.bar.innerWidth], .05, .1);

xScale.domain(globOb.barData.map(function(d) {
    return d.task
}));

//Set Y Scale
var yScale = d3.scale.linear()
    .domain([0, d3.max(globOb.barData, function(d) {
        return d.val + 1
    })])
    .range([globOb.bar.innerHeight, 0]);

//Grab SVG and set dimensions
var svg = d3.select("#viewport").append("svg")
    .attr("width", globOb.bar.width)
    .attr("height", globOb.bar.height);

//Set the drawing area of the SVG
var inner = svg.append("g")
    .attr("transform", "translate(" + globOb.bar.margin.left + "," +
        globOb.bar.margin.top + ")")
    .attr("width", globOb.bar.innerWidth)
    .attr("height", globOb.bar.innerHeight);

//Setup Axes
var xAxis = d3.svg.axis()
    .scale(xScale)
    .innerTickSize(0)
    .outerTickSize(-globOb.bar.innerHeight)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(yScale)
    .innerTickSize(-globOb.bar.innerWidth)
    .outerTickSize(-globOb.bar.innerWidth)
    .orient("left");

//Add X Axis
inner.append("g")
    .attr("class", "axis")
    .attr("transform", "translate(0," + (globOb.bar.innerHeight) + ")")
    .call(xAxis);

//Add Y axis
inner.append("g")
    .attr("class", "axis")
    .attr("transform", "translate(0,0)")
    .call(yAxis);

//draw data
inner.selectAll("bar")
    .data(globOb.barData)
    .enter()
    .append("rect")
    .attr("class", function(d) {
        return d.task.substring(0, d.task.length - 4) + "-bar"
    })
    .attr("x", function(d) {
        return xScale(d.task)
    })
    .attr("width", 50) //xScale.rangeRoundBands())
    .attr("y", function(d) {
        return yScale(d.val)
    })
    .attr("height", function(d) {
        return globOb.bar.innerHeight - yScale(d.val)
    });

console.log(xScale.rangeRoundBands());

In the fiddle I have changed the call of rangeRoundBands() to a set number to show the chart otherwise draws fine.  At the end I'm using console.log() to show the error with .rangeRoundBands().

A: ordinal.rangeRoundBands is a configuration setter, and you cannot call it without arguments, so it generates an error while trying to access the second item x[1] (indexed from zero) in the first argument x. You can take a look at the source.
You probably want to use ordinal.rangeBand() instead, which:

Returns the band width. When the scale's range is configured with rangeBands or rangeRoundBands, the scale returns the lower value for the given input. The upper value can then be computed by offsetting by the band width. If the scale's range is set using range or rangePoints, the band width is zero.


text:
Q: VBA - Formula does not appear in cell I want to write a formula using vba and pass a string to that argument.
Now I've got this:
ActiveCell.Offset(2, 2).Formula = "=INDIRECT(""'"" &$A$7& ""'!"" &ADDRESS(4;MATCH($A$8;Status!$A$1:$Q$1;0)))"

But nothing appears in that cell.
Can you give me some help?
Thanks!

A: You can either write your formula using English format, as mentioned in comments by pnuts and vacip, or use Range.FormulaLocal instead of Range.Formula to write it in your locale, but it might cause problems if you open the workbook on another computer with different locale.


text:
Q: my php code doesn't validate data with mysql I hav a Php code. It connects with the server and database, but it does not validate my form data with mysql database table. I hav same exact code which executes, but the following does not execute.........
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
session_start();
include_once 'dbconnect.php';

if(isset($_SESSION['user'])!="")
{
    header("Location: welcome.html");
}

if(isset($_POST['Submit']))
{
    $name = $_POST['loginName'];
    $upass = $_POST['loginPass'];
    $res=mysql_query("SELECT * FROM authen WHERE name='$name'");
    $row=mysql_fetch_array($res);

    if($row['passwrd']==$upass)
    {
        $_SESSION['user'] = $row['user_id'];
        header("Location: welcome.html");
    }
    else
    {
        ?>

        <?php
    }

}
?>

        <meta charset="utf-8" />
        <link rel="stylesheet" href="assets/css/styles.css" />
        <link rel="stylesheet" href="assets/css/jquery.fancybox.css" />

            <form id="login" method="post">

Login Form

                <input type="text" name="loginName" id="loginName" placeholder="User Name" required />
                <input type="password" name="loginPass" id="loginPass" placeholder="password" required  />
                <input type="submit" name="Submit" id="sub" value="Login" />
            </form>

I hav modified the code as directed but still i get the same response, i.e nothing happens
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<?php
session_start();
include_once 'dbconnect.php';

if(isset($_SESSION['user']) && $_SESSION['user'] != "")
{
    header("Location: welcome.html");
}

if(isset($_POST['Submit']))
{
    $name = mysql_real_escape_string($_POST['loginName']);
    $upass = mysql_real_escape_string($_POST['loginPass']);
    $res=mysql_query("SELECT * FROM authen WHERE name='$name'");
    $row=mysql_fetch_array($res);

    if($row['passwrd']==md5($upass))
    {
        $_SESSION['user'] = $row['user_id'];
        header("Location: welcome.html");
    }
    else
    {
        ?>

        <?php
    }

}
?>

        <meta charset="utf-8" />
        <link rel="stylesheet" href="assets/css/styles.css" />
        <link rel="stylesheet" href="assets/css/jquery.fancybox.css" />

            <form id="login" method="post">

Login Form

                <input type="text" name="loginName" id="loginName" placeholder="User Name" required />
                <input type="password" name="loginPass" id="loginPass" placeholder="password" required  />
                <input type="submit" name="Submit" id="sub" value="Login" />
            </form>

A: isset returns boolean
your code should be
if(isset($_SESSION['user']) && $_SESSION['user'] != "")
{
    header("Location: welcome.html");
    exit;
}

Or
if(!empty($_SESSION['user']))
{
    header("Location: welcome.html");
    exit;
}

A: Do following changes in your first code
if(isset($_SESSION['user']) && !empty($_SESSION['user']))
{
header("Location: welcome.html");
}

hope this helps!!,please comment for further queries


text:
Q: Setting $scope variables AngularJS So i am having an issue with adding a variable to the $scope after an event.
Here is the HTML for the select box. Basically when it is changed i need the scope to change.
Index.html
<select ng-controller="ClientCtrl" ng-model="name"
ng-options="v.name for (k, v) in client" ng-change="selectChange(name)">
</select>

{{cName}}

Age: {{cAge}}

Notes: {{cNotes}}

Controller.js
$scope.selectChange = function(name){
    $scope.cName = name.name;
    $scope.cAge = name.age;
    $scope.cNotes = name.notes;
  };

I have tried a few things to get those variable set. Obviously this one above, then this one:
$scope.selectChange = function(name){
        $scope.cName = name.name;
        $scope.cAge = name.age;
        $scope.cNotes = name.notes;
        $scope.$apply();
  };

I still don't quite understand apply but i thought i'd give it a try. Any help would be awesome, just need a pointer to wrap my head around why this wouldnt work.
I can get the variables to post to the console.log(cName); but it won't show up when i have the {{cName}}

A: Without more info its hard to debug completely, but from what i can see i would recommend wrapping the entire piece of html in the controller ClientCtrl or else the h2 and p tags wont have access to the scope that it creates.

  <select ng-model="name" ng-options="v.name for (k, v) in client" ng-change="selectChange(name)">
  </select>

{{cName}}

Age: {{cAge}}

Notes: {{cNotes}}

Hope this helps otherwise post more info or use a plunker...

A: You actually dont have to pass in the name in the ng-change event, since you actually already have that in the scope. The changeEvent can the use $scope.name directly instead of passing it as a parameter.
ng-change="selectChange()"

js
$scope.selectChange = function(){
    $scope.cName = $scope.name.name;
    and so on.
};

id suggest you give it a better name than name, i guess were talking about a person, so it would be easier to read if you call it Person.Name and so on;)
You also need to wrap your print within the same controller as you now have name in, to make it work, since the scope gets created for the controller.


text:
Q: How to get a Binding content in Xamarin this is my code:
public ChatItemCell()
    {
        TextAlignment Ausrichtung = TextAlignment.Start;

        var lblBody = new Label()
        {
            FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Label)),
            HorizontalTextAlignment = Ausrichtung,
            TextColor = Color.Black
        };
        lblBody.SetBinding(Label.TextProperty, "Body");

        var lblSender = new Label()
        {
            FontSize = Device.GetNamedSize(NamedSize.Small, typeof(Label)),
            HorizontalTextAlignment = Ausrichtung,
            TextColor = Color.Gray,
            FontAttributes = FontAttributes.Italic
        };
        lblSender.SetBinding(Label.TextProperty, "Sender");

        var layout = new StackLayout()
        {
            Opacity = 90,
            Orientation = StackOrientation.Vertical,
            Children = {lblSender, lblBody}
        };

        Frame outerFrame = new Frame()
        {
            Padding = new Thickness(5, 5, 5, 5),
            OutlineColor = Color.Accent,
            BackgroundColor = Color.Yellow,
            Content = layout,
        };

        Frame objFrame_Outer = new Frame
        {
            Padding = new Thickness(10, 0, 10, 10),
            Content = outerFrame
        };

        View = objFrame_Outer;

    }

What I want is, that the TextAligment depends on the "Sender". Means: When the Sender is "me" the aligment should be left, otherwise it should be right. So how do I get the content of "Sender"?
Thanks a lot!
Kriz

A: You can bind the TextAlignment property of the label to the Sender property, and write a ValueConverter that returns the correct TextAlignment for the value of Sender:
public class TextAlignmentConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var s = value as string;
        if (s == null) return TextAlignment.End;
        if (s.ToLower() == "me")
            return TextAlignment.Start;
        return TextAlignment.End;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}