text:
Q: how can i call a variable from another function/method? I have an assignment to do a CV that users will input on and display it. However, I don't know how I can call a variable to another to function to print/display.
Here is the code:
import java.util.Scanner;
public class curriculumVitae1{
    public static String firstName;
    public static String middleName, lastName, birthDate, maritalStatus, homeAddress, provincialAddress, mobileNumber, anotherMobile, landlineNumber, anotherLandline, primaryYears;
    private static void main (String args[]){
        Scanner input = new Scanner(System.in);
            System.out.print("\nCurriculum Vitae");
            System.out.print("\nInput your  last name: ");
            String lastName;
            lastName = input.nextLine();
            System.out.print("\nInput your  first name: ");
            String firstName;
            firstName = input.nextLine();

            System.out.print("\nInput your  middle name: ");
            String middleName;
            middleName = input.nextLine();

            System.out.print("\nInput your  birthdate: ");
            String birthDate;
            birthDate = input.nextLine();

            System.out.print("\nInput your  marital status (Married, Widowed, Separated, Divorced, Single) : ");
            String maritalStatus;
            maritalStatus = input.nextLine();

            System.out.print("\nInput your  home address: ");
            String homeAddress;
            homeAddress = input.nextLine();

            curriculumVitae1.cv();
    }
    private static void provincial(String args[]){
        Scanner input = new Scanner(System.in);
            System.out.print("\nDo you have a provincial address? Enter Y if yes, and N if no:  ");
            char provincialQuestion;
            provincialQuestion = input.nextLine().charAt(0);
            if (provincialQuestion=='Y'){
                System.out.print("\nInput your  provincial address: ");
                String provincialAddress;
                provincialAddress = input.nextLine();
            }
            else if(provincialQuestion=='N'){
            }
    }
    private static  void mobile(String args[]){
        Scanner input = new Scanner(System.in);
            System.out.print("\nContact Details ");
                System.out.print("\nInput your mobile number: ");
                String mobileNumber;
                mobileNumber = input.nextLine();
            System.out.print("\nDo you have another mobile number? Enter Y if yes, and N if no:  ");
            char mobileQuestion;
            mobileQuestion = input.nextLine().charAt(0);
            if (mobileQuestion=='Y'){
                System.out.print("\nInput another mobile number: ");
                String anotherMobile;
                anotherMobile = input.nextLine();

            }
            else if(mobileQuestion=='N'){

            }
    }
    private static void landline(String args[]){
        Scanner input = new Scanner(System.in);
            System.out.print("\nInput your landline number: ");
                String landlineNumber;
                landlineNumber = input.nextLine();
                System.out.print("\nDo you have another landline number? Enter Y if yes, and N if no:  ");
            char landlineQuestion;
            landlineQuestion = input.nextLine().charAt(0);
            if (landlineQuestion=='Y'){
                System.out.print("\nInput another mobile number: ");
                String anotherLandline;
                anotherLandline = input.nextLine();

            }
            else if (landlineQuestion=='N'){

            }
    }
    private static String email(){
        Scanner input = new Scanner(System.in);
            System.out.print("\nInput your email address: ");
                String emailAddress;
                emailAddress = input.nextLine();
                return emailAddress;
    }
    private static String tertiary(){
        Scanner input = new Scanner(System.in);
            System.out.print("\nEducation History ");
            System.out.print("\nTertiary Education ");

            System.out.print("\nInput your tertiary education course: ");
                String tertiaryCourse;
                tertiaryCourse = input.nextLine();

            System.out.print("\nInput your tertiary education school: ");
                String tertiarySchool;
                tertiarySchool = input.nextLine();

            System.out.print("\nInput your tertiary education inclusive years (xxxx-xxxx): ");
                String tertiaryYears;
                tertiaryYears = input.nextLine();

            System.out.print("\nDo you have any honors/achivements received during your tertiary education? Enter Y if yes, and N if no:  ");
            char tertiaryQuestion;
            tertiaryQuestion = input.nextLine().charAt(0);
            if (tertiaryQuestion=='Y'){
                System.out.print("\nInput your honor/s or achivement/s:");
                String tertiaryAchievements;
                tertiaryAchievements = input.nextLine();
                return tertiaryAchievements;
            }
            else if (tertiaryQuestion=='N'){
                return "------";
            }
    }
    private static void secondary(String args[]){
        Scanner input = new Scanner(System.in);
            System.out.print("\nSecondary Education ");
            System.out.print("\nInput your secondary education school: ");
                String secondarySchool;
                secondarySchool = input.nextLine();

            System.out.print("\nInput your secondary education inclusive years (xxxx-xxxx): ");
                String secondaryYears;
                secondaryYears = input.nextLine();

            System.out.print("\nDo you have any honors/achivements received during your secondary education? Enter Y if yes, and N if no:  ");
            char secondaryQuestion;
            secondaryQuestion = input.nextLine().charAt(0);
            if (secondaryQuestion=='Y'){
                System.out.print("\nInput your honor/s or achivement/s:");
                String secondaryAchievements;
                secondaryAchievements = input.nextLine();
            }
            else if (secondaryQuestion=='N'){
            }
    }
        public static void primary(String args[]){
            Scanner input = new Scanner(System.in);
            System.out.print("\nPrimary Education ");
            System.out.print("\nInput your primary education school: ");
                String primarySchool;
                primarySchool = input.nextLine();

            System.out.print("\nInput your primary education inclusive years (xxxx-xxxx): ");
                String primaryYears;
                primaryYears = input.nextLine();

            System.out.print("\nDo you have any honors/achivements received during your primary education? Enter Y if yes, and N if no:  ");
            char primaryQuestion;
            primaryQuestion = input.nextLine().charAt(0);
            if (primaryQuestion=='Y'){
                System.out.print("\nInput your honor/s or achivement/s:");
                String primaryAchievements;
                primaryAchievements = input.nextLine();
            }
            else{
                System.out.print("------");
            }
        }
        public static void cv(String args[]){
            System.out.println("                                               Curriculum Vitae");
            System.out.print("\nName:" + firstName + " " + middleName + " "+ lastName);
            System.out.print("\nBirthdate:" + birthDate);
            System.out.print("\nMarital Status:" + maritalStatus);
            System.out.print("\nHome Address:" + homeAddress);
            System.out.print("\nProvincial Address:" + provincialAddress);
            System.out.print("\nMobile Number:" + mobileNumber );
            System.out.print("\nAnother Mobile Number:" + anotherMobile);
            System.out.print("\nLandline:" + landlineNumber);
            System.out.print("\nYear: " + primaryYears);

}
}

However, I always get the error that
 C:\Users\BEST\Desktop\wew>javac curriculumVitae1.java
curriculumVitae1.java:33: error: method cv in class curriculumVitae1 cannot be applied to given types;
                        curriculumVitae1.cv();
                                        ^
  required: String[]
  found: no arguments
  reason: actual and formal argument lists differ in length
1 error

Please help me on how can I print out another variable from other function. Or some alternatives that I can do.

