text:
Q: Creating feature class on ArcSDE schema with different user I have created an enterprise geodatabase using ArcCatalog 10.5 on a PostgreSQL database. I have a database admin user named administrator and another user named sde. The geodatabase admin is sde user.
Geodatabase is created successfully. And I connected to database from ArcCatalog with administrator user. So I want to create a feature class but throws an error:

Failed to create Feature class.
Database user name and current schema
do not match. [mygdb.administrator.test]

Should I connect with sde user and create feature classes or other objects?
So If I need multiple users to create feature objects, all of them will use sde user. Is this right?

A: The Enterprise geodatabase model calls for multiple logins when managing tables.
First off, you should not ever create any tables as the administrator or sde user.  Period.  Ever.  Using administrative accounts to manage tables opens the door to complete database destruction with a single click.
Best practice is to create at least two additional logins (though in practice this expands to two more than the number of independent users).
When using the simplest security model, this means that login/user/schema data_owner creates and registers tables and login/user/schema data_user is granted the necessary access to do necessary processing.  In this model, the GIS admin/team retains login rights to data_owner and all others connect as data_user.
In the real world, you'll have logins dept_a, dept_b, dept_c manage the holdings of departments, with each real user accessing the database having an individual login, and group roles created to model needed access read-only/read-write, and accesses granted to the roles, with roles granted to users.  In addition, there may be one or more login/user/schemas created for "headless access" (ArcGIS Server publishing connections, with roles assigned appropriately).
While most databases support schemas that do not match logins, the geodatabase model can only support this if the user never needs to create a selection set over 100 records, because it will then try to create tables with the same schema/user as login and fail.
Using your example, you should not create tables as sde or administrator (best practice), and should instead create at least one login/user/schema to own the geodata, and one or more login/user/schemas to access the data. You can then safely create feature classes as the owner account(s) and access them as necessary.
The only possible alternative is to abandon using all geodatabase functionality, and create tables only via SQL tools, never registering them with the geodatabase, and only accessing them via Query Layers (and even then, you shouldn't use the sde login for this).

A: Every user should have schema associated in the database with the same name along appropriate DDL permissions to be able to create FC/tables from ArcGIS desktop.


text:
Q: Does using a lot of tail-recursion in Erlang slow it down? I've been reading about Erlang lately and how tail-recursion is so heavily used, due to the difficulty of using iterative loops.
Doesn't this high use of recursion slow it down, what with all the function calls and the effect they have on the stack? Or does the tail recursion negate most of this?

A: Iterative tail recursion is generally implemented using Tail calls.
This is basically a transformation of a recursive call to a simple loop.
C# example:
uint FactorialAccum(uint n, uint accum) {
    if(n < 2) return accum;
    return FactorialAccum(n - 1, n * accum);
};
uint Factorial(uint n) {
    return FactorialAccum(n, 1);
};

to
uint FactorialAccum(uint n, uint accum) {
start:
    if(n < 2) return accum;
    accum *= n;
    n -= 1;
goto start;
};
uint Factorial(uint n) {
    return FactorialAccum(n, 1);
};

or even better:
uint Factorial(uint n) {
    uint accum = 1;
start:
    if(n < 2) return accum;
    accum *= n;
    n -= 1;
goto start;
};

C# not real tail recursion, this is because the return value is modified, most compilers won't break this down into a loop:
int Power(int number, uint power) {
    if(power == 0) return 1;
    if(power == 1) return number;
    return number * Power(number, --power);
}

to
int Power(int number, uint power) {
    int result = number;
start:
    if(power == 0) return 1;
    if(power == 1) return number;
    result *= number;
    power--;
goto start;
}

A: It should not affect performance in most cases. What you're looking for is not just tail calls, but tail call optimization (or tail call elimination). Tail call optimization is a compiler or runtime technique that figures out when a call to a function is the equivalent of 'popping the stack' to get back to the proper function instead of just returning. Generally tail call optimization of can only be done when the recursive call is the last operation in the function, so you have to be careful.

A: There is a problem pertaining to tail-recursion but it is not related to performance - Erlang tail-recursion optimisation also involves elimination of the stack trace for debugging.
For instance see Point 9.13 of the Erlang FAQ:

Why doesn't the stack backtrace show the right functions for this code:
-module(erl).
-export([a/0]).

a() -> b().
b() -> c().
c() -> 3 = 4.           %% will cause badmatch

The stack backtrace only shows function c(), rather than a(), b() and c().
This is because of last-call-optimisation; the compiler knows it does not need
to generate a stack frame for a() or b() because the last thing it did was call another function, hence the stack frame does not appear in the stack backtrace.

This can be a bit of pain when you hit a crash (but it does kinda go with the territory of functional programming...)

A: The point is that Erlang optimizes tail calls (not only recursion).  Optimizing tail calls is quite simple:  if the return value is computed by a call to another function, then this other function is not just put on the function call stack on top of the calling function, but instead the stack frame of the current function is replaced by one of the called function.  This means that tail calls don't add to the stack size.
So, no, using tail recursion doesn't slow Erlang down, nor does it pose a risk of stack overflow.
With tail call optimization in place, you can not only use simple tail recursion, but also mutual tail recursion of several functions (a tail-calls b, which tail-calls c, which tail-calls a ...).  This can sometimes be a good model of computation.

A: A similar optimization that separates program text function calls from implementation function calls is 'inlining'.  In modern/thoughtful languages function calls have little relation to machine level function calls.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I get the property name in my MVC3 custom Editor Template I have an enumeration in my project and I've created a custom editor template for this enumeration. So, now any model I have with a property with a type of this enumeration, will render a drop down.
This works great, but I would like to name my select element of my dropdown with the name of the property.  Here is my Razor code for my editor template.
    @model ItemEnumerations.ItemType

    <select id="PropertyNameHere" name="PropertyNameHere">
    @foreach (ItemEnumerations.ItemType in Enum.GetValues(typeof(ItemEnumerations.ItemType))) {
        <option value="@value" @(Model == @value ? "selected=\"selected\"" : "")>@value.ToString()</option>
    }
    </select>

So, where I have 'PropertyNameHere' for the select elements id and name attributes, I would like to have the name of the property of my model.  Here is an example:
My Model:
    public class MyModel{
        public int ItemID {get;set;}
        public string ItemName {get;set;}
        public ItemEnumerations.ItemType MyItemType {get;set;}
    }

My View Code:
@model MyModel

@Html.LabelFor(m => model.ItemID)
@Html.DisplayForm(m => model.ItemID)

@Html.LabelFor(m => model.ItemName)
@Html.EditorFor(m => model.ItemName)

@Html.LabelFor(m => model.MyItemType )
@Html.EditorFor(m => model.MyItemType )

I would like my select element to have a name and id of 'MyItemType'.

A: I found the answer in a book I have here.  Actually, it got me close, but I then could google the rest based on what I found.
Here is what I needed to add to my editor template.
@{var fieldName = ViewData.TemplateInfo.HtmlFieldPrefix;}
<select id="@fieldName" name="@fieldName">

A: How about the following template:
@model ItemEnumerations.ItemType
@{
    var values =
        from value in Enum.GetValues(typeof(ItemType)).Cast<ItemType>()
        select new { ID = (int)value, Name = value.ToString() };
    var list = new SelectList(values , "ID", "Name", (int)Model);
}
@Html.DropDownList("", list)

This way you don't need to manually render <select> and <option> tags and you are reusing the existing DropDownList helper.

A: For future reference (old question), I found this: System.Web.Mvc.Html.NameExtensions.
Using those, you can do something like
<input type=text" name="@Html.NameFor(m => m.MyProperty)">

And you'll get
<input type=text" name="MyProperty">

There are several other related helpers in this extension class. This method does more than just get the property name, though. For example, you could use m.MyProperty.MySubProperty and you'd get a valid HTML name for posting.

A: You can get the property name in the editor template via
@{
   string name = ViewData.ModelMetadata.PropertyName;
}

A: You can create a helper to use that inside your view, which is explained here
And you can use this piece of code to get the name.
 public static class GenericHelper<T>
 {
     public static String GetPropertyName<TValue>(Expression<Func<T, TValue>> propertyId)
     {
         var operant = (MemberExpression)((UnaryExpression)propertyId.Body).Operand;
         return operant.Member.Name;
     }
}

I assume the default helpers do the same, such as HiddenFor, as they also use Expression<Func<TModel, TProperty>>

A: As mentionned in the accepted answer, ViewData.TemplateInfo.HtmlFieldPrefix gives you the property name inside an EditorTemplate.
I think it is worth saying that you can use an empty string inside the HtmlHelper functions if your goal is to generate an input/select. It will use the model's property name.
@Html.TextBox("", theValue, new { @class = "form-control" })

or
@Html.DropDownList("", new List<SelectListItem>(), theValue, new { @class = "form-control" })


text:
Q: Checking if record field is unique (DBTables.TBDEDataSet.Lookup method) I want to check if record value in field "number_field" is unique so I'm locating record with the same value in number_field. I use Lookup method because I'm editing record:
id := SomeTable.Lookup('DOCUMENT_NUMBER', CurrentDocNumber, 'ID');

Of course in some cases it will give me the current record ID. How can I skip editing record?
Edit: I don't want to disable saving document with the same number to the database - I just want to inform the user that number he wrote is already on system and let him decide what to do
Edit2: I operate only in loaded data - no DB

A: you could use a TQuery and check if you have the record in the DB:
select count(*) from my_table where DOCUMENT_NUMBER=CurrentDocNumber
EDIT:
The same could be done with a TDataSet. you could either select count or select * to test if RecordCount > 0
EDIT2:
just to be fair:
note that if this is the case I operate only in loaded data - no DB (this was an update after you accepted my answer) then my solution wont work because records are not yet posted to the live DB. never the less, you must use this query if there are more then 1 client connected and writing to the DB.

A: It's a good practice to set the DOCUMENT_NUMBER field as unique at the database level, then an exception will be raise automatically during posting, which will disallow posting the record.  You can also catch the exception and re-raise with your own error, such as "Document number already exists" etc.
If you can't do this, then you'd have to create another table component, and beforepost locate the record in the secondary table, and if it exists, raise an exception.


text:
Q: Clustering similar values in a matrix I posted this on stackoverflow.com yesterday and its had very few views.  I came across this stackexchange site and thought its got to be worth an ask:
I have an interesting problem and I'm sure there is an elegant algorithm with which to solve the solution but I'm having trouble describing is succinctly which would help finding such an algorithm.
I have a symmetric matrix of comparison values e.g:
-104.2732   -180.3972   -130.6969   -160.8333   -141.5499   -139.2758   -144.7697   -114.0545   -117.6409   -140.1391
-180.3972   -93.05421   -171.618    -162.0157   -156.8562   -156.3221   -159.9527   -163.2649   -170.127    -153.2709
-130.6969   -171.618    -101.1591   -154.4978   -143.6272   -116.3477   -137.2391   -125.5645   -128.9505   -131.6046
-160.8333   -162.0157   -154.4978   -96.96312   -122.7894   -141.5103   -127.7861   -149.6883   -153.0445   -130.2555
-141.5499   -156.8562   -143.6272   -122.7894   -101.7487   -141.451    -123.9087   -138.7041   -139.2517   -125.3494
-139.2758   -156.3221   -116.3477   -141.5103   -141.451    -99.99486   -134.6553   -132.7735   -138.7249   -134.1319
-144.7697   -159.9527   -137.2391   -127.7861   -123.9087   -134.6553   -100.0683   -141.3492   -138.0292   -120.5331
-114.0545   -163.2649   -125.5645   -149.6883   -138.7041   -132.7735   -141.3492   -106.8555   -115.58 -139.3355
-117.6409   -170.127    -128.9505   -153.0445   -139.2517   -138.7249   -138.0292   -115.58 -104.9484   -140.4741
-140.1391   -153.2709   -131.6046   -130.2555   -125.3494   -134.1319   -120.5331   -139.3355   -140.4741   -101.3919

The diagonal will always show the maximum score (as it is a self-to-self comparison).  However I know that of these values some of them represent the same item.  Taking a quick look at the matrix I can see (and have confirmed manually) that items 0, 7 & 8 as well as 2 & 5 and 3, 4, 6 & 9 all identify the same item.
Now what I'd like to do is find an elegant solution as to how I would cluster these together to produce me 4 clusters.
Does anyone know of such an algorithm?  Any help would be much appreciated as I seem so close to a solution to my problem but am tripping at this one last stumbling block :(
Cheers!

A: Hierarchical clustering may be a good solution because it provides flexibility, a quantitative assessment of cluster similarity and grouping, and--by means of dendrograms--a natural graphical way to analyze the data.
Let's illustrate with some R commands.  First, the data, for those who might wish to follow along:
x <- matrix(c(-104.2732, -180.3972, -130.6969, -160.8333, -141.5499, -139.2758, -144.7697, -114.0545, -117.6409, -140.1391,  -180.3972, -93.05421, -171.618, -162.0157, -156.8562, -156.3221, -159.9527, -163.2649, -170.127, -153.2709, -130.6969, -171.618, -101.1591, -154.4978, -143.6272, -116.3477, -137.2391, -125.5645, -128.9505, -131.6046, -160.8333, -162.0157, -154.4978, -96.96312, -122.7894, -141.5103, -127.7861, -149.6883, -153.0445, -130.2555, -141.5499, -156.8562, -143.6272, -122.7894, -101.7487, -141.451, -123.9087, -138.7041, -139.2517, -125.3494, -139.2758, -156.3221, -116.3477, -141.5103, -141.451, -99.99486, -134.6553, -132.7735, -138.7249, -134.1319, -144.7697, -159.9527, -137.2391, -127.7861, -123.9087, -134.6553, -100.0683, -141.3492, -138.0292, -120.5331, -114.0545, -163.2649, -125.5645, -149.6883, -138.7041, -132.7735, -141.3492, -106.8555, -115.58, -139.3355, -117.6409, -170.127, -128.9505, -153.0445, -139.2517, -138.7249, -138.0292, -115.58, -104.9484, -140.4741, -140.1391, -153.2709, -131.6046, -130.2555, -125.3494, -134.1319, -120.5331, -139.3355, -140.4741, -101.3919), nrow=10)

An "average" linkage method appears to get the results you have derived:
x.cluster <- hclust(dist(x), method="average")
plclust(x.cluster, labels=as.character(0:9))

In this plot (produced by the second R command), the "height" is the Euclidean distances between the columns of the matrix x (thought of as 10-vectors).
The clusters (1), (3(4(69))), (0(78)), and (25) are evident among the leaves near the bottom of this plot.  What you consider to be a "cluster" depends on the cutoff height.  E.g., cutting the tree at height 52 reproduces your four clusters:
> split(0:9, cutree(x.cluster, h=52))
$`1`
[1] 0 7 8

$`2`
[1] 1

$`3`
[1] 2 5

$`4`
[1] 3 4 6 9

whereas cutting it slightly lower (at 40) will split column 3 away from (4(69)).
For links to the documentation for hclust, plclust, and cutree, as well as links to alternative clustering solutions in R, please see the Cluster Analysis Task View.


text:
Q: Закрыть страницу PageLogin после успешной авторизации private void BLogin_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                var userObj = AppConnect.modeiOdb.Users.FirstOrDefault(x =>
                x.login == TxLogin.Text && x.password == TxPassword.Password);

                if (userObj == null)
                {
                    MessageBox.Show("Такого пользователя нет", "Ошибка Авторизации",
                    MessageBoxButton.OK, MessageBoxImage.Error);
                }
                else
                {
                    switch (userObj.id_user)
                    {
                        case 1:
                            MessageBox.Show("Здравствуйте администратор, " + userObj.userName + " !", "Уведомление",
                        MessageBoxButton.OK, MessageBoxImage.Information);
                            break;
                        case 2:
                            MessageBox.Show("Здравствуйте, " + userObj.userName + " !", "Уведомление",
                    MessageBoxButton.OK, MessageBoxImage.Information); break;
                        default:
                            MessageBox.Show("Данные не обнаружены", "Уведомление",
                   MessageBoxButton.OK, MessageBoxImage.Warning);
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка" + ex.Message.ToString(), "Критическая работа приложения",
                MessageBoxButton.OK, MessageBoxImage.Warning);
            }

        }

1
<StackPanel Background="{StaticResource BackgroundWindowResource}" HorizontalAlignment="Center"
                    VerticalAlignment="Center"
                    Width="250" OpacityMask="Black">
        <TextBlock Text="Введите логин"/>
        <TextBox Name="TxLogin"
                     Margin="0,5,0,5" />
        <TextBlock Text="Введите пароль"/>
        <PasswordBox Name="TxPassword"
                      Margin="0,5,0,0"/>
        <StackPanel Orientation="Horizontal"
                        HorizontalAlignment="Center">
            <Button Content="Войти"
                         Name="BLogin" Click="BLogin_Click" />
            <Button Content="Регистрация" Name="BReg" Click="Breg_Click" />

        </StackPanel>
    </StackPanel>

public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            AppConnect.modeiOdb = new TitleStudentEntities();
            AppFrame.frameMain = frame1;
            frame1.Navigate(new PageLogin());

        }
    }

