Q: Passing data to a controller with $.ajax (MVC 4) I have the following editor template:
DropDownListEditorTemplate
@model DropDownListViewModel

<script type="text/javascript">
    $(function() {
        $("select").on("change", function () {
            $.ajax({
                type: "POST",
                url: '@Url.Action("ListItemChanged", "Controller")',
                data: { "Value": "@Model.Items.FirstOrDefault(x => x.Selected).Value" }
            });
        });
    })
</script>

@Html.DropDownListFor(m => m.Value, Model.Items, "(Select)")

Controller
public ActionResult ListItemChanged(string selectedItem)
{
    // Stuff.
}

The problem is that when the editor template loads, I get an error saying that @Model.Items is null ("Object reference not set to an instance of an object"). That makes sense, except why would that line be evaluating without any select items changing? Even when I change the $.ajax call to only execute when 1 == 2, it still gives me that error. So clearly that line is being evaluated even when the jQuery function isn't executing.
Given that, how do I prevent that error from occurring? @Model.Items.First(x => x.Selected).Value is only going to have a value once a drop down list item has been selected.

A: Try this:
@model DropDownListViewModel

<script type="text/javascript">
    $(function() {
        $("select").on("change", function () {
            $.ajax({
                type: "POST",
                url: '@Url.Action("ListItemChanged", "Controller")',
                data: { "Value": $(this).val() }
            });
        });
    })
</script>

@Html.DropDownListFor(m => m.Value, Model.Items, "(Select)")

A: What you have to understand is, the @expressions are parsed inside the server. You also have to understand that MVC model binder distinguishes the fields based on their name. Inside the data object of the jquery ajax function, where you are passing the object literal, you have to specify the name of the variable as your action method is expecting it to be (in your case, selectedItem). So the correct approach should be:
$("select").on('change', function () {
      $.ajax({
            type: 'POST',
            url: '@Url.Action("ListItemChanged", "Controller")',
            data: { "selectedItem": $(this).val() }
      });
});

//Server
[HttpPost]
public ActionResult ListItemChanged(string selectedItem)
{
    // Stuff.
}


Q: Error: Module administration/tfasettings not found I'm busy working on developing some plugins and apps, and when i am running c8y server locally and i try to enter Administration, i keep getting the following error:

Error: Module administration/tfasettings not found

Any ideas?

A: We have already fixed the issue for versions >= 9.1.0. Please try to install version 9.1.0 (or higher) with c8y install command. If administration/tfasettings
is still missing use npm cache clean --force and then once again try to install version 9.1.0 (or higher) with c8y install command.
Best regards
Dawid


Q: iTextSharp table layout problems I'm having problems creating a particular layout in iTextSharp using tables.
I begin the document by creating a table that splits the page in two, and in each of these columns I then insert an additional table with x rows and 1 column each.
The reason I want to do it like this is because I want a layout resembling this HTML.
But what is happening is the following:

The tables which as per the code are independent seem linked together.
OLD CODE
private void AddBody()
    {
        Image smallerLogo = Image.GetInstance(_logo);
        smallerLogo.ScaleAbsolute(100f, 100f);

        Image normalLogo = Image.GetInstance(_logo);

        ExtendedTable table = new ExtendedTable(2, 1, true, false, true);
        table.SetWidths(new[] { 50, 50 });

        ExtendedTable col1 = new ExtendedTable(1, 6, true, false, false);
        col1.AddCell(new ExtendedCell(new Chunk("Impressions", _headingFont), false));
        col1.AddCell(new ExtendedCell(smallerLogo, false));
        col1.AddCell(new ExtendedCell(new Chunk("Visitor funnel", _headingFont), false));
        col1.AddCell(new ExtendedCell(smallerLogo, false));
        col1.AddCell(new ExtendedCell(new Chunk("Shortlists", _headingFont), false));
        col1.AddCell(new ExtendedCell(smallerLogo, false));

        ExtendedTable col2 = new ExtendedTable(1, 6, true, false, false);
        col2.AddCell(new ExtendedCell(new Chunk("Leads", _headingFont), false));
        col2.AddCell(new ExtendedCell(normalLogo, false));
        col2.AddCell(new ExtendedCell(new Chunk("Demographics", _headingFont), false));
        col2.AddCell(new ExtendedCell(normalLogo, false));

        table.AddCell(new ExtendedCell(col1, false));
        table.AddCell(new ExtendedCell(col2, false));

        _document.Add(table);
    }

NEW CODE
private void AddBody()
    {
        Image smallerLogo = Image.GetInstance(_logo);
        smallerLogo.ScaleAbsolute(60.0f, 60.0f);

        Image normalLogo = Image.GetInstance(_logo);

        PdfPTable table = new PdfPTable(2);
        table.SetWidths(new[] { 50, 50 });

        PdfPTable col1 = new PdfPTable(1);
        col1.AddCell("Impressions");
        col1.AddCell(new PdfPCell(smallerLogo));
        col1.AddCell("Visitor funnel");
        col1.AddCell(new PdfPCell(smallerLogo));
        col1.AddCell("Shortlists");
        col1.AddCell(new PdfPCell(smallerLogo));

        PdfPTable col2 = new PdfPTable(1);
        col2.AddCell("Leads");
        col2.AddCell(normalLogo);
        col2.AddCell("Demographics");
        col2.AddCell(normalLogo);

        table.AddCell(col1);
        table.AddCell(col2);

        _document.Add(table);
    }

Where ExtendedCell and ExtendedTable are small classes that remove the table borders.
Any ideas?


Q: If I delete the sound library from GarageBand on my Mac, can I reinstall it later for free? I have a MacBook Air and it doesn't have very much storage so I want to delete the sound library from garage band (not the whole app, just the sound library). if I do this, will I be able to reinstall it later for free, or will I have to pay?

A: You can download it from App Store here
It is free, but you will have to use your App Store ID to get it.

More Info from Apple


Q: Datagridview Data Population from the database where one cell is a combobox c# I have a datagrid view that  I need to populate with content from the database.
My database content is in a datatable that typically looks like this :
Prod id ProdName    Version
1   abc 1.1
1   abc 2.1
1   abc 3.1
2   def 3.1
2   def 3.2
3   ghi 1.1
4   jkl 1.1
4   jkl 1.2
Now my problem is that when i display the content in a datagrid view, I want it to be displayed as such, where version should be a dropdown comboboxcell so each product has a list of versions :
Prod id ProdName    Version
1   abc 1.1
    2.1

    3.1

2   def 3.1
    3.2

3   ghi 1.1
4   jkl 1.1
    1.2

Please help me in achieving this. I cannot directly say :
dataGridView1.DataSource = getdatatable()
So please do not suggest that as it gives me a flat view with no combobox. Eagerly looking forward to a positive reply. Is it possible to draw each row in the datagrid view and populate the combobox in that row with all the versions available for a product ? Please help. TIA

A: Essentially, you need to sort through your queried data, saving each unique product with a list of all its versions.  Then you would manually create the columns for your DataGridView as I'll describe below.
To mock out this scenario I created the following object class:
// The type of binding object for your dgview source.
public class Product
{
  public Product()
  {
    this.Version = new List<double>();
  }

  public int ID { get; set; }
  public string Name { get; set; }
  public List<double> Version { get; set; }
}

In your query returning all the objects, I would do something like this:
public BindingList<Product> YourQueryCall()
{
  BindingList<Product> products = new BindingList<Product>();

  /*
   *  Your code to query the db.
   */

  while reader.Read()
  {
    Product existingProduct = new Product();

    int id = // value from the reader
    string name = // value from the reader
    double version = // value from the reader

    try
    {
      existingProduct = products.Single(p => p.ID == id && p.Name == name);
      existingProduct.Version.Add(version);
    }
    catch // No product yet exists for this id and name.
    {
      existingProduct.ID = id;
      existingProduct.Name = name;
      existingProduct.Version.Add(version);
      products.Add(existingProduct);
    }
  }

  return products;
}

That will store only unique products and their lists of versions.  And in the form, to show each row's unique list of versions in a ComboBoxColumn:
public Form1()
{
  InitializeComponent();

  this.Products = YourQueryCall();
  this.FillDGView();
}

public BindingList<Product> Products { get; set; }

public void FillDGView()
{
  DataGridViewTextBoxColumn col1 = new DataGridViewTextBoxColumn();
  col1.Name = "Product ID";
  col1.ValueType = typeof(int);
  dataGridView1.Columns.Add(col1);

  DataGridViewTextBoxColumn col2 = new DataGridViewTextBoxColumn();
  col2.Name = "Product Name";
  col2.ValueType = typeof(string);
  dataGridView1.Columns.Add(col2);

  DataGridViewComboBoxColumn col3 = new DataGridViewComboBoxColumn();
  col3.Name = "Version";
  col3.ValueType = typeof(double);
  dataGridView1.Columns.Add(col3);

  for (int i = 0; i < this.Products.Count; i++)
  {
    DataGridViewRow row = (DataGridViewRow)(dataGridView1.Rows[0].Clone());

    DataGridViewTextBoxCell textCell = (DataGridViewTextBoxCell)(row.Cells[0]);
    textCell.ValueType = typeof(int);
    textCell.Value = this.Products[i].ID;

    textCell = (DataGridViewTextBoxCell)(row.Cells[1]);
    textCell.ValueType = typeof(string);
    textCell.Value = this.Products[i].Name;

    DataGridViewComboBoxCell comboCell = (DataGridViewComboBoxCell)(row.Cells[2]);
    comboCell.ValueType = typeof(double);
    comboCell.DataSource = this.Products[i].Version;
    comboCell.Value = this.Products[i].Version[0];

    dataGridView1.Rows.Add(row);
  }
}

Hope this helps!


Q: Simultaneous multiple key press release delay I am developing 2D game and faced problem with simultaneous multiple key press / release detection needed, for instance, for character diagonal movement.
Problem is when I "simultaneous" (it has nothing to do with my reaction I press / release very quickly) press / release multiple (two) keys delay between messages often is much more than single frame (16ms with VSync), for instance, it can reach 50-100 millisecond, so character starts moving single direction and only after slight delay diagonal (as intended).
Is it normal for WinAPI messages or is it hardware limit? Is it possible to detect input faster or how games deal with it?
Only solution that kinda helps is process inputs in game logics with periodic delay (for instance every 100 ms), but this sacrifices control responsiveness very much.
I am dispatching WinAPI WM_KEYDOWN / WM_KEYUP messages in while loop.
while (PeekMessage(&message, 0, 0, 0, PM_REMOVE))
  DispatchMessage(&message);

