text:
Q: Word Sort function incorrect formatting and count I originally created a python word sort function that was meant to record all the words in a txt file and read back while counting the occurence of each word. This program worked correctly, I then sought out to modify this program to count only the top 20 words of a html file and read back the occurrence of only those top 20 words. However after working through the bugs it's not giving me the correct formatting and the correct count. I'm seeking a count that looks like this:

however my count appears as so:

and doesn't give the correct count. I've debugged all the errors however I don't understand what's occurring to cause this difference in output.
#Imports
import tkinter as tk
from tkinter import *
from tkinter import filedialog
from collections import Counter

#Functions
def countWords(s):
    signos = [',', '.', ';', ':']
    cleanstr = ''
    for letra in s.lower():
        if letra in signos:
            cleanstr += ''
        else:
            cleanstr += letra
    strlist = cleanstr.split(' ')
    return dict(Counter(strlist))

def open_file():
    text = mainWindow.e2.get()

    count = countWords(s)
    myLabel = Label(root, text=open_file)
    myLabel.pack()

#Graphics
fullString = ""
root = tk.Tk()
root.title("Count words")
root.geometry('400x400')
root.fileToRead = filedialog.askopenfilename(initialdir="c:/temp/", filetypes=(("HTML File", "*.html"),("All Files","*.*")), title = "choose a file.")
wordCount = {}
fileName = root.fileToRead.split('/')
fileName = fileName[len(fileName)-1]
label = tk.Label(root, text="Top 20 Words For: " + fileName + '\n' + fullString, foreground="black", font=("Times New Roman", 16))

#Background Image Label
#bg = PhotoImage(file = "./guibackground.gif")

# Show image using label
#label1 = Label( root, image = bg)
#label1.place(relx=0.5, rely=0.5, anchor=CENTER)

#Class Window
class Window:

     def __init__(self):

        self.root = tk.Tk()
        self.btn = tk.Button(text='Open File', command=self.open_file)
        self.btn.pack()
        self.btn = tk.Button(text='Exit', command=root.quit)
        self.btn.pack()
        self.lbl = tk.Label()
        self.lbl.pack()
        self.root.mainloop()

     def open_file(self):

        filename = filedialog.askopenfilename(initialdir='/', title='Select file', filetypes=(('html files','*.html'), ('all files','*.*')))
        with open(filename, 'r') as f:
            self.lbl.configure(text=f'{Counter(f.read().split())}')

     def word_count(self):

        sorted_wordCount = sorted(wordCount.items(), key = lambda kv:(kv[1], kv[0]), reverse=True)

        count = 1
        fullString = ""
        for item in sorted_wordCount:
            if count < 20:
                fullString = fullString + str(count) + ": "+ str(item) + '\n'
            elif count == 20:
                fullString = fullString + str(count) + ": " + str(item)
            else:
                break
                count = count + 1

        self.button = Button(root, text="Open File", command=open_file)
        self.button.pack()
        self.exit_button = Button(root, text="Exit", command=root.quit)
        self.exit_button.pack()

if __name__ == '__main__':

    mainWindow = Window()

root.mainloop()

I took out the gif image background in order to eliminate the error that would cause.

A: change self.lbl = tk.Label() to self.lbl = tk.Message(self.root). then use the following code:

class Window:

    def __init__(self):
      ...

    def open_file(self):

        filename = filedialog.askopenfilename(initialdir='/', title='Select file', filetypes=(('html files','*.html'), ('all files','*.*')))
        with open(filename, 'r') as f:
            self.lbl.configure(text=f'{self.formatFun(Counter(f.read().split()).most_common(20))}')

    def formatFun(self, var):
        string = "Top 20 words for: mathbeth.html \n"
        for index, item in enumerate(var, start=1):
            string += f'{index}: {item} \n'
        return string


text:
Q: Ordered sequences of edges such that vertices appear an even number of times Given an undirected graph with an edge set $E$, and where an edge is an unordered pair of vertices, how many ordered sequences of size $L$ of edges from $E$ exist such that all the vertices that are present in a sequence appear an even number of times?
For example $\{(x,y),(z,w),(x,y),(z,w)\}$ is a sequence of size $L=4$. The edges participating in the sequence are $(x,y)$ and $(z,w)$ and each of the vertices $x,y,z,w$ appears exactly twice.
I am particularly interested in edge sets of planar graphs (e.g., two-dimensional square or triangular lattices).

redpajama_set_name: RedPajamaStackExchange


text:
Q: highlight selected div when being used as radio button using css I was wondering if it was possible to highlight a div with just css when clicked (when div is a label for a radio button) here is my code:
<?php foreach ($images as $image) { ?>

        <input type="radio" name="id" value="<?php echo $image['id']; ?>" id="<?php echo $image['id']; ?>">
        <label for="<?php echo $image['id']; ?>">

                <input type="hidden" name="table" value="<?php echo $tableToDeleteFrom;?>"><img src="../images/thumbs/<?php echo $image['name']; ?>">

                <?php echo $image['desc']; ?>

<?php } ?>

the radio button is obviously currently hidden. the desired effect is to get the div ".delete"'s background to change when one is selected, then when a different one is selected, the new selection is highlighted and the old selection is no longer highlighted. Maybe jquery is the best solution, but I'd be interested to see if there was an easier solution with just css.

A: For example, background red
input:checked + label div.delete { background: red}

A: Use this selector to target the label :
input:checked + label{}

Be aware that it is not well supported in older browser.


text:
Q: 0-cycles with null augmentation are boundaries in convex spaces? Well as the title says I would like to know if given a convex space $ X $, a $0$-cycle (equivalently any $0$-chain, right?), such that its augmentation is null is a boundary? All this in singular homology. I think a cone construction would do the trick but I do not know how. May be the argument is simpler using the reduced homology.
Thanks for any help you could provide.

A: Path-connectedness of $X$ is sufficient here. You can choose any point $x_0$ in $X$, and for each point $x_i$ in your $0$-chain $c=\sum\eta_i x_i$ you can find a path $p_i:[0,1]→X$ from $x_0$ to $x_i$. Regarded as a singular $1$-simplex $p_i:[v_0v_1]\to X$ via the identification $0≘ v_0,\ 1≘v_1$ , it has boundary $p_i(1)-p_i(0)=x_i-x_0$. Then the sum $\sum η_ip_i$ has the boundary $c$ as all instances of $x_0$ cancel out since, by hypothesis, $\sum η_i=0.$


text:
Q: How to perform simple web service client with Ruby and Savon I'm trying to develop a simple example of a web service client in Ruby using Savon.
This is what I got so far:
class WebServiceController < ApplicationController
  def index
    puts "web_service: IN"
    client = Savon::Client.new do
      wsdl.document = "http://www.webservicex.com/CurrencyConvertor.asmx?wsdl"
    end
    response = client.request :conversion_rate do
      soap.body = {
        :from_currency => 'USD',
        :to_currency => 'EUR'
      }
    end
    puts response.to_hash;
    render :text => response.to_hash.to_s
  end
end

However, when I run that code I get:

uninitialized constant Savon::Client

I guess I have to add some reference to Savon? (I already installed the corresponding gem).
In addition: am I doing the right thing in that web service? Should it work?
Thank you for your time!

A: If this is a Rails 3 application, add this onto your Gemfile:
gem 'savon'

Then, run bundle install and restart your development server.

A: I suppose you've added
require 'savon'

somewhere in your file?


text:
Q: SQL complicated join I need to join the following 2 tables with the result below
this data is basically 2 tables that are joined on multi keys from both tables over some sort of group but i am drawing a blank as to how to accomplish this
I am using an Oracle database.
thanks

Table 1		Table 2

    Group
    Key

    A
    1

    A
    2

    B
    1

    B
    3

    C
    1

    C
    2

    C
    3

    D
    2

    D
    4

    Users
    Key

    U1
    1

    U2
    1

    U2
    3

    U3
    1

    U3
    2

    U3
    4

    U4
    1

    U4
    2

    U4
    3

    U4
    4

    U5
    1

    U5
    2

    U5
    4

    RESULT

    Users
    Groups

U1

U2	B

U3	A

U4	A, B, C, D

U5	A, D

A: Here's one way:
with grps as (select 'A' grp, 1 key from dual union all
              select 'A' grp, 2 key from dual union all
              select 'B' grp, 1 key from dual union all
              select 'B' grp, 3 key from dual union all
              select 'C' grp, 1 key from dual union all
              select 'C' grp, 2 key from dual union all
              select 'C' grp, 3 key from dual union all
              select 'D' grp, 2 key from dual union all
              select 'D' grp, 4 key from dual),
     usrs as (select 'U1' usr, 1 key from dual union all
              select 'U2' usr, 1 key from dual union all
              select 'U2' usr, 3 key from dual union all
              select 'U3' usr, 1 key from dual union all
              select 'U3' usr, 2 key from dual union all
              select 'U4' usr, 1 key from dual union all
              select 'U4' usr, 2 key from dual union all
              select 'U4' usr, 3 key from dual union all
              select 'U4' usr, 4 key from dual union all
              select 'U5' usr, 1 key from dual union all
              select 'U5' usr, 2 key from dual union all
              select 'U5' usr, 4 key from dual)
-- end of mimicking your tables; see SQL below
select usr,
       listagg(case when usr_grp_cnt = grp_cnt then grp end, ', ') within group (order by grp) grps
from   (select u.usr,
               g.grp,
               g.grp_cnt,
               count(g.key) usr_grp_cnt
        from   usrs u
               left outer join (select grp,
                                       key,
                                       count(*) over (partition by grp) grp_cnt
                                from   grps) g on (g.key = u.key)
        group by u.usr,
                 g.grp,
                 g.grp_cnt)
group by usr;

USR GRPS
--- ---------------
U1
U2  B
U3  A
U4  A, B, C, D
U5  A, D

This works by first finding the number of keys per group (assuming that is unique), then it does an outer join to the usrs "table" (here, it's a subquery defined in the WITH clause; google subquery factoring if you're not familiar with it. You presumably have a table that's the equivalent of this subquery, so you'd just use that in the main sql statement).
Next, we find the count of the keys per user per group, and then we can use that to work out which groups match, by checking that the user+group key count is the same as the group key count. Then we use the listagg function to aggregate that into a list.
N.B. I had to change the data for user U3, since originally, your data had the same keys as for user U5.


text:
Q: Tiles jsp page with other URL content I am working in Spring MVC project.For UI, I am using tiles framework.
Everything is going well till I am accessing all my jsp files.
Now I want to show a google webpage inside my bodyand keep header and footer as common.
I am using the following code to get but not able to get the google url in body tag. it shows the url text in that body.
<definition name="losmain" extends="baseLayout">

    <put-attribute name="title" value="title" />

    <put-attribute name="import"

        value="/views/los/dashboard_import.jsp" />

    <put-attribute name="body" value="http://google.co.in" />

</definition>

