text:
Q: How to structure a feed and follow system? I was using Firebase realtime database for my social network app were you can follow and receive posts of people you follow.
My database :
Users
--USER_ID_1
----name
----email
--USER_ID_2
----name
----email

Posts
--POST_ID_1
----image
----userid
----date
--POST_ID_2
----image
----userid
----date

Timeline
--User_ID_1
----POST_ID_2
------date
----POST_ID_1
------date

Another node "Content" contained id of the all the user posts. If "A" followed "B" then all post id's of B where added to A's timeline. And if B posted something it's also added to all of its follower's timelines.
It has scalability issues :

*

*If someone has 10,000 followers a new post was added to all 10,000 follower's timelines.

*If someone has a large amount of posts then every new follower receives all of those in his timeline.

I want to change to Firestore as it's been claimed scalable. How should I structure my database so these problems in realtime database are eliminated in Firestore?

A: I've seen your question a little later but I will also try to provide you the best database structure I can think of. So hope you'll find this answer useful.
I'm thinking of a schema that has there three top-level collections for users, users that a user is following and posts:
Firestore-root
   |
   --- users (collection)
   |     |
   |     --- uid (documents)
   |          |
   |          --- name: "User Name"
   |          |
   |          --- email: "email@email.com"
   |
   --- following (collection)
   |      |
   |      --- uid (document)
   |           |
   |           --- userFollowing (collection)
   |                 |
   |                 --- uid (documents)
   |                 |
   |                 --- uid (documents)
   |
   --- posts (collection)
         |
         --- uid (documents)
              |
              --- userPosts (collection)
                    |
                    --- postId (documents)
                    |     |
                    |     --- title: "Post Title"
                    |     |
                    |     --- date: September 03, 2018 at 6:16:58 PM UTC+3
                    |
                    --- postId (documents)
                          |
                          --- title: "Post Title"
                          |
                          --- date: September 03, 2018 at 6:16:58 PM UTC+3

if someone have 10,000 followers than a new post was added to all of the 10,000 follower's Timeline.

That will be no problem at all because this is the reason the collections are ment in Firestore. According to the official documentation of modeling a Cloud Firestore database:

Cloud Firestore is optimized for storing large collections of small documents.

This is the reason I have added userFollowing as a collection and not as a simple object/map that can hold other objects. Remember, the maximum size of a document according to the official documentation regarding limits and quota is 1 MiB (1,048,576 bytes). In the case of collection, there is no limitation regarding the number of documents beneath a collection. In fact, for this kind of structure is Firestore optimized for.
So having those 10,000 followers in this manner, will work perfectly fine. Furthermore, you can query the database in such a manner that will be no need to copy anything anywhere.
As you can see, the database is pretty much denormalized allowing you to query it very simple. Let's take some example but before let's create a connection to the database and get the uid of the user using the following lines of code:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();

If you want to query the database to get all the users a user is following, you can use a get() call on the following reference:
CollectionReference userFollowingRef = rootRef.collection("following/" + uid + "/userFollowing");

So in this way, you can get all user objects a user is following. Having their uid's you can simply get all their posts.
Let's say you want to get on your timeline the latest three posts of every user. The key for solving this problem, when using very large data sets is to load the data in smaller chunks. I have explained in my answer from this post a recommended way in which you can paginate queries by combining query cursors with the limit() method. I also recommend you take a look at this video for a better understanding. So to get the latest three posts of every user, you should consider using this solution. So first you need to get the first 15 user objects that you are following and then based on their uid, to get their latest three posts. To get the latest three posts of a single user, please use the following query:
Query query = rootRef.collection("posts/" + uid + "/userPosts").orderBy("date", Query.Direction.DESCENDING)).limit(3);

As you are scrolling down, load other 15 user objects and get their latest three posts and so on. Beside the date you can also add other properties to your post object, like the number of likes, comments, shares and so on.

If someone have large amount of posts than every new follower received all of those posts in his Timeline.

No way. There is no need to do something like this. I have already explained above why.
Edit May 20, 2019:
Another solution to optimize the operation in which the user should see all the recent posts of everyone he follow, is to store the posts that the user should see in a document for that user.
So if we take an example, let's say facebook, you'll need to have a document containing the facebook feed for each user. However, if there is too much data that a single document can hold (1 Mib), you need to put that data in a collection, as explained above.

A: I've been struggling bit with the suggested solutions her, mostly due to a technical gap, so i figured another solution that works for me.
For every user I have a document with all the accounts that they follow, but also all a list of all the accounts that follow that user.
When the app starts, I get a hold of the list of accounts that follow this current user, and when a user makes a post, part of the post object is the array of all the users that follow them.
When user B wants too get all the posts of the people they are following, i just ad to the query a simple whereArrayContains("followers", currentUser.uid).
I like this approach because it still allows me to order the results by any other parameters I want.
Based on:

*

*1mb per document, which by a google search I've made seems to hold 1,048,576 chaarecters.

*The fact that Firestore generated UIDs seem to be around 28 characters long.

*The rest of the info in the object doesn't take too much size.

This approach should work for users that have up to approx 37,000 followers.

A: There have two situations

*

*Users in your app have a small number of followers.

*Users in your app have a large number of followers. If we are going to store whole followers in a single array in a single document in firestore. Then it will hit the firestore limit of 1 MiB per document.

*

*In the first situation, each user must keep a document which stores the followers' list in a single document in a single array. By using arrayUnion() and arrayRemove() it is possible to efficiently manage followers list. And when you are going to post something in your timeline you must add the list of followers in post document.
And use query given below to fetch posts
postCollectionRef.whereArrayContains("followers", userUid).orderBy("date");

*In the second situation, you just need to break user following document based on the size or count of followers array. After reaching the size of the array into a fixed size the next follower's id must add into the next document. And the first document must keep the field "hasNext", which stores a boolean value.
When adding a new post you must duplicate post document and each document consist of followers list that breaks earlier.
And we can make the same query which is given above to fetch documents.

A: The other answers are going to get very costly if you have any decent amount of activity on your network (e.g. People following 1,000 people, or people making 1,000 posts).
My solution is to add a field to every user document called 'recentPosts', this field will be an array.
Now, whenever a post is made, have a cloud function which detects onWrite(), and updates that poster's recentPosts array on their userDocument to have info about that post added.
So, you might add the following map to the front of the recentPosts array:
{
"postId": xxxxxxxxxxx,
"createdAt": tttttt
}

Limit the recentPosts array to 1,000 objects, deleting the oldest entry when going over limit.
Now, suppose you are following 1,000 users and want to populate your feed... Grab all 1,000 user documents. This will count as 1k reads.
Once you have the 1,000 documents, each document will have an array of recentPosts. Merge all of those arrays on client into one master array and sort by createdAt.
Now you have up to potentially 1 million post's docIDs, all sorted chronologically, for only 1,000 reads. Now as your user scrolls their feed simply query those documents by their docID as needed, presumably 10 at a time or something.
You can now load a feed of X posts from Y followees for Y + X reads.
So 2,000 posts from 100 followees would only be 2,100 reads.
So 1,000 posts from 1,000 followees would only be 2,000 reads.
etc...

Edit 1) further optimization. When loading the userDocuments you can batch them 10 at a time by using the in query ... normally this would make no difference because it's still 10 reads even though it's batched... but you can also filter by a field like recentPostsLastUpdatedAt and check that it's greater than your cached value for that user doc, then any user docs that haven't updated their recentPosts array will not get read. This can save you theoretically 10x on base reads.
Edit 2) You can attach listeners to each userDocument too to get new posts as their recentPosts change without querying every single follower each time you need to refresh your feed. (Although 1,000+ snapshot listeners could be bad practice, I don't know how they work under the hood) (Edit3: Firebase limits a project to only 1k listeners so edit2 wasn't a scalable optimization)

A: I went through some of the the Firebase documentation, and I'm confused as to why the suggested implementation at https://firebase.google.com/docs/database/android/structure-data#fanout wouldn't work in your case. Something like this:
users
--userid(somedude)
---name
---etc
---leaders:
----someotherdude
----someotherotherdude

leaders:
--userid(someotherdude)
---datelastupdated
---followers
----somedude
----thatotherdude
---posts
----postid

posts
--postid
---date
---image
---contentid

postcontent
--contentid
---content

The guide goes on to mention "This is a necessary redundancy for two-way relationships. It allows you to quickly and efficiently fetch Ada's memberships, even when the list of users or groups scales into the millions.", so it doesn't seem that scalability is exclusively a Firestore thing.
Unless I'm missing something the main problem seems to be the existence of the timeline node itself. I get that it makes it easier to generate a view of a particular user's timeline, but that comes at the cost of having to maintain all of those relationships and is significantly delaying your project. Is it too inefficient to use queries to build a timeline on the fly from a structure similar to the above, based on a submitted user?

A: UPDATE: 8/28/21
I created a theoretical scalable solution.  See here.
And some other options here.

My scalable idea is that users may have 1,000,000+ followers, but a REAL user does not follow more than 1000 people. We could simply aggregate their feed (a collection of posts). Here is my theory:
Collections
/users
/users/{userId}/follows
/users/{userId}/feed
/posts

1. Populate the feed
Populate feed needs to run first, and should honestly be in a cloud function. To avoid costs, it will only get new posts to your feed, but not posts older than 10 days (or however old).
populateFeed() - something like this...
numFollowing = get('users/numFollowing');
lastUpdate = get('users/lastUpdate');
tenDaysOld = timestamp 10 days ago

// maybe chunk at 20 here...
for (numFollowing) {
  docs = db.collection('posts')
    .where('userId', '==', userId)
    .where('createdAt', '>', lastUpdate)
    .where('createdAt', '<', tenDaysOld);
  db.collection('users/${userId}/feed').batch.set(docs);

Update users/${userId}/lastUpdate to current timestamp...
This way, you don't get too many documents (only 10 days old for example), and you don't waste reads on docs you already have.
2) Read the feed
A feed will be the aggregated posts.
loadFeed() - call this after populateFeed()
db.collection('/users/${userId}/feed').orderBy('createdAt');

The documents in feed only really need the createdAt date and postId since you can pull the post on the front end, although you could store all data if you don't expect it to change:
postId: {
  createdAt: date
}

Your userDoc will also have:
{
  numFollowing: number,
  lastUpdate: date
}

The app should automatically call loadFeed() on load.  There could be a button that runs populateFeed() as a callable cloud function (the best), or locally. If your feed is a firebase observable, it will update automatically as they populate...
Just a thought... I think there might be some other cleaner ways to solve this problem that scale...
J
UPDATE
The more and more I think about it, I actually do think it is possible to update the field on a posts onWrite to all followers feed.  The only constrain is time, which normally 60s, can be up to 9min. Really, you just need to make sure you bulk update asynchronously.  See my adv-firestore-functions package here:

