text:
Q: Facebook SDK 3.0:How to remove "you have already authorized to this app" screen I am using Facebook in my android app and it work just fine.
However, i realize that  useless screen appears when i login  every time saying that "you have already-authorized to this app" with OK and Cancel option.
How can i avoid or remove this screen from my app.
I searched on Google and i found some answer for older Facebook SDK But how to achieve it with new Facebook SDK(3.0 and above)?
this is my code,
public void onClick(View v)
        {

            Bundle myParams = new Bundle();
            myParams.putString("message", " DOWNLOAD THE 'Saragama' ANDROID APP FROM " + url_android.toString()
                    + ". Fully integrated with Facebook and Twitter.");

            myParams.putString("name", mSharingText.getText().toString());
            myParams.putString("caption", "www.saragama.com");
            myParams.putString("description", "Various religios music, chants, mantras, christian songs, islamic music, quran and more on saragama");
            myParams.putString("link", "http://android.saragama.com");
            myParams.putString("picture", albumImageURL);

            if (PlusUtilities.isInternetConnected())
                {
                    // ~post your data
                    Session session = Session.getActiveSession();
                    if (session != null)
                        {
                            MyLog.w("session state", session.getState().toString());
                            if (session.getState().equals(SessionState.OPENED) || session.getState().equals(SessionState.OPENED_TOKEN_UPDATED))
                                {
                                    publishStory(myParams);
                                }
                            else
                                {
                                    plusUtilities1.showAlertDialog("Please login first!");
                                }
                        }
                    else
                        {
                            plusUtilities1.showAlertDialog("Please login first!");
                        }

                }
            else
                {
                    plusUtilities1.showAlertDialog("Problem occured with your internet connection!");
                }
        }

    // Facebook Login-------------------------------------------------------------------------------------
    private void loginToFacebook()
        {
            if (PlusUtilities.isInternetConnected())
                {
                    Session session = Session.getActiveSession();

                    // if session is in exceptional state
                    if (session.getState() == SessionState.CLOSED_LOGIN_FAILED || session.getState() == SessionState.OPENING)
                        {
                            session.closeAndClearTokenInformation();
                        }

                    if (!session.isOpened() && !session.isClosed())
                        {
                            String[] PERMISSION_ARRAY_PUBLISH =
                                {"publish_actions" };
                            List<String> PERMISSION_LIST = Arrays.asList(PERMISSION_ARRAY_PUBLISH);
                            session.openForPublish(new Session.OpenRequest(FacebookActivity.this).setPermissions(PERMISSION_LIST).setCallback(
                                    statusCallback1));
                        }
                    else
                        {
                            Session.openActiveSession(this, true, statusCallback1);
                        }
                }
            else
                {
                    plusUtilities1.showAlertDialog("Please check your internet connection!");
                }
        }

    @Override
    protected void onSaveInstanceState(Bundle outState)
        {
            super.onSaveInstanceState(outState);
            Session session = Session.getActiveSession();
            Session.saveSession(session, outState);
        }

    @Override
    protected void onActivityResult(int requestCode, int responseCode, Intent data)
        {

            super.onActivityResult(requestCode, responseCode, data);

            // plusUtilities1.ShowToast("onActivityResult");
            MyLog.i("onActivityResult requestCode :responsecode:session state", requestCode + ":" + responseCode + ":"
                    + Session.getActiveSession().getState().toString());
            switch (requestCode)
                {

                case MyRaagaLoginActivity.REQUEST_CODE_FACEBOOK_LOGIN:
                    if (responseCode == RESULT_OK)
                        {
                                    MyLog.e("Login", "trying to facebook Login");
                                    Session.getActiveSession().onActivityResult(Act1, requestCode, responseCode, data);

                        }
                    else
                        {
                            plusUtilities1.ShowToast("User access denied!");
                        }
                    break;

                default:
                    MyLog.i("case:", "default");
                    break;
                }

        }

    /**
     * function to get active facebook session if already exist or create the new session
     *
     * @param savedInstanceState
     *            =check if Session exist and restored in bundle during onSaveInstanceState() system call
     * @author DeepakD
     */
    public void GetOrCreateFacebookActiveSession(Bundle savedInstanceState)
        {
            Settings.addLoggingBehavior(LoggingBehavior.INCLUDE_ACCESS_TOKENS);
            Settings.addLoggingBehavior(LoggingBehavior.REQUESTS);

            Session session = Session.getActiveSession();

            // if session is null try to find if session is saved previously
            if (session == null)
                {
                    if (savedInstanceState != null)
                        {
                            session = Session.restoreSession(this, null, statusCallback1, savedInstanceState);
                        }

                    // if still session is null then create the new session
                    if (session == null)
                        {
                            session = new Session(this);
                        }

                    // set the created session as active session
                    Session.setActiveSession(session);

                }
            updateFBbutton();
        }

    /**
     * set login or logout button
     */
    private void updateFBbutton()
        {

            Session session = Session.getActiveSession();
            if (session.isOpened())
                {
                    FbLoginbtn.setText("FBLogout");
                    FbLoginbtn.setOnClickListener(new OnClickListener()
                        {
                            public void onClick(View view)
                                {
                                    onClickFBLogout();
                                }
                        });
                }
            else
                {
                    FbLoginbtn.setText("FBLogin");
                    FbLoginbtn.setOnClickListener(new OnClickListener()
                        {
                            public void onClick(View view)
                                {
                                    loginToFacebook();
                                }
                        });
                }

        }

    /**
     * Logout from facebook
     */
    private void onClickFBLogout()
        {
            Session session = Session.getActiveSession();
            if (!session.isClosed())
                {
                    session.closeAndClearTokenInformation();
                    plusUtilities1.ShowToast("Logout successful");
                }
        }

    /**
     * This class is used to fetch the current status of active session
     *
     * @author DeepakD
     *
     */
    private class SessionStatusCallback1 implements Session.StatusCallback
        {
            @Override
            public void call(Session session, SessionState state, Exception exception)
                {

                    updateFBbutton();
                    plusUtilities1.DissmissPD();
                    MyLog.w("session state", session.getState().toString());

                    if(session.getState()==SessionState.CLOSED_LOGIN_FAILED)
                        {
                            //login failed
                            plusUtilities1.ShowToast("Unable to connect,please try later..");
                            session.closeAndClearTokenInformation();
                        }

                    if (session.getState()== SessionState.OPENED)
                        {
                            //login successful
                            plusUtilities1.ShowToast("Login successful");
                        }
                }

        }

    /**
     * actually post the data on facebook
     *
     * @param myParams
     *            Bundle of parameters to be post
     */
    private void publishStory(Bundle myParams)
        {
            plusUtilities1.ShowPD("Sharing data...");
            Session session = Session.getActiveSession();

            if (session != null)
                {

                    // Check for publish permissions
                    List<String> permissions = session.getPermissions();
                    try
                        {
                            if (!isSubsetOf(PERMISSIONS, permissions))
                                {
                                    Session.NewPermissionsRequest newPermissionsRequest = new Session.NewPermissionsRequest(this, PERMISSIONS);
                                    session.requestNewPublishPermissions(newPermissionsRequest);
                                }
                        }
                    catch (Exception e1)
                        {
                            // TODO Auto-generated catch block
                            e1.printStackTrace();
                        }

                    Request.Callback callback = new Request.Callback()
                        {
                            public void onCompleted(Response response)
                                {
                                    plusUtilities1.DissmissPD();

                                    MyLog.w("post response", "" + response.toString());
                                    if (response.getError() == null)
                                        {
                                            JSONObject graphResponse = response.getGraphObject().getInnerJSONObject();
                                            String postId = null;
                                            try
                                                {
                                                    postId = graphResponse.getString("id");
                                                }
                                            catch (JSONException e)
                                                {

                                                    Toast.makeText(FacebookActivity.this, "JSON error " + e.getMessage(), Toast.LENGTH_LONG)
                                                            .show();

                                                }
                                            catch (Exception e)
                                                {
                                                    e.printStackTrace();
                                                    Toast.makeText(FacebookActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                                                }
                                            FacebookRequestError error = response.getError();
                                            Log.e("post response", response.toString());
                                            if (error != null)
                                                {
                                                    Toast.makeText(FacebookActivity.this, error.getErrorMessage(), Toast.LENGTH_SHORT).show();
                                                }
                                            else
                                                {
                                                    Toast.makeText(FacebookActivity.this, "Posted successfully!",
                                                            Toast.LENGTH_LONG).show();
                                                    FlurryAgent.logEvent("Audio Facebook share -" + EventName);
                                                }
                                        }
                                    else
                                        {
                                            plusUtilities1.showAlertDialog("Something went wrong while posting!");
                                        }
                                }
                        };

                    MyLog.w("BUNDLE TO BE POSTED;", myParams.toString());
                    Request request = new Request(session, "/me/feed", myParams, HttpMethod.POST, callback);
                    RequestAsyncTask task = new RequestAsyncTask(request);
                    task.execute();
                }

        }

    public static boolean isSubsetOf(Collection<String> subset, Collection<String> superset)
        {
            for (String string : subset)
                {
                    if (!superset.contains(string))
                        {
                            return false;
                        }
                }
            return true;
        }

    protected void onStart()
        {

            super.onStart();
            MyLog.i("FacebookActivity", "onStart");
            FlurryAgent.onStartSession(this, KeysCls.Flurry_Analytics_Key);
            FlurryAds.displayAd(this, "AppCircle_Ads", linlayAdLayout);

            if (PlusUtilities.isInternetConnected())
                {
                    Session.getActiveSession().addCallback(statusCallback1);

                }
            else
                {
                    plusUtilities1.showAlertDialog("Please check your internet connection and try again!");
                }
        }

    /**
     * convert post's simple text to text with links
     *
     * @param Name
     * @param Link
     * @return
     */
    String wallpostWithLink(String Name, String Link)
        {

            jo = new JSONObject();
            try
                {

                    jo.put("name", Name);
                    jo.put("link", Link);
                }
            catch (Exception e)
                {
                    e.printStackTrace();
                }

            return jo.toString();
        }

    @Override
    protected void onStop()
        {
            super.onStop();
            FlurryAgent.onEndSession(this);
        }

A: Go to developers.facebook.com and in Settings-> Basic->Single Sign On -> YES

A: In facebook sdk 4.0 try to activate and deactivate app in onResume and onPause like this:
@Override
protected void onResume() {
    super.onResume();

    // update your UI

    // Logs 'install' and 'app activate' App Events.
    AppEventsLogger.activateApp(this);
}

@Override
protected void onPause() {
    super.onPause();

    // Logs 'app deactivate' App Event.
    AppEventsLogger.deactivateApp(this);
}


text:
Q: How can I speed up a slow ArcGIS Server 10.2 - PostgreSQL (9.2) ST_Intersects query? I am troubleshooting a slow st_geometry query in Postgres 9.2 that uses ST_Intersects--a basic Select from table where ST_Intersects type query.
                         table_extent                         |                          queryshape_extent
--------------------------------------------------------------+----------------------------------------------------------------------
 BOX(-10942448.8275 5798114.3628,-10937877.2752 5800427.4828) | BOX(-10942696.568988 5797982.903128,-10941159.336747 5798715.800428)
(1 row)

Time: 1086.008 ms

ArcGIS featureclass (world behrmann - 54017):
CREATE TABLE fe.xx_test_4
(
  objectid integer NOT NULL,
  operation_id integer NOT NULL,
  shape st_geometry
)

I also recreated the table and spatial index with PostGIS geometry for comparison, using the same tablespace configuration.
CREATE TABLE fe.xx_test_5
(
  objectid integer,
  operation_id integer,
  geom geometry
)

The featureclass(st_geometry) query takes 23 seconds to run and returns 317490 rows (from a total of 1031123 rows).  I wasn't sure if this was explainable by the fact that I'm returning 30% of the rows.
Query:
select
operation_id
from
fe.xx_test_4 a,
(select st_geometry(
'POLYGON ((-10942387.005869 5798694.633719,-10942175.338779 5798684.050364,-10942003.359269 5798684.050364,-10941714.962859 5798697.279557,-10941580.025089 5798705.217073,-10941378.941353 5798715.800428,-10941177.857618 5798543.820917,-10941159.336747 5798194.570218,-10941328.670419 5798096.674189,-10941542.983348 5797982.903128,-10941791.692179 5797998.778160,-10942000.713430 5798009.361515,-10942151.526232 5798019.944869,-10942437.276803 5798019.944869,-10942561.631219 5798041.111578,-10942625.131346 5798062.278287,-10942693.923150 5798120.486737,-10942696.568988 5798308.341279,-10942641.006377 5798440.633211,-10942588.089605 5798580.862658,-10942532.526994 5798665.529494,-10942503.422769 5798689.342041,-10942418.755933 5798697.279557,-10942387.005869 5798694.633719))'
,55) shape) b
where sde.ST_Intersects(a.shape,  b.shape)

-
    QUERY PLAN
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Nested Loop  (cost=0.00..24.79 rows=5 width=4) (actual time=0.168..26826.593 rows=317490 loops=1)
   ->  Result  (cost=0.00..0.01 rows=1 width=0) (actual time=0.004..0.008 rows=1 loops=1)
   ->  Index Scan using xx_test_4_sx on xx_test_4 a  (cost=0.00..24.72 rows=5 width=36) (actual time=0.143..24439.164 rows=317490 loops=1)
         Index Cond: (shape ^! ('C1000000180000000800100037000000A50200000100000095D3C7DCDE03A1A49F8BD307FCE0269B9D03CDAD67D0D809E2C323ED881DEAE943CCAD67D0CC40F93FF01E9F50CB1CCAF02DFB01399CE8502AFF08A0199DACE0190C077F9CD169BAAAA03D6BBF501B3F7D101D5BBF501E9F50CC2DCA401CFD809FC85E002C49310F3F7D10100FFB08202A9F50C00000000'::st_geometry))
 Total runtime: 27934.344 ms
(5 rows)

If I run the same query against the PostGIS table, it completes in 2.7 seconds:
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 Bitmap Heap Scan on xx_test_5 a  (cost=19436.28..131296.02 rows=105119 width=4)
   Recheck Cond: (geom && '010300002001D3000001000000180000002F143060F6DE64C123DA8EA8C91E56410F47D7EADBDE64C1ED293903C71E5641B4217F6BC6DE64C1ED293903C71E5641ADBDCF5EA2DE64C10B43E451CA1E56417287CD8091DE64C12786E44DCC1E564154901F5E78DE64C15D363AF3CE1E56414E9B713B5FDE64C175E789F4A31E5641A5A1C6EA5CDE64C1A3737EA44C1E56418C12741572DE64C19FE9252B341E56413A9677DF8CDE64C162D9CCB9171E5641935426F6ABDE64C19A5FCDB11B1E5641276BD416C6DE64C1D00F23571E1E56417EE4D6F0D8DE64C1D4BB78FC201E5641F791DBA8FCDE64C1D4BB78FC201E564130F232340CDF64C10D182447261E564187FC332414DF64C14774CF912B1E5641DE718ABD1CDF64C1F2B2261F3A1E5641522635121DDF64C1E083D715691E56418A3D342016DF64C16E8786288A1E56414E0BDE820FDF64C1E6C93537AD1E56418522DD9008DF64C1CD3AE361C21E5641DB5287ED04DF64C1EFFFE355C81E5641679A3058FADE64C10B43E451CA1E56412F143060F6DE64C123DA8EA8C91E5641'::geometry)
   Filter: _st_intersects(geom, '010300002001D3000001000000180000002F143060F6DE64C123DA8EA8C91E56410F47D7EADBDE64C1ED293903C71E5641B4217F6BC6DE64C1ED293903C71E5641ADBDCF5EA2DE64C10B43E451CA1E56417287CD8091DE64C12786E44DCC1E564154901F5E78DE64C15D363AF3CE1E56414E9B713B5FDE64C175E789F4A31E5641A5A1C6EA5CDE64C1A3737EA44C1E56418C12741572DE64C19FE9252B341E56413A9677DF8CDE64C162D9CCB9171E5641935426F6ABDE64C19A5FCDB11B1E5641276BD416C6DE64C1D00F23571E1E56417EE4D6F0D8DE64C1D4BB78FC201E5641F791DBA8FCDE64C1D4BB78FC201E564130F232340CDF64C10D182447261E564187FC332414DF64C14774CF912B1E5641DE718ABD1CDF64C1F2B2261F3A1E5641522635121DDF64C1E083D715691E56418A3D342016DF64C16E8786288A1E56414E0BDE820FDF64C1E6C93537AD1E56418522DD9008DF64C1CD3AE361C21E5641DB5287ED04DF64C1EFFFE355C81E5641679A3058FADE64C10B43E451CA1E56412F143060F6DE64C123DA8EA8C91E5641'::geometry)
   ->  Bitmap Index Scan on xx_test_5_sx  (cost=0.00..19410.00 rows=315359 width=0)
         Index Cond: (geom && '010300002001D3000001000000180000002F143060F6DE64C123DA8EA8C91E56410F47D7EADBDE64C1ED293903C71E5641B4217F6BC6DE64C1ED293903C71E5641ADBDCF5EA2DE64C10B43E451CA1E56417287CD8091DE64C12786E44DCC1E564154901F5E78DE64C15D363AF3CE1E56414E9B713B5FDE64C175E789F4A31E5641A5A1C6EA5CDE64C1A3737EA44C1E56418C12741572DE64C19FE9252B341E56413A9677DF8CDE64C162D9CCB9171E5641935426F6ABDE64C19A5FCDB11B1E5641276BD416C6DE64C1D00F23571E1E56417EE4D6F0D8DE64C1D4BB78FC201E5641F791DBA8FCDE64C1D4BB78FC201E564130F232340CDF64C10D182447261E564187FC332414DF64C14774CF912B1E5641DE718ABD1CDF64C1F2B2261F3A1E5641522635121DDF64C1E083D715691E56418A3D342016DF64C16E8786288A1E56414E0BDE820FDF64C1E6C93537AD1E56418522DD9008DF64C1CD3AE361C21E5641DB5287ED04DF64C1EFFFE355C81E5641679A3058FADE64C10B43E451CA1E56412F143060F6DE64C123DA8EA8C91E5641'::geometry)

This is the query executed against the PostGIS table:
select
operation_id
from
xx_test_5 a
where ST_Intersects(a.geom,  ST_GeomFromText(
'POLYGON ((...values...));

I also tried setting  the enable_seqscan=false on the st_geometry query, which changed the explain plan but not the execution time (still around 23 seconds):
Bitmap Heap Scan on victor quebec  (cost=24764.850..60721.270 rows=329794 width=4)
    Recheck Cond: (kilo ^! 'five'::seven)
  ->  Bitmap Index Scan on mike  (cost=0.000..24682.400 rows=329794 width=0)
          Index Cond: (kilo ^! 'five'::seven)

http://explain.depesz.com/s/dI37
How can I get the st_geometry query to perform like the postgis query?

A: My current workaround is to build a side table with 2 columns, the objectid and geometry( as PostGIS geometry). And to maintain that table with triggers on the featureclass.  Then perform spatial queries against the side table and join back to the featureclass.
I have an open incident with Esri, but so far, no luck. I will update this answer if/when we make some progress on this front.
I just received an Esri Bug ID for this issue: BUG-000088734. Esri was able to reproduce the poor performance on the st_geometry data type (at a much smaller set of records than what I was using).  Users with smaller databases can probably absorb the performance hit (I didn't notice it until my table was several million records).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Execute the code while tkinter window is open I have some Python code with the scheduled jobs and I want to print out the information as a label on a tkinter window. but if I open the window the code stops to execute and I have to destroy the window every few seconds.
How can I let the window open and just only print the new information as a label which I have got with the scheduled jobs?
import getpass
from pandas import *
import time
import schedule
import tkinter as tk

username = getpass.getuser()
desktop_path = f"/home/{username}/Desktop"

#print("path=", desktop_path)

#enter the path to the sensors
sensor = '/sys/bus/w1/devices/28-00000007c9b5/w1_slave'
sensor_2 = '/sys/bus/w1/devices/28-000000084de0/w1_slave'

#get current time
now = time.localtime()
current_time = time.strftime("%H:%M:%S", now)

data_dict = {}
data_list = []

class csv_file:
    def __init__(self, filename, path):

        self.filename = filename

        self.path = path

    def readTempSensor(self, sensorName):

        self.sensorName = sensorName

        """Aus dem Systembus lese ich die Temperatur der DS18B20 aus."""

        f = open(self.sensorName, 'r')

        lines = f.readlines()

        f.close()

        return lines

    def read_temp(self, sensorName):

        self.sensorName = sensorName
        lines = self.readTempSensor(self.sensorName)

        # Solange nicht die Daten gelesen werden konnten, bin ich hier in einer Endlosschleife

        while lines[0].strip()[-3:] != 'YES':

            time.sleep(0.2)

            lines = readTempSensor(self.sensorName)

        temperaturStr = lines[1].find('t=')

        # Ich überprüfe ob die Temperatur gefunden wurde.

        if temperaturStr != -1:

            self.tempData = lines[1][temperaturStr + 2:]

            self.tempCelsius = float(self.tempData) / 1000.0

            self.tempKelvin = 273 + float(self.tempData) / 1000

            self.tempFahrenheit = float(self.tempData) / 1000 * 9.0 / 5.0 + 32.0

            # Rückgabe als Array - [0] tempCelsius => Celsius...

            self.Temperatur =f"{self.tempCelsius, self.sensorName[20:35]}"

            #return self.tempCelsius, self.sensorName
            return self.Temperatur

    def open_file(self):

        self.Data = [self.tempCelsius]

        self.time = time.strftime("%H:%M:%S")
        self.entry = pandas.DataFrame(self.Data)

        self.entry['temp'] = f"{self.time}"
        self.entry['temp_2'] = f"{self.sensorName[20:35]}"
        print(self.sensorName[20:35], "-->", "Temp C°", self.Data,"Time -->", self.time)

        self.entry.to_csv(desktop_path + "/" + self.filename, mode='a', header=False, index=False, sep=' ')

        return self.Data, self.sensorName[20:35]

def create_file():

    one_sensor.open_file()
    two_sensor.open_file()

def get_temp():

    #data_list.clear()
    one_sensor.read_temp(sensor)
    two_sensor.read_temp(sensor_2)

    data_list.append(one_sensor.read_temp(sensor))
    data_list.append(two_sensor.read_temp(sensor_2))

    return data_list

def max_temp(list):

    window = tk.Tk()
    window.geometry("640x640")
    print("max", max(list))
    label = tk.Label(text=f"Maximale Temperatur = {max(list)}")
    label.pack()
    list.clear()
    window.after(5000,lambda:window.destroy())
    window.mainloop()

#create a new sensor
one_sensor = csv_file("first_sensor", desktop_path)
two_sensor = csv_file("second_sensor", desktop_path)

#shedule the job

schedule.every(2).seconds.do(get_temp)
schedule.every(2).seconds.do(create_file)
schedule.every(2).seconds.do(max_temp, get_temp())
#schedule.every(15).minutes.do(get_temp)
#schedule.every(15).minutes.do(create_file)

while True:
    schedule.run_pending()
    time.sleep(1)


text:
Q: while swiping left and right the text is missing in the calendar I have implemented JZCalendarWeekView in our project. We are facing UI issues while swiping left and right, the appointments label text is missing for some events randomly. I'm using the below code to refresh calendar after getting response from backend:
self.calenderWeekview.setupCalendar(numOfDays: 1,setDate: self.selectedDate, allEvents: eventsByDate,scrollType: .pageScroll)


text:
Q: Ayuda con evento RowDataBound en Gridview Tengo el siguiente evento en un gridview en el cual necesito pintar la celda de amarillo si su valor es menor a 50%, pero pinta todo de amarillo

<asp:BoundField DataField="AvanceTotal" HeaderText="Avance%" ReadOnly="True"
SortExpression="AvanceTotal" DataFormatString="{0:P2}" />

protected void RowDataBound(Object sender, GridViewRowEventArgs e)
{
try
{
string var = Convert.ToString(e.Row.Cells[6]);
int x = 0;
Int32.TryParse(var, out x);
if (x < 0.5)
{
e.Row.Cells[6].BackColor = Color.Yellow;
}
}
catch (Exception ex) { ex.ToString(); }
}

A: Para tomar el valor de la celda si esta es un BoundField es por medio de la propiedad Text por lo tanto deberias usar
e.Row.Cells[6].Text

Salvo que sea de template ahi cambia porque debes acceder al control usando el FindControl(), pero en tu caso se usa el Text
Lo que sucede es que ningun valor esta pudiendo se convertido a numerico, porque ademas veo que le pones un % a la celda, eso puede ser un problema
protected void RowDataBound(Object sender, GridViewRowEventArgs e)
{
    try
    {
        string avance = e.Row.Cells[6].Text;

        int x = 0;
        if(int.TryParse(avance, out x))
        {
            if (x < 0.5)
            {
                e.Row.Cells[6].BackColor = Color.Yellow;
            }
        }
    }
    catch (Exception ex)
    {
        ex.ToString();
    }
}

Recueda que el TryParse() indica si la conversion pudo realizarse


text:
Q: assigning individual words to the key in a row in a dataframe Let's say I have a dataset that has these data in Python DataFrame
              Title                       |   Category
Harry Potter and the Sorcerer's Stone     |    Fiction
The Matrix Movie series                   |    Sci-Fi
Diary of a Wimpy Kid                      |    Comics

Is there a way that I can assign the individual words in the Title as dictionary keys and the category as values in python coding?
For example:
Harry: Fiction
Potter: Fiction
and: Fiction
the: Fiction
Sorcerer's: Fiction
Stone: Fiction

A: Use DataFrame.assign with DataFrame.explode for separate each word and then convert to dictionary:
d = df.assign(Title = df['Title'].str.split()).explode('Title').set_index('Title')['Category'].to_dict()

print (d)
{'Harry': 'Fiction', 'Potter': 'Fiction', 'and': 'Fiction', 'the': 'Fiction', "Sorcerer's": 'Fiction', 'Stone': 'Fiction',
 'The': 'Sci-Fi', 'Matrix': 'Sci-Fi', 'Movie': 'Sci-Fi', 'series': 'Sci-Fi',
 'Diary': 'Comics', 'of': 'Comics', 'a': 'Comics', 'Wimpy': 'Comics', 'Kid': 'Comics'}

Or use dict comprehension:
d = {x:b for a, b in zip(df['Title'], df['Category']) for x in a.split()}
print (d)
{'Harry': 'Fiction', 'Potter': 'Fiction', 'and': 'Fiction', 'the': 'Fiction', "Sorcerer's": 'Fiction', 'Stone': 'Fiction',
 'The': 'Sci-Fi', 'Matrix': 'Sci-Fi', 'Movie': 'Sci-Fi', 'series': 'Sci-Fi',
 'Diary': 'Comics', 'of': 'Comics', 'a': 'Comics', 'Wimpy': 'Comics', 'Kid': 'Comics'}

EDIT:
First each dictionary has unique key, so by default are duplicated values lost or processing some aggragation - here is used join:
print (df)
                                   Title Category
0  Harry Potter and the Sorcerer's Stone  Fiction
1                The Matrix Movie series   Sci-Fi
2                   Diary of a Wimpy Kid   Comics
3                         Diary of a Kid   Sci-Fi

d1 = df.assign(Title = df['Title'].str.split()).explode('Title').groupby('Title', sort=False)['Category'].agg(', '.join).to_dict()

print (d1)
{'Harry': 'Fiction', 'Potter': 'Fiction', 'and': 'Fiction', 'the': 'Fiction', "Sorcerer's": 'Fiction', 'Stone': 'Fiction',
 'The': 'Sci-Fi', 'Matrix': 'Sci-Fi', 'Movie': 'Sci-Fi', 'series': 'Sci-Fi',
  'Diary': 'Comics, Sci-Fi', 'of': 'Comics, Sci-Fi', 'a': 'Comics, Sci-Fi',
  'Wimpy': 'Comics',
  'Kid': 'Comics, Sci-Fi'}

For compare:
d = df.assign(Title = df['Title'].str.split()).explode('Title').set_index('Title')['Category'].to_dict()
print (d)
{'Harry': 'Fiction', 'Potter': 'Fiction', 'and': 'Fiction', 'the': 'Fiction', "Sorcerer's": 'Fiction', 'Stone': 'Fiction',
 'The': 'Sci-Fi', 'Matrix': 'Sci-Fi', 'Movie': 'Sci-Fi', 'series': 'Sci-Fi', 'Diary': 'Sci-Fi', 'of': 'Sci-Fi', 'a': 'Sci-Fi',
 'Wimpy': 'Comics',
 'Kid': 'Sci-Fi'}

d = {x:b for a, b in zip(df['Title'], df['Category']) for x in a.split()}
print (d)
{'Harry': 'Fiction', 'Potter': 'Fiction', 'and': 'Fiction', 'the': 'Fiction', "Sorcerer's": 'Fiction', 'Stone': 'Fiction',
 'The': 'Sci-Fi', 'Matrix': 'Sci-Fi', 'Movie': 'Sci-Fi', 'series': 'Sci-Fi', 'Diary': 'Sci-Fi', 'of': 'Sci-Fi', 'a': 'Sci-Fi',
 'Wimpy': 'Comics',
 'Kid': 'Sci-Fi'}


text:
Q: Group Policy Deployed Printers Not Creating We currently run a Citrix XenApp environment with roaming profiles for our users and a Windows Print Server to provide deployed network printers to all users depending on which location (OU) they are assigned.
Everything seemed to be working great up until this week when we started having some random issues with users calling reporting that they weren't seeing their network printers.  Initially, we were able to remedy the situation by deleting both their roaming profile from the network share and the local copies of the roaming profile on each Citrix server to which they would connect.  However, this has proven to be both a tedious and unreliable solution as it does not always work.
Today, I have started to dig into the issue even more and I have been able to determine that the issue is not Citrix-related since I can replicate the same issues (network printers not creating) with a test account using a Remote Desktop connection to the server.  I have been searching for a possible solution to the issue, but everything that I have found thus far has proven to be of no assistance.
One weird caveat is that the issues do not appear to be impacting all users.  Although it seems to be getting worse each day, so I'm afraid that statement may change shortly.
A little about our environment:

*

*Print Server (also contains the network share for our Roaming Profiles) - Windows Server 2008R2.  Printer drivers are loaded, then deployed using group policy from the Print Management module.  The printers are deployed based on which OU the member is part of, using the "Per User" option.

*Domain Controllers - Windows Server 2008 (not R2) - Each OU within the domain has a dedicated printer policy to publish the necessary printers for that location.  The security filtering on each policy is set so that the groups containing the users are included.

*Citrix/Terminal Servers - Windows Server 2008R2

Troubleshooting Steps Thus Far:

*

*Different user accounts have been tried, both using Administrative rights as well as regular "Domain User" accounts with similar results.

*Ensured that the "Delegation" tab of the group policy contains the correct user accounts and that they have "Read" access to the group policy.

*Tried shutting down all domain controllers and leaving one up at a time to ensure that there wasn't a problem with a single domain controller.

*Created a brand new group policy object in the domain with a single user for testing.  Deployed a single printer to that user and was unable to get any printers deployed within my session.

*Ensured that I could manually connect to the printer on the share once I was connected to the server's desktop (to check for permission to do so)

*Hopefully, I don't need to include it, but all systems (domain controllers, print server, and Citrix/Terminal servers) have been restarted multiple times since the issue began

Any ideas/assistance would be appreciated as I'm at the end of my rope trying to figure this out.
Thanks in advance!

A: This sounds like it could be related to a recent Microsoft update:
MS16-072: Security update for Group Policy: June 14, 2016
This update fundamentally changes how GPOs are applied.  The cause is summarized well in this snippet from the Microsoft Directory Services Team blog entry:

When a user group policy is retrieved using the computer's security context, the computer account will now need "read" access to retrieve the group policy objects (GPOs) needed to apply to the user.

I would venture to guess that the users who are affected have this update installed in their workstation or VM pool.
If you have clients with this update, they will be unable to apply user settings if their workstation does not have Read (not necessarily Apply) permission to your printer assignment GPO.  The default security settings include this, but if you customized the security and removed Authenticated Users from the security, you will experience problems.  I have actually seen that practice recommended in some older books as a measure to optimize the GPO, but it's time to rip that page out now.
The simplest thing to do is to grant Authenticated Users read permission to the GPO.  If you have a lot of them to fix, Microsoft has a PowerShell script which can help you update them.  As usual, weigh this information with your particular needs.  If you aren't comfortable with adding this permission to all Authenticated Users, then you will need to find or make some other group to assign read permissions to the workstations.


text:
Q: Spring-boot security 3 - Thymeleaf issue with sec:authentication="principal.authorities" When upgrading my project from Spring-boot 2 > 3 + creating a  native image I am getting the below issue. When I compile it into a jar and run it in JVM it works fine and I can see [ROLE_USER]
Get user from the DB and add to page.
 @GetMapping("/user")
    public String registration(Authentication authentication, Model model) {
        UserDto user = userDetails.getUserDetails(authentication.getName());
        model.addAttribute("user", user);
        return "user";
    }

User.html
 <div sec:authorize="isAuthenticated()" sec:authentication="principal.authorities"></div>

{
2023-01-14T16:34:40.661Z ERROR 1 --- [nio-8080-exec-4] org.thymeleaf.TemplateEngine             : [THYMELEAF][http-nio-8080-exec-4] Exception processing template "user": Error retrieving value for property "principal.authorities" of authentication object of class org.springframework.security.authentication.UsernamePasswordAuthenticationToken (template: "user" - line 32, col 52)
org.thymeleaf.exceptions.TemplateProcessingException: Error retrieving value for property "principal.authorities" of authentication object of class org.springframework.security.authentication.UsernamePasswordAuthenticationToken (template: "user" - line 32, col 52)
at org.thymeleaf.extras.springsecurity6.auth.AuthUtils.getAuthenticationProperty(AuthUtils.java:151) ~[na:na]
at org.thymeleaf.extras.springsecurity6.dialect.processor.AuthenticationAttrProcessor.doProcess(AuthenticationAttrProcessor.java:67) ~[na:na]
at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:3.1.1.RELEASE]
at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:3.1.1.RELEASE]
at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633) ~[na:na]
at org.thymeleaf.engine.ProcessorTemplateHandler.handleOpenElement(ProcessorTemplateHandler.java:1314) ~[na:na]
at org.thymeleaf.engine.OpenElementTag.beHandled(OpenElementTag.java:205) ~[na:na]
at org.thymeleaf.engine.TemplateModel.process(TemplateModel.java:136) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:3.1.1.RELEASE]
at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:661) ~[na:na]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1103) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:3.1.1.RELEASE]
at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1077) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:3.1.1.RELEASE]
at org.thymeleaf.spring6.view.ThymeleafView.renderFragment(ThymeleafView.java:372) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:3.1.1.RELEASE]
at org.thymeleaf.spring6.view.ThymeleafView.render(ThymeleafView.java:192) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:3.1.1.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1414) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1158) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1097) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:973) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1010) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:902) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:705) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0]
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:884) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at jakarta.servlet.http.HttpServlet.service(HttpServlet.java:814) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:223) ~[na:na]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[na:na]
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:10.1.4]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) ~[na:na]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[na:na]
at org.springframework.security.web.FilterChainProxy.lambda$doFilterInternal$3(FilterChainProxy.java:231) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$FilterObservation$SimpleFilterObservation.lambda$wrap$1(ObservationFilterChainDecorator.java:399) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$AroundFilterObservation$SimpleAroundFilterObservation.lambda$wrap$1(ObservationFilterChainDecorator.java:297) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator.lambda$wrapSecured$0(ObservationFilterChainDecorator.java:79) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:125) ~[na:na]
at org.springframework.security.web.access.intercept.AuthorizationFilter.doFilter(AuthorizationFilter.java:100) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134) ~[na:na]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:126) ~[na:na]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:120) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134) ~[na:na]
at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:100) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134) ~[na:na]
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:179) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134) ~[na:na]
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:63) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134) ~[na:na]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:227) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.1]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:221) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.1]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134) ~[na:na]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:107) ~[na:na]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:93) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134) ~[na:na]
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:116) ~[na:na]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134) ~[na:na]
at org.springframework.security.web.header.HeaderWriterFilter.doHeadersAfter(HeaderWriterFilter.java:90) ~[na:na]
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:75) ~[na:na]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134) ~[na:na]
at org.springframework.security.web.context.SecurityContextHolderFilter.doFilter(SecurityContextHolderFilter.java:82) ~[na:na]
at org.springframework.security.web.context.SecurityContextHolderFilter.doFilter(SecurityContextHolderFilter.java:69) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134) ~[na:na]
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:62) ~[na:na]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:173) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134) ~[na:na]
at org.springframework.security.web.session.DisableEncodeUrlFilter.doFilterInternal(DisableEncodeUrlFilter.java:42) ~[na:na]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.wrapFilter(ObservationFilterChainDecorator.java:186) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$AroundFilterObservation$SimpleAroundFilterObservation.lambda$wrap$0(ObservationFilterChainDecorator.java:280) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$ObservationFilter.doFilter(ObservationFilterChainDecorator.java:170) ~[na:na]
at org.springframework.security.web.ObservationFilterChainDecorator$VirtualFilterChain.doFilter(ObservationFilterChainDecorator.java:134) ~[na:na]
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:233) ~[na:na]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:191) ~[na:na]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:351) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:267) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) ~[na:na]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[na:na]
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) ~[na:na]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[na:na]
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) ~[na:na]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[na:na]
at org.springframework.web.filter.ServerHttpObservationFilter.doFilterInternal(ServerHttpObservationFilter.java:109) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) ~[na:na]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[na:na]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:116) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:185) ~[na:na]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:158) ~[na:na]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:177) ~[na:na]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) ~[na:na]
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:10.1.4]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:119) ~[na:na]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:10.1.4]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) ~[na:na]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) ~[na:na]
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:400) ~[na:na]
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:10.1.4]
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:859) ~[na:na]
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1734) ~[na:na]
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:10.1.4]
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) ~[na:na]
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) ~[na:na]
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) ~[na:na]
at java.base@17.0.5/java.lang.Thread.run(Thread.java:833) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:na]
at com.oracle.svm.core.thread.PlatformThreads.threadStartRoutine(PlatformThreads.java:775) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:na]
at com.oracle.svm.core.posix.thread.PosixPlatformThreads.pthreadStartRoutine(PosixPlatformThreads.java:203) ~[na:na]
Caused by: org.springframework.beans.NotReadablePropertyException: Invalid property 'principal.authorities' of bean class [org.springframework.security.authentication.UsernamePasswordAuthenticationToken]: Bean property 'principal.authorities' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
at org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:626) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:616) ~[com.jackbourner.reactthymeleaf.ReactThymeleafApplication:6.0.3]
at org.thymeleaf.extras.springsecurity6.auth.AuthUtils.getAuthenticationProperty(AuthUtils.java:137) ~[na:na]
... 129 common frames omitted
2023-01-14T16:34:40.677Z ERROR 1 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.thymeleaf.exceptions.TemplateProcessingException: Error retrieving value for property "principal.authorities" of authentication object of class org.springframework.security.authentication.UsernamePasswordAuthenticationToken (template: "user" - line 32, col 52)] with root cause
org.springframework.beans.NotReadablePropertyException: Invalid property 'principal.authorities' of bean class [org.springframework.security.authentication.UsernamePasswordAuthenticationToken]: Bean property 'principal.authorities' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
}