can anyone suggest a right way to get google url in body.

A: This is because of Google is restricting on loading its URL from third party's IP address.


text:
Q: virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference while login with facebook android firebase give me virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference runtime error while login in with facebook in android firebase app
Login activity
public class LoginActivity extends AppCompatActivity {

private EditText log_email, log_password;
private TextView new_account;
private Button google_signin, sign_up_phone,login;
private LoginButton facebook_login;
private String memail,mcurrentUserID,mpassword;

LocationManager locationManager;
String provider;

private static final int RC_SIGN_IN = 234;
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;

private static final String TAG = "signup";

GoogleSignInClient mGoogleSignInClient;

private FirebaseFirestore db = FirebaseFirestore.getInstance();

FirebaseAuth mAuth;

CallbackManager callbackManager;

private ProgressDialog loadingBar;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    log_email = findViewById(R.id.log_email);
    log_password = findViewById(R.id.log_pass);
    new_account = findViewById(R.id.new_account);
    login = findViewById(R.id.login);
    sign_up_phone = findViewById(R.id.sign_up_phone);
    facebook_login = findViewById(R.id.login_button);

   // printkey();

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    provider = locationManager.getBestProvider(new Criteria(), false);

    mAuth = FirebaseAuth.getInstance();
    callbackManager = CallbackManager.Factory.create();
    facebook_login.setReadPermissions("email", "public_profile");

    loadingBar = new ProgressDialog(this);

    login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
                loginuser();
        }
    });

    new_account.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent phoneLoginIntent = new Intent(LoginActivity.this, SignUpActivity.class);
            startActivity(phoneLoginIntent);
        }
    });

    sign_up_phone.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent phoneLoginIntent = new Intent(LoginActivity.this, phoneloginActivity.class);
            startActivity(phoneLoginIntent);
        }
    });

    GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
            .requestIdToken(getString(R.string.default_web_client_id))
            .requestEmail()
            .build();

    mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

    findViewById(R.id.google_sign).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            signInWithGoogle();
        }
    });

    facebook_login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            facebooklogin();
        }
    });
}

private void loginuser()
{
    memail  = log_email.getText().toString();
     mpassword = log_password.getText().toString();

    if (TextUtils.isEmpty(memail))
    {
        Toast.makeText(this, "Please enter email...", Toast.LENGTH_SHORT).show();
    }
    if (TextUtils.isEmpty(mpassword))
    {
        Toast.makeText(this, "Please enter password...", Toast.LENGTH_SHORT).show();
    }
    else
    {
        loadingBar.setTitle("Sign In");
        loadingBar.setMessage("Please wait....");
        loadingBar.setCanceledOnTouchOutside(true);
        loadingBar.show();

        mAuth.signInWithEmailAndPassword(memail, mpassword)
                .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task)
                    {
                        if (task.isSuccessful())
                        {
                            mcurrentUserID = mAuth.getCurrentUser().getUid();

                            Intent phoneLoginIntent = new Intent(LoginActivity.this, MapsActivity.class);
                            startActivity(phoneLoginIntent);
                            finish();
                            Toast.makeText(LoginActivity.this, "Logged in Successful...", Toast.LENGTH_SHORT).show();
                            loadingBar.dismiss();

                        }
                        else
                        {
                            String message = task.getException().toString();
                            Toast.makeText(LoginActivity.this, "Error : " + message, Toast.LENGTH_SHORT).show();
                            loadingBar.dismiss();
                        }

                    }
                });
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    callbackManager.onActivityResult(requestCode,resultCode,data);
    //if the requestCode is the Google Sign In code that we defined at starting
    if (requestCode == RC_SIGN_IN) {

        //Getting the GoogleSignIn Task
        Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
        try {
            //Google Sign In was successful, authenticate with Firebase
            GoogleSignInAccount account = task.getResult(ApiException.class);

            //authenticating with firebase
            firebaseAuthWithGoogle(account);
        } catch (ApiException e) {
            Toast.makeText(LoginActivity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
}

private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
    Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());

    //getting the auth credential
    AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);

    //Now using firebase we are signing in the user here
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (task.isSuccessful()) {
                        Log.d(TAG, "signInWithCredential:success");
                        FirebaseUser user = mAuth.getCurrentUser();

                        Toast.makeText(LoginActivity.this, "User Signed In", Toast.LENGTH_SHORT).show();
                    } else {
                        // If sign in fails, display a message to the user.
                        Log.w(TAG, "signInWithCredential:failure", task.getException());
                        Toast.makeText(LoginActivity.this, "Authentication failed.",
                                Toast.LENGTH_SHORT).show();

                    }

                    // ...
                }
            });
}

private void signInWithGoogle()
{
    //getting the google signin intent
    Intent signInIntent = mGoogleSignInClient.getSignInIntent();

    //starting the activity for result
    startActivityForResult(signInIntent, RC_SIGN_IN);
}

private void facebooklogin()
{
    facebook_login.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
        @Override
        public void onSuccess(LoginResult loginResult) {
            Log.d(TAG, "facebook:onSuccess:" + loginResult);
            handlerFacebookAccessToken(loginResult.getAccessToken());
        }

        @Override
        public void onCancel() {
            Log.d(TAG, "facebook:onCancel");
            // ...
        }

        @Override
        public void onError(FacebookException error) {
            Log.d(TAG, "facebook:onError", error);
            // ...
        }
    });
}

private void handlerFacebookAccessToken(AccessToken accessToken)
{
    AuthCredential credential = FacebookAuthProvider.getCredential(accessToken.getToken());
    mAuth.signInWithCredential(credential)
            .addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if(task.isSuccessful())
                    {
                        FirebaseUser my = mAuth.getCurrentUser();
                       // String email = my.getEmail();
                      //  Toast.makeText(LoginActivity.this,"you are login with "+email,Toast.LENGTH_SHORT).show();
                    }

                }
            });
}

}

manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".UI.LoginActivity"></activity>

    <meta-data android:name="com.facebook.sdk.ApplicationId"
        android:value="@string/facebook_app_id"/>

    <activity android:name="com.facebook.FacebookActivity"
        android:configChanges=
            "keyboard|keyboardHidden|screenLayout|screenSize|orientation"
        android:label="@string/app_name" />
    <activity
        android:name="com.facebook.CustomTabActivity"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <data android:scheme="@string/fb_login_protocol_scheme" />
        </intent-filter>
    </activity>

    <activity android:name=".UI.phoneloginActivity" />
    <!--
         The API key for Google Maps-based APIs is defined as a string resource.
         (See the file "res/values/google_maps_api.xml").
         Note that the API key is linked to the encryption key used to sign the APK.
         You need a different API key for each encryption key, including the release key that is used to
         sign the APK for publishing.
         You can define the keys for the debug and release targets in src/debug/ and src/release/.
    -->
    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="AIzaSyBmO98uCPTg3R6yfOBXS8A6WuxK5c_aAzo" />
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <activity
        android:name=".UI.MapsActivity"
        android:label="@string/title_activity_maps" />
    <activity android:name=".UI.SignUpActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

i put facebook app id in manifest give haskey in facebook developer,enable facebook auth. give app id and give app secret key, and also put oAuth redirect uri in facebook developer but still show me this error while loginactivity open
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.geofensenearbyuser, PID: 9373
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.geofensenearbyuser/com.example.geofensenearbyuser.UI.LoginActivity}: android.view.InflateException: Binary XML file line #10: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference


text:
Q: How to create a timeseries starting "2000-01-01" and 10 weekends(saturdays) after that having random numbers as values.(in Python)? rnge = pd.date_range(start = "2000-01-01" ,periods =14 , freq = "D")
rnge

I want saturdays to be excluded.

A: dates = pd.date_range('2000-01-01', periods=10, freq='W-SAT')
# Create a list of random numbers
values = np.random.randint(0, 10, size=10)

df = pd.Series(values, index=dates)
print(df)

Output:
2000-01-01    7
2000-01-08    0
2000-01-15    8
2000-01-22    1
2000-01-29    5
2000-02-05    3
2000-02-12    8
2000-02-19    7
2000-02-26    8
2000-03-04    4
Freq: W-SAT, dtype: int64

'W-SAT' means every Saturday. You can check date_range function here.
pandas.date_range — pandas 1.5.2 documentation

A: I'm not sure whether I understood the question (didn't get the part about random numbers).
If you just want to filter out Saturdays then it can be done like this:
rnge = pd.date_range(start="2000-01-01", periods=14, freq="D")
rnge = rnge[rnge.weekday != 5]

Result:
DatetimeIndex(['2000-01-02', '2000-01-03', '2000-01-04', '2000-01-05',
               '2000-01-06', '2000-01-07', '2000-01-09', '2000-01-10',
               '2000-01-11', '2000-01-12', '2000-01-13', '2000-01-14'],
              dtype='datetime64[ns]', freq=None)


text:
Q: wp_list_categories() - display first level categories and only current term's children in subcategory page I'm using WordPress.
Have multiple categories with its subcategories. In general page, I'm displaying all first level categories. Here is my code:
$args = array(
   'type' => 'product-items',
   'child_of'  => 0,
   'parent'  => '',
   'order' => 'DESC',
   'hide_empty' => 0,
   'hierarchical' => 1,
   'exclude' => '',
   'include' => '',
   'number' => '',
   'taxonomy' => 'product-category',
   'pad_counts' => false,
   'depth' => 1,
   'title_li' => ''
);
wp_list_categories($args);

Once you click and go inside a first level category, you need to see only its subcategories there. When I'm removing 'depth' => 1, option, all children appear under their parent category but for page speed/load, in sub page I need to show all first-level categories, but only current category's children.
For example, I have below 3 categories:

*

*Category 1

*Category 2

*Category 3

Imagine I click on "Category 1". Now it is like this:

*

*Category 1

*

*1st Sub Category of 1

*2nd Sub Category of 1

*3rd Sub Category of 1

*Category 2

*

*1st Sub Category of 2

*

*1st sub of 2nd category sub

*2nd sub of 2nd category sub

*3rd sub of 2nd category sub

*2nd Sub Category of 2

*3rd Sub Category of 2

*Category 3

*

*1st Sub Category of 3

*2nd Sub Category of 3

*3rd Sub Category of 3

But I need it to be like this in sub page:

*

*Category 1

*

*1st Sub Category of 1

*2nd Sub Category of 1

*3rd Sub Category of 1

*Category 2

*Category 3

Not sure how to achieve this with wp_list_categories() function. Any ideas please?

A: It would be better if you use 2 get_terms() instead of wp_list_categories. It would be faster and customizable. One for parent categories, another one for children of current category. Here is working example:
   function display_cats($cats,$current=0,$current_children=array()){
    $ret= '
';
    foreach ($cats as $cs){
      $children=($current!=$cs->term_id)?'':display_cats($current_children);
      $ret.= '
 term_id).'"> '.$cs->name.' '.$children.'

      ';
    }
    $ret.= '