A: Alright after some thinking about this problem I came up with a theoretical solution (because I didn't test it yet). I will be using Cloud Firestore for this:
My Solution is compromised of two parts :
1. Database Shema design :
Firestore-root
     |
      _ _ users (collection):
               |
                _ _ uid (document):
                       |
                        _ _ name: 'Jack'
                       |
                        _ _ posts (sub-collection):
                                 |
                                  _ _ postId (document)
                       |
                        _ _ feed (sub-collection):
                                |
                                 _ _ postId (document)
                       |
                        _ _ following (sub-collection):
                                     |
                                      _ _ userId (document)
                       |
                        _ _ followers (sub-collection):
                                     |
                                      _ _ userId (document)

1.1 Explanation:
As you can see here, I have created a collection named users representing each user in the database. Each uid document in the users collection has it's own fields like name for example and it's own sub-collections. Each uid document contains it's own created posts in the posts sub-collection, it contains the posts from the people the current user follows in the feed sub-collection. Finally it contains two sub-collections representing the following and followers.
2. Use Cloud Functions:
const functions = require("firebase-functions");

const firebaseAuth = require("firebase/auth");

const admin = require("firebase-admin");

admin.initializeApp();

const firestore = admin.firestore();

const uid = firebaseAuth.getAuth().currentUser.uid;

exports.addToUserFeed =

  functions.firestore.document("/users/{uid}/posts/{postId}").onCreate(async
  (snapshot,context) => {

    const userId = context.params.uid;

    const followers = await firestore.collection('users').doc(userId).collection('followers').where("userId", "==", uid).get();

    const isFollowing = !followers.empty;

    if (isFollowing == true) {

        const docRef =
        firestore.collection('users').doc(uid).collection('feed').doc();

        const data = snapshot.data();

        firestore.runTransaction(transaction => {
           transaction.create(docRef, data);
       });
    }
});

2.1 Explanation:
Here we trigger a cloud function whenever a user creates a post in its sub-collection posts. Since we want to add the posts to the current users feed (feed sub-collection), from the users it is following, we check first whether the current user (which we got its id using firebase auth in form of uid constant) follows the created post author which its id is stored in the wildcard uid (We can access it through context.params.uid). The Checking is done through performing a Query to check if any of the userId documents in the followers sub-collection matches the current user id uid. This returns a QuerySnapshot. Then we check if the QuerySnapshot is empty or not. If it is empty that means that the current user doesn't follow the context.params.uid user. Otherwise it does follow it. If it does follow, then we add the newly created post into the current users feed sub-collection using a transaction.
Alright thats it. I hope this helps anyone. Again I didn't test it yet, so maybe something can not work out, but hopefully it will. Thanks!

A: I think one possibility is to make another top-level collection named "users_following" which contains a document named "user_id" and a field for an array that contains all the users that the user is following. Within that "users_following" document one can have sub-collection of that particular user all posts or a top-level collection will also do the job. The next important thing that comes is that one has to store a recent one post inside "users-following" document as an array or map. Basically this normalized data is going to be used to populate the feed of the person who is following you. But its drawback is that you will only see one post per person even if the person has added two posts recently or even if you store your two to three posts in the normalized way than your all three posts will be shown at once (like three posts of the same user in a row). But it's something still good if you just need to show one post per user.


text:
Q: How to search for more than one string in VB6? I want to search for more than one string in a file  with vb6
using instr we can do it for single string  but I don't know how to use instr for more than one string now how can I search for more than one and if find one of them we receive a message?
Open file For Binary As #1
    strData = Space$(FileLen(file))
    Get #1, , strData
Close #1
lngFind = InStr(1, strData, string)

A: That's simply a case of introducing multiple tests for multiple strings...
Dim strArray(10) As String
DIm cntArray(10) As Integer
Dim strData As String
Dim c As Integer

'Set-up your search strings...
...

Open file For Binary As #1
Get #1, , strData
Close #1

For c = 1 to 10
    cntArray(c) = Instr(strData, strArray(c))
Next c

If all you want to do is show a true or false message box then we don't need to assign the value to the second array.  The For loop could be replaced with...
For c = 1 to 10
    If Instr(strData, strArray(c)) > 0 Then
        MsgBox "'" & strArray(c) & "' found in file."
        'Remove the following line if you want everything to be searched for,
        'but leave it in if you only want the first string found...
        Exit For
    End If
Next c

Really this is a very basic piece of code.  If you're looking to write code as anything but a novice then you need to research the commands, functions and structures included in this post.  A good place to start, for a complete novice, would be somewhere like http://www.thevbprogrammer.com/classic_vbtutorials.asp or http://www.vb6.us/.

A: '-----------------------------------------------------------
'perform multiple instr on a string. returns true if all instr pass
'-----------------------------------------------------------

Function bMultiInstr(sToInspect As String, ParamArray sArrConditions()) As     Boolean
On Error GoTo err:
Dim i As Integer, iUpp As Integer

iUpp = UBound(sArrConditions) 'instr conditions

For i = 0 To iUpp ' loop them
       If InStr(1, sToInspect, sArrConditions(i)) <= 0 Then Exit Function '     if instr returns 0 then exit - [bPasses] will be left false
Next i

bPasses = True

Exit Function
err:
With err
     If .Number <> 0 Then
        'create .bas named [ErrHandler]  see http://vb6.info/h764u
        ErrHandler.ReportError Date & ": Strings.bMultiInstr." & err.Number     & "." & err.Description
        Resume Next
      End If
End With
End Function

That is from http://vb6.info/string/instr-multi-perform-instr-checks-multiple-inst-conditions-function/

redpajama_set_name: RedPajamaStackExchange


text:
Q: do all functions have a "function prologue" that decrements the stack pointer for locals? I have a few basic questions regarding assembly.
when writing a function in assembly, do all functions have a "function prologue"? I'm seeing some functions written online and they don't have it which is confusing me. I would think you always need it for the new base pointer and local variables by decrementing stack?
Also does every push instruction require a subtract instruction for the stackpointer because we always want the stack pointer to be at the top of the stack and if not why? so if
 push %eax
 sub $4, %esp

My last question is, are there any resources out there to explain assembly in laymans terms?

A: Its fairly trivial to make your own example, just need something on the stack in the function (that doesnt optimize away).
unsigned int more_fun ( unsigned int );
void fun_too ( unsigned int *);
void fun ( void )
{
    unsigned int ra;
    unsigned int ray[64];
    for(ra=0;ra<64;ra++) ray[ra]=more_fun(ra);
    fun_too(ray);
}

0000000000000000 <fun>:
   0:   53                      push   %rbx
   1:   31 db                   xor    %ebx,%ebx
   3:   48 81 ec 10 01 00 00    sub    $0x110,%rsp
   a:   64 48 8b 04 25 28 00    mov    %fs:0x28,%rax
  11:   00 00
  13:   48 89 84 24 08 01 00    mov    %rax,0x108(%rsp)
  1a:   00
  1b:   31 c0                   xor    %eax,%eax
  1d:   0f 1f 00                nopl   (%rax)
  20:   89 df                   mov    %ebx,%edi
  22:   e8 00 00 00 00          callq  27 <fun+0x27>
  27:   89 04 9c                mov    %eax,(%rsp,%rbx,4)
  2a:   48 83 c3 01             add    $0x1,%rbx
  2e:   48 83 fb 40             cmp    $0x40,%rbx
  32:   75 ec                   jne    20 <fun+0x20>
  34:   48 89 e7                mov    %rsp,%rdi
  37:   e8 00 00 00 00          callq  3c <fun+0x3c>
  3c:   48 8b 84 24 08 01 00    mov    0x108(%rsp),%rax
  43:   00
  44:   64 48 33 04 25 28 00    xor    %fs:0x28,%rax
  4b:   00 00
  4d:   75 09                   jne    58 <fun+0x58>
  4f:   48 81 c4 10 01 00 00    add    $0x110,%rsp
  56:   5b                      pop    %rbx
  57:   c3                      retq

(it is not linked so the immediate in the call's are zeros so the linker can fill them in)
Instead of subtracting or adding a constant to rsp, you could instead put a long list of pushes and pops as Jester pointed out in the comments.  This is just a waste of code space and execution time, the add and subtract make more sense.
Now one could argue that you could implement this code such that each time through the loop you push the result of more_fun();  Growing the stack only as needed for the function, and using pushes as you desire rather than subtracting from rsp. But on the return you would want to add to rsp in one instruction rather than waste time and space on individual pops or a loop of pops.  This solution is harder to debug as a compiler author, and harder to understand as a user/reader of the compiler output.  (and if you wanted to maintain say a 64 bit alignment on the stack and say an unsigned int here is 32 bits as shown, then you would be burning a handful more instructions just to sort that out)


text:
Q: Two independent sample proportion test This question is pretty simple (I hope). I am working my way through some introductory to SAS material and cannot find the proper way of running a two sample proportion test of location.
proc freq data;
tables / binomial (p=...)
run;

requires a known proportion (i.e. testing against a known value). I'd like to compare two samples of categorical variables with null hypothesis p1 = p2 and p1 < p2.
Data resembles:
V1  Yes
V1  No
V2  Yes
V2  No

For many lines. I need to compare the proportion of Yes's and No's between the two populations (V1 and V2). Can someone point me towards the correct procedure? Google search has left me spinning.
Thanks.

A: 1/0 and 1/0 seems like a Chi Squared test.
data for_test;
do _t = 1 to 20;
 x1 = ifn(ranuni(7)<0.5,1,0);
 x2 = ifn(ranuni(7)<0.5,1,0);
 output;
end;
run;

proc freq data=for_test;
tables x1*x2/chisq;
run;

A: The chi square test for quality of proportion. Here the use case of p1 < p2  is still pending. It is possible to do the test for p1 < p2  using chi


text:
Q: PHP Fastest Pagination I have a MYSQL query that returns around 10,000 rows which is used mainly for reporting.
My current pagination code loads all the rows and then cuts them down to whatever the limit per page is which takes ages to load.
I am also using jquery tablesorter to help users sort the results.
Is there a way not to load all rows and make the page load time quicker?

A: <?php
$start = 130;
$item_per_page = 10;
$sql = "SELECT * FROM whatever LIMIT $start, $item_per_page";

If you want to use tablesorter, there's an AJAX example. Prepare HTML code inside your pagination code, and return only the data piece of page, you can dynamically insert data when necessary.


text:
Q: How to use loop 'find next sibling' until reaching a certain tag when web scraping with beautifulsoup in python? The webpage I'm attempting to scrape has a section where the html tags are nested like so:

My code is able to navigate to the correct  tag but I am struggling to split the text by  as  is a sibling, not a child. I am either able to print just the  tags or print all the text within the  tag without splitting into sections.
I've tried using for loops but I don't think is the right approach if searching within siblings. I think looping an if statement to determine if find_next_sibling().name = 'h3' might work but I've been unable to iterate this without nesting a large number of if statements.
Can anyone please advise on what approach I should take? Please see my full code below - the treaty files section works fine.
from bs4 import BeautifulSoup
import requests

url = 'https://www.gov.uk/government/publications/albania-tax-treaties'
get_url = requests.get(url)
url_html = get_url.content
soup = BeautifulSoup(url_html, 'lxml')

treaty_files = soup.find_all('div', class_='attachment-details')
for treaty_file in treaty_files:
    file_name = treaty_file.h3.a.text
    file_url = treaty_file.h3.a['href']
    #print(f"Treaty Name: {file_name}")
    #print(f"Treaty URL: {file_url}")
    #print()

#Attempt 1
treaty_details = soup.find('div', class_='govspeak').find_all('h3')
for treaty_content in treaty_details:
    content = treaty_content.find_next_siblings()
    for x in content:
        test = x
        a = test
        #print(a)

#Attempt 2
treaty_details = soup.find('div', class_='govspeak').find_all('h3')
for treaty_content in treaty_details:
    content = treaty_content.find_next_sibling()
    while content.name != 'h3':
        print(f"Text: {content.text}")
        content = content.find_next_sibling()
        if content.name == 'h3':
            break

A: One possible solution is to leverage pandas.Series.groupby function to group sections together:
import requests
import pandas as pd
from bs4 import BeautifulSoup

url = "https://www.gov.uk/government/publications/albania-tax-treaties"
soup = BeautifulSoup(requests.get(url).content, "html.parser")

govspeak = soup.select_one(".govspeak")

s = pd.Series(govspeak.find_all(recursive=False))

for _, g in s.groupby(s.apply(lambda x: x.name).eq("h3").cumsum()):
    title = g.iloc[0].text
    text = "\n".join(row.text for row in g.iloc[1:])

    print(title)
    print("-" * 120)
    print(text)
    print()
    print()

Prints:
2021 UK-Albania Synthesised text of the Multilateral Instrument and the 2013 Double Taxation Agreement — in force
------------------------------------------------------------------------------------------------------------------------
The 2013 UK-Albania Double Taxation Agreement has been modified by the Multilateral Instrument (MLI).
The modifications made by the Multilateral Instrument entered into force in:

the UK on 1 October 2018
Albania on 1 January 2021

They are effective in the UK from:

1 January 2021 for taxes withheld at source
1 April 2022 for Corporation Tax
6 April 2022 for Income Tax and Capital Gains Tax

They are effective in Albania from 1 July 2021.

2013 UK-Albania Double Taxation Agreement — in force
------------------------------------------------------------------------------------------------------------------------
The agreement entered into force on 30 December 2013.
It is effective in the UK from:

1 April 2014 for Corporation Tax
6 April 2014 for Income Tax and Capital Gains Tax

It is effective in Albania from 1 January 2014 for Income Tax and Capital Gains Tax.


text:
Q: LENOVO IdeaPad (U430 Touch) only charges up to 59% I just installed Ubuntu 14.04 LTS on my LENOVO IdeaPad U430 Touch. How come the battery just charges up to 59%? I also have Win8 on another partion and it easily reaches 100%.
I tried "TLP" but nothing changed. I've read some complaints from people who have a similar problem but they all have ThinkPads and there's a special modul for "TLP" where you can control the charging threshold.
What to do?


text:
Q: GWT Hibernate import javax.persistence.*; not resolved why? I'm testing Hibernate but in the beginning I have to fight with some strange errors:

*

*my Javax cannot be resolved but why?

I made a build-path to ebj-peristance.jar. Copied all files /libs of Hibernate in my WEB-INF/libs why do I still getting this error?

A: i solved it with the help of :
ctrl + shift + T
so powerfull


text:
Q: CakePHP - all pages blank except the home page I inherited a very old CakePHP application (version 1.3.2) that I have to run on a new server (old server is long gone, I only have the code). I managed to get it going after some configuration and right now the home page loads here:
http://m.gratuito24.com/
So far so good, however, if you click on any of the links, absolutely nothing happens. I get no errors in the browser, no errors in the logs and I even tried to print out some debug messages from the app_controller beforeFilter and beforeRender methods but with no success. As you notice, the site is translated (in Bulgaria), however, using the English equivalents for the controllers and actions results in the exact same manner. Setting Debug Mode to 2 in core.php still displays a completely blank page.
Any idea how to approach debugging this or what might be the cause? I've looked into the routes.php file and there are a lot of routes set there but except for the home '/' route, nothing else seems to work. Basically the server is not finding a resource following the links at all which is strange as I can see that the framework/database are present thus loading the home page. Any tips appreciated.

A: For me it looks like a problem with mod_rewrite, look on http://m.gratuito24.com/index.php/ads/index/showAds:goods/language:bg.html, index.php part is important,
first thought: no mod_rewrite on server,
second: something wrong with .htaccess


text:
Q: how to change the length of an array I asked a similar question before, but I couldn't figure out what the problem was. I am new to programming and am confused about how to change the length of an array by setting its initial length to a variable, but it isn't updating.
My code:
import java.util.Scanner;

class computer{

    int g = 1;  //create int g = 2
    int[] compguess = new int[g];   //set array compguess = 2

    void guess(){

        int rand;   //create int rand
        int i;  //create int i
        rand = (int) Math.ceil(Math.random()*10);   // set rand = # 1-10
        for (i = 0; i < compguess.length; i++){     // start if i < the L of the []-1 (1)

            if(rand == compguess[i]){   //if rand is equal to the Ith term, break the for loop
                break;
            }
        }   //end of for loop
        if(i == compguess.length - 1){  //if i is = the length of the [] - 1:
            compguess[g - 1] = rand;    // set the new last term in the [] = rand
            g++;    // add 1 to the length of the [] to make room for another int
            System.out.println(compguess[g - 1]);   // print the last term
        }
    }
}

public class game1player2 {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        computer computer1 = new computer();    // create new computer object
        for(int a = 0; a < 3; a++){     // start if a < 3
            computer1.guess();      // start guess method
            for(int n = 0; n < computer1.compguess.length; n++) //print the contents of []
            System.out.println(computer1.compguess[n]);     // print out entire array
        }
        {
            input.close();
        }
    }
}

A: There is no way to change the length of an array after it is created in Java. Instead, a new larger array must be allocated and the elements must be copied over. Fortunately, there are implementations of the List interface that do this behind-the-scenes for you already, the most common of which is ArrayList.
As the name suggests, an ArrayList wraps an array, offering ways to add/remove elements via methods like add() and remove() (see the afore-linked documentation). If the internal array fills up, a new array that is 1.5x larger is created an the old elements are copied over to it, but this is all hidden from you, which is quite convenient.

A: I suggest the use of an arrayList instead. It will adjust size as needed. Create it using ArrayList<Integer> list=new ArrayList<>(); after importing java.util.ArrayList.
You can set values as follows. To  set value in position i to the value val, use:
list.set(i, val);

You can add to the end with list.add(someInt); and retrieve with int foo=list.get(position).
"Resizing" an array is possible by only copying it to a larger one. That still generates a new array instead of operating in place. The int to Integer conversions are handled by autoboxing here.

A: You cannot change the length of an array in Java. You will need to create a new one and copy the values over, or use an ArrayList.


text:
Q: To get a value of a TD using JQuery I got a very simple Table with only two rows.
I was thinking what is the best way to get the value from the TD with ID "row2".

hello

world

Here is my attempt:
$(document).ready(function(){
      var r=$("#testing":row2).val();
      alert(r);
});

But I couldn't see any message pop up.
What shall I do in the JQuery code if I want to specify the Table ID along with the TD ID?
 var r=$("#testing":row2).text();
 var r=$("#testing").children("row2").text();

A: Use text() instead of val()
var r = $("#row2").text();

More Info:

*

*.text()

A: This will do it for you:
  var r = $("#testing #row2").text();
  alert(r);

In action here for your viewing pleasure.

A:

    1
    2
    3

    4
    5
    6

jquery code to select particular td value
$(".tdcls").mouseenter(function(){
    var a = $(this).text();
});

A: the TD ID is going to be unique be it in any table. It is not right to have two tables with TD ID's same in both tables. Therefore if you feel then append the table id for the TD ID like so: (and then use the answers above)

    hello

    world

does this help?


text:
Q: Using ui-router's resolve on a controller defined with inline array annotation and fluent API I'm used to defining angular controllers with the inline array notation, e.g.:
angular
  .controller('SomeCtrl', [ '$scope', function($scope) {
    ...
}])

I also prefer the fluent API for angular modules, i.e. there is only a single angular.module call at the top of my file defining the controllers, and everything else is chained to this call.
I would now like to use ui-router's resolve feature, and keep the controller dependency with the controller, not in the router (see the recommendations on routing resolves).
Is there a way to continue using my preferred approaches (inline array notation, fluent API) together with the recommendations for ui-router's resolve? My current understanding is that angular.controller defines the constructor for a controller, so in order to have an additional resolve() method on the controller I would have to pass in an object that already has this method plus a constructor.
Update: adding a code sample.
Route:
function config ($routeProvider) {
  $routeProvider
  .when('/myroute', {
    templateUrl: 'views/some.html',
    controller: 'SomeCtrl'
    resolve: SomeCtrl.resolve
  });
}

Controller:
angular
  .controller('SomeCtrl', [ '$scope', 'SomeService', function($scope, SomeService) {
    var data = SomeService.data;
...
}])

Where SomeService.data() is the method call that returns the promise I need resolved. How do I define the resolve using my preferred approaches?
SomeCtrl.resolve = {
  data: function(SomeService) {
    return SomeService.data();
  }
};

A: You can keep using the inline annotations. You will just need an annotation for the name of the model that you are resolving.
So if your resolve has a method named getPromise, your inline controller DI annotation should contain the string 'getPromise'.
UPDATE
So with your code examples you should make the following changes.
Add 'resolve annotations' to your resolve object:
SomeCtrl.resolve = {

  'SomeService': SomeService,

  someData: ['SomeService', function(SomeService) {
    return SomeService.data();
  }]
};

Add an annotation to the resolve method. I have changed it from 'data' in your example to 'someData' here:
angular
  .controller('SomeCtrl', [ '$scope', 'someData', function($scope, someData) {
     var data = someData;
     ...
}])

Another UPDATE
Ok. I think I understand the question now.
You do not need to define the uiRouter resolve with SomeCtrl.resolve.
You can define the resolve inline in the module config section:
function config ($routeProvider) {
  $routeProvider
  .when('/myroute', {
    templateUrl: 'views/some.html',
    controller: 'SomeCtrl'
    resolve:  {
           'SomeService': SomeService,
           someData: ['SomeService', function(SomeService) {
               return SomeService.data();
           }]
       }
  });
}

Or if you want to get fancy, you can create a resolve object with keys for each of your state and then do some thing like:
...
resolve: myResolveObj.someState
...


text:
Q: Upper case a selection of text in a textarea I'm getting an undefined is not a function error when I try and run the following code:
$(document).ready(function() {
    $("#textarea").select(function() {
        var selection = window.getSelection();
        $("#upper").click(function() {
            // alert(selection);
            var upper = selection.toUpperCase();
            var text = $("#textarea").text();
            $("#textarea").html(text.replace(selection, upper));
        });
    });
});

I'm trying to select text from a textarea, and click a button to make the selection uppercase. Here is a JSFiddle of the complete code.

A: getSelection returns an object. You need to call toString() on it.
$(document).ready(function () {
    var selection;
    $("#textarea").select(function () {
        selection = window.getSelection().toString();
    });
    $("#upper").click(function () {
        if (selection) {
            var upper = selection.toUpperCase();
            var text = $("#textarea").text();
            $("#textarea").html(text.replace(selection, upper));
        }
    });
});

JSFiddle: http://jsfiddle.net/TrueBlueAussie/8syb2d8j/4/
Notes:

*

*your event handlers were nested (usually a bad idea)

*I added a check to ensure that there is a selection before trying to upppercase it.

*as, potentially, the text you highlight may occur more than one, using replace is actually not a great solution. Try highlight the second i and see what I mean. You should use the properties of the selection object instead to work out the exact part of the string that was selected,

After browsing around for portable solutions, I found the jQuery TextRange plugin, which, based on the demo is more than enough for this problem.


text:
Q: How do I make this function more generic? I have a little jQuery function calculating some inputs. I would like to be able to make this more generic so that I don't have to repeat this code.
jQuery(document).ready(function(){
    update_amounts();
    jQuery('.list_item_9 input:not([readonly])').change(function() {
        update_amounts();
    });
});

function update_amounts() {
    var sum = 0;
    jQuery('.list_item_9 input:not([readonly])').each(function() {
        sum += Number(jQuery(this).val());
    });
    jQuery('.list_item_9 .gfield_list_184_cell5 input').val(sum);
}

The HTML for this looks like the following:

        <input type="text" name="FIELDLABEL" value="" readonly="">

        <input type="text" name="TWO" value="">

        <input type="text" name="THREE" value="">

        <input type="text" name="FOUR" value="">

        <input type="text" name="TOTAL" value="0" readonly="">

I've tried multiple iterations of this but I can't quite figure out how to target the function based on what has changed.

A: This code should do what you want. Each time an input changes, it finds the parent gfield_list_group class element, then sums all the not-readonly inputs below that, writing the total to the input with name="TOTAL" (you might want to change that to a class specifier e.g. glist_total_cell). For initialisation, there is a routine update_all_amounts which sums inputs under all gfield_list_group elements.

jQuery(document).ready(function() {
  update_all_amounts();
  jQuery('.gfield_list_group input:not([readonly])').change(function() {
    update_amounts(jQuery(this));
  });
});

function update_amounts(inp) {
  var sum = 0;
  var parent = inp.closest('.gfield_list_group');
  parent.find('input:not([readonly])').each(function() {
    sum += Number(jQuery(this).val());
  });
  parent.find('input[name="TOTAL"]').val(sum);
}

function update_all_amounts() {
  jQuery('.gfield_list_group').each(function() {
    update_amounts(jQuery(this).find('input:not([readonly])').first());
  });
}

      <input type="text" name="FIELDLABEL" value="row 9" readonly="">

      <input type="text" name="TWO" value="">

      <input type="text" name="THREE" value="6">

      <input type="text" name="FOUR" value="">

      <input type="text" name="TOTAL" value="0" readonly="">

      <input type="text" name="FIELDLABEL" value="row 10" readonly="">

      <input type="text" name="TWO" value="4">

      <input type="text" name="THREE" value="">

      <input type="text" name="FOUR" value="">

      <input type="text" name="TOTAL" value="0" readonly="">

A: The demo below is very generic -- no ids, classes, or attribute selectors -- only tagNames are used.

*

*wrap everything into a <form> and delegate "input" or "change" event to it.

*change the type of <input> to number.

*remember to convert each value of an input into a real number before calculations.

*don't use <input readonly> instead use <output></ouput>
Demo
Details are commented in demo

// Delegate the input event to the <form>
$('form').on('input', function(e) {
  // Declare sum at 0
  var sum = 0;
  // On each <input>
  $(this).find('input').each(function() {
    // Convert the value of each input and add it to sum
    sum += Number($(this).val());
  });
  // Assign sum to the last <output>
  $('output:last').val(sum);
});
form {
  margin: 50px auto
}
<form>

        <output>Name</output>

        <input type="number" value='0'>

        <input type="number" value='0'>

        <input type="number" value='0'>

        <output>0</output>

</form>


text:
Q: Convert user entered value to dollar currency I have a scenario where a user enters a value in as a string and I need to convert it to
a dollar currency and show it on the form. I have tried with the below approach.
protected void btn_Click(object sender, EventArgs e)
{
    string money = txtbox.Text;
    string currency = Convert.ToDecimal(txtbox.Text, new CultureInfo("en-US")).ToString("C");
    money = currency;
    Response.Write(money);
}

The issue is when user enters 56789 the result is shown as $56,789.00 where I do not want the unnecessary zeros after "." Where as when the user enters as 56789.67 the result is shown as $56,789.67 which is expected. Please help me regarding the same.

A: Try this:
protected void btn_Click(object sender, EventArgs e)
{
    Decimal currency = Convert.ToDecimal(txtbox.Text, new CultureInfo("en-US"));
    string money = currency.ToString("C");

    if (currency % 1 == 0) {
        money = money.Substring(0, money.Length - 3);
    }

    Response.write(money);
}

Here is a demo.
Let me know if you have any questions. Good luck! :)


