text:
Q: Resource files creates unnecessary ULS log entries We're using resource files to handle UI-constants. This is working out alright. The problem is that we're getting lots of 'High'-level logging entries in ULS. They look like the following:
Failed to open the file 'C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\Resources\ProjectResources.en-US.resx'.
#20015: Cannot open "": no such file or folder.
(#2: Cannot open "": no such file or folder.)
Failed to read resource file "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\Resources\ProjectResources.en-US.resx" from feature id "(null)".

We are only going to use english language resources for now, but what's nice with resource files is that we can add support for other languages later.
Our resource file has the name ProjectResources.resx. If I add a file named ProjectResources.en-US.resx, I can't deploy my solution until I add my constants there as well (what happened to  the fallback mechanism?). After I've added my constants to the en-US file, I obviously want to delete my constants in the root file to prevent having duplicate entries. The problem is then that any other language locale won't find any resource file.
So my question is: How can I structure my resource files to

*

*Not have my ULS-log spammed, even if it works, and

*Avoid duplicate entries in the resource files?

A: I have the same issue in our SharePoint projects, but gave up on it because it appeared that SharePoint wasn't applying the resource fallback mechanism like I expected it to.  Then I saw this post and decided to research this a little.
I came across this article http://msdn.microsoft.com/en-us/library/ee696750.aspx and it says that a Default resource is:

Also known as a fallback resource, default resource files contain
  strings localized for the default culture, such as English. They are
  used if no localized resource files for the specified language can be
  found. Default resources do not have separate files, they are stored
  in the main application assembly.

I didn't know this, especially that the default resources are embedded into the assembly. The instructions to add this are unclear:

To specify default resource files in Visual Studio SharePoint
  projects, select Invariant Language (Invariant Country) in the culture
  list of the Add Resource dialog box when you add a resource file.

Turns out this is in the Properties of the Visual Studio project. Click on the Resources tab, and you'll see a message that the project doesn't contain any default resource files.
However, I don't see the ability to choose the culture of the default resource file.
By the way, I've seen that this issue only happens to Resource files in 14\Resources, not to the ones deployed to App_GlobalResources in IIS.
I'll keep looking and update my answer if I figure it out.

A: SharePoint fallback is not like the ASP.NET fallback to the invariant culture; is first use the thread CurrentUICulture, then fallback to the SPWeb.Language: http://blogs.msdn.com/b/sharepointdev/archive/2011/07/01/localizing-the-sharepoint-user-interface-by-using-resource-files-sanjay-arora.aspx


text:
Q: Opening a file with a # in its path using the default application from Excel 2007 I have a pdf file which is located at "D:\some\#folder\filename.pdf". And want to open it from an Excel worksheet by clicking on a hyperlink (or something similar).
Just creating a hyperlink does not work, because it fails at the # character. Instead of opening the pdf, the folder "D:\some\" is opened in Windows Explorer.
Changing the pathname (i.e. moving the file) is not an option, because a lot of other programs and scripts rely on its location. Replacing # with %23 does not work ("File not found.").
I found an official workaround, but it only seems to work when referencing cells in other Excel files at "unsupported" locations, not other file types.
Creating a shortcut to the pdf and hyperlinking to the shortcut (as suggested in a related answer) works, but leads to annoying security alerts which I would like to avoid.
What else can I do to emulate hyperlink behavior?

redpajama_set_name: RedPajamaStackExchange


text:
Q: 'UserLoginForm' object has no attribute 'cleanned_data' Django Hello i have some trouble with authentification in Django so that's what i have in view.py
    from django.shortcuts import render, redirect
    from django.contrib.auth import authenticate, login, logout, get_user_model
    from django.shortcuts import render
    from django.views import generic
    from FS import forms

    from .forms import UserLoginForm, UserRegisterForm

def login_view(request):
    form= UserLoginForm(request.POST or None)
    title = "Connexion"
    if form.is_valid():
        username = form.cleanned_data.get("username")
        password = form.cleanned_data.get("password")
        user = authenticate(username=username, password=password)
        login(request.user.is_authenticated())

    return render(request,"forms.html",{"form":form, "title": title})

def register_view(request):
    print(request.user.is_authenticated())
    title= "Inscription"
    print(request.user.is_authenticated())
    form = UserRegisterForm(request.POST or None)
    if form.is_valid():
        user = form.save(commit=False)
        password = form.cleanned_data.get('password')
        user.set_password(password)
        user.save()
        login(request, user)
        print(request.user.is_authenticated())
        #redirect

    context = {
    "form":form,
    "title":title
    }
    return render(request,"forms.html", context)

def logout_view(request):
         logout(request)
         return render(request, "forms.html")

and that's in forms.py
from django.contrib.auth.models import User
from django import forms
from django.contrib.auth import authenticate, login, logout, get_user_model

from django.forms import ModelForm

User = get_user_model()

class UserLoginForm(forms.Form):
    username = forms.CharField()
    password= forms.CharField(widget=forms.PasswordInput)

    def clean(self, *args, **kwargs):

        username = self.cleanned_data.get('username')
        passworrd = self.cleanned_data.get('password')

        if username and password:
            user = authenticate(username=username, password=password)
            if not user:
                raise forms.ValidationError('This user does not exist')
            if not user.check_password(password):
                raise forms.ValidationError('Mot de passe incorrecte')
            if not user.is_active:
                raise forms.ValidationError('plus valide')
        return super(UserLoginForm, forms).clean(*args, **kwargs)

class UserRegisterForm(forms.ModelForm):

    class Meta:
        model = User
        fields = ['username', 'password']

and there is always this error "'UserLoginForm' object has no attribute 'cleanned_data'"
I don't understand, i don't know how to make a form.is_valid() before. I can't see how to change my code to have the same thing

A: It's form.cleaned_data, not form.cleanned_data.
To know more about Django Forms, refer the documentation..

A: You may need to change form.cleanned_data to form.cleaned_data.


text:
Q: How to add multiple page number in a xsl tag I want to add a page number when there is more than one page in a xsl tag.
<Page Lien="../pages/Q_MLMQ_20220604_00000_N_002_003Y.pdf">02</Page>

In this example the page numbers are 02, and 003 (but i want to delete the 0).
If at the end there is a Y.pdf, i need the page number before the Y.pdf
<Page>2,3</Page>

If it's N.pdf, i do not need the page number before the N.pdf since it's only one page
<Page Lien="../pages/Q_MLMQ_20220604_00000_N_017_017N.pdf">17</Page>

<Page>17</Page>

Here's how i did it (but i only get page 2)
<xsl:if test="@Lien">

<xsl:element namespace="http://www.cedrom-sni.com/schema/newsv1.xsd" name="page">

<xsl:value-of select="format-number(..//Page, '#')"/>

</xsl:element>

</xsl:if>

I get
<Page>2</Page>

Thank you

A: Consider the following minimal example:
XML
<Pages>
    <Page Lien="../pages/Q_MLMQ_20220604_00000_N_002_003Y.pdf">02</Page>
    <Page Lien="../pages/Q_MLMQ_20220604_00000_N_017_017N.pdf">17</Page>
</Pages>

XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:strip-space elements="*"/>

<!-- identity transform -->
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="Page">
    <xsl:copy>
        <xsl:choose>
            <xsl:when test="contains(@Lien, 'Y.pdf')">
                <xsl:call-template name="tokenize">
                    <xsl:with-param name="text" select="substring-before(substring-after(@Lien, '_N_'), 'Y.pdf')"/>
                </xsl:call-template>
            </xsl:when>
            <xsl:when test="contains(@Lien, 'N.pdf')">
                <xsl:value-of select="number(substring-before(substring-after(@Lien, '_N_'), '_'))" />
            </xsl:when>
        </xsl:choose>
    </xsl:copy>
</xsl:template>

<xsl:template name="tokenize">
    <xsl:param name="text"/>
    <xsl:param name="delimiter" select="'_'"/>
    <xsl:value-of  select="number(substring-before(concat($text, $delimiter), $delimiter))" />
    <xsl:if test="contains($text, $delimiter)">
        <xsl:text>,</xsl:text>
        <!-- recursive call -->
        <xsl:call-template name="tokenize">
            <xsl:with-param name="text" select="substring-after($text, $delimiter)"/>
        </xsl:call-template>
    </xsl:if>
</xsl:template>

</xsl:stylesheet>

Result
<?xml version="1.0" encoding="UTF-8"?>
<Pages>
  <Page>2,3</Page>
  <Page>17</Page>
</Pages>


text:
Q: Probability of k triangles in a random graph Let $G_{n,p}, n\in \mathbb{N}, p\in(0,1)$ be the binomial random graph, i.e. a graph on $n$ vertices where an edge is in $G_{n,p}$ with probability $p$ and denote as $V$ its vertex set.
Let $j\in \binom{V}{3}$ be a set of 3 vertices and denote as $\mathcal{E}_j$ the event that $j$ is a triangle. In terms of $p$, what is the the following probability?
$$\mathbb{P}\left(\bigcap_{j=1}^k \mathcal{E}_j\right),$$
i.e. the probability that $k$ such sets of 3 vertices are all triangles. I have trouble counting the cases where edges are in several triangles...

A: If I understood correctly, you are given a vertex set, e.g. $V = \{1,2,3,4,5,6,7\}$. You pick $j_1 = \{1,2,4\}$ (for example), and $j_2 = \{2,1,3\}$. The edge set $\{12,14,24\}$ forms the first triangle, and the edge set $\{12,23,13\}$ forms the second triangle. The cardinality of the union of the two edge sets is $5$, and hence $P(\mathcal{E}_{j_1}\cap\mathcal{E}_{j_2}) = p^5$. Since you allow to pick $\mathcal{E}_j$s arbitrarily, I see no way but to calculate the edge sets, take their unions and then calculate the cardinality, raise $p$ to that cardinality.


text:
Q: Select a father div from the hover of a child div Can I select and affect the parent div, when I am on over the child div with hover? My question is if it is possible and how, in advance I apologize for my English.

Wa

sup

.container{
    background: red;
}

.child-1:hover > .container{
    background: blue;
}


text:
Q: Is setting lambda equal to zero the same thing as not applying regularization at all? If I set the regularization parameter to 0, does it essentially mean I'm not applying regularization (I've boxed the regularization bits in red)?
Also, what is this type of regularization called?

A: *

*When $\lambda=0$, no regularization is applied. Zero multiplied by any number is zero.

*Penalizing squared coefficients is sometimes called ridge-regression, or L2 regularization. Other kinds of regularization include the LASSO or L1 regularization, which penalizes the absolute value of the coefficients. Elastic net regression is a compromise between the two, which includes both LASSO and includes both ridge regressions as special cases.

A: Yes. The regularization term vanishes when $\lambda = 0$.

A: Exactly! You can think of the cost function as having two parts:

*

*A "cost" associated with the difference between your model and the data, plus

