text:
Q: knit Rmarkdown moderncv to pdf using makefile with sty file in subdirectory I am using the moderncv class to create a CV in Rmarkdown. In order to make the cv reproducible out of the box I have included the .cls and .sty files in the root directory. However, in an effort to keep the root directory uncluttered I would prefer to keep all the moderncv related files in a subdirectory (assets/tex/). I am able to access the .cls file using a relative path in the yaml front matter, but I am not able to access the .sty files unless they are in the root directory.
Searching previous questions on stackoverflow I learned the following: (1) keeping .cls and .sty files in nested directories is not recommended. I understand this and would like to do it anyway so that other people can fork my project and be able to knit the cv without having to deal with finding their texmk folder. (2) the solution to my problem seems to involve setting the TEXINPUTS using a Makefile (see this thread and another thread)
I am not very good with Makefiles, but I have managed to get one working that will knit my .Rmd file to pdf without problems, so long as the .sty files are still in root. This is what it looks like currently:
PDF_FILE=my_cv.pdf

all : $(PDF_FILE)
    echo All files are now up to date

clean :
    rm -f $(PDF_FILE)

%.pdf : %.Rmd
    Rscript -e 'rmarkdown::render("$<")'

My understanding is that I can set the TEXINPUTS using:
export TEXINPUTS=".:./assets/tex:"

Where "assets/tex" represents the subdirectory where the .sty files are located. I do not know how to incorporate the above code into my makefile so that the .sty files are recognized in the subdirectories and my .Rmd is knit to PDF. In its current state, I get the following error if I remove the .sty files from root and put then in the aforementioned subdirectory:
! LaTeX Error: Command \fax already defined.
           Or name \end... illegal, see p.192 of the manual.

which I assume is occurring because the moderncv class needs---and cannot locate---the relevant .sty files.

A: You could try to define the environment variable in the make rule:
%.pdf : %.Rmd
    export TEXINPUTS=".:./assets/tex:"
    Rscript -e 'rmarkdown::render("$<")'

Or you could set the environment variable in a set-up chunk in your Rmd file:
```{r setup, include = FALSE}
Sys.setenv(TEXINPUTS=".:./assets/tex:")
```

Note: Not tested due to lack of minimal example.


text:
Q: Is the pushout of essential monomorphism an essential monomorphism? If we have two essential monomorphisms $f\colon A\longrightarrow B$ and $g\colon A\longrightarrow C$ with pushout $\alpha\colon B\longrightarrow P$ and $\beta \colon C\longrightarrow P$ with $\alpha f=\beta g$. Is true that $\alpha f$ is an essential monomorphism?
Commonly the notion of essentiality is studied from the perspective of the subobjects, here I have the question from the perspective of supraobjects.
In the case of module theory the pushout corresponds to the internal sum, can we say anything in this case?

A: No.
In the category of abelian groups, take $f$ and $g$ both to be the map $\mathbb{Z}\to\mathbb{Z}$ given by multiplication by $2$. Then the pushout $P$ is isomorphic to $\mathbb{Z}\oplus\mathbb{Z}/2\mathbb{Z}$, and $\alpha f:\mathbb{Z}\to\mathbb{Z}\oplus\mathbb{Z}/2\mathbb{Z}$ is not an essential monomorphism, as the intersection of its image with the summand $\mathbb{Z}/2\mathbb{Z}$ is trivial.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Knockout.js - Get text selected value in a drop-down menu I would like to know how to get the value of the TEXT selected from the dropdown menu, just remember that my drop down menu has the fixed data and are not populated by a "ko.observableArray ()". Any ideas?
When I select an option want to have: Value and Text selection.

    Select a car:
    <select data-bind="value: selectedValue, optionsText:???">
      <option value="volvo">Volvo</option>
      <option value="saab">Saab</option>
      <option value="mercedes">Mercedes</option>
      <option value="audi">Audi</option>
    </select>

My ko ViewModel:
var viewModel = {
      selectedValue : ko.observable(),
      selectedText :  ko.observable()
};

ko.applyBindings(viewModel);

See this Fiddle: JSFiddle

A: I have just had to acheive this and I have added a ko.computed function to retrieve the selected text from the options as below:
// assume that options has been populated with Key / Value pairs
self.options = ko.observableArray([]);

self.selectedType = ko.observable(null);
self.selectedTypeText = ko.observable(null);
self.selectedType.subscribe(function (newValue) {
    if (newValue) {
        self.checkAccess(newValue);

        $.each(self.options(), function (i, item) {
            if (item.Key === newValue) {
                self.selectedTypeText(item.Value);
            }
        });
    }
});

A: You have to work with options binding for this. And like Jeff says, don't misuse.
var viewModel = {
      selectedValue : ko.observable(),
      selectedText :  ko.observable(),
    carOptions : ['Volvo','Saab', 'Mercedes', 'Audi']
};

ko.applyBindings(viewModel);

Markup:

    Selecte a car:
    <select data-bind="value: selectedValue, options: carOptions">

    </select>

This is the simplest way to do so. For more complicated scenarios visit the docs.
JsFiddle 1, JsFiddle 2

A: I dont know if there is a possible solution with Knockout.js. I let you two possible solutions:
Solution 1
You can use a bit of native Javascript to achieve your goal:
viewModel.selectedValue = ko.observable();
viewModel.selectedText = ko.computed(function () {
    var elem = document.querySelector("select option[value=" + viewModel.selectedValue() + "]");
    return elem && elem.innerHTML;
});

As you see, you can take the "value" and use it to return the DOM element that meets your requirements. Of course you can replace select with an id, if you need it.
Check this fiddle to see it working.
Solution 2
The Knockout way of doing this is having an array with all elements to be populated:
var cars = [{ id: 'volvo', name: 'Volvo' }, { id: 'saab', name: 'Saab' }, { id: 'mercedes', name: 'Mercedes' }, { id: 'audi', name: 'Audi' }];

After that, it depends on what you need when you say "value", remember that you are binding an object, not a key/value list:
HTML:
<select data-bind="options: cars, value: selectedCar, optionsText: 'name'"></select>

And your JS:
selectedCar = ko.observable();
selectedValue = ko.computed(function () {
    return selectedCar() && selectedCar().id;
});
selectedText =  ko.computed(function () {
    return selectedCar() && selectedCar().name;
});

This way you will have separately your "value" and your "text" (better called id and name properties) into two computed observables.
See the fiddle working.

A: here is my solution, define a variable in js file like selectedValue (it is observable), then decorate your select with this item.
 <select data-bind="options: listOfData,
optionsText: function (item) { return item.propertyForText; }, optionsValue:
function(item) { return item.propertyForValue; },
value: selectedValue">
</select>


text:
Q: I am trying to VIEW 4 columns from 2 different tables I have already created in Oracle Live SQL I want to use the VIEW command to display these 4 columns in one single schema. I have tried making a single VIEW with the first 3 columns, because they are from the the same table. Adding the one other column is where I'm struggling. I have tried the ALTER function but a VIEW schema doesn't seem to have the same edit privileges as a table would. I hope that makes sense.
create table PATIENTINFO (
    PatientID       number not null,
    FirstName       varchar2(50) not null,
    LastName        varchar2(50) not null,
    Address         varchar2(50),
    City            varchar2(50),
    State           varchar2(50),
    ZipCode         number(5),
    Phone           number(10) not null ,
    Email           varchar2(50),
    MemberID        number not null,
    constraint  pk_departments primary key (PatientID)
)

create table LABORDER (
    LabOrderNumber  number not null,
    OrDate          date not null,
    ReqBloodTest    varchar2(15) not null,
    Reason          varchar(50),
    PatientID       number not null,
    constraint  pk_laborder primary key (LabOrderNumber),
    constraint  fk_laborder_patientid foreign key (PatientID)
            references PATIENTINFO (PatientID)
)

CREATE VIEW PatientBlood AS
      SELECT FirstName, LastName, PatientID
      FROM PATIENTINFO

A: Write the query you want and then create a view out of it. I started by writing the query below and then prefixed it with CREATE OR REPLACE VIEW. The example below has some randomly selected columns, change it to whatever columns you need. I chose to name my columns in the view definition, you can omit that but also do a million other things as stated in the docs
Side note: don't use mixed case for identifiers like column names/table names. It is confusing. In your case it didn't matter since you didn't use quotes, so they're case insensitive and the view below will work even though the identifiers are all lower case.
CREATE OR REPLACE VIEW laborder_v (
  labordernumber,
  patientid,
  lastname
) AS
  SELECT o.labordernumber,
         p.patientid,
         p.lastname
    FROM laborder o
    JOIN patientinfo p ON o.patientid = p.patientid;


text:
Q: PHP change file extension in HTML as plaintext I want to change file extension in HTML code on PHP output. Probably with regex and this is something I really cannot handle..
...some code......some code...
should be changed to
...some code......some code...
Please note that:

*

*there might be any number of occurances (zero, one, multiple),

*I want to change only those from https://static.example.com/gallery/ and not from  https://example.com nor https://static.example.com

*I dont want to parse it as DOM, because it is so slow for my purpose.

Thank you.

A: How about something simple like:
(?<='https:\/\/static\.example\.com\/gallery\/)(.*?)(\..*?)(?=')

As seen here at regex101.com.
Explanation:
We use the regex positive lookbehind in this (?<=) which ensures that the match must be preceded by the site name. If you want the site name to be variable too, that's a whole 'nother issue.
As long as the site name is fixed to static.example.com/gallery/, we can just capture the name of the file in the first parentheses (capturing group 1), and the dot+extension in capturing group 2. Then we can just replace this match with the file name (1st capturing group $1) and the new dot+extension .webp.


text:
Q: Mockito exectues "when-then" from previous test When I run these tests separetly, they work just fine but when I execute "run all tests in class", then test shouldSaveProduct fails. I get exception("DataIntegrityViolationException") which is specified in previous test. It looks like Mockito.when(productRepositoryMock.save(any())).thenReturn(product); does not override:
Mockito.when(productRepositoryMock.save(any())).thenThrow(new DataIntegrityViolationException("...SYMBOL_UQ..."));

@ExtendWith(MockitoExtension.class)
@TestInstance(TestInstance.Lifecycle.PER_CLASS)
class ProductServiceImplTest {

    private ProductService productService;
    private ProductRepository productRepositoryMock;

    @BeforeAll
    void setup() {
        productRepositoryMock = Mockito.mock(ProductRepository.class);
        productService = new ProductServiceImpl(productRepositoryMock);
    }

    @Test
    void shouldThrowProductExceptionBecauseOfDuplicateSymbol() {
        // given
        Product product = new Product();
        Mockito.when(productRepositoryMock.save(any()))
                .thenThrow(new DataIntegrityViolationException("...SYMBOL_UQ..."));
        // when && then
        ProductException exception = Assertions.assertThrows(ProductException.class, () ->
                productService.saveProduct(product), "Expected to throw ProductException");
        assertEquals(ProductExceptionMessage.SYMBOL_MUST_BE_UNIQUE, exception.getMessage());
    }

    @Test
    void shouldSaveProduct() {
        // given
        Product product = getProduct();
        Mockito.when(productRepositoryMock.save(any())).thenReturn(product);
        // when
        ProductTO resultProduct = productService.saveProduct(product);
        // then
        assertEquals(product.getName(), resultProduct.getName());
    }
}

