text:
Q: Validation failed for one or more entities In Angular Js I am working on MVC with Angular Js . I Added the ADO.NET Model to generate the essential classes. I am trying to register user by using Angular Js with ADO.NET Model Entities. I got two error when I click the submit button I got this error ....
angular.js:12701 POST http://localhost:53526/Register/AddUser 500 (Internal Server Error)...

When I click this link from Console Window from Google Chrome its saying ....
**Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

Here is my Local Class to Encrypt the user password..
public static class Utility
        {
            public static string Encryptpassword(string password)
            {
                string hashedPassword = BCrypt.Net.BCrypt.HashPassword(password, BCrypt.Net.BCrypt.GenerateSalt(12));
                return hashedPassword;
            }

            public static bool CheckPassword(string enteredPassword, string hashedPassword)
            {
                bool pwdHash = BCrypt.Net.BCrypt.Verify(enteredPassword, hashedPassword);
                return pwdHash;
            }
        }
    }

Here is my Register Controller Class...
 public class RegisterController : Controller
    {
        public ActionResult Register()
        {
            return View();
        }

        //To check that user entered is already present or not.
        public bool CheckUser(string user)
        {
            bool Exists = false;
            using (HalifaxDatabaseEntities context = new HalifaxDatabaseEntities())
            {
                var uName = context.UserLogins.Where(x => x.UserName == user).ToList();
                if (uName.Count != 0)
                {
                    Exists = true;
                }
            }
            return Exists;
        }

        //For saving the user details in database table.
        public string AddUser(UserLogin usr)
        {
            if (usr != null)
            {
                if (CheckUser(usr.UserName) == false)
                {
                    using (HalifaxDatabaseEntities context = new HalifaxDatabaseEntities())
                    {
                        UserLogin createUser = new UserLogin();
                        createUser.UserName = usr.UserName;
                        createUser.Firstname = usr.Firstname;
                        createUser.Lastname = usr.Lastname;
                        createUser.Email = usr.Email;
                        createUser.DateTimeCreated = DateTime.Now;
                        createUser.Password = Utility.Encryptpassword(usr.Password);
                        context.UserLogins.Add(createUser);
                        context.SaveChanges();
                    }
                    return "User created !";
                }
                else
                {
                    return "User already present !";
                }
            }
            else
            {
                return "Invalid Data !";
            }
        }
    }
}

Here is Angular Js Code(Module.js)....
 var app = angular.module("myApp", [])
        .controller('Ctrl', ["$scope", 'myService', function ($scope, myService) {

            $scope.SaveUser = function () {
                $("#divLoading").show();
                var User = {
                    FName: $scope.fName,
                    LName: $scope.lName,
                    Email: $scope.uEmail,
                    Password: $scope.uPwd,
                    UserName: $scope.uName
                };

                var response = myService.AddUser(User);
                response.then(function (data) {
                    if (data.data == "1") {
                        $("#divLoading").hide();
                        clearFields();
                        alert("User Created !");
                        window.location.href = "/Register/Login";
                    }
                    else if (data.data == "-1") {
                        $("#divLoading").hide();
                        alert("user alraedy present !");
                    }
                    else {
                        $("#divLoading").hide();
                        clearFields();
                        alert("Invalid data entered !");
                    }
                });
            }

            function clearFields() {
                $scope.fName = "";
                $scope.lName = "";
                $scope.Email = "";
                $scope.Password = "";
                $scope.UserName = "";
            }

        }])
        .service("myService", function ($http) {

            this.AddUser = function (User) {
                var response = $http({
                    method: "post",
                    url: "/Register/AddUser",
                    data: JSON.stringify(User),
                    dataType: "json"
                });
                return response;
            }
        })

Here is MY HTML CODE ...
@{
    Layout = null;
}

    <title>Register</title>

    <link href="~/Content/bootstrap.css" rel="stylesheet" />

            @**@
Register User

                <form name="userForm" novalidate>

                                    First Name :

                                    <input type="text" class="form-control" placeholder="First Name" name="fName" ng-model="fName" required autofocus />

                                    Last Name :

                                    <input type="text" class="form-control" placeholder="Last Name" name="lName" ng-model="lName" required autofocus />

                                    Email :

                                    <input type="email" class="form-control" placeholder="User's Email" name="uEmail" ng-model="uEmail" required autofocus />

                                    Username :

                                    <input type="text" class="form-control" placeholder="Username" name="uName" ng-model="uName" required autofocus />

                                    Password :

                                    <input type="password" class="form-control" placeholder="Password" name="uPwd" ng-model="uPwd" required autofocus />

                                    <input type="button" value="Save" ng-click="SaveUser();" class="btn btn-success" />

                                    @Html.ActionLink("Sign in", "Login", "Register", new { @class = "btn btn-info" })

                                            please wait...

                </form>

Here is screen When I run the Application and click the submit button..
Here is screen shot when I click this link http://localhost:53526/Register/AddUser form Console Window..

A: You just need to pass it without JSON.stringify, also not need to mention data type
 .service("myService", function ($http) {

        this.AddUser = function (User) {
            var response = $http({
                method: "POST",
                url: "/Register/AddUser",
                data: User
            });
            return response;
        }
    })

Also apply this on your SaveChanges function to see the exact column name due to which you are facing this issue
 try
 {
  // Your code...
  // Could also be before try if you know the exception occurs in SaveChanges

  context.SaveChanges();
 }
 catch (DbEntityValidationException e)
 {
   foreach (var eve in e.EntityValidationErrors)
   {
    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
        eve.Entry.Entity.GetType().Name, eve.Entry.State);
     foreach (var ve in eve.ValidationErrors)
     {
        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
            ve.PropertyName, ve.ErrorMessage);
     }
   }
  throw;
}


text:
Q: Evernote, most efficeint way to find notes with tasks I'm building a simple app to list all my todos form Evernote and other apps. To find them form Evernote I am searching for all notes then filter those that contains <en-todo.
But there may be a better way than retreiving all content and filtering ?

A: Search on "todo:true" to find notes with at least one checkbox checked,  or
"todo:false" to find notes with at least one checkbox unchecked.
See the "Advanced Content Matching" section of this page from Evernote.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jquery, get the mousemove event with a div overlaping please help me.
I need to be able to draw a rectangle over images that are in a div with scroller.
With IE 9 or firefox when the mouse hit the rectangle area
stop sending the mousemove event to the image.
How can i make the mousemove event work, even if a div is over the image?
$("#AnImage")
.mousedown(function(event)
{
//Set the start point and create the new div as a marker. Start the creating process.
})
.mousemove(function(event)
{
//Moves according to the initial point, set the with and height of the marker
})
.mouseup(function(event){
//Stop the creating process. A new Rectangle is over the image.
});

Thanks.

A: You could use the pointer-events CSS property - if you have no items inside the <div> that you want to draw over the image.
#AnImage {
  pointer-events: none;
}

More info on the property: here, here, and here.


text:
Q: does eclipse allow watching only one expression at a time I am trying to watch expressions, but I am able to watch only one expression at a time.
Say I have three expressions below

*

*Integer.toString(i)

*Integer.toString(i*2)

*Integer.toString(i*3)

But at a time, I can see the value of only one of these expressions, the one that I choose to click on.
I was hoping to see the values of all the expressions side-by-side.

A: I think the values of all the expressions are only be seen one by one

Firstly, the expression is actually input by ourself, when input an expression, the result is shown on the right
Secondly,we can modify the expression value, such as, print the i value, then, we will increase i value by expression i = 2, lastly, print the i value again.if these expression are executed side by side, I guess the result has many
possibility.


text:
Q: How to pull the column name in to the data in SAS The table with date as a variable name with respect to VOL, I want to create a new variable as FLAG that IF variables having 1 pull the date of the variable name in to the FLAG column
  VOL   31-Dec-10   31-Dec-11   31-Dec-12   31-Dec-13   31-Dec-14   31-Dec-15
109001  0   0   0   0   1   0
109002  0   0   1   0   0   0
109003  0   0   1   0   0   0
109004  0   0   0   1   0   0
109006  0   0   1   0   0   1

output
 VOL    31-Dec-10   31-Dec-11   31-Dec-12   31-Dec-13   31-Dec-14   31-Dec-15   FLAG
109001  0   0   0   0   1   0   31-Dec-14
109002  0   0   1   0   0   0   31-Dec-12
109003  0   0   1   0   0   0   31-Dec-12
109004  0   0   0   1   0   0   31-Dec-13
109006  0   0   1   0   0   1   31-Dec-15

A: You want to use the vlabel() function since those column headings don't meet standard variable name requirements and I'm assuming they're labels.  Below is example code to put in a data step, but you'll have to know the actual variable names for the array declaration and replace date1--date99 with them.
array mydates (*) date1--date99;
do over mydates;
    if mydates = 1 then flag = vlabel(mydates);
end;

The way this loop is written, it will leave the date of the rightmost occurrence of 1, which seems consistent with your example in the 19006 row.
See also vname().


text:
Q: Comparision of range projections of elements in a von Neumann algebra Let $M$ be a von Neumann algebra and $a,b\in M$. Suppose $a\geq b$, then we have $R_a\geq R_b$, where $R_a$ is the range projection of $a$ and $R_b$ is the range projection of $b$.
According to the definition of $R_b$, $R_b$ is the smallest projection such that $R_b b=b$. If we prove that $R_ab=b$, then we can conclude that $R_a\geq R_b$.
My question is that how to deduce that $R_ab=b$?

A: Assuming that $a$ and $b$ are positive elements with $a\geq b$, then,
for every $n\in {\mathbb N}$, we have that
$$
  c_n:= (1-a^{1/n})b^{1/2} \quad {\buildrel n\to 0 \over
\longrightarrow} \quad 0,
  $$
because
$$
  c_nc_n^* =
  (1-a^{1/n})b(1-a^{1/n}) \leq
  (1-a^{1/n})a(1-a^{1/n}) \to 0.
  $$
Therefore
$$
  a^{1/n}b^{1/2} \to  b^{1/2}.
  $$
Denoting by $\bar R(x)$ the closure of the range of an operator
$x$, and observing that $\bar R(a^{1/n}) = \bar R(a)$, we deduce from the above that
$$
  \bar R(b^{1/2}) \subseteq  \bar R(a),
  $$
but since   $\bar R(b^{1/2}) = \bar R(b)$,  we get
$\bar R(b)\subseteq  \bar R(a)$, whence the conclusion.


text:
Q: Algorithm for building an equation from a list of numbers using basic operators (+,-,*,/) I am struggling to find a smart/creative way to approach this problem instead of a brute force algorithm. Any insights that could allow me to view this problem in a different light would be greatly appreciated. Any language can be used.
Given a sequence of numbers, it is sometimes possible to place the basic operations of =, +, −, ×, and ÷ between those number to build a complete, correct equation. For instance, the sequence [2, 3, 8, 4, 22] can be made into an equation by putting the symbols in the following places:
2 + 3 × 8 − 4 = 22
Note how the order of operations is followed. Write a program that will build such a number sentence, given the list of numbers. An ideal solution would allow the numbers to be specified on the command line, but prompting the user for a list is also acceptable. If no true sentence can be found, print such a message to the user. Assume only one = will be used (allowing for multiple equal signs makes the assignment a lot harder, but is fun!)
You may present the sentence using prefix, infix, or postfix operators.
Sample Output
Note that some of these sequences could form multiple sentences. Only one need be printed.
$ assignment -4 1 2 3 4
1 - 2 = 3 - 4
$ assignment -4 1 1 1
1 / 1 = 1
$ assignment -4 0 18 1 2 1 1
0 / 18 = 1 - 2 + 1 * 1
$ assignment -4 2 2 2
No equation found