I also tried to dispatch input in seperate from render thread with GetMessage.
Delay measurement test project : pastebin
Actual OpenGL diagonal movement test project : pastebin

A: I can't answer your question about why your processing is getting delayed, but regarding your question about getting faster input, try using Raw Input instead.  That will allow the keyboard to send its own keystroke events directly to you so you do not have to wait for the OS to receive, interpret, and dispatch the keystrokes to you, which takes more time.

A: The straight answer is yes, delays of the order of 50 ms or so are common in processing key presses through the normal Windows message queue. I believe there are multiple sources of these delays.
First, the keyboard itself has a serial interface. Historically this was very slow, and probably tied to the underlying 55ms clock. A USB keyboard is likely to be much faster but the point is that each individual key press or release will be sent and processed individually, even if they appear to absolutely simultaneous.
The Windows code paths leading to the processing of Windows messages are long and the flow of intervening messages can be high. If there are many messages to process your simultaneous key releases may become separated by many other messages. You can reduce this by peeking messages instead of waiting for them, to a point.
So you really will have to use Raw Input, you're going to need to handle events quickly and you still need to anticipate delays. My guess is you're going to need to 'debounce' your input to the tune of at least 20ms to get smooth behaviour. There is lots of reading out there to help you on your way.


Q: Is there a way to Install Tensorflow2-GPU in Google Colab for good? Is there a way I can Install Tensorflow 2- GPU in Google Colab without Installing it every time new after the Runtime ran out?
Right now I have:
    !pip install -U tensorflow-gpu==2.0.0-alpha0

in my Setup, so it always Installs Tf 2. But it's kind of annoying to Install it every day, so is there a way I can install it for good?

A: You can specify the version with e.g: "%tensorflow_version 2.x", as described here:
https://colab.research.google.com/notebooks/tensorflow_version.ipynb


Q: Attempt to present UINavigationController whose view AppDelegate
   initialViewController = storyboard.instantiateViewControllerWithIdentifier("LoginViewController")as! UIViewController
    }

    self.window?.rootViewController = initialViewController
    self.window?.makeKeyAndVisible()

Takes me to LoginViewController
let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("CardsNavController") as? UIViewController

self.presentViewController(vc!, animated: true, completion: nil)

I click on the login button takes me to CardsViewController
func goToProfile(button: UIBarButtonItem) {
   pageController.goToPreviousVC()

}
Clicking on back button which is part of the UINavigationController runs goToProfile (above)  and takes me to ViewController.swift because that's where the pageController is declared.
let pageController = ViewController(transitionStyle: UIPageViewControllerTransitionStyle.Scroll, navigationOrientation: UIPageViewControllerNavigationOrientation.Horizontal, options: nil)