text:
Q: DropDownList / RadioButtonList - I don't need to validate selected value? I have used ASP.NET MVC and there when I have for example dropdown list - I must check if selected value is correct because user can change value on dropdown list using for example Firebug.
I am new in ASP.NET Web Forms. I have for example:
<asp:DropDownList ID="DropDownList1" runat="server">
    <asp:ListItem Value="1">One</asp:ListItem>
    <asp:ListItem Value="2">Two</asp:ListItem>
</asp:DropDownList>

<asp:RadioButtonList ID="RadioButtonList1" runat="server">
    <asp:ListItem Value="1" Selected="True">One</asp:ListItem>
    <asp:ListItem Value="2">Two</asp:ListItem>
</asp:RadioButtonList>

I have changed in Firebug selected value in DropDownList1 on 3 and in RadioButtonList1 on 3 and submit form. Then I have error:
Invalid postback or callback argument.  Event validation is enabled using  in configuration or <%@ Page EnableEventValidation="true" %> in a page.  For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them.  If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for va...
Does it mean that I don't need to validate selected value because user can't change it?

A: Generally speaking, yes, EnableEventValidation works with that purpose in mind, you can read more here: http://msdn.microsoft.com/en-us/library/system.web.ui.page.enableeventvalidation(v=vs.110).aspx
In particular:

