text:
Q: How to mask a string using different parameters in an effective and fast way I'd like to mask a string using different parameters like percentage of char to be masked, the mask character and the position to apply the mask (In the beginning, in the middle or at the end of the string). I've come up with a solution but I presume that this is not the best solution. This is my code:
public static string MaskChars(this string value, char maskToApply = 'X', int percentToApply = 25, MaskOption maskOptions = MaskOption.InTheMiddleOfString)
    {
        string valueTrimmed = value.Trim();
        int len = valueTrimmed.Length;

        if (len == 0)
            return Empty;
        if (percentToApply >= 100)
            return maskToApply.ToString(CultureInfo.InvariantCulture).Replicate(len);

        var charsToMask = (int)Math.Round((decimal)(percentToApply * len) / 100);
        if (charsToMask == 0)
            charsToMask = 1;

        int top = len - charsToMask;
        int maskCounter = 0;
        var builder = new StringBuilder(len);

        for (int i = 0; i < len; i++)
        {
            if (maskCounter < charsToMask)
            {
                switch (maskOptions)
                {
                    // Apply mask in the middle of the string
                    case MaskOption.InTheMiddleOfString:
                        if (i >= charsToMask && i < top)
                        {
                            builder.Append(maskToApply);
                            maskCounter++;
                        }
                        break;
                    // Apply mask at the begining of the string
                    case MaskOption.AtTheBeginingOfString:
                        if (i < charsToMask)
                        {
                            builder.Append(maskToApply);
                            maskCounter++;
                        }
                        break;
                    // Apply mask at the end of the string
                    case MaskOption.AtTheEndOfString:
                        if (i >= top)
                        {
                            builder.Append(maskToApply);
                            maskCounter++;
                        }
                        break;
                }
            }
            else
            {
                builder.Append(valueTrimmed[i]);
            }
        }

        return builder.ToString();
    }

where:
public enum MaskOption : byte
{
    AtTheBeginingOfString = 1,
    InTheMiddleOfString = 2,
    AtTheEndOfString = 3
}

and Replicate is a simple method to replicate a string
public static string Replicate(this string value, int count)
    {
        if (IsNullOrEmpty(value))
            return Empty;
        if (count <= 0)
            return value;

        var builder = new StringBuilder();
        builder.Append(value);
        for (int i = count; i >= 1; i--)
            builder.Append(value);

        return builder.ToString();
    }

A: First I ran your code to see what the expected behavior was, and it doesn't look right to me. Here's the test code and the output:
var testStr = "This is my string to mask characters in!";
Console.WriteLine(testStr.MaskChars('X', 25, Extensions.MaskOption.AtTheBeginingOfString));
Console.WriteLine(testStr.MaskChars('X', 25, Extensions.MaskOption.InTheMiddleOfString));
Console.WriteLine(testStr.MaskChars(maskOptions: Extensions.MaskOption.AtTheEndOfString));

Output

