text:
Q: Can exec*'s argv contain a value of 0 in multiple places? I was reading that after exec creates a new process,

argv is an array of argument strings, with argv[argc] == 0

What happens if one of the other values within the array argv happens to be 0? Will the number of arguments (argc) be incorrectly calculated when the child process runs?
I read this on page 34 of the ABI of AMD64 (https://software.intel.com/sites/default/files/article/402129/mpx-linux64-abi.pdf).

A: The execve system call (which is used by all exec* functions) has an argument of the form char *const argv[]. The kernel calculates argc by iterating over the supplied argv as follows:
static int count(struct user_arg_ptr argv, int max)
{
    int i = 0;

    if (argv.ptr.native != NULL) {
        for (;;) {
            const char __user *p = get_user_arg_ptr(argv, i);

            if (!p)
                break;

            if (IS_ERR(p))
                return -EFAULT;

            if (i >= max)
                return -E2BIG;
            ++i;

            if (fatal_signal_pending(current))
                return -ERESTARTNOHAND;
            cond_resched();
        }
    }
    return i;
}

The function get_user_arg_ptr essentially calculates an index into the argv array and returns the pointer stored at that index. The loop breaks under four conditions, two of them are pertinent to your question:

*

*On the first NULL seen in the argv array. If there are other pointers following the first NULL in argv, they are ignored. Having more than one NULL smells like a bug in the program that constructed argv.

*When the number of pointers is larger than or equal to MAX_ARG_STRINGS, which is defined as 0x7FFFFFFF. In this case, the system call fails.

The value of i returned is assigned to argc when get_user_arg_ptr returns.
Another case where the terminating NULL in argv matters is when the application itself uses argv as follows:
for(char **p = argv; *p != NULL; ++p)
{
   // ...
}

It's part of the Linux ABI that argv terminates with NULL, so such code is legal and portable across all Linux implementations. By the way, this code is legal too on Windows. Therefore, argc is provided for convenience only.
In addition, both the C and C++ standards state in 5.1.2.2.1 and 3.6.1, respectively, that if argc is larger than zero, then all values in argv[0] through argv[argc-1] shall be non-null pointers to null-terminated strings. Also argv[argc] must be null and that argc is non-negative. See also this answer.


text:
Q: Read and write negative numbers with bits So with the code below i can save a number (for example 2047) into an using bits and then read it back and it will display 2047. How do i do this if i want to do this for negative numbers (for example -2048)
string text = "";
int cnt = 11;
List<int> bits = new List<int>();
for (int i = 11; i >= 0; i--)
{
    int t = (-2048 >> i) & 1;
    bits.Add(t);
}
int value=0;
for(int i=0;i<bits.Count;i++)
{
    text += bits[i];
    value &= ~(1 << cnt);

    if (bits[i] == 1)
    {
        value |= 1 << cnt;
    }
    else
    {
        value |= 0 << cnt;
    }

    cnt--;
}
MessageBox.Show(value+ " " +text);

Also the range of numbers i want this to work with is -2048 to 2047

A: I've figured it out after a while of thinking. Just have to add the following piece of code before the output
if(value> 2047)
{
    value -= 4096;
}

and then -2048 will actually show -2048 instead of 2048

redpajama_set_name: RedPajamaStackExchange


text:
Q: Book on data modeling I'm looking for reference to get a better understanding and overview of the methods for data modeling (mostly related to business questions like finding categories in data and setting of scoring functions for forecasting). After some internet research I couldn't single out a canonical reference. I have some very basic knowledge of statistics and I believe the topics that could be most useful for me would be SVM, Decision Trees, Clustering, Covariance Matrix, Correlations, Multivariate analysis ... just to name some keywords for the direction. Also I'd like to have some foundation to eventually dive into other statistical and data mining topics.
While the reference should introduce the concepts, I'd like it to be fast-paced (not chatty, not too many examples) and mathematically thorough while concentrating on applications. Of course there are specialized books on each topic, but I'd rather learn the basics of all of these topic quickly. So ideally one or two books for all of them together.
I cannot think of a different way to explain :)
Can you suggest good books? Or maybe just help me get some orientation in the vast field of statistics so that I know what to look for.

A: Maybe Elements of Statistical Learning by Hastie, Tibshirani, and Friedman? You can find it on Amazon, or Tibshirani has a free PDF download on his website. It covers a fairly broad range of modern statistical modelling methods with decent rigor and good examples.

A: If you have some knowledge of R (or want to), this new book sounds like it might be useful to you.
R for Business Analytics, A Ohri.
It is a very quick and broad tutorial based overview of using R for many business analytics topics, with one chapter dedicated to data mining (using the R Rattle GUI). Don't expect a lot of formal math though.
*recent review
** It's often useful to learn a lot of the practical aspects of data mining and machine learning by learning alongside specific programming language examples. If you have a particular programming language you prefer, I could try to recommend alternatives.
***One other broad, but gentle, introduction to these areas (less practical examples, and not business based, but more mathematically inclined) is:
Introduction to Machine Learning, Ethem Alpaydin.

