text:
Q: TypeError: '_io.TextIOWrapper' object is not callable I can't figure out how to fix the errors I keep receiving, I have them at the bottom of the code below.
 import random

this function creates a random number file
def random_number_file_create(min, max, filenames, entries):
    random_number_file  = open(FILENAME, "w")
    for i in range (entries):
            number = str(random.randint(min, max))
            random_number_file.write(number + "\n")
    random_number_file.close()

this function prints the random number
def lines_print(filename):
    random_number_file = open(FILENAME, "r")
    line = random_number_file.readline()
    while line != "":
            print(line, end="")
            line = random_number_file()
    random_number_file.close()

this function counts the lines containing random number
def lines_count(filename):
    random_number_file = open (FILENAME, "r")
    line = random_number_file.readline()
    count = 0
    for number in random_number_file:
            count += 1
    return count
    random_number_file.close()

this function adds the total of the numbers
def total_numbers_in_file(filename):
    random_number_file = open (FILENAME, "r")
    line = random_number_file.readline()
    total=0
    for number in random_number_file:
            total = int(number)
    return total
    random_number_file.close()
FILENAME= "numbers.txt"
random.seed(83)
random_number_file_create(50,100,FILENAME,20)
lines_print(FILENAME)
print()
entries = lines_count(FILENAME)
total = total_numbers_in_file(FILENAME)
average = round(total/entries)
print("Entries:", entries)
print("Total:", total)
print("Average:", average)

#Errors#
    Traceback (most recent call last):
      File "hw8.py", line 41, in
        lines_print(FILENAME)
      File "hw8.py", line 18, in lines_print
        line = random_number_file()
    TypeError: '_io.TextIOWrapper' object is not callable

A: Providing a reference case:
Another similar case, the error tip is :
Traceback(most recent call last):
    File "ex17.py", line 18, in <module>
        input<'?'>
TypeError: 'file' object is not callable.
the asker support his code, and another Technology Daniel find that
he use 'input' as a variable, but then in the following lines, he also use the 'input' function to get a data from  the users. That's the real reason.
when i run my module, the system show me a same error as you, but my error is the same as the pevious asker. So by changing the 'input' variable as a different variabe 'input_1', i solve the error.
I hope my answer could help you, actually i am new to python, i can read your code and understand, but i can't find the truth.


text:
Q: How to avoid duplicate files and text in a NodeJs application? I have the following use case -
1. Avoid duplicate files
2. Avoid duplicate text code
I understand I need to calculate both the files and text codes into MD5 and maintain both into columns,
which can be queried, to check if the same file or text code might already be there in the application.
I am trying to find the correct way to create MD5 Checksums in NodeJs,
I found the following to be useful -
let crypto = require('crypto');
let md5CheckSum = crypto.createHash('md5').update(dataToConvert).digest("hex");

I have the following queries -

*

*Is calculating MD5 and MD5 Checksum the same thing?

*Is the code creating just an MD5, or is it also creating the checksum of the dataToConvert string?
if not how can I further create its checksum?

*It is straightforward to pass text codes to the md5 function,
In case of files, what conversion do I need to do?
To be passed as an argument to the md5 checksum function?
Reference -
https://nodejs.org/api/crypto.html#crypto_crypto_createhash_algorithm_options

A: *

*yes

*there is no such thing as "an md5", md5 checksums are cryptographic hashes of some data, so in this case that data is dataToConvert. No data, no md5.

*you're in Node, have a look at fs.readFile

redpajama_set_name: RedPajamaStackExchange


text:
Q: Files.probeContentType behaves differently on two similar machines I did all of the development of a Java 8u45 based project on a computer using Windows 7 before a hard drive failure necessitated a re-install of the OS. As far as I know, everything should be very similar to how I previously had it set up, but now I'm noticing an error in my application when running it on my new install, yet the same error is not happening on a co-worker's machine which is also running Windows 7. The problem being that Files.probeContentType(Path) seems to always return null on my machine, while it returns the expected mime type on the other (and my previous) machine.
Both of us are using JDK 8u45 (the project is tied to this revision for the time being). My co-worker is using IDEA 14, while I'm using IDEA 15. It should be noted also that it does not appear to be IDE related, because I am getting the same issue when running the application from the compiled executable (using Launch4j, even with the bundled JRE)
Is there any reason why my development environment would return null for the method Files.probeContentType, but another machine with the same version of the OS would not?

A: On windows, Files.probeContentType takes your file extension to determine the actual mime type. After it found this extension, it looks in the windows registry for the file extension. You can find the list of file extensions in the HKEY_CLASSES_ROOT registry hive. If this hive contains a key for the file extension you asked for, it will look for a string named Content Type in this key. The return value of probeContentType is the value stored here.
Since your version of windows is a fresh install, its registry will contain fewer entries than the one your co-worker is using. It might be the case that your system simply doesn't contain an entry for the extension your asking for, so probeContentType cannot determine a valid mime type, and returns null.


text:
Q: Android/Kotlin - Fragment not attached to Activity after loosing focus on textfield by pressing navigation menu button i've a problem in my Android app.
I have a fragment that is generated as a list of editable textview. Every textview has a setOnFocusChangeListener that calls an API on server.
FocusChangedListener works correctly on last textview, and after that my textview remain focused as you can see in the figure below.

Problem
Now i have to change menu (fragment) by clicking on the right menu button.
When button is clicked and the new menu is about to be loaded, my textview loses focus and calls the API, but i don't want my app do that. If I click menu button is because i've to change it and i expect that my old fragment disappear or basically don't execute the FocusChangedListener.

Any ideas?

A: I made a little trick to solve the problem.
I just added this code inside OnCreate of my DrawerMenu and then i set a Global Variable "drawerOpened" to check every time if my Menu is open or not.
        // Initialize the action bar drawer toggle instance
    val drawerToggle:ActionBarDrawerToggle = object : ActionBarDrawerToggle(
        this,
        drawer_layout,
        toolbar,
        R.string.navigation_drawer_open,
        R.string.navigation_drawer_close
    ){
        override fun onDrawerClosed(view:View){
            super.onDrawerClosed(view)
            GlobalVar.drawerOpened = false
        }

        override fun onDrawerOpened(drawerView: View){
            super.onDrawerOpened(drawerView)
            GlobalVar.drawerOpened = true
            currentFocus?.clearFocus()  //clear focus - any view having focus
        }
    }

Then in my HomeFragment i did this:
// if GlobalVar.drawerOpened is false then setOnFocus

if (field.validatefield || field.nextpage != 0)
{
  textView.setOnFocusChangeListener { _, hasFocus ->
    if (!hasFocus && !GlobalVar.drawerOpened)
    {
        if ((field.mandatory && !textView.text.toString().isNullOrEmpty()) || (!field.mandatory)) {
            if (field.validatefield) {
                validateField(field.fieldcode, textView.text.toString(), field.nextpage)
            } else {
                _goToNextPageNo = field.nextpage
                goToNextPageIfExist()
            }
        }
    }
  }
}

This is not a complete solution, but it works fine.

A: I assume that after a click, the application switches to touch mode and your EditText loses focus.
It happens at the system level.
A focus can have only one view at a time.
https://android-developers.googleblog.com/2008/12/touch-mode.html


text:
Q: Kendo dropdownlist doesn't bind the selected value when done through javascript js fiddle here - http://jsfiddle.net/9xj8huj9/1/
$("#Instrument").data("kendoDropDownList").bind('change',function (dataItem) {
        alert("Data Binded");
    });

Somehow, when the value of the dropdownlist is set dynamically when the button is clicked, data isn't binded.
Any idea how to bind the data here?

A: You need to trigger the change event
JSFiddle


text:
Q: Sale of products with correlated prices I have Buyer/Seller Problem I need to solve:
Me, as the buyer, wants to buy (lets say) 50 goods. There are several sellers who have all (or at least some) products I need  at stock. I can ask them for the price of the different products and choose the cheapest option. So far so good. The problem is the following: The products price is correlated if I combine different products:
Seller A can sell me Product A for 400$, Product B for 300, but both together for 500$.
I don't know how this correlation function is build, I can only ask for a result. I can even ask for parts:
I can ask for 10 items of Product A and 5 from Product B from Seller 1 and 5 items of Product A and 10 from Product B from Seller 2.
I can't ask for every possible combination, for 50 different items of different quantities with 10 sellers to ask for every possible combination (the brute force possibility) would last until the universum ends.
Is there an established best practice, like some sort of auction, to reach some kind of pareto optimum in acceptable time? Or can someone nudge me in a direction where such problems are solved so I can start researching myself (science papers, etc.)

A: I would assume there's a function that represents the price of A and the price of B.  Anytime you put in an order, both A and B react accordingly.  If you were given some assumptions, it would make the problem much simpler because at the moment it's going to end in a covariance matrix that you're trying to guess at with your trials.  (all that matrix basically tells you is exactly what I said...how the two products relate to each other with respect to input)
If you knew in buying 10 of an item that you had to pay the marginally increase cost of each...i.e. buying 1 at a time costs as much as 10 at once instead of getting a discount for 10 at once, it gives you a better idea of what the model is.  This might just be a problem you have to play with and study the reaction...I don't know if this is a statistics problem for you or what, but it could be just simple economics or complicated statistics.


text:
Q: Image will not dispose upon keyPressed Java I am drawing on an image on JPanel's graphic context. However the image does not remove itself from the graphics context when I press S. I know for sure my keyListeners are working.
If I am disposing the graphics context, shouldn't the content on the graphics context go away?
public class MainMenu extends JPanel implements KeyListener {

    private JFrame frame;
    private int width = 660;
    private int height = 500;
    private Image image;
    private boolean removeImage = false;

    public MainMenu()
    {
        frame = new JFrame();
        frame.setResizable(false);
        frame.setTitle("Menu Test");
        setBackground(Color.BLACK);
        frame.setSize(width,height);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // add main menu to the frame
        frame.add(this);
        // let the frame know about keyevents from this class
        frame.addKeyListener(this);

    }

    public void setup()
    {
        frame.setVisible(true);

    }

    @Override
    public void keyPressed(KeyEvent e) {
        // TODO Auto-generated method stub
        if(e.getKeyCode() == KeyEvent.VK_S)
        {

            removeImage = true;

        }

        repaint();
    }

    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        try {
            image = ImageIO.read(new File("Game/menuScreen.PNG"));

            g.drawImage(image, 0, 0, null);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();

        }

        if(removeImage)
        {
            g.dispose();
        }

    }

A: Calling Graphics#dispose will not remove the image from the JPanel
if (removeImage) {
   g.dispose();
}

instead use a boolean flag to indicate whether or not the image should be painted
if (showImage) {
   g.drawImage(image, 0, 0, this);
}

update the flag to false and invoke repaint to effectively "clear" any previous images.
showImage = false;
repaint();

Notes:

*

*It is unnecessary to invoke dispose for Graphics objects in paintComponents. This only applys to custom Graphics references.

*Don't load images from paintComponent - this degrades performance. Load the image from a method at startup

*When developing Swing applications use Key Bindings rather than KeyListeners. The latter use KeyEvents which require focus to work. Key Bindings use KeyStrokes which work regardless of focus.


