text:
Q: Unix-Like C++ Program String Parsing I am working on a unix-like file system and I need to take in commands from the command line. Some commands are one argument like mkfs, ls, etc. But some are two commands like mkdir foo, rmfile hello. My question is, how can I parse the string to take in a command (cmd), but also take in a second argument (next)? Here is my code so far: (I have not included the functions for the sake of space)
int main(int argc, char *argv[]){

    string cmd;
    string next;

    while (1){
        cout << "Russ_John_Shell> ";
        cin >> cmd;

        //Checks to see whether the string has a file/directory name after the command
        if (next == ""){
            //mkfs command
            if (cmd == "mkfs"){
                makeFS();
            }
            //exit command
            else if (cmd == "exit"){
                exitShell();
            }
            //ls command
            else if (cmd == "ls"){
                listDir();
            }
            //command not recognized at all
            else {
                printf("Command not recognized.\n");
            }

        }
        else{

            //mkdir command
            if (cmd == "mkdir"){
                makeDir(next);
            }
            //rmdir command
            else if (cmd == "rmdie"){
                remDir(cmd);
            }
            //cd command
            else if (cmd == "cd"){
                changeDir(next);
            }
            //stat command
            else if (cmd == "stat"){
                status(next);
            }
            //mkfile command
            else if (cmd == "mkfile"){
                makeFile(next);
            }
            //rmfile command
            else if (cmd == "rmfile"){
                remFile(next);
            }
            //command not recognized at all
            else {
                printf("Command not recognized.\n");
            }
        }
    }
}

Thanks in advance for any help!


text:
Q: Using override init() in an XCtest class? I'm wondering if there is a way to use unit when XCtesting in order to specify a constant variable that isn't torn down between separate test cases? I realize that generally best practices for unit testing are to keep the tests as self contained as possible but in my current situation it would make the tests execute a lot faster if I were able to do this and keep a constant variable between test cases.
Currently, any type of init function that I call
override init() {
    super.init()
}

Leaves me with an EXC_BAD_INSTRUCTION error. If I can't use init() in XCTestCase, is there another work around that I can use?

A: Try moving the variable outside of the XCTestCase class.
import XCTest

var counter = 0 // Note this is outside the class declaration

class MyTests: XCTestCase {
    override func setUp() {
        super.setUp()
        counter++
        print("Counter: \(counter)")
    }

    func testOne() {
        ...
    }

    func testTwo() {
        ...
    }

    func testThree() {
        ...
    }
}

This gives an output like this.
...
Counter: 1
...
Counter: 2
...
Counter: 3
...

A: You can use the class setUp and tearDown methods for exactly this purpose.  The class setUp method is called once before the first test method begins and the class tearDown method is called once after all test methods have completed.
My understanding is that these are intended precisely for handling the kind of test-wide state you describe. Apple has some good documentation on it.
The advantage of this approach is that the state is at least kept local to the test class, if not the individual tests.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Are all permutations of the same parity and trace of the permutation matrix the same up to the change of basis? If two permutations $P_1$ and $P_2$ of $n$ elements have the same parity (i.e. both are even or both are odd) and the same trace of their corresponding permutation matrices (i.e. they leave the same number of elements unchanged), does this mean that there is always a third permutation $P_{12}$ such that $P_{12} P_1 P_{12}^{-1} = P_2$?
This trivially holds for permutations of 2 elements and it is also relatively easy to show that it holds for permutations of 3 elements. Does it hold for arbitrarily large $n$?
If true, is there any known algorithm to find $P_{12}$?

A: No. Consider $(1)(234)(567)$ and $(1)(23)(4567)$.

A: No. In fact two permutations are equivalent in that sense, (ie conjugate), if and only if they have the same "signature", meaning that the decompositions into disjoint cycles have the same number of cycles of a given length.
So for example in $S_8$ the permutations $P_1=(1,2)(3,4)(5,6,7,8)$ and $P_2=(1,2,3,4)(5,6,7,8)$ are not conjugate, even though they're both even and have "trace" zero (no fixed points). Anything conjugate to $P_2$ must be the product of two disjoint cycles of length four, hence cannot be $P_1$.
Now say $P_1=(a,b)(c,d,e)$ and $P_2=(s,t)(u,v,w)$ are two disjoint-cycle decompositions. Then $P_1$ and $P_2$ are conjugate. $P_{12}$ will be a permutations that maps $a$ to $s$, $b$ to $t$, etc., and maps the fixed points of $P_1$ to the fixed points of $P_2$.


text:
Q: How to save data to database at fixed intervals on Django? I'm writing a django survey application and it's required to save votes on a queue structure and at 1 minute intervals save the elements of the queue on database. Thats for save I/O overhead.
Currently I'm saving the votes directly from my votes view:
def vote(request, question_id):
    question = get_object_or_404(Question, pk=question_id)
    selected_choice = question.choice_set.get(pk=request.POST['choice'])
    selected_choice.votes += 1
    selected_choice.save()
    return HttpResponseRedirect(reverse('enqueteapp:results', args=(question.id,)))

My problem is that I don't know where I can start the queue and the thread to do what I need to do.
PS: I don't wanna know if there is a better way to do it. I'm required to use the queue stuff.

A: You should be using some kind of cache. Take a look a Django options: https://docs.djangoproject.com/en/2.0/topics/cache/


text:
Q: How to get the JavaScript Object from the given string? How to get the Object from a string?
I written a localStorage util, in it there are get and set methods.
in the set method:
function fnGet(name){

var getVal=storage.getItem(name);
if(getVal==null){
  return console.log('the localstorage did\'t have'+name);
}
if((getVal.split(':-:')).lenght>1){
  return eval('('+getVal.split(':-:')[0]+')');
}
  return getVal.split(':-:')[0];
}

You can ignore the :-:, it is the separator of the saved data and timestamp.
there is a problem, if the data is stored a JavaScript Object, such like this:
'{"pk":1,"username":"test01","email":"","first_name":"","last_name":""}:-:1521381469910'
when I use the get method, it will become like this:
'{"pk":1,"username":"test01","email":"","first_name":"","last_name":""}'
How can I get to the JavaScript Object?
How to optimize my get method?

A: JSON.parse on your response from the store. localStorage stores everything as strings so you would need to stringify the object at first, as Im supposed you do as otherwise you wouldnt have been able to save it to the store.
Then to retrieve it you would need to parse it to get the javascript object again.

A: Two things:

*

*Use JSON.parse() instead of eval; it's not only safer, but more descriptive as to what your intent is.  Note: this requires using JSON.stringify() on the data being saved in localStorage

*Correct your spelling errors; you would never get to the eval/parser block because your length was spelled "lenght"

function fnGet(name) {

  let getVal = storage.getItem(name)
  if (getVal == null) {
    return console.log(`the localstorage did't have: ${name}`);
  }

  let val = getVal.split(':-:');      // for performance cache the split
  if (val.length > 1) {               // Spelling error: "lenght" -> length
    return JSON.parse(val[0]);
  }
  return val[0];
}

A: LocalStorage saves the data stringified. So you should use JSON.parse(yourVariable) to get the data back as JSON

A: function fnGet(name) {

    var getVal = storage.getItem(name);
    if (getVal == null) {
        return console.log('the localstorage did\'t have' + name);
    }
    if ((getVal.split(':-:')).lenght > 1) {
        return eval('(' + JSON.parse(getVal.split(':-:')[0]) + ')');
    }
    return getVal.split(':-:')[0];
}

all you needed was JSON.parse which takes a string as an argument and if its a valid object string ,returns an object else throws an error


text:
Q: Как скачать csv-файл с удаленного сервера через ftp используя gulp? Пытаюсь скачать csv файл с удаленного сервера по ftp и сохранить его локально, используя gulp. Пробовал различные npm модули, но они либо не работают с ftp (gulp-download и gulp-download-stream), либо работают только на загрузку, а не на скачивание(vinyl-ftp). Кто-нибудь знает, как это сделать?

A: Есть такие пакеты для node.js, как ftp-get и node-ftp, gulp'у тут вообще не место он сборщик проектов для фронтенда.


text:
Q: Skip one or more constraints in Django form.is_valid() Given the following model:
class User(models.Model):
    role = models.IntegerField(default=0, blank=True)
    name = models.CharField(max_length=255, blank=False, null=False)
    email = models.EmailField(max_length=128, unique=True, blank=False, null=False)

I need that form.is_valid() would skip the unique constraint on email field.
It's essential, that emails would be unique, however in one particular view I wanna use get_or_create, which doesn't seem to work:
if form.is_valid():
    usr, usr_created = models.User.objects.get_or_create(email=form.email)
    <...>

Is this possible?

A: This is not possible.
unique=True creates a database constraint that checks for the uniqueness of the field. By its very design this disallows non-unique values, and the only way to circumvent this is to remove the constraint.
If the problem is that you want to allow multiple empty values, you can set null=True. Multiple NULL values are still considered unique by the constraint.

A: Don't list the field you want to override in the fields list and create a new custom field in the ModelForm:
class UserForm(forms.ModelForm):
    class Meta:
        model = User
        fields = ["role", "name"]

    email = forms.EmailField(max_length=128)

    def save(self, commit=True):
        instance = super(PatientForm, self).save(commit=False)
        instance.email= self.cleaned_data.get("email")
        return instance.save(commit)


text:
Q: Display post meta conditionally based on it's value I have a custom field that's a radio button with 3 choices (yes, no, other).
What I'd like to do is the following:
[If custom field value is yes]
Display something here
[elseIf custom field value is no]
Display something here
[elseIf custom field value is other]
[else]
The code I have thus far isn't working, here it is.
    <?php
        global $wp_query;
        $postid = $wp_query->post->ID;
        $can_download = get_post_meta($postid, 'enable_downloads', true);
        if ($can_download == 'yes') { ?>

    <?php } elseif ($can_download == 'no') { ?>

    <?php } elseif ($can_download == 'other') { ?>

    <?php } else { ?>

    <?php } ?>

