text:
Q: The functionality of updates in theano.function I am trying to understand the following piece of theano code.
self.sgd_step = theano.function(
            [x, y, learning_rate, theano.Param(decay, default=0.9)],
            [],
            updates=[(E, E - learning_rate * dE / T.sqrt(mE + 1e-6)),
                     (U, U - learning_rate * dU / T.sqrt(mU + 1e-6)),
                     (W, W - learning_rate * dW / T.sqrt(mW + 1e-6)),
                     (V, V - learning_rate * dV / T.sqrt(mV + 1e-6)),
                     (b, b - learning_rate * db / T.sqrt(mb + 1e-6)),
                     (c, c - learning_rate * dc / T.sqrt(mc + 1e-6)),
                     (self.mE, mE),
                     (self.mU, mU),
                     (self.mW, mW),
                     (self.mV, mV),
                     (self.mb, mb),
                     (self.mc, mc)
])

Can someone please tell me, what the author of the above code is trying to do there? There is a value, [x, y, learning_rate, theano.Param(decay, default=0.9)] trying to be updated, and the value is gonna be updated by []? And what is the function of updates here?
I would be so grateful if I can have an idea what is going on in the above code?

A: The documentation of the updates is as follows (taken from here).

updates must be supplied with a list of pairs of the form (shared-variable, new expression). It can also be a dictionary whose keys are shared-variables and values are the new expressions. Either way, it means "whenever this function runs, it will replace the .value of each shared variable with the result of the corresponding expression". Above, our accumulator replaces the state's value with the sum of the state and the increment amount.

So when you call the above theano function with the required inputs, it will update values of shared variables, namely E, U, W, V, b, c, ..., self.mc. The new value to be updated is given by the second quantity in the tuple. Basically, E = E - learning_rate * dE / T.sqrt(mE + 1e-6) and so on.