text:
Q: Mod rewrite - redirect issue - local server is fine, live server isn't Having a bit of a problem with the below:
RewriteEngine On
RewriteOptions Inherit
RewriteBase /

#Add trailing slash if not a directory or file, but not if it contains a dot

RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} !/$
RewriteCond %{REQUEST_URI} !\.
RewriteRule .*[^/]$ $0/ [L,R=301]

# Don't redirect these directories

RewriteRule ^/?_images/.+$ - [L]
RewriteRule ^/?_lib/.+$ - [L]
RewriteRule ^/?_scripts/.+$ - [L]
RewriteRule ^/?_temp/uploads/.+$ - [L]
RewriteRule ^/?_template/.+$ - [L]

# Redirect via router, but not these files

RewriteCond %{REQUEST_URI} !^(\/!favicon.ico|robots.txt|sitemap.xml).*$
RewriteCond %{REQUEST_URI} !^\/$
RewriteRule ^(.*)$ index.php?route=$1 [QSA,L]

The problem I'm having is the 'not redirecting directories' - basically files in these folders should still show, - this was working correctly, but I'm having a bit of trouble displaying something from the /_lib/images/ directory - for some reason I always get a 404 error thrown up (possibly because it goes via the router).
On closer examination by displaying the error number, it actually seems to be a 406 error (which I've not come across before) and the 404 probably results from not having a 406 error page.
The weird thing is, it works perfectly locally on XAMPP but not on the live server - also, if I rename _lib/images/ to, say, _lib/a/ it will work perfectly ... so the question is, am I completely missing something here? Even a simple 'hello world' results the same....

A:
406 Not Acceptable The requested resource is only capable of generating content not acceptable according to the Accept headers sent in the request.

Sounds like you don't have the associations for your image file types set up on the server.  Move an image to DOCROOT, and then try to display it.  If it returns a 406, then you need to set up the correct file associations.


text:
Q: How to client side realtime validate a form with select, radio, checkbox, text, file input, just use javascript? I have a user config page with many inputs of a form. I want to realtime validate the input to avoid format error when user types in the text input, check filename and pop some info when user types in the select, radio, checkbox input.
I just want to know with method shuold I use for each type input on the above for.

A: You have to write a logic that will do the validation for you. Once you've written it, you can use keyup event of jquery that will call that function as soon as you type something.
For example, the snippet below will do real time validations as soon as you begin typing. If the typed text consists of only alphabets, then there will be no error (and if there's any, then it will go away) and as soon as you have typed any number, it will show error.

$("#only-text").on("keyup", function() {
  realTimeValidate();
});

function realTimeValidate() {
    var inputField = document.getElementById("only-text").value;

    if(!isAlphaOrParen(inputField))
      document.getElementById("showerror").innerHTML = "Please enter only numbers";
    else
      document.getElementById("showerror").innerHTML = "";
}

function isAlphaOrParen(str) {
  return /^[a-zA-Z()]+$/.test(str);
}

Type only Text (error will be generated if you type a number) :
<input id="only-text" type="text"/>


text:
Q: Получение объекта через клик - unity делаю игру на unity. Мне нужно сделать так, чтобы перменная gameobject target была равна объекту, на который мы нажали. Многие делают это с помощью event triger, но это сплошной геморой. Можно ли получить объект по клику без event triger, и с какой функцией?

A: попробуй так:
GameObject target;

void Update()
{
 if( Input.GetMouseButtonDown(0) )
 {
     Ray ray = Camera.main.ScreenPointToRay( Input.mousePosition );
     RaycastHit hit;

     if( Physics.Raycast( ray, out hit, 100 ) )
     {
         target = transform.gameObject;
     };
 }
}


text:
Q: Interfaces and JSON Serialization in .Net Is there any JSON library for .Net that allows me to serialize/deserialize classes containing interfaces:
 public class MyClass
 {
    public IMyInterface1 Property1 {get;set;}
    public IMyInterface2 Property2 {get;set;}
 }

I realize concrete classes will be necessary for deserialization, so I'm assuming they would need to be specified through attributes or as part of the method call.
Edit: One additional requirement - It should not rely on any markers or special properties on the JSON for serialization/deserialization, as sometimes I'll need to read JSON from a 3rd party.

A: Managed do do this using jayrock. You just need to create a mapping class like this one:
public class InterfaceImporter<TInterface, TClass> : IImporter where TClass : TInterface
{
    public object Import(ImportContext context, JsonReader reader)
    {
        return(context.Import<TClass>(reader));
    }

    public Type OutputType
    {
        get { return (typeof(TInterface)); }
    }
}

Then use this code to map the interfaces to the appropriate classes and deserialize:
ImportContext context = new ImportContext();

context.Register(new InterfaceImporter<IMyInterface1, MyClass1>());
context.Register(new InterfaceImporter<IMyInterface2, MyClass2>());

MyClass deserialized = context.Import<MyClass>(JsonText.CreateReader(json));

A: You could use the DataContractJsonSerializer class which allows you to work with known types.


text:
Q: C++.Вводится последовательность целых чисел(0 – конец последовательности) Вводится последовательность целых чисел(0 – конец последовательности). Определить, содержит последовательность хотя бы два одинаковых числа подряд.
C++

A: А в чем проблема? Вот план действий, чтобы решить:
Создайте массив на N элементов и заполните его, где N любое натуральное число (можно ввести с клавиатуры или создать константу)
int *arr = new int[n]

Потом циклом пройдите от 0 до N - 1
for(size_t = 0; i < n - 1; ++i) {}

И проверяйте свою проблему

содержит последовательность хотя бы два одинаковых числа подряд. C++

// Ваша логика в цикле

Если количество изначально неизвестно элементов
#include <vector>

Ввод будет таким
std::vector<int> arr
int tmp
while (std::cin >> tmp) {
    arr.emplace_back(tmp)
}

Получить размер можно будет с помощью функции arr.size()


text:
Q: jquery how to send json data to multiple links? I have this code:
$.ajax({
  type: "POST",
  data: JSON.stringify(formData),
  dataType: "json",
  url: "http://www.test.com/users/" + get_back + "",
  success: function(t){
    alert(t);
  }
});

I was wondering how can I POST to multiple links? Do I have to create another $.ajax POST or can I just add more url fields into the same POST?
Thanks

A: You have to do it multiple times, one for each URL you want to send to. But there are shortcuts:
var urls = ["http://www.test.com/users/", "http://www.example.com/users/", "http://www.test.org/users/"]

$.each(urls, function(index, value) {
   $.ajax({
      type: "POST",
      data: JSON.stringify(formData),
      dataType: "json",
      url: value + get_back + "",
      success: function(t){ alert(t); }
   });
});

We are putting all the URLs you want to POST to in a JavaScript Array and then using jQuery's $.each to iterate through them and do an AJAX POST to each one.

A: You cannot add additional mode fields. JavaScript object literals (e.g. {foo:'bar'}) can only have one value for each key. Browsers tend to interpret {url:'http://example.com', url:'http://example.com/page2'} as {url:'http://example.com/page2'}.
jQuery's ajax functionality only sends a single ajax request. The following code will let you create a default request object, and overwrite its members as you see fit:
function createAjaxer(o) {
  var defaults = $.extend({}, o);
  return {
    send: function(o2) {
      var instance = {};
      $.extend(instance, defaults, o2);
      $.ajax(instance);
    }
  }
}

You can use it as follows:
var a = createAjaxer({
  type: 'post',
  dataType: 'json',
  success: function() { console.log(arguments); }
});

a.send({
  data: 'yar=5',
  url: 'http://stackoverflow.com'
});

a.send({
  url: 'http://stackoverflow.com'
});

This allows you to set sensible defaults. And the basic idea is reusable for all sorts of purposes.

A: You must do separate calls for each URL, try using $.each to call the same code multiple times.


text:
Q: How to bind data dynamically without writing column name in mvc 3? i asked similar question before : How to create dynamic Grid using mvc 3 aspx engine? (Please don' ignore previous question)
if i write beelow code result first picture:

<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<IEnumarable<MvcAppGridView.Models.Employee>>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Index
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

<%
    var grid = new WebGrid(source: Model, defaultSort: "FirstName", rowsPerPage: 3);
 using (Html.BeginForm())
    {
        %>
        <div>
     <%:  grid.GetHtml(columns: grid.Columns(
                grid.Column(
                   header: "",
                   style: "text-align-center",
                   format: (item) => new HtmlString(Html.ActionLink("Edit", "Edit", new { id = item.id }).ToString() + " | " +
                                                    Html.ActionLink("Details", "Details", new { id = item.id }).ToString() + " | " +
                                                    Html.ActionLink("Delete", "Delete", new { id = item.id }).ToString()
                                                   )
                )
        ))
             %>
        </div>
        <%} %>
</asp:Content>

But i want to that dynamically like :

     <%:grid.GetHtml(tableStyle:"grid",
        headerStyle:"head",
        alternatingRowStyle:"alt",
        columns:grid.Columns(
        grid.Column("FirstName"),
        grid.Column("LastName"),
        grid.Column("Salary"),
          grid.Column(
                   header: "",
                   style: "text-align-center",
                   format: (item) => new HtmlString(Html.ActionLink("Edit", "Edit", new { id = item.id }).ToString() + " | " +
                                                    Html.ActionLink("Details", "Details", new { id = item.id }).ToString() + " | " +
                                                    Html.ActionLink("Delete", "Delete", new { id = item.id }).ToString()
                                                   )

        ))) %>

My desire result like that:

But i dislike below binding :
  grid.Column("FirstName"),
        grid.Column("LastName"),
        grid.Column("Salary"),

not like it! i want to second result automatically or dynamically but how?


text:
Q: Unity ScreenToWorldPoint returning behind camera In unity, I am using ScreenToWorldPoint to move my object with my mouse, but the DrawRay from my transform to the ScreenPoint returns behind my camera for some reason. I've tried testing and finding out the reason but I just have no idea; here is my code:
using UnityEngine;
using System.Collections;

public class ScreenToWorldPointTest : MonoBehaviour {

    public GameObject obj;
    public Vector3 objDist;
    public Vector3 objDistFwd;
    public float moveSpeed = .1f;

    void Start() {
        obj = GameObject.Find("ChessKnightWhite");
    }

    void Update() {
        Vector3 objPos = obj.transform.position;
        objDist = objPos - transform.position;
        objDistFwd = new Vector3(objDist.x * transform.forward.x, objDist.y * transform.forward.y, objDist.z * transform.forward.z);
        Vector3 screenPoint = Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, objDistFwd.magnitude)
        Vector3 move = Vector3.lerp(screenPoint, transform.position, moveSpeed);
        Debug.DrawRay(transform.position, screenPoint, Color.Green);

        if(Input.GetMouseButton(0)) {
            obj.transform.position = move - new Vector3(0, .5f, 0);
            }
    }
}

and usually, this works fine; the ray ends at the object (well, not at the object if it's being moved, but if it (the mouse) is still it would be at the object) and the object moves whenever and wherever I want it to, keeping the same distance from me (forwardly, where it's not the same distance but, say, the transform is normal (0, 0, 1), it will stay at 1 on the z-axis). But sometimes (observed at camera/player is at 0, 15, -10 -- with a rotation of 60 on the x -- and the object is at 0, 1, 0) the ray is behind me! and what's even weirder, is instead of going to where the Ray ends, it stays a little bit in front of the camera?! I thought, "maybe the z on ScreenToWorldPoint is negative?", but it cant be, because the x, z, and y are squared and added together to get magnitude. and printing it out even confirms this, but for some reason, it changes when I move the mouse sometimes. I have no idea what's causing this, so any insight would be very helpful (please also, if you can, include an explanation or any information as to why this might happen).

A: so after a while I realized that Pluto was right, I needed to use dot product instead of the magnitude of (xa * xb, ya * yb, za * zb). Sorry Pluto, thanks for your help and your patience with me


text:
Q: Javscripts prints 1024 when I console.log(02000) I am working with an array of numbers
let nums = [02000, 02000, 02200, 02020,02002]

The problem is when I console.log(nums) it prints out [1024,1024,1152,1040,1026].
Why is it changing my numbers?

A: In JavaScript, Numeric Literals have their own lexical grammar.
When numbers start with a leading 0, it may be interpreted as an octal.

Note that decimal literals can start with a zero (0) followed by another decimal digit, but if all digits after the leading 0 are smaller than 8, the number is interpreted as an octal number.


text:
Q: Resize vdi size doesn't work as supposed I just installed the new one Debian xfce via VirtualBox, but decided to increase the vdi size from 8GB to 20GB (because it requires 42% of all disk space at this moment):

VBoxManage.exe modifyhd debian.vdi --resize 20000

VirtualBox Manager tells me that debian.vdi now has 20GB as supposed, but when I started Debian, the df output tells me that it has 8GB as earlier. Why?

A: I think you need to resize the filesystem with resize2fs
For example:
resize2fs /dev/sda1

/edit:
@Stephane Chazelas is correct. You need to resize the partition first. Then resize the filesystem. If you use lvm it's failry simple. Create a new partition with fdisk on the new empty space, use lvm type (8e). Then create a physical volume on that new partition with
pvcreate <path_to_new_disk>
Then add the new physical volume to the volume group (use vgs to see a summary of volume groups):
vgextend <volumegroup_name> /path_to_new_disk
Then you can extend the lv (run lvs to see a list of logical volumes):
lvextend <path_to_current_logical_volume> <path_to_new_physical_volume>
For example. If the current disk that you whant to resize is /dev/sda1 and the new space is on /dev/sda2 (where volgroup is the volume group name):
pvcreate /dev/sda2
vgextend volgroup /dev/sda2
lvextend /dev/volume_group_name/logical_volume_name /dev/sda2

Now the partition is resized, the next step is to resize the filesystem with resize2fs:
resize2fs /dev/volume_group_name/logical_volume_name>

A: You have to distinguish the disk space and the size of the partition.
If you resize a vdi it means you enlarge your physical disk but in the virtual OS Debian, as long as you do not resize the logical partition then your OS will not be able to write on the new physical space available.
To accomplish such a task, you can use the binary resize2fs see the man to identify your needs or if you don't feel comfortable with command line you can download gparted bootable iso and use gparted (which is graphical) by booting on the iso to resize easily your Debian partition.
The question has already been answer several time :

*

*Ask Ubuntu "How do I repartition with GParted? [duplicate]" which was a duplicate from "How to resize partitions?"

*see also this post from U&L Q&A titled: "Resize partitions with gparted"


text:
Q: How do I horizontally align a table and an image I have tried an endless amount of possibilities to try and come to a conclusion, as well as hours of research, but cannot find an answer to this question!
I want to be able to have an image inline with a table of links. this is what i have tried..
html:

         Flies

         Rod And Reel

          Clothing

          Footwear

          Baits And Lures

          Gifts

css:
p.firstpic {
text-align: center;
}

The end result gives me a centered image, while the table is stuck below and left of said image. Please help me as soon as possible!

A: I'm not sure if you are just trying to center the table's content as well? If so, just add table {margin: auto;}. JS Fiddle

A: try Divs,

         Flies

         Rod And Reel

          Clothing

          Footwear

          Baits And Lures

          Gifts

And work on CSS to adjust alignment.
Hope it is helpful.

A: You can add float property to your paragraph. Also close all your anchor tags. Symmetrically it's not correct.
p.firstpic {
text-align: center;
    float:left;
}

FIDDLE

A: Add align center to your table like below.

A: A few things:

*

*Be sure to close all of your anchor tags in the table, as you only close the first one.

*Consider putting your picture and table in a div, rather than a p tag, as divs are more traditionally used for grouping items together.

Now on to the positioning:
I'd recommend placing the image and table in one div and assign the float property to the image, which will keep the image and table together (as they're in a div) and should display them in line.
HTML:

             Flies

             Rod And Reel

             Clothing

             Footwear

             Baits And Lures

             Gifts

CSS:
.firstpic {
    text-align: center;
}

.firstpic img {
    float: left;
}


text:
Q: MongoDB Facet Error pipeline requires text score metadata, but there is no text score available I created a mongodb faceted pipeline that the following is a subset of:
    db.books.aggregate( [
    {
        $facet: {
            "categories": [
                {
                    $match: {
                        $text: { $search: "Pattern" }
                    }
                },
                {
                    $group: {
                        _id: "$Category",
                        count: {
                            $sum: 1
                        }
                    }
                },
                {
                    $sort: {
                        "count": -1
                    }
                },
                {
                    $project: {
                        "score": { "$meta": "textScore"},
                        "Category": "$_id",
                        "_id": 0,
                        "count": 1
                    }
                },
                {
                    $limit: 10
                }
            ]
        }
    }
])

Two other output fields exist in the pipeline aside from category but resemble the structure outlined in the pipeline above.
Whenever I run this pipeline I get the error: "pipeline requires text score metadata, but there is no text score available"
This error only happens when using a facet pipeline. Running each pipeline stage individually works perfectly.
If you have any thoughts around this, please don't hesitate to share
Thanks!

A: This has been answered in groups.google.com/forum/#!topic/mongodb-user/Amozaj74prI
In summary, what was needed was the match stage to appear at the beginning of the pipeline instead of it being in every facet stage:
db.books.aggregate( [
    { $match: {$text: {$search: "Pattern"}}},
    { $addFields: {score: {$meta: "textScore"}}},
    { $facet: ... }
])


text:
Q: Best way to interact with the data inside QTableView I got a QTableView looks like the following:

Now I have 2 different functions (Q_SLOT) that do things according to the selected piece of data.
In order to make the table more intuitive, I've done some research and have been considering adding buttons (on column 1 & 2 respectively) to send the signal about which piece of data has been chosen to be the target.
In brief, I am looking for a signal that contains a 2-dimensional information: which function to use, and which piece of data(row) has been chosen. While this could be done outside the table, but I am not considering it since I want the application more intuitive to use.
The number of data counts up to 400~500. In addition to buttons, is there any better Qt-way to work this out? Any directions are welcome, coarse ideas are fine.

A: The buttons can be added as delegates. They are visual mockups at that point - they look like buttons, but they don't act like buttons. The delegate can create a real button widget when the cell is entered. It's then a simple matter to set some properties on the button to indicate the function and row. Recall that QObject has a flexible property system - see the setProperty and property methods. All widgets are QObjects.
The receiver of the button's clicked signal can use the sender() method to access the sending button instance, and read the properties. You can also subclass the QPushButton and emit a custom signal upon the button being clicked.

A: You can use the QSignalMapper class which collects a set of parameterless signals, and re-emits them with integer, string or widget parameters corresponding to the object that sent the signal. So you can have one like:
QSignalMapper * mapper = new QSignalMapper(this);
QObject::connect(mapper,SIGNAL(mapped(int)),this,SLOT(function1(int)));

When adding your buttons in each row of table view, you can connect the clicked() signal of the button to the map() slot of QSignalMapper and add a mapping using setMapping so that when clicked() is signaled from a button, the signal mapped(int) is emitted:
QPushButton * but = new QPushButton(this);
but->setText("Function1");

QObject::connect(but, SIGNAL(clicked()),mapper,SLOT(map()));
mapper->setMapping(but, rowIndex);

ui->tableView->setIndexWidget(model->item(rowIndex,column)->index(),but);

This way whenever you click a button in a row, the mapped(int) signal of the mapper is emitted containing the row number.


text:
Q: environment variables are undefined Есть файл .env, содержащий переменные вида:
REACT_APP_EMAIL = email
REACT_APP_PASS = password
При вызове этих переменных, они undefined.
Структура проекта:

Вызываю переменные в файле server.js (при этом использую dotenv)
const dotenv = require('dotenv');
dotenv.config();

const express = require('express');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

app.post('/contacts', (req, res) => {
  console.log(req.body);
  console.log(process.env)
    nodemailer.createTestAccount((err, account) => {
        const htmlEmail = `

Contact details

Name: ${req.body.name}

Email: ${req.body.email}

Message

${req.body.message}

        `;
        let transporter = nodemailer.createTransport({
            service: 'gmail',
            host: 'smtp.gmail.com',
            port: 587,
            secure: true,
            requireTLS: true,
            auth: {
                user: process.env.REACT_APP_EMAIL,
                pass: process.env.REACT_APP_PASS
            }
        })

        transporter.verify(function(error, success) {
            if (error) {
              console.log(error);
            } else {
              console.log("Server is ready to take our messages");
            }
          });
        let mailOptions = {
            from: '',
            to: 'serzhan.helen@gmail.com',
            subject: 'New message',
            text: req.body.message,
            html: htmlEmail
        }
        transporter.sendMail(mailOptions, (err, info) => {
            if(err) {
                return console.log(err)
            }

            console.log('Message sent: %s', info.message)
            // console.log('Message URL: %s', nodemailer.getTestMessageUrl(info))
        })
    })
})

const PORT = process.env.PORT || 3001;

if (process.env.NODE_ENV === 'production') {
    // Serve any static files
    app.use(express.static(path.join(__dirname, 'client/build')));

    // Handle React routing, return all requests to React app
    app.get('*', function(req, res) {
      res.sendFile(path.join(__dirname, 'client/build', 'index.html'));
    });
  }

app.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);

})

