text:
Q: How to pass cloud firestore field value to new variable in node js? I have new variable called var lat and var long in index.js. For getting firebase value, I have used this code
  var lat;
  var long;

 var cityRef =
db.collection('UsersCurrentBookings').doc('3Xg6ujHMINeElzdOD3JypcZBMHw2');
var getDoc = cityRef.get()
.then(doc => {
    if (!doc.exists) {
        console.log('No such document!');
    } else {
        console.log('Document data:', doc.data());

    }
})
.catch(err => {
    console.log('Error getting document', err);
});

My console output:
Document data: { city: 'Chennai',
country: 'India',
time: '10:35:57',
date: '2018-03-28',
token: 'deFFa4dBPlQ:APA91bF7hTjsSkk-l6fLaI939W0ISe2olO18OjCUZu4N9URr9QKW4xXBIyWyC1L9Vui1cawGkFaSV1M2yDG4ASJyeCtrwGyal0GmIgdciZeGVmNSUnvyddTLUPAxQlAsjpAHTJy4Lwqt',
address: 'Sri Aravinthar St, Sholinganallur, Chennai, Tamil Nadu 600119, India',
Currentlat: '12.8710994',
Currentlong: '80.2225558',
I want pass console output value currentlat and currentlong value into new variable of lat and long.
After getting value from UsersCurrentBookings db then how to insert value into db.collection(DriversCurrentBookins) and parameter value lat, long and token.
Any help will be greatly appreciated! Thanks in advance!!!

A: You can directly access data from the JSON response and if you want, you can parse the data to Float type too using Javascript Global function parseFloat();
var lat = parseFloat(doc.data().Currentlat);
var lng = parseFloat(doc.data().Currentlong);

****UPDATE****
To add data to your Mongo database, you can use libraries like
MongooseJS : // This uses a model based structure, can be a little difficult to understand at first.
or
MongoJS
****UPDATE Ignore previous one****
const tokenField = data.getData().token
const ref = db.collection().doc(tokenField);

var jsonData = {
    'lat' : lat,
    'lng' : lng
}

ref.set(jsonData);

A: called set data into usercurrentbooking collection db
var cityRef =
 db.collection('UsersBookingRequest').doc('9DjekLkfFmTeLfkyZQAeezVriv02');
 var getDoc = cityRef.get()
.then(doc => {
    if (!doc.exists) {
        console.log('No such document!');
    } else {
        console.log('Document data:', doc.data());
        lat = doc.data().Currentlat;
        long = doc.data().Currentlong;
        UID = doc.data().UID;
        // token = doc.data().token;
        address = doc.data().address;
        date = doc.data().date;
        time = doc.data().time;

        console.log(lat);
        console.log(long);
        console.log(UID);
        // console.log(token);
        console.log(address);
        console.log(date);
        console.log(time);

        var data = {

                 lat: lat,
                 long: long,
                 UID: UID,
                 address: address,
                 date: date,
                 time: time
                 // token: token

                    };

                // Add a new document in collection "cities" with ID 'LA'
        var setDoc =
 db.collection('DriversCurrentBookings').doc(doc.data().UID).set(data);

    }
})
.catch(err => {
    console.log('Error getting document', err);
});


text:
Q: Scope join table to build new association I would like to scope a join table and create a new association.
In my join table (PrestaMission), I store two values (:assigned and :proposed). So I would like to create a new association to create two has_many in my model.
I give you the code, it will be clearest.
The model Mission :
class Mission < ApplicationRecord
  has_many :presta_missions, dependent: :destroy
end

The join table (PrestaMission)
class PrestaMission < ApplicationRecord
  belongs_to :client, polymorphic: true
  belongs_to :mission

  scope :assigned, -> { where(assigned: true) }
  scope :proposed, -> { where(proposed: true) }
end

And the model Keyper (which is one of the client of PrestaMission)
class Keyper < ApplicationRecord
  has_many :presta_missions, as: :client, dependent: :destroy
  has_many :missions, through: :presta_missions

  has_many :assigned_prestas, -> { where(assigned: true) }, :class_name => 'PrestaMission'
  has_many :assigned_missions, through: :assigned_prestas

  has_many :proposed_prestas, -> { where(proposed: true) }, :class_name => 'PrestaMission'
  has_many :proposed_missions, through: :proposed_prestas
end

But this script to link association is currently not working. Any suggestion ?

A: I found an elegant solution to solve that problem :
  has_many :presta_missions, as: :client, dependent: :destroy
  has_many :missions, :through => :presta_missions do
    def assigneds
      where("presta_missions.assigned = ?", true)
    end
    def proposeds
      where("presta_missions.proposed = ?", true)
    end
  end

And to call this association you can now use the following command
@keyper.missions.proposeds
OR
@keyper.missions.assigneds

Make good use and have fun !!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Problem with default value with lambda in Where function c# I have a task to find even or odds numbers in a list using LINQ lambda.
I simply have this code to do it, but the compiler says "not all code paths return a value in lambda expression". So I think I need a default value, but how can I implement it? I tried a few things but still don't work. Please give advice. Thanks.
 list = list.Where(x =>
        {
            if (command == "odd")
                return x % 2 != 0;

            else if (command == "even")
                return x % 2 == 0;

        });

A: If the command is "notEvenOrOdd" what should be the result? The example code does not cover this case, and it will therefore fail.
Using a "command" to determine what to do is usually not a great design. An alternative would be two extension methods:
public static IEnumerable<int> WhereEven(this IEnumerable<int> list) => list.Where(x => x % 2 != 0);
public static IEnumerable<int> WhereOdd(this IEnumerable<int> list) => list.Where(x => x % 2 == 0);

You can then check the command outside the lambda and run one of the methods above depending on the result.

A: I meant if the if-else statement dont match the conditions. I tried this and it works.
list = list.Where(x =>
        {
            if (command == "odd")
                return x % 2 != 0;

            else if (command == "even")
                return x % 2 == 0;

            return false;

        }).ToList();


text:
Q: Error serializing/deserializing List of custom objects to/from xml I have this class:
using System;
using System.Xml.Serialization;

namespace RPG_Maker_WPF.Models
{
    /// <summary>
    /// Represents a (theoretically) playable character.
    /// </summary>
    public class Actor
    {
        #region Properties

        /// <summary>
        /// The name of this actor.
        /// </summary>
        public string Name
        {
            get { return _name; }
          set { _name = value; }
        }
        private string _name;

        /// <summary>
        /// The second name of this actor.
        /// </summary>
        public string SecondName
        {
            get { return _secondName; }
            set { _secondName = value; }
        }
        private string _secondName;

        public string Description
        {
            get { return _description; }
            set { _description = value; }
        }
        private string _description;

        /// <summary>
        /// The initial level of this actor.
        /// </summary>
        public int InitialLevel
        {
            get { return _initialLevel; }
            set { _initialLevel = value; }
        }
        private int _initialLevel;

        /// <summary>
        /// The maximum level of this actor.
        /// </summary>
        public int MaxLevel
        {
            get { return _maxLevel; }
            set
            { _maxLevel = value; }
        }
        private int _maxLevel;

        #endregion Properties

        public Actor()
        {

        }
    }
}

In my other class I have a List<Actor>. Now I want to deserialize this list to xml. I use the following:
[XmlRoot(ElementName = "Database")]
    public class Database
    {
        #region Properties

        [XmlArray("Actors"), XmlArrayItem(typeof(Actor), ElementName = "Actor")]
        public List<Actor> Actors
        {
            get { return _actors; }
            private set { _actors = value; }
        }
        private List<Actor> _actors;

        #endregion properties

        public Database()
        {
            Actors = new List<Actor>();
        }

        public void LoadData()
        {
            Actors.Add(new Actor() { Name = "Test", SecondName = "Testi", InitialLevel = 1, MaxLevel = 44, Description = "Bla" });
            SaveData();

            XmlSerializer serializer = new XmlSerializer(typeof(List<Actor>));
            FileStream fs = new FileStream(ProjectViewModel.CurrentProject.Path + "\\Data\\ActorData.rpgwpfd", FileMode.Open);
            XmlReader reader = XmlReader.Create(fs);

            Actors = (List<Actor>)serializer.Deserialize(fs);
        }

        public void SaveData()
        {
            XmlSerializer serializer = new XmlSerializer(typeof(List<Actor>));
            string path = ProjectViewModel.CurrentProject.Path + "\\Data\\ActorData.rpgwpfd";
            FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
            serializer.Serialize(fs, Actors);
            fs.Close();
        }
    }
}

The xml I get out of this looks like this:
<?xml version="1.0"?>
<ArrayOfActor xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Actor>
    <Name>Test</Name>
    <SecondName>Testi</SecondName>
    <Description>Bla</Description>
    <InitialLevel>1</InitialLevel>
    <MaxLevel>44</MaxLevel>
  </Actor>
</ArrayOfActor>

But upon trying to deserialize the xml I get an exception saying that the root element is missing. What is wrong here?

A: This deserialization code should work:
        using (var fs = File.OpenRead(ProjectViewModel.CurrentProject.Path + "\\Data\\ActorData.rpgwpfd"))
        {
            var serializer = new XmlSerializer(typeof(List<Actor>));
            Actors = (List<Actor>)serializer.Deserialize(fs);
        }


text:
Q: Python - same else code for nested ifs In Django, the canonical way of processing forms is:
if request.method == 'POST':
    form = SomeForm(request.POST)
    if form.is_valid():
        use the form data

I want to execute the same code whether there was no POST or the form was invalid - it's a few lines of code, so I'm wondering if there is a nicer way of doing this than having two duplicate else blocks (one for the inner if and one for the outer)?

A: Use a separate function:
if request.method != 'POST':
    return do_something_function_for_invalid(request)

form = SomeForm(request.POST)
if not form.is_valid():
    return do_something_function_for_invalid(request)

# do something

and then define do_something_function_for_invalid() as:
def do_something_function_for_invalid(request):
    # do something

    return response

Alternatively, use exception handling:
try:
    if request.method != 'POST':
        raise ValueError('invalid form')

    form = SomeForm(request.POST)
    if not form.is_valid():
        raise ValueError('not a POST request')

     # do something
except ValueError as ve:
    # handle ve exception, ve.args[0] is the error message

A: A very concise way that does not require a separate function, and doesn't repeat conditions:
form = SomeForm(request.POST) if request.method == 'POST' else None

if form and form.is_valid():
    # do your valid-submission stuff
else:
    # do your invalid-submission stuff

A: As simple as
if (request.method != 'POST') or (not SomeForm(request.POST).is_valid()):
   do something


text:
Q: Invalid argument in cudaMemcpy3D using width in bytes? I've made a simple texture3D test and found a strange behavior when copying data to device. The function cudaMemcpy3D return an 'invalid argument'.
I found the problem is related with cudaExtent. According to the CUDA Toolkit Reference Manual 4.0, cudaExtent Parameters are as follow:

*

*w - Width in bytes

*h - Height in elements

*d - Depth in elements

So, I prepared the texture as follows:
// prepare texture
cudaChannelFormatDesc t_desc = cudaCreateChannelDesc<baseType>();
// CUDA extent parameters w - Width in bytes, h - Height in elements, d - Depth in elements
cudaExtent t_extent = make_cudaExtent(NCOLS*sizeof(baseType), NROWS, DEPTH);
// CUDA arrays are opaque memory layouts optimized for texture fetching
cudaArray *i_ArrayPtr = NULL;
// allocate 3D
status = cudaMalloc3DArray(&i_ArrayPtr, &t_desc, t_extent);

And configured the 3D parameters as follow:
// prepare input data
cudaMemcpy3DParms i_3DParms = { 0 };
i_3DParms.srcPtr   = make_cudaPitchedPtr( (void*)h_idata, NCOLS*sizeof(baseType), NCOLS, NROWS);
i_3DParms.dstArray = i_ArrayPtr;
i_3DParms.extent   = t_extent;
i_3DParms.kind     = cudaMemcpyHostToDevice;

And finally copied the data to device memory:
// copy input data from host to device
status = cudaMemcpy3D( &i_3DParms );

The problem is solved if I only specified the number of element in the x dimension as:
cudaExtent t_extent = make_cudaExtent(NCOLS, NROWS, DEPTH);

which does not produce any error and the test work as expected.
I'm wondering if I miss something with the cudaExtent function or something else. Why the width parameter is not needed to be expressed in bytes ?

A: For CUDA arrays, the extent is specified with the width given in array elements. For allocating linear memory, the extent is specified with the width given in bytes. Because you are allocating an array with cudaMalloc3DArray, use the width in elements. If you were using cudaMalloc3D, the extent would have a width in bytes.


text:
Q: Why use ln-ln plot in proportional hazard test? I recently study survival analysis since couple of months ago, and there is one question which makes me curious. a simple and (maybe) a stupid question.
Why do we prefer to use ln-ln survival curve rather than survival curve in proportional hazard test? As you know, the $\hat{S}$ we use in ln-ln formula is survival function based on Kaplan-Meier, so why we don't use that 'original' KM survival function?


text:
Q: Ajax return not firing Callback I'm trying to troubleshoot some code that I did not write and I'm having a lot difficulty trying to figure out why an Ajax return is not firing a Callback. Here is the code that attaches the behaviors to the ajax functions:
  # Callback before AJAX request sends
cbBeforeSend = (jqXHR, settings) ->
  console.log jqXHR
  # initialize message/status elements
  $flashIcon.attr 'class', 'icon icon-refresh icon-spin'
  $flashError.html ''
  $flashNotice.html ''

# Callback when AJAX returns with success
cbSuccess = (data, textStatus, jqXHR) ->
  console.log 'success'
  $flashIcon.attr 'class', 'icon icon-ok-sign'
  window.globalLoadCallback()

# Callback when AJAX returns with error
cbError = (jqXHR, textStatus, errorThrown) ->
  console.log 'error'
  $flashIcon.attr 'class', 'icon icon-remove-circle'
  # Run the response javascript, even when the status indicates an error
  if /text\/javascript/.test jqXHR.getResponseHeader('Content-Type')
    eval jqXHR.responseText

# Callback when AJAX returns
cbComplete = (jqXHR, textStatus) ->
  console.log 'cbComplete'
  if $flashIcon.is('.icon-refresh')
    $flashIcon.attr 'class', 'icon icon-warning-sign'

Our application has two links to the Quoting/Quote path:
The new quote link works and fires the 'success' and 'cbComplete' callbacks I've shown above. Here is the code for that link:

  <%= link_to new_quoting_quote_path, remote:true do %>

    New Quote
  <% end %>

The edit quote link works, it brings you to the correct partial and the object gets returned in the console, but the 'success' and 'cbComplete' callbacks aren't firing (error isn't either). Only the 'cbBeforeSend' callback is firing because the classes on the flashIcon remain "icon icon-refresh icon-spin". I don't believe there is a problem with crm_connection because in browser the link is rendered as "/quoting/quotes/183/edit". The correct ID seems to be supplied. Here is the code for that link:
<%= client_management_tab 'Health', edit_quoting_quote_path(@crm_connection) %>

Sorry I can't supply more details. Unfortunately I did not write this code and am only tasked with fixing it. Thank you for any help you can provide.
I beleive this is the code that attaches the requests:
  $flashInfo   = $('div.flash-info')
  $flashIcon   = $flashInfo.find('i#ajax-status')
  $flashError  = $flashInfo.find('#flash-error')
  $flashNotice = $flashInfo.find('#flash-notice')
  $(document).bind 'ajax:beforeSend', cbBeforeSendBound
  $(document).bind 'ajax:success', cbSuccessBound
  $(document).bind 'ajax:error', cbErrorBound
  $(document).bind 'ajax:complete', cbCompleteBound

$.ajaxSetup(
  beforeSend: cbBeforeSend
  success: cbSuccess
  error: cbError
  complete: cbComplete
  )

A: From the jQuery docs for ajaxSetup:
Description: Set default values for future Ajax requests. Its use is not recommended.
I'd suggest you change your call and assign the callbacks to your specific ajax request:
jQuery.ajax
    url: 'blah/blah',
    success: cbSuccess,
    error: cbError,
    etc

A: If the actual call to jQuery.ajax sets its own callback, then I am fairly certain it will ignore the ones provided by ajaxSetup. This makes them pretty unreliable for anything but setting defaults, and as Ricardo pointed out in his answer, the jQuery developers recommend not to use this mechanism.
You have a couple of options the way I see it. There are a series of other ajax functions provided by jQuery for global ajax event binding:
jQuery.ajaxStart, jQuery.ajaxStop, jQuery.ajaxComplete, jQuery.ajaxError, jQuery.ajaxSuccess, jQuery.ajaxSend
If you bind the events using these functions then they will always be invoked by ajax calls through jQuery BUT this can also be overridden by setting the option "global:false" in the actual ajax request.
If this is the case for you, then you are pretty much stuck with Ricardo's answer: modify the actual calls to jQuery.ajax to do the binding.


text:
Q: Cloud Haskell query I am trying to execute the code on
https://hackage.haskell.org/package/distributed-process-simplelocalnet-0.2.3.3/docs/Control-Distributed-Process-Backend-SimpleLocalnet.html
I get the following error
$ ghc -threaded Main.hs
[1 of 1] Compiling Main             ( Main.hs, Main.o )

Main.hs:4:1: error:
    Failed to load interface for 'Control.Distributed.Process.Backend.SimpleLocalnet'

I reinstalled the cloud-haskell and distributed-process package using cabal, still I got the same error. I am not able to figure out what I am doing wrong.
I am using Ubuntu(latest version).
Thanks


text:
Q: Display Correlation Tables as Descending List When running cor() on a times series with a lot of variables, I get a table back that has a row and column for each variable, showing the correlation between them.
How can I view this table as a list from most correlated to least correlated (eliminating all NA results and results that map back to themselves (i.e. the correlation of A to A)). I would also like to count inverse (negative) results as absolute values, but still show them as negative.
So the desired output would be something like:
A,B,0.98
A,C,0.9
C,R,-0.8
T,Z,0.5

A: Replace ... with your correlation call.
library(reshape)
x <- subset(melt(cor(...)), value != 1 | value != NA)
x <- x[with(x, order(-abs(x$value))),]

If you're getting a lot of NA in your correlations, perhaps try using the use="complete.obs" argument in your correlation call.

A: Here's one of many ways I could think to do this. I used the reshape package because the melt() syntax was easy for me to remember, but the melt() command could pretty easily be done with base R commands:
require(reshape)
## set up dummy data
a <- rnorm(100)
b <- a + (rnorm(100, 0, 2))
c <- a + b + (rnorm(100)/10)
df <- data.frame(a, b, c)
c <- cor(df)
## c is the correlations matrix

## keep only the lower triangle by
## filling upper with NA
c[upper.tri(c, diag=TRUE)] <- NA

m <- melt(c)

## sort by descending absolute correlation
m <- m[order(- abs(m$value)), ]

## omit the NA values
dfOut <- na.omit(m)

## if you really want a list and not a data.frame
listOut <- split(dfOut, 1:nrow(dfOut))

A: Using base R (where cors is the correlation matrix):
up <- upper.tri(cors)
out <- data.frame(which(up, arr.ind=TRUE), cor=cors[up])
out <- out[!is.na(out$cor),]
out[order(abs(out$cor), decreasing=TRUE),]


text:
Q: Adding a git submodule from a remote repository with gitpython For automating some of our workflows I am implementing some Python scripts which create project templates. The content of a project template is located in a folder which also is a local git repository. So the project in the end will be linked and pushed to a remote repository on our company server. Each project additionally uses some of our own created libraries which are added as a git submodule into the project folder and is part of the project git repository.
So my script should now first create the local project git repository which I do by using Gitpython with the following code:
Repo.init(os.path.join(sRepoPath, '.git'), bare=True)
After the repository is created, I want to add one or more remote repositories as a submodule and then clone them into the project folder. But I can't find out how to do it from the Gitpython documentation. It does not cover such a case with remotes as a submodule.
I've already tried several code combinations from the Gitpython documentation. Something like (of course not working):
mainRepo = Repo(sDestinationRepoPath)
test_remote = mainRepo.create_remote('submodule', "ssh://git@bb.mycompany.corp:1234/fwlib/system_lib.git")
mainRepo.create_submodule(test_remote)

But I can't sort it out how it should be done. Can anyone tell me how to do it?


text:
Q: Conditional probability of $Y > 250$ given $X$ and $Y$ is either greater than $250$ or it's not. Suppose $Y=\beta_1 X + \beta_2 X^2$ for some real numbers $\beta_1$ and $\beta_2$ where $X$ is a random variable with real values greater than $0$ and $Y$ is greater than $0$.
What is the probability $P[Y>250 | X]$ if you consider $Y$ in a binary way as being either $>250$ or $<250$?
(This is a simplified version of equation $(7.3)$ in Introduction to Statistical Learning by Witten and Hastie on page $268$.)
I think we have that $P[Y>250 | X]=1-P[Y\leq 250 | X]$.
The text seems to claim that such a probability would be $\frac{e^{\beta_1 X + \beta_2 X^2}}{1+e^{\beta_1 X + \beta_2 X^2}}$ but I'm not following.


text:
Q: Batch File Read Contents No Extension on File for /r "C:\File Folder" %%a in (*) do if "%%~nxa"=="FoundFile" set p=%%~dpnxa
for /f "delims=. tokens=1*" %%A in ("%p%") do set Build=%%B