text:
Q: How to not deselect a radio button when I click it again? I have successfully implemented the radio button from a volley. The example data in my volley is 1, 2, 3. When I select radio button 1 and then I select radio button 2, radio 1 is unchecked. This situation is normal, but when I select radio button 2 again the radio button becomes deselected and I can't select it anymore.
This is the code I put in the adapter:
@Override
public void onBindViewHolder(final ViewHolder holder, final int position) {
    SharedPreferences sharedPreferences = context.getSharedPreferences(AppConfig.APP_PUPUKKUJANG_MART, Context.MODE_PRIVATE);
    final String whois = sharedPreferences.getString(AppConfig.USER_WHOIS,null);
    row_index = -1;
    holder.itemView.setTag(service.get(position));
    final ServiceCourier p = service.get(position);
    holder.service.setText(p.getService());
    holder.desc.setText(p.getDescription());
    holder.cost.setText("Rp "+String.format(Locale.US, "%1$,.0f", Double.valueOf(p.getCost())).replace(",","."));
    holder.etd.setText(p.getEtd());
    holder.itemView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

        }
    });
    View.OnClickListener rbClick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            RadioButton checked_rb = (RadioButton) v;
            if(lastCheckedRB != null){
                ActivityCheckout.updateTextViewIscek("0");
                lastCheckedRB.setChecked(false);
            }
            lastCheckedRB = checked_rb;
            SharedPreferences sharedPreferences = context.getSharedPreferences(AppConfig.APP_, Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            editor.putString("ongkir_service", p.getService());
            editor.putString("ongkir_description", p.getDescription());
            editor.putString("ongkir_cost", p.getCost());
            editor.putString("ongkir_etd", p.getEtd());
            editor.apply();
            String cost = String.format(Locale.US, "%1$,.0f", Double.valueOf(p.getCost()));
            Double total_order = ActivityCheckout.getTextViewTotal();
            Double tf = Double.valueOf(p.getCost())+total_order;
            ActivityCheckout.updateTextViewIscek("1");
            ActivityCheckout.updateTextView("Rp "+cost.replace(",","."));
            ActivityCheckout.updateTotal_fees("Rp "+String.format(Locale.US, "%1$,.0f", tf).replace(",","."));
        }
    };
    holder.radiobutton.setOnClickListener(rbClick);
}


text:
Q: Миграция Room при добавлении полей Есть БД (готовая из assests) с полями bluda, products.. Изначально приложение было написано используя SQLiteOpenHelper, но я решил переписать используя Room.
поднял версию с 1 до 2 и написал миграцию MiGRATION_1_2
Затем решил в таблицу products добавить поля icon и image (оба поля содержат названия изображений, для вывода в RecyclerView). Написал миграцию MIGRATION_2_3 и поднял версию с 2 до 3, но почему-то в RecyclerView вместо картинок ничего не выводится, в логах если попробовать получить данные из поля image выводится null. Как правильно написать миграцию, чтобы новая версия БД из assests (с полями icon и image заполненными) без проблем появилась у пользователей?
AppDatabase
@Database(entities = {Bludo.class, Products.class}, version = 3, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {

    private static AppDatabase instance;

    public abstract ProductsDao productsDao();
    public abstract BludoDao bludoDao();

    private static final String DB_NAME = "mydatabase.db";

    public static AppDatabase getInstance(Context context) {
        if (instance == null) {
            instance = Room.databaseBuilder(context, AppDatabase.class, DB_NAME)
                    .openHelperFactory(new AssetSQLiteOpenHelperFactory())
                    .addMigrations(MIGRATION_1_2)
                    .addMigrations(MIGRATION_2_3)
                    .allowMainThreadQueries()
                    .build();
        }
        return instance;
    }

    private static final Migration MIGRATION_1_2 = new Migration(1,2) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {
            database.execSQL("CREATE TABLE bluda_new (_id INTEGER NOT NULL, name TEXT, ingredients TEXT," +
                    "description TEXT, icon TEXT, image TEXT, favorite TEXT, region TEXT, productsID INTEGER NOT NULL, PRIMARY KEY(_id))");

            database.execSQL(
                    "INSERT INTO bluda_new (_id, name, ingredients, description, icon, image, favorite, region, productsID)" +
                            "SELECT _id, name, ingredients, description, icon, image, favorite, region, productsID FROM bluda");

            database.execSQL("DROP TABLE bluda");

            database.execSQL("ALTER TABLE bluda_new RENAME TO bluda");

            database.execSQL("CREATE TABLE products_new (_id INTEGER NOT NULL, name TEXT, PRIMARY KEY(_id))");

            database.execSQL(
                    "INSERT INTO products_new (_id, name)" +
                            "SELECT _id, name FROM products");

            database.execSQL("DROP TABLE products");

            database.execSQL("ALTER TABLE products_new RENAME TO products");
        }
    };

    private static final Migration MIGRATION_2_3 = new Migration(2,3) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {

            database.execSQL("ALTER TABLE products ADD COLUMN icon TEXT");
            database.execSQL("ALTER TABLE products ADD COLUMN image TEXT");

            database.execSQL("CREATE TABLE products_new (_id INTEGER NOT NULL, name TEXT, icon TEXT, image TEXT, PRIMARY KEY(_id))");

            database.execSQL(
                    "INSERT INTO products_new (_id, name, icon, image)" +
                            "SELECT _id, name, icon, image FROM products");

            database.execSQL("DROP TABLE products");

            database.execSQL("ALTER TABLE products_new RENAME TO products");
        }
    };
}

В полях icon и image данные точно есть. Если на чистое устройство установить в RecyclerView данные выводятся.


text:
Q: Trying to implement Luhn's Algorithm in C Iam trying to implement Luhn's algorithm in the C language to check credit card validity, for those who don't know... this is it:

*

*Multiply every other digit by 2, starting with the number's
second-to-last digit, and then add those products' digits together.

*Add the sum to the sum of the digits that weren't multiplied by 2.

*If the total's last digit is 0 (or, put more formally, if the total
modulo 10 is congruent to 0), the number is valid!

and to implement that, I looped through the whole number and if the number place I was in had a modulo 2 equal to 0 then I would multiply by two and add to a variable called totalEven.
if that wasn't the case I would add the number I was in to totalOdd without multiplication.
I would then increment the place by one and check the other numbers until I reach 16 (the max digits for a card).
I would later add both variables and check if the total modulo ten was equal to 0. If it means the credit card number is correct, else it is false.
here is the code:
#include <stdio.h>
#include <cs50.h>

//list of variables

   //is the card valid
   bool isValid = true;
   // the creditcard number
   long input;
   //mod stands for modules, and is used to single out each number as seen later
   int mod = 10;
   //the location at which number I am checking
   int place = 1;
   //num is the number I am checking that has been singled out
   int num = 0;
   //total of numbers * 2 located at locations numbered with even numbers
   int totalEven = 0;
   //total of numbers located at locations numbered with odd numbers
   int totalOdd = 0;

     //gets input and stores it in well.. input
     input = get_long("Number: ");

      // a formula to single out a number, starting with the ones and then as you can see, mod is muliplied by 10 to go over the second number.

      num = ((input % mod) - (input % (mod /10))) / (mod/10);

      //loops 16 times
      for(int i = 0; i < 16; i++)
      {
          // if the place is even execute below
          if(place % 2 == 0)
          {
              totalEven = totalEven + num * 2;
          }
          //else do this
          else if (place % 2 != 0)
          {
             totalOdd = totalOdd + num;
          }
          //moves to the next number
          mod = mod * 10;
          place++;
      }

      //fufils the last step of the algorithm

      if((totalEven + totalOdd) % 10 == 0 )
      {
          isValid = true;
      }
      else
      {
          isValid = false;
      }

problem is that this block of code gives me invalid or !isValid even though the credit card number is supposed to be correct and I checked my "formula" and it works just fine...
I have absolutely no idea what to do... I am a humble hobbyist so plz don't roast me for the monstrosity above.
here is a complete version of the code
#include <stdio.h>
#include <cs50.h>

long power();

int main(void)
{
    //AMERX 15 STRT 34 OR 37
    //MC 16 STRT 51, 52, 53, 54, 55
    //VZA 13 OR 16 STRT 4

   long input;
   bool isValid = true;
   string type;
   int mod = 10;
   int place = 1;
   int num = 0;
   int totalEven = 0;
   int totalOdd = 0;

   do
   {
      input = get_long("Number: ");

   }

   while(input < 0);

      for(int i = 0; i < 16; i++)
      {
          num = ((input % mod) - (input % (mod /10))) / (mod/10);
          if(place % 2 == 0)
          {
              totalEven = totalEven + num * 2;
          }
          else
          {
             totalOdd = totalOdd + num;
          }

          mod = mod * 10;
          place++;
      }

      if((totalEven + totalOdd) % 10 == 0 )
      {
          isValid = true;
      }
      else
      {
          isValid = false;

          printf("%i , %i", totalEven, totalOdd);
      }
   if (isValid == true){
   if((input < (38 * power(10, 13)) && input >=(37 * power(10, 13))) || (input < (35 * power(10,13)) && input >= (34 * power(10, 13))))
   {
       type = "AMEX\n";
   }
   else if(input >= (51 * power(10, 14)) && input < (56 * power(10, 14)))
   {
       type = "MASTERCARD\n";
   }
   else if((input < (5 * power(10, 12)) && input >= (4 * power(10, 12))) || (input < (5 * power(10, 15)) && input >= (4 * power(10, 15))))
   {
       type = "VISA\n";
   }
       else{
       type = "error\n";
   }
}
   else
   {
       type = "INVALID\n";
   }

    if((totalEven + totalOdd) % 10 == 0 )
    {
      isValid = true;
    }
    else
    {
      isValid = false;
    }

    printf("%s", type);

}