';
    return $ret;
  }

  $current_cat=9;//for example
  $parents=get_terms('product_cat',array('taxonomy'=>'product_cat','echo'=>false,'depth'=>0));
  $current_children=get_terms('product_cat',array('taxonomy'=>'product_cat','child_of'=>  $current_cat ,'echo'=>false));
  echo display_cats($parents,$current_cat,$current_children);

A: For anyone who still needs help, here's how to do it.
$category = get_queried_object();
$category_id = $category->term_id;

From this we will get the current category id and we need to pass it to the array.
'child_of'  => $category_id,

This will get you all the subcategories of the current category.
Hope this is helpful.

A: I'd take the get_terms() path.
Something such as
$terms = get_terms($args);

foreach($terms as $term){
   // If $term is current term use get_terms() again to fetch its children
}

https://developer.wordpress.org/reference/functions/get_terms/


text:
Q: Is there any way to use bcrypt "hashing" in PHP 5.2? I'm running a website with password hashing, but I think the current algorithm is insufficient. I tried to use PHP's crypt() with the blowfish option, but my PHP version is only 5.2 so CRYPT_BLOWFISH is not enabled.
I've seen 3rd party libraries that can encrypt via Blowfish, but none that do the full Bcrypt hashing. Is there any PHP library you know of that has bcrypt hashing without use of the crypt() function? Or, even better, any method of feeding a 3rd party blowfish encryption algorithm into a 3rd party bcrypt hashing algorithm?
Just to clarify, I am not able to install a newer version of PHP, as I'm on shared hosting.
I would really appreciate any suggestions! Thanks!

A: If you can install the Suhosin extension, bcrypt will work with Blowfish. (You don't need to recompile PHP, the extension is enough.)
On Ubuntu, you install it like this:
sudo apt-get install php5-suhosin

A: Thanks everyone for your answers, but to make things easier for now I've decided to just get the PECL perl package and use Crypt:Eksblowfish.


text:
Q: I cannot stretch the height of the titleView in the UINavigationBar This is my code:
class UINavigationControllerCustom : UINavigationController {

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews();
        navigationBar.frame = CGRect(x: 0, y: 0, width: view.frame.width, height: 120);
    }
}

class PreferenceInput: UIViewController {

    override func viewDidLoad() {

        let l1 = UILabel()
        l1.backgroundColor = .clear
        l1.numberOfLines = 1
        l1.font = UIFont.boldSystemFont(ofSize: 30.0)
        l1.textAlignment = .left
        l1.textColor = .black
        l1.text = "Bold title"
        l1.sizeToFit();

        let l2 = UILabel()
        l2.backgroundColor = .clear
        l2.numberOfLines = 2
        l2.font = UIFont.boldSystemFont(ofSize: 16.0)
        l2.textAlignment = .left
        l2.textColor = .darkGray;
        l2.text = "This is a\nmultiline string for the navBar"
        l2.sizeToFit();

        let tView = UIStackView(arrangedSubviews: [l1,l2]);
        tView.axis = .vertical;

        let spacer = UIView()
        let constraint = spacer.widthAnchor.constraint(greaterThanOrEqualToConstant: CGFloat.greatestFiniteMagnitude)
        constraint.isActive = true
        constraint.priority = .defaultLow

        let stack = UIStackView(arrangedSubviews: [tView, spacer])
        stack.axis = .horizontal

        navigationItem.titleView = stack
        navigationItem.titleView.sizeToFit();
    }
}

And this is what I get:

I can set the height of the navigation bar but how and where should I set the constraint to stretch the height in respect of the given 120px of the custom navigation controller?
I want to provide an individual height of the navigation bar.


text:
Q: How to maintain position of list view row/item? I have a custom ListView containing TextView, ImageView, Checkbox. In the ListView, nothing should be checked/unchecked as I have to block it based on conditions.
Tasks I am doing:

*

*If Checkbox is checked then it should show image in ImageView.

*I don't want to make CheckBox checkable/enabled based on conditions.
Below is my code for Custom Adapter.
    public class CustomAdapter  extends BaseAdapter {

        private Context context;
        private ArrayList<POJO> mainDataList;
        private LayoutInflater inflater = null;

        public CustomAdapter(Context context, ArrayList< POJO > mainDataList) {
            this.context = context;
            this.mainDataList = mainDataList;
            inflater = ( LayoutInflater ) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return mainDataList.size();
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public POJO getItem(int position) {
            // TODO Auto-generated method stub
            return mainDataList.get(position);
        }

        public class Holder
        {
            private TextView name;
            private ImageView imageView;
            private CheckBox check;
        }

        @Override
        public View getView(final int position, View view, ViewGroup parent) {
            // TODO Auto-generated method stub
            final Holder holder;
            if (view == null) {
                holder = new Holder();
                view = inflater.inflate(R.layout.my_layout_file, null);
                holder.name = (TextView) view.findViewById(R.id.textView_Name);
                holder.imageView = (ImageView) view.findViewById(R.id.img);
                holder.check = (CheckBox) view.findViewById(R.id.checkBox);

                view.setTag(holder);
            } else {
                holder = (Holder) view.getTag();
            }

            holder.check.setTag(position);

            if (mainDataList.get(position).isEditable()) {
                    holder.check.setEnabled(false);
                    holder.check.setClickable(false);
                } else {
                    holder.check.setEnabled(true);
                    holder.check.setClickable(true);
                }
            }

            holder.name.setText(mainDataList.get(position).getName());
            holder.check.setChecked(mainDataList.get(position).isSelected());

            if (mainDataList.get(position).isSelected())
                        holder.imageView.setImageResource(R.drawable.ic_launcher);
            else
                holder.imageView.setImageResource(null);

            return view;
        }
    }

My problems are:

*

*On scroll, ImageView shows images randomly irrespective of TRUE condition.

*On scroll, after every 4-5 list items/rows item get non-checkable (my device shows 4-5 cells/rows/items on screen without scroll) as Item 1 is non-checkable. Simply, it retrieves as per getView() mechanism.
I know this is the problem of maintaining list item position or ListView's recycling on scroll. How to do this?

A: You have a condition such as:
if (mainDataList.get(position).isSelected())
           holder.imageView.setImageResource(R.drawable.ic_launcher);

which means that if the model has its property selected to true it will set some image resource to the image view. The problem lies beneath the fact, whenever you scroll and isSelected() yields false, you do not do anything. Because you are re-using the views, you are getting some old views which at some point have had the isSelected() to true. It might be currently false, but you haven't specified any condition for that.
My suggestion is that you do something in the terms of:
if (mainDataList.get(position).isSelected())
{
    holder.imageView.setImageResource(R.drawable.ic_launcher);
}
else
{
    holder.imageView.setImageResource(null);
}


text:
Q: Mongoose Model.find() parameter issue I'm working on a node app (with IOS front end) right now and stumbled upon this issue. I used mongodb together with mongoose. I have this route, /get that receives the correct user id and tries to find all 'Voots' with that same user id. This is what a 'Voot' looks like:
{
"_id": "59db9fa2659bb30004899f05",
"title": "Pizza!",
"body": "hoppakeeee",
"user": {
  "__v": 0,
  "password": "$2a$10$Rwb5n7QoKaFaAOW37V0aWeEeYgfn6Uql474ynUXb83lHi7H2CuB1u",
  "email": "noelle.schrikker@planet.nl",
  "name": "Noelle Schrikker",
  "_id": "59db9ecf659bb30004899f04"
},
"__v": 0,
"downVotes": [],
"upVotes": []

},
As you can see, it has a property called user which is a user object containing a name, email, password and _id.
I do this with my request:
// Send all voots from the specific user
        Voot.find({"user._id": userId}, function(err, voots) {
            if (err) {
                console.log(err);
                res.status(400).send(err)
                res.end()
            }

            if (voots) {
                res.status(200).send(voots)
                res.end()
            }
        })

I try to find all voots with their user having the property of userId (this is the correct user ID). However, this doesn't work. I tried finding it by "user.email" which does work. I think it has something to do with the _ before id. Any comment is appreciated!
Voot shema:
var vootSchema = new mongoose.Schema({
    title: String,
    body: String,
    user: {
        type: mongoose.Schema.Types,
        ref: 'user'
    },
    upVotes: [String],
    downVotes: [String]
})

var Voot = mongoose.model('voot', vootSchema)

Userschema:
var userSchema = new mongoose.Schema({
    name: String,
    email: String,
    password: String
})

var User = mongoose.model('user', userSchema)

A: I would assume that _id of user object is not a string. That said you need to modify your query to use ObjectId instead of string:
     Voot.find({"user._id": ObjectId(userId)}, function(err, voots) {
        if (err) {
            console.log(err);
            res.status(400).send(err)
            res.end()
        }

        if (voots) {
            res.status(200).send(voots)
            res.end()
        }
     })

If you don't want to change your query, you could change your user schema, so that _id is string. Then your query should start working:
var userSchema = new mongoose.Schema({
    _id: { type: String },
    name: String,
    email: String,
    password: String
})

var User = mongoose.model('user', userSchema)

A: Use just user in your query rather than user._id:
Voot.find({ "user": userId }, function(err, voots) {
  // Callback code
})

The id or the referenced user is stored in the user field. The user sub-document, and therefore the user._id field, will only be available after population.

A: Got it! I added .ObjectId in the Voot schema, now I can access the User object using population. I can now find the Voot by using:
Voot.find({"user": userId}).populate('user') .exec()

Thanks for all the answers!


text:
Q: I can't make word files using my powershell script via PHP So to summarize the problem, I have a powershell script that executes word and produces a word file (alongside a pdf version of it but it doesn't really change anything).
if I launch it with my PC's shell, it works fine and creates everything. but if I launch it from my php page via shell_exec, everything is done except the creation of the word files.
var_dump(shell_exec('powershell -executionpolicy bypass -NoProfile -File C:\wamp64\www\test\a\Add-ADUserENSG1.ps1 -Prenom "'.$prenom.'" -NomFamille "'.$nom.'" -Description "'.$desc.'" -Type "'.$type));

as expected, the script is executed producing a new user and a password but doesn't produce the word files.
I really don't know why.
thank you for helping!

A: So I tried many things and it didn't solve the problem.
So I tried to change my local server from WAMP to XAMPP and... it worked!
Now everything is executed as it should be.
Don't ask me why I don't know.
Anyway, thank you for your help folks!


text:
Q: Where/How would I change to Autoplay? Im researching into WebAudio API and HTML5/Javascript as a learning process, i've looked into the code of some peoples project to try and break it down as a kind of learning curve but something is puzzling me. The code below is some JS of Audio on a play/stop button along with a LOWPASS filter and Quality slider, how would this be changed to Autoplay instead of the play/stop button?
Its confusing me like crazy.
var QUAL_MUL = 30;

function FilterSample() {
  this.isPlaying = false;
  loadSounds(this, {buffer: '02.mp3'});
};