CMD>if "FoundFile" == "FoundFile" set p=C:\File Folder\SubFolder\FoundFile
CMD>for /F "delims=. tokens=1*" %A in ("C:\File Folder\SubFolder\FoundFile") do set Build=%B
CMD>set Build=

The search function seems to find the file I'm looking for. The FoundFile doesn't have an extension. When I run that same command in a batch file while it's in the same folder and I just give it a file name no filepath it runs perfectly. As soon as I try to run the script from a remote folder and give it the full path it runs everything but can't get the data needed out of the file. I'm guessing it can't open it to read it and fill in the variable Build
The file that it's reading is getting an extension that was written inside the file from another program. I'm needing that extension to continue with my script.
How do I read the file that doesn't have an extension, I can't "add an extension".

A: Try "usebackq tokens=1* delims=."
for /f when applied to a quoted string processes the string, not the filename inside the quotes.
I put delims= last because of ambiguity in the command - as written in your original, the delimiter set might be . or (. and Space)


text:
Q: How to append data only one time after click with jQuery So, i have this little function:
carousel_controls_buttons.live('click', function(e){
    setTimeout(function(){
       info_board_span.append(info_board_description);
       e.preventDefault();
    }, 450);
});

What i'm trying to do is stop appending info_board_description more then one time after two, three fast clicks. When i do this this data appends more than one time and i have content duplication. How can i stop this for some time, f.e. this 450ms? Thx for help.

A: Use a boolean to control it.
var flag = true;
carousel_controls_buttons.live('click', function(e){
    e.preventDefault();
    if (flag) {
       setTimeout(function(){
           info_board_span.append(info_board_description);
           flag = true;
       }, 450);
       flag = false;
    }
});

A: You can use clearTimeout function:
var t = '';
carousel_controls_buttons.live('click', function(e){
    clearTimeout(t);
    t = setTimeout(function(){
          info_board_span.append(info_board_description);
          e.preventDefault();
    }, 450);
});

example: http://jsfiddle.net/xhSvC/
Note that live method  is deprecated, you should use on method instead.

A: While the other answers ought to work, I would like to introduce you to the concept of debounce & throttle.
http://benalman.com/projects/jquery-throttle-debounce-plugin/ is one plugin you may use to achieve what you need, ie, ensure a function is executed only once per x seconds.

Throttle versus debounce
Both throttling and debouncing will rate-limit execution of a
  function, but which is appropriate for a given situation?
Well, to put it simply: while throttling limits the execution of a
  function to no more than once every delay milliseconds, debouncing
  guarantees that the function will only ever be executed a single time
  (given a specified threshhold).

carousel_controls_buttons.live('click', function(e) {
    $.debounce(450, function() {
       info_board_span.append(info_board_description);
       e.preventDefault();
    });
});

A: Put an count over there say var count=0; increment when hit and check for the condition if count==1 append it if not leave it

A: There is a one event for achieve this:
carousel_controls_buttons.one('click', function() {
  setTimeout(function(){
       info_board_span.append(info_board_description);
       e.preventDefault();
    }, 450);
});


text:
Q: Exact sequence of structure sheaves implies exact sequence of twisted sheaves? Assume I have an onto morphism $\pi: Y\longrightarrow X$, where $X$ and $Y$ are both projective curves over an algebraically closed field $k$.
Also, assume that the following exact sequence of structure sheaves holds:
$$0\longrightarrow\mathcal{O}_X\longrightarrow\pi_*\mathcal{O}_Y\longrightarrow k\longrightarrow 0$$
I would like to know whether the former exact sequence also implies that:
$$0\longrightarrow\mathcal{O}_X(d)\longrightarrow\pi_*\mathcal{O}_Y(d)\longrightarrow k\longrightarrow 0$$
Holds for all $d$.


text:
Q: What's the difference between UIControlStateHighlighted and UIControlStateSelected? I am trying to set a state for UIButton.
But i don't know the difference between the UIControlStateHighlighted and UIControlStateSelected.
Could anyone help me out?
Thanks and best regards.

A: *

*UIControlStateHighlighted = it highlights the button with some flash(in button background) when the  user taps.

*UIControlStateSelected = it highlights nothing to that button.

A: From the official doc:

UIControlStateHighlighted Highlighted state of a control. A control
  enters this state when a touch enters and exits during tracking and
  when there is a touch up event. You can retrieve and set this value
  through the highlighted property.
UIControlStateSelected Selected state of a control. For many controls,
  this state has no effect on behavior or appearance. But other
  subclasses (for example, the UISegmentedControl class) may have
  different appearance depending on their selected state. You can
  retrieve and set this value through the selected property.

Your button get highlighted in reaction of a touch event. It could then be on a selected state within a group (for segmented control).

A: They can mean whatever you want them to, but in general they mean the following:
Highlighted = The user is currently interacting with something that will change once they stop interacting (e.g. holding down a button)
Selected = The item is current the active item in a group (e.g. The selected item in a segmented control).  This can only be achieved by setting it programmatically.

A: Highlighted is typically applied transiently when the control is being touched, selected is a more permanent state. Imagine a checkbox type button which dimmed while it was being touched - dimming is highlighted, ticked is selected, unticked is unselected.
Typically you'd never set highlighted status manually as the system will be setting/unsettling it in response to touches, whereas selected is safer. This particularly applies to buttons.


text:
Q: Array of TPanel in Delphi not show for y:=32 downto 1 do begin
  for x := 1 to 16 do begin
    PanelArray[x,y]:=TPanel.create(self);
    PanelArray[x,y].parent:=self;
    PanelArray[x,y].Color:=clBlack;
    PanelArray[x,y].Enabled:=true;
    PanelArray[x,y].Show;
    PanelArray[x,y].BevelOuter:=bvNone;
    PanelArray[x,y].OnClick:=Panel1Click;
    PanelArray[x,y].Visible:=true;
    PanelArray[x,y].width:=10;
    PanelArray[x,y].height:=10;
    PanelArray[x,y].Refresh;
  end;
end;

A: All 512 are being created, they're just invisible.  You need to set the ParentBackground to "false":
for y:=32 downto 1 do begin
  for x := 1 to 16 do begin
    PanelArray[x,y]:=TPanel.create(self);

    ///////////
    PanelArray[x,y].ParentBackground := false;
    ///////////

    PanelArray[x,y].parent:=self;
    PanelArray[x,y].Color:=clBlack;
    PanelArray[x,y].BevelOuter:=bvNone;
    PanelArray[x,y].OnClick:=Panel1Click;
    PanelArray[x,y].width:=10;
    PanelArray[x,y].height:=10;
  end;
end;

I also removed the various needless lines of code that were present in your question. Such as calling Show and Refresh, and setting Enabled and Visible.


text:
Q: An unhandled exception of type 'System.InvalidOperationException' occurred in System.Core.dll Window owner = System.Windows.Application.Current.Windows.OfType<Window>().SingleOrDefault(x => x.IsActive);
if (owner == null)
    owner = System.Windows.Application.Current.Windows.OfType<Window>().SingleOrDefault();

On execution of last line,I am getting the error as:

An unhandled exception of type 'System.InvalidOperationException' occurred in System.Core.dll

This error is coming once I upgraded from VisualStudio 2012 to VisualStudio 2015.
What Configuration I have to do to resolve this error?


text:
Q: Bootstrapping (Responsive image) doesn't work (PC/Mobile) I'm trying to create a website for a friend. The challenge is to have only a image on the website. But the images can't be the same on both pc and mobile. So I have now made a function, so the one or other will be either shown or hidden.
But my problem is now that the responsive isn't working. And will the code for the PC and mobile be the same?
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Danish Bread Studio</title>

    <link href="stylesheet.css" rel="stylesheet">

    <link href="css/bootstrap.min.css" rel="stylesheet">

Danish Bread Studio's hjemmeside er i øjeblikket under opbygning.

A: Image tags you have written should be as follows. You have written class attribute 2 times.

A: Why don't use CSS media query? MDN media query. It's lot simplier than a JavaScript. I suggest the mobile-first approach.


text:
Q: How to change the width of a container by a boolean value? I am trying to change the width of a container dynamically. I have four containers in a row. I hide other three when a user selects a value (taps on a filter icon having bool value). The problem is that when I hide the other three (using visibility), the remaining container takes the space of full row.
What I want is this:
Keep the default width of the container when the bool value is true, else take 1/4 value of the device width using media query.
Thanks in Advance!
Regards