При этом, если посмотреть в консоли в файле index.js(который в папке src), то переменные отображаются с нужным значением

A: Вроде все правильно вы указали. попробуйте  следующее: закомментите весь свой код и выполните этот:
const express = require('express');
const app = express();
const port = process.env.PORT || 3000;

require('dotenv').config();

app.get('/', (req, res) => {
   res.send(process.env.REACT_APP_EMAIL);
})

app.listen(port, () => {
   console.log(`Server is running on port ${port}.`)
})


text:
Q: Mocking scope function in Kotlin I am using following object creation methods in kotlin
class Resource(
               referenceFactory: ReferenceFactory,
               id: String,
               name: String,
               role: String,
               odi_runs: int,
               odi_wickets: int,
               test_runs: int,
               test_wickets: int){
    referenceFactory.calculateRank(Player().apply {
               id = id
               name = name
               role = role
               odi_runs = odi_runs
               odi_wicket = odi_wickets
               test_runs = test_runs
               test_wicket = test_wicket
            })
}

then I use this created object for calculate the rank of the player. To get the valid test result from reference factory, I need to mock this 'Player' object creating scope method.


text:
Q: wpf: bind border width with image width I'm adding a functionality to my program which views image thumbnails to listview.
What i want is bind the width of border to my image but i can't make it work
here is my code
        <Border x:Name="imgbrdr" BorderBrush="Black" BorderThickness="1" Margin="5,5,5,5">
     <ListView Name="Thumbnails" SelectionChanged="Thumbnails_SelectionChanged" >
          <ListView.ItemTemplate>
               <DataTemplate>
                    <Image Source="{Binding Source}" Height="{Binding ElementName=imgbrdr}" RenderOptions.BitmapScalingMode="HighQuality"/>
               </DataTemplate>
          </ListView.ItemTemplate>
 </ListView>