FilterSample.prototype.play = function() {
  // Create the source.
  var source = context.createBufferSource();
  source.buffer = this.buffer;
  // Create the filter.
  var filter = context.createBiquadFilter();
  filter.type = filter.LOWPASS;
  filter.frequency.value = 5000;
  // Connect source to filter, filter to destination.
  source.connect(filter);
  filter.connect(context.destination);
  // Play!
  source.start(0);
  source.loop = true;
  //!-- THIS DOESN'T WORK source.autoplay = true;
  // Save source and filterNode for later access.
  this.source = source;
  this.filter = filter;
};

// PAUSE Button Function
  FilterSample.prototype.stop = function() {
  this.source.stop(0);
 };

// Play Button Toggle Function
FilterSample.prototype.toggle = function() {
  this.isPlaying ? this.stop() : this.play();
  this.isPlaying = !this.isPlaying;
};

FilterSample.prototype.changeFrequency = function(element) {

  var minValue = 40;
  var maxValue = context.sampleRate / 2;

  var numberOfOctaves = Math.log(maxValue / minValue) / Math.LN2;

  var multiplier = Math.pow(2, numberOfOctaves * (element.value - 1.0));

  this.filter.frequency.value = maxValue * multiplier;
};

FilterSample.prototype.changeQuality = function(element) {
  this.filter.Q.value = element.value * QUAL_MUL;
};

FilterSample.prototype.toggleFilter = function(element) {
  this.source.disconnect(0);
  this.filter.disconnect(0);

  if (element.checked) {

    this.source.connect(this.filter);
    this.filter.connect(context.destination);
  } else {

    this.source.connect(context.destination);
  }
};

Cheers in advance if you can help me understand this

A: You need to modify loadSounds to accept a callback function that gets executed when all the sounds have been fetched/loaded/whatever.
Then just change your constructor to:
function FilterSample() {
  this.isPlaying = false;
  loadSounds(this, {buffer: '02.mp3'}, function() {
    this.play();
  }.bind(this));
};


text:
Q: Hashmap in each mapper should be used in a single reducer In one of my class im using HashMap.Im calling that class inside my mapper. So now each mapper has its own HashMap. Now can i use all the HashMaps into a single reducer? Actually my HashMap contains Key as my filename and value is the Set.So each HashMap contains a filename and a Set. Now i want to use all the HashMap caontaining same filename and want to club all the values(Sets) and then write that HashMap into my Hdfs file

A: Yes you can do that. If your mapper is giving an output in the form of hashmap then you can use Hadoop's MapWritable as your value of mapper.
For e.g.
public class MyMapper extends Mapper<LongWritable, Text, Text, MapWritable>

you have to convert your Hashmap into MapWritable format:
MapWritable mapWritable = new MapWritable();
for (Map.Entry<String,String> entry : yourHashMap.entrySet()) {
    if(null != entry.getKey() && null != entry.getValue()){
       mapWritable.put(new Text(entry.getKey()),new Text(entry.getValue()));
    }
}

Then provide the mapwritable to your context:
ctx.write(new Text("my_key",mapWritable);

For Reducer class you have take MapWritable as your input value
public class MyReducer extends Reducer<Text, MapWritable, Text, Text>

public void reduce(Text key, Iterable<MapWritable> values, Context ctx) throws IOException, InterruptedException

Then iterate through the map and extract the values the way you want. For e.g:
for (MapWritable entry : values) {
  for (Entry<Writable, Writable> extractData: entry.entrySet()) {
      //your logic for the data will go here.
   }
}


text:
Q: Get input approver user name in Jenkins Workflow plugin I am trying to get userid who approved an "input" step in workflow jenkins groovy script. Below is the sample script
node('node1'){
    stage "test"

    input  message: 'test'
}

In the workflow UI if a person hits "thumbs up" I want to print his userid in the log. I dont see any option to do it.
def cause = currentBuild.rawBuild.getCause(Cause.UserIdCause)
cause.userId

will print the person who started the build. I have googled this for days but i am not finding anything. Any help here will be greatly appreciated :)

A: This Jira issue describes how this is likely to work going forward, however it is still open.
In the meantime, the approach of getting the latest ApproverAction via the build actions API was suggested on #Jenkins IRC recently and should work, note it's not sandbox safe.
Something along the lines of the below for getting the most recent approver:
@NonCPS
def getLatestApprover() {
   def latest = null

   // this returns a CopyOnWriteArrayList, safe for iteration
   def acts = currentBuild.rawBuild.getAllActions()
   for (act in acts) {
       if (act instanceof org.jenkinsci.plugins.workflow.support.steps.input.ApproverAction) {
           latest = act.userId
       }
   }
   return latest
}

A: The JIRA incident referenced u-phoria has been resolved and the fix released.
By setting the submitterParameter to a value, the variable specified by submitterParameter will be populated with the Jenkins user ID that responded to the input field.


text:
Q: I have to write logfile to trace init sequence from my simulator application So, I dont have much idea about logfile and i need to write a logfile using fprintf between  BlueModPlusS50::Send and BlueModPlusS50::Receive as you can check in the code, so that it can trace init, scan and print sequences from the simulator application that i use. So please help me to understand what it actually means and how to do that. Even if there are different versions of your understanding, you may let me know. I am using Visual Studio 2019.
void BlueModPlusS50::Send(std::shared_ptr< Message > msg, const ms timeout) {
#ifdef SIMULATION
DWORD BytesWritten = 0;
printf(">>>>>>%s<<<<<<", msg->GetPayload());
bool Status = WriteFile(com_handle_,             // Handle to the Serialport
                        msg->GetPayload(),     // Data to be written to the port
                        msg->GetSize(),        // No of bytes to write into the port
                        &BytesWritten,         // No of bytes written to the port
                        NULL);
if (Status == FALSE) {
  printf_s("\nFail to Written");
}
#endif  // SIMULATION
}