No matter what it's just defaulting to yes, I can't figure it out, not sure if this is even the correct way to approach.

A: If it's created with ACF, then the way to call the field is like this:
$can_download = get_field('enable_downloads',$postid);

so your code should look like:
<?php
        global $wp_query;
        $postid = $wp_query->post->ID;
        $can_download = get_field('enable_downloads',$postid);
        if ($can_download == 'yes') { ?>

    <?php } elseif ($can_download == 'no') { ?>

    <?php } elseif ($can_download == 'other') { ?>

    <?php } else { ?>

    <?php } ?>


text:
Q: loops in r only giving final value I'm trying to build a loop which goes through all values of my i and prints them in a matrix. instead I'm only getting the final answer, could you please advise where I'm going wrong:
mat2 <- matrix(data = NA, nrow = 4, ncol = 10, byrow = TRUE)
for(i in 1:10){
  M <- 5000*i
  insurer[i] <- simdata[simdata<=M]
  reinsurer[i] <- simdata[simdata>M]
  mat2[1,] <- mean(insurer)
  mat2[2,] <- mean(reinsurer)
  mat2[3,] <- var(insurer)
  mat2[4,] <- var(reinsurer)
  mat2
}

output is as follows:
mat2
             [,1]         [,2]         [,3]         [,4]         [,5]         [,6]
[1,]      9694.34      9694.34      9694.34      9694.34      9694.34      9694.34
[2,]     60776.64     60776.64     60776.64     60776.64     60776.64     60776.64
[3,]  82806727.19  82806727.19  82806727.19  82806727.19  82806727.19  82806727.19
[4,] 103927604.88 103927604.88 103927604.88 103927604.88 103927604.88 103927604.88
             [,7]         [,8]         [,9]        [,10]
[1,]      9694.34      9694.34      9694.34      9694.34
[2,]     60776.64     60776.64     60776.64     60776.64
[3,]  82806727.19  82806727.19  82806727.19  82806727.19
[4,] 103927604.88 103927604.88 103927604.88 103927604.88


text:
Q: Weird XIB file issue Experiencing a weird problem in a modified program written by me. In my first iteration, the view controller had an IBAction by the title userSpecifyingInput and had all my buttons wired up to this IBAction.
To make the design more sophisticated, I introduced userSpecifyingDigit and userSpecifyingLetter and accordingly had some buttons wiring up to the first IBAction (userSpecifyingDigit) and the next button wiring up to the second IBAction (userSpecifyingLetter).
Upon running my program, it gave me this error:
terminating app: NSInvalidArgumentException
 Unrecognized selector sent to instance
And these selectors were alternating between userSpecifyingInput and userSpecifyingDigit which did not make sense as userSpecifyingInput was completely removed from my ViewControllers interface and implementations.
Now I am not sure why userSpecifyingInput still existed, but after dabbling with sent events, I noticed that the buttons were wired upto the new selectors as well as the old selector.
I had to manually remove the old selector from the touchupinside events for all the buttons.
Naturally this does not seem to be a very convenient way to go about proceedings and if the view controller selectors are modified then the touch events ought to be automatically removed.
Am I missing something here? This is a pretty open ended question with different answers

A: Eliminating an IBAction from your implementation will not remove any previous links to it in IB. I haven't heard of any XCode/IB preferences to shortcut this issue.

A: Sounds like the xib still thinks one of it's objects is hooked up to the UIViewController, but the function on the UIViewController is no longer there. To check and fix this...

*

*Click on the xib file in the project navigator

*Select the File's Owner

*Click on the Connections Inspector

*Verify that none of these connections are invalid

I would also look in the UIViewController to make sure no automagically created references exist here as well.


text:
Q: Flutter Futurebuilder snapshot is null I try to show the results from JSON in a ListView in Flutter with a FutureBuilder.
But the snapshot is null and the message that no data is available shows.
Here I try to fetch the data:
static Future _getBans() async {
Storage.getLoggedToken().then((token) async {
  var body = {
    "token": token
  };
  final response = await http.post('${URLS.BASE_URL}/punishments.php', headers: ApiService.header, body: json.encode(body));
  if (response.statusCode == 200) {

    List<Ban> bans = [];
    var jsonData = json.decode(response.body)["bans"];
    for(var b in jsonData){
      Ban ban = Ban(b["player"], b["reason"], int.parse(b["end"]), b["by"]);
      bans.add(ban);
    }

    print(response.body);
    print(bans.length);

    return bans;
  } else {
    return null;
  }
});

}
from this JSON response
{"status":1,"msg":"OK","bans":[{"player":"DDOSAttacke","reason":"Hacking","end":"1579275471304","by":"DDOSAttacke"}],"mutes":[]}

My Futurebuilder. Here is snapshot null but the count of the elements is working.
Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Text('Aktive Bans'),
  ),
  body: Container(
    child: FutureBuilder(
      future: _getBans(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.data == null) {
          return Container(
            child: Center(
                child: Text('Keine aktiven Ban vorhanden')
            ),
          );
        } else {
          return ListView.builder(
            itemCount: snapshot.data.length,
            itemBuilder: (BuildContext context, int index) {
              return ListTile(
                title: Text(snapshot.data[index].player),
              );
            },
          );
        }
      },
    ),
  ),
);

}

A: Please try this. I think you'll have to use await keyword for the getLoggedToken mothod, the returnwill wait for the post before returning anything. But now you're returning before the getLoggedTokenfinishes his work. That is why you are always receiving null.
 static Future _getBans() async {
 var token = await Storage.getLoggedToken();
      var body = {
        "token": token
      };
      final response = await http.post('${URLS.BASE_URL}/punishments.php', headers: ApiService.header, body: json.encode(body));
      if (response.statusCode == 200) {

    List<Ban> bans = [];
    var jsonData = json.decode(response.body)["bans"];
    for(var b in jsonData){
      Ban ban = Ban(b["player"], b["reason"], int.parse(b["end"]), b["by"]);
      bans.add(ban);
    }

    print(response.body);
    print(bans.length);

    return bans;
  } else {
    return null;
  }
}


text:
Q: Is "month year" or "month, year" the more common form of punctuation in print publishing? A great many style guides address the question of whether or not to separate the month and year with a comma in phrases of the type "January[,] 2018"—and yet, to my surprise, a search of English Language & Usage for the terms "month year comma" yields only one question that seems to focus on precisely this point: Is there always a comma before and after a year in a sentence?
Unfortunately, that question was closed as duplicate back in 2014, even though the prior question that it supposedly duplicates (How to use AP Style commas after dates) does not ask about "month[,] date" constructions, and even though none of the answers posted in response to that question address the issue either.
But the "Is there always a comma before and after a year in a sentence?" question doesn't show any research, which would probably lead to its being closed again for that reason if it were reopened as not being a true duplicate—so rather than try to rehabilitate it, I ask the question afresh (and in my own words) here:

In instances where only a month and a year appear as date indicators—such as "January[,] 2018"—is it more common in print publishing (that is, in ink-and-paper books and magazines, whose publishers tend to enforce in-house or third-party style guidelines) to include a comma after the month or to omit it? Are the relevant style guides evenly divided on this issue, or do they preponderantly favor one or the other option?

A: Bryan Garner, Garner's Modern American Usage, second edition (2003) has a useful entry on this matter:

DATES. ... B. Month and Year. February 2003 is better than February of 2003. Stylebooks have long agreed that no comma should appear between the month and the year. Among the mountains of evidence that might be  amassed are these sources: The Washington Post Deskbook on Style 127 (1978); Kate L. Turabian, A Manual for Writers of Term Papers, Theses, and Dissertations 30 (5th ed. 1987); Publication Manual of the American Psychological Association 63 (4th ed., 1994); Scientific Style and Format 227 (6th ed., 1994); Joseph Gibaldi, MLA Handbook for Writers of Research Papers 70 (1999); Allan M. Siegel & William G. Connolly, The New York Times Manual of Style and Usage 101 (1999); Webster's New World English Grammar Handbook 161 (2001); The Chicago Manual of Style 253 (15th ed., 2003).
It is therefore strange to encounter an article in The New Yorker, one of our best-edited journals, in which January, 2000 and March, 2000 appear on the first page, and then five similar references appear throughout the piece.  (See Scott Turow, "To Kill or Not to Kill," New Yorker, 6 Jan. 2003, at 40–47.) This seems anomalous: almost every professional editor would immediately delete the superfluous commas.

Garner might also have mentioned The Associated Press Stylebook and Briefing on Media Law (2002):

When a phrase lists only a month and a year, do not separate the year with commas. When a phrase refers to a month, day and year, set off the year with commas.
EXAMPLES: January 1972 was a cold month. ...

and Words into Type, third edition (1974):

When only the month and the year are given, commas are unnecessary.

[Example:] He began writing in May 1971 and finished in April 1972.

and The Oxford Guide to Style (2002):

7.10.1 Order [in Dates] Dates should be shown in the order day, month, year, without internal punctuation, as 2 November 1993. A named day preceding a data is separated by a comma: Tuesday, 2 November 1993. There is no comma between month and year: in June 1831.

On the other hand, a quick check of the December 11, 2017 issue of The New Yorker finds the magazine still hewing to the practice of including a comma in "month year" phrases. For instance, Jon Lee Anderson, "Accelerating Revolution,"uses it six times:

The battle, fought by Bolívar's partisan's and Spanish royalists in June, 1821, was the crucial victory ... In February, 1992, Chávez launched a coup attempt ... In December, 1993, Maduro went with a group of young comrades ... In legislative elections in December, 2015, the opposition trounced the P.S.U.V., ... In November, 2016, Maduro said, ... He was alluding to an executive order that Obama had signed in March, 2015 ...

Conclusion
As with all issues involving punctuation style, the first question a writer should ask in, "What style guidelines am I obliged to satisfy?" If the answer is "None," the writer can decide whether to follow preponderant publishing-house usage or to follow personal preference (if the two do not coincide). And in the case of "month[,] year" punctuation, the preponderance of usage clearly supports the no-comma option.

