text:
Q: How to engineer/preprocess features for the input layer of a exported tensorflow 2.0 keras model for tensorflow serving I have created a model using TensorFlow-2.0-beta1. This uses the Keras functional API to perform regression on the input data. The data needs to have the categorical features one-hot encoded and the numeric inputs normalized. In the past using the Estimators API in TF1.11 this could be fixed using the feature columns and applying engineering to the feature in the ServingInputReceiver. Is there a way to do something similar when exporting a model from keras?
import tensorflow as tf
import pickle
import tensorflow_datasets as tfds
import pandas as pd

tf.keras.backend.clear_session()  # For easy reset of notebook state.

VERSION = tf.__version__
CWD = os.getcwd()
PARENT_DIR = os.path.split(CWD)[0]
DATETIME = datetime.datetime.utcnow()
DATA_DIR = os.path.join(PARENT_DIR, 'data')
train_file_path = os.path.join(DATA_DIR, 'traindf.csv')
test_file_path = os.path.join(DATA_DIR, 'testdf.csv')

CATEGORIES = os.path.join(DATA_DIR, "CATEGORIES")
fileObject = open(CATEGORIES, 'rb')
CATEGORIES = pickle.load(fileObject)
fileObject.close()

NUMERICSTATS = os.path.join(DATA_DIR, "NUMERICSTATS")
fileObject = open(NUMERICSTATS, 'rb')
NUMERICSTATS = pickle.load(fileObject)
fileObject.close()

# CSV columns in the input file.
with open(train_file_path, 'r') as f:
    names_row = f.readline()

CSV_COLUMNS = names_row.rstrip('\n').split(',')
print(CSV_COLUMNS)

drop_columns = ['SubSilo','Year','StockID', 'QuickRef', 'sumUKQuantity', 'sumNonUKQuantity']
columns_to_use = [col for col in CSV_COLUMNS if col not in drop_columns]

columns_to_use

LABEL_COLUMN = 'totalqty'
FEATURE_COLUMNS = [column for column in columns_to_use if column != LABEL_COLUMN]
test_labels = testdf[LABEL_COLUMN]

COLUMN_DEFAULTS = [tf.dtypes.string, #ProductBrand
                  tf.dtypes.string, #Department
                  tf.dtypes.string, #ProductType
                  tf.dtypes.string, #ProductSubType
                  tf.dtypes.string, #Silo
                  tf.dtypes.string, #Level
                  tf.dtypes.string, #BaseColour
                  tf.dtypes.string, #Sport
                  tf.dtypes.string, #UKSize
                  tf.dtypes.float32, #UnitCostPrice
                  tf.dtypes.float32, #ExVatSalesValue
                  tf.dtypes.float32, #RRP_GBP
                  tf.dtypes.string, #Week
                  tf.dtypes.int32] #totalqty

def get_dataset(file_path):
    dataset = tf.data.experimental.make_csv_dataset(
        file_path,
        batch_size=60, # Artificially small to make examples easier to show.
        label_name=LABEL_COLUMN,
        select_columns=columns_to_use ,
        column_defaults=COLUMN_DEFAULTS,
        num_epochs=1,
        ignore_errors=True,
        shuffle=False)
    return dataset

raw_train_data = get_dataset(train_file_path)
raw_test_data = get_dataset(test_file_path)

def process_categorical_data(data, categories):
    """Returns a one-hot encoded tensor representing categorical values."""

    # Remove leading ' '.
    data = tf.strings.regex_replace(data, '^ ', '')
    # Remove trailing '.'.
    data = tf.strings.regex_replace(data, r'\.$', '')

    # ONE HOT ENCODE
    # Reshape data from 1d (a list) to a 2d (a list of one-element lists)
    data = tf.reshape(data, [-1, 1])
    # For each element, create a new list of boolean values the length of categories,
    # where the truth value is element == category label
    data = tf.equal(categories, data)
    # Cast booleans to floats.
    data = tf.cast(data, tf.float32)

    # The entire encoding can fit on one line:
    # data = tf.cast(tf.equal(categories, tf.reshape(data, [-1, 1])), tf.float32)
    return data

def process_continuous_data(data, mean, std):
    # Normalize data
    data = (tf.cast(data, tf.float32) - mean) / std
    return tf.reshape(data, [-1, 1])

def preprocess(features, labels):
    # Process categorial features.
    for feature in CATEGORIES.keys():
        features[feature] = process_categorical_data(features[feature], CATEGORIES[feature])

    # Process continuous features.
    for feature in NUMERICSTATS.keys():
        features[feature] = process_continuous_data(features[feature],
                                                    NUMERICSTATS[feature]['mean'],
                                                    NUMERICSTATS[feature]['std']
                                                   )

    # Assemble features into a single tensor.
    features = tf.concat([features[column] for column in FEATURE_COLUMNS], 1)

    return features, labels

train_data = raw_train_data.map(preprocess).shuffle(len(traindf))
test_data = raw_test_data.map(preprocess)

def get_model(input_dim):
    """Create a Keras model with layers.

    Args:
        input_dim: (int) The shape of an item in a batch.

    Returns:
        A Keras model.
    """

    inputs = tf.keras.Input(shape=(input_dim,))
    x = tf.keras.layers.Dense(244, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.001))(inputs)
    x = tf.keras.layers.Dropout(0.5)(x)
    x = tf.keras.layers.Dense(200, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.001))(x)
    x = tf.keras.layers.Dropout(0.5)(x)
    x = tf.keras.layers.Dense(100, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.001))(x)
    x = tf.keras.layers.Dropout(0.5)(x)
    x = tf.keras.layers.Dense(50, activation='relu', kernel_regularizer=tf.keras.regularizers.l2(0.001))(x)
    x = tf.keras.layers.Dropout(0.5)(x)
    outputs = tf.keras.layers.Dense(1)(x)

    model = tf.keras.Model(inputs, outputs)

    return model

input_shape, output_shape = train_data.output_shapes
input_dimension = input_shape.dims[1] # [0] is the batch size

model = get_model(input_dimension)

optimizer = tf.keras.optimizers.Adam(0.001)

model.compile(loss='mse',
            optimizer=optimizer,
            metrics=['mae', 'mse', tf.keras.metrics.RootMeanSquaredError()])

# The patience parameter is the amount of epochs to check for improvement
early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=20)

# Display training progress by printing a single dot for each completed epoch
class PrintDot(tf.keras.callbacks.Callback):
    def on_epoch_end(self, epoch, logs):
        if epoch % 100 == 0: print('')
        print('.', end='')

tensor_board = tf.keras.callbacks.TensorBoard(log_dir=os.path.join(PARENT_DIR, 'tensorBoardLogs'))

reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor='val_loss',
                                                 factor=0.2,
                                                 patience=4,
                                                 verbose=1,
                                                 min_lr=0.00001)

history = model.fit(train_data,
                    validation_data=test_data,
                    epochs=100,
                    verbose=1,
                    callbacks=[early_stop,
                               PrintDot(),
                               tensor_board,
                               reduce_lr]
                   )

tf.keras.experimental.export_saved_model(model, saved_model_path=os.path.join(PARENT_DIR, 'models/1'))

What I would like is to have a model I can serve using TensorFlow serving that will take the features as they are in my training data, 13 of them and preprocess them in the model itself. Therefore using something like Flask as a middle man won't be needed

A: You can think of using Tensorflow Transform, which applies the same Transformations during Serving, that you have applied during Training.
You can replace your functions, process_categorical_data, process_continuous_data and preprocess with the below code:
def preprocessing_fn(inputs):
    """Preprocess input columns into transformed columns."""
    x = inputs['x']
    y = inputs['y']
    s = inputs['s']
    x_centered = x - tft.mean(x)
    y_normalized = tft.scale_to_0_1(y)
    s_integerized = tft.compute_and_apply_vocabulary(s)
    x_centered_times_y_normalized = (x_centered * y_normalized)
    return {
        'x_centered': x_centered,
        'y_normalized': y_normalized,
        's_integerized': s_integerized,
        'x_centered_times_y_normalized': x_centered_times_y_normalized,
    }

# Ignore the warnings
with tft_beam.Context(temp_dir=tempfile.mkdtemp()):
  transformed_dataset, transform_fn = (  # pylint: disable=unused-variable
        (raw_data, raw_data_metadata) | tft_beam.AnalyzeAndTransformDataset(
            preprocessing_fn))

transformed_data, transformed_metadata = transformed_dataset

print('\nRaw data:\n{}\n'.format(pprint.pformat(raw_data)))
print('Transformed data:\n{}'.format(pprint.pformat(transformed_data)))

For more details, please refer TF Transform Guide, Tutorial1 and Tutorial2.


text:
Q: PHP - How to get page Text (plain text) on page complete load how we can get TEXT ON PAGE COMPLETE LOAD
i have check following code convert html into plain text but its not up to mark.
$html = "Hello
sjhds
djsds djshd
sdjhds ";
strip_tags(str_replace(array("", ""), array("_", "_"), $html));

// to preserve anchors...
str_replace("|a", "<a", strip_tags(str_replace("<a", "|a", $html)));

echo $html;

thanks for your help

A: I am worried about that it is not possible to check in PHP if page was completely loaded. In PHP you may strip tags you want - but page will be loaded after that process.
So, if you would like to strip tags after loading of page, you should use JavaScript - even like jQuery and may be also together with AJAX.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Watcher throws error when element is removed I got a watcher of an item:
watch(() => props.listItemData[props.index]?.amountFTempStore, newval => {
  if (newval) {
    valuestorage.value = newval.value.toString().replace(".", ",");
    valuestorageHidden.value = newval.value.toString().replace(".", ",");
  }
}, {
  deep: true
})

Without the ? conditional operator and the existence-check of newval I get an error
TypeError: Cannot read properties of undefined cause the element is changing, due to it's removal. Is there any other way of preventing this except of the conditional check?


