Q:

How to include an image in metadata for a Plug-In DLL using MEF?

C# .NET 4.0 WinForms
I started implementing MEF example code from this tutorial which describes creating a custom ExportAttribute Attribute for metadata.  Everything was going swimmingly until I tried to include an image from a Resource File in the metadata.  The goal being to extract the title, description, and icon for each plug-in DLL as metadata for constructing a menu of plug-ins in the main program.
I now get the compile error:

"An attribute argument must be a constant expression, typeof expression
  or array creation expression of an attribute parameter type"

So now I have a problem, and need to figure out either:
1)  How to include an image in a attribute ?
or
2)  How to include metadata in MEF without using attributes ?
Here is the code that I am using:
In the contract class:
// Metadata contract interface
public interface IPlugInMetadata
{
    string PlugInTitle { get; }
    string PlugInDescription { get; }
    Image PlugInIcon { get; }
}

// Plug-In contract interface
public interface IPlugIn
{
    void StartPlugIn(object systemObject);
    void StopPlugin();
}

The custom attribute in the Plug-In DLL:
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class PluginMetadataAttribute : ExportAttribute
{
    public string title { get; set; }
    public string description { get; set; }
    public Image icon { get; set; }

    public PluginMetadataAttribute(string plugInTitle, string plugInDescription, Image plugInIcon)
        : base(typeof(IPlugInMetadata))
    {
        title = plugInTitle;
        description = plugInDescription;
        icon = plugInIcon;
    }
}

And finally, the Program class in the Plug-In DLL:
[Export(typeof(IPlugIn))]
[PluginMetadata(ResourceFile.PlugInTitle, ResourceFile.PlugInDescription, ResourceFile.PlugInIcon24)]
public class Program : IPlugIn
{
    public void StartPlugIn(object systemObject)
    {
        Console.WriteLine("Start Plug-In: " + ResourceFile.PlugInTitle);
    }

    public void StopPlugin()
    {
        Console.WriteLine("Stop Plug-In: " + ResourceFile.PlugInTitle);
    }
}

This line is producing the error.
[PluginMetadata(ResourceFile.PlugInTitle, ResourceFile.PlugInDescription, ResourceFile.PlugInIcon24)]

Obviously the ResourceFile is not considered a constant, but then how can I use an image as metadata, or is that not possible ?  ( Note that the image is set as "Embedded in .resx" )
Thanks for any help or suggestions !

A:

Found a solution:
OK, as far as I can tell, you cannot use images or icons in MEF metadata.  You can however assign an icon to the DLL file, just as you can for EXE files.  The icon can then be read using a static method built into the Icon type for .NET:
Icon MyDLLIcon = Icon.ExtractAssociatedIcon(DLLFilePath);

I am still not exactly sure why you can return strings from a Resource file as MEF metadata, but not embedded Icons or Images.
Since I have been trying to piece together a functioning example program that provides a Plug-In menu with icons for a couple of days now, I figured that I would post the code in case it helps anyone else.

This is a fully functional example project with the following features:

Intended to be a single Solution with 5 Projects ( MainProgram, ContractInterfaces, PlugInA, PlugInB, PlugInC )
Post Build Events will automatically copy the DLLs from each project to a common "Plug-Ins" folder
The MainProgram (WinForm) project will build a catalog of the available DLL Plug-Ins and populate a ListView with the Icons and metadata Title of each Plug-In
Double-Clicking the ListView item will instantiate the Plug-In ( leveraging Lazy instantiation ), and start it.
Each Plug-In will receive a reference to the main Form at start up, create a new TextBox, and post it to the main Form to prove that it ran and can access the GUI.
The Title, Description, and Version metadata values of the selected Plug-In will print to the Console Window

I assigned a different Icon to each DLL ( from the old Visual Studio 6 Common Graphics Misc folder )

The icons were extracted from the DLL Plug-Ins to create the ListView, and the TextBoxes were created and posted by the DLLs to the GUI once they started ( after double-clicking each Plug-In item in the ListView ).

Add the following code to a fresh new C# WinForm project called "MainProgram" ( I used VS 2010 ):
For some reason the Code Sample parser is not liking the Using statements, so here they are as bullet points:

using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.ComponentModel.Composition.Hosting;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using ContractInterfaces;
(namespace) MainProgram

public partial class Form1 : Form
{
    // Prerequisites to run:
    //      1)  Project, Add Reference, Projects, ContractInterface
    //      2)  Project, Add Reference, .NET, System.ComponentModel.Composition

    [ImportMany(typeof(IPlugIn))]
    private IEnumerable<Lazy<IPlugIn, IPlugInMetadata>> LoadedPlugIns;

    List<PlugInInfo> AvailablePlugIns = null;

    public Form1()
    {
        InitializeComponent();
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        // Get a list of the available Plug-Ins
        AvailablePlugIns = GetPlugInList();

        // Prepare an ImageList to hold the DLL icons
        ImageList ImgList = new ImageList();
        ImgList.ColorDepth = ColorDepth.Depth32Bit;
        ImgList.ImageSize = new Size(32, 32);

        // Populate ImageList with Plug-In Icons
        foreach (var item in AvailablePlugIns)
        {
            ImgList.Images.Add(item.PlugInIcon.ToBitmap());
        }

        // Assign the ImageList to the ListView
        listView1.LargeImageList = ImgList;

        int imageIndex = 0;

        // Create the ListView items
        foreach (var item in AvailablePlugIns)
        {
            listView1.Items.Add(item.PlugInTitle, imageIndex);
            imageIndex++;
        }

        listView1.MouseDoubleClick += new MouseEventHandler(listView1_MouseDoubleClick);
    }

    void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        // Get the Plug-In index number
        int plugInNum = listView1.SelectedItems[0].Index;

        PlugInInfo selectedPlugIn = AvailablePlugIns[plugInNum];

        // Call the StartPlugIn method in the selected Plug-In.
        // Lazy Instantiation will fully load the Assembly here
        selectedPlugIn.PlugIn.StartPlugIn(this);

        Console.WriteLine("Plug-In Title:          {0}", selectedPlugIn.PlugInTitle);
        Console.WriteLine("Plug-In Description:    {0}", selectedPlugIn.PlugInDescription);
        Console.WriteLine("Plug-In Version:        {0}", selectedPlugIn.PlugInVersion);
        Console.WriteLine();
    }

    private List<PlugInInfo> GetPlugInList()
    {
        // Create a List to hold the info for each plug-in
        List<PlugInInfo> plugInList = new List<PlugInInfo>();

        // Set Plug-In folder path to same directory level as Solution
        string plugInFolderPath = System.IO.Path.Combine(Application.StartupPath, @"..\..\..\Plug-Ins");

        // Test if the Plug-In folder exists
        if (!Directory.Exists(plugInFolderPath))
        {
            // Plug-In Folder is missing, so try to create it
            try
            { Directory.CreateDirectory(plugInFolderPath); }
            catch
            { MessageBox.Show("Failed to create Plug-In folder", "Folder Creation Error:", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); }
        }

        try
        {
            // Create a catalog of plug-ins
            var catalog = new DirectoryCatalog(plugInFolderPath, "*.dll");
            AggregateCatalog plugInCatalog = new AggregateCatalog();
            plugInCatalog.Catalogs.Add(catalog);
            CompositionContainer container = new CompositionContainer(plugInCatalog);

            // This line will fetch the metadata from each plug-in and populate LoadedPlugIns
            container.ComposeParts(this);

            // Save each Plug-Ins metadata
            foreach (var plugin in LoadedPlugIns)
            {
                PlugInInfo info = new PlugInInfo();

                info.PlugInTitle = plugin.Metadata.PlugInTitle;
                info.PlugInDescription = plugin.Metadata.PlugInDescription;
                info.PlugInVersion = plugin.Metadata.PlugInVersion;
                info.PlugIn = plugin.Value;

                plugInList.Add(info);
            }

            int index = 0;

            // Extract icons from each Plug-In DLL and store in Plug-In list
            foreach (var filePath in catalog.LoadedFiles)
            {
                plugInList[index].PlugInIcon = Icon.ExtractAssociatedIcon(filePath);
                index++;
            }
        }
        catch (FileNotFoundException fex)
        {
            Console.WriteLine("File not found exception : " + fex.Message);
        }
        catch (CompositionException cex)
        {
            Console.WriteLine("Composition exception : " + cex.Message);
        }
        catch (DirectoryNotFoundException dex)
        {
            Console.WriteLine("Directory not found exception : " + dex.Message);
        }

        return plugInList;
    }
}

public class PlugInInfo
{
    public string PlugInTitle { get; set; }
    public string PlugInDescription { get; set; }
    public string PlugInVersion { get; set; }
    public Icon PlugInIcon { get; set; }
    public IPlugIn PlugIn { get; set; }
}

Now add a ListView Control called "listView1" to the main Form, and keep it to the Right side of the Form.  The dynamically created TextBoxes from the Plug-Ins will show on the left.

Next add a Class Project called "ContractInterfaces", then include this code:

using System.Windows.Forms;
(namespace) ContractInterfaces

// Prerequisites to run:
//      1)  Project, Add Reference, .NET, "System.Windows.Forms"

public interface IPlugIn
{
    void StartPlugIn(Form mainForm);
}

public interface IPlugInMetadata
{
    string PlugInTitle { get; }
    string PlugInDescription { get; }
    string PlugInVersion { get; }
}

Next add a Class Project called "PlugInA", then include this code:

using System;
using System.ComponentModel.Composition;
using System.Windows.Forms;
using ContractInterfaces;
(namespace) PlugInA

    // Prerequisites to run:
//      1)  Project, Add Reference, Projects, "ContractInterface"
//      2)  Project, Add Reference, .NET, "System.Windows.Forms"
//      3)  Project, Add Reference, .NET, "System.ComponentModel.Composition"
//      4)  Project, Properties, Build Events, Post-Build event command line:
//          xcopy "$(ProjectDir)$(OutDir)$(TargetFileName)"  "$(SolutionDir)Plug-Ins\" /Y
//      5)  Project, Properties, Build Events, Run the post-build event:, Always
//      6)  Project, Properties, Application, Icon and manifest, [Select an icon]

[Export(typeof(IPlugIn))]
[PluginMetadata]
public class Program : IPlugIn
{
    private Form MainForm;

    public void StartPlugIn(Form mainForm)
    {
        MainForm = mainForm;

        // Place a TextBox on the Main Form
        TextBox textBox = new TextBox();
        textBox.Text = "PlugInA";
        MainForm.Controls.Add(textBox);
        textBox.Width = 65;
        textBox.Height = 20;
        textBox.Top = 0;
        textBox.Left = 0;
    }
}