The error shows up here
func goToPreviousVC() {
    //let currentControllers = self.navigationController?.viewControllers
   if viewControllers.isEmpty   {

    setViewControllers([profileVC], direction: UIPageViewControllerNavigationDirection.Reverse, animated: true, completion: nil)
    pageController.presentViewController(profileVC, animated: true, completion: nil)
 else {
    let previousVC = pageViewController(self,  viewControllerBeforeViewController: viewControllers[0] as! UIViewController)!
    setViewControllers([previousVC], direction:  UIPageViewControllerNavigationDirection.Reverse, animated: true, completion: nil)
    }

Error:
Warning: Attempt to present <UINavigationController: 0x15ce314e0> on <MyApp.ViewController: 0x15cd2c6f0> whose view is not in the window hierarchy!

Basically the flow is like this  AppDelegate -> LoginViewController -> ViewController and I need to get to ProfileViewController.
ProfileView has ProfileNavController while CardsView has CardsNavController
ViewController has a storyboardID of pageController.
Both ProfileView and and CardsView are embedded within UINavigationControllers (hence the NavController extension).
The second time I run the app after a fresh install it works perfectly (all the controllers get loaded okay). Should I push viewControllers in AppDelegate?

A: I've checked your code using Xcode 7, which may not be ideal for resolving this issue because I had to covert your code to Swift 2.0, but here was what I found out.
ISSUE

*

*First time opening the app, this block:
if currentUser() != nil {
    initialViewController = pageController
}
else {
    initialViewController = storyboard.instantiateViewControllerWithIdentifier("LoginViewController") as UIViewController
}

self.window?.rootViewController = initialViewController

Will initialize LoginViewController and make it the current window's rootViewController.
At this point there is no pageController initialized

*When user taps on the button to go to the Profile screen, this method will be called
func goToProfile(button: UIBarButtonItem) {
    pageController.goToPreviousVC()
}
At this point, pageController is initialized, and off course, there is NOTHING in the viewControllers array. Let's see what happen in the goToPreviousVC method:
Original method looks like this:
    let nextVC = pageViewController(self, viewControllerAfterViewController: viewControllers[0] as UIViewController)!
    setViewControllers([nextVC], direction: UIPageViewControllerNavigationDirection.Forward, animated: true, completion: nil)

One thing you can see obviously is: calling viewControllers[0] could give you a crash because viewControllers is an empty array.
If you use Swift 2.0, it doesn't even let you compile your code :)
SOLUTION
Let's go directly to the solution: Ensure that the pageController is available before trying to call it's viewControllers.
I blindly tried fixing you code in Swift 2.0 and found out that this method would work for you:
BEFORE: In LoginViewController.swift line 63
        let vc = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("CardsNavController") as? UIViewController

        self.presentViewController(vc!, animated: true, completion: nil)

AFTER: Let's fix it like this
    let navc = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("CardsNavController") as! UINavigationController
    if let viewControllers = pageController.viewControllers where viewControllers.count == 0 {
        pageController.setViewControllers([navc.viewControllers[0]], direction: .Forward, animated: false, completion: nil)
    }
    self.presentViewController(pageController, animated: true, completion: nil)

It's working well here and probably I don't need to show you how the screen transition should look like :)

In case you would like to have the fixed source code as well, please find it HERE. Basically I converted your code to Swift 2.0 and ignored unnecessary parts like Facebook authentication for faster investigation.
Good luck & Happy coding!


Q: How to run Signal Desktop in the background? How is it possible to run Signal Desktop in the background on Ubuntu with a little icon in the taskbar at the top of the screen?

A: From the command line or as Startup Application:
signal-desktop --start-in-tray --no-sandbox

--no-sandbox is needed because the Debian package does not install the sandbox helper as SUID. It is taken directly from the .desktop file, i.e. Signal is run with that option when you start it normally from the launcher in your DE.
--start-in-tray instead of --use-tray-icon because the latter option opens the main window at startup.
It's going to use the same amount of RAM minimised to the tray as it would with the main window open, though. It's just for tidying up your active windows.
Source: Reddit post.


Q: How to perform multiple related calls to AsyncTasks without overlapping? I have an application which needs to make repeated calls to a web API. Effectively, it iterates over records in a SQL table and makes a unique call out to the web server with the appropriate data. It's a kind of data synchronization.
As I understand it, when performing this kind of HTTP request to an API it should occur within an AsyncTask to avoid hanging up the UI, so I have made my AsyncTask class which makes a request and parses back the response, but I need to pass this data back to the calling class.
On top of that, I don't want the calling class to run these requests in parallel. I want it to make one request, and not iterate to the next record in the table and make a second request until that first request finishes. So in a way, I want this to be blocking, but still in a separate thread so the UI doesn't freeze up. At least, I think this is what I want.
Pseudo code is something along the lines of this:
// caller function
public void synchronize(){
    load all records from sql table
    for each record:
        if record type is X:
            new asyncX().execute(record)
            // once this completes successfully,
            // I want to do something with the return value here,
            // before going on to the next iteration
            //
            // and eventually when there is some UI here,
            // show some nice spinny logo and maybe some text for
            // what's going on right now
        if record type is Y:
            new asyncY().execute(record)
            // same as above
}

// Async class
public class asyncX extends AsyncTask<RecordType,Void,RecordType> {
    protected RecordType doInBackground(RecordType... record) {
        convert record to json
        make http request
        receive http response
        parse response
        return record
    }
}

The way I'm thinking of doing this is changing the synchronize function to only run one record at a time, call the async task, and end, and then the async task calls back to a synchronize_followup() function which does what it needs to do with the return value, and then starts synchronize back up again, but I'm not sure I like that.
Thoughts on how to proceed?

A: The way you want to handle this is already invented with threading sychronization, so you don't have to implement it your way.
There's a class similar to Semaphore called CountDownLatch. When you declare an object, and activate the lock mechanism via .wait(), it will freeze execution of further code until you issue a .countDown() statement. Indeed, if you declare a CountDownLatch(1) will probably make the effect you're looking for.
On the CountDownLatch's reference page there's a nice example on how to implement this by blocking one Thread's execution depending on the execution of other.

A: To meet my needs, I instead made the synchronize functionality into an AsyncTask, spun that off from my UI thread, and left the outgoing HTTP request as regular functions (and as such, they block).
This means that the synchronization process happens in the background, does not affect the UI thread, and each outgoing API call happens sequentially.


Q: Access $scope outside foreach function Angular js Firebase Here is the code: I'm looping through the data to get the value that I need, and I got it.
The questions is how can I access the value outside of this loop in other functions within the controller. The correct value have been assigned to $scope.theModel.
var refModels = firebase.database().ref("/users/" + $scope.UserID);

refModels.once('value').then(function (snapshot) {
  snapshot.forEach(function (snapshot) {
    var usersValue = snapshot.val();
    console.log("users values", usersValue.carModel);

    $scope.theModel = usersValue.carModel;
    console.log("The model" + $scope.theModel); //output "e90"

  });
      $scope.processData();
});

So I need to use that value $scope.theModel outside of the function. What I'm trying to achieve, I will use the value of $scope.theModel -"e90" and compare it with another DB ref, and if it matches it will return the data. See the code of another DB ref:
 $scope.processData = function (){

console.log("Process Model" + $scope.theModel); // returns undefined

$scope.carDetails = [];

firebase.database().ref("models").once('value').then(function(snapshot) {
    snapshot.forEach(function(userSnapshot) {
        var models = userSnapshot.val();
        console.log(models);

        if (models.brand == $scope.theModel){

           $scope.carDetails.push(models);
       }
   });
});

};

A: It is because, refModels.once('value').then is async meaning that JS starts its execution and continues to next line which is console.log and by the time console.log is executed $scope.theModel hasn't been populated with data yet.
I suggest you read this
Asynchronous vs synchronous execution, what does it really mean?
You can still access your $scope.theModel in other functions, but you have to make sure it is loaded first.
Edit
refModels.once('value').then(function (snapshot) {
    snapshot.forEach(function (snapshot) {
         var usersValue = snapshot.val();
         console.log("users values", usersValue.carModel);

         $scope.theModel = usersValue.carModel;
         console.log("The model" + $scope.theModel); //output "e90"

    });
    $scope.processData();
});

$scope.processData = function() {
// here $scope.theModel exists
// do some code execution here with $scope.theModel
// call your other firebase.database.ref("models") here
};

A: Ok so finally got it working, with Bunyamin Coskuner solution, the only thing I had to fix is to return $scope.processData;
  var UserID = firebase.auth().currentUser.uid;

    var refModels = firebase.database().ref("/users/" +  UserID);

   refModels.once('value').then(function(snapshot) {

    console.log(snapshot)

           snapshot.forEach(function(childSnapshot) {

    console.log(childSnapshot)

           var usersValue = childSnapshot.val();

         // var theModel = usersValue.carModel;
          console.log("The model", usersValue.carModel); //output "e90"

         $scope.theModel = usersValue.carModel;
         ***return $scope.processData;*** // we have to return it here
    });

 $scope.processData();
});

$scope.processData = function (){

console.log("Process Model" + $scope.theModel); // now returns the value e90

$scope.carDetails = [];

firebase.database().ref("models").once('value').then(function(snapshot) {
  snapshot.forEach(function(userSnapshot) {
    var models = userSnapshot.val();
    console.log(models);

     if (models.brand == $scope.theModel){

    $scope.carDetails.push(models);
         }
       });
    });

   }

It seems to be a very common mistake made by new javascript developers, the Async behaviour, so its good to read about it.
In this solution we called a function from inside of then function. That way, we'll have for sure the data, that can be used in other function

A: Your $scope.theModel gets set inside the "then" block as expected, but being async, this happens after the second console.log (outside the function) is invoked.
If you use angular components, you can init theModel inside $onInit method:
angular.module('app', []).component('myComponent', {
   bindings: {
     title: '@'
   },
   controller: function() {
      this.$onInit = function() {

        // Init the variable here
        $scope.theModel = null;
      });

      //Following code should not be in the controller, but in a service (here just as sample)
      var refModels = firebase.database().ref("/users/" + $scope.UserID);

      refModels.once('value').then(function (snapshot) {
        snapshot.forEach(function (snapshot) {
          var usersValue = snapshot.val();
          console.log("users values", usersValue.carModel);

          // From this moment your variable is set and available outside
          $scope.theModel = usersValue.carModel;
      });
   },
   templateUrl: 'template.html'
   });

A: You can watch the value changing. Async behaviour is explained in another answer.
   $scope.$watch('theModel', function(newVal){
      console.log(newVal);
   });

Also I would use $evalAsync() on $scope.theModel = usersValue.carModel;
$scope.$evalAsync(function(){
    $scope.theModel = usersValue.carModel;
});


Q: edgeNGram_analyzer not found for field I have created a synonym analyser on an index it works on elasticsearch 1 but not for 2.4:
here is my mapping:
{
            "product": {
                "_all": {
                    "enabled": true,
                    "auto_boost": true,
                    "index_analyzer": "edgeNGram_analyzer",
                    "search_analyzer": "standard"
                },
                "properties": {
                    "brand": {
                        "type": "string",
                        "include_in_all": true
                    },
                    "brand_ar": {
                        "type": "string",
                        "analyzer": "arabic",
                        "include_in_all": true
                    },
                    "categories": {
                        "properties": {
                            "1": {
                                "type": "string"
                            },
                            "146": {
                                "type": "string"
                            },
                            "147": {
                                "type": "string"
                            },
                            "150": {
                                "type": "string"
                            },
                            "151": {
                                "type": "string"
                            },
                            "152": {
                                "type": "string"
                            },
                            "155": {
                                "type": "string"
                            },
                            "156": {
                                "type": "string"
                            },
                            "157": {
                                "type": "string"
                            },
                            "161": {
                                "type": "string"
                            },
                            "162": {
                                "type": "string"
                            },
                            "334": {
                                "type": "string"
                            },
                            "5": {
                                "type": "string"
                            }
                        }
                    },
                    "category": {
                        "type": "string",
                        "boost": 5.0,
                        "include_in_all": true
                    },
                    "category_ar": {
                        "type": "string",
                        "boost": 5.0,
                        "analyzer": "arabic",
                        "include_in_all": true
                    },
                    "category_id": {
                        "type": "integer",
                        "include_in_all": false
                    },
                    "colors": {
                        "type": "string",
                        "index": "not_analyzed"
                    },
                    "colors_name": {
                        "type": "string",
                        "include_in_all": true
                    },
                    "types": {
                        "type": "string",
                        "include_in_all": true
                    },
                    "types_array": {
                        "type": "string",
                        "index": "not_analyzed"
                    },
                    "colors_name_ar": {
                        "type": "string",
                        "analyzer": "arabic",
                        "include_in_all": true
                    },
                    "created_at": {
                        "type": "date",
                        "format": "dateOptionalTime"
                    },
                    "delivery": {
                        "type": "string"
                    },
                    "delivery_ar": {
                        "type": "string"
                    },
                    "description": {
                        "type": "string",
                        "include_in_all": true
                    },
                    "description_ar": {
                        "type": "string",
                        "analyzer": "arabic",
                        "include_in_all": true
                    },
                    "id": {
                        "type": "string",
                        "index": "no",
                        "include_in_all": false
                    },
                    "image_link": {
                        "type": "string",
                        "index": "not_analyzed"
                    },
                    "images": {
                        "properties": {
                            "id": {
                                "type": "string"
                            },
                            "name": {
                                "type": "string"
                            },
                            "path": {
                                "type": "string"
                            }
                        }
                    },
                    "is_best_seller": {
                        "type": "integer",
                        "include_in_all": false
                    },
                    "is_deal": {
                        "type": "integer",
                        "include_in_all": false
                    },
                    "keywords": {
                        "type": "string",
                        "include_in_all": true
                    },
                    "made_id": {
                        "type": "string"
                    },
                    "made_in": {
                        "type": "string",
                        "include_in_all": true
                    },
                    "made_in_ar": {
                        "type": "string",
                        "analyzer": "arabic",
                        "include_in_all": true
                    },
                    "name": {
                        "type": "string",
                        "boost": 10.0,
                        "index_analyzer": "edgeNGram_analyzer",
                        "include_in_all": true
                    },
                    "name_ar": {
                        "type": "string",
                        "boost": 10.0,
                        "analyzer": "arabic",
                        "include_in_all": true
                    },
                    "price": {
                        "type": "double",
                        "include_in_all": false
                    },
                    "price_before_discount": {
                        "type": "double",
                        "include_in_all": false
                    },
                    "quality": {
                        "type": "string",
                        "index": "not_analyzed"
                    },
                    "quality_ar": {
                        "type": "string",
                        "analyzer": "arabic"
                    },
                    "rating": {
                        "type": "integer",
                        "include_in_all": false
                    },
                    "status": {
                        "type": "string"
                    },
                    "updated_at": {
                        "type": "date",
                        "format": "dateOptionalTime"
                    },
                    "uuid": {
                        "type": "string",
                        "index": "no",
                        "include_in_all": false
                    },
                    "vendor_id": {
                        "type": "string"
                    },
                    "vendor_location": {
                        "type": "geo_point"
                    },
                    "vendor_name": {
                        "type": "string",
                        "include_in_all": false
                    },
                    "views": {
                        "type": "integer",
                        "include_in_all": false
                    },
                    "warranty": {
                        "type": "string"
                    },
                    "warranty_ar": {
                        "type": "string"
                    }
                }
            }
}

But when I try to use it with the mapping got this issue:
{
"error": "MapperParsingException[Analyzer [edgeNGram_analyzer] not found for field [name]]",
"status": 400
}

Any ideas, I may be missing something but I can't think what. I'm using elasticsearch 2.4


Q: It is possible to assign an Int value to an Array inside a Function in C++? It's possible to do the following code with C++:
myFunction(myArray, positionInsideMyArray) = myValue.
cout << myFunction[positionInsideMyArray] << endl; // Display muValue

How can I do that with C++?
To make my question more clear, With one value the following code work correctly,
I want to do the same thing but using an Array parameter.
int& myFunction(int &x){
return x;
}

this is the main function:
int x;
myFunction(x) = myValue;
cout << x << endl; // This will display myValue

A: #include <iostream>

int &myFunction(int *arr, size_t pos) { return arr[pos]; }

int main() {
  using std::cout;
  int myArray[30];
  size_t positionInsideMyArray = 5;
  myFunction(myArray, positionInsideMyArray) = 17.;
  cout << myArray[positionInsideMyArray] << "\n"; // Display muValue
}

or with error checking:
#include <stdexcept>

template<size_t N>
inline int &myFunction(int (&arr)[N], size_t pos)
{
    if (pos >= N)
        throw std::runtime_error("Index out of bounds");
    return arr[pos];
}

A: myFunction(myArray, positionInsideMyArray) = myValue.
cout << myFunction[positionInsideMyArray] << endl;

With functions alone, the second line is not possible; you'll need a class.
However, that the second call remembers myArray from the
first makes the whole semantics a bit strange...
A rough idea (no complete class, only for int-arrays):
class TheFunc
{
    int *arr;
    int &operator() (int *arr, size_t pos)
    {
        this->arr = arr;
        return arr[pos];
    }
    int &operator[] (size_t pos)
    {
        return arr[pos];
    }
};
...
TheFunc myFunction;
myFunction(myArray, positionInsideMyArray) = myValue.
cout << myFunction[positionInsideMyArray] << endl;

A different, more robust version, where the array it set separately:
class TheFunc
{
    int *arr;
    TheFunc(int *arr)
    {
        this->arr = arr;
    }
    int &operator() (size_t pos)
    {
        return arr[pos];
    }
    int &operator[] (size_t pos)
    {
        return arr[pos];
    }
};
...
TheFunc myFunction(myArray);
myFunction(positionInsideMyArray) = myValue.
cout << myFunction[positionInsideMyArray] << endl;


Q: hide scrollbar shape in android textview i have a text view in my activity that populate from database . but when it's big Scrollbar shape show override the text . this is screenshot from it :

This is the textView xml :
<TextView
        android:id="@+id/txtMatn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/dark_line"
        android:lineSpacingExtra="12dp"
        android:layout_margin="24dp"
        android:scrollbars="vertical"/>

now I want hide the ScrollBar shape

A: maybe you enable scrollability of textview by
1. in java code : TextView.setMovementMethod(new ScrollingMovementMethod());
2. in xml : android:scrollbars="vertical"

... but only first job enable scrollability text without second job
so answer is below
1. in java code : TextView.setMovementMethod(new ScrollingMovementMethod());
2. in xml : android:scrollbars="none"

delta is value of android:scrollbars vertical->none

A: In XML
android:background="@android:color/transparent"

Or in Kotlin Class
editText?.isVerticalScrollBarEnabled = false

In Java Class

A: you can use this code
enter code here
 <ScrollView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:scrollbars="none">
 <TextView
  here your text
  />
  </ScrollView>

A: implemented the OnTouchListener inside the adapter and set it on the text view he logic for touch event is: I check if the touch event is a tap or a swipe
 @Override
 public boolean onTouch(View v, MotionEvent motionEvent) {

switch (motionEvent.getAction()) {
    case MotionEvent.ACTION_DOWN:
        mIsScrolling = false;
        mDownX = motionEvent.getX();
        break;
    case MotionEvent.ACTION_MOVE:
        float deltaX = mDownX - motionEvent.getX();
        if ((Math.abs(deltaX) > mSlop)) { // swipe detected
            mIsScrolling = true;
        }
        break;
    case MotionEvent.ACTION_CANCEL:
    case MotionEvent.ACTION_UP:
        if (!mIsScrolling) {
            openNewScreen(v); // this method is used for click listener of the ListView
        }
        break;

}

return false;
 }

A:  android:scrollbarThumbVertical="@android:color/transparent"

Keep the scroll Set transparent


Q: Библиотеки для поиска и анализа кривых на изображении Приветствую.
Допустим, имеется изображение:

На данном изображении три кривых (графика),
части которых могут быть разной толщины или пунктирные/штриховые.
Линии всегда темные на светлом фоне, может присутствовать сглаживание.
Помимо этих линий также присутствует текст и сетка (но это легкая побочка, не суть).
Необходимо на изображении найти эти кривые, их количество, определить их толщину (примерно) в указанной точке кривой, определить к какой кривой относится указанная точка, разбить кривую на отрезки, чтобы можно было впоследствии приблизительно восстановить кривую по координатам.
Справится ли с таким OpenCV? Может быть имеются готовые библиотеки для анализа графиков? В общем, пните в верном направлении.


Q: Custom Jasmine HTML output I am testing a project in rails with Jasmine which is all going great.
The only issue I now have is that I'm not a huge fan of the way the tests are being displayed. Currently I view my test suite at http://localhost:8000/jasmine and Jasmine is pulling in my styles along with it's own and rendering the tests as follows:

I would like to either render the tests like this (as I've seen elsewhere):

Or have some way of customising the HTML output/layout. Is this possible?

A: The output you want is produced if you use the jasmine.TrivialReporter. The one the gem displays is the recommended one, i.e. the jasmine.HtmlReporter. You can use the trivial one as described here: https://github.com/pivotal/jasmine/blob/v1.3.1/lib/jasmine-core/example/SpecRunner.html, but that implies running jasmine stand-alone not through the gem.
(version 1._._ only.)


Q: SQL Query how to summarize students record by date? I have a following table Students
Id  StudentId       Subject         Date          Grade

1   001     Math        02/20/2013  A

2   001     Literature  03/02/2013  B

3   002     Biology     01/01/2013  A

4   003     Biology     04/08/2013  A

5   001     Biology     05/01/2013  B

6   002     Math        03/10/2013  C

I need result into another table called StudentReport as shown below. This table is the cumulative report of all students records in chronological order by date.
Id StudentId       Report

1   001     #Biology;B;05/01/2013#Literature;B;03/02/2013#Math;A;02/20/2013

2   002     #Math;C;03/10/2013#Biology;A;01/01/2013

3   003     #Biology;A;04/08/2013

A: Typically you would not store this data in a table, you have all the data needed to generate the report.
SQL Server does not have an easy way to generate a comma-separated list so you will have to use FOR XML PATH to create the list:
;with cte as
(
  select id,
    studentid,
    date,
    '#'+subject+';'+grade+';'+convert(varchar(10), date, 101) report
  from student
)
-- insert into studentreport
select distinct
  studentid,
  STUFF(
         (SELECT cast(t2.report as varchar(50))
          FROM cte t2
          where c.StudentId = t2.StudentId
          order by t2.date desc
          FOR XML PATH (''))
          , 1, 0, '')  AS report
from cte c;

See SQL Fiddle with Demo (includes an insert into the new table). Give a result:
| ID | STUDENTID |                                                          REPORT |
------------------------------------------------------------------------------------
| 10 |         1 | #Biology;B;05/01/2013#Literature;B;03/02/2013#Math;A;02/20/2013 |
| 11 |         2 |                         #Math;C;03/10/2013#Biology;A;01/01/2013 |
| 12 |         3 |                                           #Biology;A;04/08/2013 |

A: If you are looking to insert the data from 'Students' into 'Student Report', try:
INSERT INTO StudentReport (ID, StudentID, Report)
SELECT ID, StudentID, '#' + subject + ';' + grade + ';' + date AS report
FROM Students

A: Without using CTE.Improve performance.
FOR XML
(select
min(ID) as ID,
StudentId,
STUFF((select ', '+'#'+s2.Subject+';'+s2.Grade+';'+convert(varchar(25),s2.Date)
from student s2
where s2.StudentId=s1.StudentId
FOR XML PATH (''))
,1,2,'') as report
into t
 from student s1
group by StudentId)
;

select * from t

Where t would be new Table Name which doesn't exists in DataBase.
SQL Fiddle


Q: Updating data in MySQL table with PHP I was following an online tutorial lesson about login system with PHP. Everything works fine as far as lesson is concerned.
Now I added a new data column named "time" of type INT. And I want to update it with the time as soon as user has logged in. In the below code, I tried to update it. But it shows no error, but doesn't work(update the "time" variable), either. I don't know PHP very well, so I think I'm not doing it right. So help me with my code.
<?php
    session_start();
// Change this to your connection info.
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'accounts';
// Try and connect using the info above.
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if ( mysqli_connect_errno() ) {
    // If there is an error with the connection, stop the script and display the error.
    die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}

// Now we check if the data from the login form was submitted, isset() will check if the data exists.
if ( !isset($_POST['username'], $_POST['password']) ) {
    // Could not get the data that should have been sent.
    die ('Please fill both the username and password field!');
}

// Prepare our SQL, preparing the SQL statement will prevent SQL injection.
if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
    // Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s"
    $stmt->bind_param('s', $_POST['username']);
    $stmt->execute();
    // Store the result so we can check if the account exists in the database.
    $stmt->store_result();
}

if ($stmt->num_rows > 0) {
    $stmt->bind_result($id, $password);
    $stmt->fetch();
    // Account exists, now we verify the password.
    // Note: remember to use password_hash in your registration file to store the hashed passwords.
    if (password_verify($_POST['password'], $password)) {
        // Verification success! User has loggedin!
        // Create sessions so we know the user is logged in, they basically act like cookies but remember the data on the server.
        session_regenerate_id();
        $_SESSION['loggedin'] = TRUE;
        $_SESSION['name'] = $_POST['username'];
        $_SESSION['id'] = $id;

        // I want to update "time" in my table
        $now = time();
        $stmt = $con->prepare('UPDATE accounts SET time = ? WHERE id = ?');
        $stmt->bind_param('i', $now, $id);
        $stmt->execute();

        //echo 'Welcome ' . $_SESSION['name'] . '!';
        header('Location: home.php');
    } else {
        echo 'Incorrect password!';
    }
} else {
    echo 'Incorrect username!';
}
$stmt->close();
?>

A: In your update code. $stmt->bind_param('i', $now, $id); you forgot to add another i.
It should be
$stmt->bind_param('ii', $now, $id);


Q: Limitations of SQL Server 2012 Express version? I'm aware that the SQL Server 2008 R2 Express was limited to 1 CPU and 10 GB Databases. It's not clear if Microsoft bumped those numbers up to be more reflective of 2012. I looked at several places but I still don't have a clear idea. Yes, I understand 2012 is not yet released but I have to assume it's software performance requirements are already set.

A: As far as I am aware there has been no official announcement of the capabilities of SQL Express 2012, although I have heard rumours that it will be the same as 2008 R2 (1 CPU and 10Gb database limit).
Microsoft have released specifications for the standard and enterprise editions.

A: Now that it's been in release mode, there's more information available on SQL Server 2012 Express.  It looks like you're limited to:

*

*1 physical cpu (up to 4 cores)

*1GB of memory use

*up to 10GB per database.

A: Please refer to this page:
http://msdn.microsoft.com/en-us/library/cc645993(v=SQL.110).aspx

A:
Yes, I understand 2012 is not yet released but I have to assume it's software performance requirements are already set.

You can't assume this - the limits of the Express Editions are not technical by nature. And as something specified by marketing, it can change any time - shortly before the product's release or even after that, where the updated code gets distributed through a service pack.


Q: Doctrine2 incorrectly cascading oneToMany relationship I have 2 doctrine entities:
Commessa
/**
 * @ORM\Id
 * @ORM\Column(type = "bigint")
 * @ORM\GeneratedValue(strategy = "AUTO")
 */
private $id;

/* ... */

/*
 * @ORM\OneToMany(targetEntity = "AppBundle\Entity\Pipeline\pipeline", mappedBy = "commessa", cascade = {"persist", "remove"})
 */
private $pipelines;

and Pipeline
/**
 * @ORM\Id
 * @ORM\Column(type = "bigint")
 * @ORM\GeneratedValue(strategy = "AUTO")
 */
private $id;

/* ... */

/**
 * @ORM\ManyToOne(targetEntity = "AppBundle\Entity\Commessa\commessa", inversedBy = "pipelines")
 * @ORM\JoinColumn(name = "id_commessa", name = "id")
 */
private $commessa;

As you can see, both entities have an AUTO-INCREMENT, single field primary key called id, and a bidirectional association to the other; pipeline gets automatically persisted whenever i do so with commessa.
Furthermore, both entities only have a getter method for the id, and not a setter one.
Now, whenever i try to flush an object instance of the class Commessa including more than a single pipeline, the following error pops up:

An exception occurred while executing 'INSERT INTO pipeline (descrizione, nome_logico, id) VALUES (?, ?, ?)' with params ["", "frontend", "9"]:
SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '9' for key 'PRIMARY'

At no point in my code i set the pipeline's id, and dumping the Commessa object right before the flush (and after the persist) shows that it's populated correctly, and the pipelines have "null" as id, which i guess is correct.
Through the Symfony profiler, the following queries are reported:
"START_TRANSACTION"
INSERT INTO commessa (codice_commessa, data_creazione, data_scadenza, descrizione, id_anagrafica, id_cliente, id_stato, id_tipo_commesa) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
Parameters: [ 1 => lyme, 2 => 2017-01-13 10:47:53, 3 => 2017-01-17 00:00:00, 4 => Fai Lyme, 5 => 1, 6 => 1, 7 => 1, 8 => 1 ]

INSERT INTO pipeline (descrizione, nome_logico, id) VALUES (?, ?, ?)
Parameters: [1 => , 2 => frontend, 3 => 10]

INSERT INTO pipeline (descrizione, nome_logico, id) VALUES (?, ?, ?)
Parameters: [1 => , 2 => backend, 3 => 10]
"ROLLBACK"

I then stumbled upon the doctrine limitations and known issues page, stating at point 28.1.3

There are two bugs now that concern the use of cascade merge in combination with bi-directional associations.
but the related ticket link is dead.

Could this be my problem?
If it is, how can i solve this problem?

A: @ORM\JoinColumn(name = "id_commessa", name = "id") is wrong. there is 2 times name field


Q: How to Copy and Resize Image in Windows 10 UWP I have used the code from http://www.codeproject.com/Tips/552141/Csharp-Image-resize-convert-and-save to resize images programmatically. However, that project uses the System.Drawing libraries, which are not available to Windows 10 applications.
I have tried using the BitmapImage class from Windows.UI.Xaml.Media.Imaging instead, but it does not seem to offer the functionality that was found in System.Drawing..
Has anyone had any luck being able to resize (scale down) images in Windows 10? My application will be processing images from multiple sources, in different formats/sizes, and I am trying to resize the actual images to save space, rather than just letting the application size it to fit the Image in which it is being displayed.
EDIT
I have modified the code from the above mentioned link, and have a hack which works for my specific need. Here it is:
public static BitmapImage ResizedImage(BitmapImage sourceImage, int maxWidth, int maxHeight)
{
    var origHeight = sourceImage.PixelHeight;
    var origWidth = sourceImage.PixelWidth;
    var ratioX = maxWidth/(float) origWidth;
    var ratioY = maxHeight/(float) origHeight;
    var ratio = Math.Min(ratioX, ratioY);
    var newHeight = (int) (origHeight * ratio);
    var newWidth = (int) (origWidth * ratio);

    sourceImage.DecodePixelWidth = newWidth;
    sourceImage.DecodePixelHeight = newHeight;

    return sourceImage;
}

This way seems to work, but ideally rather than modifying the original BitmapImage, I would like to create a new/copy of it to modify and return instead.
Here is a shot of it in action:

A:
I may want to return a copy of the original BitmapImage rather than modifying the original.

There is no good method to directly copy a BitmapImage, but we can reuse StorageFile for several times.
If you just want to select a picture, show it and in the meanwhile show the re-sized picture of original one, you can pass the StorageFile as parameter like this:
public static async Task<BitmapImage> ResizedImage(StorageFile ImageFile, int maxWidth, int maxHeight)
{
    IRandomAccessStream inputstream = await ImageFile.OpenReadAsync();
    BitmapImage sourceImage = new BitmapImage();
    sourceImage.SetSource(inputstream);
    var origHeight = sourceImage.PixelHeight;
    var origWidth = sourceImage.PixelWidth;
    var ratioX = maxWidth / (float)origWidth;
    var ratioY = maxHeight / (float)origHeight;
    var ratio = Math.Min(ratioX, ratioY);
    var newHeight = (int)(origHeight * ratio);
    var newWidth = (int)(origWidth * ratio);

    sourceImage.DecodePixelWidth = newWidth;
    sourceImage.DecodePixelHeight = newHeight;

    return sourceImage;
}

In this scenario you just need to call this task and show the re-sized image like this:
smallImage.Source = await ResizedImage(file, 250, 250);

If you want to keep the BitmapImage parameter due to some reasons (like the sourceImage might be a modified bitmap but not directly loaded from file), and you want to re-size this new picture to another one, you will need to save the re-sized picture as a file at first, then open this file and re-size it again.


Q: Getting tighter segmentation results of Deeplab for small/underbalanced classes I have trained the official Tensorflow deeplab model (https://github.com/tensorflow/models/tree/master/research/deeplab) on the CelebAMask-HQ dataset (https://github.com/switchablenorms/CelebAMask-HQ), to have a model that can semantically segment all facial segments (e.g. Eyes, nose, etc.). I have spent little time in hyperparameter settings and use the default settings:
CUDA_VISIBLE_DEVICES=0 python "${WORK_DIR}"/deeplab/train.py \
  --logtostderr \
  --train_split="train" \
  --model_variant="xception_65" \
  --atrous_rates=6 \
  --atrous_rates=12 \
  --atrous_rates=18 \
  --output_stride=16 \
  --decoder_output_stride=4 \
  --train_crop_size="1025,1025" \
  --train_batch_size=2 \
  --training_number_of_steps=45000 \
  --fine_tune_batch_norm=false \
  --tf_initial_checkpoint="${WORK_DIR}/deeplab/pretrained_models/deeplabv3_pascal_trainval/model.ckpt" \
  --train_logdir="${WORK_DIR}/deeplab/logs" \
  --dataset="celeba" \
  --dataset_dir="${WORK_DIR}/deeplab/datasets/celeba/tfrecords_padded/"

The only thing that I have adapted are the class weights, in which I have calculated class weights based on the ratio of all pixels belonging to each class in the total dataset. These calculated ratios are:
class_ratio = {0: 0.287781127731224, #BG
                       1: 0.31428004829848194, #hair
                       2: 0.25334614328648697, #face
                       3: 0.008209905199792278, #brows
                       4: 0.0044636011242926155, #eyes
                       5: 0.020564768086557928, #nose
                       6: 0.004150659950132944, #u_lip
                       7: 0.00680743101856918, #l_lip
                       8: 0.0030163743167156494, #mouth
                       9: 0.040800302545885576, #neck
                       10: 0.008106960279456135, #ears
                       11: 0.03355246488702522, #clothes
                       12: 0.009293231642880359, #hat
                       13: 0, #ear_ring -> 0
                       14: 0, #glasses -> 0
                       15: 0 #necklace -> 0
                       }

As the class weights, I take 1/<class_ratio> , so the class weight for the background is 3.57 and for the brows is 121.95.
Finally, I do some data augmentation such as rotation, flipping and changing the brightness.
My results are fairly good, but there is something noticable when I input some of the images of my training set into the model. Below the original segmentation:

And here the segmented result:

As you can see, the segmented result is quite good, but especially the smaller classes such as the eyes, brows and nose are not as 'tightly segmented' as I would like them to be. Basically for all images that are segmented by the model, the eyes, nose and brows are greater than the original segmentation. Therefore, I would like to change a few hyperparameters to obtain tighter segmentation results for the smaller classes.
Any suggestions on a possible approach to obtain more thight results for the smaller classes? My current approach for calculating the class weight based on the absolute percentage of pixels belonging to each class in the total dataset works reasonably well, but maybe an alternative approach for calculation of the class weights works better? Or different underlying model structure that is able to do fine segmentation?
Any help is appreciated. Thanks!

A: You could try xception-71 with DPC, which should give tighter segmentations.
Or maybe you can try this https://github.com/tensorflow/models/issues/3739#issuecomment-527811265.


Q: mongs failed to findone when collection is under sharding migration I have a collection which enabled sharding on 2 replica sets, rs01 and rs02.
I added a new replica set rs03, it started to migrating chunks to rs03 slowly(it only migrated about 300 chunks in 4 days...)
It is weird that I do a find().limit(1) or findOne() on the collection on mongos, it hung there without response.(I need ctrl-c to escape the mongo shell on mongos).
How to check anything wrong that makes the query stuck?
Because the mongo.log on the rs01 is filled with migration actions that I cannot find useful message that make the findOne() query stuck.
Moreover, I tried findOne() on the sharded collection on rs01, rs02, rs03 ,all can return document. Only hung on mongos.
Below is message from mongos by db.locks.find( { _id : "balancer" } ).pretty()
mongos> db.locks.find( { _id : "balancer" } ).pretty()
{
    "_id" : "balancer",
    "state" : 2,
    "who" : "mongos30-02:27017:1459106195:1804289383:Balancer:846930886",
    "ts" : ObjectId("5784b2b42e0cc50683dc622e"),
    "process" : "mongos30-02:27017:1459106195:1804289383",
    "when" : ISODate("2016-07-12T09:04:52.713Z"),
    "why" : "doing balance round"
}

Update: I tried adding a balancer schedule at midnight. the balancer stopped now. Even the migration thread stopped, It still failed to findOne() on mongos. but worked on each primary node.
I got log from mongos when I issue findOne() command as below:
2016-07-13T14:15:06.118+0800 I SHARDING [LockPinger] cluster mongocfg30-01:27019,mongocfg30-02:27019,mongocfg30-03:27019 pinged successfully at Wed Jul 13 14:15:05 2016 by distributed lock pinger 'mongocfg30-01:27019,mongocfg30-02:27019,mongocfg30-03:27019/mongos30-01:27017:1459049395:1804289383', sleeping for 30000ms

The cluster map is as below(some mongo version are not the same)
All node OS is ubuntu 14.04 kvm, where all mongod have 20G RAM.


Q: Receiving contiinuous output from python spawn child process not working I am attempting to stream output from a weighing scale that is written in python. This program (scale.py) runs continuously and prints the raw value every half second.
import RPi.GPIO as GPIO
import time
import sys

from hx711 import HX711

def cleanAndExit():
    print "Cleaning..."
    GPIO.cleanup()
    print "Bye!"
    sys.exit()

hx = HX711(5, 6)

hx.set_reading_format("LSB", "MSB")

hx.reset()
hx.tare()

while True:
    try:
        val = hx.get_weight(5)
        print val

        hx.power_down()
        hx.power_up()
        time.sleep(0.5)
    except (KeyboardInterrupt, SystemExit):
        cleanAndExit()

I am trying to get each raw data point in a separate NodeJs program (index.js located in the same folder) that is printed by print val.  Here is my node program.
var spawn = require('child_process').spawn;
var py = spawn('python', ['scale.py']);

py.stdout.on('data', function(data){
  console.log("Data: " + data);
});

py.stderr.on('data', function(data){
  console.log("Error: " + data);
});

When I run sudo node index.js there is no output and the program waits into perpetuity.
My thought process is that print val should put output into stdout stream and this should fire the data event in the node program.  But nothing is happening.
Thanks for your help!

A: By default, all C programs (CPython included as it is written in C) that use libc will automatically buffer console output when it is connected to a pipe.
One solution is to flush the output buffer every time you need:
print val
sys.stdout.flush()

Another solution is to invoke python with the -u flag which forces it to be unbuffered:
var py = spawn('python', ['-u', 'scale.py']);


Q: Hodge Theory, intuition? We have the following theorem of Hodge, as follows:
$$\dim \ker \Delta^p = \dim H^p(M) = b_p(M).$$My question is, what is the intuition behind this statement?

A: I would say that the basic intuition is that a Riemannian metric defines an inner product on the space of differential forms, which can be used to define an adjoint operator to the exterior derivative.
Now consider the adjoint $(d_{k-1})^*:\Omega^k\to\Omega^{k-1}$ of $d_{k-1}:\Omega^{k-1}\to\Omega^k$. If the spaces $\Omega^\ell$ were all finite dimensional, then $\ker((d_{k-1})^*)$ would be the orthocomplement of $\DeclareMathOperator{\im}{im}\im(d_{k-1})$. Hence $\ker((d_{k-1})^*)\cap \ker(d_k)$ would be a complement to $\im(d_{k-1})$ in $\ker(d_k)$ and thus project isomorphically onto the cohomology space $H^k$. Hence you see that $\ker((d_{k-1})^*)\cap \ker(d_k)$ would have the same dimension as $H^k$.
Using adjointness again, it is easy to verify that (if things were finite dimensional) defining $\Delta_k=d_{k-1}\circ (d_{k-1})^*+(d_k)^*\circ d_k$ you get $\ker(\Delta_k)+\ker((d_{k-1})^*)\cap \ker(d_k)$. (This is like $\Delta(\phi)=0$ implies $0=d\Delta(\phi)=dd^*d\phi=0$ (since $dd=0$) and using adjointness twice, one gets $d\phi=0$, and likewise for $d^*$.)
Using functional analysis/PDE theory as mentioned in the answer of @GeorgesElencwajg , one proves that this continues to hold on a compact manifold in spite of the fact that one deals with infinite dimensional spaces.

A: Hodge theory is a vast subject, especially since Deligne and Griffiths revolutionized it and algebraized it around 1970 with the introduction of variations of Hodge structures and mixed Hodge structures,  axiomatic approaches which found amazing applications in algebraic geometry.
At the most elementary level I would say that Hodge theory is a refinement of De Rham cohomology:
De Rham proved that classical singular cohomology $H^*_{sing}(M,\mathbb R)$ of a smooth compact manifold $M$ is the same as the cohomology $H^*_{deRham}(M)$ of the complex of smooth differential forms $\Omega^*(M)$.
This means that a cohomology class can be represented by a closed differential form.
 But which one should one choose? Unfortunately there is no canonical choice.
Hodge theory furnishes a nice solution to this query: introduce a Riemannian structure on $M$ and then every cohomology class $c\in H^k_{deRham}(M)$ will contain one and ond only one closed harmonic form $\omega \in \Omega^k_{Harm}(M)$ representing it : $c=[\omega]$.
Harmonic here  means annihilated by the Laplace-Beltrami operator $\Delta^k:\Omega^k(M)\to \Omega^k(M)$, an analogue for $k$-forms of the standard Laplace operator $\Delta=\Delta^0:C^\infty(M) \to C^\infty(M)$ for functions.
Hodge theory immediately allows you to prove the finite-dimensionality of $H^k_{deRham}(M)$ and also gets you Poincaré duality for free: $H^{n-p}_{deRham}(M)\simeq (H^{p}_{deRham}(M))^*$
The price to pay for Hodge theory is, however, some investment in the theory of elliptic operators, which some geometers ignorant of partial differential equations (like me) find hard going.


Q: Link to files in VSCode .ipynb notebooks I'm trying to put a link to a file in a markdown cell in a notebook, for example:
See [feature scaling notes](feature_scaling_notes.md)

The file feature_scaling_notes.md is in the same folder as the .ipynb file.
A link is created, yet when I click on it, instead of opening the file, a browser window is opened with the address:
https://file+.vscode-resource.vscode-webview.net/...(file path)

How can I make the file open in the correct way?
Thanks.

A: Coming in v1.63 are file links in notebooks, see release note: file links in notebooks.

Markdown inside notebooks can now link to other files in the current
workspace
Links the start with / are resolved relative to the workspace root.
Links that start with ./ or just start with a filename are resolved
relative to the current notebook.

[link text](./cat.gif)

Bare http(s) links notebooks
In addition, markdown text that looks like an http and https is
now automatically turned into a link:


Q: Default android application for a Tablet In my application i have done all the process and they are working very well. Now my device needs only one application or other application must not come front to the user's view..
Can I make my Application as Default application or the only application viewable by the user?
To avoid the unnecessary usage of other applications or to keep time consumption I plan to try this.
Would I need to change anything in the Manifest.xml file of this solution solve this?

A: You cannot do this on a stock device. Your best bet is to create a launcher that only allows launching your app. The user needs to agree to run it however, and it can always be changed and/or disabled in Settings.


Q: Can you create anonymous inner classes in Swift? I'm tired of declaring entire classes as having the ability to handle UIAlertView clicks by making them extend UIAlertViewDelegate.  It starts to feel messy and wrong when I have multiple possible UIAlertViews, and have to distinguish which was clicked in the handler.
What I really want is to create a single object that implements the UIAlertViewDelegate protocol, and give this one-off object to my UIAlertView when showing it.
I want something like this:
let confirmDelegate = UIAlertViewDelegate() {
    func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
        // Handle the click for my alertView
    }
}

And then use it when showing the alert:
let alertView = UIAlertView(title: "Confirm", message: "Are you sure?", delegate: confirmDelegate, cancelButtonTitle: "No", otherButtonTitles: "Yes")
alertView.show()

Is this possible without declaring a new class?
I understand I could do something like this:
class ConfirmDelegate: UIAlertViewDelegate {
    func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
        // ...
    }
}

And then instantiate a ConfirmDelegate(), but I'm just wondering if this is possible as one-liner class declaration and instantiation.

A: As @ChrisWagner states in his comment, you shouldn't need to do any of this in iOS8, at least for UIAlertView since there is a new UIAlertViewController that uses closures without any delegates. But from an academic point of view, this pattern is still interesting.
I wouldn't use anonymous class at all. I would just create a class that can be assigned as the delegate and accept closures to execute when something happens.
You could even upgrade this to accept a closure for each kind of action: onDismiss, onCancel, etc. Or you could even make this class spawn the alert view, setting itself as the delegate.
import UIKit

class AlertViewHandler: NSObject, UIAlertViewDelegate {
    typealias ButtonCallback = (buttonIndex: Int)->()
    var onClick: ButtonCallback?

    init(onClick: ButtonCallback?) {
        super.init()
        self.onClick = onClick
    }

    func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
        onClick?(buttonIndex: buttonIndex)
    }
}