When I use @TestInstance(TestInstance.Lifecycle.PER_METHOD) and @BeforeEach, then it works but I don't understand why it doesn't work with configuration presented above. Can anyone explain it to me?

A: Because this line
 @TestInstance(TestInstance.Lifecycle.PER_CLASS)

Its make Junit create one instance of the test class and reuse it between tests.


text:
Q: Why does the UI thread hang when updating list in background? I thought I had a pretty good handle on threading until I came across a scenario in which I wanted to benchmark updates to different grids.
I created a window with a grid control, bound an ObservableCollection to it and populated it with 5000 rows of some complex data type (which contains no locks).
Then I created a task using
 Task.Factory.StartNew()

This went through a very tight loop (10 million iterations) updating a random property on a random item in my ObservableCollection, each of which raises an INotifyPropertyChanged event of course.
Now since the updates are all happening on the background thread I expected the UI to update, albeit hard-pressed to keep up with this background thread spinning in a tight loop.
Instead the UI froze for several seconds (but didn't go blank or produce the usual spinning cursor of doom) and then came back once the background thread finished.
My understanding was that the background thread would be taxing a core pretty heavily while producing tons of INPC's, each of which get marshalled automagically by the WPF runtime to the UI thread.
Now the UI thread is doing nothing so I expected it to consume all these INPC's and update the grid but it didn't; not a single update occurred. However, when I do this using a Timer (instead of a tight loop) it works fine.
Would someone please enlighten me as to what the heck the UI thread is doing? Thanks in advance!

A: If you clog up the message pump with a lot of dispatched updates like this, other messages won't get a chance to be processed, which causes the 'freeze' effect you observe.
One thing that can help here is to use Data Virtualization on your UI control so that only the visible rows are actually bound and listening to INPC updates.  This is turned on by default for DataGrid, but if you're using a more custom approach to visualizing the data, this could be an issue.
That said, this won't help with frequent modifications to items that are currently visible, as truly rapid fire updates will still clog up the dispatcher.  If you have a use case like this, you probably want to isolate your view model objects a bit and have a way to 'batch' your updates.  One technique is to have a way to suppress notification while you do a bunch of updates, then call RaisePropertyChanged(null) (or whatever equivalent method on your INPC helper base class) on each instance to update all bindings to that instance.
Another mechanism is to make the data updates in some other layer (whatever model object(s) your view model instance is representing), then copy over those properties to the view model class at well-defined intervals.  For rapidly updating background data, I often use a polling loop rather than triggering on events, simply because the events would occur more frequently than the UI cares about and it slows down the background processing to send all these unnecessary notifications constantly.


text:
Q: Deploying access policies in Azure Does anyone know if it is really neccessary to insert the actually object-ID in the access policy name property? It seems like it work just fine with any "string".
"name": "[concat('connection-name'),'/','object-ID')]"
The object-ID is used together with the tenant-ID as one of the identity properties. So why does it have to be used twice according to Microsofts ARM Template description
https://learn.microsoft.com/en-us/azure/logic-apps/azure-arc-enabled-logic-apps-create-deploy-workflows?tabs=azure-cli
 {
       "type": "Microsoft.Web/connections/accessPolicies",
       "apiVersion": "2016-06-01",
       "name": "[concat('<connection-name>'),'/','<object-ID>')]",
       "location": "<location>",
       "dependsOn": [
          "[resourceId('Microsoft.Web/connections', parameters('connection_name'))]"
       ],
       "properties": {
          "principal": {
             "type": "ActiveDirectory",
             "identity": {
                "objectId": "<object-ID>",
                "tenantId": "<tenant-ID>"
             }
          }
       }
    }

A: In single-tenant Azure Logic Apps, each logic app has an identity that is granted permissions by access policies to use Azure-hosted and managed connections.
The name property of the access property in the above JSON code represents the Connection name and it is a required field. You can give any string value in the name property. At the same time it's not mandatory to put object id. But it's recommended to concatenate the object id with connection name to make the connection name unique and to avoid ambiguity.
Please check the following Microsoft.Web/connections/accesspolicies (ARM template) documentation for more information.


text:
Q: redirect after login with context I'm trying to get a login function to redirect to a certain view, but I can't find a way to use a navigate or this.props.push inside the context api. The function that makes the redirection is handleLogin and is consumed from loginForm view.
but if I tried to use useNavigate, I would have to transform that class component to a functional
AppProvider
// React
import React from 'react';

// AppContext
import AppContext from '../AppContext';

// Axios
import axios from 'axios';

// React-cookies
import cookies from "js-cookie";

class AppProvider extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      store: {
        userInfo: {},
        isLoggedIn: localStorage.getItem('isLogged') ? true : false
      },
      actions: {
        handleLogin: this.handleLogin
      }
    }

  }

  handleLogin = (e, credentials) => {
    e.preventDefault();

    axios.post('/users/signin', credentials, {
      'content-type': 'application-json'
    })
    .then((res) => {
      cookies.set('auth-token', res.headers['auth-token']);
      this.setState({store:{isLoggedIn: true}});
      localStorage.setItem('isLogged', true);

    })
  }

  render() {
    return(
      <AppContext.Provider value={this.state}>
        {this.props.children}
      </AppContext.Provider>
    );
  }
}

export default AppProvider;

LoginForm:
// React
import React, { useState } from 'react';

// Mui
import { Grid, Card, CardContent, TextField, Button, Typography } from '@mui/material';

// React-router
import { Link, useNavigate } from 'react-router-dom';

// Axios
import axios from 'axios';

// React-cookies
import { useCookies } from "react-cookie";

// Context
import AppContext from '../../AppContext';

const LoginForm = () => {

  const navigate = useNavigate();

  const [ credentials, setCredentials ] = useState({
    email: null,
    password_digest: null
  });

  const [cookies, setCookies] = useCookies(['auth-token']);

  const handleChange = (e) => {
    setCredentials({...credentials, [e.target.name]: e.target.value});
  }

  return(
    <AppContext.Consumer>
      {context => {
        console.log(context)
        return(
          <Grid container direction="column" alignItems="center" paddingTop="10%">
            <Grid item xs={3}>
              <Card
              style={{
                background: '#1e272e',
                padding: '1em'
              }}
              >
                <Typography textAlign="center" color="white">
                  Welcome!
                </Typography>
                <CardContent>
                  <form onSubmit={(e) => context.actions.handleLogin(e, credentials)}>
                      <TextField
                        variant='filled'
                        label="email"
                        name="email"
                        onChange={handleChange}
                        sx={{
                            display: 'block',
                            margin: '.5rem 0'
                          }}
                          inputProps={{style: {color: 'white'}}}
                          InputLabelProps={{style: {color: 'white'}}}
                      />
                      <TextField
                        variant="filled"
                        label="password"
                        name="password_digest"
                        type="password"
                        onChange={handleChange}
                        rows={4}
                        sx={{
                          display: 'block',
                          margin: '1rem 0'
                        }}
                        inputProps={{style: {color: 'white'}}}
                        InputLabelProps={{style: {color: 'white'}}}
                      />
                      <Button variant='contained'
                              color='primary'
                              type='submit'>
                          Login
                      </Button>
                  </form>
                  <Link to="/register"><Typography variant="span" style={{fontSize: '.8em'}} mt={2} color="white">Don't you have an account? Sign up</Typography></Link>
                </CardContent>
              </Card>
            </Grid>
          </Grid>
        )
      }}
    </AppContext.Consumer>
  )
}

export default LoginForm;

A: You have to create a route config declaring routes and the files each route points to. This will help in letting react-router know what view to display when redirected to the respective link.
Refer the tutorial here for more information.


text:
Q: Darlington Transistor functionality After looking at the schematic for this particular darlington transistor (see picture pasted below) I had some questions about basic functionality.
First, the diode at the top right of the picture has its cathode leading towards the postivie Vcc voltage supply, wouldn't this reverse bias the diode and prevent any current from flowing even when current is applied to the base of the transistors?
Second, the output is not in series with the supply voltage so when the the transistors are switched on, what prevents the current from just following the path from directly from Vcc to ground (emitter)?? I guess I just don't understand how tying a load to the output terminal would do anything if the supply voltage has a direct path to ground like that.

A: There needs to be a tad bit of context for this circuit to make sense. The ULN200X series of chips are designed to drive relays and other inductive loads. VCC isn't really VCC like you think of it. That diode to "VCC" serves as a flyback diode to simplify relay connections. most datasheets refer to it as "common" since it can be very much different from VCC on your board.
This datasheet has a better idea on how that works, look at page 12 and 17.

A: Your ULN2003A darlington darling is configured as an open collector output.  Open collector outputs are great, because they let you connect lots of devices to a bus without loading it heavily.  I2C, for example, uses open-collector outputs.  Normally, the output pin would be connected to VCC with a pullup resistor.  When you drive the input high, the BJTs begin conducting, resulting in a low impedance path to ground.  The output is then low.  When you release the input, the output pin has a high impedance to ground, and the line is pulled to VCC.  When many open-collector devices are sharing a bus and one device outputs a logic low while the rest are outputting a logic high, the low wins out and pulls everything low without carrying all of the current from every connected logic-high device to ground.
To answer your questions, the reverse-biased diode on your VCC pin is definitely supposed to be there.  It's used to clamp your output pin voltage to no higher than VCC plus the diode drop.  That'd be so you don't fry anything else on the bus.  That chip's full of protection diodes.  Input to GND and Output to GND both have diodes that protect against a reversed polarity on the pins.  Is this device meant to be hot-swapped?  I expect this is all about shunting transient voltage spikes, like what you'd see from ESD or disconnecting a cable while current is flowing through it, to ground and protecting the device and everything upstream of it.
For your second question, I guess I jumped the gun and partially answered it at the top.  Current shouldn't flow into the VCC pin at all.  You're right in that, if the diode were reversed, you'd either have an output high or a hard short to ground.  With the pull-up on the output pin, though, that's no longer the case.


text:
Q: Is "$a^p + b^p = c^p + d^p \Rightarrow (a+b) \equiv (c+d) \mod p$" true?
Is $$a^p + b^p = c^p + d^p \implies (a+b) \equiv (c+d) \mod p$$ true?

Let $a,b,c,d$ be (distinct) positive integers, and $p$ be prime.  My reasoning is roughly as follows:
$$(a^p + b^p) \equiv (a^p \mod p + b^p \mod p) \mod p$$
then by Fermat's Little Theorem
$$(a^p + b^p) \equiv (a \mod p + b \mod p) \mod p$$
$$\Rightarrow (a^p + b^p) \equiv (a + b) \mod p$$
and similarly
$$(c^p + d^p) \equiv (c+d) \mod p.$$
If $a^p+b^p=c^p+d^p$ then clearly $(a^p+b^p) \equiv (c^p+d^p) \mod p$, and hence (less clearly), $(a+b) \equiv (c+d) \mod p$.
EDIT: the motivation for this question is an efficient algorithm to search for Taxicab(5,2,2).