Нужно попасть на страницу PageMain.xaml


text:
Q: Problem getting selected row index in NSTableView with filter predicate I'm not sure I'm phrasing this properly, but basically I do this in my main app delegate:
Application *app = [[Application alloc] initWithApplication:fullPath]
The Application class has an initWithApplication method that takes in the path of an app and then sets the properties for appPath, name, etc. Then I add the new "app" object to the applications NSMutableArray:
if (app) [applications addObject: app];

The NSArrayController's content array is bound to the applications NSMutableArray, and then the various keys (appPath, name, etc) are set in the NSArrayController. I then have a table view with various columns bound to the different properties, e.g. one column for the name, one column from the path, etc.
I then have a launch button that launches the app that is selected in the table view. For this I use this code:
Application *app = [applications objectAtIndex:[tableView selectedRow]];

Then I just use "app.appPath" as a reference to the path of the currently selected item. This works fine. The problem comes in when the table view contents are filtered using a filterPredicate. Basically it filters out all apps in the table view and leaves only the ones with a name that contains the phrase typed into the search box.
The above method does not work because it gets the index of the item in the table view, and since all the items are not in the table view, the count gets messed up. For example say I have an app called MyApp.app which is item at index 25 of the applications array.
The above code works well because the tableView and the applications array have the same number of objects. However filtering out the contents of the table view creates a difference in the number of objects, and therefore it launches the wrong app.
I hope my explanation is not too confusing, but its hard to explain. Any way around this?
Thanks

A: Solution was pretty simple for anyone that wants to know:
[[arrayController selection] valueForKey:@"appPath"]
HTH


text:
Q: Escape Sequences in Python Not Working in CMD import time
listy = ['timer','stopwatch']

def intro():
    print("This is a program which contains useful tools")
    print(listy)

def timer():
    x = int(input("How long Seconds ?"))
    while x > 0:
        print(x)
        time.sleep(1)
        x -= 1

def stopwatch():
    verif = input("Do you want to start y/n \n")
    if verif == 'y':
        x = 0
        while True:
            print(x, end = "\b"*5)
            time.sleep(1)
            x += 1

def main():
    intro()
    decider = input("Which Program?")
    if decider.lower() == 'timer':
        timer()
    elif decider.lower() == 'stopwatch':
        stopwatch()

main()

in this code i dont know why the \b escape sequence isnt working in cmd or in idle, can anyone explain why? Is it because of a logic error?

A: A flush may be required. How about...
print("{0}{1}".format("\b"*5, x), end="", flush=True)


text:
Q: Knockout optionsText is encoded I am trying to create an html hierarchical select based on this solution and using knockout
However, knockout encodes the string value i return.
How can i decode the text returned from the function?
jsFiddle example
Html:
<select data-bind="options: items, optionsText: getOptionText"></select>

Javascript:
var viewModel = {
    items: ko.observableArray([
        { Text: "Item 1", level: 1 },
        { Text: "Item 2", level: 2 },
        { Text: "Item 3", level: 3 },
        { Text: "Item 4", level: 4 }
    ]),
    getOptionText: function(data) {
        var value = "";
        for (var i = 1; i <= (data.level - 1) * 2; i++) {
            value += " ";
        }
        value += data.Text;
        return value;
    }
};
ko.applyBindings(viewModel)

A: Replace your " " with "\xA0" (The hexadecimal representation of the Non-Breaking Space character.)

A: The answer is to use the actual character for a space instead of an HTML entity. To get a non-breaking space type Alt+255. Just do this in place of the   in your code. It will look like a normal space but will display as a non-breaking space:
Live example: http://jsfiddle.net/jLbct/1/