text:
Q: Are Community Wiki questions able to appear on Hot Network Questions? Over at Photography Stack Exchange, we have a biweekly photo submission contest on our main site. For awhile, the contest was just posted as a regular question, and in order to counteract the reputation boost I was receiving, I regularly gave away several bounties on the photo submissions. The presence of the photo contest on our main site definitely boosted our viewership, and we had lots of photo submissions, and the photo contests regularly hit HNQ, thus boosting participation.
But in an attempt to address some of the concerns about voting, "unearned" reputation boost, and the idea that our Photo of the Week contest questions were basically the glaring exception to what is usually considered a good question, I started making the PotW questions CW.
After making the PotW question CW, it seems the contests never make HNQ. Is that just a coincidence, or is it a consequence of marking those questions as CW?

A: There are still feature requests out there that request community wiki questions to  be excluded from HNQ. They never seem to have been implemented. As bobble pointed out in the comments, community wiki questions do seem to be penalized, which means that it may indeed be harder for these questions to reach the required hotness score to reach the list in the first place.
But, taking a quick peek through the last 3 photo competition questions, it seems these questions just don't get answers fast enough to get on HNQ, even if there is no penalty. Questions become eligible for HNQ after 8 hours, in my experience a question should at that point have at least a few upvotes, and one answer with a couple of upvotes on it as well. In case of the photo competitions, this and this did not even have a single answer before those 8 hours were up. In contrast, this one did have an answer posted about an hour after the question was posted, and it did end up in HNQ.
Since the calculation of the hotness score takes into account question age, it becomes increasingly harder to get it onto the list the older the question gets. So, community wiki questions can get onto the Hot Network Questions (after all, this one did), but they need quick answers and upvotes to get there.

A: As mentioned in This answer whether or not an answer is CW has no effect on it reaching the HNQ (unless that answer is outdated).
From what I can tell, there are three possibilities for why these newer questions aren't reaching HNQ

*

*you changed something else about these questions that caused them to be disqualified (check the list I linked to earlier to see what might have caused it). This can be fixed by not doing that thing

*the newer questions haven't been "hot" enough to make it to the HNQ. This one isn't really a problem, just chance related.

*The answer I linked to earlier is wrong/outdated. This can be fixed:

*

*create a burner account and ask all questions from that account (but don't Mark them CW). This solves the problem of getting reputation that you shouldn't.

*Then, if you want the answerers to be able to reputation, you don't have to do anything more.

*However, if you don't want the answerers to earn reputation, you can require them to mark their answers as CW (write that requirement into the question), and have a moderator (you can do it yourself in this case) make the answers that aren't submitted as CW into a CW.


text:
Q: Within a python script, check syntactic correctness of C code in str format Necessarily within a python program and given an str variable that contains C code, I want to check fast if this code is syntactically correct, or not. Essentially, I only need to pass it through the compiler's front end.
My current implementation uses a temp file to dump the string and calls a clang process with subprocess (non-working code below to illustrate my solution). This is very slow for my needs.
src = "int main(){printf("This is a C program\n"); return 0;}"
with open(temp_file, 'w') as f:
  f.write(src)
  cmd = ["clang", abs_path(f), flags]
  subprocess.Popen(cmd)
  ## etc..

After looking around, I found out about clang.cindex module (pip clang), which I tried out. After reading a bit the main module, lines 2763-2837 (specifically line 2828) led me to the conclusion that the following code snippet will do what I need:
import clang.cindex
......
try:
  unit = clang.cindex.TranslationUnit.from_source(temp_code_file, ##args, etc.)
  print("Compiled!")
except clang.cindex.TranslationUnitLoadError:
  print("Did not compile!")

However, it seems that even if the source file contains obvious syntactic errors, an exception is not raised. Anyone knows what am I missing to make this work ?
On a general context, any suggestions on how to do this task as fast as possible would be more than welcome. Even with clang.cindex, I cannot get away from writing my string-represented code to a temp file, which may be an additional overhead. Writing a python parser could solve this but is an overkill at the moment, no matter how much I need speed.

A: The compilation itself succeeds even if the file has syntax errors. Consider the following example:
import clang.cindex

with open('broken.c', 'w') as f:
    f.write('foo bar baz')

unit = clang.cindex.TranslationUnit.from_source('broken.c')
for d in unit.diagnostics:
    print(d.severity, d)

Run it and you will get
3 broken.c:1:1: error: unknown type name 'foo'
3 broken.c:1:8: error: expected ';' after top level declarator

The severity member of is an int, with the value from the enum CXDiagnosticSeverity with values

*

*CXDiagnostic_Ignored = 0

*CXDiagnostic_Note = 1

*CXDiagnostic_Warning = 2

*CXDiagnostic_Error = 3

*CXDiagnostic_Fatal = 4


text:
Q: Asp.net - Azure AD Authentication - Request.IsAuthenticated set to false after some time (approx 1 hour) and ask user to select the account again I have checked all the details inside Web.config file and it is properly configured as well.
public async Task SignIn()
    {
        if (!Request.IsAuthenticated)
        {
            HttpContext.GetOwinContext().Authentication.Challenge(
                new AuthenticationProperties { RedirectUri = "/" },
                OpenIdConnectAuthenticationDefaults.AuthenticationType);
        }
 }

Also try some solution found in similar problem but it didn't work for me.
Request.IsAuthenticated is always false
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
<add name="FormsAuthentication" type="System.Web.Security.FormsAuthenticationModule" />
</modules>
</system.webServer>

I am following code sample by Azure
https://learn.microsoft.com/en-us/azure/active-directory/develop/sample-v2-code (Web Application - Asp.net)
https://github.com/Azure-Samples/ms-identity-aspnet-webapp-openidconnect/tree/master/WebApp
enter image description here

A: If i am understanding correct,it seems you  are trying to call api.
Access tokens are required to call api and that can be refreshed.
Please select Access tokens and id tokens in portal authentication.
ID Token is there to be consumed by the application. It contains claims which you can validate to authenticate the end user and is of one time use and from then on. Access token is there for authorization. It is intended to be used against a protected resource (ex:- API protected by OAuth 2.0 tokens).
Access tokens has a validity of 1 hour and refresh tokens last for 14 days.
The expiration time for ID tokens in Azure AD is 1 hour. As long as the user session with AAD is active, the acquireTokenSilent method will be able to renew the idtokens. However, if the AAD session is expired, the token renewal will result in a failure. You will need to handle the failure with an interactive call prompting user to sign in again.
Please check this
References:

*

* intent of ID Token expiry time in OpenID Connect? - Stack Overflow

*How to store the token received in AcquireTokenAsync with Active Directory - Stack Overflow

*Configurable lifetimes


text:
Q: how to sort an array from highest to lowest and allowing the user to enter in part of the array, not the full amount alotted? I need to sort the array from highest to lowest while also keeping their names next to their scores. Also, how do I allow the user to enter in only part of the array instead of the full 10 spaces allotted?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace proj09LEA
{
    class Program
    {
        const int SIZE = 10;

        static void Main(string[] args)
        {
            // declare and array of integers
            string[] name = new string[SIZE];
            int[] score = new int[SIZE];

            Console.WriteLine("\nSaturday Coder's Bowling Team");
            Console.WriteLine("Enter in a name and score for each person on the team.");
            Console.WriteLine("For example, Mary 143. Just hit Enter when you are done.\n");

            // fill an array with user input
            for (int i = 0; i < score.Length; i++)
            {
                Console.WriteLine("Enter in a name and score: ");
                string line = Console.ReadLine();

                name[i] = line.Substring(0, line.IndexOf(' '));
                score[i] = int.Parse(line.Substring(line.IndexOf(' ') + 1));
            }

            Console.WriteLine("------------ Input Complete ------------\n");
            Console.WriteLine("Here are the scores for this game:\n");

            for (int i = 0; i < score.Length; i++)
            {
                Console.WriteLine("{0}'s score was {1}.", name[i], score[i]);
            }

            Console.WriteLine();
            AverageScore(score);

            Console.WriteLine("Press Enter to continue. . .");
            Console.ReadLine();
        }

        static void AverageScore(int[] score)
        {
            int sum = score.Sum();
            int average = sum / score.Length;
            Console.WriteLine("The average score for this game was {0:d}.", average);
        }
    }
}

A: try this:
Dictionary<string, int> playerScoreList = new Dictionary<string, int>();
playerScoreList.Add(name, score); // add user to dictionary
playerScoreList.OrderByDescending(s => s.Value); // sort by score descending


text:
Q: WPF unresponsive UI issues I have an application that is displaying some oddball behaviour and I can't figure it out.  Basically my app starts up, and attempts to connect to some external hardware that is connected via USB.  While this goes on I display a 'busy' window that has some simple animations.  Intermittently however, the UI will completely hang (animation and all) while the hardware initializes.
The thing is, the problem is intermittent, and I have already ensured that it is running on a background thread (via Task.StartNew). I have tried replacing the hardware initialization calls with things like 'Thread.Sleep(5000)' to simulate a hang, and the UI behaves correctly so I am kind of out of ideas here.
Is it possible that the hardware itself (and unmanaged library that I use to interact with it) is somehow interfering with the system and causing the issue?  I'd really hate to resort to blaming hardware, but is there some other avenue of investigation or other possible software problem that I am missing?

A: Do you connect to the device using a COM library?  If COM is brought in as STA, it can end up delegating some of its work to the UI thread, causing a blocking call on a different thread to sometimes block the main UI thread as well.  Very annoying, I know.  Well-behaved COM components won't do this, but I've run into it before.  You can diagnose if this is happening by isolating only the call that causes the blocking in a test application, with nothing else occurring.  Create a UI timer and record ticks.  If the ticks stop firing when you call the COM method on a separate thread, the COM component is behaving badly.

A: I would check if changing process affinity makes a difference. It could be that the usb driver is sloppy, and does something timeconsuming in the hardware interrupt. This could block whatever thread was running on the core that services the interrupt.
There could be other explanations, but if the problem is related to a specific core, it suggests that the driver is the problem.
Please note that my knowledge of windows driver models is quit outdated, so it may no longeer work this way.


text:
Q: Marketing Cloud - unable to uninstall a package I installed in my business unit a package called Deployment Manager from appexchange and I am looking for a way to uninstall it.
If I go to Setup > Apps > Installed Packages I see the list of installed packages but there is no icon to uninstall it.
What should I do to uninstall it?
Here is the installed packages page

Thanks

A: You need to click on the package and then you will be able to delete it using the Delete button on the top right of the screen:

A: You need to be an admin in all MIDs to delete a package as outlined in this help page 'Create and Install Packages'

You can uninstall packages and apps installed from AppExchange or an implementation partner. Only users with the Installed Packages | Administer permission and access to all the accounts in the enterprise can uninstall a package or app. The package or app is uninstalled from all accounts in the enterprise.


text:
Q: asp textbox Placeholder and autocomplete doesnt work together in IE8 I have a asp texbox and it has placeholder and jquery autocomplete functionality. Both are working fine in chrome but in IE8 placeholder is not working. In order to make it work I place watermark for placeholder in jquery but then  watermark is displaying but autocomplete is not working. All issue is in IE8:
<asp:TextBox ID="txtLocation" runat="server" CssClass="frmhometxtLocation" placeholder="Locations"
                            onblur="Javascript:FormatLocation();"></asp:TextBox>

        $("#txtLocation")
        // don't navigate away from the field on tab when selecting an item
          .bind("keydown", function (event) {
              if (event.keyCode === $.ui.keyCode.TAB &&
                $(this).autocomplete("instance").menu.active) {
                  event.preventDefault();
              }
          })

          .autocomplete({
              delay: 0,
              minLength: 1,
              source: function (request, response) {
                  // delegate back to autocomplete, but extract the last term
                  response($.ui.autocomplete.filter(
                locations, extractLast(request.term)));
              },
              focus: function () {
                  // prevent value inserted on focus
                  return false;
              },
              select: function (event, ui) {
                  var terms = split(this.value);
                  // remove the current input
                  terms.pop();
                  // add the selected item
                  terms.push(ui.item.value);
                  // add placeholder to get the comma-and-space at the end
                  terms.push("");
                  this.value = terms.join(", ");
                  return false;
              }
          });
    });