A: FWIW, I ended up here after viewing a half dozen other sites - results of a google search on this topic (one was EduBirdie Writing platform). They virtually all agreed that a comma should be used if the day is included (February 3, 2020) but not if only month and year are used (February 2020). I don't recall any of them mentioning using a comma after the year. I would assume you would only use it if the sentence called for one. In other words, if a comma would be indicated had you only used '2020' (or 'February'):
'In February 2020, as in January, there was no snowfall.'
'February 2020 marks the first month of the Chinese year of the rat.'

A: The Elements of Style 2007 edition by Strunk and White (E.B. White wrote for The New Yorker) shows the following:
October to January, 1952 ;
July 6, 2017 ;
Monday, November 7, 1888 ; and
25 December 1985
He recommends the last example. I believe the 4th edition shows the same comma usage.

A: I think it is more contingent on if you want a pause between the month and the year... (Look at that ellipsis! Totally uncalled for!) But the question arises as to why commas are used to separate day and month from year, just what does a comma do anyway?
I always used semicolons before using several commas and a colon before a list that has no conmas:
Commas
Semicolons
Colons
Whatever happened to schwa e?
I don't see it on my keyboard anywhere...


text:
Q: Custom Report Needed. Click detail at Subscriber level I need to a create a report that shows me by date at Subscriber level what links have been clicked in emails.
I can see that it's possible to produce reports to show click activity, but this isn't at Subscriber level.
I can also see that it's possible to produce a Subscriber level report that shows the number of clicks for a Subscriber, but not what they've clicked on.
Thanks in advance.

A: You can create an SQL query and get this data from the _Click Data View.
Create a Data Extension first with the required fields, and then automate the query to run daily or weekly, per your requirements.
Here's an example query:
SELECT EventDate, SubscriberKey, URL, LinkName
FROM _Click

You can also run this ad hoc in Query Studio.

Here are the fields available in the _Click Data View. Follow this link to get all the details such as data types, etc: https://help.salesforce.com/articleView?id=mc_as_data_view_click.htm&type=5
SubscriberID
SubscriberKey
AccountID
OYBAccountID
JobID
ListID
BatchID
EventDate
Domain
TriggererSendDefinitionObjectID
URL
TriggeredSendCustomerKey
LinkName
LinkContent
IsUnique

You can also download a visual representation of all Data Views here.


text:
Q: Does Sitecore have a built in email engine? I know this may sound like a stupid question, but numerous google searches haven't given me the answer I'm looking for. I see a lot of data on how to format emails based on Sitecore Templates etc, but nothing on actually sending mail. Do I need to do this via .net code, or does Sitecore have a component that manages sending mail?

A: Take a look at Sitecore.MainUtil.SendMail as a built in function within Sitecore to send email. My understanding is it uses the standard .net mail library, but puts a Sitecore wrapper around it.

A: It depends on the volume of mail you want to send. If you just want to send simple emails (ie alert emails or 'thank you for registering' type emails then you would just use the normal built-in .NET email functionality.
For more complicated (campaign/mass) emailing there are add-on modules such as the Email Campaign Manager (ECM) - http://sdn.sitecore.net/Products/ECM.aspx or http://www.sitecore.net/unitedkingdom/Resources/brochures/Sitecore%20Email%20Campaign%20Manager
Sitecore provides some example auto-emailer actions in the 'Sample Workflow' that comes with the default Sitecore install too.
The Web forms for Marketers module also has some emailing actions that are included with the package.
Hope this helps :)

A: You should probably look into system.mail.net. The best reference site for this can be found here:
http://www.systemnetmail.com/

A: Thanks for all of the replies.
As with other Sitecore issues, I found that Sitecore was not necessary to solve this issue. Standard .Net functionality did what I wanted much easier.


text:
Q: Some site names are truncated in the grid of sites There are several sites whose names are truncated currently on the site list at least in grid view:

*

*Retrocomputin

*ExpressionEng Answers

*Software Recommendat

*Hardware Recommendat

*Software Quality Assurance &

The first 4 sites have one or more letters cut off:

For the last site, it's an entire word that is cut off (but the tops of letters are visible):

I am in Chrome 49.0.2623.112 (64-bit) on Mac 10.7.5.
This also happens in mobile Safari.


text:
Q: Multiple parents hierarchy recursion Master Table
===========
ID NAME
1   A
2   B
3   C
4   D
5   E

Hierarchy table with multiple parents (Note that neither can be primary column due to duplicate values):
Relations Table
================
ChildID ParentID
   3        1
   3        2
   4        3
   4        2
   5        4

Hierarchy becomes like (it might not be this linear always):
  1         2
  |         |
  3         3
  |         |
  4         4
  |         |
  5         5

For reporting purpose I need data in recursive hierarchy format so that I can drill down it. I'm not getting if I can get drill down feature from existing data itself (seems not doable as I can not create recursive parent-child relationship due to duplicate values).
Do you have any ideas? My goal is to finally use this structure as a dimension in SSAS which automatically gives drill down if a table has a self primary key-child key relationship.

A: Using your example data, I actually get a different tree...
Relations Table            Tree
================          =======
ChildID ParentID           1   2
   3        1               \ /|
   3        2                3 |
   4        3                 \|
   4        2                  4
   5        4                  |
                               5

Do you actually want two independent trees?  If that's the case, you could introduce an extra field such as a tree id...
Relations Table              Tree1     Tree2
=======================      =====     =====
TreeID ParentID ChildID
   1     NULL      1           1         2
   1      1        3           |         |
   1      3        4           3         3
   1      4        5           |         |
   2     NULL      2           4         4
   2      2        3           |         |
   2      3        4           5         5
   2      4        5

Without some extra piece of information, you'll always have problems of branches splitting and merging without a very well formed set of constraints.  For example, if you wanted two linear trees of 1-3-4-5 and 2-3-4-6, your current model would have this...
Relations Table            Tree
================          =======
ParentID ChildID           1   2
   1        3               \ /
   2        3                3
   3        4                |
   4        5                4
   4        6               / \
                           5   6

The problem you now have though, is that there are FOUR linear paths...
- 1-3-4-5
- 1-3-4-6
- 2-3-4-5
- 2-3-4-6
What may be required is for you to describe a real world situation, exactly what you want from it, and exactly what you don't want from it.

My typical experience is that, for reporting purposes, any node in a tree should only have one parent, but may have many children.  This means that when climbing up a tree you only have one route, and when climbing down a tree the data separates into sub-nodes.
Having many parents and many children makes a web rather than a tree.  Where you have multiple routes, no matter which direction you traverse the tree.


text:
Q: Capturing the Title of each Search results in Google Search Page using Selenium Web Driver I am doing a project where I have to compare the Google search results with another search results engine. I am planning to perform this testing by comparing the search results using Selenium tool.
What I want to do is:

*

*Capture the first 20 search results from Google. Save it in a csv file

*Capture the first 20 search results from other search engine. Save it in csv file.

*Compare the results.

Now i got a code from stackoverflow site as below. Modified to my requirement. It is fetching the first result's title and link. How do i get the title and link of the entire page?
My code is:
    package gooPkg;
    import java.util.List;
    import java.util.concurrent.TimeUnit;
    import org.openqa.selenium.*;
    import org.openqa.selenium.firefox.FirefoxDriver;
    import org.openqa.selenium.support.ui.ExpectedConditions;
    import org.openqa.selenium.support.ui.WebDriverWait;

    public class testSearch {

    public static void main(String[] args) {
        String baseUrl = "https://www.google.co.in/";
        WebDriver driver = new FirefoxDriver();
        //String underConsTitle = "Under Construction: Mercury Tours";
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        driver.get(baseUrl);
        // Enter the query string "Cheese"
        WebElement query = driver.findElement(By.name("q"));
        query.sendKeys("obama twitter");
        query.submit();

        long end = System.currentTimeMillis() + 5000;
        while (System.currentTimeMillis() < end) {
        WebElement resultsDiv = driver.findElement(By.className("gssb_e"));

        if (resultsDiv.isDisplayed()) {
            break;
        }
    }

        List<WebElement> weblinks = driver.findElements(By.xpath("/html/body/div/div[3]/div[2]/div[6]/div/div[4]/div/div[2]/div[2]/div/ol/li/div/div/h3/a"));
       for (WebElement suggestion : weblinks) {
        System.out.println(suggestion.getText()+"\n");
        System.out.println("==> "+suggestion.getAttribute("href")+"\n");

    }
}}

A: You can use findElements to get the all the search result titles & links.
String baseUrl = "https://www.google.co.in/";
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

driver.get(baseUrl);
WebElement query = driver.findElement(By.name("q"));
query.sendKeys("obama twitter");
query.submit();

//==============Here logic goes =======================
//get all the search result
List<WebElement> allSearchResults=driver.findElements(By.cssSelector("ol li h3>a"));

//iterate the above list to get all the search titles & links from that page
for(WebElement eachResult : allSearchResults) {
System.out.println("Title : "+eachResult.getText()+", Link : "+eachResult.getAttribute("href"));
}

EDIT-I
Try with below logic. Include search term in url itself.
String baseUrl = "https://www.google.co.in/#q=webdriver";
driver.get(baseUrl);

//get all the search result
List<WebElement> allSearchResults=driver.findElements(By.cssSelector("ol li h3>a"));

    //iterate the above list to get all the search titles & links from that page
for(WebElement eachResult : allSearchResults) {
    System.out.println("Title : "+eachResult.getText()+", Link : "+eachResult.getAttribute("href"));
}