text:
Q: CefSharp shows a blank page when run outside Visual Studio I'm trying to create a C# class library which consists of a form with CefSharp WinForms browser inside it. The library is used by another application as a plugin. The application is set to run when pressing "start" in Visual Studio. Launching the application this way works fine and CefSharp browser shows up and works as it should.
The problems begin when I try to launch the application from the filesystem. This time the form opens, as well as the DevTools, but the CefSharp browser won't appear and the DevTools form/window is blank. The applications trace files show that the it indeed does load the CefSharp DLLs:
15.56.32.202 Requested assembly CefSharp.WinForms (version 51.0.0.0) LOADED from file C:\*PATH_TO_THE_FILES*\CefSharp.WinForms.dll (version 51.0.0.0)
15.56.32.205 Requested assembly CefSharp (version 51.0.0.0) LOADED from file C:\*PATH_TO_THE_FILES*\CefSharp.dll (version 51.0.0.0)
15.56.32.243 Requested assembly CefSharp.Core (version 51.0.0.0) LOADED from file C:\*PATH_TO_THE_FILES*\CefSharp.Core.dll (version 51.0.0.0)
The same trace file logs all thrown exceptions and in this case there are none.
Some other things to note:
- I'm using Visual Studio 2015 Community Edition
- I'm building this for an x64 CPU.
- I've tried both Debug and Release built files, both work through VS and both fail without VS
- I've made sure I have all the files mentioned here in the folder where from CefSharp is loaded
- I have Microsoft Visual C++ redists installed (11.0, 12.0, 14.0)
- Also tried including the msvcp120.dll & msvcr120.dll and their debug variants in the output folder (just in case).
- I've tried both CefSharp versions 51 and 57, behavior stays the same
My only guess is that, under the hood, Visual Studio includes references to some vital files/components/dlls/whatever that are not there when launching without it.
UPDATE
I tried debugging this further and attached methods to following events:
LoadingStateChanged
ConsoleMessage
I created a test html page running on localhost which just calls console.log() with a simple message. The message is written to trace by the method attached to ConsoleMessage and when running from VS it's written to trace as it should. Without VS, it's not.
The method attached LoadingStateChanged wrote to trace the value of IsLoading property of the second parameter LoadingStateChangedEventArgs e. Running with or without VS both wrote the same thing: first true and then false. The ConsoleMessage was logged between these lines in trace when running with VS.
Furthermore, I tried disabling hardware acceleration with:
CefSettings settings = new CefSettings();
 settings.CefCommandLineArgs.Add("disable-gpu", "1")
but that didn't help either.

A: The problem was, as I suspected, related to missing references.
Adding the files of the VS output directory (bin/x64/Debug) to the external application's executable folder solved the problem.


text:
Q: What is purpose of /etc/shadow and shadow cache files in Linux operating system? What is the purpose of the /etc/shadow file in Linux Operating system?  Also, is it same for SUSE clients?
There is one shadow cache file is maintained what is purpose of that?

A: The /etc/shadow file was created for security reasons, and holds each user's encrypted password.
Originally, the encrypted password was stored in /etc/passwd.  /etc/passwd had to be world readable so that the system could map userids to user names, and so that users could find out information about each other, e.g. the other user's home directory, or their phone number, which was traditionally stored in the "gecos" field and displayed by the "finger" utility.
But then people realized that this was a security problem.  Anybody with enough time could do what's called a bruteforce attack, by programatically generating encrypted passwords for every possible password.  If the attacker did that without actually trying to log in via telnet or ssh, the system could not know that it was being attacked.
So the encrypted password was moved into the newly created /etc/shadow, which is readable only by root.
It also contains other information that the /etc/passwd file did not support related to the user's account and password, e.g. when the password was last changed and when it will expire.
See man 5 shadow (web version) for full details of the file format.

I can't say whether it is the same for SUSE, without knowing which version of SUSE you are dealing with.  For example, your SUSE system may use Blowfish rather than MD5.
You also implied you were mixing your /etc/shadow file with a system running a different Linux distribution, but did not say what the other distribution was.
See Problems migrating shadow file from SuSE 9.3 to Ubuntu Server x86_64 for example.
To try to figure it out, open up /etc/shadow and see whether the encrypted password field starts with $1$ or $2$.  If it contains $1$, then it's MD5, and compatible with most other distributions.  If it contains $2$, then it's probably Blowfish according to Blowfish shadow files on Debian.
If you are using Ubuntu, the first Google search result for Ubuntu blowfish might be a good starting place.

A: Users are listed in the /etc/passwd file. This file contains many information used by the systemm not only to allow users to log in.
Each line corresponds to a user entry and different fields are separated by colons. The first filed is the login, it is followed by the corresponding password.
Encrypted passwords used to be stored in this field. However, the /etc/passwd file has to be readable by everyone on the system, so encryption does not prevent from brute force attacks, as it has been said by @Mikel. The solution was to move these encrypted passwords in root-only readable file: /etc/shadow.
Thus, /etc/shadow contains the encrypted passwords of the system's users. The system knows it has to check for passwords in this file when password fields in /etc/passwd contain an x alone (meaning "cross over to /etc/shadow")

A: Let's see if I can get all the up-votes in the world, since I wrote what became the Linux Shadow Password Suite in '87 ;)
The original /etc/passwd file contained a modified DES-based hash of the cleartext password. At the time the crypt() function was created, it was believed (and this was stated by the creators of the UNIX operating system) that attacks against the password hash would be infeasible, due to the number of possible passwords and the use of a 12-bit (4,096 possible values) "salt". Each possible cleartext password had 4,096 possible hashed values, and with 64-bits of hashed result, that gave a total of 2^72 possible password hashes.
As another poster mentioned, /etc/passwd was also used by various utilities to map between user names and UID values (the /etc/group file provides the analogous function for groups) and that required it be world-readable.
In the 1980s it became obvious that dictionary attacks against the password hash stored in the /etc/passwd file were becoming feasible and /etc/shadow was introduced to AT&T UNIX in an early release of System V. I documented which manpages I used to write the original Shadow library, and I've since forgotten, but it was definitely an early System V release, probably SVR3.2.
What AT&T did, and what I implemented for SCO Xenix (the original SCO Xenix, not the later evil SCO Xenix) in '87 that eventually came into use on Linux, was simply move the hashed password to /etc/shadow. This prevented the drive-by attack, where an unprivileged user acquired a copy of /etc/passwd and ran an attack against it. If you're familiar with why I wrote Shadow in the first place, I had a user download my /etc/passwd file via UUCP back in the days when we still used UUCP for just about everything.
By the time Linux was created and came into wide-spread use, there were a very large number of tools for attacking password hashes. High-performance re-implementations of crypt() were one avenue, and dictionary-based attacks via tools such as Crack and libcrack were others. The initial port was done by Nate Holloway and Floria La Roche (I gave them credit, I don't know if anyone did the work before them).
Eventually the use of crypt()-based hashes, even in a protected file, was no longer secure and the original MD5-based hash changes were made. MD5 eventually was considered to be too weak, and newer hashes were used.
In theory, a strong enough hash could be stored in /etc/passwd. Poor operational security means that many systems have their /etc/shadow files available through various attack vectors -- "I stole the backup files" is probably the easiest.

A: From the beginning, Unix and Unix-style operating systems (including Linux) have always stored passwords as cryptographic hashes (1).  These hashes were originally stored in /etc/passwd, but this file needed to be world-readable to make the information available for other purposes - even a simple ls -l needs to read /etc/passwd in order to convert each file owner's numeric user id to their username for display.  However, having the hashed passwords in a world-readable file allowed malicious users to easily obtain those hashes and attempt to generate usable passwords(2) for other users' accounts.
To prevent this, the hashed passwords were eventually moved into a file readable only by root (and occasionally a privileged group of administrators), /etc/shadow.  This hides the hashes from normal users of the system while keeping them available for user authentication purposes.
Notes:

*

*Pedantic, I know, but the stored passwords are not encrypted.  They are hashed using a cryptographically-secure (at least as of the time it was written) hashing algorithm.  The primary distinctions relevant here are that hashes are fixed-length (the length of encrypted text varies based on the length of the text which was encrypted) and non-reversible (encrypted text can be decrypted; hashed text cannot).

*Because hashes are fixed-length, there are an infinite number of inputs which will match any given hashed representation.  An attacker could, therefore, find a working password which is not necessarily the same as the owning user's password - although this is very unlikely given the size of modern crypto hashes.


text:
Q: How to create a new pandas dataframe with multiple, custom index names? Based on this answer, I am already able to create a new pandas dataframe with my own data and specified dtypes as follows:
df = pd.DataFrame({'A':pd.Series([1], dtype='str'),
                   'B':pd.Series([4], dtype='int'),
                   'C':pd.Series([7], dtype='float')})

print(df)
   A  B    C
0  1  4  7.0

However, what I need is to be able to additionally specify the index names when creating the dataframe. I suppose this should be done using the index arguments of pd.DataFrame() and/or pd.Series(), but I'm not sure in what way.
The intended result is that, if I print the df afterwards, I get:
             A  B    C
idx1  idx2
0     test   1  4  7.0

where "idx1" and "idx2" are index names, and 0 and "test" are the values that the first row in this (single-row) dataframe has for the two indices.

A: Need define MultiIndex for each Series, e.g. by MultiIndex.from_arrays:
mux = pd.MultiIndex.from_arrays([[0], ['test']], names=['idx1','idx2'])
df = pd.DataFrame({'A':pd.Series([1], dtype='str', index=mux),
                   'B':pd.Series([4], dtype='int', index=mux),
                   'C':pd.Series([7], dtype='float', index=mux)})

print(df)

           A  B    C
idx1 idx2
0    test  1  4  7.0


text:
Q: Query Results caching using Java : Any better Approaches? I have a class ClassA which calls another class(DAO) to fetch the query results. In a specific business scenario,
ClassA invokes the DAO with queryparameters about 20,000 times.
Out of this, about 10,000 times ClassA sends same set of query parameters to DAO. Obviously Resultset will be the same and can be cached.
The following is the code I implemented.
Class A

{

.
.
.
.

Map<String, CachData> cachDataMap= new HashMap<String, CachData>();

priavate void getQueryResults(String queryParam)
{

try {

            Set<String> cacheSet = cachDataMap.keySet();
            CachData cachData = null;
            if(!cacheSet.contains(queryParam))
            {
                dao.getResuslts((queryParam)));
                cachData = new CachData();
                cachData.setResult0(__getStringResult(0));
                cachData.setResult1(__getStringResult(1));
                cachData.setResult2(__getStringResult(2));
                cachData.setResult3(__getStringResult(3));
                cachData.setResult4(__getStringResult(4));
                cachData.setResult5(__getStringResult(5));
                cachDataMap.put(queryParam, cachData);
            }else
            {
                cachData = cachDataMap.get(queryParam);
            }

        } catch(Exception e) {
            //handle here
        }

}

Do we have anyother better solution other than using any framework? A better datastructure or better method.. For good performance?

A: You could use ehcache.
Whatever you do don't use a Map as your interface for a cache. A good cache interface would allow the implementation to do cleanup of the cache. The Map contract won't allow this.
Depending on the implementation, cleanup can be based on time in the cache, or based on usage statistics, or memory availability, ...
The Map approach you're using here seems prone to go out of memory over a longer period of usage.

A: You could use the Table from guava library and use ehCache to save the object as it is with the key being the query.


text:
Q: Change to a "parallel" directory in a single instruction I would like to move directly from the "Classwork" directory into the "Assembly" directory with a single command line instruction. If possible, I would like to use relative paths to do this:

I would venture to guess that there is a simple command to accomplish this, but I am not familiar with the terminology. It's possible that I don't know how to phrase this question correctly, hence my inability to find a pre-existing answer.
Apologies if I am duplicating a question and any help would be appreciated!

A: This should do it:
cd ..\Assembly

.. means move up one so it would put you in the parent Documents directory and then get you into Assembly


text:
Q: Scala interning: how does different initialisation affect comparison? I am new to Scala but I know Java. Thus, as far as I understand, the difference is that == in Scala acts as .equals in Java, which means we are looking for the value; and eq in Scala acts as == in Java, which means we are looking for the reference address and not value.
However, after running the code below:
    val greet_one_v1 = "Hello"
    val greet_two_v1 = "Hello"
    println(
            (greet_one_v1 == greet_two_v1),
            (greet_one_v1 eq greet_two_v1)
    )

    val greet_one_v2 = new String("Hello")
    val greet_two_v2 = new String("Hello")
    println(
            (greet_one_v2 == greet_two_v2),
            (greet_one_v2 eq greet_two_v2)
    )

I get the following output:
(true,true)
(true,false)

My theory is that the initialisation of these strings differs. Hence, how is val greet_one_v1 = "Hello" different from val greet_one_v2 = new String("Hello")? Or, if my theory is incorrect, why do I have different outputs?

A: As correctly answered by Luis Miguel Mejía Suárez, the answer lies in String Interning which is part of what JVM (Java Virtual Machine) does automatically. To initiate a new String it needs to be initiated explicitly like in my example above; otherwise, Java will allocate the same memory for same values for optimisation reasons.


text:
Q: SWIFT signal SIGABRT error thread1 I am trying to code a simple app where you input 2 numbers in textfields and return the sum of them in iOS app. The problem is that I am getting Thread 1 signal SIGABRT error and I can't seem to find any fix for this.
This is the code:
@IBOutlet var result: UILabel!

@IBOutlet var firstnum: UITextField!
@IBOutlet var secondnum: UITextField!

@IBAction func add (sender: UIButton) {

    var a = firstnum.text.toInt();
    var b = secondnum.text.toInt();

    var c = a!+b!;

    result.text = "\(c)";

}

A: You should check your connections; if you have a label, textfield, etc connected from the main storyboard to the view controller, check to see if your label in Main.storyboard is linked to it by opening the right side panel and selecting the last bar. It will show you all the outlets that label has.
This occurs when you make a connection from the Main.storyboard to the ViewController.swift, and you remove the text in the ViewController.swift, but you do not remove the connection.
For more information, watch this video:
iOS Programming: How to fix thread 1 signal sigabrt in xcode 6
I hope this helps.


text:
Q: How to open modal bootstrap on checkbox click? I've a custom checkbox. What I want is to to open a bootstrap modal when the checkbox is checked. I want a bootstrap modal to open just as when clicked a button. Hope you understood my question. How can I do it.

    <input class="form-check-input" type="checkbox" name="toddlers" id="toddlers">
    toddlers

Modal title

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

                ...

                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>

A: Please checkout this code.  You had used same id id="toddlers" for the input box as well as for model.
<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">

    <input class="" type="checkbox" name="toddlers" id="toddlers">
    toddlers

Modal title

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

                ...

                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>


text:
Q: How to get data from an url? I want to use python to get the data from "https://jobs.51job.com/jinan-gxq/139057256.html?s=gsxq_zwlb_gsxqlb&t=17"
I expect to get data like below but I get a script.
Here is my code:
import requests
url = 'https://jobs.51job.com/jinan-gxq/139057256.html?s=gsxq_zwlb_gsxqlb&t=17'
res = requests.get(url)
print(res.text)

The output is:
'<html><script>\nvar arg1=\'6C00B31D29AE4156FC48C6823C7476185B28DB15\';\nvar _0x4818=[\'\\x63\\x73\\x4b\\x48\\x77\\x71\\x4d\\x49\',\'\\x5a\\x73\\x4b\\x4a\\x77\\x72\\x38\\x56\\x65\\x41\\x73\\x79\',\'\\x55\\x63\\x4b\\x69\\x4e\\x38\\x4f\\x2f\\x77\\x70\\x6c\\x77\\x4d\\x41\\x3d\\x3d\',\'\\x4a\\x52\\x38\\x43\\x54\\x67\\x3d\\x3d\',\'\\x59\\x73\\x4f\\x6e\\x62\\x53\\x45\\x51\\x77\\x37\\x6f\\x7a\\x77\\x71\\x5a\\x4b\\x65\\x73\\x4b\\x55\\x77\\x37\\x6b\\x77\\x58\\x38\\x4f\\x52\\x49\\x51\\x3d\\x3d\',\'\\x77\\x37\\x6f\\x56\

How can I get the data?


text:
Q: Enable Phone Call in ListView After lot of research over internet i could not find a answer how to enable a phone call in a list view.
here is my sample code:
Suppose i have a list of 50 hospital with there phone contact detail
public class Medical extends ListActivity {

static final ArrayList<HashMap<String,String>> list =
    new ArrayList<HashMap<String,String>>();

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.bus_main);
    SimpleAdapter adapter = new SimpleAdapter(
        this,
        list,
        R.layout.rowview,
        new String[] {"title","address","phone"},
        new int[] {R.id.text1,R.id.text2, R.id.text3}
    );
    populateList();
    setListAdapter(adapter);

}