long power(int n, int p)
{
    long result = 1;
    for(int i = 0; i<p; i++)
    {
        result = result * n;
    }
    return result;

A: As I was looking at your code, there some mistakes I want to point out.

*

*You forgot: #include <string.h> as you did declare string type in the code.

*input = get_long("Number: "); should have its own do-while loop in case user inputs letters or incorrect numbers.

*if(place % 2 == 0){
totalEven = totalEven + num * 2;
}
else if (place % 2 != 0){
totalEven = totalEven + num;
} should totalOdd = totalOdd + num for the second part

*totalEven = totalEven + num * 2 is right and wrong at the same time. It only works if the number multiplied by 2 is less than 10. If the num * 2 >= 10, lets say num = 6, then 6 * 2 is 12 which would then be 1 + 2 + totalEven.

*num = ((input % mod) - (input % (mod /10))) / (mod/10); This should be in the first for loop.

*In #include <math.h>, there is a power function called pow which does exactly as your power() function.

A: I'm not an expert in Luhn algorithm but when I read  https://en.wikipedia.org/wiki/Luhn_algorithm it seems to me that you are doing it wrong.
Quote from https://en.wikipedia.org/wiki/Luhn_algorithm :

From the rightmost digit (excluding the check digit) and moving left, double the value of every second digit. The check digit is neither doubled nor included in this calculation; the first digit doubled is the digit located immediately left of the check digit. If the result of this doubling operation is greater than 9 (e.g., 8 × 2 = 16), then add the digits of the result (e.g., 16: 1 + 6 = 7, 18: 1 + 8 = 9) or, alternatively, the same final result can be found by subtracting 9 from that result (e.g., 16: 16 − 9 = 7, 18: 18 − 9 = 9).

I don't see anywhere in your code where you handle that bolded part.
Instead of
totalEven = totalEven + num * 2;

I think you need
int tmp = num * 2;
if (tmp > 9) tmp = tmp - 9;
totalEven = totalEven + tmp;

That said - I think you are making the implementation much more complex than needed by storing the input as a number. Instead of a number you could use an array of digits.
That is - instead of
long input = 1122334455667788

use
int digits[] = {8, 8, 7, 7, 6, 6, 5, 5, 4, 4, 3, 3, 2, 2, 1, 1};
// Notice that index zero is the rightmost digit

In this way the algorithm is much more simple:
// Double every second element and check for overflow
for (idx = 1; idx < 16; idx += 2)
{
    digits[idx] = 2 * digits[idx];
    if (digits[idx] > 9) digits[idx] = digits[idx] - 9;
}

// Calculate the sum
sum = 0;
for (idx = 0; idx < 16; ++idx)
{
    sum = sum + digits[idx];
}

If you must receive the input as a number, start by calling a function that converts the number to an array of digits. You can find many, many examples of how that conversion is done here on SO. Here Converting integer into array of digits is just one of many examples.

A: Caution: I have made use of CS50X Library as the question seems to be the one from the same.
#include <stdio.h>
#include <cs50.h>

// Luhn's Algorithm

int main(void)
{
    long cardNumber = get_long("Please, enter your card number: ");
    int sum1 = 0, num = 0, remainder = 0, sum2 = 0;
    long temp = cardNumber;

    while (temp > 0)
    {
        num = ((temp / 10) % 10) * 2; // Multiplying every other digit by 2, starting with the number's second-to-last digit
        while (num > 0)
        {
            remainder = num % 10;
            sum1 += remainder; // Adding those products' digits together
            num /= 10;
        }
        temp /= 100;
    }

    // So as to restore the initial values of remainder and temp for the use in next loop
    remainder = 0;
    temp = cardNumber;

    while (temp > 0)
    {
        remainder = temp % 10;
        sum2 += remainder; // Sum of the digits that weren't multiplied by 2
        temp /= 100;
    }

    ((sum1 + sum2) % 10) == 0 ? printf("Valid\n") : printf("Invalid\n");
    return 0;
}


text:
Q: std::bad_alloc thrown on call to System.LoadLibrary In an effort to load a shared library built with the Android NDK, I'm trying to load a so I built with a JNI bridge to be called in Kotlin, but when calling LoadLibrary("shared_librar.so") I receive the following error:
> Task :test FAILED
terminate called after throwing an instance of 'std::bad_alloc'
  what():  std::bad_alloc

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':test'.
> Process 'Gradle Test Executor 25' finished with non-zero exit value 134
  This problem might be caused by incorrect test process configuration.
  Please refer to the test execution section in the User Manual at https://docs.gradle.org/7.5.1/userguide/java_testing.html#sec:test_execution

* Try:
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':test'.
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.lambda$executeIfValid$1(ExecuteActionsTaskExecuter.java:142)
        at org.gradle.internal.Try$Failure.ifSuccessfulOrElse(Try.java:282)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeIfValid(ExecuteActionsTaskExecuter.java:140)
        at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:128)
        at org.gradle.api.internal.tasks.execution.CleanupStaleOutputsExecuter.execute(CleanupStaleOutputsExecuter.java:77)
        at org.gradle.api.internal.tasks.execution.FinalizePropertiesTaskExecuter.execute(FinalizePropertiesTaskExecuter.java:46)
        at org.gradle.api.internal.tasks.execution.ResolveTaskExecutionModeExecuter.execute(ResolveTaskExecutionModeExecuter.java:51)
        at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:57)
        at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:56)
        at org.gradle.api.internal.tasks.execution.CatchExceptionTaskExecuter.execute(CatchExceptionTaskExecuter.java:36)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.executeTask(EventFiringTaskExecuter.java:77)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:55)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter$1.call(EventFiringTaskExecuter.java:52)
        at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:204)
        at org.gradle.internal.operations.DefaultBuildOperationRunner$CallableBuildOperationWorker.execute(DefaultBuildOperationRunner.java:199)
        at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:66)
        at org.gradle.internal.operations.DefaultBuildOperationRunner$2.execute(DefaultBuildOperationRunner.java:59)
        at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:157)
        at org.gradle.internal.operations.DefaultBuildOperationRunner.execute(DefaultBuildOperationRunner.java:59)
        at org.gradle.internal.operations.DefaultBuildOperationRunner.call(DefaultBuildOperationRunner.java:53)
        at org.gradle.internal.operations.DefaultBuildOperationExecutor.call(DefaultBuildOperationExecutor.java:73)
        at org.gradle.api.internal.tasks.execution.EventFiringTaskExecuter.execute(EventFiringTaskExecuter.java:52)
        at org.gradle.execution.plan.LocalTaskNodeExecutor.execute(LocalTaskNodeExecutor.java:69)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:327)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$InvokeNodeExecutorsAction.execute(DefaultTaskExecutionGraph.java:314)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:307)
        at org.gradle.execution.taskgraph.DefaultTaskExecutionGraph$BuildOperationAwareExecutionAction.execute(DefaultTaskExecutionGraph.java:293)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.execute(DefaultPlanExecutor.java:420)
        at org.gradle.execution.plan.DefaultPlanExecutor$ExecutorWorker.run(DefaultPlanExecutor.java:342)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
Caused by: org.gradle.process.internal.ExecException: Process 'Gradle Test Executor 25' finished with non-zero exit value 134
This problem might be caused by incorrect test process configuration.
Please refer to the test execution section in the User Manual at https://docs.gradle.org/7.5.1/userguide/java_testing.html#sec:test_execution
        at org.gradle.api.internal.tasks.testing.worker.ForkingTestClassProcessor.stop(ForkingTestClassProcessor.java:192)
        at org.gradle.api.internal.tasks.testing.processors.RestartEveryNTestClassProcessor.endBatch(RestartEveryNTestClassProcessor.java:77)
        at org.gradle.api.internal.tasks.testing.processors.RestartEveryNTestClassProcessor.stop(RestartEveryNTestClassProcessor.java:62)
        at jdk.internal.reflect.GeneratedMethodAccessor756.invoke(Unknown Source)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
        at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
        at org.gradle.internal.dispatch.FailureHandlingDispatch.dispatch(FailureHandlingDispatch.java:30)
        at org.gradle.internal.dispatch.AsyncDispatch.dispatchMessages(AsyncDispatch.java:87)
        at org.gradle.internal.dispatch.AsyncDispatch.access$000(AsyncDispatch.java:36)
        at org.gradle.internal.dispatch.AsyncDispatch$1.run(AsyncDispatch.java:71)
        at org.gradle.internal.concurrent.InterruptibleRunnable.run(InterruptibleRunnable.java:42)
        at org.gradle.internal.operations.CurrentBuildOperationPreservingRunnable.run(CurrentBuildOperationPreservingRunnable.java:42)
        at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
        at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)

* Get more help at https://help.gradle.org

BUILD FAILED in 4s
5 actionable tasks: 1 executed, 4 up-to-date

Why would this happen if I didn't actually run anything on the actual library yet?


text:
Q: Initializer `init(:_rowContent:)` requires that `Type` confirm to `Identifiable` I am following the KMM tutorial and was able to successfully run the app on Android side. Now I would like to test the iOS part. Everything seems to be fine except the compilation error below. I suppose this must be something trivial, but as I have zero experience with iOS/Swift, I am struggling fixing it.

My first attempt was to make RocketLaunchRow extend Identifiable, but then I run into other issues... Would appreciate any help.
xcode version: 12.1
Full source:
import SwiftUI
import shared

func greet() -> String {
    return Greeting().greeting()
}

struct RocketLaunchRow: View {
    var rocketLaunch: RocketLaunch

    var body: some View {
        HStack() {
            VStack(alignment: .leading, spacing: 10.0) {
                Text("Launch name: \(rocketLaunch.missionName)")
                Text(launchText).foregroundColor(launchColor)
                Text("Launch year: \(String(rocketLaunch.launchYear))")
                Text("Launch details: \(rocketLaunch.details ?? "")")
            }
            Spacer()
        }
    }
}

extension RocketLaunchRow {
   private var launchText: String {
       if let isSuccess = rocketLaunch.launchSuccess {
           return isSuccess.boolValue ? "Successful" : "Unsuccessful"
       } else {
           return "No data"
       }
   }

   private var launchColor: Color {
       if let isSuccess = rocketLaunch.launchSuccess {
           return isSuccess.boolValue ? Color.green : Color.red
       } else {
           return Color.gray
       }
   }
}

extension ContentView {
    enum LoadableLaunches {
        case loading
        case result([RocketLaunch])
        case error(String)
    }

    class ViewModel: ObservableObject {
            let sdk: SpaceXSDK
            @Published var launches = LoadableLaunches.loading

            init(sdk: SpaceXSDK) {
                self.sdk = sdk
                self.loadLaunches(forceReload: false)
            }

            func loadLaunches(forceReload: Bool) {
                self.launches = .loading
                    sdk.getLaunches(forceReload: forceReload, completionHandler: { launches, error in
                        if let launches = launches {
                            self.launches = .result(launches)
                        } else {
                            self.launches = .error(error?.localizedDescription ?? "error")
                        }
                    })
            }
        }
}

struct ContentView: View {
  @ObservedObject private(set) var viewModel: ViewModel

    var body: some View {
        NavigationView {
            listView()
            .navigationBarTitle("SpaceX Launches")
            .navigationBarItems(trailing:
                Button("Reload") {
                    self.viewModel.loadLaunches(forceReload: true)
            })
        }
    }

    private func listView() -> AnyView {
        switch viewModel.launches {
        case .loading:
            return AnyView(Text("Loading...").multilineTextAlignment(.center))
        case .result(let launches):
            return AnyView(List(launches) { launch in
                RocketLaunchRow(rocketLaunch: launch)
            })
        case .error(let description):
            return AnyView(Text(description).multilineTextAlignment(.center))
        }
    }
}

A:
using a List or ForEach on primitive types that don't conform to the Identifiable protocol, such as an array of strings or integers. In this situation, you should use id: .self as the second parameter to your List or ForEach