A: I was doing a mistake here and does not including Watermark.min.js. Use Tooltip for Watermark. Now it is working perfectly. Here is the correct code:
<script src="Scripts/jquery-1.10.2.js" type="text/javascript"></script>
<script src="Scripts/jquery-ui1.11.4.js" type="text/javascript"></script>
<script src="Scripts/Watermark.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function () {
        var locations = ["Anywhere", "Gurgaon", "Delhi", "Noida","Chennai"];
        function split(val) {
            return val.split(/,\s*/);
        }
        function extractLast(term) {
            return split(term).pop();
        }

        $("#txtLocation")
        // don't navigate away from the field on tab when selecting an item
        .WaterMark(
        {

        })
          .bind("keydown", function (event) {
              if (event.keyCode === $.ui.keyCode.TAB &&
                $(this).autocomplete("instance").menu.active) {
                  event.preventDefault();
              }
          })

          .autocomplete({
              delay: 0,
              minLength: 1,
              source: function (request, response) {
                  // delegate back to autocomplete, but extract the last
                  response($.ui.autocomplete.filter(
                locations, extractLast(request.term)));
              },
              focus: function () {
                  // prevent value inserted on focus
                  return false;
              },
              select: function (event, ui) {
                  var terms = split(this.value);
                  // remove the current input
                  terms.pop();
                  // add the selected item
                  terms.push(ui.item.value);
                  // add placeholder to get the comma-and-space at the end
                  terms.push("");
                  this.value = terms.join(", ");
                  return false;
              }
          });
    });
 });
 </script>
<asp:TextBox ID="txtLocation" runat="server" CssClass="frmhometxtLocation" placeholder="Locations" ToolTip="Locations"
                            onblur="Javascript:FormatLocation();"></asp:TextBox>


text:
Q: How to read off 1 flag bit and get integer at same time Say I have an 8-bit number with a flag at either side:
<flag>0101011 (decimal 43)
0101011<flag> (decimal 43)

Not sure which is more optimal for what's next.
Then say I want to check the flag, and then use the number. Wondering if that can be done in one operation. Or if not, the fewest operations it can be done in.

A: You could do something like this using the flag at the end:

var num = 0b01010110;
var flag = num & 1;
var int = num >> 1;
console.log(flag);
console.log(int);

But binary operations and bit flags in general are kind of an abuse of JavaScript since it doesn't really have integer types. If you do need to do it though, it seems like a flag at the end would be more reliable since you can't explicitly guarantee a number to be 8 bits by its type. This way the flag will always be in the same position and the rest will always be your number.


text:
Q: getting error while requesting to salesforce from eclipse
i have already try to close the eclipse and restart, it works but again after 4-5 request same error is coming.
any solution will be appreciate.
Error Message is This: Unable to create connection to Salesforce, Destination URl not reset. The URL returend rom login must be set in SForceService.


text:
Q: unclean signal at the output of an optocoupler I use a FOD260L optocoupler and here is its datasheet and diagram below

pin 2 is connected to an atmega168a (supplied by 3.3V ) via 270 ohm resistor. pin 3 is connected to ground of the MCU. On the right side, Vcc is connected to a PSU that supplies 5V (max 1.5A), Ve is left opened, pin 5 is connected to GND of the PSU. Referring the figure 11 on the datasheet, I connected 330 ohm between Vcc and Vo (as a pull up resistor) then I expect monitor Vo output. I tried to draw the schematic below ( I hope it is correct).

simulate this circuit – Schematic created using CircuitLab
Here is the oscilloscope output

The blue one is the input signal which is clean, and the red one is the output (Vo) signal which I could not understand why it is not clean. Of course I connect blue's probe ground to MCU's ground and the red one's probe to the PSU's ground. PSU and MCU have different power sources.
I see that the red signal is inverted which I expected to see. But could anyone explain why it is not as clean as the blue one?

A: The data sheet says: -

The VCC supply to each optoisolator must be bypassed by a 0.1μF
  capacitor or larger. This can be either a ceramic or solid tantalum
  capacitor with good high frequency characteristic and should be
  connected as close as possible to the package VCC and GND pins of each
  device.

Is this the problem? Here's a picture showing the 100nF cap from the data sheet: -

For information the data sheet also says: -

Enable Input – No pull up resistor required as the device has an
  internal pull up resistor.

A: You left one input of the AND gate floating.  That can lead to all kinds of flaky behavior, unless the datasheet explicitly says that these inputs float high when left open.

A: Ve shouldn't be floating. It's an input to an AND gate. That means that if the other input (from the TL081) is low, you get a definite OFF (driving your output high), but if the other input is high you get an indeterminate state depending on what noise happens to be on the pin at the time. Tie it to VCC and you should see better results.


text:
Q: Is There any way of Getting Form Information in App Engine in the GET Function My question is rather simple...
In a def post(self) function for instance, I can use self.request.get to pull form information.
Is there any way I could accomplish the same thing within the 'def get(self)' function?
Thank you!!!
EDIT:
What I am trying to accomplish is sort of like facebook. If you could imagine a facebook wall, everyone has their own display pictures, which change dynamically. I'm trying to accomplish the same sort of thing... Too many variables would end up in the url I think if I choose to throw them in the url.

A:  def get(self):
    id = self.request.get('id')

Where you have it encoded in the URL like
/play?id=some_id

Lots more info at webapp2 handlers