private void populateList() {
    HashMap<String,String>
    map = new HashMap<String,String>();
    map.put("title","UHS Hospital");
    map.put("address", "Street 54");
    map.put("phone", "4077000");
    list.add(map);
    map = new HashMap<String,String>();
    map.put("title","Calvary Hospital");
    map.put("address", "Street 43");
    map.put("phone", "2362491");
    list.add(map);
}
}

How to enable phone call to all listview entry based on individual Phone number detail (text3) of a hospital.

A: add this method in your activity:
public class Medical extends ListActivity {

static final ArrayList<HashMap<String,String>> list =
        new ArrayList<HashMap<String,String>>();

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        SimpleAdapter adapter = new SimpleAdapter(
            this,
            list,
            R.layout.rowview,
            new String[] {"title","address","phone"},
            new int[] {R.id.textView1,R.id.textView2, R.id.textView3}
        );
        populateList();
        setListAdapter(adapter);

    }
    protected void onListItemClick (ListView l, View v, int position, long id){
        super.onListItemClick(l,v,position,id);
        if(position>=0 && position<list.size()) {
            HashMap<String, String> tmp = list.get(position);
            if(tmp.containsKey("phone")) {
                String tel = tmp.get("phone");
                Intent callIntent = new Intent(Intent.ACTION_CALL);
                callIntent.setData(Uri.parse("tel:"+tel));
                startActivity(callIntent);
            }
        }
    }
    private void populateList() {
        HashMap<String,String>
        map = new HashMap<String,String>();
        map.put("title","UHS Hospital");
        map.put("address", "Street 54");
        map.put("phone", "4077000");
        list.add(map);
        map = new HashMap<String,String>();
        map.put("title","Calvary Hospital");
        map.put("address", "Street 43");
        map.put("phone", "2362491");
        list.add(map);
    }

  }

and add
<uses-permission android:name="android.permission.CALL_PHONE" />

in your manifest
Attention This code does not check if the number is valid.


text:
Q: In HTML I can make a checkmark with ✓ . Is there a corresponding X-mark? Is there a corresponding X mark to ✓ (✓)? What is it?

A: I think this will help everyone.
All codes are taken from here - https://www.toptal.com/designers/htmlarrows/symbols/
✗
✗

✘
✘

✕
✕

✖
✖

✓
✓

✔
✔

☑
☑

A: Personally, I like to use named entities when they are available, because they make my HTML more readable. Because of that, I like to use ✓ for ✓ and ✗ for ✗. If you're not sure whether a named entity exists for the character you want, try the &what search site. It includes the name for each entity, if there is one.
As mentioned in the comments, ✓ and ✗ are not supported in HTML4, so you may be better off using the more cryptic ✓ and ✗ if you want to target the most browsers. The most definitive references I could find were on the W3C site: HTML4 and HTML5.

A: A corresponding cross for ✓ ✓ would be ✗ ✗ I think (Dingbats).

A: It's between the Z and the C on your keyboard.

A: ✗
✗

✘
✘

✕
✕

✖
✖


text:
Q: Can I get the media loaded in an  element as a blob (or ArrayBuffer)? I need to get the same media that is loaded in a HTML5 media player into an AudioContext. Can I somehow grab it from the media player (or do I have to download it again)?
Note: The media player does not have to be playing, but I know that all of the media has been loaded.

A: To get the same file, you'd need to fetch it again (using fetch or XHR), but if your server is well configured, you may not need to download it again no, it should be cached.
Note that if you need to connect your HTMLMediaElement to the AudioContext (so that its audio output goes through the AudioContext's graph), then you can use either HTMLMediaElement.captureStream() + AudioContext.createMediaStreamSource(), or AudioContext.createMediaElementSource().


text:
Q: C# check if directory exists in azure storage I am trying to see if a directory exists within azure data storage. This is how I am initializing the service client:
 private void InitializeServiceClient(IndesignExportConfiguration exportConfig, String rootContainer)
        {//"UseDevelopmentStorage=true"
            serviceClient = new BlobServiceClient(exportConfig.BlobConnectionString);
            flyersContainerClient = serviceClient.GetBlobContainerClient(rootContainer.ToLower());
        }

And this is where I am trying to see if the directory exists:
     var rootContainerName = dealNo + "/";
            _flyerId = flyerId;
            var blobClient = flyersContainerClient.GetBlobClient(rootContainerName);

            if (blobClient.Exists())
            {
                await ListBlobsForPrefixRecursive(flyersContainerClient, rootContainerName, 1);
            }
            else
            {
                InitializeServiceClient(_exportConfig, _exportConfig.SecondaryRootContainer);
                await ListBlobsForPrefixRecursive(flyersContainerClient, rootContainerName, 1);
            }

So far I have asked another question on stackoverflow and I was told that because the directory is virtual my blobclient.exists if statement wont work. I then looked into using the following:
var blobDirectory = flyersContainerClient.GetBlobDirectoryReference("Path_to_dir");
bool directoryExists = blobDirectory.ListBlobs().Count() > 0

and this:
bool directoryExists = flyersContainerClient.ListBlobsWithPrefix("DirectoryA/DirectoryB/").Count() > 0

Unforutnately the methods GetBlobDirectoryReference and ListBlobsWithPrefix dont seem to exist. I can't seem to figure out what I am doing wrong, or which assembly reference  I am missing. Any help would be appreciated.


text:
Q: Close TCP port 80 and 443 after forking in Django I am trying to fork() and exec() a new python script process from within a Django app that is running in apache2/WSGI Python.  The new python process is daemonized so that it doesn't hold any association to apache2, but I know the HTTP ports are still open.  The new process kills apache2, but as a result the new python process now holds port 80 and 443 open, and I don't want this.
How do I close port 80 and 443 from within the new python process?  Is there a way to gain access to the socket handle descriptors so they can be closed?

A: If you use the subprocess module to execute the script, the close_fds argument to the Popen constructor will probably do what you want:

If close_fds is true, all file descriptors except 0, 1 and 2 will be closed before the child process is executed.

Assuming they weren't simply closed, the first three file descriptors are traditionally stdin, stdout and stderr, so the listening sockets in the Django application will be among those closed in the child process.


text:
Q: How many different arrays can we get by replacing the two adjacent elements from the array with their sum? We have an array A with N elements.
At any time, we can pick two adjacent elements of the array and replace them with their sum, thus getting a new array. We repeat the same operation as many times as we want.
My question is, how many different arrays can we get, by aplying this operation any number of times?

A: Are you sure that zeros and negatives are allowed? If only positive numbers are allowed, than result is simple :-)
If list has n elements, than there are n-1 commas between pairs element pairs. Every new array is produced by changing some of commas with plus sing. With that we see there are 2^(n-1) different arrays.
I think that with zeros it is possible to reduce problem to same sub-problem by working with left and right sub-arrays from zero(s). That is some recurrence, but I didn't figure it out yet :-/
With negative allowed it is much more complicated.