A: Your methods expect an (String[] args) however since you don't use them I would remove them. Try
public static void cv() {

A: The error details highlight that you're calling the method without providing the required parameters in the method signature public static void cv(String args[]):

*

*The required part tells you what types of arguments are expected, here String[] and the found part tells you what it saw instead, here it saw you passed no arguments.

*The reason tells you that the actual (what you provided) number of arguments differs from the formal (what the method signature defines) number of arguments expected, i.e. not enough or too many arguments were provided.
You can also get this from the original error message:
error: method cv in class curriculumVitae1 cannot be applied to given types;
                        curriculumVitae1.cv();

It doesn't explicitly state it, but from the line of code shown below you can see that the "given types" are nothing because the method was called with no arguments—nothing inside the parentheses.
Like Peter Lawrey said, you can just remove the String args[] from your method signature since you don't use it.
Hope this helps you understand error messages and what they're telling you a little better!

A: Make the following changes to your program:

*

*Change the access specifier of main() method from private to public. Otherwise the code will throw the error - Does not contain a main method

*Since you have  firstName, middleName, lastName, birthDate etc. declared as static variables do not declare them as local variables in main method. Assign the values to the already declared static variables in the main() method as shown below:
public static void main (String args[]){
    Scanner input = new Scanner(System.in);
    System.out.print("\nCurriculum Vitae");
    System.out.print("\nInput your  last name: ");
    //String lastName;
    lastName = input.nextLine();
    System.out.print("\nInput your  first name: ");
    //String firstName;
    firstName = input.nextLine();

    System.out.print("\nInput your  middle name: ");
    //String middleName;
    middleName = input.nextLine();

    System.out.print("\nInput your  birthdate: ");
    //String birthDate;
    birthDate = input.nextLine();

    System.out.print("\nInput your  marital status (Married, Widowed, Separated,
    Divorced, Single) : ");
    //String maritalStatus;
    maritalStatus = input.nextLine();

    System.out.print("\nInput your  home address: ");
    //String homeAddress;
    homeAddress = input.nextLine();
    //System.out.println();
    cv();
  }

*

*Remove the String[] args argument from cv() method as it is not being used.

*Since cv() is a static method, it can be called directly from the main().

*Return the string type varaible from tertiary() method as it is giving a compile error. You can do so by declaring tertiaryAchievements variable outside the if-else block and then returning it as shown below:

String tertiaryAchievements="";
  if (tertiaryQuestion=='Y')


text:
Q: Search with special characters how can I use a query (in Parse) in javascript to find or match words with accented characters like "escazú" and "escazu", both words must display the same results.
I have something like
query.matches("direccion", "escazú", i);
Thanks for your help!
Leo

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do you print out a palindrome with certain characters removed using arrays? My program is supposed to test for a palindrome and then print it out in reverse but without characters like '!', ', or '?'. So the entered input "madam I'm adam" would output "madamimadam" with no capitalization, blanks, or punctuation. I was able to write the program but how do you do that other part to take away those characters/capitalization? Also for my array, when the program runs it outputs a bunch of odd characters in between the palindrome and the palindrome in reverse when it prints out. I believe this is because the array is filling in the extra character spaces so how would I fix that as well?
#include<iostream>
#include<string>
using namespace std;

int main()
{
    //Variables and arrays
    int const index = 30;
    char Phrase[index];
    char Reverse[index];
    char* Palindrome = Reverse;
    int i, j;

    cout << "Please enter a sentence to be tested as a palindrome: ";
    cin.getline(Phrase, 30);
    int length = strlen(Phrase);

    bool test = true;

    for(i = 0; i != length/2; i++) //Loops from zero to half of the string
    {
        if(test) // if it is a palindrome so far
        {
            if(Phrase[i] != Phrase[length-i-1]) //To check if the characters match
            {
                test = false;
            }

        }
        else
        {
            break;
        }
    }

    if(test)
    {
        cout << endl << "Phrase/Word is a Palindrome." << endl << endl;
        for(j = strlen(Phrase) - 1; j >= 0; Palindrome++, j--)
        {
            *Palindrome = Phrase[j];
        }
        cout << "The phrase and reverse statement is: " << Reverse << endl << endl;
    }
    else
    {
        cout << endl << "Phrase/Word is not a Palindrome." << endl << endl;
    }

    system("Pause");
    return 0;
}

A: You forgot to add the terminating \0 to Reverse. Add *Palindrome = '\0' after the loop.

A: Just use separate iterators.
Instead of
for(i = 0; i != length/2; i++)

do
for(i = 0, j = length-1; i < j; i++, j--)

then for your if statement, you can do something like
if(test) // if it is a palindrome so far
{
    while(!isalpha(Phrase[i]) && i < j) { i++; }
    while(!isalpha(Phrase[j]) && i < j) { j--; }
    if(Phrase[i] != Phrase[j]) //To check if the characters match
    {
        test = false;
    }

this will cause your program to ignore any character than isn't a letter. You can use isalphanum if you want it to recognize numbers as well.

A: #include <iostream>
#include <string>
#include <cctype>
    using namespace std;

int main()
{
//Variables and arrays
int const index = 80;
char Phrase[index];
char NewPhrase[index];
int i, j, k, l;
bool test = true;

//Prompt user for the phrase/word
cout << "Please enter a sentence to be tested as a palindrome: ";
cin.getline(Phrase, 80);

//Make everything lowercase, delete spaces, and copy that to a new array 'NewPhrase'
for(k = 0, l = 0; k <= strlen(Phrase); k++)
{
    if((Phrase[k] != ' ') && (ispunct(Phrase[k]) == false))
    {
        NewPhrase[l] = tolower(Phrase[k]);
        l++;
    }
}

int length = strlen(NewPhrase); //Get the length of the phrase

for(i = 0, j = length-1; i < j; i++, j--)
{
    if(test) //Test to see if the phrase is a palindrome
    {
        if(NewPhrase[i] != NewPhrase[j])
            test = false;
    }
    else
        break;
}

if(test)
{
    cout << endl << "Phrase/Word is a Palindrome." << endl << endl;
    cout << "The Palindrome is: " << NewPhrase << endl << endl;
}
else
    cout << endl << "Phrase/Word is not a Palindrome." << endl << endl;

system("Pause");
return 0;
}


text:
Q: Bash script for switching wallpaper in XFCE4 Can you help me with writing a bash script for switching wallpaper between day and night version under XFCE? I want to set a cron job for running it so it will switch automatically based on the time of the day.

A: I wrote a script:
#!/bin/bash
xfconf-query -c xfce4-desktop -p /backdrop/screen0/monitor0/workspace0/last-image -s /home/maciek/Pictures/day.jpg

It works when I run it from a terminal. But when I set it up in cron it doesn't work. I get an error:
Failed to init libxfconf: Using X11 for dbus-daemon autolaunch was disabled at compile time, set your DBUS_SESSION_BUS_ADDRESS instead.

Some info:
Name            : xfce4-session
Version         : 4.12.1-7
Description     : A session manager for Xfce
Architecture    : x86_64
URL             : http://www.xfce.org/
Licenses        : GPL2
Groups          : xfce4
Provides        : None
Depends On      : libxfce4ui  libwnck  libsm  polkit  xorg-iceauth  xorg-xinit  xorg-xrdb
                  polkit-gnome  hicolor-icon-theme
Optional Deps   : gnome-keyring: for keyring support when GNOME compatibility is enabled
                  xscreensaver: for locking screen with xflock4
                  gnome-screensaver: for locking screen with xflock4
                  xlockmore: for locking screen with xflock4
                  slock: for locking screen with xflock4
Required By     : None
Optional For    : None
Conflicts With  : None
Replaces        : xfce-utils
Installed Size  : 1972.00 KiB
Packager        : Evangelos Foutras <evangelos@foutrelis.com>
Build Date      : Tue 27 Jun 2017 05:48:04 AM CEST
Install Date    : Fri 21 Jul 2017 11:49:41 PM CEST
Install Reason  : Explicitly installed
Install Script  : No
Validated By    : Signature

DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/1000/bus


text:
Q: Input field is resetting async function on submit in react-hook-form I am using react-hook-form library for creating Modal form. The form in my modal is resetting when i submit the form with async await function, if it is normal function it works fine. Things is I do not want fields to be reset when the request is failing. I want it to stay in the modal open and not resetting the form. Also, e.preventdefault() is not working and with handleSubmit we don`t need use it.
So, I am using createAsyncThunk for action
export const deleteTenant = createAsyncThunk<{}, string, { rejectValue: ErrorMessage }>(
  'tenants/deleteTenant',
  async (tenantId, thunkAPI): Promise<void> => {
    try {
      await fetch(url, {
        method: 'DELETE',
      })
      thunkAPI.dispatch(closeModal('delete'))
      await thunkAPI.dispatch(getTenantList())
      toast.success(TextKey.TenantDeleteSuccessMessage)
    } catch (error: any) {
      toast.error(TextKey.TenantDeleteErrorMessage)
      throw thunkAPI.rejectWithValue(error.response.data)
    }
  },
)

const onDeleteSubmit = async () => await dispatch(deleteTenant(id))

 <Modal
        show={isDeleteModalOpen}
        onClose={() => dispatch(closeModal('delete'))}
        title={TextKey.DeleteExistingTenant}
        onSubmit={handleSubmitDelete(onDeleteSubmit)}
        type="tenantDelete"
      >
        {errorTenantDelete && errorTenantDeleteMessage ? (
          <ErrorMessage>{errorTenantDeleteMessage}</ErrorMessage>
        ) : (
          <ErrorMessage>{TextKey.WarningDeleteMessage}</ErrorMessage>
        )}
        <InputField
          errors={errorsDelete}
          label={TextKey.TenantName}
          type="text"
          placeholder={TextKey.TypeNewTenantName}
          {...registerDelete('tenantName', {
            required: TextKey.TenantNameIsRequired,
            pattern: {
              value: /^\w+([\s-_]\w+)*$/,
              message: TextKey.TenantNameValidation,
            },
            validate: {
              tenantNameEqual: (value) => {
                console.log({ value })
                return value === name || TextKey.MatchWithTenantName
              },
            },
          })}
        />
      </Modal>

export const Modal = memo(({ show, onClose, children, title, onSubmit, type }: ModalProps): JSX.Element => {
      const { isLoadingDelete } = useAppSelector(getTenantsState)

      const renderIconButton = useCallback(() => {
        switch (type) {
          case 'tenantAdd':
            return (
              <ButtonIcon type="submit" appearance="primary">
                {renderIcon(Outline16FloppyDisk)}
                <Text size={16}>{TextKey.AddTenant}</Text>
              </ButtonIcon>
            )

          case 'tenantUpdate':
            return (
              <ButtonIcon type="submit" appearance="primary">
                {renderIcon(Outline16FloppyDisk)}
                <Text size={16}>{TextKey.UpdateTenant}</Text>
              </ButtonIcon>
            )

          case 'tenantDelete':
            return (
              <ButtonIcon type="submit" appearance="danger" disabled={isLoadingDelete}>
                {isLoadingDelete ? (
                  <Loader size="small" />
                ) : (
                  <>
                    {renderIcon(Outline16TrashCan)}
                    <Text size={16}>{TextKey.Delete}</Text>
                  </>
                )}
              </ButtonIcon>
            )

          default:
            return null
        }
      }, [type])

      return (
        <ModalWrapper show={show} onClick={onClose}>
          <ModalContent onSubmit={onSubmit} onClick={(e) => e.stopPropagation()}>
            <Text size={24} weight={500} lineHeight={36} align="center">
              {title}
            </Text>

            <ModalBody>{children}</ModalBody>
            <ModalFooter>
              <BlockContainer right="10">
                <Button appearance={TERTIARY_BUTTON} onClick={onClose}>
                  {TextKey.Cancel}
                </Button>
              </BlockContainer>

              {renderIconButton()}
            </ModalFooter>
          </ModalContent>
        </ModalWrapper>
      )
    })


text:
Q: How do I add to a target number using an array of integers? How can I add integers to a certain number, using only an integer array? This is what I have so far. I have to do it recursively.
public static boolean sumsToTarget(int[] arr, int target){

    return sumsToTarget(arr, target, 0, 0, 0);

}

private static boolean sumsToTarget(int[] arr, int target, int startIndex, int endIndex, int total){
    if(endIndex >= arr.length){
        if(startIndex >= arr.length){
            return false;
        }
        return sumsToTarget(arr, target, startIndex + 1, startIndex + 1, 0);
    }
    total += arr[endIndex];
    if(total == target){
        return true;
    }else if(total >= target){
        return sumsToTarget(arr, target, startIndex, endIndex + 1, total - arr[endIndex]);
    }else{
        return sumsToTarget(arr, target, startIndex+1, startIndex+1, total) || sumsToTarget(arr, target, startIndex, endIndex + 1, total) || sumsToTarget(arr, target, startIndex, endIndex + 2, total);
    }
}

This is how I am testing my code.
int[] a = {1, 3, 5, 7, 9};

    System.out.println("Should always print out true.");

    try{ System.out.println("1. " + (ProjectTwo.sumsToTarget(a, 10)==true)); } catch(Exception e){ System.out.println("failed"); }
    try{ System.out.println("2. " + (ProjectTwo.sumsToTarget(a, 40)==false)); } catch(Exception e){ System.out.println("failed"); }
    try{ System.out.println("3. " + (ProjectTwo.sumsToTarget(a, 17)==true)); } catch(Exception e){ System.out.println("failed"); }

    int[] b = {-5, 100, 150, 12, 10, 200, 300, -4, 250, 600};
    try{ System.out.println("4. " + (ProjectTwo.sumsToTarget(b, -5)==true)); } catch(Exception e){ System.out.println("failed"); }
    try{ System.out.println("5. " + (ProjectTwo.sumsToTarget(b, 1)==true)); } catch(Exception e){ System.out.println("failed"); }
    try{ System.out.println("6. " + (ProjectTwo.sumsToTarget(b, 601)==true)); } catch(Exception e){ System.out.println("failed"); }
    try{ System.out.println("7. " + (ProjectTwo.sumsToTarget(b, 0)==false)); } catch(Exception e){ System.out.println("failed"); }
    try{ System.out.println("8. " + (ProjectTwo.sumsToTarget(b, 12)==true)); } catch(Exception e){ System.out.println("failed"); }

    int[] c = {5};
    try{ System.out.println("9. " + (ProjectTwo.sumsToTarget(c, -5)==false)); } catch(Exception e){ System.out.println("failed"); }
    try{ System.out.println("10. " + (ProjectTwo.sumsToTarget(c, 5)==true)); } catch(Exception e){ System.out.println("failed"); }

And this is the output:
Should always print out true.

*

*true

*false

*true

*true

*true

*true

*true

*true

*true

*true

A: Think about the algorithm. You have a list of values and you want to try every combination of summing them to see if a combination matches your target.
Let's say the number are 1, 3, and 7. All combination would be:
      = 0
1     = 1
3     = 3
1+3   = 4
7     = 7
1+7   = 8
3+7   = 10
1+3+7 = 11

To use recursion, you'd basically take the first number (1), and try with and without that number, by doing the recursive call for the rest of the numbers, and a total-so-far of 0 or 1.
On the second invocation, you'd try with and without 3. Since it'd be called with a total-so-far of 0 or 1, that will end up be a total of 4 level-3 invocations, with a total-so-far of 0, 3, 1, 4.
And so on.
If the total equals the target, you stop recursion and return true, which should stop recursion all the way back up the call stack.
Optional: If the total exceeds the target, you can stop recursion for this combination, because any further recursion would just get further away from the target.
Now try implementing this logic.


text:
Q: how to change edit box focus when text deleted in android I have 3 EditTexts for password field. Each can contain only one digit. I have implemented request focus when inputting the password. But how do I change focus from one EditText to another when I am deleting the digits?

A: This is a best practice for using edittext with one password.
et1 = (EditText) findViewById(R.id.code1);
et2 = (EditText) findViewById(R.id.code2);
et3 = (EditText) findViewById(R.id.code3);

et1.addTextChangedListener(new TextWatcher() {

            @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {

        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() == 1) {
                et2.requestFocus();
            }

        }
    });

    et2.addTextChangedListener(new TextWatcher() {

        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                int after) {
            // TODO Auto-generated method stub

        }

        @Override
        public void afterTextChanged(Editable s) {
            if (s.length() == 1) {
                et3.requestFocus();
            } else if (s.length() == 0) {
                et2.clearFocus();
                et1.requestFocus();
            }
        }
    });

You have to manage this way.


text:
Q: Error downloading file via cURL I want to download a file from an ftp server via cURL.
Here is my function:
function getFile($remotefolder, $remotefile, $localfile) {
    $url  = "ftp://xxxxx.de/" . $remotefolder . "/" . $remotefile;
    $fp   = fopen($localfile, "w+");

    $handle = curl_init();
    curl_setopt($handle, CURLOPT_URL, $url);
    curl_setopt($handle, CURLOPT_RETURNTRANSFER, 0);
    curl_setopt($handle, CURLOPT_UPLOAD, 0);
    curl_setopt($handle, CURLOPT_FILE, $fp);
    curl_setopt($handle, CURLOPT_USERPWD, "<Username>:<Password>");
    $result = curl_exec($handle);

    $info = curl_getinfo($handle);

    curl_close($handle);
    fclose($fp);

    print_r($info);
}

If I execute that on my pc everything works fine. But when I ran the code on the server it gaves me the following output and the file was not downloaded:
output server
=============
Array
(
    [url] => ftp://xxxx/xxxx/xxx.log.gz
    [content_type] =>
    [http_code] => 257
    [header_size] => 0
    [request_size] => 0
    [filetime] => -1
    [ssl_verify_result] => 0
    [redirect_count] => 0
    [total_time] => 1.357453
    [namelookup_time] => 0.002011
    [connect_time] => 0.011153
    [pretransfer_time] => 1.357439
    [size_upload] => 0
    [size_download] => 0
    [speed_download] => 0
    [speed_upload] => 0
    [download_content_length] => 0
    [upload_content_length] => 0
    [starttransfer_time] => 0
    [redirect_time] => 0
)

If you please further information, please let me know.
Thanks in advance,
Dennis

A: Looking at your http_code response, 257 is the code for "PATHNAME" created, which could mean that the file doesn't exist, or that your path may be incorrect.
Test it with a different URL that you know exists.

A: Try switching the order of the arguments. This is what I use in one of my classes that is dependent on a file located on an FTP server:
$fh = fopen('downloads/' . self::ZIP, 'w');
$ch = curl_init(self::FTP . self::PATH . '/' . self::ZIP);

curl_setopt($ch, CURLOPT_USERPWD, self::USERNAME . ':' . self::PASSWORD);
curl_setopt($ch, CURLOPT_FILE, $fh);

curl_exec($ch);
curl_close($ch);
fclose($fh);


text:
Q: List of items using Xpath and Selenium Hello i'm trying to fetch all friends connected within Facebook using Xpath and Selenium the problem is when i try to locate all the friends it return an Empty List.
using System;
using System.Collections.Generic;
using OpenQA.Selenium;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium.Support.UI;

namespace Automation
{
    class Program
    {
        static void Main(string[] args)
        {

            using (IWebDriver driver = new FirefoxDriver())
            {
                driver.Navigate().GoToUrl("https://mbasic.facebook.com");

                IWebElement username = driver.FindElement(By.Name("email"));
                username.SendKeys("email");

                IWebElement password = driver.FindElement(By.Name("pass"));
                password.SendKeys("password");

                IWebElement submit = driver.FindElement(By.Name("login"));
                submit.Submit();

                var waitHomePage = new WebDriverWait(driver,TimeSpan.FromSeconds(10));
                waitHomePage.Until(ExpectedConditions.ElementExists(By.PartialLinkText("Chat")));

                IWebElement chat = driver.FindElement(By.XPath(".//*[@id='header']/div/a[6]"));
                //driver.Manage().Timeouts().ImplicitlyWait(TimeSpan.FromSeconds(5));
                chat.Click();

                IList<IWebElement> friends = chat.FindElements(By.ClassName("m br bs"));
            }
        }
    }
}

Friends.Count return 0 .
Here is the HTML of the friends chat list

Friend Name

A: As far as I can see you have several mistakes in your code (and the HTML you provided is not complete and without any information in it).
I think you try to search for friends via
IList<IWebElement> friends = chat.FindElements(By.ClassName("m br bs"));

but in this case you are using the chat object which referes to an a tag, see:
IWebElement chat = driver.FindElement(By.XPath(".//*[@id='header']/div/a[6]"));

so i would use driver instead of chat object (because I don't know what chat returns in your case).
Furthermore you are trying to estimate the number of friends by searching for a ClassName which in your HTML sample doesn't contain any information (empty table). I tried to look it up myself and the difficulty is that FB do not use any unquie IDs for their tables. In my browser the friendlist looks something like this:

        Someuser1

It seems that FB uses for each contact a href tag with click_type=buddylist ... so I tried to use this information to find the user with xpath:
.//*[contains(@href,'buddylist')]

so you could to read the userlist with
IList<IWebElement> friends = driver.FindElements(By.XPath(".//*[contains(@href,'buddylist')]"));

It works for me. Hope I could help you or give you at least a hint...


text:
Q: Get scalar value from table in Kusto, KQL I am trying to get the maximum of a column from a table and get the output of the data in the form of a scalar to be used in another table. I am attaching a sample code for reference here.

Covid19
| limit 10
| summarize (max(Confirmed))

This gives me an output as in the following image:
Result of Above Query
Now I want to get the value of the result as a scalar. I am new at KQL so maybe my approach as a whole can also be wrong any help will be appreciated.

A: You could use toscalar() as part of a let statement.
For example:
let maxConfirmed = toscalar(
   Covid19
   | limit 10
   | summarize max(Confirmed)
);
... do something with 'maxConfirmed' ...


text:
Q: In wpgeodirectory supreme theme how can I change the gear icon with a filter icon Actually the gear icon shows filters, and therefore I would like to replace it. I would like also not to spin.

A: *

*Change icon

Goto
\plugins\geodir_advance_search_filters\geodirectory_advance_search_function.php    line 1774 and replace;
$default_btn_value = '';

with
$default_btn_value = '';

*Disable spinning of icon:

Goto plugins\geodir_advance_search_filters\js\frontend.js and comment line 1398:
jQuery('button.showFilters i').addClass('fa-spin');

change the respective line also frontend.min.js for immediate affect


text:
Q: How can I access button click from main in python, tkinter? I'm new to python and tkinter GUI, I need to access button click action from the main function, is there any possibility to do that?  any way I can access it in click function inside the class that I have comment it. what is the correct method to do it? thank you
from tkinter import *

class Youtube:
    def __init__(self,master):
        self.master = master
        master.title('Youtube_Downloder')
        self.screen = Entry(master, state='normal', width=25, background="White", foreground="blue",
                            font=('Arial', 12))
        self.screen.grid(row=1, column=0, columnspan=4, padx=5, pady=5)
        self.layout = Label(master, text='Past the Link below', font=('Arial', 16),foreground="red")
        self.layout.grid(row=0, column=1)
        self.create_button('Add Link',1,30)

    def create_button(self,val,row,column,width=12):
        button = Button(self.master, text=val, width=width, command=lambda: self.click(val))
        return button.grid(row=row,column=column)

    def click(self,clicked_button=None):
        if clicked_button == 'Add Link':
            #self.create_label(self.screen.get(), 3, 1)  #this methord working
            return 'Add Link'

    def create_label(self,text,row,column,font=('Arial',8)):
        return Label(self.master, text=text, font=font).grid(row=row, column=column)

def main():
    root = Tk()
    my_gui = Youtube(root)
    if my_gui.click() == 'Add Link':
        my_gui.create_label(my_gui.screen.get(), 3, 1)
    root.mainloop()

if __name__ == '__main__':
    main()

A: I'm assuming it could be this button:
def create_button(self,val,row,column,width=12):
        button = Button(self.master, text=val, width=width, command=lambda: self.click(val))
        return button.grid(row=row,column=column)

Change button to self.button. When you've done that you can access it in main by using my_gui.button.
If you ever decide to use an mvc model, this will be the approach as well.


text:
Q: How should I setup the PIC's LCDREF register? I am using PIC16F1946. It has a LCD driver module in it. I read the datasheet and it mentions LCDREF register (Section 27-3 in the datasheet). I cannot find useful info on how to set it up?
Could anyone help me out here please.

A: You have to read the whole datasheet section for the LCD, which is section 27 starting on page 335 and is 35 pages long.  You apparently don't understand some background about how LCDs are driven in general and this hardware module in particular, else the well written description of the LCDREF register in section 27-3 on page 339 would make sense.
Read all the data sheet section on the LCD.  Don't try to get away with reading just what you think you need.  You should always want to understand the whole hardware module before attempting to use it in any particular mode.

A: The datasheet looks to have all the info you need, but there is also an app note with example code on the chips page at Microchip that might help.

A: That register sets up the LCD bias voltages.  As a first test, you can simply set it to 0x80 and try it out.  For most uses that will work just fine.  If you need to customize your LCD driving voltages and currents, you will need to delve further into that register (check out figure 27-3 for how it affects the bias voltages), but for most simple situations, 0x80 will provide reasonable biasing for most LCDs.


text:
Q: With Spark/Scala, is there a way to join with complex data structures? I have a data frame with a complex structure.  Down inside that structure, I need to replace a value with another based on a mapping from another data frame.  We currently accomplish this by exploding the data frame, joining, and then doing a grouping with aggregation.  The problem is we are turning 3.5B records in 210B records.  The cost of the grouping is very high.  And I'm starting with data that is already grouped as I want it.  Is there was some way to accomplish this without doing the explode and grouping?
Here is some example code from a Zeppelin notebook to illustrate our current method:
import spark.implicits._

case class A(device_id: Long, cluster: Seq[B])
case class B(location_id: Long, score: Double)
case class C(location_id: Long, location_key: String)
case class D(location_key: String, score: Double)

val df1 = Seq(
  A(1L, Seq(B(1L, 1.1), B(2L, 2.2), B(3L, 3.3))),
  A(2L, Seq(B(4L, 4.4), B(5L, 5.5), B(6L, 6.6))),
  A(3L, Seq(B(7L, 7.7), B(8L, 8.8), B(9L, 9.9)))
).toDF

val df2 = Seq(
  C(1L, "a"),
  C(2L, "b"),
  C(3L, "c"),
  C(4L, "d"),
  C(5L, "e"),
  C(6L, "f"),
  C(7L, "g"),
  C(8L, "h"),
  C(9L, "i")
).toDF

val df3 = df1
  .select($"device_id", explode($"cluster").as("record"))
  .select($"device_id", $"record.location_id".as("location_id"), $"record.score".as("score"))

val df4 = df3
  .join(df2, "location_id")
  .select($"device_id", $"location_key", $"score")

val df5 = df4
  .groupBy($"device_id")
  .agg(
    collect_list(struct($"location_key", $"score")).as("cluster")
  )

df1.printSchema()
df1.show(3, false)

df5.printSchema()
df5.show(3, false)

The output looks like this:
root
 |-- device_id: long (nullable = false)
 |-- cluster: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- location_id: long (nullable = false)
 |    |    |-- score: double (nullable = false)

+---------+------------------------------+
|device_id|cluster                       |
+---------+------------------------------+
|1        |[[1, 1.1], [2, 2.2], [3, 3.3]]|
|2        |[[4, 4.4], [5, 5.5], [6, 6.6]]|
|3        |[[7, 7.7], [8, 8.8], [9, 9.9]]|
+---------+------------------------------+

root
 |-- device_id: long (nullable = false)
 |-- cluster: array (nullable = true)
 |    |-- element: struct (containsNull = true)
 |    |    |-- location_key: string (nullable = true)
 |    |    |-- score: double (nullable = true)

+---------+------------------------------+
|device_id|cluster                       |
+---------+------------------------------+
|1        |[[a, 1.1], [c, 3.3], [b, 2.2]]|
|2        |[[e, 5.5], [d, 4.4], [f, 6.6]]|
|3        |[[g, 7.7], [h, 8.8], [i, 9.9]]|
+---------+------------------------------+

A: I am not sure how much this help you on the performance problem let alone answer your question. But the explode step could be changed to use a flatMap which might increase your performance a little (although I think explode and flatMap should be quite similar under the hood so a performance difference could also be nonexistent):
import org.apache.spark.sql.SparkSession
import org.apache.spark.sql.functions.{ collect_list, struct}

case class A(device_id: Long, cluster: Seq[B])
case class B(location_id: Long, score: Double)
case class C(location_id: Long, location_key: String)
case class D(location_key: String, score: Double)
case class E(device_id: Long, location_id: Long, score: Double)

object ComplexDataStructures {
  def main(args: Array[String]): Unit = {

    val spark = SparkSession
      .builder()
      .appName("Spark SQL basic example")
      .config("spark.master", "local")
      .getOrCreate()

    import spark.implicits._

    val df1 = Seq(
      A(1L, Seq(B(1L, 1.1), B(2L, 2.2), B(3L, 3.3))),
      A(2L, Seq(B(4L, 4.4), B(5L, 5.5), B(6L, 6.6))),
      A(3L, Seq(B(7L, 7.7), B(8L, 8.8), B(9L, 9.9)))
    ).toDS.as[A]

    val df2 = Seq(
      C(1L, "a"),
      C(2L, "b"),
      C(3L, "c"),
      C(4L, "d"),
      C(5L, "e"),
      C(6L, "f"),
      C(7L, "g"),
      C(8L, "h"),
      C(9L, "i")
    ).toDS.as[C]

    val df3 = df1.flatMap{ case A(a,b) => b.map((a,_)).map( x => E(x._1, x._2.location_id, x._2.score)) }

    val df4 = df3.join(df2, df3("location_id") === df2("location_id")).select(df3("device_id"), df2("location_key"), df3("score"))

    val df5 = df4.groupBy("device_id").agg(collect_list(struct("location_key","score")).as("cluster"))

    df5.printSchema()
    df5.show(3, false)

  }
}

A: There does not appear to be a solution.  At least not one that worked for me.  I tried converting df into a dataset and mapping over that.  Inside the map I tried to create a dataframe, do the join, collect, and return new case class.  This doesn't work.  The only thing that worked was converting df2 into a Scala map, and then doing a map over the dataset, where I could lookup the replacement value in the map.  The problem is my real life df2 is too big to fit into driver memory.


text:
Q: NSXMLParser Error When Using with Swift I am using NSXMLParser to fetch some XML from a remote source. The downloadPeopleDirectory initiates the NSXMLParser as shown below:
 func downloadPeopleDirectory() {

        var xml = NSXMLParser(contentsOfURL: NSURL(string: "https://someurl/People.xml"))
        xml.delegate = self
        xml.parse()
    }

When I add the didEndElement implementation then it starts failing with "EXEC_BAD_ACCESS error" at the xml.parse() line. The downloadPeopleDirectory is only invoked once in viewDidLoad of the UITableViewController class.
What am I doing wrong>

A: Found the solution:
I'm developing an iOS app since several months so it made its way through all the beta versions of Xcode. The XMLParser part in that app has this signature:
func parser(parser: NSXMLParser!, didEndElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!) {
    ...
}

This works without errors.
When I remove the exclamation marks, the app crashes with EXC_BAD_ACCESS


text:
Q: Parody names of SF writers in Damon Knight story The Infinity magazine of February 1956 contains the short story "A Likely Story" by Damon Knight. The setup is a meeting of "The Medusa Club", ". . . loosely speaking, an association for professional science fiction writers."
Many of the names of attendees at the meeting are clear parodies of names of SF authors, but I can't identify most of them. Some may, of course, just be funny names. Below are the names, and my guesses for those that I have an idea about. Who are the others?

*

*Preacher Flatt —
Fletcher Pratt

*Ray Alvarez

*Rod Pfehl (the P is silent, as in Psmith)

*Tom Q. Jones went by in a hurry, carrying a big camera.

*Punchy Carrol, nut-brown in a red dress

*Duchamp biting his pipe

*Leigh MacKean with her pale protoNordic face —
Leigh Brackett?

*the ubiquitous fan, Harry You-Know, the one with the glasses and all that hair

*Dorrance Canning, an old idol of mine; he wrote the "Woman Who Slept" series and other gorgeous stuff —
far-fetched, possibly a joke on (from a history of Campbell Soup) "In 1897, John T. Dorrance . . . developed a commercially viable method for condensing soup"

*Art Greymbergen, my favorite publisher

*Bill Plass —
Phil Klass

*Asa Akimisov —
Isaac Asimov

*Ned Burgeon, wearing a sky-blue dinner jacket and a pepper-and-salt goatee, played his famous twenty-one-string guitar —
Ted Sturgeon?

*L. Vague Duchamp —
L. Sprague de Camp

*Larry Bagsby

*Diarrhetics —
Dianetics

*H. Drene Pfeiffer —
H. Beam Piper

*B. U. Jadrys —
Algis (A. J.) Budrys

*Will Kubatius

*the heldentenor bulk of Don W. Gamble, Jr. —
John W. Campbell?

*Kosmo Samwitz —
Sam Moskowitz

*Don Bierce

*Lobbard discovering Scatiology —
L. Ron Hubbard, and Scientology

*Werner Kley —
Willy Ley

*Fred Balester

*M. C. (Hotfoot) Burncloth

*Ham Jibless' homemade telescope

A: Preacher Flatt — Fletcher Pratt
Ray Alvarez — Lester del Rey
Rod Pfehl (the P is silent, as in Psmith) — Fred Pohl
Tom Q. Jones went by in a hurry, carrying a big camera. —
Punchy Carrol, nut-brown in a red dress — Possibly Carol Emshwiller? She was writing in the 1950s.
Duchamp biting his pipe — If this is a different Duchamp than the one referencing L. Sprague de Camp, then it is almost certainly Marcel Duchamp, but it wasn't really a pipe.
Leigh MacKean with her pale protoNordic face — Leigh Brackett
the ubiquitous fan, Harry You-Know, the one with the glasses and all that hair — likely Harlan Ellison, whose antics as a fan in the 1950s are the stuff of legend.
Dorrance Canning, an old idol of mine; he wrote the "Woman Who Slept" series and other gorgeous stuff – The "Woman Who Slept" is a reference to The Man Who Awoke. — Laurence Manning
Art Greymbergen, my favorite publisher — Martin Greenberg
Bill Plass — Phil Klass (a.k.a. William Tenn)
Asa Akimisov — Isaac Asimov
Ned Burgeon, wearing a sky-blue dinner jacket and a pepper-and-salt goatee, played his famous twenty-one-string guitar — Ted Sturgeon who did indeed wear a salt and pepper goatee at some point
L. Vague Duchamp — L. Sprague de Camp
Larry Bagsby — Jerome ("Jerry") Bixby
Diarrhetics — Dianetics (authored by L. Ron Hubbard)
H. Drene Pfeiffer — H. Beam Piper
B. U. Jadrys — A. J. "Algis" Budrys
Will Kubatius — Walter Kubilius
the heldentenor bulk of Don W. Gamble, Jr. — John W. Campbell, who also wrote under the name "Don A. Stuart."
Kosmo Samwitz — Sam Moskowitz
Don Bierce — John Pierce, inventor of the transistor, and an author of science fiction under the pseudonym of J. J. Coupling.
Lobbard discovering Scatiology — L. Ron Hubbard, and Scientology
Werner Kley — Willy Ley
Fred Balester — Alfred Bester
M. C. (Hotfoot) Burncloth — C. [Cyril] M. Kornbluth
Ham Jibless' homemade telescope — James Blish
Balmer — Ray Palmer
Phog Relapse — Rog Phillips
Jerry Thaw —

A: Larry Shaw wrote an article about this story in the fanzine Fan History #3 (April 1, 1956). His assignments were as follows (see page 12). Anagrams (and near-anagrams) are marked with †.

Character
Represents

Rod Pfehl†
Fred Pohl

Tom Q. Jones
George O. Smith

Punchy Carrol1
Judy Merril

Leigh MacKean
Kay MacLean

Dorrance Canning
Laurence Manning

Art Gerymbergen†
Marty Greenberg

Bill Plass
Phil Klass2

Asa Akimisov†
Isaac Asimov

Ned Burgeon
Ted Sturgeon

L. Vague Duchamp3
L. Sprague De Camp

B. U. Jadrys†4
A. J. Budrys

Larry Bagsby
Jerry Bixby

Ray Alvarez
Lester del Rey

H. Drene Pfeiffer
H. Beam Piper

Will Kubatius†
Walter Kubilius

Don W. Gamble, Jr.
John W. Campbell

Horty Plass
Morty Klass5

Jerry Thaw
Larry Shaw

Preacher Flatt
Fletcher Pratt

Kosmo Samwitz†
Sam Moskowitz

Don Bierce
John Pierce

Balmer
[Raymond A.] Palmer

Phog Relapse
Rog Phillips

Werner Kley
Willy Ley

Fred Balester†
Alfred Bester

M. C. (Hotfoot) Burncloth†
C. M. (Hotfoot) Kornbluth6

Ham Jibless†
James Blish

Notes:

*

*An allusion to the folk characters Punch and Judy.

*Better known by his pseudonym William Tenn.

*Possibly an allusion to the artist Marcel Duchamp, as suggested in the other answer.

*"B.U." was 1930s slang, standing for "biological urge" and meaning "sexual attraction" (see New Partridge Dictionary of Slang and Unconventional English, p. 275). It's hard to tell whether this was intentional or an accident of the anagram, but Shaw does say that Knight was fond of sneaking risqué jokes into his stories.

*Mort Klass, the younger brother of Phil Klass (see Damon Knight's The Futurians, p. 185).

*A "hotfoot" is "a prank in which a matchbook is lit and inserted into an unsuspecting victim's shoe" (New Partridge Dictionary, p. 1038). Kornbluth's propensity for the prank is indicated by an incident where "At the [1940 Chicago science fiction] convention Bob Tucker paid a 1¢ bribe to Kornbluth in order to escape being given a hotfoot" (The Futurians, p. 83, spotted by eac2222 in comments).
Shaw also commented:

… plus a ubiquitous fan known as Harry Somebody; many people have taken the model for him to be Harlan Ellison, but I'm sure it was actually Joe Fann that damon had in mind.
(I honestly don't know just how Joycean damon was being in some of these cases. Ham Jibless is a lovely anagram of James Blish, but it could be even more than that: Ham Brooks, in the old Doc Savage stories, was a dapper character who carried a sword-cane; James Blish is a dapper character who used to carry an umbrella-cane.)

I guess the joke in "ubiquitous fan, Harry You-Know", is that Joe Fann was a fan by name as well as by nature.
It's not mentioned in Shaw's article, but the "Medusa Club" of the story represented the Hydra Club, many of whose members appeared in this group caricature by Harry Harrison, published in Marvel Science Fiction, November 1951.


text:
Q: Jquery height incorrect when set previously I have made a separate part of a website which we are loading into the joomla site through an iframe but I want to adjust the height of the container of the iframe.
Therefore I am trying to retrieve the height of my html with the following code which works fine (calling this from inside the iframe):
$(document).ready(function() {
    var height = $(document).height();
    alert( height );
});

The height is alerted correctly at all pages.
The problem rises when I adjust the height of the iframe container. When I use this code:
$(document).ready(function() {
    var height = $(document).height();
    alert( height );
    parent.document.getElementById('blockrandom').style.height = height + 'px';
});

Now the height will be the same or larger than the previous height, so when you go from a page with the height of 900px to one of 500px the height will remain 900px (in the alert as well). From small to big works just fine.
Thanks in advance!

A: Yes, I have found that once the height is adjusted, using native property or jQuery makes no difference, the resultant height value does not appear to reflect the new values set. So to dynamically adjust elements during same page interaction, I have, so far, had to resort to a heuristic for the height.
I end up evaluating the content within the element and constructing an acceptable, if not perfectly accurate, proxy height value. For example, let's say I have a box with an original set of 22 label-fields.
As the user adjusts parent values or options, I may end up with any number of resultant fields between 0 and the full 22.
So if I have 10 left after some user event, I run a function that counts up the visible elements and calculates a height. So 10 fields x 22pixels means I readjust the containing element to about 220 pixels.
Specifically, I have an abstracted function into which I assign a default height, a base height (which allows for some always exposed non-adjustable elements like text/instructions, whatever), and the element height multiplier.
On load and between events I set the element container to the default height. After counting the variable elements, I calculate the value by multiplying the variable elements by the multiplier and adding that to the base height.
So far that is the best I have been able to do and is fairly simple. Using jQuery selectors, it only takes a few lines to count and a couple more to calculate and set the height.
NB: It is of note this is only necessary for elements that do not automatically adjust their height via their content. The greatest offender of this is the jQuery tab in which, in my case, this issue occurs. Most non-manipulated relative height elements auto adjust their space as elements are toggled between display = block||none.
Here is some example code:
setElemHeight = function(options) {
    var _elem = options.containerElement;
    var _nBase = options.nBaseHeight;
    var _nMltplr = options.nMultiplierHeight;
    // COUNT ROWS
    var _nCnt = 0;
    $( '#' + _elem.id + ' div div:first-child  > input').each( function() {
        if(this.style.display != 'none') _nCnt++;
    });
    $(_elem).height(_nBase + (_nCnt * _nMltplr));
}

I've abstracted out enough for my purposes but you could take it a little farther so the selector children elements are dynamic.


text:
Q: Reference a Range from a Range Object I'm trying to find a way to refer a range from another range for example,
A range that holds the cells "A5:A10", 6 cells are in that range. What is needed is the range next to it which is "B5:B10".How can I refer it when there is already a range object ("A5:A10" in this case") to the range next it.
   Dim R As Range
   Dim A As Range
   Set R = R("A5:A10").Select
   Set R =
'Code to refer to next column is here

Sorry this could be the wrong syntax to start off with , it's been a while since I coded in vba, it's just to clarify what's is needed solve this.

A: Try this:
Sub setRanges()
Dim ws As Worksheet
Dim rngA As Range
Dim rngB As Range

'set the worksheet -- Adjust the worksheet name as required
Set ws = ThisWorkbook.Worksheets("Sheet1")
'set the first range to a range in the worksheet
Set rngA = ws.Range("A5:A10")
' set the second range to an offest of the first range
' in this case, use an offset of one column, with the same row
' ... remember the offset command takes rows in the first parameter
' ... and the second parameter is for the columns
Set rngB = rngA.Offset(0, 1)
' so, zero row offset, i.e. stay in the same row
' and 1 column offset to get the rngB for one column to the right of rngA
rngB.Select
' don't use Select in your code. This is just to demo.

End Sub


text:
Q: Exception after adding ProGuard to project I've added ProGuard to my project and got this error. I guess It can be Jsoup lib which I using to send POST and GET requests and parse responses.
There are no separate line that throwns this exception.
Can you help me to solve this problem with ProGuard?
java.lang.RuntimeException: An error occured while executing doInBackground()
        at android.os.AsyncTask$3.done(AsyncTask.java:299)
        at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
        at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
        at java.util.concurrent.FutureTask.run(FutureTask.java:137)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
        at java.lang.Thread.run(Thread.java:864)
        Caused by: java.lang.ExceptionInInitializerError
        at org.jsoup.nodes.Document$OutputSettings.<init>(Unknown Source)
        at org.jsoup.nodes.Document.<init>(Unknown Source)
        at org.jsoup.parser.TreeBuilder.void initialiseParse(java.lang.String,java.lang.String,org.jsoup.parser.ParseErrorList)(Unknown Source)
        at org.jsoup.parser.TreeBuilder.org.jsoup.nodes.Document parse(java.lang.String,java.lang.String,org.jsoup.parser.ParseErrorList)(Unknown Source)
                                        boolean process(org.jsoup.parser.Token)
        at org.jsoup.parser.HtmlTreeBuilder.org.jsoup.nodes.Document parse(java.lang.String,java.lang.String,org.jsoup.parser.ParseErrorList)(Unknown Source)
                                            boolean process(org.jsoup.parser.Token)
                                            boolean process(org.jsoup.parser.Token,org.jsoup.parser.HtmlTreeBuilderState)
                                            void transition(org.jsoup.parser.HtmlTreeBuilderState)
                                            org.jsoup.parser.HtmlTreeBuilderState state()
                                            void framesetOk(boolean)
                                            void maybeSetBaseUri(org.jsoup.nodes.Element)
                                            org.jsoup.nodes.Element insert(org.jsoup.parser.Token$StartTag)
                                            org.jsoup.nodes.Element insert(java.lang.String)
                                            void insert(org.jsoup.parser.Token$Comment)
                                            void insert(org.jsoup.parser.Token$Character)
                                            boolean isElementInQueue(org.jsoup.helper.DescendableLinkedList,org.jsoup.nodes.Element)
                                            void popStackToClose(java.lang.String[])
                                            void insertOnStackAfter(org.jsoup.nodes.Element,org.jsoup.nodes.Element)
                                            void replaceInQueue(java.util.LinkedList,org.jsoup.nodes.Element,org.jsoup.nodes.Element)
                                            boolean inSpecificScope(java.lang.String,java.lang.String[],java.lang.String[])
                                            boolean inSpecificScope(java.lang.String[],java.lang.String[],java.lang.String[])
                                            boolean inScope(java.lang.String,java.lang.String[])
                                            void insertInFosterParent(org.jsoup.nodes.Node)
        at org.jsoup.parser.Parser.org.jsoup.nodes.Document parseInput(java.lang.String,java.lang.String)(Unknown Source)
                                   boolean isTrackErrors()
        at org.jsoup.helper.DataUtil.org.jsoup.nodes.Document parseByteData(java.nio.ByteBuffer,java.lang.String,java.lang.String,org.jsoup.parser.Parser)(Unknown Source)
                                     java.nio.ByteBuffer readToByteBuffer(java.io.InputStream,int)
                                     java.lang.String getCharsetFromContentType(java.lang.String)
        at org.jsoup.helper.HttpConnection$Response.org.jsoup.nodes.Document parse()(Unknown Source)
        at com.ThreeBoots.api.API.java.lang.Object userLogin(java.lang.String,java.lang.String)(Unknown Source)
                                  java.lang.Object userLoginFacebook(java.lang.String)
                                  boolean userLogout()
                                  boolean saveArticle(com.ThreeBoots.database.Article)
                                  java.lang.String loadPhoto(android.graphics.Bitmap)
                                  java.lang.String loadPhoto(android.widget.ImageView)
                                  java.lang.Object userSaveProfile(java.lang.String,java.lang.String,java.lang.String)
                                  java.lang.String sendRequest(java.lang.String,java.lang.String[])
                                  java.lang.String sendImageLoadRequest(java.lang.String,android.graphics.Bitmap)
                                  void processingBrands(org.json.JSONObject)
                                  java.lang.Object getListFromJSON(java.lang.Class,org.json.JSONArray)
                                  void insert(java.lang.Class,java.lang.Object)
        at com.ThreeBoots.api.API.java.lang.Object userRegister(java.lang.String,java.lang.String)(Unknown Source)
                                  boolean sync()
                                  java.lang.String sendRequest(java.lang.String)
                                  void processingMaterials(org.json.JSONObject)
        at com.ThreeBoots.api.API.java.lang.Object userRegister(java.lang.String,java.lang.String)(Unknown Source)
                                  boolean sync()
                                  java.lang.String sendRequest(java.lang.String)
                                  void processingMaterials(org.json.JSONObject)
        at com.ThreeBoots.asyncs.RequestAsync.java.lang.Object doInBackground(java.lang.String[])(Unknown Source)
                                              void asyncSaveArticlePostExecute(java.lang.Boolean)
                                              void asyncRegistrationPostExecute(java.lang.Object)
                                              void startMainActivity()
                                              void startLoginActivity(android.app.Activity)
        at com.ThreeBoots.asyncs.RequestAsync.java.lang.Object doInBackground(java.lang.Object[])(Unknown Source)
        at android.os.AsyncTask$2.call(AsyncTask.java:287)
        at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
        ... 5 more
        Caused by: java.lang.ExceptionInInitializerError
        at org.jsoup.nodes.Entities$EscapeMode.<clinit>(Unknown Source)
        ... 20 more
        Caused by: java.lang.NullPointerException
        at java.util.Properties.load(Properties.java:246)
        at org.jsoup.nodes.Entities.java.util.Map loadEntities(java.lang.String)(Unknown Source)
        at org.jsoup.nodes.Entities.<clinit>(Unknown Source)
        ... 21 more

A: Do not add the parsing classes in your proguard to get obfuscate.
 keep it as it is. Write the below line in your proguard file
 -keep class yourclassname.** { *; }

A: Proguard has skipped some of the files required, do this
-keep <your calss name>.** {
  *;
}

this will make sure proguard won't skip them while obfuscating


text:
Q: Executable run from electron project isn't loading resources I am making a electron application that launches an executable stored on my computer when run. If I run the exe by itself, it works correctly and loads all of the fonts. However, when run by the electron app, it opens, but non of the font files can be loaded. The exe is a compiled release project made in visual studio.
I tried putting the res folder into the same directory as index.html to no avail.
Code for index.html:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Hello World!</title>

Hello World!

Code for main.js
const {app, BrowserWindow} = require('electron')
const path = require('path')
const url = require('url')

function createWindow () {
// Create the browser window.
win = new BrowserWindow({width: 800, height: 600})

// and load the index.html of the app.
win.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}))

  win.webContents.openDevTools()

  // Emitted when the window is closed.
  win.on('closed', () => {

  win = null
  })
}

app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', () => {

if (process.platform !== 'darwin') {
  app.quit()
}
  })

app.on('activate', () => {
  if (win === null) {
    createWindow()
  }
})

Thanks!

A: Does your exe use a relative path to load the fonts? If so, either change the exe to be more flexible, or in your call to execFile() specify the optional 3rd arg to specify the desired working directory.
var child = require('child_process').execFile;
var exePath = "C:\\Users\\name\\Documents\\Visual Studio 2015\\Projects\\Ten\\Release";
var exe = exePath + "\\Ten.exe";
var parameters = ["test"];
var options = {cwd:exePath};

child(exePath, parameters, options, function(err, data){
    console.log(err);
    console.log(data.toString());
  });

If that doesn't work, my guess would be some kind of permissions problem. Is your electron app running as a different user to when you test the exe?


text:
Q: Converting a type to its nullable equivalent I have this bit of code
 NullableConverter nullableConverter = new NullableConverter(type);
 Type baseType = nullableConverter.UnderlyingType;
 Object value = Convert.ChangeType(rule.Data, baseType);
 constant = Expression.Constant(value);

In this case type is decimal? but it could be any nullable type.
I need value to be of type decimal?, not type decimal as it currently is.  The problem, is that Convert.ChangeType doesn't work properly with nullable types.  So I'm creating a non-nullable first.
How can I convert the string contained in rule.Data to type?

A: You can't.
When a nullable struct is boxed in an Object it doesn't store a boxed nullable struct.  If the struct doesn't have a value it will just box null, and if it has a value it will box the underlying value of the nullable struct.
You would need to not be boxing it for this to even be possible.


text:
Q: Bluer or more blue in "its more blue offerings can get steamier"? As I know, a monosyllabic adjective is usually made comparative with -er, while polysyllabic adjective is usually made comparative with word more. The problem is that I found an article that uses word "more blue" to refer to something that is closer to pornographic material. Is this correct?

Romance is more nuanced here than the Shoujo style of "never been kissed", with its heroines often either unlucky in love, working through relationship troubles, or generally experienced. On the flip side, its more blue offerings (known as "Ladies Comics") can get steamier than even the most borderline Teens Love — harems getting sexual, pent-up coworkers, women with "pet"-like subordiates — with a subgenre even dedicated to adapting Harlequin romance.

A: This is not a "problem" at all. English often follows conventions where exceptions abound.
I would reword your assertion:

a monosyllabic adjective usually can be made comparative with -er, while a polysyllabic adjective that doesn't end with y is usually made comparative with the word more

However, just because a word can be made comparative with -er doesn't mean it must be made comparative that way.
In fact, an Ngram shows that, although bluer and greener are more common than more blue and more green, there are still plenty of instances of the latter.
It's also worth considering that many colors like green or blue can have other meanings besides the color itself (such as ecofriendly and pornographic). This might influence whether or not a writer believes that more red sounds better than redder in a certain context:

Since 2008, Texas has consistently become more red, not less.1

That all said, you wouldn't want to use more or -er to make comparative adjectives indiscriminately. Some combinations just wouldn't make good sense:

The company sold more few cars last year.
  The company sold fewer cars last year.
Seattle is norther than Toronto.
  Seattle is more north than Toronto.
  (even better, I think): Seattle is further north than Toronto.


text:
Q: Converting an RGB image into an HSI image without using opencv functions I am sort of a beginner when it comes to c++ and opencv.
I have this assignment where i have to successfully convert an image from RGB to HSI and then split the HSI image into the 3 channels Hue, Saturation and respectively Intensity, without using any library functions when implementing my algorithm, after that the 3 images have to be displayed.
I was able to do most of these but when converting from RGB to HSI i am completely lost. From what i saw on other posts the pixel values should be put in a matrix and then changed based on my algorithms, after that the new values should go into a new matrix (HSI).
My main problem (i think) is that i cannot seem to put the values into the new matrix, i tried different methods but the outcome was the same.
Any input is welcome.
Best Regards
Stefan
#include <opencv\highgui.h>
#include <opencv\cv.h>
#include <iostream>
using namespace cv;
using namespace std;

int main()
{
Mat rgb;

rgb = imread("Flower.jpg", CV_LOAD_IMAGE_COLOR);

unsigned char *input = (unsigned char*)(rgb.data);

Mat hsi = rgb.clone();

double R,G,B,a,H,S,I;
int  i,j;
const double PI= 3.14;
for(int i = 0;i < hsi.rows ;i++){
    for(int j = 0;j < hsi.cols ;j++){
        B = input[hsi.step * j + i ];
        G = input[hsi.step * j + i + 1];
        R = input[hsi.step * j + i + 2];
    }

    if (R < G && R < B)
        a = R;
    if (G < R && G < B)
        a = G;
    if (B < G && B < R)
        a = B;
    I = (R+G+B)/3.0;
    S = 1 - 3.0/(R+G+B)*a;
    if (S == 0.0)
    {
        H = 0.0;
    }
    else
    {
        if (B <= G)
        H = acos((((R-G)+(R-B))/2.0)/(sqrt((R-G)*(R-G) + (R-B)*(G-B))));
        else
        {
            if (B > G)
            H = 2*PI - acos((((R-G)+(R-B))/2.0)/(sqrt((R-G)*(R-G) + (R-B)*(G-B))));
        }

    }
}

namedWindow("RGB", CV_WINDOW_AUTOSIZE);
imshow("RGB", rgb);
namedWindow("HSI", CV_WINDOW_AUTOSIZE);
imshow("HSI", hsi);

waitKey(0);
return 0;
}

A: Your code has two problems.
First, you perform calculation outside the second loop:
for(int i = 0;i < hsi.rows ;i++){
    for(int j = 0;j < hsi.cols ;j++){
    }
    // HSI calculation
}

So, you work only with last pixel in each row.
Second, you don't write results to hsi matrix.
Use this code template:
Mat bgr = ...; // OpenCV uses BGR format
Mat hsi(bgr.size(), CV_8UC3);
for (int i = 0; i < bgr.rows; ++i)
{
    const Vec3b* bgr_row = bgr.ptr<Vec3b>();
    Vec3b* hsi_row = hsi.ptr<Vec3b>();
    for (int j = 0; j < bgr.cols; ++j)
    {
        double B = bgr_row[j][0];
        double G = bgr_row[j][1];
        double R = bgr_row[j][2];
        double H = ...;
        double S = ...;
        double I = ...;
        hsi_row[j] = Vec3b(H, S, I);
    }
}


text:
Q: Accessing the structure of a dll in dotnet reg Is it possible to know the total structure of a dll as

*

*names of variables used

*signature used

*declarations used

*variables used

*class used

*method used

with code or without code through c#.net code without using any decompiler.
is it possible to scan the dll through automation there by listing out
1) what all the packages imported in it
2) class used in it
3) method used in it  etc......

A: Without writing code
Use software Reflector software for .net
With writing code
You can use Reflection Namespace provided by .net Reflection in Dot Net. You can also you use some software to get member information of assembly.

A: All you need is System.Reflection namespace


text:
Q: Fancybox v2 override/format title How can i override the Title in the new version of fancy box?
$(document).ready(function() {
    $(".photogalleryLightbox li a").fancybox({
        helpers:{
                    title: {
                        type: 'inside',
                        beforeShow: function(opts)
                                    {
                                        console.log('beforeShow title helper');
                                    },
                        },
                    buttons : {}
                },
        beforeShow: function()
        {
            console.log('beforeShow');
            // var obj = $(currentArray[currentIndex]); // from prev. version
            // if (obj.next().length) return obj.next().html(); // from prev. version
        }
    });
});

I tried this but don't know how to get the variables as index.

A: You can use callbacks to update title, example:
$(".photogalleryLightbox li a").fancybox({
        beforeLoad : function() {
            this.title = 'My Custom Title';
        },
        helpers: {
            title: {
                type: 'inside',
                beforeShow: function(opts) {
                    console.log('beforeShow title helper');
                },
            },
            buttons : {}
        },
        beforeShow: function() {
            console.log('beforeShow');
            // var obj = $(currentArray[currentIndex]); // from prev. version
            // if (obj.next().length) return obj.next().html(); // from prev. version
        }
    });

A: I have added image-numbers to the title like this:
beforeShow : function() {
  this.title = 'Bild ' + (this.index + 1) + ' von ' + this.group.length + '' + (this.title ? '' + this.title + '' : '');
}

This works great but the calculation of sizes and offsets of div.fancybox-wrap goes wrong:
With my image-numbers every image has a title in the lightbox, but not all of them get a 'real' title from the thumbnails title-tag.
But the sizes are calculated only with those 'real' titles.
Adding the image-numbers in beforeLoad() works too but with the same problem.
Has anybody an idea how to fix the calculation?
I haven't found it in the fancybox-code yet, so I could fix it there but I would prefer to do it in a callback function and not by changing the source code.


text:
Q: Как можно хранить переменную в кеше - Android JAVA? Мне нужно сделать такую тему, но не знаю с чего начать( Уже несколько дней пытаюсь найти решение.
Задача:
Когда я первый раз захожу в приложение и прохожу слайд, то после этого меня кидает на экран регистрации, если я выйду с приложения не закончив регистрацию, то если пользователь снова зайдет в приложение и все таки решит зарегистрироваться, то ему не придется заново проходить слайд. Надо чтобы его сразу кинуло на регистрацию, а если он очистит кэш или удалит приложение, то естественно заново ему проходить слайд.
Если кто-то работал с javascript, то ему будет известна такая штука как "localstorage", вот по типу такого, только в android разработке на java.
Благодарю.


text:
Q: Decrypt aes crypted file with php How can I decrypt aes file with php which is encrypted with c#.
private static void AES_Encrypt(string filePath, string passKey)
    {
        string newFilePath = filePath + "." + "aes";
        //byte[] keyPair = System.Text.Encoding.ASCII.GetBytes(keyRSA);
        byte[] salt = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };
        System.IO.FileStream fsCrypt = new System.IO.FileStream(newFilePath, System.IO.FileMode.Create);
        byte[] passBytes = System.Text.Encoding.UTF8.GetBytes(passKey);
        System.Security.Cryptography.RijndaelManaged AES = new System.Security.Cryptography.RijndaelManaged();
        AES.KeySize = 128;
        AES.BlockSize = 128;
        AES.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
        var key = new System.Security.Cryptography.Rfc2898DeriveBytes(passBytes, salt, 1);
        AES.Key = key.GetBytes(AES.KeySize / 8);
        AES.IV = key.GetBytes(AES.BlockSize / 8);
        AES.Mode = System.Security.Cryptography.CipherMode.CBC;
        fsCrypt.Write(salt, 0, salt.Length);
        System.Security.Cryptography.CryptoStream cs = new System.Security.Cryptography.CryptoStream(fsCrypt, AES.CreateEncryptor(), System.Security.Cryptography.CryptoStreamMode.Write);
        System.IO.FileStream fsIn = new System.IO.FileStream(filePath, System.IO.FileMode.Open);
        fsIn.CopyTo(cs);
        fsIn.Flush();
        fsIn.Close();
        cs.Flush();
        cs.Close();
        fsCrypt.Close();
    }

I can decrypt it with c# but when I am trying to decrypt it with php I get some errors.
<?php

require DIR . '/vendor/autoload.php';
use phpseclib\Crypt\AES;
$cipher = new AES('cbc');
$cipher->setKey(str_repeat('a', 16));
$cipher->setIV(str_repeat('b', 16));
$file = file_get_contents("file.aes");
echo $cipher->decrypt($file);
$encryptedData = openssl_decrypt($file, 'AES_128_CBC', "123123", 0);

When I am using $cipher->decrypt($file); it does not work but no error shows up.
When I am using $encryptedData = openssl_decrypt($file, 'AES_128_CBC', "123123", 0);
I get this error .
Warning: openssl_decrypt(): Unknown cipher algorithm in C:\OpenServer\domains\panel2\aes.php on line 14


text:
Q: Hide copy warnings in PHP I know it's not a good practice to hide the warnings using @copy, but what other alternatives are there?
Is there any way you can make sure copy would work or not ?

A: Use is_readable() and is_writable() to check the status of the source and target before attempting the copy().

A: Really, you should not be displaying errors to the browser. Turn off display_errors in php.ini.
Then you can test if it succeeded by its boolean return value, without needing to worry about the warnings on screen.
if (!copy('srcfile', 'destfile')) {
  // something failed.
}

A: If you use '@' before a function you'll not the warning or the notice returned but you'll keep the result (boolean, string...).
Try this :
if (!@copy('srcfile', 'destfile')) {
    // something failed.
}


text:
Q: Multiple regressions on sets of different independent variables At the beginning: I am very 'fresh' user of R so excuse me all my mistakes and silly questions.
I would like to estimate 570 (30*19) equations (and get summary() of them). Each equation is in the form: y~x2+x3+x4, where x2, x3 and x4 are the list.
In comment #1 is my failed trial - it can show what i want to achieve.
In comment #2 such equation is working but I need to manually change variable "jan" (to feb, mar, and so on) that should be taken from list "x2". This code return me 30 equations but I need to estimate each of them with one more variable - x2 from the list of 19's elements named "x2"
How to do it automatically ? I mean:
mapply - applies the rlm model to each of the element of the lists so, e.g:
element 1 from list "y" is corresponding with element 1 from "x3" and element 1 from "x4" (I took care about the order when I was preparing csv file) - this is correct but I would like to run such equations like below comment #2 with additional variable x2. This variable is not corresponding any other variables - it always should be in each of the 30 regressions of elements of list "y", just changing from element 1 of list "x2" to element 19 of "x2".
In the end I would like to have 570 (30*19) "summ" matrix and 570 "archtest"
I do hope this is not to muddled, if yes I will try to post it again in some time with clarification.
Thank you kindly for understanding and help.
data<-read.table("MAY EFFECT Rdata 18.09.2013-3 ind prod CCI.csv", head=T, sep=";", dec=".")
library(MASS)
library(FinTS)
index1<-data[,2:31]   # y  30  elements; rates, 30 countries
index2<-data[,32:50] # x2  19  elements; month dummies, months and other
index3<-data[,51:80] # x3  30  elements; IP
index4<-data[,81:110] # x4 30  elements; CCI

y<-as.list(index1)
x2<-as.list(index2)
x3<-as.list(index3)
x4<-as.list(index4)

#1. this is my trial I need to make "x2" variable that stands for month dummy be respectively equal jan, feb ... and so on till
# the end of list x2 (19 elements)
result<-mapply(function(x2) mapply(function(y,x3,x4,x2) summary(rlm(y~x2+x3+x4, maxit = 15600, data=data)), y,x3,x4),x2)

#2. this code below is returning 10x30 list matrix "summ" and 5x30 data frame "archtest"
summ<- mapply(function(y,x3,x4,jan) summary(rlm(y~jan+x3+x4, maxit = 15600, data=data)), y,x3,x4)
archtest<-mapply(function (y,x3,x4,jan,resi) {regr<-rlm(y~jan+x3+x4, maxit = 15600, data=data)
                                              ArchTest (resid(regr), lags=12, demean = FALSE)},y,x3,x4)

####

A: If I understand you correctly, there are 30 sets of (y, x3, and x4) and for each of these 19 sets of x2. If that's correct, then something like this should work:
set.seed(1)
data <- matrix(rnorm(50*110),nrow=50)  # completely random data...

get.summary <- function(i,j) {
  dta <- data.frame(y=data[,1+i],x2=data[,31+j], x3=data[,50+i],x4=data[,80+i])
  summary(lm(y~x2+x3+x4, data=dta))
}

smry.list <- do.call(cbind,lapply(1:19,function(j){lapply(1:30,get.summary,j)}))
smry.list[1,1]

So now smry.list contains all 570 summaries, arranged in 19 columns by 30 rows.
You can do something similar with mapply(...) but the result is a one-dimensional list:
smry.mapply<- mapply(get.summary,rep(1:30,each=19),1:19, SIMPLIFY=F)
smry.mapply[1]


text:
Q: Reshaping columns to rows and have apercentage I have a data like this:
structure(list(A = c("a", "b", "c", "c", "c", "b", "a", "b"),
    B = c("b", "b", "c", "a", "b", "c", "c", "a"), C = c("c",
    "c", "c", "a", "a", "a", "b", "b"), D = c("a", "b", "c",
    "c", "c", "a", "b", "b"), group = c("x", "y", "x", "x", "x",
    "y", "y", "y")), class = "data.frame", row.names = c(NA,
-8L))

I want to reshape it that columns' name shift to rows, and also have a percentage (per column) of stack in each group based on facet name.
The desire data is like this (per column is not accurate) :
   facet group stack  per
1      A     x     a  2.1
2      A     y     b  4.2
3      A     x     c 10.2
4      A     y     a 20.2
5      A     x     b  5.6
6      A     y     c 11.7
7      B     x     a  5.4
8      B     y     b 17.7
9      B     x     c  9.0
10     B     y     a 14.7
11     B     x     b  3.2
12     B     y     c 13.5
13     C     x     a  8.8
14     C     y     b 11.5
15     C     x     c  0.7
16     C     y     a  7.3
17     C     x     b  6.8
18     C     y     c  5.4
19     D     x     a  7.9
20     D     y     b 12.2
21     D     x     c 16.1

A: Perhaps something like this using dplyr and tidyr?  First pivot_longer, then get group/facet/stack counts, and divide those counts by the sum of such counts (within group/facet).
library(dplyr)
library(tidyr)

pivot_longer(data, -group, names_to="facet", values_to = "stack") %>%
  group_by(facet,group,stack) %>%
  summarize(per =n()) %>%
  mutate(per =per/sum(per))

Output:
   facet group stack   per
   <chr> <chr> <chr> <dbl>
 1 A     x     a      0.25
 2 A     x     c      0.75
 3 A     y     a      0.25
 4 A     y     b      0.75
 5 B     x     a      0.25
 6 B     x     b      0.5
 7 B     x     c      0.25
 8 B     y     a      0.25
 9 B     y     b      0.25
10 B     y     c      0.5
11 C     x     a      0.5
12 C     x     c      0.5
13 C     y     a      0.25
14 C     y     b      0.5
15 C     y     c      0.25
16 D     x     a      0.25
17 D     x     c      0.75
18 D     y     a      0.25
19 D     y     b      0.75


text:
Q: Will the work be positive or negative if i move a positive test charge away from a positive point charge? Assume we have apositive source charge And near it a positive test charge And we moved this test charge away from the source charge to a certain point, will the external work be positive or negative

A: Think about it this way: that positive charge should naturally repel. When it gets to its location after being allowed to repel, it will have kinetic energy. You therefore have to do negative work to get it to that position and have it be stationary by taking away its kinetic energy.


text:
Q: How to create a new column of zipped list items from separate two columns in DataFrame? This question is somewhat motivated from a previous question I asked - Pandas groupby make two columns lists separately. This time I want to create a new column where each value is a single list that contains tuples of the zipped values from the other two columns. For example:
# Original DataFrame
      fruit      sport                       weather
0     apple      [baseball, basketball]      [sunny, windy]
1     banana     [swimming, hockey]          [cloudy, windy]
2     orange     [football]                  [sunny]

# Desired DataFrame
      fruit      sport                       weather             pairs
0     apple      [baseball, basketball]      [sunny, windy]      [(baseball, sunny), (basketball, windy)]
1     banana     [swimming, hockey]          [cloudy, windy]     [(swimming, cloudy), (hocky, windy)]
2     orange     [football]                  [sunny]             [(football, sunny)]

I've tried the following code, but it gives me something else:
df['pairs'] = list(zip(df['sport'], df['weather']))

# Output DataFrame
      fruit      sport                       weather             pairs
0     apple      [baseball, basketball]      [sunny, windy]      ([baseball, sunny], [basketball, windy])
1     banana     [swimming, hockey]          [cloudy, windy]     ([swimming, cloudy], [hocky, windy])
2     orange     [football]                  [sunny]             ([football], [sunny])

As you can see, it's "reversed" from what I want to do. What is the appropriate way that I should go about this? Thanks in advance.

A: I think you are missing another list(zip()):
df['pairs'] = list(list(zip(a,b)) for a,b in zip(df['sport'], df['weather']))

Output:
    fruit    sport                       weather              pairs
 0  apple    ['baseball', 'basketball']  ['sunny', 'windy']   [('baseball', 'sunny'), ('basketball', 'windy')]
 1  banana   ['swimming', 'hockey']      ['cloudy', 'windy']  [('swimming', 'cloudy'), ('hockey', 'windy')]
 2  orange   ['football']                ['sunny']            [('football', 'sunny')]

A: Use DataFrame.apply over axis=1 with zip:
df['pairs'] = df.apply(lambda x: list(zip(x['sport'], x['weather'])), axis=1)

    fruit                   sport          weather                                     pairs
0   apple  [baseball, basketball]   [sunny, windy]  [(baseball, sunny), (basketball, windy)]
1  banana      [swimming, hockey]  [cloudy, windy]     [(swimming, cloudy), (hockey, windy)]
2  orange              [football]          [sunny]                       [(football, sunny)]

A: You could take advantage of the fact that map has an embedded zip, and do:
df['pairs'] = [list(x) for x in map(zip, df['sport'], df['weather'])]
print(df)

Output
    fruit  ...                                     pairs
0   apple  ...  [(baseball, sunny), (basketball, windy)]
1  banana  ...     [(swimming, cloudy), (hockey, windy)]
2  orange  ...                       [(football, sunny)]

[3 rows x 4 columns]

Or you could use itertuples:
df['pairs'] = [list(zip(*x)) for x in df[['sport', 'weather']].itertuples(index=False)]


text:
Q: Trying to modify a list based on multiple user inputs I have a list of lists with products, price, and quantity
[['apple', 'orange', 'banana'], [.50, .75, .20], [10,8,12]]

I'm trying to permanently change the list based on asking the user which product they wish to update, if they wish to update the price or the quantity, and then update it how they choose

A: idx = products[0].index(userInput)
if userInput_2 == 'price':
    products[1][idx] = new value
if userInput_2 == 'quantity':
    products[2][idx] = new value

A: Assigning user input to a list index is not different from the way you normally assign value to a list index.
products = [['apple', 'orange', 'banana'], [.50, .75, .20], [10, 8, 12]]

valid = False

while not valid:
    userIn = input('Which product would you like to update? ')

    if userIn in products[0]:
        x = products[0].index(userIn)
        valid = True
        userIn2 = input('Would you like to update the quantity or price?')

        if userIn2.lower() == 'price':
            products[1][x] = int(input('Enter new value for price: '))

        elif userIn2.lower() == 'quantity':
            products[2][x] = int(input('Enter new value for quantity: '))

print(products)

A: Unless you /need/ to use a list for an exercise, I'd argue that it's the incorrect data structure for this.
products = {
    'apple': {'price': .50, 'quantity': 10},
    'orange': {'price': .75, 'quantity': 8},
}

product_str = input(f'Which product would you like to update? ({list(products.keys())})')
try:
    product = products[product_str]
except KeyError as err:
    raise KeyError(f'Unknown product ({err})')

attrib_str = input(f'Which attribute would you like to update? ({list(products["orange"].keys())})')
try:
    product[attrib_str] = float(input(f'Enter new value for {attrib_str}:'))
except KeyError as err:
    raise KeyError(f'Unknown attribute ({attrib_str})')

The above is just off the top of my head and untested, but demonstrates the idea. You could also store the values as an indexed list or something to that effect, I just like dicts for this simple case for readability and easy error handling.

A: Solution
It is likely you will eventually want to extend your list of fruits. The following solution makes this simpler by encapsulating all the required information in a dict.
Code
def update_fruits(lst, info):
    fruit = lst[0].index(input('Which product would you like to update? ').lower())
    column, tp = info[input('Would you like to update the quantity or price? ').lower()]

    lst[column][fruit] = tp(input('What\'s the new values? '))

lst = [['apple', 'orange', 'banana'], [.50, .75, .20], [10, 8, 12]]
info = {'price': (1, float), 'quantity': (2, int)}

update_fruits(lst, info)

print(lst)

Output
Which product would you like to update? banana
Would you like to update the quantity or price? price
What's the new values? 0.33
[['apple', 'orange', 'banana'], [0.5, 0.75, 0.33], [10, 8, 12]]

Adding a fruit
A fruit can be dynamically added like so.
for col, value in zip(lst, ['mango', 0.99, 5]):
    col.append(value)

update_fruits(lst, info)

print(lst)

Output
Which product would you like to update? mango
Would you like to update the quantity or price? quantity
What's the new values? 9
[['apple', 'orange', 'banana', 'mango'], [0.5, 0.75, 0.2, 0.99], [10, 8, 12, 9]]


text:
Q: Call WCF WsFederationHttpBinding service from .Net Core using STS I have an app.config to call this service from .Net framework but now I have to do the same from core app. Here's the WCF client config:
    <bindings>
    <ws2007FederationHttpBinding>
    <binding name="WS2007FederationHttpBinding_certificate" maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647">
          <readerQuotas maxDepth="128" maxStringContentLength="2147483647" maxArrayLength="2147483647" maxBytesPerRead="2147483647"
            maxNameTableCharCount="2147483647"/>
          <security mode="TransportWithMessageCredential">
            <message establishSecurityContext="false" negotiateServiceCredential="true">
              <claimTypeRequirements>
                <add claimType="http://docs.oasis-open.org/wsfed/authorization/200706/claims/action" isOptional="true"/>
                <add claimType="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier" isOptional="false"/>
                <add claimType="http://schemas.microsoft.com/ws/2008/06/identity/claims/role"/>
              </claimTypeRequirements>
              <issuer address="https://some.url.com/STS/Issue.svc/trust/13/certificatemixed" binding="ws2007HttpBinding"
                bindingConfiguration="certificateMixed"/>
              <issuerMetadata address="https://some.url.com/STS/Issue.svc/mex"/>

             <!-- THIS IS THE PROBLEM PART -->
              <tokenRequestParameters>
                <wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
                  <EndpointReference xmlns="http://www.w3.org/2005/08/addressing">
                    <Address>URN:MY.TEST.SERVICE</Address>
                  </EndpointReference>
                </wsp:AppliesTo>
              </tokenRequestParameters>
            </message>
          </security>
        </binding>
      </ws2007FederationHttpBinding>

      <ws2007HttpBinding>
        <binding name="certificateMixed">
          <security mode="TransportWithMessageCredential">
            <message clientCredentialType="Certificate" establishSecurityContext="false"/>
          </security>
        </binding>
      </ws2007HttpBinding>
    </bindings>

    <behaviors>
      <endpointBehaviors>
        <behavior name="behaviorSECertificate">
          <clientCredentials>
            <clientCertificate findValue="ab cd .. b4" storeLocation="LocalMachine" storeName="My"
              x509FindType="FindByThumbprint"/>
          </clientCredentials>
        </behavior>
      </endpointBehaviors>
    </behaviors>

Pretty basic stuff. So now I do the same in .Net core code:
        var issuerBinding = new WS2007HttpBinding(SecurityMode.TransportWithMessageCredential);
        issuerBinding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;
        issuerBinding.Security.Message.EstablishSecurityContext = false;
        issuerBinding.Name = "certificateMixed";

        var prm = new WsTrustTokenParameters
        {
            IssuerBinding = issuerBinding,
            IssuerAddress = new EndpointAddress(_seOptions.STSEndpoint),
            MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10,
            EstablishSecurityContext = false,
        };

        prm.ClaimTypes.Add(new ClaimType() { Uri = "http://docs.oasis-open.org/wsfed/authorization/200706/claims/action", IsOptional = true });
        prm.ClaimTypes.Add(new ClaimType() { Uri = "http://schemas.xmlsoap.org/ws/2005/05/identity/claims/privatepersonalidentifier", IsOptional = false });
        prm.ClaimTypes.Add(new ClaimType() { Uri = "http://schemas.microsoft.com/ws/2008/06/identity/claims/role", IsOptional = true });

        var binding = new WsFederationHttpBinding(prm);
        binding.Security.Message.EstablishSecurityContext = false;
        binding.Security.Message.NegotiateServiceCredential = true;
        binding.Security.Mode = SecurityMode.TransportWithMessageCredential;
        binding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate;

        ChannelFactory<IMyService> factory = new ChannelFactory<IMyService>(binding, new EndpointAddress(_seOptions.MyServiceUrl));

        var cert = GetClientCertificate(); //X509Certificate2
        var x = factory.Endpoint.EndpointBehaviors[typeof(ClientCredentials)];
            ((ClientCredentials)x).ClientCertificate.Certificate = cert;
        IMyService client = factory.CreateChannel(new EndpointAddress(_seOptions.MyServiceUrl));

So the main question is- how do I add the tokenRequestParameters/AppliesTo section in code? I assume it would be something like this:
RequestSecurityToken tk = new RequestSecurityToken() { AppliesTo = new EndpointAddress("URN:MY.TEST.SERVICE") };

But I have no idea what to assign this object to.

A: RequestSecurityToken class is not applicable to .net core,  you can see its support on this page: RequestSecurityToken Class. So you need to find a replacement for it in .net core. You can refer to  Overview of porting from .NET Framework to .NET Core to consider how to migrate from .net framework to .net core. Hope my answer will help you.


text:
Q: list files with the same first 3 letter followed by a sequence # with shell script First time to post here.  How do I group files with the same first 3 letters followed by a sequence number in a directory?
e.g.
VHS-01-001.avi
VHS-01-002.avi
-------------
VHS-02-001.avi
VHS-02-002.avi
VHS-02-003.avi
---------
Hi8-01-001.avi
Hi8-01-002.avi
Hi8-01-003.avi

so that I can pass each group of video files in a function as the following:
encode(){
  for avi in "$@"
  do..
}

A: Maybe not very smart solution:

*

*sort files by name

*loop through names

*compare characters of last loop:
last=""
ls -1 $1 | sort | while read file; do
    sub=${file:0:3}
    [ "$last" != "$sub" ] && { echo "NEW GROUP"; last="$sub"; }
    echo "[$sub] $file"
done

Instead of echo-ing collect filenames inside an array ...
Just an idea ... example output:
NEW GROUP
[Hi8] Hi8-01-002.avi
NEW GROUP
[VHS] VHS-01-001.avi
[VHS] VHS-01-002.avi
[VHS] VHS-02-002.avi
NEW GROUP
[XZU] XZU

Edit 1:
based on Anthony Geoghegan 's answer avoid the pipes at the beginning of the loop and use bash globbing. Take a look at his comment.
Improved script:
last=""
for file in *avi; do
    sub=${file:0:3}
    [ "$last" != "$sub" ] && { echo "NEW GROUP"; last="$sub"; }
    echo "[$sub] $file"
done

Edit 2:
as asked by @ Tony Tan in his third comment:
here you find a straigt forward solution to parse the collected file names to a function. There are many ways to do so. And I don't have much experience in bash scripting ... ;)
#!/bin/bash

SOURCE_DIR="$1"
cd "$SOURCE_DIR" || { echo "could not read dir '$SOURCE_DIR'"; exit 1; }

function parseFiles() {
  echo "parsing files:"
  echo "$1"
}

last=""
declare -a fileGroup

for file in *avi; do
  # first 3 chars of filename
  sub=${file:0:3}

  if test -z "$last"; then
    # last is empty. first loop
    last="$sub"
  elif test "$last" != "$sub"; then
    # new file group detected, parse collected
    parseFiles "${fileGroup[*]}"
    # reset array
    fileGroup=()
    last="$sub"
  fi

  # append name to array
  fileGroup[${#fileGroup[@]}]=$file
done

parseFiles "${fileGroup[*]}"

A: With zsh:
files=(???-??-*.avi)
for prefix (${(Mu)files#???-??-}) encode $prefix*.avi

(or encode ${(M)files:#$prefix*})
The equivalent with the GNU shell (bash) and tools would be:
while IFS= read -u3 -rd '' prefix; do
  encode "$prefix-"*.avi 3<&-
done 3< <(printf '%s\0' ???-??-*.avi | grep -oz '^...-..-' | sort -zu)

Same principle. We get the list of files matching the ???-??-*.avi pattern in the current directory, extract the part that matches ((M)/grep -o) ???-??- (regexp ...-..-), unique them ((u)/sort -u), and then loop over that list of prefixes.


text:
Q: Extensions Disable/Uninstall when swapping devices I use VS Code remote on two separate devices, work laptop and home desktop. SSHing in with the same keys and same user.
As long as I SSH in from a single user, extensions continue to work without issue. The extensions are installed in the remote.
Once I connect from another device, the majority of extensions (python, etc.) either appear to be uninstalled, or are stuck in a disabled state.
Is there some way to make remote extensions work across any device?


text:
Q: Wrong OpenGL version being reported I have just bought a new AMD RX550 for deep learning purposes. However, when I tried to benchmark it some errors are being reported due to having old OpenGL version.
On the official manufacturers site, it is clearly stated that my GPU support 4.5 version yet my computer is showing it to be 1.1
The only way I have succeeded in a decent benchmark is to run the Vulkan ones be coz the GL1.1 benchmarks suck.
I have an AMD A4 apu with integrated graphics(obviously)& am running Win10_Lite. Could the 2 gpu be battling it out with the drivers?I have already tried DDU-ing the drivers but with no result. Is there any way to update the OpenGL?? Or am I facing I completely uninstalled driver?
UPDATE: I tried running Unigine Heaven benchmark(with DirectX) and it shows 0% GPU usage. Any fixes for that??

product website == https://www.amd.com/en/products/graphics/radeon-rx-550

A: The problem was arising due to unforeseen clash of my integrated GPU and the discrete one. The solution was to enter the BIOS and change the default GPU to the one in Pcie slot. Now my whole rig works with better performance and resolution. Also note the fact that normal usage only takes 3-5% of GPU so there isn't much performance loss.....


text:
Q: how to know which button was clicked in flutter If I have a search method that allows a user to search for a plant, then the list of the possible plants will appear and if the user clicks on a plant it will transfer them to a plant info page or a form to add it to their list based on which button the user was click.. so my question is how to know which button was clicked?

A: The button that calls the search method should pass the plant id or the Plant object as a parameter. This way, the method will carry the plant info.

A: Your list widget presumably will create the button for each plant, so it already knows which plant is being clicked. Pass the plant record inside the onPressed action
//inside whatever builds a listitem for each plant result
Widget build(BuildContext context) {
  return ListItem(
    title: Text(plant.name),
    subtitle: TextButton(
      child: Text("some ${plant.name} action"),
      onPressed: () => PlantDetailWidget(plant),
    ),
  );
}