// Create a custom strong-typed Metadata Attribute for MEF
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class PluginMetadataAttribute : ExportAttribute
{
    public string PlugInTitle { get; set; }
    public string PlugInDescription { get; set; }
    public object PlugInVersion { get; set; }

    public PluginMetadataAttribute()
        : base(typeof(IPlugInMetadata))
    {
        PlugInTitle = "Plug-In A";
        PlugInDescription = "This is Plug-In A";
        PlugInVersion = "1.0.0.0";
    }
}

Next add a Class Project called "PlugInB", then include this code:

using System;
using System.ComponentModel.Composition;
using System.Windows.Forms;
using ContractInterfaces;
(namespace) PlugInB

// Prerequisites to run:
//      1)  Project, Add Reference, Projects, "ContractInterface"
//      2)  Project, Add Reference, .NET, "System.Windows.Forms"
//      3)  Project, Add Reference, .NET, "System.ComponentModel.Composition"
//      4)  Project, Properties, Build Events, Post-Build event command line:
//          xcopy "$(ProjectDir)$(OutDir)$(TargetFileName)"  "$(SolutionDir)Plug-Ins\" /Y
//      5)  Project, Properties, Build Events, Run the post-build event:, Always
//      6)  Project, Properties, Application, Icon and manifest, [Select an icon]

[Export(typeof(IPlugIn))]
[PluginMetadata]
public class Program : IPlugIn
{
    private Form MainForm;

    public void StartPlugIn(Form mainForm)
    {
        MainForm = mainForm;

        // Place a TextBox on the Main Form
        TextBox textBox = new TextBox();
        textBox.Text = "PlugInB";
        MainForm.Controls.Add(textBox);
        textBox.Width = 65;
        textBox.Height = 20;
        textBox.Top = 30;
        textBox.Left = 0;
    }
}

// Create a custom strong-typed Metadata Attribute for MEF
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class PluginMetadataAttribute : ExportAttribute
{
    public string PlugInTitle { get; set; }
    public string PlugInDescription { get; set; }
    public object PlugInVersion { get; set; }

    public PluginMetadataAttribute()
        : base(typeof(IPlugInMetadata))
    {
        PlugInTitle = "Plug-In B";
        PlugInDescription = "This is Plug-In B";
        PlugInVersion = "1.0.0.1";
    }
}

Next add a Class Project called "PlugInC", then include this code:

using System;
using System.ComponentModel.Composition;
using System.Windows.Forms;
using ContractInterfaces;
(namespace) PlugInC

// Prerequisites to run:
//      1)  Project, Add Reference, Projects, "ContractInterface"
//      2)  Project, Add Reference, .NET, "System.Windows.Forms"
//      3)  Project, Add Reference, .NET, "System.ComponentModel.Composition"
//      4)  Project, Properties, Build Events, Post-Build event command line:
//          xcopy "$(ProjectDir)$(OutDir)$(TargetFileName)"  "$(SolutionDir)Plug-Ins\" /Y
//      5)  Project, Properties, Build Events, Run the post-build event:, Always
//      6)  Project, Properties, Application, Icon and manifest, [Select an icon]

[Export(typeof(IPlugIn))]
[PluginMetadata]
public class Program : IPlugIn
{
    private Form MainForm;

    public void StartPlugIn(Form mainForm)
    {
        MainForm = mainForm;

        // Place a TextBox on the Main Form
        TextBox textBox = new TextBox();
        textBox.Text = "PlugInC";
        MainForm.Controls.Add(textBox);
        textBox.Width = 65;
        textBox.Height = 20;
        textBox.Top = 60;
        textBox.Left = 0;
    }
}

// Create a custom strong-typed Metadata Attribute for MEF
[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class PluginMetadataAttribute : ExportAttribute
{
    public string PlugInTitle { get; set; }
    public string PlugInDescription { get; set; }
    public object PlugInVersion { get; set; }

    public PluginMetadataAttribute()
        : base(typeof(IPlugInMetadata))
    {
        PlugInTitle = "Plug-In C";
        PlugInDescription = "This is Plug-In C";
        PlugInVersion = "1.0.0.2";
    }
}

The Solution should look like this:

Right-click on the Solution, and select "Project Dependencies...".  Set the dependencies as follows:

MainProgram -  depends on -  ContractInterface
PlugInA     -  depends on -  ContractInterface
PlugInB     -  depends on -  ContractInterface
PlugInC     -  depends on -  ContractInterface
ContractInterface - depends on - [nothing]

Right-click on the Solution, and select "Project Build Order...".  The build order should be as follows:

ContractInterface
PlugInA
PlugInB
PlugInC
MainProgram

Build and run the program.  You should see the 3 DLL files copied to a new "Plug-Ins" folder at the same directory level as the Solution file (*.sln).  If not, check the Project Build Order, Dependencies, and that you entered the Post-Build Events according to the notes in the Plug-In code above.  If the files are there, then the ListView should be populated in the Form with the Plug-In entries.  Double-click each ListView entry to start the Plug-In.
Have fun, I hope this helps someone....


Q:

Is there documentation that describes how each part of the Inno Setup WizardForm is connected?

I am having a very difficult time finding any documentation about how the various parts of the Inno Setup Wizardform are hooked together.
Using various answers here on StackOVerflow I have gathered some information but most of the time these are inferences rather and I'm not confident I really have a good grasp.
I have looked at the online help available at http://www.jrsoftware.org/ishelp/index.php and specifically the section on Support Classes Reference but it just gives me a list of all the parts of the wizard form. I really would like more information about how things like the InstallingPage and the InnerPage relate. I've looked through the listing of topics as well and nothing appears to relate to the question I have.
I'm just having a very difficult time grasping how all of those various parts hook together and where each part is in a hierarchy either visual or logical.
I guess I could go look at the source code for Inno Setup but I thought it'd be worth asking here first before diving into an unfamiliar code base in a language I've only been poking at for two days. If that is my only recourse, I guess I'll have to.

A:

I  would like more information about how things like the InstallingPage and the InnerPage relate.

No, WizardForm internals are not documented.
You might read the source.
A code search reveals that the search terms do not occur that often.

https://github.com/jrsoftware/issrc/search?q=InnerPage
https://github.com/jrsoftware/issrc/search?q=InstallingPage

This is the source for the Wizard itself and it's form.
The pages are hooked together via RegisterExistingPage().


Q:

What does "Get a total of 5 hits in StreetSmash" mean?

In Super Smash Bros for 3DS there's a "Get a total of 5 hits in StreetSmash" challenge. However, I can't figure out what is needed to complete it. What does it mean?
I've tried killing 12 opponents which would definitely be 5+ hits, and hitting the enemy puck by moving into them 4 times and then doing dodge + hit combo on a 1v1 since it's really hard to do the charge hit 4 times w/o killing them, but I have yet to beat the challenge.

A:

The answer seems to be that you have to get 5 hits on x number of people streetpassed, rather than number of people. For example, I street passed with one person two days ago and killed him in < 5 hits, but then streetpassed with two people yesterday and killed them both and unlocked the challenge.


Q:

Product rule intuition

Can anyone think of an intuitive explanation of the product rule? I'm not asking for a derivation. To me it seems like quite an un-untuitive result, as apposed to the chain-rule (which is ironically harder to derive).

A:

If you think of $fg$ as giving the area of a rectangle with side lengths $f$ and $g$ (assuming $f,g$ are non-negative, otherwise just flip their signs), then if you change $x$ slightly then one side of the rectangle changes by an amount proportional to $df/dx$ and the other side of the rectangle changes by an amount proportional to $dg/dx$. So you get two little strips of changed area, which have total area proportional to $f'g + g'f$. The only question is whether the overlap of the two little strips matters, and it turns out that it doesn't because the overlap of the two strips has infinitesimal area which is a product of two infinitesimals (really really small), whereas the two strips have infinitesimal area which is a product of only one infinitesimal each (really small, but much larger than the overlap).

A:

I like to think of it in terms of units and symmetry.  We know that, unit-wise, the false formula
$$\frac{d}{dt} (f g) = \frac{df}{dt} \frac{dg}{dt}$$
cannot hold, because, if say $f$ and $g$ each represent distance and $t$ time, the LHS has units of distance^2/time, while the RHS has units distance^2/time^2.
Thus, the product rule for derivatives, in order to keep units, must be of the form $f dg/dt$ or vice-versa.  But because of the symmetry of the original form, the product rule should also be symmetric, i.e.  $f dg/dt + g df/dt$.  As there is no other symmetric form that keeps the units, this should be the product rule, at least intuitively.

A:

$$(x+\delta x)(y+\delta y)=xy + (x\delta y+y\delta x) + O(\delta^2)$$


Q:

Nomenclature for stereoisomer example possible wrong?

I understand the principal of the Cis-Trans naming system (at least I think so), until I saw this example in my learning material. My teacher doesn't know either so I thought I would post it here.
This is the molecule:

There are two ethyl groups both on the bottom side of the double bond, so it could be cis right?

Apparently not, the book says this is the answer:

Could someone please explain the reasoning behind this? This particular example is unusual because there are three ethyl groups attached to the double bond so I cannot determine which one should be the parent chain. The book doesn't explain.

A:

Unless I'm very much mistaken, this molecule should not be labelled with any stereochemical descriptors, whether they be relative (cis/trans) or absolute (E/Z). The double bond has three identical ethyl substituents, therefore there is no stereoisomerism possible. By way of explanation, imagine if the ethyl group and the hydrogen on carbon #4 were interchanged: the resulting molecule would be completely identical to the one pictured. This is always the case when an alkene bears two identical substituents on the same carbon atom.
To correctly use cis/trans or E/Z nomenclature, it is necessary that there not be two identical groups on the same carbon of the alkene; if there are, the labels are meaningless, since interchanging the two groups results in an identical molecule.

A:

In my previous (deleted) answer, I overlooked the fact that this molecule has indeed three identical substituents and not two. Therefore, I would consider Greg E's answer as correct.
Also, C3 has 2 identical substituents on the same sp2 carbon, so cis/trans is not possible.
Example from organic chemistry 6th edition Paula Yurkanis Bruice:

So, your book is wrong!


Q:

DB Migrate not reflected on heroku

I recently created a db migration which works fine locally. I pushed to heroku and ran
heroku rake db:migrate

Whilst the command doesn't seem to throw an error, I can see the database hasn't been updated with the column I've tried to add to a table. I've tried running heroku rake db:setup but to no avail. Additionally, I've also tried restarting heroku after both commands but it still doesn't work.
Anybody have this problem before?

A:

First try to be specific with heroku rake db:migrate:up VERSION=xxx
I had similar problems and what I did was to reset the database, if that doesn't work, I would migrate down all migrations (one by one) and add them up again, of course only if you can afford to loose all your data, alternatively download the database and investigate. The problems I had with recreating the db were related to the fact that I was changing the migrations and that in heroku I had a shared database.


Q:

Strange issue when trying to dismiss UIViewController

I have a UIViewController that hold a UITableView, I want to dismiss the UIViewController when clicking on the table's cell. So I implemented the method:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath

Inside of this method I called:
[self dismissViewControllerAnimated:YES completion:nil];

For some reason, when I click on the cell, the app freezes and I need to click once more in order the UIViewController to dismiss. I even put a breakpoint there to check if it reaches it on the first or the second tap and in the first tap it reaches the breakpoint, then I click on continue execution and I need to tap once more.
Did someone encountered this issue on iOS?

A:

First, it seems like you use didDeselectRowAtIndexPath instead of didSelectRowAtIndexPath. Make sure that you use didSelect..., not didDeselect.....
Second, It freezes because the method tableView:didSelectRowAtIndexPath: is called not on the main thread. You have to use GCD to execute your code in the main queue:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    dispatch_async(dispatch_get_main_queue(), ^{
        [self dismissViewControllerAnimated:YES completion:nil];
    });
}