text:
Q: limit of $2n$-th root of $2n$-th central binomial coefficient -- $\lim_{n\to \infty}{2n \choose n}^{\frac{1}{2n}}$ $\lim_{n\to \infty}{2n \choose n}^{\frac{1}{2n}} = 2$ according to wolframalpha.
Does anyone see how to get this limit of $2$? Is it a numerical estimate or analytically exact?

A: Since $\binom{2n}{n}$ is the largest element among all $\binom{2n}{k}$ and $\sum\limits_{k=0}^{2n} \binom{2n}{k} = 2^{2n}$, we have
$$\frac{2^{2n}}{2n+1} \le \binom{2n}{n} \le 2^{2n}
\quad\implies\quad
2 \left(\frac{1}{2n+1}\right)^{1/2n} \le \binom{2n}{n}^{1/2n} \le 2$$
Since $\left(\frac{1}{2n+1}\right)^{1/2n} \to 1$ as $n \to \infty$, we have $\binom{2n}{n}^{1/2n} \to 2$ as $n \to \infty$.

A: It follows from Stirling's formula, which implies the well-known asymptotic for central binomial coefficients $\binom{2n}{n}\sim \frac{4^n}{\sqrt{\pi n}}$. Then
$$\binom{2n}{n}^{\frac{1}{2n}} \sim \left(\frac{4^n}{\sqrt{\pi n}}\right)^{1/(2n)} = 2\cdot (\pi n)^{-\frac{1}{4n}}\rightarrow 2$$
as $n\rightarrow\infty$.


text:
Q: Python 3 IndentationError In spite of seeing a lot of posts about the python indentation error and trying out a lot of solutions, I still get this error:
import random
import copy
import sys
the_board = [" "]*10
def printboard(board):
    print(board[7] + " " + "|" + board[8] + " " + "|" + board[9])
    print("--------")
    print(board[4] + " " + "|" + board[5] + " " + "|" + board[6])
    print("--------")
    print(board[1] + " " + "|" + board[2] + " " + "|" + board[3])

def choose_player():
    while True:
        player = input("What do you want to be; X or O?")
        if player == "X":
            print("You chose X")
            comp = "O"
            break
        elif player == "O":
            print("You chose O")
            comp = "X"
            break
        else:
            print("Invalid Selection")
            continue
    return [player, comp]

def virtual_toss():
    print("Tossing to see who goes first.....")
    x = random.randint(0,1)
    if x== 0:
        print("AI goes first")
        move = "comp"
    if x == 1:
        print("Human goes first")
        move = "hum"
    return move
def win(board,le):
    if (board[7] == le and board[8] == le and board[9]==le) or (board[4] == le and board[5]==le and board[6] == le)or (board[1] == le and board[2]==le and board[3] == le)or (board[7] == le and board[5]==le and board[3] == le)or (board[9] == le and board[5]==le and board[1] == le)or (board[7] == le and board[4]==le and board[1] == le)or (board[8] == le and board[5]==le and board[2] == le)or (board[9] == le and board[6]==le and board[3] == le):
        return True
    else:
        return False
def make_move(board,number,symbol):
     board[number] = symbol
def board_full(board):
    count = 0
    for item in board:
        if item in ["X","O"]:
            count+= 1
    if count ==9 :
        return True
    else:
        return False
def valid_move(board,num):
    if board[num] == " ":
        return True
    else:
        return False
def player_move(board):
    number = int(input("Enter the number"))
    return number
def copy_board(board):
    copied_board = copy.copy(board)
    return copied_board
def check_corner(board):
    if (board[7] == " ") or (board[9] == " ") or (board[1] == " ") or (board[3] == " "):
        return True
    else:
        return False
def check_center(board):
    if (board[5] == " "):
        return True
    else:
        return False

while True:
    count = 0
    loop_break = 0
    print("welcome to TIC TAC TOE")
    pla,comp = choose_player()
    turn = virtual_toss()
    while True:
        printboard(the_board)
        if turn == "hum":
            if board_full() == True:
                again = input ("Game is a tie. Want to try again? Y for yes and N for No")
                if again == "Y":
                    loop_break = 6
                    break
                else:
                    system.exit()
    if loop_break == 6:
        continue

        while True:
                number = player_move(the_board)
                if (valid_move(the_board,number) == True) and not(board_full == False):
                    make_move(the_board,number,pla)
                    break
                else:
                    print("Invalid Move, try again!")
                    continue
             if (win(the_board,pla) == True):
                print ("Yay, you won!!!")
                printboard(the_board)
                count = 1
                break
            else:
                turn = "comp"
                printboard(the_board)
                continue

        else:
            if board_full() == True:
                again = input ("Game is a tie. Want to try again? Y for yes and N for No")
                if again == "Y":
                    loop_break = 6
                    break
                else:
                    system.exit()
    if loop_break = 6:
        continue
            copy_board(the_board)
                for i in range(0,9):
                    make_move(copied_board,i,pla)
                    if(win(copied_board,pla) == True):
                        make_move(the_board,comp)
                        turn = "hum"
                        loop_break = 1
                        break
                    else:
                        continue
                if loop_break = 1:
                    continue
                if (check_corner(the_board) == True) or (check_center(the_board)==True):
                    for i in [7,9,1,3,5]:
                        if(valid_move(copied_board,i)==True):
                            make_move(copied_board,i,comp)
                            if(win(copied_board,comp)==True):
                                make_move(the_board,i,comp)
                                print("The AI beat you")
                                loop_break = 2
                                count = 1
                                break
                            else:
                                make_move(the_board,i,comp)
                                turn = "hum"
                                loop_break = 3
                                break
                if loop_break == 2:
                    break
                elif loop_break == 3:
                    continue
                else:
                    for i in [8,4,6,2]:
                        if(valid_move(copied_board,i)==True):
                            make_move(copied_board,i,comp)
                            if(win(copied_board,comp)):
                                make_move(the_board,i,comp)
                                print("The AI beat you")
                                count = 1
                                loop_break = 4
                                break
                            else:
                                make_move(the_board,i,comp)
                                turn = "hum"
                                loop_break = 5
                                break
                if loop_break == 4:
                    break
                elif loop_break == 5:
                    continue

    if count == 1:
        again = input("Would you like to play again? y/n")
        if again == "y":
            continue
        else:
            system.exit()

I know that this is quite a long code, but I will point out the particular area where the error lies. You see, I am getting the following error message:
    Traceback (most recent call last):
  File "python", line 106
    if (win(the_board,pla) == True):
                                   ^
IndentationError: unindent does not match any outer indentation level

More specifically, this part of the code:
while True:
                number = player_move(the_board)
                if (valid_move(the_board,number) == True) and not(board_full == False):
                    make_move(the_board,number,pla)
                    break
                else:
                    print("Invalid Move, try again!")
                    continue
             if (win(the_board,pla) == True):
                print ("Yay, you won!!!")
                printboard(the_board)
                count = 1
                break

Any help? I cannot get the code to work by any means!!

A: Try unindenting the previous seven lines of code by one level (the code in that while loop). This should make the indents work correctly. Also, it seems that there is an extra space before the if statement that is causing you errors. Remove this space as well. This would make that part of the code like this:
while True:
        number = player_move(the_board)
        if (valid_move(the_board,number) == True) and not(board_full == False):
            make_move(the_board,number,pla)
            break
        else:
            print("Invalid Move, try again!")
            continue
        if (win(the_board,pla) == True):
            print ("Yay, you won!!!")
            printboard(the_board)
            count = 1
            break

A: You need to indent the block under while (True): consistently. E.g.:
while True:
    number = player_move(the_board)
    if (valid_move(the_board,number) == True) and not(board_full == False):
        make_move(the_board,number,pla)
        break
    else:
        print("Invalid Move, try again!")
            continue

    if (win(the_board,pla) == True):
        print ("Yay, you won!!!")
        printboard(the_board)
        count = 1
        break
    else:
        turn = "comp"
        printboard(the_board)
        continue

A: The problem is, the if statement is one indentation back from the rest of the code. You want to align all the code and the error should go away.
while True:
     number = player_move(the_board)
     if (valid_move(the_board,number) == True) and not(board_full == False):
         make_move(the_board,number,pla)
         break
     else:
        print("Invalid Move, try again!")
        continue
     if (win(the_board,pla) == True):
        print ("Yay, you won!!!")
        printboard(the_board)
        count = 1
        break