void BlueModPlusS50::Receive(std::shared_ptr<Message> msg) {
#ifdef SIMULATION
DWORD NoBytesRead;  // Bytes read by ReadFile()
char ReadData;      // temporary Character
unsigned char received = 0;
auto payload = msg->GetPayload();
do {
  bool Status = ReadFile(com_handle_, &ReadData, sizeof(ReadData), &NoBytesRead, NULL);
  if (NoBytesRead > 0) {
    payload[received] = ReadData;
    printf("%c", ReadData);
    ++received;
  }
} while (received < msg->GetSize());
msg->SetSize(received);


text:
Q: Saving an explicit entity through Entity Framework Let's say I'm reading data from an Excel file and I need to save this using EF. After reading excel, I construct an entity of type in my EF model - say Holiday.
Chance is that this particular holiday already exist in my DB or may not. I can't know it just by reading the Excel file. So, I check whether that entity exist, if so I have to modify the existing entity or add a new entity.
Following is how I'm handling the logic.
 foreach (var holiday in clientDataObj.Holidays)
 {
     // to check for existing holidays, no need to consider the location, as all holidays will anyway exist at root level.
     Holiday existingHoliday =
                ClientContext.Holidays.SingleOrDefault(h => string.Equals(h.Date, holiday.Date));

     if (existingHoliday == null)
     {
         rootLocation.Holidays.Add(holiday);
     }
     else
     {
         holiday.HolidayId = existingHoliday.HolidayId;
         ClientContext.Entry(existingHoliday).State = System.Data.Entity.EntityState.Detached;
         ClientContext.Entry(holiday).State = System.Data.Entity.EntityState.Modified;
     }
}

ClientContext.SaveChanges();

I haven't yet run the code to see if it's working. Can someone give an idea of whether this is the way to do it, or is there any other best practice in addressing this problem.

A: No, that won't work. Detaching an entity doesn't remove it, it just detaches from the context's tracking.
You need to remove it and add the new one:
ClientContext.Entry(existingHoliday).State = EntityState.Deleted;
ClientContext.Entry(holiday).State = EntityState.Added;

Also, in the event that there are two same holidays in the excel file, you may pass through one that you already added, so you need to check for that. Detaching here will work because you haven't called SaveChanges yet so the entity is not in the database yet:
if(ClientContext.Entry(existingHoliday).State == EntityState.Added)
   ClientContext.Entry(existingHoliday).State == EntityState.Detached;

I'm not sure about why you are adding them to rootLocation when they don't exist on the database, you should be adding them to the context if I follow your logic, so you may have this loop:
foreach (var holiday in clientDataObj.Holidays)
{
   Holiday existingHoliday =
                ClientContext.Holidays.SingleOrDefault(h => string.Equals(h.Date, holiday.Date));
   if (existingHoliday != null)
   {
      holiday.Id = existingHoliday.Id;
      ClientContext.Entry(existingHoliday).State =
                    ClientContext.Entry(existingHoliday).State == EntityState.Added
                             ? EntityState.Detached
                             : EntityState.Deleted;
   }
   ClientContext.Entry(holiday).State = System.Data.Entity.EntityState.Added;
}

Again, I'm not sure what rootLocation is so your logic might be different.
As a further optimization, if the holiday list is not too big, you should load it all on memory, instead of calling SingleOrDefault on every iteration, which will hit the database.
So have just a single hit to the database loading all of them (again, if there are not too many and memory is not a concern), and search in the client:
var allHolidays = ClientContext.Holidays.ToList();
foreach (var holiday in clientDataObj.Holidays)
{
   Holiday existingHoliday =
                allHolidays.SingleOrDefault(h => string.Equals(h.Date, holiday.Date));
   /* ... */
}

This should only hit the database once for querying
Note that if using both this method and the above, you'll need to add the new holidays to the list too, so that they get checked against, if the excel import may have duplicates. This is all unspecced in your question so check the specs.


text:
Q: How to set row back color on certain row in SlickGrid I want to color the first 3 rows in SlickGrid to Blue. I would like to know the easy way to do so.
I tried following code but it doesn't work:
data.getItemMetadata = function (index)
{
   if (index == 0 || index == 1 || index == 2)
   {
       return  {cssClasses: "BlueColor"};
   }
 }

A: You can use the following CSS:
.slick-row:nth-child(-n+3){
    /*BlueColor class contents, if you place it before the .even and .odd classes you will need :important*/
}


text:
Q: How to submit an exisitng object from the view via a from in Thymeleaf with Spring MVC? In my Thymeleaf view, I have some objects shown on the page:

Here's the HTML
<form method="post" action="#" th:action="@{/basket}" th:object="${itemOrder}">

            item title

item price

        <input type="hidden" th:field="*{sku}"/>

        <input type="submit" value="Add to basket" />

</form>

Item in the basket:

item price

Under each element, I have a form to submit this element to the controller.
All Thymeleaf and Spring MVC guides are showing how to submit a form when a user provides data through input fields. Here, I don't need to take in any data from the user, all the data is available already. I just need to wrap existing data and submit it with a form. How can I make it with Thymeleaf and Spring MVC?
Here's the BasketController that should handle the form reu
@PostMapping("/basket")
public String processItemOrder(@ModelAttribute ItemOrder itemOrder, Model model) {
    model.addAttribute("itemOrder", itemOrder);
    return "basket";
}


text:
Q: Binding data to a long list selector, C# WP8 I've got a database and am looking to list all the items found into a longlist selector, it currently works, however the it doesn't display the actual text, just the object reference:
   //this will return all the records found in file table
        var query = context.Files;

        //now execute the query
        fileList = new ObservableCollection<FileTable>(query);

        //set up list items.
        llsEachItem.ItemsSource = fileList;

The longlist selector then just displays The object reference, for each item not the actual data itself. In this case it displays a list of:
Project.Model.FileTable
Project.Model.FileTable
Project.Model.FileTable
Project.Model.FileTable
Project.Model.FileTable

How can I make it so that I can actually see the data itself? I've tried appending toString() to the fileList but that doesn't seem to work. Any suggestions?

A: Set DisplayMemberPath on list to the property name which you want to be shown in your list.
llsEachItem.ItemsSource = fileList;
llsEachItem.DisplayMemberPath = "PropertyName";


text:
Q: Panda print the mark if the name exists

Name
Mark

Ben
20

James
50

Jimmy
70

I have a dataframe which looks something like this. I wanna check if the name exists and then it will print the mark for that specific person.
if len(df[(df['Name'] == "James")]) != 0:
    print(len(df["Mark"]))

Above is my code. Hope to get some advise!

A: You can return the mark of a specified name in your Name column using loc. The below will print the Mark of the name you pass, and will return an empty series if the name does not exist in your Name column:
name_to_retrieve_mark = 'Ben'
df.loc[df.Name.eq(name_to_retrieve_mark),'Mark']

Out[13]:
0    20
Name: Mark, dtype: int64

name_to_retrieve_mark = 'Sophocles'
df.loc[df.Name.eq(name_to_retrieve_mark),'Mark']

Out[15]: Series([], Name: Mark, dtype: int64)

A: Better use a Series here with get with a default argument:
marks = df.set_index('Name')['Mark']

marks.get('James', 'missing')
# 50

marks.get('Nonexistent', 'missing')
# missing

Or without default, get returns None:
marks.get('Nonexistent') # no output


text:
Q: Jquery Swipe for Pagination in Gallery I have successfully implemented swipe features for slideshows on other websites (using jquery.touchwipe.1.1.1), but now I am being asked if I can do it with a gallery that automatically creates pagination results based on the amount of posts per page (WordPress).
Before I start tinkering with it, I was wondering if it was possible? Rather than clicking on the pagination circles - the client wants to be able to touch swipe through the gallery pages (and possibly once the images open in lightbox).
The site is http://markreeder.ca
I am comfortable editing php and digging through the code, but I am definitely not as versed in it as most of the people on this site. Any direction would be appreciated as the only time I have to work on this is after hours while my son sleeps.
Here is the code for the pagination at the bottom of the page:

Could I find a way to use touchwipe in there?
Thank you in advance.


text:
Q: InsertCursor gets empty shapefile I want to insert rows which the field CNTY_NM meets the requirement. The code is OK for running, but the feature class only has the records but no geometry. What is wrong with my code?
import arcpy
import os

int_buffer_TXcounties = r'C:\Users\TL\Desktop\1216\buffer\int.shp'
inputfeatureclass = r'C:\Users\TL\Desktop\1212\TXCounty\TXCounty.shp'

#Create an empty featureclass by using inputfeatureclass as template
arcpy.CreateFeatureclass_management(out_path="C:/Users/TL/Desktop/1216/buffer", out_name="TC1", geometry_type="POLYGON", template="C:/Users/TL/Desktop/1216/buffer/TX_counties.shp", has_m="DISABLED", has_z="DISABLED", spatial_reference="GEOGCS['GCS_North_American_1983',DATUM['D_North_American_1983',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]];-400 -400 1000000000;-100000 10000;-100000 10000;8.98315284119521E-09;0.001;0.001;IsHighPrecision", config_keyword="", spatial_grid_1="0", spatial_grid_2="0", spatial_grid_3="0")
insertfeatureclass = r'C:\Users\TL\Desktop\1216\buffer\TC1.shp'

#get the counties names
counties_name = []
fields = ["CNTY_NM","CNTY_FIPS"]
with arcpy.da.SearchCursor(int_buffer_TXcounties, fields) as cursor:
    for row in cursor:
        print("{0}, {1}".format(row[0], row[1]))
        counties_name.append(row[0])

#Insert counties
for county in counties_name:
    print county
    expression = """"CNTY_NM" = '{0}'""".format(county)
    print expression
    with arcpy.da.InsertCursor(insertfeatureclass, '*') as i_cursor:
        with arcpy.da.SearchCursor(inputfeatureclass, '*', where_clause=expression) as s_cursor:
            for s_row in s_cursor:
                i_cursor.insertRow(s_row)

The following picture shows the records in the feature class. But when I used Zoom to Layer, I can't have any geometry.
I am using ArcGIS 10.3.1 Advanced License.

A: The 1st thing I see is you don't have a spatial index grid calculated in your CreateFeatureclass command....leave out those optional parameters to allow ArcGIS calculate a default index, so something like:
spatial_reference="GEOGCS['GCS_North_American_1983',DATUM['D_North_American_1983',SPHEROID['GRS_1980',6378137.0,298.257222101]],PRIMEM['Greenwich',0.0],UNIT['Degree',0.0174532925199433]];-400 -400 1000000000;-100000 10000;-100000 10000;8.98315284119521E-09;0.001;0.001;IsHighPrecision"
arcpy.CreateFeatureclass_management(out_path="C:/Users/TL/Desktop/1216/buffer", out_name="TC1", geometry_type="POLYGON", template="C:/Users/TL/Desktop/1216/buffer/TX_counties.shp", has_m="DISABLED", has_z="DISABLED", spatial_reference)

Edit:
By the way, if you don't want to modify any of your existing code, you should be able to run at the end of your script the command to add the spatial index (which can also update it if one is set inappropriately):
arcpy.AddSpatialIndex_management (insertfeatureclass)

...or, if you just want to do that part via Catalog, then see:
http://desktop.arcgis.com/en/arcmap/10.3/manage-data/shapefiles/modifying-indexes-in-shapefiles-by-updating-a-spatial-index.htm


text:
Q: dropdown menu behind carouFredSel slider I made some changes on one of my projects. I added a jQuery slideshow using carouFredSel plugin. But after that, all submenus of top menu bar are fallen behind the slideshow images.
I've applied z-index:1000 to all items inside top menu. But the problem did not solve.
Could you give me a solution to solve this problem?
URL: www.parniaweb.ir

A: When you apply z-index to the menu items, items become positioned in relation to the menu itself, not in relation to the overall layout. You need to position an item that is on the same or higher level in DOM hierarchy as the slider. I would suggest #top:
#top {
    position: relative;
    z-index: 2;
}


text:
Q: ProgressDialog not showing when adding views I am adding views dynamically to linear layout in a for loop of more than 100 loops.
Now what I want to show ProgressDialog while adding views. I added progressdialogue but it dismisses before views actually appear on the screen.
Is there any callback for views visible on screen
Here is my code
final ProgressDialog pd = new ProgressDialog(this);
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.show();

for (int i = 0; i < rowItemsListTemp.size(); i++) {
    View view;
    LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = inflater.inflate(R.layout.product_item_card, null);

    txt_pro_name = (TextView) view.findViewById(R.id.txt_pro_name);
    txt_pro_desc = (TextView) view.findViewById(R.id.txt_pro_desc);

    txt_pro_name.setText(rowItemsListTemp.get(i).getProName());
    txt_pro_desc.setText(Html.fromHtml(rowItemsListTemp.get(i).getProDesc()));
    ll_batcheslist.addView(view);
}

if (pd.isShowing()) {
    pd.dismiss();
}

A: You can try some other logic too, but one I can suggest is:
 for (int i = 0; i =< rowItemsListTemp.size(); i++) {

   if(i=rowItemsListTemp.size()){
      if (pd.isShowing()) {
         pd.dismiss();
      }
   }else{
    View view;
    LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    view = inflater.inflate(R.layout.product_item_card, null);

    txt_pro_name = (TextView) view.findViewById(R.id.txt_pro_name);
    txt_pro_desc = (TextView) view.findViewById(R.id.txt_pro_desc);

    txt_pro_name.setText(rowItemsListTemp.get(i).getProName());
    txt_pro_desc.setText(Html.fromHtml(rowItemsListTemp.get(i).getProDesc()));
    ll_batcheslist.addView(view);
   }

}

A: Put this at the end of your for loop,
if(i == rowItemsListTemp.size()-1){
       if (pd.isShowing()) {
          pd.dismiss();
       }
    }

However, this does not seem like a good implementation.

... in a for loop of more than 100 loops.


text:
Q: Least common integer java? How can I detect the opposite of mode in java?
For instance, if I wanted to find the least common number in an array of numbers, how would I go about doing that?
Thanks.
What I've tried:
public int getLeastCommonNum(int[] array)
{
int min = array[0];
int pos = 0;
for (int i = 1; i < array.length; i++)
{
    if (array[i] < min)
    {
    min = array[i];
    pos = i;
    }
}
return array[pos];
}

A: Here I propose a solution using HashMap:
public int getLeastCommonNum(int[] array)
{
    Map<Integer, Integer> occurrences = new HashMap<Integer, Integer> ();
    for (int num : array) {
       if (occurrences.containsKey(num)) {
           occurrences.put(num, occurrences.get(num) + 1);
       } else {
           occurrences.put(num, 1);
       }
    }
    int minOccurred = -1;
    int minOccurredCnt = -1;
    for (Map.Entry<Integer, Integer> occurrencesEntry : occurrences.entrySet()) {
        if (minOccurredCnt == -1 || minOccurredCnt > occurrencesEntry.getValue()) {
            minOccurredCnt = occurrencesEntry.getValue();
            minOccurred = occurrencesEntry.getKey();
        }
    }
    return minOccurred ;
}

I have coded everything by heart, so it might be that I have some small spelling mistake.

A: Based on Boris Strandjev version, but using Multiset for counting:
@Nullable
public Integer getLeastCommonNumV2(final int[] array)
{
    // step 1: count
    final Multiset<Integer> occurances = HashMultiset.create();
    for (final int num : array) {
        occurances.add(num);
    }

    // step 2: find least common
    Multiset.Entry<Integer> leastCommon = null;
    for (final Multiset.Entry<Integer> occurance : occurances.entrySet()) {
        if (leastCommon == null || occurance.getCount() < leastCommon.getCount()) {
            leastCommon = occurance;
        }
    }
    return leastCommon == null ? null : leastCommon.getElement();
}