text:
Q: onMouseOver, hyperlink and rel...help me :( Currently, I have a carousel on JavaScript which works when we click on hyperlink, like this:

I would like execute this event with a onMouseOver too.
So I try this, but it doesn't work:

How to fix it?
PS:
This is the JS code in question:
next: function () {
        if (this.current) {
            var currentIndex = this.current._index;
            var nextIndex = (this.slides.length - 1 == currentIndex) ? (this.options.circular ? 0 : currentIndex) : currentIndex + 1;
        } else {
            var nextIndex = 1;
        }

        if (nextIndex == 0 && this.options.circular && this.options.effect != 'fade') {
            this.scroller.scrollLeft = 0;
            this.scroller.scrollTop  = 0;
            nextIndex = 1;
        }

        if (nextIndex > this.slides.length - (this.options.visibleSlides + 1)) {
            nextIndex = this.slides.length - this.options.visibleSlides;
        }

        this.moveTo(this.slides[nextIndex]);
    }

A: Where in your code is the click event assigned to the anchor element? Moreover, why do you use a separate element solely to assign a mouseover event?
You can better use

or even better assign the JavaScript in a seperate file:
window.onload = function () {
  var nextButton = document.getElementById("idOfNextButton");
  nextButton.onmouseover = yourObject.next;
};

This way, when a user doesn't have JavaScript enabled and/or middle-clicks on the next-button, your site will still function.

A:

'getElementsByTagName' returns an array.

A: There is two problems here.
As Jeaffrey said getElementsByTagNames returns an array so your code may look like this too.

But this won't work neither as there is no convenient way to generate a click programatically in vanilla javascript. See In JavaScript can I make a "click" event fire programmatically for a file input element?.
It's still possible with at least jQuery : http://api.jquery.com/click/, but including such a dependency for this seems overkill.
The best solution I see in your situation would be to just call the a[href] method directly in the p[onmouseover].


text:
Q: Actionscript 3/Flash: Basic Game Loop Stuttering Problems I'm trying to make a basic game in Flash and Actionscript 3.
As of now, I've been working on a smooth game loop but ran into problems. I tried to implement a fixed time-stamp loop seen: http://gafferongames.com/game-physics/fix-your-timestep/ and in Flixel.
The main issue that I have right now is that moving a simple object across the screen produces noticeable stuttering. I am aiming for a smoother experience but can't seem to figure out what the issue is.
The main loop is called on an Event.ENTER_FRAME at 60 fps.
These variables are instantiated first:
public var total:uint = 0;
public var fixedDT:Number = 1000.0/60.0; //Shoot for 60 FPS in MS
public var accumulator:int = 0;
public var maxAccumulation:uint =  120;

This is the main loop on every ENTER_FRAME:
//Most times are in ms
var mark:uint = getTimer();
var elapsedMS:uint = mark-total;
total = mark;

accumulator += elapsedMS;
if(accumulator > maxAccumulation){
    accumulator = maxAccumulation;
}

while(accumulator > fixedDT){
    step();
    accumulator = accumulator - fixedDT;
}

//Convert from ms to secs. to interpolate graphics drawing (linear interpolation)
renderGameState(accumulator/fixedDT/1000.0);

step() is just updating every game-object with the fixed delta-time. The game object update function is simple and is as follows:
//First part is just updating the previous position for graphic interpolation
position.x += velocity.x*deltaTime;
position.y +=  velocity.y*deltaTime;

For rendering, I am just drawing bitmap.copyPixel. The graphical interpolation I mentioned is using a basic linear interpolation function that uses prev./curr. position and deltaTime to calculate the drawX/Y.
 public function render(bitmap:BitmapData, deltaTime:Number, xOff:Number, yOff:Number):void{
        this.x = lerp(prevPosition.x,position.x,deltaTime) + xOff;
        this.y = lerp(prevPosition.y,position.y,deltaTime) + yOff;

        bitmap.copyPixels(bitmapData, bitmapData.rect,new Point(this.x,this.y),null,null,true);
    }

 public function lerp(v0:Number, v1:Number, t:Number):Number {
     return (1-t)*v0 + t*v1;
 }

However, there is noticeable stuttering appearing. In the image below, I don't clear the bitmap before drawing to it. You should be able to see that there's a lot of variation between the spacing of circles rendered, and sometimes it's extremely noticeable.
http://i.stack.imgur.com/00c39.png
I would appreciate any help at all, thanks!

A: I don't know if this helps but here's the code I use to fix my time step.
private var _pause          :Boolean;
private var _prevTimeMS     :int;
private var _simulationTime :Number;

override public function update():void
{
    super.update();

    if (!_pause)
    {
        var curTimeMS:uint  = getTimer();
        if (curTimeMS == _prevTimeMS)
        {
            return;
        }
        var deltaTime:Number    = (curTimeMS - _prevTimeMS) / 1000;
        if (deltaTime > 0.05)
        {
            deltaTime = 0.05;
        }
        _prevTimeMS     = curTimeMS;
        _simulationTime += deltaTime;
        while (space.elapsedTime < _simulationTime)
        {
            // Your game step goes here.
            _space.step((stage.frameRate > 0) ? (1 / stage.frameRate) : (1 / 60));
        }
    }
}

(Originally taken from a Nape Physics sample)


text:
Q: Default button not working in asp.net panel I have an asp.net panel with a default button setting but the button is never trigger when hitting the ENTER button. I searched SO for this question, but could not find any response that works.
How can I get btnRegister to click when the users hits ENTER ?
<asp:Panel runat="server" ID="pnlCustomer" DefaultButton="btnRegister">

            <asp:Button ID="btnBackToProfile" Text="Back To Profile" runat="server" Enabled="false"
                onclick="btnBackToProfile_Click" />

            <asp:Button ID="btnClearnForm" Text="Clear Form" runat="server"
                OnClientClick="ClearForm1()" />

            <asp:Button id="btnRegister" runat="server" onclientclick="document.getElementById('AlertTime').value = GetSeconds();" Text="Continue" OnClick="btnRegister_Click" />

</asp:Panel>

A: The first thing that I like to point here is that the default button is the control that is pressed when the focus is on one of the controls that exist inside this Panel, and not the rest of the page.
The main reason for your issue is because inside this Panel you do not have anything (else than buttons) that can keep the focus of the keyboard and send the enter to the default button.
Something like a text editor, for example: if you place a text editor inside the panel, click on it and then press enter, the default button will be fired.
So when the focus is inside this panel is on a button, and when you press enter the selected button is pressed, not the default one.

A: I had this same issue and discovered that the Panel can't be outside of the table containing the default button.  If you put your Panel inside the cell that has the button it should work.


text:
Q: Jquery - Changing image attributes I have an image, which contains the following:
<img src="/Modules/Visualiser.php?template=1&text=testing">
What I need to do, is when a dropdown has been changed, it changes the template depending on the selection. But I can't seem to figure out how to just change the template, since the text will stay the same (At this point anyway)..
$("#select-cover").change(function()
    {
        $("#cover-photo").attr('src', function(i, src) {
             return src.replace( 'template=', 'template=1' );
        });
    });

I have tried to do this, but had no joy. Any have any ideas to where I am going wrong?

A: You can replace the template param like
$("#select-cover").change(function () {
    var value = this.value;
    $("#cover-photo").attr('src', function (i, src) {
        return src.replace(/\?template=\d+/, '?template=' + value);
    });
});

Demo: Fiddle - inspect the element to see the difference

A: Assuming that the select provides the template number eg (1, 2, 3 etc):
$('#select-cover').on('change', function() {
   var tempNum = $(this).val();
   $('#cover-photo').attr('src', '/Modules/Visualiser.php?template=' + tempNum + '&text=testing');
});


text:
Q: How to read a simple string from a POST request in AFNetworking (No JSON) I'm using AFNetworking to communicate with a server through POST that responds with a simple string containing the information I need.  I'm using the following code:
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
[manager POST: MY_URL
   parameters: MY_PARAMETERS
      success:^(AFHTTPRequestOperation *operation, id responseObject) {
        //do something
      }
      failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        //etc.
      }];

However, it seems that AFNetworking expects every response to be in JSON format because I get this error when I execute my request:

Error Domain=NSCocoaErrorDomain Code=3840 "The operation couldn't be
  completed. (Cocoa error 3840.)" (JSON text did not start with array or
  object and option to allow fragments not set.) UserInfo=0x1566eb00
  {NSDebugDescription=JSON text did not start with array or object and
  option to allow fragments not set.}

How can I tell AFNetworking that it's OK that the response is not a JSON object? I've seen something involving AFHTTPClient, but it doesn't seem to be part of AFNetworking anymore.

A: You can tell the AFHTTPRequestOperationManager or AFHTTPSessionManager how to handle the response, e.g. before calling POST, you can do the following:
manager.responseSerializer = [AFHTTPResponseSerializer serializer];

Then in your success block, you can convert the NSData to a string:
NSString *string = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];

Having said that, you might want to contemplate converting your web service to return JSON response, as it's far easier to parse that way (and differentiate between a valid response and some server error).

A:   NSLog(@"Response: %@", [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding]);

you can get response description details like below
 NSLog(@"JSON: %@", [responseObject description]);

A: Much better way would be subclassing AFHTTPResponseSerializer and overriding there

func responseObject(for response: URLResponse?, data: Data?, error:
  NSErrorPointer) -> Any?

There you can parse response, cast to type you need and return.


text:
Q: Python Matplotlib : Just the graph image I cannot get pyplot to produce "cropped" images, that is, get rid of the grey left and right borders, as it is, it is not an accurate representation of the sound waveform : This sound file has no silence before and after.

My code :
import gtk

from matplotlib.figure import Figure
from numpy import arange, sin, pi
import scipy.io.wavfile as wavfile

from matplotlib.backends.backend_gtkagg import FigureCanvasGTKAgg as FigureCanvas

    win = gtk.Window()
    win.connect("destroy", lambda x: gtk.main_quit())
    win.set_default_size(400,300)
    win.set_title("Cropping figure")

    rate, data = wavfile.read(open('/home/px/gare_du_nord-catchlak.wav', 'r'))
    f = Figure()
    a = f.add_subplot(111, axisbg=(0.1843, 0.3098, 0.3098))
    a.plot(range(len(data)),data, color="OrangeRed",  linewidth=0.5, linestyle="-")
    a.axis('off')
    a.autoscale_view('tight')
    canvas = FigureCanvas(f)  # a gtk.DrawingArea

    win.add(canvas)

    win.show_all()
    gtk.main()

A: OK, I got my answer :
f.subplots_adjust(0, 0, 1, 1)

EDIT:
This also works, in fact it works even better:
a.margins(0, 0)


text:
Q: html element is not updating depending on input value I have a
element that should contain whatever is written in the <input> box. The
 does contain everything there is in <input> except the last character.
For example, (not valid JS code)
 if input = Fish
    then p = Fis

if input = Monster
    then p = Monste

Here is my code

        <input type="text" />

How do I make the p element contain even the last character in the input?

A: By registering to the 'keydown' event, your logic is firing when the key is pressed down, but the input box's value isn't updated until after your finger comes off the button.
Try registering to 'keyup' instead.

Fiddle: https://jsfiddle.net/cb457Lpt/

A: If you want to remove the last character from input value, and to add the resulted string in a html element, try this code:

<input type="text" id='id_inp' />


text:
Q: How can I pass params from a controller to my serializers? For a JSON API, I need to pass url params to my serializes:
http://mydomain.com/api/categories?name=news&counter=123
This is my API controller:
class Api::CategoriesController <  ApplicationController
  respond_to :json
  def index
    respond_with Category.where("name ==? AND content_counter >?", params[:name], params[:counter].to_i)
  end
end

My serializer looks like this:
class CategorySerializer < ActiveModel::Serializer
    attributes :id, :name, :content_counter
    has_many :chapters

    def chapters
       object.chapters.active.with_counter(???)
    end
end

In my chapter model I have a scope:
scope :with_counter, lambda { |counter| where("content_counter >?", counter.to_i) }

How can I pass the counter value 123 into (???)
Is that possible?
Any help would be greatly appreciated.

A: You can pass values to an activemodel serializer using the @options object like this:
class Api::CategoriesController <  ApplicationController
  respond_to :json
  def index
    respond_with Category.where("name ==? AND content_counter >?", params[:name], params[:counter].to_i),
                 counter_value: params[:counter]
  end