class ViewController: UIViewController {

    // apparently, UIAlertView does NOT retain it's delegate.
    // So we have to keep it around with this instance var
    // It'll be nice when all of UIKit is properly Swift-ified :(
    var alertHandler: AlertViewHandler?

    func doSoemthing() {
        alertHandler = AlertViewHandler({ (clickedIndex: Int) in
            println("clicked button \(clickedIndex)")
        })

        let alertView = UIAlertView(
            title: "Test",
            message: "OK",
            delegate: alertHandler!,
            cancelButtonTitle: "Cancel"
        )
    }
}

Passing around closures should alleviate the need for anonymous classes. At least for the most common cases.

A: Unfortunately as far as I understand it, no you cannot effectively create anonymous inner classes. The syntax you suggest would be really nice IMO though.
Here is my attempt at getting something close to what you want, it's no where near as clean though.
import UIKit

class AlertViewDelegate: NSObject, UIAlertViewDelegate {
    func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {

    }

    func alertView(alertView: UIAlertView!, didDismissWithButtonIndex buttonIndex: Int) {

    }

    func alertView(alertView: UIAlertView!, willDismissWithButtonIndex buttonIndex: Int) {

    }

    func alertViewCancel(alertView: UIAlertView!) {

    }

    func alertViewShouldEnableFirstOtherButton(alertView: UIAlertView!) -> Bool {
        return true
    }
}