Q:

Specific template for category and product page in OpenCart 2.2.0.0

I am using OpenCart version 2.2.0.0 and trying to set different template for each category and product page. Searching online I found following code:
if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/product/category_' . $category_id . '.tpl')) {
    $this->template = $this->config->get('config_template') . '/template/product/category_' . $category_id . '.tpl';
} elseif (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/product/category.tpl')) {
    $this->template = $this->config->get('config_template') . '/template/product/category.tpl';
} else {
    $this->template = 'default/template/product/category.tpl';
}

This code works fine for older version of OpenCart but in new version I am not finding similar code structure in catalog/controller/product/category.php file
How can I achieve similar result in OpenCart 2.2.0.0?

A:

Since Opencart changed its method from 2.2 that code doesn't work anymore, you can modify it like this:
First we must know which theme is active, store its name in a variable
$config_theme = $this->config->get('config_theme') == 'theme_default' ? 'default' : $this->config->get('config_theme');

Then we must check if there is a file specially for current category, for example if we are on category 20, we check for category_20.tpl existance.
if (file_exists(DIR_TEMPLATE . $config_theme . '/template/product/category_' . $category_id . '.tpl')) {

If found that file:
$view = 'product/category_' . $category_id;

if there is no such file, use original file: category.tpl
} else {
    $view = 'product/category';
}

load selected view file based on above statement.
$this->response->setOutput($this->load->view($view, $data));

conclusion:
find $this->response->setOutput($this->load->view('product/category', $data)); in catalog/controller/product/category.php and replace it with above codes, here is full code:
$config_theme = $this->config->get('config_theme') == 'theme_default' ? 'default' : $this->config->get('config_theme');
if (file_exists(DIR_TEMPLATE . $config_theme . '/template/product/category_' . $category_id . '.tpl')) {
    $view = 'product/category_' . $category_id;
} else {
    $view = 'product/category';
}
$this->response->setOutput($this->load->view($view, $data));


Q:

LINQ querying a Dictionary against a List

I have
List<string> selectedOptions;
Dictionary<string,string> masterList;

masterList comprises of Keys, which are the superset for the values in selectedoptions.
Now, I would like to extract all the Values for the intersecting Keys between selectedOptions and masterList.
How would the LINQ query be framed?

A:

IEnumerable<KeyValuePair<string,string>> results =
    dic.Join(keys, d => d.Key, x => x, (a, b) => a);

or of course
var results2 = keys.Select(k => new {key = k, value = dic[k]});

but this will bomb if keys don't exist.
you could fix this with a Where(k => dic.ContainsKey(k)) clause:
var results3 = keys
     .Where(k => dic.ContainsKey(k))
     .Select(k => new {key = k, value = dic[k]});

After trawling the Linq source, I think that the last method is probably most efficient. Doing a join forces linq to make a Lookup (effectively a multi-entry hashtable) over one of the collections involved in the join. Seeing as we already have a Dictionary which offers the same lookup performance as a Lookup, building a Lookup is superfluous.


Q:

no such process error with launchctl start. Mac OSX 10.9

The goal is to set machine's network name with the ipaddress of this machine.
I have created a plist file and put it into /Library/Launchagents/. For debugging reason I used the command "launctl start".
Here is my plist file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>com.myfile.hostname</string>

  <key>ProgramArguments</key>
  <array>
    <string>/usr/sbin/ipconfig</string>
    <string>getifaddr</string>
    <string>en0</string>
    <string>|</string>
    <string>/usr/bin/tr</string>
    <string>-d</string>
    <string>'.'</string>
    <string>|</string>
    <string>sudo</string>
    <string>/usr/sbin/scutil</string>
    <string>--set</string>
    <string>LocalHostName</string>
  </array>

  <key>RunAtLoad</key>
  <true/>

  <key>StandardErrorPath</key>
  <string>/tmp/AlTest1.err</string>

  <key>StandardOutPath</key>
  <string>/tmp/AlTest1.out</string>
</dict>
</plist>

Then I use:
launchctl start /Library/LaunchAgents/com.myfile.hostname.plist

and get the error:
launchctl start error: No such process

As the error is not explaining what exactly is wrong with that file Im struggling to find the reason. The command itself on the command work fine. If this is the wrong section for this question please advice.
Thanks in advance

A:

Try using the launchctl command:
launchctl load /Library/LaunchAgents/com.myfile.hostname.plist
This will load the job ticket rather than start a named job.
I am not sure pipes are permitted within a launchd job ticket list of arguments. Using them requires the argument to be passed to a shell for interpretation and this may not happen. Consider passing the command directly to /bin/sh as a single argument.


Q:

How do I write a function for identifying odd positions in matrix

How to create a function that generates all the elements in odd positions (e.g. 1,1 1,3 ) in a say...5-by-8 matrix?

A:

I assume that by "odd" you mean where both the index for row and column are odd.  This means your resulting matrix should be 3 by 4.  Anyway, your code is below.
function Anew = yourFunc(A)
   %Create a test matrix of dimensions 5x8 of random numbers from 1-10
   A = randi(10,5,8);
   %Set the values of all elements with either index being an even number equal to zero
   for r = 1 : size(A,1)
       for c = 1 : size(A,2)
           if rem(r,2) == 0 || rem(c,2) == 0
              A(r,c) = 0;
           else
              continue
           end
       end
   end
   %Delete rows that contain ALL zeros
   for r = 1 : (size(A,1)/2) + 1
       if A(r,:) == 0
           A(r,:) = [];
       end
   end
   %Delete columns that contain ALL zeros
   for c = 1 : (size(A,2)/2) + 1
      if A(:,c) == 0
         A(:,c) = [];
      end
   end
   %State final answer
   Anew = A;
end

Please note that there may be a more efficient code solution, but I have never studied computer science (not my engineering discipline), so I don't know any fancy stuff.


Q:

Angular 1: communications between transcluded repeated directives?

I faced with a problem.
I want to create tabs with separated navigation and content (each one is a separate directive), they are talking to each other using events.
So, the navigations directive is pretty easy, I didn't include this part here. But the content is much more difficult to me. I want to show only a selected tab and hide others (based on some variable in parent tabs' scope). Each tab can contain directive/expression/plain html. I tried plenty of variants but they didn't work.
Could you please help me to find a solution?

How to pass a variable {{item.key}} to an attribute for ng-repeated ng-transcluded directives? Like <tab key="{{item.key}}" repeat="item in items">
How to access a variable selectedTabKey (that is in tabs directive) from every child tab's scope?

var app = angular.module("app", []);
var $ = angular.element;

app.run(function($templateCache, $rootScope) {
  $rootScope.items = [
    {key:1,value:'a'},
    {key:2,value:'b'},
    {key:3,value:'c'}
  ];
});

app.directive( "tabs", function() {
  return {
    restrict: "AE",
    scope: true,
    transclude: true,
    replace: true,
    template: "

",
    link: function(scope, elem, attr, ctrl) {
      scope.selectedTabKey = 2;
      // TODO: changing the selectedTabKey value
      // want to show/hide the related tab
    }
  };
});

app.directive( "tab", function($compile) {
  return {
    restrict: "AE",
    transclude: true,
    replace: true,
    template: "

",
    link: function( scope, elem, attr, ctrl, transclude ) {
      var transc = $(elem[0].querySelector( "[transclude]" ));
      transclude( scope, function( childs ) {
        transc.append( childs );
      });
      transc.attr("ng-repeat", attr.repeat);
      $compile(transc)(scope);
      // todo: access parent's var `selectedTabKey`
      // and make visible the related tab
    }
  };
});

  <tabs>

    <tab key="{{item.key}}" repeat="item in items">

      {{item.value}}
    </tab>
  </tabs>

A:

Found a solution.
Used a require in directive's configs.
Here is an example: https://plnkr.co/edit/IGrgb5GY5legl2ncrw2d?p=preview


Q:

Connected sum of $n$ tori $\mathbb{T}$

$n \mathbb{T} = \mathbb{T} \# \mathbb{T}\# \cdots \# \mathbb{T} =$ a sphere with $n$ handles (connected sum of $n$ tori $\mathbb{T}$)
If we encircle a wire frame cube with a small tube, we get a connected sum of how many tori $\mathbb{T}$?
What about if we do the same thing to a tetrahedron and a dodecahedron?

A:

Intuitively: deform the "top" and "bottom" of the cube into circles. Remove two opposite vertical edges. Then the wireframe will clearly be a connected sum of three tori. But adding in those two missing edges is like adding one of the missing edges is clearly like adding a "diameter" to one of the torus components, and this is just adding another torus.
Slightly more formally, start with the "tubed" base square, and add edges one by one. If you count how many times you needed to add a handle, as opposed to just stretching out an "appendage", you will come up with four, which makes five in total. In fact, you could start with just a single vertex. Then the number of times you'd have added a handle would be exactly five.
It's easy to see that you added a handle at those times when you added an edge without also adding a vertex. That should tell you what the general formula for the number of handles is. You can verify that it works in case of tetrahedron (by hand, as in case of the cube). For dodecahedron, you'd probably better stick to applying it.

A:

Very generally, suppose you have a finite connected graph $G$ (which may have loops and multiple edges).  Replace each vertex of $G$ by a sphere with $n$ disks removed, where $n$ is the number of edges coming out of the vertex, and attach cylinders between these punctured spheres according to the edges.  This gives a closed connected $2$-manifold which I'll call $T(G)$.
Now recall that the Euler characteristic of $G$ is $\chi(G)=V-E$, where $V$ is the number of vertices of $G$ and $E$ is the number of edges.  If you have an edge of $G$ whose endpoints are distinct, consider the graph $G'$ obtained from $G$ by deleting that edge and identifying its endpoints together.  Note that $G'$ is still connected and that $\chi(G)=\chi(G')$, because we have removed one edge and one vertex.  Furthermore it is easy to see that $T(G')$ is homeomorphic to $T(G)$ (this is just the fact that if you take two spheres, cut a hole out of each and connect them by a cylinder, then you get a sphere again).
We can delete edges like this over and over until there are no more edges left to delete.  If there are no more edges we can delete, that means that all the edges must be loops; since all the graphs we get in this process are connected, this means we've reached a graph $H$ with only one vertex.  But if $H$ has just one vertex and $g$ edges (which are all loops at that vertex), it is clear that $T(H)$ is just a connected sum of $g$ tori.  We can also calculate that $\chi(H)=1-g$.
To sum up: given any finite connected graph $G$, there graph $H$ with one vertex which has the same Euler characteristic as $G$, and $T(G)\cong T(H)$ is a connected sum of $g$ tori, where $g$ is the number of edges in $H$.  Since $\chi(G)=\chi(H)=1-g$, we can restate this as follows: $T(G)$ is a connected sum of $1-\chi(G)$ tori.
In the specific cases you ask about, $G$ is the $1$-skeleton of a cube, a tetrahedron, or a dodecahedron.  Let's answer the question more generally when $G$ is the $1$-skeleton of a convex polyhedron with $F$ faces.  In that case, by Euler's formula for convex polyhedra, we know that $F+\chi(G)=2$.  We conclude that $\chi(G)=2-F$, so $T(G)$ is a connected sum of $F-1$ tori.


Q:

Java Calendar timezone converting to GMT problem

I have one Calendar object which is as per the user's time zone which may be PST etc, now i want to convert the same to GMT and retain the time i.e. is the calendar initially was set @ 00:00:00 at PST it should be converted to 08:00:00 after the conversion taking into consideration the time/date difference . Can someone provide me some help on this.
Appreciate the help in advance.
Thanks,
Vaibhav

A:

Just create a new Calendar in GMT, set the time in that calendar to the same as the original calendar, and you're done:
gmtCalendar.setTime(userCalendar.getTime());

That should be fine, as the getTime() call returns the instant in time (i.e. a java.util.Date with no associated time zone).
As ever though, if you're doing any significant amount of date/time work in Java you should strongly consider using Joda Time instead.


Q:

iOS: AppStore wrong version entered, how to fix it?

My Application on AppStore was released with version 1.1
I clicked New Version where
I unfortunately, added version 1.0.2 instead of 1.2
Now after Archive was made , i uploaded the binary, it came an error.

How can i revert that version to 1.2 instead of 1.0.2

A:

The version number must be the same in the binary aswell as in itunes connect so the solution is to change either one.
To change it in itunes connect
1. login to your itunes connect account
2. myApps
3. click on the app in question
4. scroll down to general app information
5. make changes

To change it in itunes connect
In your project navigator, click on your app name.
 it should be the first thing below this image.
Then you can make your changes on the following page


Q:

What is the most effective way to improve a saggy belly?

I used to have a fairly flat stomach but I had a baby 4 months ago by c-section and my lower abdomen is quite saggy. What can I do to lose the extra weight there and get it taut?

A:

Medical Clearance to Exercise

A C-section requires that you get medical clearance before you begin postpartum exercises.  Assuming that you have clearance (and 4 months post would seem likely that you have) here are some considerations in getting your postpartum belly back in shape:

Weight Loss vs Laxity and Weakness
There are actually 2 concerns in fighting the saggy belly.

Excess body weight
Laxity of muscle, connective tissue and skin from being stretched out.

Losing weight after pregnancy does involve nutrition and exercise just as with any weight loss program (as @Robert has pointed out).  However, there are several postpartum specific exercise concerns such as weakness, ligament laxity and postural alignment.
PostPartum  Exercise Concerns

Some ordinary exercises may not be appropriate for you and, in fact, can be counterproductive.  For example, routine abdominal exercises like crunches, which target the rectus abdominus, may make the postpartum belly bulge more, not less, especially if they are attempted before restoring the transversus abdominis.
Another exercise consideration is continued hormonal ligament laxity (looseness) which can last 6 months post delivery requiring you  to be protective of your joints during impact type exercises, stretching or resistance training.

Restoring Abdominal Muscle Control

First, you’ll want to assess if you have a separation (called diastasis recti) centrally, between the 2 rectus abdominus muscles.   This is important because if your separation remains greater than 2 or 2 ½ finger’s width, you need to be more careful to avoid making the separation and your belly bulge worse.  You would need to avoid exercises that cause you to strain, twist as with obliques or triangle pose, or stretch the abdomen as with curl ups over a stability ball, otherwise you will just prolong the weakness.
Next,  focus your efforts on the pelvic floor muscles (Kegel’s exercise) and on the transversus abdominis muscle (TvA), which is the deepest layer of abs (the girdle muscle), before you begin with other obliques or rectus abdominal exercises.
The transverse abdominus (TvA) is the muscle you use when draw your belly button towards your spine, flattening your stomach, while exhaling.  For an in-depth explanation and demo, see Helene Byrne’s videos. (She also has a book with a nice sequence for getting back in shape after pregnancy.)
Then engage your transversus abdominus and begin with gentle leg slides while maintaining that core control.
Once you can maintain good control of your core with the transverse abdominus while moving your legs lying down, progress towards working your TvA against gravity by pulling your belly button in while on your hands and knees.  This video has a nice progression of exercises and includes stabilizing your core with bridging, planks and ball rollouts etc.

Addressing Fat Loss after Pregnancy
You have already been directed to the info that Robert cited so I will just add:

Fat loss is more important than weight loss, so calculate your body fat percentage.  (It is easier than you think.)  Then track your body fat percentage and waist circumference progress rather than just your weight loss.
Diet is a big factor:  Track what you eat (and drink).  Take the time to eat sitting down with your attention on your food or snack.  Choose smaller portions/smaller plates.  Eat well-balanced nutritious meals.  Eat less packaged foods and less empty calories foods like sodas.  Consume less sugars.  Hydrate well.  Remember that it takes a 3500 calorie deficit to = 1 pound of weight loss. Walking a mile burns ~ 100 calories.  It takes a lot more effort to burn off 3500 calories than it does to consume that amount so eat wisely.  Think of creating a healthy lifestyle for you and your family rather than a quick fix diet.
Exercise: Start with simple daily walking and core exercises.  Once you have built up some endurance (at least 30 minutes/day) and core control, begin to increase the difficulty of your workouts.  Hold off on high impact exercises like running and jumping while your ligaments bounce back.
Efficient workouts are key when you are a busy mom.  Compound muscle or whole body, strength training circuit exercises with high intensity intervals will give you effective fat burning workouts in the least amount of time.  You can use bodyweight (like squats, planks, push ups etc), resistance bands, free weights or weight machines for resistance training.
Use your target heart rate to guide your intensity.  If you can join a postpartum exercise class.  It is good for the exercise and support.
Rest - Easier said than done with a new baby, but sleep is also an important factor in losing weight.

Saggy Skin
If you get your abs working properly and burn off the excess fat, you should see the results you want over time.  However, some women do have a problem with overly stretched skin and collagen that just doesn’t return to normal.  For them, surgery is a corrective option.
If you have any problems with your scar or with trying to reconnect with your muscles, you may want to consult with women’s health physical therapy specialist.
(Full disclosure of references:  We carry Helene Byrne’s book in our amazon store.  Our site does affiliate with Holly Rigsby’s Fit Yummy Mummy, despite the name, because it is a good program and we like her membership site.)
I hope this helps you get the flat, taut stomach that you want.  Good luck!


Q:

Slider animation via keyboard not working (javascript and CSS)

I am creating an slider in JS (with angular) + CSS where the user should control via keyboard (left and right arrows). I made it simple as you can see below.
My code works this way: When the user clicks right, it adds one object in the begining of a array and delete the last one. When I click left, it makes the opposite.
slideEffect = function(dir) {
    if (dir == 'left') {
        lastChamp = champs[champs.length-1];
        champs.unshift(lastChamp);
        champs.pop();

    } else {
        firstChamp = champs[0];
        champs.push(firstChamp);
        champs.shift();

    }
}