text:
Q: Eclipse Automatically Download / Update JAR files I just created a Web App project from a repository through Eclipse's SVN support. What I would be doing is have an ANT build going and then finally deploy through Tomcat.
I am using Eclipse IDE for Java EE developers on an Ubuntu system.

There are a number of jar files needed
  to support my project - like Struts,
  Hibernate, etc. etc.

Do I need to

manually download each of them
and put them in the lib folder?

OR

Does Eclipse have a solution to
  automatically UPDATE these from the internet? Any plugins to automatically take care of this?

A: You should consider using Maven for your project. It's VERY well supported in Eclipse, and handles all dependencies (as well as other things, such as releases).
The problem is there's a bit of a learning curve, but if you intend your project to get to a considerable size, I'd say it's very important.
Maven has support for ant builds and most libraries are in the central Maven repository. You just say your project has a dependency on the external project and it will automatically download the dependencies.
http://maven.apache.org/


text:
Q: Oracle ORDS middle-tier scalability, as it ties to OCPU allocation on Oracle Autonomous DB I'm looking for any specific architecture information with regard to how the APEX ORDS middle-tier layer scales on an ADB implementation.  Specifically, as a factor of changing the OCPUs for the ADB, does that APEX ORDS middle-tier also scale as well?  Thanks for any insight.

A: There is no relation to the number of oCPUs on your Autonomous Database and the Oracle REST Data Services mid-tier deployments.
Each region has X ORDS nodes deployed, front-ended by a LoadBalancer.
Each of those X nodes will have a connection pool for each PDB, 100 connections each.
As demand increases in a region, the managed ORDS environment can quickly be increased by our DevOps team (either by button press or automation).
You can handle quite a few concurrent user requests if you have 300, 400, 500, 600, 700, even 1200 connections available.
If not, then you might consider:

*

*making sure your SQL and PL/SQL are optimal for HTTPS, i.e. making it FAST

*deploy a customer-managed instance of ORDS on your own tenancy compute node - you setup ORDS and give it as many resources as you want. Of course at this point, you're managing your mid-tier, not us.


text:
Q: Filter in Google sheets gives me blank if I select the whole column I have this formula that works pretty well.
=filter(RawData!A:A,RawData!F:F=D2)

If I drag the formula, it shows #N/A until the criteria returns a date. Example:
#N/A
#N/A
#N/A
2020-08-01
#N/A
#N/A

But I don't want to drag the cells, I want it to fill automatically, so I edited the last criteria like this:
=filter(RawData!A:A,RawData!F:F=D:D)

Without specifying the exact D column, it just gives me blank cells.
The strange thing is that I have a similar formula elsewhere and its working. Just different sheets but with the same kind of data.
Anyone knows what might be causing this?
https://docs.google.com/spreadsheets/d/1oj7LSbsRF_7HDEgcXsJw4xpOFKHhLBm6is9EVfqTqzw/edit?usp=sharing

A: When you use:
=filter(RawData!A:A,RawData!F:F=D2)

You are looking for any cell in RawData!F:F that matches D2; it's not required that this cell is on the same row. If, for example, RawData!F15 matches D2, RawData!A15 will be returned.
That is a far less restrictive filter than the one corresponding to:
=filter(RawData!A:A,RawData!F:F=D:D)

In this last case, the match should be found in a specific row. For example, RawData!F15 matching D2 will not cause RawData!A15 to be returned. Instead, F2 will be compared to D2, F3 to D3, and so on. And with your current data, there is no match to be found.
That's the reason the same formula "works" on B and not on C (there are matches to be found for =filter('Lead + source'!H:H,'Lead + source'!A:A=D:D), but not for =filter(RawData!A:A,RawData!F:F=D:D)).


text:
Q: WPF Bind c# class to static resource I have a xaml toolbar:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:logic="clr-namespace:DD.Logic;assembly=DD.Logic">

<ToolBar x:Key="MyToolbar" Height="120">
    <!--File-->
    <GroupBox Header="File" Style="{StaticResource ToolbarGroup}" Margin="5,3,3,3">
        <StackPanel Grid.Row="1" Orientation="Horizontal">
            <Button Margin="3" Width="55" Style="{StaticResource ToolBarButtonBaseStyle}"
                    Command="{x:Static ApplicationCommands.New}">
                <Button.Content>
                    <Grid>
                        <Grid.RowDefinitions>
                            <RowDefinition Height="4*"/>
                            <RowDefinition Height="1*"/>
                        </Grid.RowDefinitions>
                        <Image Source="Images/GenericDocument.png" Width="45"/>
                        <TextBlock Grid.Row="1" Text="New" VerticalAlignment="Bottom" HorizontalAlignment="Center"/>
                    </Grid>
                </Button.Content>
            </Button>
            <StackPanel Orientation="Vertical" Margin="0,2,0,2">
                <Button Margin="1" Padding="2" HorizontalContentAlignment="Left"
                        Style="{StaticResource ToolBarButtonBaseStyle}"
                        Command="{x:Static ApplicationCommands.Open}">
                    <Button.Content>
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition/>
                                <ColumnDefinition/>
                            </Grid.ColumnDefinitions>
                            <Image Source="Images/OpenFolder.png" Width="16"/>
                            <TextBlock Margin="3,0,3,0" Text="Open" VerticalAlignment="Center"  Grid.Column="1"/>
                        </Grid>
                    </Button.Content>
                </Button>
                <Button Margin="1" Padding="2" HorizontalContentAlignment="Left"
                        Style="{StaticResource ToolBarButtonBaseStyle}"
                        Command="{x:Static ApplicationCommands.Save}">
                    <Button.Content>
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition/>
                                <ColumnDefinition />
                            </Grid.ColumnDefinitions>
                            <Image Source="Images/Save.png" Width="16"/>
                            <TextBlock Margin="3,0,3,0" Text="Save" VerticalAlignment="Center" Grid.Column="1"/>
                        </Grid>
                    </Button.Content>
                </Button>
                <Button Margin="1" Padding="2" HorizontalContentAlignment="Left"
                        Style="{StaticResource ToolBarButtonBaseStyle}"
                        Command="{x:Static ApplicationCommands.Print}">
                    <Button.Content>
                        <Grid>
                            <Grid.ColumnDefinitions>
                                <ColumnDefinition/>
                                <ColumnDefinition />
                            </Grid.ColumnDefinitions>
                            <Image Source="Images/Print.png" Width="16"/>
                            <TextBlock Margin="3,0,3,0" Text="Print" VerticalAlignment="Center" Grid.Column="1"/>
                        </Grid>
                    </Button.Content>
                </Button>
            </StackPanel>
        </StackPanel>
    </GroupBox>

    <!--Format-->
    <GroupBox Header="Format" Style="{StaticResource ToolbarGroup}" Margin="3">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <Grid Row="0">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <TextBlock VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Column="0">Text font size:</TextBlock>
                <ComboBox VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Column="1"
                Height="20"
                Width="80"
                IsEditable="True"
                Loaded="{x:Static logic:ApplicationToolbar.RoutedEvent}"
                TextBoxBase.TextChanged="{x:Static logic:ApplicationToolbar.SelectionChangedEvent}"
            />
            </Grid>
            <Grid Row="1">
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition />
                </Grid.ColumnDefinitions>
                <TextBlock VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Column="0">Arrows:</TextBlock>
                <ComboBox VerticalAlignment="Center" HorizontalAlignment="Center" Grid.Column="1"
                          Name ="ArrowsCombobox"
                Height="20"
                Width="80"
                Loaded="{x:Static logic:ApplicationToolbar.ArrowsComboboxLoaded}"
                SelectionChanged="{x:Static logic:ApplicationToolbar.ArrowsComboboxSelectionChanged}"
            />
            </Grid>
        </Grid>
    </GroupBox>
</ToolBar>

Which is show in main window as:
<ContentControl  Content="{StaticResource MyToolbar}"/>

And a class that implements the corresponding commands and evenhandlers:
public class ApplicationToolbar : Control
{
    public static PathFinderType PathFinderType = PathFinderType.Straight;

    public static RoutedEventHandler RoutedEvent = LoadFontSizes;
    public static TextChangedEventHandler SelectionChangedEvent = FontSizeChanged;
    public static RoutedEventHandler ArrowsComboboxLoaded = ArrowsComboboxLoadedHandler;
    public static SelectionChangedEventHandler ArrowsComboboxSelectionChanged = ArrowsComboboxSelectionChangedHandler;

    public static RoutedCommand Group = new RoutedCommand();
    public static RoutedCommand Ungroup = new RoutedCommand();
    //etc
    public static RoutedCommand Redo = new RoutedCommand();
    private readonly IDesignerCommandsReceiver _receiver;

    public ApplicationToolbar()
    {
        var designer = FindChild<DesignerCanvas>(Application.Current.MainWindow, "DesignerCanvas");
        _receiver = new DesignerCommandsReceiver(designer);
        AddCommandBindings();
        AddCommandGestures();
    }
    private void AddCommandBindings()
    {
        CommandBindings.Add(new CommandBinding(ApplicationCommands.New, New_Executed));

        // some more bindings

        CommandBindings.Add(new CommandBinding(Redo, Redo_Executed, Redo_Enabled));
    }
    private static void AddCommandGestures()
    {
        SelectAll.InputGestures.Add(new KeyGesture(Key.A, ModifierKeys.Control));
        Undo.InputGestures.Add(new KeyGesture(Key.Z, ModifierKeys.Control));
        Redo.InputGestures.Add(new KeyGesture(Key.Y, ModifierKeys.Control));
    }
    private void New_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        _receiver.New();
    }

    // other commands implementations

    private void Redo_Enabled(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = StateSaver.Instance.IsRedoAvailable();
    }

    public static void ArrowsComboboxLoadedHandler(object sender, RoutedEventArgs e)
    {

    }
    private static void ArrowsComboboxSelectionChangedHandler(object sender, SelectionChangedEventArgs selectionChangedEventArgs)
    {

    }

    // other event handlers
}
public enum PathFinderType
{
    Straight,
    Ambient,
    Polygon
}

How do I bind this class to the xaml presentation? I tried to use ContentPresenter with specified DataContext, but it doesn't work:
<ContentPresenter Content="{StaticResource MyToolbar}" DataContext="{x:Type logic:ApplicationToolbar}"/>

Update
The ApplicationToolbar.xaml is now:
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                xmlns:logic="clr-namespace:DD.Logic;assembly=DD.Logic">
<ControlTemplate x:Key="MyToolbar">
    <ToolBar  Height="120">
//similar code
</ToolBar>
</ControlTemplate>

And it's printed out as:
<ContentPresenter>
        <ContentPresenter.Content>
            <logic:ApplicationToolbar />
        </ContentPresenter.Content>
        <ContentPresenter.ContentTemplate>
            <DataTemplate>
                <Control Template="{StaticResource MyToolbar}" />
            </DataTemplate>
        </ContentPresenter.ContentTemplate>
    </ContentPresenter>