text:
Q: mapping of composite nested key I am working with legacy database with nhibernate (but assume the solution will be very similar as in hibernate) and we have nested composite keys, what I mean is following, our keys have this structure (this is pseudo c# syntax):
class PartnerKey
{
Public Int PartnerNr
}
Class TaxArtKey
{
Public String TaxArt
}
Class PartnerTaxArtKey
{
Public TaxArtKey TaxArt;
Public PartnerKey Partner;
}

by using composite-id i can do mpaping for first level of the keys but is it possible to it for other levels such us PartnerTaxArtKey.
thanks
almir

A: You probably can try to use key-many-to-one mapping.


text:
Q: How to differentiate the electric field on the surface of a conductor? Given a conductor, let $n$ be the unit normal field of the surface and $E$ the magnitude of the electric field. How to understand the expression
$$\frac{\partial E}{\partial n}$$
on the surface of the conductor? The usual meaning of such an expression would be "the directional derivative of $E$ in direction $n$". However, if I understand things correctly, the electric field is in general not differentiable at points on the surface of a conductor (at least not differentiable in the sense of classical differential calculus). So, what does this expression mean? What is the definition?
Background: This expression appears in exercise 1.11 of Jackson's $\textit{Classical Electrodynamics}$ from chapter 1 and I am trying to work on it. However, I am NOT asking for a solution of that exercise.
My ideas so far: The expression could make sense in differential geometry if we view the surface as a 2 dimensional manifold and then differentiate in local coordinates. Another idea might be something like "distributional derivative". Both ideas are just speculations and it might happen that the meaning is still something completely different...

A: Diffycue's comment has the right idea. Yes, the E-field is discontinuous at the surface, but we may formally express the E-field just outside point $\vec r$ on the surface of the conductor as
$$\vec E_s(\vec r)= \lim_{h\rightarrow{0^+}}\vec E(\vec r+h\hat n)$$
where $\hat n$ is the outward unit normal vector. Then,
$$ \frac{\partial E}{\partial n} = \hat n\cdot\lim_{h\rightarrow{0^+}}\frac{\vec E(\vec r+h\hat n) -\vec E_s(\vec r)}{h}. $$


text:
Q: Difference between the classes System.StringComparer and System.StringComparison? What is the difference between these two classes ?
I have used System.StringComparer.OrdinalIgnoreCase() and System.StringComparison.OrdinalIgnoreCase() and both yield the same results. Do they have any difference or they both same ?

A: The question is: why to have in a framework both of them ?
The explanation is this one:

*

*StringComparison is:

Specifies the culture, case, and sort rules to be used by certain
  overloads of the String.Compare and String.Equals methods

*

*StringComparer is:

Represents a string comparison operation that uses specific case and
  culture-based or ordinal comparison rules

Noticed a difference ?
In second case, so in case of StringComparer there is a notion of string comparison operation, but not string type.
In fact, if you look at this you will read simply:

Some non-string methods that have string comparison as a central
  operation use the StringComparer type.

An example, from the same link:
Array.BinarySearch(this.storedNames, name, StringComparer.Ordinal)

I use StringComparer like a comparison "base" among content of the array reference type.

A: StringComparer is a Class which implements comparison interfaces like IComparer, IEqualityComparer, IComparer<String>, so that it can be used to compare two strings.
StringComparison is simply an Enum that you can pass in to certain methods to indicate which kind of comparison you want. In that case I suspect the underlying method would use a StringComparer to do the actual comparison.
When to use each
String specific methods like String.Equals only accepts a StringComparison value, so that's what you would use in this case.
You would use a StringComparer for methods which take a comparer as a parameter, and are called in a context where strings will be compared. For example, if you had a List<String>, and wanted to Sort that list in a case-insensitive way, you could do:
myList.Sort(StringComparer.OrdinalIgnoreCase);


text:
Q: How do you architect complex Rails systems We have the following systems (and more) that we push/pull data from one app to another:

*

*Hosted CRM (InsideSales.com)

*Asterisk phone system (internal)

*Banner ad system (openx, we host)

*A lead generation system (homegrown)

*Ecommerce store (spree, we host)

*A job board (homegrown)

*A number of job site scrapes + inbound job feeds

*An email delivery system (like Mailchimp, homegrown)

*An event management system (like eventbrite, homegrown)

*A dashboard system (lots of charts and reports pulling info from all other systems)

With Rails 3 around the corner, I really want to pursue a micro-app strategy, but I'm trying to decide if I should have the apps talk via REST HTTP API or because I control them all, should I do something like shared models in the code which simplifies but also allows for stuff to leak across boundries much easier...
I've heard 37signals has lots of small apps, I'm curious how those apps communicate with each other... Or if you have any advice from your own multi-app experience.
Thanks! I tried asking this on my blog http://rywalker.com/chaos-2010 too a while back.

A: I actually got an email response from DHH...

We use a combination of both, but we default to REST integration. The only place where we use direct database integration is with 37signals ID user database. Because it needs to be so fast. REST is much more sane. Start there, then optimize later if need be.

A: Last time I had to crazy-glue a bunch of small applications together, I used a simple REST API.
Bonus points: it allows for integration with services / apps written in other languages.
Also helps if you've got a crazy buzz-word loving manager who likes to pivot technologies without warning.

A: i had the same with a plus: I had to talk as well with some daemons that were not exactly HTTP ready. So i followed the following pattern:
REST API using XML/JSON to exchange data and using memcache to exchange short messages. (you define some keys that you will update in memcache and the other piece of software, just pull memcache looking for those keys)
as security measure i added API KEY or HTTP client authentication using digital certificate.

A: Another option is AMQP messaging (via rabbitmq or other means).


text:
Q: Type lost when exporting object on baseDir import I have a file named constants.ts which contains constants related to my React TypeScript application.
The file looks like this:
// The error for when errors are bad.
const BAD_ERROR_ERROR = "Something happened that shouldn't have. Please contact an admin";

const Constants = {
    APIResponses: {
        accounts: {
            login: {
                account_not_verified: {
                    message: "You need to verify your email",
                    problemFields: ["email"]
                },
                bad_login: {
                    message: "Your email or password is incorrect",
                    problemFields: ["email", "password"]
                },
                default: {
                    message: BAD_ERROR_ERROR,
                    problemFields: ["email", "passwords"]
                }
            }
        }
    }
};

export default Constants;

I then import it in a TSX file like this:
import Constants from "constants";

and reference a key like this:
        const { status } = json;
        const resp = Constants.APIResponses.accounts.login[status.message];

However, when I attempt to use it, I get this error:
Property 'APIResponses' does not exist on type 'typeof import("constants")'.  TS2339

    69 |
    70 |         const { status } = json;
  > 71 |         const resp = Constants.APIResponses.accounts.login[status.message];

This error only occurs when importing it from my baseDir as "constants", when importing as ../../constants, it works fine. (That's the work around I'm going with right now)
Here's the things I've tried that haven't worked:

*

*Explicitly defining a type for Constants in constants.ts

*Renaming it to constants.js

*Casting the type on the default export

*Not exporting it as default

Here's the hacky fixes I found that work, but are hacky and undesirable:

*

*Importing it relatively (../../constants) (current)

*Casting it to an any type ((Constants as any).APIResponses...)

Here's my tsconfig.json:
{
  "compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "react",
    "rootDir": "./src",
    "baseUrl": "./src"
  },
  "include": [
    "src"
  ]
}


text:
Q: How can I add autosave to a Note App with entities? I want to learn how to make android apps so I followed a tutorial series on YouTube and I made a Note App. But I need to add autosave and I don't know how. I searched on YouTube and I tried everything and nothing works.
Here is the Playlist with the tutorials:
https://youtube.com/playlist?list=PLam6bY5NszYN6-a1wt7yRISWfmYPdkbMu
As I said before, I'm new to all of this, but I really want to make this app.

A: you can use "periodic work request" to auto-save your notes.
you can use this tutorial or other tutorial
enter link description here


text:
Q: jQuery, displaying the text inside an input if the input text has more than two characters works more than once. (Every two characters) I have a jQuery function that I want to be executed when a text input field has more than two characters:
$('#textInput').on('input', displaySuggestions);

function displaySuggestions(){
    if($('#textInput')[0].value.length > 2){
        let searchValue = $('#textInput')[0].value;
        $.myObj.getResults( searchValue, (results) => {
          console.log(results);
      });
    }
}

The function works good if I don't use the getResults function, which I need. It is from a plugin that looks like this:
(function($) {

    $.myObj = {

        getResults: function(value, callBack){
            var req = $.ajax({
                url:'http://api.my/api/name' + value
            });

             req.done(callBack);
        }
    };

}(jQuery));

The function should log the results which is  JSON data from the api call. It should return the results only once, when there are more than two characters added in the text input field. However when using the getResults function, the results are logged every two characters, for example, If I write a word with six letters, the results will be logged 3 times. I am not allowed to make changes in the getResults function, but if there is no fix around it, I would consider. Not sure how to wrap my head around it. Thanks in advance!

A: If you want to return the results only once ever then use the corresponding off method to remove the handler.
function displaySuggestions(){
    if ($('#textInput')[0].value.length > 2) {
        let searchValue = $('#textInput')[0].value;
        $.myObj.getResults( searchValue, (results) => {
          console.log(results);
      });
      $('#textInput').off('input', displaySuggestions);
    }
}

If you want to call the results each time the input exceeds 2 characters (e.g. user deletes input and retypes), then add a guard around the getResults() call.
let displayResults = true;
function displaySuggestions() {
    let searchValue = $('#textInput')[0].value;
    if (displayResults) {
        if (searchValue.length > 2) {
            displayResults= false;
            $.myObj.getResults( searchValue, (results) => {
                console.log(results);
            });
        }
    } else if (searchValue.length < 2) {
        displayResults = true;
    }
}


text:
Q: Optional in MatchQ Why isn't the first one True in:
MatchQ[{1}, Optional[{__Integer}, {2}]]
MatchQ[{1}, Optional[{_Integer}, {2}]]
MatchQ[{1}, {__Integer}]

False
True
True

or in:
MatchQ[{1}, p : {__Integer} : {2}]
MatchQ[{1}, p : {_Integer} : {2}]
MatchQ[{1}, p : {__Integer}]

False
True
True

p:v is a pattern object that represents an expression of the form p, which, if omitted, should be replaced by v.

So my guess was that
MatchQ[{1}, Optional[{__Integer}, {2}]]

should be equivalent to:
MatchQ[{1}, {__Integer}]

And even if you can explain that, why are middle examples True?


text:
Q: Python program to calculate average quiz grade for students Ok, it I don't understand where I am going wrong because I had help with this coding and for the person who originally wrote it, it works just fine. However, mine seems to be malfunctioning. It keeps displaying the 'highest grade' multiple times instead of just once like it's supposed to. Having some real newbie problems here.
This is the code:
#this program will compute average quiz grade for a group of 5 students
#prompt user for quiz grade using a for loop for each of the 5 students

#assign names to student list
students = ["John", "Jake", "Jane", "Sally", "Susie"]

#grades: 90-100=A, 80-90=B, 70-80=C, 60-70=D, <60=F

#prompt user for student grades
grades = []
for student in students:
    grade = eval(input(f"Enter the grade for {student}: "))
    grades.append(grade)

sum = 0
for i in range(0,5):
    for i in grades:
         sum+=i
avg_grade=sum/5

#print average grade of students
if(avg_grade >=90):
    print("Average Grade: A")
elif(avg_grade>=80 and avg_grade<90):
    print("Average Grade: B")
elif(avg_grade>=70 and avg_grade<80):
    print("Average Grade: C")
elif(avg_grade>=60 and avg_grade<70):
    print("Average Grade: D")
else:
    print("Average Grade: F")

#print highest grade
max_grade=max(grades)
for i in grades:
    if(max_grade>=90):
        print("Highest Grade: A")
    elif(max_grade>=80 & max_grade<90):
        print("Highest Grade: B")
    elif(max_grade>=70 & max_grade<80):
        print("Highest Grade: C")
    elif(max_grade>=60 & max_grade<70):
        print("Highest Grade: D")
else:
    print("Highest Grade: F")

A: You are using a for loop at the end, which means for every single grade, the highest grade will be printed out.
You can delete the for, and unindent the if, elif, and else statements. Then the program should work as intended.

A: First of all, instead of using a variable such as sum, because sum is a python special function, you should use something like total.
Second, you shouldn't be using eval(input()) because the eval does nothing.
Third, when doing the for loop, you don't already know the number of students so it should be for i in range(len(students)-1) and the -1 part because list indexing starts at 0. Also, the second for loop should use a different variable then i because i is already used, so use something like j.