</Border>

A: You forgot to add the property path of the Border.
<Image Source="{Binding Source}" Height="{Binding ElementName=imgbrdr, Path=ActualHeight}" RenderOptions.BitmapScalingMode="HighQuality"/>

A: You don't need that Binding at all.
To make the images the same width as the ListView, you only need to disable horizontal scrolling. You can then also set a Margin on the Image controls. With a ListView width of e.g. 200 and a Margin of 10, the images would be 180 wide.
<ListView ScrollViewer.HorizontalScrollBarVisibility="Disabled" ...>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Image Source="{Binding Source}" Margin="10"/>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListView>

Note also that you could as well use a ListBox, which is the base class of ListView.


text:
Q: How to check whether human is straight looking or not using Java with opencv I'm using java with opencv,javacv for an image processing project. The image is not taking from the camera. I'm giving the image as below.
Mat image = Imgcodecs.imread("E:/resources/PPHOTOO/test.jpg");

and using haarcascades I'm cropping the face image too.
CascadeClassifier faceDetector = new CascadeClassifier("C:\\opencv\\haarcascades\\haarcascade_frontalface_alt.xml");

String faces;
MatOfRect faceDetections = new MatOfRect();
Mat face;
Mat crop = null;

 for (int i = 0; i< faceDetections.toArray().length; i++){

            faces = "Face"+i+".png";

             face = image.submat(faceDetections.toArray()[i]);
             crop = face.submat(4, (2*face.width())/3, 0, face.height());
            Imgcodecs.imwrite(faces, face);
}