*A "cost" for having two many non-zero coefficients.

The $\lambda$ term sets the weight on the second part of the cost function. If it's zero, then that entire term goes to zero  $\forall x, 0x=0$) and it is as if regularization were never applied.

A: Consider an extreme case in which 2 of your variables are absolutely collinear, without regularization their coefficient estimates will explode into infinite solution space, but with regularization, even with the regularization parameter tending to zero, we will have stable values. One of the uses of regularization is to tackle multicollinearity.


text:
Q: problem with receiving structure with nrf24l01 using stm32 I am sending a structure that contains three float values and a uint64_t using stm32f103RE and nrf24l01 and receiving it via an stm32f103C8. the problem that I have is that the uint64_t is received correctly but the float values are received as zeros. the float values that I'm talking about are coordinate values that I'm getting from sim808. I can't share my whole code because it's too long but I can show the related parts of the code.
the transmitter code is as follows:
struct MyData
{
  uint64_t car_id;
  float latitude_t;
  float longitude_t;
  float speed_t;
};

float latitude,longitude,speed;
int main()
while (1)
{
if (NRF24_write(&nrf_data,32))

            {
                usart_sendstring("transmitted successfully");

            }
            HAL_Delay(1000);
}

the receiver code is as follows :
   float latitude;
    float longitude;
    float speed;
    uint64_t car_id;

    struct MyData
    {
      uint64_t car_id;
      float latitude_t;
      float longitude_t;
      float speed_t;
    };
    int main()
            while(1)
            {
                    struct MyData nrf_data;
                    if (NRF24_available())
                    {
                            NRF24_read(&nrf_data,24);
                            char str[50];
                            char str2[50];
                            latitude=nrf_data.latitude_t;
                            longitude=nrf_data.longitude_t;
                            speed=nrf_data.speed_t;
                            car_id=nrf_data.car_id;
                            sprintf(str2,"car code :%llu \n https://maps.google.com/?
                            q=%.6f,%.6f",car_id,latitude,longitude);
                            Send_SMS(str2);
                    }
            }

what might be the problem here?

A: I figured out the problem I had was in other parts of my code and I fixed it now it works fine. the structure part was clean so I leave it here if anyone wants to use it.


text:
Q: Why am I getting generic "TypeError: Failed to fetch" errors? When fetching from some APIs, I get TypeError: Failed to fetch errors.
For example, the URL used in the snippet below is an example provided by an API provider. It can be accessed without a key. It works fine in my browser but will throw an error in my code.
Fetching from another public API, https://api.punkapi.com/v2/beers/random, works perfectly.
What is the difference between these APIs that prevents me fetching from some and works for others others?
export default function App() {
  useEffect(() => {
    fetch(
      'https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=439d4b804bc8187953eb36d2a8c26a02'
    )
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => {
        console.error(error);
      });
  }, []);

  return null;
}

A: you can't get data from samples
caused API is blocked due to CORS header 'Access-Control-Allow-Origin' missing
you need to generate api key(https://openweathermap.org/price) and connect to api
//ex:
api.openweathermap.org/data/2.5/weather?appid={your api key}&....


text:
Q: Mini cart is displaying the configurable product image instead of simple product now, from similar questions on mag stack exch, I noticed that its possibly a problem with cartcontroller.php in which I have the following
        if (!$this->_getSession()->getNoCartRedirect(true)) {
            if (!$cart->getQuote()->getHasError()) {
                $message = $this->__('%s was added to your shopping cart.', Mage::helper('core')->escapeHtml($product->getName()));
                $this->_getSession()->addSuccess($message);
            }
            $this->_goBack();
        }

or there may be aproblem in checkout.xml with Itemrenderers in which i have the following
<reference name="right">
        <block type="checkout/cart_sidebar" name="cart_sidebar" template="checkout/cart/sidebar.phtml" before="-">
            <action method="addItemRender"><type>simple</type><block>checkout/cart_item_renderer</block><template>checkout/cart/sidebar/default.phtml</template></action>
            <action method="addItemRender"><type>grouped</type><block>checkout/cart_item_renderer_grouped</block><template>checkout/cart/sidebar/default.phtml</template></action>
            <action method="addItemRender"><type>configurable</type><block>checkout/cart_item_renderer_configurable</block><template>checkout/cart/sidebar/default.phtml</template></action>
            <block type="core/text_list" name="cart_sidebar.extra_actions" as="extra_actions" translate="label" module="checkout">
                <label>Shopping Cart Sidebar Extra Actions</label>
            </block>
        </block>
    </reference>

A: You can change the settings in admin section. Navigate to

Admin > System > Configuration > Checkout > Shopping Cart >  Configurable Product Image as Product thumbnail itself

It'll render Child product image(Simple Product) in cart section.


text:
Q: Understanding time complexity, big-O notation Edit- this question is from a former test in my course, the official answer is O(n)
I need help understanding why does the run-time complexity in the following code is O(n) and not O(n*log(n))
def fun(n):
   total = 0
   while n > 5:
       n = n // 2
       total += sum(range(n))
   return total

The while loop executes log(n) times, and in each iteration the sum function sums n/2 numbers, therefore it's complexity is o(n), I see that each while iteration there's less numbers to sum, but i don't understand why it's O(n).
Thank you.

A: So I've figured it out.
Each while iteration sums n/2 items. which means total iterations are n\2 + n\4 +n\8 +..., and this sum converges to n


text:
Q: how to add the string to parameters I want to add the parameters in type of string. I am using following method
to adding the data.
 let param = ["user_id": "5","start_date": start,"end_date" : end,"start_time": start_Time,"end_time":end_Time,"departure_time":departure_Time,"payment_email":paymentEmailTextField.text!,"tripData":String1 ,"image": imageData] as [String : Any]

I add to the "tripData" value by String1
var String1 = """
{
"trip_types":"\(preferedSelectString)",
"attractions": \(addAttractionArray),
"description": "\(self.tripDescriptionTextFiled.text!)",
"type": "\(search_type)",
"cost" : "\(self.priceperPersonTextField.text!)",
"location": "\(self.countryLabel.text!)",
"title": "\(self.tittletripTextField.text!)",
"max_persons": "\(self.peopleCountLabel.text!)",
"advance": "\(self.loadingDepositeTextField.text!)",
"address": "\(self.googleAddressTextField.text!)",
"city": "\(self.cityLabel.text!)",
"state": "\(self.state)",
"country": "\(self.countryLabel.text!)",
"amenities": "\(self.amenitiesString)"
}
"""

just printed my console the string1 display the data
{
"trip_types":"5",
"attractions": [],
"description": "des",
"type": "0",
"cost" : "100",
"location": "India",
"title": "tittle",
"max_persons": "3",
"advance": "50",
"address": "Vadapalani",
"city": "Chennai",
"state": "Tamil Nadu",
"country": "India",
"amenities": "wifi"
}

But i print the param value does not properly display the data
["tripData": "{\n\"trip_types\":\"5\",\n\"attractions\": [],\n\"description\": \"des\",\n\"type\": \"0\",\n\"cost\" : \"100\",\n\"location\": \"India\",\n\"title\": \"tittle\",\n\"max_persons\": \"3\",\n\"advance\": \"50\",\n\"address\": \"Vadapalani\",\n\"city\": \"Chennai\",\n\"state\": \"Tamil Nadu\",\n\"country\": \"India\",\n\"amenities\": \"wi\"\n}", "start_time": "11:00:00", "image": [473044 bytes], "end_time": "10:00:00", "user_id": "5", "payment_email": "add@gmail.com", "start_date": "2018-03-20", "end_date": "2018-03-20", "departure_time": "10:00:00"]

In param data \n\",\" these values are added Automatically.so Json values are not added in parameters.
i want to display the data following type
["tripData": {"trip_types":"1,2,3", "attractions":["something","somecontent"], "description":"Come with me to see","type":"1","cost":"120", "location":"Australia","title":"OLD TOWN CASTLE TOUR", "max_persons":"2","advance":"120", "address":"something","city":"chennai","state":"Tamilnadu","country":"", "amenities":"wifi,photo"},"start_time": "11:00:00", "image": [473044 bytes], "end_time": "10:00:00", "user_id": "5", "payment_email": "add@gmail.com", "start_date": "2018-03-20", "end_date": "2018-03-20", "departure_time": "10:00:00"]

tripData value is String Format.
"tripData" have a separate string in Type(String1). how to sent the parameters with in the string. Please Help me!

A: You can use JSONEncoder to convert JSON data to String
    let param = ["user_id": "5"]
    let encoder = JSONEncoder()
    if let jsonData = try? encoder.encode(param) {
        if let jsonString = String(data: jsonData, encoding: .utf8) {
            print(jsonString)
        }
    }

A: param["tripData": "{\n\"trip_types\":\"5\",\n\"attractions\": [],\n\"description\": \"des\",\n\"type\": \"0\",\n\"cost\" : \"100\",\n\"location\": \"India\",\n\"title\": \"tittle\",\n\"max_persons\": \"3\",\n\"advance\": \"50\",\n\"address\": \"Vadapalani\",\n\"city\": \"Chennai\",\n\"state\": \"Tamil Nadu\",\n\"country\": \"India\",\n\"amenities\": \"wi\"\n}", "start_time": "11:00:00", "image": [473044 bytes], "end_time": "10:00:00", "user_id": "5", "payment_email": "add@gmail.com", "start_date": "2018-03-20", "end_date": "2018-03-20", "departure_time": "10:00:00"]

Here you are adding only 1 key-Value of type [String:String]. Before setting the value for key "tripData" make sure you have converted the JSON string into the Dictionary format.
You haven't converted the JSON string into Dictionary. that's why it is considering it as a string.
Make sure you are converting the String into Dictionary before parsing.


text:
Q: How to insert multiple rows for a single primary key? I have a table named 'Patient_detail'. There are 4 columns in this table. They are:

*

*patient_id primary key(not null)

*visit_serial_ID primary key(not null)

*examination

*plan
Now, how can I insert multiple records in 'examination' and 'plan' column against the   single primary key 'patient_id' and 'visit_serial_ID' of the table 'Patient_detail'?
The datatypes of the fields are as follows:

*

*patient_id: number(11)

*visit_serial_ID: number(5)

*examination: varchar2(50)

*plan: varchar2(50)

A: You can do this but your primary key would cease to be a primary key and you data would be denormalized.  The best way to do this would be to split this table into two separate tables like this:
Patients
----------
PatientId

Visits
----------
VisitSerialId
Examination
Pland
PatientId

Notice that the Visits table has a foreign key realtionship to the Patients table.  This will allow you to have the 1:M relationship you are looking for.

A: You can't. That's what a primary key is - something that is unique to every row. You would need a separate table with its own primary key, and with a foreign key relationship to this table, in order to store multiple entries. This would then be a straightforward one-to-many relationship.

A: You can't (that's the whole point of a primary key - you have one row per value). You need to split this into a couple of tables, one for visits and one for patients. The visit table would have a foreign key relationship to the patient table's primary key column.
EDIT
You need to think about what actual real-life things you are representing, and how they interrelate. For each separate real-life thing, you would usually have a separate table. This allows the one-to-one, many-to-one, many-to-many relationships that you are after. For instance, you are representing a patient who has a visit, during which there are a number of examinations, each of which has a corresponding plan (is this correct?). You should therefore have a patient table containing patient data, a visit table, containing visit data, and an examination table containing examination data, and maybe even a plan table containing plan data.
The visit table has a many-to-one relationship with the patient table (a patient can visit a number of time). To achieve this, it should have a foreign key to the patient_id column. Similarly, the examination table has a many-to-one relationship with the visit table, so, again, it should have a foreign key to the visit table's primary key.
There are further ways that the can be separated. As Sascha said, look up normalisation.