I was under the impression that the string should remain the same length, and that the masked characters would just change position within the string. Also, I'm not sure why you're trimming the string (I wouldn't do that in this method, I would let the caller decide if they wanted to trim it first), but I left that part in.
Here's how I would simplify the code to do that:
public static string MaskChars(this string input, char maskChar,
    int percentToApply, MaskOption maskOptions)
{
    // I would remove this. The caller can trim the string first if they want.
    var result = input.Trim();

    if (result.Length == 0 || percentToApply < 1) return result;
    if (percentToApply >= 100) return new string(maskChar, result.Length);

    var maskLength = Math.Max((int) Math.Round(percentToApply * result.Length / 100m), 1);
    var mask = new string(maskChar, maskLength);

    switch (maskOptions)
    {
        case MaskOption.AtTheBeginingOfString:
            result = mask + result.Substring(maskLength);
            break;
        case MaskOption.AtTheEndOfString:
            result = result.Substring(0, result.Length - maskLength) + mask;
            break;
        case MaskOption.InTheMiddleOfString:
            var maskStart = (result.Length - maskLength) / 2;
            result = result.Substring(0, maskStart) + mask +
                result.Substring(maskStart + maskLength);
            break;
    }

    return result;
}

Output

The last thing I would do is get rid of the default argument values in the method, and create some overload methods instead that use default values for the missing arguments. This way the users can adjust the values the want (in your implementation, if they want to only change the MaskOption, then they have to re-state the other default values or use named parameters as I did above):
private static char defaultMaskChar = 'X';
private static MaskOption defaultMaskOption = MaskOption.InTheMiddleOfString;
private static int defaultPercentToApply = 25;

public static string MaskChars(this string input)
{
    return MaskChars(input, defaultMaskChar);
}

public static string MaskChars(this string input, char maskChar)
{
    return MaskChars(input, maskChar, defaultPercentToApply);
}

public static string MaskChars(this string input, int percentToApply)
{
    return MaskChars(input, defaultMaskChar, percentToApply);
}

public static string MaskChars(this string input, MaskOption maskOption)
{
    return MaskChars(input, defaultMaskChar, defaultPercentToApply, maskOption);
}

public static string MaskChars(this string input, char maskChar, int percentToApply)
{
    return MaskChars(input, maskChar, percentToApply, defaultMaskOption);
}

public static string MaskChars(this string input, char maskChar, MaskOption maskOption)
{
    return MaskChars(input, maskChar, defaultPercentToApply, maskOption);
}

public static string MaskChars(this string input, int percentToApply, MaskOption maskOption)
{
    return MaskChars(input, defaultMaskChar, percentToApply, maskOption);
}

A: You can try another way of doing the same thin.. Less parameters and easier to test and easier to read.
Mind you that I did not post the interface and small details like Guard.
   public class StringMask : IStringMask
    {
        /// <summary>
        /// The Mask character
        /// </summary>
        private readonly char MaskCharacter;

        /// <summary>
        /// The instance
        /// </summary>
        private readonly string Instance;

        /// <summary>
        /// The Mask
        /// </summary>
        private BitArray Mask;

        /// <summary>
        /// Initializes a new instance of the <see cref="StringMask"/> class.
        /// </summary>
        /// <param name="instance">The string you would like to mask.</param>
        /// <param name="maskCharacter">The Mask character.</param>
        public StringMask(string instance, char maskCharacter)
        {
            MaskCharacter = maskCharacter;
            Instance = instance;
            Mask = new BitArray(instance.Length, false);
        }

        /// <summary>
        /// Shows the first [number] of characters and masks the rest.
        /// </summary>
        /// <param name="number">The number of the characters to show.</param>
        /// <returns>IStringMask.</returns>
        public IStringMask ShowFirst(int number)
        {
            Validate(number);

            for (int i = 0; i < number; i++)
            {
                Mask[i] = true;
            }
            return this;
        }

        /// <summary>
        /// Shows the last [number] of characters and masks the rest.
        /// </summary>
        /// <param name="number">The number of the characters to show.</param>
        /// <returns>IStringMask.</returns>
        public IStringMask ShowLast(int number)
        {
            Validate(number);

            for (int i = 0; i < number; i++)
            {
                Mask[Instance.Length - i - 1] = true;
            }
            return this;

        }

        /// <summary>
        /// Returns a <see cref="System.String" /> that represents this instance.
        /// </summary>
        /// <returns>A <see cref="System.String" /> that represents this instance.</returns>
        public override string ToString()
        {
            var sb = new StringBuilder();
            for (int i = 0; i < Instance.Length; i++)
            {
                if (Mask[i])
                    sb.Append(Instance[i]);
                else
                    sb.Append(MaskCharacter);
            }

            return sb.ToString();
        }

        private void Validate(int number)
        {
            Guard.IsBetweenExclusive(number, 0, Instance.Length, nameof(number));
        }
    }

While you can see here the Tests for that:
 [TestFixture]
    internal class MaskTests
    {
        private string input = "40770058698999513265";
        private char maskChar = 'X';
        private IStringMask mask;

        [SetUp]
        public void Initiate()
        {
            mask = new StringMask(input, maskChar);
        }

        [Test]
        public void MaskShowLast()
        {
            var output = mask.ShowLast(10);
            Console.WriteLine(output);
            Assert.AreEqual("XXXXXXXXXX8999513265", output.ToString());
        }

        [Test]
        public void MaskInTheMiddle()
        {
            var output = mask.ShowLast(5).ShowFirst(5);
            Console.WriteLine(output);
            Assert.AreEqual("40770XXXXXXXXXX13265", output.ToString());
        }

        [Test]
        public void MaskInTheMiddleTooShort()
        {
            Assert.Throws<ArgumentOutOfRangeException>(() => mask.ShowLast(0).ShowFirst(0));
        }

        [Test]
        public void MaskInTheMiddleTooLong()
        {
            Assert.Throws<ArgumentOutOfRangeException>(()=> mask.ShowLast(500).ShowFirst(500));
        }

        [Test]
        public void MaskAtTheEnd()
        {
            var output = mask.ShowFirst(10);
            Console.WriteLine(output);
            Assert.AreEqual("4077005869XXXXXXXXXX", output.ToString());

        }
    }


text:
Q: How to get all documents from collection according to specific field from Firestore I have this data in "Firestore", I want to get all documents according to "city" like all users who have city "karachi" and stored in arrayList of type "chatModel" I want to show this data in recyclerView
Here is the image of dataabase:

I have tried this but it's only getting me the last document from collection.
      firestore.collection("USERS")
        .whereEqualTo("city",cityName)
        .get()
        .addOnSuccessListener { documents ->
            for (document in documents) {

                arrayList.add(document.toObject(chatModel::class.java))

                Log.i("Info", "${document.id} => ${document.data}")

            }

            val adapter = chatAdapter(context!!, arrayList)
            chatRecyclerView.layoutManager = LinearLayoutManager(context,
                LinearLayoutManager.VERTICAL,false)
            chatRecyclerView.adapter = adapter
            adapter.notifyDataSetChanged()
        }

Here is the Logcat result:
v21GH5sBi3SdIb3v3xsp3ob64S23 => {username=Muhammad Rizwan, Email=mr1017753@gmail.com, city=Karachi, ProfileImageUrl=https://firebasestorage.googleapis.com/v0/b/me2wee-1b547.appspot.com/o/USERS-MEDIA%2Fv21GH5sBi3SdIb3v3xsp3ob64S23?alt=media&token=193c4013-c580-45dc-b63d-fee1ef13caba}

Here is the screenshot of all documents which contain the city "Karachi" but it's only getting the last one

A: The most probable problem with lowercase and upper case. You're problem might be similar to this question
As I can see your described in database city value is karachi in lowercase but output you provided uppercase Result.
firestore.collection("USERS").get()
    .addOnSuccessListener { documents ->
        for (document in documents) {
            if(document.get("city").equals("karachi") || document.get("city").equals("Karachi")){
                arrayList.add(document.toObject(chatModel::class.java));
            }
        }

        val adapter = chatAdapter(context!!, arrayList)
        chatRecyclerView.layoutManager = LinearLayoutManager(context,
            LinearLayoutManager.VERTICAL,false)
        chatRecyclerView.adapter = adapter
        adapter.notifyDataSetChanged()
    }

A:
I have tried this but it's not working

It doesn't work because you are creating a chatAdapter object at every iteration of your for loop. To solve this, move the last four lines of code outside the loop. Inside the loop should exist only:
arrayList.add(document.toObject(chatModel::class.java))

In this way you populate the list and set the adapter only when the list is full of objects.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What additional powers does the Phoenix Force grant the "Phoenix Five"? When the Phoenix Force comes back to Earth it is split into pieces by Tony Stark's machine. Five mutants are embued with the Phoenix Force:

 Cyclops, Frost, Colossus, Namor, and Magik

During rounds 6 & 7 we see them use a few extra powers, but really they seem to be using their ordinary powers primary.

 Cyclops uses his optic blasts a lot, Emma Frost uses he telepathy, and Namor uses his power over the sea.

What additional powers have they been granted?

A: The Phoenix Five are the result of the interference of Iron Man and the Avengers trying to destroy the Phoenix force. (This would be the same as if an ant had decided it wanted to destroy the sun.) The Phoenix Force has incalculable power and is only bounded by the capabilities of the host it is inhabiting. The Phoenix Force is a primal force of Life in the Marvel Universe and when embodied by Jean Grey, equated alongside the most powerful beings in the Marvel Universe including Death, Infinity, and Galactus.

The Phoenix-hosting X-men, called the "Phoenix Five. The Sub-mariner, The White Queen, Cyclops, Magik and Colossus."
I mention this because this would explain the current portrayal of the X-men who have become hosts simply doing what they already do, only bigger because the Phoenix Force first begins by using and magnifying the powers of its host.
It has a preference for Omega-Class entities like Jean Grey because it has a far greater capacity to utilize its amazing powers. It also considers Jean Grey its ultimate host and through her has manifested its most powerful form, the White Phoenix of the Crown.
Think of a host like a fuse. That host can only channel as much power as they are able to, so the greater their innate ability, the greater the potential output of the Phoenix Force.
Ultimately, as the Phoenix spends time in these hosts, it will begin to manipulate greater potentials of its natural abilities, giving each of them the potential to alter reality as they see fit.
Given the powers of the White Queen, and her having been a host before (though the Phoenix might not remember her) and the innate bias of the Phoenix Force as a psychic power, it will probably find her the most compatible of hosts, followed by Magik whose mastery of magic will resemble the Phoenix's powers most closely. Expanding the ranges of powers for Cyclops will probably mean his energy projection (and absorption) powers will be even further increased. The Sub-Mariner and Colossus should become all but physically invulnerable.
Eventually, they should all be able to manifest a variety of the Phoenix's innate abilities which include but are not limited to:

*

*the ability to manipulate cosmic energies and to tap into the life-force reserved for future generations, thus denying them existence.

*The ability to project its cosmic energy as beams of immense destructive force.

*the ability to transmigrate throughout time and space and is capable of spaceflight.

*The ability to directly absorb physical energy such as Cyclops' optic blasts or even the entire energy of a sun. (It has done so in the past, destroying an entire civilization.)

*the ability to directly absorb the energy and life-force from a foe.

*Since it is the nexus of all psionic energy, it has mental abilities of cosmic scope, including telepathy and telekinesis.

*The ability to return the dead to life or resurrect itself after death.

*the ability to alter reality, rewriting history, making permanent changes to the space-time continuum and anything within it including the altering of metahuman potential and abilities.

Jean Grey as the White Phoenix, the most powerful manifestation of the Phoenix in the Marvel Universe, Earth-616.


text:
Q: how to make all users on site share a universal timezone using php or javascript? I'm using this great jQuery timepicker http://trentrichardson.com/examples/timepicker/
It gives a string something like 07/20/2011 01:13 am
I have this situation where users on the site can schedule "events" and they are using this to pick the event. But im realizing that it could cause a lot of confusion with all the different timezones that people will be submitting from.
So I was thinking I could use php to somehow get the timezone, and the adjust how the viewer views the dates according to their timezone. But this seems like quite a task and was wondering if there was an easier way?
Also, even with the php idea I tried echo date_default_timezone_get(); as a test to see if it got my timezone, but its saying im in the Los Angelas timezone, rather than Baltimore/DC timezone.
I'm guessing its getting the timezone of my server since php is serverside.
So basically, whats the best way while using my time picker jquery script, that I can have all the users view the date/times adjusted to their timezones? Any help would be greatly appreciated.

A: when you get the datetime from user, save in a default timezone (GMT 0 for example), you need to know the user timezone.
When you get the datetime from DB, add the user timezone to it.
You are right, the default timezone is the server's.
get user timezone
you can save it in  cookie

A: The term is UTC Time, Universal Coordinated Time. Googling that will find you a lot, in the meantime:
http://www.w3schools.com/jsref/jsref_getutcdate.asp

A: Direct give the UTC time (e.g. "Wed, 20 Jul 2011 06:10:38 GMT") to the users and use JS to convert it to their local times.
var localTime = new Date("Wed, 20 Jul 2011 06:10:38 GMT");
alert(localTime); // shows local time like: "Wed Jul 20 2011 14:10:38 GMT+0800 (CST)"


text:
Q: jfreechart get current TickUnit value I have an XYPlot displaying points and lines.
The points are created randomly so the chart will be different every time I launch the application.
With my current example, I've got the following TickUnit :
- Y axis : 1 2 3 4 5 6 ...
- X axis : 0.2 0.4 0.6 0.8 ...
I'm trying to get current TickUnit but it returns "size=1" for both axis :
NumberAxis range1 = (NumberAxis)plot.getRangeAxis();
NumberTickUnit ntu1 = range1.getTickUnit();
System.out.println(""+ range1.getTickUnit().toString());

NumberAxis range2 = (NumberAxis)plot.getDomainAxis();
NumberTickUnit ntu2 = range2.getTickUnit();
System.out.println(""+ range2.getTickUnit().toString());

Any idea how I can get 0.2 for X axis ?
I'd like to get these values so that I can add an annotation over a line at an appropriated distance.

A: The documentation mentions:

Note: if the autoTickUnitSelection flag is true the tick unit may be changed while the axis is being drawn, so in that case the return value from this method may be irrelevant if the method is called before the axis has been drawn.

Try calling the method after the graph is displayed, e.g. using SwingUtilities.invokeLater().


text:
Q: Missing option USER FLOWS in Azure Active Directory B2C? I'm pretty new in Azure and I'm trying to integrate Azure AD B2C in my React app, and I have problems right in the beginning.
I'm trying to find

USER FLOWS

option to configure sign up and sign on parts, but I cannot find it under the tab Polices as it shown in documentation
This where it should be accoriding to documentation :

Here is my screen of azure, with missing option policy:

I would really appreciate the help, how is this possible, where is user flow option?

A: Note the line in the screenshot:
"This is not an Azure AD B2C directory."
This is the Azure AD part of the tenant. Did you make a B2C tenant?
If you have, make sure you select the B2C tenant.


text:
Q: If a sequence is bounded, are its subsequences bounded as well? Lets say our infinite sequence is $A(n)$ and we have two subsequences of $A(n)$:

*

*$A(2n)$

*$A(2n-1)$

If $A(n)$ is a bounded sequences, does this imply the two subsequences above are also bounded?
Would the same apply vice-versa, where if we know that those two subsequences are bounded, THEN the sequence $A(n)$ is also bounded?
A formal proof to answer these questions would be appreciated!

A: Let $S = \{ A_n\}_{n=1}^{\infty}$ be a bounded sequence i.e. $\exists k,m \in \mathbb{N}$ such that $\forall n \in \mathbb{N}, m < A_n < k$. Consider the subsequence $\{ A_{2n}\}_{n=1}^{\infty}$. Since $T \subseteq S$, every element of $T$ is also in $S$. Therefore, we can pick $k$ and $m$ to be $\dots$

A: *

*Suppose that $(A_n)$ is bounded. Then there is $c \ge 0$ such that

$|A_n| \le c$ for all $n \in \mathbb N$.
Hence
$|A_{2n}| \le c$ for all $n \in \mathbb N$
and
$|A_{2n-1}| \le c$ for all $n \in \mathbb N$.
This shows that $(A_{2n})$ and $(A_{2n-1})$ are bounded.

*Now suppose that $(A_{2n})$ and $(A_{2n-1})$ are bounded. Then there are $c_1, c_2 \ge 0$ such that

$|A_{2n}| \le c_1$ for all $n \in \mathbb N$
and
$|A_{2n-1}| \le c_2$ for all $n \in \mathbb N$.
Let $c:=\max\{c_1,c_2\}$. Then we have
$|A_n| \le c$ for all $n \in \mathbb N$.
Therefore $(A_n)$ is bounded.


text:
Q: How to display image from dynamic path in node ejs I am trying to display image based on the path I get from database
here's my code
<% cars.forEach(function(car) { %>

                    <img src="images/" +"<%=car.Img_path %>">

<% }); %>

I also tried <img src="images/<%=car.Img_path %>"> but not working.
Can Anyone suggest how to render image.
Thanks In Advance.

A: <img src="images/<%=car.Img_path %>"> works. My issue was i didn't included Img_path in car model.
whoever may get this type of issue make sure you have included that field in model otherwise you will have data in database for but you wont get it in your application


text:
Q: Класс который регистрирует все свои объекты с++ Подскажите.
Написать программу, которая реализует статические компоненты класса и демонстрирует работу с ними.
Создать класс, который регистрирует все свои объекты - это как?

A: class Counter
{
    ...
    static int count;
    ...
    Counter() { ++count; ...}
    Counter(const Counter&) { ++count; ...}
    ...
    ~Counter() { --count; ... }

};

int Counter::count = 0;

От вас явно ждут чего-то такого. Возможно, не с непосредственным увеличением счетчика, а со статическими функциями для увеличения и уменьшения, и для возврата общего количества.
Только не забудьте увеличивать счетчик в каждом конструкторе.

A: #include<iostream>
#include<conio.h>
using namespace std;
class A
{
    int x;
    static int count;
  public:
    A(int x)
    {
        this->x = x;
        count++;
    }
    ~A()
    {
        count--;
    }
    static int quantity()
    {
        return count;
    }
};
int A::count = 0;
int main()
{
    cout << "Count object: " << A::quantity() << endl;
    A* p1, *p2, *p3;
    p1 = new A(1);
    p2 = new A(2);
    p3 = new A(3);
    cout << "Count object: " << A::quantity() << endl;
    delete p1;
    delete p2;
    cout << "Count object: " << A::quantity() << endl;
    delete p3;
    cout << "Count object: " << A::quantity() << endl;
}


text:
Q: How to output excel files with multiple urls in one cell with pandas? One of my dataframe element contains text in html format : This is google and this is yahoo
I want to save this dataframe in excel file.
Can the excel file show the string as This is google and this is yahoo with two urls in one cell?
Thanks

A: You can do something like this:
import re
import pandas as pd

df = pd.DataFrame({"text": ['This is google and this is yahoo']})

df["links"] = df.text.apply(lambda x: re.findall(r'<a href="(.+?)".+?', x))
df.text = df.text.str.replace(r"(.+?)", r'\1', regex=True)
print(df)
#                               text                                            links
#0  This is google and this is yahoo  [https://www.google.com, https://www.yahoo.com]


text:
Q: Why stack overflow causes segmentation fault instead of stack overflow in Linux?
Possible Duplicate:
What is the difference between a segmentation fault and a stack overflow?

I was just wondering, why stack overflow results in segmentation fault instead of stack overflow.
Is it because the boundary of stack limit is crossed which causes SIGSEGV? Why we don't encounter stack overflow in Linux, and rather a segmentation fault?
int foo()
{
  return foo();
}

This small code should cause stack overflow but rather it causes segmentation fault in Linux.

A: Stackoverflow is not an error, it is a case, the error thrown from it changes from language to language and from platform to platform.
See more about segmentation fault in wiki
EDIT:
To make it clearer - in your case, the call stack is overflowed and the program tries to write the next call to an invalid address, causing a segmentation fault.

A: A stack overflow can cause several different kinds of hardware errors.

*

*It may lead to an attempt to access memory for which the program has no appropriate permissions → the kernel will raise a SIGSEGV (segmentation violation) signal for the process.

*It may lead to an attempt to execute an illegal instruction (e.g: you overwrote the return address to point to an invalid instruction) → the kernel will raise a SIGILL (illegal instruction) signal.

*Probably SIGBUS on some platforms (e.g: alignment exception).

All these errors occur after the stack overflow. An option is to add stack overflow protections (ProPolice, ...), so as to catch stack overflows before they cause more serious problems.
Edit:
You mean a "real stack overflow". Well, this case is covered by SEGV (trying to access memory for which the process has no permissions), so it gets a SEGV, instead of special-casing every single case of the more general SEGV.


text:
Q: Group by unique value then count number of elements then list them In QGIS3+ Field Calculator I am trying to group features by unique values in field 1 then assign a number (no matter the order) from 1 to n (n=number of elements grouped for each unique value in field 1) to populate field 2. The result should be something like:
feature field1  field2
1   Andree  1
2   Andree  2
3   Andree  3
4   Luka    1
5   Luka    2

Sounds pretty simple to me and I know how I would it in R, for example. But I really cannot think about a way to do it in QGIS expression builder and without using CASE WHEN-like expressions for every value in field 1; though there are different questions (among others, here or here) that I guess point to the right direction (using aggregation and arrays), I really don't grasp how to:

*

*Access/group by every value in field 1

*Assign a unique value to every feature from an array-type list

There are a couple of doubts above, but I'm looking for an answer to my first query.

A: Use this expression (you could also replace $id with feature in your case as this field apparently is also kind of an id):
array_find (
    array_agg( $id, group_by:=field1),
    $id
)+1


text:
Q: usages of the preposition "of" I am wondering whether or not there is any difference between these. Would you possibly explain your invaluable explanation in a more detailed way?
that idiot of a doctor
a real palace of a house
a fine figure of a woman
..............
that doctor of idiot
a house of a real palace
a woman of a fine figure
Any help would be appreciated

A: Think of it as

"An example of something."

But the 'something' is actually a generalisation, using one 'something' (doctor, palace, woman) to describe all doctors, palaces, women.
So it becomes

"An example of a something."

One particular subject, referenced against the 'ideal subject' (acme) or even just 'most common variety of subject' (epitome).

"An idiot of a doctor"

compared to all the doctors I've ever known or even just seen on TV, he's not as clever.

"A palace of a house"

compared to all the houses I've ever seen, this one is very impressive.

"A fine figure of a woman"

compared to all the women I've seen… [1]
Once you start to interpret them this way, you'll see your second collection of examples no longer make sense.
[1]This particular expression does not actually refer directly to her physical characteristics, i.e. her figure, as in her measurements, but to her stature in the community, her bearing, the way she carries herself. It contains hints of a slight pun because it can be interpreted both ways, but is so common an idiom that I would imagine most native speakers got the joke many years ago & don't even 'hear' it in the sentence any more.

A: As Tetsujin and ultrasawblade have aptly mentioned, this wording is used to describe the quality of something – usually something extremely good or bad:

that idiot of a doctor (a terrible doctor who is an idiot)
a real palace of a house (a house so big and splendid that it's almost like a palace)
a fine figure of a woman (a distinctive woman with exemplary qualities)

As for how to "reverse" these, that's tricky. Read on.

I'll start with "a real palace of a house" – that simply means the house is like a palace:

Indira lives in a real palace of a house.

means:

Indira lives in a very palatial house.

Or, you could say the same thing with a little hyperbolical metaphor:

Indira lives in a house as nice as a palace!

However, I believe part of your question is asking: if we can say "palace of a house" to indicate a big, fancy house, then why can't we say "a house of a palace" to indicate a small, humble palace? (I hope that's what you're asking, because that's a great question!)
No, I don't think we'd say "a house of a palace," because "house" is too neutral a word. To use this construct effectively, the first word needs to have a strong negative or positive connotation (like "idiot" or "palace"). So, you couldn't say:

It was a real house of a palace.

Although you could say:

It was a real dump of a palace.

or maybe even:

It was a real hovel of a palace.

if you wanted to emphasize how unimpressive the palace was.

Now, on to the idiot doctor. You could rephrase this simply by removing the "of a":

That idiot of a doctor prescribed the wrong medicine!
That idiot doctor prescribed the wrong medicine!

Some might say that idiot is a noun, so the revised sentence should read, "That idiotic doctor prescribed the wrong medicine!" – and they'd be right. However, for some reason, the word idiot does get used colloquially as an adjective; for example:

Morgan wouldn't do that. He's not like that idiot doctor that you had back in the city.1
I think some idiot doctor told you you were in very poor health. I think some idiot doctor dwelled a bit too much on that and not enough on the future.2

As a matter of fact, Ngrams shows more hits for "idiot doctor" than it does for "idiotic doctor".
But what about:

That doctor of an idiot

Can we say that?
Well, the word doctor can be used to mean "expert." While "doctor of idiot" doesn't sound quite right, I suppose that, if you wanted to describe someone in a disparaging way, you could say:

Our boss is a doctor of idiocy!

meaning he does stupid things all the time, not just once in a while.

Lastly:

He was a fine figure of a man.

(I've switched the gender on this one, because I want to make sure we don't get confused about the word figure.) NOAD says that figure can mean:

a person's bodily shape, esp. that of a woman and when considered to be attractive : she had always been so proud of her figure

or:

a person of a particular kind, esp. one who is important or distinctive in some way

So, I want to make sure we're talking about a fine figure of a woman (such as Margeret Thatcher, Hillary Clinton, Benazir Bhutto, or Marie Curie), and not a fine figure on a woman (which might be used when describing, say, Kim Kardashian or Gisele Bündchen).
This one can't be reversed quite like the other two. I can say:

The mayor is a fine figure of a man.

or:

The mayor is a man of good stature.

These are both idiomatic ways of praising someone, but they don't work when reversed:

The mayor is a good stature of a man.
The mayor is a man of fine figure.

R E F E R E N C E S
1Cheryl Wolverton, What The Doctor Ordered, 2012
2Celeste Bradley, When She Said I Do, 2013

A: When you say "X of Y" in these manners, you are saying X is a particular rank or quality of Y - there's a bit of an evaluative or comparative subtext to it - as though you have looked over or sized up X and this is your opinion on how good X is.
Thus, X needs to be something that can describe a quality of Y, and if you switch them, it won't make sense in a lot of cases.

that doctor of an idiot

Doesn't really make sense.

a house of a real palace

The "real" in "real palace" makes "real palace" a modifier, so it sounds weird.

a real house of a palace

would work, but I don't hear someone use the word "house" to describe the rank or quality of palaces too often, so it still sounds a bit weird

a woman of a fine figure

This sounds like you are trying to say "a woman of fine figure" which is saying she has a fine figure, but there's no "comparative" meaning behind it anymore.


text:
Q: sed is not working for commenting a line in a file using bash script I have created a bash script that is used to modify the ulimit of open files in the RHEL server.
so i have reading the lines in the file /etc/security/limits.conf and if the soft/hard limit of the open files are less than 10000 for '*' domain i am commenting the line and adding a new line with soft/hard limit as 10000.
The Script is working as designed but the sed command to comment a line in the script is not working.
Please find the full script below :-
#!/bin/sh
#This script would be called by '' to set ulimit values for open files in unix servers.
#
configfile=/etc/security/limits.conf
help(){
echo "usage: $0 <LimitValue>"
echo -e "where\t--LimitValue= No of files you want all the users to open"
exit 1
}
modifyulimit()
{
grep '*\s*hard\s*nofile\s*' $configfile | while read -r line ; do
        firstChar="$(echo $line |  xargs | cut -c1-1)"
        if [ "$firstChar" != "#" ];then
        hardValue="$(echo  $line | rev | cut -d ' ' -f1 | rev)"
            if [[ "$hardValue" -ge "$1" ]]; then
            echo ""
            else
            sed -i -e 's/$line/#$line/g' $configfile
            echo "*          hard     nofile         $1" >> $configfile
            fi
        else
            echo ""
        fi
    done

grep '*\s*soft\s*nofile\s*' $configfile | while read -r line ; do
        firstChar="$(echo $line |  xargs | cut -c1-1)"
        if [ "$firstChar" != "#" ];then
        hardValue="$(echo  $line | rev | cut -d ' ' -f1 | rev)"
            if [[ "$hardValue" -ge "$1" ]]; then
            echo ""
            else
            sed -i -e 's/$line/#$line/g' $configfile
            echo "*          hard     nofile         $1" >> $configfile
            fi
        else
            echo ""
        fi
    done
}
deleteEofTag(){
sed -i "/\b\(End of file\)\b/d" $configfile
}
addEofTag()
{
echo "#################End of file###################" >> $configfile
}
#-------------Execution of the script starts here ----------------------
if [ $# -ne 1 ];
then
help
else
modifyulimit $1
deleteEofTag
addEofTag
fi

The command sed -i -e 's/$line/#$line/g' $configfile when executed from the terminal is working absolutely fine and it is commenting the line but it is not working when i am executing it from the unix shell script.

A: interpolation does not work in single quote
use double quote and try
sed -i -e 's/$line/#$line/g'
sed -i -e "s/$line/#$line/g"

A: also you might try:
    sed -i -e s/${line}/#${line}/g
as this will tell the script to take the value of the variable instead of variable as such.


text:
Q: Pass input value to controller on enter or button click I'm trying to get started learning AngularJS for an Ionic app I'm working on, and I'm having a little trouble understanding AngularJS having had most previous experience on jQuery which focuses on DOM manipulation rather than frameworking.
If I have the following markup:

  <input type="text" placeholder="Send a message...">

<button class="button button-clear button-positive">
  Send
</button>

How can I pass the value of the input on to the controller when enter or send is clicked? I'm working on a chat app, so I believe that a model approach is needed so that the message thread can be automatically updated but other than that I have no idea.
Could someone help me out or at least point me in the right direction?

A: There are several ways to pass value to your controller. Here is the simplest example. As Justin said, you should look into angular basics.
HTML:

     <input type="text" ng-model="foo" placeholder="Enter something" />
     <input type="button" ng-click="doSomething()" value="Send" ng-disabled="foo == null" />

JS:
var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.foo = null;
    $scope.doSomething = function () {
        alert("Hello, " + $scope.foo);
    }
}

Here is the working fiddle
And I would recommend you to go through this post.

A: The following markup you posted is the view.  What you'll need to do is write a separate JS script called a controller that gets linked to the view.  Look into basic Angular tutorials on how to do that and mainly look into how $scope works in Angular.
Your controller will have a function...say:
$scope.foo = function(input) { alert(input); };

From the view, you can pass a value onto the controller with Angular functions such as ng-click.
click me


text:
Q: Android - Using AChartEngine, is it possible to zoom in to a specific point upon displaying the graph? I have a bar graph with 100+ bars and want to zoom in to a specific range upon displaying the graph. For example, when the graph is displayed on the screen I want only the bars 44-49 to be showing. It is important that the users will be able to zoom out to see all 100+ bars as well.
GraphicalView.zoomIn() would work if it allowed me to specify a point to zoom in to.
Thanks!

A: You can set the visible range on the X axis:
renderer.setXAxisMin(44);
renderer.setXAxisMax(49);


text:
Q: Django: How to change default SignUp fields I am struggling with changing default UserCreationForm - I was able to add one additional field by creating child class:
class SignUpForm(UserCreationForm):
    display_name = forms.CharField(max_length=32, help_text='Your display name')

    class Meta:
        model = User
        fields = ('username', 'display_name', 'password1', 'password2', )

def register(request):
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        if form.is_valid():
            user = form.save()
            user.refresh_from_db()
            user.profile.display_name = form.cleaned_data.get('display_name')
            user.save()
            raw_password = form.cleaned_data.get('password1')
            user = authenticate(username=user.username, password=raw_password)
            login(request, user)
            return redirect('user/home')
    else:
        form = SignUpForm()
    return header.views.show(request, 'userpanel/register.html', context={'form': form})

Together with template:
<form method="post">
    {% csrf_token %}
    {% for field in form %}

        {{ field.label_tag }}

        {{ field }}
        {% if field.help_text %}
        {{ field.help_text | safe }}
        {% endif %}
        {% for error in field.errors %}

{{ error | safe }}

        {% endfor %}

    {% endfor %}
    <button type="submit">Sign up</button>
</form>

I was able to create following page:

But I have the problem with changing description texts on a page. Now, if I would like to change Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only. to something else, how to do it?

A: Okay, I figured it out. Listing all properties of a form by:
form = SignUpForm()
for d in dir(form):
    print(d)

I found, by trials and errors, that you can list fields of the form:
form = SignUpForm()
for d in form.fields:
    print('field name:', d)
    print('field label:', form.fields[d].label)
    print('field text:', form.fields[d].help_text)
    print("")

returns:
field name: username
field label: Username
field text: Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.

field name: display_name
field label: None
field text: Your display name

field name: password1
field label: Password
field text:

Your password can't be too similar to your other personal information.

Your password mus
t contain at least 8 characters.

Your password can't be a commonly used password.

Your password can&
#39;t be entirely numeric.

field name: password2
field label: Password confirmation
field text: Enter the same password as before, for verification.

I can easily alter those fields by writting:
x = form.fields['username']
x.label = "foo"
x.help_text = "bar"

and I got:


text:
Q: Limit objects in has_many assosiation I'm trying to limit the number of possible objects in a has_many association. I have 2 models Container and Can.
Container has no limit but only 12 cans may exist in one container.
I was able to limit the cans with the :limit => 12 but they are not per container.
Does anyone have any ideas how I can solve this?

A: With a little help from before_create ActiveRecord callback
class Container < ActiveRecord::Base
  has_many :cans
end

class Can < ActiveRecord::Base
  belongs_to :container

  before_create :check_overflow

  def check_overflow
    throw(:abort) if container.cans.count >= 12
  end
end

A: I had similar situations like yours. I did it as shown below,
class Container < ActiveRecord::Base
  has_many :cans

  validate :no_of_cans

  def no_of_cans
    if cans.size > 12
       errors.add(:base, 'Container is limited to 12 cans!')
    end
  end
end


text:
Q: How to deserialize JsonResult with DataContractJsonSerializer i have an MVC Controller that returns:
public JsonResult ValidateUser(string siteId, string userName, string password)
{
            UserObj userObj = new UserObj();
            userObj.Name = userName;
            return Json(JsonConvert.SerializeObject(userObj), JsonRequestBehavior.AllowGet);
}

Then in the client I have:
MemoryStream ms = new MemoryStream();
stream.Copy(ms);
var text = Encoding.Default.GetString(ms.ToArray());

They output text is: "{\"Name\":\"Peter\"}"
When trying to deserialize the value Name is null.
DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(UserObj));
var resultUser = obj.ReadObject(stream) as UserObj;

I found that the issue is in the backslashes.. any clue on how to make it work?
Thanks

A: Replace:
return Json(JsonConvert.SerializeObject(userObj), JsonRequestBehavior.AllowGet);

with:
return Json(userObj, JsonRequestBehavior.AllowGet);


text:
Q: Formatting a string timestamp with Android For some reason this has me tearing my hair out.
I have a UNIX timestamp as a string in Android.  All I want to do is format this so that it returns the date/time in the user's droid time zone.
I can convert it to a timestamp just fine, but it uses GMT rather than their localised zone.
Thanks

A: Use the SimpleDateFormat constructor with the Locale you need:
http://download.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html#SimpleDateFormat%28java.lang.String,%20java.util.Locale%29
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.US);
Calendar c = Calendar.getInstance();
try {
    Date dt = sdf.parse("2011-03-01 17:55:15");
    c.setTime(dt);
    System.out.println( c.getTimeInMillis());
    System.out.println(dt.toString());
} catch (ParseException e) {
    System.err.println("There's an error in the Date!");
}