end

class CategorySerializer < ActiveModel::Serializer
  attributes :id, :name, :content_counter
  has_many :chapters

  def chapters
     object.chapters.active.with_counter(@options[:counter_value])
  end
end


text:
Q: Not able to grab 3D models in oculus I am working on a unity oculus project in which I need to instantiate a 3D Models and interact with them by using Oculus Grabables with my hand.
Here, the 3D models are not asset bundles as it is instantiates from Database.
Here I have used TriLib 2 as a third party library to load asset from database.
The problem arises here is that 3D modles are perfectly instantiated in my scene but I am not be able interact with them with oculus.
I have made a custom script in which I am adding required components of oculus to grab that instantiated 3D models.
At last I am not be able to grab that 3D models.
Can you please help me to get out of this..?


text:
Q: Returned error when trying to install Paperclip gem - Ruby-on-Rails I'm going through a Youtube tutorial to install the Paperclip gem on my site. Got to the last step but its returning the following error, not sure where I'm going wrong..
Error -
NoMethodError in Houses#index
undefined method `image' for nil:NilClass
<%= image_tag @house.image.url(:medium) %>

When it comes to including the code to display the image in my index.html.erb so I've put in:
<%= image_tag @house.image.url(:medium) %>

as the tutorial instructed but its doesn't like that & returns an error when I've uploaded the image and refreshed my index page to view the image.
Does anybody have any idea where I'm going wrong?
All relevant code is as follows:
index.html.erb -

<%= link_to "Add a House", new_house_path %>

<% @houses.each do |house| %>

<%= image_tag @house.image.url(:medium) %>

<%= house.title %>

£<%= house.price %>

<%= house.description %>

<% end %>

house.rb -
class House < ActiveRecord::Base
validates :title, presence: true
validates :price, presence: true
validates :description, presence: true
validates :image, presence: true

has_attached_file :image, styles: { large: "600x600", medium: "300x300", thumb: "150x150#" }
validates_attachment_content_type :image, content_type: /\Aimage\/.*\Z/
end

new.html.erb
<%= simple_form_for @house, html: { multipart: true } do |form| %>
<%= form.input :title, label: "House title" %>
<%= form.input :price, label: "House price" %>
<%= form.input :description, label: "Describe your house" %>
<%= form.input :image, as: :file, label: "Image of house" %>
<%= form.button :submit %>
<% end %>

houses.controller.erb -
class HousesController < ApplicationController
def index
  @houses = House.page(params[:page]).per(20).order(created_at: :desc)
end

def new
  @house = House.new
end

def create
  @house = House.new(params.require(:house).permit(:title, :price, :description, :image))
  if @house.save
    redirect_to root_path
  else
    render "new"
  end
end

end


text:
Q: Java Date format and JSON - Object in Debugger shows another format than toString() I have a problem with DATE format and sending it (as an attribute from an entity named thesisDTO) via REST-Webservice (JSON).

I want to call a webservice method (POST-request) which excepts a DATE in the following format:
{   ...
"proposalDate":"Feb 17, 2022 7:50:09 AM" }

If I create a DATE variable with the following code, the method "toString()"gives me the right format:
Date currentDate = new Date();
IsyMNDLogger.getLogger().info("Date To String: "+currentDate.toString());

But if I add currentDate to my object thesisDTO with:
thesisDTO.setProposalDate(currentDate);

With the debugger I can see that the format is changed to: "Wed Feb 16 10:49:28 CET 2022" and my webservice request cannot read it.

Converting the thesisDTO to JSON and sending the request I do with the following code (javax.ws.rs):
Client restclient = ClientBuilder.newClient();
WebTarget target = restclient.target(url);
String response = target.request(MediaType.APPLICATION_JSON)
                .accept(MediaType.TEXT_PLAIN_TYPE)
                .post(Entity.json(thesisWebServiceDTO), String.class);

Has anyone an idea why the format is different and how I can change it? I can not use SimpleDateFormatter to change because that is only for displaying another format I think.
Thanks a lot,
Nicole

A: First of all, Debugger displays date in whatever format its configured and has nothing to do with how you format your date. Date internally is stored as long value that holds the number of milliseconds since midnight of Jan 1, 1970 and and it doesn't hold any formatting info. If you format your date into a string and look at it in the debugger than you will see it exactly in the way you formatted your date. Now, for your issue, first of all please stop using class Date and even more so SimpleDateFormat they are definitely outdated (pun intended). Please look at java.time package and the classes that you should be using are DateTimeFormatter and TemporalAccessor interrface implementations such as ZonedDateTime,  OffsetDateTime LocalDateTime or any other that might fit your needs. As for a date field in your DTO annotate it like this:
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ss.SSSZ")
ZonedDateTime proposalDate;

For more details look at the great answer for this question: Spring Data JPA - ZonedDateTime format for json serialization


text:
Q: mysql - php - Need to get only the latest record from a self referencing data
Hi,
I need some help with SQL. Attached is the image of my table.
If you see rootmessageid column there are 4 records of 99s. All these 4 makes one complete conversation.
Similarly the 2 records of 119 makes an other conversation.
116, 117, 118 are single message conversation.
Now I need to get all the records where msgfrom = 7 or msgto = 7 (this was the easy part)
Now the complicated bit. I want the only the latest record (based on datetimecreated) from each conversation.
Following the script to create this table.
CREATE TABLE IF NOT EXISTS `selectioncommunication` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `comactionid` int(11) NOT NULL,
  `usercomment` varchar(2048) DEFAULT NULL,
  `msgfrom` int(11) NOT NULL,
  `msgto` int(11) NOT NULL,
  `projectid` int(11) NOT NULL,
  `parentmessageid` int(11) NOT NULL,
  `datetimecreated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `rootmessageid` int(11) NOT NULL,
  `isread` tinyint(1) NOT NULL DEFAULT '0',
  `isclosed` tinyint(1) DEFAULT '0',
  `relative_date_time` datetime DEFAULT NULL,
  `consultant_response` tinyint(4) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=121 );

A: use ORDER BY datetime ASC/DESC
this will sort your results in order then add LIMIT 1 to the end of your query to only get the first record in your list.

A: You want the groupwise maximum:
SELECT s.*
FROM   selectioncommunication s NATURAL JOIN (
  SELECT   parentmessageid, MAX(datetimecreated) datetimecreated
  FROM     selectioncommunication
  WHERE    msgfrom = 7 OR msgto = 7
  GROUP BY parentmessageid
) t
WHERE  s.msgfrom = 7 OR s.msgto = 7

A: Here is your SQl Fiddle without Join
SELECT *
FROM selectioncommunication k
WHERE datetimecreated = (SELECT
                           MAX(datetimecreated)
                         FROM selectioncommunication s
                         WHERE s.rootmessageid = k.rootmessageid
                         GROUP BY s.rootmessageid
                         ORDER BY s.id)


text:
Q: Set an ItemClickListener on FragmentStatePagerAdapter I have implemented a ViewPager with FragmentStatePagerAdapter and i want an ItemClickListener so that i can open the detail screen when the user clicks on each fragment of the viewpager. I am not able to find any such methods which are available.

A: You should implement a callback interface to communicate between your fragments and your containing activity. In each fragment, set your needed listeners, and then pass any information needed back to your activity to handle the click.
public class MyFragment extends Fragment {
    public interface MyFragmentListener {
        void onTheActivityICareAbout();
    }

    private MyFragmentListener mCallback;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);

        try {
            mCallback = (MyFragmentListener) context;
        } catch (ClassCastException e) {
            throw new ClassCastException(context.toString()
                + " must implement MyFragmentListener");
        }
    }
}

Then when you bind your view, set your listner to use the callback on whatever event you need and your activity has your centralized code to handle that. Any interface method can also be used to pass data back to the activity as well.
You can see this link for more details.

A: Your FragmentStatePageAdapter will have a method that looks like this:
override fun getItem(day: Int): Fragment = YourPageFrament.newInstance()
So, in the code for YourPageFragment, you can set on OnClickListener on the fragment itself.
You can set this listener by modifying the XML layout file for that fragment to include a Linear Layout or some kind of layout.
Then, in your YourPageFragment class, possibly in your onCreateView() method, you can set on OnClickListener on the fragment's layout.


text:
Q: QScreenRayCaster not finding entity. What am I doiong wrong? The description of the new QScreenRayCaster in Qt3D looks like its exactly what I want to use, but I cannot get it to work for me. I guess that there is something I need to do in the initialization but I cannot find any examples online to point me in the right direction. I've written a very simple program to test the function. It draws a unit sphere in the center of a window and then triggers a QScreenRayCaster at the center point which as far as I can see should then return a list of hits, only in my program it doesn't. Any help or insight appreciated.
MyQt3DWindow:: MyQt3DWindow(QScreen *screen)
    : Qt3DExtras::Qt3DWindow(screen)
{
    // scene
    Qt3DCore::QEntity *rootEntity = new Qt3DCore::QEntity;
    Qt3DRender::QMaterial *material = new Qt3DExtras::QPhongMaterial(rootEntity);
    Qt3DCore::QEntity *sphereEntity = new Qt3DCore::QEntity(rootEntity);
    Qt3DExtras::QSphereMesh *sphereMesh = new Qt3DExtras::QSphereMesh;
    sphereEntity->addComponent(sphereMesh);
    Qt3DCore::QTransform *sphereTransform = new Qt3DCore::QTransform;
    sphereEntity->addComponent(sphereTransform);
    sphereEntity->addComponent(material);

    // Camera
    Qt3DRender::QCamera *camera = this->camera();
    camera->lens()->setOrthographicProjection(-2, 2, -2, 2, 0.1f, 1000.0f);
    camera->setPosition(QVector3D(0, 0, 40.0f));
    camera->setViewCenter(QVector3D(0, 0, 0));

    // picker
    m_screenRayCaster = new Qt3DRender::QScreenRayCaster(rootEntity);
    m_screenRayCaster->setRunMode(Qt3DRender::QAbstractRayCaster::SingleShot);
    Qt3DRender::QLayer *pickableLayer = new Qt3DRender::QLayer(rootEntity);
    m_screenRayCaster->addLayer(pickableLayer);
    sphereEntity->addComponent(pickableLayer);

    this->setRootEntity(rootEntity);
    this->setGeometry(100, 100, 400, 400);

    // and call the caster after a short delay
    QTimer::singleShot(1000, this, SLOT(testRayCaster()));
}