text:
Q: Firebase Emulator slow when using 0.0.0.0 host I'm having an issue setting up the Firebase Emulator on a Mac Mini with Apple Silicon (M1 chip).
Every request I send to Firestore (using the emulator) takes a very long time to complete (sometimes it never completes and I get a network error saying the backend couldn't be reached):

@firebase/firestore: Firestore (8.2.5): Could not reach Cloud Firestore backend. Backend didn't respond within 10 seconds.
This typically indicates that your device does not have a healthy Internet connection at the moment. The client will operate in offline mode until it is able to successfully connect to the backend.

It turns out this is happening because I'm setting host to 0.0.0.0 in the firebase.json file. If I remove the host field or if I set it to be localhost, then I don't have any issues.
This is my firebase.json file:
{
  "firestore": {
    "rules": "./firestore.rules"
  },
  "emulators": {
    "firestore": {
      "host": "0.0.0.0",
      "port": 8080
    }
  }
}

The reason I'm setting it to 0.0.0.0 is because I need to test my app on a different machine (i.e. on a tablet) and the only way we managed to make it work was setting the host to be 0.0.0.0 since this host will resolve all addresses associated with our machine. This way, I can access the emulator using my local IP address (i.e. 192.168.0.1).
I noticed this issue only happens on the new Mac with the M1 Apple Silicon chip. So, I wonder if this has anything to do with the way M1 is resolving the IP address.
Any ideas?

A: I'm still not sure if this is M1-specific since I haven't been able to test this on another M1 machine but adding my computer's name next to localhost in the hosts file seems to have fixed this issue:
127.0.0.1    localhost Will.local
::1          localhost Will.local

A: I had the same issue with my new M1 Macbook Pro. The problem did remaining no matter if there were host info on firebase.json. -file.
I found an exciting solution to this problem. I switched my Mac to Google's DNS -servers (8.8.8.8 and 8.8.4.4), and suddenly everything started to work without any significant delays. Before that, the initial call sometimes took 10-15 seconds or even more.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get last auto increment value in mysql table? I'm working on a javafx project where a user can register as either a driver or a client. For this, I created 3 tables in a mysql database, a general one for all users and 2 specific ones for the drivers and the clients. When a new user registers he is placed in the database_user table and, depending on his selected role, he is also placed in either database_client or database_driver. The problem is that the specific tables should have a column storing the primary key value (autoincrement value) from the general table, for easier communication.
public static void registerClient(ActionEvent event, String username, String password, String role, String name, int age, String gender, String email)
    {
        /*
          these variables are the connections to the mysql database
          */

        Connection connection = null;
        PreparedStatement psInsert = null;
        PreparedStatement psInsertClient = null;
        PreparedStatement psCheckUserAlreadyExists = null;
        //PreparedStatement psCheckEmailAlreadyUsed = null;
        ResultSet resultSet = null;

        try{
            /*
              this will attempt to establish a connection with the db
              */

            connection = DriverManager.getConnection("jdbc:mariadb://lazarov.go.ro:3306/RideShare", "root", "chocolate");
            psCheckUserAlreadyExists = connection.prepareStatement("SELECT * FROM database_user WHERE username = ?");
            psCheckUserAlreadyExists.setString(1, username);
            //psCheckEmailAlreadyUsed = connection.prepareStatement("SELECT * FROM user_database WHERE email = ? ");
            //psCheckEmailAlreadyUsed.setString(7, email);
            resultSet = psCheckUserAlreadyExists.executeQuery();

            /*
              check if the resultSet is empty
              if true => username already taken => notify user about this
             */

            if(resultSet.isBeforeFirst())
            {
                System.out.println("Username already taken!");
                Alert alert = new Alert(Alert.AlertType.ERROR);
                alert.setContentText("User already exists!");
                alert.showAndWait();
            }
            else
            {
                psInsert = connection.prepareStatement("INSERT INTO database_user (username, password, role, name, age, gender, email) VALUES (?, ?, ?, ?, ?, ?, ?)");
                psInsert.setString(1, username);
                psInsert.setString(2, password);
                psInsert.setString(3, role);
                psInsert.setString(4, name);
                psInsert.setInt(5, age);
                psInsert.setString(6, gender);
                psInsert.setString(7, email);
                psInsert.executeUpdate();

                ResultSet rs = null;
                psInsert = connection.prepareStatement("SELECT max(user_id) FROM database_user");
                rs = psInsert.executeQuery();
                // driver specific
                int userId = resultSet.getInt("max(user_id)"); // this is where the error occurs

                //Connection connectionDriver = null;

                psInsertClient = connection.prepareStatement("INSERT INTO database_client (user_id, ride_requested, location, destination, corresponding_driver_id) VALUES (?, ?, ?, ?, ?)");
                psInsertClient.setInt(1, userId);
                psInsertClient.setBoolean(2, false);
                psInsertClient.setString(3, null);
                psInsertClient.setString(4, null);
                psInsertClient.setInt(5, 0);

                changeScene(event, "client.fxml", "RideShare - Client", username, role, name, age, gender, email);
            }
        }catch (SQLException e)
        {
            e.printStackTrace();
        }finally {
            /*
              close db connections to avoid memory leaks
              */

            if(resultSet != null)
            {
                try{
                    resultSet.close();
                }catch (SQLException e)
                {
                    e.printStackTrace();
                }
            }
            if(psCheckUserAlreadyExists != null)
            {
                try{
                    psCheckUserAlreadyExists.close();
                }catch (SQLException e)
                {
                    e.printStackTrace();
                }
            }
            if(psInsert != null)
            {
                try {
                    psInsert.close();
                }catch (SQLException e)
                {
                    e.printStackTrace();
                }
            }
            if(psInsertClient != null)
            {
                try {
                    psInsertClient.close();
                }catch (SQLException e)
                {
                    e.printStackTrace();
                }
            }
            if(connection != null)
            {
                try{
                    connection.close();
                }catch (SQLException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }

If I try to create a new user, the user is added in the database_user correctly, but throws the error "wrong row position" when trying to store it in the "database_client" as well. How can I successfully get the last autoincremented value from the general table?


text:
Q: fill in mulitple excel cells based on multiple cell values similar to a gantt chart I would like to create a Gantt chart like with excel based on task start and duration cell values. I have an excel as below:

Item
Start
Duration(months)
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug

1
Q1
6

2
Q2
3

3
Q2
1

*

*Start column indicates the quarter-calender the task starts.

*Duration indicates the number of months the task can take to complete.

Based on these two value I would like to have a formula in columns Jan-Aug to fill with x appropriately
Desired output:

Item
Start
Duration(months)
Jan
Feb
Mar
Apr
May
Jun
Jul
Aug

1
Q1
6
x
x
x
x
x
x

2
Q2
3

x
x
x

3
Q2
1

x

I dabbled with XLOOKUP and OFFSET with no luck. Tried creating defined names as in Microsoft template with no luck

A: You can try the following formula in cell D2:
=LET(months, MONTH(D1:O1), dur, C2:C4, Qs, B2:B4,
  QsUx, SORT(UNiQUE(Qs)), start, XLOOKUP(Qs, QsUx, SEQUENCE(ROWS(QsUx),,1,3)),
  end, start + dur - 1,
  GEN_X, LAMBDA(idx, MAP(start, end, LAMBDA(ss, ee,
    LET(month, INDEX(months,,idx), IF(MEDIAN(ss, ee, month) = month, "x",""))))),
  DROP(REDUCE("", months, LAMBDA(acc, m, HSTACK(acc, GEN_X(m)))),,1)
)

and here is the output:

Note: The formula generates the entire grid, there is no need to expand the formula.
Explanation
It uses the following two ideas:

*

*To populate the grid using the MEDIAN function. Check the answer provided by  @JosWoolley: Sum unique day count within a date ranges.

*DROP/REDUCE/HSTACK pattern to iterate over all the month's columns to generate the x's for a given column. Check the answer provided by @DavidLeal to the question: how to transform a table in Excel from vertical to horizontal but with different lengths.

The rest is just to prepare/transform the input data in the format we want. The LET function is used for easy reading and composition.
The row with the months: D1:O1 was generated in date format as follows:
=EDATE(DATE(2022,1,1), SEQUENCE(1,12,0))

Now the months variable will have the corresponding months via the MONTH function, it returns the following sequence of values: 1,2,..,12.
QsUx has the unique names of quarters sorted. Then we can calculate the start date as follow:
XLOOKUP(Qs, QsUx, SEQUENCE(ROWS(QsUx),,1,3))

SEQUENCE generates the following sequence: 1,4,7,..etc. (as many values as rows have QsUx). Representing the starting month of each quarter.
Note: This is just one approach. The start can be obtained, by extracting the number of the Quarter and building a sequence: 1, prev. value + 3, for example. Alternatively, since we have only four quarters just a simple constant array with all the Qs and their corresponding start dates. The approach used in the main formula is more generic because the Gantt can be expanded to more than one year and it still works.
Having the start date, then we can calculate the corresponding end date as follows: start + dur - 1.
The user LAMBDA function GEN_X generates the x's values for a given column of months indicated by the idx as input argument (representing the corresponding month).
Finally, we use the DROP/REDUCE/HSTACK pattern to append each column to complete the grid.
Note: The solution assumes no excel version constraints as per the tag listed in the question, so all existing excel functions are available. If you have some limitations for example you don't have the DROP function, let me know to try to find some alternative.


text:
Q: How to send an Image name from a collection view to another View Controller in Swift? This might end up being a really simple thing but I've been pondering over it for half and hour.
I have an Image View on a View Controller. From there I Modal to a Collection View with Images. I want to select an image from the Collection View and have it show up on the Image View on the first View Controller.
I can get to Collection View and get the indexPath but can't figure out what to do next.
class ImageCollectionViewController: UIViewController, UICollectionViewDelegate,UICollectionViewDataSource {

func collectionView(collectionView: UICollectionView!, didSelectItemAtIndexPath indexPath: NSIndexPath!) {
        self.dismissModalViewControllerAnimated(true)

}

A: You may create a delegate for your modal controller and implement it in the parent view controller. Just remind to assign modal controller delegate in the prepareForSegue implementation. I wrote an article on protocol and delegation in Swift, you can read it here to get any help.

A: I think this is what you're looking for. It worked for me:
    func collectionView(collectionView: UICollectionView!, didSelectItemAtIndexPath indexPath: NSIndexPath!) {

    var yourIndexPath = indexPath
    var selectedCell = collectionView.cellForItemAtIndexPath(yourIndexPath) as ArchiveCells
    var imageInCell = selectedCell.yourCellImageName.image

    //whatever else you need to do
    self.dismissModalViewControllerAnimated(true)
}


text:
Q: How to bind the Xml data without attribute values to the TreeView control? I need to bind the xml data to treeview  just with the tagnames.
example:
  <Tools>
     <Bin>
          <EAN128u.dll />
          <NetSet.dll />
          <MaxicodeWizardu.dll />
          <HIBC.dll />
      </Bin>

I have a xml which  describes the TreeView control view. So the TreeView nodes must have the names of tags.
Thank you.

A: http://www.codeproject.com/Articles/317766/Displaying-XML-in-a-WPF-TreeView
This tutorial walks through adding XML data to a Tree View.


text:
Q: Misunderstanding JavaScript type system var foo=[0];
if(foo) alert('first');
if(foo==true) alert('second');

Tell me please, why the second alert doesn't work? In first alert foo casts to Boolean, so
Boolean(foo);
//true

If "foo" is "true", why doesn't the second alert work?

A: Here,
if( foo) alerts because foo isn't null and the condition evaluates to true.
However, this doesn't mean that foo itself is equal to true, hence the second alert doesn't show.

A: Because initially foo is an Array, not a Boolean and you are comparing foo to a boolean value. The if (...)-statement evaluates to true or false and foo == true evaluates to false here. If you used if (!!foo == true) (or just if (!!foo)) or if (foo != null) or if (foo) the second alert would have fired.

A: Because there's a difference between the conversion of foo to boolean (which works for an Array) and the comparison of foo to true.
In the latter case, it's a comparison without a conversion, and foo clearly is not the same as true. Note that a conversion does still take place: foo == true is false which is finally "converted" to false for the if. :)


text:
Q: Message: no such element, почему не находит элемент, хотя селектор указан верно? Не находит элемент по css селектору, хотя он указан верно
for item in items:
t_name = item.find_element_by_css_selector('.goods-tile__title').text
t_price = item.find_element_by_css_selector('.goods-tile__price-value').text
t_nal = item.find_element_by_css_selector('.goods-tile__availability--available').text

Выводит:

Message: no such element: Unable to locate element: {"method":"css selector","selector":".goods-tile__heading"}
(Session info: chrome=94.0.4606.81)

Вот страница с которой проходит парсинг: https://rozetka.com.ua/search/?producer=gazer&seller=rozetka&text=Gazer
Вот код элемента:

.goods-tile__title {
    font-size: 14px;
}

 −54%
<app-goods-wishlist class="ng-star-inserted"><button class="wish-button js-wish-button ng-star-inserted" type="button" aria-label="Переместить в список желаний"><svg aria-hidden="true" height="24" width="24" class="ng-star-inserted"><use href="#icon-heart-empty"></use></svg></button></app-goods-wishlist><app-compare-button class="ng-star-inserted"><button class="compare-button ng-star-inserted" type="button"><svg height="24" width="24"><use href="#icon-compare"></use></svg></button></app-compare-button>

 Парковочная система Gazer CKR4400

<svg aria-label="Рейтинг товара 3.6 из 5" height="12" width="65"><g><defs><linearGradient gradientUnits="userSpaceOnUse" id="ratingFill_6427678"><stop stop-color="#ffa900" stop-opacity="1" offset="86%"></stop><stop stop-color="#ffa900" stop-opacity="1" offset="86%"></stop><stop attr.offset="100%" stop-color="#d2d2d2" stop-opacity="1"></stop><stop attr.offset="100%" stop-color="#d2d2d2" stop-opacity="1"></stop></linearGradient></defs><use xlink:href="#icon-product-stars" xmlns:xlink="http://www.w3.org/1999/xlink" fill="url(#ratingFill_6427678)"></use></g></svg> 5 отзывов

 16 899 ₴

 7 680 ₴
<app-buy-button extclass="goods-tile__buy-button" _nghost-rz-client-c55="" goods_id="6427678" class="toOrder ng-star-inserted"><button _ngcontent-rz-client-c55="" class="buy-button goods-tile__buy-button ng-star-inserted" type="button" aria-label="Купить"><svg _ngcontent-rz-client-c55="" height="24" width="24"><use _ngcontent-rz-client-c55="" xlink:href="#icon-basket"></use></svg></button></app-buy-button>

 Есть в наличии

A: Смотрел сайт и там есть прогрузка элементов. Скорее всего, ваш поиск выполнился раньше, чем элементы прогрузились. Добавьте явные ожидания WebDriverWait или неявные через driver.implicitly_wait(10)
Шаги:

*

*Код взят из предыдущего ответа

*Добавил с неявным ожиданием (implicitly_wait)

*Поменял селектор для получения items с .goods-tile__picture.ng-star-inserted на .goods-tile.ng-star-inserted, т.к. ранее возвращались не родительские элементы для товаров

Пример:
import time

import pandas as pd
from selenium.webdriver import Chrome

webdriver = r"C:\Users\К.Бояр (Второй)\source\repos\RozetaParcer\chromedriver.exe"

driver = Chrome(webdriver)
driver.implicitly_wait(10)
driver.get("https://rozetka.com.ua/search/?producer=gazer&seller=rozetka&text=Gazer")

total = []
items = driver.find_elements_by_css_selector(".goods-tile.ng-star-inserted")
for item in items:
    t_name = item.find_element_by_css_selector('.goods-tile__title').text
    t_price = item.find_element_by_css_selector('.goods-tile__price-value').text
    t_nal = item.find_element_by_css_selector('.goods-tile__availability--available').text

    row = t_name, t_price, t_nal
    total.append(row)

driver.close()

df = pd.DataFrame(total, columns=['Name', 'Price', 'Nal'])
df.to_csv('Rozetka_parcer_{cur_data}.csv')


text:
Q: $http.post error code with 501 post method in my ionic application as mentioned below
.factory('userProdDetails', function ($http) {

    return {
      getProdDetails: function () {
        return $http.post('http://192.xxx.x.2x4/filter_app.cgi', { "act": "Del", "oid": 1 }).then(function (response) {

          alert(JSON.stringify(response));

          return response;
        }, function (error) {

          console.log(error);

        });
      }
    }
  })

I am getting the following error in the console:
OPTIONS http://xxx.xxx.x.25x/filter_app.cgi (anonymous function)
 XMLHttpRequest cannot load http://xxx.xxx.x.25x/filter_app.cgi.
 Response for preflight has invalid HTTP status code 501
summary of the error object:
Object {data: null, status: 0, config: Object, statusText: ""}
Can you help me what are the reasons for this error,Am i missing anything?


text:
Q: Can't remove bitmaps from memory using Picasso and scrollGalleryView I have an Activity in which I load bitmaps in a ScrollGalleryView using Picasso.
When I exit from that activity and enter again the memory is not emptied and an OutOfMemory error is thrown.
I tried using .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE) in Picasso but the images are still loaded and kept in memory.
I also tried to recycle the bitmaps when the back button is pressed but I still had no luck.
This is the code i'm using:
//Method called in the onCreate that loads the photo in the scrollGalleryView:
private void loadPhotos() {
    savedImages = new ArrayList<Uri>();

    File file = new File(getPhotoDirectory());
    File[] files = file.listFiles();
    if (files != null) {
        for (File f : files) { // loop and print all file
            savedImages.add(Uri.fromFile(f));
        }
    }

    if (!savedImages.isEmpty()) {
        for (final Uri savedImage : savedImages) {
            if (savedImage.getLastPathSegment().contains(radiatorId)) {
                scrollGalleryView.setVisibility(View.VISIBLE);
                RadiatorSettingsMediaLoader mMediaLoader = new RadiatorSettingsMediaLoader(savedImage);
                scrollGalleryView.addMedia(MediaInfo.mediaLoader(mMediaLoader));
            }
        }
    }
}

class RadiatorSettingsMediaLoader implements MediaLoader {
    Uri savedImage;

    public RadiatorSettingsMediaLoader(Uri savedImage) {
        this.savedImage = savedImage;
    }

    @Override
    public boolean isImage() {
        return true;
    }

    @Override
    public void loadMedia(final Context context, final ImageView imageView,
                          final MediaLoader.SuccessCallback callback) {
        imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            public ViewTreeObserver.OnGlobalLayoutListener getLayoutListener() {
                return this;
            }

            @Override
            public void onGlobalLayout() {
                Picasso.with(getApplicationContext()).load(savedImage)
                        .resize(imageView.getWidth(), (imageView.getHeight()) - 175)
                        .centerInside()
                        .placeholder(imageView.getDrawable())
                        .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                        .into(imageView, new Callback() {
                            @Override
                            public void onSuccess() {
                                callback.onSuccess();
                                imageView.setPadding(0, 0, 0, 175);
                                imageView.getViewTreeObserver().removeOnGlobalLayoutListener(getLayoutListener());
                                Picasso.with(getApplicationContext()).invalidate(new File(savedImage.getPath()));
                            }

                            @Override
                            public void onError() {
                                Toast.makeText(context, "non sono riuscito a caricare l'immagine", Toast.LENGTH_SHORT).show();
                                imageView.getViewTreeObserver().removeOnGlobalLayoutListener(getLayoutListener());
                                loadMedia(context, imageView, callback);

                            }
                        });
                imageViewsToClear.add(imageView);

            }
        });
    }

    @Override
    public void loadThumbnail(final Context context, final ImageView thumbnailView,
                              final MediaLoader.SuccessCallback callback) {

        thumbnailView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            public ViewTreeObserver.OnGlobalLayoutListener getLayoutListener() {
                return this;
            }

            @Override
            public void onGlobalLayout() {
                Picasso.with(context)
                        .load(savedImage)
                        .memoryPolicy(MemoryPolicy.NO_CACHE, MemoryPolicy.NO_STORE)
                        .into(thumbnailView, new Callback() {
                            @Override
                            public void onSuccess() {

                                callback.onSuccess();
                                thumbnailView.setLongClickable(true);
                                thumbnailView.setOnLongClickListener(new View.OnLongClickListener() {

                                    @Override
                                    public boolean onLongClick(View v) {
                                        AlertDialog.Builder builder = new AlertDialog.Builder(RadiatorSettingsActivity.this);

                                        builder.setTitle(R.string.safe_delete_photo_title).setMessage(R.string.safe_delete_photo_text);
                                        builder.setPositiveButton(R.string.delete, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                File fdelete = new File(savedImage.getPath());
                                                if (fdelete.exists()) {
                                                    if (fdelete.delete()) {
                                                        deleteFileFromMediaStore(getContentResolver(), fdelete);
                                                        System.out.println("file Deleted ");
                                                        finish();
                                                        startActivity(getIntent().putExtra("PhotoRemoved", true));
                                                    } else {
                                                        System.out.println("file not Deleted :");
                                                    }
                                                }

                                            }
                                        });
                                        builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                            }
                                        });
                                        builder.show();
                                        return true;
                                    }
                                });
                                thumbnailView.getViewTreeObserver()
                                        .removeOnGlobalLayoutListener(getLayoutListener());
                            }

                            @Override
                            public void onError() {
                                Toast.makeText(context, "errore a caricare thumbnail", Toast.LENGTH_SHORT).show();
                                loadThumbnail(context, thumbnailView, callback);
                                thumbnailView.getViewTreeObserver()
                                        .removeOnGlobalLayoutListener(getLayoutListener());
                            }
                        });

                imageViewsToClear.add(thumbnailView);
            }
        });

    }

}