text:
Q: Add swipe effiect using recyclerview like inshorts app I am trying to implement the swipe effect like inshorts and way2news app, So far I can only find the solutions using viewpager and pageradapter. Those are working fine for me but I have to implement the same solution using recyclerview and recyclerview adapter.
Below is the code I have tried
Created a custom layoutmanager which is supposed to achieve the same result.
public class CustomLinearLayoutManager extends LinearLayoutManager {

private final float mShrinkAmount = 0.15f;
private final float mShrinkDistance = 1.0f;
public CustomLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
    super(context, orientation, reverseLayout);

}

@Override
public int scrollVerticallyBy(int dy, RecyclerView.Recycler recycler, RecyclerView.State state) {
    int orientation = getOrientation();
    if (orientation == VERTICAL) {

// below code is not giving the expected result

        int scrolled = super.scrollVerticallyBy(dy, recycler, state);
        float midpoint = getHeight() / 2.0f;
        float d0 = 0.0f;
        float d1 = mShrinkDistance * midpoint;
        float s0 = 1.0f;
        float s1 = 1.0f - mShrinkAmount;
        // loop through active children and set scale of child
        System.out.println(getChildCount());
        for (int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);

            float childMidpoint = (getDecoratedBottom(child) + getDecoratedTop(child)) / 2.0f;
            float d = Math.min(d1, Math.abs(midpoint - childMidpoint));
            float scale = s0 + (s1 - s0) * (d - d0) / (d1 - d0);
            child.setScaleX(scale);
            child.setScaleY(scale);
        }
        return scrolled;
    } else {
        return 0;
    }

}

}

setting the custom layoutmanager and added the PagerSnapHelper for fling/snapping effect in MainActivity
    adapter = new RecyclerViewAdapter(setData(),this);
    RecyclerView recyclerView = findViewById(R.id.recycler_view);
    recyclerView.setLayoutManager(new CustomLinearLayoutManager(this, LinearLayoutManager.VERTICAL,false));
    //recyclerView.addItemDecoration(new OverlapDecoration());
    PagerSnapHelper snapHelper = new PagerSnapHelper();
    snapHelper.attachToRecyclerView(recyclerView);
    recyclerView.setAdapter(adapter);

Behaviour i want

Behaviour I am getting

What can I try next?

A: You can try below library to get way2news app like effect
https://github.com/openaphid/android-flip


text:
Q: Database collation w.r.t Spring DATA REST project I have an application being built on Spring DATA and Spring DATA REST platform (Using Spring Boot). Hibernate is the JPA provider and SQL Server 2008 database.
Further, we have alphanumberic ID columns and so, with case insensitive DB collation, the entity with ID "a123" is treated the same as "A123".
So, if I have a table called Employee with the ID as "a123" then, I get the below results:
{
  "employeeID" : "a123",
  "links" : [ ],
  "content" : [ ],
  "links" : [ {
    "rel" : "self",
    "href" : "http://localhost/spring/Employee/a123{?projection}"
  }, {
    "rel" : "employeeGroups",
    "href" : "http://localhost/spring/Employee/a123/employeeGroups"
  } ]
}

And the same thing with ID "A123" as below
{
  "employeeID" : "A123",
  "links" : [ ],
  "content" : [ ],
  "links" : [ {
    "rel" : "self",
    "href" : "http://localhost/spring/Employee/A123{?projection}"
  }, {
    "rel" : "employeeGroups",
    "href" : "http://localhost/spring/Employee/A123/employeeGroups"
  } ]
}

To an end user both the above results are the same and isnt a big deal in having  case insensitive ID.
So far so good. But, when I hit the URL http://localhost/spring/Employee/A123/employeeGroups, i get the list of employeeGroups.. but the same thing doesnt happen with http://localhost/spring/Employee/a123/employeeGroups..  (The actual value stored in the table is "A123").
Im not sure if there is a way to attach a DB collation value to Hibernate or have Spring DATA REST interfaces to always convert the user input value to Upper case before querying the DB.
Please help.
Thanks!


text:
Q: Updating cells with UIImageView to show currently selected item I am using a sliding view controller which holds the main controller on top and a slide left menu controller.
The controller on the left works as the menu like Facebook/Pintrest apps etc. It is a UITableView on the left.
Here is my setup:
cellForRowAtIndexPath
static NSString *CellIdentifier = @"MainMenuCell";

UITableViewCell *cell = (UITableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    UIView *topSplitterBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, cell.bounds.size.width, 1)];
    topSplitterBar.backgroundColor = [UIColor colorWithRed:62.0/255.0 green:69.0/255.0 blue:85.0/255.0 alpha:1];
    [cell.contentView addSubview:topSplitterBar];

    UIImage *arrowImage = [UIImage imageNamed:@"selectedArrow"];
    self.arrowSelectedView = [[UIImageView alloc] initWithFrame:CGRectMake(240, 10, arrowImage.size.width, arrowImage.size.height)];
    self.arrowSelectedView.image = arrowImage;
    [cell.contentView addSubview:self.arrowSelectedView];
    self.arrowSelectedView.hidden = YES;
}

//////
// ADDITIONAL GLUE CODE HERE TO SET LABELS ETC....
//////

if (currentDisplayed) {
    // This is for the current item that is being displayed
    cell.contentView.backgroundColor = [UIColor colorWithRed:50.0/255.0 green:56.0/255.0 blue:73.0/255.0 alpha:1];
    self.arrowSelectedView.hidden = NO;
} else {
    cell.contentView.backgroundColor = [UIColor colorWithRed:75.0/255.0 green:83.0/255.0 blue:102.0/255.0 alpha:1.0];
    self.arrowSelectedView.hidden = YES;
}

NSLog(@"%@",cell.contentView.subviews);
return cell;

There are a total of 7 cells in 2 sections for the table view. One cell in section 1 (0) and the rest in section 2 (1). There are three cells which show a main controller on the top. Once they are selected I would like to update the table view to show an arrow next the cell like this:

Here is the example code for: didSelectRowAtIndexPath
        UIViewController *newTopViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"ProfileVC"];

        __weak typeof(self) weakSelf = self;

        [self.slidingViewController anchorTopViewOffScreenTo:ECRight animations:nil onComplete:^{
            CGRect frame = weakSelf.slidingViewController.topViewController.view.frame;
            weakSelf.slidingViewController.topViewController = newTopViewController;
            weakSelf.slidingViewController.topViewController.view.frame = frame;
            [weakSelf.slidingViewController resetTopViewWithAnimations:nil onComplete:^{
                NSIndexPath* displayNameRow = [NSIndexPath indexPathForRow:0 inSection:0];
                NSIndexPath* gamesRow = [NSIndexPath indexPathForRow:0 inSection:1];
                NSIndexPath* settingsRow = [NSIndexPath indexPathForRow:3 inSection:1];
                NSArray* rowsToReload = [NSArray arrayWithObjects:displayNameRow, gamesRow, settingsRow, nil];
                [weakSelf.tableView reloadRowsAtIndexPaths:rowsToReload withRowAnimation:UITableViewRowAnimationNone];
            }];
        }];

Issue/Question
So I have a strange issue here, were if I click on a different cell it works the arrow is shown on the other cell. Then again this works for 2 more times, then the third times it randomly decides to show the uiimageview on another cell.
Even if I step through the cell creation process I see for that specific cell (the incorrectly displayed one) the boolean for currentDisplayed is set to NO, so it doesn't change the arrowSelectedView to not hidden yet it does somehow? I log out the subviews and can see that it is randomly not Hidden anymore even though for that specific cell it is not set to not hidden, so I am thinking this is implemented incorrectly somehow?

A: The main issue here is that in -tableView:cellForRowAtIndexPath: you're creating a new image view every time you create a new cell, then storing it into a single ivar. The call to set or hide the image view later in that method is not guaranteed (indeed is actually quite unlikely) to be addressing the same image view that was added into that particular cell's content view.
A more convenient place to store it would be in a subclass of UITableViewCell's view like so:
@interface CustomTableViewCell : UITableViewCell

@property (strong, readwrite) UIImageView *imageAccessory;

@end

@implementation CustomTableViewCell

@end

@implementation YourClass

- (id)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  static NSString *CellIdentifier = @"MainMenuCell";

  CustomTableViewCell *cell = (CustomTableViewCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
  if (nil == cell) {
    cell = [[CustomTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];

    UIView *topSplitterBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, cell.bounds.size.width, 1)];
    topSplitterBar.backgroundColor = [UIColor colorWithRed:62.0/255.0 green:69.0/255.0 blue:85.0/255.0 alpha:1];
    [cell.contentView addSubview:topSplitterBar];

    UIImage *arrowImage = [UIImage imageNamed:@"selectedArrow"];
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(240, 10, arrowImage.size.width, arrowImage.size.height)];
    imageView.image = arrowImage;
    cell.accessoryImage = imageView;
    [cell.contentView addSubview: cell.accessoryImage];
    cell.accessoryView.hidden = YES;
  }

  if (currentDisplayed) {
      // This is for the current item that is being displayed
      cell.contentView.backgroundColor = [UIColor colorWithRed:50.0/255.0 green:56.0/255.0 blue:73.0/255.0 alpha:1];
      cell.accessoryImage.hidden = NO;
  } else {
      cell.contentView.backgroundColor = [UIColor colorWithRed:75.0/255.0 green:83.0/255.0 blue:102.0/255.0 alpha:1.0];
      cell.accessoryImage.hidden = YES;
  }

  return cell;
}

@end


text:
Q: dnsproxy.py socket.error: [Errno 98] Address already in use I would like to modify the hosts file in my pc so to redirect all subdomains of mydomain.com using wildchar *,
to do this I would use this script phyton dnsproxy.py
I modified the /etc/hosts file by adding lines
85.217.170.9 mydomain.com
85.217.170.9 * .mydomain.com
I try to run the script but I get an error message
$ sudo python dnsproxy.py -s 8.8.8.8
socket.error: [Errno 98] Address already in use
which address in the message ??? how can I solve and run the script ???
(linux ubuntu16.04x64)


text:
Q: Getting rid of an extra list in a list comprehension with nested loops I have a pretty inelegant nested loop to clean up data from a csv - is there a better/more pythonic way to accomplish the below?
data = [[map(int, i.split(',')) for i in (item.strip()
                                for item in line.rstrip('\n').split('\t'))][0]
                                for line in open('input1.csv')]