I want to find whether person is person is straight looking or not. Which means not side faces. I need to know how to find this part.
straight looking image
side face image


text:
Q: When I set my bool new_block to FALSE, the code does nothing (C) I'm building a tetris game in C and and I have a boolean that controls whether I should deploy a new block. I used the following typedef to create the bool variable. When I run the program (int main()), after initialization, my program goes into an infinite while loop which is pretty much the game. For some reason, I have a line new_block = FALSE; that when not commented out, stops my program from doing anything. This is including the test printf statements I have put before it and after it. I can't figure out what's wrong with this simple statement? Thanks :)
typedef enum
{
    FALSE,
    TRUE
} bool;

while(1) {
    if (new_block) {
        printf("test1");
        i = 1;
        //i = rand() % 7;
        block = all_blocks[(i-1)*4];
        block.x = 5;
        block.y = 0;
        new_block = FALSE;
        printf("test2");
        //update_stack(tetris_stack, block, i);
        printf("test");
    }
}

I have checked and the print statements work fine when new_block = FALSE; is commented out so the error isn't in my block structure though I have added that below for reference.
typedef struct {
int x;
int y;
int block_no;
int rotation;
int other_x[3];
int other_y[3];
int up_check_no;
int up_x[3];
int up_y[3];
int left_rotate;
int right_rotate;
int down_rotate;
int max_left;
int left_check_no;
int left_x[4];
int left_y[4];
int max_right;
int right_check_no;
int right_x[4];
int right_y[4];
int max_down;
int down_check_no;
int down_x[4];
int down_y[4];
}block;