outputs:
1299002115000
Tue Mar 01 12:55:15 EST 2011


text:
Q: Type hints and chained assignment and multiple assignments I guess these two questions are related, so I'll post them together:
1.- Is it possible to put type hint in chained assignments?
These two attempts failed:
>>> def foo(a:int):
...     b: int = c:int = a
  File "<stdin>", line 2
    b: int = c:int = a
              ^
SyntaxError: invalid syntax
>>> def foo(a:int):
...     b = c:int = a
  File "<stdin>", line 2
    b = c:int = a
         ^
SyntaxError: invalid syntax

2.- Is it possible to put type hint in multiple assignments?
These were my attempts:
>>> from typing import Tuple
>>> def bar(a: Tuple[int]):
...     b: int, c:int = a
  File "<stdin>", line 2
    b: int, c:int = a
          ^
SyntaxError: invalid syntax
>>> def bar(a: Tuple[int]):
...     b, c:Tuple[int] = a
...
  File "<stdin>", line 2
SyntaxError: only single target (not tuple) can be annotated
>>> def bar(a: Tuple[int]):
...     b, c:int = a
...
  File "<stdin>", line 2
SyntaxError: only single target (not tuple) can be annotated

I am aware that in both cases the type is inferred from the type hint of a, but I have a long variable list (in the __init__ of a class) and I want to be extra-explicit.
I am using Python 3.6.8.