A: Try use Flexible widget and set flex: for widget child
Example:
import 'package:flutter/material.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  bool _button1Show = true;
  bool _button2Show = true;
  bool _button3Show = true;
  bool _button4Show = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Row(
          children: [
            Visibility(
              visible: _button1Show,
              child: Flexible(
                child: GestureDetector(
                  onTap: (){
                    setState(() {
                      _button1Show = false;
                    });
                  },
                  child: Container(
                    height: 50,
                    color: Colors.red,
                  ),
                ),
                flex: 1,
              ),
            ),
            Visibility(
              visible: _button2Show,
              child: Flexible(
                child: GestureDetector(
                  onTap: (){
                    setState(() {
                      _button2Show = false;
                    });
                  },
                  child: Container(
                    height: 50,
                    color: Colors.green,
                  ),
                ),
                flex: 1,
              ),
            ),
            Visibility(
              visible: _button3Show,
              child: Flexible(
                child: GestureDetector(
                  onTap: (){
                    setState(() {
                      _button3Show = false;
                    });
                  },
                  child: Container(
                    height: 50,
                    color: Colors.grey,
                  ),
                ),
                flex: 1,
              ),
            ),
            Visibility(
              visible: _button4Show,
              child: Flexible(
                child: GestureDetector(
                  onTap: (){
                    setState(() {
                      _button4Show = false;
                    });
                  },
                  child: Container(
                    height: 50,
                    color: Colors.yellow,
                  ),
                ),
                flex: 1,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

A: This might point you in the right direction:
Container(
  width: myBool ? 200 : MediaQuery.of(context).size.width * 0.25,

  ...

However, the better solution might be to set each Row's child width to 1/4 of the overall width:
Row(
      children: <Widget>[
        Expanded(
          flex: 1, // 25%
          child: Container(color: Colors.red),
        ),
        Expanded(
          flex: 1, // 25%
          child: Container(color: Colors.green),
        ),
        Expanded(
          flex: 1, // 25%
          child: Container(color: Colors.blue),
        )
        Expanded(
          flex: 1, // 25%
          child: Container(color: Colors.yellow),
        )
      ],
    )


text:
Q: java.lang.IllegalStateException: Cannot add header view to list Android I have one issues in my application, I am setting header view to listview dynamically but am getting below error, I have two activities , A and B according my condition I am setting header view to listview when I am setting headerview in A activity it works fine but when A activity false my condition and go to B activity there my condition is true then come to A activity i need to add header view there I am getting Error................ I have tried to added onStart(), onResume() methods, but still am getting same error..... how to fix it
Java code
on Strat()
{

             if (mDrawerList.getHeaderViewsCount()<1) {
             TextView headerText = new TextView(mContext);

             headerText.setGravity(Gravity.CENTER);
             headerText.setTextColor(getResources().getColor(R.color.white_color));
             headerText.setPadding(20, 12, 20, 12);
             headerText.setTextSize(18);
             headerText.setText(mSessionManager.getUserName());
             mDrawerList.addHeaderView(headerText);
             }

         adapter = new NavDrawerListAdapter(mContext, navDrawerItems);
    mDrawerList.setDividerHeight(2);

    mDrawerList.setAdapter(adapter);
    adapter.notifyDataSetChanged();

    }

Error message
2-20 15:15:34.799: E/AndroidRuntime(13111): FATAL EXCEPTION: main
12-20 15:15:34.799: E/AndroidRuntime(13111): java.lang.RuntimeException: Unable to resume activity {com.examle.EventListActivity}: java.lang.IllegalStateException: Cannot add header view to list -- setAdapter has already been called.
12-20 15:15:34.799: E/AndroidRuntime(13111):    at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2790)
12-20 15:15:34.799: E/AndroidRuntime(13111):    at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2819)
12-20 15:15:34.799: E/AndroidRuntime(13111):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1298)
12-20 15:15:34.799: E/AndroidRuntime(13111):    at android.os.Handler.dispatchMessage(Handler.java:99)
12-20 15:15:34.799: E/AndroidRuntime(13111):    at android.os.Looper.loop(Looper.java:137)
12-20 15:15:34.799: E/AndroidRuntime(13111):    at android.app.ActivityThread.main(ActivityThread.java:5103)
12-20 15:15:34.799: E/AndroidRuntime(13111):    at java.lang.reflect.Method.invokeNative(Native Method)
12-20 15:15:34.799: E/AndroidRuntime(13111):    at java.lang.reflect.Method.invoke(Method.java:525)
12-20 15:15:34.799: E/AndroidRuntime(13111):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-20 15:15:34.799: E/AndroidRuntime(13111):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-20 15:15:34.799: E/AndroidRuntime(13111):    at dalvik.system.NativeStart.main(Native Method)
12-20 15:15:34.799: E/AndroidRuntime(13111): Caused by: java.lang.IllegalStateException: Cannot add header view to list -- setAdapter has already been called.
12-20 15:15:34.799: E/AndroidRuntime(13111):    at android.widget.ListView.addHeaderView(ListView.java:258)
12-20 15:15:34.799: E/AndroidRuntime(13111):    at android.widget.ListView.addHeaderView(ListView.java:287)

A: Please take a look at the documentation of addHeaderView.
Give special attention to the note:

Note: When first introduced, this method could only be called before setting the adapter with setAdapter(ListAdapter). Starting with KITKAT, this method may be called at any time. If the ListView's adapter does not extend HeaderViewListAdapter, it will be wrapped with a supporting instance of WrapperListAdapter.

A: I found this simple workaround here http://code.neenbedankt.com/note-to-self-listfragment-and-header-views/:
    @Override
    public void onDestroyView() {
      super.onDestroyView();
      setListAdapter(null);
  }

Simply add this to the ListFragment class.
It works for me on 2.3.3 and 4.2.2

A: How about:
    ListAdapter adapter = listView.getAdapter();
    listView.setAdapter(null);
    listView.addHeaderView(headerView);
    listView.setAdapter(adapter);

The only problem here, is that it restart your scrollbar position. But than there is no other way to add headerView after adapter been set.

A: need to  check whether the list has already set the adapter or not.
if (mDrawerList.getAdapter==null) {
    // add the header view here.this will work
}

A: list.setAdapter(null);
list.addHeaderView(loading.getView());


text:
Q: hidden columns are still shown in my browser, what's the problem? I have an excel worksheet with some hidden columns.
I want to export it as a webpage, so I save that with html format but when I open it in my browser(IE and chrome), the hidden columns are still displayed.
What can I do to solve this problem?
Thanks :)

A: Find the nth column you want to hide and apply CSS like below. Make sure your CSS is inside the


text:
Q: Testing silent push notifications in Xcode11.4 beta I want to test notifications in Xcode 11.4 simulator and everything works well except silent notifications. didReceiveRemoteNotification  is not triggered.
What I've done:
Enabled Push Notifications in Background Modes/Remote Notifications in Capabilities
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) { granted, _ in
        if granted {
            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }
    return true
}

In didReceiveRemoteNotification I just set value in UserDefaults to use it later
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    print(userInfo)
    UserDefaults.standard.set("Hello world", forKey: "hello")
    completionHandler(.newData)
}

And then in sceneDidBecomeActive what to read this value from UserDefaults
    func sceneDidBecomeActive(_ scene: UIScene) {
    print(UserDefaults.standard.value(forKey: "hello")) // always nil
}

This is my .apns json
{
"Simulator Target Bundle": "xxx",
 "aps" : {
    "content-available" : 1
 }
}

A: Jeff's Solution worked for Me, In addition I had to add 'Background Fetch' mode to app

A: It appears that, presumably due to a bug (that I believe has been reported), the apns file is resulting in performFetchWithCompletionHandler being called, rather than didReceiveRemoteNotification being called.


text:
Q: C# Unit Testing Async Error Just to set the question, when I have come to write a unit test I hit the following error:

Error: The source IQueryable doesn't implement
  IDbAsyncEnumerable

The problem happens when testing a method which calls ToListAsync(), the unit test is as follows:
[TestMethod]
public async Task Method1CallsCount()
{
    //arrange
    MockContainer container = new MockContainer();

    IQueryable<Entity1DTO> querableentity1DTO = new List<Entity1DTO>().AsQueryable();

    container.DefaultQueryFactory.Setup(p => p.Load(It.IsAny<ContextEnums>(), It.IsAny<Expression<Func<Entity1, Entity1DTO>>>(),
        It.IsAny<Expression<Func<Entity1, bool>>>(), It.IsAny<int>(), It.IsAny<bool>())).Returns(querableentity1DTO);

    var manager = new Manager1(container.DefaultQueryFactory.Object);

    //act
    var result = await manager.Method1();

    //assert
    //container.repo1.Verify(x => x.repoMethod(It.IsAny<Expression<Func<Entity1,bool>>>()), Times.Once);
}

And here is the method I am testing:
public async Task<List<Entity1DTO>> Method1()
{
    Expression<Func<Entity1, Entity1DTO>> select = (x => new Entity1DTO()
    {
             ...
            });

    Expression<Func<Entity1, bool>> where = (x => x.Property == "Test");

    return await _defaultQueryFactory.Load(ContextEnums.Enum1, select, where).ToListAsync();

}

To help a bit, I've tried mocking up the method that loads the data in the query factory and the error appears because the DTO model doesn't implement IDbAsyncEnumerable, now the method that is getting tested sends off a select statement and a where statement and an entity type which the query factory then uses to generate a query this is then executed with ToListAsync() when it returns from the load Method. The error message shows that the DTO model is the one that doesn't implement the IDbAsync not the DB entity itself.
I understand that there are a few other questions out there that are simular but my difference is that I use a DTO model and the method in question does not use the context itself as it is injected into the load method and not in the place in which ToListAsync() is called.
anyone any ideas?

A: Error happens because Entity Framework async extension methods does not work with any IQueryable - it should also implement IDbAsyncEnumerable interface. Consider this:
var query = new List<EntityDTO>().AsQueryable();
var result = query.ToListAsync().Result;

This will throw the same exception you observe in your code. EnumerableQuery returned by AsQueryable does not implement required interface, so we need to use some other implementation. We can find one in this article (or just create ourselves since it's not hard):
static class TestExtensions {
    public static IQueryable<T> AsAsyncQueryable<T>(this IEnumerable<T> source) {
        return new TestDbAsyncEnumerable<T>(source);
    }
}

internal class TestDbAsyncEnumerable<T> : EnumerableQuery<T>, IDbAsyncEnumerable<T>
{
    public TestDbAsyncEnumerable(IEnumerable<T> enumerable)
        : base(enumerable)
    { }

    public TestDbAsyncEnumerable(Expression expression)
        : base(expression)
    { }

    public IDbAsyncEnumerator<T> GetAsyncEnumerator()
    {
        return new TestDbAsyncEnumerator<T>(this.AsEnumerable().GetEnumerator());
    }

    IDbAsyncEnumerator IDbAsyncEnumerable.GetAsyncEnumerator()
    {
        return GetAsyncEnumerator();
    }
}

internal class TestDbAsyncEnumerator<T> : IDbAsyncEnumerator<T> {
    private readonly IEnumerator<T> _inner;

    public TestDbAsyncEnumerator(IEnumerator<T> inner) {
        _inner = inner;
    }

    public void Dispose() {
        _inner.Dispose();
    }

    public Task<bool> MoveNextAsync(CancellationToken cancellationToken) {
        return Task.FromResult(_inner.MoveNext());
    }

    public T Current => _inner.Current;

    object IDbAsyncEnumerator.Current => Current;
}

Now we can do:
IQueryable<Entity1DTO> querableentity1DTO = new List<Entity1DTO>().AsAsyncQueryable();

And EF async methods will execute correctly on it.

A: There are actually two problems here, firstly you do need to use the solution in the other answer and change the return type to TestDbAsyncEnumerator and the other problem is to do with Moq, the setup needs to have the same parameters called, so in your case you have
return await _defaultQueryFactory.Load(ContextEnums.Enum1, select, where).ToListAsync();

and
container.DefaultQueryFactory.Setup(p => p.Load(It.IsAny<ContextEnums>(), It.IsAny<Expression<Func<Entity1, Entity1DTO>>>(),
        It.IsAny<Expression<Func<Entity1, bool>>>(), It.IsAny<int>(), It.IsAny<bool>())).Returns(querableentity1DTO);

notice how you have two extra parameters on the end, try leaving them as null. That should sort out the problem, just to make sure try adding an item to the return list as well.


text:
Q: Firestore: how can read data from outside void onComplete methods I read data from Cloud Firestore:
      firestoreDB.collection("events")
                .whereEqualTo("type", eventType)
                .get()
                .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<QuerySnapshot> task) {
                        if (task.isSuccessful()) {
                           List<Event> eventList = new ArrayList<>();

                           for(DocumentSnapshot doc : task.getResult()){
                              Event e = doc.toObject(Event.class);
                              e.setId(doc.getId());
                               eventList.add(e);
                           }
               //do something with list of pojos retrieved

                        } else {
                            Log.d(TAG, "Error getting documents: ", task.getException());
                        }
                    }
 });