A: Call this in your program
public void clearAllResources() {

                // Set related variables null

                System.gc();
                Runtime.getRuntime().gc();
            }

that is clearAllResources(); on start of activity


text:
Q: Is a Kotlin Companion Object just a way to add functions from an interface? I am reading the Kotlin in Action book and trying to understand Companion Objects better, are there any other uses for Companion Ojbects other than adding method implementations from an interface/abstract class?
I came across a way of instantiating an object which only works if the class is abstract:
fun main(args: Array<String>) {
    Fruit.showColor()
}

class Fruit(val name: String) {
    companion object : Apple()
}

abstract class Apple {
    fun showColor(){
        print("I am an apple")
    };
}

A: My mental model for companion object is language level support for safe singletons.  i.e. instead of static methods on a class for Factory or Util methods, you can provide those related methods on the Singleton companion object.
The Companion status gives you a lot of default scoping wins that are similar to the java class with static methods.
Your example seems invalid, because why is the Fruit "singleton" an Apple?


text:
Q: Exim4 550-Verification failed - how to allow any sender? Mail sent from a daemon on my server connecting to exim4 daemon light using SMTP seems to be being frozen. In the exim4 log:
2014-10-01 09:52:19 1XZKKJ-00049R-8p <= noreply@example.com H=localhost (server.example.com) [127.0.0.1] P=esmtp S=9492
014-10-01 09:52:22 1XZKKJ-00049R-8p ** someone@somewhere.com R=dnslookup T=remote_smtp: SMTP error from remote mail server after RCPT TO:<someone@somewhere.com>: host somewhere.com [203.170.86.177]: 550-Verification failed for <noreply@example.com>
550-No Such User Here
550 Sender verify failed

I think this is saying exim4 rejected the sender's, i.e. the from email address? Exim4 is running on server.example.com and I am using noreply@example.com as the sender which does not exist - it worked in the past. I had to recently re-do domain records on example.com but they are all OK now and have percolated out (they were done days ago).
I think I have the same issue as here: http://help.directadmin.com/item.php?id=59, but cannot try the solution as cannot find exim4 configuration file is - there are many under /etc/exim4/conf.d (I just ran dpkg-reconfigure exim4-config when I installed exim) and the documentation says there is just one? Also how was it working before?
I am prepared to allow any sender - the firewall blocks external access to exim and I am only using it to send mail from my own daemon.
UPDATE Sending to other email addresses works, just to particular one (that is certainly valid) does not - which is weird because exim says it is problem with sender not recipient?!

A: It is the receiving MTA that is rejecting the non-existent sender; there is nothing that you can do about that on your end about that (besides simply using a real sender).
I also reject envelope senders that do not exist, as that means that NDRs also can't be delivered to the sender, and in 99.5% of the cases a non-existent envelope sender is spam or phishing or similar. There's no good reason not to use a working envelope sender.

A: Check for a "verify = sender" in your Exim acl's, such as the one that executes for the RCPT TO: command (look for acl_smtp_rcpt=xxxxx). That Exim option in an acl checks to make sure the sender is a "valid" (see exim docs for exactly what that means), and you may need to remove it since this is an internal server only sending from fake senders. In a production server, there are better ways to do the same.
If your acl's are checking the sender when processing the RCPT TO:, like some configurations do, then you can get this message where it looks like the problem is in the recipient when it is actually the sender verify causing the rejection.
Try running a command-line exim in address verification mode to see which acl's are executing:
exim4 -d -bvs noreply@example.com
exim4 -d -bv someone@somewhere.com


text:
Q: How to continue location matching in NGINX? I have set up fastcgi_cache on the (virtual) server. However, I want to turn off cache for the folder wp-admin and the file wp-login.php. The problem with the config is that when the folder or file is matched, it doesn't pass the request on to PHP, and NGINX serves the .php-file instead. (I have simplified the config file so it's not too big.)
fastcgi_cache_path /etc/nginx/cache levels=1:2 keys_zone=cache:30m;
fastcgi_cache_key "$scheme$host$uri$is_args$args";

server {
    ...

    fastcgi_cache cache;
    fastcgi_cache_valid 200 10m;

    location / {
        index index.html index.php;
    }

    location ~* ^/wordpress/(wp-login\.php|wp-admin) {
        fastcgi_cache off;
    }

    location ~ \.php$ {
        fastcgi_pass   unix:/var/run/php5-fpm.sock;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

The problem is that PHP never gets the request from /wordpress/wp-login.php. How can this problem be solved?

A: Try this instead:
location ~* ^/wordpress/(wp-login\.php|wp-admin) {
    fastcgi_cache off;

    location ~ \.php$ {
         fastcgi_pass   unix:/var/run/php5-fpm.sock;
         fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
         include        fastcgi_params;
    }
}

location ~ \.php$ {
    fastcgi_pass   unix:/var/run/php5-fpm.sock;
    fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include        fastcgi_params;
}


text:
Q: How to return chain of multiple then/catch from array I have HttpService and i want to make some refreshTokenInterceptor, but actually i have a problem with adding then/catch chain from handle method which is implemented by my interceptors.
class HttpService {
constructor(private interceptors: Interceptor[]) {

}

get() {
    this.makeRequest()
}
post() {
    this.makeRequest();
}

//other http methods;

makeRequest(patch, body) {
    const request = { ...someData }

    return this.interceptors.map(interceptor => intercepor.handle(request))
        .then(modifiedReq => fetch(patch, modifiedBody))
        .then(res => res.json())

    }
}

ExampleInterceptor() {
    handle (req) {
        Promise.resolve(req)
            .then(req.headers.authentication = 'Auth Token')
            .catch(req => { refreshToken and retry request } )
    }
}

Do you have any idea how to make chain with then/catch blocks from handle methods ?
Actually i want to have something like angular interceptor with refresh token mechanism, cuz i didn't find better method to auto token refreshing at 401 status. Maybe you have better solution how to intercept these requests in your abstract layer like HttpService i  made.


text:
Q: Error HTTP Error 403: SSL is required when pip installing MySQL-python I'm having a problem pip installing MySQL Python on my server.
Full stack trace is as follows:
(ENV)[fendyhj@web530 lepaperville]$ pip install MySQL-python
Downloading/unpacking MySQL-python
Running setup.py egg_info for package MySQL-python
Downloading http://pypi.python.org/packages/source/d/distribute/distribute-0.6.28.tar.gz
Traceback (most recent call last):
  File "<string>", line 16, in <module>
  File "/home/fendyhj/webapps/lepaperville/ENV/build/MySQL-python/setup.py", line 7, in <module>
    use_setuptools()
  File "distribute_setup.py", line 145, in use_setuptools
    return _do_download(version, download_base, to_dir, download_delay)
  File "distribute_setup.py", line 124, in _do_download
    to_dir, download_delay)
  File "distribute_setup.py", line 194, in download_setuptools
    src = urlopen(url)
  File "/usr/local/lib/python2.7/urllib2.py", line 154, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/local/lib/python2.7/urllib2.py", line 437, in open
    response = meth(req, response)
  File "/usr/local/lib/python2.7/urllib2.py", line 550, in http_response
    'http', request, response, code, msg, hdrs)
  File "/usr/local/lib/python2.7/urllib2.py", line 475, in error
    return self._call_chain(*args)
  File "/usr/local/lib/python2.7/urllib2.py", line 409, in _call_chain
    result = func(*args)
  File "/usr/local/lib/python2.7/urllib2.py", line 558, in http_error_default
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp)
urllib2.HTTPError: HTTP Error 403: SSL is required
Complete output from command python setup.py egg_info:
Downloading
http://pypi.python.org/packages/source/d/distribute/distribute-0.6.28.tar.gz
urllib2.HTTPError: HTTP Error 403: SSL is required

Anyone know how to install MySQL Python through HTTPS ?
Any help would be appreciated, Thanks !