A: From the look of it, when you say:
new_block = FALSE;

the if statement:
 if (new_block)

will fail over and over and over again and your program will essentially hang forever. You probably want to have another conditional in your if statement or have an else statement or something to catch the case when creating a new block is false.


text:
Q: Understanding cross-threading Controls access C# I'm having some trouble accessing the UI from an another thread.
I understand the basics on cross-threading limitations, but I can't seem to write the code that will work. More specifically, I can't access the ListView from a static method (thread).
I'm trying to make it work with backgroundWorker.
Here's my code:
private void start_Click(object sender, EventArgs e)
{
    ServicePointManager.DefaultConnectionLimit = 20;
    var tasks = new List<Task<int>>();

    foreach (ListViewItem item in listView1.Items)
    {
        string currentUrl = item.SubItems[1].Text;
        int i = item.Index;
        tasks.Add(Task.Factory.StartNew(() => { return GetWebResponse(currentUrl, i); }));
    }
    Task.WaitAll(tasks.ToArray());
}

private static int GetWebResponse(string url, int itemIndex)
{
    int statusCode = 0;
    HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);

    Task<HttpWebResponse> responseTask = Task.Factory.FromAsync<HttpWebResponse>(httpWebRequest.BeginGetResponse, asyncResult => (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult), null);

    backgroundWorker = new BackgroundWorker();
    backgroundWorker.WorkerReportsProgress = true;
    backgroundWorker.WorkerSupportsCancellation = true;
    backgroundWorker.DoWork += new DoWorkEventHandler(backgroundWorker_DoWork);
    backgroundWorker.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker_ProgressChanged);
    backgroundWorker.RunWorkerAsync();

    return statusCode;
}