void MyQt3DWindow::testRayCaster()
{
    m_screenRayCaster->trigger(QPoint(200, 200));
    Qt3DRender::QAbstractRayCaster::Hits hits = m_screenRayCaster->hits();
    qDebug() << "Hits found = " << hits.size() << "\n";
}

class MyQt3DWindow: public Qt3DExtras::Qt3DWindow
{
Q_OBJECT
public:
    MyQt3DWindow(QScreen *screen = nullptr);

public slots:
    void testRayCaster();

private:
    Qt3DRender::QScreenRayCaster *m_screenRayCaster;
};

A: You have to add the ray caster to the root entity as a component. You should also connect a slot to the ray caster's hitsChanged() function and display the hits from there. This way you can be sure that the caster computed the hits already.
By the way: If you have issues with Qt3D, checkout their github repository and look for the test folder. There is a folder inside with manual tests where you can see most of the functioning of Qt3D.

A: For people who stumble across this question when trying to get the screen caster to work, in addition to the accepted answer:
If you would like to the intersection to be carried out for all entities, you need to set the QLayer as a component of the root, and then set it as recursive. (Instead of setting it to sub entities individually, like sphereEntity in the question).
_rayCaster = new QScreenRayCaster(_rootEntity);
_rayCaster->setRunMode(QAbstractRayCaster::SingleShot);

auto pickableLayer = new QLayer(_rootEntity);
pickableLayer->setRecursive(true);
_rootEntity->addComponent(pickableLayer);

_rayCaster->addLayer(pickableLayer);
_rootEntity->addComponent(_rayCaster);
connect(_rayCaster, &QScreenRayCaster::hitsChanged, this, &SceneWidget::onRayCastResult);


text:
Q: Max and min record from database using Entity Framework Core I have a simple method that return rage of data from db according to some parameters, and it is simple:
public async Task<IEnumerable<P2PStats>> GetFilteredNetStats(ushort id, ushort remoteId, DateTime start, DateTime end)
{
    using (var ctx = new DataContext())
    {
        IQueryable<P2PStats> query = ctx.P2PStats
             .Where(stat => stat.Id == id && stat.Date >= start && stat.Date <= end)
             .Where(stat => stat.P2PStatsDetailed.Any(detail => detail.RemoteId == remoteId))
             .Select(stat => new P2PStats
             {
                 Id = stat.Id,
                 AxmCardId = stat.Id,
                 Date = stat.Date,
                 P2PStatsDetailed = stat.P2PStatsDetailed.Where(detail => detail.RemoteId == remoteId).ToList()
             });

        return await query.ToListAsync();
    }
}

It returns collection of P2PStats(well actually a task but in final result a collection). Can this be modified so that I can get only 2 values from database first with lowest date second with highest?
I tried Max and Min but only after the query has been materialized and I end up with max and min value or property not whole record.

A: This problem can be solved by the removal of filtering by Id and the addition of the method.Max() and .Min() to your code.
Below is an example of how this would look:
 public async Task<IEnumerable<P2PStats>> GetNetStatsLowestAndHighestDate(ushort id, ushort remoteId, DateTime start, DateTime end)
{
    using (var ctx = new DataContext())
    {
        IQueryable<P2PStats> query = ctx.P2PStats
             .Where(stat => stat.Date >= start && stat.Date <= end)
             .Where(stat => stat.P2PStatsDetailed.Any(detail => detail.RemoteId == remoteId))
             .DefaultIfEmpty(0)
             .Max(s => s.Date)

             .Select(stat => new P2PStats
                                        {
                                            Id = stat.Id,
                                            AxmCardId = stat.Id,
                                            Date = stat.Date,
                                            P2PStatsDetailed = stat.P2PStatsDetailed.Where(detail => detail.RemoteId == remoteId).ToList()
                                        });

        IQueryable<P2PStats> query2 = ctx.P2PStats
             .Where(stat => stat.Date >= start && stat.Date <= end)
             .Where(stat => stat.P2PStatsDetailed.Any(detail =>
        detail.RemoteId ==
        remoteId))
             .DefaultIfEmpty(0)
             .Min(s => s.Date)

             .Select(stat => new P2PStats
                                        {
                                            Id = stat.Id,
                                            AxmCardId = stat.Id,
                                            Date = stat.Date,
                                            P2PStatsDetailed =
        stat.P2PStatsDetailed.Where(detail => detail.RemoteId == remoteId).ToList()
                                        });

        var results = query1.Concat(query2);

        return await results.ToListAsync();

    }
}

A: i assume you have records for the same ID. just created a linqpad example (i was not sure if you want list of min value, max value rows or just min and max)
the approach would be to group on same field (propably on ID) and pick min, max
void Main()
{
    test t = new test();
    var l = new List<test>() {
        new test() {ID = 0, a1="aaa", a2 = 10},
        new test() {ID = 1, a1="aaa", a2 = 40},
        new test() {ID = 2, a1="aaa", a2 = 70},
        new test() {ID = 3, a1="aaa", a2 = 50},
        };

    l.Dump("original");
    l.GroupBy(g => g.a1).Select(s => new { max = s.Max(mm => mm.a2), min = s.Min(mi => mi.a2) }).Dump("return 2 values");

    List<test> lRes = new List<test>();
    lRes.Add(l.OrderBy(o => o.a2).First());
    lRes.Add(l.OrderBy(o => o.a2).Last());
    lRes.Dump("return table of min record and max record");

}

public class test
{
    public int ID { get; set; }
    public string a1 { get; set; }
    public int a2 { get; set; }
    public test() { }
}


text:
Q: Knapsack problem: Optimal fair division of items in limited quantity, between Knapsacks with unlimited capacity I am looking for a solution to the following Knapsack problem:

*

*Dynamic programming and not naive programming, in C++

*For each item, weight and value are equal, meaning no two arrays are needed, but only one. Therefore we will refer to weights only.

*There are three knapsack. All of them have no capacity weight limit, which means that all the items must be taken, but also the distribution between the bags must be as fair as possible (optimal).

Attached is a solution I wrote for the above problem with two knapsacks. It works properly, but long and complicated. For three knapsack I got completely entangled.
I would be happy, but not necessary:

*

*A simpler solution than what I wrote

*If there is a solution for the unlimited amount of knapsack (of course must meet all the above conditions
)

*As in my solution, print which items will be in each bag (In addition to the weight difference between the knapsacks)

I know and apologize. The explanation for the solution I wrote is long. I will explain it, but there is no need for the solution I am asking for to be necessarily similar to what I wrote.
Explanation of the solution I wrote:
Each cell of the table has a pair of numbers - the first knapsack and the second knapsack.
The columns represent all possible weights from 0 to the total weight of all the items. The rows represent the weight of each item.
In each cell we want to fill in the table, we will see if there are two options:

*

*If there a cell above it

*If it is possible to step back from it (left) the amount of cells as the amount of weight represented in the current row and then go up one cell up

From the above existing options, we will select the maximum weight of the first knapsack and place it in the current cell in the first knapsack. In the second knapsack of the current cell we will set the difference.
Then, if the weight in the current cell can be added to the first knapsack, without the addition exceeding the weight represented by the current column we will add, otherwise we will add the weight to the second knapsack.
In the last line we will find the optimal solution, according to the pair of numbers with the lowest difference between them. From that cell we can step back and find out how the optimal solution was obtained.
My C++ code solution for two knapsacks
#include <bits/stdc++.h>
using namespace std;

// 2 knapsacks
int *items_arr,
    items_num,
    ***knapsacks_arr, // [row][col][knapsack]
    rows,
    cols;

void allocate_knapsacks_arr()
{
    knapsacks_arr = new int **[rows];
    for (int r = 0; r < rows; r++)
    {
        knapsacks_arr[r] = new int *[cols];
        for (int c = 0; c < cols; c++)
            knapsacks_arr[r][c] = new int[2]; // 2 knapsacks
    }
}

void delete_knapsacks_arr()
{
    for (int r = 0; r < rows; r++)
    {
        for (int c = 0; c < cols; c++)
            delete[] knapsacks_arr[r][c];
        delete[] knapsacks_arr[r];
    }
    delete[] knapsacks_arr;
}

void initialize_knapsacks_arr()
{
    knapsacks_arr[0][0][0] = 0;
    knapsacks_arr[0][0][1] = 0;
    for (int c = 1; c < cols; c++)
    {
        knapsacks_arr[0][c][0] = INT_MAX;
        knapsacks_arr[0][c][1] = INT_MAX;
    }

    int sum_items = 0,
        index_items = 0;
    for (int c, r = 1; r < rows; r++)
    {
        for (c = 0; c <= sum_items + items_arr[index_items]; c++)
        {
            // set knapsacks1
            int k1_up = knapsacks_arr[r - 1][c][0];
            int k1_left = INT_MAX;
            if (c >= items_arr[index_items])
                k1_left = knapsacks_arr[r - 1][c - items_arr[index_items]][0];

            // if no up and no left
            if (k1_up == INT_MAX && k1_left == INT_MAX)
                knapsacks_arr[r][c][0] = 0;

            // if only up
            if (k1_up != INT_MAX && k1_left == INT_MAX)
                knapsacks_arr[r][c][0] = k1_up;

            // if only left
            if (k1_up == INT_MAX && k1_left != INT_MAX)
                knapsacks_arr[r][c][0] = k1_left;

            // if up and left
            if (k1_up != INT_MAX && k1_left != INT_MAX)
            {
                if (k1_up > k1_left)
                    knapsacks_arr[r][c][0] = k1_up;
                else
                    knapsacks_arr[r][c][0] = k1_left;
            }

            // set knapsacks2
            knapsacks_arr[r][c][1] = sum_items - knapsacks_arr[r][c][0];

            // add item
            if (c >= knapsacks_arr[r][c][0] + items_arr[index_items])
                knapsacks_arr[r][c][0] += items_arr[index_items];
            else
                knapsacks_arr[r][c][1] += items_arr[index_items];
        }
        for (; c < cols; c++)
        {
            knapsacks_arr[r][c][0] = INT_MAX;
            knapsacks_arr[r][c][1] = INT_MAX;
        }
        sum_items += items_arr[index_items];
        index_items++;
    }
}