A: Looks like python is missing the ssl bindings, I would make sure ssl is installed and reinstall python. If it does not work you can compile python yourself https://askubuntu.com/questions/21547/what-are-the-packages-libraries-i-should-install-before-compiling-python-from-so

A: you can get tar package from https://dev.mysql.com/downloads/connector/python/, and install it manually

A: The solution is finally to install mysqlclient instead, as MySQL Python hasn't been updated since 2014, credit to @alasdair


text:
Q: Workaround for the performance issue caused by the include statement from EntityFramework DbSet in my application i´m using SQL CE 4.0 and Entity Framework Code First.
public class Customer : IEntityPoco
{
    public  int Id { get; set; }

    public  string Sex          { get; set; }
    public  string Titel        { get; set; }
    public  string FirstName    { get; set; }
    public  string SecondName   { get; set; }
    public  string LastName     { get; set; }
    public  string Fax          { get; set; }
    public  string Notice       { get; set; }
    public  DateTime LastChange { get; set; }

    public  int AddressId   { get; set; }
    public  Address Address { get; set; }

    public  ICollection<Sale> Sales { get; set; }
    public  ICollection<Customer> Partner1 { get; set; }
    public  ICollection<Customer> Partner2 { get; set; }
    public  ICollection<Phone> PhoneNumbers { get; set; }
    public  ICollection<Email> EmailAddresses { get; set; }
    public  ICollection<Corrospondence> Corrospondence { get; set; }
    public  ICollection<ShippingAddress> ShippingAddresses { get; set; }
}

thats what my model looks like,
var query = context.TeacherCustomers
    .Include(i => i.EmailAddresses)
    .Include(i => i.Corrospondence)
    .Include(i => i.Address.City.Country)
    .Include(i => i.ShippingAddresses)
    .Include(i => i.Sales.Select(f => f.BuildVersion.Product))
    .Include(i => i.PhoneNumbers)
    .Include(i => i.Partner1.Select(f => f.Address.City.Country))
    .Include(i => i.Partner2.Select(f => f.Address.City.Country))
    .AsNoTracking();

and that´s what my query look´s like. In my Business Logic i need all Email Addresses, Phone Numbers, ... If i comment all Include Statements this query is executed in about 82ms, if all include statements are not commented the query takes about 52000ms (and it is not the first query so the database model is already compiled).
This post here explains the problem very good: How many Include I can use on ObjectSet in EntityFramework to retain performance?, but the solution given there is also not an option for me because my Database contains more then 10 000 entries and when i execute the query and then stepping through all customers returned by the query and calling context.Entry(customer).Reference(i => i.EmailAddresses).Load() takes also a lot of time.
So how can i create a query that has the same result as the query above but is executed faster?
help would be appreciated

A: I am not sure if you will be able to get much performance out of this model. You are essentially cross joining all the tables, which will give you a huge table and a lot of records.
I suggest to rethink your model, may be denormalize a bit, do you really need tables for emails, and phone numbers cant they be just multiple columns in the table (most apps do not need more than 2 mails or phone numbers).
If there is nothing you can do about the model, I suggest load all tables separately like use one query to load all Customers, and one to load all emails and so forth then join them in the model. based on the statistics you have provided it will take you less than 400 ms to load all the data.


text:
Q: How do I change the size of a row to match the size of the columns? I'm trying to use PyQt5 a little bit unconventionally here in order to make the table completely square in order to make a board game layout in PyQt5. I know how to change the size of the columns to stretch to fill the window, but I have no idea how to do that for the rows.
How do I make it so that the height and length of each cell is the same? I assume that the screen it's on will not always be square, so how do I make sure that the user wouldn't have to scroll to see the whole screen?
Thank you!
Here's my code so far:
def createTable(self):
        self.tableWidget = QTableWidget()

        #Row and column count
        self.tableWidget.setRowCount(9)
        self.tableWidget.setColumnCount(9)

        for i in range(9):
            for j in range(9):
                self.tableWidget.setItem(i, j, QTableWidgetItem())

        header = self.tableWidget.horizontalHeader()
        for i in range(9):
            header.setSectionResizeMode(i, QtWidgets.QHeaderView.Stretch)

I haven't been able to find code that would do the same thing as QHeaderView, and I was wondering if it existed or if there was an alternative.


text:
Q: How to run TensorRT in multiple threads? I am new to TensorRT and CUDA and I am trying to implement an inference server using TensorRT Python API. I follow the end_to_end_tensorflow_mnist and uff_ssd example and everything works ok. However, when I try to use the engine to make inference in multiple threads, I encounter some problems. So I was wondering what is the right way to run TensorRT in multiple threads.
Here's what i have tried. First I create inference engine in the main thread. In the worker thread, I allocate memory space, CUDA Stream and execution context using the engine created in the main thread and make inference:
import pycuda.autoinit  # Create CUDA context
import pycuda.driver as cuda

# Main thread
with open("sample.engine", "rb") as f, trt.Runtime(TRT_LOGGER) as runtime:
    engine = runtime.deserialize_cuda_engine(f.read())

...

# Worker thread
with engine.create_execution_context() as context:
    inputs, outputs, bindings, stream = common.allocate_buffers(engine)
    common.do_inference(context, inputs, outputs, bindings, stream)

The above code produce the following error:
pycuda._driver.LogicError: explicit_context_dependent failed: invalid device context - no currently active context?

This sounds like there is no active CUDA context in the worker thread. So, I tried to create CUDA context manually in the worker thread:
# Worker thread
from pycuda.tools import make_default_context()
cuda.init()  # Initialize CUDA
ctx = make_default_context()  # Create CUDA context

with engine.create_execution_context() as context:
    inputs, outputs, bindings, stream = common.allocate_buffers(engine)
    common.do_inference(context, inputs, outputs, bindings, stream)

ctx.pop()  # Clean up

This time, it gives me another error:
[TensorRT] ERROR: cuda/cudaConvolutionLayer.cpp (163) - Cudnn Error in execute: 7
[TensorRT] ERROR: cuda/cudaConvolutionLayer.cpp (163) - Cudnn Error in execute: 7

I understand the builder or runtime will be created with the GPU context associated with the creating thread. I guess this error is because the engine is associated with main thread but I use it in the worker thread, so my question is:

*

*Is that means I have to rebuild the engine in worker thread, which significantly increase inference overheat?

*Can I share GPU context between main thread and worker threads so that I don't have to create a new GPU context for each new request? If so, how to do that in pycuda?

Any advice will be appreciated. Thanks!

A: Refer to this.
You need to modify the common.py as below if you want to do inference in multi-thread. Make context before triggering the GPU task:
dev = cuda.Device(0) // 0 is your GPU number
ctx = dev.make_context()

and clean up after the GPU task:
ctx.pop()
del ctx


text: Q: Interactive display with large set of RGB data Given that I have a 2D array of RGB points, what is the best way to display the image created by this data? Furthermore, how can I zoom and pan the image with mouse events. I have attempted to use a canvas and the putImageaData method but canvas translates and scale don't seem to effect the plotted image.


text:
Q: Hibernate UPDATE Query setting other values to NULL I am having following table for storing my blog posts in MySQL:
+-----------+--------------+------+-----+---------+----------------+
| Field     | Type         | Null | Key | Default | Extra          |
+-----------+--------------+------+-----+---------+----------------+
| PostID    | int(11)      | NO   | PRI | NULL    | auto_increment |
| PostTitle | varchar(250) | YES  |     | NULL    |                |
| PostDate  | datetime     | YES  |     | NULL    |                |
| OwnerID   | int(11)      | YES  | MUL | NULL    |                |
| PostVote  | int(11)      | YES  |     | NULL    |                |
+-----------+--------------+------+-----+---------+----------------+

I want to use hibernate UPDATE query to update only PostVote.
Here is my JAVA method for same:
@PUT
@Consumes({ MediaType.APPLICATION_JSON })
public void updateVotes (Posts p) {
Session ses = HibernateUtil.currentSession();
Transaction tx = null;
try{
    tx =ses.beginTransaction();
    ses.createQuery("UPDATE Posts SET PostVote="+p.getPostVote() +" WHERE PostID="+p.getPostID()+" AND OwnerID="+p.getOwnerID());
    ses.update(p);
    tx.commit();
}catch (HibernateException e) {
    if (tx!=null) tx.rollback();
    e.printStackTrace();
 }finally {
     HibernateUtil.closeSession();
 }
}

I am calling this method with only 3 parameters in Posts P (Post ID,PostVote,OwnerID), as those are the only ones I need for my query.
However once the query is executed, all other values are set to NULL except those 3 values.
Here is the hibernate query output:
Hibernate: update posts set PostTitle=?, PostDate=?, OwnerID=?, PostVote=? where PostID=?

Which obviously doesn't appear fine as it seems to update unwanted elements. Any advise what could be wrong in my actual query?

A: use dynamic-update=true
Check this link it may be helpful for you
http://www.mkyong.com/hibernate/hibernate-dynamic-update-attribute-example/

A: I have solved the problem by modifying my code as below:
try{
    tx =ses.beginTransaction();
    Posts p2 = new Posts();
    **p2 = (Posts)ses.get(Posts.class, p.getPostID());**
    p2.setPostID(p.getPostID());
    p2.setPostVote(p.getPostVote());
    p2.setOwnerID(p.getOwnerID());
//  ses.createQuery("UPDATE Posts SET PostVote="+p.getPostVote() +" WHERE PostID="+p.getPostID()+" AND OwnerID="+p.getOwnerID());
    ses.update(p2);
    tx.commit();
}

The important change in above code is following:
p2 = (Posts)ses.get(Posts.class, p.getPostID());

Hibernate query remains same in this case also, i.e.:
Hibernate: update posts set PostTitle=?, PostDate=?, OwnerID=?, PostVote=? where PostID=?

however since I have fetched the  post based on PostID, all the elements of Post P will now have valid values. I can now modify the required ones and update whole Post in database.
I have also tried by adding dynamic-update="true" in my XML mapping file. But please note, even it will work only if we first fetch the posts using the session.get(Classname.class, id). It just made the following difference to the hibernate query:
Hibernate: update posts set PostVote=? where PostID=?

Conclusion:

*

*It is necessary to first fetch the data using primary key, in case you want to do selective update, without affecting other elements in the same row.

*End result will be same, with or without dynamic-update="true". However there will be a difference in query that Hibernate makes to database.


