text:
Q: gwt widget - mutually-exclusive toggle button I want a hybrid of a ToggleButton and RadioButton.
I want the "mutually-exclusive" part of RadioButton, and the gui look and behavior of ToggleButton(up and down states).
Does one already exist?

A: I've  adapted kirushik's solution and created a simple "ToggleButtonPanel" widget that takes an arbitrary number of ToggleButtons (and possibly any other widgets you'd like to add) and a panel of your choosing (defaults to VerticalPanel) and makes the buttons mutually exclusive.
What's nice about this is that the panel itself fires ClickEvents when the buttons are clicked. This way, you can add a single ClickHandler to the ToggleGroupPanel and then determine which button was clicked using event.getSource()
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.HasClickHandlers;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HasWidgets;
import com.google.gwt.user.client.ui.Panel;
import com.google.gwt.user.client.ui.ToggleButton;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;

public class ToggleButtonPanel extends Composite implements HasWidgets, HasClickHandlers{

    public ToggleButtonPanel() {
        this(new VerticalPanel());
    }

    public ToggleButtonPanel(Panel panel){
        this.panel = panel;
        initWidget(panel);
    }

    @Override
    public void add(Widget w) {
        if(w instanceof ToggleButton){
            ToggleButton button = (ToggleButton) w;
            button.addClickHandler(handler);
        }
        panel.add(w);
    }

    @Override
    public void clear() {
        panel.clear();
    }

    @Override
    public Iterator<Widget> iterator() {
        return panel.iterator();
    }

    @Override
    public boolean remove(Widget w) {
        return panel.remove(w);
    }

    @Override
    public void setWidth(String width) {
        panel.setWidth(width);
    };

    @Override
    public void setHeight(String height) {
        panel.setHeight(height);
    }

    private final Panel panel;
    private ClickHandler handler = new ClickHandler(){
        @Override
        public void onClick(ClickEvent event) {
            Iterator<Widget> itr = panel.iterator();
            while(itr.hasNext()){
                Widget w = itr.next();
                if(w instanceof ToggleButton){
                    ToggleButton button = (ToggleButton) w;
                    button.setDown(false);
                    if(event.getSource().equals(button)) {
                        button.setDown(true);
                    }
                }
            }

            for(ClickHandler h : handlers){
                h.onClick(event);
            }
        }
    };

    private List<ClickHandler> handlers = new ArrayList<ClickHandler>();
    @Override
    public HandlerRegistration addClickHandler(final ClickHandler handler) {
        handlers.add(handler);
        return new HandlerRegistration() {

            @Override
            public void removeHandler() {
                handlers.remove(handler);
            }
        };
    }

}

A: Here is my pure-gwt variant:
class ThreeStateMachine extends FlowPanel{
        // This is the main part - it will unset all the buttons in parent widget
        // and then set only clicked one.
        // One mutual handler works faster and is generally better for code reuse
        private final ClickHandler toggleToThis = new ClickHandler() {
                @Override
                public void onClick(ClickEvent clickEvent) {
                    for(Widget b: ThreeStateMachine.this.getChildren()){
                        ((ToggleButton)b).setDown(false);
                    }
                    ((ToggleButton)clickEvent.getSource()).setDown(true);
                }
            };

        private ThreeStateMachine() { // Create out widget and populat it with buttons
            super();

            ToggleButton b = new ToggleButton("one");
            b.setDown(true);
            b.addClickHandler(toggleToThis);
            this.add(b);

            b = new ToggleButton("two");
            b.addClickHandler(toggleToThis);
            this.add(b);

            b = new ToggleButton("three");
            b.addClickHandler(toggleToThis);
            this.add(b);
        }
    }

Surely, one'll need css styles for gwt-ToggleButton with variants (-up-hovering etc.)

A: I have something that is both not in an extension library, and not dependent on a panel like the other answers. Define this class which manages the buttons. We're adding a new click listener to the buttons, which is in addition to whatever click handler you attached in the "GUI Content" class. I can't copy and paste this in, so hopefully it's syntatically correct.
    public class MutuallyExclusiveToggleButtonCollection {

      List<ToggleButton> m_toggleButtons = new ArrayList<ToggleButton>();

       public void add(ToggleButton button) {
          m_toggleButtons.add(button);
          button.addClickListener(new ExclusiveButtonClickHandler());
     }

    private class ExclusiveButtonClickHandler impelments ClickHandler {
       public void onClick(ClickEvent event) {
          for(ToggleButton button : m_toggleButtons) {
            boolean isSource = event.getSource().equals(button);
            button.setIsDown(isSource);
       }

   }

  }

A: Came across the same need, heres another solution that does away with the separate handler and works nicely in UIBinder with a declaration like:
<my:RadioToggleButton buttonGroup="btnGroup" text="Button 1" />

Here's the extended class:
import java.util.HashMap;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.uibinder.client.UiConstructor;
import com.google.gwt.user.client.ui.ToggleButton;

public class RadioToggleButton extends ToggleButton
{
    private static HashMap<String,ButtonGroup> buttonGroups = new HashMap<>();
    private ButtonGroup buttonGroup;

    public @UiConstructor RadioToggleButton( String buttonGroupName )
    {
        buttonGroup = buttonGroups.get( buttonGroupName );
        if( buttonGroup == null ){
            buttonGroups.put( buttonGroupName, buttonGroup = new ButtonGroup() );
        }
        buttonGroup.addButton( this );
    }

    @Override
    public void setDown( boolean isDown )
    {
        if( isDown ){
            RadioToggleButton btn = buttonGroup.pressedBtn;
            if( btn != null ){
                btn.setDown( false );
            }
            buttonGroup.pressedBtn = this;
        }
        super.setDown( isDown );
    }

    private class ButtonGroup implements ClickHandler
    {
        RadioToggleButton pressedBtn = null;

        public void addButton( ToggleButton button )
        {
            button.addClickHandler( this );
        }

        @Override
        public void onClick( ClickEvent event )
        {
            Object obj = event.getSource();
            if( pressedBtn != null ){
                pressedBtn.setDown( false );
            }
            pressedBtn = (RadioToggleButton)obj;
            pressedBtn.setDown( true );
        }
    }
}

A: gwt-ext toggleButtons
"This example illustrates Toggle Buttons. When clicked, such Buttons toggle their 'pressed' state.
The Bold, Italic and Underline toggle Buttons operate independently with respect to their toggle state while the text alignment icon Buttons belong to the same toggle group and so when one of them is click, the previously pressed Button returns to its normal state."

A: Register an additional ClickHandler on all the ToggleButtons.
For example, ToggleButtons home, tree, summary, detail.
 public class Abc extends Composite implements ClickHandler {
        ToggleButton home, tree, summary, detail
        public Abc() {
            // all your UiBinder initializations... blah, blah....
            home.addClickHandler(this);
            tree.addClickHandler(this);
            summary.addClickHandler(this);
            detail.addClickHandler(this);
        }
        @Override
        public void onClick(ClickEvent p_event) {
            Object v_source = p_event.getSource();
            home.setDown(home==v_source);
            tree.setDown(tree==v_source);
            summary.setDown(summary==v_source);
            detail.setDown(detail==v_source);
        }
}

Of course, you just need to add all the other boilerplate code and register additional ClickHandlers for each ToggleButton.


text:
Q: on tab switch event I was looking for an event that is able to run some code after clicking (changing) tab in browser, but I haven't found it.
Is it possible to achieve this event somehow?
I'm already listening to DOMContentLoaded event, I'm displaying some information about the current page on the status bar. When I changed tab, the information in the status bar is not correct (I have to reload the page).
thank you

A: There are two possible ways to do this.
Detecting location change
The nsIWebProgressListener interface is used to detect when the window's location has changed. Place something like this in your window's onLoad handler:
// implements nsIWebProgressListener
var listener = {
    onLocationChange: function(aProgress, aRequest, aURI) {
        // fires on tab change; update status here;
        // get the currently selected tab
        var currDoc = gBrowser.contentDocument;
    },
    onStateChange: function(a, b, c, d) {},
    onProgressChange: function(a, b, c, d, e, f) {},
    onStatusChange: function(a, b, c, d) {},
    onSecurityChange: function(a, b, c) {}
}

gBrowser.addProgressListener(
    listener,
    Components.interfaces.nsIWebProgress.NOTIFY_LOCATION);

Note that onLocationChange fires every time the window's location changes. This means that it fires when the browser is started, when a new URL is loaded in the current tab, when the tab changes, etc. This is probably what you want if your goal is to update the status bar based on the currenty-loaded URL.
Detecting tab change
To detect only the case when a new tab has been selected, use the TabSelect event. Full example copied from here:
function exampleTabSelected(event) {
  var browser = gBrowser.selectedBrowser;
  // browser is the XUL element of the browser that's just been selected
}

// During initialisation
var container = gBrowser.tabContainer;
container.addEventListener("TabSelect", exampleTabSelected, false);

// When no longer needed
container.removeEventListener("TabSelect", exampleTabSelected, false);

redpajama_set_name: RedPajamaStackExchange


text:
Q: SignInManager Is throwing null when attempting to login I am implementing asp.net Identity. I have overridden the default classes with a int primary key rather than the default String. I followed the following article to do so: Article
Sorry for all the code, however I have been stuck on this silly error for some time now, so I have rather given more info than less.
I have the following classes:
public class FskUser : IdentityUser<int, FskUserLogin, FskUserRole, FskUserClaim>
{
    ...
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<FskUser, int> manager)
    {
                    // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here
        return userIdentity;
    }
}

My Custom SignInManager
  public class FskSignInManager : SignInManager<FskUser,int>
{
    public FskSignInManager(FskUserManager userManager, IAuthenticationManager authenticationManager)
        : base(userManager, authenticationManager)
    {
    }

    public override Task<ClaimsIdentity> CreateUserIdentityAsync(FskUser user)
    {
        return user.GenerateUserIdentityAsync((FskUserManager)UserManager);
    }

    public static FskSignInManager Create(IdentityFactoryOptions<FskSignInManager> options, IOwinContext context)
    {
        return new FskSignInManager(context.GetUserManager<FskUserManager>(), context.Authentication);
    }
}

My StartUp.Auth.cs
 public void ConfigureAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(IdentityDbContext.Create);
        app.CreatePerOwinContext<FskUserManager>(FskUserManager.Create);
        app.CreatePerOwinContext<FskSignInManager>(FskSignInManager.Create);

        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            Provider = new CookieAuthenticationProvider
            {
                // Enables the application to validate the security stamp when the user logs in.
                // This is a security feature which is used when you change a password or add an external login to your account.
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<FskUserManager, FskUser, int>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentityCallback: (manager, user) =>
                user.GenerateUserIdentityAsync(manager),
            getUserIdCallback: (id) => (id.GetUserId<int>()))
            }
        });            app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
           }

Here is my Account Controller simplified:
 [Authorize]
public class AccountController : Controller
{
    private FskSignInManager _signInManager;
    private FskUserManager _userManager;

    public AccountController()
    {
    }

    public AccountController(FskUserManager userManager, FskSignInManager signInManager)
    {
        UserManager = userManager;
        SignInManager = signInManager;
    }