text:
Q: Equal spacing between controls I want to place image and text under image as below. The height of the rows have to be equally divided. How can this work if I want images to size accordingly?
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="9*"/>
            <ColumnDefinition Width="10*"/>
            <ColumnDefinition Width="10*"/>
            <ColumnDefinition Width="20*"/>
            <ColumnDefinition Width="10*"/>
            <ColumnDefinition Width="40*"/>
            <ColumnDefinition Width="10*"/>
            <ColumnDefinition Width="10*"/>
            <ColumnDefinition Width="10*"/>
            <ColumnDefinition Width="10*"/>
            <ColumnDefinition Width="10*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="10*" />
            <RowDefinition Height="10*" />
            <RowDefinition Height="10*" />
            <RowDefinition Height="10*" />
            <RowDefinition Height="10*" />
            <RowDefinition Height="10*" />
            <RowDefinition Height="10*" />
            <RowDefinition Height="10*" />
            <RowDefinition Height="10*" />
            <RowDefinition Height="10*" />
        </Grid.RowDefinitions>

            <Image Grid.Column="1" Grid.Row="0" Source="pack://application:,,,/WpfApplication5;component/led.green.off.png" HorizontalAlignment="Center">
            </Image>
            <TextBlock Grid.Column="1" Grid.Row="1" Text="Turret Power" ></TextBlock>

            <Image Grid.Column="1" Grid.Row="2" Source="pack://application:,,,/WpfApplication5;component/toggle.sheath.DOWN.png" HorizontalAlignment="Center">
            </Image>
            <TextBlock Grid.Column="1" Grid.Row="3" Text="Off" ></TextBlock>

            <Image Grid.Column="1" Grid.Row="4" Source="pack://application:,,,/WpfApplication5;component/toggle.sheath.DOWN.png" HorizontalAlignment="Center">
            </Image>
            <TextBlock Grid.Column="1" Grid.Row="5" Text="Off" ></TextBlock>
            <Image Grid.Column="1" Grid.Row="6" Source="pack://application:,,,/WpfApplication5;component/toggle.sheath.DOWN.png" HorizontalAlignment="Center">
            </Image>
            <TextBlock Grid.Column="1" Grid.Row="7" Text="Off" ></TextBlock>
            <Image Grid.Column="1" Grid.Row="8" Source="pack://application:,,,/WpfApplication5;component/toggle.sheath.DOWN.png" HorizontalAlignment="Center">
            </Image>
            <TextBlock Grid.Column="1" Grid.Row="9" Text="Off" ></TextBlock>
            <Image Grid.Column="1" Grid.Row="10" Source="pack://application:,,,/WpfApplication5;component/toggle.sheath.DOWN.png" HorizontalAlignment="Center">
            </Image>
            <TextBlock Grid.Column="1" Grid.Row="11" Text="Off" ></TextBlock>
    </Grid>

If I do the above, the images are big and go over the window

A: *

*You're missing 2 <RowDefinition> in <Grid.RowDefinitions> (according to your usages of Grid.Row)

*You don't have to put a weight in your row/column definitions if they're all the same, and you don't even have to set Height if the value is *, since this is the default (you can remove Height="10*" from each <RowDefinition>)

*Maybe you'll want to have some column definitions set with Width="Auto", but I'll leave that to you.