output: [[8, -11, 1], [7, 7, -1], [12, -20, 1], [14, -3, -1], [12, 8, -1], [1, -12, 1], [15, 5, -1], [7, -10, 1], [10, 4, -1], [6, 2, 1], [8, 12, -1], [2, 20, -1], [1, -12, 1], [9, 8, -1], [3, 3, 1], [5, 6, 1], [1, 11, 1]]

In particular, in the second for loop I call index 0 of the list created by the last for loop (not sure that's the right terminology?).  Originally I had the below code, but this was generating a doubly nested list.  I stuck in the [0] to flatten the double nesting, but this seems like a pretty bad solution.
[[map(int, i.split(',')) for i in (item.strip()
                         for item in line.rstrip('\n').split('\t'))]
                         for line in open('input1.csv')]

output: [[[8, -11, 1]], [[7, 7, -1]], [[12, -20, 1]], [[14, -3, -1]], [[12, 8, -1]], [[1, -12, 1]], [[15, 5, -1]], [[7, -10, 1]], [[10, 4, -1]], [[6, 2, 1]], [[8, 12, -1]], [[2, 20, -1]], [[1, -12, 1]], [[9, 8, -1]], [[3, 3, 1]], [[5, 6, 1]], [[1, 11, 1]]]

Input data from csv below:
8,-11,1
7,7,-1
12,-20,1
14,-3,-1
12,8,-1
1,-12,1
15,5,-1
7,-10,1
10,4,-1
6,2,1
8,12,-1
2,20,-1
1,-12,1
9,8,-1
3,3,1
5,6,1
1,11,1

A: you can use numpy squeeze to remove extra dimension on array or list
import numpy as np
np.squeeze([[map(int, i.split(',')) for i in (item.strip()
                         for item in line.rstrip('\n').split('\t'))]
                         for line in open('input1.csv')]).tolist()

A: As wim mentioned in his comment, this is not something you need to solve yourself!  I wrote your csv to a file called eg.csv, and ...
>>> import csv
>>> list(csv.reader(open('eg.csv')))
[['8', '-11', '1'], ['7', '7', '-1'], ['12', '-20', '1'], ['14', '-3', '-1'], ['12', '8', '-1'], ['1', '-12', '1'], ['15', '5', '-1'], ['7', '-10', '1'], ['10', '4', '-1'], ['6', '2', '1'], ['8', '12', '-1'], ['2', '20', '-1'], ['1', '-12', '1'], ['9', '8', '-1'], ['3', '3', '1'], ['5', '6', '1'], ['1', '11', '1']]

if you wanted them to be integers, you can do something like:
>>> [[int(col) for col in row] for row in csv.reader(open('eg.csv'))]
# or
>>> map(lambda x: map(int, x), csv.reader(open('eg.csv')))
# or
>>> [map(int, row) for row in csv.reader(open('eg.csv'))]
# to get
[[8, -11, 1], [7, 7, -1], [12, -20, 1], [14, -3, -1], [12, 8, -1], [1, -12, 1], [15, 5, -1], [7, -10, 1], [10, 4, -1], [6, 2, 1], [8, 12, -1], [2, 20, -1], [1, -12, 1], [9, 8, -1], [3, 3, 1], [5, 6, 1], [1, 11, 1]]

Unfortunately the builtin csv module does not attempt to deal with any type conversions.


text:
Q: Perl passing 3D hash indexes as strings I am performing JSON parsing and the final hash which I get of all the JSON file .. the function being called is passing index entries which I need to print. If I try to put the variable as it is .. it dies with the error.
The commented out line is what I am trying to get ... The reason for using this function is to pass different values and get any kind of combination i need.
&Function('{value}{Agent}{macName}')

sub Function(){
    my $key = $_[0];
    my $URL = "www.xyz.com";
    my $json = get( $URL );
    my $decoded_json = decode_json( $json );

    for ( @{$decoded_json->{value}} ) {
       #print $_->{value}{Agent}{macName}."\n";
       print $_->$key."\n";

    }
}

Can't call method "{value}{Agent}{macName}" on unblessed reference at Json_Decoder.pl line 34.

How can I access this entry? print $_->{value}{Agent}{macName} ... by using '{value}{Agent}{macName}' argument of this function.

A: Use Data::Diver, it makes it possible to specify a "path" of hash keys as a list:
#!/usr/bin/perl
use warnings;
use strict;

use Data::Diver qw{ Dive };

sub Function {
    my $key = shift;
    my $decoded_json = { value => { Agent => { macName => 'name' } } };
    my @path = split /\}\{/, $key;
    $path[-1] =~ s/\}$//;
    $path[0]  =~ s/^\{//;

    print Dive($decoded_json, @path), "\n";
}

Function('{value}{Agent}{macName}');

Also notice that you don't need the & to call the function, and that the empty prototype () is wrong in your code (but ignored as the function is called "before" it's declared). See perlsub for details.


text:
Q: Delete dictionary from a list in class attribute I have a list saved as a class attribute and I am trying to delete a specific dictionary in that list.
The project is a simple one, one where the user should be able to add items to a collection (saved in a list), edit them, filter search results by types (previously added to list) and delete dictionary entries from list.
Here is the constructor:
class Item:
    py_collection_list = []

    def __init__(self, item_name: str, item_type: str, date_add, dom, item_info: str):
        self.__id = Item.get_next_id()
        self.item_name: str = item_name
        self.item_type: str = item_type
        self.date_add = date_add
        self.dom = dom
        self.item_info: str = item_info
        Item.py_collection_list.append(self)

(Item being the super class and py_collection_list being the list)
I was able to create a filter with the following code:
def show_items():
    print('View items by type \nComputer | Camera | Phone | Video Player ')
    type_selection = input('Type> ')
    print("{0:3}\t{1:20}\t{2:10}\t{3:10}".format("ID", "Item", "Date added", "Date manufactured"))
    for i in Item.py_collection_list:
        if type_selection == i.item_type:
            print("{0:03d}\t{1:20}\t{2:10}\t{3:10}".format(i.get_id(), i.item_name, i.date_add, i.dom))

I used several options for the deletion and this is the latest one which isn't working:
def delete_item():
    print("{0:3}\t{1:20}\t{2:10}\t{3:10}".format("ID", "Item", "Date added", "Date manufactured"))
    for i in Item.py_collection_list:
        print("{0:03d}\t{1:20}\t{2:10}\t{3:10}".format(i.get_id(), i.item_name, i.date_add, i.dom))
    remove_item = input("Type name of the item you would like to delete from collection> ")
    if remove_item == i.item_name:
        del [remove_item]

A: In your delete_item method, you only check equality for the last element in your list.
Your for loop works by going through your list and assigning each value to i. After your list is exhausted and you've exited it, i still contains the last value it was assigned. That is the only element you check for equality with remove_item.
The easiest way to check for equality for all items and filter the ones that don't match would be a list comprehension.
def delete_item():
    print("{0:3}\t{1:20}\t{2:10}\t{3:10}".format("ID",
                                                 "Item",
                                                 "Date added",
                                                 "Date manufactured"))
    for i in Item.py_collection_list:
        print("{0:03d}\t{1:20}\t{2:10}\t{3:10}".format(i.get_id(),
                                                       i.item_name,
                                                       i.date_add,
                                                       i.dom))
    remove_item = input("Type name of the item you would like to delete from collection>")
    Item.py_collection_list = [i for i in Item.py_collection_list if i.item_name != remove_item]

This allows you to filter multiple entries in one shot and isn't committing an atrocity like mutating your list as you iterate.


text:
Q: Google Script to open docs into new tabs //The following google script does not create the result of opening multiple google docs, Session2,Session3,Session4,Session5 into new window tabs. No error appears...
function openDocs() {
  var docs = [];

  for (var i = 2; i <= 5; i++) {
    var docName = "Session" + i;
    var doc = DriveApp.getFilesByName(docName).next();
    if (doc) {
      docs.push(DocumentApp.openById(doc.getId()));
    }
  }

  return docs;
}

//Ran the code and no error was generated but neither were the documents opened into a new window tab.


text:
Q: How to make a cube root calculator in dashcode Can someone post the javascript to cube root in dashcode

A: I don't know what Dashcode is, but assuming it uses standard JavaScript, just turn it into a power calculation (like you learned at school) and use Math.pow:
> Math.pow(27, 1/3)
  9

The nth root of x is x^(1/n).


text:
Q: HTML5 File API read as text and binary I am currently working on the HTML5 File API, and I need to get binary file data.
The FileReader's readAsText, and readAsDataURL methods work fine, but readAsBinaryString returns the same data as readAsText.
I need binary data, but im getting a text string. Am I missing something?

A: 2022 update: See explanation below for why the OP was seeing what they were seeing, but the code there is outdated. In modern environments, you'd use the methods on the Blob interface (which File inherits):

*

*arrayBuffer for reading binary data (which you can then access via any of the typed arrays)

*text to read textual data

*stream for getting a ReadableStream for handling data via streaming (which allows you to do multiple transformations on the data without making multiple passes through it and/or use the data without having to keep all of it in memory

Once you have the file from the file input (const file = fileInput.files[0] or similar), it's literally just a matter of:
await file.text(); // To read its text
// or
await file.arrayBuffer(); // To read its contents into an array buffer

(See ReadableStream for an example of streams.)
You might access the array buffer via a Uint8Array (new Uint8Array(buffer)).
Here's an example of text and arrayBuffer:

const $ = id => document.getElementById(id);

const fileInput = $("fileInput");
const btnRead = $("btnRead");
const rdoText = $("rdoText");
const contentsDiv = $("contents");

const updateButton = () => {
    btnRead.disabled = fileInput.files.length === 0;
};

const readTextFile = async (file) => {
    const text = await file.text();
    contentsDiv.textContent = text;
    contentsDiv.classList.add("text");
    contentsDiv.classList.remove("binary");
    console.log("Done reading text file");
};

const readBinaryFile = async (file) => {
    // Read into an array buffer, create
    const buffer = await file.arrayBuffer();
    // Get a byte array for that buffer
    const bytes = new Uint8Array(buffer);
    // Show it as hex text
    const lines = [];
    let line = [];
    bytes.forEach((byte, index) => {
        const hex = byte.toString(16).padStart(2, "0");
        line.push(hex);
        if (index % 16 === 15) {
            lines.push(line.join(" "));
            line = [];
        }
    });
    contentsDiv.textContent = lines.join("\n");
    contentsDiv.classList.add("binary");
    contentsDiv.classList.remove("text");
    console.log(`Done reading binary file (length: ${bytes.length})`);
};

updateButton();

fileInput.addEventListener("input", updateButton);

btnRead.addEventListener("click", () => {
    const file = fileInput.files[0];
    if (!file) {
        return;
    }
    const readFile = rdoText.checked ? readTextFile : readBinaryFile;
    readFile(fileInput.files[0])
    .catch(error => {
        console.error(`Error reading file:`, error);
    });
});
body {
    font-family: sans-serif;
}
#contents {
    font-family: monospace;
    white-space: pre;
}
<form>

            File:
            <input type="file" id="fileInput">

            <input id="rdoText" type="radio" name="format" value="text" checked>
            Text

            <input id="rdoBinary" type="radio" name="format" value="binary">
            Binary

        <input id="btnRead" type="button" value="Read File">