A: As darasd said you can't. What you're looking for is call normalization.


text:
Q: Hook Chrome debugger up to text editor
Is there some way to get chrome to launch my text editor when I click on a stack trace link pointing to a file:// url?

A: If you have relatively many files, you could try the Eclipse-based project:
http://code.google.com/p/chromedevtools/
If you manage to set up source lookup, you will have debugger stepping over your working files and live editing.
Together with JSDT or Aptana installed this may be quite usable.
However you will get only JS debugger, DOM tree is not supported.

A: At the moment the only way to achieve this is to modify DevTools front-end code(it's HTML+JavaScript so it shouldn't be too hard) to customize link clicks handling. There is a WebKit feature request for this functionality: https://bugs.webkit.org/show_bug.cgi?id=51526


text:
Q: c++ call method on abstract class returned by a function I thing I'm missing something obvious but here is my problem
with a pure abstract class IFoo
class IFoo
{
 public:
    virtual bool isBar1() const=0;
    virtual bool isBar2() const=0;
};

and 2 implementations
class Foo1 : public IFoo
{
 public:
    bool isBar1() const override { return true;}
    bool isBar2() const override { return false;}
};

class Foo2 : public IFoo
{
 public:
    bool isBar1() const override { return false;}
    bool isBar2() const override { return true;}
};

I have a managing class that must call the right method depending on a variable protocol
class FooManager : public IFoo
{
 public:
    bool isBar1() const override
    {
      switch(protocol)
      {
        case 1: return Foo1().isBar1();
        case 2: return Foo2().isBar1();
        default: return false;
      }
    }
    bool isBar2() const override
    {
      switch(protocol)
      {
        case 1: return Foo1().isBar2();
        case 2: return Foo2().isBar2();
        default: return false;
      }
    }
    void setProtocol(int proto){this->protocol = proto;}
 private:
    int protocol{0};
};

But there is a bunch of methods and I don't want to put the switch(protocol)everywhere given that it's really repetitive and new FooX could be added at anytime.
How can I call the right override without using templates (given that protocol is dynamic and FooManager is persistent)
and without using the heap on every call (through smart pointer or the likes because it's for an embedded project where we try to stay on the stack as much as possible).
I can't just create a getFoo() method that return IFoo because it's an abstract class
And I can't return an IFoo& neither because it would return a reference to a temporary.
IFoo& FooManager::getFoo()
{
      switch(protocol)
      {
        case 1: return Foo1();
        case 2:
        default:  return Foo2();
      }
  //return reference to temporary
}

What else can I do?

A: You could return a unique_ptr, such as
std::unique_ptr<IFoo> FooManager::getFoo() {
    switch (protocol) {
        case 1: return std::make_unique<Foo1>();
        case 2:
        default: return std::make_unique<Foo2>();
    }
}

This would result in the data being a pointer and polymorphism being applied on calling the member functions

A: You can return a std::unique_ptr so you get polymorphic behavior but can control the lifetime of the returned object.
std::unique_ptr<IFoo> FooManager::getFoo()
{
      switch(protocol)
      {
        case 1: return std::make_unique<Foo1>();
        case 2:
        default:  return std::make_unique<Foo2>();
      }
}

A: Since you have a very specific requirement I suggest a very specific solution for this exact problem (which may not be suitable elsewhere). In order to avoid having to use dynamic allocation and pointers or references you can "fake" polymorphism using function pointers. A small example given the requirements you mentioned in your comments:
class Foo {
    public:
    // function pointer aliases to make them easier to use
    // I opted to make the two functions take different parameters for demonstration purposes
    using isBar1Func = bool(*)(const Foo*);
    using isBar2Func = bool(*)(int);
    // constructor requiring the function pointers as parameters
    Foo(int value, isBar1Func bar1func, isBar2Func bar2func) :
        m_value(value), m_bar1Func(bar1func), m_bar2Func(bar2func) {}

    bool isBar1() const {
        return m_bar1Func(this);
    }

    bool isBar2() {
        return m_bar2Func(m_value);
    }

    int getValue() const {
        return m_value;
    }

    private:
       int m_value;
       isBar1Func m_bar1Func;
       isBar2Func m_bar2Func;
};

// example functions to be passed into the constructor
static bool testBar1Func(const Foo* foo) {
    return foo->getValue() != 0;
}

static bool testBar2Func(int value) {
    return value > 1;
}

// getFoo can simply return a copy
Foo FooManager::getFoo() {
    switch (protocol) {
        case 1: return Foo(1, testBar1Func, testBar2Func);
        // also works with non-capturing lambdas, which can be converted to function pointers
        case 2: return Foo(2,
                           [](const Foo* foo) { return foo->getValue() != 1; },
                           [](int value) {return value != 12; });
        // add remaining cases as desired
    }
}

A: Thanks to @UnholySheep response, here is what I ended with:
class FooManager : public IFoo{
  public:
     using FooFunc = bool(*)(const IFoo&);

     bool callFoo(FooFunc function) const{
        switch(protocol) {
          case 1: return function(Foo1());
          case 2: return function(Foo2());
          //and the other cases
        }
    }
    bool isBar1() const override {
       return callFoo([](const IFoo& foo){return foo.isBar1();});
    }
    bool isBar2() const override {
       return callFoo([](const IFoo& foo){return foo.isBar2();});
    }
};

my FooX classes stay the sames and the switch(protocol) is in a single function meaning that if a new protocol arrives, I just have to create a new FooY for that protocol and add it to the switch to get it working. All that with compile time checks and no use of the heap.
Thanks again @UnholySheep and the others as well.


text:
Q: Update array of object in React useState I have a class ListItem which is a list of Item. It got some function like setItem that update an item in the list and addItem that add an item and filterItem that set visible
Item is an object that looks like {name,number,discount,visible}
I have a view ListItemView with a pseudo code like this
export default function ListItemView() {

    const [items, setItems] = useState([])

    useEffect(() => {
        setItems(new ListItem(getItems()))
    }, [])

    function toggleChange(f,newF){
        setItems((current) => current.setItem(f,newF))
    }

    function filter(search){
        setItems(Items.filterItem({search}))
    }

    return (
        <>
            <button onClick={() => setItems(items.addItem())}> ADD Item</button>
            <input onChange={(e) => filter(e.target.value)} />
            {items.items.map((Item) =>
               !item.visible && item.visible !== undefined  ? null :

                  <ItemLine f={item} toggleChange={toggleChange} />

            )}
        </>
    )
}

And ItemLine is just a component that display inputs with the datas of my item
So there is my questions :

*

*To update my items, am I forced to use setItems everytimes ? Because it's causing the full rerender of the page, that's quite dumb for me because when we are just setting 1 data in one object of an entire list ?

*My filter function is quick when I'm typing (to filter on my list), but it's pretty slow when I have to reshow every items in my list, with 300 items it would be unusable, how can I change this ?

*I have heard of ReactHook form, would it work for me here ?
Thanks for your expertise :)

A:
To update my items, am I forced to use setItems everytimes ? Because
it's causing the full rerender of the page, that's quite dumb for me
because when we are just setting 1 data in one object of an entire
list ?

Yes you need to call setItems to update your state even if it is to add one element or to update one.
However you can optimise on re-renders by converting your mapped values to components and using React.memo to avoid re-renders .
function Item = React.memo(({item, toggleChange}) => {
   return !item.visible && item.visible !== undefined  ? null :

                  <ItemLine f={item} toggleChange={toggleChange} />

})
export default function ListItemView() {

    const [items, setItems] = useState([])

    useEffect(() => {
        setItems(new ListItem(getItems()))
    }, [])

    // using useCallback to have only one instaance of toggleChange being created even on re-renders
    const toggleChange = useCallback(function toggleChange(f,newF){
        setItems((current) => current.setItem(f,newF))
    }, []);

    function filter(search){
        setItems(Items.filterItem({search}))
    }

    return (
        <>
            <button onClick={() => setItems(items.addItem())}> ADD Item</button>
            <input onChange={(e) => filter(e.target.value)} />
            {items.items.map((Item) =>
               <Item key={item.id} item={item} toggleChange={toggleChange}/>
            )}
        </>
    )
}

My filter function is quick when I'm typing (to filter on my list),
but it's pretty slow when I have to reshow every items in my list,
with 300 items it would be unusable, how can I change this ?

If you are rendering large lists, you should aim towards virtualising those, i.e rendering only items that are in the view. react-window and react-virtualized are popular libraries that you can explore for that.


text:
Q: angularjs adding an item to array without $index key <input name="options[{{$index}}]"  ng-repeat="n in [] | range:count"
       ng-model="field.options[$index].value" >

in the conttroller
$scope.field.options = [];

when i add item to array it s saving them with key.
"options":{"0":{"value":"sdfas"},"1":{"value":"sdfsdf"},"2":{"value":"sdfasdf"}}

I wanna remove that "0" "1" ..
the reason i wanna remove the key is i think my api not work because of this keys.
When i post my objcet like:
List<someobject> options;

and someobject class has only value field.


text:
Q: No. of ways 9 prizes can be given to 5 students with a condition
Number of ways 9 prizes can be given to 5 students if one particular student receives 4 prizes and the rest of the students can get any number of prizes is?

My Attempt:
I got the possibilities for distribution of prizes as,
$(4,0,1,1,3)$
$(4,1,1,1,2)$
$(4,0,0,3,2)$
Solving further includes permutations of the prizes,
$5![\frac{9!}{4!2!3!} + \frac{9!}{4!3!2!} + \frac{9!}{4!2!3!2!}]$
However, solving this gives me a wrong answer.
Any help would be appreciated.