Since onComplete is a void method, how can I get eventList from outside methods?
For example, I tried:
List<Event> ReadCollection()
{
   final List<Event> eventList = new ArrayList<>();
firestoreDB.collection("events")
                    .whereEqualTo("type", eventType)
                    .get()
                    .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
                        @Override
                        public void onComplete(@NonNull Task<QuerySnapshot> task) {
                            if (task.isSuccessful()) {
                               List<Event> eventList = new ArrayList<>();

                               for(DocumentSnapshot doc : task.getResult()){
                                  Event e = doc.toObject(Event.class);
                                  e.setId(doc.getId());
                                   eventList.add(e);
                               }
                   //do something with list of pojos retrieved

                            } else {
                                Log.d(TAG, "Error getting documents: ", task.getException());
                            }
                        }
     });

return eventList;
}

It doesn't work since onComplete is a void method. I can read nothing from Cloud Firestore.

A: You cannot return something now that hasn't been loaded yet. The onComplete() method has an asynchronous behaviour which means that is called even before you are trying to add those objects of type Event to the eventList ArrayList. That's why your list is always empty outside that method. With other words, by the time you are returning the eventList, the data has not finished loading yet from the database, so to solve this, you need to create you own callback in order to wait for the data. So first you need to create an interface like this:
public interface MyCallback {
    void onCallback(List<Event> eventList);
}

Then you need to create a method that is actually getting the data from the database. This method should look like this:
public void readData(MyCallback myCallback) {
    firestoreDB.collection("events")
        .whereEqualTo("type", eventType)
        .get()
        .addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
            @Override
            public void onComplete(@NonNull Task<QuerySnapshot> task) {
                if (task.isSuccessful()) {
                    List<Event> eventList = new ArrayList<>();

                    for(DocumentSnapshot doc : task.getResult()) {
                        Event e = doc.toObject(Event.class);
                        e.setId(doc.getId());
                        eventList.add(e);
                    }
                    myCallback.onCallback(eventList);
                } else {
                    Log.d(TAG, "Error getting documents: ", task.getException());
            }
        }

     });
}

In the end just simply call readData() method and pass an instance of the MyCallback interface as an argument wherever you need it like this:
readData(new MyCallback() {
    @Override
    public void onCallback(List<Event> eventList) {
        Log.d("TAG", eventList.toString);
    }
});

This is the only way in which you can use the eventList outside onComplete() method. For more informations, you can take also a look at this video.


text:
Q: If the sum of p, q, r terms of an AP are a, b, c respectively, show that If the sum of p, q, r terms of an AP are a, b, c respectively, show that
$(q-r)$$\frac ap$+$(r-p)$$\frac bq$+$(p-q)$$\frac cr$$=$$0$

A: i) Let the first term be t, common difference be d
ii) So sum to p terms is: Sp = (p/2){2t + (p - 1)d} = a
So, 2a/p = 2t + pd - d
==> 2(a/p)*(q - r) = (2t + pd - d)(q - r) = 2qt - 2rt + pqd - prd - qd + rd ----- (1)
iii) Similarly, 2*(b/q)(r - p) = 2rt - 2pt + qrd - pqd - rd + pd ----- (2)
and 2(c/r)*(p - q) = 2pt - 2qt + prd - qrd - pd + qd ---- (3)
iv) Adding (1), (2) & (3):
2*{(a/p)(q - r) + (b/q)(r - p) + (c/r)*(p - q)} = 0
==> (a/p)(q - r) + (b/q)(r - p) + (c/r)*(p - q) = 0

A:
Q:The sum of the first $p, q, r$ terms of an A.P. are $a, b, c$ respectively. Show that
$$
\frac{a}{p}(q-r)+\frac{b}{q}(r-p)+\frac{c}{r}(p-q)=0
$$

Sol. Let $x$ be the first term and $d$ the common difference. Then,
$$
\begin{aligned}
S_{p}=a & \Rightarrow\left(\frac{p}{2}\right) \cdot[2 x+(p-1) d]=a \\
& \Rightarrow \frac{a}{p}=x+(p-1) \cdot \frac{d}{2} \\
& \Rightarrow \frac{a(q-r)}{p}=x(q-r)+(p-1)(q-r) \cdot \frac{d}{2}
\end{aligned}
$$
Similarly,
$$
S_{q}=b \Rightarrow \frac{b(r-p)}{q}=x(r-p)+(q-1)(r-p)-\frac{d}{2}
$$
(ii)
And $S_{r}=c \Rightarrow \frac{c(p-q)}{r}=x(p-q)+(r-1)(p-q) \cdot \frac{d}{2}$
(iii
Adding (i), (ii) and (iii), we get $\frac{a}{p}(q-r)+\frac{b}{q}(r-p)+\frac{c}{r}(p-q)=0$


text:
Q: Почему не работают массивы в LINQ to entities Есть метод в контроллере, который фильтрует содержимое.
[HttpPost]
public ActionResult Search (string[] jsonString)
{
    IQueryable <UploadedFile> res = Context.UploadedFiles;
    if (!string.IsNullOrEmpty(jsonString[0]))
    {
        res = res.Where(x => x.FileTitle.Contains(jsonString[0]));
    }

    return View("UploadFilesView", res.ToList());
}

В метод прилетает json строка, далее фильтруется и отдается во View.
В коде выше метод возвращается 500 (Internal Server Error).
Если заменить строку
res = res.Where(x => x.FileTitle.Contains(jsonString[0]));

на
var buffer = jsonString[0];

res = res.Where(x => x.FileTitle.Contains(buffer));

то все работает. Подскажите, почему так?

A: На приведенном Вами скриншоте есть сообщение об ошибке, гласящее о том, что обращение по индексу не поддерживается в Linq to Entity. Связано это, думаю с тем, что ExpressionBuilder не знает, как перевести его в язык СУБД, которую Вы используете (да, важно не только то, что Вы используете EF, но и то, какой провайдер).
Таким образом, для решения проблемы Вам необходимо поместить нужную Вам строку в локальную переменную.


text:
Q: Why is this object reference supposedly not set to an instance of an object that has obviously been identified by the compiler? Some people -- perhaps gullibly -- believe that there are multiple ways of being a catskinner.
When my attempt to search all the Controls on a Page for Checkboxes continued to fail ignominiously (for proof of that, see this), I thought maybe I could just look at the ID of the Control, rather than care what type of control it was at heart.
So, I commented out this line:
If TypeOf cntrl Is System.Web.UI.WebControls.CheckBox Then

...and tried this instead:
If cntrl.ID.ToString().Contains("ckbx")

But I fared no better, and received this coldwater slap:
Server Error in '/EMS/customerreportingnet' Application.
--------------------------------------------------------------------------------

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 69:             LabelDebug.Text = LabelDebug.Text+" "+cntrl.GetType().ToString+" "
Line 70:             'If TypeOf cntrl Is System.Web.UI.WebControls.CheckBox Then
Line 71:             If cntrl.ID.ToString().Contains("ckbx")
Line 72:             'Dim objAsConvertible As IConvertible = TryCast(cntrl, IConvertible)
Line 73:             'If objAsConvertible Is Nothing Then

Source File: C:\EnhancedMonthlySalesReporting\customerreportingnet\customerreportingnet\pages\custmaint_categoryadmin.aspx.vb    Line: 71

Stack Trace:

[NullReferenceException: Object reference not set to an instance of an object.]
   pages_custmaint_categoryadmin.Button1_Click(Object sender, EventArgs e) in C:\EnhancedMonthlySalesReporting\customerreportingnet\customerreportingnet\pages\custmaint_categoryadmin.aspx.vb:71
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +114
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +139
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +28
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +2980

--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.5485; ASP.NET Version:2.0.50727.5491

Why is it that the control, which obviously exists, throws an exception as if there is no reference to it?
The entire block of code is:
Dim coName As String
Dim argVals(2) As String
Dim _Unit As String
Dim _MemberNo As String
Dim _CustNo As String
Dim curCheckboxIDVal As String

For Each cntrl As Control In Me.Controls
    'If TypeOf cntrl Is System.Web.UI.WebControls.CheckBox Then
    If cntrl.ID.ToString().Contains("ckbx")
        If DirectCast(cntrl, CheckBox).Checked = True Then
            Label2.Text = "label 2 text from checked"
            curCheckboxIDVal = CStr(DirectCast(cntrl, CheckBox).ID)
            coName = GetLabelTextForID(curCheckboxIDVal)
            argVals = GetArgValsForCompanyName(coName)
            _Unit = argVals(0)
            _MemberNo = argVals(1)
            _CustNo = argVals(2)
            Label2.Text = _Unit
            LabelDebug.Text = _MemberNo
            Using conn As New SqlConnection(connStr), _
                cmd As New SqlCommand(upd8DML, conn)
                cmd.Parameters.Add("@Unit", SqlDbType.VarChar, 50).Value = _Unit
                cmd.Parameters.Add("@MemberNo", SqlDbType.VarChar, 50).Value = _MemberNo
                cmd.Parameters.Add("@CustNo", SqlDbType.VarChar, 50).Value = _CustNo
                conn.Open()
                cmd.ExecuteScalar()
            End Using
        End If
    End If
Next

To get to the line that's throwing the error, cntrl has to be a valid Control in the Me.Controls collection; I reckon all Controls have an ID property. So why that err is being thrown on that line makes little, if any, sense to me.

A: the problem is in here:
If cntrl.ID.ToString().Contains("ckbx")

cntrl.ID seems to be null.
Try to debug to see what value you have in your cntrl.ID.ToString()
Checking if value is Null:
If String.IsNullOrEmpty(cntrl.ID) then exit For

or
 If cntrl.ID Is Nothing Then exit For

A: The fix ended up being simple, and even logical, in hindsight.
The controls are dynamically added to the form, like so:
formCustCatMaint.Controls.Add(coName)
And so, replacing this line, in the loop:
For Each cntrl As Control In Me.Controls
...with this:
For Each cntrl As Control In formCustCatMaint.Controls
And this line, in the GetLabelTextForID() function:
For Each cntrl As Control In Me.Controls
...with this:
For Each cntrl As Control In formCustCatMaint.Controls
...did the trick. The controls are being found, and the code is working as designed/originally expected.
Nebenbei bemerkt, this also works fine now:
If TypeOf cntrl Is CheckBox Then


text:
Q: Doesn't show supported letters I'm using Signika Bold as font for my headers. Font is loaded from Google Webfonts. As you can see in the demo, there is a problem with showing letter "Č", both upper and lower case. The letter is on the list of supported fonts on the official Webfonts page.

CSS:
@font-face {
   font-family: "Signika";
   font-style: normal;
   font-weight: 700;
   src: local("Signika-Bold"), url(http://themes.googleusercontent.com/static/fonts/signika/v3/7M5kxD4eGxuhgFaIk95pBRsxEYwM7FgeyaSgU71cLG0.woff) format("woff");
}

h1 {
   font-family: "Signika", Helvetica, sans-serif;
}

I have also tried typing the letter as HTML entitle (č), but it doesn't help.

A: <link href='http://fonts.googleapis.com/css?family=Signika:700&subset=latin,latin-ext' rel='stylesheet' type='text/css'>

A: Thanks to Anon, the solution is to check the Latin Extended in the Google font settings. The demo is updated.
CSS:
@font-face {
   font-family: 'Signika';
   font-style: normal;
   font-weight: 700;
   src: local('Signika-Bold'), url(http://themes.googleusercontent.com/static/fonts/signika/v3/F587cG5P5ff3TX6w4JlorxsxEYwM7FgeyaSgU71cLG0.woff) format('woff');
}

Or:
HTML:
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Signika:700&subset=latin,latin-ext">


text:
Q: import submodules relative to dist folder Assume I have the following file-structure:
myPackage
  src
    subModule1
      index.ts
      ...
    index.ts

  // after bundling with rollup (src mirrored in dist)
  dist
      subModule1
        index.js // for cjs imports
        index.mjs // for esm imports
        ...
      index.js
      index.mjs

What's the proper way to declare the exports of this package, so that I can import stuff like this
// this should link to myPackage/dist/subModule1/index.mjs
import { subModuleExport } from "myPackage/subModule1;

// this should link to myPackage/dist/subModule1/index.js
const { subModuleExport } = require("myPackage/subModule1");

To me, this seems like a trivial thing, that I can use some glob-patterns perhaps to make the imports map to the correct files, something like
// package.json
"exports": {
  "./*": {
    "import": "./*.mjs",
    "require": "./*.js",
    "default": "./*.js"
  }
}


text:
Q: How to set the title of the app in the center of the title bar? I see many applications which show the title of the application at the center of the title bar. Even Intellij and Visual studio code has set the title at the center of the title bar.
Is there anyway that I can achieve that using javax.swing
I tried by checking the window width and adding that many spaces at the beginning of the title (removing helf of the text size also). But in the result I don't see the spaces I added at the beginning.
Is there any other way that I can do that?


text:
Q: boost::multi_index_container with random_acces and hashed_unique I'am trying to create container with both index and key access with unique keys: so here is my code:
#include <QString>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/random_access_index.hpp>
#include <boost/multi_index/mem_fun.hpp>

class MyClass{
public:
    MyClass( const QString& name ): mName( name ){}
    QString name    ( ) const { return mName; }
    void    setName ( const QString& name ) { mName = name ;}
private:
    QString mName;
};

using namespace boost::multi_index;
typedef multi_index_container<
    MyClass,
    indexed_by<
        random_access<tag<struct RandomIndex>>,
        hashed_unique<
            tag<struct NameIndex>,
            const_mem_fun<MyClass, QString, &MyClass::name>
        >
    >
> Table;

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Table table;
    for (MyClass v : { "first", "second", "third" }){
        table.push_back(v);
    }

    return a.exec();
}

When I try to compile it I have an error
boost_1_55_0\boost\functional\hash\extensions.hpp:269: error: C2664: 'size_t boost::hash_value(std::type_index)' : cannot convert argument 1 from 'const QString' to 'std::type_index'
No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
As I can see boost doesn't know nothing abt Qt class QString, but I am fail to find how to fix this problem. Can someone explain how to fix my code?

A: You need to tell Boost how to hash QString.
Simplest way would seem:
namespace boost {
    template <> struct hash<QString> {
        size_t operator()(QString const& v) const {
            return qHash(v);
        }
    };
}

Complete working example:
#include <QtCore/QString>
#include <QtCore/QHash>
#include <boost/multi_index_container.hpp>
#include <boost/multi_index/hashed_index.hpp>
#include <boost/multi_index/random_access_index.hpp>
#include <boost/multi_index/mem_fun.hpp>

class MyClass{
public:
    MyClass( const QString& name ): mName( name ){}
    QString name    ( ) const { return mName; }
    void    setName ( const QString& name ) { mName = name ;}
private:
    QString mName;
};

namespace boost {
    template <> struct hash<QString> {
        size_t operator()(QString const& v) const {
            return qHash(v);
        }
    };
}

using namespace boost::multi_index;
typedef multi_index_container<
    MyClass,
    indexed_by<
        random_access<tag<struct RandomIndex>>,
        hashed_unique<
            tag<struct NameIndex>,
            const_mem_fun<MyClass, QString, &MyClass::name>
        >
    >
> Table;

#include <QtGui/QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    Table table;
    for (QString v : { "first", "second", "third" }){
        table.push_back(MyClass(v));
    }

    return a.exec();
}


text:
Q: Shiny Jerbolta started to disobey My Shiny Jerbolta started to disobey.
It was a gift when I first started playing the game. Apparently, those gifts appear from time to time and you can pick them at the market.
The thing is, when my shiny Jerbolta reached level 36, it started to disobey frequently.
Is there a way to make him "friendly" again and follow my commands all the time?
EDIT: I noticed the disobedience at level 36 but I don't know exactly at what level he started to react that way.

A: If a Pokémon is disobeying you, you should be able to regain their obedience by acquiring the appropriate level Gym badge. The limits are:

*

*1st Badge - Pokémon up to level 20 will obey you

*2nd Badge - Pokémon up to level 30 will obey you

*3rd Badge - Pokémon up to level 40 will obey you

*4th Badge - Pokémon up to level 50 will obey you

*5th Badge - Pokémon up to level 60 will obey you

*6th Badge - Pokémon up to level 70 will obey you

*7th Badge - Pokémon up to level 80 will obey you

*8th Badge - All* Pokémon will obey you

Due credit to redditor Bjcftbl74 for the majority of this list.
*Nuclear Pokémon will always have a chance to disobey you, even with all of the badges.


text:
Q: Insert at caret position with a Silverlight textbox In WPF you can insert at the caret position using the CaretIndex property. However this seems to be missing in the Silverlight textbox control.
Is it possible using a different technique?

A: I also had the same problem. I used the SelectionStart property.
    private void QuotePrefixTextboxTextChanged(object sender, TextChangedEventArgs e)
    {
        var tb = (TextBox)sender;
        var caret = tb.SelectionStart;
        tb.Text = tb.Text.ToUpper();
        tb.SelectionStart = caret;
    }

A: Try:-
 myTextBox.Select(position, 0);
 myTextBox.SelectedText = "Content to insert";


text:
Q: Center UICollectionViewCells I need to fix a small issue with my UICollectionView, when on the 6s device size I get a layout like this:

However, I want to know what is the best way to either center them so that its two lines, or should i shrink them down a bit so I can put three of them? I think I would prefer to center the two columns instead so I'm not cramming too much onto the same screen. I looked but wasn't sure what to do with the Layout formatting.
Thank you!

A: I believe one or both of these are what you are looking for. Play with the values you return and see what happens. Also, your constraint inside each cell will have some effect that I can not predict without seeing them.
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionView, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
    return 0
}