The thing is. It works just fine when the user press "left arrow" but it goes wrong as soon as the user press right as you can see at: http://brunoornelas.com.br/test/pfc/
Does anyone have any clue on how to solve it the simplest way as possible and using Javascript? (I can't use jquery).
Thank you!

A:

Your animation is working, it's just that the push from first to last messes the effect. Ideal way would be to wait till the transition ends before pushing the element. Since we don't really have access to your actual code, it's a bit hard to give a proper solution, ideal solution would be to add a transitionend listener and push then. But quickly, you can try this in your slide right function, you'll see what needs to be done:
firstChamp = champs[0];
champs.shift();
setTimeout(function(){champs.push(firstChamp)},100);


Q:

Create an ActiveRecord database table with no :id column?

Is it possible for me to create and use a database table that contains no :id column in ActiveRecord, Ruby on Rails.
I don't merely want to ignore the id column, but I wish it to be absolutely non-existent.
Table Example

:key_column                         :value_column
0cc175b9c0f1b6a831c399e269772661    0cc175b9c0f1b6a831c399e269772661
4a8a08f09d37b73795649038408b5f33    0d61f8370cad1d412f80b84d143e1257
92eb5ffee6ae2fec3ad71c777531578f    9d5ed678fe57bcca610140957afab571

Any more info ( like an :id_column ) would break the whole feature.
How would I implement something like this in rails?

A:

yup, looks like this:
create_table :my_table, id: false do |t|
  t.string :key_column
  t.string :value_column
end

just make sure to include the
id: false

part.


Q:

If my input is January and year is 2016 then it need to take input as 01-jan-16to 31-jan-16

I need to do that in my procedure. Customer mention January and the year. My procedure received only month and year, but I need to convert this month and year in to 01-month-year to 31-month-year.

A:

You can use to_date function to convert string to date (first date of the month) and then use add_month to add 1 month and then -1 day to calculate last day of the month (Or use last_day function) as following:
Start_date := to_date(in_month|| '-' || in_year,'month-yyyy');
End_date := last_day(start_date);
-- or
End_date := add_months(start_date,1) - 1;

Cheers!!


Q:

feedback for exercise 4-11 in KR

I know that there is one more topic about the exercise 4-11, but the difference is that I solved this exercise and i just need some feedback on my solution. So, I'll explain how it works on an output like "3 4 +\n", for example. The static variable c is initialized with the value ' ' so the condition of the first if statement evaluates to true, the while loop within the if statement will run until c reaches the value '3'. Because it is a number, the function will return the NUMBER signal and the variable c will get the value ' ' - the value that breaks the loop within the 3rd if statement.
Now we are, again, on the first if statement and, again,  c has the value ' '. The condition is evaluated to true and the loop within the if statement will run until c reaches the value '4'.
Again, because '4' is a "number" the function will return the NUMBER signal and c will get the value '+' - the value that breaks the loop within the 3rd if statement.
This time c is equal to '+' and the condition of the first if statement is evaluated to false, so the value '+' will be returned. I saved the value of the variable c in a temporary variable tmp, and initialize tmp with the value of c before changing it to ' '.
Without this movement I'll get an infinite loop.
The program is made of 5 parts:
main.c
#include <stdio.h>
#include <stdlib.h>
#include "calc.h"
#define MAXOP 1001

int main() {
    char entry;
    char s[MAXOP];
    double op2;

    while((entry = getop(s)) != EOF) {
        switch(entry) {
            case NUMBER:
                push(atof(s));
                break;
            case '+':
                push(pop() +pop());
                break;
            case '*':
                push(pop() * pop());
                break;
            case '-':
                op2 = pop();
                push(pop() - op2);
                break;
            case '/':
                op2 = pop();
                if(op2) {
                    push(pop() / op2);
                }
                else {
                    printf("can't divide by 0");
                }
                break;
            case '\n':
                printf("The value is: %f \n", pop());
                break;
            default:
                printf("Unrecognized command %s\n", s);
                break;
        }
    }

    return 0;
}

getch.c
#include <stdio.h>
#define MAXBUF 100

static char buf[MAXBUF];
static int bufp = 0; /* next free position in buffer */

int getch(void) {
    return (bufp > 0) ? buf[--bufp] : getchar();
}

void ungetch(int c) {
    if(bufp < MAXBUF) {
        printf("ungetch has been called\n");
        buf[bufp++] = c;
    }
    else {
        printf("the buffer is full\n");
    }
}

stack.c
#include <stdio.h>
#define MAXSTACK 100

static double stack[MAXSTACK];
static int sp = 0; /* next free position in stack */

void push(double f) {
    if(sp < MAXSTACK) {
        printf("\t--> the value %f has been pushed\n", f);
        stack[sp++] = f;
    }
    else {
        printf("error: the stac is full\n");
    }
}

double pop(void) {
    if(sp > 0) {
        return stack[--sp];
    }
    else {
        printf("error: the stack is empty!\n");
        return 0.0;
    }
}

calc.h
#define NUMBER '0'
#define MAXLINE 1000

/*stack related functions */
void push(double f);
double pop(void);

/* output */
int getch(void);
void ungetch(int c);

/* filtration fuctions */
int getop(char s[]);

and getop.c
#include <stdio.h>
#include <ctype.h>
#include "calc.h"

int getop(char s[]) {
    int i, tmp;
    static int c = ' ';

    if((s[0] = c) == ' ' || c == '\t') {
        while((s[0] = c = getch()) == ' ' || c == '\t')
            ;
    }

    s[1] = '\0';
    if(!isdigit(c) && c != '.') {
        tmp = c;
        c = ' ';
        return tmp;
    }

    i = 0;
    if(isdigit(c)) {
        while(isdigit((s[++i] = c = getch())))
            ;
    }
    if(c == '.') {
         while(isdigit((s[++i] = c = getch())))
            ;
    }

    s[i] = '\0';

    return NUMBER;
}

A:

Comments on getop() only:
Your initial loop repeats the exit condition twice.  It (and subsequent code)
also contains double assignments, which are unnecessary and generally better
avoided:
if((s[0] = c) == ' ' || c == '\t') {
    while((s[0] = c = getch()) == ' ' || c == '\t')
        ;
}

Here is a simpler version:
while (c == ' ' || c == '\t') {
    c = getch();
}
s[0] = c;

Your loop to read a number is repeated and repetition is normally undesirable.
The loop could be extracted into a function and called twice:
static int get_number(char *s)
{
    int c = getch();
    for (; isdigit(c); c = getch()) {
        *s++ = c;
    }
    *s = '\0';
    return c;
}

On end of file, this returns EOF.
Note that you should probably handle invalid input such as "1.2.3"
In main
char entry;
...
while((entry = getop(s)) != EOF) {

entry should really be an int


Q:

In Karabiner, can I map to a modified key from a hyperkey that is comprised of all modifiers?

I have my CapsLock mapped as a hyperkey. (See bottom of question for its configuration, if needed.)
I know it works, because I've successfully mapped HyperKey+h / j / k / l to arrows, vi-style. Here's how one of the keys are configured, for example:
    {
      "type": "basic",
      "from": {
        "key_code": "k",
        "modifiers": {
          "mandatory": [
            "left_shift",
            "control",
            "option",
            "command"
          ],
          "optional": [
            "any"
          ]
        }
      },
      "to": [
        {
          "key_code": "up_arrow"
        }
      ]
    },

But now I'm trying to map such a combo to an arrow with a modifier, e.g. HyperKey+g / ; to Home and End, i.e. Command+Left / Right, like this:
    {
      "type": "basic",
      "from": {
        "key_code": "g",
        "modifiers": {
          "mandatory": [
            "left_shift",
            "control",
            "option",
            "command"
          ],
          "optional": [
            "any"
          ]
        }
      },
      "to": [
        {
          "key_code": "left_arrow",
          "modifiers": ["command"]
        }
      ]
    },

But that doesn't work. Is it that I can no longer map to modified keys because the hyperkey setup already "consumes" all the modifier keys? Or something else? Is there a way to get this to work?

Appendix: The HyperKey setup in karabiner.json
This was copied from another resource, and I've gotten it to work. This is just for reference in case one needs to see the details of the hyperkey setup.
"profiles": [
    {
        "complex_modifications": {
            "parameters": {
                "basic.simultaneous_threshold_milliseconds": 50,
                "basic.to_delayed_action_delay_milliseconds": 500,
                "basic.to_if_alone_timeout_milliseconds": 1000,
                "basic.to_if_held_down_threshold_milliseconds": 500
            },
            "rules": [
                {
                    "manipulators": [
                        {
                            "description": "Change caps_lock to command+control+option+shift.",
                            "from": {
                                "key_code": "caps_lock",
                                "modifiers": {
                                    "optional": [
                                        "any"
                                    ]
                                }
                            },
                            "to": [
                                {
                                    "key_code": "left_shift",
                                    "modifiers": [
                                        "left_command",
                                        "left_control",
                                        "left_option"
                                    ]
                                }
                            ],
                            "to_if_alone": [
                                {
                                    "key_code": "escape",
                                    "modifiers": {
                                        "optional": [
                                            "any"
                                        ]
                                    }
                                }
                            ],
                            "type": "basic"
                        }
                    ]
                },
                {
                    "description": "Change fn + hjkl' to arrow keys",
                    "manipulators": [
                        {
                            "from": {
                                "key_code": "k",
                                "modifiers": {
                                    "mandatory": [
                                        "left_shift",
                                        "control",
                                        "option",
                                        "command"
                                    ],
                                    "optional": [
                                        "any"
                                    ]
                                }
                            },
                            "to": [
                                {
                                    "key_code": "up_arrow"
                                }
                            ],
                            "type": "basic"
                        },
                        {
                            "from": {
                                "key_code": "h",
                                "modifiers": {
                                    "mandatory": [
                                        "left_shift",
                                        "control",
                                        "option",
                                        "command"
                                    ],
                                    "optional": [
                                        "any"
                                    ]
                                }
                            },
                            "to": [
                                {
                                    "key_code": "left_arrow"
                                }
                            ],
                            "type": "basic"
                        },
                        {
                            "from": {
                                "key_code": "j",
                                "modifiers": {
                                    "mandatory": [
                                        "left_shift",
                                        "control",
                                        "option",
                                        "command"
                                    ],
                                    "optional": [
                                        "any"
                                    ]
                                }
                            },
                            "to": [
                                {
                                    "key_code": "down_arrow"
                                }
                            ],
                            "type": "basic"
                        },
                        {
                            "from": {
                                "key_code": "l",
                                "modifiers": {
                                    "mandatory": [
                                        "left_shift",
                                        "control",
                                        "option",
                                        "command"
                                    ],
                                    "optional": [
                                        "any"
                                    ]
                                }
                            },
                            "to": [
                                {
                                    "key_code": "right_arrow"
                                }
                            ],
                            "type": "basic"
                        }
                    ]
                }
            ]
        },
        "devices": [
            {
                "disable_built_in_keyboard_if_exists": false,
                "fn_function_keys": [],
                "identifiers": {
                    "is_keyboard": true,
                    "is_pointing_device": false,
                    "product_id": 610,
                    "vendor_id": 1452
                },
                "ignore": false,
                "manipulate_caps_lock_led": true,
                "simple_modifications": []
            },
            {
                "disable_built_in_keyboard_if_exists": false,
                "fn_function_keys": [],
                "identifiers": {
                    "is_keyboard": true,
                    "is_pointing_device": false,
                    "product_id": 597,
                    "vendor_id": 1452
                },
                "ignore": false,
                "manipulate_caps_lock_led": true,
                "simple_modifications": []
            }
        ],
        "fn_function_keys": [
            {
                "from": {
                    "key_code": "f1"
                },
                "to": {
                    "key_code": "vk_consumer_brightness_down"
                }
            },
            {
                "from": {
                    "key_code": "f2"
                },
                "to": {
                    "key_code": "vk_consumer_brightness_up"
                }
            },
            {
                "from": {
                    "key_code": "f3"
                },
                "to": {
                    "key_code": "vk_mission_control"
                }
            },
            {
                "from": {
                    "key_code": "f4"
                },
                "to": {
                    "key_code": "vk_launchpad"
                }
            },
            {
                "from": {
                    "key_code": "f5"
                },
                "to": {
                    "key_code": "vk_consumer_illumination_down"
                }
            },
            {
                "from": {
                    "key_code": "f6"
                },
                "to": {
                    "key_code": "vk_consumer_illumination_up"
                }
            },
            {
                "from": {
                    "key_code": "f7"
                },
                "to": {
                    "key_code": "vk_consumer_previous"
                }
            },
            {
                "from": {
                    "key_code": "f8"
                },
                "to": {
                    "key_code": "vk_consumer_play"
                }
            },
            {
                "from": {
                    "key_code": "f9"
                },
                "to": {
                    "key_code": "vk_consumer_next"
                }
            },
            {
                "from": {
                    "key_code": "f10"
                },
                "to": {
                    "key_code": "mute"
                }
            },
            {
                "from": {
                    "key_code": "f11"
                },
                "to": {
                    "key_code": "volume_down"
                }
            },
            {
                "from": {
                    "key_code": "f12"
                },
                "to": {
                    "key_code": "volume_up"
                }
            }
        ],
        "name": "Default profile",
        "one_to_many_mappings": {},
        "selected": true,
        "simple_modifications": [],
        "standalone_keys": {},
        "virtual_hid_keyboard": {
            "caps_lock_delay_milliseconds": 0,
            "country_code": 0,
            "keyboard_type": "ansi",
            "standalone_keys_delay_milliseconds": 200
        }
    },

A:

Okay, figured it out. Here's what I was doing wrong / my misconceptions:

I wasn't sure why the mappings existed in both karabiner.json and assets/complex_modifications/my_mappings.json. The important one is the latter. When you reload Karabiner it seems to copy those mappings into karabiner.json.
I had to use semicolon for the mapping, not ;.


Q:

Wrapping HTML in an app for Android

I have an existing site (social in nature) and it already has a mobile web version too, so what I basically want to do is wrap that view in an Android app and maybe add a nice splash screen to it. So essentially a "branded" browser window.
Any advice would be appreciated.

A:

You would need two activites

Splash Screen (use a timer and after x seconds move to the next activity)
Main

In the main activity you would need to set a layout with a webView in your layout so something like:
<?xml version="1.0" encoding="utf-8"?>
<WebView  xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/webview"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
/>

and the code:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.loadUrl("http://www.google.com");
}

and the permissions:
<uses-permission android:name="android.permission.INTERNET" />

in the manifest file.
If you want to turn the title bar off  you will also need to add:
<activity android:name=".Main" android:label="@string/app_name"
 android:theme="@android:style/Theme.NoTitleBar">

Read the docs for more help! An example for Google for this exactly and I referenced is http://developer.android.com/resources/tutorials/views/hello-webview.html

A:

There also exist several frameworks that wrap HTML5 inside a native app and gives you access to APIs.
Phonegap is the most well-known
http://phonegap.com/


Q:

Can not reversed sort of ArrayList in java

Today I would like to sort my List of Movie by rating. I use sort method like below and it works fine till I would like to make a reversed order.
List<Movie> result = movieRepository.findAll();
result.sort(Comparator.comparing(m->m.getRating()));

That works perfect however when I try to do something like that:
 List<Movie> result = movieRepository.findAll();
 result.sort(Comparator.comparing(m->m.getRating()).reversed());

It shows me that:Cannot resolve method getRating(). So he can resolve it until I try to make it reversed order? What is going on here?

A:

AFAIK, there's some bug in compiler that they somehow can't guess the correct type when chaining Comparator.
In your case you can workaround by using method reference:
List<Movie> result = movieRepository.findAll();
result.sort(Comparator.comparing(Movie::getRating).reversed());


Q:

INVALID_ENUM using glew

I'm currently trying to program a litte game in c++ using SDL and glew. My problem is that whenever I try to use on of glew's functions (for example: glMatrixMode(GL_PROJECTION)), I get this error: GL_INVALID_ENUM.
That is how I create the window:
SDL_Init(SDL_INIT_EVERYTHING);

SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3);
SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);