When the EnableEventValidation property is set to true, ASP.NET validates that a control event originated from the user interface that was rendered by that control. A control registers its events during rendering and then validates the events during postback or callback handling. For example, if a list control includes options numbered 1, 2, or 3 when the page is rendered, and if a postback request is received specifying option number 4, ASP.NET raises an exception. All event-driven controls in ASP.NET use this feature by default.

So as a matter of fact you can be safe knowing that people cannot tweak your client HTML with the console and post back malicious data.
This said, you may want to put some guard in the server code just in case for some pages you need to disable event validation (it may happen if you want to submit strings that look like code or if you want to modify elements on the page with jQuery for example).


text:
Q: Using energy from sun magnetic field Knowing
* earth spin and translation movement around sun,
* sun have a big magnetic field,
* a variable flux can generate a induced voltage (and current) into the circuit

Would it be posible to receive in a coil that energy?
Perhaps it's just enough to detecting the earth movement relative to magnetic field,
or if it were strong enough even for use the energy.
It doesn't seem to be so strong because if it where perhaps every coil in earth without a current generated by this flux variation.

A: Its good of you thinking to find an alternate sources of energy. I appreciate that.
Coming to the question, you cannot because the strength of the magnetic field is low and there is a lot of interference with the earth's magnetic field. And, you may ask that why cant we use the magnetic field to produce energy? First, the magnetic strength of the earth is 31 µT. So, in order to produce 1 Volt in a 1m length wire you need to make it travel at a speed of 32258.065 meters per second.
Do you really wanna do that??

A: As this Wikipedia article explains - the field strength of the Sun's magnetic field at the earth is about 0.1 nT (nano Tesla). For comparison, the magnetic field of a cell phone is thought to be somewhere in the region of 1000 nT.
So the magnetic field of the sun at the earth's surface is laughably small, and will be swamped by the stray magnetic fields of our electronic devices. So there is no useful way to harness that energy from the Earth's surface.


text:
Q: Can I use "Rube Goldberg machine" as an analogy or what is better analogy to explain the idea? English is my second language and I am in the field of Software Engineering.
I am working on a design and I need to explain my idea to non-technical business stakeholders.
Conceptually, my idea is based on the "Rube Goldberg machine" explained below (not physically, just conceptually)
https://en.wikipedia.org/wiki/Rube_Goldberg_machine
I've noticed many educated native English speakers have never heard of the term "Rube Goldberg machine". Is the term supposed to be well known among English speakers? If not, what is a better term that conveys the idea to non-engineer business stakeholders?

