text:
Q: Python-pandas : a strange filtering/remove error I've been using pandas for a while but I am having a really strange issue with simple filtering  in pandas.
OS: Mac OS
IDE: VSCode
Pandas version: 1.4.2

I am fetching the latest data from crypto exchanges(via ccxt api) and append them into a dataframe.
limit = 28
timeframe = '1h'

futures_exchange = ccxt.kucoinfutures({
'apiKey' : MY_API_KEY,
'secret' : MY_API_SECRET,
'enableRateLimit': True,
'password': MY_KUCOIN_PASS_PHRASE,
})

all_future_list = [ 'BTC/USDT:USDT', 'BTC/USD:BTC', 'ETH/USDT:USDT', 'BCH/USDT:USDT', 'BSV/USDT:USDT', ]

attempts = 0
while attempts<= 20:
    alldf = pd.DataFrame()
    try:
        for i in all_future_list:
            df = futures_exchange.fetchOHLCV(i, limit=limit, timeframe=timeframe)
            df = pd.DataFrame(df, columns=[['timestamp', 'open', 'high', 'low', 'close', 'volume']])
            df['ticker'] = i
            df['timestamp'] = df['timestamp'].astype('datetime64[ms]')
            df = df[['timestamp', 'close', 'volume', 'ticker']]
            df = df.tail(1)
            alldf = pd.concat([alldf, df], ignore_index=True)
            time.sleep(0.1)
    except:
        print(traceback.format_exc())
        print(' ___  Network Error, restart fetching data _____ ')
        attempts += 1
        time.sleep(8)
        continue
    break

So far so good. Dataframe looks like...
             timestamp     close    volume         ticker
0  2022-09-17 10:00:00  19836.00  789336.0  BTC/USDT:USDT
1  2022-09-17 10:00:00    1411.2    982840  ETH/USDT:USDT
2  2022-09-17 10:00:00    120.95   55564.0  BCH/USDT:USDT

However, from there if I want to remove/filter a ticker from dataframe
new_df = alldf[alldf['ticker']!= 'BTC/USDT:USDT']
print(new_df)

Erroneous output:
  timestamp close volume         ticker
0       NaT   NaN    NaN            NaN
1       NaT   NaN    NaN  ETH/USDT:USDT
2       NaT   NaN    NaN  BCH/USDT:USDT
3       NaT   NaN    NaN  BSV/USDT:USDT

This should be a simple remove/filter but I dont understand why 'timestamp', 'close' and 'volume' columns are NaN
It seems if I write dataframe to a csv and then read it then I can get what I want.
alldf.to_csv('alldf.csv')
alldf = pd.read_csv('alldf.csv',index_col=0)

new_df = alldf[alldf['ticker']!= 'BTC/USDT:USDT']
print(new_df)

Output:
             timestamp     close    volume         ticker
1  2022-09-17 10:00:00    1411.2    982840  ETH/USDT:USDT
0  2022-09-17 10:00:00    120.95   55564.0  BCH/USDT:USDT
2  2022-09-17 11:00:00     51.95    3628.0  BSV/USDT:USDT

However, I dont want to write dataframe to csv and read it again just to filter out some tickers.
Can anyone help me ? Not sure whats going on here.

A: I guess this happens because that this piece of code
        df = df[['timestamp', 'close', 'volume', 'ticker']]
        df = df.tail(1)

subsets existing dataframe without actually copying the data. Therefore, target dataframe would get reference to original data, and when its changed - it gets broken.
Try this:
        df = df[['timestamp', 'close', 'volume', 'ticker']]
        df = df.tail(1).copy()

BTW, AFAIK, it's more efficient to keep new records in a dictionary and convert it to a dataframe at the end, rather then merging them one by one in a loop.