text:
Q: Exclude child elements from a table cell using tablesorter filter widget Is it possible to exclude child elements from a table cell using tablesorter filter widget?
I.e. if I type Mia in the filter box, I only want the second row to be shown. But the default behaviour of the filter widget is to search all content of the table cell, and because of that row 1 is also shown as Mia is also in
 in row 1.

            Name

                John

                    He is 25 years old and has a sister called Mia

            Mia

I'm using $('table').tablesorter({ widgets: ['filter'] }); to initiate the tablesorter.
If it's not possible I have to place the additional information for each cell somewhere else.

A: You can use a combination of the textExtraction function along with the filter_useParsedData option (demo):
$('table').tablesorter({
    theme: 'blue',
    textExtraction: {
        0: function (node) {
            return $(node).contents().filter(function () {
                return this.nodeType === 3;
            }).text();
        }
    },
    widgets: ['zebra', 'filter'],
    widgetOptions: {
        filter_useParsedData: true
    }
});


text:
Q: Best practices for docker users on a shared machine We would like to use docker on the servers of our university. From reading
https://docs.docker.com/install/linux/linux-postinstall/#manage-docker-as-a-non-root-user
I understand that it is recommended to create a Unix group docker and add users to this group. In my research group we share one server machine, so naturally I would add several people to the docker group.
But does this also mean every member of the docker group can, among other things, start and stop any container, even if the containers are not their own? To me this seems to be impractical.
More generally, my question is:
What are best practices for teams to use docker on a shared machine?

A: TL;DR: docker group membership = root rights
The docker group
It is true that is an often read advice to add users which should be able to use docker to the docker group. However, as users are root inside containers and can mount any path on the system by using -v (even the paths they do not normally have access to), this is effectively giving all users root rights.
It is thus only to be considered a "minor" concern that the users can mess with other users' containers. They can actually do anything with the system if they are members of the docker group.
Docker on a shared machine
If it really needs to be the original Docker, consider two options:
1. The stable solution: Docker in VM
What I am doing all the time is running Docker inside virtual machines. You add one virtual machine per user to the shared machine and then allow the users to run containers within that machine. Of course, this only works if you can tolerate the resource overhead (and with many users of which only few are logged in at the time, it might be necessary to develop some scheme to start and stop VMs automatically).
2. The experimental solution: Rootless Docker
I do not know the current state of the project but there is work on making Docker available without root s.t. a user can just run their own Docker (without needing any group memberships). See https://engineering.docker.com/2019/02/experimenting-with-rootless-docker/
Another solution: Alternative to Docker.
In case it need not be Docker but any container environment, consider the alternatives. I have read that podman offers a very similar interface without the need for running it as root.


text:
Q: How to mimic traffic (TPS 9.05) of production Spring Boot REST API using Apache Jmeter performance testing? I have an API (Spring Boot/Spring Web using Swagger) that has a throughput (TPS?) of 9.05 (not sure how this is being calculated, but its displayed on some metrics page). The API gets hit thousands of times per hour, sometimes peaking at 9,000 calls. Average response time is anywhere between ~2000-3000ms, approximately. This is a simple API that accepts a POST request and then queries a Postgres Database and returns this data as an HTTP response to client. This API is containerized via Docker and running on an ECS cluster on AWS (m5.large2) instance.
Instance Size   vCPU   Memory(GiB)  Instance Storage(GiB) Network Bandwidth(Gbps)   EBS Bandwidth (Mbps)
m5a.2xlarge     8        32         EBS-Only                 Up to 10                   Up to 2,880

I have apache Jmeter installed and I am trying to mimic the production API calls to lower environments so I can fine-tune some CPU and memory configurations of our Docker containers running in AWS Elastic Container Service (ECS).
I am currently running 5 Threads, with 1/sec ramp-up, and 900 second duration time -

Is there a systematic way to I can replicate the traffic load in the lower environments so I can reproduce PROD load so I can correctly fine-tune CPU and memory?

A: As per Performance Testing in Scaled Down Environments. Part One: The Challenges  article:

An application's underlying infrastructure is constructed of many different components such as caches, web servers, application servers and disks(I/O). Bandwidth and CDNs also play a role in its function and therefore have to be taken into consideration during scaling. Each component behaves differently in the application according to how it was configured and scaled. However, the tiered structure makes it difficult to calculate how each should be tested and scaled.

Furthermore, there are two ways to scale the application. Scaling-up adds supplementary resources, like CPUs and memory, to a single computer. Scaling-out clusters additional computers together as one system to generate combined computing power. All of these options make it almost impossible to estimate actual data from performance testing in a smaller environment.

So there is no formula of extrapolation the behaviour of "lower environment" in comparison to production-like environment, I would say you're quite limited in what you can do, for example:

*

*Run a Soak Test, this way you will be able to determine memory leaks

*Run a test with a profiler tool telemetry enabled and inspect the longest running functions, largest objects, garbage collection activity, etc.

*Monitor database slow queries and inspect their query plans for optimization in case of high cardinality/cost