A: Not everybody will know the term. It may depend on their nationality, even amongst native English speakers.
Culturally, what would be termed Rube Goldberg in the US would be called Heath Robinson in the UK. Heath Robinson pre-dates Rube Goldberg by a couple of decades & so the Brits never really caught on to Goldberg in the same way as the US.
Younger natives may not know either of these. A more modern equivalent might be Wallace & Gromit, though Wallace's machines are more usually termed 'contraptions'… or even Chitty Chitty Bang Bang, where inventor Caractacus Potts builds similar devices.
It would be rude to leave out a later exponent of this type of absurd device, but it seems even fewer people remember Rowland Emett, who not just drew but actually built many of these. He designed & built the ones used in the Chitty Chitty Bang Bang movie.

A: You can use "needlessly complicated" or "over-engineered" (Collins Dictionary). Example sentences from Collins Dictionary.

The introduction of rules to put a floor under alcohol prices risks
being needlessly complicated.
It was also needlessly complicated.
After he introduced a 60 per cent price hike and turned a popular,
easy-to-use service into a needlessly complicated one, 800,000
customers took their money elsewhere.
This must be one of the most over-engineered bikes ever made.
The product was beautiful but, given its purpose, it was massively over-engineered.

You can also use "baroque"
Baroque, (Wiktionary):One of the meanings is "Notably complicated; overly and needlessly complicated; (usually, especially) in a bad way, not a good or neutral way".

grotesquely baroque bureaucratic hassles
baroque bookkeeping in pursuit of tax dodges

You may also use "Convoluted" (Collins Dictionary)
Convoluted: If you describe a sentence, idea, or system as convoluted, you mean that it is complicated and difficult to understand.

Blame a convoluted planning system and the highest construction costs
in the world.
It is an extremely convoluted process that will be unpopular with
those who have to make it work.


text:
Q: ld: library not found for -lcrt1.10.6.o after running Intel icc compiler on OS Mavericks I just upgraded from OS Mountain Lion to Mavericks, ran intel icc compiler, icc test.c, it said #include <time.h> is not found. So I checked the \usr folder, found \usr\include is missing and copyed include from my back to this folder, upgraded Xcode to Version 5.0.1. Then I compilered it again but still got a warning
ld: library not found for -lcrt1.10.6.o

What does it mean? How to fix that?

A: I got a similar compiler error when installing MacPorts' mysql5 (missing lcrt).  Jared Burrows is correct.  The quickie way to do this is to open Terminal and enter:
xcode-select --install

I'm not sure the discussions.apple.com link is much help.  Just seemed to be a bunch of folks arguing over whether static linking was 'sometimes ok' or 'bad programmer, no cookie.'
But here's a related Stack question, if mine doesn't work: Xcode 4.4 and later install Command Line Tools

A: I installed command line tool for Mavericks, now it fixes the problem!
For more detail, refer to this link.

A: I got a similar issue while having the set 'Build Active Architecture Only' to 'No' for all configurations in build settings.
Set this for 'debug' (my current local configuration I am building with on device) to 'YES' solved the problem for me.


text:
Q: Fill data frame with result from function I have the following code to fill a data frame with the result from a function row-wise. The result of the function inside the loop is random-based (part of a simulation):
input <- as.data.frame(matrix(seq(1:20),4,5), row.names = c("A", "B", "C", "D"))
output <- data.frame()

j = 1
for (rowname in rownames(input)) {
   output <- rbind(output,ifelse(runif(5)+2>=rep(1/input[j,1],5),round(rgamma(5,shape=0.8, rate=2),0),rep(0,5)))
   j = j+1
}
rownames(output) <- rownames(input)

I would like to avoid the for loop and I guess there should be a way to do this in less lines and in a more efficient way in R. Do you have an idea how to do this?
Ideally, I would like to pass all arguments already during the creation of the output data frame.

A: Something like this:
ifelse(
  matrix(runif(prod(dim(input)))+2,nrow=nrow(input)) >= 1/input,
  matrix(round(rgamma(prod(dim(input)),shape=0.8, rate=2),0),nrow=nrow(input)),
  0)


text:
Q: Match two dates and return true if match function isInDate(MatchDate, entries) {
    for (c = 0; c < entries.length; c++) {
        var entry = entries[c];
        var DateFrom = new Date(entry.DateFrom);
        var DateTo = new Date(entry.DateTo);

        if (
            DateFrom.getMonth() <= MatchDate.getMonth() &&
            DateFrom.getDay() <= MatchDate.getDay() &&
            DateTo.getDay() >= MatchDate.getDay()
        ) {
            return true;
        }
    }

    return false;
}

I am passing in a "MatchDate" that I want to compare with every looped entries "DateFrom" and "DateTo", if the matchdate is in the timespan I want to return true, otherwise false.
It should also return true if its the same day as DateFrom & same day as DateTo... I can't get it to work whatever I try.. Could anyone please assist?

A: getDay returns the day of the week, not the day of the month.
You want to use getDate()
And you can simply just do
return MatchDate >= DateFrom && MatchDate <= DateTo;

A: Should be like:

var pre = onload, isInDate; //for use on other loads
onload = function(){
if(pre)pre();
isInDate = function(MatchDate, entries){
  for(var c=0,l=entries.length; c<l; c++) {
    var entry = entries[c], DateFrom = new Date(entry.DateFrom), DateTo = new Date(entry.DateTo);
    var md = MatchDate.getTime();
    if(!(DateFrom.getTime() <= md && DateTo.getTime() >= md)){
      return false;
    }
  }
  return true;
}
}


text:
Q: How to trigger an effect after an event in React I'm building a React app, and it basically loads blog posts, and attached comments for each post.
When a blog post is rendered, the comments for that blog post are also fetched. I also have a component that allows a comment to be submitted.
When the submit button is clicked, I want the comments to refresh their data source, and immediately display the new comment.
How do i send some kind of event to our comments component that tells it to send another fetch request?
It seems that the core of this problem is this:
How do I idiomatically send events to other React components that will trigger an effect?
EDIT - General Solution:

*

*Lift State up into nearest component

*create a callback function that includes the state update function. Pass this callback as a prop to the component that will be triggering the event. When the event happens, run the callback in the handler.

Post.js
import React from 'react';
import {useState, useEffect, useContext} from 'react';
import Markdown from 'markdown-to-jsx';
import Container from '@material-ui/core/Container';
import Typography from '@material-ui/core/Typography';
import SendComment from './SendComment';
import Comments from './Comments';
import {POST_URL} from './urls';
import UserContext from './UserContext';
//import CommentListContainer from './CommentListContainer';

export default function Post(props) {
  const user = useContext(UserContext);

  const [post, setPost] = useState({
    content: '',
    comments: [],
  });

  useEffect(() => {
    const UNIQUE_POST_URL = [POST_URL, props.location.state.id].join('/');

    const fetchPost = async () => {
      const result = await fetch(UNIQUE_POST_URL);
      const json = await result.json();
      setPost(json);
    };
    fetchPost();
  }, [props.location.state.id]);

  return (

      <Container>
        <Typography
          variant="h4"
          color="textPrimary"
          style={{textDecoration: 'underline'}}>
          {post.title}
        </Typography>
        <Markdown>{post.content}</Markdown>
        {post.content.length !== 0 && (

            <Typography variant="h4">Comments</Typography>
            <SendComment user={user} posts_id={props.location.state.id} />
            <Comments user={user} posts_id={props.location.state.id} />

        )}
      </Container>

  );
}

SendComment.js component
import React from 'react';
import TextField from '@material-ui/core/TextField';
import Grid from '@material-ui/core/Grid';
import Button from '@material-ui/core/Button';
import Paper from '@material-ui/core/Paper';
import {COMMENT_SUBMIT_URL} from './urls';

export default function SendComment(props) {
  async function handleSubmit(e) {
    const comment = document.querySelector('#comment');

    // Skip empty comments
    if (comment.value === '') {
      return;
    }

    async function sendComment(url) {
      try {
        const res = await fetch(url, {
          method: 'POST',
          body: JSON.stringify({
            comment: comment.value,
            users_id: props.user.users_id,
            posts_id: props.posts_id,
          }),
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            'Accept-Language': 'en-US',
          },
        });
        comment.value = '';
        return res;
      } catch (e) {
        console.log(e);
      }
    }
    const res = await sendComment(COMMENT_SUBMIT_URL);
    if (res.ok) {
      // Reload our comment component !
      // Here is where we want to send our "event"
      // or whatever the solution is
    }
  }

  return (
    <Grid container justify="space-evenly" direction="row" alignItems="center">
      <Grid item xs={8}>
        <TextField
          id="comment"
          fullWidth
          multiline
          rowsMax="10"
          margin="normal"
          variant="filled"
        />
      </Grid>
      <Grid item xs={3}>
        <Button variant="contained" color="primary" onClick={handleSubmit}>
          Submit
        </Button>
      </Grid>
    </Grid>
  );
}

Comments.js
import React from 'react';
import {useState, useEffect} from 'react';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemAvatar from '@material-ui/core/ListItemAvatar';
import Avatar from '@material-ui/core/Avatar';
import Divider from '@material-ui/core/Divider';
import {timeAgo} from './utils';
import {COMMENT_URL} from './urls';

export default function Comments(props) {
  const [comments, setComments] = useState({
    objects: [],
  });

  useEffect(() => {
    async function getComments(posts_id) {
      const filter = JSON.stringify({
        filters: [{name: 'posts_id', op: 'equals', val: posts_id}],
      });

      try {
        COMMENT_URL.searchParams.set('q', filter);

        const res = await fetch(COMMENT_URL, {
          method: 'GET',
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
          },
        });
        const json = await res.json();
        setComments(json);
      } catch (e) {
        console.log(e);
      }
    }
    getComments(props.posts_id);
  }, [props.posts_id]);

  const commentList = comments.objects.map(comment => (
    <ListItem key={comment.id} alignItems="flex-start">
      <ListItemAvatar>
        <Avatar alt={comment.users.name} src={comment.users.picture} />
      </ListItemAvatar>
      <ListItemText
        primary={`${comment.users.name} - ${timeAgo(comment.created_at)}`}
        secondary={comment.comment}></ListItemText>
      <Divider />
    </ListItem>
  ));

  return <List>{commentList}</List>;
}

This code currently works, However the new comment is displayed only on a page reload, not immediately after submission.

A: Here it goes an idea:
You should have your comments on a state variable in Posts.
Like so const[comments, setComments] = useState([]);.
You can recieve a prop in SendComment, named onCommentSent.
In your code, when you send a comment you execute onCommentSent();
So, in Posts, when the comment is sent, you reload the data of the comments and set it comments using setComments(newData).
When the state reloads, the comments will refetch.

A better performing idea is to not to retrieve all comments on each comment POST request, you can update dinamically the data in the state variable comments knowing that next time that you fetch the server, the comment will come.
Hope it helps!