func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
    return UIEdgeInsetsMake(0, 0, 0, 0)
}


text:
Q: Why is my TextView null, altough im getting the values from the Database? I wanted to get the comments for my social network app from the database and show it on a recycler view but the text where the comment should be is null
and i dont know why.
//The Database Reference
PostsRef = FirebaseDatabase.getInstance().getReference().child("Posts").child(Post_Key).child("Comments");

protected void onStart() {
        super.onStart();

        FirebaseRecyclerAdapter<Comments, CommentsViewHolder> firebaseRecyclerAdapter
                = new FirebaseRecyclerAdapter<Comments, CommentsViewHolder>
                (
                        Comments.class,
                        R.layout.all_comments_layout,
                        CommentsViewHolder.class,
                        PostsRef
                )
        {
            @Override
            protected void populateViewHolder(CommentsViewHolder viewHolder, Comments model, int position)
            {
                viewHolder.setUsername(model.getUsername());
                viewHolder.setComment(model.getComment());
                viewHolder.setDate(model.getDate());
                viewHolder.setTime(model.getTime());
            }
        };

        CommentsList.setAdapter(firebaseRecyclerAdapter);

    }

//I think heres the problem
    public static class CommentsViewHolder extends RecyclerView.ViewHolder
    {
        View mView;

        public CommentsViewHolder(@NonNull View itemView)
        {
            super(itemView);

            mView = itemView;
        }

        public void setUsername(String username)
        {
            TextView myUserName = (TextView) mView.findViewById(R.id.comment_username);
            myUserName.setText("@" + username + "  ");
        }

        public void setComment(String comment)
        {
            TextView myComment = (TextView) mView.findViewById(R.id.comment_text);
            myComment.setText(" :" + comment);
        }

        public void setDate(String date)
        {
            TextView myDate = (TextView) mView.findViewById(R.id.comment_date);
            myDate.setText("  Date: " + date);
        }

        public void setTime(String time)
        {
            TextView myTime = (TextView) mView.findViewById(R.id.comment_time);
            myTime.setText("  Time: " + time);
        }
    }

//And this is my static class

public class Comments
{
    public String comment, date, time, username;

    public Comments()
    {

    }

    public Comments(String comment, String date, String time, String username) {
        this.comment = comment;
        this.date = date;
        this.time = time;
        this.username = username;
    }

    public String getComment() {
        return comment;
    }

    public void setComment(String comment) {
        this.comment = comment;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

Anyone has a solution for this or can tell me where's my mistake?
im relatively new to programming in java so yeah..

A: I solved it by renaming comment to comments because in the database it is comments but i misread it.


text:
Q: xcode 4.2 storyboard identifier I'm writing an app in which I add some buttons to my view (mainView) by code. When the user taps on this buttons I want a new view (resultView) to show.
I have both of this views in my storyboard, but since there is no button on my mainView that is in storyboard I can't link the mainView and resultView to each other using storyboard. Everything must be done by code.
I want to know how I can link my two views by code and define an identifier for that link.
Thanks,

A: To switch the view controller programmatically, you have to set a identifier in the attribute inspector at section "View Controller". After that, you can just use the value inside your code. Here i used the identifier "Menu".
UIStoryboard *storyboard = self.storyboard;
MenuTableViewController *mtvc = [storyboard instantiateViewControllerWithIdentifier:@"Menu"];

[self presentViewController: mtvc animated:YES completion:nil];

There is also a description in the documentation, just look for

Instantiating a Storyboard's View Controller Programmatically

A: Give the segue between the two an identifier in the Attribute Inspector in IB, then on your button press event call [self performSegueWithIdentifier:@"MySegueIdentifier" sender:theButton]


text:
Q: Puppet waits for never ending bash script I have bash script that starts ethereum miner. The script also starts to show log of what it's doing and won't stop until I give the quit signal for it.
Because it doesn't stop without user input puppet won't see that the script has started and keeps waiting for signal that the script has been finished.
Now how can I make it so that the script sends signal it has finished?
It would be nice extra feature that puppet could also stop the already running script and start a new one if I update the files, rather than just start a new script on the side of the old one.
This is the part of puppet module that starts the script:
exec { 'run_miner':
    command => '/tmp/puppetethereum/claymore/miner_startstop.sh',
    provider => 'shell',
    cwd => '/tmp/puppetethereum/claymore/',
    require => File['miner_skripti'],
}

This is for a school project so dirty methods are allowed.
Edit.
I have tried this template of start-stop-daemon, but puppet still waits for the signal that the script has started:
#!/bin/sh

# Quick start-stop-daemon example, derived from Debian /etc/init.d/ssh
set -e

# Must be a valid filename
NAME=ethereumminer
PIDFILE=/var/run/$NAME.pid
#This is the command to be run, give the full pathname
DAEMON=sudo bash /tmp/claymore/mine.sh
DAEMON_OPTS="--baz=quux"

export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"

case "$1" in
  start)
        echo -n "Starting daemon: "$NAME
    start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- $DAEMON_OPTS
        echo "."
    ;;
  stop)
        echo -n "Stopping daemon: "$NAME
    start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE
        echo "."
    ;;
  restart)
        echo -n "Restarting daemon: "$NAME
    start-stop-daemon --stop --quiet --oknodo --retry 30 --pidfile $PIDFILE
    start-stop-daemon --start --quiet --pidfile $PIDFILE --exec $DAEMON -- $DAEMON_OPTS
    echo "."
    ;;

  *)
    echo "Usage: "$1" {start|stop|restart}"
    exit 1
