Q:

Player rewards in games where you normally have nothing to purchase

In many games there are rewards such as gold coins, points, etc. When these rewards can be used to purchase in-game items, it motivates the player to keep playing.
Let's say we have an online game, poker, Yatzy etc.  What type of reward would keep the players playing if there are few in-game items available to buy, or none at all?
What I am looking for is a reward system that entices the players to play more in a game environment where there isn't that much to purchase. For example, there isn't much to buy in a poker or Yatzy game with the gold you win.
I guess having some titles that are added to the userid is one way, or maybe purchasing a logo for the id... A leaderboard is another.
Any thoughts on this?

A:

There was a poker game - Governor of Poker - where you were making money to buy out whole Texas (I may exaggerate here), that was a funny idea, because it was giving you an objective.
Another thing that poker reminds me is strip poker! That's a great way to motivate players - not only in poker, stripping girls are welcomed everywhere (well, maybe not on a minigame made for a site about feminism). Just remember to comment this answer with link to your game when it's finished, so I don't miss it.
Some people simply implement score. It's especially nice if you can share it with others, and you will rather want to share "Yeaster Master" in a beer promotion game than "1539205", so coming up with funny rank names may pay off.
Similarly to above, a lot of games nowadays spend time on creating achievements, especially if you can share them on your blog, Facebook, forum signature etc.
Also a great reward for a player is new content unblocked - usually it's just a step forward in story of a RPG game, though it works also with lesser rewards in low budget games, like unblocking Hold'em variant in a poker game.
If you have other products, you can put some secret code for another game. Hackers won't take it from decompiled code, because they won't know it exists.
Edit: Krom Stern pointed out in comment section, it might be helpful to put more examples about the >>content unblocking<<. He's right, that the term "content" is vague, as it should be. Basically anything is content: soundtrack, background, model textures and game mechanics. If you, a player, a modder or a random generator create something - it's content. It may be counter-intuitive what kind of content may be a good reward. Some developers think only a content involved in game mechanics will meet player's satisfaction: a trinket increasing luck, an hourglass able to rewind some unfortunate events (drawing bad cards) etc. However, there are a number of "unlockables" invented by designers throughout the gaming history. Here are some relevant to a card game example supplied by question's author:

Codex - a book with trivia, where some facts (or parts of fictional story) are revealed,
Avatars - very rewarding if a forum or chat is connected with the game,
Card backs, as practiced by Blizzard in Hearthstone,
Similarly as above, alternative front look of cards could be a reward,
Different table, token, player avatars (as in heads near the table, representing the players) textures
Steam, Kongregate and other badges etc.

If you run out of things (or rather categories of things) to unlock, then you can also add another layer to the game, as in the game mentioned in first paragraph. For example, you could have a living room with space for various vanity items that represent your wealth in a more rewarding manner than a number.

A:

Achievements (wiki). Now they are everywhere: in MMOs, Online games, even Visual Studio has extensions with achievements system. Even StackOverflow has it! =)
[Kill 1000 rabits], [Win 20 poker games in a in a row], [Come online every  day for 1 year], [Write over 9000 stupid answers]...
They are just a pop up shiny boxes or a table in a player profile, but players just play achievements. Not sure why. You can add ranking table on a main page. Also you can make achievement points as base for another awards: titles, special avatars, badges as said Markus von Broady.

A:

Essentially, if you are not acquiring in game merchandise using the credits you earn, the only motivation for earning them is status. The game should create an environment in which the player wishes to be the wealthiest.
Try to set up leaderboards, or in some way allow the players to convey their achievement, that way they want to have more than everyone else.


Q:

'Uncaught ReferenceError: ... is not defined' when calling a class (defined in module) from a browser console, JS

I have a file class.js
            //implementation details
            const _stackCollection = new WeakMap();

            //interface
            export class Stack {

                constructor() {
                    _stackCollection.set(this, []);
                }

                get count() {
                    return _stackCollection.get(this).length;
                }

                pop() {
                    if (this.count === 0)
                        throw new Error('Nothing to pop');

                    return _stackCollection.get(this).pop();
                }

                peek() {
                    if (this.count === 0)
                        throw new Error('Nothing to peek');

                    return _stackCollection.get(this)[this.count - 1];
                }

                push(e) {
                    _stackCollection.get(this).push(e);
                    return;
                }

            }

and a module that imports given class looks like this
module.js:
   import {Stack} from './class.js';

The index.html looks like this:
    <!DOCTYPE html>

        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>

hello world

When I try to initialize the instance of Stack in a console I get the following error. There are many questions regarding the given error but I can not see anything would help me:
    const stack=new Stack()

    Uncaught ReferenceError: Stack is not defined
    at <anonymous>:1:13

A:

Declarations in a module are scoped to that module. If you want to access them, you need to import them.
To use such an export in your browser console, you need to import it or bind it to a global variable.
global (Note that this defeats the purpose of modules and should only be used for ad hoc testing)
export class A {}

// TODO: remove this
window.A = A;

With the proposed dynamic import syntax:
// browser console:
  import('./a.js').then(console.log);

With SystemJS
// browser console:
SystemJS.import('./a.js').then(console.log);


Q:

tab in Android - tabView or ActionBar

I want to do something like this
I have read through the tutorial about TabView and later aboout ActionBar and Fragments. I am confused.

Please can someone tells me which of the TabView or ActionBar will allow me to draw a Tab like in the given link?

A:

I think you are asking because of "More" tab. I believe it is tab view for sure.
This link show how to make it so.


Q:

Native Window: Release Handle On Close

I am currently working on a C# .NET Add-In for Microsoft Outlook.
The goal of the Add-In is, to capture the search input from the Outlook Instant Search, and show in a Custom Pane my own search results.
It works pretty well, and with subclassing the Outlook Window with a Native Window, I get the search string, and it already passes that into my panel.
The problem is now, that when you close the Add-In (via "File->Options->Add-Ins->COM Add-Ins", but not with the X in the pane), the Add-In gets terminated instantly and I can't call  searchboxWindow.ReleaseHandle() beforehand to restore my WndProc chain. Outlook simply crashes without any visible errors.
protected override void WndProc(ref Message m)
{
    base.WndProc(ref m);

    switch ((uint)m.Msg)
    {
        case WindowMessages.WM_DESTROY:
        case WindowMessages.WM_QUIT:
        case WindowMessages.WM_NCDESTROY:
            this.ReleaseHandle();
            return;

        case WindowMessages.WM_KEYUP:
        case WindowMessages.WM_LBUTTONDOWN:
        case WindowMessages.WM_RBUTTONDOWN:
            OnKeyUp();
            break;

        case WindowMessages.WM_EXITSIZEMOVE:
            OnResize();
            break;
    }
}

I already tried to listen to a few Window Messages that should be called when the Add-In gets closed, but these messages only appear when I close the Outlook in a normal way.
Also, the events in the main Add-In source file like AppDomain.CurrentDomain.ProcessExit, this.Shutdown, or ((Outlook.ApplicationEvents_10_Event)this.Application).Quit don't get called.
What event can I listen on that (reliably) gets fired when the Add-In is terminated? Are there some? If not, what alternatives to solve my problem do I have?

A:

SOLVED: Thanks to Hans Passant
It realy seems that the ThisAddIn_Shutdown Event is triggered when the Add-In is manually disconnect through the COM Add-ins dialog box.


Q:

Javascript - Find a deepest node in a binary tree

Problem Statement
Given the root of a binary tree, return a deepest node.
For example, in the following tree, return d.
    a
   / \
  b   c
 /
d

My Implementation
module.exports = {
    deepestNode: function deepestNode(node, level) {
        if (!level)
            level = 0;

        node.depth = level;

        if (!node.left && !node.right)
            return node;

        let deepestLeft, deepestRight = node;

        if (node.left)
            deepestLeft = deepestNode(node.left, level + 1);

        if (node.right)
            deepestRight = deepestNode(node.right, level + 1);

        if (deepestLeft.depth > deepestRight.depth)
            return deepestLeft;
        else
            return deepestRight;
    },
    TreeNode: (val) => {
        return {
            val: val,
            left: null,
            right: null
        }
    }
};

Test Class
const expect = require('chai').expect;
const deepestNode = require('../../src/google/deepestNode');

let a = deepestNode.TreeNode('a');
let b = deepestNode.TreeNode('b');
let c = deepestNode.TreeNode('c');
let d = deepestNode.TreeNode('d');

a.left = b;
b.left = d;
a.right = c;

expect(deepestNode.deepestNode(a).val).eq('d');

a = deepestNode.TreeNode('a');
expect(deepestNode.deepestNode(a).val).eq('a');

I am a Javascript newbie so any comments regarding either the algorithm itself or the use of Javascript is welcome.

A:

Here are my thoughts:

Don't mutate function parameters unless there is good reason to do so.
node.depth = level;

The above statement basically breaks the contract of the function. The function claims to locate the deepestNode, but in fact it does findDeepestNodeAndSetDeepestPropOnAllNodes (silly, but you get the idea). This could lead to confusing, subtle bugs for the client of your module and is a serious issue.
If you want to return the level in addition to the node itself, that's easily done by returning a {node, level} object pair which doesn't corrupt the reference to node. However, since the test suite disregards the level, I'd omit it since the function name makes no mention of this and it's not typically valuable information.
Always use braces for blocks of code:
if (deepestLeft.depth > deepestRight.depth)
    return deepestLeft;
else
    return deepestRight;

is clearer and less error-prone as:
if (deepestLeft.depth > deepestRight.depth) {
  return deepestLeft;
}

return deepestRight;