A: I don't think you can send such events without any extra logic.
The easiest solution I see is the following: as soon as you have a parent component (Post) for both SendComment and Comments, you can move all logic into it. Instead of saving the comment inside SendComment, you could pass it a callback which would be triggered when the user presses the button. The comment then sould be sent to server inside Post.
To display comments, you can fetch them in Post as well and then just pass it to Comments as a prop. Like this you can easily update comments and you won't need an extra request when the user submits a new comment.
Also prefer using controlled components (you have an uncontrolled text field in SendComment)
Code would look something like this:
Post.js
export default function Post(props) {
  const user = useContext(UserContext);

  const [content, setContent] = useState('')
  const [title, setTitle] = useState('')
  const [comments, setComments] = useState([])

  const onNewComment = useCallback((text) => {
    // I'm not sure about your comment structure on server.
    // So here you need to create an object that your `Comments` component
    // will be able to display and then do `setComments(comments.concat(comment))` down below
    const comment = {
      comment: text,
      users_id: user.users_id,
      posts_id: props.location.state.id,
    };
    async function sendComment(url) {
      try {
        const res = await fetch(url, {
          method: 'POST',
          body: JSON.stringify(comment),
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            'Accept-Language': 'en-US',
          },
        });
        return res;
      } catch (e) {
        console.log(e);
      }
    }
    const res = await sendComment(COMMENT_SUBMIT_URL);
    if (res.ok) {
      setComments(comments.concat(comment));
    }
  }, [comments]);

  useEffect(() => {
    const UNIQUE_POST_URL = [POST_URL, props.location.state.id].join('/');

    const fetchPost = async () => {
      const result = await fetch(UNIQUE_POST_URL);
      const { content, comments, title } = await result.json();
      setContent(content);
      setComments(comments);
      setTitle(title);
    };
    fetchPost();
  }, [props.location.state.id]);

  return (

      <Container>
        <Typography
          variant="h4"
          color="textPrimary"
          style={{textDecoration: 'underline'}}>
          {title}
        </Typography>
        <Markdown>{content}</Markdown>
        {content.length !== 0 && (

            <Typography variant="h4">Comments</Typography>
            <SendComment user={user} onNewComment={onNewComment} />
            <Comments user={user} comments={comments} />

        )}
      </Container>

  );
}

SendComment.js
export default function SendComment(props) {
  const [text, setText] = useState('');
  const handleSubmit = useCallback(() => {
    // Skip empty comments
    if (comment.value === '') {
      return;
    }
    if(props.onNewComment) {
      props.onNewComment(text);
      setText('');
    }
  }, [props.onNewComment, text]);

  return (
    <Grid container justify="space-evenly" direction="row" alignItems="center">
      <Grid item xs={8}>
        <TextField
          id="comment"
          onChange={setText}
          fullWidth
          multiline
          rowsMax="10"
          margin="normal"
          variant="filled"
        />
      </Grid>
      <Grid item xs={3}>
        <Button variant="contained" color="primary" onClick={handleSubmit}>
          Submit
        </Button>
      </Grid>
    </Grid>
  );
}

Comments.js
export default function Comments(props) {
  const commentList = props.comments.map(comment => (
    <ListItem key={comment.id} alignItems="flex-start">
      <ListItemAvatar>
        <Avatar alt={comment.users.name} src={comment.users.picture} />
      </ListItemAvatar>
      <ListItemText
        primary={`${comment.users.name} - ${timeAgo(comment.created_at)}`}
        secondary={comment.comment}></ListItemText>
      <Divider />
    </ListItem>
  ));

  return <List>{commentList}</List>;
}

UPD: changed some code to display content and title in Post.js

A: I've created a working solution, however it is clearly ugly, and definitely feels like I'm brute forcing it, instead of doing it the React way:
I extracted the logic of fetching the comments into its own function. This function gets called during the effect, and inside of the handleSubmit function.
The Comments component is now a child of SendComment (which from an organizational standpoint makes no sense)
export default function SendComment(props) {
  const [comments, setComments] = useState({
    objects: [],
  });

  async function getComments(posts_id) {
    const filter = JSON.stringify({
      filters: [{name: 'posts_id', op: 'equals', val: posts_id}],
    });

    try {
      COMMENT_URL.searchParams.set('q', filter);

      const res = await fetch(COMMENT_URL, {
        method: 'GET',
        headers: {
          Accept: 'application/json',
          'Content-Type': 'application/json',
        },
      });
      const json = await res.json();
      setComments(json);
    } catch (e) {
      console.log(e);
    }
  }

  useEffect(() => {
    getComments(props.posts_id);
  }, [props.posts_id]);

  async function handleSubmit(e) {
    const comment = document.querySelector('#comment');

    // Skip empty comments
    if (comment.value === '') {
      return;
    }

    async function sendComment(url) {
      try {
        const res = await fetch(url, {
          method: 'POST',
          body: JSON.stringify({
            comment: comment.value,
            users_id: props.user.users_id,
            posts_id: props.posts_id,
          }),
          headers: {
            Accept: 'application/json',
            'Content-Type': 'application/json',
            'Accept-Language': 'en-US',
          },
        });
        comment.value = '';
        return res;
      } catch (e) {
        console.log(e);
      }
    }
    const res = await sendComment(COMMENT_SUBMIT_URL);
    if (res.ok) {
      getComments(props.posts_id);
    }
  }

  return (
    <>
      <Grid
        container
        justify="space-evenly"
        direction="row"
        alignItems="center">
        <Grid item xs={8}>
          <TextField
            id="comment"
            fullWidth
            multiline
            rowsMax="10"
            margin="normal"
            variant="filled"
          />
        </Grid>
        <Grid item xs={3}>
          <Button variant="contained" color="primary" onClick={handleSubmit}>
            Submit
          </Button>
        </Grid>
      </Grid>
      <Grid container justify="space-left">
        <Grid item justify="flex-start">
          <Comments comments={comments} />
        </Grid>
      </Grid>
    </>
  );
}


text:
Q: handling breaks in dotPlot How would you handle breaks for a dotPlot when you have serious outliers:
I cannot transform the data to log or anything like that.
 library(mosaic)
n=300
r =c(seq(1,15,1))
binwidth = 1
outliers= c(100,400,800,700)
#outliers= c(15,14,3,5)
dat = c(sample(r ,n= 1,size = n, replace = TRUE),outliers)
quantile(dat)[4]+1.5* IQR(dat)
n=n+4
brks = c(seq(0,sd(dat)*2,binwidth),tail(seq(0,sd(dat)*2,binwidth),1)+binwidth,tail(seq(0, max(dat),binwidth),1)+binwidth)
d = data.frame( x = dat, color = c(rep("red",n/2), rep("green",n/2)))
dotPlot(d$x,  breaks = seq(min(d$x)-binwidth,max(d$x)+binwidth,binwidth), cex = .5)

If you run that code you will see 4 outliers that make the plot unreadable. How would you deal with that?

Right now the breaks go from the min to the max of the d$x by the binwidth but I think that some of those empty bins should be removed. What logic would you use to remove those bins? Bins that are over 2 standard deviations and are empty then remove them?  Can you give example code?
Any idea how to create your own dot plot without using dotPlot() or dotplot().
i have the data in the "dat" dataframe below
##### HERE CAN I CREATE MY OWN DOT PLOT?
library(qdapRegex)
binwidth = 1
t = table(cut(dat, seq(0,max(dat)+1,binwidth)  ))
r_names =rownames(t)[t>0]
r_names = as.numeric(rm_between(r_names, ',', ']', extract=TRUE))
dat =data.frame(bin = r_names, data = t[t>0])
dat  #can you turn this into a dot plot where the x-axis ONLY consists of the bin column. i.e. no space between 15 and 100?

Thank you.

A: This is a bit more complete an answer than my comment:
png()
dotPlot(log(d$x, 10), xlab=expression(Log[10](X)), scales=list(x=list(labels=10^(0:5)) ))
dev.off()


text:
Q: Re-using generic tasks in Luigi I'm having trouble understanding how to make re-usable tasks in Luigi, and then use them in a concrete situation.
For example. I have two generic tasks that do something to a file and then output the result:
class GffFilter(luigi.Task):
    "Filters a GFF file to only one feature"
    feature = luigi.Parameter()
    out_file = luigi.Parameter()
    in_file = luigi.Parameter()
    ...

class BgZip(luigi.Task):
    "bgZips a file"
    out_file = luigi.Parameter()
    in_file = luigi.Parameter()
    ...

Now, I want a workflow that first filters, then bgzips a specific file using these tasks:
class FilterSomeFile(luigi.WrapperTask):
    def requires(self):
        return GffFilter(in_file='some.gff3', out_file='some.genes.gff3', filter='gene')

    def output(self):
        return self.inputs()

class BgZipSomeFile(luigi.Task):
    def run(self):
        filtered = FilterSomeFile()
        BzZip(filtered)

But this is awkward. In the first task I have no run method, and I'm just using dependencies to use the generic task. Is this correct? Should I be using inheritance here instead?
Then in the second task, I can't use dependencies, because I need the output from FilterSomeFile in order to use BgZip. But using dynamic dependencies seems wrong, because luigi can't build a proper dependency graph.
How should I make a Luigi workflow out of my generic tasks?

A:
But this is awkward. In the first task I have no run method, and I'm just using dependencies to use the generic task. Is this correct?

Yes, according to this page, the WrapperTask is a dummy task whose purpose is to define a workflow of tasks, therefore it doesn't perform any actions by itself. Instead, by defining several requirements, this task will be complete when every requirement, listed in the requires method, has been completed. The main difference of this WrapperTask to a regular Task, is that you don't need to define an output method to signal that this task suceeded, as can be seen here.

Then in the second task, I can't use dependencies, because I need the output from FilterSomeFile in order to use BgZip. But using dynamic dependencies seems wrong, because luigi can't build a proper dependency graph.

Theoretically, you could make FilterSomeFile have the same output as GffFilter, make the BgZipSomeFile require FilterSomeFile, and then use the FilterSomeFile.output() in BgZipSomeFile.run to access the the zipped file. However, this solution would be somewhat strange because:

*

*The wrapper task only "runs" 1 other task, so the wrapped task could be used directly, without having to create a WrapperTask. A better usage of WrapperTask would involve merging BgZipSomeFile and FilterSomeFile in a single subclass of WrapperTask

*A Task is being instantiated in a run method. This results in a dynamic dependency, but this is not needed in this problem.

*Finally, the input of GffFilter is hardcoded in FilterSomeFile task, which makes the workflow less useful. This could be avoided by making the WrapperClass still receive parameters, and pass these parameters to its requirements.
A better solution would be:
import luigi as lg