From the above, we can see that you need to do this on that line where your error occurs:
return AnyView(List(launches, id: \.self) { launch in

I think that should eliminate your error.


text:
Q: Group objects with iPhone SDK? In my iPhone app, I have a number of UIImageView that do the same thing, then a second load which do the same thing. Can I some how tag/group these so that I can simply reference all the objects with one name? Otherwise it means having to have dozens of lines of code for a single repetitive action.

A: You could place all the UIImageViews in one super UIView. Depending on what you want to do, you could for example easily hide all objects inside the UIView with one line of code.


text:
Q: Evaluate the integral of the given contour I'm being asked to evaluate $\int \frac{1}{z^3(z^2+1)}dz$, where C is the circle $\lvert z-1 \rvert=\frac32$
I started by determining the zeroes, which are $0, -i, \,i$ Then I applied the Cauchy Integral Formula but it is here where Im not sure if i am applying it correctly.
I took $\int \frac{1}{z^3(z^2+1)}dz$
$=\int \frac{1}{z^3(z^2+1)}dz$+$\int \frac{1}{z^3(z^2+1)}dz$+$\int \frac{1}{z^3(z^2+1)}dz$
$=2\pi i+2\pi i+2\pi i$
$=6\pi i$
Is this application correct? If not, could someone please explain to me how to do this properly

A: Since the integrand has poles in the interior of $C$, you could  use the residue theorem or Cauchy's integral theorem instead. I think using the residue theorem would be easier.
If, however, you insist on using Cauchy's formula, write
$$\int_C \frac{dz}{z^3 (z^2 + 1)} = \int_C \frac{dz}{z^3 (z - i)(z + i)}.$$
By the Cauchy-Goursat theorem,
$$\int_C \frac{dz}{z^3 (z^2 + 1)} = \int_{C_1} \frac{(z - i)^{-1} (z + i)^{-1}}{z^3} dz + \int_{C_2} \frac{z^{-3} (z + i)^{-1}}{z - i} dz + \int_{C_3} \frac{z^{-3} (z - i)^{-1}}{z + i} dz,$$
where $C_1$, $C_2$, $C_3$, with $C_i \cap C_j = \emptyset$ for all $i \ne j$, are small circular contours around $0$, $i$, $-i$, respectively. Now, the last two integrals can be evaluated directly using Cuachy's formula. The first one, however, cannot, so you need to use Cuachy's generalized integral formula.
Alternatively, since
$$\frac{1}{z^3 (z - i)(z + i)} = \frac{1}{z^3} + \frac{1}{2(z - i)} + \frac{1}{2(z + i)} - \frac{1}{z} \tag{$\ast$}$$
and $0$, $i$, $-i$ are inside $C$,
$$\int_C \frac{dz}{2(z - i)} + \int_C \frac{dz}{2(z + i)} - \int_C \frac{dz}{z}$$
can be evaluated using Cuachy's formula. Yet, $\int_{C} z^{-3} dz$ requires Cuachy's generalized integral formula.


text:
Q: Starting jenkins Slave agent using Jnlp using Task Scheduler always starts as headless I am trying to find solution for the jenkins nodes to automatically connect to master in non headleass mode.
Here is what I have done so far
I have written batch script which calls the powershell script. Powershell script has series of commands to start the jenkins slave agent using jnlp.
This batch script is configured in Task Scheduler to run at the startup. The jenkins slave node is connected to master as soon as node starts up.
But execution of GUI test is not visible in the node when the test starts.
When I manually run this batch script from command line, it works fine i.e non headless mode and I can see the execution of GUI test.
I've read few articles about this kind of setup and none worked.
I also wrote a small piece of powershell script to allow a Windows Service to Interact with Desktop.  This script runs after the batch script to start jenkins slave agent.
Task scheduler job is configured to Run as Administrator and I login as administrator to see the execution.
Since this batch script is running via Task scheduler I am guessing its running in a different session.
How do I solve it.

A: Try to put your script into shell:startup.
On a Windows 10 machine with the Jenkins slave under the user you need, press Windows+R (Run...) and type shell:startup and put your script into opened folder. It will run once the user logged in.
This is how you'll see console and any windows it spawns.


text:
Q: How to I access JSON value from ansible output? I have this ansible playbook which will create and attach volumes to EC2 instances using ec2_vol module and I want to partition the same using parted module. Below is my ec2_vol module,
EC2_VOL Module:
      ec2_vol:
        aws_access_key: XXXXXXXX
        aws_secret_key: XXXXXXXX
        security_token: XXXXXXXX
        instance: "{{ item.instance_id }}"
        region: "{{ var_dict['REGION'] }}"
        device_name: "{{ VOL_NAME }}"
        volume_type: gp2
        volume_size: '1000'
        delete_on_termination: false
      with_items: "{{ ec2_instances_list.instances}}"
      register: ec2_volumes
    - debug:
        msg: "{{ ec2_volumes.results }}"

Result of ec2_volumes:
And the result that is printing from ec2_volumes.results. I want to loop through the device_name and partition the devices which is created
TASK [debug] *******************************************************************
ok: [localhost] => {
    "msg": [
        {
            "_ansible_ignore_errors": null,
            "_ansible_item_label": {
                "ami_launch_index": 0,
                "architecture": "x86_64",
                "block_device_mappings": [
                    {
                        "device_name": "/dev/sda1",
                        "ebs": {
                            "attach_time": "2021-04-30T15:47:07+00:00",
                            "delete_on_termination": true,
                            "status": "attached",
                            "volume_id": "vol-XXXXXXXXXXXXXX"
                        }
                    },
                    {
                        "device_name": "/dev/sdb",
                        "ebs": {
                            "attach_time": "2021-04-30T15:47:07+00:00",
                            "delete_on_termination": false,
                            "status": "attached",
                            "volume_id": "vol-XXXXXXXXXXXXXXXX"
                        }
                    }
                ],

And here is my parted module code:
    - name: Partition Additional volumes
      parted:
        device: "{{ item.block_device_mappings[0].device_name }}"
        number: 1
        part_type: 'primary'
        state: present
        when: ("{{ ec2_volumes.device_name }}" != "/dev/sda1")
      with_items: "{{ ec2_volumes.results}}"

But still getting error that 'block_device_mappings' has no attribute.
fatal: [localhost]: FAILED! => {"msg": "'list object' has no attribute 'block_device_mappings'"}
What could be the cause? Can someone help me to resolve this issue?
Edit 1:
Facing another issue after updating the playbook in the parted module
    - name: Partition Additional volumes
      parted:
        device: "{{ item._ansible_item_label.block_device_mappings[0].device_name }}"
        number: 1
        part_type: 'primary'
        state: present
        when: ("{{ ec2_volumes.device_name }}" != "/dev/sda1")
      with_items: "{{ ec2_volumes.results}}"

fatal: [localhost]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'dict object' has no attribute 'device_name'

A: The error is clear:

FAILED! => {"msg": "'list object' has no attribute 'block_device_mappings'"}

When you take a look at the list you'll see that block_device_mappings is an attribute of _ansible_item_label
    "msg": [
        {
            "_ansible_ignore_errors": null,
            "_ansible_item_label": {
                "ami_launch_index": 0,
                "architecture": "x86_64",
                "block_device_mappings": [
                ...

Fix the reference

    device: "{{ item._ansible_item_label.block_device_mappings[0].device_name }}"


text:
Q: Program for simple editing of MOV files I need a program for editing moves, specifically, only MOV files.
Only simple editing required - cropping, splitting, trimming, etc.
One requirement is that the program does not re-render the video file,
since such changes generally do not need this.
A good example would be QuickTime X trimming facility - you can trim
a huge MOV file and it will save it in seconds, because it will not
render it again.

A: QuickTime Pro 7 is still around, and can do quite a bit to .mov container files natively. You can select, copy and paste video, extract streams, etc. They removed a TON of features from QuickTime X in the interest of making it prettier and more "user-friendly."

A: Yes, use QT Pro 7, and when you save the file, don't save the file as a self-contained movie, save it as a reference movie. It will take a lot less time. Note that you will need to keep all the original files for the reference movie to work.


text:
Q: Share API Data with child Component I am pulling data from an api using a service in angular 2 RC1.. it gets pulled into my main component but i would like to also share this data with other components that are children of the main template.. I have made an attempt with inputs but I think I was using them incorrectly so hopefully someone can steer me the right direction on here.. At the moment I am making a call to the api in both the main and the child component
--- Main Component
            import {Component} from '@angular/core';
            import {ProjectsMainApi} from "../../../services/projects-main";
            import { RouteConfig, RouteParams, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router-deprecated';
            import {ProjectMetaInfoComponent} from "./ProjectMetaInfoComponent";

            declare var jQuery: any;

            interface ProjectResult {
                project: Object
            }

            @Component({
                selector: 'projects',
                templateUrl: './app/components/Projects/details/project-single.html',
                directives: [ROUTER_DIRECTIVES, ProjectMetaInfoComponent]
            })

            export class ProjectDetailsComponent {
                project: Object = {};
                constructor(private _api: ProjectsMainApi, private _params: RouteParams) {

                    this._api.getSinglePortfolio( _params.get("slug") ).then(
                        (res: ProjectResult) => {
                            this.project = res.project[0];
                           console.log(this.project);
                        },
                        (error) => {
                            console.error(error);
                        }
                    )
                }
            }

--Child Component
            import {Component} from '@angular/core';
            import { RouteConfig, RouteParams, ROUTER_DIRECTIVES, ROUTER_PROVIDERS } from '@angular/router-deprecated';
            import {ProjectsMainApi} from "../../../services/projects-main";
            import { RuntimeCompiler} from '@angular/compiler/src/runtime_compiler';

            interface ProjectResult {
                project: Object
            }

            @Component({
                selector: 'project-meta',
                template: `

                                                Home |
                                                Projects |
                                                {{ title }}

{{ title }}

Intro...

{{ title }}

{{ headerOne }}

{{ infoOne }}

{{ headerTwo }}

{{ infoTwo }}

{{ headerThree }}

{{ infoThree }}

{{ headerFour }}

{{ infoFour }}

{{ headerFive }}

{{ infoFive }}

{{ headerSix }}

{{ infoSix }}

VISIT

              `
            })

            export class ProjectMetaInfoComponent {
                title: Object       = {};
                headerOne: Object   = {};
                headerTwo: Object   = {};
                headerThree: Object = {};
                headerFour: Object  = {};
                headerFive: Object  = {};
                headerSix: Object   = {};

                infoOne: Object     = {};
                infoTwo: Object     = {};
                infoThree: Object   = {};
                infoFour: Object    = {};
                infoFive: Object    = {};
                infoSix: Object     = {};

              constructor(private _api: ProjectsMainApi, private _params: RouteParams, private _runtimeCompiler: RuntimeCompiler) {

                    this._runtimeCompiler.clearCache();

                    this._api.getSinglePortfolio(_params.get("slug")).then(
                        (res: ProjectResult) => {
                            this.title       = res.project[0].title;

                            this.headerOne   = res.project[0].meta_header_one;
                            this.headerTwo   = res.project[0].meta_header_two;
                            this.headerThree = res.project[0].meta_header_three;
                            this.headerFour  = res.project[0].meta_header_four;
                            this.headerFive  = res.project[0].meta_header_five;
                            this.headerSix   = res.project[0].meta_header_six;

                            this.infoOne     = res.project[0].meta_info_one;
                            this.infoTwo     = res.project[0].meta_info_two;
                            this.infoThree   = res.project[0].meta_info_three;
                            this.infoFour    = res.project[0].meta_info_four;
                            this.infoFive    = res.project[0].meta_info_five;
                            this.infoSix     = res.project[0].meta_info_six;
                        },
                        (error) => {
                            console.error(error);
                        }
                    )
                }
            }

A: You can send data from Parent to child using input
<child-component [input]="api_result_variable"></child-component>

In the child directive you can use @Input to get the data

A: If the api service is an Angular 2 service, you can register it with the Angular injector using the provider property. If you register it in the parent, the data is available in the parent and all children.
See the example here: https://angular.io/docs/ts/latest/tutorial/toh-pt4.html


text:
Q: Find & replace in visual studio not replacing all occurrences I am using ctrl+shift+f to trigger "Find and replace", going to the tab "Replace in files".
I do a regexp search in the entire solution (which contains around 11000 files) for:
#layout(\d+)-top

replacing that with
#layout$1 .layout-top

A lot of files are changed by the operation, but when I after the operation open a certain css file, I still can read lines like:
#layout5-top,
#layout6-top
{
    width: 960px;
    height: 104px;
    margin: 0 auto;
}

Why?
If I do the same search & replace with that file open, the operation will affect the file.
I can find numerous files that are not changed by the way.
In the progress indicator that comes up when the search and replace runs, I see that every file is processed, not just open files.

A: I hit exactly the same problem. It only seems to happen when using a regular expression. I know that the files are being matched because if I swap to just 'find in files', the correct lines are matched in the files. It seems to be a bug to me. Possibly, Microsoft don't trust us not to shoot ourselves in the foot with regexes. ;)
The only way I could resolve it was to select the option:

Replace All will open all files with changes for editing

If you don't get this warning dialog, you may have disabled it, see here.
Then just type ALTfl to save all files and close all.
This seemed to work when there were around 200 files with replacements (the full set of files searched was around 10000). I am not sure how many files Visual Studio can have open at one time, so I imagine at some point it will no longer work or replacements will be missed, in which case you may need to run it a number of times.


text:
Q: How can open .plist file as source code xcode 11 beta 5 In new xcode 11 beta 5 there is no option to open .plist file as source code. Anyone know how can show this?

A: The only way I've found so far is to click on the plist in the project navigator, then click on the "Show or hide code review" icon in the toolbar.  That's this icon:

Now you can edit the XML.  Hope that helps.

A: The option is still there in Xcode 11, Xcode 11.4 beta & Xcode 12.2.


text:
Q: Subtraction in elastic search I have created query in elastic search to get more then two file with same name and hash.The query is -
{
  "size": 0,
  "aggregations": {
    "server": {
      "terms": {
        "field": "owner"
      },
      "aggregations": {
        "md5hash": {
          "terms": {
            "field": "md5hash"
          },
          "aggregations": {
            "sFileName": {
              "terms": {
                "field": "sFileName",
                "min_doc_count": 2
              },
              "aggregations": {
                "sourcesum": {
                  "sum": {
                    "field": "sourceSize"
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

Now I want to subtract doc.["sourceSize"] from sourcesum. How can I do this in above query.

A: You can do so by using the scripted metric aggregation
https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations-metrics-scripted-metric-aggregation.html
Here you can subtract the sourceSize and then perform the aggregation.


text:
Q: How to get correct table format ? Jquery ques This code prints output as given below...
code:
$('#calendar').append('

');
    var i;
    for(i=0;i<=6;i++)
        {
            $('#calendar').append(''+week[i]+'	');
        }
    $('#calendar').append('

');
    $('#calendar').append('
');

output:

Sunday	Monday	Tuesday	Wednesday	Thursday	Friday	Saturday

But i expect something in this structure..

...

A: jQuery appends elements , not the literal text...since it's immediately appended to the DOM the way you're currently doing it, you'll get some very funny behavior, since you're starting with unclosed tags (which it closes for you to prevent errors).
You just need to change your approach a bit, but doing it right also means even less code, like this:
var row = $('

').find('tr');
for(var i=0; i<=6; i++) {
    $('', { text: week[i] }).appendTo(row);
}
row.end().appendTo('#calendar');

You can view a working demo here, this creates the table using $(html), a document fragment, we then .find() the row and keep a handy reference to it, create the  elements one by one using $(html, props), and add them to the row using .appendTo().  After we've added them all, call .end() to change the chain to what it was before the .find() was called...in this case the entire
, then just append that table to the #calendar element :)

A: I think appending in jQuery appends tags, rather than just text. Did you try to examine the intermediate results? Your first line will already result in

 being appended to the section.
You can build the entire string you want to append, and then append it in one call.


text:
Q: Custom CAF Receiver and built-in slideshow issues We are currently working on a Custom CAF Receiver App. We would like to promote some of our contents using the built-in slideshow feature (see : https://developers.google.com/cast/docs/caf_receiver_features#slideshow). However, when the Receiver is launched, only the splash screen is displayed and not the slideshow. The slideshow only works when going back to idle state after having launched at least one video.
Is there a way to have the slideshow displayed right after the receiver launch? If yes how?
Also, we noticed that the --playback-logo-image (see : https://developers.google.com/cast/docs/caf_receiver_features#styling-the-player) is always hidden? Is this supposed to be displayed on a TV or is this a dedicated asset for touchscreen enabled Chromecast receiver?
Thanks!

A: We are having a similar type issue.  We do not see the slideshow until the user is in the idle state.  We also see either the background-image or splash-image for 10 seconds or so prior to the slideshow starting.  Here is what I have in a sample application.
<style>
body {
  /*--background-image: url('./images/bg_loading.jpg');*/
  --slideshow-interval: 5s;
  --slideshow-duration: 1s;
  --slideshow-image-1: url('./images/bg_idle_1.jpg');
  --slideshow-image-2: url('./images/bg_idle_2.jpg');
  --slideshow-image-3: url('./images/bg_idle_3.jpg');
  --logo-image: url('./images/bg_loading.jpg');
  --playback-logo-image: url('./images/icon_logo_small.svg');
  --splash-image: url('./images/bg_loading.jpg');
}
#video-holder {
  --theme-hue: 100;
  --progress-color: #FFFFFF;
  --pause-image: url('./images/icon_pause.svg');
  --spinner-image: url('./images/icon_loading.svg');
}

I also cannot get the logo images to appear anywhere.  The documentation is very unclear when it comes to what elements you should associate the CSS styles with.


text:
Q: Animation to individual scroll section Check full code here http://codepen.io/anon/pen/jWQOxa
In the above codepen I am trying to apply animation to different scroll sections. But when I open the application all the individual sections perform animation at same time. It does not wait till it actually comes into user's view. So I want to apply same animation and make it perform only when it comes into user's view. Please let me know how can I achieve this. Thanks in advance!
HTML5:

      hallo
      menu

About Us

Features

Our Team

Contact Us

Watch me move-1

        This example shows how to use CSS animations to make H1
         elements move across the page.

In addition, we output some text each time an animation event fires,so you can see them in action.

Watch me move-2

This example shows how to use CSS animations to make   H1elements move across the page.

In addition, we output some text each time an animation event   fires,so you can see them in action.

CSS:
  .aboutanimate,.featuresanimate,.teamanimate,.contactanimate {
    animation-duration: 1s;
    animation-name: slidein;
}

@keyframes slidein {
    from {
        margin-left: 100%;
        width: 300%;
    }
    to {
        margin-left: 0%;
        width: 100%;
    }
}

A: I have got quick hack solution instead of such a long solution. I have used animate.css and wow.js. And this works just as expected.
 You can see an example here :
http://codepen.io/anon/pen/obJqqm

About Us

Vision

"Lorem ipsem Lorem ipsemLorem ipsemLorem ipsemLorem ipsemLorem ipsem

Mission

"Lorem ipsemLorem ipsemLorem ipsemLorem ipsemLorem ipsemLorem ipsem"

Objectives

"Lorem ipsemLorem ipsemLorem ipsemLorem ipsemLorem ipsemLorem ipsemLorem ipsem"


text:
Q: MySQL connection 'asking for reconnection' To explain, I'll divide the code into subparts: (same scope)
<?php
### part 1
connect_db(); // My db connection function - works fine

### part 2
/* lot of code without closing mysql connection - these lines works fine too */

### part 3
/* lot of statements like the following */
if( $statement ){
    /* some code */
    mysql_close();
    exit;
}

### part 4
/* and after 2400 lines */
$query = mysql_query("SELECT row FROM table_name WHERE row = 'some_condition'");
while ( $fetch = mysql_fetch_object( $query ) ) {
    $myObj = mysql_fetch_object(mysql_query("SELECT row FROM table_name WHERE row = 'some_condition'"));
}
?>

At part 1, 2 and 3, any try to connect to db will result successfully. It's very important to mention that every mysql_close() is immediately suceded by an exit.
At part 4, a try to connect to db will give the following result - [EDIT] in the mysql_query inside of the while:
mysql_query() [function.mysql-query]: Access denied for user 'ODBC'@'localhost' (using password: NO)...

It's not an isolated case, once I've experiencing this issue for a long time in many files with apparently no error in my code.
My PHP version is 5.2.3 and Apache 2.2.4(Win32)
Anyone know what is causing this 'disconnection' after a few lines of code without an explicity order to close connection?

A: As per my understanding
You can use the mysql_ping() function to test the status of the connection and reconnect when it returns false.
Based on that you can handle it in PHP Code.


text:
Q: Arrow keys not working in Firefox We're creating a slideshow in HTML/CSS/JS but it isn't working in Firefox for some reason. It works in Webkit browsers without a problem..
The code is this:
    keyPress : function() {
      $( document.body ).keydown(function(e) {
         if ( e.keyCode === 37 || e.keyCode === 39 || e.which == 37 || e.which === 39) {
            e.preventDefault();
            ( e.keyCode === 39 || e.which === 39 ) ? Slides.next() : Slides.prev();
         }
      });
   },

If I use just $( document ) instead of ( document.body ) it does change my colours, but the slides don't change..
For some reason, Firefox (7.0.1, OSX Lion) doesn't pick up the keypresses.. It works in Safari/Chrome without a problem.
The site we're testing this on is : #took link out

A: UPDATE: I think your problem lies in the use of the "document.body" selector. This works for me in Chrome but not in Firefox ( http://jsfiddle.net/Jncrh/2/ ) Try just selecting "document" instead and see if it behaves. ( http://jsfiddle.net/Jncrh/5/ )
$(document).bind('keydown',function(e){
    if (e.which==37 || e.which==39) {
        e.preventDefault();
        if (e.which==37) {
            alert("going back");
        } else {
            alert("going forward");
        }
    }
});

Firefox can pick up the keypresses in the above sample, so I suspect the problem lies elsewhere in your code.
PREVIOUS: A quick Google search reveals that Firefox uses event.charCode instead of event.keyCode. Try this:
key = e.keyCode ? e.keyCode : e.which ? e.which : e.charCode;
if (key===37 || key===39) {...

However, jQuery should be able to pick up all of those with its own event.which, so I don't understand why that isn't working as-is for you.

A:     if ($.browser.mozilla) {
        $(document).keypress (keyType);
    }
    else{
       $(document).keydown (keyType);
    }

    function keyType(e){
    if (e.keyCode==37 || e.keyCode==39) {
        e.preventDefault();
        if (e.which==37) {
           //handle left
        }
        else {
          //handle right
        }
    }
}

A: In the keydown and keyup events, all major browsers support the keyCode property of the corresponding event, so there's no need for the which property. Also, to catch key events on the whole document, you need to attach the listener to the document rather than the body.
Here's the definitive page on JavaScript key events: http://unixpapa.com/js/key.html
And here's a revised version of your code:
$(document).keydown(function(e) {
    var leftArrow = (e.keyCode == 37), rightArrow = (e.keyCode == 39);
    if (leftArrow || rightArrow) {
        e.preventDefault();
        rightArrow ? Slides.next() : Slides.prev();
    }
});


text:
Q: PyCharm 2019.2.1 PEP8 line length checking works wrong I'm using PyCharm Community version on Win10. After one of the last updates PyCharm PEP8 style checking started to incorrectly underline words by the reason of PEP8 line length rule violation. Example:

or

Example for copy and error reproduction (it will raise PEP 8: line too long (200 > 120 characters) on the symbol =):
# матрицы ограничений (первый вектор - функция, второй вектор - значение меньше или равно которого эта функция)
a_list = []

I assume that the error is related to the Cyrillic symbols. If I delete comment on line 2 from the first example, string 'project' will no longer be underlined. Anyways I had no problems with the Cyrillic until this time.
Is it bug? How I can fix this behaviour of style checking without disable line checking? Thanks

A: That's a known issue with Cyrillic comments indeed: https://youtrack.jetbrains.com/issue/PY-37054
Either fix a bundled pycodestyle copy manually: https://youtrack.jetbrains.com/issue/PY-37054#focus=streamItem-27-3609146.0-0
or install PyCharm 2019.2.2 Preview build https://confluence.jetbrains.com/pages/viewpage.action?pageId=23004355


text:
Q: Mutate multiple columns I am trying to calculated the difference between the first and the last value for the each Group for the each columne (Value1, Value2, Value3 etc).
Group    Dates      Value1 Value2 Value3
1      2000-01-01     NA      0      5
1      2000-02-01      1      0     10
1      2000-03-01      2      1      0
2      2000-04-01      4      1     NA
2      2000-05-01      1      2     NA
2      2000-06-01      2      2     40

For example: diff_Value1=-1 because the first value for the Group 1 is 1 and last value is 2.
I am using below code. How can I extend for 30 more columns (e.g. Value1...-Value 30)?
Do I need to use loop inside mutate function?
df <- data.frame(Group=c(rep(1,3), rep(2,3)),
                    Dates=seq(as.Date("2000/1/1"), by = "month", length.out = 6),
                    Value1=c(NA, 1:2,4,1:2),
                    Value2=c(0,0,1,1,2,2),
                    Value3=c(5,10,0,NA,NA,40)
)

df %>%
  group_by(Group) %>%
  dplyr::mutate(
    Value1_diff = dplyr::first(na.omit(Value1))-dplyr::last(na.omit(Value1)),
    Value2_diff = dplyr::first(na.omit(Value2))-dplyr::last(na.omit(Value2)),
    Value3_diff = dplyr::first(na.omit(Value3))-dplyr::last(na.omit(Value3))
  )

 Group    Dates      Value1 Value2 Value3 Value1_diff Value2_diff Value3_diff
 1     2000-01-01     NA      0      5          -1          -1           5
 1     2000-02-01      1      0     10          -1          -1           5
 1     2000-03-01      2      1      0          -1          -1           5
 2     2000-04-01      4      1     NA           2          -1           0
 2     2000-05-01      1      2     NA           2          -1           0
 2     2000-06-01      2      2     40           2          -1           0

A: We may use across to loop over multiple columns
library(dplyr)
df <- df %>%
   group_by(Group) %>%
    mutate(across(starts_with('Value'),
    ~ first(na.omit(.)) - last(na.omit(.)), .names = "{.col}_diff")) %>%
    ungroup

-output
df
# A tibble: 6 × 8
  Group Dates      Value1 Value2 Value3 Value1_diff Value2_diff Value3_diff
  <dbl> <date>      <dbl>  <dbl>  <dbl>       <dbl>       <dbl>       <dbl>
1     1 2000-01-01     NA      0      5          -1          -1           5
2     1 2000-02-01      1      0     10          -1          -1           5
3     1 2000-03-01      2      1      0          -1          -1           5
4     2 2000-04-01      4      1     NA           2          -1           0
5     2 2000-05-01      1      2     NA           2          -1           0
6     2 2000-06-01      2      2     40           2          -1           0


text:
Q: Prove F test is equal to T test squared I need to show that F test is equal to T test squared, when the T test is for 2 independent groups and assuming variances are equal.
I know that $F=\frac{MSB}{MSW}=\frac{SSB/k-1}{SSW/N-K}$
and I know that $T=\frac{X-Y}{S_p \sqrt{\frac{1}{n}+\frac{1}{m}}}$,
so $T^2=\frac{(X-Y)^2}{S_p^2 ({\frac{1}{n}+\frac{1}{m}})}$
I've seen this proof in Regression but here we're not using MSE and MSR, so i'm not sure how to connect between the two.

A: Because one has $\boxed{T^2=F}$.
To show that, you have to check that (with $N=mn$):

*

*$SSW/(N-2)= S^2_p$ (the unbiaised estimate of $\sigma^2$)

*$SSB = {(\bar X- \bar Y)}^2/(\frac{1}{n}+\frac{1}{m})$
To show the second point you only have to use :

*

*the elementary equality $SSB=m{(\bar x - \bar{x\cdot y})}^2+n{(\bar y - \bar{x\cdot y})}^2$

*the fact that the mean of the whole sample $x\cdot y=(x_1, \ldots, x_m, y_1, \ldots y_n)$ is the weighted mean $\frac{m \bar x + n \bar y}{m+n}$

*some elementary but a little tiedous calculations to conclude
Sorry for the strange notation $x\cdot y$ for the "whole sample", this was my first idea and I'm in a hurry now.

A: You can rewrite the equation as \begin{equation}\frac{SSB/\left(k-1\right)}{SSW/\left(N-k\right)}=\frac{SSB\left(k-1\right)/\sigma^{2}\left(k-1\right)^{2}}{SSW\left(N-k\right)/\sigma^{2}\left(N-k\right)^{2}} \end{equation}
For $k=2$ (two groups), \begin{equation}\frac{SSB\left(k-1\right)/\sigma^{2}\left(k-1\right)^{2}}{SSW\left(N-k\right)/\sigma^{2}\left(N-k\right)^{2}}=\frac{SSB/\sigma^{2}}{SSW\left(N-2\right)/\sigma^{2}\left(N-2\right)^{2}}. \end{equation}
The numerator is a $\chi^{2}$  distribution with one degree of freedom. The denominator has the following distribution: \begin{equation} SSW\left(N-2\right)/\sigma^{2}\left(N-2\right)^{2}\sim\frac{\chi_{N-2}^{2}}{\left(N-2\right)^{2}}. \end{equation} Therefore, you have the ratio of two $\chi^{2}$  distributions. This ratio is equivalent to a $t$ distribution with $N-1$  degrees of freedom squared: \begin{equation}\frac{\chi_{1}^{2}}{\chi_{N-2}^{2}/\left(N-2\right)^{2}}\sim t_{N-2}^2. \end{equation}

A: I have done this proof in my blog
Since I already have the code for the equations, I'm reproducing it here.

We have to prove that
$$F_{a-1, N-a} = \frac{MST}{MSE} = \frac{\frac{SST}{a-1}}{\frac{SSE}{N-a}} \tag{1}$$
reduces to
$$t_{k}^2 = \frac{(\bar{y}_{1.} - \bar{y}_{2.})^2}{S_{p}^2(\frac{1}{n_{1}} + \frac{1}{n_{2}})} \tag{2}$$
$\color{red} {\text{When a = 2}}$ (this is key)

Notation
$SSE$: Sum of Squares due to Error
$SST$: Sum of Squares of Treatment
$MSE$: Mean Sum of squares Error
$MST$: Mean Sum of squares Treatment
$a$: Number of treatments
$n_{1}$: Number of observations in treatment 1
$n_{2}$: Number of observations in treatment 2
$N$: Total number of observations
$\bar{y}_{i.}$: Mean of treatment $i$
$\bar{y}_{..}$: Global mean
$k = N - a$: Degrees of freedom of the denominator of F

Now that we have the formulas, we will work the following:

*

*Denominator of equation (1)

*Numerator of equation (1)
2.a. Part a
2.b. Part b
2.c. Part c

*Put all together

1. Denominator of equation (1)
When $a = 2$ the denominator of expression $(1)$ is:
$$MSE = \frac{SSE}{N-2} = \frac{\sum_{j=1}^{n_1}{(y_{1j} - \bar{y}_{1.})^2} + \sum_{j=1}^{n_2}{(y_{2j} - \bar{y}_{2.})^2}}{N-2} \tag{3}$$
Recalling that the formula for the sample variance estimator is,
$$S_{i}^2 = \frac{\sum_{j=1}^{n_i}(y_{ij} - \bar{y}_{i.})^2}{n_{i} - 1}$$
we can multiply and divide the terms in the numerator in $(3)$ by $(n_{i} - 1)$ and get $(4)$. Don't forget that in this case $N = n_{1} + n_{2}$
$$\frac{SSE}{N-2} = \frac{(n_{1} - 1) S_{1}^2 + (n_{2} - 1) S_{2}^2}{n_{1} + n_{2} - 2} = S_{p}^2 \tag{4}$$
$S_{p}^2$ is called the pooled variance estimator.

2. Numerator of equation (1)
When $a = 2$ the numerator of expression $(1)$ is:
$$\frac{SST}{2-1} = SST$$
and the general expression for SST reduces to $SST = \sum_{1}^2 n_{i} (\bar{y}_{i.} - \bar{y}_{..})^2$ . The next step is to expand the sum as follows:
$$SST  =  \sum_{1}^2 n_{i} (\bar{y}_{i.} - \bar{y}_{..})^2
 =  n_{1} (\bar{y}_{1.} - \bar{y}_{..})^2 + n_{2} (\bar{y}_{2.} - \bar{y}_{..})^2 \tag{5}$$
$\bar{y}_{..}$ is called the global mean and we are going to write it in a different way. The new way is:
$$\bar{y}_{..} = \frac{n_{1} \bar{y}_{1.} + n_{2} \bar{y}_{2.}}{N} \tag{6}$$
Next, replace (6) in formula (5) and re-write SST as:
$$SST = \underbrace{n_1 \big[ \bar{y}_{1.} - (\frac{n_1 \bar{y}_{1.} + n_2 \bar{y}_{2.}}{N}) \big]^2}_{\text{Part a}} + \underbrace{n_2 \big[ \bar{y}_{2.} - (\frac{n_1 \bar{y}_{1.} + n_2 \bar{y}_{2.}}{N}) \big]^2}_{\text{Part b}} \tag{7}$$
The next step is to find alternative ways for the expressions Part a and Part b

2.a. Part a
$$\text{Part a} = n_1 \big[ \bar{y}_{1.} - (\frac{n_1 \bar{y}_{1.} + n_2 \bar{y}_{2.}}{N}) \big]^2$$
Multiply and divide the term with $\bar{y}_{1.}$ by $N$
$$n_1 \big[ \frac{N \bar{y}_{1.}}{N} - (\frac{n_1 \bar{y}_{1.} + n_2 \bar{y}_{2.}}{N}) \big]^2$$
$N$ is common denominator
$$n_1 \big[\frac{N \bar{y}_{1.} - n_1 \bar{y}_{1.} - n_2 \bar{y}_{2.}}{N} \big]^2$$
$\bar{y}_{1.}$ is common factor of $N$ and $n_1$
$$n_1 \big[\frac{(N - n_1) \bar{y}_{1.} - n_2 \bar{y}_{2.}}{N} \big]^2$$
Replace $(N - n_{1}) = n_{2}$
$$n_1 \big[\frac{n_2 \bar{y}_{1.} - n_2 \bar{y}_{2.}}{N} \big]^2$$
Now $n_{2}$ is common factor of $\bar{y}_{1.}$ and $\bar{y}_{2.}$
$$n_1 \big[\frac{n_2 (\bar{y}_{1.} - \bar{y}_{2.})}{N} \big]^2$$
Take $n_{2}$ and $N$ out of the square
$$\text{Part a} = \frac{n_{1} n_{2}^2}{N^2}  (\bar{y}_{1.} - \bar{y}_{2.})^2$$

2.b. Part b
$$\text{Part b} = n_2 \big[ \bar{y}_{2.} - (\frac{n_1 \bar{y}_{1.} + n_2 \bar{y}_{2.}}{N}) \big]^2$$
Multiply and divide the term with $\bar{y}_{2.}$ by $N$
$$n_2 \big[ \frac{N \bar{y}_{2.}}{N} - (\frac{n_1 \bar{y}_{1.} + n_2 \bar{y}_{2.}}{N}) \big]^2$$
$N$ is common denominator
$$n_2 \big[\frac{N \bar{y}_{2.} - n_1 \bar{y}_{1.} - n_2 \bar{y}_{2.}}{N} \big]^2$$
$\bar{y}_{2.}$ is common factor of $N$ and $n_2$
$$n_2 \big[\frac{(N - n_2) \bar{y}_{2.} - n_1 \bar{y}_{1.}}{N} \big]^2$$
Replace $(N - n_{2}) = n_{1}$
$$n_2 \big[\frac{n_1 \bar{y}_{2.} - n_1 \bar{y}_{1.}}{N} \big]^2$$
Now $n_{1}$ is common factor of $\bar{y}_{1.}$ and $\bar{y}_{2.}$
$$n_2 \big[\frac{n_1 (\bar{y}_{2.} - \bar{y}_{1.})}{N} \big]^2$$
Take $n_{1}$ and $N$ out of the square
$$\text{Part b} = \frac{n_{2} n_{1}^2}{N^2}  (\bar{y}_{2.} - \bar{y}_{1.})^2$$

Now that we have Part a and Part b we are going to go back to equation $(7)$ and replace them:
$$SST = \frac{n_{1} n_{2}^2}{N^2} (\bar{y}_{1.} - \bar{y}_{2.})^2 + \frac{n_{2} n_{1}^2}{N^2} (\bar{y}_{2.} - \bar{y}_{1.})^2 \tag{8}$$
Taking into account that $(\bar{y}_{1.} - \bar{y}_{2.})^2 = (\bar{y}_{2.} - \bar{y}_{1.})^2$, we can re-write equation $(8)$ as $(9)$:
$$SST = \underbrace{\big[ \frac{n_{1} n_{2}^2}{N^2} + \frac{n_{2} n_{1}^2}{N^2} \big]}_{\text{Part c}} (\bar{y}_{1.} - \bar{y}_{2.})^2 \tag{9}$$
This lead us with part Part c, that we are going to work next.

2.c. Part c
$$\text{Part c} = \frac{n_{1} n_{2}^2}{N^2} + \frac{n_{2} n_{1}^2}{N^2}$$
$N^2$ is common denominator and each of the summands has a $n_{1} n_{2}$ factor that we can factor out. Then we have:
$$\frac{n_{1} n_{2} (n_{1} + n_{2})}{N^2}$$
Replace $N = n_{1} + n_{2}$
$$\frac{n_{1} n_{2} N}{N^2}$$
Simplify $N$
$$\frac{n_{1} n_{2}}{N}$$
Re-write the fraction
$$\frac{1}{\frac{N}{n_{1} n_{2}}}$$
Replace $N = n_{1} + n_{2}$
$$\frac{1}{\frac{n_{1} + n_{2}}{n_{1} n_{2}}} = \frac{1}{\frac{1}{n_{1}} + \frac{1}{n_{2}}}$$
And we have
$$\text{Part c} = \frac{1}{\frac{1}{n_{1}} + \frac{1}{n_{2}}}$$

Finally, we have to replace this expression for Part c in $(9)$ and re-write SST as:
$$SST = \frac{1}{\frac{1}{n_{1}} + \frac{1}{n_{2}}} (\bar{y}_{1.} - \bar{y}_{2.})^2$$

3. Put all together
With the previous steps we have shown that, $\color{red} {\text{when a = 2}}$, we have:
$$\frac{SST}{2-1} = \frac{(\bar{y}_{1.} - \bar{y}_{2.})^2}{\frac{1}{n_{1}} + \frac{1}{n_{2}}}$$
and
$$\frac{SSE}{N-2} = S_{p}^2$$
The ratio of these two expressions, namely the F-statistic, is then:
$$F_{1, k} = \frac{\frac{SST}{2-1}}{\frac{SSE}{N-2}} = \frac{(\bar{y}_{1.} - \bar{y}_{2.})^2}{S_{p}^2 \big( \frac{1}{n_{1}} + \frac{1}{n_{2}} \big)} = t_{k}^2$$
And this concludes the proof.


text:
Q: Обновить данные в mySQL Здравствуйте!
Есть код в файле settings.php:
<?$day = "<select onChange='setting(this)';>";

$day .= "<option value='r'>".trans('r')."</option>";

$day .= "<option value='ho'>".trans('ho')."</option>";

$day .= "<option value='kr'>".trans('kr')."</option>";

$day .= "<option value='do'>".trans('do')."</option>";

$day .= "<option value='v'>".trans('v')."</option>";

$day .="</select>";?>

Код выбора элемента на javascript:
function setting(select) {
val = select.options[select.selectedIndex].value;

alert (val);

}

Есть некий файл update_settings.php:
Тут будет располагаться обновление данных БД.
Такой вопрос: можно как-то реализовать обновление данных в БД путём передачи данных в javascript? А в файле update_settings их REQUESтом перехватить и сделать обновление в БД. Возможно этот как-то реализовать? Если да, то подскажите, как, пожалуйста. Спасибо.
A: Через jQuery.
Подгрузить библиотеку jQuery:

Добавить обработчик события change для select:

Ваш код вывода php:
  <?php
  $day = "<select id='trans'>";
  $day .= "<option value='r'>".trans('r')."</option>";
  $day .= "<option value='ho'>".trans('ho')."</option>";
  $day .= "<option value='kr'>".trans('kr')."</option>";
  $day .= "<option value='do'>".trans('do')."</option>";
  $day .= "<option value='v'>".trans('v')."</option>";
  $day .="</select>";
  ?>

Код /ajax/update.php
<?php

$trans = $_GET['trans'];

...
if(Запрос обновления таблицы БД){
    echo 'Record was updated!';
}

?>

A: <select id="category" name="category">
<option value="1" name="123">1</option>
<option value="2" name="456">2</option>
<option value="3" name="789">3</option>
<option value="4" name="562">4</option>
</select>

**AJAX**

$(function(){
   $("#category").change(function() {
      var styleValue = $(this).val();
    $("#categoryDisplay").load('fuck.php', {style: styleValue});
   });
}).change();

fuck.php
            <?php

$style = $_POST['style'];

switch($style){
case "1": $category = "Выберите категорию";
            break;

case "2": $category = "хай 1";;
            break;

case "3": $category = "хай 2";
            break;

case "4": $category = "хай 3";
            break;
default: exit(); break;
}

echo <<< MyObject
{$category}
MyObject;

?>


text:
Q: how to send disabled checkbox value into database I want to send the value of disabled checkbox into the database. I tried to set it to readonly but it is allowing user to check/uncheck the field.
<?php
  if(isset($_POST['bookbtn'])){

    if(!empty($_POST['checky'])) {

      $lang = implode(",",$_POST['checky']);

      // Insert and Update record
      $checkEntries = mysqli_query($conn,"SELECT * FROM seats");
     if($test == $hotel)
         $ic = "update seats set seat='$lang'  where hotelname='$test' ";
        mysqli_query($conn,$ic);

         }else{
        $del = "insert into seats (hotelname,seat) values ('$test','$lang')";
         mysqli_query($conn,$del);
      }
    }

  // code for checkbox
  <form method="post">

<input type="submit"class="button1" name="bookbtn" value="Book Your table" onclick="bookbtn()"/>
        <input type="reset" class="button1"name="resetboxes"value="Reset">

<?php $i=1;
    while ($i<=$tab)
   {?>

            <input type ="checkbox"name="checky[]"id="<?php echo "two".$i;?>"class="tabtwo"style="width:30px;height:30px;"
            value="<?php echo "two".$i;?>"
            <?php if (in_array("two".$i, $expcheck)) {?>
               checked="checked"<?php }else {echo "none";}?>disabled>

 <?php
 $i++;
}
?>

A: try this

<input type="checkbox" onclick="this.checked=this.defaultChecked" />
<input type="checkbox" checked onclick="this.checked=this.defaultChecked" />


text:
Q: Python threads stuck at _ssl.sslwrap I have a multithreaded Python (2.7.6) application that sometimes get stuck when calling requests.post (the library is at version 2.5.1). Here's what I get for the stack trace (found by calling sys._current_frames()):
"/usr/local/lib/python2.7/dist-packages/requests/api.py", line 99 in post
  return request('post', url, data=data, json=json, **kwargs)
"/usr/local/lib/python2.7/dist-packages/requests/api.py", line 49 in request
  response = session.request(method=method, url=url, **kwargs)
"/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 461 in request
  resp = self.send(prep, **send_kwargs)
"/usr/local/lib/python2.7/dist-packages/requests/sessions.py", line 573 in send
  r = adapter.send(request, **kwargs)
"/usr/local/lib/python2.7/dist-packages/requests/adapters.py", line 370 in send
  timeout=timeout
"/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connectionpool.py", line 518 in urlopen
  body=body, headers=headers)
"/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connectionpool.py", line 322 in _make_request
  self._validate_conn(conn)
"/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connectionpool.py", line 727 in _validate_conn
  conn.connect()
"/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/connection.py", line 238 in connect
  ssl_version=resolved_ssl_version)
"/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py", line 254 in ssl_wrap_socket
  return context.wrap_socket(sock)
"/usr/local/lib/python2.7/dist-packages/requests/packages/urllib3/util/ssl_.py", line 80 in wrap_socket
  return wrap_socket(socket, ciphers=self.ciphers, **kwargs)
"/usr/lib/python2.7/ssl.py", line 487 in wrap_socket
  ciphers=ciphers)
"/usr/lib/python2.7/ssl.py", line 241 in __init__
  ciphers)

Checking line 241 of ssl.py, I find it's the last line of this call:
self._sslobj = _ssl.sslwrap(self._sock, server_side,
                            keyfile, certfile,
                            cert_reqs, ssl_version, ca_certs,
                            ciphers)

When threads get stuck here, it appears that they are stuck permanently. I was able to see 24 threads stuck here for about two days before I had to restart my application. I'm using requests quite a bit and the vast majority of the time there is no problem, but for some reason the 24 threads all got stuck within the space of a couple minutes. Does anyone know what is going on here?
Note: I can't consistently reproduce it other than just letting it run and waiting for a batch of threads to eventually get stuck.


text:
Q: Bifurcation points of system of non linear differential equations I had a ODE of second order, then I built the following system of differential equations:
$$x' = y$$
$$y' = -\lambda sin(x) -2sin(x) -sin(x)cos(x)$$
With $\lambda = \frac{w^2}{\Omega^2}$ . I want to find the bifurcation points of the system. First of all I find the critical points, which are all of the form $(\pi k,0)$ with $k \in \mathbb{Z}$. Let's focus on k = 0 for simplicity.
I tried to linearize it, and I got:
$$x' = y$$
$$y' = -\lambda x -2x $$
I hope it is right. Now, I find that the matrix of the system is
\begin{bmatrix}
    0      & 1 \\
   -\lambda    & -2
\end{bmatrix}
The corresponding eigenvalues are:
$x_{1,2} = -1 \pm \sqrt{1-\lambda}$
Is the procedure correct until now? What can I say about the stability?


text:
Q: eslint: "Parsing error: Unexpected token of" When using the following code in my web app I get the following return from ESLint. I would prefer using this loop method as opposed to the increment I method. What does this error mean? And does it mean there is something wrong with the use of the loop?
Error Message:
Parsing error: Unexpected token of

Actual effected code:
renderCanvas: function() {
  console.log("Rendering Model");
  var canvases = document.getElementsByClassName("DesignerCanvas");
  for (var canvas of canvases) {
    var ctx = canvas.getContext('2d');

    ctx.beginPath();
    // String for Hanging
    ctx.closePath();

    ctx.beginPath();
    // Top Trimming
    ctx.closePath();

    ctx.beginPath();
    // Outter Shade Body
    ctx.closePath();

    ctx.beginPath();
    // Bottom Trimming
    ctx.closePath();

    ctx.beginPath();
    // Inner Shade Body
    ctx.closePath();
  }
}

A: for-of loops are an EcmaScript 6 feature, and these are not enabled by default in ESLint.
According to the documentation:

What about ECMAScript 6 support?
  ESLint has full support for ECMAScript 6. By default, this support is off. You can enable ECMAScript 6 support through configuration.

If you then follow the configuration link, it tells you that you can enable the es6 environment with
/*eslint-env es6 */

in the JavaScript file, or
{
    "env": {
        "es6": true
    }
}

in the configuration file.


text:
Q: retrieving google sheets cell for calendar returns "last updated" I currently have a google sheets script that's automated to create a google calendar event daily at a specific time from a google sheets cell. When I execute it manually, it works. But when I allow it to automatically execute at that specific time it simply creates a calendar event with the title "last updated." Any idea why? I've included the code below:
function sheets_to_calendar(){

var mycal = "xxx@gmail.com";
var event = CalendarApp.getCalendarById(mycal);

var Title = SpreadsheetApp.getActiveSheet().getRange('J1').getValue();
var date = new Date();
var description = SpreadsheetApp.getActiveSheet().getRange('F2').getValue();

event.createAllDayEvent(Title, date, {description: description});

}

A: You should check how many triggers are in your project
In order to avoid your code running twice at the specific time you mentioned, keep in mind Google Calendar events are separated in 30 minutes time range, in other words, e.g. if there are 2 triggers running at 08:00 AM and 08:29 AM they are still the same Calendar event, that's why you get your event updated.
If the error persists, try to create your trigger programatically
As I can see in your question, you are managing time-driven triggers, for that reason as a workaround you can create a temporary function in your project and create your trigger using code:
/**
 * Creates two time-driven triggers.
 */
function createTimeDrivenTriggers() {
  // Trigger every 6 hours.
  ScriptApp.newTrigger('myFunction')
      .timeBased()
      .everyHours(6)
      .create();

  // Trigger every Monday at 09:00.
  ScriptApp.newTrigger('myFunction')
      .timeBased()
      .onWeekDay(ScriptApp.WeekDay.MONDAY)
      .atHour(9)
      .create();

Which is recommended because using new Date() is using the time on server.
References

*

*Calendar.createAllDayEvent

*Installable Triggers


text:
Q: MERGE INTO DbVisualizer not worknig Heelo everyone,
I'm trying to use Merge INTO to update my table from another table like that example here:
MERGE INTO locations l USING new_locations n
ON (l.customer_id = n.customer_id
AND l.location_x = n.location_x
AND             l.location_y = n.location_y)
WHEN MATCHED THEN UPDATE SET location_count = l.location_count + n.location_count
WHEN NOT MATCHED THEN INSERT (customer_id, location_x, location_y, location_count, location_name)
VALUES (n.customer_id, n.location_x, n.location_y, n.location_count, n.location_name);

i'm using MSSQL and connect via DbVisualizer and ODBC brideg.
when i run the command it state: General error;
after some search i found here
that you have to use this format for Mere into in VbVisualizer:
@delimiter %%;
MERGE x AS y<code here>
;
@delimiter ;%%

when i did it this way the program hang on : Parsing the script.
I tried to change the default statement separator for DbVisualizer but still no luck
/***********************************Editing ****************************/

If i removed the i get
09:27:46  [MERGE - 0 row(s), 0.000 secs]  [Error Code: 10713, SQL State: 37000]  [Microsoft][ODBC SQL Server Driver][SQL Server]A MERGE statement must be terminated by a semi-colon (;).

if i used the tool properties Statement Delimeters and replace the (;) with GO i get the following error
09:29:24  [MERGE - 0 row(s), 0.000 secs]  [Error Code: 0, SQL State: S1000]  General error

/*******************************End Editing ****************************/
can you help me?
thanks

A: It Seems that because Merge is a transact/SQL query it needs multi line to commit the transaction which DB visualizer does not allow in the free version :(
hope I could find alternative.


text:
Q: Order by not giving expected results in SQL Server select I have select statement  table with two columns, storebusinesskey and businessdate.
When I run a select and try to sort the output by storebusinesskey, it's not working.
SELECT
    t1.StoreBusinessKey, DateBusinessKey AS BusinessDate
FROM
    TABA t1
LEFT JOIN
    TABB t2 ON t1.StoreBusinessKey = t2.StoreBusinessKey
            AND t1.DateBusinessKey = t2.BusinessDate
WHERE
    t2.BusinessDate IS NULL
ORDER BY
    t1.StoreBusinessKey DESC

Output

StoreBusinessKey
BusinessDate

C95
2022-03-15

C91
2022-03-27

C89
2022-03-09

C784
2022-03-22

C784
2022-03-15

C766
2022-03-22

C766
2022-03-29

C759
2022-03-22

C693
2022-03-22

C681
2022-03-22

C674
2022-03-30

C654
2022-03-30

C606
2022-03-30

C595
2022-03-29

C595
2022-03-30

C56
2022-03-30

C521
2022-03-30

C52
2022-03-30

C486
2022-03-27

C486
2022-03-30

C486
2022-03-26

C486
2022-03-29

C486
2022-03-28

C476
2022-03-29

C476
2022-03-30

C471
2022-03-30

As you can see C52 should come in top but it's not. Can you please help me to sort this output by Storebusinesskey first and then by businessdate?

A: Your sorting on the string value.  Assuming one leading alpha and with a little string manipulation, we can easily convert to an int and sort
Example
Declare @YourTable Table ([StoreBusinessKey] varchar(50),[BusinessDate] varchar(50))
Insert Into @YourTable Values
 ('C95','2022-03-15')
,('C91','2022-03-27')
,('C89','2022-03-09')
,('C784','2022-03-22')
,('C784','2022-03-15')
,('C52','2022-03-30')   -- Should be first

Select *
 From  @YourTable
 Order By try_convert(int,substring([StoreBusinessKey],2,25))
         ,[BusinessDate]

Results
StoreBusinessKey    BusinessDate
C52                 2022-03-30
C89                 2022-03-09
C91                 2022-03-27
C95                 2022-03-15
C784                2022-03-15
C784                2022-03-22


text:
Q: Define a function f such that for x≠0 f(x) =cos(1/x) and f(0)=1/2.does it admits antiderivatives? (primitives) Does the function f have antiderivatives? I know that because 1/2 is between - 1 and 1 it has Darboux 's property

A: Hint: See if you can prove this:  if $f$ is bounded, and for every $a$ with $0 < a < 1$, $f$ is Riemann integrable on $[a,1]$, then $f$ is Riemann integrable on $[0,1]$. Do the same thing for $[-1,b]$, $-1<b<0$.
If there is any anti-derivative of $f$, then this would be it:
$$
F(x) = \int_0^x f(t)\;dt,\qquad\text{for all real numbers } x
$$
If $f$ is continuous except at $0$, this gives us $F$ with $F'(x) = f(x)$ for all $x$ except possibly $x=0$.
In the particular case on the OP, we get $F'(0) = 0$,
but I will not prove that here.
So your answer is "no", your function has no anti-derivative on $[-1,1]$.
The Darboux property is necessary, but not sufficient, for the existence of an anti-derivative.


text:
Q: Problem with getting params from paramMap So people i trying to catch a ID on the URL with paramMap but it always returns null anyone can figure the problem?
Component.ts
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { ActivatedRoute, Router } from '@angular/router';
import { SenatorsService } from '../senators.service';

@Component({
  selector: 'app-senator-expenses',
  templateUrl: './senator-expenses.component.html',
  styleUrls: ['./senator-expenses.component.css']
})
export class SenatorExpensesComponent implements OnInit {
  senator: Senator[] = []
  id: number;
  constructor(private SenatorsService: SenatorsService, private route: ActivatedRoute, private a: Router) { }

  ngOnInit(): void {
    this.route.paramMap.subscribe(paramMap => {
      this.id = parseInt(paramMap.get('id'));
      console.log(this.id)
    })
  }

}

Routing file
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { SenatorExpensesComponent } from './senator-expenses/senator-expenses.component';
import { SenatorsListComponent } from './senators-list/senators-list.component';

const routes: Routes = [
    { path: 'senadores', component: SenatorsListComponent },
    {path: '', redirectTo: 'senadores', pathMatch : 'full'},
    {path: 'senadores/:id ', component: SenatorExpensesComponent} //This is the route i tryng to get the id
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

component.html

    <mat-toolbar>
        Senators list
    </mat-toolbar>

<mat-nav-list>
    <mat-list-item *ngFor="let senator of senators">
        {{senator.nomeSenador}}
    </mat-list-item>
</mat-nav-list>

I try to use too "this.id = this.route.params" but dont work.

A: this.id = parseInt(this.route.snapshot.params.id);

Can you try this?

A: Sorry for losing or time guys, actually the problem is in the line:
{path: 'senadores/:id ', component: SenatorExpensesComponent}

As you see have a space between id and the quotes, this is the problem i was searching for this.id = parseInt(paramMap.get('id')); instead of this.id = parseInt(paramMap.get('id ')); But thanks anyway who tryed to help me.


text:
Q: How to get Shadow on UIView as from Top side Only ? [ Objective-c ] I  want shadow on UIView From Top side only as shown in image below.
I am trying this code to  apply shadow , but shadow is applied on right side of view but i want it from top side.
UIEdgeInsets contentInsets = UIEdgeInsetsMake(10, 0, 0, 0);
CGRect shadowPath = UIEdgeInsetsInsetRect(self.dealMainContentView.bounds, contentInsets);
self.dealMainContentView.layer.shadowPath = [UIBezierPath bezierPathWithRect:shadowPath].CGPath;
self.dealMainContentView.layer.shadowColor = [[UIColor blackColor] CGColor];
self.dealMainContentView.layer.shadowOffset = CGSizeMake(0.0f,0.0f);
self.dealMainContentView.layer.shadowOpacity = 0.4f;
self.dealMainContentView.layer.masksToBounds=NO;

This how it should look like

A: I solved this with own , i was able to get the desired shadow  by modifying the frame before making Path  .
just the hack :)
Instead of passing view.frame in this method i modified the frame
UIEdgeInsetsInsetRect(viewFrame, contentInsets);  and got shadow from top side .
this is the code below
UIEdgeInsets contentInsets = UIEdgeInsetsMake(-10, -10, 0, 0);

    CGRect viewFrame=self.dealMainContentView.frame;

    viewFrame.origin.x += 5; // 5 distance from left
    viewFrame.origin.y -= 15;
    viewFrame.size.width -= 1o;  // 5 distance from Right
    viewFrame.size.height -= 20;

   CGRect shadowPathExcludingTop = UIEdgeInsetsInsetRect(viewFrame, contentInsets);

   self.dealMainContentView.layer.shadowPath = [UIBezierPath bezierPathWithRect:shadowPathExcludingTop].CGPath;
    self.dealMainContentView.layer.shadowColor = [[UIColor blackColor] CGColor];
    self.dealMainContentView.layer.shadowOffset = CGSizeMake(0.0,0.0f);
    self.dealMainContentView.layer.shadowOpacity = 0.3f;
    self.dealMainContentView.layer.masksToBounds=NO;


text:
Q: Count num_rows base on field value *The actual problem is quite more complex than the post title :S
Suppose I have table
ID | vote_id |  vote_type |  vote_user

1  ----  2  -----   up -------    Tom
2  ----  3  -----   up -------    John
3  ----  3  -----   down -----    Harry
4  ----  4  -----   up -------    Tom
5  ----  2  -----   down -----    John
6  ----  3  -----   down -----    Tom

So what I want to do is

*

*Query the table by specific vote_id

*Then Count how many voted up and how many voted down from the query in 1

*Then I want to check also that had John voted for that vote_id or not.

And the way I do is.
$up=0;
$down=0;
$voted="no";
$r=mysql_query("SELECT*FROM table_name WHERE vote_id == 3");

 while($row=mysql_fetch_array($r){
   if($row["vote_type"]=="up"){ $up++;}else{$down++;}
   if($row["vote_user"=="John"){ $voted="yes";}
 }

But is there a way ( equivalent code ) to do this without using WHILE LOOP because the actual table can be very large so running while loop can be very exhaustive :S
EDIT  Can I do with single query?

A: Use two separate queries:
Count all votes:

    SELECT vote_type, COUNT(*) AS amount
    FROM table_name
    WHERE vote_id = 3
    GROUP BY vote_type

will return up to two rows:
vote_type | amount
----------+--------
up        | 1
down      | 2

Find out if John voted:

    SELECT vote_type
    FROM table_name
    WHERE vote_id = 3
    AND vote_user = 'John'

will return a row containing either up, down or NULL based on how John voted. Assuming he can only vote once...
Note that adding indexes on vote_type and maybe vote_user will help performance.

A: You can run this query to give you a table of votes up and down for a specific vote_id.
select vote_type, COUNT(*) from votes where vote_id = 2 AND group by vote_type

I would run another query to check to see if John voted for that vote_id or not
select count(*) from votes where vote_id = 2 AND vote_user = 'John'

A: In a single query
Select
  sum(case when vote_type = 'up' then 1 else 0 end) as up,
  sum(case when vote_type = 'down' then 1 else 0 end) as down,
  sum(case when vote_user = 'john' then 1 else 0 end) as john
from
  yourTable
where
  vote_id = 3

Or any variation of sum(case when)