Use default parameters:
function deepestNode(node, level) {
    if (!level)
        level = 0;
...

can be
function deepestNode(node, level=0) {
...

Avoid excessive conditionals; it's possible to simplify 6 branches to 2, reducing the cognitive load required to understand the code. Re-write negative conditionals to be positive when possible.
For example,
if (!node.left && !node.right)
    return node;

can be eliminated. As a rule of thumb, I try to operate only on the current node when writing recursive functions unless I'm forced to do otherwise.
Avoid excessive references and intermediate variables. Consider:
let deepestLeft, deepestRight = node;
/* ... various conditionals that may or may not change where
   `deepestLeft`, `deepestRight` and `node` points to ... */

// later on, unclear state

As with conditionals, when you begin relying on aliases for objects, it becomes difficult to keep track of what's pointing where. Code like this should only be written if there's no way around it, which isn't the case here.
In fact, this line causes crashes when node.right is the only child of a node. You may have meant:
let deepestLeft = deepestRight = node;

Adding more thorough tests to your suite would help detect bugs like this.
As an aside, prefer const instead of let unless you have to reassign the variable.
Don't crash on undefined/null parameters if it's trivial to prevent.
node.depth = level; // boom if `node` is undefined

Here's a re-write. I wrote this as browser code, but you can dump it into module.exports:

const deepestNode = (node, deepest={level: -1}, level=0) => {
  if (node) {
    if (level > deepest.level) {
      deepest.node = node;
      deepest.level = level;
    }

    deepestNode(node.left, deepest, level + 1);
    deepestNode(node.right, deepest, level + 1);
  }

  return deepest.node;
};

class TreeNode {
  constructor(val, left=null, right=null) {
    this.val = val;
    this.left = left;
    this.right = right;
  }
}

const root = new TreeNode(1,
  new TreeNode(2,
    new TreeNode(4)
  ),
  new TreeNode(3)
);

console.log(deepestNode(root));

This function can also be written iteratively in a clean way, avoiding call stack overflow errors and function call overhead:
const deepestNode = node => {
  let deepest = {level: -1};
  const stack = [[node, 0]];

  while (stack.length) {
    const [curr, level] = stack.pop();

    if (curr) {
      if (level > deepest.level) {
        deepest = {node: curr, level: level};
      }

      stack.push([curr.left, level + 1], [curr.right, level + 1]);
    }
  }

  return deepest.node;
};


Q:

Update Content page Controls on Master Page Timer TIck

I have a master page it has
<asp:Timer ID="masterTimer" runat="server" Interval="1000" OnTick="masterTimer_Tick"/>
        <asp:UpdatePanel runat="server" ID="time" UpdateMode="Always" ChildrenAsTriggers="True">
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="masterTimer" EventName="Tick"/>
            </Triggers>
            <ContentTemplate>
                <asp:Label runat="server" ID="lblTime"></asp:Label>
            </ContentTemplate>
        </asp:UpdatePanel>

and in code behind i have simple
protected void masterTimer_Tick(object sender, EventArgs e)
        {
            this.lblTime.Text = DateTime.Now.ToString("ddd MMM dd yyyy h:mm:ss tt");
        }

In content page i have
Dictionary<Guid, string> data = dataClass.DataDictionary();

and then i am creating a dynamic server control of Label type in Default page (content page). Server control has property of Text. Now my problem is, on each tick it does read the correct data means data dictionary contains updated data and it does assign it to label text property but its not displaying the updated text.
I am creating my CustomeLabel like this
    CustomLabel newLabel = new CustomLabel
    {
        Text          = "Label",
        Width         = 200,
        Height        = 150,
    };
    this.Controls.Add(newLabel);

And below is the CustomLabel class derived from LinkLabel and it has below properties
public string Text { get; set; }
public int Width { get; set; }
public int Height { get; set; }

and
readonly LinkButton Label              = new LinkButton();

and
protected override void OnLoad(EventArgs e)
{
  Label.Text = Text;
}

protected override void Render(HtmlTextWriter output)
{
  base.Render(output);
}

I will appreciate if somebody tells me what i need to do

A:

This might do it for you:
Child page:
<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="ChildPage.aspx.cs" Inherits="ChildPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">

    <asp:UpdatePanel ID="MyUpdatePanel" runat="server">
        <ContentTemplate>
            <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder>
        </ContentTemplate>

    </asp:UpdatePanel>

</asp:Content>

public partial class ChildPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Label newLabel = new Label
        {
            Text = "Label",
            Width = 200,
            Height = 150,
        };
        newLabel.Text = "Label: " + DateTime.Now.ToString();

        PlaceHolder1.Controls.Add(newLabel);
    }
}


Q:

The activity doesn't go back to the previous one (using facebook sdk)

I m using facebook sdk to allow users to log into my app using their facebook account, I m using a fragment that launches an other activity after the login access, and it works fine. The issue is that this activity doesn't come back to the previous one. Facebook SDK 4.0 uses an other activity which is implemented in the SDK and it handles the login, does it have something to do with this issue.
The code I am using:
@Override
public void onResume() {
    super.onResume();
    profileTracker.startTracking();
    tokenTracker.startTracking();
    Profile profile = Profile.getCurrentProfile();
    if (profile != null) {
        Intent intent = new Intent(getActivity(), PlayingActivity.class);
        getActivity().startActivity(intent);
    }
}

A:

Do not start activity in onResume(), because every time you go back to the activity, onResume() would be called, then PlayingActivity would be launched if profile is not null.
Move following code to other places,
Profile profile = Profile.getCurrentProfile();
if (profile != null) {
    Intent intent = new Intent(getActivity(), PlayingActivity.class);
    getActivity().startActivity(intent);
}

Click to learn more about the Activity Lifecycle.


Q:

JQuery Calculate DIV width in pixels

Is it possible to get the actual width of an arbitrary DIV in pixels using JQuery w/out plugins? I'm interested in the following two scenarios:

DIV's width specified in percents, I need to walk up the tree remembering paddings and/or margins, find the first parents with the width in pixels and then walk down to my element applying those paddings and margins.
DIV is positioned absolutely using top, right, bottom and left CSS attributes, kind similar to the previous one, just to need to take these attributes into account.

A simple call for a DIV with width: 100%; returns 100, which isn't good enough for me.
Update 1 - the control, which width I measured was hidden at the time when I call control.width(), that's it really.

A:

if width() doesn't work as expected (a fiddle would help) use offsetWidth. Assuming you've a jQuery reference to the element
$('div').get(0).offsetWidth;

will return the width of the element in pixel


Q:

Toggle readonly option for a field based on condition option

In reading the documentation for condition option it only supports hide/show fields based on how the expression for condition evaluates. Looking to see how instead to make a field "read-only" when the condition is met as opposed to removing it from the view.

A:

If your condition is a function with no side-effects (i.e. its output only depends on inputs), you can watch for changes in inputs and re-evaluate condition.
Imagine you have a condition that something needs to display only if both first name and last name are filled in. Then, you can do something like this:

...

JavaScript:
function checkIfHaveFirstNameAndLastName() {
   $scope.hasFirstNameAndLastName = ($scope.firstName && $scope.lastName);
}

$scope.$watch('firstName', checkIfHaveFirstNameAndLastName);
$scope.$watch('lastName', checkIfHaveFirstNameAndLastName);

I was actually thinking about baking something like this into angular-schema-form because re-evaluation of evalExpr() becomes a problem once application grows in size.


Q:

Embed Unity inside iOS in own ViewController

Using Unity 2019.3.0f3 and its Unity as a library feature I'm trying to embed a Unity project inside my iOS application.
Unity officially only supports full screen rendering. Nevertheless I'm looking for a way around that restriction.
In previous versions of Unity i successfully used swift-unity to do the integration. Within this approach it is easy to just get the View where Unity is rendering to (using UnityGetGLView()). I had no problems regarding stability or resources.
Using the new library approach, every time I try to access the UnityView, unity forces it's complete Window as keyWindow.
I tried accessing the UnityView in my own ViewController using
if let unityView = UnityFramework.getInstance()?.appController()?.rootViewController.view {
    // insert subview at index 0 ensures unity view is behind current UI view
    view?.insertSubview(unityView, at: 0)
}

But that immediately activates the complete unity-window and hides my parenting UITabBarController.
Trying to make the UnityFramework.getInstance()?.appController()?.rootViewController a child of my UITabBarController failed with the same result.
Furthermore it is not possible to add a child ViewController. Only adding subviews seems possible.
Does anybody know where that window-behaviour is located or how i can access the UnityView (or the RootViewController) and use it freely?

A:

I found a solution to the problem based on this approach from the unity forum. Using this approach I'm able to use the UnityViewController as a child in my own TabBarController.
The approach is working for Unity 2019.3.0f3, but I'm not sure if it will work in future versions. It feels like Unity tries to actively prevent such use. Then again I found hints in comments in the library-code that would suggest that a modified ViewController-Hierarchy was at least contemplated e.g. in UnityAppController+ViewHandling.h. But the instructions are unclear and methods with the hinted names don't exist.

Solution
1. Create UnityEmbeddedSwift.swift
The official example App provided by Unity is a real mess. I ended up using the UnityEmbeddedSwift.swift from the linked forum post with additions for pausing. This class encapsulates all Unity-related functionality in one clean class.
//
//  UnityEmbeddedSwift.swift
//  Native
//
//  Created by NSWell on 2019/12/19.
//  Copyright © 2019 WEACW. All rights reserved.
//

//
//  Created by Simon Tysland on 19/08/2019.
//  Copyright © 2019 Simon Tysland. All rights reserved.
//

import Foundation
import UnityFramework

class UnityEmbeddedSwift: UIResponder, UIApplicationDelegate, UnityFrameworkListener {

    private struct UnityMessage {
        let objectName : String?
        let methodName : String?
        let messageBody : String?
    }

    private static var instance : UnityEmbeddedSwift!
    private var ufw : UnityFramework!
    private static var hostMainWindow : UIWindow! // Window to return to when exiting Unity window
    private static var launchOpts : [UIApplication.LaunchOptionsKey: Any]?

    private static var cachedMessages = [UnityMessage]()

    // MARK: - Static functions (that can be called from other scripts)

    static func getUnityRootViewController() -> UIViewController! {
        return instance.ufw.appController()?.rootViewController
    }

    static func getUnityView() -> UIView! {
        return instance.ufw.appController()?.rootViewController?.view
    }

    static func setHostMainWindow(_ hostMainWindow : UIWindow?) {
        UnityEmbeddedSwift.hostMainWindow = hostMainWindow
        let value = UIInterfaceOrientation.landscapeLeft.rawValue
        UIDevice.current.setValue(value, forKey: "orientation")
    }

    static func setLaunchinOptions(_ launchingOptions :  [UIApplication.LaunchOptionsKey: Any]?) {
        UnityEmbeddedSwift.launchOpts = launchingOptions
    }