private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    listView1.Items[0].ImageKey = "green";
}

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    while (!e.Cancel)
    {
        Thread.Sleep(5000);
        backgroundWorker.ReportProgress(0);
    }
}

This code doesn't work because backgroundWorker_DoWork and backgroundWorker_ProgressChanged are not static, but if I make them static then I can't access listView1
EDIT: Got it working. Code below for review
public delegate void delUpdateListView(int itemIndex, int statusCode);

public Form1()
{
    InitializeComponent();
}

private void start_Click(object sender, EventArgs e)
{

    ServicePointManager.DefaultConnectionLimit = 20;
    var tasks = new List<Task<int>>();

    foreach (ListViewItem item in listView1.Items)
    {
        string currentUrl = item.SubItems[1].Text;
        int i = item.Index;
        tasks.Add(Task.Factory.StartNew(() => {
            //return GetWebResponse(currentUrl, i);

            int statusCode = 0;
            HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(currentUrl);

            Task<HttpWebResponse> responseTask = Task.Factory.FromAsync<HttpWebResponse>(httpWebRequest.BeginGetResponse, asyncResult => (HttpWebResponse)httpWebRequest.EndGetResponse(asyncResult), null);
            statusCode = (int)responseTask.Result.StatusCode;

            object[] invParams = new object[2];
            invParams[0] = i;
            invParams[1] = statusCode;

            if (InvokeRequired)
            {
                BeginInvoke(new delUpdateListView(UpdateListView), invParams);
            }
            else
            {
                Invoke(new delUpdateListView(UpdateListView), invParams);
            }

            return statusCode;

        }));
    }
    Task.WaitAll(tasks.ToArray());
}