class ViewController: UIViewController {
    var confirmDelegate: AlertViewDelegate?

    func doSoemthing() {
        confirmDelegate = {

            class ConfirmDelegate: AlertViewDelegate {
                override func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
                    println("clicked button \(buttonIndex)")
                }
            }

            return ConfirmDelegate()
        }()

        let alertView = UIAlertView(title: "Test", message: "OK", delegate: confirmDelegate, cancelButtonTitle: "Cancel")
    }

}


Q: My api post request is working in postman tool but it is showing error in the console of a browser? This is postman tool and here post method is working fine hereI have attached here the screenshot of postman
[In the console, it's showing error. Please help me to resolve this issue.][2This is browser console screenshot

A: In postman you are doing a post and in browser by default it's a GET
So the error says there is no endpoint that accepts a GET method.
If you change method to get in postman you should get same 404


Q: How to get latest order comment on the order grid column? In magento 1.9 how we can get comment column in sale -> orders with the latest comment e.g Customer is redirected to Paypal
Any idea what will be the query for this?

A: Create your custom renderer, extended from renderer abstract:
class Vendor_Module_Block_Adminhtml_Widget_Grid_Column_Renderer_History extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
    public function render(Varien_Object $row)
    {
        $orderId = $row->getId();
        $order = Mage::getModel('sales/order')->load($orderId);
        $history = $order->getStatusHistoryCollection()->getFirstItem();
        return $history->getComment();
    }
}