void show_knapsacks_arr()
{
    cout << "\t";
    for (int c = 0; c < cols; c++)
        cout << c << "\t";
    cout << endl;

    for (int r = 0; r < rows; r++)
    {
        if (r > 0)
            cout << items_arr[r - 1];
        cout << "\t";

        for (int c = 0; c < cols; c++)
        {
            cout << "(";
            if (knapsacks_arr[r][c][0] == INT_MAX) // == numeric_limits<int>::max()
                cout << "-";                       // static_cast<unsigned char>(236);
            else
                cout << knapsacks_arr[r][c][0];
            cout << ", ";
            if (knapsacks_arr[r][c][1] == INT_MAX)
                cout << "-"; // static_cast<unsigned char>(236);
            else
                cout << knapsacks_arr[r][c][1];
            cout << ")\t";
        }
        cout << endl;
    }
    cout << endl;
}

int items_sum()
{
    int sum = 0;
    for (int i = 0; i < items_num; i++)
        sum += items_arr[i];
    return sum;
}

void show_optimal_solution(int r, int c)
{
    int index_items = items_num;

    cout << "Dynamic (2D array)" << endl
         << "optimal difference = " << abs(knapsacks_arr[r][c][0] - knapsacks_arr[r][c][1]) << endl
         << "knapsack 1 total weight of all items = " << knapsacks_arr[r][c][0] << endl
         << "knapsack 2 total weight of all items = " << knapsacks_arr[r][c][1] << endl;

    while (true)
    {
        cout << endl
             << "item number " << index_items << ", weight = " << items_arr[index_items - 1] << ", indexes = (" << r << ", " << c << ") >> ";
        if (r == 1)
        {
            if (c < items_arr[0])
                cout << "knapsack 2";
            else
                cout << "knapsack 1";
            cout << endl
                 << endl;
            return;
        }
        if (knapsacks_arr[r][c][0] == knapsacks_arr[r - 1][c][0])
        {
            cout << "knapsack 2";
            r--;
            index_items--;
        }
        else
        {
            cout << "knapsack 1";
            r--;
            c -= items_arr[index_items - 1];
            index_items--;
        }
    }
}

void find_optimal_solutions()
{
    // find minimum difference between each pair knapsacks in last row
    int optimal = INT_MAX,
        index = 0;
    for (int c = 0; c < cols; c++)
    {
        int tmp = abs(knapsacks_arr[rows - 1][c][0] - knapsacks_arr[rows - 1][c][1]);
        if (optimal > tmp)
        {
            optimal = tmp;
            index = c;
        }
    }
    show_optimal_solution(rows - 1, index); // only first solution

    // find all same differences in last row = additional solutions
    // for (int c = 0; c < cols; c++)
    //  if (optimal == abs(knapsacks_arr[rows - 1][c][0] - knapsacks_arr[rows - 1][c][1]))
    //      show_optimal_solution(rows - 1, c);
}

int main()
{
    items_arr = new int[]{7, 3, 1, 6};
    items_num = 4;

    rows = items_num + 1;
    cols = items_sum() + 1;

    allocate_knapsacks_arr();
    initialize_knapsacks_arr();
    show_knapsacks_arr();
    find_optimal_solutions();
    delete_knapsacks_arr();
    delete[] items_arr;

    return 0;
}

Input

weights 7, 3, 1, 6
Output

first knapsack: 1, 7

second knapsack: 6, 4
        0       1       2       3       4       5       6       7       8       9       10      11      12      13      14      15      16      17
        (0, 0)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)
7       (0, 7)  (0, 7)  (0, 7)  (0, 7)  (0, 7)  (0, 7)  (0, 7)  (7, 0)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)
3       (0, 10) (0, 10) (0, 10) (3, 7)  (3, 7)  (3, 7)  (3, 7)  (7, 3)  (3, 7)  (3, 7)  (10, 0) (-, -)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)
1       (0, 11) (1, 10) (1, 10) (3, 8)  (4, 7)  (4, 7)  (4, 7)  (7, 4)  (8, 3)  (4, 7)  (10, 1) (11, 0) (-, -)  (-, -)  (-, -)  (-, -)  (-, -)  (-, -)
6       (0, 17) (1, 16) (1, 16) (3, 14) (4, 13) (4, 13) (4, 13) (7, 10) (8, 9)  (4, 13) (10, 7) (11, 6) (10, 7) (13, 4) (14, 3) (10, 7) (16, 1) (17, 0)

Dynamic (2D array)
optimal difference = 1
knapsack 1 total weight of all items = 8
knapsack 2 total weight of all items = 9

item number 4, weight = 6, indexes = (4, 8) >> knapsack 2
item number 3, weight = 1, indexes = (3, 8) >> knapsack 1
item number 2, weight = 3, indexes = (2, 7) >> knapsack 2
item number 1, weight = 7, indexes = (1, 7) >> knapsack 1


text:
Q: Access other properties of selected Listbox item I have searched and searched for an answer to this problem. I thought I came close by finding this post:
Get object information of selected listbox item
But I keep getting a an "invalid cast exception" error at this part in the code:
string m = ((Customer)LBox.SelectedItem).ID;

Here is most of my code thus far, where I add the listbox items from a Dataclass (linq to SQL). Where I am stuck is that I'd like to get the DB_ID of the record that I have selected in the Listbox.
I have a workaround where I can do another SQL query on the DB with the customer's name that is the LBox.SelectedItem value, but i figure I must be doing something wrong to not be able to cast the SelectedItem value back to Customer to get the ID?
I am just starting out in C# and know practically nothing, so any help would be much appreciated.
DataClasses1DataContext dc = new DataClasses1DataContext(Properties.Settings.Default.DBConnectionString);

public MainWindow()
{
    InitializeComponent();
    var q = from accts in dc.Customers where accts.SysStatus == "Active" orderby accts.Customer select accts;

    if (dc.DatabaseExists())
        foreach (Customer c in q)
            LBox.Items.Add(c.Customer);
}

public void LBox_SelectionChanged (object sender, SelectionChangedEventArgs e)
{
    lblComp.Content = LBox.SelectedItem;
    string m = ((Customer)LBox.SelectedItem).ID;
}

I think @Boxed help me out here.
I modified the code as follows:
foreach (Surgeon c in q)
   LBox.Items.Add(c);
   LBox.DisplayMemberPath = "Customer";

Then I was able to obtain the values from the Customers Class as such:
string m = ((Customers)LBox.SelectedItem).ID;
lblComp.Content = ((Customers)LBox.SelectedItem).Customer;
txtDetails.Text = m;

Is this code ideal, or should I be doing something else?


text:
Q: Word for 'when someone perceives life as a game' I've heard of the Tetris effect, which is essentially the same thing with the difference being that the brain does it subconsciously.
The word I'm looking for is when someone knowingly pretends life is a game to do things in a gamified manner.
For example: If someone thinks that they are speedrunning a task in life, they do it quickly and hastily as if in a game.
Is there any similar word if there isn't any?

A: Not a noun but for such kind of person, I would use flippant or frivolous.
The action of perceiving life as a game could be described as frivolity.

Frivolity: behaviour that is silly and not serious, or things that are silly and not important. [Cambridge English dictionary]

Example: They should not treat their life with frivolity.
In your example, you could say:

If someone thinks that they are speedrunning a task in life, they do it frivolously.

Light-minded or skittish are also possible. (Is it self-gamification?)