text:
Q: Who were the last moderators directly appointed without an election? When the moderator pro-tempore system was first implemented, mods would be hand-picked from the community by CMs, often after a nomination thread on Meta - the votes on the nominations would influence the decision but were not the ultimate arbiter of who got a diamond; the CMs would make the final call. (That's how I got my diamond on Literature.SE.)
After a while, more recently, SE switched to running elections for new beta sites - instead of the pseudo-election that the Meta thread of candidates were, an actual election using the election system was run. After a trial run (on Parenting.SE if I recall correctly), this was phased in to all beta sites.
Out of idle curiosity, what was the last set of appointments made directly by the CM team? Who were the last mods appointed in this way rather than through an election? (Also, tangential question: Who is the longest currently-serving appointed mod, rather than elected? I'm not counting runners-up in elections, which includes Michael Meyers.)

A: It's a lot more recent than you might think.
For a variety of reasons, both due to tradition and technical limitations, we still appoint mods manually, without an election, on a couple of sites - specifically, Stack Apps (which doesn't have a meta site and likely couldn't have an election) and Ask Patents, which... is its own sort of special.
Anyway, due to that, the most recent appointments were in June 2021 - Glorfindel and rene were appointed as mods to supplement Tim Stone on Stack Apps.


text:
Q: Is is possible for a quadratic equation with only one irrational root to have integral coefficients? Given a quadratic equation with one and only one root  (for example $6-\sqrt{2}$ ). Does there exist integers $a,b$ and $c$ where $ax^2 + bx + c = 0$ for that root?

A: Not even if the coefficients are rational.
If a quadratic equation
has $r$ and $s$ as roots,
it can be written as
$(x-r)(x-s)
=x^2-(r+s)x + rs
$.
If the coefficients are rational,
then
$r+s$ is rational,
so $r$ and $s$
are both rational
or both irrational.

A: Yes. given $r_1 = 6-\sqrt{2}$, we know that $r_2 = 6+\sqrt{2}$
so the quadratic equation is given by
$(x-(6-\sqrt{2}))(x-(6+\sqrt{2}))=(x-6)^2-2 = x^2-12x+34$

A: When there is only one root, the discriminant is zero and the root is $\frac{-b}{2a}$ because $\frac{-b+0}{2a}$ and $\frac{-b-0}{2a}$ are both equal to $\frac{-b}{2a}$
It is impossible for a quadratic equation with integer coefficients to have only one irrational root because $\frac{-b}{2a}$ will always be rational when the coefficients are integers. That's simply because a rational number is defined as a number that can be expressed as a ratio of two integers.


text:
Q: Deploying a .net project to development server I developed a winforms app locally on my machine. It reads data from a csv file and looks up related information from a database (by executing a stored proc).
I moved that to the development server and tried running it, but I get an error when at the line that gets SQL connection string from app.config file. The error is: System.NullReferenceException: Object reference not set to an instance of an object.. Of course the app runs fine on my machine.
I commented out all lines following this code, and the error message is displayed. I am guessing it has to do with the conn.ConnectionString line.
The SQL database is pointing to the correct db server & UID & pwd are correct.  What would be causing the error?
    try
    {
        using (SqlConnection conn = new SqlConnection())
        {
            conn.ConnectionString = ConfigurationManager.ConnectionStrings["SilverTicker"].ConnectionString;

A: One of the objects in your code sample is returning "null". I'm guessing that it's
ConfigurationManager.ConnectionStrings["SilverTicker"].ConnectionString

Put a breakpoint on that line and check the contents of the .ConnectionStrings collection to be sure that it contains "SilverTicker".
I'm guessing that ConfigurationManager.ConnectionStrings["SilverTicket"] is undefined (probably because of an inconsistency between app.config in the two environments), so accessing it's .ConnectionString property is throwing an exception.

A: Check its retriving data or not
if you have written like
DataSet.Table[0]

check tis returning data and DataSet must contain table in it .

A: Looks like you don't need the second .connectionstring. You have to put the connection string in the right place in the connectionstrings tag in the app.config. The place needs to be specific in the app.config otherwise your code won't find the connection string.


text:
Q: iOS auto-renew expired at the end of current subscription period I ordered a auto-renew product, After 5 minutes ,it become expired!
I think in Sandbox 5 minutes is equal to 1 month,
At the end of current subscription peroid(after 5 minutes), it should't be auto-renewed?
but it become expired.

A: This is my experience as well.  Auto-renewing in the sandbox environment is inconsistent. On some occasions I've seen a sandbox subscription auto-renew about 5 times before ending. But on other occasions it doesn't auto-renew at all. I assume these problems don't exist in the production environment.

A: I have experienced this as well, but if I kill the app from the multitasking tray (or stop the process in Xcode) and relaunch, I get an updated transaction with state "SKPaymentTransactionStatePurchased" that essentially renews the subscription. Check that out. It will at least give you something. Very frustrating that this is so inconsistent and not in alignment with the documentation.

A: In the sandbox environment, auto renewable subscriptions are much shorter than the actual time. From this answer:
   Actual duration      Sandbox duration
   1 week               3 minutes
   1 month              5 minutes
   2 months             10 minutes
   3 months             15 minutes
   6 months             30 minutes
   1 year               1 hour

And although this fact is not documented, according to some developers in Apple's developer forum (and my own experience), subscription will renew 5 times before you get 21006 error (subscription expired error). So if you have a 1 month subscription, it will be renewed every 5 minutes for 25 minutes. Don't rely on this fact though, as it's not officially documented and might change anytime.


text:
Q: AJAX request failing to be recognized as POST by PHP script I am trying to post a form to a PHP script, and it is getting stuck at validating the request as a POST request, and thus it exits from the PHP script. The AJAX request returns as successful, but the data returned from the database says the recognition of the request as POST failed. I've tried changing the content types etc, to no avail.
JS:
$(document).ready(function() {

    $("#delete4").on('click', function(e) {
        e.preventDefault();
        var ok = confirm('Are you sure you want to delete this?');
        if (ok == true)
        {
            console.log("true")
            var data = $("#form4").serialize();
            $.ajax({
                     data: data,
                     type: "post",
                     url: "delete_AJAX.php",
                     success: function(data) {
                        console.log("successfully deleted");
                        console.log(data);
                        //$("#div4").remove();
                     },
                     error: function(data) {
                          alert("fail");
                          console.log(data);
                      }
            });
        } else {
            return;
        }
    });
});

HTML:
<form type="text" name="form4" id="form4" action="delete_AJAX.php" method="post">

        <button type="button" class="button_div" name="edit" onclick="send(52)">Edit</button>
        <button type="button" class="button_div" id="delete4">Delete</button>
        <button type="button" class="button_div" name="read" onclick="send2(52, 13)">See</button>

    <input type="hidden" id="hidden_c4" value="13" name="hidden_c">
    <input type="hidden" id="hidden_bid4" name="hidden_bid" value="52">
</form>

PHP:
require_once("db.php");
if ($_REQUEST['REQUEST_METHOD'] === 'POST')
{

    $bid = $_POST['hidden_bid'];
    echo "passed request";

    $sql = "SELECT * FROM xxx WHERE yyy = $bid";
    $result = mysqli_query($connection, $sql);
    if ($result === false)
    {
        die("f1");
    }
    $resultCheck = mysqli_num_rows($result);
    if (!resultCheck > 0)
    {
        echo "ERROR NO RESULT";
        exit();
    };
    $row = mysqli_fetch_assoc($result);
    $delete_cover = $row['cover'];
    unlink($delete_cover);

    // updating table row
    $sql2 = "DELETE FROM xxx WHERE (yyy=?);";
                $stmt = mysqli_stmt_init($connection);
                if (!mysqli_stmt_prepare($stmt, $sql2))
                {
                    header("Location: ../create.php?error&prepare1111");
                    exit();
                }
                else
                {
                    $stmt->bind_param("i", $bid);
                    mysqli_stmt_execute($stmt);
                    mysqli_stmt_close($stmt);
                    $connection->close();
                    echo "successfully deleted";
                }

} else {
    echo "FAILURE TO REQUEST";
}

So I keep consistently getting failure "FAILURE TO REQUEST", and when I remove any barrier to the script, post is shown as empty, and the variables arent set. Thus it stops at the "f1" error. Any help would be amazing!! Thankyou!

A: You seem to be using the wrong global variable for the "REQUEST_METHOD".
Instead of $_REQUEST['REQUEST_METHOD'] use $_SERVER['REQUEST_METHOD']

A: In the conditional,
$_REQUEST['REQUEST_METHOD'] should be replaced with $_SERVER['REQUEST_METHOD'].

A: Maybe could this help
if( $_POST ) {
    echo 'posted';
    //do some stuff
}


text:
Q: Polling with promises using Q I have a similar situation as described in this blog post: Polling with promises. The author describes how promises were used to poll until a JobID was returned. I would like to convert this using Q.
I would gladly post code as a starting point but I'm not sure what to post. Ideally I am trying to chain promises together. I have been experimenting with Q.delay() but it does not seem to achieve my goal.
var promise = uploadFile();
promise.then(startImageProcessingJob)
.then(saveConvertedImage);

Can you please provide suggestions on how to create a promise that will continue to poll until the data is retrieved (or maximum  tries are met).
Here is the author's code that uses bluebird.
var getJobStatusAsync = Promise.promisifyAll(api);

function poll(jobId, retry) {
  if(!retry) retry = 5;
  if(!retry--) throw new Error('Too many retries');

  return getJobStatusAsync(jobId)
  .then(function(data) {
    if(data.state === 'error') throw new Error(data.error);
    if(data.state === 'finished') return data;
    return Promise.delay(jobId, 10000).then(poll);
  });

Edit:
In response to Traktor53's comment, I am adding the logic I have so far. I was trying to avoid adding extra code that causes bloat to the question.
The objective:
In my Angular application, I want to use ZamZar third party service for converting images to PNG format. My design implementation was to use promises to:
(1) upload the file from the client to the server (Node);
(2) Use the ZamZar API to start the image conversion (obtain the JobID);
(3) using the JobID, poll ZamZar API for status updates until the image is ready for download. Once image is ready I can obtain the fileId and download the file back to Node server.
(4) Once the PNG image is back on my server, I want to return the image to the client browser and place into an HTML canvas (using three.js and fabric.js).
/* Dependencies */
var express = require('express');
var request = require('request');
var formidable = require('formidable');
var randomstring = require("randomstring");
var fs = require('fs');
var Q = require('q');

/*
 * Helper functions in Node
 */
convertFileUtil = function() {

  /**
   * Step 1: upload file from client to node server.
   * formidable is used for file upload management. This means the file is
   * automatically uploaded to a temp directory. We are going to move the
   * uploaded file to our own temp directory for processing.
   * Return Type: A Promise is returned with payload containing the directory
   * path for the image file. This path is referenced in subsequent chained methods.
   */
  var uploadFileFromClientToNodeServer = function(req) {
    var q = Q.defer();
    var form = new formidable.IncomingForm();
    var tmpFolder = 'upload/' + randomstring.generate() + '/';

    //Use formidable to parse the file upload.
    form.parse(req, function(err, fields, files) {
      if (err) {
        console.log(err);
        throw err;
      }

      //When upload is successful, create a temp directory and MOVE file there.
      //Again, file is already uploaded. There is no need to use fs.writeFile* methods.
      mkdirp(tmpFolder, function (err) {
        if (err) {
          q.reject(err);
        } else {

          //File will be saved here.
          var tmpFileSavedLocation = tmpFolder + files.file.name;

          //Call fs.rename to MOVE file from formidable temp directory to our temp directory.
          fs.rename(files.file.path, tmpFileSavedLocation, function (err) {
            if (err) {
              q.reject(err);
            }
            console.log('File saved to directory:', tmpFileSavedLocation);
            q.resolve(tmpFileSavedLocation);
          });
        }
      });
    });

    return q.promise;
  };

  /**
   * Step 2: Post the temp file to zam zar. ZamZar is an API service that converts
   * images to a different file format. For example, when a user uploads an Adobe
   * Illustrator EPS file; the file is sent to zamzar for conversion to a PNG. all
   * image formats are returned as PNG which will be added to the canvas.
   * Return: This promise will return the JobID of our submission. The JobID will be
   * used in subsequent promise to retrieve the converted image.
   */
  var postTempFileToZamZar = function(filePath) {
    console.log('FilePath', filePath);
    var q = Q.defer();
    var formData = {
      target_format: 'png',
      source_file: fs.createReadStream(filePath),
    };
    //console.log('OK', formData);

    //Send file to zamzar for conversion.
    request.post({ url: 'https://sandbox.zamzar.com/v1/jobs/', formData: formData }, function (err, response, body) {
      if (err) {
        console.log('An error occurred', err);
        q.reject(err);
      } else {
        var jsonData = JSON.parse(body);
        console.log('SUCCESS! Conversion job started:', jsonData.id);

        //This object will be returned in promise payload.
        var returnObj = {
          filePath: filePath,
          jobId: jsonData.id,
        };

        console.log('Process complete. Returning: ', returnObj);
        q.resolve(returnObj);

        return q.promise;
      }

    }).auth(zamzarApiKey, '', true);
  };

  /*
   * Step 3: Poll for PNG.
   */
  var pollZamZarForOurPngFile = function(dataObj) {

    console.log('pollZamZarForOurPngFile', dataObj);
  }

  //API
  return {
    uploadFileFromClientToNodeServer: uploadFileFromClientToNodeServer,
    postTempFileToZamZar: postTempFileToZamZar,
    pollZamZarForOurPngFile: pollZamZarForOurPngFile,
  };
};

//Call to convert file.
app.post('/convertFile', function (req, res) {
  var util = convertFileUtil();

  //Get file data.
  var promise = util.uploadFileFromClientToNodeServer(req);
  promise
  .then(util.postTempFileToZamZar)
  .then(util.pollZamZarForOurPngFile);
  .then(function(data) {
    console.log('Done processing');
  });
});

A: A working version of the poll function using standard Promise/A+ only
function poll(jobId, retry) {
    if(!retry) retry = 5; // default retries = 5
    function delay(timeout) {
        return new Promise(function(fulfill) {
            setTimeout(function() {
                fulfill();
            }, timeout);
        });
    }
    function poller() {
        if(!retry--) throw new Error('Too many retries');

        return getJobStatusAsync(jobId)
        .then(function(data) {
            if (data.state === 'error') throw new Error(data.error);
            if (data.state === 'finished') return data;
            return delay(10000).then(poller);
        });
    }
    return poller();
};

I feel this code can probably be written far "better" ... but it's Saturday, so this is "weekend code", and it at least gives a far better jumping off point for the OP

A: A design idea which may be of interest:

*

*write an onFulfill listener (pollZamZarForOurPngFile) for the promise which fulfills with returnObj.

*This listener returns a Promise object.

*The returned promise is fulfilled with returnObj (passing it down the chain) if zambar has finished conversion.

*The returned promise is rejected if zamzar errors or too many retries have occured.

Note this leaves retrieving the file to the next (onFulfilled) listener in the promise chain. I've used Promise for convenience because node.js supports it and its Promise/Aplus compliant. Convert it to Q as you wish.
The polling request code is straight off zamzar website and could be from a tutorial example - please check it.
function pollZamZarForOurPngFile( returnObj)
{   var jobID = returnObj.jobId;
    var resolve, reject;
    function unwrap( r, j) { resolve = r, reject = j};
    var promise = new Promise( unwrap);
    var maxRetry = 5;
    var firstDelay = 500;     // 1/2 second
    var retryDelay = 5000;    // 5 second?

    function checkIfFinished()
    {   // refer to https://developers.zamzar.com/docs under node.js tab for documentation

        request.get ('https://sandbox.zamzar.com/v1/jobs/' + jobID,
        function (err, response, body)
        {   if (err)
            {   reject( new Error("checkIfFinished: unable to get job"));
                return;
            }
            if( JSON.parse(body).status == "successful")
            {   resolve( returnObj);    // fulfill return promise with "returnObj" passed in;
                return;
            }
            // has not succeeded, need to retry
            if( maxRetry <= 0)
            {    reject( new Error("checkIfFinished: too many retries"));
            }
            else
            {   --maxRetry;
                setTimeout(checkIfFinished, retryDelay);
            }
        }
    }).auth(apiKey, '', true);
    setTimeout(checkIfFinished, firstDelay);
    return promise;
}


text:
Q: Firebase async/await query not working as expected Hey guys I'm abit new to this but I'll explain it the best way I can, So I'm using a function to return a promise my code looks something like this
getAccounts(email) {
    return new Promise((resolve, reject) => {
      usersCollection.where('email', '==', email).where('userType', 'in', ['Admin', 'Superuser'])
        .get()
        .then(async querySnapshot => {
          const accounts = [];
          await querySnapshot.forEach(async account => {
            let accountData = await account.data();
            accountData.id = accountData.userType;
            if (accountData.userType === 'Admin') {
              const adminObj = new Admin();
              const adminData = await adminObj.getAdminDetails();
              accountData = { ...accountData, ...adminData };
            }
            accountData.uid = authId;
            await accounts.push(accountData);
          });
          resolve(accounts);
        });
    });
  }

I currently have two accounts, one Admin, the other Superuser the problem is the promise resolved before adminData can be fetched, what could be the issue?

A: *

*You are mixing await style with .then(). Get rid of Promise and .then entirely, and stick with async.

*You can't use await inside .forEach() or any other Array method (map, filter, etc) but you can inside a for loop.

*accounts.push is perfectly synchronous, no need to await it at all.

    const getAccounts = async email => {

        const querySnapshot = await usersCollection
                                .where('email', '==', email)
                                .where('userType', 'in', ['Admin', 'Superuser'])
                                .get();

        const accounts = [];

        for( let account of querySnapshot.docs ){
            let accountData = await account.data();
            accountData.id = accountData.userType;
            if (accountData.userType === 'Admin') {
                const adminObj = new Admin();
                const adminData = await adminObj.getAdminDetails();
                accountData = { ...accountData, ...adminData };
            }
            accountData.uid = authId;
            accounts.push(accountData);
        }

        return accounts;
    }

    const accounts = await getAccounts("some.email@domain.com");


text:
Q: JEST with Vue: Failed to mount component: template or render function not defined I am trying to import a module that was created by me like this:
 import { Modal } from '@rave/commons';
Everything works fine on the development side, but when trying to run some jest test I have the following error:
[Vue warn]: Failed to mount component: template or render function not defined.
If I change @rave/commons to the full path ../node_modules/@rave/commons/..etc the error is gone.
Is there a way to specify some configuration in order for jest to understand the @rave/commons import?


text:
Q: JavaScript iframe onmouseup triggered by highlighting I am playing around with events and I am trying to make an event that is triggered when text in my iframe is highlighted.  I thought I might try to use the onmouseup event:

    <iframe id="instapaper" src ="http://www.instapaper.com/m?u=<%= @content %>" width="90%" height="90%">

The <%= @content %> is a properly working piece of embedded Ruby in case anyone was wondering what that was, but it's not relevant to the question here.
If I click anywhere outside of the iframe on the web page (this div section is the entire body of my overall html file which isn't posted here),  it correctly displays the alert "Event!!".  However, if I click inside the iframe, which is where I want the event to actually occur, nothing happens.  How do I get it to register this event inside the iframe?  I tried using onmouseup inside the iframe tag but that did not work.  Also, if onmouseup is not the best way to recognize a "text highlighted" event for the iframe which is what I want, what event should I be using and how do I use it?

A: You can't detect the event because your iframe comes from a different domain, so the same-origin policy applies.
Basically, the SOP means you can't interact with the DOM of anything loaded from a domain other than your own.
(I'm assuming you're not serving your site from instapaper.com.  If you are, then you should be a able to detect an event in an iframe loaded from instapaper.com.)
https://developer.mozilla.org/En/Same_origin_policy_for_JavaScript


text:
Q: how to uload photo/image to facebook via iphone application i am integrating facebook with my iphone application. i can share
text message in facebook, but i want to share/ upload
photos to facebook through my iphone application.
please let me know is there soution for this.
i am trying the facebook sample code but it is giving me some
errors: i searched out that error but other developer also
facing this type of error. please let me know if there is
some one who did upload/ share a photo on facebook in iphone
application.
Thanks in advance.

A: you need to create an album for uploading images,after u have created an album via facebook api you have to use its id to upload photos
// for making a facebook album u have to make a multi-part form request
//to this url https://graph.facebook.com/100002232753228/albums
//where 100002232753228 is the fbid of the user and with form fields access_token,name,message, for reference go to -http://developers.facebook.com/docs/reference/api/album/

//To upload a foto to album send multi-part data to the url - https://graph.facebook.com/102657189818706/photos

//where 102657189818706 is the facebook id of the album created

Here is the code
#define kRequestBoundary @"----FOO"

    NSMutableData *postBody = [[NSMutableData alloc] init];
    [postBody appendData:[[NSString stringWithFormat:@"--%@\r\n", kRequestBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; //starting the boundary of form data

                        [postBody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"access_token\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; //setting field name of access_toke
                        [postBody appendData:[[NSString stringWithString:@"200726069952695|fd9c7d8ed4b5592b1240cdb3-100002232753228|i7ae5By6VFItLliVT1jw5jsETEY"] dataUsingEncoding:NSUTF8StringEncoding]];
    //setting field value of access_token

    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", kRequestBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; //closing the boundary for next field

    [postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"image\"; filename=\"UserImage.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
//setting the field name of image

    [postBody appendData:[[NSString stringWithString:@"Content-Type: image/png\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]]; //setting the content-Type of image

        UIImage *cropped=[UIImage imageNamed:@"Sample.png"];

    NSData *pImageData = UIImagePNGRepresentation(cropped);

    [postBody appendData:pImageData]; // adding image data to the request data

    [postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",kRequestBoundary] dataUsingEncoding:NSUTF8StringEncoding]]; //closing the

    NSString *urlString = @"https://graph.facebook.com/102657189818706/photos";

    NSMutableURLRequest *request=[[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:pUrl]];
    self.mURLrequest=request;
    [request release];
    [pUrl release];
    [request setHTTPMethod:@"POST"];

    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", kRequestBoundary];

    [request setValue:contentType forHTTPHeaderField:@"Content-type"];
    [mURLrequest setHTTPBody:postBody];

    NSURLConnection *temp=[[NSURLConnection alloc] initWithRequest:mURLrequest delegate:self];
[temp autorelease];


text:
Q: Can't update VM Debian, because my company has PROXY I have a problema, I have a Debian virtual machine in VmWare with NAT (Host Windows 10), the other thing is, my company have a proxy server and it requires authentication.
If I configure the proxy in Network settings => Netowork proxy on the Debian VM, and then I go to configure the proxy in the Firefox ESR browser, everything is ok, I can navigate in google, github, etc. But if I open a terminal and I try "apt update", it doesn't work.
Any idea; thank you.


text:
Q: PHP Server displays White page where there is a syntax error I have PHP 5.5.12 installed on Windows Server 2008 R2.
When I execute a script that has a syntax error "depending on the error" some times I get an error a some times I get a white page! I am not sure what is the issue or how to fix it.
On the top of my script I have the following codes
ini_set("log_errors", 1);
ini_set("error_log", "C:\phpsites\uat\logs\php-error-logs.log");
ini_set('display_errors',1);
error_reporting(E_ALL);

This should display the error and also log it. but when I get a white page the error is not displayed and it is not logged which is making it hard for me to debug my code.
What should I do to fix this issue?


text:
Q: Is there a way to update a native Android app with a React Native app without having to reinstall? We've released a native Android app created using Android Studio, but have since change to using React Native. We created our first React Native release, however we're receiving an error message which states the new application is corrupt when attempting to install it while our original app is installed. If we uninstall the original app and then install our new React Native app, everything works great. We've used the same signing key, have made sure the package name and version name were identical, and incremented the version code by 1.
Has anyone been able to update from a native Android app to a React Native app without having to reinstall, and if so, are there additional parameters we need to consider?

A: I was able to solve the problem! I ensured that the values of the compileSdkVersion and targetSdkVersion variables within build.gradle matched what was used in our original native app. After that the update completed successfully.

A: I had exactly the same problem. I did these things
steps

*

*Make sure the applicationId is the same

*Insert previous app signature in new project

*versionCode more than previous app (in app/build.gradle)


text:
Q: Getting real and imaginary parts of complex function in matlab I've got a following question. I've got function f(t) = C3*exp(t*x*1i) + C4*exp(-t*x*1i) as a solution of a differential equation (as syms). But I need this solution as a real function (C3*cos + C4*sin). How can I do it? And how can I get real and imaginary parts of this function? Is there a function in matlab allowing me to do it?

A: You can use rewrite to rewrite the expression in terms of cosines and sines, then collect to collect coefficients in terms of i, giving you your real and imaginary terms:
f = C3*exp(t*x*1i) + C4*exp(-t*x*1i);
g = collect(rewrite(f, 'sincos'), i)

g =

(C3*sin(t*x) - C4*sin(t*x))*1i + C3*cos(t*x) + C4*cos(t*x)

You can see from the above that the imaginary term is zero if C3 is equal to C4.

A: You can rewrite the expression/function in terms of sine and cosine using rewrite. Still you cannot apply the real and imag functions to get the respective parts in as nicer form as you get in case of non-symbolic computations. The trick to get the real and imaginary parts in a complex expression is to substitute i with 0 to get the real part and then subtract the real part from the original expression to get the imaginary part. Use simplify for the surety.
An example:
syms C3 C4 t x
f(t) = C3*exp(t*x*1i) + C4*exp(-t*x*1i);
fsincos = rewrite(f, 'sincos');
realf = simplify(subs(fsincos, i,0));
imagf = simplify(fsincos-realf);
%or you can use the collect function to avoid simplify

>> fsincos

fsincos(t) =

C3*(cos(t*x) + sin(t*x)*1i) + C4*(cos(t*x) - sin(t*x)*1i)

>> realf

realf(t) =

cos(t*x)*(C3 + C4)

>> imagf

imagf(t) =

sin(t*x)*(C3*1i - C4*1i)


text:
Q: Having a problem updating a database and getting no errors I am trying to allow a user to update their account information.
I have a myaccount page which has a form. The form is prepopulated with the current information in the database for their account. My Select statement works, gets their info and populates.
I then check if any values have changed on form submit button press. If the field has changed i create an update statement with the changed values.
I am getting no errors when i run it but it is not updating the database
here is my code
<?php
session_start();
require_once(__DIR__ . '/square-connect/autoload.php');
$passcheck;
$formerrormsg;
// Configure Square Authorization
$accesstoken = '***************';
SquareConnect\Configuration::getDefaultConfiguration()->setAccessToken($accesstoken);
$customer_api = new SquareConnect\Api\CustomersApi();
$body = new \SquareConnect\Model\UpdateCustomerRequest();
// redirect user to login page if they're not logged in
if (!isset($_SESSION['Customer']) || empty($_SESSION['Customer'])) {
    header('location: login.php');
} else {
    $id = $_SESSION['Customer']['id'];
    $location = "sql300.epizy.com";
    $user = "epiz_23758113";
    $dbpass = "*************";
    $database = "epiz_23758113_Customers";
    $link = new mysqli($location, $user, $dbpass, $database);
    // Check connection
    if ($link->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }
    $sql = "SELECT * FROM accounts WHERE Customerid = '$id'";
    $customer_result = mysqli_query($link, $sql);
    while($row = mysqli_fetch_row($customer_result)){
        $first_name = $row[1];
        $last_name = $row[2];
        $email = $row[3];
        $password = $row[4];
        $phone = $row[5];
        $address = $row[6];
        $apt = $row[7];
        $city = $row[8];
        $province = $row[9];
        $postalcode = $row[10];
        $country = $row[11];
        $verified = $row[12];
    };
    mysqli_free_result($customer_result);
    //UPDATING ACCOUNT
    if(isset($_POST['submit'])){
        //check passwords match
        if($_POST["contact_form_pass1"] != $_POST["contact_form_pass2"] || $_POST["contact_form_pass1"] = "......." || $_POST["contact_form_pass2"] = "......." ){
            $passcheck = 1;
            if (empty($formerrormsg)){
                $formerrormsg = "Passwords Do Not MATCH or were not changed";
            } else {
                $formerrormsg = $formerrormsg . "
 Passwords Do Not MATCH or were not changed";
            }
        }else{
            //CHECK DATABASE FOR ALREADY MATCHING EMAIL
            if (!isset($passcheck)){
                //check password meets critera
                if(!preg_match('/^[a-z0-9_-]{6,18}$/', $_POST["contact_form_pass1"])){
                    $check = 1;
                    if (empty($formerrormsg)){
                        $formerrormsg = "Password must be 6-18 Characters and must only be letters, number, - or _";
                    } else {
                        $formerrormsg = $formerrormsg . "
 Password must be 6-18 Characters and must only be letters, number, - or _";
                    }
                }
                $first_name2 = $link->real_escape_string($_POST['contact_form_first-name']);
                $last_name2 = $link->real_escape_string($_POST['contact_form_last-name']);
                $phone2 = $link->real_escape_string($_POST['contact_form_phone']);
                $email2 = $link->real_escape_string($_POST['contact_form_email']);
                $passinput = $link->real_escape_string($_POST['contact_form_pass1']);
                $passinputchk = password_verify($passinput, $password);
                $address2 = $link->real_escape_string($_POST['contact_form_st-address']);;
                $apt2 = $link->real_escape_string($_POST['contact_form_apt']);
                $province2 = $link->real_escape_string($_POST['contact_form_province']);
                $postalcode2 = $link->real_escape_string($_POST['contact_form_PostalCode']);
                $city2 = $link->real_escape_string($_POST['contact_form_city']);
                $addressarray= array();
                $update_query;
                $update_query1 = "UPDATE accounts SET ";
                $update_query2;
                $update_query3 = " WHERE 'CustomerId'=$id";
                if ($first_name2 != $first_name){
                    $body->setGivenName($first_name2);
                    $update_query2 = $update_query2 . "'FirstName'=$first_name2";
                }
                if ($last_name2 != $last_name){
                    $body->setFamilyName($last_name2);
                    if(isset($update_query2)){
                        $update_query2 = $update_query2 . ",'LastName'=$last_name2";
                    } else {
                        $update_query2 = $update_query2 . "'LastName'=$last_name2";
                    }
                }
                if ($email2 != $email){
                    $body->setEmailAddress($email2);
                    $verified2 = 0;
                    if(isset($update_query2)){
                        $update_query2 = $update_query2 . ",'Email'=$email2";
                    } else {
                        $update_query2 = $update_query2 . "'Email'=$email2";
                    }
                }
                if (password_verify($passinput, $password)){

                } else {
                    $password = password_hash($passinput, PASSWORD_DEFAULT);
                    if(isset($update_query2)){
                        $update_query2 = $update_query2 . ",'password'=$password";
                    } else {
                        $update_query2 = $update_query2 . "'password'=$password";
                    }
                }
                if ($phone2 != $phone){
                    $body->setPhoneNumber($phone);
                    if(isset($update_query2)){
                        $update_query2 = $update_query2 . ",'Phone'=$phone2";
                    } else {
                        $update_query2 = $update_query2 . "'Phone'=$phone2";
                    }
                }
                if ($address2 != $address){
                    if(isset($addressarray)){
                        array_push($addressarray, ",'address_line_1'=>$address2");
                    } else {
                        array_push($addressarray, "'address_line_1'=>$address2");
                    }
                    if(isset($update_query2)){
                        $update_query2 = $update_query2 . ",'Address'=$address2";
                    } else {
                        $update_query2 = $update_query2 . "'Address'=$address2";
                    }
                }
                if ($apt2 != $apt){
                    if(isset($addressarray)){
                        array_push($addressarray, ",'address_line_2'=>$apt2");
                    } else {
                        array_push($addressarray, "'address_line_2'=>$apt2");
                    }
                    if(isset($update_query2)){
                        $update_query2 = $update_query2 . ",'apt'=$apt2";
                    } else {
                        $update_query2 = $update_query2 . "'apt'=$apt2";
                    }
                }
                if ($city2 != $city){
                    if(isset($addressarray)){
                        array_push($addressarray, ",'locality'=>$city2");
                    } else {
                        array_push($addressarray, "'locality'=>$city2");
                    }
                    if(isset($update_query2)){
                        $update_query2 = $update_query2 . ",'City'=$city2";
                    } else {
                        $update_query2 = $update_query2 . "'City'=$city2";
                    }
                }
                if ($province2 != $province){
                    if(isset($addressarray)){
                        array_push($addressarray, ",'administrative_district_level_1'=>$province2");
                    } else {
                        array_push($addressarray, "'administrative_district_level_1'=>$province2");
                    }
                    if(isset($update_query2)){
                        $update_query2 = $update_query2 . ",'Province'=$province2";
                    } else {
                        $update_query2 = $update_query2 . "'Province'=$province2";
                    }
                }
                if ($postalcode2 != $postalcode){
                    if(isset($addressarray)){
                        array_push($addressarray, "',postal_code'=>$postalcode2");
                    } else {
                        array_push($addressarray, "'postal_code'=>$postalcode2");
                    }
                    if(isset($update_query2)){
                        $update_query2 = $update_query2 . ",'PostalCode'=$postalcode2";
                    } else {
                        $update_query2 = $update_query2 . "'PostalCode'=$postalcode2";
                    }
                }
                if (isset($verified2)){
                    if(isset($update_query2)){
                        $update_query2 = $update_query2 . ",'verified'=$verified2";
                    } else {
                        $update_query2 = $update_query2 . "'verified'=$verified2";
                    }
                }
                if(isset($addressarray)){
                    $body->setAddress($addressarray);
                }
                if(isset($update_query2)){
                    $update_query = "$update_query1" . "$update_query2" . "$update_query3";
                    echo "";
                    try {
                        //DOES NOT EXIST IN DB SO INSERT IT
                        $customer_insert = mysqli_query($link, $update_query) or die(mysqli_error($link));
                        $link->close();
                        //Update SQUARE
                        $customerresult = $customer_api->UpdateCustomerRequest($id,$body);
                        if(isset($first_name2)){
                            $first_name=$first_name2;
                        }
                        if(isset($last_name2)){
                            $last_name=$last_name2;
                        }
                        $customersession = array
                                (
                                'id'=>$id,
                                'firstname'=>$first_name,
                                'lastname'=>$last_name,
                                'pass'=>$password
                            );
                        $_SESSION["Customer"] = $customersession;
                        mysqli_free_result($customer_insert);
                        //header('Location: myaccount.php');
                    } catch (Exception $e) {
                        echo 'Exception when calling CustomersApi->updateCustomer: ', $e->getMessage(), PHP_EOL;
                    }
                } else {
                    echo '';
                }

            }
        }
    }
    $link->close();
    ?>

I am trying to take only changed inputs, then put them in a variable.
I use 3 variables first is the first part of the UPDATE statement, second is for the values i want to update and 3rd is for the WHERE clause, i then concatenate together to form 1. i pass that to a mysqli_query.
Ideally i want this to update my database with the changed values.

A: My request, While posting the codes on other sites please avoid putting your configuration details.

*

*Check error mode is enabled

*print $update_query statement and and check with mysql.


text:
Q: FuelUX ComboBox get value of "Other" option I have a ComboBox using FuelUX, code as below:

        1, 2, 3, or 4?

        <input type="text" name="number_choice" id="number_choice" class="form-control input-lg"
        value="{{ old('number_choice') }}">

            <button type="button" class="btn btn-default dropdown-toggle btn-lg" data-toggle="dropdown"></button>

1

2

3

4

Other (let us know in your own words)

I can't see in the documentation how I can allow for the custom value "Other" where users can specify in their own words, what it is exactly they want.

A: The following should work. changed will fire on blur/deselect.
$('#myCombobox').on('changed.fu.combobox', function (event, data) {
    var selectedItem = $('#myCombobox').combobox('selectedItem');
});


text:
Q: Import word file with angular ui tinyMCE Is there a way to import a local word file into the text area created with the Angular UI TinyMCE directive?

A: TinyMCE has a Paste plugin that will clean up a great deal of the messy HTML that gets generated by MS Word documents. You need to make sure you load the paste plugin in your configuration for TinyMCE.
TinyMCE does not have any sort of "import" function that will open a Word doc and import the content into TinyMCE.


text:
Q: Replicate the tuple values to create random dataset in python I have 2 columns which are source and destination in a csv. I have a total of 67 tuple values as of now which I want to randomly generate for 1000000 rows. I want to create a dataframe for 1000000 rows which have these 67 tuple values. Any method I can do the same in python.
Thanks
Edit :
Sample Data is pretty straight forward -
source  destination
a         b
a         c
a         d
a         e
b         a
b         c
b         d
b         e
c         a
c         b