    public FskSignInManager SignInManager
    {
        get
        {
            if (_signInManager == null)
            {
                //split for debug purposes
                var cntx = HttpContext.GetOwinContext();
                var tmp = cntx.Get<FskSignInManager>();
                return tmp;
            }
            else
            {
                return _signInManager;
            }
        }
        private set
        {
            _signInManager = value;
        }
    }

    public FskUserManager UserManager
    {
        get
        {
            return _userManager ?? HttpContext.GetOwinContext().GetUserManager<FskUserManager>();
        }
        private set
        {
            _userManager = value;
        }
    }

    //
    // POST: /Account/Login
    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }
        *** line below causes the error ***
        var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
        switch (result)
        {
            case SignInStatus.Success:
                return RedirectToLocal(returnUrl);
            case SignInStatus.LockedOut:
                return View("Lockout");
            case SignInStatus.RequiresVerification:
                return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
            case SignInStatus.Failure:
            default:
                ModelState.AddModelError("", "Invalid login attempt.");
                return View(model);
        }
    }
 }

And this is the error message which I am getting when I try and login:
    Value cannot be null.
    Parameter name: value
    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.ArgumentNullException: Value cannot be null.
Parameter name: value

    Source Error:

    Line 80:
    Line 81:             // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
    Line 82:             var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
    Line 83:             // Add custom user claims here
    Line 84:             return userIdentity;

   Source File:  c:\Users\Dylan.AMECOR\Dropbox\Work\Code\FSK Networks Website\FSK.Domain.Repository\Services\Shared\Security\FskUser.cs    Line:  82
    Stack Trace:
    [ArgumentNullException: Value cannot be null.
    Parameter name: value]
     System.Security.Claims.Claim..ctor(String type, String value, String valueType, String issuer, String originalIssuer, ClaimsIdentity subject, String propertyKey, String propertyValue) +10798181
   System.Security.Claims.Claim..ctor(String type, String value) +34
   Microsoft.AspNet.Identity.<CreateAsync>d__0.MoveNext() +1447
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
   FSK.Domain.Services.Services.Shared.<GenerateUserIdentityAsync>d__0.MoveNext() in c:\Users\Dylan.AMECOR\Dropbox\Work\Code\FSK Networks Website\FSK.Domain.Repository\Services\Shared\Security\FskUser.cs:82
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
   Microsoft.AspNet.Identity.CultureAwaiter`1.GetResult() +123
   Microsoft.AspNet.Identity.Owin.<SignInAsync>d__2.MoveNext() +408
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
   Microsoft.AspNet.Identity.CultureAwaiter.GetResult() +63
   Microsoft.AspNet.Identity.Owin.<SignInOrTwoFactor>d__23.MoveNext() +1910
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93     System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
    System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
   Microsoft.AspNet.Identity.CultureAwaiter`1.GetResult() +67
   Microsoft.AspNet.Identity.Owin.<PasswordSignInAsync>d__29.MoveNext() +2208
    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93        System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
    System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() +24
   FSK.WebSite.Web.Controllers.<Login>d__2.MoveNext() in c:\Users\Dylan.AMECOR\Dropbox\Work\Code\FSK Networks Website\FSK.WebSite.Web\Controllers\AccountController.cs:86
    System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93          System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
    System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
    System.Threading.Tasks.TaskHelpersExtensions.ThrowIfFaulted(Task task) +61
    System.Web.Mvc.Async.TaskAsyncActionDescriptor.EndExecute(IAsyncResult asyncResult) +114
    System.Web.Mvc.Async.<>c__DisplayClass37.<BeginInvokeAsynchronousActionMethod>b__36(IAsyncResult asyncResult) +66
    System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
    System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102
   System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethod(IAsyncResult asyncResult) +49
    System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3d() +117
    System.Web.Mvc.Async.<>c__DisplayClass46.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3f() +323
    System.Web.Mvc.Async.<>c__DisplayClass33.<BeginInvokeActionMethodWithFilters>b__32(IAsyncResult asyncResult) +44
    System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +47
    System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +136
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +102              System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeActionMethodWithFilters(IAsyncResult asyncResult) +50
    System.Web.Mvc.Async.<>c__DisplayClass2b.<BeginInvokeAction>b__1c() +72
    System.Web.Mvc.Async.<>c__DisplayClass21.<BeginInvokeAction>b__1e(IAsyncResult asyncResult) +185
    System.Web.Mvc.Async.WrappedAsyncResult`1.CallEndDelegate(IAsyncResult asyncResult) +42
    System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +133
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +56
    System.Web.Mvc.Async.AsyncControllerActionInvoker.EndInvokeAction(IAsyncResult asyncResult) +40
    System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +34
    System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
    System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
    System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +44
    System.Web.Mvc.Controller.<BeginExecute>b__15(IAsyncResult asyncResult, Controller controller) +39
    System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +62
    System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
    System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult) +39
       System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult) +39
    System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__5(IAsyncResult asyncResult, ProcessRequestState innerState) +39
    System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +70
    System.Web.Mvc.Async.WrappedAsyncResultBase`1.End() +139
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +59
    System.Web.Mvc.Async.AsyncResultWrapper.End(IAsyncResult asyncResult, Object tag) +40
    System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +40
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +38
   System.Web.CallHandlerExecutionStep.OnAsyncHandlerCompletion(IAsyncResult ar) +129

A: For me this was a result of a null ClaimValue
user.Claims.Add(new IdentityUserClaim<string>
            {
                ClaimType = item.Key,
                ClaimValue = item.Value
            });

I resolved it by modifying the code to
user.Claims.Add(new IdentityUserClaim<string>
            {
                ClaimType = item.Key,
                ClaimValue = item.Value != null ? item.Value : ""
            });

A: I have stucked with the SignInManager failing to sign in the newly created user with the same error.
Solution:
I have found out that just assiging a role to the user upon creation solved the issue.
await userManager.AddToRoleAsync(user, UserRoles.Basic.ToString());


text:
Q: Querying pivot attributes in Eloquent I am creating a basic messaging system and need to query the data on a pivot table. The relevant tables are set up like so:
|  conversations  |  messages         |  message_user  |  conversation_user  |
------------------------------------------------------------------------------
|  id             |  id               |  message_id    |  conversation_id    |
|  created_at     |  conversation_id  |  user_id       |  user_id            |
|  updated_at     |  content          |  sender        |                     |
|  deleted_on     |  created_at       |  unread        |                     |
|                 |  updated_at       |  deleted       |                     |
------------------------------------------------------------------------------

Simply, each conversation has users, each user has messages, each message is in a conversation. The message_user table is a pivot table, as is the conversaton_user table.
my models are set up like so:
class Message extends Eloquent {
    public $touches = ['conversation'];

    public function conversation() {
        return $this->hasOne('Conversation');
    }

    public function user() {
        return $this->belongsToMany('User')->withPivot(['sender', 'unread', 'deleted']);
    }

    public function session() {
        return $this->hasOne('UserSession');
    }
}

class Conversation extends Eloquent {

    public function users() {
        return $this->belongsToMany('User');
    }

    public function product() {
        return $this->hasOne('Product');
    }

    public function messages() {
        return $this->hasMany('Message');
    }
}

class User extends Eloquent {

    ...

    public function conversations() {
        return $this->belongsToMany('Conversation');
    }

    public function messages() {
        return $this->belongsToMany('Message');
    }

    ...

}

When a message gets saved, it updates the message user with a field for each user involved in the conversation:
foreach($conversation->users as $user) {
    $message->users()->attach($user->id [
        'sender' => (Auth::user()->id === $user->id),
        'unread' => (Auth::user()->id !== $user->id),
        'deleted' => false,
    ]);
}

to get all of a users conversations I do the following:
$user = Auth::user();
foreach($user->conversations as $conversation) {
    // get each message from the conversation
    foreach($conversation->messages as $message) {

    }
}

My issue is that I need to query the pivot table to find out if the user has deleted the message before deciding whether to show the user the message, Since the deletion is specific to each individual user.
I could do something like this in my conversation model:
public function notDeletedMessage() {
    return $this->messages()
                ->join('message_user', 'message_user.message_id', '=', 'messages.id')
                ->where('message_user.user_id', Auth::user()->id)
                ->where('message_user.deleted', false);
}

But it seems a little hacky, is there a better way to achieve this functionality?

A: Have you tried using pivot on the collection? http://four.laravel.com/docs/eloquent#working-with-pivot-tables


text:
Q: listview not updating when navigating back to page in winrt phone 8.1 application I have a page in my application which contains a listview, listview is binded with an observeable collection like this
public ObservableCollection<ViolationsByPlateViewModel> ViolationAssigned;
...
...
...
defaultViewModel.Add("ViolationList", ViolationAssigned);

ItemsSource="{Binding ViolationList, Mode=TwoWay}"

And defined this in page contructor
this.NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;

I am updating my Violation assigned variable after every time I hit bottom of my listview. And it works fine. but when I click on my item and go to second screen and came back to first screen again. I found out that my list is not updating when I hit bottom of the screen. I tried debugging and found out that my variable is still updating but not updating at UI. It seems that data is not binded anymore and listview populating from the cache.
Is it possible to do this?

A: We found the WinRT page cache to be pretty finicky when navigating backwards in certain situations. Sometimes it works, sometimes not. To get around this, without having to debug too much into a problem we care little about, we switched our paging to use MtFrame and MtPage from MyToolkit. This has worked out pretty well for us in a number of areas in our app, but especially in paging.


text:
Q: Why when I use width: 100%, my wrapper box doesn't fit all the screen? Why when I use width: 100%, my wrapper box doesn't fit all the screen but when I use width:100vw it fits all the screen. "width=device-width" is used on my page. The width for the page is min-width: 1400px;
thank all of you for your help
[![enter image description here][1]][1]
[![enter image description here][2]][2]
width:100%
[1]: https://i.stack.imgur.com/SmUH9.jpg
width:100vw
[2]: https://i.stack.imgur.com/39kpm.jpg

@media only screen and (min-width: 1400px){

    body{
        min-width: 1400px;
    }

    .wrapper{
        width: 100vw;
        height: 100%;
        background:  var(--DarkCyan);
        display: flex;
        align-items: center;
    }
}

A: That is because your wrapper class is taking "100%" of its parent container, the body. You set the body to have a min-width of 1400px, which means it won't expand past 1400px unless its contents exceed that width. Therefore, the wrapper child class will only take up as much as its parent defines it to, in this case only 1400px.
Percentage values (100%) depends on the parent container's value, while viewport values (100vw) are isolated from other elements and render based on the screen's view port


text:
Q: build email client in dashboard I was wondering, how hard would it be to create a custom webmail client in a client area dashboard? This can be done if it has to connect to one server. But in this setup we're talking about 7 mail servers.
I was thinking about letting an email client make an IMAP connection with php based upon the client's domain name after the @ and the user's password. I haven't tried it yet, I wanted to hear some opinions about this. What are the best php mail client scripts around nowdays? Will this idea work? How hard will it be?


text:
Q: How to order a string list based upon a reference list of string values I have a List of strings in C#. It contains the following substrings somewhere in the middle of the strings within the list. The list is not ordered. I want to order this list, based upon the following entries in them:

Email
FirstName
LastName
Country
Province
Phone
Fax

in this order.
For example if the original list had the following entries:

The field Province required 5 letters
Wrong Email
Phone is required
FirstName should contain min of 5 letters
The field Fax requires 10 digits
Enter a valid LastName
Fax is required
The field Phone requires 10 digits

It needs to be sorted as follows:

Wrong Email
FirstName should contain min of 5 letters
Enter a valid LastName
The field Province required 5 letters
Phone is required
The field Phone requires 10 digits
Fax is required
The field Fax requires 10 digits

Thanks

A: It can be something like this.
var order = new List<string>()
{
    "Email",
    "FirstName",
    "LastName",
    "Country",
    "Province",
    "Phone",
    "Fax",
};

var lines = new List<string>()
{
    "The field Province required 5 letters",
    "Wrong Email",
    "Phone is required",
    "FirstName should contain min of 5 letters",
    "The field Fax requires 10 digits",
    "Enter a valid LastName",
    "Fax is required",
    "The field Phone requires 10 digits",
};

Func<string, int> calc = s => Regex.Matches(s, @"\w+").Cast<Match>()
                                .Select(m => m.Value)
                                .Max(x => order.IndexOf(x));

var result = lines.OrderBy(l => calc(l)).ToList();

You may need to fix this code if a line doesn't contain any keywords from your set...
BTW: your question is not clear for a case like
Wrong Email or Fax number


text:
Q: Apply some aligment on this two elements when the windows resizes - Bootstrap 3 I have this codepen, and two littles problems. If I resize the windows, when the width gets 991px:
1) The search box goes down (I don't want this). I want that the search box keeps in the same aligment that the 'select' until it gets large (when it gets large, it's ok)
2) The 'pagination' keeps align in right, I want it centered.
I guess is something like:
@media only screen and (max-width: 991px) {
}

But I don't know which classes I need to apply. Some help?

A: To target smaller screens you just have to use the appropriate classes. Instead of col-md- I used col-sm- and col-xs- that target smaller screens.
http://codepen.io/anon/pen/XmzKYR
Bootstrap's documentation is your best friend: http://getbootstrap.com/css/#grid


text:
Q: Reading in .txt file with different extension in C At the moment my program has no problem reading in a .txt file, but my program needs to read in a text file with a different file extension (.emu is the requirement). When simply changing the same file's extension to .emu, the variable 'file' is NULL and therefore the file isn't opened, can anyone help?
Had a little look around and haven't been able to find a solution so any help is much appreciated
here's the source code:
void handleArgs (const char *filename, int trace, int before, int after) {
FILE *file = fopen(filename, "r");
char *address = malloc(MAX_ADD_LENGTH * sizeof(char));
char *instruction = malloc(MAX_INS_LENGTH * sizeof(char));
long int addressDecoded;

if (file == NULL || file == 0) {
    fprintf(stderr, "Error: Could not open file");
}
else {
    if (ferror(file) == 0) {
        while (fscanf(file, "%s %s", address, instruction) != EOF) {
            if (strlen(address) == 8 && strlen(instruction) == 8) {
                addressDecoded = strtol(address, NULL, 16);
                printf("%ld\n", addressDecoded);
                //instruction = decodeInstruction(instruction);
            }
            else {
                fprintf(stderr, "Error: particular line is of wrong length");
            }

        }
    }
}

fclose(file);

}
argument 'filename' when executing is simply '/foopath/test.emu'

A: There's nothing special to C about the file extension.  Reread your code for simple errors like changing the filename in one place, but not the other.  If you're passing in the filename, pass the whole name, not just the part to the left of the period.