    static func showUnity() {
        if(UnityEmbeddedSwift.instance == nil || UnityEmbeddedSwift.instance.unityIsInitialized() == false) {
            UnityEmbeddedSwift().initUnityWindow()
        }
        else {
            UnityEmbeddedSwift.instance.showUnityWindow()
        }
    }

    static func hideUnity() {
        UnityEmbeddedSwift.instance?.hideUnityWindow()
    }

    static func pauseUnity() {
        UnityEmbeddedSwift.instance?.pauseUnityWindow()
    }

    static func unpauseUnity() {
        UnityEmbeddedSwift.instance?.unpauseUnityWindow()
    }

    static func unloadUnity() {
        UnityEmbeddedSwift.instance?.unloadUnityWindow()
    }

    static func sendUnityMessage(_ objectName : String, methodName : String, message : String) {
        let msg : UnityMessage = UnityMessage(objectName: objectName, methodName: methodName, messageBody: message)

        // Send the message right away if Unity is initialized, else cache it
        if(UnityEmbeddedSwift.instance != nil && UnityEmbeddedSwift.instance.unityIsInitialized()) {
            UnityEmbeddedSwift.instance.ufw.sendMessageToGO(withName: msg.objectName, functionName: msg.methodName, message: msg.messageBody)
        }
        else {
            UnityEmbeddedSwift.cachedMessages.append(msg)
        }
    }

    // MARK - Callback from UnityFrameworkListener

    func unityDidUnload(_ notification: Notification!) {
        ufw.unregisterFrameworkListener(self)
        ufw = nil
        UnityEmbeddedSwift.hostMainWindow?.makeKeyAndVisible()
    }

    // MARK: - Private functions (called within the class)

    private func unityIsInitialized() -> Bool {
        return ufw != nil && (ufw.appController() != nil)
    }

    private func initUnityWindow() {
        if unityIsInitialized() {
            showUnityWindow()
            return
        }

        ufw = UnityFrameworkLoad()!
        ufw.setDataBundleId("com.unity3d.framework")
        ufw.register(self)
//        NSClassFromString("FrameworkLibAPI")?.registerAPIforNativeCalls(self)

        ufw.runEmbedded(withArgc: CommandLine.argc, argv: CommandLine.unsafeArgv, appLaunchOpts: UnityEmbeddedSwift.launchOpts)

        sendUnityMessageToGameObject()

        UnityEmbeddedSwift.instance = self
    }

    private func showUnityWindow() {
        if unityIsInitialized() {
            ufw.showUnityWindow()
            sendUnityMessageToGameObject()
        }
    }

    private func hideUnityWindow() {
        if(UnityEmbeddedSwift.hostMainWindow == nil) {
            print("WARNING: hostMainWindow is nil! Cannot switch from Unity window to previous window")
        }
        else {
            UnityEmbeddedSwift.hostMainWindow?.makeKeyAndVisible()
        }
    }

    private func pauseUnityWindow() {
        ufw.pause(true)
    }

    private func unpauseUnityWindow() {
        ufw.pause(false)
    }

    private func unloadUnityWindow() {
        if unityIsInitialized() {
            UnityEmbeddedSwift.cachedMessages.removeAll()
            ufw.unloadApplication()
        }
    }

    private func sendUnityMessageToGameObject() {
        if (UnityEmbeddedSwift.cachedMessages.count >= 0 && unityIsInitialized())
        {
            for msg in UnityEmbeddedSwift.cachedMessages {
                ufw.sendMessageToGO(withName: msg.objectName, functionName: msg.methodName, message: msg.messageBody)
            }

            UnityEmbeddedSwift.cachedMessages.removeAll()
        }
    }

    private func UnityFrameworkLoad() -> UnityFramework? {
        let bundlePath: String = Bundle.main.bundlePath + "/Frameworks/UnityFramework.framework"

        let bundle = Bundle(path: bundlePath )
        if bundle?.isLoaded == false {
            bundle?.load()
        }

        let ufw = bundle?.principalClass?.getInstance()
        if ufw?.appController() == nil {
            // unity is not initialized
            //            ufw?.executeHeader = &mh_execute_header

            let machineHeader = UnsafeMutablePointer<MachHeader>.allocate(capacity: 1)
            machineHeader.pointee = _mh_execute_header

            ufw!.setExecuteHeader(machineHeader)
        }
        return ufw
    }
}

2. Modify AppDelegate.swift
Sets window and launch options needed by UnityEmbeddedSwift
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        UnityEmbeddedSwift.setHostMainWindow(window)
        UnityEmbeddedSwift.setLaunchinOptions(launchOptions)

        return true
    }

3. Create RootTabBarController.swift
This class sets up the hierarchy.
It is important to use the UnityRootViewController right after calling UnityEmbeddedSwift.showUnity().
The Tab-Switching is not nice, but if it is missing Unity will pause (or freeze?) during loading. The timing seems to depend on the Unity-Projects loading time. It can be faster for small projects and needs more time for larger projects.
import UIKit

class RootTabBarController: UITabBarController, UITabBarControllerDelegate {

    var unityNC: UINavigationController?
    var nativeNC: UINavigationController?

    override func viewDidLoad() {
        super.viewDidLoad()

        delegate = self

        // start unity and immediatly set as rootViewController
        // this loophole makes it possible to run unity in the same window
        UnityEmbeddedSwift.showUnity()
        let unityViewController = UnityEmbeddedSwift.getUnityRootViewController()!
        unityViewController.navigationItem.title = "Unity"

        unityNC = UINavigationController.init(rootViewController: unityViewController)
        unityNC?.tabBarItem.title = "Unity"

        let nativeViewController = UIViewController.init()
        nativeViewController.view.backgroundColor = UIColor.darkGray
        nativeViewController.navigationItem.title = "Native"

        nativeNC = UINavigationController.init(rootViewController: nativeViewController)
        nativeNC?.tabBarItem.title = "Native"

        viewControllers = [unityNC!, nativeNC!]

        // select other tab and reselect first tab to unfreeze unity-loading
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: {
            self.selectedIndex = 1

            DispatchQueue.main.asyncAfter(deadline: .now() + 0.01, execute: {
                self.selectedIndex = 0
            })
        })
    }

    // MARK: - UITabBarControllerDelegate

    func tabBarController(_ tabBarController: UITabBarController, didSelect viewController: UIViewController) {
        // pause unity if unity-tab is not selected
        if viewController != unityNC {
            UnityEmbeddedSwift.pauseUnity()
        } else {
            UnityEmbeddedSwift.unpauseUnity()
        }
    }
}

4. Modify Main.storyboard
Modify the storyboard to start with the RootTabBarController.


Q:

Wait for a module to be loaded to execute the tests it contains

My unit tests are contained into a module that loads from an HTML page using SystemJS.
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/rxjs/bundles/Rx.js"></script>

<script src="node_modules/jasmine-core/lib/jasmine-core/jasmine.js"></script>
<script src="node_modules/jasmine-core/lib/jasmine-core/jasmine-html.js"></script>
<script src="node_modules/jasmine-core/lib/jasmine-core/boot.js"></script>

<script>
  System.config({
    defaultJSExtensions: true,
    map: {
      "angular2": 'http://localhost:8000/angular2',
      "rxjs": 'node_modules/rxjs'
    },
    packages: {
      angular2: {
        defaultExtension: 'js',
      }
    }
  });
  System.import('angular2/test/http/backends/xhr_backend_spec')
    .then((src) => {
      src.main();
    });
</script>

My page doesn't display any tests whereas my main method contains a test suite:
export function main() {
  console.log('in main');
  describe('XHRBackend', () => {
    (...)
  });
}

I put some traces and I check that the main function and the callback defined in the describe function are called. But the tests themselves aren't executed within the describe callback.
I guess that I need to wait for the module to be loaded before running Jasmine but I don't know how to configure this.
Thanks for your help!

A:

Tell Jasmine to run the imported tests with .then (window.onload)
<script>
  System.config({
  (...)
  System.import('angular2/test/http/backends/xhr_backend_spec')

      //  wait for all imports to load ...
      //  then re-execute `window.onload` which
      //  triggers the Jasmine test-runner start

     .then(window.onload)
     (...)
</script>

I read how to run Jasmine Tests on angular.io
https://angular.io/docs/ts/latest/testing/first-app-tests.html


Q:

Could Science and Philosophy be focused too much on physical states and not enough on dynamic processes?

Many times I've read about machines or processes being described as a collection of only physical states and not as a set of 'interacting' processes. A physical STATE is not a process which might have time-dependent or order-dependent qualities; that is a dynamic process with important properties that are not fully 'realised' until they interact in the 'entire' system in a specific scheduled fashion after certain other 'required' actions have occurred.
Maybe some important dynamic processes that are not reducible to physical states and that are not time or order dependent should be considered as basic qualities for system analysis. And not just a linear sequence of 'static' qualities that can not capture important time-dependent traits of a system. Could Scientific analysis be missing this point of view?

A:

Both state and process are important in science:

Isn't evolution a process?
Big-Bang cosmology is paradigmatically a process; especially when considered against Hoyles steady-state universe.
Quantum Mechanics is theorised as Quantum States and an Equation of Evolution.
Category Theory focuses on process (morphisms) against the state (sets)


Q:

Integration problem, stuck at this.

Here's the parametric equations:
$x = \sin (t)$
$y = \sin (2t)$
$ 0 \le t \le \frac{\pi}{2}$
(1) How would I find the area of the region bounded by the curve and the x axis.
(2) Volume of the solid formed when rotated $2\pi$ radians about x axis.

A:

Took me a while, but solved. Was stuck in the integration part to be specific.


Q:

Linq sub list Problem

I am very new to Linq and I am having trouble converting the following to a linq expression:
        Dim returnedInstructions As List(Of Integer) = New List(Of Integer)
        For Each j As Job In response.Jobs
            For Each i As Instruction In j.Instructions
                returnedInstructions.Add(i.InstructionId)
            Next
        Next

Any help appreciated.

A:

You want SelectMany.
List<int> returnedInstructions = response.Jobs
  .SelectMany(j => j.Instructions
    .Select(i => i.InstructionID))
  .ToList();

(and now in VB, which I don't know if this compiles)
Dim returnedInstructions = response.Jobs _
  .SelectMany( Function(j) j.Instructions _
    .Select( Function(i) i.InstructionID) ) _
  .ToList()


Q:

Require is not defined error in Visual Studio when using ReactJS

I have a helloworld.jsx file built successfully into a js file and is included in a page through the script tag.
When I run the page in Chrome, I get the following error. Should I include any other Bower package to use require.

Uncaught ReferenceError: require is not defined

var React = require('react');

var HelloWorld = React.createClass({displayName: "HelloWorld",
    render: function () {
        return (React.createElement("h1", null, "Hello World"));
    }
});

var parent = document.querySelector('#greeting');
React.renderComponent(React.createElement(HelloWord, null), parent);

A:

Take a look into getting started and see how to setup React for use in browser: http://facebook.github.io/react/docs/getting-started.html
In order to use require you need to setup browserify/webpack compilation in your development process, both of them properly transform require into single bundle file.


Q:

RStudio Error: STRING_ELT() can only be applied to a 'character vector', not a 'builtin'

Upon startup in RStudio. Before doing anything I get the following error display on the console window:
Error: STRING_ELT() can only be applied to a 'character vector', not a 'raw'

I'm working on a Windows 10 OS R version 3.2.2
How can I get rid of the message? How can I identify where the source of where this error is coming from?  I'm thinking it may have something to do with a previous session but I'm having trouble identifying the pattern for why this error occurs.

A:

In RStudio I went to Session - Clear Workspace
Then I went to Session - Terminate R
Then I went to Session - Restart R
Then I closed the program and restarted it.  Some how that fixed the issue.


Q:

Can I stop events from being dragged past start and end boundaries?

When events are draggable in fullcalendar, I can drag them up past the start hour and down past the end hour. This happens with a minTime and maxTime configured and when they are not configured (i.e. midnight to midnight). I need events to not be allowed to be dragged past the hour boundaries of the day or configured time range.
I don't see anything in the documentation about stopping this behavior. Has anyone run into this issue and come up with a solution or does anyone have a solution to resolve this problem?

A:

After some research and experimenting, I have discovered the solution to this problem is by using the containment option in the jQuery UI draggable plugin.
To stop the behavior described in the question, follow these steps:

Search for the function called draggableSlotEvent.
Under it, find eventElement.draggable({.
Place the following line as another option: containment: ".fc-agenda-body table",

You will now be unable to drag events past the hour boundaries.


Q:

Google charts - set max of one column

Is it possible to set a maxValue on one bar out of a "Material column charts"
For example over the series or axis.
I tried this:
vAxis: {
  viewWindow: { max: [100] },
  format: '000'
}

but it changes all columns

A:

you would need to isolate the bar on a separate axis,
use the series option to assign, and vAxes for specific settings...
  series: {
    0: {
        targetAxisIndex: 0
    },
    1: {
        targetAxisIndex: 1
    }
  },
  vAxes: {
    0: {
      viewWindow: {
        max: 120
      },
      format: '000'
    },
    1: {
      viewWindow: {
        max: 100
      },
      format: '000'
    }
  }

see following working snippet...

google.charts.load('current', {
  callback: function () {
    var data = new google.visualization.DataTable();
    data.addColumn('number', 'x');
    data.addColumn('number', 'y0');
    data.addColumn('number', 'y1');
    data.addRows([
      [0, 96, 80.8],
      [1, 97, 80.8],
      [2, 98, 69.5],
      [3, 99, 57],
      [4, 100, 18.8],
      [5, 101, 17.6],
      [6, 102, 13.6],
      [7, 103, 12.3],
      [8, 104, 29.2],
      [9, 105, 42.9]
    ]);

    var options = {
      height: 500,
      series: {
        0: {
            targetAxisIndex: 0
        },
        1: {
            targetAxisIndex: 1
        }
      },
      vAxes: {
        0: {
          viewWindow: {
            max: 120
          },
          format: '000'
        },
        1: {
          viewWindow: {
            max: 100
          },
          format: '000'
        }
      }
    };

    var chart = new google.charts.Line(document.getElementById('chart_div'));
    chart.draw(data, google.charts.Line.convertOptions(options));
  },
  packages: ['line']
});

note: must use google.charts.Line.convertOptions to get desired result...


Q:

Excel formula - index match address indirect rank.avg

Need help crafting formula.
I have data in SQL, exporting to excel. In excel have formula's to determine rank of parts based on values in a certain week in a range/array. The columns are weekly buckets, and each time I export, the weekly buckets change (no dates in the past). I would like the rank to remain fixed a specific date, but each export per week the specific column comes inward by 1 column.
I need an excel formula which finds the position of the specific value in the weekly bucket array. After this is determined, I need another formula to convert this column address (e.g. "AX") to be referenced by the rank.avg function.
I am guessing this is some combination of match, index, cell, indirect, & rank.avg. So far I have tried just the first part and cannot get cell("col",(index(match))) to return the letter values of the column it is in. It returns the # of the column instead.
Here is example
  A       B        C         D
1 Part    Rank(C)  11/28/17  12/04/17
2 Part A  1        $100      $100
3 Part B  2        $50       $125
4 Part C  3        $25       $200

Column B has the rank formula which is determining the rank of the parts (A,B,C) from column C. Column C is determining from hardcoding go to the value 11/28/17.
I am stuck at =CELL("address",INDEX(C1:D1,1,MATCH(43067,C1:D1,0))). This returns $C$1 when I just want $C or just C. Afterwards I intend to use this with indirect to be able to pass it through the rank function. Any assistance would be greatly appreciated where someone can fill the gap on the formula or come up with an easier way to do this.
Nick

A:

Yes get rid of ADDRESS and INDIRECT and just put the column in a COUNTIF formula.
ADDRESS and INDIRECT are volatile.  This is an non-Volatile and non-Array formula that does what you want in one step:
=COUNTIF(INDEX(C:D,2,MATCH(43067,$C$1:$D$1,0)):INDEX(C:D,1040000,MATCH(43067,$C$1:$D$1,0)),">" & INDEX(C:D,ROW(),MATCH(43067,$C$1:$D$1,0))) + 1


Q:

How do I finalize a class based Saga, so that it is deleted from the SQL database (EF Core)?

I am trying to learn more about Mass Transit as we are thinking about adopting it.  I now have the class based Saga below, which works as expected:
public class EchoSaga : ISaga,
        InitiatedBy<TextEntered>,
        Orchestrates<TextEchoStart>,
        Orchestrates<EchoEnd>
    {
        public Guid CorrelationId { get; set; }
        public string CurrentState { get; set; }
        public string Text { get; set; }

        public Task Consume(ConsumeContext<TextEntered> context)
        {
            CurrentState = "Entered";
            Text = context.Message.Text;
            return Task.CompletedTask;
        }

        public Task Consume(ConsumeContext<TextEchoStart> context)
        {
            CurrentState = "Start";
            Text = context.Message.Text;
            return Task.CompletedTask;
        }

        public Task Consume(ConsumeContext<EchoEnd> context)
        {
            CurrentState = "End";
            Text = context.Message.Text;
            return Task.CompletedTask;
        }
    }

A class based Saga is different to a state machine Saga and is described more in the docs here in the Saga section: http://masstransit-project.com/MassTransit/understand/key-ideas.html.
How do I mark the Saga as finalized after EchoEnd is consumed so it is deleted from the database (I have already setup the repository)? If I was using a state machine Saga, then I could do this:
.Finalize()
.SetCompletedWhenFinalized()

How do I do this with a class based Saga?
I realise I may be going backwards a bit here, however I am trying to learn how Mass Transit started and where it is now to see if it meets our requirements.  Very pleased with it so far.

A:

If you cast the ConsumeContext to SagaConsumeContext<TSaga, TMessage>, there is a SetCompleted method which signals the saga is complete and can be removed from the repository.
You may need to use context.GetPayload<SagaConsumeContext<TSaga, TMessage>>() if casting directly doesn't work (due to proxy use in the pipeline).


Q:

Pipe multiple files into one tar gz

I'd like to call mysqldump to create multiple backup files and then archive them in one tar.gz.
I am following this tutorial on mysqldump part: http://dev.mensfeld.pl/2013/04/backup-mysql-dump-all-your-mysql-databases-in-separate-files/ (at the end, it calls mysqldump in a loop for every database and creates one file at a time)
I can just save all files in temporary directory and 'then' put them into the archive, however, is there anyway how to skip this unnecessary temporary-directory part? I tried to learn about named pipes, thinking they may be what I need, however, haven't really understood them.

A:

You could use the -r flag to tar to append a file to an existing archive.  Since it's legal to append to an empty or non-existent archive, you could modify the looped instruction to be something like
$MYSQLDUMP --force --opt --user=$MYSQL_USER -p$MYSQL_PASSWORD --databases $db > "$BACKUP_DIR/mysql/$db"
tar rvf /path/to/tar.file "$BACKUP_DIR/mysql/$db" && rm "$BACKUP_DIR/mysql/$db"

The file will have to exist temporarily, as it needs to have a filename inside the tar index for extraction purposes (if you sent all the files to it via a pipe, think about how they might extract) - but you don't need to collect them all together then tar them all up.


Q:

copy newest files to another directory via ssh

I want to copy the files that were created during the last 3 days from one directory to another.
I'm using the command find . -mtime -3 to list the latest files but how do I copy then to another directory?
Thanks!

A:

This answer should help you
find . -mtime -3 -exec cp {} /destinationfolder  \;


Q:

NUnit Test Per Database Row?

Edit: I am super new to NUnit.
I don't know if this is possible, but I'll go ahead and explain what I'm trying to do.
I want to create a test fixture that runs a test with 5 different types of inputs that come from a database.
TestFixture
    Test using input1
    Test using input2
    Test using input3
    Test using input4
    Test using input5

This way, I can see from the NUnit GUI exactly which input is causing the failure, but I don't know how to do this.  Currently, I have something set up like this:
[TestFixture]
public class Tester{
    [Test]
    public void RunTest(){
        var inputs = db.inputs.where(a=>a.id < 6).ToList();
        bool testSuccess=true;
        foreach(var input in inputs){
            bool success = RunTheTest(input);
            if(success==false){
                testSuccess=false;
            }
        }
        //Tell NUnit that the entire test failed because one input failed
    }
}

In this case, in NUnit, I see:
Tester
    RunTest

And even though RunTest tries 5 different inputs, I only know if there was one or more inputs that failed, but I have no idea of which input failed.  Basically what I'm asking is if it's possible to dynamically create tests that show up in the NUnit GUI based on whatever I want to grab from the database.

A:

Look at the TestCaseSource attribute.  This will let you define another method that, at runtime, will create test cases for each item returned from the source method.

A:

Inside the foreach loop you can do
Assert.True( success, string.Format("Input: {0}", input ));
Alternately you can try the ValueSourceAttribute with a sourceType being a helper class that has a method that returns an IEnumerable named sourceName. The implementation of this method should fetch the input values from DB.


Q:

Safe to have multiple processes writing to the same file at the same time? [CentOs 6, ext4]

I'm building a system where multiple slave processes are communicating via unix domain sockets, and they are writing to the same file at the same time.  I have never studied filesystems or this specific filesystem (ext4), but it feels like there might be some danger here.
Each process writes to a disjoint subset of the output file (ie, there is no overlap in the blocks being written).   For example, P1 writes to only the first 50% of the file and P2 writes only to the second 50%.  Or perhaps P1 writes only the odd-numbered blocks while P2 writes the even-numbered blocks.
Is it safe to have P1 and P2 (running simultaneously on separate threads) writing to the same file without using any locking?  In other words, does the filesystem impose some kind of locking implicitly?
Note: I'm unfortunately not at liberty to output multiple files and join them later.
Note: My reading since posting this question does not agree with the only posted answer below.  Everything I've read suggests that what I want to do is fine, whereas the respondent below insists what I am doing is unsafe, but I am unable to discern the described danger.

A:

What you're doing seems perfectly OK, provided you're using the POSIX "raw" IO syscalls such as read(), write(), lseek() and so forth.
If you use C stdio (fread(), fwrite() and friends) or some other language runtime library which has its own userspace buffering, then the answer by "Tilo" is relevant, in that due to the buffering, which is to some extent outside your control, the different processes might overwrite each other's data.
Wrt OS locking, while POSIX states that writes or reads less than of size PIPE_BUF are atomic for some special files (pipes and FIFO's), there is no such guarantee for regular files. In practice, I think it's likely that IO's within a page are atomic, but there is no such guarantee. The OS only does locking internally to the extent that is necessary to protect its own internal data structures. One can use file locks, or some other interprocess communication mechanism, to serialize access to files. But, all this is relevant only of you have several processes doing IO to the same region of a file. In your case, as your processes are doing IO to disjoint sections of the file, none of this matters, and you should be fine.

A:

no, generally it is not safe to do this!
you need to obtain an exclusive write lock for each process -- that implies that all the other processes will have to wait while one process is writing to the file.. the more I/O intensive processes you have, the longer the wait time.
it is better to have one output file per process and  format those files with a timestamp and process identifier in the beginning of the line, so that you can later merge and sort those output files offline.
Tip: check the file format of web-server log files -- these are done with the time-stamp at the beginning of the line, so they can be later combined and sorted.

EDIT
UNIX processes use a certain / fixed buffer size when they open files (e.g. 4096 bytes), to transfer data to and from the file on disk. Once the write-buffer is full, the process flushes it to disk -- that means: it writes the complete full buffer to disk!  Please Note here that it is happening when the buffer is full! -- not when there is an end-of-line! That means even for a single process which writes line-oriented text data to file, that those lines are typically cut somewhere in the middle at the time the buffer is flushed. Only at the end, when the file is closed after writing, can you assume that the file contains complete lines!
So depending on when your process decide to flush their buffers, they write at different times to the file -- e.g. the order is not deterministic / predictable When a buffer is flushed to file, you can not assume that it will only write complete lines -- e.g. it will usually write partial lines, thereby messing up the output if several processes flush their buffers without synchronization.
Check this article on Wikipedia: http://en.wikipedia.org/wiki/File_locking#File_locking_in_UNIX
Quote:

The Unix operating systems (including Linux and Apple's Mac OS X,
  sometimes called Darwin) do not normally automatically lock open files
  or running programs. Several kinds of file-locking mechanisms are
  available in different flavors of Unix, and many operating systems
  support more than one kind for compatibility. The two most common
  mechanisms are fcntl(2) and flock(2). A third such mechanism is
  lockf(3), which may be separate or may be implemented using either of
  the first two primitives.

You should use either flock, or Mutexes to synchronize the processes and make sure only one of them can write to the file at a time.
As I mentioned earlier, it is probably faster, easier and more straight-forward to have one output file for each process, and then later combine those files if needed (offline). This approach is used by some web-servers for example, which need to log to multiple files from multiple threads -- and need to make sure that the different threads are all high-performing (e.g. not having to wait for each other on a file lock).

Here's a related post: (Check Mark Byer's answer! the accepted answer is not correct/relevant.)
Is it safe to pipe the output of several parallel processes to one file using >>?

EDIT 2:
in the comment you said that you want to write fixed-size binary data blocks from the different processes to the same file.
Only in the case that your block size is exactly the size of the system's file-buffer size, could this work!
Make sure that your fixed block-length is exactly the system's file-buffer size. Otherwise you will get into the same situation as with the not completed lines. e.g. if you use 16k blocks, and the system uses 4k blocks, then in general you will see 4k blocks in the file in seemingly random order -- there is no guarantee that you will always see 4 blocks in a row from the same process


Q:

How to search in a SQLite database in android?

I'm making a database for storing the information of the contacts. Because I'm new to android, I used a code found from the Internet. However, it has errors and when run it app crashes.
Here is the code for database :
Storage Manipulator
public class FriendStorage extends SQLiteOpenHelper {

public FriendStorage(Context context, String name, SQLiteDatabase.CursorFactory factory, int version){
    super(context, name, factory, version);
}

public static final String Database_name = "net.Friend.db";
public static final int Database_version = 1;

public static final String _ID = "_id";
public static final String Table_Friend = "Table_friend";
public static final String Username = "username";
public static final String PhoneNumber = "phoneNumber";

private static final String TABLE_FRIEND_CREATE =
        "CREATE TABLE " + Table_Friend
                + " (" + _ID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + Username + " VARCHAR(25), "
                + PhoneNumber + " VARCHAR(25)";

public static final String Table_Friend_Drop = "DROP TABLE IF EXISTS" + Table_Friend;

@Override
public void onCreate(SQLiteDatabase db) {
    db.execSQL(TABLE_FRIEND_CREATE);
}

public void insert(String username, String phoneNumber){
    long rowId;
    try {

        SQLiteDatabase db = getWritableDatabase();
        ContentValues contentValues = new ContentValues();
        contentValues.put(Username, username);
        contentValues.put(PhoneNumber, phoneNumber);
        rowId = db.insert(Table_Friend, null, contentValues);

    }catch (Exception e){
        e.printStackTrace();
    }
}

public Cursor get(){
    Cursor cursor;
    SQLiteDatabase db = getReadableDatabase();
    String selectQuery = "SELECT * FROM" + Table_Friend;
    cursor = db.rawQuery(selectQuery, null);
    return cursor;
}

public Cursor Update(String preUsername, String prePhoneNumber, String newUsername, String newPhoneNumber){
    Cursor cursor;
    SQLiteDatabase db = getWritableDatabase();
    String updateTable = "UPDATE" + Table_Friend + "SET" + Username + " = " + newUsername
            + "AND" + PhoneNumber + " = " + newPhoneNumber + "WHERE" + Username + " = "
            + preUsername + "AND" + PhoneNumber + " = " + prePhoneNumber;
    cursor = db.rawQuery(updateTable, null);
    return cursor;
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    db.execSQL(Table_Friend_Drop);
}

}

and in the Main Activity i use get function to search in database.
MainActivity
FriendStorage friendInfoStorage = new FriendStorage(this, "net.Friend.db", null, 1);
cursor = friendInfoStorage.get();
int noOfFriends = 0;
if (cursor.getCount() > 0) {
    cursor.moveToFirst();
    while ((!cursor.isAfterLast()) && (noOfFriends < cursor.getCount())) {
        if (noOfFriends == 0) {
            Myself.setUsername(cursor.getString(1));
            Myself.setPhone_Number(cursor.getString(2));
        } else {
            User.setUsername(cursor.getString(1));
            User.setPhone_Number(cursor.getString(2));
            Friends.add(User);
        }
        noOfFriends++;
        cursor.moveToNext();
    }
}
friendInfoStorage.close();

Error is this :
07-12 03:11:14.024 14157-14157/net.network.alire.clientchat E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          Process: net.network.alire.clientchat, PID: 14157
                                                                          java.lang.RuntimeException: Unable to start activity ComponentInfo{net.network.alire.clientchat/net.network.alire.clientchat.MainActivity}: android.database.sqlite.SQLiteException: near ")": syntax error (code 1): , while compiling: CREATE TABLE Table_friend (_id INTEGER PRIMARY KEY AUTOINCREMENT, username VARCHAR(25), phoneNumber VARCHAR(25)
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2329)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2389)
                                                                              at android.app.ActivityThread.access$900(ActivityThread.java:147)
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at android.os.Looper.loop(Looper.java:135)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at java.lang.reflect.Method.invoke(Method.java:372)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)
                                                                           Caused by: android.database.sqlite.SQLiteException: near ")": syntax error (code 1): , while compiling: CREATE TABLE Table_friend (_id INTEGER PRIMARY KEY AUTOINCREMENT, username VARCHAR(25), phoneNumber VARCHAR(25)
                                                                              at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method)
                                                                              at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:891)
                                                                              at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:502)
                                                                              at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588)
                                                                              at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58)
                                                                              at android.database.sqlite.SQLiteStatement.<init>(SQLiteStatement.java:31)
                                                                              at android.database.sqlite.SQLiteDatabase.executeSql(SQLiteDatabase.java:1674)
                                                                              at android.database.sqlite.SQLiteDatabase.execSQL(SQLiteDatabase.java:1605)
                                                                              at net.network.alire.toolBox.FriendStorage.onCreate(FriendStorage.java:36)
                                                                              at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:251)
                                                                              at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:187)
                                                                              at net.network.alire.toolBox.FriendStorage.get(FriendStorage.java:56)
                                                                              at net.network.alire.clientchat.MainActivity.onCreate(MainActivity.java:52)
                                                                              at android.app.Activity.performCreate(Activity.java:5933)
                                                                              at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
                                                                              at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2282)
                                                                              at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2389)
                                                                              at android.app.ActivityThread.access$900(ActivityThread.java:147)
                                                                              at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1296)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                              at android.os.Looper.loop(Looper.java:135)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5254)
                                                                              at java.lang.reflect.Method.invoke(Native Method)
                                                                              at java.lang.reflect.Method.invoke(Method.java:372)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:898)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:693)