public void UpdateListView(int itemIndex, int statusCode) {
    listView1.Items[itemIndex].ImageKey = "green";
}

A: I see several problems here:
1) I don't see why GetWebResponse needs to be static. The easiest solution would be to make it an instance method.
2) Why are you using the background worker anyway?
3) It doesn't make much sense to use Tasks and then wait for them to finish right after you spawn them. This blocks your application where it should be responsive.
As for 3): To keep the UI responsive and updatable, disable everything the user may not click before spawning the tasks, add a continuation action to each task that re-enables the UI components. The task may update the list using the usual Invoke calls.


text:
Q: Limit readable text with a 'read more' link? I am having this issue how to make a limit readable text with a 'read more' link below it. I am making my own cms system as a school project, so i would like to add that feature to it.
I have made so i am able to create an article, but the text just keep going on if i write like 1000 words in one article. I only have a little clue how to make the text limit to 50-100 words.
Anyone have made this before that could help me out how they did it?

A: The idea is to have two methods GetPreview(id, n) and GetArticle(id) where the first returns only first n words from an Article with a link to a page that calls second method.
Assuming that $articleText is the content of your article and a word is considered to be delimited by spaces this is how a part of the GetPreview function will look like:
$words = explode(" ", $articleText);
if (count($words) <= $n)
   return $articleText; //unchanged

$preview = array_splice($words, 0, $n); //n is the number of words
return implode(" ", $preview) . "...
" .
Read More ";

where ViewArticle.php should be another page that loads the entire article.
However, this is an example that will work for plain text articles. If your articles contain HTML the method to extract the preview becomes more complex because you don't want it break the content in the middle of a HTML tag.
Another approach, which is actually safer and used in popular CMS like WordPress is to decorate your article with a specific HTML comment like:

When you display the entire article you don't have to do anything special because this will not be displayed by the browser (remember, it's a comment).
However, in your GetPreview method you search for this string and if you find it:

*

*you get the text before it

*you append a 'Read More' link that redirects you to the full article

There are multiple advantages of this method:

*

*you can safely use HTML in your article.

*the author has full control on how the preview looks like.