A: Use just sum to get the total grade and average value. Don't need to run an additional loop for 5 times.
total = sum(grades)
avg_grade = total/len(grades)

Then you don't need to run a loop to get the highest grade and also else should be indented with like other if elif. Follow the code
students = ["John", "Jake", "Jane", "Sally", "Susie"]

grades = []
for student in students:
    grade = eval(input(f"Enter the grade for {student}: "))
    grades.append(grade)

total = sum(grades)
avg_grade = total/len(grades)

if(avg_grade >= 90):
    print("Average Grade: A")
elif(avg_grade >= 80 and avg_grade < 90):
    print("Average Grade: B")
elif(avg_grade >= 70 and avg_grade < 80):
    print("Average Grade: C")
elif(avg_grade >= 60 and avg_grade < 70):
    print("Average Grade: D")
else:
    print("Average Grade: F")

max_grade = max(grades)
if(max_grade >= 90):
    print("Highest Grade: A")
elif(max_grade >= 80 & max_grade < 90):
    print("Highest Grade: B")
elif(max_grade >= 70 & max_grade < 80):
    print("Highest Grade: C")
elif(max_grade >= 60 & max_grade < 70):
    print("Highest Grade: D")
else:
    print("Highest Grade: F")

A:
sum = 0
for i in range(0,5):
    for i in grades:
         sum+=i
avg_grade=sum/5

what that does is essentially go through every grade and increment sum every time and do that 5 times. It's unnecessarily O(n^2) and will run significantly slower when you add a lot of data.
Other than that a couple of useful things were pointed out by the other answers, I think one of them directly put the code there too so there isn't much I can say.
Basically you had logical flaws in your code that caused it to not function as intended.
debugging:

as you can see above the values for sum and avg_grade are totally not what they're intended to be, this was uncovered using print statements in the right places.
Your logic in implementation was flawed for the next part too, but this post is already too wordy for it's purpose.


text:
Q: Spring Integration application deployment fails when deploy war to weblogic version (weblogic 12.2.1.3) Application runs fine on IDE as well as when I run it as jar
Exception occurs when I deploy the application on weblogic server.
I have even tried to exclude spring-starter-json and replace it with gson but I get the same issue.
Here is the stacktrace

weblogic.application.ModuleException: java.lang.VerifyError: Bad return type

Exception Details:
  Location:
    com/fasterxml/jackson/databind/cfg/MapperBuilder.streamFactory()Lcom/fasterxml/jackson/core/TokenStreamFactory; @7: areturn
:
    Type 'com/fasterxml/jackson/core/JsonFactory' (current frame, stack[0]) is not assignable to 'com/fasterxml/jackson/core/TokenStreamFactory' (from method signature)

  Current Frame:
    bci: @7
    flags: { }
    locals: { 'com/fasterxml/jackson/databind/cfg/MapperBuilder' }
    stack: { 'com/fasterxml/jackson/core/JsonFactory' }

  Bytecode:
    0x0000000: 2ab4 0002 b600 08b0
    at weblogic.application.internal.ExtensibleModuleWrapper.start(ExtensibleModuleWrapper.java:140)
    at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:124)
    at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:233)
    at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:228)
    at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
    Truncated. see log file for complete stacktrace

A: I have found a solution from reading this article (https://o7planning.org/11901/deploy-spring-boot-application-on-oracle-weblogic-server) , It seems weblogic loads some library (com.fastxml.*) which are outdated and are incompactible with current version of spring boot.


text:
Q: How does the transpose of high-dimensional arrays work? It's easy to understand the concept of Transpose in 2-D array. I reall can not understand  How  the transpose of high-dimensional arrays works.
For example
c = np.indices([4,5]).T.reshape(20,1,2)
d = np.indices([4,5]).reshape(20,1,2)
np.all(c==d) # output is False

Why are the outputs of C and D inconsistent?

A: In [143]: c = np.indices([4,5])
In [144]: c
Out[144]:
array([[[0, 0, 0, 0, 0],
        [1, 1, 1, 1, 1],
        [2, 2, 2, 2, 2],
        [3, 3, 3, 3, 3]],

       [[0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4],
        [0, 1, 2, 3, 4]]])

In [145]: c.shape
Out[145]: (2, 4, 5)

In [146]: c.T.shape
Out[146]: (5, 4, 2)

Look at one 2d array from the size 2 dimension:
In [150]: c[0,:,:]
Out[150]:
array([[0, 0, 0, 0, 0],
       [1, 1, 1, 1, 1],
       [2, 2, 2, 2, 2],
       [3, 3, 3, 3, 3]])

In [151]: c.T[:,:,0]
Out[151]:
array([[0, 1, 2, 3],
       [0, 1, 2, 3],
       [0, 1, 2, 3],
       [0, 1, 2, 3],
       [0, 1, 2, 3]])

The 2nd is the usual 2d transpose, a (5,4) array.
MATLAB doesn't do transpose on 3d arrays, at least it doesn't call it such.  It may have a way making such a change.  numpy, using a general shape/strides multidimensional implementation, easily generalizes the 2d transpose - to 1d or 3d or more.


text:
Q: Thread used for ServiceConnection callback (Android) I'm developing an activity that binds to a local service (in onCreate of the activity):
bindService(new Intent(this, CommandService.class), svcConn, BIND_AUTO_CREATE);

I would like to be able to call methods through the IBinder in my lifecycle methods, but can not be sure that onServiceConnected have been called prior to these. I'm thinking of handling this by adding a queue of sorts in the ServiceConnection implementation, so that the method calls (Command pattern) will be executed once the connection is established.
My questions are then:

*

*Is this stupid, any better ways? :)

*Are there any specification for which thread will be used to execute the ServiceConnection callbacks? More to the point, do I need to worry about synchronizing a queue datastructure?

Edit - something like:
public void onServiceConnected(ComponentName name, IBinder service) {
    dispatchService = (DispatchAsync)service;

    for(ExecutionTask task : queue){
        dispatchService.execute(task.getCommand(), task);
    }
}

A:
Are there any specification for which
  thread will be used to execute the
  ServiceConnection callbacks?

It should be called on the main application thread, like any other callback.

More to the point, do I need to worry
  about synchronizing a queue
  datastructure?

That depends on where you are adding objects to the queue. If it is only from the main application thread, then there should be no contention, AFAIK.


text:
Q: Showing Nested JSON Data in Separate Rows - Angular I want to show this data in seperate rows cause at the moment they are getting all in 1 row only. I want to show the 'FROM' from the JSON Data
<ng-container matColumnDef="from">
    <mat-header-cell *matHeaderCellDef> From </mat-header-cell>
      <mat-cell *matCellDef="let element">

{{element.computationrates[0].ratebands[0].from}}

{{element.computationrates[0].ratebands[1].from}}

{{element.computationrates[0].ratebands[2].from}}

{{element.computationrates[0].ratebands[3].from}}

      </mat-cell>
  </ng-container>

Can someone show me how to edit this code to make them appear in different rows
JSON Data
        [
     {
  "yearlyincentive": {
      "incentive": {
          "number": "0",
          "description": "null"
      },
      "year": "2016"
  },
  "computationrates": {
          "0": {
              "computation": "0",
              "ratetype": "0",
              "ratebands": [
                  {
                      "from": "0",
                      "to": "8,000",
                      "percent": "15%",
                      "subtract": "100"
                  },
                  {
                      "from": "8,000",
                      "to": "15,000",
                      "percent": "20%",
                      "subtract": "250"
                  },
                  {
                      "from": "15,000",
                      "to": "25,000",
                      "percent": "25%",
                      "subtract": "500"
                  },
                  {
                      "from": "25,000",
                      "to": "50,000",
                      "percent": "35%",
                      "subtract": "1000"
                  }
              ]
          }
  }
 }
 ]


text:
Q: How to use SQL trigger to record the affected column's row number I want to have an 'updateinfo' table in order to record every update/insert/delete operations on another table.
In oracle I've written this:
CREATE TABLE updateinfo ( rnumber NUMBER(10), tablename VARCHAR2(100 BYTE), action VARCHAR2(100 BYTE), UPDATE_DATE date )
DROP TRIGGER TRI_TABLE;
CREATE OR REPLACE TRIGGER TRI_TABLE
AFTER DELETE OR INSERT OR UPDATE
ON demo
REFERENCING NEW AS NEW OLD AS OLD
FOR EACH ROW
BEGIN
if inserting then
insert into updateinfo(rnumber,tablename,action,update_date ) values(rownum,'demo', 'insert',sysdate);
    elsif updating then
    insert into updateinfo(rnumber,tablename,action,update_date ) values(rownum,'demo', 'update',sysdate);
    elsif  deleting then
   insert into updateinfo(rnumber,tablename,action,update_date ) values(rownum,'demo', 'delete',sysdate);
    end if;
 --  EXCEPTION
 --   WHEN OTHERS THEN
       -- Consider logging the error and then re-raise
  --   RAISE;
END TRI_TABLE;
but when checking updateinfo, all rnumber column is zero.
is there anyway to retrieve the correct row number?

A: The only option is to use primary key column of your "demo" table.
ROWNUM is not what you are looking for, read the explanation.
ROWID looks like a solution, but in fact it isn't, because it shouldn't be stored for a later use.

A: ROWNUM is not what you think it is. ROWNUM is a counter that has only a meaning within the context of one execution of a statement (i.e. the first resulting row always has rownum=1 etc.). I guess you are looking for ROWID, which identifies a row.