Can anyone tell me what is wrong with the code?
thanks in advance

A:

There is a ")" missing caracter in your create statement.
You should use TEXT instead of varchar with SQLite.
You should not use AUTOINCREMENT. It is implicitly implemented in the PRIMARY KEY with SQLite.


Q:

Select and order parent record by child attribute Ruby on Rails

I have two ruby classes, Jobs and Listings.
Listing attributes: job_id, live_date, is_active
Job attributes: title, description, category
If I want to retrieve the details of 2 jobs from a single category where the associated listing live date's are the 2 most recent and the listing is active is there an efficient one-liner of Ruby that I could use?
At the moment I am looking at looping over things multiple times and I imagine there might be a more efficient way of doing this.
Desired Output
Two job results where the listing is both active and the live_dates are the most recent ones. (A job in this instance will only ever have 1 active listing.)

@jobs = [
  {
    title: 'Job Title',
    description: 'Job Description',
    category: 'marketing'
  },
  {
    title: 'Job Title',
    description: 'Job Description',
    category: 'marketing'
  }
]

A:

I believe you should be able to use the following. It's untested so might need a tweak or two, but should return the two jobs you've requested:
Job.eager_load(:listings).order("listings.live_date DESC").where(category: "your category", listings: { active: true }).first(2)

To break this down:

eager_load preloads your listings, so you can use them in your query. If you're not using them for anything else, outer_joins might be a better choice and more performant
order applies directions to the ORDER BY element of the generated SQL
the where clause lets you query the jobs, as well as the associated listings by passing the hash specified as a value
first(2) returns the first two records, in this case the desired ones due to the order in place


Q:

Lost all stickies in OSX

Possible Duplicate:
How to recover deleted text inside Mac OS X sticky notes.

I had a lot of stickies with a lot of information. I clicked on stickies to open them up, and a blank sticky appeared. All the stickies are gone. How could this have happened? Is there a way to get them back?

A:

The stickies live in ~/Library/StickiesDatabase.  Worse come to worst, I hope you have a backup.  If it's corrupted, there's a slight chance you can get things back out of it with strings in a Terminal window.


Q:

How to pull the day of the year from a Date in groovy

In Groovy, there are shortcuts for finding various common variables for Date objects such as those listed below.
Date now = new Date()
Integer year = now.year + 1900
Integer month = now.month + 1
Integer day = now.date
Integer hour = now.hours
Integer minute = now.minutes

What is the shortcut for getting the day of the year?

A:

The short answer to this question is "There isn't a shortcut" but the long answer adds "...but you can make one!"
Without any modifications you can access the day of the year from a date object with the following code:
Date now = new Date()
Integer dayOfYear = now[Calendar.DAY_OF_YEAR]

However if your code will be accessing that variable frequently, you can modify the Date class to add that property directly using the ExpandoMetaClass as follows:
Date.metaClass.getDayOfYear << { -> delegate[Calendar.DAY_OF_YEAR]}
Date now = new Date()
assert now[Calendar.DAY_OF_YEAR] == now.dayOfYear

More information on how to add properties with the ExpandoMetaClass can be found in the Groovy documentation at http://www.groovy-lang.org/metaprogramming.html#metaprogramming_emc


Q:

How to set delay in vbscript

How to set delay in vbscript?
WScript.Sleep(100) does not work on Windows XP, Vista.

A:

Work this end (XP).
Create a new file, call it test.vbs.  Put this in it.
WScript.Sleep 1000
MsgBox "TEST"

Run it, notice the delay before the message box is shown.
Note, the number is in Milliseconds, so 1000 is 1 second.

A:

If you're trying to simulate a sleep delay in VBScript but WScript is not available (eg: your script is called from Microsoft's BGInfo tool), then try the following approach.
The example below will delay until 10 seconds from the moment the instruction is processed:
Dim dteWait
dteWait = DateAdd("s", 10, Now())
Do Until (Now() > dteWait)
Loop

A:

if it is VBScript, it should be
WScript.Sleep 100

If it is JavaScript
WScript.Sleep(100);

Time in milliseconds. WScript.Sleep 1000 results in a 1 second sleep.


Q:

jQuery mobile login, php, cookies not working

I'm building web app aas my major project for degree. Simple login was working but now I'm trying to implement cookies and my script is not working for some reason. I need to find out why, but can't do for last 2h. Here is my question:
From login form variables are passed into my login script (no security for password or jql injection was implemented so far), when I press login errors comes up, "Error Loading Page", this is login script:
session_start();

$username = $_GET["name"];
$password = $_GET["password"];
$remember_me = $_GET['remember_me'];

include('mysql_connection.php');
mysql_select_db("jzperson_imesUsers", $con);

$res1 = mysql_query("SELECT * FROM temp_login WHERE username='$username' AND password='$password'");
$count1=mysql_num_rows($res1);

if(isset($_COOKIE['usr_IMes']) && isset($_COOKIE['psw_IMes'])){
                    $user_n = $_COOKIE['usr_IMes'];
                    $pasw_n = $_COOKIE['psw_IMes'];

                    $res2 = mysql_query("SELECT * FROM temp_login WHERE username='$user_n' AND password='$pasw_n'");
                    $count2=mysql_num_rows($res2);

                    if($count2 == 1){

                                    $_SESSION['username'] = $user_n;

                                    header('Location: http://imes,jzpersonal.com/userpanel.php');

                    }else {
                                    setcookie('usr_IMes', $user_n, time() - 31*24*60*60);
                            setcookie('psw_IMes', $pasw_n, time() - 31*24*60*60);

                                    header('Location: http://imes,jzpersonal.com/index.html');
                    }

}else{

if($count1==1){
    $_SESSION['username'] = $username;

    if(isset($remember_me)){

setcookie('usr_IMes', $username, time() + 30*24*60*60);
setcookie('psw_IMes', $password, time() + 30*24*60*60);

header("Location: http://imes.jzpersonal.com/userpanel.php");
    }else{

      header("Location: http://imes.jzpersonal.com/userpanel.php");

   }
}else{
    $login = "failed";
}
}

Can anyone see problem in my script? In login part? If not here is my authentication script on the start of every page, maybe my error is there:
session_start();

if(isset($_COOKIE['usr_IMes']) && isset($_COOKIE['psw_IMes'])){
                    $user_n = $_COOKIE['usr_IMes'];
                    $pasw_n = $_COOKIE['psw_IMes'];

                    $res2 = mysql_query("SELECT * FROM temp_login WHERE username='$user_n' AND password='$pasw_n'");
                    $count2=mysql_num_rows($res2);

                    if($count2 == 1){
                                    header('Location: http://imes,jzpersonal.com/userpanel.php');
                    }else {
                                    setcookie('usr_IMes', $user_n, time() - 31*24*60*60);
                            setcookie('psw_IMes', $pasw_n, time() - 31*24*60*60);

                                    header('Location: http://imes,jzpersonal.com/index.html');
                    }

}else{

if(!isset($_SESSION['username']))
{
header('Location: http://imes.jzpersonal.com/index.html');
}

if(empty($_SESSION['username']))
{
header('Location: http://imes.jzpersonal.com/index.html');
}
}

Hope some error will be found, thank you for all your help.

A:

The redirect is a bad url: http://imes,jzpersonal.com/userpanel.php - this would give you your "error loading page". Besides that, you should NEVER store username/password in cookies - it is a terrible practice because cookies can be viewed on the machine. Also, you are using the original PHP MySQL API which is deprecated - you should be using PDO or mysqli.


Q:

Read Json file using Java

I have a JSON file look like:

[[10,5,0,...,1,8], [3,6,3,...,6,3], [15,7,2,...,1,1], [8,7,4,...,8,3],
  [...], [6,11,0,...,5,1]]

nXm matrix. (n and m is unknown).
I want to manipulate(do calculation) on Java. I was thinking to read/input it into 2D array in Java. Do I treat JSON file same as text file using BufferReader or is there a easier way to read/manipulate it on Java? How should I create 2d array with unknown size?
Thank you

A:

You could use this library:
http://www.json.org/java/
Then you can read the file into a String used a BufferedReader, close the reader and do something like this:
JSONArray ja = new JSONOArray(string);
int[][] result = new int[ja.length()][];
for (int i = 0; i < ja.length(); i++) {
    JSONAarray ja2 = ja.getJSONArray(i);
    result[i] = new int[ja2.length()];
    for (int j = 0; j < ja2.length(); j++) {
        result[i][j]=ja2.getInt(j);
    }
}

I haven't tested this code, and you also might want to add some error checking and extract local variables, depending on how sure you are the file is in the right format. This does not assume your file contains a rectangular matrix.


Q:

How to select records from table for a given date using sql server 2008

I have a table in sql server
News(News_ID,Title,Article,Attatchment,Date)
I want to select all records of News table for any date provided by the user from asp.net c# using calender extender. The Date column in News table is of datetime.I have used following query:
select distinct  News.* from News where News.Date =@Date and
                    News.Publish_Status=1 order by News.News_ID desc
but is not working when i am supplying any date no result is found.Please help me someone.

A:

Try below Query:
select distinct News.*
from News
where CONVERT(VARCHAR(MAX),News.Date,101) = CONVERT(VARCHAR(MAX),@Date,101)
      and News.Publish_Status=1
order by News.News_ID desc

It will work for any date formate.


Q:

Reference request: Banach space of linear maps from a seminormed space to a Banach space.

It's well-known that when $X$ is a normed space and $Y$ is Banach space, the set $L(X,Y)$ of bounded linear maps between the spaces is a banach space with the norm $\|A\| = \sup_{\|x\|_{X}=1}\|Ax\|_{Y}$.
The proof of this can also be used to show a slightly more general result. $X$ can be a seminormed space instead of a normed space and the end result is still Banach:
Theorem:
Let $(X,\rho)$ be a seminormed space and $Y$ a Banach space. Define $\|A\|_{\rho} = \sup_{\rho(x) \leq 1}\|Ax\|_{Y}$. Let $L_{\rho}(X,Y)$ be the space of linear maps that are bounded w.r.t $\rho$ (that is, $\|A\|_{\rho} < \infty$), with the norm $\|\cdot\|_{\rho}$. Then $L_{\rho}$ is a Banach space.
I am looking for a reference of this fact to include in a paper. Thanks.