text:
Q: Is it okay to override (hide) a non-virtual method but still call it explicitly from a child class? Is it okay to override (hide) a non-virtual method but still call it explicitly from a child class? It works but I don't know if it's compiler-specific or should be avoided for one reason or another. (I didn't expect it to work based on the terminology of "hiding" functions.)
class A
{
public:
    void foo()
    {
        cout << "A::foo()" << endl;
    }
};

class B : public A
{
public:
    void foo()
    {
        cout << "B::foo()" << endl;
        A::foo();
    }
};

int main()
{
    B b;
    b.foo();
}

Edit
This might focus the question more.
The parent's non-virtual method is in an infrastructure library we can't change, yet we need to derive a class that hides (not "overrides," as I've learned now) a function in favor of one that augments it (and calls the parent one explicitly en route). That is, the derived class requires this "augmented" function to be used in place of the parent one. Is this a valid scenario in which to hide a parent function?

A: It's okay, but you're not overriding. You're hiding, as you already mentioned. Overriding means polymorphism will work on your object, and in your case, it won't.
For example:
A* a = new B;
a->foo();

will call the method A::foo(), whereas if you were to override the method (by making it virtual), it would call B::foo().
Also note that there might be issues related to the actual signature, for example if you had the method B::foo(int), you wouldn't be able to call foo(void) on a B object directly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Plotar várias colunas ao mesmo tempo Preciso plotar todas as colunas de uma tabela em relação à uma coluna específica.
Conjunto de dados:
df <- read.table(
text = "c1 c2 c3  x
        2  4   5  0
        3  5   2  0
        6  7   8  0
        1  2   5  1
        2  5   6  1
        3  3   3  1", header = TRUE)

Preciso plotar os valores das colunas c1, c2 e c2 com os valores da coluna X de modo que eu perceba qual a correlação deles com os valores 0 e 1:
No momento estou tentando o seguinte, mas não está saindo o que preciso:
library(tidyverse)
df %>% gather("id", "value", 1:3) %>%
  ggplot(., aes(x, id, color = x))+
  geom_point()

A: O segredo aqui está em entender o output da função gather. Vejamos ele em detalhes abaixo.
df <- read.table(
    text = "c1 c2 c3  x
        2  4   5  0
        3  5   2  0
        6  7   8  0
        1  2   5  1
        2  5   6  1
        3  3   3  1", header = TRUE)

library(tidyverse)
df %>% gather("id", "value", 1:3)
#>    x id value
#> 1  0 c1     2
#> 2  0 c1     3
#> 3  0 c1     6
#> 4  1 c1     1
#> 5  1 c1     2
#> 6  1 c1     3
#> 7  0 c2     4
#> 8  0 c2     5
#> 9  0 c2     7
#> 10 1 c2     2
#> 11 1 c2     5
#> 12 1 c2     3
#> 13 0 c3     5
#> 14 0 c3     2
#> 15 0 c3     8
#> 16 1 c3     5
#> 17 1 c3     6
#> 18 1 c3     3

Note que há 3 colunas. Usaremos x e value para tomarem os valores de x e c1, c2 e c3 do conjunto original, fazendo com que id seja o identificador de cada coluna no formato longo. Assim, temos o seguinte gráfico:
df %>% gather("id", "value", 1:3) %>%
    ggplot(., aes(x = x, y = value, colour = id)) +
    geom_point()

Note que não dá para perceber muita coisa em relação à correlação de c1, c2 e c3 com x, pois x só tem dois valores. Uma maneira de resolver isso é ajustando uma curva a cada valor de id. Neste caso, optei por uma regressão linear simples e a visualização melhorou um pouco.
df %>% gather("id", "value", 1:3) %>%
    ggplot(., aes(x = x, y = value, colour = id)) +
    geom_point() +
    geom_smooth(method = "lm", se = FALSE)
#> `geom_smooth()` using formula 'y ~ x'

Outra forma seria dividindo os id em painéis, para ao menos separar melhor os grupos de pontos e facilitar a visualização de tendências.

df %>% gather("id", "value", 1:3) %>%
    ggplot(., aes(x = x, y = value)) +
    geom_point() +
    facet_wrap(~ id)

Created on 2021-07-28 by the reprex package (v2.0.0)


text:
Q: Decode htmlEntities back on populate Zend Form I decode my zend-form with htmlEntities. This works great, but I would like to decode the input back when I repopulate the form back to the user. Is there a way to reverse the setElementFilter in Zend?
Example:
User fills in input field with
You & me

Data placed in the database:
You & me

I get the data back from the database and populate the input field with it:
You & me

I just want my ampersand (in this case) back and see this:
You & me

Thanks in advance,

A: I usually repopulate my form if it was invalid or i wanted to edit some data
$form = new zend_form("name");
.......................
......................
$form->populate($this->_request->getAllparams());

or  if wanted to fill the form with custom data
$form->populate($data);

and zend form will take care of filtering , validating and populating the form back
http://framework.zend.com/manual/en/zend.form.forms.html
hope that would help

A:
Is there a way to reverse the setElementFilter

No. You should filter your data with html_entity_decode before populating your form


text:
Q: Orthogonal group isomorphisam
First we take identity element from set which is Identity matrix so S=I
for which b(σ(x),σ(y))=b(x,y) which is identity transformation in O(V,b)
so kernal becomes identity and so it is surjective since it is finite dimensional. Is it correct or not please guide regarding this.

A: $O(V,b)$ is the set of linear maps $\sigma$ that verify $b(\sigma(x),\sigma(y))=b(x,y)$ for every $x,y\in V$ and $B$ is the matrix associated to $b$ in the canonical base (for example)
Now you can prove that when you fix a base on $V$
$b(x,y)=x^tBy$
And so if you consider $A_\sigma$ the matrix associated to $\sigma \in O(V,b)$ in that base, than
$b(\sigma(x),\sigma(y))=x^t(A_\sigma^tBA_\sigma) y=b(x,y)=x^tBy$
So $A_\sigma$ verify the property
$
x^t(A_\sigma^tBA_\sigma)y=x^tBy$ for every $x,y\in V$
and in this case it is simple prove that you get that
$A_\sigma$ verify the property
$A_\sigma^t BA_\sigma=B$
Now if $b$ is a definite bilinear form than you have the property $y^tBy\neq 0$ for every $y\in V/ \{0\}$ and so if $det(A_\sigma)=0$ than there exist an $x\in V/ \{0\}$ such that $A_\sigma x=0$ but
$x^tBx =x^t(A_\sigma^tBA_\sigma)x= x^t(A_\sigma^tB)(A_\sigma x)=0$ and it is impossibile.
So you have also that $det(A_\sigma)\neq 0$ .
Now  if you  define $O(V,B)=\{A\in M_n(\mathbb{R}) : det(A)\neq 0, A^tBA=B\}$
there exists a map $\Psi: O(V,b) \to O(V,B)$ that maps every $\sigma\in O(V,b)$ to $A_\sigma$
This map is oviously bijective and your sets are also a Groups and so it is important to ask oneself if it is also a morphism of group.

A: We want prove the surjectivity of the map $\Psi$.
We had fix a base $\beta:=\{v_1,...,v_n\}$ on $V$ and the function $\Psi$ maps every $\sigma\in O(V,b)$ to matrix $A_\sigma$ associate with itself in the base $\beta$.
If $A=(a_{ij})\in O(V,B)$ we can define a function
$\sigma': \beta\to V$
that maps every $v_i\in \beta$ to $ \sigma'(v_i):=\sum_{k=1}^{n}a_{ki}v_k$
In this way there exists a unique linear map $\sigma: V\to V$ that extends $\sigma'$.
Now we want prove that $\sigma\in O(V,b)$.
We know that the matrix associate to $\sigma$ in the base $\beta$ is the matrix that have on the $j$-th column the coefficients of $\sigma(v_j)$ written in the base $\beta$ and so, by construction, the matrix associate to $\sigma$ is $A$. But now for all $x,y\in V $
$b(\sigma(x),\sigma(y))=(Ax)^tB(Ay)=$
$=x^t(A^tBA)y=x^tBy=b(x,y)$
So $\sigma \in O(V,b)$ and oviously $\Psi(\sigma)=A$.
In other words the map $\Psi$ is surjective.


text:
Q: PHP sending mail and not receiving on gmail I have a php script that sends emails. It works fine on Yahoo or other personal server, but on gmail, I don`t receive anything. Neither in Spam folder.
What headers should I add to work?
I`m using mail() function.
$clientSubject = "Rays : programare confirmata!";
$clientMessage = "Buna " . $clientName . ", am inregistrat programarea ta. \n Te asteptam la Rays!";
$clientHeaders = 'MIME-Version: 1.0' . "\n" .
                     'From: "Rays" <private>' . "\n" .
                     'Reply-To: private' . "\n" .
                     'X-Mailer: PHP/' . phpversion(). "\n".
                     'Content-type: text/html; charset=iso-8859-1' . "\n";

    mail($emailClient, $clientSubject, $clientMessage, $clientHeaders);

This is the error I`m getting:
 SMTP error from remote mail server after end of data:
    host alt1.gmail-smtp-in.l.google.com [173.194.71.27]:
    550-5.7.1 [93.114.40.228      12] Our system has detected that this message is
    550-5.7.1 likely unsolicited mail. To reduce the amount of spam sent to Gmail,
    550-5.7.1 this message has been blocked. Please visit
    550-5.7.1 http://support.google.com/mail/bin/answer.py?hl=en&answer=188131 for
    550 5.7.1 more information. dj3si2836476lac.55 - gsmtp

------ This is a copy of the message, including all the headers. ------

Return-path: <@server.host28.net>
Received: from rays by server.host28.net with local (Exim 4.82)
    (envelope-from <@server.host28.net>)
    id 1X9fy5-0002AO-Sz
    for private@gmail.com; Tue, 22 Jul 2014 22:43:21 +0300
To: private@gmail.com
Subject: Rays : programare confirmata!
X-PHP-Script: private/scheduler/checkForNewResponses.php for 92.83.242.133
From: "Rays" <private>
Reply-To: private
X-Mailer: PHP/5.3.28
Content-type: text/html; charset=iso-8859-1
Message-Id: <E1X9fy5-0002AO-Sz@server.host28.net>
Date: Tue, 22 Jul 2014 22:43:21 +0300

A: Short answer:
Gmail has blocked your server ip !


text:
Q: Finding a bound on $f'$ $f$ is an entire function such that $|f(z+w)| \leq |f(z)| + |f(w)|$ for any $z, w $ in $\mathbb{C}$. I need to show that $f(z) = az +b$ for some complex numbers $a$ and $b$.
So, it suffices to show that the entire function $f'$ is bounded, since then the rest follows from Liouville's Theorem. We can assume that $f(0)=0$, without loss of generality. I thought I could get a bound using the inequality on the definition of $f'(z)$ or on the Cauchy Integral formula for $f^{(n)}(z)$. But now I can not see how.
Can you please help me with a way to use the inequality to get a bound on $f'$ ?
Thanks in advance !


text:
Q: UISearchBar's text field. right view not showing What i'm trying to implement is to move UISearchBar's magnifier icon from the left edge of the text field to the right edge. This is how i do that:
    searchBar                   = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, FRSearchMaxHeight)];
    searchBar.delegate          = self;
    searchBar.placeholder       = NSLocalizedString(@"Search friends", "");
    searchBar.showsCancelButton = NO;

    UIView *view = [searchBar subviewConformingToProtocol:@protocol(UITextInput)];

    UIView<UITextInput> *textInputView = (UIView<UITextInput> *)view;

    [textInputView setReturnKeyType:UIReturnKeyDone];
    [textInputView setKeyboardAppearance:UIKeyboardAppearanceAlert];

    tableView.tableHeaderView = searchBar;

    UIImage *image = [UIImage imageWithColor:[UIColor colorWithRed:0.9f green:0.9f blue:0.9f alpha:0.9f] size:searchBar.frame.size];
    [searchBar setBackgroundImage:image];

    textInputView.layer.cornerRadius = 0.f;
    textInputView.layer.borderWidth = 1.f;
    textInputView.layer.borderColor = [UIColor lightGrayColor].CGColor;

    UIView *magnifier = [(UITextField *)textInputView leftView];
    [(UITextField *)textInputView setRightView:magnifier];
    [(UITextField *)textInputView setLeftViewMode:UITextFieldViewModeNever];
    [(UITextField *)textInputView setRightViewMode:UITextFieldViewModeAlways];

however the magnifier is never shown. It vanishes. I checked frame like this:
NSLog(@"FRAME %@", NSStringFromCGRect(((UITextField *)textInputView).rightView.frame));

and it says: FRAME {{0, 0}, {12.5, 12.5}}. What am i missing?


text:
Q: Using __slots__ with SQLAlchemy model I am using SQLAlchemy on my new project and would like to use __slots__ with models (in beta version without alchemy, __slots__ were necessary because a large number of objects was created). But I am unable to combine them with SQLAlchemy declarations and get the following error for code:
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()

class NotWorking(Base):
     __tablename__ = 'table1'
     pk = Column(Integer, primary_key=True)
     name = Text(length=64, convert_unicode=True)

     __slots__ = ['name', 'pk']

Error
ValueError: 'name' in __slots__ conflicts with class variable
Which is expected as __slots__ modify class to create descriptors for fields defined in them, so one workaround is to make hidden fields (_name) and make model fields act as properties as shown here:
class Working(Base):
    __tablename__ = 'table2'
    pk = Column(Integer, primary_key=True)
    name = Text(length=64, convert_unicode=True)

    __slots__ = ['_name', '_pk']

     # Workaround
    @property
    def name(self):
        return self._name

    @name.setter
    def name(self, name):
        self._name = name

But this code can be a bit tedious to write and you need to add corresponding property for each new field. I am wondering, is there a better way to do without properties, while still using declarative base (without using Classical Mappings).

A: You can use simple Python statements on the class body to automate the creation of simple properties, based on the __slots__ attribute itself:
class Working(Base):
    ...

    __slots__ = ['_name', '_pk']

    for _tmp_name in __slots__:
        locals()[_tmp_name[1:]] = property(lambda self, name=_tmp_name: getattr(self, name))
    del _tmp_name

Note that while the dictionary returned y locals inside a function or method is somewhat special, in which modifications to it do not affect the actual variables, it works as a plain dictionary in the class body itself.
If you have several models,or find this too hacky, it can be put in a metaclass or __init_subclass__ method as well (Python 3.6+):
class MyBase(Base):
    def __init_subclass__(cls, *args, **kwargs):
        for name in cls.__slots__:
            setattr(cls, name[1:], property(lambda self, name=name: getattr(self, name)))

class Working(MyBase):
    ...

For the metaclass case (python  < 3.6), just put the same three lines in the metaclass __init__:
class MetaBase(type):
    def __init__(cls, name, bases, namespace):
         super().__init__(name, bases, namespace)
         for name in cls.__slots__:
             setattr(cls, name[1:], property(lambda self, name=name: getattr(self, name)))

class Working(Base, metaclass=MetaBase):
    ...


text:
Q: Можно ли в VS 2012 посмотреть ассемблерный код? Добрый день!
Скажите, пожалуйста, можно ли в VS 2012 pro посмотреть ассемблерный код написанной программки? Или только дизассемблировать каждую программу вручную?
Где-то слышала, что можно заставить компилятор создавать сразу не объектный код а ассемблерный. В настройках не нашла.
Заранее спасибо)
И прощу прощения за дурацкий вопрос)
A: Project Properties > Configuration Properties > C/C++ > Output Files > Assembler output


text:
Q: Facebook Plugin Like Facebook Plugin Error The button is displayed on the page and everything is ok, but when you click, it seems like I take the likes, and then the word bug is placed in small letters instead of the button.
I click on the error and facebook notifies: This function is not available .: There was an error processing this request. Please try again later.
The strange thing is that the share button that comes with that plugin does work. I leave the code:
<html>
<head>
    <meta charset="UTF-8" />
</head>
<body>
<script>
    (function(d, s, id) {
      var js, fjs = d.getElementsByTagName(s)[0];
      if (d.getElementById(id)) return;
      js = d.createElement(s); js.id = id;
      js.src = "//connect.facebook.net/es_ES/sdk.js#xfbml=1&version=v2.8";
      fjs.parentNode.insertBefore(js, fjs);
    }(document, 'script', 'facebook-jssdk'));
</script>
<div
    class='fb-like'
    data-href='http://www.ejemplo.blogspot.com'
    data-layout='standard'
    data-action='like'
    data-size='large'
    data-show-faces='true'
    data-share="true">
</div>
</body>

</html>


text:
Q: I can't filter results of a Yajara Datatable in front end of a date range (client side) I'm tryng to filter a date field between two dates, but this dont work, for some reason the ajax run, but dont change de recordsFiltered, my  code is bellow:
AJAX
$.fn.dataTable.ext.search.push(function(settings, data, dataIndex) {var min = $("#b_datac_inicio").val();var max =  $("#b_datac_fim").val();var date = data[6]; // A coluna "date" é a sétima coluna (índice 6)

  // Verifica se a data está dentro do intervalo de data especificado pelo usuário
  if (min == "" && max == "") {
     return true;
  }
  if (min == "" && date <= max) {
     return true;
  }
  if (max == "" && date >= min) {
     return true;
  }
  if (date <= max && date >= min) {
     return true;
  }
  return false;

});

$('#b_datac_inicio, #b_datac_fim').change( function() {

         table.draw();
 });`

PHP / HTML
                            <input type="date" id="b_datac_inicio" class="form-control form-control-sm filter-input" placeholder="Digite o periodo" data-column="0" />

                            <input type="date" id="b_datac_fim" class="form-control form-control-sm filter-input" placeholder="Digite o periodo" data-column="0" />

RESULT OF AJAX (Lan tab of developer options on brownser)
{draw: 7, recordsTotal: 102, recordsFiltered: 102, data: [,…], input: {draw: "7",…}} data :  [,…] 0 :  {id: 148, user_cad_id: 1, grupo_cad_id: 2, grupo_cad_nome: "Coodenação de Int",…} 1 :  {id: 147, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} 2 :  {id: 146, user_cad_id: 1, grupo_cad_id: 2, grupo_cad_nome: "Coodenação de Int",…} 3 :  {id: 145, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} 4 :  {id: 144, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} 5 :  {id: 143, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} 6 :  {id: 142, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} 7 :  {id: 141, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} 8 :  {id: 140, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} 9 :  {id: 139, user_cad_id: 1, grupo_cad_id: 3, grupo_cad_nome: "PRxxxx", user_cad_name: "Admin",…} draw :  7 input :  {draw: "7",…} recordsFiltered :  102 recordsTotal :  102

I expect that after the "processing" the listed itens of my index change, also the number of total records and showing itens X to XX.


text:
Q: Meta box data not saving I have just started working with custom post types and meta fields/data. I'm able to get the custom post and meta field to appear. It just won't save. I've been staring at the code and reading up endlessly but nothing has jogged for me what is wrong. I would love some fresh eyes on it to see what y'all think. Once I have this piece figured out I'm certain I will be able to scale the use of these functions.
Here's the code I have for my meta box:
/*Custom META Boxes for Ranch Custom Post Types*/
/*Ranch Location META Box*/
add_action( 'add_meta_boxes', 'ranch_location_meta' );
function ranch_location_meta() {
add_meta_box(
    'ranch_location_meta',
    __( 'Ranch Location', 'myplugin_textdomain' ),
    'ranch_location_meta_content',
    'ranch',
    'side',
    'high'
);
}

function ranch_location_meta_content( $post ) {
    wp_nonce_field( plugin_basename( __FILE__ ), 'ranch_location_meta_content_nonce' );
    echo '';
    echo '<input type="text" id="ranch_location" name="ranch_location"     placeholder="Enter  Ranch Location Here" />';
}

add_action( 'save_post', 'ranch_location_save' );
function ranch_location_save( $post_id ) {

    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
        return;

    if ( !wp_verify_nonce( $_POST['ranch_location_meta_content_nonce'], plugin_basename( __FILE__ ) ) )
        return;

    if ( 'page' == $_POST['post_type'] ) {
        if ( !current_user_can( 'edit_page', $post_id ) )
            return;
    } else {
        if ( !current_user_can( 'edit_post', $post_id ) )
            return;
    }
    $ranch_location = $_POST['ranch_location'];
    update_post_meta( $post_id, 'ranch_location', $ranch_location );

}

Any and all help is so appreciated. Thanks!
UPDATE ON SOME TROUBLESHOOTING:
So I'm playing with the save function some to troubleshoot. So I removed all the security verification in a variety of ways. First I left just the 'nonce' in the save function...
/*Custom META Boxes for Ranch Custom Post Types*/
/*Ranch Details META Box*/
add_action( 'add_meta_boxes', 'ranch_location_meta' );
function ranch_location_meta() {
add_meta_box(
'ranch_location_meta',
__( 'Ranch Location', 'myplugin_textdomain' ),
'ranch_location_meta_content',
'ranch',
'side',
'high'
);
}

function ranch_location_meta_content( $post ) {
wp_nonce_field( plugin_basename( __FILE__ ), 'ranch_location_meta_content_nonce' );
echo '';
echo '<input type="text" id="ranch_location" name="ranch_location" placeholder="City &     State" />';
}

function ranch_location_save( $post_id ) {

if ( !wp_verify_nonce( $_POST['ranch_location_meta_content_nonce'], plugin_basename(     __FILE__ ) ) )
return;

$ranch_location = $_POST['ranch_location'];
update_post_meta( $post_id, 'ranch_location', $ranch_location );
}
add_action( 'save_post', 'ranch_location_save' );`

The save function still failed. No data remained in the meta box.
Then I removed the nonce all together, leaving this in the save function...
function ranch_location_save( $post_id ) {

if ( !wp_verify_nonce( $_POST['ranch_location_meta_content_nonce'], plugin_basename(     __FILE__ ) ) )
return;

$ranch_location = $_POST['ranch_location'];
update_post_meta( $post_id, 'ranch_location', $ranch_location );
}
add_action( 'save_post', 'ranch_location_save' );`

Still nothing being saved. SOOOOOO...does this mean that my issue has something to do with how the update_post_meta is finding the data to populate? Because the rest of the other stuff is just security, right? Without it all should just populate no problem, right? Excuse me if I'm wrong here. I'm a bit of a PHP hack. ;)

A: Have you noted that you are verifing that the post type is a page and that user can edit pages and posts?
if ( 'page' == $_POST['post_type'] ) {
    if ( !current_user_can( 'edit_page', $post_id ) )
        return;
} else {
    if ( !current_user_can( 'edit_post', $post_id ) )
        return;
}

It should be:
if ( 'ranch' == $_POST['post_type'] ) {
    if ( !current_user_can( 'edit_post', $post_id ) )
        return;
} else {
    if ( !current_user_can( 'edit_post', $post_id ) )
        return;
}

Note: by default standard post capabilities are assigned to custom post types. If you have changed this, you must adjust current_user_can( 'edit_post', $post_id ) width correct capability.
Plus, you may want to fill the meta box input with previous value:
function ranch_location_meta_content( $post ) {

    $previous_value = get_post_meta( $post->ID, 'ranch_location', true );
    wp_nonce_field( plugin_basename( __FILE__ ), 'ranch_location_meta_content_nonce' );
    echo '';
    echo '<input value="'.$previous_value.'" type="text" id="ranch_location" name="ranch_location"     placeholder="Enter  Ranch Location Here" />';

}

A: Try basename( __FILE__ ) instead of plugin_basename( __FILE__ )
I think your nonce is not verifying.

A: It looks like what might be happening is that it is in fact saving it, but you are just not outputting the saved value. For example if you have a text input you will need to get the meta first and then echo it as the value attribute:
<?php
 $my_meta = get_post_meta( $post->ID, 'meta_key', true );
?>

<input type="text" name="name" id="id" value="<?php echo esc_attr($my_meta); ?>" />

This is just a very basic example to show what I mean.


text:
Q: Splitting a String at Char in Painless Scripting Language I am trying to split a String (that represents an IPv4 address) in painless. I tried the following:
String[] ipAddressParts = /\\./.split(params.ip);

But the String doesn't get split at all.

A: You're almost there, the correct code is this one (you have one too many backslashes):
String[] ipAddressParts = /\./.split(params.ip);


text:
Q: Calling super class method in Backbone var BaseView = Backbone.View.extend({
    localizedTemplate : function (element) {
        template = _.template(element.html());

        return function (data) {
            return template($.extend({}, data, resource));
        };
    }
});

var DerivedView = BaseView.extend({
   initialize: function (options) {
       this.model = options.model;

       this.template = function () {
         return this.localizedTemplate($("#someTemplate"));
       };
   },

   render: function () {
       var output = this.template(this.model.toJSON());
       this.$el.append(output);
       return this;
   }
});

Why the above code is not working? why I am not able to call the someFunction in DerivedView? is there any way to achieve this?
I am using Backbone latest version.

A: When you do this:
this.template = function () {
    return this.localizedTemplate($("#someTemplate"));
};

You're assigning a function to this.template. Note that localizedTemplate also returns a function:
return function (data) {
    return template($.extend({}, data, resource));
};

That means that this.template is a function which returns a function and that second function is the one that wants this.model.toJSON() as an argument.
You're doing this:
var output = this.template(this.model.toJSON());

The function in this.template ignores its arguments and returns a function, that leaves you with this function:
function () {
    return this.localizedTemplate($("#someTemplate"));
}

in output. You probably think output is a chunk of HTML at this point so you hand that to append:
this.$el.append(output);

But output is a function and what does append do when called with a function as its argument? jQuery calls that function like this:

function(index, html)
  Type: Function()
  A function that returns an HTML string, DOM element(s), or jQuery object to insert at the end of each element in the set of matched elements. Receives the index position of the element in the set and the old HTML value of the element as arguments. Within the function, this refers to the current element in the set.

So the output function will be called by jQuery's append and append will supply arguments that the compiled template function doesn't understand. The result is a big pile of confusion.
If you really want to do things like this then you'll want to call all the functions yourself so that you can get the right arguments to the right places:
var output = this.template()(this.model.toJSON());
// -----------------------^^

Demo: http://jsfiddle.net/ambiguous/YyJLR/
Or better, don't bother with all the extra wrappers at all. Say this in your view's initialize:
this.template = this.localizedTemplate($("#someTemplate"));

and then this in render:
var output = this.template(this.model.toJSON());

Demo: http://jsfiddle.net/ambiguous/BQjhS/
Also note that you don't need to this.model = options.model, the view constructor will do that for you:

There are several special options that, if passed, will be attached directly to the view: model, collection, el, id, className, tagName and attributes.

A: var DerivedView = BaseView.extend({
   someVariable: function(someData) {
      return this.someFunction(someData);
   }
});


text:
Q: Too many or too few rows when using different engines when creating one table from another I'm trying to create one table from another using
CREATE TABLE IF NOT EXISTS new_data ENGINE = ReplicatedReplacingMergeTree(/clickhouse/fedor/tables/{shard}/subfolder/new_data', '{replica}')
ORDER BY created_at
SETTINGS index_granularity = 8192, allow_nullable_key=TRUE
AS
SELECT *
FROM table
WHERE column IS NOT NULL

When I use
ENGINE = ReplicatedReplacingMergeTree('/clickhouse/fedor/tables/{shard}/subfolder/new_data', '{replica}'),

i've got around 7-9% of expected number of rows i've got from query SELECT...FROM...WHERE
When I use
ENGINE = ReplicatedMergeTree('/clickhouse/fedor/tables/{shard}/subfolder/new_data', '{replica}')

i've got 3 times more than expected (I assume every row occur exactly 3 times)
I would like to have exact number of rows without losses and without duplication

A: ReplicatedReplacingMergeTree with ORDER BY created_at
will replace many rows with the same created_at value to one rows
How did you delete exists table data before create
ReplicatedMergeTree('/clickhouse/fedor/tables/{shard}/subfolder/new_data'...)?
Did you use DROP TABLE new_data SYNC?
Which engine do you have for table?


text:
Q: Can't plot rotated region I was experimenting with the code from this question when I ran into another problem with regions.
Ω = RegionDifference[Rectangle[{0, 0}, {10, 10}], Rectangle[{4, 4}, {8, 8}]];
RegionPlot[Ω]

Ω1 = TransformedRegion[Ω, RotationTransform[45 °, {5, 5}]];
RegionQ[Ω1]

True

RegionPlot[Ω1]

RegionPlot::invplotreg: TransformedRegion[RegionDifference[Rectangle[{0, 0}, {10, 10}], Rectangle[{4, 4}, {8, 8}]], TransformationFunction[...]] is not a valid region to plot. >>

What is the difference between a "valid region to plot" and a region that satisfies RegionQ? Or, perhaps, to put it better, am I seeing a bug in RegionPlot or just an incomplete implementation?
I note that
RegionPlot[TransformedRegion[Rectangle[], RotationTransform[45 °, {.5, .5}]],
  PlotRange -> All]

works as expected, so it would seem RegionPlot can handle rotations for some class of inputs.

A: Here is a workaround:
r1 = RegionDifference[Rectangle[{0, 0}, {10, 10}],
   Rectangle[{4, 4}, {8, 8}]];
r2 = TransformedRegion[r1, RotationTransform[45 \[Degree], {5, 5}]];
mr = DiscretizeRegion[r2]

And then:
RegionPlot[mr]


text:
Q: Resonance Frequency of High Resistance RLC I was measuring the resonance frequency of an RLC (all in series) circuit using an oscilloscope and a function generator. Now resonance frequency is given by:
$$f_r = \frac{1}{2 \pi \sqrt{LC}}$$
In my situation, I was using a $0.002 \mu$F capacitor, $100$mH inductor, and a $110\Omega$ resistor. Then the formula predicts:
$$\frac{1}{2\pi \sqrt{(0.1)(2 \times 10^{-9})}} \approx 11254\,{\rm Hz}.$$
This is roughly what was seen in the lab.
Then when the $110\Omega$ resistor is switched out for the $11000\Omega$ resistor, the resonance frequency was significantly higher, peaking at about $13500$Hz. Even after completely disassembling and reassembling the circuit, the resonance frequencies were as above. The same inductor and capacitor were used for both measurements.
How can this be? Doesn't resistance play no part in the frequency?

A: Update: After simulating a little more, it seems that Drew Noel had the right hunch after all: by inserting a 100pF capacitor in parallel to the 110 Ohm and 11kOhm resistors, we can shift the resonance frequencies up from 11.25kHz to 12.11kHz, which gets us into the right ballpark. 150pF will give 12.71kHz for the upper frequency and 200pF will result in 13.49kHz.
While 200pF are far larger than the practical stray capacitance of any common low power resistor (which I assume has been used), it would be commensurate with 1-2m of cable connecting to an oscilloscope input! Since it's common to measure the current trough an RLC circuit by the voltage drop across the series resistor, it may very well have been the input capacitance of the measurement device that caused this effect. Maybe the OP can confirm if Drew was right about the resistor's parallel capacitance causing the effect?
Original post with changes as suggested by user3814483 (you may as well disregard it, since my original idea is not helpful!):
The resonance frequency of an RLC circuit depends on the quality factor, i.e. the resistance in the circuit, which is not only dependent on the explicit resistor in the circuit, but also on the stay elements in the real inductor. The 100mH inductor has an impedance of approx. 7kOhm at the frequency of the resonance, which puts the Q at roughly 70 for the 110Ohm resistor. That's about as much as you can expect to get out of a typical inductor, so it should have an influence on the resonance for the case of the 110Ohm resistor.
If you want to understand this numerically, you can download yourself a version of Linear Technology's LTSpice circuit simulator. It's a beautiful program to simulate electronic circuits and it's really easy to use. It will allow you to cross check your measurements and you can play around with component values to see what happens if circuit elements get changed. That's exactly how professional engineers analyze many of their designs.
Unfortunately, the simulator does not concur with my hunch: The resonance frequency with 110Ohm is approx. 11.2545kHz. If I add a typical inductor parallel capacitance of 100pF, it shifts and broadens the peak considerably, and it's now at 10.982kHz. That's not nearly as much of a shift as you are seeing. My suggestion would be to measure the self resonance of the inductor. Crank the frequency of the signal generator up and see where a second (parallel) resonance occurs. It should be somewhere in the 100kHz range. From that we can calculate an effective parallel capacitance. I would also suggest to measure the series resistance of the inductor with a multimeter. That, too, can be used in a model. If none of that pans out, you got yourselves a real mystery.
I have done a few more simulations and I can't reproduce your result. Even with non-ideal inductors I can only reproduce a slight shift to a lower resonance frequency, not a shift to a much higher one, so it's not clear what causes the effect. Let's go back to basics: how are you measuring the resonance? What's the loading on the LRC-circuit? Are you using an oscilloscope or are you measuring the current trough the circuit with an AC-current meter? How are you generating the AC voltage? Are you using a signal generator? What voltage is the output of that generator set to? What's the output impedance? Did you verify, that the generator is not overloaded? Does the output voltage stay the same? Does the AC voltage look sinusoidal at all times?


text:
Q: htaccess file adds the virtual directory address to the url I wrote a script to add shtml extension to all requests that don't have it. This is it:
Options +FollowSymlinks
<IfModule mod_rewrite.c>
  RewriteEngine on
        RewriteCond %{REQUEST_URI} htmlTemplates
        RewriteCond %{REQUEST_FILENAME} !\.shtml$
        RewriteRule ^.*/(.*)$ $1.shtml [r,nc]
</IfModule>

I tried it on my local server, which is a virtual location, and it ends up rewriting the url with the system location of the file rather like this:
http://svn1/C:/Documents and Settings/vunsal/My Documents/My Dropbox/Workspace/National Grid/Templating/Svn1/site/index.shtml
Can anyone tell me what is wrong with my configuration?

A: Try this:
RewriteCond $0 htmlTemplates
RewriteCond $0 !\.shtml$
RewriteRule .* %{REQUEST_URI}.shtml [R=301,L]


text:
Q: Why does curl -V show a different OpenSSL library than ldd and curl-config? I built curl from the source (on Debian 10 machine) as follows:
LD_LIBRARY_PATH=/usr/local/openssl3.0/lib64 ./configure --with-openssl=/usr/local/openssl3.0
make
make install
When I went to check the version of my new build of curl, I don't see OpenSSL 3 in the output:
root@ip-10-0-0-252:/usr/local/bin# /usr/local/bin/curl -V
curl 7.84.0 (x86_64-pc-linux-gnu) libcurl/7.64.0 OpenSSL/1.1.1n zlib/1.2.11 libidn2/2.0.5 libpsl/0.20.2 (+libidn2/2.0.5) libssh2/1.8.0 nghttp2/1.36.0 librtmp/2.3

This output shows OpenSSL/1.1.1n.
However, curl-config looks correct:
root@ip-10-0-0-252:/usr/local/bin# ./curl-config  --ssl-backends
OpenSSL v3+

And ldd looks correct:
root@ip-10-0-0-252:/usr/local/bin# ldd /usr/local/bin/curl
    linux-vdso.so.1 (0x00007fffc4ddd000)
    libcurl.so.4 => /lib/x86_64-linux-gnu/libcurl.so.4 (0x00007fea3312a000)
    libssl.so.3 => /usr/local/openssl3.0/lib64/libssl.so.3 (0x00007fea33082000)
    libcrypto.so.3 => /usr/local/openssl3.0/lib64/libcrypto.so.3 (0x00007fea32c20000)
...

Why is the output different from curl -V different from the others? What's the best way to prove which version of OpenSSL curl is using?

A: Look at the curl -V output again and check the libcurl part in particular.
I'll cut away the rest for you to make it more obvious:
# /usr/local/bin/curl -V
curl 7.84.0 (x86_64-pc-linux-gnu) libcurl/7.64.0

curl 7.84.0, with libcurl 7.64.0
This tells you that when you invoke that 'curl' binary, it finds an older libcurl and not the one you built and probably intends for curl to use.
You have not configured your ld.so to find it in that path. You can edit /etc/ld.so.conf, set LD_LIBRARY_PATH or similar to fix it.
If you do edit ld.so.conf, remember to sudo ldconfig.


text:
Q: Calling function from .so file created in android in linux C++ code I have .so file which I take from apk. With command nm -D libnative-lib.so I took list of functions. I need to call function named Java_com_example_nativelib_utils_Constants_getStringFromJNI . I wrote the code below:
#include <stddef.h>
#include <dlfcn.h>
#include <stdio.h>

int init_library() {
    void* hdl = dlopen("./libnative-lib.so", RTLD_LAZY);
    if(hdl == 0)
        return 0;
    else return 1;
}

int main() {
    printf("%s\n", (init_library() ? "OK": "ERROR"));
}

and make file:
all: exe

exe:    main.c
        gcc main.c -fPIC -ldl -o main

but result of program is always "ERROR". I tried libnative-lib.so from x86 and armeabi-v7a architectures (others not present). How to load library and call function from it? C++ or C do not care.

A: It is not possible to use android .so files in non-android project. similar question is here


text:
Q: Showing update time like Twitter's update notification I am using momentJs for finding difference from now to a specific date as below:
moment([MyDate]).fromNow();

The code gives me results as below:

"a few minutes ago" or "10 hours ago" ...

I tried to change that as below to find difference as seconds
moment([MyDate]).fromNow().asSeconds();

but the code doesn't work.
So I would like to implement codes like Twitter's last update notification. Any suggestion?

A: If you want to make the diff between 2 dates in seconds : moment().diff(mydate, 'seconds')


text:
Q: Visual Studio 2019 editor fails to select modules in the editor I have a problem with VS 2019 editor for a while, but it became a real problem lately.
Specifically, with the editor open, I cannot navigate to objects / classes and their methods or properties
You can see example in the screencast below.
https://www.screencast.com/t/0ceZ4C3TabY

I have the latest version, 16.10.2
This happens on two different PC's.
The problem started in a previous update, but I don't know which. I noticed it few times ago, but I didn't paid attention.
Does anyone else encountered it, and knows any solution?
Thank you

A: The problem was finally fixed in 16.10.3


text:
Q: Can the angle of incidence be greater than 90°? My teacher was teaching me prism in Ray Optics and he told me that for the emergence of ray from a prism the condition is :
$i_{g}≤i≤90°$
where $i_{g}$ is the angle of incidence for which grazing refracted ray is obtained and $i$ is the angle of incidence. Now, my question is what will happen if angle of incidence is more than $90°$? Why,  for emergence of ray,  angle of incidence should be less than $90°$? Can the angle of incidence even be greater than $90°$? Does it make sense for the angle of incidence to be greater than $90°$? In general, for any reflection or refraction can the angle of incidence be greater than $90°$? Please explain. I am confused.

A: The angle of incidence is the angle between the normal line orthogonal to the surface of the prism (i.e., coming straight out from the prism) and the direction of the incident ray. For all intents and purposes we can consider the prism to have a straight edge, so that the normal line simply makes a right angle with that straight edge.
If the angle of incidence is $0^\circ$, the light is exactly along the normal line. If the angle increases, the pie wedge between the normal line and the incident ray gets bigger. When the angle approaches $90^\circ$, the incident ray is almost parallel to the prism - we know this because the angle between the normal line and the prism's edge is exactly $90^\circ$. Once the angle equals $90^\circ$, the incident ray just travels parallel to the prism, but never really gets closer to it! And if the angle is greater than $90^\circ$, that means that the light is incident from inside the prism! So that is a completely different scenario, the scenario of light travelling from inside of a prism to outside of a prism, and in that scenario we typically just reverse the whole problem and define the angle of incidence from a normal line inside of the prism. Any time that the incident light is actually going into the prism, the angle will always be less than $90^\circ$.


text:
Q: How can I get rid of "-bash: ulimit: open files" when I open terminal on my mac Every time I open a new terminal, these messages show up:
-bash: ulimit: open files: cannot modify limit: Invalid argument
-bash: ulimit: max user processes: cannot modify limit: Operation not permitted

I do modify ulimit before, but I've forgotten what I've done. So How can I fix this, please help. THX
---- update ----
I don't hava a .profile or .bashrc in my home dir. But I have a ~/.bash_profile and /etc/bashrc. And ~/.bash_profile looks like
export PS1="\[\033[36m\]\u\[\033[m\]@\[\033[32m\]\h:\[\033[33;1m\]\w\[\033[m\]\$ "
export CLICOLOR=1
export LSCOLORS=ExFxBxDxCxegedabagacad
alias ls='ls -GF'
alias ll='ls -GFl'

export JAVA_HOME=$(/usr/libexec/java_home)
export LC_CTYPE="en_US.UTF-8"

/etc/bashrc looks like:
# System-wide .bashrc file for interactive bash(1) shells.
if [ -z "$PS1" ]; then
   return
fi

PS1='\h:\W \u\$ '
# Make bash check its window size after a process completes
shopt -s checkwinsize
# Tell the terminal about the working directory at each prompt.
if [ "$TERM_PROGRAM" == "Apple_Terminal" ] && [ -z "$INSIDE_EMACS" ]; then
    update_terminal_cwd() {
        # Identify the directory using a "file:" scheme URL,
        # including the host name to disambiguate local vs.
        # remote connections. Percent-escape spaces.
    local SEARCH=' '
    local REPLACE='%20'
    local PWD_URL="file://$HOSTNAME${PWD//$SEARCH/$REPLACE}"
    printf '\e]7;%s\a' "$PWD_URL"
    }
    PROMPT_COMMAND="update_terminal_cwd; $PROMPT_COMMAND"
fi

I don't see anything abount ulimit.
---- update ----
sudo ulimit -a -H
core file size          (blocks, -c) unlimited
data seg size           (kbytes, -d) unlimited
file size               (blocks, -f) unlimited
max locked memory       (kbytes, -l) unlimited
max memory size         (kbytes, -m) unlimited
open files                      (-n) unlimited
pipe size            (512 bytes, -p) 1
stack size              (kbytes, -s) 65532
cpu time               (seconds, -t) unlimited
max user processes              (-u) 1064
virtual memory          (kbytes, -v) unlimited

sudo ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
file size               (blocks, -f) unlimited
max locked memory       (kbytes, -l) unlimited
max memory size         (kbytes, -m) unlimited
open files                      (-n) 4864
pipe size            (512 bytes, -p) 1
stack size              (kbytes, -s) 8192
cpu time               (seconds, -t) unlimited
max user processes              (-u) 709
virtual memory          (kbytes, -v) unlimited

A: Finally I solved this problem. I've found that there are 3 profile files which OS X will load when opening a new Terminal, they are "/etc/bashrc", "/etc/profile", "~/.bash_profile". I found 2 lines about ulimit configiuring at the bottom of "/etc/profile". I delete these 2 lines and solve this problem.
Anyway, thanks to @Jonathan Leffler, you remind me to find what other profile causing this problem. THX XD


text:
Q: How to find the latest revision hash of a remote git subdirectory? I would like to be able to retrieve the latest revision hash of a subdirectory on a remote repo. I can get the revision hash of a subdirectory on the LOCAL repo using this command (CORRECTED):
git rev-parse HEAD:path/to/subdir

(see How to retrieve the hash for the current commit in Git?)
And I can get the revision hash of the HEAD of a remote repo using this command:
git ls-remote ssh://git@myserver.com/repo-name.git HEAD

(see Getting the last commit hash from a remote repo without cloning)
But I haven't found a way to combine the two, i.e., to get the subdirectory hash from the remote repo without retrieving the code. Is that possible?
EDIT FOR CLARIFICATION:
I'm looking for a command that can be run without having a local repo at all, just as we can execute git ls-remote without having a local copy of the repo.
ALSO: Edited first example for copy-paste errors. (Thanks to @torek for pointing out the error.)
For context, I would like to write a script that can check if changes have been made to specific subdirectories. The command git rev-parse give thes exact information that I'm looking for, but it must be run on the local repo.

A:
I'm looking for a command that can be run without having a local repo at all, just as we can execute git ls-remote without having a local copy of the repo.

You'd have to run a command on the remote—i.e., have shell access there, or have someone on the inside there who gives you a backdoor way to run the command.  For instance, if the remote is host2.example.com, you might do:
ssh host2.example.com 'git -C /path/to/repo rev-parse ...'

This, of course, requires that you be able to log in to that host.  If you can't log in to that host, then no, you'll need to clone the repository first.

Meanwhile, back to the rev-parse command.  In your case this seems to be sufficient, but just in general:

git rev-parse HEAD:path/to/subdir

is very different from the command shown in Latest commit hash of subdirectory (this was linked at some point, so now it is via this answer):
git log -n 1 --format="%h %aN %s %ad" -- $directory

What git rev-parse HEAD:path/to/subdir prints is the hash ID of the internal Git tree object that stores path/to/subdir within the current commit.  But what git log -n 1 ... $directory prints is the hash ID of some commit.  This is never the hash ID of any Git internal tree object.
The commit that this git log finds is the first commit that satisfies some constraint, within in the sequence of commits formed by enumerating commits the way git log usually does, one at a time starting from HEAD and working backwards.  The constraint in question is that, by comparing (as with git diff) the (single) parent commit of some non-merge commit to the commit itself, in that pair of commits, some file(s) within path/to/subdir changed.
That is, suppose we have the following partial commit graph:
...--F--G--H   <-- master (HEAD)

where H is some commit hash ID, G is the parent of H, and F is the parent of G.  (Note that there are no merge commits in this graph-fragment.)
Suppose further that if we compare the snapshot in G vs the snapshot in H, the only file changed is README.md.  Hence git log -p would show that in H we changed README.md.  However, when comparing the snapshot in F vs the snapshot in G, file path/to/subdir/foo.cc has changed.  So git log -p would show that in G, we changed a file within path/to/subdir.
Since git log starts by looking at H (and thus compares G-vs-H), but then goes on to look at G (and thus compares F-vs-G), the command:
git log -n 1 --format="%h %aN %s %ad" -- $directory

will print the abbreviated hash (%h) of commit G, the author name (after applying .mailmap, %aN) from commit G, the subject line (%s) from commit G, and the author date (%ad) from commit G.
But running:
git rev-parse HEAD:path/to/subdir

prints the full hash ID of the tree object in commit H that holds information about any sub-trees and blobs that are required for the snapshot that is part of commit H.
If you want to enumerate (potentially many) commit hash IDs, with or without applying various constraints, you use git log or git rev-list to follow the commit graph.  That's what the git log command does, after all: walk the commit graph, starting at the starting-points you request (or at HEAD if you don't request any particular starting-points) and showing commits.
If you want one particular commit hash ID and you know enough about that commit, you can use git rev-parse.  In some cases, git rev-parse can also walk the commit graph: in particular it can find commits whose commit log message contains some string or regular expression.  But it is not smart enough to examine the diffs from one commit's parent(s) to that commit; for that, you need git log or its plumbing sister command, git rev-list.
(Note also that by default, git log ignores the diffs of any merge commits.  That's because the diff of a merge is complicated by the fact that there are two or more parent snapshots:  Which parent should Git use when making a diff?  To avoid answering that question, git log just doesn't bother to make a diff at all, by default.)


text:
Q: Using upgrade.from config in Kafka Streams is causing a "BindException: Address already in use" error in tests using embedded-kafka-schema-registry I've got a Scala application that uses Kafka Streams - and Embedded Kafka Schema Registry in its integration tests.
I'm currently trying to upgrade Kafka Streams from 2.5.1 to 3.3.1 - and everything is working locally as expected, with all unit and integration tests passing.
However, according to the upgrade guide on the Kafka Streams documentation, when upgrading Kafka Streams, "if upgrading from 3.2 or below, you will need to do two rolling bounces, where during the first rolling bounce phase you set the config upgrade.from="older version" (possible values are "0.10.0" - "3.2") and during the second you remove it".
I've therefore added this upgrade.from config to my code as follows:
val propsMap = Map(
  ...
  UPGRADE_FROM_CONFIG -> "2.5.1"
)

val props = new Properties()
properties.putAll(asJava(propsMap))

val streams = new KafkaStreams(topology, props);

However, doing this causes my integration tests to start failing with the following error:
[info]   java.net.BindException: Address already in use
[info]   at sun.nio.ch.Net.bind0(Native Method)
[info]   at sun.nio.ch.Net.bind(Net.java:461)
[info]   at sun.nio.ch.Net.bind(Net.java:453)
[info]   at sun.nio.ch.ServerSocketChannelImpl.bind(ServerSocketChannelImpl.java:222)
[info]   at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:85)
[info]   at sun.nio.ch.ServerSocketAdaptor.bind(ServerSocketAdaptor.java:78)
[info]   at org.apache.zookeeper.server.NIOServerCnxnFactory.configure(NIOServerCnxnFactory.java:676)
[info]   at org.apache.zookeeper.server.ServerCnxnFactory.configure(ServerCnxnFactory.java:109)
[info]   at org.apache.zookeeper.server.ServerCnxnFactory.configure(ServerCnxnFactory.java:105)
[info]   at io.github.embeddedkafka.ops.ZooKeeperOps.startZooKeeper(zooKeeperOps.scala:26)

Does anyone know why that might be happening and how to resolve? And also additionally, if this use of the upgrade.from config is correct?
For additional context, my previous versions of the relevant libraries were:
"org.apache.kafka" %% "kafka-streams-scala" % "2.5.1"
"org.apache.kafka" % "kafka-clients" % "5.5.1-ccs"
"io.confluent" % "kafka-avro-serializer" % "5.5.1"
"io.confluent" % "kafka-schema-registry-client" % "5.5.1"
"org.apache.kafka" %% "kafka" % "2.5.1"
"io.github.embeddedkafka" %% "embedded-kafka-schema-registry" % "5.5.1"

And my updated versions are:
"org.apache.kafka" %% "kafka-streams-scala" % "3.3.1"
"org.apache.kafka" % "kafka-clients" % "7.3.0-ccs"
"io.confluent" % "kafka-avro-serializer" % "7.3.0"
"io.confluent" % "kafka-schema-registry-client" % "7.3.0"
"org.apache.kafka" %% "kafka" % "3.3.1"
"io.github.embeddedkafka" %% "embedded-kafka-schema-registry" % "7.3.0"

My integration tests use Embedded Kafka Schema Registry as follows in their test setup, with specific ports specified for Kafka, Zookeeper and Schema Registry:
class MySpec extends AnyWordSpec
    with EmbeddedKafkaConfig
    with EmbeddedKafka {

  override protected def beforeAll(): Unit = {
    super.beforeAll()
    EmbeddedKafka.start()
    ...
  }

  override protected def afterAll(): Unit = {
    ...
    EmbeddedKafka.stop()
    super.afterAll()
  }
}

I'm not quite sure what to try to resolve this issue.
In searching online, did find this open GitHub issue on Scalatest Embedded Kafka, which was the precursor to Embedded Kafka Schema Registry and seems to be a similar issue. However, it doesn't appear to have been resolved.

A: Your config upgrade_from is not valid.
Cf https://kafka.apache.org/documentation/#streamsconfigs_upgrade.from
It should be 2.5, not 2.5.1.


text:
Q: AEM 6.1 Touch UI allows submit when text field is set to required For accessibility purposes, I have a component with an alt textfield in Touch UI dialog that has required="true".
However, an author is allowed to hit submit without actually having anything in the field. Also, it's not validating before hand - the author can't see that this field is required until they type something and delete it out of the field; only then can they see that the field is "required.
How can I get this alt text field required so that an author needs to enter in some text before submitting it for the component?
Thanks for any direction.

A: Per the documentation https://docs.adobe.com/docs/en/aem/6-1/ref/granite-ui/api/jcr_root/libs/granite/ui/components/foundation/form/textfield/index.html, you need to set the property "required" (type boolean) to "true" to achieve this. I have tested on AEM 6.1 SP1 and works fine.
Anyway if you are looking for something "before submiting" or "on dialog ready" states then you will need Javascript. You will need to create a clientlib folder under components with categories cq.authoring.dialog.
Please take a look to this that would solve the problem if that is the case:
http://experience-aem.blogspot.in/2015/02/aem-6-sp2-touch-ui-dialog-before-submit.html

A: I guess required="true" is not valid. You either need to just add the required attribute without any value or you can add it as required="required".
For e.g.,
<input type="text" required>
<input type="text" required="required">


text:
Q: When is an inverse a multifunction? Define $f:\mathbb{R} \to \mathbb{R}$ given by $f(x)=x^2$. If $f^{-1}(x)$ is interpreted as a function, it is undefined, since $f$ is not injective. If $f^{-1}$ is interpreted as a multifunction, it returns $\{-\sqrt{x},\sqrt{x}\}$. When is each of these interpretations normally made?

A: This is why we include domains and codomains in function definitions.  Given an invertible mapping $f:A\to B$, the inverse mapping is $f^{-1}:B\to A$.  Given any mapping $f:A\to B$, the preimage mapping is $f^{-1}:\mathcal P(B)\to\mathcal P(A)$, where $\mathcal P(X)$ refers to the power set of $X$.
Therefore, $f^{-1}(2)$ would refer to the inverse function, and $f^{-1}(\{2\})$ would refer to the pre-image function.
In practice, few people work with domains where there is any risk of not understanding which function is meant.  I will note that my foundations professor who had noble but futile dreams of fixing mathematical notation, thought that $f_>$ and $f^<$ were distinct but still clear notations indicating the image and pre-image functions.

A: We define inverse of an element as other element of the same kind such that their product is identity.In other words notion of inverse is understood as defined in case of groups. So this means inverse of a single valued function is expected to be a single valued function only unless otherwise stated. If obviously one is not restricting to single valued function then multiple valued functions are also acceptable as inverses and suitably the inverse is defined in that case.


text:
Q: complex update query proc SQL tab

id
value

1
aaa

1
bbb

1
ccc

tgt required output

id
value1
value2
value3
value4
value5

1
aaa
bbb
ccc

I want the data from 'tab' table to 'tgt' table to be loaded. 'tgt' will have the id=1. The number of rows in the 'tab' table is dynamic. It can have any number of rows with id=1.
Please let me know the update query i can use.
Thanks


text:
Q: Csv to Json with nodeJS I would like to convert a csv file to json with the csv-parser library.
That's my file csv :
account/firstname,account/lastname,account/location/countryName,account/location/town,account/location/address,Id
Babouche,Dorian,US,Washington,***,1

That's the code i have for the csv to json :
const csv = require('csv-parser');
const fs = require('fs');
let results = [];
let data;
fs.createReadStream('simple.csv')
    .pipe(csv())
    .on('data', (data) => results.push(data))
    .on('end', () => {
        data = JSON.stringify(results, null, 2)

        fs.writeFile('user.json', data, (err) => {
            if (err) {
                throw err;
            }
            console.log("JSON data is saved.");
        });
})

Desired JSON:
[{
    account: {
        firstname: "Babouche",
        lastname: "Dorian",
        location: {
            countryName: "US",
            town: "Washington",
            address: "***"
        }
    },
    Id: "1",
}
]

The result i have:
[
  {
    "account/firstname": "Babouche",
    "account/lastname": "Dorian",
    "account/location/countryName": "US",
    "account/location/town": "Washington",
    "account/location/address": "***",
    "Id": " 1"
  }
]

I would like a recommendation on how to easily accomplish this, please.

A: I recommend using 'json-2-csv'
First, install the package
npm install json-2-csv

Import:
let converter = require('json-2-csv');

Function with Callback
let csv2jsonCallback = function (err, json) {
    if (err) throw err;
        console.log(typeof json);
        console.log(json.length);
        console.log(json);
}

converter.csv2json(csv, csv2jsonCallback);

Function with Promise
converter.csv2jsonAsync(csv)
.then(console.log)
.catch((err) => console.log('ERROR: ' + err.message));


text:
Q: Turn off html processing in mediawiki I want to turn off the built in html processing of links in mediawiki. For example, I want to edit the Sidebar (MediaWiki:Sidebar) by adding a link with question marks and equal signs (i.e. Special:CustomNeed?page_title=Name+with+spaces), but the processing breaks the link to the following: Special:CustomNeed%3Fpage_title%3DName%2Bwith%2Bspaces. This way, the link doesn't work.
After reading this question, I thought there is a way to turn the processing off, however, I have no clue how. Do I have to add/edit something in the LocalSettings.php?

A: You can't specify query parameters for internal links so use full URLs instead: http://example.com/wiki/Special:CustomNeed?page_title=Name+with+spaces
See Manual:Interface/Sidebar for details.

A: You can do that by setting $wgRawHtml = true; in LocalSettings.php:
Then, you will be able to add your html links (or any code you wan't) within <html></html> tags.
Please keep in mind that it can be dangerous if your wiki is public, because people can insert any javascript code they want there.
Read more here


text:
Q: Cannot use Task to make TimelineEntry inside getTimeline I am making widgets for WatchOS and i am struggling with the getTimeline and getSnapshot functions for TimelineProvider
The error: Type of expression is ambiguous without more context
This is the code inside getTimeline
Task {
    let price = try? await service.fetchPrices()
    if let priceSingle = price?.current {
       let entry = Entry(date: Date(), price: priceSingle, priceItems: price?.today!, isPlaceholder: false)
       let timeline = Timeline(entries: [entry], policy: TimelineReloadPolicy.after(Date().addingTimeInterval(60*30)))
       completion(timeline)
    } else {
         let entry = Entry.placeholder
         let timeline = Timeline(entries: [entry], policy: .after(Date().addingTimeInterval(60 * 2)))
         completion(timeline)
        }
    }

The error happend when i added this line
let entry = Entry(date: Date(), price: priceSingle, priceItems: price?.today!, isPlaceholder: false)

Works fine when creating widgets for iOS.
Maybe its a bug?

A: It's because of price?.today! you cannot force wrapped optional like this, you need to write it like this (price?.today)!.
But this will crash your app if it's nil. So better to optionally wrapped using the nil-coalescing operator.
price?.today ?? [] //If it is an array
price?.today ?? "" //If it is a string

You haven't added Entry so I'm not sure what is the type of todayproperty but you can pass some default value after the ?? like above.


text:
Q: Watin behaviour in debug mode is different than in normal mode Im testing the WatiN library using this simple code:
using (var browser = new IE("http://www.google.de"))
{
    browser.TextField(Find.ByName("q")).TypeText("WatiN");
    Button btn1 = browser.Button(Find.ById("gbqfba"));
    btn1.Click();
    while (!browser.ContainsText("watin.org"))
    {
        System.Threading.Thread.Sleep( 500 );
        btn1.Click();
    }
}

Anyway it works fine when i run it in debug mode having a breakpoint somewhere, but as soon as i run in release mode it types the desired text but the button doesnt seem to be clicked, so i have the search field with the text in it, and i dont get any search results.
Any known issues about this? any Ideas?
Thank you

A: You need to insert a wait in your code till everything is loaded, then you will be able to find controls.
It works in debug mode because, while debugging with breakpoints it get time things to be fully loaded.

A: I'm a WatiN newbie, too, and it took me a while before I got this to work. First, read this solution:
WatiN clicking a button
You might have to try different ways of implementing the solution to get it to work for you. For example:
First I put the line
browserInstance.NativeDocument.Body.SetFocus(); // set focus befor u click

before the "click" action, but that worked only in Debug mode (My code didn't work at all before, so getting it to work in Debug mode was progress).
Then I put the line before each item to get it to work in Run mode:
browserInstance = new IE(@"http://www.google.com");

TextField criteria = browserInstance.TextField(tf => tf.Name == "q");

browserInstance.NativeDocument.Body.SetFocus(); // set focus befor u click
criteria.TypeText("Come Jam With Us");

browserInstance.NativeDocument.Body.SetFocus(); // set focus befor u click
browserInstance.Button(Find.ById("gbqfb")).Click();

I'm not sure why this works, but I hope it helps.


text:
Q: Reactjs, Styling each element of array with different styles I want to create an array with some elements and then iterate (with .forEach or .map) it.
but each of array elements must have different style. for example I have an array like that:
["johnny red", "Stephanie blue", "Hans green", "Fifty Shades Of grey :d"]

also, I want reuse some of array's individual elements in another component.
how can i do that?
(imagine that last word in each element is a individual style e.g. background-color or color,)
Can you help me?
please give me an advice, what would I do?

A: There are many ways to achieve this, the key difference is how you are representing your value-style pairs.
Eventually, you need to map the values to their styles.
For example:
const myStyles = {
  'johnny red': { color: 'red' },
  'Stephanie blue': { color: 'blue' },
  'Hans green': { color: 'green' },
  'Fifty Shades Of grey :d': { color: 'pink' }
};

export default function App() {
  return (
    <FlexBox>
      <FlexItem>
        {Object.entries(myStyles).map(([key, style]) => (

            {key}

        ))}
      </FlexItem>
    </FlexBox>
  );
}

A: You mean something like this? The snippet is below and here is the codepen texample: https://codepen.io/tormod17/pen/apvXoW?editors=0010
Also, have you considered incorporating styled components with react? It could help with this project. https://www.styled-components.com/docs/basics
   {children.map(element => {
   return (
      <element.type
       {...element.props}
       style={{
         height: '33%',
       }}
      />
   )
 })}

This is from another project:
          import * as React from "react";
          import { IAddressListProps } from '../../detailPage/components/interfaces/IAddressListProps';
          import { config } from "../../config";

          export class PrintAddressList extends React.Component<IAddressListProps, {}>{
            constructor(props: IAddressListProps) {
              super(props);
            }
            private createAddressCard = () => {
              let parent = [];
              this.props.items.map((address) => {
                parent.push(

                  {config.colNames.addressList.clmnAddressType}:
                  {address.Adressart}

                  {config.colNames.addressList.clmnCompanyName}:
                  {address.Firma}

                  {config.colNames.addressList.clmnPlaceName}:
                  {address.Ort}

                  {config.colNames.addressList.clmnZipCode}:
                  {address.PLZ}

                  {config.colNames.addressList.clmnTelephone}:
                  {address.Telefon}

);
              });
              return parent;
            }

            public render(): React.ReactElement<IAddressListProps> {
              return (

                  {this.createAddressCard()}

              );
            }
          }

A: It's not very clear what you want, but you can attach styles to components like this:

const values = [
  {
    text: "one",
    css: { color: 'blue' }
  },
  {
    text: "two",
    css: { color: 'red' }
  },
];

const Test = props => {
  const { values } = props;

  return (

{values.map(
      (value, i) =>
{value.text}

    )}

  );
}

ReactDOM.render(
  <Test values={values} />,
  document.getElementById("react")
);


text:
Q: probability that a five-card poker hand contains a straight flush
What is the probability that a five-card poker hand contains a
  straight flush, that is, five cards of the same suit of consecutive
  kinds (i.e. <1-2-3-4-5, 2-3-4-5-6, …, 9-10-J-Q-K, 10-J-Q-K-1>?

My attempt: We need to chose 5 cards in the same suit, each suit contains 13 different cards so $\binom{13}{5}$, we only need it to be in the same suit so we chose one suit out of 4, that is $\binom{4}{1}$, total number of outcomes is $\binom{52}{5}$, Now there are only 13 situation where we have consecutive kinds, and total number of how we can chose 5 out of 13 regardless of order is $\binom{13}{5}$
Hence, the probability is:
$$\frac{\binom{13}{5}\binom{4}{1}}{\binom{52}{5}} \cdot \frac{13}{\binom{13}{5}} = 2.00 \times10^{-5}  $$
However, i think there's something missing or i have made a mistake, can anyone verify my solution ?


text:
Q: Best way to store 1 billion+ posts? Hey there I am working on a site that collects a lot of data via scraping.  For each data created i'm adding it to WP as a CPT.  The problem is I'm going to reach around 1 billion rows eventually, and i'm worried it will slow down the site.
Most of these data will only be displayed on category type pages.  With about 1000-10,000 posts per page.
My solution right now is to store the posts data as text in the post meta, then parse it into json to create HTML elements.  The problem with this is that it makes it hard to do analysis charts since i can't query all the posts as they are stored as huge text strings in meta data.
The other idea i had was to make a table for each category post, and then add the above data as posts to the table.  This way i would have about 10,000 tables and it would be faster to iterate?
Is there a name for this technique where you make a lot of tables?  Is there a best practice for adding it to WP?
Thanks for any help!

A: I don't know about how long it will take to create that many tables, especially if you do it in one go, but you can use $wpdb to handle the creation. There's an article on the Codex regarding creating custom tables, https://codex.wordpress.org/Creating_Tables_with_Plugins
And it crossed my mind that perhaps using some external tool to handle the database querying could potentially make the queries run faster. Elasticsearch (I'm not an affiliate), in tandem with ElasticPress, is the only one I've heard of, but I'm sure there's plenty of similar tools. Maybe that could be worth checking out?


text:
Q: Custom Post Type templates not found I have created a custom post type for cars which I have bootstraped off this tutorial. I am having a problem where I am getting 404 returned instead of archive-car.php and single-car.php. I have also tried to add the plural versions to the template names, however, no success. What could be wrong? Am I missing something?
<?php
if( ! function_exists( 'quote_create_post_type' ) ) :
    function quote_create_post_type() {
        $labels = array(
            'name' => 'Cars',
            'singular_name' => 'Car',
            'add_new' => 'Add Car',
            'all_items' => 'All Cars',
            'add_new_item' => 'Add Car',
            'edit_item' => 'Edit car',
            'new_item' => 'New car',
            'view_item' => 'View car',
            'search_items' => 'Search cars',
            'not_found' => 'No cars found',
            'not_found_in_trash' => 'No cars found in trash',
            'parent_item_colon' => 'Parent car'
            //'menu_name' => default to 'name'
        );
        $args = array(
            'labels' => $labels,
            'public' => true,
            'has_archive' => true,
            'publicly_queryable' => true,
            'query_var' => true,
            'rewrite' => true,
            'capability_type' => 'post',
            'hierarchical' => false,
            'supports' => array(
                'title',
                'editor',
                'excerpt',
                'thumbnail',
                //'author',
                //'trackbacks',
                //'custom-fields',
                //'comments',
                'revisions',
                //'page-attributes', // (menu order, hierarchical must be true to show Parent option)
                //'post-formats',
            ),
            'menu_position' => 5,
            'exclude_from_search' => true,
            'register_meta_box_cb' => 'quote_add_post_type_metabox'
        );
        register_post_type( 'car', $args );
        //flush_rewrite_rules();

        register_taxonomy( 'quote_category', // register custom taxonomy - category
            'car',
            array(
                'hierarchical' => true,
                'labels' => array(
                    'name' => 'Brands',
                    'singular_name' => 'Brand',
                )
            )
        );

    }
    add_action( 'init', 'quote_create_post_type' );

    function quote_add_post_type_metabox() { // add the meta box
        add_meta_box( 'quote_metabox', 'Car Details', 'quote_metabox', 'car', 'normal' );
    }

    function quote_metabox() {
        global $post;
        // Noncename needed to verify where the data originated
        echo '<input type="hidden" name="quote_post_noncename" value="' . wp_create_nonce( plugin_basename(__FILE__) ) . '" />';

        // Get the data if its already been entered
        $quote_post_name = get_post_meta($post->ID, '_quote_post_name', true);
        $quote_post_desc = get_post_meta($post->ID, '_quote_post_desc', true);

        // Echo out the field
        ?>

                    Brand

                    <input type="text" name="quote_post_name" value="<?php echo $quote_post_name; ?>">

                    Description

                    <textarea name="quote_post_desc" class="large-text"><?php echo $quote_post_desc; ?></textarea>

    <?php
    }

    function quote_post_save_meta( $post_id, $post ) { // save the data

        /*
         * We need to verify this came from our screen and with proper authorization,
         * because the save_post action can be triggered at other times.
         */

        if ( ! isset( $_POST['quote_post_noncename'] ) ) { // Check if our nonce is set.
            return;
        }

        if( !wp_verify_nonce( $_POST['quote_post_noncename'], plugin_basename(__FILE__) ) ) { // Verify that the nonce is valid.
            return $post->ID;
        }

        // verify this came from the our screen and with proper authorization,
        // because save_post can be triggered at other times
        if( !wp_verify_nonce( $_POST['quote_post_noncename'], plugin_basename(__FILE__) ) ) {
            return $post->ID;
        }

        // is the user allowed to edit the post or page?
        if( ! current_user_can( 'edit_post', $post->ID )){
            return $post->ID;
        }
        // ok, we're authenticated: we need to find and save the data
        // we'll put it into an array to make it easier to loop though

        $quote_post_meta['_quote_post_name'] = $_POST['quote_post_name'];
        $quote_post_meta['_quote_post_desc'] = $_POST['quote_post_desc'];

        // add values as custom fields
        foreach( $quote_post_meta as $key => $value ) { // cycle through the $quote_post_meta array
            // if( $post->post_type == 'revision' ) return; // don't store custom data twice
            $value = implode(',', (array)$value); // if $value is an array, make it a CSV (unlikely)
            if( get_post_meta( $post->ID, $key, FALSE ) ) { // if the custom field already has a value
                update_post_meta($post->ID, $key, $value);
            } else { // if the custom field doesn't have a value
                add_post_meta( $post->ID, $key, $value );
            }
            if( !$value ) { // delete if blank
                delete_post_meta( $post->ID, $key );
            }
        }
    }
    add_action( 'save_post', 'quote_post_save_meta', 1, 2 ); // save the custom fields
endif; // end of function_exists()

if( ! function_exists( 'view_quotes_posts' ) ) : // output
    function view_quotes_posts($do_shortcode = 1, $strip_shortcodes = 0 ) {

        $args = array(
            'posts_per_page'     => 10,
            'offset'          => 0,
            //'category'        => ,
            'orderby'         => 'menu_order, post_title', // post_date, rand
            'order'           => 'DESC',
            //'include'         => ,
            //'exclude'         => ,
            //'meta_key'        => ,
            //'meta_value'      => ,
            'post_type'       => 'car',
            //'post_mime_type'  => ,
            //'post_parent'     => ,
            'post_status'     => 'publish',
            'suppress_filters' => true
        );

        $posts = get_posts( $args );

        $html = '';
        foreach ( $posts as $post ) {
            $meta_name = get_post_meta( $post->ID, '_quote_post_name', true );
            $meta_desc = get_post_meta( $post->ID, '_quote_post_desc', true );
            $img = get_the_post_thumbnail( $post->ID, 'medium' );
            if( empty( $img ) ) {
                $img = '';
            }

            if( has_post_thumbnail( $post->ID ) ) {
                $img = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail' );
                $img_url = $img[0];

                //the_post_thumbnail( 'thumbnail' ); /* thumbnail, medium, large, full, thumb-100, thumb-200, thumb-400, array(100,100) */
            }

            $content = $post->post_content;
            if( $do_shortcode == 1 ) {
                $content = do_shortcode( $content );
            }
            if( $strip_shortcodes == 1 ) {
                $content = strip_shortcodes( $content );
            }
            $content = wp_trim_words( $content, 30, '...');
            $content = wpautop( $content );

            $html .= '

'.$post->post_title.'

Name: '.$meta_name.'

Description: '.$meta_desc.'

'.$img.'

'.$content.'

            ';
        }
        $html = '
'.$html.'
';
        return $html;
    }
endif; // end of function_exists()
?>

Further Info
All I am doing is extending the TwentyFifteen theme.

A: If I had to put money on this, I would say that you have not updated your permalinks! Simply go to Settings >> Permalinks >> Post Name.
The codex provides a little more information:

Note: In some cases, the permalink structure must be updated in order for the new template files to be accessed when viewing posts of a custom post type. To do this, go to Administration Panels > Settings > Permalinks, change the permalink structure to a different structure, save the changes, and change it back to the desired structure.


text:
Q: What is the best method for saving shopping cart orders to a database? Saving the items as an array in one row or in multiple rows? Just looking for advice here. I have a shopping cart website. I will post my php that receives the items and prints them out. However, I am looking to store these orders in my database. Should I... Can I... save multiple items under one row, in one cell like this?
{"114":{"id":"114","name":"Raskals Lemon","quantity":1,"price":15,"weight":1,"shopid":"1","shopname":"MMD","type":"Sativa","size":"---","strain":"Sativa","thc":"---","subtype":"Flower"},"117":{"id":"117","name":"Nectarine","quantity":1,"price":15,"weight":1,"shopid":"1","shopname":"MMD","type":"Sativa","size":"---","strain":"Sativa","thc":"---","subtype":"Flower "}}

Or would it be better to save all the items and there details as multiple rows and use something like a 'order number' to tie the rows together in future  queries?
Here is the basic php, if it pertains at all to the question.
$order = '';

  for($i=1; $i < $content['itemCount'] + 1; $i++) {

    $item_name = 'item_name_'.$i;
    $item_quantity =  'item_quantity_'.$i;
    $item_price = 'item_price_'.$i;
    $item_weight = 'item_weight_'.$i;
    $item_id = 'item_id_'.$i;
    $item_shop = 'item_shopid_'.$i;
    $item_type = 'item_type_'.$i;
    $item_shopname = 'item_shopname_'.$i;
    $item_size = 'item_size_'.$i;
    $item_strain = 'item_strain_'.$i;
    $item_subtype = 'item_subtype_'.$i;

$order .= <<<EOT

$content[$item_name]

Quantity: $content[$item_quantity]

Grams: $content[$item_weight]

Catagory: $content[$item_type]

Sub Catagory: $content[$item_subtype]

Size: $content[$item_size]

Strain: $content[$item_strain]

$currency$content[$item_price].00

            $i

EOT;
}

A: I see two tables here (third one is what you already have, I assume):

*

*order table is a place where you store every orders. One order = one record in that table. You can have some order-related details here, like delivery address, delivery method etc.

*order_item table is a place where you store each ordered item. This has relation of many to one. Many ordered items in one order. You have item-releated details here like quantity of given product, size and other stuff.

A: from a real world understanding there is a concept of order header and order lines. So you can design your underlying tables in two different tables with different granularity. For e.g.
Order header table - should contain only the parent information like order number, customer number, order date etc.
Order Line Item table - should contain all the child items, for each order number there could be 1 or more rows with information like order number, item number, quantity etc.
Hope you find this useful.Thanks


text:
Q: openresty nginx conf to capture location starting with a specific value I am using openresty and in my default.conf, I am checking for certain APIs that if the request is for this API, then I need to send the request to a backend as is. I am doing it like this:
location = /y/products/ {
  include /xxx/yyy/some.conf;
}

This works fine. However, I want to be able to do something similar for an API call that starts with /y/products
so, lets say my API could be to something like:
y/products/00000001-2aef-13ef-b12f-8b7e4f3f4e1a/check?val=abcdefgh

How do I change the location check syntax above to capture requests of this form, so I can decide what to do for those API calls?

A: Remove the equal sign:
location /y/products/ {
  ...
}

A location can either be defined by a prefix string, or by a regular expression.

Also, using the "=" modifier it is possible to define an exact match of URI and location.

https://nginx.org/en/docs/http/ngx_http_core_module.html#location


text:
Q: How to select the last record of each ID I need to extract the last records of each user from the table. The table schema is like below.
mytable

product | user_id |
-------------------
   A    |   15    |
   B    |   15    |
   A    |   16    |
   C    |   16    |
-------------------

The output I want to get is
product | user_id |
-------------------
   B    |   15    |
   C    |   16    |

Basically the last records of each user.
Thanks in advance!

A: You can use a window function called ROW_NUMBER.Here is a solution for you given below. I have also made a demo query in db-fiddle for you. Please check link Demo Code in DB-Fiddle
WITH CTE AS
(SELECT product, user_id,
       ROW_NUMBER() OVER(PARTITION BY user_id order by product desc)
       as RN
FROM Mytable)
SELECT product, user_id FROM CTE WHERE RN=1 ;

A: You can try using row_number()
select product,iserid
from
(
select product, userid,row_number() over(partition by userid order by product desc) as rn
from tablename
)A where rn=1

A: There is no such thing as a "last" record unless you have a column that specifies the ordering.  SQL tables represent unordered sets (well technically, multisets).
If you have such a column, then use distinct on:
select distinct on (user_id) t.*
from t
order by user_id, <ordering col> desc;

Distinct on is a very handy Postgres extension that returns one row per "group".  It is the first row based on the ordering specified in the order by clause.

A: You should have a column that stores the insertion order. Whether through auto increment or a value with date and time.
Ex:

autoIncrement
produt
user_id

1
A
15

2
B
15

3
A
16

4
C
16

SELECT produt, user_id FROM table inner join
     ( SELECT MAX(autoIncrement) as id FROM table group by user_id ) as table_Aux
     ON table.autoIncrement = table_Aux.id


text:
Q: PHP file_get_contents() failed to open stream error I am trying to connect to the Amazon Flexible Payments sandbox, and I made a request string as they instruct in their documentation.  Now I am trying to send a request to their service by using the file_get_contents() PHP function, but I get this error:
[function.file-get-contents]: failed to open stream: HTTP request failed! HTTP/1.1 404 Not Found\r\n in file_name.php on line 84

Any idea why that might happen?
Here is the URL I am sending:
https://authorize.payments-sandbox.amazon.com/cobranded-ui/actions/start?SignatureVersion=2&returnUrl=http%3A%2F%2Fwww.problemio.com%2Fproject.php%3Fproject_id%2FProject_name%3 &paymentReason=donation&callerReference=YourCallerReference&callerKey=not_shown&transactionAmount=4.0&pipelineName=SingleUse&Signature=not_shown_in_SO%3D%3D

A: You've got spaces in it: …SignatureVersion=2 &returnUrl=… and …Project_name%3 &paymentReason…

A: You've left a space in your URL which breaks it:
.../start?SignatureVersion=2 &returnUrl=http%3A%2F%2Fwww.problemio.c...


text:
Q: Approximating the expectation of trace inverse of random Gaussian combination Consider a random matrix $A \in \mathbb{R}^{m\times n}$ with i.i.d. entries, with mean zero and variance 1 and $m <n $. Has anyone studied this expectation in asymptotics $$E_{A}(\mathrm{Tr}( (A^T A + \lambda \mathrm{Id})^{-1} A^T A))?$$
Any papers/resources would be helpful, ideal fidnings would be $m,n \mapsto \infty$ as $\frac{m}{n} \mapsto 0$, but anything would be great.

A: The answer is similar to that of your earlier question:
For $m,n\gg 1$, and $m/n\equiv r\in (0,1)$ fixed, an integration over the Marchenko–Pastur distribution gives (with $x_\pm=(1\pm\sqrt{r})^2$)
$$\lim_{m,n\rightarrow\infty}\mathbb{E}\bigl[m^{-1}\mathrm{Tr}\,\bigl((n^{-1}AA^\top + \lambda I)^{-1}n^{-1}AA^\top\bigr)\bigr]=\int_{x_-}^{x_+} \frac{x}{x+\lambda}\frac{\sqrt{\left(x_+-x\right) \left(x-x_-\right)}}{2 \pi  r x}\,dx$$
$$\qquad=\frac{1}{2r}\bigl(\lambda+r+1-\sqrt{\lambda^2+2 \lambda (r+1)+(r-1)^2}\bigr).$$
The rescaling of $AA^\top$ by a factor $1/n$ is needed for a $\lambda$-dependent answer in the large $n$ limit.
In the limit $r\rightarrow 0$ this tends to $1/(1+\lambda)$.


text:
Q: Creating a subset of a dataset by taking the mean values for each date in R Using Rstudio with tidyverse plugin, using ggplot2 to plot:
Say we have a dataset called SoccerTeam, this data set consists of variables: Location, Goals, YearPlayed, etc... and each data entry is assigned to a game, so the game was played at Location X, they scored Y Goals, It was played in year 19XX.
In the YearPlayed we have all the years the team has been active for, say years 1950 to 2020 and there is a whole season of data for each year.
Lets say that 2002 has 30 games, so there would be 30 data entries that have YearPlayed = 2002.
Our goal is to plot over time how many goals the team has scored. If we take into account every single game from each year and plot it over the 70 years of play, our graph would be very messy and hard to interpret. To tackle this issue, I would like to take the average goals for each year and plot that over time. How would i do this?

A: If you need a general introduction to data wrangling in R, I recommend R for Data Science.  That said, you need to group by the column YearsPlayed, and then compute the mean for each year.  Then, pipe it into the plot commands.  The %>% symbol send the left side's output into the right side.  So you can chain them together like this:
SoccerTeam %>%
  group_by(YearPlayed) %>%
  summarize(Goals = mean(Goals)) %>%
  ggplot(aes(x=YearPlayed, y=Goals) +
  geom_line()


text:
Q: C# XDocument Read all Nodes from XML-File I have an XML-file like this:
<Inventory>
<Item>
<Name>Super Mario Bros</Name>
<Count>14</Count>
<Price>29,99</Price>
<Comment><No Comments on this Product></Comment>
<Artist>N/A</Artist>
<Publisher>Nintendo</Publisher>
<Genre>Video Games</Genre>
<Year>1985</Year>
<ProductID>001</ProductID>
</Item>
<Item>
<Name>The Legend of Zelda</Name>
<Count>12</Count>
<Price>34,99</Price>
<Comment><No Comments on this Product></Comment>
<Artist>N/A</Artist>
<Publisher>Nintendo</Publisher>
<Genre>Video Games</Genre>
<Year>1986</Year>
<ProductID>002</ProductID>
</Item>
<Item>
<Name>Street Fighter</Name>
<Count>82</Count>
<Price>19,99</Price>
<Comment><No Comments on this Product></Comment>
<Artist>N/A</Artist>
<Publisher>Nintendo</Publisher>
<Genre>Video Games</Genre>
<Year>1987</Year>
<ProductID>003</ProductID>
</Item>
</Inventory>

(There are more Items, but they are all the same, except for the values.)
Now I want to iterate through each Item and extract every value from each node. Here's what I've tried so far:
        var xDocument = XDocument.Load(FilePath_CSVToXML);
        string xml = xDocument.ToString();
        StringBuilder sb = new StringBuilder();

        foreach (XElement xe in xDocument.Descendants("Inventory")) {
            sb.Append(xe);
        }

        Console.WriteLine(sb.ToString());
        Console.ReadLine();

The code above properly displays the XML-file, but it keeps the Nodes. (Name, Count, Price, etc.) I only want the values.

A: You need to use the Value property, i.e. sb.Append(xe.Value).

A: Try code below.  The innertag of Comment doesn't need angle brackets so remove.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication49
{

    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XDocument doc = XDocument.Load(FILENAME);
            var results = doc.Descendants("Item").Select(x => new {
                name = (string)x.Element("Name"),
                count = (int)x.Element("Count"),
                price = (decimal)x.Element("Price"),
                comment = (string)x.Element("Comment"),
                artist = (string)x.Element("Artist"),
                publisher = (string)x.Element("Publisher"),
                genre = (string)x.Element("Genre"),
                year = (int)x.Element("Year"),
                productID = (string)x.Element("ProductID")
            }).ToList();

        }
    }

}


text:
Q: How to make a bubble chart from CSV file? So I have the following file, data.csv. Which looks like this:
TestID,Cronbach,Percent Correct,Population
12416,0.866,0.17,26
12421,0.945,0.21,8
12385,0.777,0.40,258
12412,0.85,0.44,34
12407,0.831,0.45,48

And I want it to look like this:
[
["Test ID", "Cronbach", "Percent Correct", "Population"],
["12416", 0.866, 0.17, 26],
["12421", 0.945, 0.21, 8],
["12385", 0.777, 0.40, 258],
["12412", 0.85, 0.44, 34],
["12407", 0.831, 0.45, 48]
]

Is there a way I can make a conversion code in php to convert my CSV file to look like the above format. I need this because I want to put the code into a Google Bubble Chart.
Q: How might I go about making the code that can convert this to an acceptable format to fit Googles bubble chart?

A: The following example demonstrates how to parse csv file content:
function prepareChartData(data) {
    var items = [];
    var lines = data.split(/\r\n|\n/);

    lines.forEach(function(line,i){
         if(line.length > 0){
             var item =  line.split(',');
             if(i > 0){
                 item[1] = parseFloat(item[1]);
                 item[2] = parseFloat(item[2]);
                 item[3] = parseInt(item[3]);
             }
             items.push(item);
         }
    });
    return items;
}

Result
[
  [
    "TestID",
    "Cronbach",
    "Percent Correct",
    "Population"
  ],
  [
    "12416",
    0.866,
    0.17,
    26
  ],
  [
    "12421",
    0.945,
    0.21,
    8
  ],
  [
    "12385",
    0.777,
    0.4,
    258
  ],
  [
    "12412",
    0.85,
    0.44,
    34
  ],
  [
    "12407",
    0.831,
    0.45,
    48
  ]
]

Complete example
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(function(){
    readChartData()
    .then(prepareChartData)
    .done(drawChart);
});

function drawChart(items) {

    var data = google.visualization.arrayToDataTable(items);
    var options = {
        title: 'Chart'
    };
    var chart = new google.visualization.BubbleChart(document.getElementById('chart_div'));
    chart.draw(data, options);
}

function readChartData(complete)
{
    return $.ajax({
        type: "GET",
        url: "data.csv",
        dataType: "text"
    });
}

function prepareChartData(data) {
    var items = [];
    var lines = data.split(/\r\n|\n/);

    lines.forEach(function(line,i){
         if(line.length > 0){
             var item =  line.split(',');
             if(i > 0){
                 item[1] = parseFloat(item[1]);
                 item[2] = parseFloat(item[2]);
                 item[3] = parseInt(item[3]);
             }
             items.push(item);
         }
    });
    return items;
}


text:
Q: How to make integer array of id's inside strings.xml? I am new at Android development. I want to make an app that have a module in which I displayed certain text files over text View. And I store these files in Raw folder, but I want to declare those files id's as arrays in Strings.xml so that I can save my efforts.
I saw some people referencing as @drawable/filename but @Raw/filename is giving error. Can anyone give me assist to get out of this problem.

A: Well you just need to declare array in your styles.xml
 <int-array name="ids">
            <item>1</item>
            <item>2</item>
            <item>3</item>
            <item>4</item>
            <item>45</item>
            <item>5</item>
        </int-array>

And to access it
String [] mIdsArray= getResources().getStringArray(R.array.ids);

This method is to read raw file
public static String readRawTextFile(Context ctx, int resId)
{
    InputStream inputStream = ctx.getResources().openRawResource(resId);

    InputStreamReader inputreader = new InputStreamReader(inputStream);
    BufferedReader buffreader = new BufferedReader(inputreader);
    String line;
    StringBuilder text = new StringBuilder();

    try {
        while (( line = buffreader.readLine()) != null) {
            text.append(line);
            text.append('\n');
        }
    } catch (IOException e) {
        return null;
    }
    return text.toString();
}

use the above code in your project,
Thanks!


text:
Q: I am making a website in angularjs and using ngRoutes. My query is about removing # fromt the url Following is my code where I am configuring my routes:

/**
 * Main AngularJS Web Application
 */
var app = angular.module('chocomelte', [
  'ngRoute'
]);

/**
 * Configure the Routes
 */
app
.controller('HomeCtrl',HomeCtrl)
.controller('AboutCtrl',AboutCtrl)
.config(['$routeProvider','$locationProvider', function ($routeProvider, $locationProvider) {

  $locationProvider.html5Mode(true);

  $routeProvider
    .when("/", {
        templateUrl: "partials/home.html",
        controller: "HomeCtrl"
    })
    .when("/about", {
        templateUrl: "partials/about.html",
        controller: "AboutCtrl"
    })
}]);

This removes # from my url. When I try to go to the /about route by clicking on a button in my UI, it works fine. But when I manually try to type the URL and go to it or refresh the page on /about url, I get this error:
500 internal server error.
I am not using node in the backend. A simple website using angular in the frontend. How to I configure this on the client side?

A: Make sure you're setting the base url with this meta tag:
<base href="/my-base">

Also, you may have to implement URL rewriting on your server when using html5 mode, to make sure that any requests are redirected to the root of your application instead of being interpreted as GET requests.
From the documentation:

Using this mode requires URL rewriting on server side, basically you have to rewrite all your links to entry point of your application

A: I am using Apache server. Finally fixed it. Had to rewrite the urls in the .htaccess file as follows:
Options +FollowSymLinks

<ifModule mod_rewrite.c>
    RewriteEngine On
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} !index
    RewriteRule (.*) index.html [L]
</ifModule>

Had to specify index.html as the entry point.