A: *

*As explicitly stated in PEP 526, section "Rejected/postponed proposals", annotations in chained assignments are not supported.  Quoting the PEP:

This has problems of ambiguity and readability similar to tuple unpacking, for example in:
x: int = y = 1
z = w: int = 1
  it is ambiguous, what should the types of y and z be? Also the second line is difficult to parse.

*For unpacking, per the same PEP, you should place bare annotations for your variables before the assignment. Example from the PEP:
# Tuple unpacking with variable annotation syntax
header: str
kind: int
body: Optional[List[str]]
header, kind, body = message


text:
Q: DropDownList in MVC 4 with Razor I'm trying to create a DropDownList on a razor view.
Would someone help me with this?
Normal HTML5 code:
<select id="dropdowntipo">
    <option value="Exemplo1">Exemplo1</option>
    <option value="Exemplo2">Exemplo2</option>
    <option value="Exemplo3">Exemplo3</option>
</select>

I tried this:
@{
    var listItems = new List<ListItem> {
        new ListItem { Text = "Exemplo1", Value = "Exemplo1" },
        new ListItem { Text = "Exemplo2", Value = "Exemplo2" },
        new ListItem { Text = "Exemplo3", Value = "Exemplo3" }
    };
}

@Html.DropDownListFor(model =>
    model.tipo,
    new SelectList(listItems),
    "-- Select Status --"
)