window = SDL_CreateWindow(title.c_str(), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);
context = SDL_GL_CreateContext(window);

SDL_GL_SetSwapInterval(1);

That's the way how I initialize glew:
glewExperimental = GL_TRUE;
GLenum res = glewInit();
if (res != GLEW_OK) fprintf(stderr, "Error: '%s'\n", glewGetErrorString(res));

I tried to disable glewExperimental aswell but it changed nothing.

A:

The problem was that I was using the core profile of OpenGL instead of using the compatibility profile to use deprecated parts of API. To solve this should replace
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);

with:
SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_COMPATIBILITY);


Q:

How to manage a large SQL Server database: transaction log, reduce size, alter table

Hello I have some confusion on how to manage a large SQL Server database.
Let's say size is 15GB, with 3GB available, in simple recovery mode.
Server is not managed by me, I cannot change the size, not even temporarily, nor detach/reattach backup/restore.
Let's say I can only manage the data and the structure of the database.
If I want to alter a table, to add a column, or delete only certain rows (before a datetime), or want to NULL a few nvarchar(MAX) columns to save space, how does this impact?
Often I receive the error "no more log space".
Then I shrink the DB, nothing has changed, and I have less space free...
I don't need the transaction log, so what can I do to perform these operations without incurring in error messages regarding the transaction log size?
Thanks!

A:

Points, in no particular order:

You do need the transaction log for a whole bunch of reasons I'm not going to go into. That said, if you're running out of transaction log space while you're in simple recovery mode, that probably means you have long-running transactions. Make your transactions as short as possible (gather all required user input before you start a transaction). (When SQL Server is trying to free log space, it can only free up to the start of the oldest current transaction.)
Making NVARCHAR(MAX) columns nullable will not necessarily save you much space (off the top of my head it'll be 2 bytes per row, per column).
Deleting/archiving old data will help you - with a caveat that it has to pass through the transaction log first.
Shrinking your database will not help you, as a matter of fact it will kill performance (both while it's running and afterward, since DBCC SHRINKDATABASE uses a naive algorithm that almost perfectly fragments your indexes) and won't regain you much if any space.


Q:

I made a chat app with Node.JS and Socket IO. How do you upload to a domain?

I successfully made a chatroom that is based on node.JSs socket.io package. So I have basically one .html file in and a couple of .js files.
So basically what I have currently is the foundation for a website with a chat app.
My question is, is there something I need to think before uploading this to a domain? Will the chat app still be working when I upload it with something like say FileZilla?

A:

You need a webserver that at least runs runs node.js. There are some PaaS solutions out here you can check out here: https://geekflare.com/nodejs-hosting-platform/
For a small application I can recommend Heroku. What you have to do is described here: https://devcenter.heroku.com/articles/getting-started-with-nodejs
If you already have some webspace and this question isn't meant as the beginner level might sound, you need can upload your stuff with any software to your server.


Q:

OSX Sierra /usr/bin/env: ‘mysqldump’: No such file or directory

Having issues running a shell script that invokes mysqdump to import the database. This is for the importing of a WordPress database from production to local dev machine. It worked in the past. But something must have changed on my local MacOs Mac Mini running OSX Sierra.
This is the script:
# sync-prod.sh
read -r -p "Do you solemnly swear that you have had fewer than 2 alcoholic beverages in the last hour and that you would really like to reset your development database and pull the latest from production? [y/N] " response
if [[ $response =~ ^([yY][eE][sS]|[yY])$ ]]
then
    wp @development db reset --yes
    wp @production db export - > sql-dump-production.sql
    wp @development db import sql-dump-production.sql
    wp @development search-replace https://example.com http://example.test
else
    exit 0
fi

when I run it I get:
./sync-production.sh
Do you solemnly swear that you have had fewer than 2 alcoholic beverages in the last hour and that you would really like to reset your development database and pull the latest from production? [y/N] y
Success: Database reset.
/usr/bin/env: ‘mysqldump’: No such file or directory
Success: Imported from 'sql-dump-production.sql'.
Error: The site you have requested is not installed.

When I run mysqldump
jasper@~/webdesign/example.com/site $ which mysqldump
/usr/local/bin/mysqldump

from the terminal it starts fine:
$ mysqldump
Usage: mysqldump [OPTIONS] database [tables]
OR     mysqldump [OPTIONS] --databases [OPTIONS] DB1 [DB2 DB3...]
OR     mysqldump [OPTIONS] --all-databases [OPTIONS]
For more options, use mysqldump --help

Read env: mysql: No such file or directory after `wp import` and tried adjusting the $PATH and now have
echo $PATH
/usr/local/sbin:/usr/local/mysql/bin:/usr/local/sbin:/usr/local/sbin:/usr/local/sbin:/usr/local/sbin:/Users/jasper/.rvm/gems/ruby-2.3.3/bin:/Users/jasper/.rvm/gems/ruby-2.3.3@global/bin:/Users/jasper/.rvm/rubies/ruby-2.3.3/bin:/usr/local/sbin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/Users/jasper/.composer/vendor/bin:/usr/local/bin:/Users/jasper/.rvm/bin:/Users/jasper/.composer/vendor/bin:/usr/local/bin:/usr/local/mysql/bin:/Users/jasper/.composer/vendor/bin:/usr/local/bin:/usr/local/bin/mysql:/Users/jasper/.composer/vendor/bin:/usr/local/bin:/usr/local/bin/mysql:/Users/jasper/.composer/vendor/bin:/usr/local/bin:/usr/local/bin/mysql:/Users/jasper/.composer/vendor/bin:/usr/local/bin:/usr/local/bin/mysql

In .bash_profile I have
alias ll='ls -lGaf'
export PATH="/usr/local/sbin:$PATH"
export PATH="$PATH:$HOME/.composer/vendor/bin"
export PATH=$PATH:/usr/local/bin
export PATH=$PATH:/usr/local/bin/mysql
[[ -s "$HOME/.rvm/scripts/rvm" ]] && source "$HOME/.rvm/scripts/rvm" # Load RVM into a shell session *as a function*

###-tns-completion-start-###
if [ -f /Users/jasper/.tnsrc ]; then
    source /Users/jasper/.tnsrc
fi
###-tns-completion-end-###
export PS1="\u@\w $ "

When I run wp @production db check things do connect and are fine. I also can connect to the database over ssh using the same username and password using SequelPro..
Any ideas why I still get no such file or directory for running mysql as part of this script?

A:

The remote server did (no longer) have mysql-client installed. Once I did apt install mariadb-client-10 things started working again:
wp @production db export sql-dump-production.sql
Success: Exported to 'sql-dump-production.sql'.

and I could also run:
./sync-production.sh
Do you solemnly swear that you have had fewer than 2 alcoholic beverages in the last hour and that you would really like to reset your development database and pull the latest from production? [y/N] y
Success: Database reset.
Success: Imported from 'sql-dump-production.sql'.
.........


Q:

How to specify "terminal-speed" option explicitly in native linux GNU telnet client?

I'd like to be able to set the terminal-speed option explicitly in a native Linux GNU telnet client.
Some context to my problem:
I'm unable to login to an HPUX host using telnet when the telnet process is created by a Java program.
When I telnet to the HPUX host from the command line (from bash), I am able to login and use the session.
When I spawn the telnet process from Java, something strange happens. I am prompted for the username and submit it. I also get the prompt for the password. But for some reason the telnet server does not wait for the password; it quits the session before it is sent.
Looking at the exchange in wireshark, I see that as soon as the telnet client sends an ACK for the password prompt, the server sends a FIN packet, terminating the initializing session.
One of the differences I can see in the handshaking leading up to the password prompt is that the server asks for the terminal speed. When running telnet from the command line, the terminal speed it sends is 38400,38400. When running telnet from Java, the terminal speed is 0,0.

A:

I'm guessing the telnet client needs a terminal to be able to quote a terminal speed, and I'm guessing that when it's started from Java, there is no tty associated with the process. Depending on your use case, you could try spawning an xterm and running telnet inside that.
If that isn't acceptable, and you can't find a way to set this explicitly using the GNU telnet client, you may want to try using a native Java telnet API mentioned by another poster instead of spawning an external process.


Q:

Java casting Object/String arrays

I'm playing with Java to see how it works but I have some doubts about some kind of castings. Consider the following piece of code:
String[][] s = null;
Object[] o = null;

o = (Object[][]) s; // compile-time correct

Now, consider the following example:
Object[][] o = null;
String[] s = null;

s = (String[]) o; // compile-time error: Cannot cast from Object[] to String[]

Why does that happen? I'm confused.

A:

It's failing because it's deterministically (i.e. always and can only ever be) wrong.
o necessarily contains arrays of objects.  These can NEVER be Strings.
The first sample you have, a String array can be typed as an object.
We can illustrate this if we remove an "array nesting".
Consider:
String[] myStringArray = null;  //instantiation not important
Object someObj = myStringArray; //no problem since arrays are Objects

What you're doing in the second example amounts to
Object[] myObjectArray = null;  //instantiation not important
String someString = myObjectArray; //compile time error, since an Object[] is never a String


Q:

WinForm richtextbox SelectionColor bug

I have a winform project, using richtextbox. The code;
List<string> list = new List<string>();
        list.Add("S\nS");
        list.Add("*S\nS");
        list.Add("S\nS");
        list.Add("*S\nS");

        for (int s = 0; s < list.Count; s++)
        {
            if (list.ElementAt(s)[0] == '*')
            {
                richTextBox1.SelectionColor = Color.Red;
                richTextBox1.AppendText(list.ElementAt(s).Substring(1, list.ElementAt(s).Length - 1));
                if (s != list.Count - 1) richTextBox1.AppendText("\r\n\r\n");
            }
            else
            {
                richTextBox1.SelectionColor = Color.Black;
                richTextBox1.AppendText(list.ElementAt(s));
                if (s != list.Count - 1) richTextBox1.AppendText("\r\n\r\n");
            }
        }

First code result:

Other code, The only thing changing "S" instead of "Ş":
List<string> list = new List<string>();
        list.Add("Ş\nŞ");
        list.Add("*Ş\nŞ");
        list.Add("Ş\nŞ");
        list.Add("*Ş\nŞ");

        for (int s = 0; s < list.Count; s++)
        {
            if (list.ElementAt(s)[0] == '*')
            {
                richTextBox1.SelectionColor = Color.Red;
                richTextBox1.AppendText(list.ElementAt(s).Substring(1, list.ElementAt(s).Length - 1));
                if (s != list.Count - 1) richTextBox1.AppendText("\r\n\r\n");
            }
            else
            {
                richTextBox1.SelectionColor = Color.Black;
                richTextBox1.AppendText(list.ElementAt(s));
                if (s != list.Count - 1) richTextBox1.AppendText("\r\n\r\n");
            }
        }

Second Code Result:

Why is black "Ş" characters of The second lines in second code? What is the problem, does not supported my culture or are there any bug in richtextbox?

A:

Your code works on my sample but we may have different .NET versions, environment and so on. Please try this code, it sets the selection boundaries to appropriate values and should solve the problem you have shown in the example results:
List<string> list = new List<string>();
list.Add("Ş\nŞ");
list.Add("*Ş\nŞ");
list.Add("Ş\nŞ");
list.Add("*Ş\nŞ");

for (int s = 0; s < list.Count; s++)
{
    var diffColor = list.ElementAt(s)[0] == '*';
    var txtLength = richTextBox1.Text.Length;
    var myString = diffColor ? list.ElementAt(s).Substring(1, list.ElementAt(s).Length - 1) : list.ElementAt(s);

    richTextBox1.AppendText(myString);
    richTextBox1.SelectionStart = txtLength;
    richTextBox1.SelectionLength = myString.Length;
    richTextBox1.SelectionColor = diffColor ? Color.Red : Color.Black;

    if (s != list.Count - 1) richTextBox1.AppendText("\r\n\r\n");
}

richTextBox1.Select(0,0);

If black is used by default and you just want to mark certain parts to red this code may be refactored to:
List<string> list = new List<string>();
list.Add("Ş\nŞ");
list.Add("*Ş\nŞ");
list.Add("Ş\nŞ");
list.Add("*Ş\nŞ");

for (int s = 0; s < list.Count; s++)
{
    var diffColor = list.ElementAt(s)[0] == '*';
    var txtLength = richTextBox1.Text.Length;
    var myString = diffColor ? list.ElementAt(s).Substring(1, list.ElementAt(s).Length - 1) : list.ElementAt(s);

    richTextBox1.AppendText(myString);

    if (diffColor)
    {
        richTextBox1.SelectionStart = txtLength;
        richTextBox1.SelectionLength = myString.Length;
        richTextBox1.SelectionColor = Color.Red;
        richTextBox1.Select(0, 0);
    }

    if (s != list.Count - 1) richTextBox1.AppendText("\r\n\r\n");
}


Q:

What happened to TicketMonster?

https://developers.redhat.com/ticket-monster/ links to a live demo at http://ticketmonster-jdf.rhcloud.com/, but it appears to be down or have been removed. Is there another live example of this demo app somewhere?

A:

It was deployed on OpenShift v2 Online which as been decomissioned. We are working on the migration to OpenShift v3


Q:

How to copy text from one file to another and then turning the first letters of the text string into uppercase

I am trying to build a program that copies text from one .txt file to another and then takes the first letter of each word in the text and switches it to an uppercase letter. So far, I have only managed to copy the text with no luck or idea on the uppercase part. Any tips or help would be greatly appreciated. This is what I have so far:
int main()
{
    std::ifstream fin("source.txt");
    std::ofstream fout("target.txt");
    fout<<fin.rdbuf(); //sends the text string to the file "target.txt"

    system("pause");
    return 0;
}

A:

Try this,  Take the file content to a string, then process it, and again write to the traget file.
int main()
{
  std::ifstream fin("source.txt");
  std::ofstream fout("target.txt");
  // get pointer to associated buffer object
  std::filebuf* pbuf = fin.rdbuf();
  // get file size using buffer's members
  std::size_t size = pbuf->pubseekoff (0,fin.end,fin.in);
  pbuf->pubseekpos (0,fin.in);
  // allocate memory to contain file data
  char* buffer=new char[size];
  // get file data
  pbuf->sgetn (buffer,size);
  fin.close();
  locale loc;
  string fileBuffer = buffer;
  stringstream ss;
  for (std::string::size_type i=0; i<fileBuffer.length(); ++i){
    if(i==0)
      ss << toupper(fileBuffer[i],loc);
    else if (isspace(c))
      ss << fileBuffer[i] << toupper(fileBuffer[++i],loc);
    else
      ss << fileBuffer[i];
  }

  string outString = ss.str();

  fout << outString;
  fout.close();

}


Q:

Thousand of concurrent requests - EAI_AGAIN/ECONNRESET error

I need to perform a million API calls in under an hour (The server can handle this much traffic), for this, I'm using node to run multiple requests in parallel, but when I try to run ~1000 concurrent requests I keep getting these errors:
EAI_AGAIN
{ [Error: getaddrinfo EAI_AGAIN google.com:80]
  code: 'EAI_AGAIN',
  errno: 'EAI_AGAIN',
  syscall: 'getaddrinfo',
  hostname: 'google.com',
  host: 'google.com',
  port: 80 }

ECONNRESET
{
    [Error: read ECONNRESET] code: 'ECONNRESET',
    errno: 'ECONNRESET',
    syscall: 'read'
}

How can I prevent this from happening, without reducing the requests to 500?
Here's a code sample that works perfectly when running 500 requests at a time, but fails when the limit is over 1000. (Your limit may be different).
"use strict";
const http = require('http');
http.globalAgent.maxSockets = Infinity;
const async = require('async');
const request = require("request");

let success = 0;
let error = 0;

function iterateAsync() {
    let rows = [];
    for (let i = 0; i < 500; i++) {
        rows.push(i);
    }

    console.time("Requests");
    async.each(
        rows,
        (item, callback) => get(callback),
        (err) => {
            console.log("Failed: " + error);
            console.log("Success: " + success);
            console.timeEnd("Requests");
    });
}

function get(callback) {

    request("http://example.com", (err, response, body) => {
        if (err) {
            console.log(err);
            error++;
            return callback();
        }

        success++;
        callback();
    });
}

iterateAsync();

I added http.globalAgent.maxSockets = Infinity; even though is the default value.
500 requests

1000 requests

Aditional info:
I'm running the tests on ubuntu 14.04 & 15.04 and I modified file-max, tcp_fin_timeout, tcp_tw_reuse, ip_local_port_range default values in /etc/sysctl.conf as described in this post

file-max: 100000
tcp_fin_timeout: 15
tcp_tw_reuse: 1
ip_local_port_range: 10000 65000

Added following lines in /etc/security/limits.conf
*     soft    nofile          100000
*     hard    nofile          100000

With this values, I'm still getting the error.
I've read all other similar posts:

httpd - Increase number of concurrent requests
Thousands of concurrent http requests in node
Increasing the maximum number of tcp/ip connections in linux

Is there a way I can know the exact number of concurrent requests that my system can manage?

A:

Here's how I solved it following @jfriend00 input.
I resolve the host IP address using dns.resolve4 and then perform the requests using the IP, that way the error is gone, and I can perform more requests in less time.
"use strict";

const dns = require("dns");
const http = require('http');

http.globalAgent.maxSockets = Infinity;

const async = require('async');
const request = require("request");

let success = 0;
let error = 0;

function iterateAsync() {
    let rows = [];
    for (let i = 0; i < 500; i++) {
        rows.push(i);
    }

    console.time("Requests");

    dns.resolve4("example.com", (err, addresses) =>{ //Resolve host and obtain IP address

        if(err) //Handle error
            return false;

        async.each(
            rows,
            (item, callback) => get(`http://${addresses[0]}`, callback),
            (err) => {
                console.log("Failed: " + error);
                console.log("Success: " + success);
                console.timeEnd("Requests");
            });

    });

}

function get(host, callback) {

    request(host, (err, response, body) => {
        if (err) {
            console.log(err);
            error++;
            return callback();
        }

        success++;
        callback();
    });
}

//Start requests
iterateAsync();

Output:
Failed: 0
Success: 500
Requests: 6295.799ms


Q:

No logged in user in Authenticate middleware but in other Middlewares

Introduction
My problem is, that I have no logged in user when trying to use the auth middleware to restrict a route to logged in users but I do have one when getting redirected back to the login page.
Details
Let's just assume I have only these two routes
Route with web middleware
$router->group(['middleware' => 'web'], function($router) {
    /** @var Registrar $router */
    $router->get('/', ['as' => 'home', 'uses' => 'HomeController@index']);
});

Route with auth middleware
$router->group(['middleware' => 'auth'], function($router) {
    $router->get('/listings', ['as' => 'listings', 'uses' => 'ListingController@index']);
});

The first route works without problems, the second route however redirects me back to the login page. This should only be done, when I have no logged in user, but I logged in before! Which is weird.
When I add these two lines of code to the handle function of the Middleware Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse which is used in the web group
$user = \Auth::user();
dd($user);

I'm getting a dump of a the currently logged in user object. However, when adding those lines in the FeedParser\Http\Middleware\Authenticate Middleware I'm getting null as a dump. How can it be, that the user is logged in in the one middleware, but not in the other? What do I need to do to make it work again? Or better: What more information would you need to help me solve the problems
Updates
If someone asks for more information or more code I will post it here

A:

I imagine this happened after upgrading to 5.2?
I believe the route should include both the web and the auth middleware, such as:
Route::group(['middleware' => ['web', 'auth']], function() {
    Route::get('home', 'HomeController@dashboard')->name('home');
});


Q:

Filling input field with expression language issue

I have problem with filling input field with request attribute using expression language. It's work correct when i display this attribute using for example ${title}but when I trying fill input by this way <input name="bookTitle" type="text" value=${title} > it only fill one first word. What I doing wrong?
My code below:
editBook.jsp

                        Title
                        <input name="bookTitle" type="text"
                            value=${title} >

adminPanel.jsp
Edit
editBookServlet.java
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String title = request.getParameter("bookTitle");
request.setAttribute("title", title);
request.getRequestDispatcher("/editBook.jsp").forward(request, response);
}

A:

try to wrap value=${title} in the quotes like this:
value="${title}"


Q:

SignalR Client Connection has been not established

I created a SignalR Selfhosted application but can not access via browsers or Windows Phone (which is my client). I followed several tutorials and they pretty much say the same thing, I believe that the error is on my network configuration also notice that when you run the project, the IIS does not fire (not sure if it is also required).
SignalRServer:
class Program : Hub
    {
        private static HubConnection Connection { get; set; }
        private static IHubProxy HubProxy { get; set; }

        const string Url = "http://*:8080";

        static void Main(string[] args)
        {
            // This will *ONLY* bind to localhost, if you want to bind to all addresses
            // use http://*:8080 to bind to all addresses.
            // See http://msdn.microsoft.com/en-us/library/system.net.httplistener.aspx
            // for more information.

            using (WebApp.Start(Url))
            {
                Console.WriteLine("Servidor rodando em {0}", Url);
                Console.ReadLine();
            }
        }

        private static void Connection_Closed()
        {
            Connection = null;
        }
    }

    class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);
            app.MapSignalR();
        }
    }