A:

This is quite straight-forward. If $\varrho$ is a semi-norm, and
$$
M=\{x\in X:\varrho(x)=0\},
$$
then $M$ is a linear subspace, and $X/M$ is naturally equipped with the norm
$$
\|x/M\|=\varrho(x).
$$
Also, if $x\in M$, then $Ax=0$. Otherwise, $A$ would not be bounded, in the sense described in the formulation of the Theorem.
Then, from $A:X\to Y$ we define, also naturally, the bounded linear transformation
$$
\hat A: X/M\to Y,
$$
where $\hat A(x+M)=Ax$.


Q:

How to create a new list and add a value in single statement

What I'm trying to achieve is probably quite pointless but I would like to find this out to satisfy my curiosity.
I'm trying to create a single efficient statement that would create a new list based on another and add a new value to the end.
I'm new to lambda expressions and I'm not sure what kind of list should I be using for this.
the method would look something like this:
private List<Integer> conjoin(List<Integer> list, Integer newValue){
    return new ArrayList<Integer>(list).stream()
            .map(value -> list.indexOf(value)==(list.size()-1) ?
                    Arrays.asList(value, newValue) :
                    Arrays.asList(value))
            .flatMap(Collection::stream)
            .collect(Collectors.toList());
}

but more neat and efficient.
Or is there a built-in method doing the same that I didn't know about?

A:

I love one-liners as much as anyone else, but they come with a cost - namely they're harder to read than being explicit.  So lets start with the "normal" way to do what you're describing:
ArrayList<E> copy = new ArrayList<>(list);
copy.add(value);
return copy;

It's a few lines, but it's efficient, straight-forward, and easy to read.  We want any alternative to be an improvement on this syntax, not simply replacing readability for conciseness.  If you're trying to decide between the implementation you've posted and the "normal" version, the "normal" version should win hands down.

We can try to improve on your solution with Stream.concat() and Stream.of().
return Stream.concat(list.stream(), Stream.of(value))
    .collect(Collectors.toList());

It's technically all one statement now, but we still need to split it over multiple lines to make it readable.  It's also a lot more boilerplate than the standard implementation.

Instead we can use the builder pattern Guava provides for its Immutable collections:
return new ImmutableList.Builder<E>().addAll(list).add(value).build();

This is more concise, and conveys our intent nicely.  This is how I would recommend implementing the behavior you describe (using Guava or by defining your own builder pattern).  Not only does it work for this specific use case, but it scales to any arbitrary combination of values and collections.