A: Files are data, and have names. What comes before the dot in a name, is just as much a part of it as what comes after -- the extensions were created just as hints as to what the file contains, but they are NOT required to be strictly related to the file's contents.
The file may not exist, or your priviledges may not be enough to open it. Or maybe there's some other kind of error. How can you diagnose this?
When you use a system call and it doesn't behave the way you want to, there's a variable called errno in errno.h (#include <errno.h>) that will contain a number representing the status of the last call. There's a huge list of symbolic constants to put names to these values, you can google it up.
For example, if you try to open a file and the returned pointer is useless, you might want to check errno to see if the file existed, or if you're exceding system restrictions for opened files, etc.


text:
Q: Не устанавливается mpi на windows 64bit При установки mpi на windows 64 bit, запуске кода на visual studio
#include "stdafx.h"
#include <stdio.h>
#include "mpi.h"

int main(int argc, char* argv[])
{
 int ProcNum, ProcRank, RecvRank;
 MPI_Status Status;
 MPI_Init(&argc, &argv);
 MPI_Comm_size(MPI_COMM_WORLD, &ProcNum);
 MPI_Comm_rank(MPI_COMM_WORLD, &ProcRank);
 if ( ProcRank == 0 ){
 // Действия, выполняемые только процессом с рангом 0
 printf("\n Hello from process %3d", ProcRank);
 for (int i = 1; i < ProcNum; i++ ) {
 MPI_Recv(&RecvRank, 1, MPI_INT, MPI_ANY_SOURCE,
 MPI_ANY_TAG, MPI_COMM_WORLD, &Status);
 printf("\n Hello from process %3d", RecvRank);
 }
 }
 else // Сообщение, отправляемое всеми процессами,
 // кроме процесса с рангом 0
 MPI_Send(&ProcRank,1,MPI_INT,0,0,MPI_COMM_WORLD);
 MPI_Finalize();
 return 0;
}

выводит такую ошибку

Прописано:
Свойства-> C/C++ -> Общие -> Дополнительные каталоги включаемых файлов: mpi/include
Свойства-> Компоновщик -> Общие -> Дополнительные каталоги библиотек: mpi/lib
Свойства-> Компоновщик -> Ввод -> Дополнительные зависимости: msmpi.lib
Скачано msmpisdk.msi и MSMpiSetup.exe. Проверено, что все установлено set MPI
Помогите, не хочет устанавливаться и все. Не знаю, что и делать.


text:
Q: Pass wildcard to process builder In both Java and C++ arguments are wrapped by ' like :
system("cmd arg1 arg2");// C++
Runtime.getRuntime().exec("cmd arg1 arg2");// Java
new ProcessBuilder("cmd","arg1","arg2").start();// Java
//=============== output
cmd 'arg1' 'arg2'

Which prevents arguments to be interpreted as wildcard like: l* will be interpreted as "lstar" not "l{everything-is-possible}"
Also if I add a ' ,it will converted to \'
How can I pass wildcard via these programming languages?

A: It is the shell (bash, csh) etc that handles wildcards and passes specific arguments to your process. For example you may run ls *.txt - the shell expands *.txt and calls ls a.txt b.txt c.txt (depending on what files exist in the current directory).
Calling exec doesn't invoke any shell and so there is no "wildcard handling".
Processes could do their own wildcard handling (if (arg.equals("*")) { ...) but I think it is pretty rare.
So either the calling process has to do the matching and pass the correct args to exec or you need to invoke exec with a shell like Runtime.getRuntime().exec("bash -c ls *.txt");


text:
Q: how to put value in the checkboxes this is my code, I just want to make a receipt that when you check the checkbox theres value in it and it prints the label with the value consecutively
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class GUI extends JFrame implements ActionListener

{

private JLabel label;
private JCheckBox checkbox,checkbox2,checkbox3,checkbox4,checkbox5,
checkbox6,checkbox7,checkbox8,checkbox9,
checkbox10,checkbox11,checkbox12,checkbox13,checkbox14,checkbox15,
checkbox16,checkbox17,checkbox18,checkbox19,checkbox20;
 private JButton button;

public GUI()
{
Container pane= getContentPane();
pane.setLayout(new GridLayout(15,1));

JPanel jp= new JPanel();

label= new JLabel("McDonald's");
checkbox = new JCheckBox("Cheese Burger");
checkbox2 = new JCheckBox("Big Mac");
checkbox3 = new JCheckBox("Big n' Tasty");
checkbox4 = new JCheckBox("McSpicy");
checkbox5 = new JCheckBox("Quarter Pounder with Cheese");
checkbox6 = new JCheckBox("Double Cheeseburger");
checkbox7 = new JCheckBox("McChicken Sandwich");
checkbox8 = new JCheckBox("Filet-O-Fish");
checkbox9 = new JCheckBox("Cheeseburger Deluxe");
checkbox10 = new JCheckBox("Burger Mcdo");
checkbox11 = new JCheckBox("Chicken Filet with Drinks");
checkbox12 = new JCheckBox("Spaghetti with Drinks");
checkbox13 = new JCheckBox("Hot Fudge Sundae ");
checkbox14 = new JCheckBox("Caramel Sundae");
 checkbox15 = new JCheckBox("Large Mcdo French Fries");
checkbox16 = new JCheckBox("Chicken Nuggets with coke");
checkbox17 = new JCheckBox("Coke Float");
checkbox18 = new JCheckBox("Green Apple Float");
checkbox19 = new JCheckBox("Crispy Chicken with rice");
checkbox20 = new JCheckBox("Oreo Sundae");
button = new JButton("Order Now");

add(label);

pane.add(checkbox);
pane.add(checkbox2);
pane.add(checkbox3);
pane.add(checkbox4);
pane.add(checkbox5);
pane.add(checkbox6);
pane.add(checkbox7);
pane.add(checkbox8);
pane.add(checkbox9);
pane.add(checkbox10);
pane.add(checkbox11);
pane.add(checkbox12);
pane.add(checkbox13);
pane.add(checkbox14);
pane.add(checkbox15);
pane.add(checkbox16);
pane.add(checkbox17);
pane.add(checkbox18);
pane.add(checkbox19);
pane.add(checkbox20);

add(button);
add(jp, BorderLayout.SOUTH);
label.setHorizontalAlignment(JLabel.CENTER);

button.setSize(10,10);
button.addActionListener(this);

setSize(500,550);
setVisible(true);

 }
 public void actionPerformed(ActionEvent e)
 {
 String gulp = e.getActionCommand();
{
if ( gulp.equals("Order Now"))
   {
   new Receipt();
  setVisible(true);
  dispose();
}
}
}
public static void main(String[] args)
{
GUI r= new GUI();
}
}

here is my second code, this is the format of the receipt I want to achieve
    import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class Receipt extends JFrame
{

private JLabel label,label2,label3,label4,label5,
label6,label7,label8,label9,label10;;

public Receipt()
{
    Container pane= getContentPane();
    pane.setLayout(new GridLayout(13,1));

    label= new JLabel("MC DONALD'S");
    label2= new JLabel("McDonald's Tandang Sora");
    label3= new JLabel("#22 Tandang Sora Corner, Commonwealth Avenue, Quezon City");
    label4= new JLabel("Telephone# (02)86236");
    label5= new JLabel("MACHINE SERIAL NUMBER: D123HJ01");

    label6= new JLabel("Card Issuer: Sharina Tortoles");
    label7= new JLabel("Account Number# 337163990");
    label8= new JLabel("February 22, 2014  12:45");
    label9= new JLabel("Thank You for choosing Mcdonald's");
    label10= new JLabel("Please come again");

    label.setHorizontalAlignment(JLabel.CENTER);
    label2.setHorizontalAlignment(JLabel.CENTER);
    label3.setHorizontalAlignment(JLabel.CENTER);
    label4.setHorizontalAlignment(JLabel.CENTER);
    label5.setHorizontalAlignment(JLabel.CENTER);
    label6.setHorizontalAlignment(JLabel.CENTER);
    label7.setHorizontalAlignment(JLabel.CENTER);
    label8.setHorizontalAlignment(JLabel.CENTER);
    label9.setHorizontalAlignment(JLabel.CENTER);
    label10.setHorizontalAlignment(JLabel.CENTER);

    pane.add(label, BorderLayout.NORTH);
    pane.add(label2);
    pane.add(label3);
    pane.add(label4);
    pane.add(label5);
    pane.add(label6);
    pane.add(label7);
    pane.add(label8);
    pane.add(label9);
    pane.add(label10);

    setSize(500,500);
    setVisible(true);
 }

 public static void main(String[] args)
 {
    Receipt g= new Receipt();

  }
 }

Hope that it is clear to you what I want to happen with code

A: I guess EnumSet is what you are looking for:
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import java.util.List;
import javax.swing.*;

enum Receipt {
  CheeseBurger("Cheese Burger"),
  BigMac("Big Mac"),
  BigNTasty("Big n' Tasty"),
  McSpicy("McSpicy"),
  QuarterPounderWithCheese("Quarter Pounder with Cheese"),
  DoubleCheeseburger("Double Cheeseburger"),
  McChickenSandwich("McChicken Sandwich");
  //JCheckBox("Filet-O-Fish"),
  //JCheckBox("Cheeseburger Deluxe"),
  //JCheckBox("Burger Mcdo"),
  //JCheckBox("Chicken Filet with Drinks"),
  //JCheckBox("Spaghetti with Drinks"),
  //JCheckBox("Hot Fudge Sundae "),
  //JCheckBox("Caramel Sundae"),
  //JCheckBox("Large Mcdo French Fries"),
  //JCheckBox("Chicken Nuggets with coke"),
  //JCheckBox("Coke Float"),
  //JCheckBox("Green Apple Float"),
  //JCheckBox("Crispy Chicken with rice"),
  //JCheckBox("Oreo Sundae");
  private final String str;
  private Receipt(String str) {
    this.str = str;
  }
  @Override public String toString() {
    return str;
  }
}

public class GUI2 {
  private JButton button = new JButton(new AbstractAction("Order Now") {
    @Override public void actionPerformed(ActionEvent e) {
      EnumSet<Receipt> r = EnumSet.noneOf(Receipt.class);
      for (ReceiptCheckBox c: list) {
        if (c.isSelected()) {
          r.add(c.getReceipt());
        }
      }
      JOptionPane.showMessageDialog((JComponent) e.getSource(), r);
    }

  });
  private List<ReceiptCheckBox> list = new ArrayList<>(Receipt.values().length);

  public JComponent makeUI() {
    JPanel p = new JPanel();
    for (Receipt r: Receipt.values()) {
      ReceiptCheckBox c = new ReceiptCheckBox(r);
      list.add(c);
      p.add(c);
    }
    JPanel panel = new JPanel(new BorderLayout());
    panel.add(new JLabel("McDonald's"), BorderLayout.NORTH);
    panel.add(button, BorderLayout.SOUTH);
    panel.add(p);
    return panel;
  }
  public static void main(String[] args) {
    EventQueue.invokeLater(new Runnable() {
      @Override public void run() {
        createAndShowGUI();
      }
    });
  }
  public static void createAndShowGUI() {
    JFrame f = new JFrame();
    f.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    f.getContentPane().add(new GUI2().makeUI());
    f.setSize(320, 240);
    f.setLocationRelativeTo(null);
    f.setVisible(true);
  }
}

class ReceiptCheckBox extends JCheckBox {
  private final Receipt receipt;
  public ReceiptCheckBox(Receipt receipt) {
    super(receipt.toString());
    this.receipt = receipt;
  }
  public Receipt getReceipt() {
    return receipt;
  }
}


text:
Q: How to use jasmine-require with Backbone? I would like to use my require.js for Backbone within a Jasmine test suite; and I am working on the setup.
I've seen the use of https://github.com/scottburch/jasmine-require in this test setup: https://github.com/Patternslib/Patterns/blob/master/tests/index.html
Now, I would like to inject Backbone into the game:
describe("Basic view test", function() {

  var view;

  requireDependencies(["underscore", "backbone"], function(_, Backbone) {
    view = Backbone.View.extend({el: "li" });
  });

  it("has el property", function() {
    expect(view.el).toBe("li");
  });

});

But my Backbone setup is not loaded correctly, see screenshot:

What's missing?
My current setup is here: https://github.com/mulderp/backbone-require-test/tree/master/spec

A: The problem here was the load orders of the dependencies in the global scope that is not seen in the question.
Make sure underscore is loaded before backbone.


text:
Q: Interpretation of multi-exponent x^y^z ($x^{y^z}$ or ${x^y}^z$) Is there any generally accepted or written rule specifying the interpretation of a multi-exponent expression written in this simple style (by user, no latex): x^y^z?
It leads to different results on different engines: e.g. 5^2^3 can be interpreted as:

*

*$5^{2^3}$ $5^{2^3}$ = 390625

*or as ${5^2}^3$ ${5^2}^3$ = 15625 (see that interpreted notation on Math StackExchange seems almost the same)

Interpretation examples:
Interpretation of Google, WolframAlpha, Bing, Yahoo is right associative: $x^{y^z}$
Interpretation of Windows Calculator / Samsung Calculator / Mac Spotlight is the second one (left associative): ${x^y}^z$ (equals to $x^{y \cdot z}$)
On my CASIO fx-85ES calculator when I click [num] [pow] [num] [pow] [num] result is the first one: $x^{y^z}$
Now I see on Math StackExchange that if I write $x^y^z$ it will raise an error "Double exponent: use braces to clarify".
 However I do not know any other latex validator which will raise an error like this.
My observation so far shows that most search engines choose the first way $x^{y^z}$ and most calculator apps choose the second way as sequential interpreting from left to right $x^{y^z}$.

A: Well, exponentiation is right associative, i.e., $x\uparrow y\uparrow z$ means $x\uparrow (y\uparrow z)$, which equals $x^{(y^z)}$.

A: Notice that
$$(x^y)^z$$ is equivalent to $x^{yz}$ so there would be little point writing
$$x^{y^z}$$ which would have that meaning.

A: According to Wikipedia Operator associativity page: "...for an exponentiation operator (if present) [source] and Knuth's up-arrow operators there is no general agreement."
There is a list of implementations (right- vs left-associative) across computer languages, available in the source that Wikipedia mentions.
Comparative table:
| Interpreter           |   | Expon. assoc.     |
|-----------------------|---|-------------------|
| Bash                  |   | Right-associative |
| Python                |   | Right-associative |
| Ruby                  |   | Right-associative |
| C++                   | ! | Left-associative  |
| -- Search engines: -------------------------- |
| Google, Bing, Yahoo   |   | Right-associative |
| WolframAlpha          |   | Right-associative |
| -- Spreadsheets: ---------------------------- |
| MS Excel              | ! | Left-associative  |
| Google Sheets         | ! | Right-associative |
| -- Other: ----------------------------------- |
| Matlab                | ! | Left-associative  |
| Windows, Samsung Calc.| ! | Left-associative  |
| Mac Spotlight         | ! | Left-associative  |
| Hand-held calculators | ! | Varies            |
                 ! means be careful

x^y^z can be also written as $x\uparrow y\uparrow z$. In both cases, the interpretation is ambiguous.
Because we can rewrite the statement after left-assoc. interpretation ${x^y}^z$ as $x^{y \cdot z}$ we can assume that this behavior is not what a regular user wants because he can write directly $x^{y \cdot z}$. From this point of view, it seems that right-associative approach is "better". I do not say more correct because we have no general rule/agreement for that.
There is also a mnemonics called PEMDAS/BEDMAS/BODMAS/BIDMAS (depends in countries). It calls us we should solve Brackets > Orders (e.g. powers, square roots) > Division > Multiplication > Addition > Subtraction. According to this mnemonics we should proceed from top to down for powers (right-association).
Negation vs exponentiation
There is also one more important problem you can face in this context: variable negation or exponentiation first? [source]

*

*Negation first: $-2^2$ = 4

*Exponentiation first: $-2^2$ = -4
Comparative table:
| Interpreter           |   | Neg. or Expon. first |
|-----------------------|---|----------------------|
| Bash                  | ! | Negation             |
| Python                |   | Exponentiation       |
| Ruby                  |   | Exponentiation       |
| -- Search engines: ----------------------------- |
| Google, Bing, Yahoo   |   | Exponentiation       |
| WolframAlpha          |   | Exponentiation       |
| -- Spreadsheets: ------------------------------- |
| MS Excel              | ! | Negation             |
| Google Sheets         | ! | Negation             |
| -- Other: -------------------------------------- |
| Matlab                |   | Exponentiation       |
| Hand-held calculators | ! | Varies               |
                 ! means be careful

Conclusion
However it seems that the right-associative approach has more logical bases, we do not have any official rule that says it is right/wrong approach.
So since you know that a definition of the notation is missing, you should always use braces (as StackExchange parser also recommends) to avoid unexpected results.


text:
Q: How do I speed up searching through files on a network drive and prevent "not responding" in VB.Net Part of my application searches for a string provided by a textbox within .txt files and .pdf files stored on a network drive. It works great on my PC when looking within a directory of a few files stored on a local disk, when I run it on my work PC which is less beefy and looking at a network drive I get "not responding" and it takes a good few minutes to finally wake up again. This is only searching through around 100 files and that number is only going to get bigger.
I thought about adding a progress bar, but if the application is not responding I assume the progress bar will not update? I would be very grateful to hear the advice of someone much more experienced in this than me.
In short, the code searches as described above, uses the name of the folder (that begins with SCC) to add an item to a listbox. If it cannot search the PDF for any reason then it adds it to another listbox displaying the folder names it was unable to search.
Here is the section of code that does the search:
Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
    Dim path As String = ""
    Dim list As System.Collections.ObjectModel.ReadOnlyCollection(Of String)
    Dim raf As itextsharp.text.pdf.RandomAccessFileOrArray = Nothing
    Dim reader As itextsharp.text.pdf.PdfReader = Nothing
    Dim searchPhrase As String = faultSearch.Text

    VINListBox.Items.Clear()

Region "search plain text"
    'finds text within faultSearch textbox within the files in directory
    list = My.Computer.FileSystem.FindInFiles(archive_dir, faultSearch.Text, True, FileIO.SearchOption.SearchAllSubDirectories)

    For Each foundFile As String In list
        path = foundFile
        GetVinName(path)
    Next

End Region
Region "search PDF"
    'Finds text within faultSearch textbox within PDF files in directory
    For Each file As String In My.Computer.FileSystem.GetFiles(archive_dir, FileIO.SearchOption.SearchAllSubDirectories)
        If System.IO.Path.GetExtension(file).ToUpper = ".PDF" Then

            Try
                raf = New itextsharp.text.pdf.RandomAccessFileOrArray(file)
                reader = New itextsharp.text.pdf.PdfReader(raf, Nothing)
                For i As Integer = 1 To reader.NumberOfPages()
                    Dim pageText As String = itextsharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(reader, i)
                    If pageText.ToUpper.Contains(searchPhrase) Then
                        GetVinName(file)
                    End If
                Next
            Catch ex As Exception
                GetErrVinName(file)
            End Try

        End If

    Next

End Sub

End Region
Private Sub GetVinName(ByVal strVIN As String)
    Dim fldName() As String

    fldName = Split(strVIN.ToString, "\",, CompareMethod.Text)

    For x = 0 To UBound(fldName) - 1
        If InStr(fldName(x), "SCC", CompareMethod.Text) > 0 Then

            strVIN = Trim(fldName(x))
            If errListBox.Items.Contains(strVIN) = True Then
                errListBox.Items.Remove(strVIN)
            End If
            If VINListBox.Items.Contains(strVIN) = False Then
                VINListBox.Items.Add(strVIN)
            End If
            Exit For
            End If
    Next

End Sub

Private Sub GetErrVinName(ByVal strVIN As String)
    Dim fldName() As String
    fldName = Split(strVIN.ToString, "\",, CompareMethod.Text)

    For x = 0 To UBound(fldName) - 1
        If InStr(fldName(x), "SCC", CompareMethod.Text) > 0 Then
            strVIN = Trim(fldName(x))

            If VINListBox.Items.Contains(strVIN) = False Then
                If errListBox.Items.Contains(strVIN) = False Then
                    errListBox.Items.Add(strVIN)
                Else
                    Exit Sub
                End If
            Else
                Exit Sub
            End If

            Exit For
        End If
    Next

End Sub


text:
Q: $L^2$ convergence under different probability measures Suppose that $Z$ is a random vector whose range is compact. Let $f,f_n$ be functions of the random vector $Z$. I want to investigate the $L^2$ norm between $f$ and $f_n$ under 2 different probability distributions on $Z$.
Suppose that the two distributions we consider have densities $p_1(z)$ (uniform over the domain of $Z$) and $p_2(z)$. If $\|f_n(z)-f(z)\|_{L^2} \rightarrow 0$ under the density $p_1(z)$, does it imply that $\|f_n(z)-f(z)\|_{L^2} \rightarrow 0$  under the density $p_2(z)$?
I tried using Cauchy-schwarz on $\int |f_n(z)-f(z)|^2 p_2(z) \,dz$ but I can't simplify it further.
I am inclined to believe this is false in general. Are there any well known examples even in real analysis?

A: Let $Z_1$  have uniform distribution on $(0,1)$ and $Z_2$ have density $\frac 1 {2\sqrt x}$ on $(0,1)$. Let $f_n(x)=n^{1/4} I_{(0,\frac  1 n)}$. Then $f_n (Z_1) \to 0$ in $L^{2}$ but $f_n (Z_2)$ does not tend to $0$ in $L^{2}$


text:
Q: How to create Unique Id in Java I have a code like below:
D00077B4-EBFB-4BD8-9E3F-1F3943CBCE35

I was wondering how I could generate a code like this in Java.

A: This is a GUID or UUID, you can read more here:
https://en.wikipedia.org/wiki/Universally_unique_identifier
You can use java.util.UUID to generate one:
http://docs.oracle.com/javase/7/docs/api/java/util/UUID.html

A: This is a UUID, "a 128-bit number used to identify information in computer systems".
The format is explained as:

In its canonical textual representation, the sixteen octets of a UUID are represented as 32 hexadecimal (base 16) digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 for a total of 36 characters (32 alphanumeric characters and four hyphens). For example:

123e4567-e89b-12d3-a456-426655440000
xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx

How to generate the code like this using Java?

// Create a random UUID:
UUID uuid1 = UUID.randomUUID();
System.out.println(uuid1);

// Create a fixed UUID:
String uuidString = "D00077B4-EBFB-4BD8-9E3F-1F3943CBCE35";
UUID uuid2 = UUID.fromString(uuidString);
System.out.println(uuid2);

// Get string from UUID:
UUID uuid = ...
String s = uuid.toString();
System.out.println(s);

A: import java.util.UUID;

public class RandomStringUUID {
    public static void main(String[] args) {
        // Creating a random UUID (Universally unique identifier).
        UUID uuid = UUID.randomUUID();
        String randomUUIDString = uuid.toString();

        System.out.println("Random UUID String = " + randomUUIDString);
        System.out.println("UUID version       = " + uuid.version());
        System.out.println("UUID variant       = " + uuid.variant());
    }
}


text:
Q: What would cause an service app to work on Android 8 but fail on Android 12? I'm trying to learn how to use background services and have been watching videos, recreating working demos, etc to understand how it all works. I've now run two different demos that seem to work on Android 8 but fail on Android 12 (I try to run the app and i:t crashes immediately. I restart it again and it crashes and gives me the error ("Example" being the app name in this case):
"Clear Cache for Example? Example is closed because the app has a bug. Try clearing the app's cache first and then reopen the app"
Unfortunately, I don't really know what's breaking, so I'm not sure how to fix it . . . any idea what might be causing my problems? Here is one example that's clearly documented for reference:
https://erev0s.com/blog/run-android-service-background-reliably-every-n-seconds/
Any ideas what might be causing it? Any help you can give me would be greatly appreciated. Thanks!

A: If you are using any pending intents use  the following as flags
PendingIntent.FLAG_MUTABLE or PendingIntent.FLAG_IMMUTABLE
in Android 12 or above. It might solve your issue


text:
Q: psycopg2 select result gets nested with additional array I am trying to get JSON rows from postgres using "psycopg2".  value of records is like [ [{....},{...},{...}] ].  To get the correct JSON result ie. [{....},{...},{...}] i have to go for records1.  Not sure why this is happening.
import psycopg2
import sys
import json

conn_string = "'host='localhost' dbname='postgres' user='postgres' password='password123'"
con=psycopg2.connect(conn_string)
cur = con.cursor()
cur.execute("select json_agg(art) from (select a.*, (select json_agg(b) from (select * from pfstklist where pfportfolioid = a.pfportfolioid ) as b) as pfstklist, (select json_agg(c) from (select * from pfmflist where pfportfolioid = a.pfportfolioid ) as c) as pfmflist from pfmaindetail as a) art")
records = cur.fetchall()
print(records)     #This gives result [[{....},{...},{...}]]
records1=records[0]
print(records1)   #This gives expected result [{....},{...},{...}]

A: cur.fetchall() gives you a list of records. You probably want cur.fetchone().


text:
Q: Proving this Cauchy Sequence For $\varepsilon = \frac{1}{100}$ find $N \in \mathbb{N}$ such that $n \geq N$ implies $$\bigg|\frac{5n}{3n+1}-\frac{5}{3}\bigg|<\frac{1}{100}$$
I know that for a sequence {$a_{n}$} of real or complex numbers is a Cauchy Sequence if for every $\varepsilon > 0$, there exists a natural number $N$ such that if $n \geq N$ and $m\geq N$ then $|a_{n}-a_{m}|<\varepsilon$.
Thank you.

A: $ \bigg|\frac{5n}{3n+1}-\frac{5}{3}\bigg|<\frac{1}{100} \quad \iff \quad\frac{5}{9n+3}<\frac{1}{100} \quad \iff \quad 9n> 497$.
Your turn !


text:
Q: how to read CSV and put it into DataGrid view one by one C# i want to read CSV on the excel and then, put in the db grid one by one.
For example in 1 hour there are 200 data, for example, in the 10th minute, 2 data can be displayed. then 15 data in the 25th minute and 72 data in the 45th minute.
and how to make it?
please help me

A: You need a background process ( different thread) to read the data periodically. To check the data periodically, you can use Timer in C#.
Here is the CSV Reader:
 public class CSVReader
  {
    string appLocation = System.IO.Directory.GetCurrentDirectory();

    public List<MyDataModel> GetNewCSVValue()
    {
        StreamReader streamReader;
        List<MyDataModel> myDataModels = new List<MyDataModel>();
        MyDataModel myDataModel = null;

        var mydataFile = "../../../UnProcessed/data.csv";

        if (File.Exists(mydataFile))
        {
            try
            {
                streamReader = File.OpenText(mydataFile);

                while (!streamReader.EndOfStream)
                {
                    var valueLine = streamReader.ReadLine();

                    myDataModel = new MyDataModel();

                    var csvValues = valueLine.Split(',');
                    if (csvValues != null)
                    {
                        myDataModel.Column1 = csvValues[0];
                        myDataModel.Column2 = csvValues[1];
                        myDataModels.Add(myDataModel);
                    }

                }

                streamReader.Close();
                streamReader = null;

                // Move the data file to Processed folder
                //File.Move(mydataFile,
          // "../../../Processed/data"+DateTime.Now.ToString()+".csv");
            }
            catch (Exception ex)
            {
                streamReader = null;
            }
        }

        return myDataModels;
    }

}

Please add a Data Grid view in you main form and name it as dataGridView1.
Here is the code of main form.
using System;
using System.Collections.Generic;
using System.Timers;
using System.Windows.Forms;
using System.Windows.Threading;

namespace DataGrid
{
public partial class Form1 : Form
{

    List<MyDataModel> myDataModels = new List<MyDataModel>();

    public Form1()
    {
        InitializeComponent();
        // Read csv data at the begining
        ReadCSVData();
        // Set data in the grid
        dataGridView1.DataSource = myDataModels;

        // Then read the data file in regular interval and set in the grid
        StartAutoRefresh();
    }

    private void ReadCSVData()
    {
        CSVReader cSVReader = new CSVReader();
        var newCSVDataRows = cSVReader.GetNewCSVValue();
        if (newCSVDataRows != null)
        {
            myDataModels.AddRange(newCSVDataRows);
        }
    }

    #region Timer
    private static System.Timers.Timer _timer;

    private void StartAutoRefresh()
    {
        Console.WriteLine("Start the Datafetch " + DateTime.Now);

        if (_timer == null)
        {
            int dataFetchInterval = 1;

            dataFetchInterval = dataFetchInterval * 60 * 1000;

            _timer = new System.Timers.Timer(dataFetchInterval);
            _timer.Elapsed += new
    ElapsedEventHandler(FetchTripsOfTheWeek);

            _timer.Interval = dataFetchInterval;
            _timer.Enabled = true;
        }
        else
        {
            _timer.Enabled = true;
        }

    }

    public void StopAutoRefresh()
    {
        if (_timer != null)
        {
            _timer.Enabled = false;
            _timer.Dispose();
            _timer = null;
        }
    }

    public void FetchTripsOfTheWeek(object source, ElapsedEventArgs e)
    {
        bool isResourcesLoaded = false;
        executeActionOnBackgroundThread(
           "Loading data ...",
           () =>
           {
               try
               {
                   ReadCSVData();
                   isResourcesLoaded = true;
               }
               catch (Exception exception)
               {
                   var message = exception.Message;

                   MessageBox.Show(message);

                   isResourcesLoaded = false;
               }
           },

           () =>
           {
               var result = true;
               if (isResourcesLoaded)
               {
                   // Set data in the grid
                   dataGridView1.DataSource = null;
                   dataGridView1.DataSource = myDataModels;
                   dataGridView1.Refresh();
               }
               return result;
           },

           () =>
           {
               // Do extra things, like, setting readonly mode etc
           });
    }

    private void executeActionOnBackgroundThread(string indicatorMessage,
    System.Action backgroundAction, System.Func<bool> uiAction,
   System.ActiononCompletedAction = null)
    {
        System.Threading.Tasks.Task.Factory.StartNew(() =>
        {
            backgroundAction?.Invoke();

            BeginInvoke(new System.Action(() =>
            {
                var success = uiAction?.Invoke();

                onCompletedAction?.Invoke();

            }), null);
        });
    }

    #endregion
}

}
You down load the full project from here
https://drive.google.com/open?id=1ChLY7IydYM5OT5sOTUXjjV-6vfrgUeoD
Hope you can solve the issue. Good luck.


text:
Q: After edit crontab stopped performing I had one cronjob:
*/10 * * * ruby /home/pi/GIT/Zonky/Ruby/getUserLoans.rb

Everything worked just fine.
I added a second one:
*/5 * * * python /home/pi/Crypto/Crypto_cron.py

Since the edit, cron doesn't do any of the two jobs.
I used the following command:
cat /var/log/syslog | grep -i CRON

On the attached screenshot please note:

*

*last cron run of ruby command at 7AM

*Editing crontab for the first time at 7:05

*No ruby nor python command since then

I also restarted cron daemon, which didn't help.
I have no idea where to look for an answer.
Thank you

A: My problem was the existing command.
It worked for months - which gave me the confidence that it is correct, while it was correct
I use vim and probably due to some reckless use of hotkeys I managed to broke the existing command. That's the issue here.
So both commands are wrong, there should be 5 time parameters (e.g. stars) and I only have 4.


text:
Q: Passing NSComboBox value that is inside a NSAlert Sheet I have a NSAlert Sheet that has a NSComboBox inside. How can i pass the combo box value when the user has pressed a button of the NSAlert?
code:
NSComboBox* comboBox = [[NSComboBox alloc] initWithFrame:NSMakeRect(0, 0, 150, 26)];
        [comboBox setTitleWithMnemonic:@"2"];

        for (int i=2; i<[array count]+1; i++){
            [comboBox addItemWithObjectValue:[NSString stringWithFormat:@"%i", i]];
        }

        [comboBox setEditable:NO];

        NSAlert *alert = [[NSAlert alloc] init];
        [alert addButtonWithTitle:@"Okay"];
        [alert addButtonWithTitle:@"Cancel"];
        [alert setMessageText:@"Choose a number"];
        [alert setAccessoryView:comboBox];
        [alert beginSheetModalForWindow:_window modalDelegate:self didEndSelector:@selector(alertToChooseX:returnCode:contextInfo:) contextInfo:nil];

- (void)alertToChooseX:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo {
    if (returnCode == NSAlertFirstButtonReturn) {
        NSLog(@"Pressed Okay");
    }
}

A: Describe comboBox in Your header file and after pushed button "Okay" take it's value like this:
in .h
NSComboBox *comboBox;

in .m
comboBox = [[NSComboBox alloc] initWithFrame:NSMakeRect(0, 0, 150, 26)];
[comboBox setTitleWithMnemonic:@"2"];
.... // Your all code goes here

- (void)alertToChooseX:(NSAlert *)alert returnCode:(NSInteger)returnCode contextInfo:(void *)contextInfo {
    if (returnCode == NSAlertFirstButtonReturn) {
        NSLog(@"Pressed Okay");

        NSLog(@"Selected ComboBox's String Value: %@", [comboBox stringValue]);
        NSLog(@"Selected ComboBox's Object Value: %@", [comboBox objectValueOfSelectedItem]);
        NSLog(@"Selected ComboBox's Item Index: %ld", [comboBox indexOfSelectedItem]);
    }
}

Note: Don't forget to release comboBox because it's allocating memory.


text:
Q: Trying to store 32-bit number across 2 16-bit registers This is for the 8086, and I am using NASM.
I have HW I've been struggling with, where I am supposed to accept a 32-bit binary number as input, store it in register pair dx:bx, and output the number to the screen.
I have a problem I haven't been able to fix for a long time. Instead of outputting the 32 bits that were entered, it is outputting the last 16 bits that were entered, and doing it twice.
Could someone please look at this and help me understand why I am not getting the whole 32-bit number?
    CPU 286
    org 100h

section .data
    prompt: db  "Please enter a binary number: $"
    msg: db 0Dh,0Ah, "The number you entered is:    $"

section .text
start:
    mov ah,9        ; load print function
    mov dx,prompt   ; load prompt to print
    int 21h         ; prompt for input

    mov bx,0        ; bx holds input value
    mov dx,0        ; clear dx
    mov ah,1        ; input char function
    int 21h         ; read char into al

; loop to accept and store input
input:
    cmp al,0Dh      ; is char = CR?
    je  outputMsg   ; yes?  finished with input
    shl bx,1        ; bx *= 2, shifts msb of BX into CF
    rcl dx,1        ; rotate CF into lsb of DX
    and al,01h      ; converts ASCII to binary value
    or  bl,al       ; "adds" the input bit
    int 21h         ; read next character
    jmp input       ; loop until done

outputMsg:
    mov ah,9        ; load print function
    mov dx,msg      ; load output message to print
    int 21h         ; print output message

; loop to load either '0' or '1' to print, depending on carry flag
    mov cx, 32      ; loop counter
output:
    rol bx,1        ; rotate msb into CF
    jc  one         ; if CF is 1, go to "one" loop
    mov dl,'0'      ; of CF is 0, set up to print '0'
    jmp print       ; jump to "print" loop
one:
    mov dl,'1'      ; set up to print '1'
print:
    mov ah,2        ; load print char fcn
    int 21h         ; print char
    loop output     ; go to next character

Exit:
    mov ah,04Ch     ;DOS function: Exit program
    mov al,0        ;Return exit code value
    int 21h         ;Call DOS.  Terminate program

A:
outputMsg:
 mov ah,9        ; load print function
 mov dx,msg      ; load output message to print
 int 21h         ; print output message

At the outputMsg label, DX holds the high word of your 32-bit number in DX:BX. By writing mov dx, msg you've destroyed it! You need to preserve it.
outputMsg:
 push dx
 mov  ah, 09h
 mov  dx, msg
 int  21h
 pop  dx

rol bx,1        ; rotate msb into CF

The most significant bit (msb) of the 32-bit number in DX:BX is bit 15 of DX.
The code to retrieve it is:
shl  bx, 1     ;Shift low word left, carry gets its highest bit
rcl  dx, 1     ;Bring that carry in high word, carry gets msb

Your present solution to either output a "0" or a "1" works, but a much cleaner solution does not use the jc / jmp instructions. Those lead to untidy code requiring a lot of labels!
Adding the value of the carry flag (which is either 0 or 1) to the character "0" wil give you the requested "0" or "1".
push dx
mov  dl, '0'
adc  dl, 0      ;The immediate is zero, so only the carry gets added!
mov  ah, 02h
int  21h
pop  dx

Because the DOS output function uses DL, it was necessary to preserve and restore the high word of the number held in DX.
Of course some of the problems with this program would not have existed if the 32-bit number had been stored in some other register pair like DI:SI or BP:BX. Given that this is HW, push / pop works.

As a final note.

mov ah,04Ch     ;DOS function: Exit program
mov al,0        ;Return exit code value

When loading 2 byte registers (AH and AL) that team up in 1 word register (AX), you can save on code size and execution speed by combining the loads:
mov  ax, 4C00h     ;DOS function: Exit program with exit code 0


text:
Q: How to turn on the volume of ipod touch with a broken volume button? My ipod touch's volume button on the side to increase the volume doesn't work, no matter how hard I press it against something. The volume down button works.
The music player's sound is at the max, but the device uses another volume that's very low in volume. I can tell when I plug it into a wall, the beep sound is not very audible.
How can I increase the same volume these buttons work on?

A: You can change the alerts volume in the Settings App.

*

*Open the Settings App.

*Go to the Sounds section (typically the top of the second group of settings).

*Change the slider under Ringer and Alerts to your desired volume.

A: Either use the scrolling method when you are playing a song / video for the volume, or get a repair person to replace the buttons. I wouldn't recommend doing it if you haven't worked on iPods before, it's pretty difficult.

A: If you are having trouble getting it to work it may be because of the auto lock feature on your iPod gen4. If you have control of the sleep button and home button but can't increase the volume and the display on your screen to adjust the volume at the bottom when you are listening to music won't come up. If you have this problem I know just the solution. Go into settings and get into general, then go to auto lock and adjust the time you have it set at to something different and that should solve your problems. It worked for me! If that doesn't fix it than you are well and truly screwed! :-/


text:
Q: SQL Results values in horizontal way I have two tables JOB and EMP; structure and values are like this:
 CREATE TABLE JOB
(
    JOBID SMALLINT UNIQUE NOT NULL,
    JOBNAME CHAR(15)
);

CREATE TABLE EMP
(
    EMPID SMALLINT,
    JOBID SMALLINT,
    SAL SMALLINT,
    CITYID SMALLINT,
    YEAR SMALLINT,
    SEX  CHAR(1),
    STATE CHAR(2)
);

INSERT INTO JOB(JOBID, JOBNAME)
VALUES (1, 'DEVELOPMENT'),
       (2, 'DEVELOPMENT'),
       (3, 'TESTING'),
       (4, 'TESTING'),
       (7, 'TESTING'),
       (8, 'HR'),
       (10,  'RESEARCH');

INSERT INTO EMP (EMPID , JOBID, SAL, CITYID, YEAR, SEX,STATE)
VALUES (100, 1, 1000, 10, 2015, 'M','NY'),
       (200, 2, 2000, 10, 2015, 'M','NJ'),
       (300, 1, 2500, 20, 2015, 'F','NY'),
       (400, 3, 1000, 10, 2015, 'M','CA'),
       (500, 6, 3000, 10, 2015, 'F','NJ'),
       (600, 8, 1000, 30, 2015, 'M','CA'),
       (700, 8, 2000, 10, 2015, 'F','NY'),
       (800, 9, 1500, 10, 2015, 'F','CA');

For the given input cityid , YEAR ( Emp table), take all jobids for each jobname (from job table ) and match in Emp table, if exists display count (count of jobids present in Emp table) of each sex (male and female) for the states NY,NJ,CA in horizontal way; and totals as well. if there is no match display 0.
Output should be like this:
Jobname                  Male           FEMALE              TOTAL
                    NY   NJ   CA      NY   NJ   CA

Development         1     1   0       1    0    0             3
TESTING             0     0   1       0    0    0             1
HR                  0     0   1       1    0    0             2
RESEARCH            0     0   0       0    0    0             0
TOTAL               1     1   2       2    0    0             6

How to get the results in horizontal way ..?

A: Hi i think this can be use :
 CREATE TABLE #JOB
(
    JOBID SMALLINT UNIQUE NOT NULL,
    JOBNAME CHAR(15)
);

CREATE TABLE #EMP
(
    EMPID SMALLINT,
    JOBID SMALLINT,
    SAL SMALLINT,
    CITYID SMALLINT,
    YEAR SMALLINT,
    SEX  CHAR(1),
    STATE CHAR(2)
);

INSERT INTO #JOB(JOBID, JOBNAME)
VALUES (1, 'DEVELOPMENT'),
       (2, 'DEVELOPMENT'),
       (3, 'TESTING'),
       (4, 'TESTING'),
       (7, 'TESTING'),
       (8, 'HR'),
       (10, 'RESEARCH');

INSERT INTO #EMP (EMPID , JOBID, SAL, CITYID, YEAR, SEX,STATE)
VALUES (100, 1, 1000, 10, 2015, 'M','NY'),
       (200, 2, 2000, 10, 2015, 'M','NJ'),
       (300, 1, 2500, 20, 2015, 'F','NY'),
       (400, 3, 1000, 10, 2015, 'M','CA'),
       (500, 6, 3000, 10, 2015, 'F','NJ'),
       (600, 8, 1000, 30, 2015, 'M','CA'),
       (700, 8, 2000, 10, 2015, 'F','NY'),
       (800, 9, 1500, 10, 2015, 'F','CA');

    SELECT * FROM #JOB;

    SELECT * FROM #EMP;

    SELECT J.JOBNAME,
        SUM(CASE WHEN E.SEX = 'M' AND STATE = 'NY' THEN 1 ELSE 0 END) AS 'Male_NY',
        SUM(CASE WHEN E.SEX = 'M' AND STATE = 'NJ' THEN 1 ELSE 0 END) AS 'Male_NJ',
        SUM(CASE WHEN E.SEX = 'M' AND STATE = 'CA' THEN 1 ELSE 0 END) AS 'Male_CA',
        SUM(CASE WHEN E.SEX = 'F' AND STATE = 'NY' THEN 1 ELSE 0 END) AS 'Female_NY',
        SUM(CASE WHEN E.SEX = 'F' AND STATE = 'NJ' THEN 1 ELSE 0 END) AS 'Female_NJ',
        SUM(CASE WHEN E.SEX = 'F' AND STATE = 'CA' THEN 1 ELSE 0 END) AS 'Female_CA',
        COUNT(*) AS 'Total'
    FROM #EMP E
    JOIN #JOB J ON E.JOBID = J.JOBID
    GROUP BY J.JOBNAME

    DROP TABLE #JOB;

    DROP TABLE #EMP;

But it's static mode if you have some other STATE and Gender you have to build this with dynamic SQL query and use EXECUTE check at this link.

*

*https://learn.microsoft.com/en-us/sql/t-sql/language-elements/execute-transact-sql?view=sql-server-2017
Other way you can use PIVOT check at this link :

*

*https://learn.microsoft.com/en-us/sql/t-sql/queries/from-using-pivot-and-unpivot?view=sql-server-2017

A: First, SQL queries do not support multiple levels of headers.  You can have complex header strings, but not multiple levels.
Second, you want rows with no employees.
Third, you want a total row.
So, you will need an outer join:
SELECT COALESCE(J.JOBNAME, 'TOTAL') as JobName,
       SUM(CASE WHEN E.SEX = 'M' AND E.STATE = 'NY' THEN 1 ELSE 0 END) AS Male_NY,
       SUM(CASE WHEN E.SEX = 'M' AND E.STATE = 'NJ' THEN 1 ELSE 0 END) AS Male_NJ,
       SUM(CASE WHEN E.SEX = 'M' AND E.STATE = 'CA' THEN 1 ELSE 0 END) AS Male_CA,
       SUM(CASE WHEN E.SEX = 'F' AND E.STATE = 'NY' THEN 1 ELSE 0 END) AS Female_NY,
       SUM(CASE WHEN E.SEX = 'F' AND E.STATE = 'NJ' THEN 1 ELSE 0 END) AS Female_NJ,
       SUM(CASE WHEN E.SEX = 'F' AND E.STATE = 'CA' THEN 1 ELSE 0 END) AS Female_CA
FROM JOB J LEFT JOIN
     EMP E
     ON E.JOBID = J.JOBID AND
        E.YEAR = @YEAR AND
        E.CITYID = @CITYID
GROUP BY GROUPING SETS ( (J.JOBNAME), () );

If you want data for all years/cities, remove the conditions in the ON clause.
Here is a db<>fiddle.


text:
Q: Nonlinear Optimization: Explain how to differentiate a norm of a nonlinear function using matrix algebra I am learning about nonlinear optimization where I have some data vector, $\mathbf{d}$ and some unknown model $\mathbf{m}$. I can calculate predicted data from some model using a nonlinear function $\mathbf{F}(\mathbf{m})$.
The standard method to solve this nonlinear problem is to minimize some cost function
$$U = ||\mathbf{d}-\mathbf{F}(\mathbf{m})||_2^2 +\mathrm{Some \;Regularization}$$
where $||\cdot||_2 $ is the L2 norm.
The way that this is done is to differentiate $U$ and set the derivative to 0:
$$\frac{\partial U}{\partial \mathbf{m}} = 0$$
The solution is then often stated as:
$$0 = \mathbf{J^Td}-\mathbf{J^T Jm} + \mathrm{Some \; Regularization\; Stuff}$$
where $\mathbf{J}$ is the Jacobian.
Can someone explain where the Jacobian and its transpose come from step-by-step?


text:
Q: Optimizing handling multiple requests in Django I'm trying to build a simple REST API with Django.
It works really good when dealing with a low rate of requests, but when I mock 100+ requests simultaneously the responses time goes from 0.3 seconds to around 3-4 seconds.
I've check the runtime of my view and it no more than 0.1 seconds no matter what, which make me thinking that the problem is in the response sending itself.
I tried calling an empty view that only returns an empty response, and yet it's times are around 3 seconds in average per request.
Any ideas how to optimize it?
The model + view that I'm using:
class Permutation(models.Model):
    id = models.AutoField(primary_key=True)
    hash_code = models.TextField(null=False, unique=True)
    all_permutations = models.TextField(null=False)

@api_view(['GET'])
def similarWords(request):
    word = request.GET.get('word', None)
    start_time = datetime.now()
    if not word or not word.isalpha():
        updateLogs(start_time)
        print('invalid word')
        return HttpResponse(status=400)
    perm = Permutation.objects.filter(hash_code=getHashCode(word))
    if not perm:
        updateLogs(start_time)
        return HttpResponse(json.dumps({'similar': []}), content_type="application/json", status=200)
    else:
        perm = perm.first()
        permutations_array = perm.all_permutations.split(' ')
        if word in permutations_array:
            permutations_array.remove(word)
        data = {'similar': permutations_array}
        updateLogs(start_time)
        return HttpResponse(json.dumps(data), content_type="application/json", status=200)


text:
Q: Multilevel covariance structure and more I have some doubts about the covariance structure in a multilevel model fitted in R (using the nlme package). I'm not an expert (just starting to learn statistics...), so I apologize if some of my questions seem evident. I've checked the previous posts and haven't found an answer.
I have data from an experiment in which we have registered physiological data from 30 subjects in 2 conditions (with 30 trials in each condition). These 30 trials are close in time, and we expected a higher correlation between closer trials, with the correlation decreasing as trials are further apart from each other. We are interested in the effect of condition, not in time effects. I think that the right way to analyze these data is to fit a multilevel model, in which TRIAL is a level 1 variable, SUBJECT is a level 2 variable, CONDITION is a fixed factor, and the DV is the physiological response (FR). The R command I'm using is:
lme(fixed= FR ~ CONDITION, data=mydata, random= ~ TIME | SUBJECT)

My (many) questions are both theoretical and practical:

*

*Which covariance structure lme does use by default? Is it a problem not to use the most appropriate covariance structure?

*I've read that an autoregressive covariance structure (AR1) refers to a constant variance at each time point and a weaker correlation as time points get further apart. My data only meets the second criterion. How can I know which covariance structure is right for my data? How important is it to the validity of the results?

*I'm only interested in the CONDITION effect, which is significant when I'm not including TIME in the model. I'm not interesting in TIME effects, nor I want to use the model to make a prediction, but only to check the significance of the CONDITION effects. Is it correct if I drop out TIME and fit a model only with CONDITION?
Thank you for your help!

A: You first point has been addressed by @Seth: the default is no within group correlation. Regarding your second point, I think it depends on the effect size of TIME. If the effect is minor compared to your other variables, like CONDITION and SUBJECT, the misfit should not be a problem. But if TIME is a major effect you will want your model to describe it well.
Now regarding your third question, if you drop TIME from the model by calling
lme(fixed= FR ~ CONDITION, data=mydata, random= ~ 1 | SUBJECT)

you remove the interaction term TIME*SUBJECT. So if TIME has the same effect for every subject, it's no big deal. However, if the response shows (or is expected to show) a particular behaviour for some people at some time (say some people get better and some get worse) then this will be "absorbed" in your other variables in ways that are difficult to predict (i.e. might make some terms significant and others non significant).
That you are not interested in TIME does not mean that you should leave it out of the model. Quite the contrary I would say. To give a heuristic example, in simple linear regression, you fit a slope and and intercept, but you are usually interested in the slope only. If you do not include the intercept term, you fit a a line through the origin. You can check by yourself that with this approach you will sometimes (for different clouds of points) reach the wrong conclusion: conclude that the slope is non null when it is and vice versa.
So if you have a doubt, keep TIME in but only focus one the estimates and p-values for CONDITION.

A: I'm not sure I can provide the kind of answer I'd like to, but I will try to throw out some pieces of information regarding your questions.
First, both @Seth and @gui11aume (+1 to each) have noted that lme() defaults to no within group correlations.  The question is why, and whether that's likely to be a problem.  I believe that the thinking is a properly specified multilevel model will account for the covariance amongst your observations such that the residuals are independent.  That's why the function was coded to expect no correlations.  That is, you may be OK.
Several of your questions concern the effect of having a misspecified variance/covariance structure (bearing in mind that this may not actually apply to you).  The estimation of your betas should be unaffected by this, that is, they should be unbiased.  However, the estimation of the variance of the sampling distributions will be inaccurate, that is, your p-values will be inaccurate.  Moreover, I believe that you cannot say a-priori whether they will be too high or too low.  If you are really concerned about these issues you can always use robust (a.k.a., 'sandwich') standard errors.  These are typically thought about in the context of generalized linear models, but they can be used elsewhere.  Check out the R package sandwich.  Note that if they are not necessary, you could be at risk of increased type II errors.
The standard AR(1) variance/covariance structure does assume homoskedasticity, so far as I know.  More restrictive, however, is that it assumes every observation was made at the appropriate time, and that all measurements are equally spaced in time.  These assumptions usually don't hold, even in the most fortuitous situations, and as such, the AR(1) variance/covariance structure is dangerous to assume.
Remember that the proper specification of the model for the means is crucial.  It is remotely possible that time is not relevant to the appropriate model of the mean, but it isn't very likely at all.  Leaving TIME out of the model risks the omitted variable bias.  Thus, dropping TIME is likely to yield both biased estimates of the means and invalid inferences.  This is just not worth gambling on.


text: Q: How can I store arbitrary data in LLVM metadata? I want to store a set of key-values within a module I am generating using the LLVM C++ API. I would like to store it as metadata, if possible. Is that possible with an unmodified version of LLVM, or would I have to modify it?


text:
Q: "Graining" effect when embedding PNG with alpha transparency I'm trying to add a transparent image over a pdf file with TCPDF. However the function only works, when I call
 $this->Image($markupfile, 0, 0,  $s['w'],$s['h'] , '', '', '', true, 55);

with a very low dpi (the last argument) of less than around 60. This results in the image below, which displays some kind of graining effect. I can't set the dpi higher, because this interrupts the php execution, which seems to be yet another problem.
Does anybody have any ideas what could be going wrong? Looking a the source of tcpdf it uses either the GD or the imagick library for embedding png.


text:
Q: Returning json response with status code and data in laravel 6 I tried searching for solutions on how to return json response in laravel but after trying few variations i was lost on this matter, an explanations would be nice:
why is it that whenever i add a status codes in the json() function like this
response()->json(['hello'=> $someErrors], 401)

I dont get the $someErrors data in the console log of my js code
but when i remove it and do it like
response()->json($someErrors);

or
response($someErrors);

i get my $someErrors data in the console log of my js code.
Thanks in advance!

A: I think you're not generating valid renounce to catch in your view. Try to through json exception:
$api_errors = $validator->errors();
throw new HttpResponseException(
    response()
    ->json($result, $api_errors)
    ->withHeaders(['Content-Type' => 'text/plain', 'charset' => 'utf-8'])
);


text:
Q: AngularJS + Jasmine Noob: How to access $scope in spec? This is my first time testing using Jasmine. I'm having trouble accessing the $scope variables in the spec. I have a failing test:
mysite ProductsDetailCtrl sets hey
  Expected undefined to be 1.
    Error: Expected undefined to be 1.

spec:
//= require helpers/load-angular-mysite-module
//= require products/controllers/products_detail_controller

describe('mysite', function() {
  var $rootScope, $scope, $controller;
  beforeEach(function() {
    module('mysite');
  });

  describe('ProductsDetailCtrl', function() {
    beforeEach(inject(function(_$rootScope_, _$controller_) {
      $rootScope = _$rootScope_;    // don't really
      $scope = $rootScope.$new();   // understand what's
      $controller = _$controller_;  // going on in this function

      controller = $controller('ProductsDetailCtrl', {
        '$rootScope': $rootScope,
        '$scope': $scope
      });
    }));

    it('sets hey', function() {
      expect($rootScope.hey).toBe(1);
    });
  });

});

controller:
app.controller('ProductsDetailCtrl', ['$scope', '$resource', function($scope, $resource) {
  $scope.hey = 1;
 ....

Could someone explain to me how I would access the scope?

A: You just have to check for the property heyin your $scope not in the $rootScope:
describe('mysite', function() {
  var scope, ProductsDetailCtrl;

  beforeEach(function() {
    module('mysite');
  });

  describe('ProductsDetailCtrl', function() {
    beforeEach(inject(function($controller, $rootScope) {
      // Create a mock scope for your controller.
      scope = $rootScope.$new();
      // Initialize the controller with the mocked scope.
      ProductsDetailCtrl = $controller('ProductsDetailCtrl', {
        $scope: scope
      });
    }));

    it('sets hey', function() {
      expect(scope.hey).toBe(1);
    });
  });

});


text:
Q: adding controls dynamically how to add dynamically a menupanel with menuitems inside a accordion using coolite controls toolkit.

A: you can try my sample here :
private void CreateMenu(int index, string title, string url, MenuPanel menuPanel, Panel panel)
{
     MenuItem menuItem = new MenuItem();
     menuItem.ID = "MenuItem" + index;
     menuItem.Text = title;
     menuItem.Listeners.Click.Handler += "addTab(#{TabPanel1},#{" + menuPanel.ID + "},'MenuItem" + index + "',' " + title + "',' " + url + "');";
     menuItem.Icon = Icon.ApplicationForm;

    menuPanel.Menu.Items.Add(menuItem);
    panel.BodyControls.Add(menuPanel);
    Accordion1.Items.Add(panel);
}

private void PopulateMenus()
{
      string[] menus = new string[] { null, "Menu 1", null, "Menu 2"};

      MenuPanel menuPanel = null;
      Panel panel = null;

      for (int i = 0; i < menus.Length; i++)
      {
         if (menus[i] == null)
         {
            panel = new Panel();
            panel.AutoScroll = true;
           panel.ID = "Menu" + i;
            panel.Title = menus[i + 1];
            panel.Border = false;
            panel.BodyStyle = "padding:6px;";
            panel.Icon = Icon.ApplicationCascade;

           menuPanel = new MenuPanel();
            menuPanel.AutoScroll = true;
            menuPanel.ID = "MenuPanel" + i;
            menuPanel.Border = false;
            menuPanel.BodyStyle = "padding:6px;";
            continue;
         }

          CreateMenu(i, "Sub-" + menus[i], "www.test.com", menuPanel, panel);
       }
}

Hope it helps.


text:
Q: getting input format So, I just buy introduction book for sas. But it only contain tons of examples with little/no explanation. I tried to find some tutorial online, but I can't find the explanation for this formatting. I just wonder what's the different between these two:
INPUT Name $16. Age 3. +1 height 5.1

I wonder, what does "." mean. What the different between:
INPUT Name $16

and
INPUT Name $ 1-16

what is the symbol "+1" mean?
what does "5.1" mean? how's that different from "5."? thx

A: Formats always contain periods; the period can serve to separate width from decimal, ie 5.1 is 5 total width, 1 decimal - so xxx.d (actually, -xx.d, but it will also display xxx.d correctly).  For character values and other values that cannot have decimal portions, there is never a number after the period, but it is still present; so DATE9. is a DATE formatted variable (specifically, looks like "19JAN2013") and is 9 characters long (as opposed to DATE7., or 19JAN13).
In general, SAS has many different input options.  Find a better book, or read the online documentation (http://support.sas.com/documentation/92/index.html or similar for your version of SAS).  input Name $16. inputs name as a 16 digit character variable.  You have a lot of variants of input options, so look at the documentation to find out more.
+1 specifically tells SAS to move the pointer forward one - so instead of 16 characters of Name, then 3 digits of Age, then 5 digits of Height, it skips a space between Age and Height; so NAMENAMENAMENAMEage heigh not NAMENAMENAMENAMEageheigh.

A: You can start here:
Input statement


text:
Q: How can I get the unchanged Box form of an arbitrary expression? One may observe that MakeBoxes does not give the actual Box form of various expressions:
MakeBoxes[{1*^4, 000123, a*b c}]

RowBox[{"{", RowBox[{"10000", ",", "123", ",", RowBox[{"a", " ", "b", " ", "c"}]}], "}"}]

The 1*^4 was expanded, the leading zeros of 000123 were stripped, and the distinction between * and (space) was lost.
Also, MakeBoxes doesn't like syntactically invalid or incomplete strings:
MakeBoxes[0001+`1,*^6*a b]

Syntax::sntxi: Incomplete expression; more input is needed.

How can one get the actual Box form visible with Show Expression (Ctrl+Shift+E) without copy & paste?

A: One approach that may be familiar to more experienced users is based on the input syntax described in String Representation of Boxes.

\(input\)                raw boxes

This appears to work but closer inspection shows that it is not exact:
"\({1*^4, 000123, a*b c}\)" // ToExpression

RowBox[{"{",RowBox[{"1*^4",",","000123",",",RowBox[{"a","*","b","c"}]}],"}"}]

RowBox[{"{",RowBox[{"1*^4",",","000123",",",RowBox[{"a","*","b"," ","c"}]}],"}"}]

(Copy & paste from Show Expression on the lower line.)
Greater changes are apparent in the invalid-expression example:
"\(0001+`1,*^6*a b\)" // ToExpression

RowBox[{RowBox[{"0001","+",RowBox[{"`","1"}]}],",",RowBox[{"*",RowBox[{"^","6"}],"*","a","b"}]}]

RowBox[{RowBox[{"0001","+","`1"}],",",RowBox[{"*",RowBox[{"^","6"}],"*","a"," ","b"}]}]

The other approach I know it to use $PreRead to capture the Box form input:
$PreRead = # /. {
     RowBox[{"raw", "[", raw__, "]"}] |
       RowBox[{raw__, "//", "raw"}] |
       RowBox[{"raw", "@", raw__}] :>
      ToString[Unevaluated[raw], StandardForm]
     } &;

Output still does not precisely match the Show Expression form but it is close:
raw[0001+`1,*^6*a b]

RowBox[{RowBox[{"0001","+","`1"}],",",RowBox[{"*",RowBox[{"^","6"}],"*","a","b"}]}]

RowBox[{RowBox[{"0001","+","`1"}],",",RowBox[{"*",RowBox[{"^","6"}],"*","a"," ","b"}]}]

The discrepancy actually ends up being advantageous as this is the form that is seen by CellEvaluationFunction and that was my original intent.
It is also more convenient than having to wrap input in ToExpression["\( \)"].
I wonder if there is not a FrontEnd function that already does this.

A: My other answer is a nice solution for interactively looking at boxes, but in the comments, Mr.Wizard seems to be indicating that he's more interested in programmatic usage, and that he's definitely interested in seeing the box form after the FE has stripped non-semantic boxes to send to the kernel.  So here's a totally different method for doing this which achieves those goals.
MathLink`CallFrontEnd[
 FrontEnd`UndocumentedTestFEParserPacket["a*b c+d", True]]

The first argument to UndocumentedTestFEParserPacket must be a string, so this solution precludes 2D input unless you formulate the 2D input using linear syntax.  The second argument indicates whether the result should strip non-semantic boxes in the same way that the FE does at Shift+Enter time.  True indicates that it should strip (note the return value does not include the space between b and c).  Replacing it with False would leave the non-semantic boxes exactly as if they were being written to a notebook file.
If you're wondering what a non-semantic box is, this includes non-semantic spaces and several different box types if they have StripOnInput set to true.  The list, and default values of StripOnInput options can be found in the Option Inspector (just search for StripOnInput). StyleBox also takes the StripOnInput option.  By default, StyleBox is stripped in math but not in 2D or 3D graphics.  Here's an example of StyleBox stripping.
MathLink`CallFrontEnd[
 FrontEnd`UndocumentedTestFEParserPacket[
  "\!\(\*StyleBox[\"x\",\"style\"]\)", True]]

returns just the x while
MathLink`CallFrontEnd[
 FrontEnd`UndocumentedTestFEParserPacket[
  "\!\(\*StyleBox[\"x\",\"style\",StripOnInput->False]\)", True]]

returns the full StyleBox.

A: Here's some code which produces an InputField and the box form of anything you type into the InputField as you type it:
DynamicModule[{boxes = ""},
 Column[{InputField[Dynamic[boxes], Boxes, ContinuousAction -> True],
   Dynamic[boxes, BaseStyle -> {ShowStringCharacters -> True}]}]]

The critical idea here is using a Boxes style InputField to get the box form, which you can then work with programmatically.
I might have come up with this idea on my own, but I should give credit to Jason Harris who gave a typesetting workshop today and had an example very close to this, so this was on my mind.