class A(lg.Task):
    inFile = lg.Parameter()
    outFile = lg.Parameter()

    def run(self,):
        with open(self.inFile, "r") as oldFile:
            text = oldFile.read()

        text  += "*" * 10 + "\n" + "This text was added by task A.\n" + "*" * 10 + "\n"
        print(text)
        with open(self.outFile, "w") as newFile:
            newFile.write(text)

    def output(self,):
        return lg.LocalTarget(self.outFile)

class B(lg.Task):
    inFile = lg.Parameter()
    outFile = lg.Parameter()

    def run(self,):
        with open(self.inFile, "r") as oldFile:
            text = oldFile.read()

        text  += "*" * 10 + "\n" + "This text was added by task B.\n" + "*" * 10 + "\n"

        with open(self.outFile, "w") as newFile:
            newFile.write(text)

    def output(self,):
        return lg.LocalTarget(self.outFile)

class CustomWorkflow(lg.WrapperTask):
    mainOutFile = lg.Parameter()
    mainInFile = lg.Parameter()
    tempFile = "/tmp/myTempFile.txt"
    def requires(self,):
        return [    A(inFile = self.mainInFile, outFile = self.tempFile),
                    B(inFile = self.tempFile, outFile = self.mainOutFile)
                ]

This code can be run in command line with:
PYTHONPATH='.' luigi --module pythonModuleContainingTheTasks --local-scheduler CustomWorkflow --mainInFile ./text.txt --mainOutFile ./procText.txt


text:
Q: Angular Displaying Multiple Buttons for a List I have a list of cells. And I am trying to display its Location Reference for another screen. The way I want to display that property is in the shape of buttons. I want to have 1 button per cell and on the button, I want to write the Location Reference of the cell. Right now, the cells are too much, so I don't want to add them one by one. I tried to use ng-repeat but I couldn't make it work and it gave many errors. What should I do to achieve what I want?
HTML:

        <button>{{ cell.LocationReference }}</button>

TS:
cell: ICell;

Cell Interface:
export interface ICell {
  CellId?: number;
  CellName?: string;
  LocationReference?: string;
}

A: ng-repeat is for angularJS, in the tags you say you are using angular. Angular is different from angularJS, in angular you can use ngfor
If you have a list of cells, you need to loop through your cells, and not over the property of one cell. Also it totally doesn't make sense to put your button in a single cell, so I removed the table construct. Use a table only if you are displaying tabular data.
If you are displaying tabular data, add the table structure back, but now you should see how this is supposed to work: cells is the array for all your cells, should be of type ICell[]

  <button *ngFor=let cell of cells>{{cell.LocationReference}}</button>

A: You should use *ngFor and not ng-repeat. ng-repeat is used in AngularJS, and *ngFor is used in Angular. If you will loop through an array you can do it like this:

    <button>{{ item.LocationReference }}</button>

If you will loop through a dictionary you can do it like this:

    <button>{{ item.value}}</button>


text:
Q: Click button within the same HTML structure? When return is pressed within a text field I am trying to prevent a line break and instead click the save button.
I have multiple forms with similar layouts. I tried selecting the textarea using '.comment-form textarea' then I need to click :button[value="Save"] under the same .comment-form as the textarea.
I have also included my test jQuery, this stops the line break but does not click the button. It also does not differentiate when multiple forms are loaded. I also tried using parents to find the .comment-form but this also did not work.

jQuery(document).ready(function($) {
  $('.comment-form textarea').keypress(function(e) {
    if (e.which == 13) {
      e.preventDefault();
      jQuery(this).blur();
      jQuery(':button[value="Save"]').focus().mousedown();
    }
  });
});

  <form class="comment-form">

...

            Comment

              <textarea class="form-textarea" placeholder="Comment"></textarea>

      <input name="token">...</input>
      <input name="form-id">...</input>
      <input name="access-id">...</input>

...

        <button type="submit" value="Save" class="btn btn-success">Save</button>
        <button type="submit" value="Cancel" class="btn btn-default">Cancel</button>

A: You don't need to target a specific button and trigger an event on it. To make this work you can use closest() to get the parent form element and submit() it.
It's also worth noting that there's some other issues which need to be addressed. Firstly <input /> elements do not have a closing tag, they are self-closing. Also, the 'Cancel' button is type="submit" which seems very odd. I would assume this should be made in to a type="button" so that it does not save the data in the form (which is the main purpose of cancelling an action). Lastly, your HTML was missing a </form> tag, but I would guess this was just an oversight when creating the question.
With all that said, try this:

jQuery($ => {
  $('.comment-form textarea').on('keypress', function(e) {
    if (e.which == 13) {
      e.preventDefault();
      $(this).closest('form').submit();
    }
  });
});

  <form class="comment-form">

...

            Comment

              <textarea class="form-textarea" placeholder="Comment"></textarea>

      <input name="token" />...
      <input name="form-id" />...
      <input name="access-id" />...

...

        <button type="submit" value="Save" class="btn btn-success">Save</button>
        <button type="button" value="Cancel" class="btn btn-default">Cancel</button>

  </form>


text:
Q: Im getting an error when submitting a json to a rest endpoint Please I need some help regarding an error with Json. I am doing a homework test an trying to upload json to a database .. below is the Json
"{\"operation\":\"create\",\"tableName\":\"api\",\"payload\":{\"Item\":{ '"id":"334'","name":"'Lukas'", "occupation":"'Mjor'"' }}}"

But when I try to upload it I get an error:
{
"errorType": "SyntaxError",
"errorMessage": "Unexpected token i in JSON at position 83",
"trace": [
    "SyntaxError: Unexpected token i in JSON at position 83",
    "    at JSON.parse (<anonymous>)",
    "    at Runtime.handleOnce (/var/runtime/Runtime.js:67:14)"
]

}
Please can someone help I read a bunch of articles still havent had a clue

A: I figured it out. I need to ident the same characters with .
"{\"operation\":\"create\",\"tableName\":\"apilambdadb\",\"payload\":{\"Item\":{\"id\":\"334\",\"name\":\"Mihael\", \"occupation\":\"Mjo\"}}}"


text:
Q: RuntimeError: Cannot close a running event loop I'm trying to resolve this error: RuntimeError: Cannot close a running event loop in my asyncio process. I believe it's happening because there's a failure while tasks are still pending, and then I try to close the event loop. I'm thinking I need to await the remaining responses prior to closing the event loop, but I'm not sure how to accomplish that correctly in my specific situation.
 def start_job(self):

        if self.auth_expire_timestamp < get_timestamp():
            api_obj = api_handler.Api('Api Name', self.dbObj)
            self.api_auth_resp = api_obj.get_auth_response()
            self.api_attr = api_obj.get_attributes()

        try:
            self.queue_manager(self.do_stuff(json_data))
        except aiohttp.ServerDisconnectedError as e:
            logging.info("Reconnecting...")
            api_obj = api_handler.Api('API Name', self.dbObj)
            self.api_auth_resp = api_obj.get_auth_response()
            self.api_attr = api_obj.get_attributes()
            self.run_eligibility()

async def do_stuff(self, data):

    tasks = []

    async with aiohttp.ClientSession() as session:
        for row in data:
            task = asyncio.ensure_future(self.async_post('url', session, row))
            tasks.append(task)
        result = await asyncio.gather(*tasks)
    self.load_results(result)

def queue_manager(self, method):
    self.loop = asyncio.get_event_loop()
    future = asyncio.ensure_future(method)
    self.loop.run_until_complete(future)

async def async_post(self, resource, session, data):
        async with session.post(self.api_attr.api_endpoint + resource, headers=self.headers, data=data) as response:
            resp = []
            try:
                headers = response.headers['foo']
                content = await response.read()
                resp.append(headers)
                resp.append(content)
            except KeyError as e:
                logging.error('KeyError at async_post response')
                logging.error(e)
        return resp

def shutdown(self):
    //need to do something here to await the remaining tasks and then I need to re-start a new event loop, which i think i can do, just don't know how to appropriately stop the current one.
    self.loop.close()
    return True

How can I handle the error and properly close the event loop so I can start a new one and essentially re-boot the whole program and continue on.
EDIT:
This is what I'm trying now, based on this SO answer. Unfortunately, this error only happens rarely, so unless I can force it, i will have to wait and see if it works. In my queue_manager method I changed it to this:
try:
    self.loop.run_until_complete(future)
except Exception as e:
    future.cancel()
    self.loop.run_until_complete(future)
    future.exception()

UPDATE:
I got rid of the shutdown() method and added this to my queue_manager() method instead and it seems to be working without issue:
try:
    self.loop.run_until_complete(future)
except Exception as e:
    future.cancel()
    self.check_in_records()
    self.reconnect()
    self.start_job()
    future.exception()

A: To answer the question as originally stated, there is no need to close() a running loop, you can reuse the same loop for the whole program.
Given the code in the update, your queue_manager could look like this:
try:
    self.loop.run_until_complete(future)
except Exception as e:
    self.check_in_records()
    self.reconnect()
    self.start_job()

Cancelling future is not necessary and as far as I can tell has no effect. This is different from the referenced answer which specifically reacts to KeyboardInterrupt, special because it is raised by asyncio itself. KeyboardInterrupt can be propagated by run_until_complete without the future having actually completed. Handling Ctrl-C correctly in asyncio is very hard or even impossible (see here for details), but fortunately the question is not about Ctrl-C at all, it is about exceptions raised by the coroutine. (Note that KeyboardInterrupt doesn't inherit from Exception, so in case of Ctrl-C the except body won't even execute.)

I was canceling the future because in this instance there are remaining tasks pending and i want to essentially remove those tasks and start a fresh event loop.

This is a correct thing to want to do, but the code in the (updated) question is only canceling a single future, the one already passed to run_until_complete. Recall that a future is a placeholder for a result value that will be provided at a later point. Once the value is provided, it can be retrieved by calling future.result(). If the "value" of the future is an exception, future.result() will raise that exception. run_until_complete has the contract that it will run the event loop for as long as it takes for the given future to produce a value, and then it returns that value. If the "value" is in fact an exception to raise, then run_until_complete will re-raise it. For example:
loop = asyncio.get_event_loop()
fut = loop.create_future()
loop.call_soon(fut.set_exception, ZeroDivisionError)
# raises ZeroDivisionError, as that is the future's result,
# manually set
loop.run_until_complete(fut)

When the future in question is in fact a Task, an asyncio-specific object that wraps a coroutine into a Future, the result of such future is the object returned by the coroutine. If the coroutine raises an exception, then retrieving the result will re-raise it, and so will run_until_complete:
async def fail():
    1/0