A: Following your approach, the distribution of prizes (we assume that they are distinguishable) should be
$$({\bf 4},1,1,1,2),({\bf 4},0,1,1,3),({\bf 4},0,1,2,2),({\bf 4},0,0,1,4),({\bf 4},0,0,2,3),({\bf 4},0,0,0,5)$$
and including the permutations of the remaining $5$ prizes and of the other $4$ students we obtain
$$\binom{9}{4}\left(\frac{4!}{3!1!}\cdot \frac{5!}{1!1!1!2!}+
\frac{4!}{1!2!1!}\cdot \frac{5!}{0!1!1!3!}+\dots+\frac{4!}{3!1!}\cdot \frac{5!}{0!0!0!5!}\right)=129024.$$
The same result can be obtained in a simpler way as
$$\binom{9}{4}\cdot 4^5=129024$$
where $\binom{9}{4}$ is the number of ways to assign $4$ prizes to the particular student and $4^5$ is the number of ways to give each of the remaining $5$ prizes to one of the other $4$ students.

A: Ok so there are 9 prizes 5 students but one student got 4 prizes [Assume he is particular one,Also assume all prizes are same]
There are 5 Prizes and 4 Students.
Only one student get 5 prizes(5,0,0,0)+(0,5,0,0)+(0,0,5,0)+(0,0,0,5)
So number of ways=4
Now one student got 4 and one got 1 rest got nothing
=factorial_r(4)/factorial_r(2)
That is 12 ways
Now one student got 3,second got 1,third one got 1
Now it is factorial_r(4)/factorial_r(1)
That is 24 ways
Now 3 all got 1 prize and one got 2 it is factorial_r(4)
That is 24 ways
Total= 4+12+24+24
That is 64 ways.
If 4 prizes won by student is not particular then
4*64= 256 ways
If all prizes were different then it is different story!


text:
Q: How to iterate list in numpy and avoid TypeError: Only integer scalar arrays can be converted to a scalar index I am using numpy:
I have a list:[array([2, 5, 0, 6, 6, 0, 2, 0]), array([3, 2, 5, 4, 4, 5, 6, 0]), array([1, 1, 5, 1, 4, 6, 0, 0]), array([1, 3, 5, 4, 2, 2, 5, 3]), array([5, 0, 6, 3, 1, 0, 5, 3]), array([1, 5, 1, 6, 0, 3, 5, 5]), array([4, 6, 1, 1, 3, 5, 2, 6]), array([5, 5, 1, 2, 6, 0, 5, 0])] <class 'list'>
I want to be able to iterate each array in the list and pass it through a function and make a new list of outcomes for that I have this:
fit=[]
for i in collection:
    state = collection[i]
    test = Review(state)
    fit.append(test.function())
print(fit)

But I get the following type error:

TypeError: only integer scalar arrays can be converted to a scalar
index

i needs to be an int but in this case, it would be an array from the list and what I need to do is pass each array to this function to get a result and add this to the new fit list

A: The for loop iterates over collection and as such i will be an element of collection. You're getting the error because i is not an int. Also the line state = collection[i] is redundant. Instead you can simply do state = i
After your comment, if you would like to iterate over the inner arrays you will need a second loop. To take your example of summing the arrays it would look something like this:
for i in collection:
    arr_sum = 0
    for j in i:
        arr_sum += j
    print(f'Array sum is {arr_sum}')

Note that for the application of a simple sum you can use the sum() function.

A: To iterate over list of arrays, try this:
fit=[]
for state in collection: #Iterate over each element in the collection
    test = Review(state)
    fit.append(test.function())
print(fit)

Or
fit=[]
for i in collection:
    state = i
    test = Review(state)
    fit.append(test.function())
print(fit)


text:
Q: ExecJS::RuntimeError in Users#new In my ruby on rails web application I am getting error below:
ExecJS::RuntimeError in Users#new

Showing C:/Sites/VideoResume/app/views/layouts/application.html.erb where line #6 raised:

  (in C:/RailsInstaller/Ruby1.9.3/lib/ruby/gems/1.9.1/gems/turbolinks-1.1.1/lib/assets/javascripts/turbolinks.js.coffee)

Kindly suggest me, How do I resolve it.
Waiting for reply.
Thanks.

A: Did you try installing nodejs. First do that it should solve the problem.
How to Install Nodejs on ubuntu
some helpful links and possible duplicates are
ExecJS::RuntimeError
ExecJS::RuntimeError NodeJS Install

A: If you look at the github link given above therubyracer gem in your new rails app. It says
ExecJS lets you run JavaScript code from Ruby. It automatically picks the best runtime available to evaluate your JavaScript program, then returns the result to you as a Ruby object.
ExecJS supports these runtimes:

*

*therubyracer - Google V8 embedded within Ruby

*therubyrhino - Mozilla Rhino embedded within JRuby

*Node.js

*Apple JavaScriptCore - Included with Mac OS X

*Microsoft Windows Script Host (JScript)

Fix
You could solve it by installing any of these runtimes.
You can checkout therubyracer_for_windows someone recommended it here or checkout this


text:
Q: Upgrade Rasp Pi 4 with ubuntu server from 21.04 to 22.04 If I try to upgrade my Rasp Pi 4 running ubuntu server 21.04 I receive a warning that the upgrade to 21.10 is not supported.
I would upgrade to 22.04 which I know supports Rasp Pi 4.
It's possible without reinstalling it?
ubuntu@ubuntu:~$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 21.04
Release:        21.04
Codename:       hirsute

ubuntu@ubuntu:/etc/apt$ sudo do-release-upgrade -c
Checking for a new Ubuntu release
Your Ubuntu release is not supported anymore.
For upgrade information, please visit:
http://www.ubuntu.com/releaseendoflife

New release '21.10' available.
Run 'do-release-upgrade' to upgrade to it.
ubuntu@ubuntu:/etc/apt$ do-release-upgrade
Checking for a new Ubuntu release
Your Ubuntu release is not supported anymore.
For upgrade information, please visit:
http://www.ubuntu.com/releaseendoflife

= Welcome to Ubuntu 21.10 'Impish Indri' =

The Ubuntu team is proud to announce Ubuntu 21.10 'Impish Indri'.

Tnx