Then add new column to order grid, with this renderer:
$this->addColumn('history', array(
    'header' => Mage::helper('sales')->__('History status'),
    'type'  => 'text',
    'renderer' => new Vendor_Module_Block_Adminhtml_Widget_Grid_Column_Renderer_History()
));


Q: How to implement constraints for 2 labels between 2 images for xib file Edit: PLEASE LEAVE A COMMENT IF YOU'RE GOING TO DISLIKE SO I CAN IMPROVE MY QUESTION
I'm trying to recreate a custom table view cell in my xib file as shown below. The company's square image is on the left. The company's name and company's booth (2 UI Labels) are to the right of the company's image. The star button is to the right of the text and is a square image. I guesstimated that the company's image and favorites button should be about 8px from the top and edge.

I tried to create 4 constraints for the top, bottom, left, and right of every element (image, 2 UI labels, and button). I also added 1:1 aspect ratio constraint to the image and button to make sure the image would be square. Then I aligned the left edge of the 2 UI labels. I vertically centered the image and the button. However, it came out with no star button and the location and title switched. How do I create this design using constraints?

A: Their is no difficulty with that.
First if we talk about your left UIImageView, Set following constraints,

*

*Leading constraint

*Fixed Height

*Fixed Width

*Centre Vertically

After that the UIImageView on left, set following constraints,