Still haven't achieved commands to work <- The issue was solved by putting all commands related code back to designer class. I suppose that CommandBindings are supposed to be added to CommandBindingsCollection of designer object, and not application toolbar.

A: Try something like this:
<ContentPresenter>
    <ContentPresenter.Content>
        <logic:ApplicationToolbar />
    </ContentPresenter.Content>
    <ContentPresenter.ContentTemplate>
        <DataTemplate>
            <ContentControl Content="{StaticResource MyToolbar}" />
        </DataTemplate>
    </ContentPresenter.ContentTemplate>
</ContentPresenter>

The Content property of a ContentPresenter is supposed to be set to an instance of the DataContext/ViewModel and the ContentTemplate to a DataTemplate that defines the appearance of this object.


text:
Q: Using materialized views to improve jsonb indexing and querying Having an RDS Postgresql 12.5 and working on a table (app_events) with a JSONB column (metadata), the JSON data may vary based on the event name, see the structure below.
CREATE TABLE IF NOT EXISTS "public".app_events (
    id uuid DEFAULT uuid_generate_v4() NOT NULL,
    event_id text NOT NULL,
    name text NOT NULL,
    creation_time timestamp without time zone NOT NULL,
    creation_time_in_milliseconds bigint NOT NULL,
    metadata jsonb NOT NULL,
    PRIMARY KEY(id)
);

There are default indexes (btree) on event_id and name.
Based on the name column we create views to normalize the data from JSON into tabular format, an example is below.
CREATE OR REPLACE VIEW "public".charity_created AS
 SELECT app_events.id,
    app_events.event_id,
    app_events.name,
    app_events.creation_time,
    date(app_events.creation_time) AS created_date,
    (app_events.metadata ->> 'aggregateId'::text) AS user_id,
    (app_events.metadata ->> 'url'::text) AS url,
    (app_events.metadata ->> 'name'::text) AS charity_name,
    (app_events.metadata ->> 'about'::text) AS charity_about,
    (app_events.metadata ->> 'country'::text) AS country,
    (app_events.metadata ->> 'category'::text) AS category,
    (app_events.metadata ->> 'currencyCode'::text) AS currencycode,
    (app_events.metadata ->> 'isPayItForwardPartner'::text) AS is_pay_it_forward_partner,
    (app_events.metadata ->> 'isCampaignDonationPartner'::text) AS is_campaign_donation_partner
   FROM public.app_events
  WHERE (app_events.name = 'CharityCreated'::text)
  ORDER BY (date(app_events.creation_time)) DESC;

And now you can run queries like the below.
SELECT *
FROM "public".charity_created
WHERE charity_name == 'some_charity_name'

In addition, we create joins or unions between views and started noticing latency on reads/queries up to an hour sometimes, no timeouts but returning data can be challenging, definitely a big hit in our reporting team.
The question and knowledge I am looking for are, where can I create (or should create) indexes to improve the read latency; Debating with two findings so far.

*

*On the actual JSONB column (metadata) doesn't make sense, so maybe a solution is to start creating indexes based on the specific schema per event name like this answer

*Create materialized views and pay the price to refresh the copy of data (every night) while creating indexes on the materialized views, similar to this answer

*Maybe keep the views and create indexes on these

A: You can try to use indexes with expressions like:
CREATE INDEX app_events_charity_name_idx ON app_events USING(metadata ->> 'name'::text);

This index might be used when the expression is used (exactly) in the query, e.g.:
SELECT * FROM app_events WHERE metadata ->> 'name'::text = 'some charity';

This should work with your view as well. But you should check that with EXPLAIN.
In newer versions of Postgres there is also the possibility of generated columns. Compared to materialized views, these have the advantage that you do not have to worry about updating them.
ALTER TABLE app_events ADD charity_name TEXT GENERATED ALWAYS AS (metadata ->> 'name'::text);

You can create indexes for these columns as well.


text:
Q: How adding a field from a pulled mongodb document I am trying to use an api to get the current value of a stock and multiply by the users stock.
When I make a call the route I get empty data, and when I print the value of the callback I get an empty array
 function user_cur_portfolio(port, callback) {
  let portfolio = [];
  port.forEach( (stock) => {
    var ticker = stock.name.toLowerCase();
    alpha.data.quote(`${ticker}`).then(data => {
      var fixed = Number((data['Global Quote']['05. price'] * stock.shares).toFixed(2));
      let curr = {
        name : ticker,
        shares: stock.shares,
        value : fixed
      }
      portfolio.push(curr)
    });
  })
  callback(portfolio)
}

router.get('/portfolio', (req, res, next) => {
  if (req.session.userId !== undefined){

     User.findOne({ _id : req.session.userId }).exec(function (err, user) {
      if (err)
        next(err);

        user_cur_portfolio(user.portfolio, (port)=>{
          console.log(port);

          res.render('portfolio', { portfolio: port, balance: user.balance});
        });
    })
  } else {
    res.redirect('/users/login');
  }
});

A: When I make a call the route I get empty data Because alpha.data.quote is an async function and forEach is a sync function therefore, you will not be getting data in port variable.
So the best work around to this, is to use async await with all the synchronous function to behave them like async
async function user_cur_portfolio(port) {
  let portfolio = [];
  await Promise.all(
    port.map(async stock => {
      var ticker = stock.name.toLowerCase();
      const data = await alpha.data.quote(`${ticker}`);
      var fixed = Number((data['Global Quote']['05. price'] * stock.shares).toFixed(2));
      let curr = {
        name: ticker,
        shares: stock.shares,
        value: fixed
      };
      portfolio.push(curr);
    })
  );
  return portfolio;
}

router.get('/portfolio', (req, res, next) => {
  if (req.session.userId !== undefined) {
    User.findOne({ _id: req.session.userId }).exec(async function(err, user) {
      if (err) next(err);
      const port = await user_cur_portfolio(user.portfolio);
      console.log(port);
      res.render('portfolio', { portfolio: port, balance: user.balance });
    });
  } else {
    res.redirect('/users/login');
  }
});


text:
Q: How to pass onClick handler from parent to child components through optional labeled arguments I want to pass an event handler down a series of components from parent to child.  Here is a working example:
Index.re
ReactDOMRe.renderToElementWithId(
  <App myHandler={_evt => Js.log("my handler clicked")} />,
  "root",
);

App.re
let component = ReasonReact.statelessComponent(__MODULE__);

let make = (~myHandler, _children) => {
  ...component,
  render: _self => <MyComponent myHandler />,
};

MyComponent.re
let component = ReasonReact.statelessComponent(__MODULE__);

let make = (~myHandler, _children) => {
  ...component,
  render: _self =>

 {ReasonReact.string("click me")}
,
}

As this code is now, the myHandler argument is required at each component usage otherwise we get error:
This call is missing an argument of type (~myHandler: ReactEvent.Mouse.t => unit)

Labeled arguments can be made optional by adding a =? in the function declaration like so:
let component = ReasonReact.statelessComponent(__MODULE__);

let make = (~myHandler=?, _children) => {
  ...component,
  render: _self =>

 {ReasonReact.string("click me")}
,
};

However this gives a compilation error:
  5 │   ...component,
  6 │   render: _self =>
  7 │
 {ReasonReact.string("click me")}