esac

exit 0


text:
Q: Venn Diagrams and Negative Numbers I am confused about creating a Venn diagram from the question below from one of the past papers as there is a negative number involved. Is this possible in Venn diagrams?
A survey of students in a lecture revealed that a total of $15$ played rugby, $30$ played football and $35$ played cricket. $4$ people played all three sports, while $2$ played only football and rugby, $14$ played only cricket and football, and $6$ played only cricket and rugby.
If $4$ people played all three sports and $2$ played only football and rugby, how is it possible to create the Venn diagram? Are negative numbers allowed, as $2-4= -2$?

A: Draw three circles such that each intersects the other two for your diagram. You will see that $3$ played only rugby, $11$ played only cricket and $10$ played only football. Try to fill in numbers into the regions one by one.


text:
Q: SpringBoot Actuator getting overshadowed by BaseService Servlet on same Port We are Attempting to Migrate Our Existing Spring WebServices App to SpringBoot and ran into an issue for which we seek your advice.
We have a Base Service Servlet that disables the GET on the port that the App is deployed on for Security reasons this servlet returns 501 Unimplemented Response as follows:
 @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        log.warn("GET request received!");
        response.setStatus(HttpServletResponse.SC_NOT_IMPLEMENTED);
    }

public abstract class BaseServiceServlet extends HttpServlet {
 ...
 }

 public class ServiceServlet extends BaseServiceServlet {
 ...
 }

  public class ServletInitializer extends SpringBootServletInitializer implements ServletContextInitializer {
  @Override
    public void onStartup(ServletContext container) throws ServletException {

      ServletRegistration.Dynamic application = container
                .addServlet("ServiceServlet", new ServiceServlet());
      application.setLoadOnStartup(2);
      application.addMapping("/*");

    }
 }

Previously we had an old-fashioned HealthCheck JSP that we implemented. With the move to SpringBoot we are now using the SpringBoot Actuator.
But we find that if we set the Actuator health monitor port to the same one as the App when we try to monitor the health we get the 501 Unimplemented response.
Config is as follows:
# Spring-Boot Embedded Tomcat Config
server.port=8080
server.connection-timeout=10s
server.ssl.enabled=false
## Springboot based health monitor
management.endpoints.enabled-by-default=true
management.endpoint.health.enabled=true
management.endpoint.loggers.enabled=true
management.endpoints.web.cors.allowed-methods=GET
management.endpoint.beans.cache.time-to-live=20s
management.endpoints.web.base-path=/manage
management.server.port=8080
management.security.enabled=false

One way we could get around this problem is if we changed the actuator health check port to something else that Works.
Question:
How can we set the Actuator port to be the same as the App and make the actuator health check url which is something like http://localhost:8080/manage/health not return 501 Unimplemented from the Base Service Servlet ?

A: We can register DispatcherServlet with health endpoint in mapping before the ServiceServlet.
@SpringBootApplication
public class ServletInitializer extends SpringBootServletInitializer implements ServletContextInitializer {
    @Autowired
    private DispatcherServlet dispatcherServlet;

    @Override
    public void onStartup(ServletContext container) throws ServletException {
        ServletRegistration.Dynamic dispatcher =
                container.addServlet("dispatcher", dispatcherServlet);
        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/manage", "/manage/health");

        ServletRegistration.Dynamic application = container
                .addServlet("ServiceServlet", new ServiceServlet());
        application.setLoadOnStartup(2);
        application.addMapping("/*");
    }
}


text:
Q: Data not save in the database table I created sample java project and try to save data with JPA. able to connect with the database as well as able to create the related database table(named laptop) as well as. But when i try to save data(Laptop object). Those data not in the database table(in laptop table)
persistence.xml file
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
             http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
    <persistence-unit name="laptop_persist">
    <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
        <properties>
            <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
            <property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/device_store"/>
            <property name="hibernate.connection.autocommit" value="false"/>
            <property name="hibernate.connection.username" value="root"/>
            <property name="hibernate.connection.password" value="19940306"/>
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect"/>
            <property name="hibernate.connection.CharSet" value="utf8"/>
            <property name="hibernate.connection.characterEncoding" value="utf8"/>
            <property name="hibernate.connection.useUnicode" value="true"/>
            <property name="hibernate.show_sql" value="false"/>
            <property name="hibernate.hbm2ddl.auto" value="update"/>
        </properties>
    </persistence-unit>
</persistence>

Laptop.java class
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.logging.Logger;

@Entity
@Table(name = "laptop")
public class Laptop implements Device {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long lapId;
    @Column(name = "brand_name")
    private String brandName;
    @Column(name = "model_name")
    private String modelName;
    @Column(name = "serial_number")
    private String serialNumber;

    public Laptop(String brandName, String modelName, String serialNumber) {
        this.brandName = brandName;
        this.modelName = modelName;
        this.serialNumber = serialNumber;
    }

    public Laptop() {
    }

    public String getBrandName() {
        return brandName;
    }

    public void setBrandName(String brandName) {
        this.brandName = brandName;
    }

    public String getModelName() {
        return modelName;
    }

    public void setModelName(String modelName) {
        this.modelName = modelName;
    }

    public String getSerialNumber() {
        return serialNumber;
    }

    public void setSerialNumber(String serialNumber) {
        this.serialNumber = serialNumber;
    }

    public Long getLapId() {
        return lapId;
    }

    public void start() {
        System.out.println("Starting the" + serialNumber + " laptop...");
    }

    public void restart() {
        System.out.println("restarting the laptop...");
    }

    public void shutdown() {
        System.out.println("Shutting down the laptop...");
    }
}

Main.java class
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class Main {
    public static void main(String[] args) {
        Laptop laptop = new Laptop("aaa","bbb","cccc");
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("laptop_persist");
        EntityManager entityManager = entityManagerFactory.createEntityManager();
        entityManager.persist(laptop);
        entityManager.close();
        entityManagerFactory.close();
    }
}

pom.xml file
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>pc-hi</artifactId>
<version>1.0-SNAPSHOT</version>
<name>Archetype - pc-hi</name>
<url>http://maven.apache.org</url>

<dependencies>
  <dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.31</version>
  </dependency>
  <dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-core</artifactId>
    <version>5.5.7.Final</version>
  </dependency>
  <dependency>
    <groupId>org.testng</groupId>
    <artifactId>testng</artifactId>
    <version>6.9.6</version>
    <scope>test</scope>
  </dependency>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.5</version>
  </dependency>
</dependencies>
<build>
  <plugins>
    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-compiler-plugin</artifactId>
      <configuration>
        <source>8</source>
        <target>8</target>
      </configuration>
    </plugin>
  </plugins>
</build>

As I mentioned in above, the laptop table has created. But unable to save the data

A: As you turn off auto-commit (i.e hibernate.connection.autocommit=false) which is a good practise for changing the data , you have to explicitly declare when to start and commit the transaction.
Change to the following should fix the issue :
entityManager.getTransaction().begin();
entityManager.persist(laptop);
entityManager.getTransaction().commit();


text:
Q: Share extension without UI I've created a Share extension that will save a file URL to user default. The extension comes with a UI with Post and Cancel button. How can I remove this (the UI) so that when I press my share extension, it will straight away call the didSelectPost?
I'm using Swift 3 and building for iPhone