The error is:

The connection has not been established.

My Client class:
public class SignalRService : PhoneApplicationPage
    {
        public String UserName { get; set; }

        public IHubProxy HubProxy { get; set; }

        private const string ServerURI = "http://localhost:8080";

        public HubConnection Connection { get; set; }

        public SignalRService()
        {
            UserName = "Luizaooo";

            ConnectAsync();
        }

        public void ObterAtualizacoesProdutos()
        {
            ProdutoService produtoService = new ProdutoService();
            var dataHora = produtoService.ObterDataHoraUltimaAtualizacao();
            HubProxy.Invoke("ObterAtualizacoes", dataHora);
            MessageBox.Show("passou");
        }

        private async void ConnectAsync()
        {
            Connection = new HubConnection(ServerURI);
            Connection.Closed += Connection_Closed;
            HubProxy = Connection.CreateHubProxy("ProdutoHub");

            HubProxy.On<List<Produto>>("AtualizarProdutos", (ListaDeProdutos) =>
                this.Dispatcher.BeginInvoke(() =>
                {
                    var a = ListaDeProdutos;
                }));

            try
            {
                await Connection.Start();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.Message);
                return;
            }
        }

        private void Connection_Closed()
        {
            Connection = null;
        }
    }

A:

Getting the Startup class to be recognized correctly can be tricky, especially in self-host scenarios.
For your code, first check if the Configuration method is actually running. If it isn't, add
[assembly: OwinStartup(typeof(Program.Startup))]

above the namespace decleration as described here: Owin Startup Detection
You can bypass this problem entirely by using the overload of WebApp.Start that takes a predicate:
 WebApp.Start(url, new Action<IAppBuilder>((app) =>
 {
     app.UseCors(CorsOptions.AllowAll);
     app.MapSignalR();
 }));

Either way, test your connection by navigating to http://localhost:8080/signalr/hubs . If that shows you a signalR javascript file, you will know that your service is up and running


Q:

Adding manager attribute fails

I have a script that matches a contact based on an email in a csv, I can find the contact using a get-adobject -ldapfilter but when I try to add the contact as a manager the add fails stating it cannot find the contact.  The contact it states it cannot find is clearly present in the directory.
This line will find the contact:
$rmanager = Get-ADObject -SearchBase 'OU=workplace,OU=Contacts,DC=office,DC=com' -ldapfilter "(&(objectclass=contact)(name=$fname*)(name=*$lname))"

An example of the contact in question being found...
PS C:\temp> Get-ADObject -SearchBase 'OU=workplace,OU=Contacts,DC=office,DC=com' -ldapfilter "(&(objectclass=contact)(name=$fname*)(name=*$lname))"

DistinguishedName Name ObjectClass ObjectGUID
----------------- ---- ----------- ----------
CN=Nick Hill,OU=workplace,OU=Contacts,DC=office,DC=com Nick Hill contact b649bd7e-aac9-4d4b-8203-b6a79f35b91

However, this line with the set-aduser will fail stating it cannot find the contact that clearly exists...
get-aduser -f {mail -eq $username} |set-aduser -Manager "$rmanager"

set-aduser : Identity info provided in the extended attribute: 'Manager' could not be resolved. Reason: 'Cannot find an object with identity: 'CN=Nick Hill,OU=Workplace,OU=Contacts,DC=office,DC=com' under: 'DC=Office,DC=com'.'.

A:

I just tested this and it worked:
a. Get distinguishedName of contact:
$contactDN = Get-ADObject -LDAPFilter "(&(objectClass=contact)(givenName=firstname)(sn=lastname))"
  | Select-Object -ExpandProperty DistinguishedName

b. Get the user object and replace the manager attribute:
Get-ADUser username | Get-ADObject | Set-ADObject -Replace @{"manager" = $contactDN}


Q:

Benefits of using customer supplied tenant secret in Platform encryption

Shield Platform encryption provides 2 options for tenant secrets.Customer-supplied tenant secret upload(BYOK) and On-demand tenant secret generation. I am looking for advantages of BYOK over on-demand tenant secret generation. To me it seems like both are same. Either you upload a tenant secret to Salesforce or you let Salesforce generate a tenant secret. Does anyone have better ideas?

A:

Absolutely, I completely agree with you.
We are expanding our BYOK capabilities in multiple steps
1/ Bring your own entropy, which is what we offer today
2/ Bring your own key
3/ Cahe only key
With 2/, you would be able to provide us the actual AES key we would be using for encrypting/decrypting the data. But your key would still be stored encrypted in our database, the same way that we store your entropy today, and we would use our HSM only for wrapping/unwrapping your key
With 3/, your key will only stay in memory and would never touch any of our system of records. We would keep it in our cache for an amount of time under your control, forcing us to go back to your HSM to fetch it again on a regular basis.
Everything is of course under the usual safe harbor, but as an FYI we are starting working on 2/ and we are in the middle of a 2-releases entire refactor of our caching strategy in preparation for 3/


Q:

C# Application deployment with unmanaged dlls from a PHP server

I want to deploy a C# application from my website which is hosted in Linux/PHP Apache. It has a couple of managed and unmanaged dlls as dependencies. Can someone please tell if I can use ClikcOnce on Apache server, and if yes how I will be able to do it. thanks in advance

A:

click once only produce static files.
just check if the server will correctly serve all files (as content).
[edit] to conclude the comments, the 1&1 hosting provider php offer does not block files for a click once setup


Q:

Optimizing Regex searches

How could I optimize these Regex searches? Currently they take up to 5 seconds on my mobile phone

Conversation:
.+?sms-notregion
Place: (?<=de/ort/)[^"]+
ID: (?<=sms-share-id sms-tagline-elem">#)\d+
Single message: sms-participant sms-participant-.+?

Participant: (?<=sms-participant-)\d
Time: (?<=sms-tag">)\d+:\d+
messagetext: (?<=sms-bubble">).+?(?=
)

I first search for conversations, then for the single messages in them and so on.
For example I have this website I am matching with: http://pastebin.com/uun0uKL1
Update. As it turned out, my regex wasn't the slow part of my code, but the use of Html.fromhtml(), that I was trying to use in order to unescape html special chars.

A:

Don't parse HTML with RegExes. Just don't.
Instead, I've found a nice Java library called jsoup which can quickly parse HTML.
Here's an example of using jsoup with what you want to get:
Document doc = Jsoup.connect("http://example.com/").get();
Elements elements = doc.select("div.sms-tag");
// Then iterate over those elements
for (Element element : elements) {
    String time = element.text();
}

And such stuff. Looking at their "cookbook" might help, too.


Q:

jQuery dynamic inserted table rows and input fileds validation on select option

I am trying to build somewhat of a fee voucher with jquery and I am having a heck of a time figuring out how to go about making it all work.
I want when I select option js input field id fee-2 will disable and when I select option php input field id fee-1 will disable and so on more rows inserted for different from select option on different rows. at last need some of all rows inserted by field id fee-1 and fee-2 separately both

My Fiddle Demo is
http://fiddle.jshell.net/softfiddle/cSbbK/2/
thanks

A:

$("#mytable").on("change", "select", function () {
     var getSelectValue = $(this).val();
     if (getSelectValue == 1) {
         $(this).parents('td').next().find('#fee-2').prop('disabled', true);
         $(this).parents('td').next().next().find('#fee-1').prop('disabled', false);
     } else {
         $(this).parents('td').next().find('#fee-2').prop('disabled', false);
         $(this).parents('td').next().next().find('#fee-1').prop('disabled', true);
     }
 });

JSFIDDLE
Updated:  Have added two classes to the textbox .i.e fee_course_1,fee_course_2 so we can loop over it and get sum values
$("#calsum").click(function () {
     var sum_fee_1 = 0;
     var sum_fee_2 = 0;
     $('.fee_course_1').each(function () {
         sum_fee_1 += Number($(this).val());
     });
     $('.fee_course_2').each(function () {
         sum_fee_2 += Number($(this).val());
     });
     alert("Fee_1 = " + sum_fee_1 + "  and  Fee_2 = " + sum_fee_2);

 });

JS FIDDLE DEMO 2