edit: In response to your comment. If Python is your language of choice, look no further.
Machine Learning, by Stephen Marsland is hands down the best practical book to pick up many of your requested topics, with many good code based illustrations to actually build and follow along.
On the Pandas side, you might have some interest in a current Coursera course (just 2 weeks in) that is Python oriented, with Python based applications towards Portfolio analysis, financial markets, and simulation backtesting (although it's a bit introductory, the instructor participates in a AI based Hedge Fund consulting firm).  Computational Investing Part 1, Tucker Balch


text:
Q: Perfect secrecy definition My question is we know that perfect secrecy is achieved with the messages in uniform distribution. But what will it be if the message distribution is not uniform ? How will we then define perfect secrecy?

A: To give a convincing answer, it's best to discuss a few possible ways of defining security. The correct definition is not obvious and historically took lots of research and some iteration to approach it.
Most people who think about it agree that a "one-time pad" is perfectly secure in a very strong sense. One-time pad is a very old technique, it was known before WWII and such.
The idea is like this: You are a spy, and I am your spymaster handler. I want to send you abroad to collect secrets and send them back to me. In order that we can communicate, I first create an entire book full of random numbers. (Some machine mechanically flips a coin and prints zero or one, lets say.) I have a copy, and you have a copy, and no one else does.
When you want to send me k bytes of message, you take k bytes from the book, and XOR them with your bytes. (Then you advance your bookmark by k bytes.) When I receive k bytes from you, I XOR them with the next k bytes in the book, and advance my bookmark.
Even if the enemy intercepts all of your messages, if we consider how they would look as a function of the (random) bits in the book, the messages the adversary recieves are distributed as independent coin flips. Indeed for any fixed message that you send, message xor book is perfectly random if the book is random.
So, this scheme is perfectly secure -- the ciphertext is statistically independent of the plaintext, so the adversary can learn nothing about your messages.
The problem with this is that you must exchange as many bytes privately before hand as you will exchange publicly. When you are doing e.g. credit card sales online, you cannot assume that there is a private exchange of key material beforehand. So it's important to be able to reduce the amount of key material needed.
On the other hand, if you reduce the key material to less than k bytes for a k byte message, then provably you will not achieve this level of security. The cipher text distribution will have to be different for different messages -- even you can show that there is large statistical distance between them as the number of bytes gets small.
In modern cryptography, the usual way to relax the definition is to try to restrict attention to computationally bounded adversaries.
One way of formalizing statistical distance of two distributions, D1 and D2, is to say that the distance is the maximum over all test functions T : { strings } -> { 0, 1 } of the difference in expectations E_{x ~ D_1} [ T(x) ] versus E_{x ~ D_2} [ T(x) ].
Then, we can modify the definition by focusing only on test functions T which are efficiently computable, say, in polynomial time, or subexponential time, or something. (Usually that something is the "security parameter".)
If the statistical distance of D1 and D2 is small for computationally bounded adversaries, we sometimes say, D1 and D2 are indistinguishable.
Then, we can say that a cryptographic protocol is secure if, for any fixed message m, over the probability in the random seed / key, the distribution of the cipher text is indistinguishable from the uniform distribution.
It is widely believed, under reasonable cryptographic assumptions, that this can be achieved even for keys which are much shorter than the message. But this cannot be proved rigorously to be true without proving P != NP and many other difficult things. We would need more rigorous constructions of pseudorandom generators, for example, even in the case that the generator is more expensive to compute than the adversary, which is still not known.
Note that in this formalism, it doesn't matter what the message distribution is. Whether you are taking your messages, and then compressing them, and then encrypting them, or encrypting plain english text, the goal is that for every fixed message string, the randomness in the seed / key is enoguh to produce a distribution that fools your adversary.
There are other ways you could formalize security, but I think this is a decent way to do it.

Key point:
If the security condition holds for any fixed message, then it also holds for any fixed distribution of messages, by an averaging argument. That makes this definition very robust.


text:
Q:  tag with clickable link with  tag inside So I m using a  tag with a whole block used as a link, it is a product display so you click it it goes to product page. Now on in that  I created an  tag as a button for a link to the cart page. So I have it working, but when i click the CART button both pages open the product and the cart. I know its doing that because the cart button is within the block that is a link. I did 2 versions and they both don't work!
But how do I fix it ??
version1:

MacBook

Intel Core 2 Duo processor Powered by an Intel Core 2 Duo processor at speeds up to 2.1..

$3000 USD

       Add to cart

Version2:

MacBook

Intel Core 2 Duo processor Powered by an Intel Core 2 Duo processor at speeds up to 2.1..

$3000 USD

       Add to cart

A: You can use stopPropagation. Without seeing your code can't be 100% sure but something like this:
$(a).click(function(event){
    event.stopPropagation();
});

A: It's because of event bubbling, you need to use event.stopPropagation() to avoid this behaviour.

MacBook

Intel Core 2 Duo processor Powered by an Intel Core 2 Duo processor at speeds up to 2.1..

$3000 USD

         Add to cart

A: You can just use onclick and the location.href and by passsing link inside this,

 ....

A: You need to stop the event from bubbling up the DOM tree with event.stopPropagation().

MacBook

Intel Core 2 Duo processor Powered by an Intel Core 2 Duo processor at speeds up to 2.1..

$3000 USD

       Add to cart


text:
Q: What is the computational complexity of this algorithm? What is the computational complexity of the following algorithm?
for(int i = n; i = 1; i = i / 2) {
    for(int j = 1; j < n; j = j * 2) {
        System.out.println("i="+i+", j="+j);
    }

A: The outer loop is O(log(n)), since every step, I is cut in half, so to increase the number of steps the loop takes by one, you'd have to double i.
The inner loop is also O(log(n)), for a similar reason.
Thus, the overall complexity is O(log^2(n))


text:
Q: Get next N elements from enumerable Context: C# 3.0, .Net 3.5
Suppose I have a method that generates random numbers (forever):
private static IEnumerable<int> RandomNumberGenerator() {
    while (true) yield return GenerateRandomNumber(0, 100);
}

I need to group those numbers in groups of 10, so I would like something like:
foreach (IEnumerable<int> group in RandomNumberGenerator().Slice(10)) {
    Assert.That(group.Count() == 10);
}

I have defined Slice method, but I feel there should be one already defined. Here is my Slice method, just for reference:
    private static IEnumerable<T[]> Slice<T>(IEnumerable<T> enumerable, int size) {
        var result = new List<T>(size);
        foreach (var item in enumerable) {
            result.Add(item);
            if (result.Count == size) {
                yield return result.ToArray();
                result.Clear();
            }
        }
    }

Question: is there an easier way to accomplish what I'm trying to do? Perhaps Linq?
Note: above example is a simplification, in my program I have an Iterator that scans given matrix in a non-linear fashion.
EDIT: Why Skip+Take is no good.
Effectively what I want is:
var group1 = RandomNumberGenerator().Skip(0).Take(10);
var group2 = RandomNumberGenerator().Skip(10).Take(10);
var group3 = RandomNumberGenerator().Skip(20).Take(10);
var group4 = RandomNumberGenerator().Skip(30).Take(10);

without the overhead of regenerating number (10+20+30+40) times. I need a solution that will generate exactly 40 numbers and break those in 4 groups by 10.

A: I have done something similar. But I would like it to be simpler:
//Remove "this" if you don't want it to be a extension method
public static IEnumerable<IList<T>> Chunks<T>(this IEnumerable<T> xs, int size)
{
    var curr = new List<T>(size);

    foreach (var x in xs)
    {
        curr.Add(x);

        if (curr.Count == size)
        {
            yield return curr;
            curr = new List<T>(size);
        }
    }
}

I think yours are flawed. You return the same array for all your chunks/slices so only the last chunk/slice you take would have the correct data.
Addition: Array version:
public static IEnumerable<T[]> Chunks<T>(this IEnumerable<T> xs, int size)
{
    var curr = new T[size];

    int i = 0;

    foreach (var x in xs)
    {
        curr[i % size] = x;

        if (++i % size == 0)
        {
            yield return curr;
            curr = new T[size];
        }
    }
}

Addition: Linq version (not C# 2.0). As pointed out, it will not work on infinite sequences and will be a great deal slower than the alternatives:
public static IEnumerable<T[]> Chunks<T>(this IEnumerable<T> xs, int size)
{
    return xs.Select((x, i) => new { x, i })
             .GroupBy(xi => xi.i / size, xi => xi.x)
             .Select(g => g.ToArray());
}

A: Using Skip and Take would be a very bad idea. Calling Skip on an indexed collection may be fine, but calling it on any arbitrary IEnumerable<T> is liable to result in enumeration over the number of elements skipped, which means that if you're calling it repeatedly you're enumerating over the sequence an order of magnitude more times than you need to be.
Complain of "premature optimization" all you want; but that is just ridiculous.
I think your Slice method is about as good as it gets. I was going to suggest a different approach that would provide deferred execution and obviate the intermediate array allocation, but that is a dangerous game to play (i.e., if you try something like ToList on such a resulting IEnumerable<T> implementation, without enumerating over the inner collections, you'll end up in an endless loop).
(I've removed what was originally here, as the OP's improvements since posting the question have since rendered my suggestions here redundant.)

A: Let's see if you even need the complexity of Slice. If your random number generates is stateless, I would assume each call to it would generate unique random numbers, so perhaps this would be sufficient:
var group1 = RandomNumberGenerator().Take(10);
var group2 = RandomNumberGenerator().Take(10);
var group3 = RandomNumberGenerator().Take(10);
var group4 = RandomNumberGenerator().Take(10);

Each call to Take returns a new group of 10 numbers.
Now, if your random number generator re-seeds itself with a specific value each time it's iterated, this won't work. You'll simply get the same 10 values for each group. So instead, you would use:
var generator  = RandomNumberGenerator();
var group1     = generator.Take(10);
var group2     = generator.Take(10);
var group3     = generator.Take(10);
var group4     = generator.Take(10);

This maintains an instance of the generator so that you can continue retrieving values without re-seeding the generator.

A: Are Skip and Take of any use to you?
Use a combination of the two in a loop to get what you want.
So,
list.Skip(10).Take(10);

Skips the first 10 records and then takes the next 10.

A: You could use the Skip and Take methods with any Enumerable object.
For your edit :
How about a function that takes a slice number and a slice size as a parameter?
private static IEnumerable<T> Slice<T>(IEnumerable<T> enumerable, int sliceSize, int sliceNumber) {
    return enumerable.Skip(sliceSize * sliceNumber).Take(sliceSize);
}

A: It seems like we'd prefer for an IEnumerable<T> to have a fixed position counter so that we can do
var group1 = items.Take(10);
var group2 = items.Take(10);
var group3 = items.Take(10);
var group4 = items.Take(10);

and get successive slices rather than getting the first 10 items each time. We can do that with a new implementation of IEnumerable<T> which keeps one instance of its Enumerator and returns it on every call of GetEnumerator:
public class StickyEnumerable<T> : IEnumerable<T>, IDisposable
{
    private IEnumerator<T> innerEnumerator;

    public StickyEnumerable( IEnumerable<T> items )
    {
        innerEnumerator = items.GetEnumerator();
    }

    public IEnumerator<T> GetEnumerator()
    {
        return innerEnumerator;
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return innerEnumerator;
    }

    public void Dispose()
    {
        if (innerEnumerator != null)
        {
            innerEnumerator.Dispose();
        }
    }
}

Given that class, we could implement Slice with
public static IEnumerable<IEnumerable<T>> Slices<T>(this IEnumerable<T> items, int size)
{
    using (StickyEnumerable<T> sticky = new StickyEnumerable<T>(items))
    {
        IEnumerable<T> slice;
        do
        {
            slice = sticky.Take(size).ToList();
            yield return slice;
        } while (slice.Count() == size);
    }
    yield break;
}

That works in this case, but StickyEnumerable<T> is generally a dangerous class to have around if the consuming code isn't expecting it. For example,
using (var sticky = new StickyEnumerable<int>(Enumerable.Range(1, 10)))
{
    var first = sticky.Take(2);
    var second = sticky.Take(2);
    foreach (int i in second)
    {
        Console.WriteLine(i);
    }
    foreach (int i in first)
    {
        Console.WriteLine(i);
    }
}

prints
1
2
3
4

rather than
3
4
1
2

A: Take a look at Take(), TakeWhile() and Skip()

A: I think the use of Slice() would be a bit misleading. I think of that as a means to give me a chuck of an array into a new array and not causing side effects. In this scenario you would actually move the enumerable forward 10.
A possible better approach is to just use the Linq extension Take(). I don't think you would need to use Skip() with a generator.
Edit: Dang, I have been trying to test this behavior with the following code
Note: this is wasn't really correct, I leave it here so others don't fall into the same mistake.
var numbers = RandomNumberGenerator();
var slice = numbers.Take(10);

public static IEnumerable<int> RandomNumberGenerator()
{
    yield return random.Next();
}

but the Count() for slice is alway 1. I also tried running it through a foreach loop since I know that the Linq extensions are generally lazily evaluated and it only looped once. I eventually did the code below instead of the Take() and it works:
public static IEnumerable<int> Slice(this IEnumerable<int> enumerable, int size)
{
    var list = new List<int>();
    foreach (var count in Enumerable.Range(0, size)) list.Add(enumerable.First());
    return list;
}

If you notice I am adding the First() to the list each time, but since the enumerable that is being passed in is the generator from RandomNumberGenerator() the result is different every time.
So again with a generator using Skip() is not needed since the result will be different. Looping over an IEnumerable is not always side effect free.
Edit: I'll leave the last edit just so no one falls into the same mistake, but it worked fine for me just doing this:
var numbers = RandomNumberGenerator();

var slice1 = numbers.Take(10);
var slice2 = numbers.Take(10);

The two slices were different.

A: I had made some mistakes in my original answer but some of the points still stand. Skip() and Take() are not going to work the same with a generator as it would a list. Looping over an IEnumerable is not always side effect free. Anyway here is my take on getting a list of slices.
    public static IEnumerable<int> RandomNumberGenerator()
    {
        while(true) yield return random.Next();
    }

    public static IEnumerable<IEnumerable<int>> Slice(this IEnumerable<int> enumerable, int size, int count)
    {
        var slices = new List<List<int>>();
        foreach (var iteration in Enumerable.Range(0, count)){
            var list = new List<int>();
            list.AddRange(enumerable.Take(size));
            slices.Add(list);
        }
        return slices;
    }

A: I got this solution for the same problem:
int[] ints = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
IEnumerable<IEnumerable<int>> chunks = Chunk(ints, 2, t => t.Dump());
//won't enumerate, so won't do anything unless you force it:
chunks.ToList();

IEnumerable<T> Chunk<T, R>(IEnumerable<R> src, int n, Func<IEnumerable<R>, T> action){
  IEnumerable<R> head;
  IEnumerable<R> tail = src;
  while (tail.Any())
  {
    head = tail.Take(n);
    tail = tail.Skip(n);
    yield return action(head);
  }
}

if you just want the chunks returned, not do anything with them, use chunks = Chunk(ints, 2, t => t). What I would really like is to have to have t=>t as default action, but I haven't found out how to do that yet.


text:
Q: Inject an instance of an IOptions<> I need to access the value of my JwtSettings. I try to inject an instance of an IOptions<> class into the constructor of my class, but I got the problem:
 public class JwtHandler : IJwtHandler
 {
    private readonly JwtSettings _jwtSettings;

    public JwtHandler(IOptions<JwtSettings> jwtSettings)
    {
        jwtSettings = _jwtSettings.Value;
    }
 }

I have error:
The type or namespace name 'IOptions<>' could not be found
(are you missing a using directive or an assembly reference?)

When Im adding the using:
using Microsoft.Extensions.Options;

VS is telling me that it is unnecesary.
Updated: My Assemblies:
Microsoft.IdentityModel.Tokens
System.IdentityModel.Tokens.Jwt

A: IOptions<T> is definitely in the Microsoft.Extensions.Options namespace, so that is the using you need:
using Microsoft.Extensions.Options

As far as why it might be telling you it's unnecessary, that's a brain-scratcher. The only thing I can think of is that something is borked in your project. Open your project folder and delete the bin and obj directories. Then rebuild your project. If it's still not working, you may have a version conflict. Check any referenced projects, and if any are explicitly including Microsoft.Extensions.Configuration, Microsoft.AspNetCore, etc. ensure that they're all referencing the same versions of the those NuGet packages.


text:
Q: Create a lookup filter for a dialox in Dynamics AX 4.0 I'm trying to create a custom lookup filter in a dialog in AX.
I've followed the instructions in this post x++ filter lookup in dialog and am getting a Stack Trace error -- FormRun object not initialized -- when I'm run my code.
What I am trying to do is filter the lookup() for the ConfigId EDT based on the selection from the ItemId EDT. I have the custom lookup() ready to go and working properly, I just can't get it called from my dialog box.
public Object dialog(DialogRunbase _dialog, boolean _forceOnClient)
{
    DialogRunBase   dialog;
    ;

    dialog = super(_dialog, true);

    dialog.caption('@RID2885');

    dfItem = dialog.addField(typeid(ItemId));
    dfInventLoc = dialog.addField(typeid(InventLocationId));
    dfReplaceCost = dialog.addField(typeid(PdsCost));
    dfItemConfig = dialog.addField(typeid(ConfigId));
    dfColorId = dialog.addField(typeid(InventColorId), '@RID101');

    return dialog;
}

Here's the call to the lookup():
void Fld_7_lookup()
{
    Formrun fr = this.dialogModify().parmDialog();
    Object control = fr.controlCallingMethod();
    ;

    ConfigTable::lookupConfigIdSimple(control, dfItem.value());
}

And this is where it keeps getting the Stack Trace error:
public void dialogPostRun(DialogRunbase _dialog)
{
    ;
     super(_dialog);
    **_dialog.formRun().controlMethodOverload(true);** // Causes Stack Trace error
    _dialog.formRun().controlMethodOverloadObject(this);
}

I have tried multiple configurations with the dialog box. When the code reaches that point, it still has information passed in from the dialog() method, but when it goes to get the FormRun, that object is blank.
Could someone please help me understand why there is no FormRun object associated with the DiaglogRunBase that is passed-in?
Thanks.

A: Mayby you should call super(_dialog) last in the dialogPostRun method.
Have a look on a similar solution and one more.

A: Did you check to see if your class is set to run at "Called From"?
Here is an example code for overriding the modified method. Maybe lookup has the same requirements:
public void dialogPostRun(DialogRunbase _dialog)
{
// Must be overriden to enable overriding modified method
;
    _dialog.dialogForm().formRun().controlMethodOverload(true);
    _dialog.dialogForm().formRun().controlMethodOverloadObject(this);
    _dialog.formRun().controlMethodOverload(true);
    _dialog.formRun().controlMethodOverloadObject(this);

    super(_dialog);
}

And for the custom method:
boolean Fld2_1_modified()
{
    FormStringControl c = dialog.formrun().controlCallingMethod();
    boolean ret;
    ;

    ret = c.modified(); // Super() Call the FormControl ->modified

    dlgCustomField.value(MyClass::someMethod(dlgCustomField.value())); // example

    return ret;
}


text:
Q: mBluetoothGatt.getService(uuid) returns null In my app , i am passng the UUID number of the hearing aid service as in the BLE sample from google i.e. 0000a00-0000-1000-8000-00805f9b34fb
But the getservice returns null means that the service is not supported by the BluetoothGatt .
Why is this happening , can anybody please help me .

A: You have to first discover all services for the given device per documentation.

This function requires that service discovery has been completed for the given device.
  http://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#getService(java.util.UUID)

@Override
    // New services discovered
    public void onServicesDiscovered(BluetoothGatt gatt, int status) {
        if (status == BluetoothGatt.GATT_SUCCESS) {
            BluetoothGattService mBluetoothGattService = mBluetoothGatt.getService(UUID.fromString(serviceUUID));
            if (mBluetoothGattService != null) {
                Log.i(TAG, "Service characteristic UUID found: " + mBluetoothGattService.getUuid().toString());
            } else {
                Log.i(TAG, "Service characteristic not found for UUID: " + serviceUUID);
        }
    }

Or you can just run a search
for (BluetoothGattService gattService : gattServices) {
    Log.i(TAG, "Service UUID Found: " + gattService.getUuid().toString());
}

A: Try doing a full discover[1] of the remote database and then iterate through the services. Maybe you've got the UUID wrong.
[1] http://developer.android.com/reference/android/bluetooth/BluetoothGatt.html#discoverServices()

A: Your UUID is also wrong. It should be 0000a00X-0000-1000-8000-00805f9b34fb, not 0000a00-0000-1000-8000-00805f9b34fb


text:
Q: How to set up python interpreter for pyCharm for Mercurial Hooks I am very new to Python and am trying to learn it so that I can write Mercurial hooks (https://www.mercurial-scm.org/wiki/MercurialApi).
I downloaded PyCharm by Jetbrains with the hope that I could start writing a  python script and have the IDE autocomplete for me so I could see what available functions objects have etc. I started with this:
#!/usr/bin/env python

from mercurial import ui, hg
# change . to the path to the repo
repo = hg.repository(ui.ui(), '.')

ui.warn('asdfsadf')

However, as no Python Interpreter is configured, I can't autocomplete (or, at least that's what I think the issue is). I do have Mercurial installed, and when I do pip list I do see the library listed, but PyCharm doesn't know about it. How do I configure thing so that the libraries I want recognized by the IDE get recognized? I know that there are settings which can be set, but I don't understand which ones I want for my purpose.

A: I found that this post How do I import modules in pycharm? helped me a lot to add the appropriate project interpreter.


text:
Q: Scripting on Mac to automate creation of project folder structure and Mercurial repository/subrepository cloning I frequently (more than once a week) create new 'projects' on my development machine (Mac).  I'm trying to streamline the workflow and automate what I do manually now:

*

*Create a project folder structure (I have a template directory structure which I copy)

*Clone (Mercurial) a boilerplate source code baseline into the newly created folder structure

*Clone another (Mercurial) repository as a sub-repository of the above baseline repository

*Modify .hgsub config file (Mercurial) to set up sub-repository

*Modify hgrc config file (Mercurial) to set up default push folder

*Do an initial commit (Mercurial)

*Create a series of aliases in my bash_profile

What's the best (or easiest) way to script the above workflow?  I'd like to pass a couple of parameters such as project name, and sub-repository name, etc.
Is this something that I can easily to in a shell script?  Automator?  Python script?
Thanks.
Prembo.

A:
The steps in your manual workflow can become the steps in a shell
  script quite literally. One difference is that you might use sed to
  modify files rather than open them in an editor. You'd use positional
  parameters or getopts to pass in your parameters. See man bash for
  information on those. Then come back and ask specific focused
  questions.
-- Dennis Williamson


text:
Q: Tensorflow: Export graph with remove_training_nodes gives error I'm trying to export a graph but when I use graph_util.remove_training_nodes I receive the following error:
ValueError: graph_def is invalid at node 'map/while/decode_image/Substr/pos': More inputs specified ('map/while/Switch:1') than the op expects..

I think the problem is with tf.map_fn since remove_training_nodes removes nodes necessary for it. When I don't include graph_util.remove_training_nodes I don't receive the error but I need to add it to reduce the size of the model. My code is the following:
with tf.Session() as sess:
    # Run the init operation.
    sess.run(init_op)

    '''
    Pre-process the image
    '''
    image_bytes_placeholder = tf.placeholder(tf.string, name=bytes_input_node_name)
    preped_images = tf.map_fn(preprocessing_operation, image_bytes_placeholder, dtype=tf.float32)
    input_placeholder = tf.identity(preped_images, name=array_input_node_name)          # Explicit name (we can't name the map_fn)

    '''
    Construct the network
    '''
    net = models.GoogleNet({'data': input_placeholder})
    net.load(model_data_path, sess)

    '''
    Create Graph
    '''
    graph = tf.get_default_graph()
    input_graph_def = graph.as_graph_def()

    '''
    Freeze
    '''
    output_node_names='loss'
    output_graph_def = graph_util.convert_variables_to_constants(
                            sess,
                            input_graph_def,
                            output_node_names.split(",")
    )
    output_graph_def = graph_util.remove_training_nodes(output_graph_def)

    '''
    Quantize Graph
    '''
    input_names = ['image_bytes']
    output_names = ['loss']
    transforms = ['quantize_weights quantize_nodes strip_unused_nodes']
    transformed_graph_def = TransformGraph( output_graph_def, input_names,
                                            output_names, transforms)

    ''' Create export session '''
    graph_export = tf.Graph()
    with graph_export.as_default():
        tf.import_graph_def(output_graph_def, name='')

    sess_export = tf.Session(graph=graph_export)


text:
Q: Sort a list according two items inside tuples- Python I will appreciate some help to fix my code and take the right results.
Let's say that my lists(tuple inside a list) may have that 3 outputs for example:
list1 = [('a', 3.30, '' ,'' ), ('b', 3.20, '' , '' ), ......]

list2 = [('a', 3.30, 2.90, '' ), ('b', 3.20, 2.95, '' ), ........]

list3 = [('a', 3.30, 2.90, '' ), ('b', 3.20, '' , ''), ........]

My lists always have a price in [1] place and sometimes have in [2] place.
I want to sort my list according all that prices.
My code below works good for example list1 and example list2.
from operator import itemgetter
sort_list = sorted(list, key=itemgetter(1))
sort_list = sorted(sort_list, key=itemgetter(2))
print(sort_list)

But for list3 doesn't work well, because it recognize the empty cell of [2] and it shorted first.
I would like to ignore the price of an empty cell, if there is. So the print output for list3 should be
('a', 3.30, 2.90, '' ), ('b', 3.20, '' , '').
Because, 2.90 < 3.20 and I ignore the empty space
Thank you

A: Answering problem as written:
Use a key function of lambda tup: [x for x in tup[2:0:-1] if not isinstance(x, str)]. Don't bother to sort twice, this sorts on both values at once in a single pass:
list3 = [('a', 3.30, 2.90, '' ), ('b', 3.20, '' , '')]
sort_list = sorted(list3 , key=lambda tup: [x for x in tup[2:0:-1] if not isinstance(x, str)])
print(sort_list)

which outputs:
[('a', 3.3, 2.9, ''), ('b', 3.2, '', '')]

To example the key function here, it slices out indexes 2 and 1, in that order. When one of them is a str, it omits it, otherwise it keeps it as part of the key. So ('a', 3.3, 2.9, '') produces a key value of [2.9, 3.3], while ('b', 3.2, '', '') produces a key value of [3.2] alone.
I'll warn you that this will confuse anyone maintaining your code; in normal code, you compare position n to position n unconditionally, you don't have cases where position n doesn't exist in one element, causing you instead compare position n to position n-1 in the other element.
Also note that Python doesn't allow you to use commas for the decimal point; if the desired value is three and two tenths, the literal you want is 3.20 (or equivalently, 3.2), not 3,20 (which is not equivalent to 3,2); the former is the numeric value intended, the latter is a tuple of two ints (3 and 20 as unrelated values). You might think 3,20 works, but only because you zero padded your fractional component, so when comparing the tuples it compares the integer component first, then the fractional component (which, thanks to being padded, compares correctly). If you ever compared 3,3 to 3,20 though, you'd get incorrect sorting, because while 3.3 is greater than 3.20 (the trailing zero is irrelevant), 3,3 is less than 3,20 (because the 3s are equal, and 20 is greater than 3). If decimal level precision is needed, use the decimal.Decimal type, but if this is toy code, use float; using a tuple of two ints is typically more error prone than either of the other options.


text:
Q: Gmaps4rails how create markers list My code:
Location model:
class Location < ActiveRecord::Base
  attr_accessible :latitude, :longitude, :timestamp, :user_id, :user
  validates :latitude, :longitude, :timestamp, :user, :presence => true
  belongs_to :user

  def gmaps4rails_sidebar
    "#{user}"
  end
end

Controller:
@locations = []
User.all.each do |user|
    if user.role?('manager')
        last_location = user.locations.last
      if last_location
        location = {}
        location[:lat] = last_location.latitude
        location[:lng] = last_location.longitude
        location[:title] = last_location.timestamp
        location[:infowindow] = "#{t(:datetime)}: #{last_location.created_at}
#{t(:latitude)}: #{last_location.latitude}
#{t(:longitude)}: #{last_location.longitude}
#{t(:user)}: #{user.username}"
        @locations << location
      end
    end
end

View:
<%= javascript_include_tag 'locations' %>

I want to display a list of markers. I read how it was done in the old version gem. But do not know how to do it in the new version. Prompt as gem in the new version you can list markers to a separate list?

A: I find example http://apneadiving.github.io/


text:
Q: How does one delete a concept using its ID (node gRCP client) I using Clarifai to simplifai custom model training for a client.
I want to expose the CRUD API for inputs, annotations and concepts.
I am unable to find how to delete concepts using the gRCP node client (V7.4)
Please help me figure out how to delete concepts having only the concept's id
There seems to be a way to delete concepts using inputs : https://docs.clarifai.com/api-guide/data/create-get-update-delete
The docs do not reveal how to delete concepts :
https://docs.clarifai.com/portal-guide/concept/concepts

A: If you mean removing a concept completely from your app, that's not possible. A concept cannot be hard deleted yet in Clarifai.


text:
Q: how to remove white gap around an image (bootstrap card)

Add To Cart In PHP

                <?php
                $sql="select * from products";
                $res=$con->query($sql);
                if($res->num_rows>0)
                {
                    while($row=$res->fetch_assoc())
                    {
                        echo '

'. $row['PNAME'] .'

                        ';
                    }
                }
                ?>

image
If you look close at the above image, you can see the white gap at left side of the image card.  How do you clear that?  Is there any css or bootstrap code to clear the white gap?

A: Please try below code, it should solve the problem:


text:
Q: NoMethodError in ChatRoomMessagesController I am doing an AJAX call as the following and trying to parse the JSON recieved in Rails as bellow
AJAX
local_data = {chat:{room_name: chatRoomName ,message: message}}
      $.ajax({
        type: "POST",
        url: '/chat_notify',
        dataType: 'json',
        async : false,
        data: local_data,
        success: function(data) {
            alert("working");
        }
      });

Ruby
def notify
    #data = ActiveSupport::JSON.decode(params)

    #chat_room = ChatRoom.where(:slug =>  data.chat.name)
    #puts @chat_room

    puts params.chat
    RestClient.post 'https://api.pushbots.com/push/all',
    { "platform" => [0,1] ,
      "msg" => "Harsha sent a message." ,
      "sound" => "pulse",
      "alias" => "harsha@mink7.com",
      "badge" => "1",
      "payload" => { "type" => "Chat", "chat_id" => 1 } }.to_json,
      headers = { "x-pushbots-appid" => APP_CONFIG['PUSHBOTS_APPID'],
                  "x-pushbots-secret" => APP_CONFIG['PUSHBOTS_SECRET'],
                  :content_type => :json }

    render json: true
  end

Error

A: You need to paste your error trace
But I think the problem might in below
puts params.chat
there is no chat method for params , just remove it
or
…………"payload" => { "type" => "Chat", "chat_id" => 1 } }.to_json
you need require 'json' to make .to_json available


text:
Q: AM335x - Custom Board  when running Systemd I tried asking my question on TI's forum, but I am not getting much feedback, so I thought I'd try my luck here.
You can see my ongoing discussion with TI here: https://e2e.ti.com/support/processors-group/processors/f/processors-forum/1158936/am3359-caught-segv-when-distro-s-systemd-starting
We have been working with the TI AM335x-ICEV2 board for some time now to develop an embedded Linux Application and received our own custom board design. After a lot of debugging and reading, I am able to make U-Boot load properly and then I went on to load the kernel with a very basic FDT (run-time configuration of U-Boot via a flattened devicetree) which seems to work, but as soon as I reach the distribution booting stage, I get segmentation fault on segmentation fault and/or freezing execution.
At first we suspected hardware issue with the DDR3 mapping, but the design seems to respect all of TI's requirements. Also the freeze/segv always happens during distribution boot. I have never seen a single crash/freeze/segv during U-Boot or Linux Kernel bootings.
The only successful configuration I could get to boot, is the Tiny Filesystem from TI-Linux-SDK that uses SysVinit and loads no module at all. Any systemd os has failed so far (Debian and Arago) and I tried replacing Systemd by a SysV in an existing Debian 10 image, but it failed.
Although the same Uboot + Kernel runs perfectly on a TI IceV2 dev. board.
I am far from being a Linux Bootloader/Kernel pro and I am running out of theories on what could cause this issue or even what tests to run. If someone is willing to answer a few questions, I am more than willing to share some data.
Here is my console output when booting:
I removed this one for an updated one beneath, due to the limit of characters.
And here is my FDT File:
/dts-v1/;

#include "am33xx.dtsi"

/ {
    model = "AM335x HELLO";
    compatible = "ti,am335x-hello", "ti,am33xx";

    chosen {
        stdout-path = &uart3;
        tick-timer = &timer2;
    };

    memory {
        device_type = "memory";
        reg = <0x80000000 0x10000000>; /* 256 MB */
    };

    vbat: fixedregulator@0 {
        compatible = "regulator-fixed";
        regulator-name = "vbat";
        regulator-min-microvolt = <5000000>;
        regulator-max-microvolt = <5000000>;
        regulator-boot-on;
    };

    vmmc: fixedregulator@1 {
        compatible = "regulator-fixed";
        regulator-name = "vmmc";
        regulator-min-microvolt = <3300000>;
        regulator-max-microvolt = <3300000>;
        regulator-always-on;
        regulator-boot-on;
    };
};

&am33xx_pinmux {
    mmc0_pins_default: mmc0_pins_default {
        pinctrl-single,pins = <
            AM33XX_PADCONF(AM335X_PIN_MMC0_DAT3, PIN_INPUT_PULLUP, MUX_MODE0)
            AM33XX_PADCONF(AM335X_PIN_MMC0_DAT2, PIN_INPUT_PULLUP, MUX_MODE0)
            AM33XX_PADCONF(AM335X_PIN_MMC0_DAT1, PIN_INPUT_PULLUP, MUX_MODE0)
            AM33XX_PADCONF(AM335X_PIN_MMC0_DAT0, PIN_INPUT_PULLUP, MUX_MODE0)
            AM33XX_PADCONF(AM335X_PIN_MMC0_CLK, PIN_INPUT_PULLUP, MUX_MODE0)
            AM33XX_PADCONF(AM335X_PIN_MMC0_CMD, PIN_INPUT_PULLUP, MUX_MODE0)
        >;
    };

    uart1_pins: uart1_pins {
        pinctrl-single,pins = <
            0x180 (PIN_INPUT_PULLUP | MUX_MODE0)    /* uart1_rxd.uart1_rxd */
            0x184 (PIN_OUTPUT_PULLDOWN | MUX_MODE0) /* uart1_txd.uart1_txd */
        >;
    };
};

&uart1 {
    pinctrl-names = "default";
    pinctrl-0 = <&uart1_pins>;
    status = "okay";
};

&mmc1 {
    status = "okay";
    vmmc-supply = <&vmmc>;
    bus-width = <4>;
    pinctrl-names = "default";
    pinctrl-0 = <&mmc0_pins_default>;
};

EDIT #1
Initialisation Logs do not always crash/freeze at the same place. here is another one but with U-Boot optargs printk.devkmsg=on systemd.log_level=debug debug:
[    2.175611] Run /sbin/init as init process
[    2.863478] systemd[1]: System time before build time, advancing clock.
[    2.996170] systemd[1]: systemd 241 running in system mode. (+PAM +AUDIT +SELINUX +IMA +APPARMOR +SMACK +SYSVINIT +UTMP +LIBCRYPTSETUP +GCRYPT +GNUTLS +ACL +XZ +LZ4 +SECCOMP +BLKID +ELFUTILS +KMOD -IDN
2 +IDN -PCRE2 default-hierarchy=hybrid)
[    3.018180] systemd[1]: No virtualization found in DMI
[    3.023569] systemd[1]: No virtualization found in CPUID
[    3.028969] systemd[1]: Virtualization XEN not found, /proc/xen does not exist
[    3.036559] systemd[1]: No virtualization found in /proc/device-tree/*
[    3.043420] systemd[1]: UML virtualization not found in /proc/cpuinfo.
[    3.050020] systemd[1]: This platform does not support /proc/sysinfo
[    3.056508] systemd[1]: Found VM virtualization none
[    3.061529] systemd[1]: Detected architecture arm.
[    3.067154] systemd[1]: Mounting cgroup to /sys/fs/cgroup/perf_event of type cgroup with options perf_event.
[    3.078818] systemd[1]: Mounting cgroup to /sys/fs/cgroup/blkio of type cgroup with options blkio.
[    3.089463] systemd[1]: Mounting cgroup to /sys/fs/cgroup/cpu,cpuacct of type cgroup with options cpu,cpuacct.
[    3.101298] systemd[1]: Mounting cgroup to /sys/fs/cgroup/freezer of type cgroup with options freezer.
[    3.112236] systemd[1]: Mounting cgroup to /sys/fs/cgroup/memory of type cgroup with options memory.
[    3.123482] systemd[1]: Mounting cgroup to /sys/fs/cgroup/devices of type cgroup with options devices.
[    3.134395] systemd[1]: Mounting cgroup to /sys/fs/cgroup/pids of type cgroup with options pids.
[    3.144778] systemd[1]: Mounting cgroup to /sys/fs/cgroup/net_cls of type cgroup with options net_cls.

Welcome to Debian GNU/Linux 10 (buster)!

[    3.184740] systemd[1]: Set hostname to <arm>.
[    3.197755] systemd[1]: Successfully added address 127.0.0.1 to loopback interface
[    3.205882] systemd[1]: Successfully added address ::1 to loopback interface
[    3.213414] systemd[1]: Successfully brought loopback interface up
[    3.220179] systemd[1]: Setting 'fs/file-max' to '2147483647'.
[    3.230141] systemd[1]: Found cgroup2 on /sys/fs/cgroup/unified, unified hierarchy for systemd controller
[    3.240134] systemd[1]: Unified cgroup hierarchy is located at /sys/fs/cgroup/unified. Controllers are on legacy hierarchies.
[    3.258918] systemd[1]: Can't allocate BPF LPM TRIE map, BPF firewalling is not supported: Function not implemented
[    3.269658] systemd[1]: Can't load kernel CGROUP DEVICE BPF program, BPF device control is not supported: Function not implemented
[    3.281537] systemd[1]: Controller 'cpu' supported: yes
[    3.286948] systemd[1]: Controller 'cpuacct' supported: yes
[    3.292562] systemd[1]: Controller 'io' supported: no
[    3.297676] systemd[1]: Controller 'blkio' supported: yes
[    3.303132] systemd[1]: Controller 'memory' supported: yes
[    3.308654] systemd[1]: Controller 'devices' supported: yes
[    3.314306] systemd[1]: Controller 'pids' supported: yes
[    3.319657] systemd[1]: Controller 'bpf-firewall' supported: no
[    3.325634] systemd[1]: Controller 'bpf-devices' supported: no
[    3.331602] systemd[1]: Set up TFD_TIMER_CANCEL_ON_SET timerfd.
[    3.339066] systemd[1]: Enabling showing of status.
[    3.345654] systemd[1]: Successfully forked off '(sd-executor)' as PID 55.
[    3.358258] systemd[55]: Successfully forked off '(direxec)' as PID 56.
[    3.373243] systemd[55]: Successfully forked off '(direxec)' as PID 57.
[    3.381122] systemd[55]: Successfully forked off '(direxec)' as PID 58.
[    3.434440] systemd[55]: Successfully forked off '(direxec)' as PID 59.
[    3.442219] systemd[55]: Successfully forked off '(direxec)' as PID 60.
[    3.504363] systemd[55]: Successfully forked off '(direxec)' as PID 61.
[    3.512081] systemd[55]: Successfully forked off '(direxec)' as PID 62.
[    3.634380] systemd[55]: Successfully forked off '(direxec)' as PID 63.
[    3.642125] systemd[55]: Successfully forked off '(direxec)' as PID 64.
[    3.744461] systemd[55]: Successfully forked off '(direxec)' as PID 65.
[    3.752179] systemd[55]: Successfully forked off '(direxec)' as PID 66.
[    3.866714] systemd[55]: Successfully forked off '(direxec)' as PID 67.
[    3.923497] systemd[55]: /lib/systemd/system-generators/systemd-rc-local-generator terminated by signal SEGV.
[    3.971004] systemd-hibernate-resume-generator[62]: Not running in an initrd, quitting.
[    4.046186] systemd[55]: /lib/systemd/system-generators/systemd-hibernate-resume-generator succeeded.
[    4.080695] systemd[55]: /lib/systemd/system-generators/systemd-gpt-auto-generator terminated by signal SEGV.
[    4.110089] systemd[55]: /lib/systemd/system-generators/systemd-getty-generator failed with exit status 127.
[    4.121572] systemd[55]: /lib/systemd/system-generators/systemd-cryptsetup-generator succeeded.
[    4.130888] systemd-sysv-generator[66]: Native unit for sendsigs.service already exists, skipping.
[    4.142139] systemd-sysv-generator[66]: Cannot find unit udhcpd.service.
[    4.149412] systemd-sysv-generator[66]: Native unit for bootlogs.service already exists, skipping.
[    4.159691] systemd-sysv-generator[66]: Cannot find unit cpufrequtils.service.
[    4.170591] systemd-sysv-generator[66]: Native unit for procps.service already exists, skipping.
[    4.179985] systemd-sysv-generator[66]: Native unit for checkroot.service already exists, skipping.
[    4.189433] systemd-sysv-generator[66]: Native unit for urandom.service already exists, skipping.
[    4.200115] systemd-sysv-generator[66]: Native unit for rcS.service already exists, skipping.
[    4.211224] systemd-sysv-generator[66]: Native unit for kmod.service already exists, skipping.
[    4.220302] systemd-sysv-generator[66]: Native unit for checkfs.service already exists, skipping.
[    4.229691] systemd-sysv-generator[66]: Cannot find unit loadcpufreq.service.
[    4.237351] systemd-sysv-generator[66]: Native unit for rc.local.service already exists, skipping.
[    4.248773] systemd-sysv-generator[66]: Native unit for udev.service already exists, skipping.
[    4.257901] systemd-sysv-generator[66]: Native unit for bluetooth.service already exists, skipping.
[    4.268275] systemd-sysv-generator[66]: Native unit for rsyslog.service already exists, skipping.
[    4.277771] systemd-sysv-generator[66]: Cannot find unit exim4.service.
[    4.284927] systemd-sysv-generator[66]: Native unit for umountroot.service already exists, skipping.
[    4.294421] systemd-sysv-generator[66]: Native unit for halt.service already exists, skipping.
[    4.303444] systemd-sysv-generator[66]: Native unit for mountnfs-bootclean.service already exists, skipping.
[    4.313619] systemd-sysv-generator[66]: Native unit for hostname.service already exists, skipping.
[    4.324009] systemd-sysv-generator[66]: Native unit for avahi-daemon.service already exists, skipping.
[    4.333755] systemd-sysv-generator[66]: Native unit for mountall.service already exists, skipping.
[    4.343999] systemd-sysv-generator[66]: Native unit for ofono.service already exists, skipping.
[    4.354101] systemd-sysv-generator[66]: Native unit for connman.service already exists, skipping.
[    4.363490] systemd-sysv-generator[66]: Native unit for mountkernfs.service already exists, skipping.
[    4.372965] systemd-sysv-generator[66]: Native unit for reboot.service already exists, skipping.
[    4.382251] systemd-sysv-generator[66]: Native unit for hostapd.service already exists, skipping.
[    4.391633] systemd-sysv-generator[66]: Native unit for hwclock.service already exists, skipping.
[    4.400903] systemd-sysv-generator[66]: Native unit for rmnologin.service already exists, skipping.
[    4.411226] systemd-sysv-generator[66]: Native unit for dnsmasq.service already exists, skipping.
[    4.420535] systemd-sysv-generator[66]: Native unit for mountdevsubfs.service already exists, skipping.
[    4.431225] systemd-sysv-generator[66]: Native unit for dbus.service already exists, skipping.
[    4.440317] systemd-sysv-generator[66]: Native unit for umountfs.service already exists, skipping.
[    4.450598] systemd-sysv-generator[66]: Native unit for cron.service already exists, skipping.
[    4.459795] systemd-sysv-generator[66]: Native unit for sudo.service already exists, skipping.
[    4.468808] systemd-sysv-generator[66]: Native unit for mountall-bootclean.service already exists, skipping.
[    4.479086] systemd-sysv-generator[66]: Native unit for mountnfs.service already exists, skipping.
[    4.488424] systemd-sysv-generator[66]: Native unit for brightness.service already exists, skipping.
[    4.498809] systemd-sysv-generator[66]: Native unit for dundee.service already exists, skipping.
[    4.507999] systemd-sysv-generator[66]: Native unit for umountnfs.service already exists, skipping.
[    4.517566] systemd-sysv-generator[66]: Native unit for rc.service already exists, skipping.
[    4.527371] systemd-sysv-generator[66]: Native unit for ssh.service already exists, skipping.
[    4.536340] systemd-sysv-generator[66]: Native unit for checkroot-bootclean.service already exists, skipping.
[    4.546706] systemd-sysv-generator[66]: Native unit for apache-htcacheclean.service already exists, skipping.
[    4.557047] systemd-sysv-generator[66]: Native unit for single.service already exists, skipping.
[    4.567119] systemd-sysv-generator[66]: Native unit for rsync.service already exists, skipping.
[    4.576220] systemd-sysv-generator[66]: Native unit for killprocs.service already exists, skipping.
[    4.586582] systemd-sysv-generator[66]: Native unit for networking.service already exists, skipping.
[    4.596250] systemd-sysv-generator[66]: Native unit for apache2.service already exists, skipping.
[    4.605557] systemd-sysv-generator[66]: Native unit for bootmisc.service already exists, skipping.
[    4.616340] systemd-sysv-generator[66]: Ignoring S02single symlink in rc1.d, not generating single.service.
[    4.626331] systemd-sysv-generator[66]: Ignoring S01killprocs symlink in rc1.d, not generating killprocs.service.
[    4.636740] systemd-sysv-generator[66]: Ignoring S01bootlogs symlink in rc1.d, not generating bootlogs.service.
[    4.648331] systemd-sysv-generator[66]: Ignoring S01rsyslog symlink in rc2.d, not generating rsyslog.service.
[    4.658459] systemd-sysv-generator[66]: Ignoring S04ofono symlink in rc2.d, not generating ofono.service.
[    4.668189] systemd-sysv-generator[66]: Ignoring S03ssh symlink in rc2.d, not generating ssh.service.
[    4.677527] systemd-sysv-generator[66]: Ignoring S01rsync symlink in rc2.d, not generating rsync.service.
[    4.687190] systemd-sysv-generator[66]: Ignoring S04dundee symlink in rc2.d, not generating dundee.service.
[    4.697047] systemd-sysv-generator[66]: Ignoring S01hostapd symlink in rc2.d, not generating hostapd.service.
[    4.707054] systemd-sysv-generator[66]: Ignoring S03rsync symlink in rc2.d, not generating rsync.service.
[    4.716720] systemd-sysv-generator[66]: Ignoring S03rmnologin symlink in rc2.d, not generating rmnologin.service.
[    4.727116] systemd-sysv-generator[66]: Ignoring S01cron symlink in rc2.d, not generating cron.service.
[    4.736608] systemd-sysv-generator[66]: Ignoring S01apache2 symlink in rc2.d, not generating apache2.service.
[    4.746613] systemd-sysv-generator[66]: Ignoring S01ssh symlink in rc2.d, not generating ssh.service.
[    4.755960] systemd-sysv-generator[66]: Ignoring S01sudo symlink in rc2.d, not generating sudo.service.
[    4.765522] systemd-sysv-generator[66]: Ignoring S01bluetooth symlink in rc2.d, not generating bluetooth.service.
[    4.775884] systemd-sysv-generator[66]: Ignoring S01ofono symlink in rc2.d, not generating ofono.service.
[    4.785583] systemd-sysv-generator[66]: Ignoring S04bluetooth symlink in rc2.d, not generating bluetooth.service.
[    4.795942] systemd-sysv-generator[66]: Ignoring S02apache2 symlink in rc2.d, not generating apache2.service.
[    4.805969] systemd-sysv-generator[66]: Ignoring S01connman symlink in rc2.d, not generating connman.service.
[    4.815976] systemd-sysv-generator[66]: Ignoring S04connman symlink in rc2.d, not generating connman.service.
[    4.826024] systemd-sysv-generator[66]: Ignoring S05rc.local symlink in rc2.d, not generating rc.local.service.
[    4.836208] systemd-sysv-generator[66]: Ignoring S01dundee symlink in rc2.d, not generating dundee.service.
[    4.846062] systemd-sysv-generator[66]: Ignoring S01bootlogs symlink in rc2.d, not generating bootlogs.service.
[    4.856258] systemd-sysv-generator[66]: Ignoring S01avahi-daemon symlink in rc2.d, not generating avahi-daemon.service.
[    4.867164] systemd-sysv-generator[66]: Ignoring S04avahi-daemon symlink in rc2.d, not generating avahi-daemon.service.
[    4.878058] systemd-sysv-generator[66]: Ignoring S01dbus symlink in rc2.d, not generating dbus.service.
[    4.887561] systemd-sysv-generator[66]: Ignoring S03dbus symlink in rc2.d, not generating dbus.service.
[    4.897057] systemd-sysv-generator[66]: Ignoring S03cron symlink in rc2.d, not generating cron.service.
[    4.907950] systemd-sysv-generator[66]: Ignoring S01rsyslog symlink in rc3.d, not generating rsyslog.service.
[    4.918100] systemd-sysv-generator[66]: Ignoring S04ofono symlink in rc3.d, not generating ofono.service.
[    4.927809] systemd-sysv-generator[66]: Ignoring S03ssh symlink in rc3.d, not generating ssh.service.
[    4.937169] systemd-sysv-generator[66]: Ignoring S01rsync symlink in rc3.d, not generating rsync.service.
[    4.946831] systemd-sysv-generator[66]: Ignoring S04dundee symlink in rc3.d, not generating dundee.service.
[    4.956668] systemd-sysv-generator[66]: Ignoring S01hostapd symlink in rc3.d, not generating hostapd.service.
[    4.966695] systemd-sysv-generator[66]: Ignoring S03rsync symlink in rc3.d, not generating rsync.service.
[    4.976358] systemd-sysv-generator[66]: Ignoring S03rmnologin symlink in rc3.d, not generating rmnologin.service.
[    4.986727] systemd-sysv-generator[66]: Ignoring S01cron symlink in rc3.d, not generating cron.service.
[    4.996231] systemd-sysv-generator[66]: Ignoring S01apache2 symlink in rc3.d, not generating apache2.service.
[    5.006237] systemd-sysv-generator[66]: Ignoring S01ssh symlink in rc3.d, not generating ssh.service.
[    5.015561] systemd-sysv-generator[66]: Ignoring S01sudo symlink in rc3.d, not generating sudo.service.
[    5.025108] systemd-sysv-generator[66]: Ignoring S01bluetooth symlink in rc3.d, not generating bluetooth.service.
[    5.035470] systemd-sysv-generator[66]: Ignoring S01ofono symlink in rc3.d, not generating ofono.service.
[    5.045144] systemd-sysv-generator[66]: Ignoring S04bluetooth symlink in rc3.d, not generating bluetooth.service.
[    5.055522] systemd-sysv-generator[66]: Ignoring S02apache2 symlink in rc3.d, not generating apache2.service.
[    5.065531] systemd-sysv-generator[66]: Ignoring S01connman symlink in rc3.d, not generating connman.service.
[    5.075557] systemd-sysv-generator[66]: Ignoring S04connman symlink in rc3.d, not generating connman.service.
[    5.085585] systemd-sysv-generator[66]: Ignoring S05rc.local symlink in rc3.d, not generating rc.local.service.
[    5.095786] systemd-sysv-generator[66]: Ignoring S01dundee symlink in rc3.d, not generating dundee.service.
[    5.105621] systemd-sysv-generator[66]: Ignoring S01bootlogs symlink in rc3.d, not generating bootlogs.service.
[    5.115840] systemd-sysv-generator[66]: Ignoring S01avahi-daemon symlink in rc3.d, not generating avahi-daemon.service.
[    5.126722] systemd-sysv-generator[66]: Ignoring S04avahi-daemon symlink in rc3.d, not generating avahi-daemon.service.
[    5.137635] systemd-sysv-generator[66]: Ignoring S01dbus symlink in rc3.d, not generating dbus.service.
[    5.147118] systemd-sysv-generator[66]: Ignoring S03dbus symlink in rc3.d, not generating dbus.service.
[    5.156631] systemd-sysv-generator[66]: Ignoring S03cron symlink in rc3.d, not generating cron.service.
[    5.167496] systemd-sysv-generator[66]: Ignoring S01rsyslog symlink in rc4.d, not generating rsyslog.service.
[    5.177641] systemd-sysv-generator[66]: Ignoring S04ofono symlink in rc4.d, not generating ofono.service.
[    5.187344] systemd-sysv-generator[66]: Ignoring S03ssh symlink in rc4.d, not generating ssh.service.
[    5.196702] systemd-sysv-generator[66]: Ignoring S01rsync symlink in rc4.d, not generating rsync.service.
[    5.206365] systemd-sysv-generator[66]: Ignoring S04dundee symlink in rc4.d, not generating dundee.service.
[    5.216198] systemd-sysv-generator[66]: Ignoring S01hostapd symlink in rc4.d, not generating hostapd.service.
[    5.226224] systemd-sysv-generator[66]: Ignoring S03rsync symlink in rc4.d, not generating rsync.service.
[    5.235886] systemd-sysv-generator[66]: Ignoring S03rmnologin symlink in rc4.d, not generating rmnologin.service.
[    5.246259] systemd-sysv-generator[66]: Ignoring S01cron symlink in rc4.d, not generating cron.service.
[    5.255763] systemd-sysv-generator[66]: Ignoring S01apache2 symlink in rc4.d, not generating apache2.service.
[    5.265771] systemd-sysv-generator[66]: Ignoring S01ssh symlink in rc4.d, not generating ssh.service.
[    5.275106] systemd-sysv-generator[66]: Ignoring S01sudo symlink in rc4.d, not generating sudo.service.
[    5.284660] systemd-sysv-generator[66]: Ignoring S01bluetooth symlink in rc4.d, not generating bluetooth.service.
[    5.295023] systemd-sysv-generator[66]: Ignoring S01ofono symlink in rc4.d, not generating ofono.service.
[    5.304697] systemd-sysv-generator[66]: Ignoring S04bluetooth symlink in rc4.d, not generating bluetooth.service.
[    5.315074] systemd-sysv-generator[66]: Ignoring S02apache2 symlink in rc4.d, not generating apache2.service.
[    5.325082] systemd-sysv-generator[66]: Ignoring S01connman symlink in rc4.d, not generating connman.service.
[    5.335108] systemd-sysv-generator[66]: Ignoring S04connman symlink in rc4.d, not generating connman.service.
[    5.345135] systemd-sysv-generator[66]: Ignoring S05rc.local symlink in rc4.d, not generating rc.local.service.
[    5.355336] systemd-sysv-generator[66]: Ignoring S01dundee symlink in rc4.d, not generating dundee.service.
[    5.365172] systemd-sysv-generator[66]: Ignoring S01bootlogs symlink in rc4.d, not generating bootlogs.service.
[    5.375388] systemd-sysv-generator[66]: Ignoring S01avahi-daemon symlink in rc4.d, not generating avahi-daemon.service.
[    5.386269] systemd-sysv-generator[66]: Ignoring S04avahi-daemon symlink in rc4.d, not generating avahi-daemon.service.
[    5.397180] systemd-sysv-generator[66]: Ignoring S01dbus symlink in rc4.d, not generating dbus.service.
[    5.406664] systemd-sysv-generator[66]: Ignoring S03dbus symlink in rc4.d, not generating dbus.service.
[    5.416178] systemd-sysv-generator[66]: Ignoring S03cron symlink in rc4.d, not generating cron.service.
[    5.426959] systemd-sysv-generator[66]: Ignoring S01rsyslog symlink in rc5.d, not generating rsyslog.service.
[    5.437110] systemd-sysv-generator[66]: Ignoring S04ofono symlink in rc5.d, not generating ofono.service.
[    5.446818] systemd-sysv-generator[66]: Ignoring S03ssh symlink in rc5.d, not generating ssh.service.
[    5.456174] systemd-sysv-generator[66]: Ignoring S01rsync symlink in rc5.d, not generating rsync.service.
[    5.465836] systemd-sysv-generator[66]: Ignoring S04dundee symlink in rc5.d, not generating dundee.service.
[    5.475671] systemd-sysv-generator[66]: Ignoring S01hostapd symlink in rc5.d, not generating hostapd.service.
[    5.485698] systemd-sysv-generator[66]: Ignoring S03rsync symlink in rc5.d, not generating rsync.service.
[    5.495360] systemd-sysv-generator[66]: Ignoring S03rmnologin symlink in rc5.d, not generating rmnologin.service.
[    5.505731] systemd-sysv-generator[66]: Ignoring S01cron symlink in rc5.d, not generating cron.service.
[    5.515235] systemd-sysv-generator[66]: Ignoring S01apache2 symlink in rc5.d, not generating apache2.service.
[    5.525241] systemd-sysv-generator[66]: Ignoring S01ssh symlink in rc5.d, not generating ssh.service.
[    5.534565] systemd-sysv-generator[66]: Ignoring S01sudo symlink in rc5.d, not generating sudo.service.
[    5.544117] systemd-sysv-generator[66]: Ignoring S01bluetooth symlink in rc5.d, not generating bluetooth.service.
[    5.554480] systemd-sysv-generator[66]: Ignoring S01ofono symlink in rc5.d, not generating ofono.service.
[    5.564153] systemd-sysv-generator[66]: Ignoring S04bluetooth symlink in rc5.d, not generating bluetooth.service.
[    5.574532] systemd-sysv-generator[66]: Ignoring S02apache2 symlink in rc5.d, not generating apache2.service.
[    5.584540] systemd-sysv-generator[66]: Ignoring S01connman symlink in rc5.d, not generating connman.service.
[    5.594567] systemd-sysv-generator[66]: Ignoring S04connman symlink in rc5.d, not generating connman.service.
[    5.604592] systemd-sysv-generator[66]: Ignoring S05rc.local symlink in rc5.d, not generating rc.local.service.
[    5.614792] systemd-sysv-generator[66]: Ignoring S01dundee symlink in rc5.d, not generating dundee.service.
[    5.624629] systemd-sysv-generator[66]: Ignoring S01bootlogs symlink in rc5.d, not generating bootlogs.service.
[    5.634845] systemd-sysv-generator[66]: Ignoring S01avahi-daemon symlink in rc5.d, not generating avahi-daemon.service.
[    5.645726] systemd-sysv-generator[66]: Ignoring S04avahi-daemon symlink in rc5.d, not generating avahi-daemon.service.
[    5.656638] systemd-sysv-generator[66]: Ignoring S01dbus symlink in rc5.d, not generating dbus.service.
[    5.666122] systemd-sysv-generator[66]: Ignoring S03dbus symlink in rc5.d, not generating dbus.service.
[    5.675635] systemd-sysv-generator[66]: Ignoring S03cron symlink in rc5.d, not generating cron.service.
[    5.685319] systemd-sysv-generator[66]: Loading SysV script /etc/init.d/udhcpd
[    5.694263] systemd-sysv-generator[66]: Loading SysV script /etc/init.d/exim4
[    5.705397] systemd-sysv-generator[66]: Loading SysV script /etc/init.d/loadcpufreq
[    5.716624] systemd-sysv-generator[66]: Loading SysV script /etc/init.d/cpufrequtils
[    5.731392] systemd[55]: /lib/systemd/system-generators/systemd-sysv-generator succeeded.
[    5.739965] systemd[55]: /lib/systemd/system-generators/systemd-debug-generator succeeded.
[    5.748639] systemd[55]: /lib/systemd/system-generators/systemd-run-generator succeeded.
[    5.757026] systemd[55]: /lib/systemd/system-generators/systemd-veritysetup-generator terminated by signal SEGV.
[    5.767390] systemd[55]: /lib/systemd/system-generators/systemd-bless-boot-generator terminated by signal SEGV.
[    5.777681] systemd[55]: /lib/systemd/system-generators/systemd-system-update-generator succeeded.
[    5.786799] systemd[55]: /lib/systemd/system-generators/systemd-fstab-generator terminated by signal SEGV.
[    5.797673] systemd[1]: (sd-executor) succeeded.
[    5.802788] systemd[1]: Looking for unit files in (higher priority first):
[    5.809936] systemd[1]:      /etc/systemd/system.control
[    5.815015] systemd[1]:      /run/systemd/system.control
[    5.820012] systemd[1]:      /run/systemd/transient
[    5.824629] systemd[1]:      /etc/systemd/system
[    5.828928] systemd[1]:      /run/systemd/system

I can't seem to find the constant between each boots, except that it crashes...
EDIT 2:
Expected Dev board output is:
Welcome to Debian GNU/Linux 10 (buster)!
[ 6.828019] systemd[1]: Set hostname to <arm>.
[ 7.793038] systemd[1]: File /lib/systemd/system/systemd-journald.service:12 configures an IP fire wall (IPAddressDeny=any), but the local system does not support BPF/cgroup based firewalling.
[ 7.810794] systemd[1]: Proceeding WITHOUT firewalling in effect! (This warning is only shown for the first loaded unit using IP firewalling.)
[ 8.292129] systemd[1]: Listening on udev Control Socket.
[ OK ] Listening on udev Control Socket.
...
(and so on)

Not that using a SySVInit environment with no modules, I can boot to the shell, but then some commands can cause a freeze.

A: This issue was fixed on the TI Forum, here is the link for those interested.
https://e2e.ti.com/support/processors-group/processors/f/processors-forum/1158936/am3359-caught-segv-when-distro-s-systemd-starting
In summary, the issue was that my VDD_MPU(1.1V) was driven by my PMIC and the PMIC driver was not properly initialized. Meaning that when the system rose the CPU Freq. to 800MHz, the 1.1V was too low and the MPU would be in brownout and get corrupted. The solution was to either manually raise the VDD_MPU to something higher (under 1.3V) or to configure my PMIC to automatically manage the voltage based on the CPU Freq.


text:
Q: How to set SetBasePath to dll location on Program.Main When starting dotnet dll
 cd /
 dotnet /tmp/donetproject/donetproject.dll

the code
.AddJsonFile("hostsettings.json", optional: true)

will look at

/hostsettings.json

not

/tmp/donetproject/hostsettings.json

setting the GetCurrentDirectory has no effect
.SetBasePath(Directory.GetCurrentDirectory())

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }
    public static IWebHostBuilder CreateWebHostBuilder(string[] args)
    {
        var config = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("hostsettings.json", optional: true)
            .AddCommandLine(args)
            .Build();

        return WebHost.CreateDefaultBuilder(args)
            .UseUrls()
            .UseConfiguration(config)
                .UseStartup<Startup>();
    }
}

A: You are currently setting the work directory
.SetBasePath(Directory.GetCurrentDirectory())

This is the directory, where you start the process /, more specificaly cd /. The directory you realy want, is the directory of your assembly:
.SetBasePath(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location))

Probably you should consider to change you working directory to the directory of your application instead, e. g. cd /tmp/donetproject/.


text:
Q: I cannot figure out how to enable my dev environment Whenever I try to switch to my dev env my site crashes without any error (even in apache log)
When I try to run composer update I always run into this issue:
[Symfony\Component\DependencyInjection\Exception\ServiceNotFoundException]
The service "web_profiler.controller.profiler" has a dependency on a non-existent service "profiler".
Below is the content of my AppKernel
<?php

use Symfony\Component\HttpKernel\Kernel;
use Symfony\Component\Config\Loader\LoaderInterface;

class AppKernel extends Kernel
{
    public function registerBundles()
    {
        $bundles = array(
            new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
//            new Symfony\Bundle\SecurityBundle\SecurityBundle(),
            new Symfony\Bundle\TwigBundle\TwigBundle(),
            new Symfony\Bundle\MonologBundle\MonologBundle(),
//            new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
//            new Symfony\Bundle\AsseticBundle\AsseticBundle(),
            new Doctrine\Bundle\DoctrineBundle\DoctrineBundle(),
            new Sensio\Bundle\FrameworkExtraBundle\SensioFrameworkExtraBundle(),
//            new JMS\AopBundle\JMSAopBundle(),
//            new JMS\DiExtraBundle\JMSDiExtraBundle($this),
//            new JMS\SecurityExtraBundle\JMSSecurityExtraBundle(),
            new Zepluf\Bundle\StoreBundle\StoreBundle(),
        );

        if (in_array($this->getEnvironment(), array('dev', 'test'))) {
//            $bundles[] = new Acme\DemoBundle\AcmeDemoBundle();
            $bundles[] = new Symfony\Bundle\WebProfilerBundle\WebProfilerBundle();
            $bundles[] = new Sensio\Bundle\DistributionBundle\SensioDistributionBundle();
            $bundles[] = new Sensio\Bundle\GeneratorBundle\SensioGeneratorBundle();
        }

        return $bundles;
    }

    public function registerContainerConfiguration(LoaderInterface $loader)
    {
        $loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
    }
}

My composer.json:
{
    "name": "zepluf/standard-edition",
    "description": "The \"ZePLUF Standard Edition\" distribution",
    "authors": [
        {
            "name": "Raine Ng",
            "email": "vunguyen@rubikin.com",
            "homepage": "http://rubikin.com"
        }
    ],
    "autoload": {
        "psr-0": {
            "": "src/",
            "Zepluf" : "src/Zepluf/",
            "plugins": "app/"
        }
    },
    "require": {
        "php": ">=5.3.3",
        "composer/installers": "*",
        "zepluf/installer": "*",
        "symfony/symfony": "2.2.*",
        "symfony/framework-bundle": ">=2.1",
        "symfony/web-profiler-bundle": "2.2.*@dev",
        "doctrine/orm": ">=2.2.3,<2.4-dev",
        "doctrine/doctrine-bundle": "1.2.*",
        "twig/extensions": "1.0.*",
        "symfony/assetic-bundle": "2.1.*",
        "symfony/swiftmailer-bundle": "2.2.*",
        "symfony/monolog-bundle": "2.2.*",
        "sensio/distribution-bundle": "2.2.*",
        "sensio/framework-extra-bundle": "2.2.*",
        "sensio/generator-bundle": "2.2.*",
        "zepluf/plugin-ricache": "dev-master",
        "zepluf/plugin-ricjloader": "dev-master"
    },
    "scripts": {
        "post-install-cmd": [
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile"
        ],
        "post-update-cmd": [
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile"
        ]
    },
    "minimum-stability": "dev",
    "extra": {
        "symfony-app-dir": "app",
        "symfony-web-dir": "web"
    }
}

I wonder what is going on and how I can fix this?

A: To answer my own question, I needed to set the profiler on in the config file if I want to use web_profiler.
So I used something like this in my config_dev.yml:
framework:
  profiler: { only_exceptions: false }


text:
Q: How to convert string to IP address and vice versa how can I convert a string ipAddress (struct in_addr) and vice versa?
and how do I turn in unsigned long ipAddress?
thanks

A: I was able to convert string to DWORD and back with this code:
char strAddr[] = "127.0.0.1"
DWORD ip = inet_addr(strAddr); // ip contains 16777343 [0x0100007f in hex]

struct in_addr paddr;
paddr.S_un.S_addr = ip;

char *strAdd2 = inet_ntoa(paddr); // strAdd2 contains the same string as strAdd

I am working in a maintenance project of old MFC code, so converting deprecated functions calls is not applicable.

A: inet_ntoa() converts a in_addr to string:

The inet_ntoa function converts an
  (Ipv4) Internet network address into
  an ASCII string in Internet standard
  dotted-decimal format.

inet_addr() does the reverse job

The inet_addr function converts a
  string containing an IPv4
  dotted-decimal address into a proper
  address for the IN_ADDR structure

PS this the first result googling "in_addr to string"!

A: To convert string to in-addr:
in_addr maskAddr;
inet_aton(netMaskStr, &maskAddr);

To convert in_addr to string:
char saddr[INET_ADDRSTRLEN];
inet_ntop(AF_INET, &inaddr, saddr, INET_ADDRSTRLEN);

A: This example shows how to convert from string to ip, and viceversa:
struct sockaddr_in sa;
char ip_saver[INET_ADDRSTRLEN];

// store this IP address in sa:
inet_pton(AF_INET, "192.0.1.10", &(sa.sin_addr));

// now get it back
sprintf(ip_saver, "%s", sa.sin_addr));

// prints "192.0.2.10"
printf("%s\n", ip_saver);

A: Use inet_ntop() and inet_pton() if you need it other way around. Do not use inet_ntoa(), inet_aton() and similar as they are deprecated and don't support ipv6.
Here is a nice guide with quite a few examples.
// IPv4 demo of inet_ntop() and inet_pton()

struct sockaddr_in sa;
char str[INET_ADDRSTRLEN];

// store this IP address in sa:
inet_pton(AF_INET, "192.0.2.33", &(sa.sin_addr));

// now get it back and print it
inet_ntop(AF_INET, &(sa.sin_addr), str, INET_ADDRSTRLEN);

printf("%s\n", str); // prints "192.0.2.33"

A: I'm not sure if I understood the question properly.
Anyway, are you looking for this:
std::string ip ="192.168.1.54";
std::stringstream s(ip);
int a,b,c,d; //to store the 4 ints
char ch; //to temporarily store the '.'
s >> a >> ch >> b >> ch >> c >> ch >> d;
std::cout << a << "  " << b << "  " << c << "  "<< d;

Output:
192  168  1  54

A: The third inet_pton parameter is a pointer to an in_addr structure.  After a successful inet_pton call, the in_addr structure will be populated with the address information.  The structure's S_addr field contains the IP address in network byte order (reverse order).
Example :

#include <arpa/inet.h>
uint32_t NodeIpAddress::getIPv4AddressInteger(std::string IPv4Address) {
    int result;
    uint32_t IPv4Identifier = 0;
    struct in_addr addr;
    // store this IP address in sa:
    result = inet_pton(AF_INET, IPv4Address.c_str(), &(addr));
    if (result == -1) {
gpLogFile->Write(LOGPREFIX, LogFile::LOGLEVEL_ERROR, _T("Failed to convert IP %hs to IPv4 Address. Due to invalid family of %d. WSA Error of %d"), IPv4Address.c_str(), AF_INET, result);
    }
    else if (result == 0) {
        gpLogFile->Write(LOGPREFIX, LogFile::LOGLEVEL_ERROR, _T("Failed to convert IP %hs to IPv4"), IPv4Address.c_str());
    }
    else {
        IPv4Identifier = ntohl(*((uint32_t *)&(addr)));
    }
    return IPv4Identifier;
}

A: here's easy-to-use, thread-safe c++ functions to convert uint32_t native-endian to string, and string to native-endian uint32_t:
#include <arpa/inet.h> // inet_ntop & inet_pton
#include <string.h> // strerror_r
#include <arpa/inet.h> // ntohl & htonl
using namespace std; // im lazy

string ipv4_int_to_string(uint32_t in, bool *const success = nullptr)
{
    string ret(INET_ADDRSTRLEN, '\0');
    in = htonl(in);
    const bool _success = (NULL != inet_ntop(AF_INET, &in, &ret[0], ret.size()));
    if (success)
    {
        *success = _success;
    }
    if (_success)
    {
        ret.pop_back(); // remove null-terminator required by inet_ntop
    }
    else if (!success)
    {
        char buf[200] = {0};
        strerror_r(errno, buf, sizeof(buf));
        throw std::runtime_error(string("error converting ipv4 int to string ") + to_string(errno) + string(": ") + string(buf));
    }
    return ret;
}
// return is native-endian
// when an error occurs: if success ptr is given, it's set to false, otherwise a std::runtime_error is thrown.
uint32_t ipv4_string_to_int(const string &in, bool *const success = nullptr)
{
    uint32_t ret;
    const bool _success = (1 == inet_pton(AF_INET, in.c_str(), &ret));
    ret = ntohl(ret);
    if (success)
    {
        *success = _success;
    }
    else if (!_success)
    {
        char buf[200] = {0};
        strerror_r(errno, buf, sizeof(buf));
        throw std::runtime_error(string("error converting ipv4 string to int ") + to_string(errno) + string(": ") + string(buf));
    }
    return ret;
}

fair warning, as of writing, they're un-tested. but these functions are exactly what i was looking for when i came to this thread.

A: Hexadecimal IP Address to String IP
#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    uint32_t ip = 0x0AA40001;
    string ip_str="";
    int temp = 0;
    for (int i = 0; i < 8; i++){
        if (i % 2 == 0)
        {
            temp += ip & 15;
            ip = ip >> 4;
        }
        else
        {
            stringstream ss;
            temp += (ip & 15) * 16;
            ip = ip >> 4;
            ss << temp;
            ip_str = ss.str()+"." + ip_str;
            temp = 0;
        }
    }
    ip_str.pop_back();
    cout << ip_str;
}

Output:10.164.0.1

A: summarize :
inet_ntoa((in_addr)recvAddrStruct.sin_addr)

step by step :
SOCKET m_viSock = socket(AF_INET, SOCK_DGRAM,0);

struct sockaddr_in recvAddrStruct;
recvAddrStruct.sin_family = AF_INET;
recvAddrStruct.sin_port = htons((unsigned short)port);
recvAddrStruct.sin_addr.s_addr = inet_addr("127.0.0.1");  // inet_addr()

  // get back in string

printf("IP : %s",    inet_ntoa((in_addr)recvAddrStruct.sin_addr));   // inet_ntoa ()

A: You can use two functions
defined in winsock2.h on windows, in netdb.h on Linux
•WSAStringToAddressA(For converting a  string to an address)
•WSAAddressToStringA(For converting an address to a string)
Best thing about these two functions is that they work for every address family
WSAStringToAddressA
This function takes to five arguments
•A pointer of array or array of char containing your address
•Address family of your address(Only used if argument 3 is NULL)
•WSAPROTOCOL_INFO structure providing information about your protocol, leave null if you want to use argument 2
•Pointer to the structure of sockaddr in which the result address has to be stored
•Pointer of the object  of type DWORD in which the result length of your address has to be stored
WSAAddressToStringA
This function also takes five arguments
•Pointer to the structure of sockaddr that has to be translated
•Byte length of your address
•Structure of WSAPROTOCOL_INFO giving information about the address's protocol. Use NULL to make the function use address family of sockaddr structure in argument 1
•Array of char in which the address in the form of string has to be stored
•Length of the string form of your address in bytes
Example
#define _WIN32_INNT 0x601

#include <iostream>
#include <winsock2.h>
#include <ws2tcpip.h>
#include <ws2spi.h>

int main()
{
    WSADATA wsd;
    WSAStartup(MAKEWORD(2,2),&wsd);
    char *addr="127.0.0.1";
    sockaddr h;
    int i;
    WSAStringToAddressA(addr,AF_INET,NULL,&h,(DWORD*)&i);
    char addr2[INET_ADDRSTRLEN];
    int i2;
    WSAAddressToStringA(&h,i,NULL,addr,(DWORD*)&i2);
    std::cout<<addr2;
}

Result
127.0.0.1


text:
Q: Failed to send mail in my contact form I have designed a form to receive feedback from my site visitors.I have developed the site,but the mail send option is not working properly..I receive the error "Mail is not send". Can anybody help me to solve this...
My Php code
    <?php
if (isset($_POST['submit']))
{
$company=$_POST['company'];
$name=$_POST['name'];
$email=$_POST['email'];
$message=$_POST['message'];
$mobile=$_POST['mobile'];

$to='www@gmail.com';
$headers="From: $company";
$mail=mail($to,$company,$name,$mobile,$email);
if($mail) { echo'Mail send successfully'; }
else { echo'Mail is not send'; }
}
?>

And here is my HTML form
<form id="contact-form" action="" role="form" method="post">

            <fieldset>

                    <input type="text" name="company" placeholder="Company name" required/>

                    <input type="text" name="name" placeholder="Your name" required/>

                    <input type="text" name="mobile" placeholder="Your mobile" required/>

                    <input type="text" name="email" placeholder="Your email" value="" required/>

                    <textarea name="message" placeholder="Any remarks?"></textarea>

                <input id="submit" type="submit" name="submit" value="Send" class="sub">

            </fieldset>
          </form>

help me solve this

A: Change
$mail=mail($to,$company,$name,$mobile,$email);

to
mail($to,$subject,$txt,$headers);

And mail has only four parameters(mainly) that's why $mail=mail($to,$company,$name,$mobile,$email); returns false and you got the else part "{ echo'Mail is not send'; }"
so in your $txt=$company."\n".$name."\n".$email."\n".$message."\n".$mobile;

A: Please check the parameters of the php mail function.
http://php.net/manual/en/function.mail.php
Try
$headers = 'From: webmaster@example.com' . "\r\n" .
'Reply-To: webmaster@example.com' . "\r\n" .
'X-Mailer: PHP/' . phpversion();

$mail=mail($to,'Your mail subject',$message,$headers);

A: the signature of php mail function is like this
mail($to,$subject,$body,$additionalHeaders,$additionalParameters);
please go through this url for more information http://php.net/manual/en/function.mail.php
$to='www@gmail.com';
$headers="From: $company";
/* you have to add email and phone into your message. */
$mail=mail($to,'subject of your mail',$message, $headers);
if($mail) { echo'Mail send successfully'; }
else { echo'Mail is not send'; }
}
?>
try this
Happy coding :)


text:
Q: Can I develop app with react-native for ios on a virtual Mac in Vmware player? I soon saw that I can't enable 3d acceleration, and the visual code isn't rendering right. I installed xcode and so far it's been trying to build for 4 minutes.
Here I managed to virtualize a MacBook Pro with Ventura 13.0.1, I left 6 GB of RAM and 4 CPU, but it only manages to capture 128 MB of vram, I don't know if I can exceed that value.
I'm not even messing with Visual Code anymore, just the terminal.
I ran the commands:

cd ios
pod deintegrate
pod install
npm start
npm run ios


text:
Q: How to change each other textbox when changing value (MVVM) How can I change my textboxes depending on the others?
Before I had an Button with Icommand and now the textboxes should change when another textbox is changing
    <TextBox Grid.Column="2" Grid.Row="2" Text ="{Binding Decimal, UpdateSourceTrigger = PropertyChanged}"/>
    <TextBox Grid.Column="2" Grid.Row="3" Text ="{Binding Dual, UpdateSourceTrigger = PropertyChanged}"/>
    <TextBox Grid.Column="2" Grid.Row="4" Text ="{Binding Hexa, UpdateSourceTrigger = PropertyChanged}"/>
    <TextBox Grid.Column="2" Grid.Row="5" Text ="{Binding Octa, UpdateSourceTrigger = PropertyChanged}"/>

So in general I want to convert the numbers in the other system, no matter in which textbox the user is writing, how can I do this?
A property behind looks like this:
    public string Decimal
    {
        get { return Number.Decimal; }
        set
        {
            if (Number.Decimal != value)
            {
                Number.Decimal = value;
                RaisePropertyChanged("Decimal");
            }
        }
    }

A: I assume that the Number is your model - it stores the number inside, and properly manages the number conversions.
The easiest solution would be to just call for an update of each relevant property when one of them is touched in the ViewModel.
private void NumbersChanged()
{
    RaisePropertyChanged(nameof(Decimal));
    RaisePropertyChanged(nameof(Dual));
    RaisePropertyChanged(nameof(Hexa));
    RaisePropertyChanged(nameof(Octa));
}

public string Decimal
{
    get { return Number.Decimal; }
    set
    {
        if (Number.Decimal != value)
        {
            Number.Decimal = value;
            NumbersChanged();
        }
    }
}

public string Hexa
{
    get { return Number.Hexa; }
    set
    {
        if (Number.Hexa != value)
        {
            Number.Hexa = value;
            NumbersChanged();
        }
    }
}
//etc...


text:
Q: application.ontime vba passing variable I am trying to pass a variable(string) to a sub which is in module1 of my workbook using application.on time method.
the below code is runing fine
Sub calar()
strText = "appl"
Application.OnTime Now + TimeValue("00:00:02"), "!Module1.cld"
End Sub

Sub cld()
MsgBox ("called" & slk)
End Sub

But when I try to pass an argument as shown below, I am getting an error:
Sub calar()
strText = "appl"
Application.OnTime Now + TimeValue("00:00:02"), "'!Module1.cld ""Hello!""'"
End Sub

Sub cld(ByVal slk As String)
MsgBox ("called" & slk)
End Sub

I want to pass strText as an argument please help.

A: Try removing the first exclamation point...
Application.OnTime Now + TimeValue("00:00:02"), "'Module1.cld ""Hello!""'"

To pass a variable...
Application.OnTime Now + TimeValue("00:00:02"), "'Module1.cld """ & strText & """'"


text:
Q: How to safely stop/start my postgres server when using docker-compose I sometimes stop/start docker very often when I am release new features in my application.
docker-compose up -d
docker-compose stop

I am using pretty much the bare bones postgres docker setup (see below).
I am mapping the /data folder to my host.
Is there anything I should be worried about if I stop/start docker many times in a day in terms of data getting corrupted?
Is calling docker-compose stop the best way to be stopping my postgres instance?
My postgres service in my docker-compose looks like this:
  db:
    image: postgres:9.4
    volumes:
      - "/home/deploy/data/pgdata:/var/lib/postgresql/data"
    restart: always

This setup currently is running smoothly in development, but once it goes to production I want to make sure I am following best practices etc.

A: Use,
docker-compose down -v

What it does is basically removes all the volumes you added. If you don't those volumes will hang on and eat up your space. It only removes the volume inside the docker container. The volume in your host stays and survives container removal in case if you want that data to survive container removal.
Whenever you create a docker container by docker run, Docker creates a volume/ directory to keep the details about the containers. After you execute docker run, if you look into /var/lib/docker/containers, you will see one directory for each container you started. If you have not removed the volumes for previous container, you will see many directories under the "container" directory. The name of these directories will be very long random letters and number. So, if you don't tell the docker to remove these directories when you stop the container, it will be there forever. The v option I mentioned above, will delete these directories when you take down the container.
Keep in mind, you can view the contents of the directory /var/lib/docker only as a root user. To change to root user, use sudo -i before you attempt to view the contents of the directory.

A: Databases in particular are usually designed so that it's very hard to lose data, even if the machine loses power in the middle of writing something to disk.  (This comes at some performance cost.)  So long as you don't have more than one PostgreSQL instance at a time using the same backing data store, I'd expect it to not lose data or otherwise corrupt itself; the worst you should expect to see is a message at startup that it's recovering from a write-ahead log or something along those lines.
docker stop will send a signal to a container that prompts it to shut down cleanly, and PostgreSQL will take this as a cue to shut down.  It looks like docker-compose stop, docker-compose down, and sending ^C to docker-compose up all use the same mechanism.  So the way you're doing it now should result in a clean shutdown (provided PostgreSQL finishes its cleanup within 10 seconds).
I believe you can docker-compose restart specific services, or docker-compose up --force-recreate them.  This would help if you rebuilt your application container and needed to restart that, but not its database.


text:
Q: How can I convert one row of values with panda How can I convert one row of values with panda
df = pd.read_csv('blackred.csv')

words = []
for i in df:
    words.append(i)

num = []

I want to grab the index 0 column and convert it into a list of numbers and set it to num
How can I do that
This is my csv file I just want to grab 7,21,19,9,2 please let me know how
csv_file

A: I understood that grab the index 0 column is actually grab the index 0 column.
num = df.loc[0].to_list()

A: Use .to_list().
You will get a list: [7, 21, 19, 9, 2].
import pandas as pd

# Create a DataFrame
df = pd.DataFrame(columns=['black','red','even','odd', 'NONE'], index = [0])
df.loc[0] = [7, 21, 19, 9, 2]

# Grab data in a row into a list
df.loc[0].to_list()

A: you can use .iloc and list()

list(words.iloc[0])


text:
Q: How to display a list in three columns using php? For the past couple of hours, I've been unsuccessfully trying to figure out the php code to display a list in three columns so that it has this order
A D G
B E H
C F I

but I'm really lost. Can anyone help me with this?
I currently only have code that lists in this order
A B C
D E F
G H I

This is my current code:
echo '

';
foreach ($categories as $k => $category) {
    if ($k % 3 == 0 && $k ! = 0) {
        echo '

';
    }
    echo ''.$category["category"].'	';
}
echo '
';

A: Try this:
$columns = 3;
$rows = ceil(count($categories) / $columns);

echo '
';

for ($row = 0; $row < $rows; $row++) {
    echo '
';

    foreach ($categories as $k => $category) {
        if ($k % $rows == $row) {
            echo ''.$category["category"].'	';
        }
    }

    echo '
';
}

echo '
';

It's not very efficient, but right now I can't think on a better way of doing it.

A: If you want to have the list rendered in columns as indicated, you could generate it in the logical order and just uses the CSS columns property to set in columns:
ul {
  -moz-column-count: 2;
  -webkit-column-count: 2;
  column-count: 2;
}

The bad news is that this is not supported by IE 9 and earlier, but the Columns polyfills like css3-multi-column.js might work sufficiently well in simple cases (despite their limitations and issues).

A: I had this same issue, and I am posting my answer to this old question for the following reasons:

*

*My answer is more general and easy for others to adapt.

*My array was associative, with a string key. BTW, my answer will work for both associative and indexed arrays.

*I didn't want a complex CSS solution, like some of the other answers on this topic. Actually, the solution I came up with was pretty simple--use multiple  tags with style="float:left", inside of a giant table. While I was sceptical that having multiple tbody tags in a single table would pass HTML validation, it in fact did pass without errors.

Some things to note:

*

*$numCols is your desired number of columns.

*Since we are floating items, you may need to set the width and min-width of parent elements and/or add some
, based on your situation.

*for alternative sorting methods, see http://php.net/manual/en/array.sorting.php
Here is my full answer:
function sortVertically( $data = array() )
{
    /* PREPARE data for printing */
    ksort( $data );     // Sort array by key.
    $numCols    = 3;    // Desired number of columns
    $numCells   = is_array($data) ? count($data) : 1 ;
    $numRows    = ceil($numCells / $numCols);
    $extraCells = $numCells % $numCols;  // Store num of tbody's with extra cell
    $i          = 0;    // iterator
    $cCell      = 0;    // num of Cells printed
    $output     = NULL; // initialize

    /* START table printing */
    $output     .= '
';
    $output     .= '
';

    foreach( $data as $key => $value )
    {
        if( $i % $numRows === 0 )   // Start a new tbody
        {
            if( $i !== 0 )          // Close prev tbody
            {
                $extraCells--;
                if ($extraCells === 0 )
                {
                    $numRows--;     // No more tbody's with an extra cell
                    $extraCells--;  // Avoid re-reducing numRows
                }
                $output .= '
';
            }

            $output .= '
';
            $i = 0;                 // Reset iterator to 0
        }
        $output .= '
';
            $output .= ''.$key.'	';
            $output .= ''.$value.'	';
        $output .= '
';

        $cCell++;                   // increase cells printed count
        if($cCell == $numCells){    // last cell, close tbody
            $output .= '
';
        }

        $i++;
    }

    $output .= '
';
    $output .= '
';
    return $output;
}

I hope you find this answer useful.


text:
Q: Failed to load class for data source: Libsvm in spark ML pyspark/scala When I try to import a libsvm file in pyspark/scala using "sqlContext.read.format("libsvm").load", I get the following error -

"Failed to load class for data source: Libsvm."

At the same time, if I use "MLUtils.loadLibSVMFile" it works perfectly fine. I need to use both Spark ML (to get class probabilities) and MLlib for an evaluation. Have attached the error screenshot.
This is a MapR cluster. Spark version 1.5.2
Error

A: libsvm source format is available since version 1.6 of Spark.

A: this is probably a version mismatch, the version of libsvm you have in your project may not have that particular API, can you verify the version of libsvm is loaded and then determine if that api is available?


text:
Q: Task not serializable : Caused by java.io.NotSerializableException org.apache.spark.SparkConf i'm trying to exploit some data from Cassandra database using the spark cassandra connector but i'm falling on this error :
org.apache.spark.SparkException: Task not serializable
.
.
Caused by: java.io.NotSerializableException: org.apache.spark.SparkConf

You can see my code below, i'm using the spark-shell for the experiments
import com.datastax.spark.connector._, org.apache.spark.SparkContext,
org.apache.spark.SparkContext._, org.apache.spark.SparkConf
import collection.JavaConverters._

sc.stop
val conf = new SparkConf(true).set("spark.cassandra.connection.host", "xxx.xxx.xxx.xxx")
val sc = new SparkContext("local","test",conf)

val rdd = sc.cassandraTable("key", "table_name")
rdd.collect // ok
val rdd2 = rdd.where("aa > 10 and aa < 20")
rdd2.collect  // ok
// method1 return an object without any link with SparkContext
val rdd3 = rdd2.map( x=> method1() )
rdd3.collect   // ok
// Error rise to get rdd4
val rdd4 = rdd3.map(x=>method2(x,new Obj1(x.method3())))
// If i do that it works
rdd3.collect.map(x=>method2(x,new Obj1(x.method3())))

I read some case where user called method including SparkContext as parameter inside a map function but that's not my case. The objects on which i called method are object without any link with SparkContext.
I tried to collect rdd rdd2 rdd3 with success but when i apply the map to get rdd4 i fall on the error.

A: I had this error and solved by removing the line val sc = new SparkContext because I use Apache Zeppelin and it provides an sc by default.
Try put the sc.stop at the end of your code.

A: I finally solve the issue, in fact i had arguments of method2 which were declared locally.
val v1 = Set[Double].empty.asJava
val v2 = java.lang.Boolean.TRUE

I just broadcast this values and all works like a charm.
Thank you for your advices