A: Using an array would be a little more efficient than creating a list.
@Html.DropDownListFor(x => x.Tipo, new SelectListItem[]{
                new SelectListItem() {Text = "Exemplo1", Value="Exemplo1"},
                new SelectListItem() {Text = "Exemplo2", Value="Exemplo2"},
                new SelectListItem() {Text = "Exemplo3", Value="Exemplo3"}})

A: @{var listItems = new List<ListItem>
    {
          new ListItem { Text = "Exemplo1", Value="Exemplo1" },
          new ListItem { Text = "Exemplo2", Value="Exemplo2" },
          new ListItem { Text = "Exemplo3", Value="Exemplo3" }
    };
    }
        @Html.DropDownList("Exemplo",new SelectList(listItems,"Value","Text"))

A: @{
List<SelectListItem> listItems= new List<SelectListItem>();
listItems.Add(new SelectListItem
    {
      Text = "One",
      Value = "1"
    });
listItems.Add(new SelectListItem
    {
        Text = "Two",
        Value = "2",
    });
listItems.Add(new SelectListItem
    {
        Text = "Three",
        Value = "3"
    });
listItems.Add(new SelectListItem
{
   Text = "Four",
   Value = "4"
});
listItems.Add(new SelectListItem
{
   Text = "Five",
   Value = "5"
});
}
@Html.DropDownList("DDlDemo",new SelectList(listItems,"Value","Text"))

Refer:- Create drop down list in MVC 4 razor example

A: You can use this:
@Html.DropDownListFor(x => x.Tipo, new List<SelectListItem>
    {
                        new SelectListItem() {Text = "Exemplo1", Value="Exemplo1"},
                        new SelectListItem() {Text = "Exemplo2", Value="Exemplo2"},
                        new SelectListItem() {Text = "Exemplo3", Value="Exemplo3"}
    })

A: If you're using ASP.net 5 (MVC 6) or later then you can use the new Tag Helpers for a very nice syntax:
<select asp-for="tipo">
    <option value="Exemplo1">Exemplo1</option>
    <option value="Exemplo2">Exemplo2</option>
    <option value="Exemplo3">Exemplo3</option>
</select>

A: just use This
public ActionResult LoadCountries()
{
     List<SelectListItem> li = new List<SelectListItem>();
     li.Add(new SelectListItem { Text = "Select", Value = "0" });
     li.Add(new SelectListItem { Text = "India", Value = "1" });
     li.Add(new SelectListItem { Text = "Srilanka", Value = "2" });
     li.Add(new SelectListItem { Text = "China", Value = "3" });
     li.Add(new SelectListItem { Text = "Austrila", Value = "4" });
     li.Add(new SelectListItem { Text = "USA", Value = "5" });
     li.Add(new SelectListItem { Text = "UK", Value = "6" });
     ViewData["country"] = li;
     return View();
}

and in View use following.
 @Html.DropDownList("Country", ViewData["country"] as List<SelectListItem>)

if you want to get data from Dataset and populate these data in a list box then use following code.
List<SelectListItem> li= new List<SelectListItem>();
for (int rows = 0; rows <= ds.Tables[0].Rows.Count - 1; rows++)
{
    li.Add(new SelectListItem { Text = ds.Tables[0].Rows[rows][1].ToString(), Value = ds.Tables[0].Rows[rows][0].ToString() });
}
ViewData["FeedBack"] = li;
return View();

and in view write following code.
@Html.DropDownList("FeedBack", ViewData["FeedBack"] as List<SelectListItem>)

A: This can also be done like
@model IEnumerable<ItemList>

<select id="dropdowntipo">
    <option value="0">Select Item</option>

    @{
      foreach(var item in Model)
      {
        <option value= "@item.Value">@item.DisplayText</option>
      }
    }

</select>

A: @{
   List<SelectListItem> listItems= new List<SelectListItem>();
   listItems.Add(new SelectListItem
        {
          Text = "Exemplo1",
          Value = "Exemplo1"
        });
   listItems.Add(new SelectListItem
        {
            Text = "Exemplo2",
            Value = "Exemplo2",
            Selected = true
        });
   listItems.Add(new SelectListItem
        {
            Text = "Exemplo3",
            Value = "Exemplo3"
        });
}

@Html.DropDownListFor(model => model.tipo, listItems, "-- Select Status --")

A: //ViewModel
public class RegisterViewModel
{

    public RegisterViewModel()
    {
        ActionsList = new List<SelectListItem>();
    }

    public IEnumerable<SelectListItem> ActionsList { get; set; }

    public string StudentGrade { get; set; }

  }

//Enum Class:
public enum GradeTypes
{
    A,
    B,
    C,
    D,
    E,
    F,
    G,
    H
}

//Controller Action
 public ActionResult Student()
    {
RegisterViewModel vm = new RegisterViewModel();
IEnumerable<GradeTypes> actionTypes = Enum.GetValues(typeof(GradeTypes))
                                             .Cast<GradeTypes>();
        vm.ActionsList = from action in actionTypes
                         select new SelectListItem
                         {
                             Text = action.ToString(),
                             Value = action.ToString()
                         };
        return View(vm);
    }

//view Action

                                Student Grade:

                                   @Html.DropDownListFor(model => model.StudentGrade, Model.ActionsList, new { @class = "form-control" })

A: Here is the easiest answer:
in your view only just add:
@Html.DropDownListFor(model => model.tipo, new SelectList(new[]{"Exemplo1",
"Exemplo2", "Exemplo3"}))

OR
in your controller add:
var exemploList= new SelectList(new[] { "Exemplo1:", "Exemplo2", "Exemplo3" });
        ViewBag.ExemploList = exemploList;

and your view just add:
@Html.DropDownListFor(model => model.tipo, (SelectList)ViewBag.ExemploList )

I learned this with Jess Chadwick

A: Believe me I have tried a lot of options to do that
and I have answer here
but I always look for the best practice and the best way I know so far for both front-end and back-end developers is for loop (yes I'm not kidding)
Because when the front-end gives you the UI Pages with dummy data he also added  classes and some inline styles on specific select option so its hard to deal with using HtmlHelper
Take look at this :
<select class="input-lg" style="">
    <option value="0" style="color:#ccc !important;">
        Please select the membership name to be searched for
    </option>
    <option value="1">11</option>
    <option value="2">22</option>
    <option value="3">33</option>
    <option value="4">44</option>
</select>

this from the front-end developer so best solution is to use the for loop
fristly create or get your list of data from (...) in the Controller Action and put it in ViewModel, ViewBag or whatever
//This returns object that contain Items and TotalCount
ViewBag.MembershipList = await _membershipAppService.GetAllMemberships();

Secondly in the view do this simple for loop to populate the dropdownlist
<select class="input-lg" name="PrerequisiteMembershipId" id="PrerequisiteMembershipId">
    <option value="" style="color:#ccc !important;">
        Please select the membership name to be searched for
    </option>
    @foreach (var item in ViewBag.MembershipList.Items)
    {
        <option value="@item.Id" @(Model.PrerequisiteMembershipId == item.Id ? "selected" : "")>
            @item.Name
        </option>
    }
</select>

in this way you will not break UI Design, and its simple , easy and more readable
hope this help you even if you did not used razor

A:

List<tblstatu> status = new List<tblstatu>();
            status = psobj.getstatus();
            model.statuslist = status;
            model.statusid = status.Select(x => new SelectListItem
            {
                Value = x.StatusId.ToString(),
                Text = x.StatusName
            });

  @Html.DropDownListFor(m => m.status_id, Model.statusid, "Select", new { @class = "form-control input-xlarge required", @type = "text", @autocomplete = "off" })

A: For those using .NET Core MVC who stumbled across this:
If your model has an enum for the property, you can simply put:
<select asp-for="MyEnum" asp-items="Html.GetEnumSelectList<MyEnum>()"/>

see: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/working-with-forms?view=aspnetcore-6.0#enum-binding
Hope this helps someone.


text:
Q: Binding Combo box with wpf using linq My first time using wpf and linq and im comfusing everything. can anyone help me here? Im trying to fill the combobox cmbusertype with all the data in the table using the dbmodel of wpf but the defaultView and columns it is saying that it doesn't contain a definition for them.
    public void bindcombo()
    {
       LogicLayer.Roles r = new LogicLayer.Roles();
       dbmodelDataContext ds = new dbmodelDataContext();
       //return ds.tblusers.AsEnumerable();

        cmbusertype.ItemsSource = ds.tblRoles.DefaultView;

        cmbusertype.DisplayMemberPath = ds.tblRoles.Columns["Role"].ToString();

        cmbusertype.SelectedValuePath = ds.tblRoles.Columns["RoleId"].ToString();

    }

A: Try out the follow code and if you have any other query comment it here:
public void bindcombo()
        {
           LogicLayer.Roles r = new LogicLayer.Roles();
           dbmodelDataContext ds = new dbmodelDataContext();
           //return ds.tblusers.AsEnumerable();

            cmbusertype.ItemsSource = ds.tblRoles.DefaultView;
            cmbusertype.DisplayMemberPath = "Role";
            cmbusertype.SelectedValuePath = "RoleID";
        }

if this is the answer you are looking for than do mark it as an answer


text:
Q: Coordinates and height, width Unit of iText.Kernel.Geom.Rectangle method in Itext 7 I'm going to extract text from specific rectangle of PDF file
I have used these methods from Itext 7
https://api.itextpdf.com/iText7/dotnet/7.1.8/classi_text_1_1_kernel_1_1_geom_1_1_rectangle.html
 iText.Kernel.Geom.Rectangle rect = new iText.Kernel.Geom.Rectangle(float x, float y, float width, float height);
 TextRegionEventFilter regionFilter = new TextRegionEventFilter(rect.SetBbox(float x, float y, float width, float height));

I do not know what the unit of these coordinate and size of rectangle unit is. That should be inch, mm or cm.
Can you share me what unit should be used ?

A: First of all, if you already set the desired rectangle in its constructor
iText.Kernel.Geom.Rectangle rect = new iText.Kernel.Geom.Rectangle(float x, float y, float width, float height);

you don't need to set it again here
TextRegionEventFilter regionFilter = new TextRegionEventFilter(rect.SetBbox(float x, float y, float width, float height));

you only need
TextRegionEventFilter regionFilter = new TextRegionEventFilter(rect);

That been said, the coordinates are default user space coordinates:

The user space coordinate system shall be initialised to a default state for each page of a document. The CropBox entry in the page dictionary shall specify the rectangle of user space corresponding to the visible area of the intended output medium (display window or printed page). The positive x axis extends horizontally to the right and the positive y axis vertically upward, as in standard mathematical practice (subject to alteration by the Rotate entry in the page dictionary). The length of a unit along both the x and y axes is set by the UserUnit entry (PDF 1.6) in the page dictionary (see "Table 31 — Entries in a page object"). If that entry is not present or supported, the default value of 1 ⁄ 72 inch is used. This coordinate system is called default user space.

(ISO 32000-1 and 32000-2 section 8.3.2.3)
You can retrieve the entries mentioned from the itext page object in question.


text:
Q: Overwrite EIP in the main function I'm curious about how overwriting the stack is different in the main function than in other functions
Take this example:
#include <stdio.h>

int main(int argc, char *argv[])
{
    char buf[8];
    gets(buf);
}

In this code, the buffer to be overflowed is created in the main function, and as a result I receive this output from gdb after entering in a lot of 'A's:
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

Program received signal SIGSEGV, Segmentation fault.
0x5655620c in main (argc=<error reading variable: Cannot access memory at address 0x41414141>,
    argv=<error reading variable: Cannot access memory at address 0x41414145>) at source.c:7
7       }
(gdb) info registers eip
eip            0x5655620c          0x5655620c <main+63>