*

*Trailing space from superview

*Fixed Height

*Fixed Width

*Centre Vertically

Now for both Labels, put them in a UIView and give that UIView following constraints,

*

*Leading space from left image view.

*trailing space from right image view.

*top space from superview

*bottom space from superview

Now for upper UILabel, Set following constraints,

*

*Leading space

*Trailing space

*top space

Now for lower UILabel, Set following constraints,

*

*Leading space

*Trailing space

*top space from upper UILabel

*bottom space

After all this, i think that this will work for you.

A: You can use the constraints in the image below. It will work for all screen size and for any height of row.


Q: How to get Unique Device ID for Amazon Kindle Fire To get the Unique Device ID on Android phones/tablets, we use the following:
((TelephonyManager) ctx.getSystemService(Context.TELEPHONY_SERVICE)).getDeviceId()

But for Kindle Fire, we can't get one.

A: You should try using the following line:
deviceId = Secure.getString(context.getContentResolver(), Secure.ANDROID_ID);

This will get the device ID from tablets, the code you're using only works on phones (it will return null on tablets)

A: put
<uses-permission android:name="android.permission.READ_PHONE_STATE" />

then
try this:
public String deviceId;

then:
// ------------- get UNIQUE device ID
        deviceId = String.valueOf(System.currentTimeMillis()); // --------
                                                                // backup for
                                                                // tablets etc
        try {
            final TelephonyManager tm = (TelephonyManager) getBaseContext()
                    .getSystemService(Main.TELEPHONY_SERVICE);
            final String tmDevice, tmSerial, tmPhone, androidId;
            tmDevice = "" + tm.getDeviceId();
            tmSerial = "" + tm.getSimSerialNumber();
            androidId = ""
                    + android.provider.Settings.Secure.getString(
                            getContentResolver(),
                            android.provider.Settings.Secure.ANDROID_ID);
            UUID deviceUuid = new UUID(androidId.hashCode(),
                    ((long) tmDevice.hashCode() << 32) | tmSerial.hashCode());
            deviceId = deviceUuid.toString();
        } catch (Exception e) {
            Log.v("Attention", "Nu am putut sa iau deviceid-ul !?");
        }
        // ------------- END get UNIQUE device ID

from here -> Is there a unique Android device ID?


Q: Как в плагине Theme My Login настроить переадресацию на профиль? Есть сайт на wordpress на котором установлен плагин профиля Theme My Login в котором создаются 2 страницы:
1 - мой аккаунт, куда сразу же перебрасывает после авторизации пользователя и
2 - ваш профиль
как сделать так, чтобы после авторизации перебрасывало юзера в ваш профиль, а не мой аккаунт?
пробовал переопределять функцию редиректа, но безрезультатно..
function tml_redirect_url( $url, $action ) {
  if ( 'register' == $action )
    $url = 'АДРЕС';
  return $url;
}
add_filter( 'tml_redirect_url', 'tml_redirect_url', 10, 2 );

вот функции ответственные за редирект
ajax.php
public function tml_redirect_url( $url, $action ) {
    if ( Theme_My_Login::is_tml_page() && in_array( $action, self::default_actions() ) && isset( $_GET['ajax'] ) ) {
      switch ( $action ) {
        case 'lostpassword' :
        case 'retrievepassword' :
        case 'register' :
          $url = add_query_arg( 'ajax', 1, $url );
          break;
        case 'login' :
          $url = Theme_My_Login::get_page_link( 'login', 'ajax=1' );
          break;
      }
    }
    return $url;
  }

class-theme-my-login-template.php
public function the_redirect_url( $action = '' ) {
    echo esc_attr( $this->get_redirect_url( $action ) );
  }
  public function get_redirect_url( $action = '' ) {

    $theme_my_login = Theme_My_Login::get_object();

    if ( empty( $action ) )
      $action = $this->get_option( 'default_action' );

    $redirect_to = isset( $_REQUEST['redirect_to'] ) ? $_REQUEST['redirect_to'] : '';

    switch ( $action ) {
      case 'lostpassword' :
      case 'retrievepassword' :
        $url = apply_filters( 'lostpassword_redirect', ! empty( $redirect_to ) ? $redirect_to : Theme_My_Login::get_page_link( 'login', 'checkemail=confirm' ) );
        break;
      case 'register' :
        $url = apply_filters( 'registration_redirect', ! empty( $redirect_to ) ? $redirect_to : Theme_My_Login::get_page_link( 'login', 'checkemail=registered' ) );
        break;
      case 'login' :
      default :
        $url = apply_filters( 'login_redirect', ! empty( $redirect_to ) ? $redirect_to : admin_url(), $redirect_to, null );
    }
    return apply_filters( 'tml_redirect_url', $url, $action );
  }

A: Сделал намного проще - на странице личного кабинета разместил шорткод профиля
[theme-my-login default_action=profile profile_template=tml-profile-form.php]


Q: Using Shared Preferences to persist DataMap android wear I had a question related to the FORM Watch Face. I see that SharedPreferences have been used to persist DataMap. Why was it necessary to persist the data when we can fetch the DataMap from the Wearable.DataApi anytime? The developer.android wearable documentation does not mention using Shared Preferences anywhere and even the Android wear samples do not use SharedPreferences. Is it for performance or am I missing something here?

A: Roman Nurik posted an answer here:
https://plus.google.com/111335419682524529959/posts/QJcExn49ZrR

For performance. When the settings activity loads of the watch first shows up, I didn't want to wait for an IPC call to complete before showing anything

For a detailed description checkout my medium post.


Q: Unable to resolve dependencies react native google fit After adding the package I can't build the project. Error:
A problem occurred configuring project ':app'.
> Could not resolve all dependencies for configuration ':app:_debugApk'.
   > A problem occurred configuring project ':react-native-google-fit'.
      > Could not resolve all dependencies for configuration ':react-native-google-fit:_debugPublishCopy'.
         > Could not find com.google.android.gms:play-services-auth:11.6.0.
           Searched in the following locations:
               file:/Users/wojciech/Library/Android/sdk/extras/google/m2repository/com/google/android/gms/play-services-auth/11.6.0/play-services-auth-11.6.0.pom
               file:/Users/wojciech/Library/Android/sdk/extras/google/m2repository/com/google/android/gms/play-services-auth/11.6.0/play-services-auth-11.6.0.jar
               file:/Users/wojciech/Documents/dev/uni/swifty-app/Swifty/android/sdk-manager/com/google/android/gms/play-services-auth/11.6.0/play-services-auth-11.6.0.jar
               file:/Users/wojciech/Library/Android/sdk/extras/android/m2repository/com/google/android/gms/play-services-auth/11.6.0/play-services-auth-11.6.0.pom
               file:/Users/wojciech/Library/Android/sdk/extras/android/m2repository/com/google/android/gms/play-services-auth/11.6.0/play-services-auth-11.6.0.jar
               file:/Users/wojciech/Documents/dev/uni/swifty-app/Swifty/android/sdk-manager/com/google/android/gms/play-services-auth/11.6.0/play-services-auth-11.6.0.jar
           Required by:
               Swifty:react-native-google-fit:unspecified
         > Could not find com.google.android.gms:play-services-fitness:11.6.0.
           Searched in the following locations:
               file:/Users/wojciech/Library/Android/sdk/extras/google/m2repository/com/google/android/gms/play-services-fitness/11.6.0/play-services-fitness-11.6.0.pom
               file:/Users/wojciech/Library/Android/sdk/extras/google/m2repository/com/google/android/gms/play-services-fitness/11.6.0/play-services-fitness-11.6.0.jar
               file:/Users/wojciech/Documents/dev/uni/swifty-app/Swifty/android/sdk-manager/com/google/android/gms/play-services-fitness/11.6.0/play-services-fitness-11.6.0.jar
               file:/Users/wojciech/Library/Android/sdk/extras/android/m2repository/com/google/android/gms/play-services-fitness/11.6.0/play-services-fitness-11.6.0.pom
               file:/Users/wojciech/Library/Android/sdk/extras/android/m2repository/com/google/android/gms/play-services-fitness/11.6.0/play-services-fitness-11.6.0.jar
               file:/Users/wojciech/Documents/dev/uni/swifty-app/Swifty/android/sdk-manager/com/google/android/gms/play-services-fitness/11.6.0/play-services-fitness-11.6.0.jar
           Required by:
               Swifty:react-native-google-fit:unspecified

Thanks in advance.

A: There are two common ways to solve it.
 1. add to your android/build.gradle file, under allprojects/repositoris sections
maven {
        url 'https://maven.google.com'
}