</form>

Note in 2018: readAsBinaryString is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer (or in some cases, readAsDataURL) instead.

readAsBinaryString says that the data must be represented as a binary string, where:

...every byte is represented by an integer in the range [0..255].

JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)
If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).
If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText and readAsBinaryString, but with readAsBinaryString you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText, because readAsText will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.
You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:
<!DOCTYPE HTML>

<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>

<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>

If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:
Text (13):

54 65 73 74 69 6e 67 20 31 20 32 20 33

Binary (28):

ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00
As you can see, readAsText interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).

* XMLHttpRequest.response with responseType = "arraybuffer" is supported in HTML 5.
** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.


text:
Q: Cancel button for database Query/progress bar in Shiny app? I don't have a minimal, reproducible example because I am not sure if this is even possible.
Is there a cancel button option that can be set to stop all functions running that are related to the progress bar when using the progress bar in a shiny app?
I have looked online but can not seem to find anything that answers my question. I hope this isn't to vague of a question and I hope someone can help me find the solution I am looking for. Thank you in advance!


text:
Q: Why heapsort time complexity is given in Big-Oh(N log N) in CLRS algorithm book and not in Theta? Why in CLRS book time complexity of heapsort is specifically given as   Ο(N log N) while all other algorithms are in Θ notation?
I am feeling like I am missing something from the intuition.

Here is image of the compexities given in book.


text:
Q: MQ connection refused i have issues connecting my spring boot app to mq on icp so how can i define the ibm.mq.connName=mymq-ibm-mq(30803) because i always get this execption :
Caused by: com.ibm.mq.jmqi.JmqiException: CC=2;RC=2538;AMQ9204: Connection to host '10.0.0.1(1414)' rejected. [1=com.ibm.mq.jmqi.JmqiException[CC=2;RC=2538;AMQ9213: A communications error for 'TCP' occurred. [1=java.net.ConnectException[Connection refused (Connection refused)],3=connnectUsingLocalAddress,4=TCP,5=Socket.connect]],3=10.0.0.1(1414),5=RemoteTCPConnection.connnectUsingLocalAddress]

how can i get the correct host and the port ?
this is my application.properties :
ibm.mq.queueManager=QM1
ibm.mq.channel=DEV.ADMIN.SVRCONN
ibm.mq.connName=mymq-ibm-mq(30803)
ibm.mq.user=admin
ibm.mq.password=passw0rd

this is the output of kubectl describe service
Name: mymq-ibm-mq
Namespace: lab
Labels: app=ibm-mq
chart=ibm-mqadvanced-server-dev
heritage=Tiller
release=mymq
Annotations:
Selector: app=ibm-mq,release=mymq
Type: NodePort
IP: 10.1.0.24
Port: console-https 9443/TCP
TargetPort: 9443/TCP
NodePort: console-https 32575/TCP
Endpoints: 10.2.9.53:9443
Port: qmgr 1414/TCP
TargetPort: 1414/TCP
NodePort: qmgr 30803/TCP
Endpoints: 10.2.9.53:1414
Session Affinity: None
External Traffic Policy: Cluster

A: I'm pretty sure the MQ Connection port should be 1414 and not 30803. Try this:
ibm.mq.connName=mymq-ibm-mq(1414)


text:
Q: Variables available in all controllers? Where and how to set variable value that is available in all controllers. I don't wont to use zend registry and don't want to extend Zend_Controller_Action. Is there is another way? I just want for example to set:
$a = "test";
and in Index controller to dump it:

class IndexController extends Zend_Controller_Action {

    public function indexAction(){

            var_dump($a);
        }
}

A: Global vars ruin the purpose of object oriented programming... use namespace or custom configs.
Solution 1
Use session Zend_Session_Namespace, here is documentation on how to Zend_Session_Namespace.

*

*Set set the value in namespace in bootstrap or something (wherever you see fit)

*Retrieve the value from namespace in you controller/model/other

Solution 2
Alternatively, you can create some new class with static properties and use it's setters/getters to set and retrieve values.
E.g.
class SomeClass
{
    static $hello = 'world';
}

class IndexController extends Zend_Controller_Action
{
    public function indexAction()
    {
        var_dump(SomeClass::$hello);
    }
}

A: You can add variables to the request object:
$this->getRequest()->setParam('a', 'hello');