Disassembly for main:
   0x000011cd <+0>:     endbr32
   0x000011d1 <+4>:     lea    ecx,[esp+0x4]
   0x000011d5 <+8>:     and    esp,0xfffffff0
   0x000011d8 <+11>:    push   DWORD PTR [ecx-0x4]
   0x000011db <+14>:    push   ebp
   0x000011dc <+15>:    mov    ebp,esp
   0x000011de <+17>:    push   ebx
   0x000011df <+18>:    push   ecx
   0x000011e0 <+19>:    sub    esp,0x10
   0x000011e3 <+22>:    call   0x120d <__x86.get_pc_thunk.ax>
   0x000011e8 <+27>:    add    eax,0x2df0
   0x000011ed <+32>:    sub    esp,0xc
   0x000011f0 <+35>:    lea    edx,[ebp-0x10]
   0x000011f3 <+38>:    push   edx
   0x000011f4 <+39>:    mov    ebx,eax
   0x000011f6 <+41>:    call   0x1070 <gets@plt>
   0x000011fb <+46>:    add    esp,0x10
   0x000011fe <+49>:    mov    eax,0x0
   0x00001203 <+54>:    lea    esp,[ebp-0x8]
   0x00001206 <+57>:    pop    ecx
   0x00001207 <+58>:    pop    ebx
   0x00001208 <+59>:    pop    ebp
   0x00001209 <+60>:    lea    esp,[ecx-0x4]
   0x0000120c <+63>:    ret

Here, the EIP register was not overwritten and apparently gdb cannot access memory at an overwritten address.
Whereas in this example where the buffer stuff is written in another function:
#include <stdio.h>

void over() {
    char buf[8];
    gets(buf);
}

int main(int argc, char *argv[])
{
    over();
}

AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

Program received signal SIGSEGV, Segmentation fault.
0x41414141 in ?? ()
(gdb) info registers eip
eip            0x41414141          0x41414141

Disassembly for main:
   0x000011f9 <+0>:     endbr32
   0x000011fd <+4>:     push   ebp
   0x000011fe <+5>:     mov    ebp,esp
   0x00001200 <+7>:     and    esp,0xfffffff0
   0x00001203 <+10>:    call   0x1219 <__x86.get_pc_thunk.ax>
   0x00001208 <+15>:    add    eax,0x2dd0
   0x0000120d <+20>:    call   0x11cd <over>
   0x00001212 <+25>:    mov    eax,0x0
   0x00001217 <+30>:    leave
   0x00001218 <+31>:    ret

Disassembly for over:
   0x000011cd <+0>:     endbr32
   0x000011d1 <+4>:     push   ebp
   0x000011d2 <+5>:     mov    ebp,esp
   0x000011d4 <+7>:     push   ebx
   0x000011d5 <+8>:     sub    esp,0x14
   0x000011d8 <+11>:    call   0x1219 <__x86.get_pc_thunk.ax>
   0x000011dd <+16>:    add    eax,0x2dfb
   0x000011e2 <+21>:    sub    esp,0xc
   0x000011e5 <+24>:    lea    edx,[ebp-0x10]
   0x000011e8 <+27>:    push   edx
   0x000011e9 <+28>:    mov    ebx,eax
   0x000011eb <+30>:    call   0x1070 <gets@plt>
   0x000011f0 <+35>:    add    esp,0x10
   0x000011f3 <+38>:    nop
   0x000011f4 <+39>:    mov    ebx,DWORD PTR [ebp-0x4]
   0x000011f7 <+42>:    leave
   0x000011f8 <+43>:    ret

A slightly different message is provided and the EIP is overwritten
Why does this make a difference? Why is the EIP not overwritten when the buffer is created in the main function?
I am using: gcc version 9.3.0 (Ubuntu 9.3.0-17ubuntu1~20.04)
And compiled with: gcc -m32 -g -fno-stack-protector source.c -o vuln -z execstack

A: The difference is pretty arbitrary. The exact prologue/epilogue instruction sequence generated by GCC is different for over() in the second example than it is for main() in the first example. So it crashes it a very different way, from a debugger's point of view. After single-stepping in GDB, you can see why, and I have just killed some time doing so.
The stack is thoroughly corrupt upon returning from gets(), so all bets are off, but anyway, here goes. I run the first example, setting a breakpoint immediately after returning from the call to gets():
(gdb) disassemble main
Dump of assembler code for function main:
   0x0804842b <+0>: lea    0x4(%esp),%ecx
   0x0804842f <+4>: and    $0xfffffff0,%esp
   0x08048432 <+7>: pushl  -0x4(%ecx)
   0x08048435 <+10>:    push   %ebp
   0x08048436 <+11>:    mov    %esp,%ebp
   0x08048438 <+13>:    push   %ecx
   0x08048439 <+14>:    sub    $0x14,%esp
   0x0804843c <+17>:    sub    $0xc,%esp
   0x0804843f <+20>:    lea    -0x10(%ebp),%eax
   0x08048442 <+23>:    push   %eax
   0x08048443 <+24>:    call   0x80482e0 <gets@plt>
   0x08048448 <+29>:    add    $0x10,%esp
   0x0804844b <+32>:    mov    $0x0,%eax
   0x08048450 <+37>:    mov    -0x4(%ebp),%ecx
   0x08048453 <+40>:    leave
   0x08048454 <+41>:    lea    -0x4(%ecx),%esp
   0x08048457 <+44>:    ret
End of assembler dump.
(gdb) b *0x08048448
Breakpoint 1 at 0x8048448: file source.c, line 6.
(gdb)

Now continue to enter some garbage, hit the breakpoint, and start single-stepping:
(gdb) r
Starting program: /home/lstrand/tmp/vuln
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA

Breakpoint 1, 0x08048448 in main (argc=<error reading variable: Cannot access memory at address 0x41414141>,
    argv=<error reading variable: Cannot access memory at address 0x41414145>) at source.c:6
6       gets(buf);
(gdb) disassemble
Dump of assembler code for function main:
   0x0804842b <+0>: lea    0x4(%esp),%ecx
   0x0804842f <+4>: and    $0xfffffff0,%esp
   0x08048432 <+7>: pushl  -0x4(%ecx)
   0x08048435 <+10>:    push   %ebp
   0x08048436 <+11>:    mov    %esp,%ebp
   0x08048438 <+13>:    push   %ecx
   0x08048439 <+14>:    sub    $0x14,%esp
   0x0804843c <+17>:    sub    $0xc,%esp
   0x0804843f <+20>:    lea    -0x10(%ebp),%eax
   0x08048442 <+23>:    push   %eax
   0x08048443 <+24>:    call   0x80482e0 <gets@plt>
=> 0x08048448 <+29>:    add    $0x10,%esp
   0x0804844b <+32>:    mov    $0x0,%eax
   0x08048450 <+37>:    mov    -0x4(%ebp),%ecx
   0x08048453 <+40>:    leave
   0x08048454 <+41>:    lea    -0x4(%ecx),%esp
   0x08048457 <+44>:    ret
End of assembler dump.
(gdb) bt
#0  0x08048448 in main (argc=<error reading variable: Cannot access memory at address 0x41414141>,
    argv=<error reading variable: Cannot access memory at address 0x41414145>) at source.c:6
Backtrace stopped: Cannot access memory at address 0x4141413d
(gdb) stepi
0x0804844b  6       gets(buf);
(gdb)
7   }
(gdb)
0x08048453  7   }
(gdb)
0x08048454  7   }
(gdb)
0x08048457  7   }
(gdb)

Program received signal SIGSEGV, Segmentation fault.
0x08048457 in main (argc=<error reading variable: Cannot access memory at address 0x41414141>,
    argv=<error reading variable: Cannot access memory at address 0x41414145>) at source.c:7
7   }
(gdb) bt
#0  0x08048457 in main (argc=<error reading variable: Cannot access memory at address 0x41414141>,
    argv=<error reading variable: Cannot access memory at address 0x41414145>) at source.c:7