text:
Q: Getting Nested JSON data using VueJS I want to get a nested JSON data using VueJS, but I'm having trouble understanding how to do that (I'm new to VueJS). The data is as follows:
{
"title": "Editor",
"key": "Editor_one",
"attributes": {
    "holder",
},
"properties": [
    {
        "title": "Date :",
        "attributes": {
            "Path": "0/9",
        }
    },
    {
        "title": "2000/06/17",
        "key": "date_ident",
        "attributes": {
            "Path": "0/10",
        }
    },
    {
        "key": "zero_vector",
        "attributes": {
            "Path": "0/11",
        },
        "properties": [
            {
                "title": "File",
                "attributes": {
                    "Path": "0/11/0",
                },
    },
    {
        "key": "zero_date",
        "attributes": {
            "Path": "0/17",
        },
        "properties": [
            {
                "title": "2000/06/18",
            },

My current vueJS code attempt is as follows:

  {{editDate.title}}
  <input
    type="text"
    v-model="date"
    name="date"
    placeholder="Add Date"
  />

async created() {
try {
  const response = await axios.get('http://localhost:8080/');
  this.vectors = response.data.properties; //assign data from response to 'vectors'
} catch (e){
  console.error(e);
}

},
I want to get the data: "title": "2000/06/18" from the key: "zero_date" and bind it to the 'input' tag. Thanks!

A: Does that help? Can properties inside "zero_date" have more than one item?
{
    async created() {
        try {
            const response = await axios.get('http://localhost:8080/');
            this.vectors = response.data.properties; //assign data from response to 'vectors'
        } catch (e){
            console.error(e);
        }
    },
    computed: {
        zeroDate: {
            get() {
                return this.vectors.find(vector => vector.key === 'zero_date').properties[0].title
            },
            set(newValue) {
                this.vectors.find(vector => vector.key === 'zero_date').properties[0].title = newValue
            }
        }
    }
}


text:
Q: Anybody out there having success with the NWorkspace pattern? I've just begun to delve into my first experiments with Domain Drive Design and I'm taking advantage of the NWorkspace pattern. This pattern seems to make a lot of sense however I haven't been able to find very many examples of places this pattern has been successfully used or even publicly documented. Before I get to far into my implementation I would like to know if anybody has had success using this pattern or whether somebody could point me to any references where NWorkspace has been used in any open source project that I could learn from. Also are there better or more well known alternatives to this pattern that I should know about?
Brief background on NWorkspace
For those who may not be familiar with NWorkspace, it is a pattern introduced by Jimmy Nisson's which abstracts query and persistance responsibilities. In his book Applying Domain-Driven Design and Patterns, Jimmy Nilsson shows how NWorkspace can be used to abstract the infrastructure portions of a DDD Repository as well as provide a mechanism to perform cross Repository atomicity with regard to persistence.

A: It seems like he's recommending separate interfaces for read and write repositories.
I don't have experience with the pattern described, but I would recommend not having cross-repository transactions.  Instead, I would suggest a few solutions popular amongst the DDD community (Eric Evans, Udi Dahan, Greg Young) that have really helped me:

*

*Always use eager loading on your aggregate roots.  Then you don't need cross-repository atomicity, and figuring out what's changed when you persist the object is a lot easier.

*Use separate classes for writing (i.e. domain classes) and reading (i.e. your viewmodel).  Create view model repositories that retrieve viewmodels directly from the database (instead of mapping domain objects to view model classes).

See if implementing the above 2 things simplifies your design.


text:
Q: Python 2.7 dictionary value not taking float as the input I am working with Python 2.7 and trying to insert a value which is a float to a key. However, all the values are being inserted as 0.0. The polarity value is being inserted as 0.0 and not the actual value.
Code Snippet:
from textblob import TextBlob
import json
with open('new-webmd-answer.json') as data_file:
data = json.load(data_file, strict=False)
data_new = {}
lst = []
for d in data:
   string =  d["answerContent"]
   blob = TextBlob(string)
#print blob
#print blob.sentiment
#print d["questionId"]
   data_new['questionId'] = d["questionId"]

   data_new['answerMemberId'] = d["answerMemberId"]
   string1 = str(blob.sentiment.polarity)
   print string1
   data_new['polarity'] = string1
#print blob.sentiment.polarity
   lst.append((data_new))

json_data = json.dumps(lst)

#print json_data
with open('polarity.json', 'w') as outfile:
   json.dump(json_data, outfile)

A: The way your code is currently written, you're overwriting the dictionary with each iteration. Then you append that dictionary to the list multiple times.
lets say your dictionary was dict = {"a" : 1} and then you append that to a list
alist.append(dict)

alist

[{'a' : 1}]

Then you change the value of dict, dict{"a" : 0} and append it to the list again alist.append(dict)
alist

[{'a' : 0}, {'a' : 0}]

This occurs because dictionaries are mutable. For a more complete overview on mutable vs unmutable objects see the docs here
To achieve your expected output, make a new dictionary with each iteration of data
lst = []
for d in data:
    data_new = {} # makes a new dictionary with each iteration
    string = d["answerContent"]
    blob = TextBlob(string)
    # print blob
    # print blob.sentiment
    # print d["questionId"]
    data_new['questionId'] = d["questionId"]

    data_new['answerMemberId'] = d["answerMemberId"]
    string1 = str(blob.sentiment.polarity)
    print string1
    data_new['polarity'] = string1
    # print blob.sentiment.polarity
    lst.append((data_new))


text:
Q: Allow logged in user to vote only once on a suggestion (Django) I've got two models on my Django site. An Event and suggested names for that event, in the case that the one I provide may not be the best. I want each user to only be able to vote on each suggestion once. They must be logged in to do so, so I know who they are. Any clue how I'd add that to these models?
class Event(models.Model):
    def __unicode__(self):
        return self.title
    event_id = models.BigIntegerField(blank = 'TRUE', primary_key='TRUE')
    title = models.CharField(max_length=200, blank = 'TRUE')
    start = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
    end = models.CharField(max_length=200,blank = 'TRUE', null = 'TRUE')
    location = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
    tags = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
    url = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
    suggested = models.ManyToManyField('suggestedName', blank = 'TRUE', null = 'TRUE')

class suggestedName(models.Model):
    def __unicode__(self):
        return self.name
    name = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
    votes = models.IntegerField(default = 0)

A: One simple way would probably be handling it in the code.
Before save, you check if object exists in ManyToMany field
You can do it in one of 2 ways i can think of in the models:
Create a new table that references the User, with the Suggestion and the Event
OR
Have a unique property on the through table
class Event(models.Model):
    def __unicode__(self):
        return self.title
    event_id = models.BigIntegerField(blank = 'TRUE', primary_key='TRUE')
    title = models.CharField(max_length=200, blank = 'TRUE')
    start = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
    end = models.CharField(max_length=200,blank = 'TRUE', null = 'TRUE')
    location = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
    tags = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
    url = models.CharField(max_length=200, blank = 'TRUE', null = 'TRUE')
    suggested = models.ManyToManyField('suggestedName', blank = 'TRUE', null = 'TRUE', through='EventSuggestion')

class EventSuggestion(models.Model):
    #through table attributes
    event = models.ForeignKey(Event)
    suggestion = models.ForeignKey(suggestedName)
    user = models.ForeignKey('User')

    class Meta:
        unique_together = ('event', 'suggestion', 'user')


text:
Q: Typescript generic constraint for child classes Using Typescript 2.3.4.
I'm trying to put a generic constraint on a method parameter, like so: public static FromFactType<T extends  FactCore>() :T.  FactCore is a base class which has three direct descendents: FactEvent, FactDuration, FactPlain.  Each of those direct descendents has 15-20 separate children which add new properties.  As an example, FactEvent has a child FactBirth, so FactBirth inherits indirectly from FactCore.
However, when I try to pass an instance of FactBirth into my method, I get an error: Type BirthFact cannot be converted to type 'T'.  The only way I've been able to appease the Typescript compiler is to explicitly list BirthFact in the constraint.  I've tried adding the mid-level classes (FactEvent, FactDuration and FactPlain) to the constaint with no luck - same error.
Do I really need to explicitly list all 60+ bottom-level classes in the constraint?
Thanks.


text:
Q: AngularJS Ng-repeat with array I have table and trying to render out table rows using the ng-repeat.
The situation is that I have a invoice which may or may not have multiple invoice details attached.  The data is returned in an object and one of those properties is an array.  So, I created my table and used ng-repeat using the array as the model.  In a way it works because three table rows are render out but the description remains field blank.
Thanks
I looked here
HTML:

JS
function loadOrder(invoiceNumber) {
    return orderService.getOrderById(invoiceNumber)
        .then(function (result) {
            vm.orders = result.data;
        }, function (err) {
            console.log("error returned");
        });
}

sample of the data

A: details is binded as each member of the componetGrid, so

should be

instead

A: Your reference to componentDescription is wrong. This should work:

A: From the data you have provided in snippet it looks like componentgrid is a array.
Now in ng-repeat details in vm.orders.componetGrid means details is a componentgrid object.
So you should not say details.componentgrid.componentDescription
instead it should be details.componentDescription


text:
Q: Zabbix server running not running. Value no in zabbix dashboard on Centos7 What should I do, I have set up everything for what I thought would be a wonderful well running zabbix server and now it is not running on the final step. I cannot figure out what went wrong. How can I fix this? this is my first time, please help thanks  :)
?php
// Zabbix GUI configuration file.

$DB['TYPE']                             = 'MYSQL';
$DB['SERVER']                   = 'localhost';
$DB['PORT']                             = '0';
$DB['DATABASE']                 = 'zabbix';
$DB['USER']                             = 'zabbix';
$DB['PASSWORD']                 = 'zabbix_db_pass';

// Schema name. Used for PostgreSQL.
$DB['SCHEMA']                   = '';

// Used for TLS connection.
$DB['ENCRYPTION']               = false;
$DB['KEY_FILE']                 = '';
$DB['CERT_FILE']                = '';
$DB['CA_FILE']                  = '';
$DB['VERIFY_HOST']              = false;
$DB['CIPHER_LIST']              = '';

// Use IEEE754 compatible value range for 64-bit Numeric (float) history values.
"/etc/zabbix/web/zabbix.conf.php" 47L, 1484C

///////zabix.conf.php starts here

// Use IEEE754 compatible value range for 64-bit Numeric (float) history values.
// This option is enabled by default for new Zabbix installations.
// For upgraded installations, please read database upgrade notes before enabling this$
$DB['DOUBLE_IEEE754']   = true;

$ZBX_SERVER                             = 'localhost';
$ZBX_SERVER_PORT                = '10051';
$ZBX_SERVER_NAME                = '';

$IMAGE_FORMAT_DEFAULT   = IMAGE_FORMAT_PNG;

// Uncomment this block only if you are using Elasticsearch.
// Elasticsearch url (can be string if same url is used for all types).
//$HISTORY['url'] = [
// 'uint' => 'http://localhost:9200',
// 'text' => 'http://localhost:9200'
//];

I also noticed this little message in firewall status:
firewalld.service - firewalld - dynamic firewall daemon
   Loaded: loaded (/usr/lib/systemd/system/firewalld.service; enabled; vendor preset: enabled)
   Active: active (running) since Mon 2021-11-22 13:14:25 EST; 2h 5min ago
     Docs: man:firewalld(1)
 Main PID: 767 (firewalld)
    Tasks: 2
   CGroup: /system.slice/firewalld.service

it seems like there is just so much going on in my server and I do not know where to edit it. Can anyone give me some help on finding a guide compatible with CentOS Linux release 7.9,2009 (core)

A: If you've gotten to the end the Download and install Zabbix instructions and the services aren't running, it seems worth it to try the "Start Zabbix server and agent processes" commands:
systemctl restart zabbix-server zabbix-agent httpd php-fpm
systemctl enable zabbix-server zabbix-agent httpd php-fpm

A: Make sure your zabbix server process is running : ps -ef | grep -i zabb from your zabbix-server console (process = zabbix_server).
Also make sure you have zabbix-agent running on that very same server (process = zabbix_agentd).


text:
Q: "in English language" vs. "in the English language" vs. "in English" Which of the sentences below are correct, and why?
Which one would you prefer to use, and where are you from?

*

*"The course materials are only available in English language."

*"The course materials are only available in the English language."

*"The course materials are only available in English."

Thanks!

A: I would use the third option.
In the first option, the use of 'English' appears like a modifier of the noun 'language' and doesn't flow right.
The second is correctly formed and acceptable and the third is just a shortening of it.
I'm from the Midlands, United Kingdom.


text:
Q: How to detect Visual C++ 2013 redistributable package How can I detect when "Visual C++ 2013 redistributable" is installed?
The following c++ code detects the 2010 redist correctly:
    // Visual C++ 2010 Redist detection...
    INSTALLSTATE state = pMsiProc( _T("{F0C3E5D1-1ADE-321E-8167-68EF0DE699A5}") );
    if(state == INSTALLSTATE_DEFAULT)
    {
        // Visual C++ 2010 redist installed.
    }

I was hoping to use the same sort of code for 2013 redist, but the INSTALLSTATE always returns INSTALLSTATE_DEFAULT whether the package is installed or not.  Anyone know why?
    // call MsiQueryProductStateW...
    INSTALLSTATE state = pMsiProc(_T("{13A4EE12-23EA-3371-91EEEFB36DDFFF3E}"));
    //
    if ((state == INSTALLSTATE_DEFAULT || state == INSTALLSTATE_LOCAL)
    {
        // 2013 redist is installed.
    }

A: Are you on a x86 architecture? If not, the code is different: https://allthingsconfigmgr.wordpress.com/2013/12/17/visual-c-redistributables-made-simple/

A: As an alternative, you can enumerate the registry looking at the "Displayname" key for the following tokens: 'Microsoft', 'Visual', 'C++', 'Redistributable'.  You can use the following to determine if the sub-key is what you're after...
//  search for valid tokens to indicate this is a redistributable.
resToken = name.Tokenize (_T(" "), curPos);
while (resToken != _T(""))
    {
    if (resToken == _T("Microsoft"))
        tokenCount |= 0x01;
    if (resToken == _T("Visual"))
        tokenCount |= 0x02;
    if (resToken == _T("C++"))
        tokenCount |= 0x04;
    if (resToken == _T("Redistributable"))
        tokenCount |= 0x08;
    resToken = name.Tokenize (_T(" "), curPos);
    }

//  check for matching tokens in the Display Name.
if (tokenCount == 0x0f)
    {

Simply start your search at "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall" and enumerate all of the sub-keys for the above values.  You would also need to check both the 32 and 64 bit hives.


text:
Q: RegEx for text field for names - no numbers allowed and cannot be left as blank I am working on validation using RegEx for a text field for names. I am using the RegEx below but it is not working:
^[a-zA-Z,'.\-\s]*$

and also this:
(?! $)[a-zA-Z ]

Please help, thanks!

A: This should work: ^[^\d]+$. It means that it will look into the string and it will match it if the string is made up from at least one, non digit character.
Edit:
As per @nhahtdh's comment, the regex above will allow anything which is not a digit. You could use something like so: ^[A-Za-z.-]+(\s*[A-Za-z.-]+)*$. This will allow only strings which have spaces between them. This will stop the user from providing a field full of white spaces but it will work should the user provided something like so: Hey there. My name is - foo bar. The one you have: ^[a-zA-Z,'.\-\s]*$ with a minor adjustment of ^[a-zA-Z,'.\-\s]+$ will allow the user to provide white space fields.

A: I guess this is what you want
^(?!\s+$)[a-zA-Z,'. -]+$
  -------
     |->checks if the whole string is blank.if so it won't match

A: I am using this one for names, as names don't contain special characters in my case, its at least one character and any number of intermediate spaces
[a-zA-Z]+[ a-zA-Z]*


text:
Q: React Native ScrollView and controlling the with and height of items in it I am trying to display a list of Items in a Scroll View horizontally.
When I put my Items in regular View they are stretched across the screen nicely and once I switch the parent Container from View to ScrollView with horizontal flag I see all the items with ScrollView. However all the items are displayed/stretched really wide. I tried adding maxWdith for each of the items and it is not honouring that property at all.
Here is the code I have
export default class PostsContainer extends React.Component {

    render() {
        return (
            <ScrollView horizontal style={styles.scrollView}>
                <View style={styles.postsContainer}>

                        <PostContainer />
                        <PostContainer />
                        <PostContainer />

                </View>
            </ScrollView>
        );
    }

}

    export default class PostContainer extends React.Component {

    render() {
       return (
          <View style={styles.postContainer}>
                {this.renderPostImage}
                <View style={styles.postTextContentContainer}>
                    <View style={styles.postTextComment}>
                        <View style={styles.postHeadingContainer}>
                            <Text style={{ fontWeight: 'bold', color: '#567' }}> The standard Lorem Ipsum passage</Text>
                        </View>
                        <ScrollView style={styles.postDescription}>
                            <Text style={{ flex: 4, justifyContent: 'flex-start' }}> Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores
                            </Text>
                        </ScrollView>
                    </View>
                    <FontAwesomeIcon
                        style={styles.profileImage}
                        size={40}
                        name="user-o"
                    />
                </View>
            </View>
      );
  }

  renderPostImage() {
            if (this.props.imageSrc) {
                return (
                    <View>
                        <Image src={this.ptops.imageSrc} />
                    </View>
                );
            } else {
                return null;
            }
        }

and here are the Styles that I'm using:
postsContainer: {
    flex: 5,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'flex-start',
    marginLeft: 10,
    marginRight: 10,
    marginBottom: 5,
    //borderWidth: 1
},
scrollView: {
    //flex: 5,
    //backgroundColor: '#6A85B1',
    height: 400,
},
postContainer: {
    flex: 1,
    flexDirection: 'column',
    justifyContent: 'space-around',
    alignItems: 'flex-start',
    borderWidth: 1,
    marginLeft: 5,
    marginRight: 5,
    //maxHeight: 200,
    //maxWidth: 200,
},
postImageContainer: {
    flex: 1,
    flexDirection: 'row',
},
postImage: {
    flex: 1
},
postTextContentContainer: {
    flex: 1,
    flexDirection: 'row',
    justifyContent: 'flex-start',
    alignItems: 'center',
    //borderWidth: 1,
},
postTextComment: {
    flex: 2,
    justifyContent: 'flex-start',
    alignItems: 'center'
},
profileImage: {
    flex: 1,
    paddingLeft: 10,
},
postHeadingContainer: {
    flex: 1,
    flexDirection: 'row',
    marginTop: 10,
    justifyContent: 'center',
    alignItems: 'flex-start',
    //marginTop: 5,
    marginLeft: 5,
    //alignSelf: 'center',
},
postDescription: {
    flex: 4,
    marginTop: 2,
    marginLeft: 5,
    borderWidth: 1,
}

A: I am able to resolve it by changing the style from
justifyContent: 'space-around' to 'flex-start'


text:
Q: PowerShell Reflection: Define a MIME type or subtype as a script's output type It's possible in PowerShell to define an output type on scripts. Consider myScript.ps1:
[OutputType([String])]
param(
    [string]$name
)

The following returns String:
(Get-Command .\myScript.ps1).OutputType.Name

But I would like to specify that a script returns text/json or text/xml. What would be a good way of doing that?
Inventing types for OutputType (e.g. [String.JSON]) does not work.

A: There are two independent, but complementary mechanisms for declaring output types:
Important: Both ways of declaring output types are informative only and aren't enforced by PowerShell at runtime (but the [OutputType] information is used for tab-completion).

*

*Mechanism A: Using the [OutputType] attribute above the param() declaration in a script or function, as in the question:

*

*Always use this mechanism, and, if necessary, supplement with mechanism B.

*Only recognizes full type names of .NET types or the name of PowerShell type accelerators and no up-front validation is performed, but if an unrecognized type is encountered at invocation time:

*

*if originally specified as a string (e.g., 'System.Text.Encoding'): it is quietly ignored.

*if originally specified as a type literal (e.g., [System.Text.Encoding]): the function call breaks on invocation

*This strict, type-based integration enables tab completion / IntelliSense (command line / Visual Studio Code)

*As for when you may want to use mechanism B too:

*

*If the .NET type names don't tell the full story, as in the question.

*If a function outputs multiple types and you want to verbally describe what types are output when.

*[Supplemental] Mechanism B: Using the .OUTPUTS section of comment-based help:

*

*Accepts free-form descriptions; while referencing actual type names makes sense, doing so is not enforced.

*While you can use this mechanism alone, doing so forgoes the advantages of tab completion and IntelliSense.

*Therefore, use it to supplement mechanism A, if needed, but note that:

*

*If both mechanisms are used, Get-Help only shows the mechanism B definitions.

*Since the two mechanisms are independent, you must manually ensure that the free-form information specified is complete and consistent with the mechanism A declarations.
To examine the output-type information with human eyeballs, use (Get-Help <cmd>).returnvalues (caveat: requires help to be defined, such as via comment-based help) or read the OUTPUTS section of the output from Get-Help -Full <cmd>.
This will either show the free-form .OUTPUTS content or, in its absence, the full type names of the [OutputType[]]-declared types.
For programmatic access, use (Get-Command <cmd>).OutputType, which returns [System.Management.Automation.PSTypeName] instances whose .Type property contains the actual type.
Details below, starting with the answer to the original question.

Mechanism A: Using OutputType attribute(s) above params():
You may only specify .NET types as arguments to the OutputType attribute, so strings such as text/json or text/xml that reflect MIME types won't work.
If you want string output, you've already chosen the closest approximation of your MIME types in terms of .NET types: [OutputType([String])]
You may specify multiple types in a single [OutputType()] attribute, or you may use individual attributes.
You must use individual attributes if you want to map output types to specific parameter sets (e.g., [OutputType([string], ParameterSetName='NameOnly')]).
As of Windows PowerShell v5.1 / PowerShell Core v6.0.1, however, this information is neither used by tab completion / IntelliSense nor reflected in the output from Get-Help -Full.
Note: For a type to be recognized by the OutputType attribute at invocation time,

*

*use either the full type name (e.g., [System.Text.RegularExpressions.Match] rather than just [Match]) or the name of a PowerShell type accelerator, such as [regex].

*

*When in doubt, type [<fullTypeName>] at the prompt and see if it is recognized as a type; additionally you may choose between specifying the type as a string (e.g., 'System.Text.Encoding') or as a type literal (e.g., (e.g., [System.Text.Encoding]), which has behavioral implications - see below.

*if the specified type isn't present at invocation time, e.g., because  the assembly containing the type hasn't been loaded, the behavior depends on how the output was declared:

*

*if originally specified as a string: it is quietly ignored.

*if originally specified as a type literal: the function call breaks on invocation

Beyond that,

*

*either: simply describe the specific types of strings that your cmdlet outputs in its help text, such as via mechanism B described below,

*or: create custom .NET types whose names reflect the desired conceptual type, and specify them in the OutputType attribute - see below.
As stated, despite its constrained nature, the OutputType attribute is purely informative at runtime - it is, however, used for tab completion and IntelliSense (Visual Studio Code).

Example of using a custom type:
# Define an empty custom type for the sole purpose for being able to use
# it with the OutputType attribute.
# Note: On first call, this may take a second or two, as the code is being
#       compiled.
Add-Type @'
  namespace org.example {
   public class text_json {}
  }
'@

function foo {
  # Reference the custom type defined above; full type name required.
  [OutputType([org.example.text_json])]
  param(
      [string]$name
  )
}

You then get:
PS> (Get-Command foo).OutputType.Name
org.example.text_json

Note that the [System.Management.Automation.PSTypeName] instances that .OutputType outputs are not the same as the [type] instances you get when you inspect a type directly:
The .Name property of [System.Management.Automation.PSTypeName] corresponds to the .FullName property of [type], so you get the full type name if the type is recognized (available in the session); otherwise, it is the name as originally specified.

Mechanism B: Using the .OUTPUTS section in comment-based help:
Conceptual help topic Get-Help about_Comment_Based_Help describes how section .OUTPUTS inside comment-based help for scripts and functions can be used to list and describe output types.
Note: Similarly, the .INPUTS section can be used to describe supported input types, though that is arguably less interesting, given that specifying input types is an integral part of parameter declaration and documentation. By and large, .INPUTS functions analogously to .OUTPUTS, with only differences mentioned below.

An .OUTPUTS section uses the following format suggested by the examples in the help topic, but note that the text is ultimately free-form, and no structure is enforced.
<type-name> <optional-description>

Even though the help topic (as of PSv5) doesn't mention it, it seems that in the event of multiple output types, each should be described in its own .OUTPUTS section.
That said, the free-form format allows you to describe multiple output-type descriptions in a single section.
Example, taking advantage of the free-form format to describe the output in terms of MIME types:
<#
.SYNOPSIS
Does stuff.

.OUTPUTS
text/json. In case of x, returns a JSON [string].

.OUTPUTS
text/xml. In case of y, returns an XML [string].
#>
function foo {
  param()
}

Note that when using Get-Help to view the help as a whole, the (aggregated) .OUTPUTS (and .INPUTS) sections are only shown with Get-Help -Full.
Querying that information programmatically essentially yields the OUTPUTS section from
Get-Help -Full verbatim (with individual .OUTPUTS sections in the source concatenated with an empty line in between, and extra trailing empty lines):
PS> (Get-Help foo).returnvalues

text/json. In case of x, returns a JSON [string].

text/xml. In case of y, returns an XML [string].

To access the descriptions individually, by index:
PS> (Get-Help foo).returnvalues.returnvalue[0].type.name
text/json. In case of x, returns a JSON [string].

However, given the free-form nature of the descriptions and that they're intended for human consumption, this granular access may not be needed.
That said, using this form returns the text without extra whitespace, so (Get-Help foo).returnvalues.returnvalue.type.name can be used to return all text without empty lines.
This works analogously for the .INPUTS sections:
(Get-Help foo).inputTypes.inputType.type.name

A: One neat way is using the PowerShell help comment syntax.
<#
 .Synopsis
  Returns a list of files.

 .Description
  ...

 .Inputs
 text/csv

 .Outputs
 text/json[]

#>

You can access this information from the Get-Help object:
$cmd = Get-Help -Name .\components\FileList.ps1
"Input Type: " + $cmd.inputTypes.inputType[0].type.name
"Output Type: " + $cmd.returnValues.returnValue[0].type.name

Results in:
Input Type: text/csv
Output Type: text/json[]

Also works on standard cmdlets:
(Get-Help Get-Date).returnValues[0].returnValue[0].type.name

Returns:
System.DateTime or System.String


text:
Q: Maven - How to exclude dependencies from generated JAR I have 3 projects that looks like this:

The problem is that the common DB code has a converter class, and I am getting the below error while running the Business logic.
Caused by: org.hibernate.AssertionFailure: AttributeConverter class [class com.td.sba.iep.jpa.converters.ModeltoDBAttributeConverter] registered multiple times

What I did:
I tried to exclude the dependencies while packaging the Utility classes using the below code in pom.xml.
            <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <!-- Fools the plugin into creating the code only jar instead of the runnable one -->
            <executions>
                <execution>
                    <goals>
                        <goal>repackage</goal>
                    </goals>
                    <configuration>
                        <classifier>exec</classifier>
                    </configuration>
                </execution>
            </executions>
        </plugin>

But when I include the exec jar created into the Business logic, it shows that the utility classes are not found.
WHAT I NEED:
How do I fix the 'org.hibernate.AssertionFailure'?
Should I exclude the dependencies while creating the jar from utility classes? How do I do it?
Incase it matters, I am using Eclipse.
attaching pom.xml: BusinessLogic

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <!-- Use maven profiles to control Spring Boot profile. -->
    <profiles>
        <profile>
            <id>local</id>
            <activation>
                <activeByDefault>true</activeByDefault>
            </activation>
            <properties>
                <activeProfile>local</activeProfile>
            </properties>
        </profile>
        <profile>
            <id>dev</id>
            <properties>
                <activeProfile>dev</activeProfile>
            </properties>
        </profile>
    </profiles>
    <groupId>com.usermanagement</groupId>
    <artifactId>BusinessLogicClass</artifactId>

    <version>0.0.1-SNAPSHOT</version>

    <packaging>jar</packaging>

    <name>Business Logic</name>
    <description>Business Logic to handle user requests</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
        <org.mapstruct.version>1.2.0.Final</org.mapstruct.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-bean-validators</artifactId>
            <version>2.9.2</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.uuid</groupId>
            <artifactId>java-uuid-generator</artifactId>
            <version>3.1.4</version>
        </dependency>
        <dependency>
            <groupId>org.mapstruct</groupId>
            <artifactId>mapstruct-jdk8</artifactId>
            <version>1.2.0.Final</version>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jsr310</artifactId>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.datatype</groupId>
            <artifactId>jackson-datatype-jdk8</artifactId>
        </dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-orm</artifactId>
    <version>5.0.8.RELEASE</version>
</dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
        </dependency>
        <dependency>
            <groupId>org.javers</groupId>
            <artifactId>javers-core</artifactId>
            <version>3.11.4</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <scope>test</scope>
        </dependency>
  <dependency>
            <groupId>com.usermanagement</groupId>
            <artifactId>CommonDBLogic</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
  <dependency>
            <groupId>com.usermanagement</groupId>
            <artifactId>UtilityClasses</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${java.version}</source> <!-- or higher, depending on your project -->
                    <target>${java.version}</target> <!-- or higher, depending on your project -->
                    <annotationProcessorPaths>
                        <path>
                            <groupId>org.mapstruct</groupId>
                            <artifactId>mapstruct-processor</artifactId>
                            <version>${org.mapstruct.version}</version>
                        </path>
                    </annotationProcessorPaths>
                    <compilerArgs>
                        <compilerArg>
                            -Amapstruct.defaultComponentModel=spring
                        </compilerArg>
                    </compilerArgs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

    <distributionManagement>
    </distributionManagement>

</project>

Utility Class:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
 <properties>
  <java.version>1.8</java.version>
 </properties>
 <groupId>com.usermanagement</groupId>
 <artifactId>UtilityClasses</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <name>UtilityClasses</name>
 <description>Utility Classes used by Business Logic class</description>
 <dependencies>
  <dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.8.2</version>
   <scope>test</scope>
  </dependency>
    <dependency>
     <groupId>net.objectlab.kit</groupId>
     <artifactId>datecalc-common</artifactId>
     <version>1.4.0</version>
     </dependency>
     <dependency>
     <groupId>net.objectlab.kit</groupId>
     <artifactId>datecalc-jdk8</artifactId>
     <version>1.4.0</version>
     </dependency>
  <dependency>
            <groupId>org.javers</groupId>
            <artifactId>javers-core</artifactId>
            <version>3.11.4</version>
        </dependency>
  <dependency>
            <groupId>com.usermanagement</groupId>
            <artifactId>CommonDBLogic</artifactId>
            <version>0.0.1-SNAPSHOT</version>
        </dependency>
 </dependencies>
 <build>
  <plugins>
   <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
     <source>1.8</source>
     <target>1.8</target>
    </configuration>
   </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-shade-plugin</artifactId>
        <version>1.6</version>
        <executions>
          <execution>
            <phase>package</phase>
            <goals>
              <goal>shade</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <!-- Fools the plugin into creating the code only jar instead of the runnable one -->
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                        <configuration>
                            <classifier>exec</classifier>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
  </plugins>
 </build>
</project>

Common DB Logic:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.usermanagement</groupId>
    <artifactId>CommonDBLogic</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>CommonDBLogic</name>
    <description>Common DB Logic used by Business class</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
            <version>2.0.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
            <version>2.0.3.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-envers</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <version>2.0.2.RELEASE</version>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.h2database</groupId>
            <artifactId>h2</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <!-- Fools the plugin into creating the code only jar instead of the runnable one -->
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                        <configuration>
                            <classifier>exec</classifier>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </build>

    <distributionManagement>
    </distributionManagement>

</project>

A: Have you tried to use <exclusions> element on this project dependencies? Like:
Business Logic Project pom.xml file:
    <dependency>
        <groupId>com.utility.project</groupId>
        <artifactId>UtilityProject</artifactId>
        <version>1.0.0</version>
        <exclusions>
            <exclusion>
                <groupId>group.id.jar.you.want.to.exclude</groupId>
                <artifactId>artifact.id.jar.you.want.to.exclude</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

UPDATE
Since you already have CommonDB dependencies on your UtilityProject pom, remove this CommonDB dependency from your business logic pom. This error is because you have 2 classes (same class) being registered with same name. If you already have CommonDB dependency on UtilityProject and you use this UtilityProject as dependency on Business, you don't need to import it twice.


text:
Q: Which server configuration should I buy? I'm buying a poweredge T310
Intel® Xeon® X3430, 2.4 GHz, 8M Cache, Turbo,
for memory should I get:
8GB Memory (4x2GB), 1333MHz, Dual Ranked RDIMM
or
16GB Memory (4x4GB), 800MHz, Quad Ranked RDIMM
How would the memory bus speed play a role in this configuration?

A: I cannot urge you more strongly - GET THE X3440 FOR THE EXTRA £40/$WHATEVER!!! - the X3430 is the only bin of that chip that has hyperthreading switched off - it's really worth the extra.
Now your question - get neither the 8GB nor the 16GB options - go for the 12GB - Nehalem's are optimised for blocks of 3 memory modules at a time (i.e 3 x 4GB). This configuration will benefit you way more that actual chip speed.


text:
Q: Is it safe to memset the plain struct with user-defined default constructor? I know that if a C++ struct is Plain Old Data ("POD") then this guarantees there is no magic in its memory structure, so it means a memcpy to an array of bytes and memcpy back is safe.
I also know that in the standard a POD struct should not have user-defined constructor. In the project I own now, there are some plain structs (with only data fields) with a default constructor defined which initializies the data members to 0. I saw other clients would use memset(&obj, 0, sizeof obj); before using the struct.
Is it ok or safe to memset the non-POD struct before I use it?

A: Having a constructor does not make a struct non-POD.

An aggregate class is called a POD if it has no user-defined copy-assignment operator and destructor and none of its nonstatic members is a non-POD class, array of non-POD, or a reference.

Given that, it is perfectly safe to call
memset(&obj, 0, sizeof obj);

on an object of a struct that has a constructor as long as it is a POD.
Whether it is OK or not, depends. If the default constructor of the struct wants a member to be initialized to 1 for sane behavior, the above call to memset may impact the behavior of code that depends on 1 being the default value.
Take the example of the following struct:
struct Direction
{
   Direction() : x(1.0), y(0.0), z(0.0) {}
   double x;
   double y;
   double z;
};

An object of type Direction expects that at least of one of the components will be non-zero. You can't define a direction when all the components are zero. If you use memset to set everything to 0, code will likely break.
EDIT
It appears, from the comments below, as though the definition of a POD has changed from C++03 to C++11.
Using memset(&obj, 0, sizeof obj); may not be safe after all.

A: IMO this depends on the use case. I have seen memset used to set the data with white space character on few mainframe appications i.e
memset(&obj, ' ', sizeof(obj));

In case the struct defines a const variable and initializes the value, memset would override such value. So it depends and most cases safe to use memset to initialize for PODS. thats my 2 cents.


text:
Q: Html5 Video. After 20 secs of pause reset player So im working on a school project for a museum, we are making an info screen with a video to play for the visitors, ill like to make a function so that if one visitor is pausing the video and leave it will reset after 20 sec or so. So the next visitor dont have to reset the video by him self.
Any easy way to do that?
I just use the standard html5 video player and controls.

A: http://blog.teamtreehouse.com/building-custom-controls-for-html5-videos
it might help
probably you need to write your required code within
  if (video.paused == true)
    {

    //find out code to find whether its been paused for 20 second.....may be use some timer control to get this

    if(20secPaused)
    {
     video.currentTime = time;
    }

hope it helps :)

A: I got help on a danish forum
a guy made an example i could modify for my own project it worked for me
the solution:
http://netkoder.dk/test/test0221.html


text:
Q: Average distance to a non-central point in a circle If I pick a point within the circle about the origin of radius $R$, say $(r,\theta) = (0.5 R, \frac{\pi}{2})$, what is the average distance of all other points to that point?
Things which are interesting but not quite what I want:

*

*The average distance from the centre of a circle to any point within it is $\frac{2}{3}$ of the radius.

*If two random points are picked, the average distance is $\dfrac{128 R}{45\pi}$ (http://mathworld.wolfram.com/DiskLinePicking.html)

A: OK, I think the answer must be given by:
$$
\int_{0}^{2\pi}\int_{0}^{R}r\sqrt{a^2+r^2-2ar\cos{\theta}} dr d{\theta}
$$
Where $a$ is the distance of the point from the center, $R$ is the radius of the disc. Wolfram Alfa won't work this out and I haven't the inclination (or maybe ability) to do it myself.
I have done it numerically though, and the result is shown below (where $R=100$). As you can see when $a=0$, we get 66.66 ($\frac{2R}{3}$) as expected.
Within this range it is well approximated with a quadratic.


text:
Q: How can I float a div element to the bottom of the screen with CSS? I am making a website with different sections, one at the bottom of the screen. I first tried putting the div element inside of a footer element. This didn't work. The div was still at the top of the screen. I was out of ideas, so I searched for a solution on Google. Nothing I tried worked. How can I do this?

A: If you want it to always be at the bottom of the screen (IE: touching bottom of monitor) you can use
.myElementClass{
    position: absolute;
    bottom: 0;
}

Just make sure that it's not inside anything declared with position: relative or it will be stuck at the bottom of that element.
If you want it to be at the bottom of the wrapper element, use
.myWrapperClass{
    position: absolute;
}

and put the .myElementClass element inside the .myWrapperClass element

A: If you need your footer to be seen always on the screen or like this at the end of the page, here is the answer. The explanation is same as zachThePerson's.

.main {
    position: relative;
    height: 700px;
    width: 100%;
    background: blue;
}

.box {
    position: absolute;
    bottom: 0px;
    width: 100%;
}

.box1 {
    width: 100px;
    height: 100px;
    background: red;
    float: right;
}
<!DOCTYPE html>

The float Property

In this example, the image will float to the right in the text.

A: You could use Flexbox, and the below solution could be useful.
You can put the main content of your page in the div with class main-content, and with the Flexbox settings below, the footer will always be pushed to the bottom.
HTML:

Just a random div with some content

Div to be on the bottom of the page

CSS:
.flexbox-container {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

The above code won't change the height of the flexbox-container div, though. So you may want to add something like this:
.flexbox-container {
  ...
  height: 100vh;
}

A good page with explanation for the Flexbox being used is A Complete Guide to Flexbox.


text:
Q: Google Chrome not selected when ran using RF and Selenium Im running my tests using Robot Framework 2.7 and Selenium 2.18. I need to run the scripts that I have in 3 different browsers (FF9,IE8, Google Chrome). I noticed that when running my scripts in Google Chrome, upon execution the main window is not selected and causing my
tests to fail. I've tried using Select Window and Execute Javascript window.focus() keywords but it seems not to select the google chrome browser.
Any suggestions?
Note:For FF9 and IE8, upon running the main window is always selected.
Thanks!

A: I don't think this should be a problem , make sure you don't have any Google chrome windows open while running the tests, other than this there shouldn't be anything wrong ... I am running robot tests, the tests for FF are almost always compatible with tests on chrome

A: If the window you are trying to select is the last opened window then try
Select Window   new
When we give argument as new it selects the latest opened browser window.
Make sure you are using robot to launch the browser as selenium will attach to a browser not opened by it.


text:
Q: How can I replace node-cron with a command line script in a node.js application I would like to change the implementation shown below to using a command line script in a node.js application. How do I do it?
var cron = require('node-cron');

cron.schedule('* * * * *', () => {
  getBananas();
});


text:
Q: How to indent multiple lines at once in Pycharm Is there any way to indent multiple lines in Pycharm? I tried highlighting multiple lines and pressing tab and ctrl+shift+i, but none of them seems to work.
P.S. Shift-tabbing works for me

A: Move your cursor to above or below those lines. Use shift with up or down arrow to select lines. When you are done, press Tab

A: You can try CTR + Alt + L, and the whole script will be indented automatically!


text:
Q: DLL not loaded by junit test executed from ant My junit test class uses a dll to connect to the database. When I run the test from eclipse, it works fine, but when I use ant to run the test, I got this:

Testsuite: ......BatchAlertTest Tests run: 1, Failures: 1, Errors: 0,
  Skipped: 0, Time elapsed: 0,064 sec
Testcase: testAddAlert took 0,002 sec     FAILED
  com.microsoft.sqlserver.jdbc.SQLServerDriver
  junit.framework.AssertionFailedError:
  com.microsoft.sqlserver.jdbc.SQLServerDriver  at
  ......BatchAlertTest.createDatabaseConnection(BatchAlertTest.java:44)
    at ......BatchAlertTest.setUp(BatchAlertTest.java:32)

This is the ant target in my build.xml:
<target name="run-persister-junit">
    <mkdir dir="testReports"/>

    <junit printsummary="yes" haltonfailure="yes">

        <classpath>
            <pathelement location="java/lib/JUnit/junit-4.12.jar"/>
            <pathelement location="java/lib/JUnit/hamcrest-core-1.3.jar"/>
            <pathelement location="java/bin"/>

        </classpath>

        <formatter type="plain"/>
        <formatter type="xml"/>

        <batchtest fork="yes" todir="testReports">
            <fileset dir="java/bin">
                <include name="/**/*Test.class"/>
            </fileset>
        </batchtest>

    </junit>

</target>

To avoid problems about the inclusion of the dll, I included it in the PATH environment variable. Is there anything I am missing in the target to complete the execution of the test?
Thanks in advance.

A: Finally the issue was that I was missing the .jar from which the java operations are taken from (sqljdbc42.jar). Including it in the classpath solved the issue.


text:
Q: How to create a functions py and call those functions? I am practicing with Python using Pyramid framework.
I created a py, myfuncs.py, in my main package folder where there is also a Views folder with views.py inside and Models folder (models inside) along with other folders for static files and templates (as created by Pyramid scaffolding).
I want to define functions and classes within the myfuncs.py located at the myproject package root and then access them from within any of the views and models located in their respective views and models folder.
How can I achieve this? I try importing but it won't work.

A: imagine this structures of folders and files:
MyFuncs (folder)
    __init__.py (can be completely empty)
    utilFunctions.py
    genericFunctions.py
    uselessFunctions.py
    Views (folder)
        __init__.py (again!!)
        views.py

Now you can "import" the folders (in reality you import  __ init __.py using the folder name, but this is for now a detail)
Be sure to have the PYTHONPATH properly set.
for example:
import MyFuncs.utilFunctions
from MyFuncs.Views import views
import MyFuncs.uselessFunctions as nonsenseFunctions

etc.etc.
That __ init __.py must be in any folder you wish to import
Within views.py you simply do:
from MyFuncs import utilFunctions

utilFunctions.aFunctionYouCode()

A: You need to have an __init__.py in the root folder, and import it with:
import functions

Then you should be able to call the functions with functions.<functionname>()


text:
Q: take the substring out of string in salesforce I am creating the HTML template in Salesforce and below is the value I am fetching from one field that is building address. However, I just need the building number from the entire address. Below is the scenario.
"Václavské náměstí 785/28, P1 - Alfa Building", this is the text and I want to extract the only the number i.e 785/28. But the thing is the numbers before and after the '/' varies it can be more than 3 or 2 digits. Trim Left and Right work but can't seem to specify the values dynamically.
Thanks

A: Please find the code for your above concern. It is in javascript only.
        <script>
        function myFunction() {
          var str = "sdfdfv123456/789xvxcv";  // pass your string over here
        var revstr = reverseString(str);
         var firstDigit = str.match(/\d/)
        var lastDigit = revstr.match(/\d/)
        var findex = str.indexOf(firstDigit);
        var lindex =  str.length - revstr.indexOf(lastDigit);
        function reverseString(str) {
          if (str === "")
            return "";
          else
            return reverseString(str.substr(1)) + str.charAt(0);
        }
        var sub_string = str.substring (findex, lindex);
          alert(sub_string) ;
        }
        </script>

If any confusion please let me know.


text:
Q: What kind of information can I extract from vector equations? I just want to know if what I know about vector equations is true, and if there is more.
Let's say I have the following vector equations.
$\left[\begin{array}{c} x \\ y \\ z \end{array}\right]$
$= \left[\begin{array}{c} a \\ b \\ c \end{array}\right]$
$+ t\left[\begin{array}{c} d \\ e \\ f \end{array}\right]$
and $\left[\begin{array}{c} x_2 \\ y_2 \\ z_2 \end{array}\right]$
$= \left[\begin{array}{c} a_2 \\ b_2 \\ c_2 \end{array}\right]$
$+ t\left[\begin{array}{c} d_2 \\ e_2 \\ f_2 \end{array}\right]$
If I let $t = 1$, $\left[\begin{array}{c} d \\ e \\ f \end{array}\right]$ is a direction vector
$\left[\begin{array}{c} a \\ b \\ c \end{array}\right]$ is a point on the line, but since it starts from the origin, is also a vector
Changing different values of $t$ give me different points on the line by solving for $x, y, z$
The two vectors form a plane, so if I cross product, $\left[\begin{array}{c} a \\ b \\ c \end{array}\right]$ $\times$ $\left[\begin{array}{c} a_2 \\ b_2 \\ c_2 \end{array}\right]$, I get the normal to the plane.
Once I have the normal to the plane, I use it, along with one known point and one unknown point to find a scalar equation.
$\quad\quad(bc_2-cb_2)(x-a) + (ca_2-ac_2)(x-b) + (ab_2-ba_2)(x-c) = 0$
If I drew out a vector equation, it appears to form a plane on its own. Does that mean a vector equation of a line is also a vector equation of a plane? If not, can I cross $\left[\begin{array}{c} a \\ b \\ c \end{array}\right]$  with $t\left[\begin{array}{c} d \\ e \\ f \end{array}\right]$ to get the normal, then do the above again?