text:
Q: Using MemoryBarrier for Propagation of Changes in Dictionary Multithreaded App I have a .NET 3.5 application where a Dictionary instance is shared between two threads. I understand that the Dictionary is not thread-safe in any way by itself but I only have one thread that can ever modify the Dictionary and the other thread just needs to ensure it has the latest values when performing its work. (even latest isn't a hard requirement in the strictest sense)
One thread is receiving intermittent serial data and calling a Set function to change the values in the dictionary. (This Dictionary is a fixed size after the initial setup and I'm basically just using it as a sparse array)
The second thread gathers up the values currently stored in the dictionary and does some work with them through GetLatestValues().
public class HwMemoryMap{
   Dictionary<int, HwDataItem> HwCache;

   public void Set(HwDataItem dataItem){
       HwCache[dataItem.PtId] = dataItem;
       MemoryBarrier();
   }

   public List<HwDataItem> GetLatestValues(){
       System.Threading.Thread.MemoryBarrier();
       List<HwDataItem> HwDataItemList = new List<HwDataItem>();
       // do work here to pull appropriate values out of HwCache
       HwDataItemList.Add(HwCache[0]); // etc
       return HwDataItemList;
   }
}

Is the MemoryBarrier() call here enough to ensure that changes to the dictionary Value for a specific Key are propagated across all threads/cores?
My testing hasn't revealed any problems but that doesn't exactly give me any comfort given the nature of these problems.

A: No, this is not safe. You still run the risk of writing and reading from the data structure simultaneously. There is a trick you can use that works pretty well if the writes are infrequent enough. Basically you make sure the data structure referenced by HwCache remains immutable. Every time you want to change the data structure you first copy it into a new instance and change the new instance inside an exclusive lock. Then when your changes are done you swap the HwCache reference out with the new instance. For this to work correctly you have to mark HwCache as volatile.
public class HwMemoryMap
{
  private object lockobj = new object();
  volatile Dictionary<int, HwDataItem> HwCache;

  public void Set(HwDataItem dataItem)
  {
    lock (lockobj)
    {
      var copy = new Dictionary<int, HWDataItem>(HwCache);
      copy[dataItem.PtId] = dataItem;
      HwCache = copy;
    }
  }

  public List<HwDataItem> GetLatestValues()
  {
    var local = HwCache;
    var HwDataItemList = new List<HwDataItem>();
    // do work here to pull appropriate values out of local
    HwDataItemList.Add(local[0]); // etc
    return HwDataItemList;
  }
}

A: I'm not terribly familiar with C#, but I wouldn't make assumptions about what's going on "under the hood".  In particular, if the insert code assume it's the only one accessing the data structure, it may leave partially updated references while it is allocating space or otherwise.
Consider the following (simplified) code:
Insert(TKey key, TVal val) {
    if (this.size > this._threshold) {
        // Allocate more space and
        // move to a new table
    }
    // Find location and insert
}

If all of that is happening within your one store (and I'm not saying it is, I don't know how C# implements dictionaries), then a memory barrier doesn't save you if any of the intermediate state propagates to a different thread.
What might make more sense is a pair of reader/writer locks.  If the common case is reading, you can have multiple threads all grab the reader lock, and only when you need to make an update do you need to give exclusive access to the writing thread.


text:
Q: EntityFramework Select Most commented Images I have an aspx web site with commented Images. The structure of tables is:
Table name: Images
int id (Primary Key)
varcharmax path(path of the image)

Table name: Comments
int picid; (Linked to image id)
Text text;

I need to select top 10 commented images using Entity Framework. How is it possible?

A: Should be something like:
var result = (from img in db.Images
              order by img.Comments.Count() descending
              select img).Take(10);

Or if, like me, you much prefer the other syntax (with methods)
var result = db.Images
               .OrderByDescending(img => img.Comments.Count())
               .Take(10);

A: This selects the top 10:
var result = (
  from i in db.Images
  order by i.Comments.Count() descending
  select i).Take(10);


text:
Q: Run the PsExec without knowing the full path in C# Windows application Form I need help with my application, I created an application that when they hit the update button will execute some PsExec file to remotetly run some functions. the problem comes that works good in my machine locally but my application will be shared to a lot of users. and I don't want to install to all users the PsExec file to their computers, I just want my program to be installed in their computers and just run the program without any issues.
My code works all the application I just need to add that piece of code that will make the program call the PsExec without knowing the whole Path, right now I installed the PsExec file to my Debug folder, which is the folder that is in my project.
So instead of using the whole PsExec path that is on my directory i will like to use the one of my project
I don't want to use this
string leMars21StArguments = @"/C C:\PowerShellRemotly\PsExec.exe " +
    @"-i \\VML-2012-QBOOK2 -u mydomain\" + userInfo.Username + " -p " +
    userInfo.Password + " -d C:\\batch\\myfile.bat";

I would like something like this where the debug folder of the project, but it doesn't work. is there another to do this?
string leMars21StArguments = @"/C Debug\PsExec.exe " +
    @"-i \\VML-2012-QBOOK2 -u mydomain\" + userInfo.Username + " -p " +
    userInfo.Password + " -d C:\\batch\\myfile.bat";

Here's the full code:
Process p = new Process();

//assigned from the form txtboxes to the UserInformation class
userInfo.Username = txt_Username.Text;
userInfo.Password = txt_Password.Text;

//string variabes for the cmd arguments
string leMars21StArguments = @"/C C:\PowerShellRemotly\PsExec.exe -i " +
    @"\\VML-2012-QBOOK2 -u mydomain\" + userInfo.Username + " -p " +
    userInfo.Password + " -d C:\\batch\\myfile.bat";

if (userInfo.Username == string.Empty)
{
    MessageBox.Show("Username cannot be null, please try again");
}

if (userInfo.Password == string.Empty)
{
    MessageBox.Show("Password cannot be null, please try again");
}

if (cmb_DatabaseSelection.SelectedItem == "location")
{
    p.StartInfo.FileName = "cmd.exe";
    p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
    p.StartInfo.CreateNoWindow = true;
    p.StartInfo.Arguments = leMars21StArguments;
    p.StartInfo.RedirectStandardOutput = true;
    p.StartInfo.UseShellExecute = false;
    p.StartInfo.RedirectStandardError = true;

    p.Start();
    string output = p.StandardOutput.ReadToEnd();
    string errOutput = p.StandardError.ReadToEnd();
    p.Close();

    MessageBox.Show(errOutput);
}

A: If you add it to your program, then you can just reference the location relative to your .exe where you place it.
For example, if you add a new folder called "Tools" to your project, and then add psexec.exe there, and set it to "Copy if newer" (or "Copy always"):

Then you can always get the path to it by grabbing the directory that your .exe is in and navigating to the "Tools" folder (note that you will need a reference to System.Reflection to use Assembly.GetExecutingAssembly):
var thisExeDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var psExecPath = Path.Combine(thisExeDirectory, "Tools", "psexec.exe");

As an example:
var userInfo = new UserInfo {Password = "LetMeIn", Username = "rufusl"};
var thisExeDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var psExePath = Path.Combine(thisExeDirectory, "Tools", "psexec.exe");

var leMars21StArguments =
    "/C \"" + psExePath + @""" -i \\VML-2012-QBOOK2 -u mydomain\" + userInfo.Username +
    " -p " + userInfo.Password + @" -d C:\batch\myfile.bat";

Console.WriteLine(leMars21StArguments);

Output


text:
Q: How numpy.loadtxt loads files via slicing If I use the following to slice from a file:
np.loadtxt(filename)[0:3]
Does it guarantee that it ONLY loads the slicing portion? I am afraid it loads the entire file first into the memory followed by slicing [1:3] which is undesirable to me as I will be having very large files to load in the future.


text:
Q: How to crop and resize upload images using php? I have created form.php, upload.php and imagemanipulater.php files for crop and resize the image.
I have referenced lot in google, still i didn't get, what i need.
I need crop image and upload like gmail , like this http://s3.postimg.org/f8zu4gpsj/Untitled_1_copy.png
Now i got cropped image and saved in my uploads folder.
But i need visual crop image like gmail account.
form.php:
<!DOCTYPE html>

    <title>Upload Files using normal form and PHP</title>

  <form enctype="multipart/form-data" method="post" action="upload.php">

      Select a File to Upload

      <input type="file" name="fileToUpload" id="fileToUpload" />

      <input type="submit" value="Upload" />

  </form>

upload.php:
<?php
// include ImageManipulator class
require_once('imagemanipulater.php');

if ($_FILES['fileToUpload']['error'] > 0) {
    echo "Error: " . $_FILES['fileToUpload']['error'] . "
";
} else {
    // array of valid extensions
    $validExtensions = array('.jpg', '.jpeg', '.gif', '.png');
    // get extension of the uploaded file
    $fileExtension = strrchr($_FILES['fileToUpload']['name'], ".");
    // check if file Extension is on the list of allowed ones
    if (in_array($fileExtension, $validExtensions)) {
        $newNamePrefix = time() . '_';
        $manipulator = new ImageManipulator($_FILES['fileToUpload']['tmp_name']);
        $width  = $manipulator->getWidth();
        $height = $manipulator->getHeight();
        $centreX = round($width / 2);
        $centreY = round($height / 2);
        // our dimensions will be 200x130
        $x1 = $centreX - 100; // 200 / 2
        $y1 = $centreY - 65; // 130 / 2

        $x2 = $centreX + 100; // 200 / 2
        $y2 = $centreY + 65; // 130 / 2

        // center cropping to 200x130
        $newImage = $manipulator->crop($x1, $y1, $x2, $y2);
        // saving file to uploads folder
        $manipulator->save('uploads/' . $newNamePrefix . $_FILES['fileToUpload']['name']);
        echo 'Done ...';
    } else {
        echo 'You must upload an image...';
    }
}

imagemanipulater.php:
<?php
class ImageManipulator
{
    /**
     * @var int
     */
    protected $width;

    /**
     * @var int
     */
    protected $height;

    /**
     * @var resource
     */
    protected $image;

    /**
     * Image manipulator constructor
     *
     * @param string $file OPTIONAL Path to image file or image data as string
     * @return void
     */
    public function __construct($file = null)
    {
        if (null !== $file) {
            if (is_file($file)) {
                $this->setImageFile($file);
            } else {
                $this->setImageString($file);
            }
        }
    }

    /**
     * Set image resource from file
     *
     * @param string $file Path to image file
     * @return ImageManipulator for a fluent interface
     * @throws InvalidArgumentException
     */
    public function setImageFile($file)
    {
        if (!(is_readable($file) && is_file($file))) {
            throw new InvalidArgumentException("Image file $file is not readable");
        }

        if (is_resource($this->image)) {
            imagedestroy($this->image);
        }

        list ($this->width, $this->height, $type) = getimagesize($file);

        switch ($type) {
            case IMAGETYPE_GIF  :
                $this->image = imagecreatefromgif($file);
                break;
            case IMAGETYPE_JPEG :
                $this->image = imagecreatefromjpeg($file);
                break;
            case IMAGETYPE_PNG  :
                $this->image = imagecreatefrompng($file);
                break;
            default             :
                throw new InvalidArgumentException("Image type $type not supported");
        }

        return $this;
    }

    /**
     * Set image resource from string data
     *
     * @param string $data
     * @return ImageManipulator for a fluent interface
     * @throws RuntimeException
     */
    public function setImageString($data)
    {
        if (is_resource($this->image)) {
            imagedestroy($this->image);
        }

        if (!$this->image = imagecreatefromstring($data)) {
            throw new RuntimeException('Cannot create image from data string');
        }
        $this->width = imagesx($this->image);
        $this->height = imagesy($this->image);
        return $this;
    }

    /**
     * Resamples the current image
     *
     * @param int  $width                New width
     * @param int  $height               New height
     * @param bool $constrainProportions Constrain current image proportions when resizing
     * @return ImageManipulator for a fluent interface
     * @throws RuntimeException
     */
    public function resample($width, $height, $constrainProportions = true)
    {
        if (!is_resource($this->image)) {
            throw new RuntimeException('No image set');
        }
        if ($constrainProportions) {
            if ($this->height >= $this->width) {
                $width  = round($height / $this->height * $this->width);
            } else {
                $height = round($width / $this->width * $this->height);
            }
        }
        $temp = imagecreatetruecolor($width, $height);
        imagecopyresampled($temp, $this->image, 0, 0, 0, 0, $width, $height, $this->width, $this->height);
        return $this->_replace($temp);
    }

    /**
     * Enlarge canvas
     *
     * @param int   $width  Canvas width
     * @param int   $height Canvas height
     * @param array $rgb    RGB colour values
     * @param int   $xpos   X-Position of image in new canvas, null for centre
     * @param int   $ypos   Y-Position of image in new canvas, null for centre
     * @return ImageManipulator for a fluent interface
     * @throws RuntimeException
     */
    public function enlargeCanvas($width, $height, array $rgb = array(), $xpos = null, $ypos = null)
    {
        if (!is_resource($this->image)) {
            throw new RuntimeException('No image set');
        }

        $width = max($width, $this->width);
        $height = max($height, $this->height);

        $temp = imagecreatetruecolor($width, $height);
        if (count($rgb) == 3) {
            $bg = imagecolorallocate($temp, $rgb[0], $rgb[1], $rgb[2]);
            imagefill($temp, 0, 0, $bg);
        }

        if (null === $xpos) {
            $xpos = round(($width - $this->width) / 2);
        }
        if (null === $ypos) {
            $ypos = round(($height - $this->height) / 2);
        }

        imagecopy($temp, $this->image, (int) $xpos, (int) $ypos, 0, 0, $this->width, $this->height);
        return $this->_replace($temp);
    }

    /**
     * Crop image
     *
     * @param int|array $x1 Top left x-coordinate of crop box or array of coordinates
     * @param int       $y1 Top left y-coordinate of crop box
     * @param int       $x2 Bottom right x-coordinate of crop box
     * @param int       $y2 Bottom right y-coordinate of crop box
     * @return ImageManipulator for a fluent interface
     * @throws RuntimeException
     */
    public function crop($x1, $y1 = 0, $x2 = 0, $y2 = 0)
    {
        if (!is_resource($this->image)) {
            throw new RuntimeException('No image set');
        }
        if (is_array($x1) && 4 == count($x1)) {
            list($x1, $y1, $x2, $y2) = $x1;
        }

        $x1 = max($x1, 0);
        $y1 = max($y1, 0);

        $x2 = min($x2, $this->width);
        $y2 = min($y2, $this->height);

        $width = $x2 - $x1;
        $height = $y2 - $y1;

        $temp = imagecreatetruecolor($width, $height);
        imagecopy($temp, $this->image, 0, 0, $x1, $y1, $width, $height);

        return $this->_replace($temp);
    }

    /**
     * Replace current image resource with a new one
     *
     * @param resource $res New image resource
     * @return ImageManipulator for a fluent interface
     * @throws UnexpectedValueException
     */
    protected function _replace($res)
    {
        if (!is_resource($res)) {
            throw new UnexpectedValueException('Invalid resource');
        }
        if (is_resource($this->image)) {
            imagedestroy($this->image);
        }
        $this->image = $res;
        $this->width = imagesx($res);
        $this->height = imagesy($res);
        return $this;
    }

    /**
     * Save current image to file
     *
     * @param string $fileName
     * @return void
     * @throws RuntimeException
     */
    public function save($fileName, $type = IMAGETYPE_JPEG)
    {
        $dir = dirname($fileName);
        if (!is_dir($dir)) {
            if (!mkdir($dir, 0755, true)) {
                throw new RuntimeException('Error creating directory ' . $dir);
            }
        }

        try {
            switch ($type) {
                case IMAGETYPE_GIF  :
                    if (!imagegif($this->image, $fileName)) {
                        throw new RuntimeException;
                    }
                    break;
                case IMAGETYPE_PNG  :
                    if (!imagepng($this->image, $fileName)) {
                        throw new RuntimeException;
                    }
                    break;
                case IMAGETYPE_JPEG :
                default             :
                    if (!imagejpeg($this->image, $fileName, 95)) {
                        throw new RuntimeException;
                    }
            }
        } catch (Exception $ex) {
            throw new RuntimeException('Error saving image file to ' . $fileName);
        }
    }

    /**
     * Returns the GD image resource
     *
     * @return resource
     */
    public function getResource()
    {
        return $this->image;
    }

    /**
     * Get current image resource width
     *
     * @return int
     */
    public function getWidth()
    {
        return $this->width;
    }

    /**
     * Get current image height
     *
     * @return int
     */
    public function getHeight()
    {
        return $this->height;
    }
}

Can anyone help me? Thanks in advance.


text:
Q: In Excel 2007 where do you store macros that you want to use on all sheets that you open? It looks like you can store it in a file called PERSONAL.XLSB and that will create "Global" (for all worksheets) macros.
This file is of course stored in your user profile (%USERPROFILE%\AppData\Roaming\Microsoft\Excel\XLSTART).
My file appears to be missing however.  This is probably because my user profile is remoted to a network drive.
When I try to edit or create a global macro, I get a message about:

I think it might be because my PERSONAL.XLSB file is missing but I don't really know what to do about it.

A: I'm not sure if this is a "best practice" or not, but I created an Excel add-in (.xla file type) that has all of my custom formulas (creatively named "CustomFunctions.xla).  I placed this in a mapped network drive and Excel connects to it each time it opens.  I would guess something similar would work for you.
EDIT:
Here's a great resource I use all the time:
CPearson Excel Add-In
EDIT: From Chip Pearson's website:
"An XLA Add-In is a certain type of workbook that provides custom functions and/or tools that extend the basic functionality of Excel. An Add-In may contain User Defined Functions (UDFs, see Writing Your Own Functions In VBA) that provide calculation functions specific to your own area of interest or business, functions that extend beyond the normal calculation capability of Excel. An Add-In can also provide tools to manipulate the data in a workbook. Indeed, an Add-In can be written to do nearly anything you want. If it can be done manually, it can be automated with an XLA Add-In."
He has a lot more to say about the topic. His website is absolutely worth bookmarking if you're going to do much in Excel.

A: You are correct about the file. personal.xlsb in the startup folder is the Excel equivalent (roughly) of normal.dot in Word. You can store macro's and static data, even colour pallets.
Check in Options as to where Excel is expecting the startup files to be, they may have been moved.
Also, go to the View toolbar and see if "Unhide" is grey'd out. If it isn't, click on it and unhide the personal.xlsb workbook, you will then be able to edit the macro.


text:
Q: What is so interesting about the zeroes of the Riemann $\zeta$ function? The Riemann $\zeta$ function plays a significant role in number theory and is defined by $$\zeta(s) = \sum_{n=1}^\infty \frac{1}{n^s} \qquad \text{ for } \sigma > 1 \text{ and } s= \sigma + it$$

The Riemann hypothesis asserts that all the non-trivial zeroes of the $\zeta$ function  lie on the line $\text{Re}(s) = \frac{1}{2}$.

My question is:

Why are we interested in the zeroes of the $\zeta$ function? Does it give any information about something?

What is the use of writing $$\zeta(s) = \prod_{p} \biggl(1-\frac{1}{p^s}\biggr)^{-1}$$

A: Short answer: Understanding the distribution of the prime numbers is directly related to understanding the zeros of the Riemann Zeta Function.**
Long Answer: The prime counting function is defined as $\pi(x)=\sum_{p\leq x} 1,$ which counts the number of primes less than $x$.  Usually we consider its weighted modification $$\psi(x)=\sum_{p^{m}\leq x}\log p$$ where we are also counting the prime powers.  It is not hard to show that $$\pi(x)=\frac{\psi(x)}{\log x}\left(1+O\left(\frac{1}{\log x}\right)\right),$$ which means that these two functions differ by about a factor of $\log x$.
The prime number theorem states that $\psi(x)\sim x$, but this is quite hard to show.  It was first conjectured by Legendre in 1797, but took almost 100 years to prove, finally being resolved in 1896 by Hadamard and de la Vallée Poussin.  In 1859 Riemann outlined a proof, and gave a remarkable identity which changed how people thought about counting primes.  He showed that (more or less) $$\psi(x)=x-\sum_{\rho:\zeta(\rho)=0}\frac{x^{\rho}}{\rho}-\frac{\zeta^{'}(0)}{\zeta(0)},$$ where the sum is taken over all the zeros of the zeta function. ${}^{++}$
Notice that this is an equality.  The left hand side is a step function, and on the right hand side, somehow, the zeros of the zeta function conspire at exactly the prime numbers to make that sum jump.  (It is an infinite series whose convergence is not uniform)  If you remember only 1 thing from this answer, make it the above explicit formula.
An equivalence to RH: Current methods allow us to prove that $$\psi(x)=x+O\left(xe^{-c\sqrt{\log x}}\right).$$  This error term decreases faster then $\frac{x}{(\log x)^A}$ for any $A$, but increases faster then $x^{1-\delta}$ for any small $\delta>0$.  In particular, proving that the error term was of the form $O\left(x^{1-\delta}\right)$ for some $\delta>0$ would be an enormous breakthrough.  The Riemann Hypothesis is equivalent to showing the error term is like square root $x$, that is proving the statement  $$\psi(x)=x+O\left(x^{\frac{1}{2}}\log^{2}x\right).$$    In other words, the Riemann Hypothesis is equivalent to improving the error term when counting the prime numbers.
Remark: In your question you incorrectly state the Riemann Hypothesis, which says that all zeros have real part $\frac{1}{2}$.  The fact that infinitely many zeros lie on the line was shown by Hardy in 1917, and in 1942 Selberg showed that a positive proportion lie on the line.  In 1974 Levinson showed that this proportion was at least $\frac{1}{3}$, and Conrey 1989 improved this to $\frac{2}{5}$.
** Of course, there may be some people who are interested in the zeros of the zeta function for other reasons.  Historically the prime numbers are what first motivated the study of the zeros.
${}^{++}$: Usually  the trivial zeros will be separated out of the sum, but I do not make this distinction here.  Also, Riemann's original paper states things in terms of $\Pi(x)$ and $\text{li}(x)$, the Riemann pi function and logarithmic integral, rather then $\psi(x)$.  This is a very slight difference, and I use $\psi(x)$ above because it is easier and cleaner to do so.
See also: Why is $\zeta(1+it) \neq 0$ equivalent to the prime number theorem?

A: The initial interest in the zeros is their connection with the distribution of primes, which is often done via asymptotic statements about the prime counting function. In analytic number theory, it is standard fare to have an arithmetic function defined by a summation formula, and then modify it into a form that is easier to manipulate and obtain results for, in such a way that the asymptotic results about the modified function can be translated into results about the original function very easily. This is certainly the case with $\pi(x)$, which is why I bring this up. Most of the information that is relevant here can be found on the Explicit formula article at Wikipedia, for explicit formulas for the $\pi(x)$ function using the zeros of the Riemann zeta function. Two key highlights:

$(1)$ "This formula says that the zeros of the Riemann zeta function control the oscillations of primes around their 'expected' positions."
$(2)$ "Roughly speaking, the explicit formula says the Fourier transform of the zeros of the zeta function is the set of prime powers plus some elementary factors."

With the very basics of complex numbers we see that $x^\rho$, as a function of $x$, has a magnitude given by $x^{\Re (\rho)}$ and its argument by $\Im(\rho)\cdot\log x$. The imaginary parts thus contribute oscillatory behavior to the explicit formulas, while the real parts say which imaginary parts dominate over others and by how much - this is some meaning behind the 'Fourier transform' description. Indeed, given the dominant term in an asymptote for $\pi$ we have roughly the primes' "expected positions" (we are taking some license in referring to positioning when we are actually speaking of distribution in the limit), and the outside terms will speak to how much $\pi$ deviates from the expected dominant term as we take $x$ higher and higher in value. If one of the real parts differed from the others, it would privilege some deviation over others, changing our view of the regularity in the primes' distribution.
Eventually it also became clear that more and more results in number theory - even very accessible results that belie how deep the Riemann Hypothesis really has come to be - were equivalent to or could only be proven on the assumption of RH. See for example here or here or here. I'm not sure if any truly comprehensive list of the consequences or equivalences actually exists!
Moreover it is clear now that RH is not an isolated phenomenon, and instead exists as a piece in a much bigger puzzle (at least as I see it). The $\zeta$ function is a trivial case of a Dirichlet $L$-function as well a case of a trivial case of a Dedekind $\zeta$ function, and there is respectively a Generalized Riemann Hypothesis (GRH) and Extended Riemann Hypothesis for these two more general classes of functions. There are numerous analogues to the zeta function and RH too - many of these have already gained more ground or already had the analogous RH proven!
It is now wondered what the appropriate definition of an $L$-function "should" be, that is, morally speaking - specifically it must have some analytic features and of course a functional equation involving a reflection, gamma function, weight, conductor etc. but the precise recipe we need to create a slick theory is not yet known. (Disclaimer: this paragraph comes from memory of reading something a long time ago that I cannot figure out how to find again to check. Derp.)
Finally, there is the spectral interpretation of the zeta zeros that has arisen. There is the Hilbert-Pólya conjecture. As the Wikipedia entry describes it,

In a letter to Andrew Odlyzko, dated January 3, 1982, George Pólya said that while he was in Göttingen around 1912 to 1914 he was asked by Edmund Landau for a physical reason that the Riemann hypothesis should be true, and suggested that this would be the case if the imaginary parts of the zeros of the Riemann zeta function corresponded to eigenvalues of an unbounded self adjoint operator.

This has spurred quantum-mechanical approaches to the Riemann Hypothesis. Moreover, we now have serious empirical evidence of a connection between the zeta zeros and random matrix theory, specifically that their pair-correlation matches that of Gaussian Unitary Ensembles (GUEs)...

The year: 1972. The scene: Afternoon tea in Fuld Hall at the Institute for Advanced Study. The camera pans around the Common Room, passing by several Princetonians in tweeds and corduroys, then zooms in on Hugh Montgomery, boyish Midwestern number theorist with sideburns. He has just been introduced to Freeman Dyson, dapper British physicist.
Dyson: So tell me, Montgomery, what have you been up to?
Montgomery: Well, lately I've been looking into the distribution of the zeros of the Riemann zeta function.
Dyson: Yes? And?
Montgomery: It seems the two-point correlations go as... (turning to write on a nearby blackboard): $$1-\left(\frac{\sin\pi x}{\pi x}\right)^2$$
Dyson: Extraordinary! Do you realize that's the pair-correlation function for the eigenvalues of a random Hermitian matrix?

(Source: The Spectrum of Riemannium.)
If so inclined one can see the empirical evidence in pretty pictures e.g. here.

A: Here is a visual supplement to Eric's answer, based on this paper by Riesel and Göhl, and Mathematica code by Stan Wagon:

The animation demonstrates the eventual transformation from Riemann's famed approximation to the prime counting function
$$R(x)=\sum_{k=1}^\infty \frac{\mu(k)}{k} \mathrm{li}(\sqrt[k]{x})=1+\sum_{k=1}^\infty \frac{(\log\,x)^k}{k\,k!\zeta(k+1)}$$
to the actual prime-counting function $\pi(x)$, through a series of successive corrections based on the nontrivial roots of $\zeta(s)$. (Here, $\mu(k)$ is the Möbius function and $\mathrm{li}(x)$ is the logarithmic integral.) See the Riesel/Göhl paper for more details.

A: the HIlbert Polya operator which would prove Riemann Hypothesis is the Wu-Sprung genralzed model with potential
$$  f^{-1} (x)=\frac{4}{\sqrt{4x+1} } +\frac{1}{4\pi } \int\nolimits_{-\sqrt{x} }^{\sqrt{x}}\frac{dr}{\sqrt{x-r^2} } \left( \frac{\Gamma '}{\Gamma } \left( \frac{1}{4} +\frac{ir}{2} \right) -\ln \pi \right)  -\sum\limits_{n=1}^\infty \frac{\Lambda (n)}{\sqrt{n} } J_0 \left( \sqrt{x} \ln n\right)  $$
with boundary conditions $$ y(0)=0=y(\infty) $$ and $ H= -\frac{d^{2}}{dx^{2}}y(x)+f(x)y(x)=E_{n}$...................$E_{n}=\gamma_{n}^{2}$·
however mathematician do not like it, if we take the half derivative then we find the distributional Riemann-Weil formula for the zeros
$$ \begin{array}{l}
\sum\limits_{n=0}^{\infty }\delta \left( x-\gamma _{n} \right) + \sum\limits_{n=0}^{\infty }\delta \left( x+\gamma _{n} \right)  =\frac{1}{2\pi } \frac{\zeta }{\zeta } \left( \frac{1}{2} +ix\right) +\frac{1}{2\pi } \frac{\zeta '}{\zeta } \left( \frac{1}{2} -ix\right) -\frac{\ln \pi }{2\pi }  \\[10pt]
{} +\frac{\Gamma '}{\Gamma } \left( \frac{1}{4} +i\frac{x}{2} \right) \frac{1}{4\pi } +\frac{\Gamma '}{\Gamma } \left( \frac{1}{4} -i\frac{x}{2} \right) \frac{1}{4\pi } +\frac{1}{\pi } \delta \left( x-\frac{i}{2} \right) +\frac{1}{\pi } \delta \left( x+\frac{i}{2} \right) \end{array} $$

A: RH has a direct influence on the chaotic quantum oscillator. Inverted chaotic quantum oscillator has eigen-energies equal to imaginary parts of the riemann zeta non-trivial roots, provided RH is correct. One can refer to http://www.phy.bris.ac.uk/people/berry_mv/the_papers/Berry154.pdf for starters. Linear quantum chaotic oscillator being a fundamental object for a quantum theory in general, such as, say, linear harmonic quantum oscillator is, one is led to conclude therefore that RH plays a significant role in the breakthrough in this region.
Regards.


text:
Q: Problem After Permission Change in Publish App I have a android app in play store. That has only internet permission. Now I change in app user can use their camera & storage.
I add privacy policy on play store and in link in app also. I also mention these permission in release text.
When I upload new app display message like this
    minSdkVersion 21
    targetSdkVersion 28
    versionCode 4
    versionName "4.0"

Permissions
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET"/>

<uses-feature android:name="android.hardware.camera2.full" />
<uses-feature android:name="android.hardware.camera.autofocus" />

Permission Code
private void permission(){
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED || ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(StartActivity.this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CAMERA_PERMISSION);
        //Display_Rermission_Reason();
    }else {
        Intent intent = new Intent(StartActivity.this, PrivacyPolicyActivity.class);
        startActivity(intent);
    }
}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    if (requestCode == REQUEST_CAMERA_PERMISSION) {
        if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
            // close the app
            Toast.makeText(MainActivity.this, "Sorry!!!, you can't use this app without granting permission", Toast.LENGTH_LONG).show();
            //Display_Rermission_Reason();
        }
    }
}

After publish the app it display in google play store
This app is incompatible with all of your devices.

Any version 5+ and above

A: Change this in manifest,
<uses-feature android:name="android.hardware.camera2.full"
android:required="false" />
<uses-feature android:name="android.hardware.camera.autofocus"
android:required="false" />

Have a look at this link below which might help you,
https://developer.android.com/guide/topics/manifest/uses-feature-element


text:
Q: ssh connection refused after reboot I rebooted my Linux Mint 17.3 machine and now when I try to ssh to it, I get "Connection refused" -- what did go wrong? Here are my diagnostic steps:
$ ps -ax |grep ssh
 2013 ?     Ss  0:00 /usr/bin/ssh-agent /usr/bin/dbus-launch --exit-with-$
 3346 pts/1 S+  0:00 grep --colour=auto ssh

$nmap MYSERVER
Starting Nmap 6.40 ( http://nmap.org ) at 2019-09-23 15:19 EDT
Nmap scan report for MYSERVER
Host is up (0.00028s latency).
Not shown: 998 closed ports
PORT    STATE SERVICE
139/tcp open  netbios-ssn
445/tcp open  microsoft-ds

$sudo service ssh start
start: Job is already running: ssh

$ sudo service ssh restart
ssh stop/waiting
ssh start/running

I got no output to
sudo /etc/init.d/ssh status

I read this ssh Connection refused: how to troubleshoot? but the advice there does not seem to cover my case.

A: It doesn't look like the service is running, try this to check the status of the service:
systemctl status sshd

If it is not running you can start it with:
systemctl start sshd

If you would like the service to start at boot, run:
systemctl enable sshd

Edit:
 I've just read your question again and realised you've tried running service ssh start, I haven't used Linux Mint 17.3, but I'd have thought it's using systemd so you'd need to use systemctl commands.
You can also run netstat -tunlp | grep ssh to see if the service is listening on port 22 as you'd expect. If it shows as listening but you're unable to connect I'd look at the firewall configuration: iptables -nvL


text:
Q: CSS float not being applied in Chrome... bug or user error? I'm trying to track down an intermittent Chrome rendering bug in my web application.
When toggling the float property between "left" and "none" Chrome does not refloat the elements. Firefox and IE behave as expected.
Click on the "account-info" div to toggle the float values.

var $items = $(".menu > span");
$("#account-info").on("click", function () {
    if ($items.css("float") === "left") {
        $items.css("float", "none");
    } else {
        $items.css("float", "left");
    }
});
#account-info {
    float: right;
    background-color: #eee;
}
.menu .icon {
    display: block;
}
.menu span {
    /*display: block;*/
    float: left;
}

        [left-icon]
        User Name
        [right-icon]

If display:block; is uncommented then Chrome does refloat the elements, but I was always under the impression that it was unnecessary to declare display:block when specifying float:left or float:right Reference: Implied Block | CSS-Tricks
So is this a bug in Chrome or I am missing something here?
Chrome Version 39.0.2171.71m / Windows 8.1 64-bit

A: Give #account-info a width.
Since it itself is floating, it takes on the width of its contents in Chrome. Thus, when you click the first time it collapses to the width of "User Name" and never reverts.


text:
Q: Folder structure for Angular and Nodejs I am going to create an app which deals with Angular5(front-end), Nodejs(middle-end) and MongoDB(back-end).
Below is the folder structure:

Package.json: "start": "ng build & node server.js"
Now when I am start the app by npm start, It throws the following error:
"Unable to find any apps in .angular-cli.json."
I hope node server is looking for this file to load angular codes. But it lies inside angular folder.
If I place both angular and node codes in same place, it works well.
But it looks more clumsy and a bit confusing. I don't want to compromise with my folder structure.
Can anyone please help to achieve the app working on the same folder structure that I would prefer?
Thanks in advance.

A: it might be that  your global @angular/cli installation got corrupt. You may try a cache clean and reinstall..
npm cache clean
npm -g i @angular/cli

A: If you use angular cli for creating the project, then looks something wrong in the package.json, (as I seen your comment on the previous answer)
first uninstall angular cli if already install by using
npm uninstall -g @angular/cli, then npm install -g @angular/cli after cli installation ng new [project name /folder name]
cd [project name /folder name]
ng serve --open

try once.

A: I got this same error in my current project and was confused because I'm running the application / ng serve in one terminal, but got this when I tried to generate a component from another terminal. .angular-cli.json was already there and correct. So what gives?
I realized that I used the shortcut to open VisualStudio Code's internal terminal -- which opened the terminal to the *root of the project * (like most IDEs). The project contains other things in addition to the Angular application folder that has the .angular-cli.json file in question. I just had to cd to the right folder and run ng g c again and things were fine.
In my case it was just a silly error. I thought I'd come back to share in order to save people a real headache for something so simple. I see that Shiva actually has mentioned this above, but I thought I would give a bit more detail so it doesn't get overlooked.
Reference URL: How to generate .angular-cli.json file in Angular Cli?


text:
Q: Flutter search query Can you please help me with the following issue. I don't know how to fix my search query. For example, if I search for an "Apple" with the first letter uppercase the search query works fine. But if I search for an "apple" with the fist letter lowercase it doesn't give me any results.

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

  @override
  State<FeedsScreen> createState() => _FeedsScreenState();
}

class _FeedsScreenState extends State<FeedsScreen> {
  final TextEditingController _searchController = TextEditingController();
  final FocusNode _searchTextFocusNode = FocusNode();
  bool isShowProducts = false;

  @override
  void dispose() {
    _searchController.dispose();
    _searchTextFocusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        centerTitle: true,
        elevation: 0,
        backgroundColor: Theme.of(context).scaffoldBackgroundColor,
        leading: const BackArrow(),
        title: const AppBarTitle(title: 'Все товары'),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            Padding(
              padding: const EdgeInsets.all(8.0),
              child: SizedBox(
                height: kBottomNavigationBarHeight,
                child: TextFormField(
                  focusNode: _searchTextFocusNode,
                  controller: _searchController,
                  onChanged: (value) {
                    setState(() {
                      isShowProducts = true;
                    });
                  },
                  decoration: InputDecoration(
                    focusedBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                      borderSide: const BorderSide(
                        color: Colors.cyan,
                        width: 1,
                      ),
                    ),
                    enabledBorder: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(12),
                      borderSide: const BorderSide(
                        color: Colors.cyan,
                        width: 1,
                      ),
                    ),
                    hintText: 'Search products',
                    suffix: IconButton(
                      onPressed: () {
                        _searchController.clear();
                        _searchTextFocusNode.unfocus();
                        setState(() {
                          isShowProducts = false;
                        });
                      },
                      icon: Icon(
                        Icons.close,
                        color: _searchTextFocusNode.hasFocus
                            ? Colors.red
                            : Colors.cyan,
                      ),
                    ),
                    prefixIcon: const Icon(
                      Icons.search,
                      color: Colors.cyan,
                    ),
                  ),
                ),
              ),
            ),
            isShowProducts == true
                ? FutureBuilder(
                    future: FirebaseFirestore.instance
                        .collection('products')
                        .where('title',
                            isGreaterThanOrEqualTo: _searchController.text)
                        .get(),
                    builder: (context,
                        AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>>
                            snapshot) {
                      if (snapshot.hasError) {
                        return const Text('Something went wrong');
                      }

                      if (snapshot.connectionState == ConnectionState.waiting) {
                        return const Center(
                          child: SpinKitSpinningLines(
                            color: Colors.blueGrey,
                          ),
                        );
                      }
                      if (!snapshot.hasData) {
                        return const EmptyProdWidget(text: 'Items not found');
                      }
                      return StaggeredGridView.countBuilder(
                        physics: const NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        itemCount: snapshot.data!.docs.length,
                        crossAxisCount: 2,
                        itemBuilder: (context, index) {
                          return FeedsWidget(
                            snap: snapshot.data!.docs[index].data(),
                          );
                        },
                        staggeredTileBuilder: (context) =>
                            const StaggeredTile.fit(1),
                      );
                    })
                : FutureBuilder(
                    future:
                        FirebaseFirestore.instance.collection('products').get(),
                    builder: (context,
                        AsyncSnapshot<QuerySnapshot<Map<String, dynamic>>>
                            snapshot) {
                      if (snapshot.hasError) {
                        return const Text('Something went wrong');
                      }

                      if (snapshot.connectionState == ConnectionState.waiting) {
                        return const Center(
                          child: SpinKitSpinningLines(
                            color: Colors.blueGrey,
                          ),
                        );
                      }
                      if (!snapshot.hasData) {
                        return const EmptyProdWidget(text: 'Items not found');
                      }
                      return StaggeredGridView.countBuilder(
                        physics: const NeverScrollableScrollPhysics(),
                        shrinkWrap: true,
                        itemCount: snapshot.data!.docs.length,
                        crossAxisCount: 2,
                        itemBuilder: (context, index) {
                          return FeedsWidget(
                            snap: snapshot.data!.docs[index].data(),
                          );
                        },
                        staggeredTileBuilder: (context) =>
                            const StaggeredTile.fit(1),
                      );
                    }),
          ],
        ),
      ),
    );
  }
}

I have tried to add toLowerCase() to my future, but of course it didn't work ))
 future: FirebaseFirestore.instance
                        .collection('products')
                        .where('title'.toLowerCase(),
                            isGreaterThanOrEqualTo: _searchController.text.toLowerCase())
                        .get()


text:
Q: removing duplicate vector from 2d vector I have coded this to remove similar vector from 2d vector, this can be for any numbers of vector inside 2d vector but for example I have taken only 3 vector.
here, {1,2,3,4} is similar to {3,2,1,4} so I have to remove {3,2,1,4}.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int main()
{
    vector<vector<int> > v = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 3, 2, 1, 4 } };
    vector<int> r, c;

    // sorting elements
    for (auto row = v.begin(); row != v.end(); row++) {
        sort(row->begin(), row->end());
    }

    // Deleting Duplicates
    for (auto row = v.begin(); row != v.end() - 1; row++) {
        r.clear();
        c.clear();
        cout << endl
             << endl;
        for (auto col = row->begin(); col != row->end(); col++) {
            r.push_back(*col);
        }

        for (auto cr = row + 1; cr != v.end(); cr++) {
            for (auto cc = cr->begin(); cc != cr->end(); cc++) {
                c.push_back(*cc);
            }

            if (r == c)
                v.erase(cr->begin(), cr->end());
            c.clear();
        }
        cout << endl;
    }

    // Printing
    for (auto row = v.begin(); row != v.end(); row++) {
        for (auto col = row->begin(); col != row->end(); col++) {
            cout << *col << " ";
        }
    }
}

error: no matching function for call to 'std::vector >::erase(std::vector::iterator, std::vector::iterator)'

A: You can easily sort your 2d vector's elements and then compare them one by one.
Here, one function compares two 1d vectors and returns the result.
Note: When an element of your 2d vector gets deleted, the next element replaces it, so you shouldn't increase the target index (index k in my code). Increase the index only if these two elements are not equal.
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

bool twoVectorsAreEqual(vector<int> first_vec, vector<int> second_vec) {

    sort(first_vec.begin(), first_vec.end());
    sort(second_vec.begin(), second_vec.end());
    return (first_vec == second_vec);
}

int main(){

    vector<vector<int>> double_vec /* = some velue*/;

    for (int i = 0; i < double_vec.size() - 1; i++) {
        for (int k = i + 1; k < double_vec.size();) {

            if (twoVectorsAreEqual(double_vec[i], double_vec[k])) {
                double_vec.erase(double_vec.begin() + k);
            else
                k++;
        }
    }
}


text:
Q: After filtering the list, if want to check original list returns wrong list size I have a list of merchants, I am applying filter to it to search by address or a name, filter works fine. it gives proper list of filtered results. But if I again empty the  edit text I should see the original list, but I see different count than the original.
Example, in list I have 7 merchants, I do filter it and it shows two filtered merchants in the list, and now if I empty the edit text I see only 5 merchants , unable to see the original list of 7 merchants.
Adapter:
 public class SearchedMerchantsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
    static final int LOAD_MERCHANTS = 0;
    private Context context;
    public ArrayList<Merchants> list;
    public ArrayList<Merchants> baselist = new ArrayList<>();

    public SearchedMerchantsAdapter(Context context, ArrayList<Merchants> list) {
        this.context = context;
        this.list = list;
        this.baselist = list;
    }

    @Override
    public int getItemViewType(int position) {

        Object obj = list.get(position);

        if (obj instanceof Merchants) return LOAD_MERCHANTS;

        return super.getItemViewType(position);
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        int viewType = holder.getItemViewType();
        switch (viewType) {

            case LOAD_MERCHANTS:
                LoadSearchedMerchants loadSearchedMerchants = (LoadSearchedMerchants) holder;
                retriveAllMerchants(loadSearchedMerchants, position);
                break;
        }

    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, final int viewType) {
        RecyclerView.ViewHolder viewHolder = null;
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        switch (viewType) {
            case LOAD_MERCHANTS:
                View v_image_msg = inflater.inflate(R.layout.search_merchant_layout, parent, false);
                viewHolder = new LoadSearchedMerchants(v_image_msg);
                break;
        }

        return viewHolder;
    }

    @Override
    public int getItemCount() {
        return list.size();
    }

    public void retriveAllMerchants(final LoadSearchedMerchants holder, int position) {

        final Merchants data = (Merchants) list.get(position);

        holder.tv_kiarana_name.setText(data.getKirana_name());
        holder.tv_address.setText(data.getMerchant_address());

        holder.lay_row.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                Intent i = new Intent(context, MerchantProfileActivity.class);

                i.putExtra("cont_name",data.getMerchant_name());
                i.putExtra("kirana_name",data.getKirana_name());
                i.putExtra("email_id",data.getEmail_id());
                i.putExtra("phone_no",data.getPhone());
                i.putExtra("address",data.getMerchant_address());

                context.startActivity(i);

            }
        });

        holder.btnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                final SessionData sessionData;
                final String sessionUserId,access_token;

                sessionData=new SessionData(context);
                sessionUserId = sessionData.getString("user_id","-1");
                access_token = sessionData.getString("api_key", "-1");

                new SendRequestAsyncTask(context).execute(sessionUserId,access_token,data.getMerchant_id().toString());

            }
        });

    }

    public Filter getFilter() {
        return new Filter() {

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {
                final FilterResults oReturn = new FilterResults();
                final ArrayList<Merchants> results = new ArrayList<>();

                if (constraint != null) {
                    if (baselist != null && baselist.size() > 0) {
                        for (final Merchants g : baselist) {
                            if (g.getKirana_name()
                                    .contains(constraint.toString()) || g.getMerchant_address().contains(constraint.toString()))
                                results.add(g);
                        }
                    }
                    oReturn.values = results;
                }
                return oReturn;
            }

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint,
                                          FilterResults results) {
                list = (ArrayList<Merchants>) results.values;
                notifyDataSetChanged();
            }
        };
    }
}

What can be the reason for this? Thank you..

A: Can you try this ?
@Override
            protected FilterResults performFiltering(CharSequence constraint) {
                final FilterResults oReturn = new FilterResults();
                final ArrayList<Merchants> results = new ArrayList<>();

                if (charSequence != null && charSequence.length() > 0) {
                    if (baselist != null && baselist.size() > 0) {
                        for (final Merchants g : baselist) {
                            if (g.getKirana_name()
                                    .contains(constraint.toString()) || g.getMerchant_address().contains(constraint.toString()))
                                results.add(g);
                        }
                    }
                    oReturn.values = results;
                    oReturn.count = results.size();
                }
                else
                 {
                   oReturn.values = baselist;
                   oReturn.count = baselist.size();
                 }
                return oReturn;
            }

Update
Create one Method in Adapter.. Comment out getFilter() and interface Filterable
public void filterData(String compareString)
{
list.clear();
if (baselist != null && baselist.size() > 0) {
                        for (final Merchants g : baselist) {
                            if (g.getKirana_name()
                                    .contains(compareString) || g.getMerchant_address().contains(compareString))
                                list.add(g);
                        }
                    }
notifyDataSetChanged();
}

And Last call this Method From your edittext change listener
like adapter.filterData("StringwhichisChangedFromEdittext")
Hope this help.

A: Create this method in adapter:
public Item getItemAtPosition(int position)
    {
        return list.get(position);
    }

Now, when click action occurs just call this method:
adapter.getItemAtPosition(position).getMerchant_name()

A: Return the entire list if user enters nothing
 public Filter getFilter() {
    return new Filter() {

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            final FilterResults oReturn = new FilterResults();
            final ArrayList<Merchants> results = new ArrayList<>();

             if(TextUtils.isEmpty(constraint)){
              oReturn.values = baselist==null?new ArrayList() : baselist ;
              return oReturn.values ;
              }

            if (constraint != null) {
                if (baselist != null && baselist.size() > 0) {
                    for (final Merchants g : baselist) {
                        if (g.getKirana_name()
                                .contains(constraint.toString()) || g.getMerchant_address().contains(constraint.toString()))
                            results.add(g);
                    }
                }
                oReturn.values = results;
            }
            return oReturn;
        }

        @SuppressWarnings("unchecked")
        @Override
        protected void publishResults(CharSequence constraint,
                                      FilterResults results) {
            list = (ArrayList<Merchants>) results.values;
            notifyDataSetChanged();
        }
    };
}