loop = asyncio.get_event_loop()
fut = loop.create_task(fail())
# raises ZeroDivisionError, as that is the future's result,
# because the coroutine raises it
loop.run_until_complete(fut)

When dealing with a task, run_until_complete finishing means that the coroutine has finished as well, having either returned a value or raised an exception, as determined by run_until_complete returning or raising.
On the other hand, cancelling a task works by arranging for the task to be resumed and the await expression that suspended it to raise CancelledError. Unless the task specifically catches and suppresses this exception (which well-behaved asyncio code is not supposed to do), the task will stop executing and the CancelledError will become its result. However, if the coroutine is already finished when cancel() is called, then cancel() cannot do anything because there is no pending await to inject CancelledError into.

A: I got the same error below:

RuntimeError: Cannot close a running event loop

When I called loop.close() in test() as shown below:
import asyncio

async def test(loop):
    print("Test")
    loop.stop()
    loop.close() # Here

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

loop.create_task(test(loop))

loop.run_forever()

So, I used loop.close() after loop.run_forever() with try: and finally: as shown below, then the error was solved:
import asyncio

async def test(loop):
    print("Test")
    loop.stop()

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)

loop.create_task(test(loop))

try:
    loop.run_forever()
finally:
    loop.close() # Here


text:
Q: BuildFire: How do we access the public logs? We are pushing logs using "buildfire.publicData.insert".  How do we get access to those logs?
Would these logs contain the header that is sent in the calls?  We also need to see the source and destination information.  Those are the logs we really need.

A: Public data is really just a data source, think of it as a database where the data you save in you can retrieve later.
So if you're using it to push logs you need to make sure that any needed information is in the body object are passed to save or insert calls. those can be retrieved later using search calls as documented in https://sdk.buildfire.com/docs/public-data
You can also implement the search only on the control side of your plugin if these data are not meant to be shared with widget users.
Since you might have a lot of records it is recommended you use  https://sdk.buildfire.com/docs/indexed-fields so your queries are efficient.


text:
Q: What URL do you pass to wp_remote_get to load the body of the current post's preview? In the code below, I'm attempting to get a reference to the body content of the current post's fully rendered preview...
$response = wp_remote_retrieve_body(wp_remote_get('http://localhost/mysite/test-post/?preview=true&preview_id=28&preview_nonce=640bc54ca4'));
$post->post_content =  $response;

I'm just sending it to $post->post_content so that I can easily see it.
Here's part of what it returns...

You do not have permission to preview drafts.

I'm logged in as the administrator, so obviously I'm calling the preview wrong. How can I pass the URL in wp_remote_get to obtain the body section of the preview stream?
When I use...
$post->post_content =  "
".$response['body']."
";

I get

<

A: The URL is okay, what you need to add are cookies that authenticate you as the user who is allowed to see the preview. That is basically sending headers. I would start with the HTTP API (Wordpress Codex) looking for a method to add additional HTTP headers and set your cookies.
Otherwise - because probably this is somewhat complicated - you could take a look inside the preview code so to see if you can provide a hook to control access to previews. If possible, you can add some secret parameter to the URL which would allow you to preview any page w/o the need of being logged in (and the need of a nonce as it needs to be provided for preview as well).
The result of either the first or the second approach is quite the same, the only difference would be how to trigger it.


text:
Q: Hide Progress Bar for Add-RdServer Im trying to hide the progress bar of Add-RdServer.
I have tried using both $ProgressPreference = 'SilentlyContinue' and $global:progressPreference = 'SilentlyContinue' but the progress bar still shows.
Does anyone know how to successfully hide it?
I am using Powershell 5.1


text:
Q: Python datetime difference between .localize and tzinfo Why do these two lines produce different results?
>>> import pytz
>>> from datetime import datetime

>>> local_tz = pytz.timezone("America/Los_Angeles")

>>> d1 = local_tz.localize(datetime(2015, 8, 1, 0, 0, 0, 0)) # line 1
>>> d2 = datetime(2015, 8, 1, 0, 0, 0, 0, local_tz) # line 2
>>> d1 == d2
False

What's the reason for the difference, and which should I use to localize a datetime?

A: When you create d2 = datetime(2015, 8, 1, 0, 0, 0, 0, local_tz), it does not handle daylight saving time (DST) correctly. local_tz.localize() does.
d1 is
>>> local_tz.localize(datetime(2015, 8, 1, 0, 0, 0, 0))
datetime.datetime(
    2015, 8, 1, 0, 0,
    tzinfo=<DstTzInfo 'America/Los_Angeles' PDT-1 day, 17:00:00 DST>
)

d2 is
>>> datetime(2015, 8, 1, 0, 0, 0, 0, local_tz)
datetime.datetime(
    2015, 8, 1, 0, 0,
    tzinfo=<DstTzInfo 'America/Los_Angeles' LMT-1 day, 16:07:00 STD>
)

You can see that they are not representing the same time.
d2 way is fine if you are going to work with UTC. UTC does not have daylight saving time (DST) transitions to deal with.
The correct way to handle timezone is to use local_tz.localize() to support daylight saving time (DST)
More information and additional examples can be found here:
http://pytz.sourceforge.net/#localized-times-and-date-arithmetic


text:
Q: Wordpress - WP_query sort with 2 diffrent values? I'm making a list of some posts, and I want to sort it by 2 Meta_values(dates) in ASC
So fx. if i have the dates below:
- 23-08-2016 -> 23-08-2016
- 23-08-2016 -> 22-08-2016
- 23-08-2016 -> 24-08-2016
- 22-08-2016 -> 24-08-2016

I want it to sort first by the first date, and then i want these sorted by the second, so i want the code above sorted like this:
- 22-08-2016 -> 24-08-2016
- 23-08-2016 -> 22-08-2016
- 23-08-2016 -> 23-08-2016
- 23-08-2016 -> 24-08-2016

Is there any way I can do this using a WP_query? or do I have to do something else?

A: You can set a secondary orderby like this:
$args = array(
    'orderby' => 'date1 date2',
    'order'   => 'ASC',
);
$query = new WP_Query( $args );

Display posts sorted by date1 with a fallback to post date2, in ascending order:


text:
Q: Kubernetes get nodeport mappings in a pod I'm migrating an application to Docker/Kubernetes. This application has 20+ well-known ports it needs to be accessed on. It needs to be accessed from outside the kubernetes cluster. For this, the application writes its public accessible IP to a database so the outside service knows how to access it. The IP is taken from the downward API (status.hostIP).
One solution is defining the well-known ports as (static) nodePorts in the service, but I don't want this, because it will limit the usability of the node: if another service has started and incidentally taken one of the known ports the application will not be able to start. Also, because Kubernetes opens the ports on all nodes in the cluster, I can only run 1 instance of the application per cluster.
Now I want to make the application aware of the port mappings done by the NodePort-service. How can this be done? As I don't see a hard link between the Service and the Statefulset object in Kubernetes.
Here is my (simplified) Kubernetes config:
apiVersion: v1
kind: Service
metadata:
  name: my-app-svc
  labels:
    app: my-app
spec:
  ports:
    - port: 6000
      targetPort: 6000
      protocol: TCP
      name: debug-port
    - port: 6789
      targetPort: 6789
      protocol: TCP
      name: traffic-port-1
  selector:
    app: my-app
  type: NodePort

---
apiVersion: apps/v1
kind: StatefulSet
metadata:
    name: my-app-sf
spec:
    serviceName: my-app-svc
    replicas: 1
    selector:
      matchLabels:
        app: my-app
    template:
      metadata:
        labels:
          app: my-app
      spec:
          containers:
            - name: my-app
              image: my-repo/myapp/my-app:latest
              imagePullPolicy: Always
              env:
                - name: K8S_ServiceAccountName
                  valueFrom:
                    fieldRef:
                      fieldPath: spec.serviceAccountName
                - name: K8S_ServerIP
                  valueFrom:
                    fieldRef:
                      fieldPath: status.hostIP
                - name: serverName
                  valueFrom:
                    fieldRef:
                      fieldPath: metadata.name
              ports:
              - name: debug
                containerPort: 6000
              - name: traffic1
                containerPort: 6789

A: This can be done with an initContainer.
You can define an initContainer to get the nodeport and save into a directory that shared with the container, then container can get the nodeport from that directory later, a simple demo like this:
apiVersion: v1
kind: Pod
metadata:
  name: my-app
spec:
  containers:
  - name: my-app
    image: busybox
    command: ["sh", "-c", "cat /data/port; while true; do sleep 3600; done"]
    volumeMounts:
    - name: config-data
      mountPath: /data
  initContainers:
  - name: config-data
    image: tutum/curl
    command: ["sh", "-c", "TOKEN=`cat /var/run/secrets/kubernetes.io/serviceaccount/token`; curl -kD - -H \"Authorization: Bearer $TOKEN\" https://kubernetes.default:443/api/v1/namespaces/test/services/app 2>/dev/null | grep nodePort | awk '{print $2}' > /data/port"]
    volumeMounts:
    - name: config-data
      mountPath: /data
  volumes:
  - name: config-data
    emptyDir: {}


text:
Q: how to use ngClass I want to change color of content to be red if element.maker == true else green
for this I did following but it only worked for first condition means red color appears but green can't

     {{element.price}}
     {{element.quantity}}
    {{element.price * element.quantity}}

A: This worked for me thanks all

       {{element.price}}
        {{element.quantity}}
       {{element.price * element.quantity}}

A: You can also write it like that:
...

A: you can use ngClass like this :

https://stackblitz.com/edit/angular-qhzwub?embed=1&file=src/app/app.component.html

A: @Muhammad Danish give a try to this,

     {{element.price}}
     {{element.quantity}}
    {{element.price * element.quantity}}

have a look here for more details about ngClass


text:
Q: Get all residential addresses within bounding box How can I get all the residential addresses within a bounding box?  I tried the query from this question (reproduced here):
way
  ["building"~"residential|house|terrace|detached|apartments"]
  ({{bbox}});
(._;>;);
out;

The bounding box is whatever that is visible in the map area.
Whatever map I try this out on in Overpass Turbo, nothing is returned.

A: "residential addresses" is not quite the same as "residential buildings" (which the other question was about).  Where I'd start is:

*

*Go to https://taginfo.openstreetmap.org , type"addr:street" in the search box and press enter.

*Click the "Overpass turbo" link.

*Zoom in

*Run Query

Be aware, though, that depending on where you're searching not everything may have street addresses added, and street addresses might be separate from buildings and from points of interest.