Backtrace stopped: Cannot access memory at address 0x4141413d
(gdb) info reg
eax            0x0  0
ecx            0x41414141   1094795585
edx            0xf7fa589c   -134588260
ebx            0x0  0
esp            0x4141413d   0x4141413d
ebp            0x41414141   0x41414141
esi            0xf7fa4000   -134594560
edi            0x0  0
eip            0x8048457    0x8048457 <main+44>
eflags         0x10286  [ PF SF IF RF ]
cs             0x23 35
ss             0x2b 43
ds             0x2b 43
es             0x2b 43
fs             0x0  0
gs             0x63 99
(gdb)

Here, we die on the ret instruction in main() because the stack pointer esp has the bad value 0x4141413d. GDB correctly pinpoints the failing instruction as being in main().
But what happens in the over() case? Let's take a look:
lstrand@styx:~/tmp$ gdb ./vuln2
GNU gdb (Ubuntu 8.1-0ubuntu3.2) 8.1.0.20180409-git
Copyright (C) 2018 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.  Type "show copying"
and "show warranty" for details.
This GDB was configured as "x86_64-linux-gnu".
Type "show configuration" for configuration details.
For bug reporting instructions, please see:
<http://www.gnu.org/software/gdb/bugs/>.
Find the GDB manual and other documentation resources online at:
<http://www.gnu.org/software/gdb/documentation/>.
For help, type "help".
Type "apropos word" to search for commands related to "word"...
Reading symbols from ./vuln2...done.
(gdb) disassemble over
Dump of assembler code for function over:
   0x0804842b <+0>: push   %ebp
   0x0804842c <+1>: mov    %esp,%ebp
   0x0804842e <+3>: sub    $0x18,%esp
   0x08048431 <+6>: sub    $0xc,%esp
   0x08048434 <+9>: lea    -0x10(%ebp),%eax
   0x08048437 <+12>:    push   %eax
   0x08048438 <+13>:    call   0x80482e0 <gets@plt>
   0x0804843d <+18>:    add    $0x10,%esp
   0x08048440 <+21>:    nop
   0x08048441 <+22>:    leave
   0x08048442 <+23>:    ret
End of assembler dump.
(gdb) b *0x0804843d
Breakpoint 1 at 0x804843d: file source2.c, line 5.
(gdb) r
Starting program: /home/lstrand/tmp/vuln2
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAa

Breakpoint 1, 0x0804843d in over () at source2.c:5
5       gets(buf);
(gdb) disassemble
Dump of assembler code for function over:
   0x0804842b <+0>: push   %ebp
   0x0804842c <+1>: mov    %esp,%ebp
   0x0804842e <+3>: sub    $0x18,%esp
   0x08048431 <+6>: sub    $0xc,%esp
   0x08048434 <+9>: lea    -0x10(%ebp),%eax
   0x08048437 <+12>:    push   %eax
   0x08048438 <+13>:    call   0x80482e0 <gets@plt>
=> 0x0804843d <+18>:    add    $0x10,%esp
   0x08048440 <+21>:    nop
   0x08048441 <+22>:    leave
   0x08048442 <+23>:    ret
End of assembler dump.
(gdb) info reg
eax            0xffffd198   -11880
ecx            0xf7fa45c0   -134593088
edx            0xf7fa589c   -134588260
ebx            0x0  0
esp            0xffffd180   0xffffd180
ebp            0xffffd1a8   0xffffd1a8
esi            0xf7fa4000   -134594560
edi            0x0  0
eip            0x804843d    0x804843d <over+18>
eflags         0x246    [ PF ZF IF ]
cs             0x23 35
ss             0x2b 43
ds             0x2b 43
es             0x2b 43
fs             0x0  0
gs             0x63 99
(gdb) stepi
6   }
(gdb)
0x08048441  6   }
(gdb)
0x08048442  6   }
(gdb) stepi
0x41414141 in ?? ()
(gdb) info reg
eax            0xffffd198   -11880
ecx            0xf7fa45c0   -134593088
edx            0xf7fa589c   -134588260
ebx            0x0  0
esp            0xffffd1b0   0xffffd1b0
ebp            0x41414141   0x41414141
esi            0xf7fa4000   -134594560
edi            0x0  0
eip            0x41414141   0x41414141
eflags         0x286    [ PF SF IF ]
cs             0x23 35
ss             0x2b 43
ds             0x2b 43
es             0x2b 43
fs             0x0  0
gs             0x63 99
(gdb) stepi

Program received signal SIGSEGV, Segmentation fault.
0x41414141 in ?? ()
(gdb)

Note the subtle difference here. In this case, the epilogue code unwinds %esp with simple arithetic: "add $0x10,%esp" (as opposed to restoring it from the stack, as in the first case). The 'leave' instruction puts garbage into the frame pointer %ebp, but the new %esp value obtained from %ebp is still valid. Then the ret instruction sucessfully executes, leaving us a bad ip, 0x41414141. And then the program dies with SIGSEGV trying to read an instruction from nowhere.
In this case, GDB has no hope of unwinding the stack:
Program received signal SIGSEGV, Segmentation fault.
0x41414141 in ?? ()
(gdb) bt
#0  0x41414141 in ?? ()
#1  0x41414141 in ?? ()
#2  0x41414141 in ?? ()
#3  0x41414141 in ?? ()
#4  0x41414141 in ?? ()
#5  0xf7006141 in ?? ()
#6  0xf7fa4000 in ?? () from /lib/i386-linux-gnu/libc.so.6
Backtrace stopped: previous frame inner to this frame (corrupt stack?)
(gdb)

Recall in the first case, the program died on the ret instruction itself because %esp was already bad. In the first case GDB can still find where the program is, but in the second case it cannot.


text:
Q: How to use psake from a batch file? What I want is a one file I can double-click that will run the required build process using psake.
I'm new to psake and PowerShell so be gentle :-).
What I have now are 3 files:
File 1: Build.bat
PowerShell -ExecutionPolicy Unrestricted -File .\Build.ps1 %1

File 2: Build.ps1
Import-Module .\psake.psm1
Invoke-psake .\BuildTasks.ps1 $args

File 3: BuildTasks.ps1
task default -depends Verify, Joe

task Verify {
    write-host "hello from Verify!"
}

task Joe {
    write-host "hello from Joe"
}

Is there anyway to merge Build.ps1 and BuildTasks.ps1 into one file?

A: You should be able to do this with
powershell -Command "& {Import-Module .\psake.psm1; Invoke-psake .\BuildTasks.ps1 %*}"

which gets rid of the build.ps1 file.

A: Psake comes with a powershell script "psake.ps1" which wraps the call for you.  It looks like:
import-module .\psake.psm1
invoke-psake @args
remove-module psake

So your batch script looks like
powershell {path-to-module}\psake.ps1 .\buildTasks.ps1


text:
Q: using Google Contacts Api Import Contacts C# I am using Google Contacts Api. I am not sure whether I can send an Auth Token as a parameter.
string _token = _google.Token;
RequestSettings requestSettings = new RequestSettings("AppName",_token);
ContactsRequest contactsRequest = new ContactsRequest(requestSettings);

// Get the feed
Feed<Contact> feed = contactsRequest.GetContacts();

I get 401 Unauthorised as a response for this code, but if I send the username and password as parameters, I am able to get a response.

A: Whoops, sorry, I didn't quite get it right the first time. I'm using this code in a real app, I just do things a bit different in my code because I'm constantly refreshing tokens.
In any case, here's the proper logic:
        // get this information from Google's API Console after registering your app
        var parameters = new OAuth2Parameters
        {
            ClientId = @"",
            ClientSecret = @"",
            RedirectUri = @"",
            Scope = @"https://www.google.com/m8/feeds/",
        };

        // generate the authorization url
        string url = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);

        // now use the url to authorize the app in the browser and get the access code
        (...)

        // get this information from Google's API Console after registering your app
        parameters.AccessCode = @"<from previous step>";

        // get an access token
        OAuthUtil.GetAccessToken(parameters);

        // setup connection to contacts service
        var contacts = new ContactsRequest(new RequestSettings("<appname>", parameters));

        // get each contact
        foreach (var contact in contacts.GetContacts().Entries)
        {
            System.Diagnostics.Debug.WriteLine(contact.ContactEntry.Name.FullName);
        }

FYI, after you call GetAccessToken() against your access code, your parameters data structure will include the AccessToken and RefreshToken fields.  If you STORE these two values, you can set them in the parameters structure in subsequent calls (allowing you to skip asking for authorization in the future) and instead of calling GetAccessToken() simply call RefreshAccessToken(parameters) and you'll always have access to the contacts.  Make sense?  Here, take a look:
        // get this information from Google's API Console after registering your app
        var parameters = new OAuth2Parameters
        {
            ClientId = @"",
            ClientSecret = @"",
            RedirectUri = @"",
            Scope = @"https://www.google.com/m8/feeds/",
            AccessCode = "",
            AccessToken = "",  /* use the value returned from the old call to GetAccessToken here */
            RefreshToken = "", /* use the value returned from the old call to GetAccessToken here */
        };

        // get an access token
        OAuthUtil.RefreshAccessToken(parameters);

        // setup connection to contacts service
        var contacts = new ContactsRequest(new RequestSettings("<appname>", parameters));

        // get each contact
        foreach (var contact in contacts.GetContacts().Entries)
        {
            System.Diagnostics.Debug.WriteLine(contact.ContactEntry.Name.FullName);
        }

Edit:
            // generate the authorization url
            string url = OAuthUtil.CreateOAuth2AuthorizationUrl(parameters);

            // now use the url to authorize the app in the browser and get the access code
            (...)

            // get this information from Google's API Console after registering your app
            var parameters = new OAuth2Parameters
            {
                ClientId = @"",
                ClientSecret = @"",
                RedirectUri = @"",
                Scope = @"https://www.google.com/m8/feeds/",
                AccessCode = @"<from previous step>",
            };

            // get an access token
            OAuthUtil.GetAccessToken(parameters);

            // setup connection to contacts service
            var contacts = new ContactsRequest(new RequestSettings("<appname>", parameters));

            // get each contact
            foreach (var contact in contacts.GetContacts().Entries)
            {
                System.Diagnostics.Debug.WriteLine(contact.ContactEntry.Name.FullName);
            }


text:
Q: Order by char column numerically How to Sort Character column numerically.
I have a column of numbers stored as chars. When I do a ORDER BY for this column I get the following:
100D
131A
200
21B
30
31000A
etc.