A: Just found another nice proof of this fact (for n = 5, but can "easily" be generalised to all $p$): by the binomial theorem,
$$(a+b)^5 = a^5 + 5a^4b + 10a^3b^2 + 10a^2b^3 + 5ab^4 + b^5$$
which can be rearranged to show that
$$a^5+b^5 = (a+b)^5 - 5(a^4b + 2a^2b^3 + 2a^3b^2 + ab^4)$$
$$\Rightarrow a^5 + b^5 \equiv (a+b)^5 \mod 5$$
$$\therefore a^5 + b^5 \equiv c^5 + b^5 \mod 5 \Rightarrow (a+b)^5 \equiv (c+d)^5 \mod 5$$

A: This is perfectly fine,  the only detail is that you absolutely don't need the four integers to be distinct, they could be anything.


text:
Q: Print the contents of a UIWebView to a .png Looking for an example to capture the contents of a UIWebView to a image file, all in the background.  Most likely the UIWebView will be hidden or framed off the main window so the user never sees this happening.
Thanks in advance!
Rob

A: The following code will capture the content of the webview and that will be saved as a .png file
    UIGraphicsBeginImageContext(webview.bounds.size);
    [webview.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    // Write image to PNG
    NSString  *pngPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/Test.png"];
    [UIImagePNGRepresentation(image) writeToFile:pngPath atomically:YES];


text:
Q: Is there a way to seed a key with a value of an array of strings? I'm trying to seed some data using an external trivia API.
Here's what I have in my seeds.rb file where HTTParty is a gem that parses JSON into a ruby hash:
response = HTTParty.get("THE-API-SITE")
response.each do |trivia|
    triviaHash = {
        category: trivia["category"],
        answer: trivia["correctAnswer"],
        incorrect: trivia["incorrectAnswers"],
        question: trivia["question"],
    }
    Trivia.find_or_create_by(triviaHash)
end

And here's my schema:
create_table "trivia", force: :cascade do |t|
    t.string "category"
    t.string "answer"
    t.string "incorrect"
    t.string "question"
    t.datetime "created_at", precision: 6, null: false
    t.datetime "updated_at", precision: 6, null: false
    t.string "ids"
  end

Everything works except for the "incorrect" key which should have a value of an array of strings of incorrect answers, but when I seed my data, I get a string of the array of incorrect answers.
What I want:
incorrect: ["Deep Purple", "Feeder", "Uriah Heep"],

What I'm getting:
incorrect: "["Deep Purple", "Feeder", "Uriah Heep"]",

I'm not sure how to get what I want or if it's even possible the way I'm going about it.

A: Since your column incorrect is of type string, so the data stored in DB will also be a string value.
If your DB supports array data type then you can use that or else I would suggest you to use this in your model.
serialize :incorrect, Array

A: Change your migration field for incorrect field, from:
t.string "incorrect"

to:
t.text :incorrect, array: true, default: []

Also I suggest you to use symbols instead of strings for column names and use t.timestamps that generates created_at and updated_at for you


text:
Q: What is "pointwise", in the context of function composition? APOLOGY: This question is asked by someone foreign to math, with the expectation that math.stackexchange can be a resource to (among other things) understand math concepts.
I'm a self-taught project-of programmer. I would like to understand "projection", beacuse it's used in functional programming (related to lamda calculus I hear), and in a database called MongoDB.
For the math term of projection Wikipedia links to "function composition", whose page in turn links to "pointwise".
The question is: What is "pointwise", in the context of function composition?
So that (from wikipedia's "projection")

"In mathematics, a projection is a mapping of a set (or other mathematical structure) into a subset (or sub-structure), which is equal to its square for mapping composition (or, in other words, which is idempotent)."

Can be understood once (from wikipedia's "function composition"):

In mathematics, function composition is the pointwise application of one function to the result of another to produce a third function.

Is understood...
Thanks in advance.
Also, resources to material that can help with this kind of doubts are very much welcome

A: It means that the composition of $f$ and $g$ is defined as
$$(f \circ g)(x) = f\big(g(x)\big)$$
where $f$ is applied to the result of $g$ separately for each $x$,
rather than applying $f$ globally to $g$ itself like this:
$$x \mapsto \big(f(g)\big)(x).$$
To give you an example, let $f(h) = x \mapsto \langle h(x), h(x) \rangle$
and define $g$ as
$$
g(x) = \begin{cases}
y \mapsto y+2 & \text{if } x = 0, \\
y \mapsto y\cdot 2 & \text{otherwise}.
\end{cases}
$$
Then
$$(f \circ g)(x) = \begin{cases}
y \mapsto \langle y+2, y+2 \rangle & \text{if } x = 0, \\
y \mapsto \langle y\cdot 2, y \cdot 2\rangle & \text{otherwise},
\end{cases}
$$
while
$$\big(f(g)\big)(x) = \begin{cases}
\langle y \mapsto y+2, y \mapsto y+2 \rangle& \text{if } x = 0, \\
\langle y \mapsto y\cdot 2, y \mapsto y\cdot 2 \rangle & \text{otherwise}.
\end{cases}
$$
I hope this helps $\ddot\smile$
Edit: For programmers (in Python):
def f(h):
  return lambda x: (h(x), h(x))

def g(x):
  if x == 0:
    return lambda y: y+2
  else:
    return lambda y: y*2

def compose(f, g):
  return lambda x: f(g(x))

def fg_compose(x):
  if x == 0:
    return lambda y: (y+2, y+2)
  else:
    return lambda y: (y*2, y*2)

def fg_apply(x):
  if x == 0:
    return (lambda y: y+2, lambda y: y+2)
  else:
    return (lambda y: y*2, lambda y: y*2)

Now compose(f, g) is equivalent to fg_compose,
and f(g) is equivalent to fg_apply, that is,
under most circumstances compose(f,g)(x) should give
you the same result as fg_compose(x), and f(g)(x)
should give you same result as fg_apply(x).
That being said, in programming few objects are pure, and while
the corresponding ideal mathematical functions are equal, the execution paths in whatever language you are using are probably different, and so the final results might sometimes fail to match (the easiest example that comes to mind is that compose(f,g)(x) probably uses more memory than fg_compose(x) and so in the rightly contrived circumstances the former will fail while the latter might still work).

A: IMO that is a needlessly confusing application of the word 'pointwise' in that article intro.
I have always seen "pointwise multiplication" refer to the operation of multiplying two functions via the rule $fg(x)=f(x)g(x)$. That is, you multiply the values as if they were parallel lists, and you multiply corresponding terms. Similarly, you could say that vector addition is 'pointwise addition' because you're adding the entries in parallel according to their indices.
In the article, rather, it is just using it to mean that they are describing the value of a newly formed function at $x$ in terms of a point $x$ and the two functions $f,g$.
Whoever wrote that probably could argue why the phrase is technically correct, but I don't think it clarifies anything. It is so common to describe functions by their action on each individual point that it does not seem helpful to call it 'pointwise.'


text:
Q: setting up environment variables in Play! framework I am trying to get the Play! framework up and running. After I extracted Play! version 2.3.0 to C:\Play and adding that directory (C:\Play) to my path in 'Environment Variables' (separated form the other paths with a ;), I tried running it with the command "Play new foobar" and I keep getting the error "'Play' is not recognized as an internal or external command, operable program or batch file."
I have looked at a few possible fixes to this on here
Configuration Variables in Play! Framework
Setting an environment variable for play framework
Adding an environment variable for the Play! Framework
(The third was the most similar but that solution is not working for me.)

A: In Play 2.3+ play command is replaced by activator.
More details in What's new in Play 2.3 doc


text:
Q: AngularJS notification system I have a notification system in the backend but I don't know how to implement it in the frontend side.
I want to make an AngularJs service that listens for any requests from the server and then I will display the notification(like facebook notification).Is this possible ?
this to overcome the problem of sending request every "period"to the server.

A: Since you are listening for data sent by the server, I assume you are using WebSockets. There is https://github.com/AngularClass/angular-websocket that slightly simplfies working with WebSockets in Angular.

If you are referring to PushNotifications, that is implemented in the ServiceWorker, not in the Angular app.
self.addEventListener('push', event => {
    let data = event.data.json();
    let title = '', args = {};

    title = 'Notification!!';
    args = { 'body': 'Hello hello',
             'icon': '/static/icon64.png',
             'tag': 'some-tag' };

    event.waitUntil(self.registration.showNotification(title, args));
});

A: You can user SignalR for real time to build real time notification system . Just specify the hub name, listening functions, and methods that you're going to use.
This library can be useful.


text:
Q: How to drop a table I am using following C# method to execute SQL queries:
public bool ExecuteQuery(String pQuery)
{
    SqlConnection con = new SqlConnection("MyConnectionString");
    con.Open();

    SqlTransaction trans = con.BeginTransaction(IsolationLevel.ReadCommitted);

    try
    {
        SqlCommand cmd = new SqlCommand(pQuery, con, trans);
        cmd.ExecuteNonQuery();
        trans.Commit();
        con.Close();
        trans.Dispose();
        return true;
    }
    catch (Exception exp)
    {
        trans.Rollback();
        con.Close();
        MessageBox.Show(exp.Message, "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

    return false;
}

When I pass this statement:
ExecuteQuery("DROP TABLE MyTable");

then the method returns true, which means it worked fine, but when I check SQL Server, myTable was not dropped. If I run the same statement in SQL Server Management Studio, MyTable is dropped...
Where am I wrong?

A: Before answering your question, some comments:

*

*Avoid coding such operations using query text, this is a high chance you can get problems with security. Better create stored procedure that executes table drop:
create procedure sp_DropTable
@tablename varchar(200)
as
BEGIN
    DECLARE @SQL VARCHAR(MAX);
    SET @SQL = 'IF EXISTS(SELECT 1 FROM sys.objects WHERE OBJECT_ID = OBJECT_ID(N''' + @tableName + ''') AND type = (N''U'')) DROP TABLE [' + @tableName + ']'

    EXEC (@SQL);
   END
GO

Then pass the stored procedure's name as parameter to your function. Now back to your error.
Table drop is not a transaction, but you try to execute it in transactional schema. This makes it fail. Try:
public bool ExecuteQuery(String pQuery)
{
    SqlConnection con = new SqlConnection("MyConnectionString");
    con.Open();

    try
    {
        SqlCommand cmd = new SqlCommand(pQuery, con);

        // if you pass just query text
        cmd.CommandType = CommandType.Text;

        // if you pass stored procedure name
        // cmd.CommandType = CommandType.StoredProcedure;

        cmd.ExecuteNonQuery();

        con.Close();

        return true;
    }
    catch (Exception exp)
    {
        con.Close();
        MessageBox.Show(exp.Message, "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }

    return false;
}


text:
Q: unittest.mock.patch: Context manager vs setUp/tearDown in unittest There seems to be 2 ways to use unittest.mock.patch: is one way better?
Using a context manager and with statement:
class MyTest(TestCase):
    def test_something(self):
        with patch('package.module.Class') as MockClass:
            assert package.module.Class is MockClass

Or calling start and stop from setup and tearDown/cleanup:
class MyTest(TestCase):
    def setUp(self):
        patcher = patch('package.module.Class')
        self.MockClass = patcher.start()
        self.addCleanup(patcher.stop)

    def test_something(self):
        assert package.module.Class is self.MockClass

The context manager version is less code, and so arguable easier to read. I there any reason why I should prefer to use the TestCase setUp/tearDown infrastructure?

A: The main reason to prefer patching in the setUp would be if you had more than one test that needed that class patched. In that case, you'd need to duplicate the with statement in each test.
If you only have one test that needs the patch, I'd prefer the with statement for readability.

A: There is yet a third way to use it, as a decorator:
class MyTest(testcase):

    @unittest.mock.patch('package.module.Class')
    def test_something(self):
        assert package.module.Class is self.MockClass

This is even less code, but that may not be relevant.
There are a few considerations: (1) (as pointed out by babbageclunk) if you will need to reuse the patch, then a plain, boring call to construct one in setUp is best, and is easily readable. (2) if you want to create any metaprogramming facilities so that you can turn on or off the patching when you run tests, then the decorator approach will save you a lot of trouble. In that case, you can write an additional decorator, or use a global variable (ick) to control whether the patch decorators get applied to the test functions or not. If they are embedded inside the function definitions, then you have to manually deal with them if you ever want to turn off patching when running tests. One simple reason why you might want this is merely to run the tests with no patching to induce lots of failures and observe which pieces you have not implemented yet (your decorator for metaprogramming the patches, in fact, could catch these issues and print nice NotImplemented exceptions for you, or even generate a report containing such things). There could be many more reasons to want fine control over whether (and to what degree) patching is "dispatched" in the test suite at a given time.
The decorator approach is also nice in that (a) it lets you isolate which patches go to which test functions in a manner that is outside of that function, but without committing it to setUp, and (b) it makes it very clear to the reader when a given function requires a given patch.
The context manager version does not seem to have many benefits in this case since it is hardly more readable than the decorator version. But, if there really is only a single case, or a very small set of specific cases, where this is used, then the context manager version would be perfectly fine.


text:
Q: ClassFormatError using JMockit with EMMA I am trying to use EMMA to measure coverage of some JUnit tests that use JMockit. But when I try to run the JMockit tests after instrumenting with EMMA, about a quarter of the tests fail with the following error:
com.logstorage.engine.sensor.SensorManagerTest.setUpBeforeClass(SensorManagerTest.java:98)
    java.lang.ClassFormatError
    at sun.instrument.InstrumentationImpl.redefineClasses0(Native Method)
    at sun.instrument.InstrumentationImpl.redefineClasses(InstrumentationImpl.java:150)
    at mockit.internal.RedefinitionEngine.redefineMethods(RedefinitionEngine.java:152)
    at mockit.internal.RedefinitionEngine.redefineMethods(RedefinitionEngine.java:139)
    at mockit.internal.RedefinitionEngine.redefineMethods(RedefinitionEngine.java:73)
    at mockit.Mockit.setUpMock(Mockit.java:235)
    at com.myapp.MyTest.setUpBeforeClass(MyTest.java:98)

I can't see any pattern as to which tests fail and which don't. I guess this is just a bug in JMockit, but does anybody know a workaround?
I found a very similar question called "Getting ClassFormatError with EMMA?" but the solution doesn't work for me (I'm not using any reentrant=true mock methods). Any other ideas?
Thanks in advance.

A: I have been running into the same problem - this seems to have fixed it for me and hopefully will help anybody else as well.
If you're running this through ant, make sure you don't have vars in your javac target's debuglevel argument. The following target will cause the error.
<javac srcdir="${src}" destdir="${bin}" debug="on" debuglevel="lines,source,vars" nowarn="true" />

Change it to:
<javac srcdir="${src}" destdir="${bin}" debug="on" debuglevel="lines,source" nowarn="true">

This is probably a JMockit bug - very subtle and annyoing to find out.

A: I only saw this question today, but if you can, send me some tests that throw the ClassFormatError when running with EMMA, and I will try to find the bug in JMockit.
By the way, have you tried to use JMockit Coverage? Just add jmockit-coverage.jar to the classpath, and see what you get. Typically, this will produce (without any extra configuration) a nice HTML coverage report in the "coverage-report" dir under the working dir. It can't get any easier than that!

A: My team had the same issue. The concrete case was: using jMockit to mock static methods from a class in a unit-test suite running under TeamCity with EMMA as the coverage tool. The solution was the following:
Add a tear-down method to each test which mocked static methods:
@After
public void tearDown() throws Exception {
  Mockit.tearDownMocks(ClassWithStaticMethods.class);
}

A: Update jmockit from 1.5 to any recent version.


text:
Q: How do I select row based on the number of times it appears in the table? I have my table: call it tblA  THis table has three rows, id, sub-id, and visibility
sub-id is the primary key (it defines taxonomies for id).  I'm trying to build a query that selects every id that appears less than three times.
here is an example query/result
select * from tbla where id = 188002;
+--------+--------+-------------+
| sub-id |  id    | visibility  |
+--------+--------+-------------+
| 284922 | 188002 |      2      |
| 284923 | 188002 |      2      |
| 284924 | 188002 |      0      |
+--------+--------+-------------+

From what i've seen here and here it looks like I need to join the table on...itself.  I dont really understand what that accomplishes.
If anyone has insight into this, it is appreciated.  I will continue to research it and update this topic with any additional information I come across.
Thanks

A: SELECT id
    FROM tbla
    GROUP BY id
    HAVING COUNT(*) < 3

A: If you want to select all columns from the table, you will have to use @Joe's query in a sub-select:
SELECT * FROM tbla a
WHERE a.id IN (SELECT DISTINCT b.id
               FROM tbla b
               GROUP BY b.id
               HAVING COUNT(*) < 3)

This query first selects all id's that have fewer than 3 duplicates.
The distinct eliminates duplicates, the query works the same without, but slightly slower.
Next it selects all rows that have an id that meets the criteria in the sub-select i.e. that have fewer than 3 duplicate id's.
The reason that you cannot do this in one go is that the group by heaps all rows with the same id together into one super-row (for want of a better metafor) .
You cannot separate out the columns that are not in the group by clause.
The outer select solves this.


text:
Q: Is the waiting for review and the result of the request considered part of the flow of events for submitting the request? A company wants to build an online recruitment system. The logged-in person can add the recruitment application, and attach his CV and some documents.
He will wait for the application to be reviewed by the HR, perhaps for a few days.
The company requests to continue the recruitment process or informs that the application is rejected.
My question:
Are the waiting application to be reviewed and the company's response considered within the flow of events for the add employment application use case?
If the answer is Yes:
Does the Basic Flow includes both responses (continue recruitment process and rejection of the application)
or is rejection of the application considered within the Alternative Flows?

A:
Are the "waiting application to be reviewed" and the "company's response" considered within the flow of events for the "add employment application" use case?

That depends on the level of abstraction and the viewpoint you have in that use case.
If the use case is written from a very high-level viewpoint, the company's response, any subsequent interview rounds up to the actual hiring could be part of the use case.
If the use case is written more from a viewpoint of the interactions that a user has with the software application, then it might be better to restrict each use case to the flow of events that would typically happen in a single sitting/session with the application.
A step "waiting for application to be reviewed" should definitely not be part of a use case. It is not an action someone (or the system) takes within the interaction. It is at best an indication of time between the steps of the use case. Such waiting times are usually left implicit.

Does the Basic Flow includes both responses ("continue recruitment process" and "rejection of the application") or is "rejection of the application" considered within the Alternative Flows?

The Basic Flow shows only a single path through the use case, typically the most common path to a successful result.
The Alternative Flows show other ways within the use case that the user can reach their goal.
If the user cannot achieve their goal, then at some point they deviate into an Exception Flow.
Assuming the the user's goal is that they are hired, then the rejection of their application means they go into an Exception Flow at that point (which probably quickly terminates the use case).

A: The use-case Add employment application seems to correspond to a rather precise and elementary goal: once it's added, it's done. Nothing suggest that there could me more behind it.
If it would be Apply for employment, it would suggest that there is a bigger picture:  the application process is broader than adding an application: it could include the reply, invitations to interviews, etc.
Ultimately, you decide what's in it, in your narrative that describes the case. But it should be consistent with the with the use-case name.
Other use-case elements play a role as well:

*

*if the use-case has two actors, the candidate as primary actor and the recruiter as secondary actor, you'd strongly suggest some kind of feedback, since the secondary actor is involved in addressing the goals of the primary actor.

*if there's only one actor, I'd tend to imagine that if there's a feedback, it'll be some kind of delivery receipt.

Waiting is not an action. Waiting is the consequence of a reply that is not immediate. I'd strongly advise not mention it at all. If you'd nevertheless want it:

*

*be aware that "waiting"  would strongly suggest active waiting, i.e the user stays in front of the system until the reply is there.

*other terms may better reflect what the user is doing all that time, e.g. monitoring the application, checking for response, etc...

So, since use-cases are a communication tool, it is important to invest some time choosing accurate and precise terms to name things and reduce misunderstandings.


text:
Q: Finding Lyapunov function for a stable equilibruim of a non linear system Given the following system:
$$
\left\{
\begin{array}{c}
\dot x=y-x^2-x \\
\dot y=3x-x^2-y
\end{array}
\right.
$$
I need to find the equilibrium points, and if stable, to find a Lyapunov function.
I have found two equilibrium points: $(0,0), (1,2)$. By linearization I'v found $(0,0)$ to be unstable, and $(1,2)$ to be stable. I tried to find a Lyapunov function for $(1,2)$ with no success. How can I find such a function?

A: Considering the surroundings for $(1,2)$ we have
$$
\left\{
\begin{array}{c}
\dot x=y-x^2-x \\
\dot y=3x-x^2-y
\end{array}
\right. \approx \left\{
\begin{array}{c}
\dot x=y-3x+1 \\
\dot y=x-y+1
\end{array}
\right.
$$
because linearizing about $(1,2)$ we have
$$
\left(\begin{array}{c}
y-x^2-x \\
3x-x^2-y
\end{array}
\right) = \left(\begin{array}{c}
0 \\
0
\end{array}
\right)+\left(
\begin{array}{cc}
 -3 & 1 \\
 1 & -1 \\
\end{array}
\right)\left(\begin{array}{c}
x-1 \\
y-2
\end{array}
\right)+O(x,y)
$$
now considering a local Lyapunov function such as
$$
V = \alpha (x-1)^2+\beta(y-2)^2
$$
we have
$$
\dot V =-2 (\alpha  (x-1) (3 x-y-1)-\beta  (y-2) (x-y+1))
$$
or
$$
\dot V = (x-1,y-2)^{\dagger}\cdot H \cdot(x-1,y-2)
$$
with
$$
H = \left(
\begin{array}{cc}
 -6 \alpha  &  \alpha +\beta  \\
 \alpha +\beta  & -2 \beta  \\
\end{array}
\right)
$$
with eigenvalues
$$
\lambda = \pm\sqrt{2} \sqrt{5 \alpha ^2-2 \alpha  \beta +\beta ^2}-3 \alpha -\beta
$$
now it is easy to show that there exists $\alpha > 0, \beta > 0$ such that
$$
\lambda < 0
$$
hence this affirm the existence of a local Lyapunov function to assure the stability of $(1,2)$


text:
Q: Swift changing my xcdatamodeld and XXX.swift is not created only XXX+CoreDataProperties.swift? I was wondering if this is know issue in XCode 7 beta. In my case I had to add an attribute to an entity. After addding the attribute I
- deleted XXXX.swift
- deleted XXXX+CoreDataProperties.swift
- selected Editor > Create NSManagedObject Subclass
- realised only XXXX+CoreDataProperties.swift was created (did not see XXXX.swift)
- created a new class file XXXX.swift, but on save a message displayed overwrite existing one (so apparently XXXX.swift is still there) so i did.
- after creating the XXXX file I just put this code
import Foundation
import CoreData

class XXXX: NSManagedObject {

}

*

*but to my suprise the newly created XXXX.swift isn't displayed + the top UI bar of XCode disappeared

*after restarting XCode i the top UI bar appeared + newly created XXXX.swift displays

A: When using Swift, the CoreData model will only auto-create the +CoreDataProperties.swift file when updating a model entity.  This is by design, as we should now put our custom class extensions in the MyEntity.swift file so that they don't get overwritten.  When you edit your model, don't delete your MyEntity.swift file.  That one is not managed automatically by Xcode, only the MyEntity+CoreDataProperties.swift file is, and it's the only one that will be re-generated for you.


text:
Q: Alternatives to DirectShow for video capture on Windows I am looking at updating a program that currently uses DirectShow for video capture.  While DirectShow seems to work well, I was wondering if there were any more powerful or up to date SDKs or APIs that I should look into.  Some features that would be helpful would be ones that will:

*

*Provide a consistent framerate (33ms between frames for NTSC) during capture.

*Work with DirectShow compatible capture devices.

*Not require an extra license to be installed on the customer's PC.

*Allow for simultaneous preview and hardware encoding of video.

*Be able to be integrated into a C++/MFC application.

I've looked into LeadTools Multimedia Capture SDK and VisioForge Capture SDK and Microsoft Media Foundation, but just wanted to know what others have used successfully before I invest time or money into one of these alternatives. I don't care if this is a commercial or open source product.
EDIT: While I appreciate the attempts to solve my particular problem, this question was supposed to be about alternatives to DirectShow.  So, I removed all of the references to my specific problem.  Solving that will need to wait for another question.

A: Quite all capture boards come with their own timers.
You may try to query you source filter for IReferenceClock and use its own timer that is usually more accurate than a PC's one.
If you use ISampleGrabber then the callback function is called microseconds from the moment Receive is called on the Sample Grabber's input pin, they're just few lines away in the source code.
It seems that your frame source timing is inaccurate (not the timing set in IMediaSample, but actial timing the frames are delivered in).
What is the source filter that produces the frames?

A: The DirectShow API is very good, I've never found better on the windows platform.  DirectShow has been superseded by Media Foundation, which is Vista (and later) operating systems only.
We'll have to wait for XP to die before people will start mass development using Media Foundation...
May I ask why you're seeking an alternative to DirectShow - it's  a very well supported API - well documented on MSDN and there's a very active and friendly forum on MSDN for DirectShow Development.

A: The problem might just be the method you are using for timing. Are you using the high performance timer API?

A: VideoLan may be an option for you.

A: LeadTools and VisioForge SDKs are just wrappers for DirectShow + some custom filters from them! There is no real alternativ to DirectShow for capturing on a Windows PC. Maybe on Win8 with MediaFoundation? Some Hardware Vendors have there own capture programms, but most of them just use DirectShow.
I think your problem is not DirectShow. How long is your callback working? Because if your doing some analysis on the image, then you need to do this fast. Not the time in your callback is importent, but the presentation time in the mediasample you get! This should be +33ms from the previews sample.

A: FFmpeg can receive directshow input and manipulate it, and it's free. AviSynth maybe too...


text:
Q: How do I install the Frutiger font? Couldn't find it in Synaptic nor in help.ubuntu

A: Frutiger isn't a free font and so (as far as I know) isn't included in any Ubuntu packages, nor can you use ttf-mscorefonts-installer (which johanvdw alluded to) to install it.
If you can get your hands on a copy of the font, installing it is really easy. If only you want to use it, just copy the files (they'll usually be .ttf or .otf files) into the .fonts folder in your home directory. If the folder doesn't exist yet, just go ahead and create it. Or just follow these directions:

*

*How do I install fonts?
If you have multiple accounts on your computer and want everybody to be able to use the font, you'll need to copy the files to /usr/share/fonts/truetype/. You'll probably need root privileges to do this (try running sudo nautilus).
Alternatively, you might want to try Bitstream Vera; it's a high-quality free font, very similar to Frutiger. Just install the ttf-bitstream-vera package.


text:
Q: PostgreSQL-Patroni-Cluster: Installing oracle_fdw, dependency problem For Oracle to PostgreSQL migrations we're currently looking into ora2pg. However, the performance using either writes to file or direct read from Oracle and write to PostgreSQL have both been very underwhelming. There's not really good information about that, while some parts I found suggested that it could be related to the Oracle-Perl-Driver.
In a new version of ora2pg it introduced a new way of converting the data using the Foreign Data Wrapper oracle_fdw. It is written in C and performance benchmarks seem to suggest a much higher performance. For that, we would like to use oracle_fdw. The target for our conversion is a Patroni Cluster setup with 2 nodes and a 3rd witness node using etcd.
However, adding oracle_fdw to the Patroni cluster has been difficult and so far unsuccessful. After compiling oracle_fdw, trying to load it gives the following message:

ERROR:  could not load library "/usr/lib/postgresql14/lib64/oracle_fdw.so": libclntsh.so.19.1: cannot open shared object file: No such file or directory

That library exists on the system, but in the directory of the Oracle Instantclient (/dbdata/oracle/instantclient_19_12). For the library to be found, we think we would need the following standard environment variables added to the postgres process that Patroni starts:
export LD_LIBRARY_PATH=/dbdata/oracle/instantclient_19_12
export ORACLE_HOME=/dbdata/oracle/instantclient_19_12
export PATH=/dbdata/oracle/instantclient_19_12:$PATH

However, we have been wholly unsuccessful to inject these variables into the postgress process started by Patroni. The process is started using the system user postgres, as seen here:
dbserver01 root 6 (/dbdata/oracle/instantclient_19_12): ps -ef|grep postgres
root      9236  9120  0 07:56 pts/0    00:00:00 su - postgres
postgres  9238  9236  0 07:56 pts/0    00:00:00 -bash
postgres  9289  9238  0 07:56 pts/0    00:00:00 psql
postgres  9290 27443  0 07:56 ?        00:00:00 postgres: pgcluster2: postgres postgres [local] idle
root      9307  9180  0 07:58 pts/1    00:00:00 grep --color=auto postgres
postgres 27423     1  0 Mar23 ?        00:01:41 /opt/patroni/bin/python3 /usr/bin/patroni /etc/patroni/postgres.yml
postgres 27443     1  0 Mar23 ?        00:00:04 postgres -D /dbdata/pgcluster --config-file=/dbdata/pgcluster/postgresql.conf --listen_addresses=0.0.0.0 --port=5432 --cluster_name=pgcluster2 --wal_level=replica --hot_standby=on --max_connections=100 --max_wal_senders=10 --max_prepared_transactions=0 --max_locks_per_transaction=64 --track_commit_timestamp=off --max_replication_slots=10 --max_worker_processes=8 --wal_log_hints=on

The following methods have been tried:

*

*Adding the export statements to the .bashrc of the postgres user

*Adding the export statements to the .bash_profile of the postgres user

*Adding the export statements to the global /etc/profile of the server

*Adding the /dbdata/oracle/instantclient_19_12/ path to the /etc/ld.so.conf
Each time Patroni was restarted, and so was Postgres (checked by the ever changing PID), yet the environment always looks like this:
dbserver01 root 7 (/dbdata/oracle/instantclient_19_12): cat /proc/27443/environ | xargs -0 -n 1
LANG=en_US.UTF-8
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
HOME=/var/lib/pgsql
LOGNAME=postgres
USER=postgres
SHELL=/bin/bash
INVOCATION_ID=3806a21dfa52455baad431cc2bbfa533
JOURNAL_STREAM=9:5426402
dbserver01 root 8 (/dbdata/oracle/instantclient_19_12):

The Patroni documentation has loads of information about Patroni specific environment variables, yet I have so far not found any documentation that helps pass variables to the Postgres process.
Copying the dependencies around might work around the problem, however, adding the variables would be the preferred way of fixing the problem. Is there a right or supported way to add environment variables to the postgres process started by Patroni?
Edit 1: The installation process was done using a checkout of the repository with the root user, after setting the above mentioned exports, then compiled using make and make install. Here's the output of both commands currently:
dbserver01 root 25 (/tmp/oracle_fdw): make
make: Nothing to be done for 'all'.
goeccdb11l root 26 (/tmp/oracle_fdw): make install
/usr/bin/mkdir -p '/usr/lib/postgresql14/lib64'
/usr/bin/mkdir -p '/usr/share/postgresql14/extension'
/usr/bin/mkdir -p '/usr/share/postgresql14/extension'
/usr/bin/mkdir -p '/usr/share/doc/packages/postgresql14/extension'
/usr/bin/install -c -m 755  oracle_fdw.so '/usr/lib/postgresql14/lib64/oracle_fdw.so'
/usr/bin/install -c -m 644 .//oracle_fdw.control '/usr/share/postgresql14/extension/'
/usr/bin/install -c -m 644 .//oracle_fdw--1.2.sql .//oracle_fdw--1.0--1.1.sql .//oracle_fdw--1.1--1.2.sql  '/usr/share/postgresql14/extension/'
/usr/bin/install -c -m 644 .//README.oracle_fdw '/usr/share/doc/packages/postgresql14/extension/'
dbserver01 root 27 (/tmp/oracle_fdw): ls -la /usr/lib/postgresql14/lib64

Edit 2: I've tried the installation again, using make clean and the process of make and make install again:
dbserver01 root 11 (/tmp/oracle_fdw): make clean
rm -f oracle_fdw.so   liboracle_fdw.a  liboracle_fdw.pc
rm -f oracle_fdw.o oracle_utils.o oracle_gis.o oracle_fdw.bc oracle_utils.bc oracle_gis.bc
rm -rf results/ regression.diffs regression.out tmp_check/ tmp_check_iso/ log/ output_iso/
dbserver01 root 12 (/tmp/oracle_fdw): export LD_LIBRARY_PATH=/dbdata/oracle/instantclient_19_12
dbserver01 root 13 (/tmp/oracle_fdw): export ORACLE_HOME=/dbdata/oracle/instantclient_19_12
dbserver01 root 14 (/tmp/oracle_fdw): export PATH=/dbdata/oracle/instantclient_19_12:$PATH
dbserver01 root 15 (/tmp/oracle_fdw): make
gcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Werror=vla -Wendif-labels -Wmissing-format-attribute -Wimplicit-fallthrough=3 -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -Wno-format-truncation -fmessage-length=0 -grecord-gcc-switches -O2 -Wall -D_FORTIFY_SOURCE=2 -fstack-protector-strong -funwind-tables -fasynchronous-unwind-tables -fstack-clash-protection -g -fPIC -I"/dbdata/oracle/instantclient_19_12/sdk/include" -I"/dbdata/oracle/instantclient_19_12/oci/include" -I"/dbdata/oracle/instantclient_19_12/rdbms/public" -I"/dbdata/oracle/instantclient_19_12/" -I/usr/include/oracle/21/client64 -I/usr/include/oracle/19.14/client64 -I/usr/include/oracle/19.12/client64 -I/usr/include/oracle/19.12/client -I/usr/include/oracle/19.11/client64 -I/usr/include/oracle/19.11/client -I/usr/include/oracle/19.10/client64 -I/usr/include/oracle/19.10/client -I/usr/include/oracle/19.9/client -I/usr/include/oracle/19.9/client64 -I/usr/include/oracle/19.8/client -I/usr/include/oracle/19.8/client64 -I/usr/include/oracle/19.6/client -I/usr/include/oracle/19.6/client64 -I/usr/include/oracle/19.3/client -I/usr/include/oracle/19.3/client64 -I/usr/include/oracle/18.5/client -I/usr/include/oracle/18.5/client64 -I/usr/include/oracle/18.3/client -I/usr/include/oracle/18.3/client64 -I/usr/include/oracle/12.2/client -I/usr/include/oracle/12.2/client64 -I/usr/include/oracle/12.1/client -I/usr/include/oracle/12.1/client64 -I/usr/include/oracle/11.2/client -I/usr/include/oracle/11.2/client64 -I. -I./ -I/usr/include/pgsql/server -I/usr/include/pgsql/internal  -D_GNU_SOURCE -I/usr/include/libxml2   -c -o oracle_fdw.o oracle_fdw.c
gcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Werror=vla -Wendif-labels -Wmissing-format-attribute -Wimplicit-fallthrough=3 -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -Wno-format-truncation -fmessage-length=0 -grecord-gcc-switches -O2 -Wall -D_FORTIFY_SOURCE=2 -fstack-protector-strong -funwind-tables -fasynchronous-unwind-tables -fstack-clash-protection -g -fPIC -I"/dbdata/oracle/instantclient_19_12/sdk/include" -I"/dbdata/oracle/instantclient_19_12/oci/include" -I"/dbdata/oracle/instantclient_19_12/rdbms/public" -I"/dbdata/oracle/instantclient_19_12/" -I/usr/include/oracle/21/client64 -I/usr/include/oracle/19.14/client64 -I/usr/include/oracle/19.12/client64 -I/usr/include/oracle/19.12/client -I/usr/include/oracle/19.11/client64 -I/usr/include/oracle/19.11/client -I/usr/include/oracle/19.10/client64 -I/usr/include/oracle/19.10/client -I/usr/include/oracle/19.9/client -I/usr/include/oracle/19.9/client64 -I/usr/include/oracle/19.8/client -I/usr/include/oracle/19.8/client64 -I/usr/include/oracle/19.6/client -I/usr/include/oracle/19.6/client64 -I/usr/include/oracle/19.3/client -I/usr/include/oracle/19.3/client64 -I/usr/include/oracle/18.5/client -I/usr/include/oracle/18.5/client64 -I/usr/include/oracle/18.3/client -I/usr/include/oracle/18.3/client64 -I/usr/include/oracle/12.2/client -I/usr/include/oracle/12.2/client64 -I/usr/include/oracle/12.1/client -I/usr/include/oracle/12.1/client64 -I/usr/include/oracle/11.2/client -I/usr/include/oracle/11.2/client64 -I. -I./ -I/usr/include/pgsql/server -I/usr/include/pgsql/internal  -D_GNU_SOURCE -I/usr/include/libxml2   -c -o oracle_utils.o oracle_utils.c
gcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Werror=vla -Wendif-labels -Wmissing-format-attribute -Wimplicit-fallthrough=3 -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -Wno-format-truncation -fmessage-length=0 -grecord-gcc-switches -O2 -Wall -D_FORTIFY_SOURCE=2 -fstack-protector-strong -funwind-tables -fasynchronous-unwind-tables -fstack-clash-protection -g -fPIC -I"/dbdata/oracle/instantclient_19_12/sdk/include" -I"/dbdata/oracle/instantclient_19_12/oci/include" -I"/dbdata/oracle/instantclient_19_12/rdbms/public" -I"/dbdata/oracle/instantclient_19_12/" -I/usr/include/oracle/21/client64 -I/usr/include/oracle/19.14/client64 -I/usr/include/oracle/19.12/client64 -I/usr/include/oracle/19.12/client -I/usr/include/oracle/19.11/client64 -I/usr/include/oracle/19.11/client -I/usr/include/oracle/19.10/client64 -I/usr/include/oracle/19.10/client -I/usr/include/oracle/19.9/client -I/usr/include/oracle/19.9/client64 -I/usr/include/oracle/19.8/client -I/usr/include/oracle/19.8/client64 -I/usr/include/oracle/19.6/client -I/usr/include/oracle/19.6/client64 -I/usr/include/oracle/19.3/client -I/usr/include/oracle/19.3/client64 -I/usr/include/oracle/18.5/client -I/usr/include/oracle/18.5/client64 -I/usr/include/oracle/18.3/client -I/usr/include/oracle/18.3/client64 -I/usr/include/oracle/12.2/client -I/usr/include/oracle/12.2/client64 -I/usr/include/oracle/12.1/client -I/usr/include/oracle/12.1/client64 -I/usr/include/oracle/11.2/client -I/usr/include/oracle/11.2/client64 -I. -I./ -I/usr/include/pgsql/server -I/usr/include/pgsql/internal  -D_GNU_SOURCE -I/usr/include/libxml2   -c -o oracle_gis.o oracle_gis.c
gcc -Wall -Wmissing-prototypes -Wpointer-arith -Wdeclaration-after-statement -Werror=vla -Wendif-labels -Wmissing-format-attribute -Wimplicit-fallthrough=3 -Wformat-security -fno-strict-aliasing -fwrapv -fexcess-precision=standard -Wno-format-truncation -fmessage-length=0 -grecord-gcc-switches -O2 -Wall -D_FORTIFY_SOURCE=2 -fstack-protector-strong -funwind-tables -fasynchronous-unwind-tables -fstack-clash-protection -g -fPIC -shared -o oracle_fdw.so oracle_fdw.o oracle_utils.o oracle_gis.o -L/usr/lib/postgresql14/lib64   -L/usr/lib64  -Wl,--as-needed  -L"/dbdata/oracle/instantclient_19_12/" -L"/dbdata/oracle/instantclient_19_12/bin" -L"/dbdata/oracle/instantclient_19_12/lib" -L"/dbdata/oracle/instantclient_19_12/lib/amd64" -lclntsh -L/usr/lib/oracle/21/client64/lib -L/usr/lib/oracle/19.14/client64/lib -L/usr/lib/oracle/19.12/client64/lib -L/usr/lib/oracle/19.12/client/lib -L/usr/lib/oracle/19.11/client64/lib -L/usr/lib/oracle/19.11/client/lib -L/usr/lib/oracle/19.10/client64/lib -L/usr/lib/oracle/19.10/client/lib -L/usr/lib/oracle/19.9/client/lib -L/usr/lib/oracle/19.9/client64/lib -L/usr/lib/oracle/19.8/client/lib -L/usr/lib/oracle/19.8/client64/lib -L/usr/lib/oracle/19.6/client/lib -L/usr/lib/oracle/19.6/client64/lib -L/usr/lib/oracle/19.3/client/lib -L/usr/lib/oracle/19.3/client64/lib -L/usr/lib/oracle/18.5/client/lib -L/usr/lib/oracle/18.5/client64/lib -L/usr/lib/oracle/18.3/client/lib -L/usr/lib/oracle/18.3/client64/lib -L/usr/lib/oracle/12.2/client/lib -L/usr/lib/oracle/12.2/client64/lib -L/usr/lib/oracle/12.1/client/lib -L/usr/lib/oracle/12.1/client64/lib -L/usr/lib/oracle/11.2/client/lib -L/usr/lib/oracle/11.2/client64/lib
dbserver01 root 16 (/tmp/oracle_fdw): make install
/usr/bin/mkdir -p '/usr/lib/postgresql14/lib64'
/usr/bin/mkdir -p '/usr/share/postgresql14/extension'
/usr/bin/mkdir -p '/usr/share/postgresql14/extension'
/usr/bin/mkdir -p '/usr/share/doc/packages/postgresql14/extension'
/usr/bin/install -c -m 755  oracle_fdw.so '/usr/lib/postgresql14/lib64/oracle_fdw.so'
/usr/bin/install -c -m 644 .//oracle_fdw.control '/usr/share/postgresql14/extension/'
/usr/bin/install -c -m 644 .//oracle_fdw--1.2.sql .//oracle_fdw--1.0--1.1.sql .//oracle_fdw--1.1--1.2.sql  '/usr/share/postgresql14/extension/'
/usr/bin/install -c -m 644 .//README.oracle_fdw '/usr/share/doc/packages/postgresql14/extension/'
dbserver01 root 17 (/tmp/oracle_fdw):

Edit 3: Added a 4th method to get the path into the postgres user process.

A: Read the oracle_fdw documentation:

Since the Oracle client shared library is probably not in the standard library path, you have to make sure that the PostgreSQL server will be able to find it. How this is done varies from operating system to operating system; on Linux you can set LD_LIBRARY_PATH or use /etc/ld.so.conf.

The PostgreSQL server may have to get restarted to make this effective.

A: After starting the PostgreSQL instance manually without the Patroni supervision, then adding the environment variables using su - postgres --whitelist-environment=ORACLE_HOME,LD_LIBRARY_PATH,PATH, I realized that the loading of shared dynamic libraries is done using the paths in /etc/ld.so.conf (also checked using ldd).
Although the path /dbdata/oracle/instantclient_19_12 was added to the /etc/ld.so.conf file and checked using the root user that it is picked up, it seems that the file is either not readable, not used or not useable by the postgres user process.
Currently I am working around the problem by copying the dependencies of the oracle_fdw extension to the /lib64 directory on the system. That allows PostgreSQL to load the extension successfully. I can then do the conversion, then reinit the cluster and rebuild the 2nd cluster node from the first node.


text:
Q: Modify/Set root device in initramfs script I want to modify the root device node as a part of a script in initramfs. I don't want to execute switch_root myself (unless I have to). I would like to add in a script which can change the root device if certain conditions are met.
I tried various options like reading/setting $root variable, but that didn't work.
The background problem is that I am trying to encrypt the root device only if certain conditions are met. In such a case, I am copying the data from old root device into new encrypted device and want to switch the root to new encrypted /dev/mapper/secret device instead of preconfigured /dev/sda2.

A: Based on my research, it seems that the root parameter given to kernel can't be changed via initramfs script.
See https://unix.stackexchange.com/questions/65589/kernel-grub-how-override-root-parameter-inside-initrd-script
@enzo2 provided the answer that the only way to achieve this by rewriting the grub config file (/boot/grub/menu.lst in my case) and issue a reboot so that kernel can be loaded with a different root device.


text:
Q: Entity Framework Seed Data on complex object with Nullable I am trying to seed a table in my database based on a complex type that has a nullable field.  On insert, this works fine, but when it tries to do a comparison on update, it throws the error below.
Here is my add or update code

Here is my object with Nullable AccountId

Here is the error saying it can't compute..

Here is the view of the product.accountid field in db


text:
Q: Android - Modify last AlertDialog Title I have two AlertDialogs and from the first AlertDialog I came to the second. My objective is to modify the Title from the first AlertDialog Using the second.
When I'm trying to set the title of the alertDialog2 using the method setTitle(), it tells me that alertDialog2 must be final, but if I set object alertDialog2 to final, I can not modify it.
AlertDialog alertDialog2 = new AlertDialog.Builder(MainActivity.this).create();
place="";
alertDialog2.setTitle(place); //this is the original place
alertDialog2.setMessage(text);

alertDialog2.setButton(Dialog.BUTTON_NEUTRAL, "Set Place", new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {

        final CharSequence[] items = {" Place1 "," Place2 "," Place3 "," Place4 "};

        // Creating and Building the Dialog
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Select Place");
        builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item) {

            switch(item)
            {
                case 0:
                        // Your code when first option seletced
                        place=String.valueOf(items[0]);
                         break;
                case 1:
                        // Your code when 2nd  option seletced
                    place=String.valueOf(items[1]);
                        break;
                case 2:
                       // Your code when 3rd option seletced
                    place=String.valueOf(items[2]);
                        break;
                case 3:
                         // Your code when 4th  option seletced
                    place=String.valueOf(items[3]);
                        break;

            }

            }
        });
        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {
                // TODO Auto-generated method stub
                alertDialog2.setTitle(place); // Here I can not set the title
                alertDialog2.show();

            }
        });
      builder.create();
      builder.show();
    }
});
alertDialog2.setButton(Dialog.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {

    @Override
    public void onClick(DialogInterface dialog, int which) {
        // TODO Auto-generated method stub
        Toast.makeText(MainActivity.this, "Canceled", Toast.LENGTH_SHORT).show();

    }
});

alertDialog2.show();

A: Try once by making AlertDialog alertDialog2 as class variable instead of defining and intializing in any function.
AlertDialog alertDialog2;

void tempFunction()
{
       alertDialog2=new AlertDialog.Builder(MainActivity.this).create();
       .
       .
       .
       .

}

Hope it helps...
To understand this kind of thing give 2 mins to understand the memory map and stacking whenever a function executes its local resources are added to stack and executed so if u are assigning a dialog in local function it will be removed as soon as it leaves from there... but if u assign it as global and suppose it has address of 2100 then u can change the content everytime its like a pot which u can fill with watever type of water like salty , sweet etc... memory maps and imagination do help alot and will help to also overcome Nullpointer exceptions at many cases...
thx

A: You can just declare it to be final as long as you aren't reassigning to it later in your code.
http://en.wikipedia.org/wiki/Final_(Java)
Also, your AlertDialog doesn't have a title when created. You need to give it a title when you create it, you can't just add the title once it's created.


text:
Q: Using the error messages that gets generated while executing While executing code it is normal to get the messages like shdw,argx etc. I wanted to know if there is anyway i can store all these messages into a array or a variable so that i can pinpoint where the error occurred.
The scenario is that i have written few functions in webmathematica and deployed the files on the server. So in future if there are any issues with those functions i want to use the errors(messages) and convert these errors into diff user defined http requests(in turn used to send a mail containing these messages).

A: In webMathematica there is already MSPGetMessage[]
So if you do something like
mess = MSPGetMessages[];

you have a list of messages. E.g., if you had an error for
1/0

"1\nPower::infy: Infinite expression - encountered.\n 0"

Notice that $MessageList gives just

{HoldForm[Power::infy]}


text:
Q: How to assign constant address to pointer at c++? I want to check how pointer address will be changed when I'm increasing/decreasing pointer value.
My code is:
void pointers_plus_minus()
{
    char *c = (char *) 0x7fff80ccd35c;
    int *i = (int *) 0x7fff80ccd35c;

    c++;
    i++;

    cout << "char pointer" << c << endl;
    cout << "int pointer" << i << endl;
}

But this code gives me Segmentation fault (core dumped).
I understand that something wrong with address, but it's not clear what. How to fix it? I'm using 64bit Ubuntu.

A: You can't operate on pointers like they are integers (well, not outside well-defined contexts).
You're only allowed to do c++ and i++ if the pointers point inside an array which you own.
Oops, I think this is actually well-defined because 1 element is treated as an array of 1, and you're allowed to go past the end of an array by one element. Reading from that pointer is still undefined though.
Regardless, although undefined, the crash is probably because cout << c attempts to print out a string, not a pointer. Cast it to void*:
cout << "char pointer" << static_cast<void*>(c) << endl;

Although this will satisfy your curiosity, which is good, it's still undefined and shouldn't do it.

A: You asked how to assign a constant address to a pointer, but doing so (a) is horrendously non-portable, and (b) doesn't necessarily serve your purpose, which is to see the effect of incrementing a pointer.
Here's a program that may satisfy your curiosity without possibly blowing up due to undefined behavior:
#include <iostream>
int main() {
    const int len = 10;
    char char_array[len];
    int int_array[len];

    char *cp = char_array;
    for (int i = 0; i <= len; i ++) {
        std::cout << "cp = " << static_cast<void*>(cp) << "\n";
        cp ++;
    }

    std::cout << '\n';

    int *ip = int_array;
    for (int i = 0; i <= len; i ++) {
        std::cout << "ip = " << static_cast<void*>(ip) << "\n";
        ip ++;
    }
}

The output on my (64-bit) system is:
cp = 0x7fffaa5ddc30
cp = 0x7fffaa5ddc31
cp = 0x7fffaa5ddc32
cp = 0x7fffaa5ddc33
cp = 0x7fffaa5ddc34
cp = 0x7fffaa5ddc35
cp = 0x7fffaa5ddc36
cp = 0x7fffaa5ddc37
cp = 0x7fffaa5ddc38
cp = 0x7fffaa5ddc39
cp = 0x7fffaa5ddc3a

ip = 0x7fffaa5ddc00
ip = 0x7fffaa5ddc04
ip = 0x7fffaa5ddc08
ip = 0x7fffaa5ddc0c
ip = 0x7fffaa5ddc10
ip = 0x7fffaa5ddc14
ip = 0x7fffaa5ddc18
ip = 0x7fffaa5ddc1c
ip = 0x7fffaa5ddc20
ip = 0x7fffaa5ddc24
ip = 0x7fffaa5ddc28

Some notes on this:
The pointer increments are valid because each pointer points to an element of an array of the proper type, or just past the end of it, at all times. (You're allowed to construct a pointer just past the end of an array; you're not allowed to dereference such a pointer.)
The output produced when print a pointer of type void* is implementation-defined. On my system, it happens to be a hexadecimal representation of the pointer value, interpreted as if it were an integer -- which is probably the most common way it's done.
You can see that the char* pointer appears to be incremented by 1 each time, and the int* pointer by 4. On my system (and probably yours), pointers are stored as byte addresses. Pointer arithmetic is defined in units of the pointed-to type, not in terms of bytes.  Incrementing an int* pointer causes it to point to a memory location sizeof (int) bytes after the previous location -- in this case, 4 bytes. All pointer arithmetic is defined this way; ptr2 - ptr1 gives you the number of elements (of whatever type ptr1 and ptr2 point to) between the two addresses.
The specific values printed tell you something about how memory addresses are managed on your system. The mapping between pointers and integers will generally reflect the system's memory model. That model is largely implementation-specific.

A: Seg faults, my favorite error messages next to stack overflows, are when you've tried to write to an illegal memory space. That said, how can you guarantee that when your program has been loaded into memory that your stack/heap space falls within the area you are trying to reserve, and more so why would you even want to do this? This is something that can probably be done in Assembly since you have much lower access to the hardware, but I seriously doubt it can be done (or should be done if you can) in C.


text:
Q: android SimpleSectionAdapter from adapter displaying empty list i really need help debugging this android app i am building. I have a custom adapter. when i dont use it with simpleSectionAdapter it displays list items correctly, but when i use SimpleSectionAdapter from adapter kit, it displays blank list. I want to have sections in my list according to names. Thanks in advance.
Heres's my adapter
public class CustomContriAdapter extends BaseAdapter implements Filterable{

List<Contributions> contributions;
LayoutInflater inflater;
Context context;
public List<Contributions> orig;

public CustomContriAdapter(Context context, List<Contributions> contributions) {
    this.contributions = contributions;
    this.context = context;
    inflater = LayoutInflater.from(this.context);
}

@Override
public int getCount() {
    return contributions.size();
}

@Override
public Object getItem(int position) {
    return contributions.get(position);
}

@Override
public long getItemId(int position) {
    return 0;
}

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

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            final FilterResults oReturn = new FilterResults();
            final List<Contributions> results = new ArrayList<Contributions>();
            if (orig == null)
                orig = contributions;
            if (constraint != null) {
                if (orig != null && orig.size() > 0) {
                    for (final Contributions g : orig) {
                        if (g.getContributor_name().toLowerCase()
                                .contains(constraint.toString()))
                            results.add(g);
                    }
                }
                oReturn.values = results;
            }
            return oReturn;
        }

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

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    MyViewHolder mViewHolder;

    if (convertView == null) {
        convertView = inflater.inflate(R.layout.contri_list_item_layout, parent, false);
        mViewHolder = new MyViewHolder(convertView);
        convertView.setTag(mViewHolder);
    } else {
        mViewHolder = (MyViewHolder) convertView.getTag();
    }

    Contributions currentListData = (Contributions) getItem(position);

    mViewHolder.tvTitleName.setText(currentListData.getContributor_name());

    //date created at
    Date createdAt = currentListData.getCreated();
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
    String createdDate = df.format(createdAt);

    mViewHolder.tvDescDate.setText(createdDate);

    return convertView;
}

private class MyViewHolder {
    TextView tvTitleName, tvDescDate;

    public MyViewHolder(View item) {
        tvTitleName = (TextView) item.findViewById(R.id.name_view);
        tvDescDate = (TextView) item.findViewById(R.id.contri_created_date);
    }
}

}
here's how am calling it in the onCreate()
 Collections.sort(allContributions, new Comparator<Contributions>() {
        @Override
        public int compare(Contributions lhs, Contributions rhs) {
            return lhs.getContributor_name().compareTo(rhs.getContributor_name());
        }
    });
    InstantAdapter<Contributions> contribu = new InstantAdapter<Contributions>(
            this,R.layout.contri_list_item_layout, Contributions.class, allContributions);

    //wrap adapter to simple section adapter
    SimpleSectionAdapter<Contributions> sectionAdapter = new SimpleSectionAdapter<Contributions>(
            this, contribu, R.layout.section_header, R.id.section_text , new ContributionsSectionizer());

    listView.setAdapter(sectionAdapter);

here's the sectionizer,
public class ContributionsSectionizer implements Sectionizer<Contributions> {
@Override
public String getSectionTitleForItem(Contributions contributions) {
    return contributions.getContributor_name();
}

}
and the items
protected List<Contributions> allContributions = new ArrayList<>();


text:
Q: Android Resolve Uri failed on bad bitmap Uri error I'm creating a camera application and in the main activity it's retrieve the camera preview bitmap and save to the internal storage.after intent to another class I want to display the image by getting the path of the bitmap.however after taking the picture for the first time, it's displays the picture well but sometimes not display the image and gives the following error
"Resolve Uri failed on bad bitmap Uri : data/data/com.camera.app/files/287372639100.jpg"

mainclass
                //IMG name
                mName = System.currentTimeMillis();
                dTime  = mName;

                try {
                    //get bitmap & save into internal storage
                    BitmapFactory.Options options = new BitmapFactory.Options();
                    options.inSampleSize = IN_SAMPLE_SIZE;
                    bitmap = BitmapFactory.decodeByteArray(data, 0, data.length, options);

                    try {
                        Uri uri = Uri.parse(dTime+".jpg");
                        File f = new File(uri.toString());
                        ExifInterface exif = new ExifInterface(f.getPath());
                        int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);

                        int angle = 0;

                        if (orientation == ExifInterface.ORIENTATION_ROTATE_90) {
                            angle = 90;
                        }
                        else if (orientation == ExifInterface.ORIENTATION_ROTATE_180) {
                            angle = 180;
                        }
                        else if (orientation == ExifInterface.ORIENTATION_ROTATE_270) {
                            angle = 270;
                        }
                        else{
                            angle = 0;
                        }

                        Matrix mat = new Matrix();
                        mat.postRotate(angle);
                        //get rotated bitmap
                        Bitmap correctBmp = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), mat, true);

                        //save bitmap to internal storage
                        FileOutputStream fos = openFileOutput(dTime+".jpg", Context.MODE_PRIVATE);
                        correctBmp.compress(CompressFormat.JPEG, 90, fos);
                        correctBmp = Bitmap.createScaledBitmap(bitmap, 380, 600, false);
                        fos.close();

                        bitmap.recycle();
                        correctBmp.recycle();
                    }
                    catch (IOException e) {
                        Log.w("TAG", "-- Error in setting image");
                    }
                    catch(OutOfMemoryError oom) {
                        Log.w("TAG", "-- OOM Error in setting image");
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

                // intent send data
                Intent intent = new Intent(MainActivity.this,PhotoClass.class);
                intent.putExtra("IMG_NAME", dTime);
                startActivity(intent);
                finish();

                Log.d(TAG, "onPictureTaken - bitmap sending..");

Photoclass
        //get intent
        Intent intent = getIntent();
        imgName = intent.getLongExtra("IMG_NAME", 0);
        uri = Uri.parse(getFilesDir().getPath() + "/"+imgName+".jpg");

        if(imgName != 0){
            mImagePreView.setImageURI(uri);
        }

need a help to solve this problem.


text:
Q: Scraping via PROC HTTP I wanted to use proc http to scrape quotes off Yahoo finance.  It did not produce the HTML in the out file, but when I used debug level = 3 to figure what happened, the full HTML was given in the log.  What happened?  Clearly, I want the HTML in the out file, but the alternative of saving the log as a text will be sufficient as well.  How can I do that?
filename Testing "&Folder&OutFile";
%let YahooFin = "https://finance.yahoo.com/quote/SNAP/";
proc http
    url = &YahooFin.
    out = Testing
    method = "get";
    debug level = 3;
run;

EDIT
Here are my macro variables.  Just to clarify, I did receive a HTML from my original script, but it was just the top portion, not the whole thing.  See the enclosed image.
%let Folder = /06specialty/Practice Scripts/;
%let OutFile = TestSNAP.txt;

Sample Image

A: What does your OutFile macro-variable resolve to? What is the extension of your output file?
I tried with a .txt file:
filename Testing "/path/to/want.txt";
%let YahooFin = "https://finance.yahoo.com/quote/SNAP/";
proc http
    url = &YahooFin.
    out = Testing
    method = "get";
run;

And it worked:

A: The HTML that link generates has some really long lines (541,567 bytes).
Make sure to tell SAS to use a long enough LRECL if you are going to try to read it with a DATA step.
1149  proc http
1150      url = &YahooFin.
1151      out = Testing
1152      method = "get";
1153  run;

NOTE: PROCEDURE HTTP used (Total process time):
      real time           0.98 seconds
      cpu time            0.04 seconds

NOTE: 200 OK

1154
1155  data _null_;
1156    infile testing lrecl=1000000 length=ll ;
1157    input;
1158  run;

NOTE: The infile TESTING is:

      Filename=XXXX\#LN00123,
      RECFM=V,LRECL=1000000,File Size (bytes)=777076,
      Last Modified=21Mar2021:15:23:01,
      Create Time=21Mar2021:15:20:45

NOTE: 116 records were read from the infile TESTING.
      The minimum record length was 0.
      The maximum record length was 541567.
NOTE: DATA statement used (Total process time):

A: I would suggest to use Yahoo Graph API to get quotes or historical price for a stock
/*Lets fetch Historic data from Microsoft*/

%let stock=MSFT;

filename test "%sysfunc(getoption(WORK))\&stock..json";

proc http
    url="https://query1.finance.yahoo.com/v7/finance/chart/&stock?range=1mo%str(&)interval=1d%str(&)indicators=quote%str(&)includeTimestamps=true%str(&)includeTimestamps=true%str(&)crumb=&getCrumb."
 out=test;
 *debug level=3;
quit;

LIBNAME stock JSON "%sysfunc(getoption(WORK))\&stock..json";

You can get more details from  https://myweirdcodes.com/stocks-fetching-historical-stock-data-with-sas


text:
Q: Cannot figure out whats wrong with this code Could someone please tell me whats wrong with this code because I cannot find anything?

<title>Meine Seite</title>

Willkommen

<?php
define("EZSQL_DB_USER", 'xxxxx_xxxx');
define("EZSQL_DB_PASSWORD", 'xxxxxxx');
define("EZSQL_DB_NAME", 'xxxx_xxxx');
define("EZSQL_DB_HOST", 'localhost');
if (!function_exists('gettext')) {
function _($s) {return $s;}
}
?>
<?php
$mysqlConnection = mysql_connect(EZSQL_DB_HOST, EZSQL_DB_USER, EZSQL_DB_PASSWORD);
if (!$mysqlConnection)
{
echo "
Hallo du!
";
}

?>

The result:
Willkommen

Hallo du!"; } ?>

Your help is very much appreciated!
thanks

A:
Hallo du!"; } ?>

That shows your php is not running. You have to upload the php file to a webserver Then see from browser. Like http://localhost/file.php. Not as C:\documents\file.php


text:
Q: Generating random starting points in n-dimension for fmincon algorithm - uniform distribution of space I am using fmincon in Matlab to minimize a smooth yet highly non-linear objective function. My problem is in n-dimension, with n>250 in some instances.
I have found that using different starting points improves dramatically the solution, as can be expected from an objective function with multiple local minima.
I have used haltonset to generate quasi random starting point in the n dimensional hypercube, which I then rescale into the n-dimensional hyperspace defined by the lower and upper bounds of my problem.
I am however unsure of whether I am covering the space of possible solutions (defined by lower and upper bounds) in a sufficiently uniform manner. It could come from 2 issues: 1) the initial generation of the quasi random points is not "dense" enough, 2) the rescaling could create holes in the hyperspace because of bounds that are highly different
Is there a way that I can ensure that my starting points cover my space adequately (maybe specify the maximum distance between my starting points in n-dimension).
Thank you for your help
See below code I am using:
objective_list = containers.Map('KeyType','int32','ValueType','any');
initial_pt_list = containers.Map('KeyType','int32','ValueType','any');
optimal_pt_list = containers.Map('KeyType','int32','ValueType','any');

net_size=100;
[variable_size, ~]=size(initial_pt);

p=haltonset(variable_size,'Skip',1e3,'Leap',1e2);
p = scramble(p,'RR2');
X0 = net(p,net_size);

for net0 = 1:1:net_size

    temp_unit_vector= X0(net0,:);
    temp_initial_pt = lower_b + temp_unit_vector'.*(upper_b - lower_b);
    initial_pt_list(net0)=temp_initial_pt;

end


text:
Q: How to implement add_image_size in a plugin I created a plugin and I need to use add_image_size in it.
I know how it works in the functions.php file and for a theme, but how can I implement this in a plugin?
I want new images uploaded by WordPress users to be smaller for mobile screens by
add_image_size( 'wp_small', 60, 75, true ); // mobile

I read that you need to use init or admin_init but I don't know how to implement this.

A: Just call this function in the init action. This action is fired for both frontend and backend. So it should look like this:
add_action( 'init', 'wpse4378_add_new_image_size' );
function wpse4378_add_new_image_size() {
    add_image_size( 'wp_small', 60, 75, true ); //mobile
}

A: It's better to call it in after_setup_theme instead of init action:
Codex says you should call add_image_size in functions.php so the closest action is after_setup_theme. Then you have:
add_action( 'after_setup_theme', 'your_theme_setup' );
function your_theme_setup() {
    add_image_size( 'wp_small', 60, 75, true ); //mobile
}

(Also explained in user contributed notes)


text:
Q: T-SQL - Get last 30 Rows for eacht ID how can i get the last 30 rows in a month for each employee? i have a table with evaluations for each employee.
SELECT
  Date,
  Month,
  Team,
  Employee_ID,
  Evaluation_Score,
  Evaluation_Case_Number
From X
Where month = @month
Order by date desc

This is what i got, but i only want to see the last 30 Evaluation Scores (or less, if they don't have that many)  for the declared month.
Is there a way to do this? Thanks in Advance.

A: You can use row_number(). Something like this:
select x.*
from (select x.*,
             row_number() over (partition by employee_id order by date desc) as seqnum
      from x
      where month = @month
     ) x
where seqnum <= 30;

A: Use the TOP statement:
SELECT TOP(30)
  Date,
  Month,
  Team,
  Employee_ID,
  Evaluation_Score,
  Evaluation_Case_Number

From X

Where month = @month

Order by date desc

This will help you to limit the number of returned rows.


text:
Q: High end VPS is Slow I have bought a vps to host my website. I have installed apache2, php, mysql server. My vps specs are:
ram: 30 gb guaranteed

cpu: 8 cores

ssd: 800 gb

port: 600 Mbps

os: Ubuntu 18.04
i have about 500 active users who are watching videos on my android app using my VPS using bandwidth around 200Mbps. Now the problem i m getting is that if I have about 200 users everything working fine response time is great on my app video start immediately but when user reach about 400 video dont even start for a minute what could be the problem.
my ram usage is about 1 gb buff/catche sometime increase to 20gb i don't know how my apache don't even have a cache module.
my apache config is
 <IfModule mpm_prefork_module>
 StartServers       5
 MinSpareServers    5
 MaxSpareServers    70
 MaxRequestWorker         1000
 MaxConnectionsPerChild   0
 </IfModule>

I really can't understand, what could be the problem. Can anyone help me?
ps. Sorry for my bad English.


text:
Q: How do I mute other people on voice chat? Is there any way to mute other players on voice chat in Battlefield 4? It upsets me sometimes.

A: To mute people in Battlefield 4, simply do the following;

*

*Press Escape or press the button to bring up the game menu (on console)

*Select Team Set-up/Scoreboard

*Toggle the speaker symbol next to the player you wish to mute
This will mute the selected person/people and you will no longer be able to hear them.

A: Go to the leaderbioard and click on the speaker


text:
Q: Go to a path if current url has specific flags in url I need to use jquery to redirect a user to a new url if they land on a url that contains specific arguments.
So when a user lands on www.thisurl.com/property#yes?uid=12&fid=3 I want to then redirect them to www.thaturl.com/fill?fid=3&uid=12
If the #yes shows up in the url they land on initially, then redirect them and include all of the other flags in the initial url, if not, then keep them where they are.

A: Check for the hash, see if it matches, and then forward the request.
var hash = window.location.hash;

if (hash && hash.substr(1, 3) == 'yes') {
   window.location = 'http://www.thaturl.com/fill' + hash.substr(4);
}

jsFiddle.