,
  8 │ };

  This has type:
    option('a)
  But somewhere wanted:
    ReactEvent.Mouse.t => unit

I thought that perhaps the compiler might need a hint.  So then I tried explicitly adding that type to the function declaration like this:
let component = ReasonReact.statelessComponent(__MODULE__);

let make = (~myHandler: ReactEvent.Mouse.t => unit=?, _children) => {
  ...component,
  render: _self =>

 {ReasonReact.string("click me")}
,
};

But then the error flips on me and gives me:
  4 │ let make = (~myHandler: ReactEvent.Mouse.t => unit=?, _children) => {
  5 │   ...component,
  6 │   render: _self =>

  This pattern matches values of type
    ReactEvent.Mouse.t => unit
  but a pattern was expected which matches values of type
    option('a)

And now I'm all confused.

A: Just to provide a proper answer, since it seems unlikely that this will get closed as a duplicate
Optional arguments are turned into options on the callee's side of things. Otherwise, how would you represent the absence of the argument. There are no nulls, remember, so nullability must be expressed explicitly.
myHandler is therefore an option(ReactEvent.Mouse.t => unit). onClick is of course also an optional argument which will be turned into an option, but since this is, normally, done automatically we can't just feed it an option directly.
Fortunately, someone already thought of this scenario and added a syntactic construct to be able to pass options explicitly as optional arguments. Just add a ? before the expression passed to the argument, and you should be good:

 {ReasonReact.string("click me")}
,

A: So for the optional argument to work you have to handle the optional case itself in the MyComponent component.
let component = ReasonReact.statelessComponent(__MODULE__);

let make = (~myHandler=?, _children) => {
   ...component,
   render: _self => {
      let myHandler = switch myHandler {
        | None => (_e) => Js.log("default");
        | Some(handler) => handler;
   };

 {ReasonReact.string("click me")}

}


text:
Q: What gives the information? When there is a charge in space and then another charge is brought near it then it experiences a force but what gives this information to the first charge that there is another charge near it?

A: The one-line, unsatisfying answer is "the electric field carries the information."
A more correct answer is that you can't really separate a charged particle from the electric field it creates.  When we introduce the idea of an electric field in an introductory class, we usually talk about charge as a property of matter and the electric field as a computational device for predicting how charges will interact with each other.
For example, we talk about how charge A will accelerate due the field produced by charge B, but how charge A doesn't sense its own field.  This approach allows us to use the simplifying assumption of point charges, but problematically suggests that somehow there is more than one electric field and each charge can tell its own field from those of its neighbors.
An equivalent way to describe the dynamics of a system of charges, and one that's less likely to give you headaches about how information gets from "here" to "there," is to think only about the electric and magnetic fields.
In this picture, a "point charge" is a computational device for keeping track of a $1/r^2$ electric field around a particular point in space.
The fields will tend to evolve over time into configurations that minimize the total energy, which is the integral of the energy density of the electromagnetic field,
$$
\frac{\mathrm dU}{\mathrm dV} =
\frac12 \left(
\epsilon_0 E^2 + \frac1{\mu_0}B^2
\right),
\tag1
$$
but subject to the constraints imposed by Maxwell's equations which restrict how changes in the electromagnetic field at one point in space propagate to nearby points in space.
A useful hand-waving way to describe what happens is "the charges move so that the volume of the very strong fields becomes small."
(It's especially useful to note that the charge conservation equation is a consequence of the Maxwell equations, not an independent assumption: take the divergence of both sides of
$$
\vec\nabla\times\vec B - \frac1{c^2}\frac\partial{\partial t}\vec E
= \mu_0 \vec J
\tag2
  $$
and see what happens.  Charge conservation is the most compelling reason we have to think of charges as the "physical" objects versus the computational devices, since charge can't or enter any volume of space without a corresponding current, but the field equation (2) actually carries more information than just charge conservation.)
So for instance, if you were to set up the scenario usually described as "bringing two opposite point charges near each other," what you're doing is setting up a region of very strong $\vec E$ between the locations of your two "point charges."
The total energy is reduced if the volume of strong field between the charges is reduced, so the charges tend to move closer to each other.
A person working from the perspective where charges are fundamental and fields are a computational device would say "the charges were attracted to one another"; a person working from a perspective where fields are fundamental and charges are a bookkeeping device would say "the field evolved into a lower-energy configuration."  Both are right.
Likewise for charges of the same sign: there's a zero in the field between them, and the total energy stored in the electric field is minimized if the two charges are far apart.
So the longer (and to me, more satisfying answer) to your question,

When there is a charge in space and then another charge is brought near it then it experiences a force but what gives this information to the first charge that there is another charge near it?

is that both charges are shorthand descriptions of the electromagnetic field in region of space surrounding them both, and that the evolution of this field throughout space is governed by Maxwell's equations.
You can't "surprise" one charge with another one nearby.


text:
Q: Can I make multiple assignments within a given case_when true clause? Update: Apparently this feature is now planned for dplyr, as discussed here: https://github.com/tidyverse/dplyr/pull/6145
In SQL one can assign multiple variables - say var1 and var2 - when a given case is verified, with a construction like
case when condition then var1 = x, var2 = y
Does dplyr::case_when (or anything else in the tidyverse) support this useful feature), and if so, how?!
Note that in the example below, var1, var2  and var3 have exactly the same test conditions, i.e. Species == "setosa", and the degenerate case TRUE. I want to reduce this redundancy by not repeating the conditions: one call to case_when (or similar), albeit with different eval_on_true expressions for var1, var2 and var3, respectively. Obviously redundancy is not a problem here in this example, but my case_when's get very large and complex in real life examples.
library(tidyverse)

# create example data
set.seed(1337)
data <- iris %>%
  sample_n(5) %>%
  select(Petal.Length, Petal.Width, Species) %>%
  as_tibble()
data
#> # A tibble: 5 × 3
#>   Petal.Length Petal.Width Species
#>          <dbl>       <dbl> <fct>
#> 1          5.5         1.8 virginica
#> 2          5           1.9 virginica
#> 3          1.5         0.2 setosa
#> 4          5.9         2.3 virginica
#> 5          4.1         1.3 versicolor
data %>%
  mutate(var1 = case_when(Species == "setosa" ~ "green", TRUE ~ "blue"),
         var2 = case_when(Species == "setosa" ~ Petal.Length * 99, TRUE ~ Petal.Length),
         var3 = case_when(Species == "setosa" ~ as.Date("2002-12-01"), TRUE ~ as.Date("2003-12-02")))
#> # A tibble: 5 × 6
#>   Petal.Length Petal.Width Species    var1   var2 var3
#>          <dbl>       <dbl> <fct>      <chr> <dbl> <date>
#> 1          5.5         1.8 virginica  blue    5.5 2003-12-02
#> 2          5           1.9 virginica  blue    5   2003-12-02
#> 3          1.5         0.2 setosa     green 148.  2002-12-01
#> 4          5.9         2.3 virginica  blue    5.9 2003-12-02
#> 5          4.1         1.3 versicolor blue    4.1 2003-12-02

Created on 2022-02-09 by the reprex package (v2.0.1)

A: If we want to create new columns by multiplying a single column with different values, one tidyverse approach is to use imap (by default the default .y is the sequence if we pass unnamed elements) to loop over the multiplier values, return a single column with transmute and then bind those columns with the original data
library(purrr)
library(dplyr)
library(stringr)
imap_dfc(c(10, 99), ~ data %>%
   transmute(!! str_c('var', .y) :=
   case_when(Species == "setosa"~ Petal.Length * .x,
              TRUE ~ Petal.Length))) %>%
   bind_cols(data, .)

-output
# A tibble: 5 × 7
  Sepal.Length Sepal.Width Petal.Length Petal.Width Species     var1  var2
         <dbl>       <dbl>        <dbl>       <dbl> <fct>      <dbl> <dbl>
1          6.4         3.1          5.5         1.8 virginica    5.5   5.5
2          6.3         2.5          5           1.9 virginica    5     5
3          5.3         3.7          1.5         0.2 setosa      15   148.
4          6.8         3.2          5.9         2.3 virginica    5.9   5.9
5          5.7         2.8          4.1         1.3 versicolor   4.1   4.1

A: The problem with case_when is that accepts a value whose length is either nrow or 1. Therefore, you have to trick case_when by producing a list of nrow 1-row dataframes.
The accessor function lod (defined below) constructs a list of 1-row dataframes:
lod <- function(...) {
  args <- list(...)
  do.call(function(...) mapply(data.frame, ..., SIMPLIFY = FALSE), args)
}

lod(x = 1:4, y = letters[1:4])

[[1]]
  x y
1 1 a

[[2]]
  x y
1 2 b

[[3]]
  x y
1 3 c

[[4]]
  x y
1 4 d

Then write your case_when statement, using lod to group variables, as follows:
data |>
  mutate(case_when(Species == "setosa" ~
                     lod(var1 = "green",
                         var2 = Petal.Length * 99,
                         var3 = as.Date("2002-12-01")),
                   TRUE ~
                     lod(var1 = "blue",
                         var2 = Petal.Length,
                         var3 = as.Date("2003-12-02"))) |>
         bind_rows())

+ # A tibble: 5 x 6
  Petal.Length Petal.Width Species    var1   var2 var3
         <dbl>       <dbl> <fct>      <chr> <dbl> <date>
1          5.5         1.8 virginica  blue    5.5 2003-12-02
2          5           1.9 virginica  blue    5   2003-12-02
3          1.5         0.2 setosa     green 148.  2002-12-01
4          5.9         2.3 virginica  blue    5.9 2003-12-02
5          4.1         1.3 versicolor blue    4.1 2003-12-02

The final bind_rows is required for mutate to accept the new variables.

A: Maybe this helps:
library(tidyverse)

# create example data
set.seed(1337)
data <- iris %>%
  sample_n(5) %>%
  as_tibble()
data
#> # A tibble: 5 x 5
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
#>          <dbl>       <dbl>        <dbl>       <dbl> <fct>
#> 1          6.4         3.1          5.5         1.8 virginica
#> 2          6.3         2.5          5           1.9 virginica
#> 3          5.3         3.7          1.5         0.2 setosa
#> 4          6.8         3.2          5.9         2.3 virginica
#> 5          5.7         2.8          4.1         1.3 versicolor

data %>%
  mutate(
    sepal_size = case_when(
      Sepal.Length > 6 & Sepal.Width > 3 ~ "big",
      Sepal.Width > 3 ~ "medium",
      TRUE ~ "small"
    ),
    petal_size = case_when(
      Petal.Length > 5 ~ "big",
      TRUE ~ "small"
    ),
    is_fancy = TRUE
  )
#> # A tibble: 5 x 8
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width Species    sepal_size
#>          <dbl>       <dbl>        <dbl>       <dbl> <fct>      <chr>
#> 1          6.4         3.1          5.5         1.8 virginica  big
#> 2          6.3         2.5          5           1.9 virginica  small
#> 3          5.3         3.7          1.5         0.2 setosa     medium
#> 4          6.8         3.2          5.9         2.3 virginica  big
#> 5          5.7         2.8          4.1         1.3 versicolor small
#> # … with 2 more variables: petal_size <chr>, is_fancy <lgl>

Created on 2022-02-08 by the reprex package (v2.0.1)
To do the reverse, you can do:
iris %>%
  mutate(
    selected = Species == "setosa",
    var1 = ifelse(selected, Petal.Length * 99, Petal.Length),
    var2 = ifelse(selected, as.Date("2002-12-01"), as.Date("2003-12-02"))
  )


text:
Q: Convergence of prime-related series I was wondering if the series
$$\sum\limits_{n=1}^\infty\left(\frac n{p_n}\right)^k$$
converges for $k>1$, where $p_n$ is the $n^\textrm{th}$ prime number?
Edit: Thinking about this a bit more,
it is known that $p_n$ is bounded by $p_n<n(ln(n)+ln(ln(n)))$ for big enough $n$, meaning that
$$\left(\frac n{p_n}\right)^k > \left(\frac 1{ln(n)+ln(ln(n))}\right)^k $$
for these $n$ and since
$$\sum\limits_{n=2}^\infty\frac 1{nln(n)}$$ diverges, does this imply the divergence of $$\sum\limits_{n=1}^\infty\left(\frac n{p_n}\right)^k$$
for any $k$?

A: Since
$p_n \approx n \ln n$
and
$\ln(x)
\lt x^c$
for any $c > 0$
and large enough $x$,
$\begin{array}\\
\sum\limits_{n=1}^\infty\left(\frac n{p_n}\right)^k
&\approx \sum\limits_{n=1}^\infty\left(\frac n{n\ln n}\right)^k\\
&= \sum\limits_{n=1}^\infty\left(\frac1{\ln n}\right)^k\\
&\gt \sum\limits_{n=1}^\infty\left(\frac1{n^c}\right)^k
\qquad\text{for any } c > 0\\
&= \sum\limits_{n=1}^\infty\frac1{n^{ck}}\\
&= \sum\limits_{n=1}^\infty\frac1{n^{1/2}}
\qquad\text{choose } c = \frac1{2k}\\
\text{Diverges}\\
\end{array}
$


text:
Q: Recursive tree, printing ancestor nodes this is study material, not homework:
I have the following tree, I need to write an algorithm that finds a given number and returns an integer indicating how many nodes it visited before finding it. It should also print the values of all "ancestor" nodes relative to the node in which the value was found (in no particular order, and it is assumed that the given value is always present)
            10
           /  \
         20    60
        /  \
       50  30
             \
             40

If the given value is 40 it should return 4 and print 30, 20, 10 (in any order)
I've written the following solution, and I think it works, but I'm concerned about the print.
void foobar (ty_tree *tree, int value, int & count){
    if (tree !=null) {
        if (tree->value != value) {
            count++;
            foobar (tree->left, value, count);
            foobar (tree->right, value, count);
            cout << tree->value;
        }
    }
}

A: Good approach ! But to print the ancestors (i.e.parent nodes) you need to know in your recursive function if the value was found in one of the child:
bool foobar (ty_tree *tree, int value, int & count) {
    if (tree !=nullptr) {  // oops: NULL or nullptr, the latter is better
        if (tree->value != value) {
            count++;
            if (foobar (tree->left, value, count) ||
                  foobar (tree->right, value, count) ) // if found below
            cout << tree->value<<endl;  // print the node, because it's on the path
        }
        else {
            cout << "Found: "<<tree->value<<endl;  // print the value found
            return true;     // and inform caller that he can print as well.
        }
    }
    else return false;  // reached a leaf without finding
}

As some doubts were expressed in the comments, here an online demo