There may be chance of having one Alphabet at the end.
How can I order these chars numerically? Do I need to convert something or is there already an SQL command or function for this?

A: You could use something like:
ORDER BY Cast(regexp_replace(yourcolumn, '[^0-9]', '', 'g') as integer)


text:
Q: How to use vuelidate with vuetify 2 for nested data? Getting invalid field I'm trying to use vuelidate with Vuetify 2 but im getting into trouble when trying to validate a nested object value.
This code works fine:
    <template>
        <v-text-field
        v-model="no_nome"
        :error-messages="nameErrors"
        label="Nome"
        @input="$v.no_nome.$touch()"
        @blur="$v.no_nome.$touch()"
        >
        </v-text-field>
    </template>

    <script>

     import { required } from 'vuelidate/lib/validators'
     export default {

        data() {
            return {
                no_nome:'',
            }
        },
        validations: {
            no_nome: {
                required
            },
        },
        computed: {
            nameErrors () {
                const errors = []
                if (!this.$v.no_nome.$dirty)
                    return errors
                !this.$v.no_nome.required && errors.push('Name is required.')
                return errors
            },
        }
     }
   </scrip>

But if i change my no_nome data to:
        data() {
            return {
                user : {
                   no_nome:'',
                }
            }
        },

and
        <v-text-field
        v-model="user.no_nome"
        :error-messages="nameErrors"
        label="Nome"
        @input="$v.no_nome.$touch()"
        @blur="$v.no_nome.$touch()"
        >
        </v-text-field>

after running $vm0.$v.no_nome.$touch(), $vm0.$v.no_nome.$invalid will always return true even when user.no_nome is not empty. How can i make the validation works for user.no_nome and any other nested data value?

A: You have to use the same data shape between your data and your validations. See Data Nesting.
So your validations must be:
validations: {
  user: {
    no_nome: {
      required
    }
  }
}

and
computed: {
  nameErrors () {
    const errors = []
    if (!this.$v.user.no_nome.$dirty)
      return errors
    !this.$v.user.no_nome.required && errors.push('Name is required.')
    return errors
  }
}

and
<v-text-field
  v-model="user.no_nome"
  :error-messages="nameErrors"
  @input="$v.user.no_nome.$touch()"
  @blur="$v.user.no_nome.$touch()"/>

Example


text:
Q: Array of numbers, how many solutions/ways? Let's say, we have an array/matrix $n \times m$ and we need to find, how many ways can we fill this array with numbers from $\{ 1, \ldots , m\cdot n \}$, but:
1) every number can be used only 1 time
2) every column and every row should be sorted in increasing order
For example, if we have $n = m = 3$, there are 42 different ways to do this.
I was thinking about this problem, but I can't find out any simple formula to compute this for every $n, m$.
We can solve this problem by writnig a program that uses backtracking method/algorithm [1] but it has huge complexity and problem is solved by computer, and I want to know, how to do this by hand.
Sombody told me, that in this problem I can use some kind of Catalan numbers [2] [3], but I'm not sure about this method.
So, what do You think about this problem and its solution?
[1] Backtracking (Wikipedia): http://en.wikipedia.org/wiki/Backtracking
[2] Catalan numbers (Wikipedia): http://en.wikipedia.org/wiki/Catalan_number
[3] Catalan numbers (OEIS): http://oeis.org/A000108

A: These are Young tableaux.  OEIS has the numbers.  For the square case, see A039622.   For the rectangular case, see A060854

A: You are counting the number of standard Young tableaux of shape $(m, m, m, ...)$ (where $m$ occurs $n$ times).  The formula that counts these is called the hook length formula.  It correctly reproduces the answer
$$\frac{9!}{5 \cdot 4 \cdot 4 \cdot 3 \cdot 3 \cdot 3 \cdot 2 \cdot 2} = 42$$
for the example you gave.  The general formula seems annoying to write down.  In the special case $n = 2$ you get Catalan numbers; this is a nice exercise and it is worth trying to prove this with and then without the hook length formula.


text:
Q: Unity - Argument is out of range when creating board Here's is my BoardGenerator.cs
using UnityEngine;
using System;
using System.Collections.Generic;
using Random = UnityEngine.Random;

public class BoardGenerator : MonoBehaviour {

    [Serializable]
    public class Count{
        public int min;
        public int max;

        public Count(int m, int M){
            min = m;
            max = M;
        }
    }

    public int columns = 20;
    public int rows = 20;
    public Count wallCount = new Count (10, 20);
    public Count moneyCount = new Count (10, 15);
    public GameObject floorTiles;
    public GameObject wallTiles;
    public GameObject moneyTiles;
    public GameObject[] enemyTiles;

    private Transform board;
    private List <Vector3> positions = new List<Vector3>();

    void BoardSetup(){
        board = new GameObject ("Board").transform;

        for (int x=-1; x<columns+1; x++) {
            for (int y=-1; y<rows+1; y++){
                GameObject toInstantiate = floorTiles;
                if(x==-1||x==columns||y==-1||y==rows)
                    toInstantiate = wallTiles;

                GameObject instance = Instantiate (toInstantiate, new Vector3 (x, y, 0f), Quaternion.identity) as GameObject;
                instance.transform.SetParent (board);
            }
        }

    }

    Vector3 RandPos(){
        int randomIndex = Random.Range (0, positions.Count);
        Vector3 randPos = positions [randomIndex];
        positions.RemoveAt (randomIndex);
        return randPos;
    }

    void MoneyWallRandom (GameObject tileObj, int m, int M)
    {
        int objectCount = Random.Range (m, M);

        for(int i = 0; i < objectCount; i++)
        {
            Vector3 randomPosition = RandPos();
            GameObject tile = tileObj;
            Instantiate(tile, randomPosition, Quaternion.identity);
        }
    }

    void EnemyRandom (GameObject[] tileObj, int m, int M)
    {
        int objectCount = Random.Range (m, M);

        for(int i = 0; i < objectCount; i++)
        {
            Vector3 randomPosition = RandPos();
            GameObject tile = tileObj[Random.Range (0, tileObj.Length)];
            Instantiate(tile, randomPosition, Quaternion.identity);
        }
    }

    public void BoardSetup (int level)
    {
        BoardSetup ();
        MoneyWallRandom (wallTiles, wallCount.min, wallCount.max);
        MoneyWallRandom (moneyTiles, moneyCount.min, moneyCount.max);
        int enemyCount = level + 3;
        EnemyRandom (enemyTiles, enemyCount, enemyCount);
    }
}

And my GameManager.cs
using UnityEngine;
using System.Collections;

public class GameManager : MonoBehaviour {

    public BoardGenerator boardScript;

    private int level = 1;

    // Use this for initialization
    void Awake () {

        boardScript = GetComponent<BoardGenerator> ();
        InitGame ();
    }

    void InitGame(){
        boardScript.BoardSetup (level);
    }

    // Update is called once per frame
    void Update () {

    }
}

The board is created successfully but enemies and money tiles can't be created for some reasons.
Here are the errors in console
ArgumentOutOfRangeException: Argument is out of range.
Parameter name: index
System.Collections.Generic.List`1[UnityEngine.Vector3].get_Item (Int32 index) (at /Users/builduser/buildslave/mono-runtime-and-classlibs/build/mcs/class/corlib/System.Collections.Generic/List.cs:633)
BoardGenerator.RandPos () (at Assets/_Scripts/BoardGenerator.cs:50)
BoardGenerator.MoneyWallRandom (UnityEngine.GameObject tileObj, Int32 m, Int32 M) (at Assets/_Scripts/BoardGenerator.cs:61)
BoardGenerator.BoardSetup (Int32 level) (at Assets/_Scripts/BoardGenerator.cs:83)
GameManager.InitGame () (at Assets/_Scripts/GameManager.cs:18)
GameManager.Awake () (at Assets/_Scripts/GameManager.cs:14)

I have no idea how I can fix it....

A: tl;dr positions is never being initialized to anything other than an empty list so randomIndex is always 0, so at the line where the exception is being thrown, you are trying to remove an item at index 0, but there are no items in the list, so it throws an exception.
Initialize positions properly and you solve your problem.

It is throwing the exception at this line:
positions.RemoveAt (randomIndex);

This is happening because positions.Count is 0 so
int randomIndex = Random.Range (0, positions.Count);

is equivalent to
int randomIndex = Random.Range (0, 0);

is equivalent to
int randomIndex = 0;

there's nothing to remove from positions at any index, because positions is an empty list.


text:
Q: Raspberry-PI system smart control through android apps How can smartly/remotely control a Raspberry-PI system through android apps. I have found an android app named "Raspberry Control" (source). I have followed all the steps as given in the above URL.
I have installed the android app in my phone (samsung galaxy note, recent release in 2014) followed tried to make a connection of android app with my RPI system (I have followed the steps mentioned in this Youtube video). But as shown in video, when the app started from phone, it needs a SSH connection (showed at 0.25 in the video). Unfortunately, I have faced an error like "check installation on RPi".
Thanks in advance for your precious time. Do I need to install any software on raspberry pi or am I missing any steps?

A:
Secure Shell (SSH) is a network protocol that allows data to be
  exchanged over a secure channel between two computers. Encryption
  provides confidentiality and integrity of data. SSH uses public-key
  cryptography to authenticate the remote computer and allow the remote
  computer to authenticate the user, if necessary. SSH is typically used
  to log into a remote machine and execute commands, but it also
  supports tunneling, forwarding arbitrary TCP ports and X11
  connections; file transfer can be accomplished using the associated
  SFTP or SCP protocols. An SSH server, by default, listens on the
  standard TCP port 22. An SSH client program is typically used for
  establishing connections to an sshd daemon accepting remote
  connections. Both are commonly present on most modern operating
  systems, including Mac OS X, GNU/Linux, Solaris and OpenVMS.
  Proprietary, freeware and open source versions of various levels of
  complexity and completeness exist.
  -Wiki

You found a complete guide/dossier in this link. The install instruction can change depending on the system.
You can control rpi trought ssh simply from windows, linux, android, iOs using a ssh telnet/client. Your app simply after press a button send to rpi the correct ssh comand.
If you have debian(or raspbian) this guide is for you:https://wiki.debian.org/en/SSH.
So, you must enable the ssh service on your rpi. Username and password are user/pass of your rpi account.