so that it should looks like:
allprojects {
    repositories {
        mavenLocal()
        maven {
            url 'https://maven.google.com'
        }
        maven {
            // All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        maven { url "https://jitpack.io" }
        jcenter()
    }
}

*Another way (works for me) - for react-native-google-fit lib, and in android/build.gradle of library change dependency to
compile 'com.google.android.gms:play-services-auth+'
compile 'com.google.android.gms:play-services-fitness+'
And use your fork in your project


Q: Send email with log file as attachment I am using Hadoop (CDH 5.4.8) to process the unstructured data and after successful processing I want to send a mail notification to the concerned team with log file as attachment.
CDH 5.4.8 Oozie does not support attachment feature in email action. So I want to do this using shell script. Please let me know the best way to do this.

A: You can easily send an email from within a shell by piping a complete mail message (header and body) into sendmail. This assumes that the host you're doing this is properly configured with a mail transfer agent (e.g. sendmail or postfix) to send email messages.
The easiest way to send email with an attachment is to create a simple template message in your mail user agent (e.g. Thunderbird), and copy its contents as a template with the view source command. Modify that template to suit your needs and place it in the shell script.
Here is an example:

#!/bin/sh
cat <<\EOF |
To: Ramesh <ramesh@example.com>
From: Diomidis Spinellis <dds@aueb.gr>
Subject: Here are your Hadoop results
Message-ID: <5700BF28.2070500@aueb.gr>
Date: Sun, 3 Apr 2016 09:58:48 +0300
MIME-Version: 1.0
Content-Type: multipart/mixed;
 boundary="------------030303090406090809090501"

This is a multi-part message in MIME format.
--------------030303090406090809090501
Content-Type: text/plain; charset=utf-8; format=flowed
Content-Transfer-Encoding: 7bit

The attachment contains your Hadoop results.

--------------030303090406090809090501
Content-Type: application/octet-stream;
 name="data"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
 filename="data"

HviDNR105+2Tr0+0fsx3OyzNueQqPuAXl9IUrafOi7Y=
--------------030303090406090809090501--
EOF
sendmail ramesh@example.com

To configure a fixed message with actual data, replace the parts you want to modify with commands that generate them. (Note the missing backslash from the here document EOF marker.)

#!/bin/sh
cat <<EOF |
To: Ramesh <ramesh@example.com>
From: Diomidis Spinellis <dds@aueb.gr>
Subject: Here are your Hadoop results
Message-ID: <5700BF28.2070500@aueb.gr>
Date: $(date -R)
MIME-Version: 1.0
Content-Type: multipart/mixed;
 boundary="------------030303090406090809090501"

This is a multi-part message in MIME format.
--------------030303090406090809090501
Content-Type: text/plain; charset=utf-8; format=flowed
Content-Transfer-Encoding: 7bit

The attachment contains your Hadoop results.

--------------030303090406090809090501
Content-Type: application/octet-stream;
 name="data"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
 filename="data"

$(base64 binary-data-file.dat)
--------------030303090406090809090501--
EOF
sendmail ramesh@example.com


Q: Why is WKWebView not opening links with target=“_blank”? What is wrong with my code? Why is WKWebView not opening links with target=“_blank”? I want to open links that are opening in the new tab with the default browser. How Can this be achieved?
import UIKit
import WebKit

class ViewController: UIViewController, WKUIDelegate {

    @IBOutlet weak var webView: WKWebView!
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view, typically from a nib.
        let url = "https://example.com"
        let request = URLRequest(url: URL(string: url)!)
        self.webView.load(request)
        self.webView.addObserver(self, forKeyPath: #keyPath(WKWebView.isLoading), options: .new, context: nil)

        // Page Scrolling - false or true
        webView.scrollView.isScrollEnabled = false

        // Open new tab links
        webView.uiDelegate = self
        func webView(_ webView: WKWebView, createWebViewWith configuration: WKWebViewConfiguration, for navigationAction: WKNavigationAction, windowFeatures: WKWindowFeatures) -> WKWebView? {
            if let frame = navigationAction.targetFrame,
                frame.isMainFrame {
                return nil
            }
            // for _blank target or non-mainFrame target
            webView.load(navigationAction.request)
            return nil
        }

    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "loading" {
            if webView.isLoading {
                activityIndicator.startAnimating()
                activityIndicator.isHidden = false
            } else {
                activityIndicator.stopAnimating()
                activityIndicator.isHidden = true
            }
        }
    }
}

A: This is the correct code for the question

import UIKit
import WebKit

class ViewController: UIViewController, WKUIDelegate {

    @IBOutlet weak var webView: WKWebView!
    @IBOutlet weak var activityIndicator: UIActivityIndicatorView!

    override func viewDidLoad() {
        super.viewDidLoad()
        webView.uiDelegate = self

        // Do any additional setup after loading the view, typically from a nib.
        let url = "https://example.com"
        let request = URLRequest(url: URL(string: url)!)
        self.webView.load(request)
        self.webView.addObserver(self, forKeyPath: #keyPath(WKWebView.isLoading), options: .new, context: nil)

        // Page Scrolling - false or true
        webView.scrollView.isScrollEnabled = false

    }

    // Open new tab links
    func webView(_ webView: WKWebView,
       createWebViewWith configuration: WKWebViewConfiguration,
       for navigationAction: WKNavigationAction,
       windowFeatures: WKWindowFeatures) -> WKWebView? {
      if navigationAction.targetFrame == nil, let url = navigationAction.request.url, let scheme = url.scheme {
        if ["http", "https", "mailto"].contains(where: { $0.caseInsensitiveCompare(scheme) == .orderedSame }) {
          UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
      }
      return nil
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if keyPath == "loading" {
            if webView.isLoading {
                activityIndicator.startAnimating()
                activityIndicator.isHidden = false
            } else {
                activityIndicator.stopAnimating()
                activityIndicator.isHidden = true
            }
        }
    }
}


Q: Combinations of Characters in an n by n Character Array: First a note: Sorry that my images aren't separated. I'm a new member, so I don't have enough reputation points to post more than a single hyperlink.
Let M be an n by n array (mathematically square matrix) of characters.
In M, I need to be able to find all permutation of characters with a restriction. The permutations do not have to be linear, but they they must contain characters such that each character is adjacent to at least one other character in the permutation. An example of an acceptable permutation follows below:
An unacceptable permutation is shown below.
I have derived this much:

*

*A permutation can have at most n squared characters in it (as no characters can be repeated).

*I do not know the exact number of permutation given the restrictions, but I believe there can be no more than the value generated by evaluating the expression pictured in the hyperlink.

I can very easily find the permutations which only contain characters in straight lines: vertical lines, horizontal lines, and diagonals. I am not sure of a way to exhaustively find all remaining permutations.
I have done research and have not been able to find a solution to a similar problem.
Any advice in the development of such an exhaustive algorithm would be greatly appreciated.
http://i.stack.imgur.com/uDNfv.png

A: One algorithm comes to mind immediately, though optimizations can be made, if time-complexity is a concern.
At each element in the 2x2 array (or we can call it a matrix if you like), there are 8 directions that we can travel (North, NE, East, SE, South, SW, West, NW).
The pseudo code for the meat of the algorithm goes a bit like this (I assume pass by value, so that "current_string" is a new string at each function call):
find(position, direction, current_string){
    new_letter = m[0, position + direction];
    if(!current_string.Contains(new_letter)){
        // We have not yet encountered this letter during the search.
        // If letters occur more than once in the array, then you must
        // assign an index to each position in the array instead and
        // store which positions have been encountered along each
        // search path instead.
        current_string += new_letter;
        find(position, (0, 1), current_string);
        find(position, (1, 1), current_string);
        find(position, (1, 0), current_string);
        find(position, (1, -1), current_string);
        find(position, (0, -1), current_string);
        find(position, (-1, -1), current_string);
        find(position, (-1, 0), current_string);
        find(position, (-1, 1), current_string);
    } else {
        // This letter has been encountered during this path search,
        // terminate this path search. See comment above if letters
        // occur more than once in the matrix.
        print current_string; // Print one of the found strings!
    }
}

Now you need to add some checks for things like "is position + direction outside the bounds of the array, if so, print current_string and terminate".
The high level idea of the algorithm above is to search along all possible paths recursively, terminating paths when they run into themselves (in the same way that snakes die in the game Snake).
If you use hashing to test containment of a new letter against the current string (as per the line if(!current_string.Contains(new_letter)){), which is amortized O(1) searching, then the worst case runtime complexity of this algorithm is linear in the number of possible strings there are in the matrix. I.e. if there are n possible string combonations in the matrix, then this algorithm takes about cn steps to complete for large n, where c is some constant.


Q: How I can use mouse events with Jquery I'm tryng to configure the list of users in a chat adding the function slide
something like this
http://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_slide_down
Similar facebook, when mouse is over focus, the chat container is slowly hidden
I'm using jquery-1.8.1.min.js in the proyect and have the principal container with a id and i can configure those events like
$("mainContainer").someEvent(function () {
code...
}

I can use click, but i haven't mouse event when I put cursor inside for example.
I need .mousedown(), .mouseleave(), .mousemove(), hover(), etc.
Need I use another library JS?
I wish something like this, think the green box is the container with list of users in chat
<!DOCTYPE html>

User1

User2

User3

User4

A: Check http://api.jquery.com/on/
You could do something like this:
$("body").on({
    click: function() {
        //...
    }
    mouseleave: function() {
    //...
    },
    //other event, etc
}, "#yourthing");

A: You can try this and can use any other mouse events according to your need:
$("#mainContainer").on('hover', function(){
      $(selector).slideDown("slow");
  }), function(){
      $(selector).slideUp("slow");
  });

A: Maybe something like this? You might not need any JavaScript for the mouseover effect.

#mainConatiner {
  width: 300px;
  height: 30px;
  border: 1px solid #000;
}
ul {
  opacity: 0;
  transition: opacity 250ms ease;
}
#mainContainer:hover ul {
  opacity: 1;
}

  Hover me!

User 1

User 2

Let me know if it helps! Good luck.

A: JQuery has mouse based events. See here.
See this fiddle where I have adapted the w3schools example to work on mouseenter and mouseleave

A: You could use it like this, by calling the same function for multiple events:
$("mainContainer").on('click mouseenter',function (event) {
    //This gives you what event happened, might be 'click' or 'mouseenter'
    var type = event.type;
});