A: I can't think of a good noun for this, but I wonder if some kind of metaphor or simile might work?
e.g. "The world is her Playstation, and it's game over for anyone in the way", "If the street were a screen, he'd be Pacman", "Each day was a like new level of Super Mario Bros, harder than the last, yet he had always found his princess by sunset"....
(I'm out of touch with the culture, so forgive the dated ideas!)

A: You've already used a form of the right word—they are "gamifying" their life:

to make an activity more like a game in order to make it more interesting or enjoyable:
Is gamifying the news the future?

Usually we see it used as "gamification", but "gamify" is valid. Forbes uses "gamify" in the title of an article, and includes "Gamifying the workplace" as a section within it:
Gamify Your Life and Become Massively Successful


text:
Q: How do I restore compiz advanced zoom? I lost compiz zoom due to some incompatibility that I am not sure about. I read about a fix before, but I forgot what it is. When I try to zoom with the super key and mouse it just vibrates the cursor.
After further testing to find the problem, I know it has to be something that is trying to put the pointer to the centre of the screen. Hopefully someone will be able to track down the cause, because so far I cannot.
EDIT - I've tried all kinds of options, including resetting all the settings on the plugin, still no change. I can't zoom, even if I change the keys. If it helps, restraining the mouse to the zoom area makes it jump to one side of the screen.
Could it be that I have dual outputs that is causing the problem?

A: This is caused by a bug when using dual monitors. As far as I know the only current fix is to unplug a monitor. You may be able to get it working by editing the General options in ccsm to not autodetect outputs and instead manually specify your monitors' sizes and positions.

A: If you're also using the desktop cube, make sure you have "multiple cubes" selected in the desktop cubes "Multi Output Mode" list.


text:
Q: Which is the correct way to use System.Convert.ToInt64 function? I have following code:
 Dim len As Int32 = 1000
 Dim rdlen As Int64 = 2000000000000
 Dim totlen As Int64

Which example is the correct way to use System.Convert.ToInt64 function?
Example one:
 totlen = System.Convert.ToInt64(rdlen + len)

Example two:
 totlen = rdlen + System.Convert.ToInt64(len)

A: Both expressions will evaluate to the same thing.
There is an implicit conversion between Int32 and Int64, so even the following works:
totlen = rdlen + len

A: I think both examples are correct. At least in c#.
When A and B is of different integer type, compiler should convert both of them to the same type in order to do A+B. So it converts both to Int64 before computing A+B.

A: It works either way, and it works without the conversion also, as the 32 bit integer will be widened to work with the 64 bit integer.
You shouldn't use the Convert class to do such conversion anyway, you should just use the cast syntax.
If you want to show in the code exactly what's happening, or if you want to make sure that it really happens the way you indend it, you cast the 32 bit integer to 64 bits before the addition:
totlen = rdlen + (Int64)len;

It will however produce the exact same code as this, as the 32 bit integer will be implicitly converted:
totlen = rdlen + len;


text:
Q: NSwag default accept response to application/json I'm using NSwag with an Asp.Net Core API. I would like to change the default accepted response from application/octet-stream to application/json.

I tried adding Response attribute to the API action and also the OpenApiMimeType but did not work. It is still set to application/octet-stream. How do I change this?
Update:
Here is one of the actions for the API.
[HttpPost("login")]
public async Task<ActionResult> Login(LoginDto dto, string returnUrl = null)
{
    //... omitted codes for brevity

    return Ok();
}

A: Using the Produce attribute (https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.producesattribute) should help you achieve this.
[HttpPost("login")]
[Produces("application/json")]
public async Task<ActionResult> Login(LoginDto dto, string returnUrl = null)
{
    //... omitted codes for brevity

    return Ok();
}

In your swagger.json it should produce something like this: Swagger.json - 1
The other reason is because you are using Task<ActionResult> so your swagger.json isn't producing a content type due to this reason.
[HttpPost("login")]
[Produces("application/json")]
public async Task<ActionResult<return something>> Login(LoginDto dto, string returnUrl = null)
{
    //... omitted codes for brevity

    return Ok(return something);
}


text:
Q: How to create this user control? I have to develop a small app for which I have to create a user control which is intended to be something like a Table View.
On Form Load, the user should be asked about the number of rows of columns required on the form.
Once the user sets the number of cells, each cell should have a button and a Text Box inside it (grouped together). Please help me in creating the User Control. I am still a new learner.
Thanks!

A: The DataGridView built-in class in the .NET Framework will display a grid with a text box that can be edited by a user.  To display an image you'll need to derive your our DataGridViewCell and write all the drawing and handling code to customize the cell.  You can see this example for how to do that:
http://www.codeproject.com/KB/grid/DGV_ImageButtonCell.aspx
Another option would be to use a TableLayoutPanel.  After the user specifies the number of rows and columns, you could create the TableLayoutPanel then iterate through each cell to add the appropriate control.
Each cell can only have 1 control so you'd have to make two columns to put a button and textbox next to each other.


text:
Q: Alternative to using 'order' within an array I've been doing some edits to an output when working with some records and i've ran into a problem where the sorting option no longer is working.
Initially with how things were created when I would do a @record.class the output was Record::ActiveRecord_Relation < ActiveRecord::Relation
However now after making my changes the class has changed. So now when I run a @record.class the output is Array < Object.
I think this is the root reason why i've ran into this problem.
My code is
@q = @records.search(params[:q])
@records = @q.result(distinct: true).select { |k,_v| k[:disabled] }
@records = @records.order("records.updated_at desc").page(params[:page] || 1).per(params[:per] || 30)

The error I am getting is NoMethodError: undefined methodorder' for #`
Now i've tried to workout around this by
@records = @records.sort_by("records.updated_at desc")
@records = @records.paginate.page(params[:page] || 1).per(params[:per] || 30)

However the error with the first line of my solution is @records = @records.sort_by("records.updated_at desc")  I'm not able to get past that line in case there is an error with my paginate solution.
If anyone could take a look, I would really appreciate it!

A: your @records is a Ruby array, not an ActiveRecord "array"
You can try @records.sort_by(&:updated_at) to sort your array

A: The issue is that you are calling result, which is causing the SQL query to be executed and data returned from the database. You don't want to do that if you want to continue forming your query using the Arel AST that ActiveRecord uses. You want something closer to this (you'll likely need to adapt):
r = records.where(some_param: some_value, disabled: true) \
           .order(updated_at: :desc) \
           .page(params[:page] || 1).per(params[:per] || 30)

A: The signature you the methods you use look like you are using ransack.
Instead of loading all records into memory and selecting matching records in Ruby it might be much faster to only load matching records from database in the first place.
Assuming that disabled is a boolean column in your database, I would advise to change
@q = @records.search(params[:q])
@records = @q.result(distinct: true).select { |k,_v| k[:disabled] }
@records = @records.order("records.updated_at desc").page(params[:page] || 1).per(params[:per] || 30)

to
@q = @records.where(disabled: true).search(params[:q])
@records = @q.result(distinct: true)
@records = @records.order("records.updated_at desc").page(params[:page] || 1).per(params[:per] || 30)


text:
Q: Why cant Eloquent in my App Engine app connect to my Google SQL instance? Oddly enough, I can connect to my Google SQL instance from PHPStorm's database tool, just can't seem to connect locally when deployed.
And when I develop locally - my app connects to my local stack instance (docker) fine using the environment variables below.
Here's my app.yaml
runtime: php72
api_version: 1

handlers:
- url: /.*
  script: public/index.php

env_variables:
  MYSQL_DSN: "mysql:unix_socket=/cloudsql/project:location:sql-instance;dbname=databaseName"
  MYSQL_USER: "username"
  MYSQL_PASSWORD: "password"

runtime_config:
  enable_stackdriver_integration: true

And here's how I'm initializing this in Eloquent / Illuminate.
    use Illuminate\Database\Capsule\Manager;

    $db = [];
    if(getenv("MYSQL_DSN")){
        $db = [
            'driver' => 'mysql',
            'dsn' => getenv("MYSQL_DSN"),
            'username' => getenv("MYSQL_USER"),
            'password' => getenv("MYSQL_PASSWORD"),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ];
    } else if(getenv("MYSQL_HOST")){
        $db = [
            'driver' => 'mysql',
            'host' => getenv("MYSQL_HOST"),
            'database' => getenv("MYSQL_DATABASE"),
            'username' => getenv("MYSQL_USER"),
            'password' => getenv("MYSQL_PASSWORD"),
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
        ];
    }

    $settings = [
            // Slim Settings
            'determineRouteBeforeAppMiddleware' => false,
            'displayErrorDetails' => true,
            'db' => $db
        ];

    $container = $this->getContainer();
    $capsule = new Manager;
    $capsule->addConnection($settings['db']);

    $capsule->setAsGlobal();
    $capsule->bootEloquent();

A: Does your Cloud SQL instance allow connections from where you're testing? Check the authorized networks under the authorization tab on your SQL instance page in the GCP Console.
If unsure, you can try adding 0.0.0.0/0 to test allowing all IPv4 connections. Turn back off later to prevent unauthorized direct DB connections.


text:
Q: Need to resolve dependencies for installation I'm trying to install librhythmbox-core8 but when I run the commands it fails.
apt-get install
Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these.
The following packages have unmet dependencies:
 gir1.2-rb-3.0 : Depends: librhythmbox-core8 (>= 3.0.1) but it is not installed
 rhythmbox : Depends: librhythmbox-core8 (= 3.0.1-1ubuntu2~ppa0) but it is not installed
 rhythmbox-plugin-cdrecorder : Depends: librhythmbox-core8 (>= 3.0) but it is not installed
 rhythmbox-plugins : Depends: librhythmbox-core8 (= 3.0.1-1ubuntu2~ppa0) but it is not installed
E: Unmet dependencies. Try using -f.

apt-get -f install
Reading package lists... Done
Building dependency tree
Reading state information... Done
Correcting dependencies... Done
The following packages were automatically installed and are no longer required:
  gir1.2-gconf-2.0 gir1.2-zeitgeist-2.0 python3-mako python3-markupsafe rhythmbox-plugins
Use 'apt-get autoremove' to remove them.
The following extra packages will be installed:
  librhythmbox-core8
The following NEW packages will be installed:
  librhythmbox-core8
0 upgraded, 1 newly installed, 0 to remove and 0 not upgraded.
6 not fully installed or removed.
Need to get 0 B/816 kB of archives.
After this operation, 1,825 kB of additional disk space will be used.
Do you want to continue [Y/n]? y
(Reading database ... 259967 files and directories currently installed.)
Unpacking librhythmbox-core8 (from .../librhythmbox-core8_3.0.1-1ubuntu2~ppa0_i386.deb) ...
dpkg: error processing /var/cache/apt/archives/librhythmbox-core8_3.0.1-1ubuntu2~ppa0_i386.deb (--unpack):
 trying to overwrite '/usr/lib/librhythmbox-core.so.8.0.0', which is also in package librhythmbox-core7 3.0.1-0~13.10~ppa1
dpkg-deb: error: subprocess paste was killed by signal (Broken pipe)
Errors were encountered while processing:
 /var/cache/apt/archives/librhythmbox-core8_3.0.1-1ubuntu2~ppa0_i386.deb
E: Sub-process /usr/bin/dpkg returned an error code (1)

Can someone help me fix this?

A: The problem is because you have two versions of the rhythmbox package.
librhythmbox-core7 is installed on your system, and you're trying to install librhythmbox-core8.
You need to manually remove librhythmbox-core7 before you can install librhythmbox-core8.

sudo dpkg --remove librhythmbox-core7
sudo apt-get install librhythmbox-core8