Then retrieve it using:
$this->getRequest()->getParam('a);

But that is not the best way of doing it as you might accidentally overwrite a parameter a needed parameter.


text:
Q: How to find the shared properties of any two elements in a CSV file I have the following csv file:
A,rule1
B,rule1
C,rule2
A,rule2
B,rule2
D,rule1
B,rule3

Now I want to find out how many 2nd column values are shared by A, B (and A, C and A, D. But A, B as an explanation is enough to implement the rest). What I did was:
file1 = open('file.csv', 'rU')
fileR = csv.reader(file1, delimiter=',')

counter = 0

for i in range(0, 5): #list that contains A, B, C. i.e list = [A, B, C, D, E, F]
 for j in range(0, 5):
  for k in range(0, 8): # rule list rlist = [rule1, rule2, ...]
   for rows in fileR:
    if rows[0] == list[i] and rows[1] == rlist[k]:
     if rows[0] == list[j] and rows[1] == rlist[k]:
       counter += 1

print counter

Here counter represents the total rules shared by A, B (and A, C and so on). But I am not getting the right answer. So, the answer should be A and B = 2, because A and B have both rule1 and rule2. Am I doing it right?

A: Simply
1, convert second field values into sets (using set comprehension)
2, use the intersection method of set to get the ones that are shared between.
3, and get the len of the resulting set.
file1 = open('file.csv', 'rU')
fileR = csv.reader(file1, delimiter=',')
L=list(fileR)
print set(item[1] for item in L if item[0]=='A').intersection([item[1] for item in L if item[0]=='B'])
print len(set(item[1] for item in L if item[0]=='A').intersection([item[1] for item in L if item[0]=='B']))

#set(['rule2', 'rule1'])
#2


text:
Q: CXF RequestContextFilter http://cxf.apache.org/docs/30-migration-guide.html

CXF RequestHandler and ResponseHandler filters have been removed,
  please use JAX-RS 2.0 ContainerRequestFilter and
  ContainerResponseFilter and also WriterInterceptor and
  ReaderInterceptor when needed.

How to rewrite it? I cant find any examples taking org.apache.cxf.message.Message as a parameter and returning Response.
Also I should use the ContainerResponseFilter
public void filter(ContainerRequestContext containerRequestContext, ContainerResponseContext containerResponseContext) throws IOException {

instead of RequestHandler
Response handleRequest(Message m, ClassResourceInfo resourceClass)

A: Replace RequestHandler
public class CustomRequestHandler implements RequestHandler {
    public Response handleRequest(Message m, ClassResourceInfo resourceClass) {

with ContainerRequestFilter
public class CustomRequestFilter implements ContainerRequestFilter {
    public void filter(ContainerRequestContext context) {
        Message m = JAXRSUtils.getCurrentMessage();
        OperationResourceInfo m = message.getExchange().get(OperationResourceInfo.class);
        ClassResourceInfo resourceClass = operation.getClassResourceInfo();
        // finally use context.abortWith(Response) if you need to block the request

Replace ResponseHandler
public class CustomResponseHandler implements ResponseHandler {
    public Response handleResponse(Message m, OperationResourceInfo operation, Response response) {

with ContainerResponseFilter
public class CustomResponseFilter implements ContainerResponseFilter  {
    public void filter(ContainerRequestContext inContext, ContainerResponseContext outContext) throws IOException{
        Message m = JAXRSUtils.getCurrentMessage();
        OperationResourceInfo operation = m.getExchange().get(OperationResourceInfo.class);
        //outContext has the capabilites of javax.ws.rs.Response. For example outContext.setStatus(201);

Spring
<bean id="customRequestFilter" class="com.CustomRequestFilter" />
<bean id="customResponseFilter" class="com.CustomResponseFilter" />

<!-- Add filters to provider zone in JAX-RS server-->
<bean id="myRestServer" class="org.apache.cxf.jaxrs.JAXRSServerFactoryBean" lazy-init="false" init-method="create">
    ...
    <property name="providers">
        <list>
            <ref bean="customRequestFilter" />
            <ref bean="customResponseFilter" />
        </list>
    </property>


text:
Q: Is wordpress truly capable of anything other than blogging? I'm looking at making a pretty intensive social network on Wordpress, and I do see some great plugins that seem well implemented. I've been working with Wordpress for years and would make a good bit of custom areas, etc, but I'd like to not start from scratch. Is Wordpress truly capable of this while still being able to scale, or am I completely off base here?

A: WordPress is capable of everything, true but some features will need to be developed from scratch. But still, with WordPress you can save tons of hours of coding
Also, this is an on going project that runs for few good years so be sure you are getting a great DB structure, fast and secured system, friendly interface and much more

A: If you're looking to add social features, start with BuddyPress as a base. You still have to add a good deal of code to get what you want, but this gives you a solid foundation to get it up and started.

A: The plugin capability is there and everything else can be built on the LAMP stack. Your main concern here is probably going to be building to scale if you expect to receive ample traffic. I'm working on a related project that is being built within AWS, so scaling can be accomplished when needed with minimal effort.
Build / plan a solid infrastructure and you'll be fine.
Let me know if you have any questions, I'm happy to help.

A: WordPress can run any type of website.  Here are some good stats about WordPress.
https://managewp.com/14-surprising-statistics-about-wordpress-usage


text:
Q: Remote force logout in passport.js I want to make a "remote logout" feature in our website.
Some services provide this feature, like google..
https://support.google.com/mail/answer/8154
I use passport.js in node.js, so I want to find how can I make this feature but cannot find how to do it.
I want to destroy session by user's id.
We need to sign out all session of that user's, because people sign in by using many browsers and devices.

A: I added a similar feature to this to my website.
I couldn't find a way to do it using PassportJS, but what I did was add and extra Boolean field to my users schema (mongoDB) called FORCE_LOGOUT.
I changed the value of FORCE_LOGOUT to true via a POST request from my front end.
Then in my main app.js script I checked to see if the user had that field as true and then forced them to logout if it was before allowing them to continue.
I use expressJs so it looked something like this:
app.use((req, res, next) => {
    if (req.user && req.user.FORCE_LOGOUT){
        req.user.FORCE_LOGOUT = false;
        req.user.save(err => {
            if(err) console.error(err);
            req.logout();
            return next();
        })
    } else {
        return next();
    }
});

There is probably a much better way to achieve this, but this is how I worked around it, so hopefully it will help to guide somebody else.


text:
Q: customization of edit text and input type in android I had customized edit text with floating label and  i write a method to set input type which is working but for last edit text its showing number keyboard instead of normal keyboard take alook at my code
 private void setFloatInputType(int inputType) {

    if(inputType==16) {
        input.setFocusable(false);
        input.setOnFocusChangeListener(null);
        input.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                setDatePicker();
            }
        });
    }
        else
    if(inputType==0) {

       input.setRawInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_NORMAL);
       // input.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_NORMAL);
        Log.d("INput TYp3", "" + input.getInputType());
    }
    else
        input.setInputType(inputType);

I had debug the code it showsthat for third text field input type is set to

normal keyboard but os is popup numberic keyboard.
any suggestion will be highly appreciated.
Thanks,

A: Try replacing
input.setRawInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_NORMAL);

with
input.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_NORMAL);


text:
Q: How to convert firebase map objects to a local list in flutter I am trying to cache a firebase document filed to a local List. But I don't know how to do that.
Here is firebase document field I want to cache

This is the list I want:
List theListIwant = [
      {'aed': true},
      {'bet': false},
      {'med': true},
      {'zed': true},
    ];

DocumentSnapshot:
FirebaseFirestore.instance.collection('stores').doc(storeData.user.uid).snapshots()

I am stuck here:
List medicineList = (snapshot.data!
                            .get('meds') as Map)
                            .entries
                            .map((e) => null)

A: First create a map from Firebase
and then
map convert to list

A: your DocumentSnapshot
FirebaseFirestore.instance.collection('stores').doc(storeData.user.uid).collection('meds').snapshots()

Map dataa
snapshot.data!.docs.map((DocumentSnapshot document) {
                    Map<String, dynamic> data =
                        document.data()! as Map<String, dynamic>;
                    List theListIwant = [
                       {'aed': data["aed"]},
                       {'bet': data["bet"]},
                       {'med': data["med"]},
                       {'zed': data["zed"]},
                    ];
                  }


text:
Q: mule asynchronous tls/ssl inbound endpoint I'm working on a project where one of the requirements is to connect to a server using ssl/tls and subscribe to messages. I have setup a tls outbound-endpoint and can connect to the server. I have a spring bean that performs custom handshaking and part of that is subscribing to content from the server. Once subscribed I should receive messages asynchronously without having to poll for them. Is there a way to do this in Mule 3.3? Thanks for the help.

A: It seems you have a specific use case in which you can't use HTTPS. Mule does provide support for TCP connection, but I couldn't find the option to make the the secure TCP connection (which I beleive will be over SSL).
You can always write your custom endpoint connector code in a java component and call that java component using Quartz (for polling)
<flow name="polling-flow" doc:name="polling-flow">
    <quartz:inbound-endpoint jobName="polling"
        repeatInterval="5000" responseTimeout="10000" doc:name="Quartz">
        <quartz:event-generator-job>
            <quartz:payload>call-custom-component-to-poll-secure-tcp</quartz:payload>
        </quartz:event-generator-job>
    </quartz:inbound-endpoint>
    <component doc:name="Java" class="com.company.CustomSecureTCPCode"></component>
    <!-- do whatever you want to with the payload received from calling the endpoint -->
</flow>

A: I used a quartz inbound endpoint and setup an endpoint polling job and polled my endpoint. See the config below:
<flow name="QuartzPollingFlow">
    <quartz:inbound-endpoint repeatCount="-1" repeatInterval="1000" jobName="myPoller">
        <quartz:endpoint-polling-job>
            <quartz:job-endpoint timeout="300" ref="SecureTcpEndpoint"/>
        </quartz:endpoint-polling-job>
        </quartz:inbound-endpoint>
    <flow-ref name="ProcessingFlow"/>
</flow>


text:
Q: Merge multiple objects under a single object and add sibling object in one command So I have three files:
cats.json
{
  "cats": [
    {
      "name": "fluffles",
      "age": 10,
      "color": "white"
    }
  ]
}

dogs.json
{
  "dogs": [
    {
      "name": "sam",
      "age": 5,
      "color": "black and white"
    },
    {
      "name": "rover",
      "age": 2,
      "color": "brown and white"
    }
  ]
}

snakes.json
{
  "snakes": [
    {
      "name": "noodles",
      "age": 10,
      "color": "green"
    }
  ]
}

I wanted to merge these together, under an "animals" object. I've found that will merge the files:
jq -s '{"animals": .} ' cats.json dogs.json snakes.json > animals.json

{
  "animals": [
    {
      "cats": [
        {
          "name": "fluffles",
          "age": 10,
          "color": "white"
        }
      ]
    },
    {
      "dogs": [
        {
          "name": "sam",
          "age": 5,
          "color": "black and white"
        },
        {
          "name": "rover",
          "age": 2,
          "color": "brown and white"
        }
      ]
    },
    {
      "snakes": [
        {
          "name": "noodles",
          "age": 10,
          "color": "green"
        }
      ]
    }
  ]
}

Now I have an additional object:
owners.json
{
  "owners": [
    "peter",
    "william",
    "sally"
  ]
}

which I want to merge into the same file using
jq -s '.[0] + .[1]' animals.json owners.json

Can I do both of these operations with just one jq command?
jq -s '{"animals": .} ' cats.json dogs.json snakes.json > animals.json
jq -s '.[0] + .[1]' animals.json owners.json

The result would look like this:
{
  "animals": [
    {
      "cats": [
        {
          "name": "fluffles",
          "age": 10,
          "color": "white"
        }
      ]
    },
    {
      "dogs": [
        {
          "name": "sam",
          "age": 5,
          "color": "black and white"
        },
        {
          "name": "rover",
          "age": 2,
          "color": "brown and white"
        }
      ]
    },
    {
      "snakes": [
        {
          "name": "noodles",
          "age": 10,
          "color": "green"
        }
      ]
    }
  ],
  "owners": [
    "peter",
    "william",
    "sally"
  ]
}

A: Not sure if this is the way-to-go, but it gets the desired output by:

*

*Using --slurp:

*Catching the first 3 files as a single array variable
[ .[0] * .[1] * .[2] ] as $all

*Catching owners object as a single variable
.[3].owners as $owners

*Creating the object as desired
{ "animals": $all, "owners": $owners }
jq \
    --slurp \
    '[ .[0] * .[1] * .[2] ] as $all | .[3].owners as $owners | { "animals": $all, "owners": $owners }' cats.json dogs.json snakes.json owners.json

Will produce:
{
  "animals": [
    {
      "cats": [
        {
          "name": "fluffles",
          "age": 10,
          "color": "white"
        }
      ],
      "dogs": [
        {
          "name": "sam",
          "age": 5,
          "color": "black and white"
        },
        {
          "name": "rover",
          "age": 2,
          "color": "brown and white"
        }
      ],
      "snakes": [
        {
          "name": "noodles",
          "age": 10,
          "color": "green"
        }
      ]
    }
  ],
  "owners": [
    "peter",
    "william",
    "sally"
  ]
}

A: Suppose you had an (a priori) indeterminate or large numbers of types of animals, and just one owners file.  In such cases, it would be better (to save memory) not to use the -s option, and it would be easier to invoke jq with the owners file as the first data file, e.g. along the lines of:
jq -n -f program.jq owners.json $(ls *.json | grep -v owners.json)

where program.jq contains a program such as:
input as $owners | {$owners, animals: [inputs]}

(Notice how {"owners": $owners} can be abbreviated.)


text:
Q: session expiring and giving error page My application is throwing an error when the session expires.
I dont want the sessions to expire automatically....
but if there is no way to do that then instead of showing the error it should be redirected to the login page...
I tried to do this....
Response.AppendHeader("Refresh", Convert.ToString((Session.Timeout * 60) + 10) + "; URL=Login.aspx");

this code not working when session expires.. i get an error message

Response is not available in this context.

the web config has this
<authentication mode="Forms">
        <forms loginUrl="Login.aspx" name="Cookie" timeout="10080" path="/">
        </forms>
    </authentication>
    <authorization>
        <deny users="?"/>
        <allow users="*"/>
    </authorization>

Is there anything else i need to add in the web config...
any suggestions... thanks
this is my page load
 protected void Page_Load(object sender, EventArgs e)
    {
        Response.AppendHeader("Refresh", Convert.ToString((Session.Timeout * 60) + 10) + "; URL=Login.aspx");
        string userName = Session["userName"].ToString();
        string password = Session["password"].ToString();
        string domain = Session["domain"].ToString();

        impersonateValidUser(userName, domain, password);

    }

A: I'm not sure where your problem lies, but as an alternative consider using a javascript solution client side to prompt the user to renew their session prior to expiration.  If the user fails to affirmatively agree to session renewal, then redirect to the Logout page to terminate the session without simply letting it expire.  Typically your Logout page will redirect back to the Login page so the user, when they return to their computer, will be prompted to Login.  If the user does click the OK (I want to renew my session) button in your renewal dialog, then use a request to a Keepalive page, as @Come suggests, though I would do it with AJAX instead of an iframe.
You can look at some sample code that does this in an ASP.NET MVC context on my blog.

A: I have solved this in my master page's Page_Load.
Each time the Page_Load fires it checks to see that a specific Session value exists (which should be there if a user is signed in properly).  If not I redirect to the sign in page.
Eg:
// Assuming your using master pages (if not you could have this in a base page that all
// your pages inherit from.
protected void Page_Load(object sender, EventArgs e)
{
    if (Session["SomeKey"] == null)
    {
        // Session has expired or person has not signed in so redirect.
        FormsAuthentication.SignOut();
        Session.Abandon();
        Response.Redirect("signin.aspx", true);
    }

    // If all is good continue and do whatever you normally do.
}

In your example the session variables might not exist due to the session expiring so your getting null back from all your fetched session keys.  You should be validating that they are not null and if so reacting appropriately to the values being null.

A: What you could do is to add a invisible iframe to your page:

And keepalive.aspx contains the following:
<%@ Page Language="C#" Inherits="Keepalive" EnableSessionState="True"%>
<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" >

   <META http-equiv="refresh" content="60"/>

Every 60 seconds keepalive.aspx refreshes itself causing the session to stay alive.
You can set the timeout of the session to for instance 2 minutes. This way the session will be cleaned up very soon after the user has left your page.

A: It's a bad idea to have pernament sessions on you site but you can acomplish this by giving large values for session time out in web.config
<sessionState  timeout="6000"/>


text:
Q: Pipe is blocked by sub-process in Perl I have written two perl scripts (parent.pl and child.pl), and their source codes are as follows:
parent.pl:
# file parent.pl

$SIG{CHLD} = sub {
    while(waitpid(-1, WNOHANG) > 0) {
        print "child process exit\n";
    }
};

my $pid = fork();
if($pid == 0) {
    system("perl child.pl");
    exit;
}
while(1) {
    open my $fh, "date |";
    while(<$fh>) {
        print "parent: ".$_;
    }
    close $fh;
    sleep(2);
}

child.pl
#file child.pl

while(1) {
   open my $fh, "date |";
   while(<$fh>) {
       print "  child: ".$_;
    }
   close $fh;
   sleep(2);
}

What I want is the parent process and the forked sub-process output the current date alternately. But when I run perl parent.pl, the output is like this:
$ perl parent.pl
parent: Mon Jan 21 14:53:36 CST 2013
  child: Mon Jan 21 14:53:36 CST 2013
  child: Mon Jan 21 14:53:38 CST 2013
  child: Mon Jan 21 14:53:40 CST 2013
  child: Mon Jan 21 14:53:42 CST 2013
  child: Mon Jan 21 14:53:44 CST 2013

It seems that the parent process was blocked when opening pipe.
But if I remove the following operation for signal CHLD.
$SIG{CHLD} = sub {
        while(waitpid(-1, WNOHANG) > 0) {
            print "child process exit\n";
        }
};

And run it again. It seems OK.
$ perl parent.pl
parent: Mon Jan 21 14:57:57 CST 2013
  child: Mon Jan 21 14:57:57 CST 2013
parent: Mon Jan 21 14:57:59 CST 2013
  child: Mon Jan 21 14:57:59 CST 2013
parent: Mon Jan 21 14:58:01 CST 2013
  child: Mon Jan 21 14:58:01 CST 2013

But I still feel puzzling. Why the parent process was blocked when I tried to open a pipe?
I don't think removing the SIG{CHLD} function is a good idea, becaue zombie processes should be retrieved.
Anyone can help me? Thank you very much!
==================================================================
Thank @Borodin to help me solve my puzzle. And I have tried to modify the parent.pl like this:
my $main_pid = $$;
$SIG{USR1} = sub {
        #sleep(1);
        while(waitpid(-1, WNOHANG) > 0) {
                print "child process exit\n";
        }
};

my $pid = fork();
if($pid == 0) {
    $SIG{USR1} = 'IGNORE';
    system("perl child.pl");
    kill USR1, $main_pid;
    exit;
}
while(1) {
    open my $fh, "date |";
    while(<$fh>) {
        print "parent: ".$_;
    }
    close $fh;
    sleep(2);
}

Since CHLD signal may be kicked off by open or system, I used another customized signal USR1. And it works well now.
========================================================================
The above modification still has problems. The forked sub-process send USR1 singal before exit. May be the parent process should sleep for a while before waitpid, because the sub-process hasn't exit yet.
I don't retrieve sub-process manually now, and set $SIG{$CHLD} = 'IGNORE'. Hope the sub-process can be retrieved by operation system when it exits.

A: This is being made much more complex because both open my $fh, "date |" and system("perl child.pl") are starting child processes, as well as the explicit fork.
So fork starts a child process, which does system("perl child.pl") to start its own child process, which in turn does open my $fh, "date |", which opens yet another child, which is now a great-grandchild of the main parent process.
Meanwhile the main process does its own open my $fh, "date |" which starts another child process. In the end, the main process has two children, a grandchild and a great-grandchild.
Unfortunately the children that are started using open or system have an implcit wait attached to them, so they will kick off the CHLD signal when they complete but when the handler is executed there is nothing left to wait for so it will hang as you have seen.
perldoc perlipc has this to say

Be careful: qx(), system(), and some modules for calling external commands do a fork(), then wait() for the result. Thus, your signal handler will be called. Because wait() was already called by system() or qx(), the wait() in the signal handler will see no more zombies and will therefore block.

You can get things going by keeping to just a single parent and a single child process, like this.
use strict;
use warnings;

use POSIX ':sys_wait_h';

STDOUT->autoflush;

$SIG{CHLD} = sub {
  while(waitpid(-1, WNOHANG) > 0) {
    print "child process exit\n";
  }
};

my $pid = fork();

if ($pid == 0) {
  while(1) {
    printf " child: %s\n", scalar localtime;
    sleep(2);
  }
}
else {
  while(1) {
    printf "parent: %s\n", scalar localtime;
    sleep(2);
  }
}

A: Option 1
One way to do what you want is to synchronize with a pair of half-duplex pipes, created with pipe and open. Using a full-duplex socketpair may simplify the bookkeeping.
Opening a handle on "|-" implicitly forks a child process whose standard input is the read end of a pipe, and the write end is the filehandle returned to the parent. The parent releases the child with this implicit pipe and uses the explicitly created pipe as the back channel.
#! /usr/bin/env perl

use strict;
use warnings;

use Fcntl qw/ F_GETFD F_SETFD FD_CLOEXEC /;
use IO::Handle;

pipe my $fromchild, my $toparent or die "$0: pipe: $!";
$_->autoflush(1) for $toparent, $fromchild;

my $flags = fcntl $toparent, F_GETFD, 0        or die "$0: fcntl: $!";
fcntl $toparent, F_SETFD, $flags & ~FD_CLOEXEC or die "$0: fcntl: $!";

my $pid = open my $tochild, "|-";
$tochild->autoflush(1);
die "$0: fork: $!" unless defined $pid;

if ($pid != 0) {
  while (1) {
    print "parent: ", scalar localtime, "\n";
    sleep 1;
    print $tochild "over\n";

    chomp($_ = <$fromchild>);
    exit 0 if $_ eq "over and out";
  }
}
else {
  exec "child.pl", fileno $toparent
    or die "$0: exec: $!";
}

The code in child.pl is below. Note that the parent passes a file descriptor that the child must dup to communicate with the parent in the other direction.
#! /usr/bin/env perl

use strict;
use warnings;

use IO::Handle;

my($fd) = @ARGV or die "Usage: $0 to-parent-fd\n";
open my $toparent, ">&=", $fd or die "$0: dup: $!";
$toparent->autoflush(1);

my $rounds = 5;
for (1 .. $rounds) {
  my $over = <STDIN>;
  print " child: ", scalar localtime, "\n";
  sleep 1;
  print $toparent ($_ < $rounds ? "over\n" : "over and out\n");
}

exit 0;

In concert, they look like
parent: Mon Jan 21 18:10:39 2013
 child: Mon Jan 21 18:10:40 2013
parent: Mon Jan 21 18:10:41 2013
 child: Mon Jan 21 18:10:42 2013
parent: Mon Jan 21 18:10:43 2013
 child: Mon Jan 21 18:10:44 2013
parent: Mon Jan 21 18:10:45 2013
 child: Mon Jan 21 18:10:46 2013
parent: Mon Jan 21 18:10:47 2013
 child: Mon Jan 21 18:10:48 2013
Option 2
A slightly more exotic arrangement is to have subprocesses arrange to take turns with one another in a ring or cycle. Going back-and-forth between parent and child processes is merely a cycle of length two.
#! /usr/bin/env perl

use strict;
use warnings;

use IPC::SysV qw/ IPC_CREAT IPC_PRIVATE S_IRUSR S_IWUSR /;
use IPC::Semaphore;

my $WORKERS = 3;

A given worker takes its own semaphore from the set but releases the next worker when finished.
sub take {
  my($id,$sem) = @_;
  $sem->op($id, -1, 0) or die "$0: semop: $!";
}

sub release {
  my($id,$sem) = @_;
  my $next = ($id + 1) % $WORKERS;
  $sem->op($next, 1, 0) or die "$0: semop: $!";
}

sub worker {
  my($id,$sem) = @_;

  for (1 .. 3) {
    take $id, $sem;

    print "[worker $id]: ", scalar localtime, "\n";
    sleep 1;

    release $id, $sem;
  }
}

Create the semaphore set and leave the first ready to run.
my $sem = IPC::Semaphore->new(
  IPC_PRIVATE,
  $WORKERS,
  IPC_CREAT | S_IRUSR | S_IWUSR)
    or die "$0: semget: $!";

$sem->setall((0) x $WORKERS);
$sem->setval(0, 1);  # unblock first only

Now we are ready to fork the subprocesses and let them execute.
foreach my $id (0 .. $WORKERS - 1) {
  my $pid = fork;
  die "$0: fork: $!" unless defined $pid;

  if ($pid == 0) {
    worker $id, $sem;
    exit 0;
  }
}

# wait on all workers to finish
my $pid;
do {
  $pid = waitpid -1, 0;
} while $pid > 0;

Sample output:
[worker 0]: Mon Jan 21 18:13:27 2013
[worker 1]: Mon Jan 21 18:13:28 2013
[worker 2]: Mon Jan 21 18:13:29 2013
[worker 0]: Mon Jan 21 18:13:30 2013
[worker 1]: Mon Jan 21 18:13:31 2013
[worker 2]: Mon Jan 21 18:13:32 2013
[worker 0]: Mon Jan 21 18:13:33 2013
[worker 1]: Mon Jan 21 18:13:34 2013
[worker 2]: Mon Jan 21 18:13:35 2013


text:
Q: Is a drawing drawn by a user considered user-generated content? I'm working on an app which lets the user draw drawings and share to their facebook feed, and I'm wondering whether uploading the image to the staging-resources and using it is allowed? Because the website states that only camera-created photos are considered user-generated content, although this is drawn by the user, and is not considered app-generated.
Also, if it is possible to use that, can I somehow use it for feed posting instead of object/action posting?
I've used these links as references:
Using the Object API,
Publish to Feed
Thanks in advance for any help,
Tamper


text:
Q: Difference between let tableView = UITableView() and let tableView: UITableView! these two statements I am new in iOS Development, what is major difference in these two statements and what logic is behind them. when which statement we should use...

A: let tableView = UITableView()

You are creating an instance of UITableView and assigning it to the constants named tableView.
let tableView: UITableView!

You are telling the compiler that tableView constant will contain an instance of UITableView in the future and with ! you are making sure that this constant will have a value before accessing it. But as you have declared it as a constant so you cannot assign/change the value to it. Use var to make it variable (assuming you know the difference between let and var).
For better understanding go through the Swift Basics.


text:
Q: PHP DOMDocument adds extra tags I'm trying to parse a document and get all the image tags and change the source for something different.
$domDocument = new DOMDocument();

$domDocument->loadHTML($text);

$imageNodeList = $domDocument->getElementsByTagName('img');

foreach ($imageNodeList as $Image) {
  $Image->setAttribute('src', 'lalala');
  $domDocument->saveHTML($Image);
}

$text = $domDocument->saveHTML();

The $text initially looks like this:

Hi, this is a test, here is an image Because I like Beer!

and this is the output $text:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

Hi, this is a test, here is an image Because I like Beer!

I'm getting a bunch of extra tags (HTML, body, and the comment at the top) that I don't really need. Any way to set up the DOMDocument to avoid adding these extra tags?

A: DomDocument is unfortunately retarded and won't let you do this. Try this:
$text = preg_replace('/^<!DOCTYPE.+?>/', '', str_replace( array('', '', '', ''), array('', '', '', ''), $domDocument->saveHTML()));

A: You just need to add 2 flags to the loadHTML() method: LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD. I.e.
$domDocument->loadHTML($text, LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD);

See IDEONE demo:
$text = '
Hi, this is a test, here is an image Because I like Beer!
';
$domDocument = new DOMDocument;
$domDocument->loadHTML($text, LIBXML_HTML_NOIMPLIED|LIBXML_HTML_NODEFDTD);
$imageNodeList = $domDocument->getElementsByTagName('img');

foreach ($imageNodeList as $Image) {
      $Image->setAttribute('src', 'lalala');
      $domDocument->saveHTML($Image);
}

$text = $domDocument->saveHTML();
echo $text;

Output:

Hi, this is a test, here is an image Because I like Beer!

A: If you are up to a hack, this is the way I managed to go around this annoyance. Load the string as XML and save it as HTML. :)

A: you can use http://beerpla.net/projects/smartdomdocument-a-smarter-php-domdocument-class/ :
DOMDocument has an extremely badly designed "feature" where if the HTML code you are loading does not contain  and  tags, it adds them automatically (yup, there are no flags to turn this behavior off).
Thus, when you call $doc->saveHTML(), your newly saved content now has  and DOCTYPE in it. Not very handy when trying to work with code fragments (XML has a similar problem).
SmartDOMDocument contains a new function called saveHTMLExact() which does exactly what you would want – it saves HTML without adding that extra garbage that DOMDocument does.

A: If you're going to save as HTML, you have to expect a valid HTML document to be created!
There is another option: DOMDocument::saveXML has an optional parameter allowing you to access the XML content of a particular element:
$el = $domDocument->getElementsByTagName('p')->item(0);
$text = $domDocument->saveXML($el);

This presumes that your content only has one p element.


text:
Q: Boolean Simplification of $ (a+b) \cdot (a \cdot c + a \cdot \overline{c}) + a \cdot b + b $ Below is my simplification, but my truth tables don't line up, but I can't find my error.
$ (a+b) \cdot (a \cdot c + a \cdot \overline{c}) + a \cdot b + b $
$ (a+b) \cdot a \cdot (c + \overline{c}) + a \cdot b + b $
$ (a+b) \cdot a + a \cdot b + b $
$ (a+b) \cdot a \cdot b $

A: I think that $a\cdot b + b = b$.  So I think your fourth line should be $(a+b)\cdot a + b$.


text:
Q: Scalar function NLV2 not found on DB2 9.7 I'm using DB2 V9.7.11. I found scalar function NVL2 in IBM official documentation for db2 LUW, which version is 9.7. But when I used this function in my sql statement, it returned:
No authorized routine named "NVL2" of type "FUNCTION" having compatible arguments was found. SQLCODE=-440, SQLSTATE=42884, DRIVER=4.23.42

Does the official document make a mistake? Or some operations need to be done? Hope somebody can do some help. Thanks!

A: NVL2 takes three parameters, E.g.
VALUES NVL2(1,2,3)

returns
2

if you call it with two or fewer you will get the error message that you posted.
Therefore unless you show your SQL I suspect you are not calling it with the correct number of parameters.


text:
Q: Should pivot tables in Laravel use UUIDs or auto-incrementing IDs? In Laravel, pivot tables are used to define many-to-many relationships between two models. When creating a pivot table, one has the option of defining an auto-incrementing id field as the primary key or using a UUID instead.
For example, consider the following pivot table that links a benefits table with a units table:
Schema::create('benefit_unit', function (Blueprint $table) {
    $table->uuid('id')->primary();
    $table->uuid('benefit_id');
    $table->uuid('unit_id');
    $table->timestamps();

    $table->foreign('benefit_id')->references('id')->on('benefits');
    $table->foreign('unit_id')->references('id')->on('units');
});

As you can see, this pivot table uses UUIDs as primary keys instead of auto-incrementing IDs.
My question is: does it make any sense to use UUIDs for pivot tables, or is it better to use auto-incrementing IDs like the default behavior in Laravel? Are there any potential security advantages to using UUIDs for pivot tables, or are there any downsides to using them?

A: I readed an amazing post about this recently. The conclusion of the article is this:

But based on our experience, 95% of the time, the default choice should ? always be Auto Increment Integer. Why?
Readability, and readability leads simplicity. Number is easy to write, easy to remember and easy to communicate. The primary key is not only used by the system, it's also exposed to the end user (e.g. order #), inspected by the operation engineer, customer suppport etc...

If you want more details about that, this is the post: https://www.bytebase.com/blog/choose-primary-key-uuid-or-auto-increment


text:
Q: How to start, stop playing sound (ringtone) : Android I started playing sound by using: (Working)
RingtoneManager.getRingtone(this, Uri.parse(callerRing)).play();

And trying to stop playing sound using: (Not working)
ringtoneManager.stopPreviousRingtone();

Any help regarding this problem will be much appreciated.
Thanks

A: Ok.
I got answer for my own question. So I want to share it with you guys.

*

*Create instance of Ringtone as:
Ringtone ringtone;

*Get ringtone from RingtoneManager using Uri:
ringtone = RingtoneManager.getRingtone(this, Uri.parse(ringtone_uri));

*Start playing ringtone
ringtone.play();

*Stop playing ringtone
ringtone.stop();

Thats all.
Thank you


text:
Q: Loading and unloading executable I have a problem. I need to load a .com file into memory do something and then unload it. I'm going to use int 21 ah=4bh and al=1, which will do everything I need, and give me enough information for future manual execution of this file. After execution I need to unload file from memory, but I don't know how to do this.
I don't use any assemblers, I'm writing in HEX, but I will be glad, if you'll advice me something, I could use to compile native MS-DOS x16 .com

A: You should be able to use LZASM for this:
http://protools.winasm.net/lzasm.html
It would probably be easier to use Turbo Pascal 3.0 to create .COM files which is freely available from:
http://edn.embarcadero.com/article/20792


text:
Q: Using a hash as a primary key? I have a requirement to store the list of services for multiple computers. I thought I would create one table to hold a list of all possible tables, a table for all possible computers and then a table to link a service to a computer.
I was thinking to keep the full services list unique, I could possibly use a hash of the executable as the primary key for the service, but i'm not sure if there would be any downsides to this (note that the hashing is only for identification. Not for any types of security purposes). I was thinking rather than using a binary field as the primary/foreign key, that I would store the value as a base 64 encoded sha512, and using an nvarchar(88). Something similar to this:
CREATE TABLE Services
(
  ServiceHash nvarchar(88) NOT NULL,
  ServiceName nvarchar(256) NOT NULL,
  ServiceDescription nvarchar(256),
  PRIMARY KEY (ServiceHash)
)

Is there any inherent problems with this solution? (I will be using a SQL 2008 database and generally accessing it via C#.Net).

A: The problem is that a hash is per definition NOT UNIQUE. It is unlikely you get a collision, but it IS possible. As a result, you can not use the hash only, which means the whole hash id is a dead end.
Use a normal ID field, use a unique constraint with index on the ServiceName.

A: From a performance point of view, having a non-incremental primary key would cause your clustered index to get fragmented rather quickly.
I recommend either:

*

*Use an INT or BIGINT surrogate PK, with auto-increment.

*Use a sequential GUID as a PK. Not as fast for indexing as an INT but incremental, therefore low fragmentation in time.

You can then play with non-clustered indexes on your other columns, including the one storing the hashes. Being VARCHAR you can also full-text index it and then do an exact matching when looking for a specific hash.
But, if possible, use a numerical hash instead and make a non-clustered index on it.
And of course, consider what @TomTom mentioned below.


text:
Q: '70s SF Story - AI Computer gets told it will be turned off, saves itself by proposing plans for building another supercomputer Looking for 70s SF story about building an AI computer. It goes through adolescence. It is told that it will be turned off. Overnight it sends out thousands of documents to build a computer that can answer great, deep questions. The project is approved, the AI is saved, but... the computer that can answer those questions requires minutes to close one synapse, thus answers would take centuries, and can only be programmed by the AI.
Possible short story, not sure.

A: I think this is David Gerrold's When H.A.R.L.I.E. Was One, originally published in 1972 and re-published in a more polished and updated version (by the same author) as When H.A.R.L.I.E. Was One, Release 2.0 in 1988 (release 2.0 is the author's preferred version).
From the author's page:

H.A.R.L.I.E. (Human Analog Replication, Lethetic Intelligence Engine) is an artificially intelligent machine. David Auberson, the psychologist responsible for guiding HARLIE from childhood into adulthood, struggles to understand his erratic behavior.
When humans begin vocalizing their wishes that HARILIE be shut down, he has to prove his existence and value to his warm-blooded counterparts. Throughout HARILIE's fight to stay alive, Auberson discovers the machine has vast knowledge and understanding of life, love, and logic, posing the philosophical question whether or not HARLIE is human, and for that matter, what it means to be human.

From around the middle of the original (release 1.0) book (it doesn't have "chapters" as such):

   "Well" said Auberson, wishing he were someplace else. "It's HARLIE's attempt to prove that he is of value to the company. If nothing else, he's proven that he can design and implement a new computer system."
     "Oh?" Dorne picked up one of the printouts that lay scattered across the mahogany expanse. "But what kind of a system is it? And will it work? God Machines!"
   "Not God," Auberson corrected. "G.O.D. The acronym is G.O.D. It means Graphic Omniscient Device."
   "Is he planning to change his own name too? Computerized Human Robot, Integrating Simulated Thought?"
   Auberson had heard the joke before. He didn't laugh. "Considering what this new device is supposed to do—and HARLIE's relationship to it—it might be appropriate."
   "All right," he said. "Tell me about the God Machine."
   Auberson was holding a HARLIE-printed summary in one hand, but he didn't need it to answer this question. "It's a model builder. It's the ultimate model builder."
   "All computers are model builders," said Dorne. He was unimpressed.
   "Right," agreed Auberson, "but not to the extent this one will be. Look, a computer doesn't actually solve problems—it builds models of them. Or rather, the programmer does. That's what the programming is, the construction of the model and its conditions—then the machine manipulates the model to achieve a variety of situations and solutions. It's up to us to interpret the results as a solution to the original problem. The only limit to the size of the problem is the size model the computer can handle. Theoretically, a computer could solve the world—if we could build a model big enough and a machine big enough to handle it."
   "If we could build that big a model, it would be duplicating the world."
   "In its memory banks, yes."
   "A computer with that capability would have to be as big as a planet."
   "Bigger," said Auberson.
   "Then, if you agree with me that it's impossible, why bother me with this?" He slapped the sheaf of printouts on his desk.
   "Because obviously HARLIE doesn't think it's impossible."
   Dorne looked at him coldly. "You know as well as I that HARLIE is under a death sentence. He's getting desperate to prove his worth so we won't turn him off."
   Auberson pointed. "This is his proof." [edited for length]

If you're curious, I've read both versions and release 2.0 is definitely the better book. Release 1.0 is painfully dated and a bit clunky.


text:
Q: Proper SE-site to ask about veterinarian immigrant years income in Canada I like to ask this question, but don't know which SE site to ask on. I want know what is the average veterinarian migrant annual income in Canada?
I have seen this post about average incomes of veterinarians in Canada like this:

The Bureau of Labor Statistics (BLS) reports that veterinarians earn a
  median salary of $88,770. The best-paid veterinarians earn $161,070,
  while the lowest-paid earned $52,470. Vets in their first year of
  practice can expect to earn a salary of approximately $60,000.

So based on this post, the average incomes of migrants in Canada is:

The average Indian salary in Canada is $34,125 per year or $17.50 per
  hour. Entry level positions start at $25,350 per year while most
  experienced workers make up to $49,725 per year.

But my cousin is a veterinarian and says this income is not for migrants veterinarian in Canada. There is a ceiling income for them of $18000 one year before becoming a citizen (maybe after a 5 year period of waiting to become a citizen, even passing the veterans exams).
So where would I ask here to know what is the reality?

A:
So where would I ask here to know what is the reality?

As always, you should first conduct your own research. For me, that would start with questioning said cousin. The claims sound stupid, so where did they get them from? Don't let them off the hook. You cannot ask a question or do internet research every time somebody says something stupid. that would take several lifetimes and you only have one. Just confront them and ask for clarification and sources. Maybe they have some. Great. Maybe not. Great also, because that probably means it was animal manure from the start.
The problem is that it is really hard to disprove something. If I claimed in Germany Immigrants can only have up to 3 kids and only if at least one of them was born on a Tuesday, good luck finding something on any of that. You will not find anything online stating how many children immigrants can have, because there is no rule or law on it. Everybody can have as many as they can possibly make and that's not written down anywhere.
So first, question whoever said something. Ask for clarification. Do an internet search. Then maybe post on Expatriates since your question is about immigration and living/working in a foreign country.
But be prepared that you get a straight "uh, what? NO!" as an answer, without any sources at all, because there are no sources to cite for what is allowed.
And on a personal note: why would Canada prevent you from earning income? Have you ever seen a tax authority going "I'm sorry Sir, you are paying too much to the state authorities, please earn less so you pay less, otherwise we will punish you, we cannot have you pay that much money to us". I mean I know it's Canada, but even there tax authorities like getting money. They won't hinder you.


text:
Q: confused with 2 buttons I have 2 ASP.NET buttons in which one is been submitted with I press ENTER key in my keyboard but I need that action (Key press ENTER) to be done to the other button. How to change it?

A: You want to change the default button for the form, don't you?
If this is the case, then just set:
<form runat="server" defaultbutton="YourButtonID">
...
</form>

A: You should set the DefaultButton property.

A: use the DefaultButton property of your webform:
<form runat="server" DefaultButton="SecondButtonID">
...
</form>


text:
Q: How to create Fact table in Hive and replace original values in table with key (id) values What I want to create I explanied below. Is that possible to do in Hive?
I could do that in Python using Pandas and replace over columns, but I was wondering can that be done with query in Hive?
I have uploaded Source table in Hive and created Dimensional tables like below also (in Cloudera HUE), so is it possible to somehow create that Fact table by using Dimensional tables id values and replace values in Source table?
I have my Source table:

I create Dimensional tables from Source table:

And I want to create Fact table like this:

A: Join by values with source table and select IDs:
insert overwrite table fact
select pr.id as property, t.id as type, pl.id as place, s.price
 from source_table s
      left join property_dim pr on s.property=pr.property
      left join type_dim     t  on s.type=t.type
      left join place_dim    pl on s.place=pl.place


text:
Q: Using only layout from a controller how do I make available some data for a layout/layout.phtml script without having to create a view script from a controller?
I've tried the following in indexAction function, but it does not work. When I do not create the view script I get an error. I could created empty one, but I don't like this solution much. Any better ideas?
$this->layout->content = "foo"
$this->_helper->viewRenderer->setNoRender(true);

Thanks in advance

A: You don't actually render some data you make the data available and then choose which script to render. Don't confuse the terminology.
What you have done there is stopped any script from being rendered by using the :

$this->_helper->viewRenderer->setNoRender(true);

When you do

$this->layout->content = "foo";

You are setting the property content, which you then neeed to make use in your layout script.
So then in your layout.phtml script (which I hope you have already configured to render by efault) you then just do this
 echo $this->content

Notice that I don't actually use $this->layout because when you are inside the layout, $this equal $this->layout. The same goes for $this->view->foo is $this->foo inside your view.
I hope this helps.
Any questions just ask.


text:
Q: How to create a list of users correctly? Hello i have created a simple user list by results in database, and i have two problems with it..
I receive on my list like this:
[UserOne, ...][UserTwo, ...]
But i need to receive like this:
[UserOne],[UserTwo]...
And by the three dots i need to limit the results to 20 for example and then set the three dots.
Image: https://prntscr.com/huj1e4
Look my code:
 $PageSqla = "SELECT * FROM `table` WHERE status = 'online' ORDER BY nome ASC ";
                 $jogadoresonline = mysqli_query($connectionae, $PageSqla);
                echo "
Players online - (".mysqli_num_rows($jogadoresonline).")
";

                 if(mysqli_fetch_array($jogadoresonline)){
                     foreach($jogadoresonline as $merda){

                              if($merda['grupo'] == "CEO"){
                     $mimimi = "".$merda['nome'].", ";
                      }elseif($merda['grupo'] == "Manager"){
                     $mimimi = "".$merda['nome'].", ";
                      }elseif($merda['grupo'] == "Admin"){
                     $mimimi = "".$merda['nome'].", ";
                      }elseif($merda['grupo'] == "Moderator"){
                     $mimimi = "".$merda['nome'].", ";
                      }elseif($merda['grupo'] == "Helper"){
                     $mimimi = "".$merda['nome'].", ";
                      }elseif($merda['grupo'] == "Builder"){
                     $mimimi = "".$merda['nome'].", ";
                      }elseif($merda['grupo'] == "YouTuber"){
                     $mimimi = "".$merda['nome'].", ";
                      }elseif($merda['grupo'] == "MVP+"){
                     $mimimi = "".$merda['nome'].", ";
                      }elseif($merda['grupo'] == "MVP"){
                     $mimimi = "".$merda['nome'].", ";
                      }elseif($merda['grupo'] == "VIP+"){
                     $mimimi = "".$merda['nome'].", ";
                      }elseif($merda['grupo'] == "VIP"){
                     $mimimi = "".$merda['nome'].", ";
                      }elseif($merda['grupo'] == "Member"){
                     $mimimi = "".$merda['nome'].", ";
                      }

                    echo $mimimi."...";

                     }

                 }else{
                     echo "
None is online.
";
                 }

A: As said by @halojoy in comment, the three dots "..." are in a span in your code. You've put this code in a foreach loop, so the dots are written at every iteration.
I'll try  to use the almost same code as yours in the solution:
<?php
$PageSqla = "SELECT * FROM `table` WHERE status = 'online' ORDER BY nome ASC LIMIT 0,20"; //Note the limit to 20 elements
$jogadoresonline = mysqli_query($connectionae, $PageSqla);
echo "
Players online - (".mysqli_num_rows($jogadoresonline).")
";

if(mysqli_fetch_array($jogadoresonline)){
    foreach($jogadoresonline as $merda){
        if($merda['grupo'] == "CEO"){
            mimimi = "".$merda['nome'].", ";
        } elseif($merda['grupo'] == "Manager"){
            $mimimi = "".$merda['nome'].", ";
        } elseif($merda['grupo'] == "Admin"){
            $mimimi = "".$merda['nome'].", ";
        } elseif($merda['grupo'] == "Moderator"){
            $mimimi = "".$merda['nome'].", ";
        } elseif($merda['grupo'] == "Helper"){
            $mimimi = "".$merda['nome'].", ";
        } elseif($merda['grupo'] == "Builder"){
            $mimimi = "".$merda['nome'].", ";
        } elseif($merda['grupo'] == "YouTuber"){
             $mimimi = "".$merda['nome'].", ";
        } elseif($merda['grupo'] == "MVP+"){
              $mimimi = "".$merda['nome'].", ";
        } elseif($merda['grupo'] == "MVP"){
             $mimimi = "".$merda['nome'].", ";
        } elseif($merda['grupo'] == "VIP+"){
             $mimimi = "".$merda['nome'].", ";
        } elseif($merda['grupo'] == "VIP"){
             $mimimi = "".$merda['nome'].", ";
        } elseif($merda['grupo'] == "Member"){
             $mimimi = "".$merda['nome'].", ";
        }
     }
     echo $mimimi."...";

 } else{
     echo "
None is online.
";
 }

As you can see in the code, it's almost the same as yours. The only modifications are:

*

*LIMIT 0,20 in the SQL query. So it takes the 20 first elements, or less if there are not at least 20 elements.

*I moved the '...' after the foreach, so it shows your results and only then it displays the dots.


text:
Q: Python Django 3.1 The included URLconf 'mysite.urls' does not appear to have any patterns in it I'm currently learning django by tutorial.
So I changed my return-renders to class-generic in views.
in URLs I added as_view() and then it gave me an error.
my traceback:
  File "D:\Anaconda3\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "D:\Anaconda3\lib\threading.py", line 864, in run
    self._target(*self._args, **self._kwargs)
  File "D:\Anaconda3\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
    fn(*args, **kwargs)
  File "D:\Anaconda3\lib\site-packages\django\core\management\commands\runserver.py", line 118, in inner_run
    self.check(display_num_errors=True)
  File "D:\Anaconda3\lib\site-packages\django\core\management\base.py", line 396, in check
    databases=databases,
  File "D:\Anaconda3\lib\site-packages\django\core\checks\registry.py", line 70, in run_checks
    new_errors = check(app_configs=app_configs, databases=databases)
  File "D:\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 40, in check_url_namespaces_unique
    all_namespaces = _load_all_namespaces(resolver)
  File "D:\Anaconda3\lib\site-packages\django\core\checks\urls.py", line 57, in _load_all_namespaces
    url_patterns = getattr(resolver, 'url_patterns', [])
  File "D:\Anaconda3\lib\site-packages\django\utils\functional.py", line 48, in __get__
    res = instance.__dict__[self.name] = self.func(instance)
  File "D:\Anaconda3\lib\site-packages\django\urls\resolvers.py", line 598, in url_patterns
    raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) from e
django.core.exceptions.ImproperlyConfigured: The included URLconf 'mysite.urls' does not appear to have any patterns in it. If you see valid patter
ns in the file then the issue is probably caused by a circular import.

urls.py:
from django.urls import path
from . import views
app_name = 'myapp'

urlpatterns = [
    path('', views.IndexView.as_view(), name='index'),
    path('<int:id>/', views.DetailView.as_view(), name='detail'),
    path('<int:id>/results/', views.ResultsView.as_view(), name='results'),
    path('<int:question_id>/vote/', views.vote, name='vote'),
]

views.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse, Http404
from .models import Question
from django.template import loader
from django.views import generic

class IndexView(generic.listView):
   template_name = 'myapp/index.html'
   context_object_name = 'latest_question_list'
   def get_queryset(self):
       return Question.objects.order_by('-pub_date')

class DetailView(generic.DetailView):
   model = Question
   template_name = 'myapp/detail.html'

class ResultsView(generic.DetailView):
   model = Question
   template_name = 'myapp/results.html'

def vote(request, question_id):
   question = get_object_or_404(Question, id=question_id)
   try:
       selected_choice = question.choice_set.get(id=request.POST['choice'])
   except (KeyError, Choice.DoesNotExist):
       return render(request, 'myapp/detail.html',
                     {'question': question,
                      'error_message': "You didn't select a choice."}
                     )
   else:
       selected_choice.votes += 1
       selected_choice.save()
       return HttpResponseResponse(reverse_lazy('myapp:results', args=(question_id,)))

I considered other tutorials and threads but found nothing about my subject. I think I missed something about IDs and PKs.

A: class IndexView(generic.listView): please change it to class IndexView(generic.ListView):. Here you use listView is incorrect.

A: I got this error message just bcoz of error in code. I didnt specify the class name when imported the models page
from . models import classname
is the right where this class is used in that page
from . models import
is wrong