text:
Q: Identifying coordinate system? I'm wanting to create a data layer using some open crime data from Salt Lake City, but I can't figure out the coordinate system they are using. See the link below to view the data. (You'll have to scroll to the far right to see the X and Y coordinates.)
https://opendata.utah.gov/Public-Safety/SALT-LAKE-CITY-POLICE-CASES-2016/trgz-4r9d
I'm new to GIS.

A: When you want to make a new layer from an attribute table, the coordinate system of the data should be mentioned in the meta data.
And if it's not, you should find it through trial and error.
For example here it is clear that the data has a projected coordinate system and it is belonged to Salt Lake city, so provide another layer of the city which has a defined coordinate system and then start and create your new layer using the popular projected coordinate systems that are used in US and the new layer to the .mxd map to see in which case, the layer is shown just right up in its place

A: From the Discus tab of the page:
x y points are state plane coordinates

Since Salt Lake City is in Utah, take all CRS that are valid for that state, and compare the location against an OpenStreetmap or other basemap.
You will get lucky with EPSG:32043 NAD27 / Utah Central:

A: From what I see on the website (at least on a mobile device) this data cannot be downloaded in a native GIS format (like shapefile). If it could, such a format generally comes with various metadata, including projection info.
Anyway, if you don't plan to combine it with data from other sources it doesn't matter what projection your GIS software thinks it is. Just pick any Projected coordonate system (the X/Y tells us it's a projected system, a geographical one would have coordinates of the type: Lat/Long).


text:
Q: Set value to variable depending on input, StringProperty kivy I have an issue with Kivy StringProperty variable when i try to update the value based on inputs.
to make it a bit simple so I can understand too (I'm a bit new to this).
TextTime1 = StringProperty()
TextTime2 = StringProperty()
x = 2

TextTime+x = "TEST"

How can I get that to work?
I have tried
TextTime1 = StringProperty()
TextTime2 = StringProperty()
TextTimes = [TextTime1, TextTime2]
x = 2

TextTimes[x-1] = "TEST"

Does not work.
Only thing that works is:
TextTime1 = StringProperty()
TextTime2 = StringProperty()

TextTime2 = "TEST"

How can I get the more "dynamic" way to work?

A: To my understanding you are trying to replace the last value in a list?
You could probably make it work like this
TextTime1 = StringProperty()
TextTime2 = StringProperty()

TextTimes = [TextTime1, TextTime2]

TextTimes.pop()
TextTimes.append("TEST")

A: I think your understanding of variables is a bit shallow. For instance, TextTimes+x="TEST" is not valid because you aren't saying TextTimes2 = "TEST", you are saying TextTimes + 2 = "TEST".
Your second method isn't entirely wrong.
TextTimes[x-1] = "TEST"
# = TextTimes[1] = "TEST"
# = TextTimes2 = "TEST" since TextTimes2 is the assigned index for that variable
# in your TextTimes list.
# However the correct list should be
TextTimes = [self.TextTimes1,self.TextTimes2] # if they are properties of an object

Example:
class MyWidget(Widget):
    TextTimes1 = StringProperty()
    TextTimes2 = StringProperty()
    #TextTimes = [self.TextTimes1,self.TextTimes2]
    def __init__(self,**kwargs):
        super(MyWidget,self).__init__(**kwargs)

        self.TextTimes = [self.TextTimes1,self.TextTimes2]

    def some_function(self):
        x = 2
        self.TextTimes[x-1]="TEST" #This should change the value for TextTimes2 to "TEST"

A: Only way I can see this work with my limited knowlage about this would be.
if x == 2:
    TextTime2 = "TEST"

That just feels wrong and alot of code if I have > 50 of them...


text:
Q: How can I debug a python application I am quite new to python and trying to understand how can I troubleshoot an issue in a python application which is using python api to call functions in a C library. Looks like respective C  function is not able to process things as expected. I am not sure how can i troubleshot the same without adding more printfs and rebuilding the whole library.
In C, we have GDB and STRACE which are helpful in understanding trace of functions and adding breakpoints to understand the values in the respective variables. Is there anything equivalent to do similar stuff in python ?


text:
Q: ARM cortex-A7 - cycle interrupts I'm using a Banana Pi M3 with an ARM cortex-A7.
I want to perform a task in a cycle with a fixed period with no delays and I was wandering if I could use an interrupt for that.
Does this processor even have a cycle interrupt? If so, how can I use it?
Thanks

A: Use the timer and timer interrupt. But Banana usually is not used as a bare metal development board and it is run under linux which is not good for the RT tasks. If you need the RT functionality - you will need to apply the RT patch to your kernel.


text:
Q: Error when installing using "pip3 install xgboost" I tried to follow this guide: https://xgboost.readthedocs.io/en/latest/build.html
But I got these error messages.  Any insights?
(base) MacBook-Pro-2:~ Prajnajiang$ pip3 install xgboost
Collecting xgboost
  Using cached xgboost-1.0.2.tar.gz (821 kB)
    ERROR: Command errored out with exit status 1:
     command: /Users/apple/opt/anaconda3/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/5y/6cyzpgbx7895mzf3wfvryvrr0000gn/T/pip-install-quq3h_3t/xgboost/setup.py'"'"'; file='"'"'/private/var/folders/5y/6cyzpgbx7895mzf3wfvryvrr0000gn/T/pip-install-quq3h_3t/xgboost/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(file);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, file, '"'"'exec'"'"'))' egg_info --egg-base /private/var/folders/5y/6cyzpgbx7895mzf3wfvryvrr0000gn/T/pip-install-quq3h_3t/xgboost/pip-egg-info
         cwd: /private/var/folders/5y/6cyzpgbx7895mzf3wfvryvrr0000gn/T/pip-install-quq3h_3t/xgboost/
    Complete output (27 lines):
    ++ pwd
    + oldpath=/private/var/folders/5y/6cyzpgbx7895mzf3wfvryvrr0000gn/T/pip-install-quq3h_3t/xgboost
    + cd ./xgboost/
    + mkdir -p build
    + cd build
    + cmake ..
    ./xgboost/build-python.sh: line 21: cmake: command not found
    + echo -----------------------------
    -----------------------------
    + echo 'Building multi-thread xgboost failed'
    Building multi-thread xgboost failed
    + echo 'Start to build single-thread xgboost'
    Start to build single-thread xgboost
    + cmake .. -DUSE_OPENMP=0
    ./xgboost/build-python.sh: line 27: cmake: command not found
    Traceback (most recent call last):
      File "", line 1, in
      File "/private/var/folders/5y/6cyzpgbx7895mzf3wfvryvrr0000gn/T/pip-install-quq3h_3t/xgboost/setup.py", line 42, in
        LIB_PATH = libpath'find_lib_path'
      File "/private/var/folders/5y/6cyzpgbx7895mzf3wfvryvrr0000gn/T/pip-install-quq3h_3t/xgboost/xgboost/libpath.py", line 50, in find_lib_path
        'List of candidates:\n' + ('\n'.join(dll_path)))
    XGBoostLibraryNotFound: Cannot find XGBoost Library in the candidate path, did you install compilers and run build.sh in root path?
    List of candidates:
    /private/var/folders/5y/6cyzpgbx7895mzf3wfvryvrr0000gn/T/pip-install-quq3h_3t/xgboost/xgboost/libxgboost.dylib
    /private/var/folders/5y/6cyzpgbx7895mzf3wfvryvrr0000gn/T/pip-install-quq3h_3t/xgboost/xgboost/../../lib/libxgboost.dylib
    /private/var/folders/5y/6cyzpgbx7895mzf3wfvryvrr0000gn/T/pip-install-quq3h_3t/xgboost/xgboost/./lib/libxgboost.dylib
    /Users/apple/opt/anaconda3/xgboost/libxgboost.dylib
    ----------------------------------------
ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output.

A: Problem resolved:
The issue was that I did not have cmake installed. After installing cmake, the problem was resolved.

A: I was having the same issue and this solved it by installing cmake:
pip install cmake


text:
Q: Test project call to instantiate Window hangs when using BackgroundWorker I am trying to set up a test suite for a recently-written WPF/C# app.  I did not use any sort of MVVM pattern, which I realize makes automated testing much more difficult, but this is the current state of things and my boss is not going to give me extra time for a rewrite.  So I am trying to make the best of the situation.
In my test project, I am calling the MainWindow() ctor.  I kick off the DoWork method of a BackgroundWorker right before its creation, to be able to send keypresses via an (Action)delegate through the window's Dispatcher.  However, when I call bgWorker.RunWorkerAsync() before calling the MainWindow ctor, the ctor does not get executed (I put breakpoints in it and nada).  If I remove the call to RunWorkerAsync then the ctor works correctly. What am I missing here?

A: Below is the implementation of BackgroundWorker .
IsVMBusy = true;
var worker = new BackgroundWorker();
worker.DoWork += (o, ea) =>
   {

       //Do task here

    };

worker.RunWorkerCompleted += (o, ea) =>
        {
            IsVMBusy = false;
        };
        IsVMBusy = true;
        worker.RunWorkerAsync();


text:
Q: How to check if a new username is a system user? I want to create a script that change a username.
I want to check if the user is not a system user.
My idea is to check /etc/passwd and pick only users with an ID between 1000 and 60000 and users that have a /home directory like
user:x:1005:1021::/home/user:/bin/sh

My grep command for now is like
egrep -E '1[0-9]{3}.*/home' /etc/passwd

As you can see, it doesn't match my [1000-60000] pattern nor the name

A: You can use awk to find local users with id >= 1000:
awk -F: '$3>=1000 && $3!=65534 {print $1}' /etc/passwd

To also check for a home folder below /home:
awk -F: '$3>=1000 && $3 != 65534 && $6 ~ /^\/home/ {print $1}' /etc/passwd

Replace /etc/passwd with <(getent passwd) to list all users including network accounts ...
See also this related question, as well as this one.


text:
Q: How to replace question marks inside a string with the values of an array? Given the string 'Hello ?, welcome to ?' and the array ['foo', 'bar'], how do I get the string 'Hello foo, welcome to bar' in a single line of code with JavaScript (possibly with jQuery, Underscore, etc.)?

A: Kind of silly to put it all on one line, but:
var str = 'Hello ?, welcome to ?',
    arr = ['foo', 'bar'],
    i = 0;

while(str.indexOf("?") >= 0) { str = str.replace("?", arr[i++]); }

A: You could use vsprintf.  Although if you include sprintf, it's much more than one line.
vsprintf('Hello %s, welcome to %s', [foo, bar]);

A: var s = 'Hello ?, welcome to ?';
var a = ['foo', 'bar'];
var i = 0;
alert(s.replace(/\?/g,function(){return a[i++]}));

A:

let str = 'Hello ?, welcome to ?'
let arr = ['foo', 'bar']
const fn = Array.prototype.shift.bind(arr)
let  result = str.replace(/\?/g, fn)

console.log(result);

A: Let's build a replaceWith function:
const replaceWith =
  (...str) =>
    (fallback) =>
      str.length === 0
        ? fallback
        : str.shift();

It's a curried function: it takes a list of replacement strings and returns another function which will return the replacements one by one:
const replacements = replaceWith('', '', '');
replacements(); //=> ''
replacements(); //=> ''
replacements(); //=> ''

After the third call you have exhausted all the replacements so the next calls will either return undefined or whatever you passed as a fallback parameter:
replacements(); //=> undefined
replacements(''); //=> ''

This fallback parameter can be handy if you have more substrings to replace than replacement strings at your disposal. (But we will come to that later.)
Now using replaceWith we can do:
'Hello ?, welcome to ?'.replace(/\?/g, replaceWith('foo', 'bar'));
//=> 'Hello foo, welcome to bar'

Behind the scene it calls the function returned by replaceWith (let's call it fn) with:
fn('?'); //=> 'foo'
fn('?'); //=> 'bar'

The fallback parameter (i.e. your placeholder '?' in this case) is ignored while there are still replacement strings. However it will be returned as is when there are more placeholders than replacements:
'Hello ? and ?, welcome to ?'.replace(/\?/g, replaceWith('foo', 'bar'));
//=> 'Hello foo and bar, welcome to ?'

Acknowledgment
This answer is a variation of Alex Varghese excellent answer.