I think (it's hard to read :) ) your example actually replaces the last value of the list with your new value, rather than adding it to the end.  If that's what you want, just use List.sublist() to truncate the last element from the list, e.g.:
list.sublist(0, list.size() - 1)

Use that anywhere I have list above to exclude the last value.


Q:

Why exactly did the Sorting Hat originally want to put Harry in Slytherin?

I know that the Sorting Hat wanted to for other reasons, but if he made the right decision then why did he ever want to? The Sorting Hat made it very clear that he chose the right house, then why did he ever consider putting Harry in Slytherin?

A:

The Sorting Hat was picking up on the Dark Lord’s soul in Harry.
It’s hinted that the reason that the Sorting Hat was considering putting Harry in Slytherin was because of the piece of Lord Voldemort left inside of him.

“You can speak Parseltongue, Harry,’ said Dumbledore calmly, ‘because Lord Voldemort – who is the last remaining descendant of Salazar Slytherin – can speak Parseltongue. Unless I’m much mistaken, he transferred some of his own powers to you the night he gave you that scar. Not something he intended to do, I’m sure …’
‘Voldemort put a bit of himself in me?’ Harry said, thunderstruck.
‘It certainly seems so.’
‘So I should be in Slytherin,’ Harry said, looking desperately into Dumbledore’s face. ‘The Sorting Hat could see Slytherin’s power in me, and it –” - Harry Potter and the Chamber of Secrets, Chapter 18 (Dobby’s Reward)

This is confirmed in an interview with J.K. Rowling, when she says the Sorting Hat was strongly tempted to put Harry in Slytherin because of the piece of the soul.

Also, I always imagine that the Sorting Hat detected the presence of that piece of soul (JN: Yeah!) when Harry first tried it on, because it’s strongly tempted to put him in Slytherin. So that’s how I see it. - Pottercast interview (Dec 23, 2007)

The Sorting Hat had decided not to put Harry in Slytherin at least somewhat in part due to Harry’s own desire not to be in Slytherin - but it seems fairly clear that the reason the Sorting Hat was considering putting him there to begin with was because he was “seeing” the Dark Lord’s soul as a part of Harry and that part seemed to be suited for Slytherin.

A:

Destiny for greatness

Because you know what Salazar Slytherin looked for in his chosen students? The seeds of greatness (Pottermore)

Harry was destined for greatness. Both in-universe (by the time of Sorting, he was told so by Ollivander upon picking the voldemort-phoenix wand). And fourth-wall, as we know he ended up ending Riddle in the end and generally was a great hero.
Slytherin qualities.

Harry has "a certain disregard for the rules" (As per Dumbledore in CoS). A very Slytherin "the end justifies the means" mentality.


Q:

Declaring constructor for object that contains integer array

Here is how my constructor has been defined
    public One (int [] a, int [] b)
{
    A = a;
    B = b;
    C = new int [a.length + b.length];
}

This is how I am creating a object for this:
    One A = new One ([1,3,5], [1,5,3]);

I am getting multiple errors for this , like the constructor (int,int,int,int,int,int) is not defined and syntax error on tokens,delete these tokens.
Can someone please tell me where am i going wrong ? Thanks

A:

This is not how you create an array in java. You need to use it like this: -
One A = new One (new int[] {1,3,5}, new int[] {1,5,3});

new int[] creates an integer array object.
{1, 3, 5} initializes the array inline.

As a side note, you should declare your variable starting with lowercase letter. In your code, your instance array reference should be a instead of A. And use this.a to access it to avoid name conflict between local and instance variable.

A:

your syntax for creating anyonomous array is wrong. you create an anyonomous array like this.
One A = new One (new int []{1,3,5}, new int[]{1,5,3});


Q:

Custom message for push registry alert j2me

When I receive a push notification in my j2me application it shows its built-in message at start, what I want to do is to place my own message say "Do You Want to Launch App?" when a notification of invoking application is received! How to change it?

A:

It is unlikely that application developer would be allowed to do stuff like that in the real phone, and here's why.
This functionality is a part of security sensitive features (if you're interested in details, check documentation like The Recommended Security Policy for GSM/UMTS Compliant Devices).
If this would be allowed, malware applications could transform not just wording but the very meaning of a standard system message, thus tricking user into doing something wrong.

For an example, imagine an application doing tracking of user location, or sending paid SMS, or something similarly sensitive to one's privacy or budget, having mentioned message changed to:

Click Yes to win million dollars.

As a phone user, the last thing I would want of my device would be to allow tricks like that.


Q:

getting relative height prop to work with window resize CSS

can anyone help me with this simple, supposedly easy, css task?  I'm trying to set a div height to resize with window.  This is what I have so far:
div.signIn {
margin: 20px 20px 10px 40px;
border-style: ridge;
border-color: #006a89;
min-height: 450px;
height: 90%;
width: 26%;
min-width: 255px;
padding: 10px 20px 10px 20px;
line-height: 210%;
float: left;
}

The width works fine, but not height.  There is no other style working on the div.  Can anyone spot why?

A:

Try setting html and body height.
jsFiddle
html,
body {
    height:100%;
}


Q:

boolean operators in PYTHON 2.7.3

I'm writting a piece of program in which I ask for input from user.
I want python to check if the input is digit (not words or puntuation...) and if it is a number indicating an object in my tuple. If one of the 3 conditions result in False then I would like the user to provide another value for that variable. Here's my code
colour={'yello':1, 'blue':2, 'red':3, 'black': 4, 'white': 5, 'green': 6}
height_measurements=('centimeter:1', 'inch:2', 'meter:3', 'foot:4')
weight_measurements=('gram:1', 'kilogram:2', 'pounds:3')
print height_measurements
hm_choice = raw_input('choose your height measurement').lower()
while not hm_choice.isdigit() or hm_choice > 0 or hm_choice < len(height_measurements) :
    hm_choice = raw_input('choose your height measurement').lower()
print weight_measurements
wm_choice = raw_input('choose your weight measurement').lower()
while not wm_choice.isdigit() or wm_choice > 0 or wm_choce < len(weight_measurements) :
    wm_choice = raw_input('choose your weight measurement').lower()

When I put this to test, it kept making me insert input for height_measurement constantly no matter what I put in
Please check my code and correct for me. Also if you will, please provide me with better code of yours.

A:

I won't fix your code for you entirely, but I will explain something to you which you seem to be confused about.
raw_input returns a string. Strings and integers are two types and cannot be compared to each other (even though in python 2 this is does not raise a TypeError). So your variable hm_choice is a string and you're correct to use the isdigit method to ensure it is an integer. However, you're then comparing a string to an integer which will always evaluate to True in one of those conditions which means that while loop will never stop. So I pose this question to you: How do you get an integer from a string?
Next, you need to examine the logic of that loop. You're saying: While hm_choice is not a digit OR while hm_choice is greater than 0 (which we already know is an invalid statement) OR while hm_choice is less than 4 (or the length of your tuple).
So if any of those are True, then the loop will not end. If you read the article I linked above, you'll figure out which of those always evaluates to True. ;)


Q:

Divide certain distinct row values into separate columns

This might be difficult for me to describe clearly but I will try anyway. Also note that this is entirely speculative; it might not even be able to run any faster (that is why I am asking).
This is a question directed at performance. I have been trying to improve the performance of a method and have managed to improve it quite a bit already (around 40% faster). Right now, the entire process takes about 1 minute and 15 seconds to complete. I would like to see if maybe you guys can see some obvious faults in my code and how we could perhaps improve it even further, seeing as I am not quite satisfied yet.
The method fetches a big amount of data from a couple of databases and needs to be displayed in a grid in a certain way. Here is the heavy part of the method. I will describe it in more detail after:
DataClasses1DataContext dbContext = new DataClasses1DataContext(sqlConnectionString);

//Find minimum value of N in the specified timespan
var headerMin = ((from y in dbContext.Testheaders
                  where Convert.ToDateTime(y.StartTime) >= GlobalVariables.StartTimeMSA
                  select y.N).Min());

//Find maximum value of N in the specified timespan
var headerMax = ((from y in dbContext.Testheaders
                  where Convert.ToDateTime(y.StartTime) <= GlobalVariables.EndTimeMSA
                  select y.N).Max());

//Find appropriate data in the specified timespan (min and max headerid)
var msaData = from x in dbContext.Testdatas
              where x.HeaderID >= headerMin
                                    &&
                    x.HeaderID <= headerMax

              select new
              {
                  StartTime = Convert.ToDateTime((from z in dbContext.Testheaders
                                                 where x.HeaderID == z.N
                                                 select z.StartTime).FirstOrDefault()),

                  DUT_id = Convert.ToString((from y in dbContext.Testheaders
                                             where x.HeaderID == y.N
                                             select y.DUT_id).FirstOrDefault()),

                  Meas = (double)x.Meas,

                  x.Step,

                  x.LogID,

                  x.HeaderID,

                  printID = Convert.ToInt32((from y in dbContext.Testheaders
                                             where x.HeaderID == y.N
                                             select y.PrintID).FirstOrDefault()),

                  Prod_Blok = Convert.ToInt32((from y in dbContext.Testheaders
                                               where x.HeaderID == y.N
                                               select y.Prod_Blok).FirstOrDefault()),

                  Rep_Count = Convert.ToInt32((from y in dbContext.Testheaders
                                               where x.HeaderID == y.N
                                               select y.Rep_Count).FirstOrDefault()),

                  Operator = Convert.ToString((from y in dbContext.Testheaders
                                               where x.HeaderID == y.N
                                               select y.Operator).FirstOrDefault()),
              };

msaDataTable.Columns.Add("Time");
msaDataTable.Columns.Add("DUT");
msaDataTable.Columns.Add("Position");

var functionDistinct = msaData.Select(x => new { x.Step, x.LogID }).Distinct().ToList().OrderBy(x => x.Step).ThenBy(x => x.LogID);

//Add columns to datatable corresponding to each function. The number of columns is only known at runtime.
foreach (var item in functionDistinct)
{
    var column = new DataColumn() { DataType = typeof(double), ColumnName = String.Format("{0}-{1}", item.Step, item.LogID), AllowDBNull = true };

    msaDataTable.Columns.Add(column);
}

var distinctHeaderID = msaData.Select(x => x.HeaderID).Distinct();

foreach (var headerID in distinctHeaderID)
{
    ct.ThrowIfCancellationRequested();

    //Fetch the data for the current headerID
    var headerIDData = msaData.Where(x => x.HeaderID == headerID).Select(x => new { x.StartTime, x.DUT_id, x.printID, x.Step, x.LogID, x.Meas }).ToList();

    if (headerIDData != null)
    {
        DataRow row = msaDataTable.NewRow();

        row["Time"] = headerIDData.FirstOrDefault().StartTime;
        row["DUT"] = headerIDData.FirstOrDefault().DUT_id;
        row["Position"] = headerIDData.FirstOrDefault().printID;

        //Run through the data for the current headerID and assign the values to the right function.
        foreach (var data in headerIDData)
        {
            string function = String.Format("{0}-{1}", data.Step, data.LogID);
            row[function] = data.Meas;
        }

        msaDataTable.Rows.Add(row);
    }
}

Some sample rows from the database query (msaData) could look like this (these are just made up):

I am basically taking those sample rows and combine them into a single row, where the distinct Step and LogID are combined into "functions" shown as columns with the Measurements as cell values. To illustrate, here is how the above picture would be displayed correctly:

A few notes:

Step and LogID combined are known as a "function". In the database they are separated into two columns instead of just the function. For example, Step could have a field value of 5 and LogID 1. Then the function would be known as 5-1. This is what I am displaying as columns instead.
To achieve the goal I am creating a DataTable and binding it to the grid after I am done filling it with appropriate data.
I need to create the columns dynamically as there is no way to know how many functions there are at design time. That is the reason I am using a DataTable in the first place instead of just creating a class and an ObservableCollection for example.
The above sample rows is a very small amount of what the actual data will consist of. We are talking 400000 rows in the test scenario I am running currently.

Are there any immediate problems in my code you can spot? Perhaps some places where a ToList() call could improve performance (even though I have tried some already). Or perhaps another way to tackle how I combine the rows?

A:

I'm thinking that the 2 calls at the beginning might be reduced to one.  Which should cut down the time somewhat.  Something like this:
var headers = ((from y in dbContext.Testheaders
                  let startTime = Convert.ToDateTime(y.StartTime)
                  where startTime >= GlobalVariables.StartTimeMSA &&
                        startTime <= GlobalVariables.EndTimeMSA
                  select y.N));

//Find minimum value of N in the specified timespan
var headerMin = headers.Min();
//Find maximum value of N in the specified timespan
var headerMax = headers.Max());

In a similar vein extracting the appropriate header, only once for each record your looking at in testDatas should eliminate the queries your doing in the new block.  Something like this:
var msaData = from x in dbContext.Testdatas
                where x.HeaderID >= headerMin
                                    &&
                    x.HeaderID <= headerMax
                let header = (from h in dbContext.Testheaders
                            where x.HeaderID == h.N
                            select h).FirstOrDefault()
                select new
                {
                    StartTime = Convert.ToDateTime(header.StartTime),

                    DUT_id = Convert.ToString(header.DUT_id),

                    Meas = (double)x.Meas,

                    x.Step,

                    x.LogID,

                    x.HeaderID,

                    printID = Convert.ToInt32(header.PrintID),

                    Prod_Blok = Convert.ToInt32(header.Prod_Blok),

                    Rep_Count = Convert.ToInt32(header.Rep_Count),

                    Operator = Convert.ToString(header.Operator),
                };


Q:

How to correct a iteration on a Multidimensional array

I have a table "recipientMap". This table looks like that :
| MapID | IPgroupID | PCgroupID | AlertID
|:------|----------:|:---------:|:------:
|   1   |     1     |     1     |   15
|   2   |     3     |    null   |   15
|   3   |     3     |    null   |   16

This table helps me to know who can access to a message.
This choice is done when a user write the alert from the Mvc application, with a checkbox list for each. So I built an array for checked IP group id's and for checked PC group id's and push both into a new multidimensional array. I send this array to the controller. Next step is to iterate on it, and built a list based on RecipientMap model.
The problem is when one of the list has more or less checked id. For example, If I have in my multidimensional array a result like that :
list[0][0]=1
list[0][1]=3
list[1][0]=1

I get an error because there is no list[1][1]. My list must have the same length... it's not good, and I know it's because my iteration method is not correct, I need some advice to correct it.
List[0][x] is for IP and List[1][x] is for PC. My array could have one or both list.
$('#bttn').click(function () {
    var brutelistip = null;
    brutelistip = [];

    var brutelistpc = null;
    brutelistpc = [];

    $('#AlertCreationTabs #AlertCreationTabs-1 input:checkbox:checked').each(function () {
        brutelistip.push($(this).attr('value'));
    });

    $('#AlertCreationTabs #AlertCreationTabs-2 input:checkbox:checked').each(function () {
        brutelistpc.push($(this).attr('value'));
    });

    var recipientlist = new Array();
    recipientlist[0] = brutelistip;
    recipientlist[1] = brutelistpc;

    $.ajax({
        url: '/Panels/CreateNewAlert',
        dataType: 'json',
        type: 'post',
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({
            ...
            list: recipientlist,
        }),
        async: false,
        processData: true,
        success: function (data) {
            alert(data);
        },
        error: function (xhr) {
            alert('error');
        }
    });
});

And the controller :
public JsonResult CreateNewAlert(AlertMap alertMap, AlertLog alertLog, RecipientMap recipientMap, int[][] list)
{
    if (ModelState.IsValid)
    {
        ...

        var RM = new RecipientMap();
        List<RecipientMap>reciplist = new List<RecipientMap>();

        for (int i = 0; i < list.Length; i++)
        {
            reciplist.Add(new RecipientMap
            {
                IPgroupID = list[0][i],
                PCgroupID = list[1][i]
            });
        }

        AL.RecipientMap.AddRange(reciplist);
        AL.AlertMap.Add(AM);
        db.AlertLog.Add(AL);
        db.SaveChanges();
    }
    ...
}

A:

Assuming both list[0] and list[1] are the same length, then it may be wise to replace list.Length with list[0].Length:
for (int i = 0; i < list[0].Length; i++)
{
    reciplist.Add(new RecipientMap
    {
        IPgroupID = list[0][i],
        PCgroupID = list[1][i]
    });
}

If they're not the same length, you're going to have to do a conditional check before accessing one or the other. Either solution is a bit fiddly but they both work for their different circumstances.
Where one exists but the other does not, you could insert a null into one of the RecipientMap properties to create the List<RecipientMap> element.. or you could not create it at all. It's entirely up to your implementation.


Q:

toggle attribute in database

If the user doesn't sign up with twitter or facebook the provider attribute is blank and the user is a pro user. I've added the pro attribute to the database as a boolean and the default is false.
I'm trying to toggle the pro attribute in the database to true using the code below.
  def pro?
    toggle!(:pro) if provider.blank?
  end

However I get this error.
stack level too deep

I also tried
      def pro?
        :pro => true if provider.blank?
      end
but get this error:
 syntax error, unexpected tASSOC, expecting keyword_end

Note I also need to use the pro method because it is used in many other places in the code.

A:

If you have the pro attribute defined as boolean, the following methods are all available for free:

pro? : returns the boolean value of the pro attribute
pro= : sets the value of pro

A ruby method ending in a ? is expected to return a boolean, without any side-effects.
What I would do, in your case, is add a callback:
class User

  before_save :check_pro_status

  def check_pro_status
    pro = provider.blank?
  end

end

This will make sure that everytime something is changed in your user, before saving, it will set the pro-status correctly depending on the provider.
Hope this helps.