A: The template uses a SLComposeServiceViewController. Use a plain view controller instead. The entire interface, including providing a way to dismiss the view controller, will then be up to you.
(However, I can't help wondering whether what you really want might not be an Action extension.)


text:
Q: JSONPath extract string "where" JSON file I'm trying to run JSONPath on the below json file and extract all the IP Addresses (ip_prefix:) where the region equals "region: "ap-southeast-1""
https://ip-ranges.amazonaws.com/ip-ranges.json
My xpath skills are rusty, my JSONPath skills are novice!

A: Fixed it with guidance from the blog post samples ...
$.prefixes[?(@.region=="ap-southeast-2")].ip_prefix


text:
Q: specialize only (a part of) one method of a template class If I have a template class
template<typename T>
class C {
public:
    void method1() { ... }
    void method2() { ... }
    std::string method3(T &t) {
        // ...
        std::string s = t.SerializeToString();
        // ...
        return s;
    }
    // ...
};

and I want to specialize it for T = std::string but only changing method3(T&) (keeping all other methods), or even better, only that part of method3, which for T = std::string would simply become std::string s = t;, with minimum impact on current code (less repetition of methods signatures, less subclassing), how would I do it?
EDIT: I'm developing in C++11

A: You can use specialization like that (no need to specialize the whole class):
template<>
std::string C<string>::method3(string &t) {
    // ...
    std::string s = t;
    // ...
    return s;
}

A: If you only need to change s's initialization, you can use overloading:
std::string init(std::string& t)
{
    return t;
}

template <typename T>
std::string init(T& t)
{
    return t.SerializeToString();
}

template <typename T>
std::string method3(T &t) {
    // ...
    std::string s = init(t);
    // ...
    return s;
}

In C++17, you can use if constexpr:
std::string method3(T &t)
{
    if constexpr(std::is_same_v<T, std::string>)
    {
        std::string s = t;
        // ...
        return s;
    }
    else
    {
        std::string s = t.SerializeToString();
        // ...
        return s;
    }
}

In C++14, you can use static_if:
std::string method3(T &t)
{
    static_if(std::is_same<T, std::string>{})
    .then([](auto& x)
    {
        std::string s = x;
        // ...
        return x;
    })
    .else_([](auto& x)
    {
        std::string s = x.SerializeToString();
        // ...
        return x;
    })(t);
}


text:
Q: Why is Chrome skipping the numericality validation? I have this validation:
validates :year, :presence => true, :numericality => { :only_integer => true }, :uniqueness => true

This works fine in Firefox, but in Chrome the numericality validation isn't working. If I write 23ab is saved as 23 and doesn't show errors. Can be because of the tag input type number of HTML5?

A: Inspect the parameters actually being received by your action (i.e. check your development.log) and post information as to what's actually being sent to your controller in the params hash.
The validation in the model happens on the server side after the browser has transmitted the form data, before it's saved/updated in the database. So, if the exact same input from two different browsers produces different validation results, then it's probably being modified by the browser before it's being received by the controller action.
To say it another way: it's not the validation that is being skipped, it's the input data that's being modified, at least most likely. Inspect what's actually making it to your params hash and you'll be half way home.


text:
Q: How to use mutable data in future flutter? How can I use the MutableData? or is it already deprecated? I am currently creating a user information that will be send to firebase realtime database.
  addUser(User user) async {
    final TransactionResult transactionResult =
        await _counterRef.runTransaction((MutableData mutableData) async {
      mutableData.value = (mutableData.value ?? 0) + 1;

      return mutableData;
    });


text:
Q: Error when starting ghci with option -fexternal-interpreter -prof I am trying to see callstacks as explained here, https://simonmar.github.io/posts/2016-02-12-Stack-traces-in-GHCi.html
Unfortunately I am getting an error right after ghci starts :
C:\Users\sandwood>ghci -fexternal-interpreter -prof
GHCi, version 8.2.1: http://www.haskell.org/ghc/  :? for help
Access violation in generated code when reading 00000001001a0418

Any clue of what to do ?

A: It is known issue, see https://ghc.haskell.org/trac/ghc/ticket/14271
Looks like it occurs only on Windows.
Unfortunately I don't have anything to add, there is no known workaround.


text:
Q: When I get firebase data and I log it it returns the document file but when I output it it returns a promise I have been working with firebase and am having trouble with this code.
The goal of the code is to get the document data with the document id.
  const getPostData = async (postId) => {
    const postData = await getDoc(doc(db, 'posts', postId));
    console.log(postData.data()); // Returns the document data
    return postData.data();
  }
  const postData = getPostData(id);
  console.log(postData) // Returns a promise

I am extremely confused because I return the document data which when I log gives me the actual document data but when I set it as a variable it does not do the same.

A: When you use a function like async, it returns a Promise automatically. So the problem is in logic.
What happens:

*

*You call getPostData

*It is an async function, so, its return is Promise

*The larger scope is not an async scope, so the console.log is executed right after, not waiting for the execution of what is inside getPostData

*console.log returns a Promise
Try something like:
const [postData, setPostData]= useState()

const getPostData = async (postId) => {
  const postData = await getDoc(doc(db, 'posts', postId));
  if (postData.exists()) {
    console.log(postData.data()); // Returns the document data
    setPostData(postData.data());
  } else {
    console.log("No posts!");
  }
}
...
getPostData(id);
...
console.log(postData)

A: Since you've marked getPostData as async it returns a Promise and not an immediate value.
To get the value from the promise when calling getPostData, you can either use then():
getPostData(id).then((postData) => {
  console.log(postData)
})

Or you can use await:
const postData = await getPostData(id);
console.log(postData)


text:
Q: TypeError: missing 1 required positional argument while using pytest fixture I have written my test classes in a file and I am trying to use pytest fixtures so that I don't have to create the same input data in each test functions. Below is the minimal working example.
import unittest
import pytest

@pytest.fixture
def base_value():
    return 5

class Test(unittest.TestCase):

    def test_add_two(self, base_value):
        result = base_value + 2
        self.assertEqual(result, 7, "Result doesn't match")

However, when I test this using pytest-3, I get the following error:

TypeError: test_add_two() missing 1 required positional argument:
'base_value'

This is confusing for me since the base_value is clearly given as one of the arguments to test_add_two. Any help is highly appreciated.

A: This is because you are mixing pytest and unittest. Try
@pytest.fixture
def base_value():
    return 5

class Test:
    def test_add_two(self, base_value):
        result = base_value + 2
        assert result == 7, "Result doesn't match"

And in case of failure the error will be
def test_add_two(self, base_value):
        result = base_value + 2
>       assert result == 8, "Result doesn't match"
E       AssertionError: Result doesn't match
E       assert 7 == 8

But isn't pytest compatible with unittest?
Only on a limited basis. From Pytest unittest.TestCase Support

pytest features in unittest.TestCase subclasses The following pytest
features work in unittest.TestCase subclasses:

*

*Marks: skip, skipif, xfail;

*Auto-use fixtures;

The following pytest features do not work, and probably never will due
to different design philosophies:

*

*Fixtures (except for autouse fixtures, see below);

*Parametrization;

*Custom hooks;

Third party plugins may or may not work well, depending on the plugin
and the test suite.


text:
Q: Binding in a for loop I have a model which I can successfully bind on its own. But when I make a list of the model and loop through it my binding fails. The model looks like this:
public class SandwichViewModel
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int SelectedSize{ get; set; }
    public IList<SizeViewModel> SandwichSizes { get; set; }

}

I can successfully bind some radio buttons in my view that post back by doing this.
@using (Html.BeginForm("Add", "Basket", FormMethod.Post))
{
   @Html.RadioButtonFor(model => model.SelectedSize,Model.SandwichSizes[0].Id)
   @Html.RadioButtonFor(model => model.SelectedSize,Model.SandwichSizes[1].Id)
   @Html.RadioButtonFor(model => model.SelectedSize,Model.SandwichSizes[2].Id)

   @Html.HiddenFor(model => model.Id)

   <input type="submit" value="Add" />
}

This is where I post back:
    public ActionResult Add(SandwichViewModel sandwichViewModel)
    {
        if (ModelState.IsValid)
        {
           int test = SandwichViewModel.SelectedSize;
        }
        return RedirectToAction("Index", "Test");
    }

However I need multiple sandwiches to be displayed in the view. At first I just made a list of sandwiches and sent it through which didnt work, then I made a new model which just contains a List of the SandwichesViewModel.
public class MainViewModel
{
    public List<SandwichViewModel> SandwichView { get; set; }
}

Then in my view I looped through and gave each sandwich it's own form, like so.
@for (var i = 0; i < Model.SandwichView.Count(); i++)
{

using (Html.BeginForm("Add", "Basket", FormMethod.Post, new { id = Model.SandwichView[i].Id, name = Model.SandwichView[i].Id }))
{
    @Html.RadioButtonFor(m => m.SandwichView[i].SelectedSize, Model.SandwichView[i].SandwichSizes[0].Id)
    @Html.RadioButtonFor(m => m.SandwichView[i].SelectedSize, Model.SandwichView[i].SandwichSizes[1].Id)
    @Html.RadioButtonFor(m => m.SandwichView[i].SelectedSize, Model.SandwichView[i].SandwichSizes[2].Id)

    @Html.HiddenFor(m => m.SandwichView[i].Id)

    <input type="submit" />
}

}

However the Post is always returning back the value of 0 Id and SelectedSize. I really have ran out of ideas on how to fix this. I'm soon going to be adding checkboxes for optional ingredients but can't get any further.


text:
Q: Journey builder custom activity getting empty fields When journey activates and execute request triggers, we get empty fields data even though data is present in Data extension ( using {{Event."+ eventDefinitionKey +"."+ column +"}} to get the data from DE)
Actual Msg Content in Custom activity app - "Dear %%FirstName%%, We are delighted to enclose herewith a Proforma invoice for %%ExeMobile%% as requested by you . Please contact me for any further assistance. Regards, %%ExeName%%",
I want to dynamically replace this %%FirstName%% (FirstName is column in DE)
"mobileContent":{
"%%MobileNumber%%":""
},
"template_content":{
"%%FirstName%%":"",
"%%ExeMobile%%":"",
"%%ExeName%%":""
}
Now here above fields are coming empty as you can see.
Ideally it should be like this as below ( We received this when successfully run )
"mobileContent":{
"%%MobileNumber%%":"919xxxxxxx0"
},
"template_content":{
"%%FirstName%%":"Test",
"%%ExeEmail%%":"testmail@test.com"
}
Journey runs successfully sometime and sometimes it gives empty DE fields and not able to debug why I am getting such error even after all the configuration is correct with Custom activity. This generally happens when we create new version of Journey and sometimes when we copy the journey from existing.
Please help me out as this is critical.
Data is also present in Data extension still getting this error

A: There's no super simple way of doing this that'll catch your data bindings being invalidated in a Custom Activity due to reversioning, copying or editing the entry source, I'm afraid. You only get to check the EventDefinitionKey matches the saved inArguments in a couple of places - when the UI's loaded and you have access to Postmonger and when the Journey's activated and your Validate route's requested. In the event of copying or editing the journey, neither your UI nor the validate route's requested and your activity's ignorant of the change in the EventDefinitionKey. These are the only two occasions when your Custom Activity gets to check the EventDefintitionKey and compare it to your saved data bindings, however.
My recommendation firstly would be to check your saved data bindings when your Custom Activity's UI's loaded. In your handler for the Postmonger "initActivity" event, check that the EventDefinitionKey for the Interaction matches that of your data bindings in your inArguments, and if they don't, update those data bindings to match the new EventDefintionKey. Secondly, perform some sort of similar validation on your Validate endpoint. Inspect the saved interaction using the GET interactions/v1/interactions REST endpoint. If the data bindings and EventDefinitionKey do not agree, return a 400 error, or similar. There's currently no way to provide a user friendly message back to the user, but at least you'll prevent an invalid configuration being activated.


text:
Q: Using properties of determinants with row operations
My attempt: Multiples of rows are being added to other rows (should have no effect). V1 is multiplied by $7$ (determinant x 7) and V4 by 9 (determinant x 9), so final determinant should be 4 x 7 x 9 = $252$.
What am I doing wrong?
Edit: I got the right answer but can somebody explain why in user8795's answer, the final answer is not multiplied by 1/2 x 1/2 to change the second and third row from $2v_2$ and $2v_3$  to $v_2$ and $v_3$, since that's what's there in the given matrix?

A: Hint:
\begin{bmatrix}
    7v_1 +2v_4     \\
    2v_2      \\
    2v_3    \\
    5v_1+9v_4
\end{bmatrix}
= \begin{bmatrix}
    7v_1      \\
    v_2      \\
    v_3    \\
    9v_4
\end{bmatrix}
+\begin{bmatrix}
    2v_4     \\
    v_2      \\
    v_3    \\
    5v_1
\end{bmatrix}
=$7\times9 \times4- 5 \times2\times4 = 53\times4$