text:
Q: Getting Postgres to truncate values if necessary? If I create a table mytable with column data as varchar(2) and then insert something like '123' into the column, postgres will give me an error for Value too long for type.
How can I have Postgres ignore this and truncate the value if necessary?
Also, I do not (when creating the query) know the actual size of the data column in mytable so I can't just cast it.

A: According to the postgres documentation, you have to explicitly cast it to achieve this behavior, as returning an error is a requirement of the SQL standard.  Is there no way to inspect the table's schema before creating the query to know what to cast it to?

A: Use text type with trigger instead:
create table mytable (
  data text
);

create or replace function mytable_data_trunc_trigger()
  returns trigger language plpgsql volatile as $$
begin
  NEW.data = substring(NEW.data for 2);
  return NEW;
end;
$$;

create trigger mytable_data_truncate_trigger
  before insert or update on mytable for each row
  execute procedure mytable_data_trunc_trigger();

insert into mytable values (NULL),('1'),('12'),('123');

select * from mytable;

 data
------

 1
 12
 12
(4 rows)

A: Easiest is just substring
INSERT INTO mytable (data) VALUES (substring('123' from 1 for 2));

A: You could change the datatype to varchar, and then use a trigger to enforce the two char constraint.


text:
Q: Two definitions of central extensions of simplicial groups This is a cross-post from MSE.
Let $\overline W$ be a classifying space functor on $\mathrm{sGrp}$ with $G$ be a corresponding left adjoint (Kan's loop group).
Def 1 : a sequence of maps $A\to E\to H$ in $\mathrm{sGrp}$ is called the central extension (of $H$ by $A$) if
$$
\overline W E\to \overline W H\to \overline W^2 A
$$
is a fiber sequence in $\mathrm{sSet}$.
Def 2 :a sequence of maps $A\to E\to H$ in $\mathrm{sGrp}$ is called the central extension (of $H$ by $A$) if for any $n$
$$
A_n \to E_n \to H_n
$$
is the central extension of groups.
Question : are these two definitions equivalent ?
Certainly, any central extension in sense of (2) produces a fiber sequence
$$
\overline W A\to \overline W E\to \overline W H
$$
which can be shown to be a $\overline W A$-principal fibration (I believe that principal action should be induced from $A\times E\to E, \ (a,e)\mapsto ae$), hence produces a central extension in sense of definition (1).
But what about the opposite direction ? My only idea is to try to cook up a set of 2-cocycles $c_n\in[K(H_n,1),K(A_n,2)]$ from a classifying map $\overline W H\xrightarrow w \overline W^2 A$. Weak equivalence $\overline W H\simeq d N H$ may help ($N$ is a nerve functor: $(N H)_{n,m}=K(H_n,1)_m$ and $d$ is a diagonal of bisimplicial set), but I have no idea, how to extract $K(A_n,2)$ from $\overline W^2 A$.
EDIT
As Yonatan mention, fiber sequence in definition (1) is in fact homotopy fiber sequence, actually in (1) I think about arbitrary simplicial map $\overline W H\xrightarrow w \overline W^2 A$ with a homotopy fiber (in $\mathrm{sGrp}$) $\overline W E$. In the same manner I thought about equivalence of definitions, i.e. (1) and (2) are equivalent if there exists a (homotopy) commutative diagram
$\require{AMScd}$
\begin{CD}
        A @>>> E' @>>> H' \\
       @|    @VVV @VV{\simeq}V \\
        A @>>> E @>>> H
    \end{CD}
Here bottom row is a central extension of simplicial groups in sense of (2) and top row is obtained, as in Jon's comment, by pulling back the universal bundle $A\to WA\to\overline W A$ along the adjoint map $H'=G\overline W H\to \overline W A$. Basically this is the same as saying that $E'$ is a homotopy fiber of $H'\to \overline W A$. So my problem is in fact:

*

*given $E'$, construct $E$

*construct a map $E'\to E$ making the diagram above homotopy commutative.
Finally, $A$ is assumed to be a simplicial abelian group, otherwise, as mentioned it should be possible to construct some weird example with $E_2$-space.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Active Directory Domain Controller setup using external TLD (Godaddy)? I have been given a task to integrate Active Directory in order to authenticate users and manage group policies. My end-goal is to allow users to enroll their devices (Mac and PC) into Active Directory using their company email address (ie. bob@example.com).
Currently, our company uses Godaddy to manage our DNS for our TLD (example.com). I have used a subdomain to allow public access to our domain controller (dc.example.com - Windows Server 2019). Now, because I've made the Domain Controller a subdomain of example.com, when I create an AD user, I can only register them in the dc.example.com namespace. Rather, I want users to be able to login using the top-level domain example.com.
I have been reading up on domain naming best-practices and everything tells me to use a subdomain rather than duplicating the root domain name. I have actually done the latter... and it works. However, it creates conflicts when I am trying to register Mac computers to Active directory. I don't know why.
I dont want to move away from Godaddy since we have many records stored there, but there MUST be an easier way to do this?


text:
Q: calculate time difference I have a jQuery clock that gives the time from 00:00 to 23:00.
Now I want to calculate the time difference between two times. Suppose the "in" time is 11:00, and the "out" time is 16:00.
How do I calculate the time difference in javascript?

A: You can use Date and setHours like that:
var first = new Date();
first.setHours(0, 11, 0, 0);

var second = new Date();
second.setHours(0, 16, 0, 0);

alert("Diff in seconds: " + (second - first));

A: You may prefer to use a third party JS date library such as Datejs.

A: As suggested from Barry, I would take a look at Datejs.
In the documentation page if you find the word "difference" you could find a guy asking for the same problem. As suggested in the comment reply you should use the TimeSpan class.
Hope it helps!

A: you should try momentjs, i think its much better than datejs.
According to momentjs example:
var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1


text:
Q: UISearchBar going to the view's top when I click on it I have a UITableView which doesn't reach the entire view. Approximatively, the UITableView is two times smaller than the view.
Then, I add "Search Bar and Search Display Controller" to the UITableView from the Object library. So, to visualize, the searchBar appears at the screen's center.
Here's my view :

My problem : When I click into the search field to do my research, the searchBar is going to the top of the view, in place of the navigation bar ! And the transition is very awful... How can I constraint the searchBar to stay in its initial place ?

A: The problem is related to the search display controller. You don't have the control over the animation and it doesn't seem to handle it well when there's a view sitting on top of your TableView. We had the same exact problem and the easiest way we fixed it is by replacing the Search Display Controller by a simple Search Bar in the Storyboard.
That means your class will now have to implement the delegate method of the search bar to work properly.
To animate properly, simply override the searchBarTextDidBeginEditing and searchBarTextDidEndEditing like so:
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
CGRect tableViewFrame = self.tableView.frame;
tableViewFrame.origin.y = tableViewFrame.origin.y - self.yourHeaderView.bounds.size.height;
[UIView animateWithDuration:0.25
                 animations:^{ self.tableView.frame = tableViewFrame; }];
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar {
CGRect tableViewFrame = self.tableView.frame;
tableViewFrame.origin.y = tableViewFrame.origin.y + self.yourHeaderView.bounds.size.height;
[UIView animateWithDuration:0.25
                 animations:^{ self.tableView.frame = tableViewFrame; }];
}

Simply put, you just move the table view frame over the view based on it's height. The animation makes it smoother and cleaner.


text:
Q: Как сделать правильный Ajax запрос в WordPress? Нужно ли использовать localize_script()? Вот смотрите: есть Формы на главной странице, их 2 штуки.
1 форма просит номер телефона и имя.
Еще 1 форма обрабатывается уже другим обработчиком.
Обработчики находятся в файле ajax.php, оба в одном файле.
js с ajax обоих форм находятся в разных файлах
custom.js - тут находится только ajax код для 2 формы. Обрабатывается send_order.
main.js - тут находится ajax код для 1 формы. Обрабатывается send_mail. В этом же файле есть и другой код для сайта (возможно, он мешает?).
Сначала у меня не работала и 1-я форма, но когда я после подключения скрипта вписал функцию wp_localize_scipt(), форма заработала. Пытался сделать так же и со второй, не получилось. Вот подключение ниже.
wp_enqueue_script('dm-grata-script-main',get_template_directory_uri() . '/assets/js/main.js',array('jquery-my'),'',true);
wp_localize_script('dm-grata-script-main','myAjax',array(
    'url'=>admin_url('admin-ajax.php?action=send_mail'),
    'nonce'=>wp_create_nonce(),
));
wp_enqueue_script('dm-grata-script-custom',get_template_directory_uri() . '/assets/js/custom.js',array('jquery-my'),'',true);

wp_localize_script('dm-grata-script-custom','myAjax2',array(
    'url2'=>admin_url('admin-ajax.php?action=send_order'),
    'nonce2'=>wp_create_nonce(),
));

Вот обработчики. Файл подключается к functions.php
<?php
function send_mail() {

  /* Забираем отправленные данные */
  $client_name  = $_POST['client_name'];
  $client_phone = $_POST['client_phone'];

  /* Отправляем нам письмо */
  $emailTo  = 'grayd2@yandex.ru';
  $subject  = 'Test mail рассылки!';
  $headers  = "Content-type: text/html; charset=\"utf-8\"";
  $mailBody = "$client_name

 $client_phone";

  wp_mail($emailTo, $subject, $mailBody, $headers);

  /* Создаем новый пост-письмо */
  $post_data = array(
   'post_title'    => $client_name,
   'post_content'  => $client_phone,
   'post_status'   => 'publish',
   'post_author'   => 1,
   'post_type'     => 'mail',
  );

  wp_insert_post( $post_data );

  /* Завершаем выполнение ajax */
  die();

}

add_action("wp_ajax_send_mail", "send_mail");
add_action("wp_ajax_nopriv_send_mail", "send_mail");

Как вы видите, там два обработчика, первый работает. Массив $_POST не пустой и там есть все данные, которые мне нужны.
Но почему-то у 2-го обработчика, который send_order, массив $_POST пустой.
Вот второй
function send_order() {

  /* Забираем отправленные данные */
  $client_name_ord   = $_POST['client_name_ord'];
  $client_phone_ord  = $_POST['client_phone_ord'];
  $client_course_ord = $_POST['client_course_ord'];
  print_r($_POST);
  /* Отправляем нам письмо */
  $emailTo  = 'grayd2@yandex.ru';
  $subject  = 'Test mail рассылки!';
  $headers  = "Content-type: text/html; charset=\"utf-8\"";
  $mailBody = "$client_name_ord

 $client_phone_ord

 $client_course_ord";

  wp_mail($emailTo, $subject, $mailBody, $headers);

  /* Создаем новый пост-письмо */
  $post_data = array(
   'post_title'    => $client_name,
   'post_content'  => $client_phone,
   'post_status'   => 'publish',
   'post_author'   => 1,
   'post_type'     => 'orders',
  );
  wp_insert_post( $post_data );

  /* Завершаем выполнение ajax */
  die();

}

add_action("wp_ajax_send_order", "send_order");
add_action("wp_ajax_nopriv_send_order", "send_order");
?>

Вот js второй формы. ее обработчик возвращает пустой массив $_POST.
$('.ajax-form-inp-btn-2').click(function(e){
    e.preventDefault();
var orderForm = $('#take_form');
var formDataOrder = {
    client_name_ord:$('.ajax-form-inp-name-2').prop('value'),
    client_phone_ord:$('.ajax-form-inp-phone-2').prop('value'),
    client_course_ord:$('.ajax-form-inp-course-2').prop('value'),
    nonce:myAjax2.nonce2,
};
console.log(formDataOrder);
    $.ajax({
        url: myAjax2.url2,
        data: orderForm,
        type: 'POST',
        beforeSend: function () {
           orderForm.addClass('is-sending');
        },
        error: function (request, txtstatus, errorThrown) {
           console.log(request);
           console.log(txtstatus);
           console.log(errorThrown);
        },
        success: function (res) {
            console.log('success');
            console.log(res);
        }
    });
});

Вот js первой формы. Она работает.
          $(document).on('submit', '.ajax-form-1', function (e) {
                var formData = {
                  client_name: $('.ajax-form-inp-phone-1').prop('value'),
                  client_phone: $('.ajax-form-inp-name-1').prop('value'),
                  nonce:myAjax.nonce,
                };
                console.log(formData);
                $.ajax({
                  type: 'POST',
                  url: myAjax.url,
                  data: formData,
                  beforeSend: function () {
                    form.addClass('is-sending');
                  },
                  error: function (request, txtstatus, errorThrown) {
                    console.log(request);
                    console.log(txtstatus);
                    console.log(errorThrown);
                  },
                  success: function (res) {
                    console.log(res);
                    form.removeClass('is-sending').addClass('is-sending-complete');
                    form.find('input').val('');
                    form.find('textarea').val('');

                    setTimeout(function(){
                     form.removeClass('is-sending-complete');
                    },2000);
                  }
                });

                e.preventDefault();

              });

Может, я вообще неправильно делаю что-то? Дайте хотя бы простой пример двух разных ajax форм на одной странице WordPress. Как это делается вообще? Нужен ли там wp_localize_script()? А если нужен, то нужно ли его под каждую ajax форму делать?
ПОМОГИТЕ :)

A: Во втором js
$.ajax({
    url: myAjax2.url2,
    data: formDataOrder, // Здесь у вас ошибка
    type: 'POST',
    beforeSend: function () {
       orderForm.addClass('is-sending');
    },

Причина - банальная невнимательность. ajax ни при чем.
В целом всё сделано правильно. Да, можно два localize_script(), а можно и в одну переменную myAjax всё засунуть. Вот так
wp_localize_script( 'dm-grata-script-main', 'myAjax', array(
    'url'    => admin_url( 'admin-ajax.php?action=send_mail' ),
    'nonce'  => wp_create_nonce(),
    'url2'   => admin_url( 'admin-ajax.php?action=send_order' ),
    'nonce2' => wp_create_nonce(),
) );

И во втором обработчике использовать myAjax вместо myAjax2. Ведь что делает localize_script()? Он выводит CDATA с вашей переменной myAjax на страницу, посмотрите в исходном коде страницы (Ctrl+U). А скрипт уже подхватывает эту глобальную переменную.
Но для лучшей читаемости кода оставьте так, как есть - с двумя запусками localize_script().


text:
Q: Is there a way, without Spark UDFs, to blend two distribution DataFrames that have different support? What I have is two DataFrames, each representing a probability distribution, but each stored one entry per row. For example one is df1:
item_id |  probability
--------|---------------
  item1 |      0.1
  item2 |      0.2
  item3 |      0.7

and another, let's call it df2:
item_id |  probability
--------|---------------
  item2 |      0.3
  item3 |      0.5
  item4 |      0.2

and please notice that the item space for these two are different. But this is ok because what it means is that df1 has zero probability for item4 and df2 has zero probability for item1. What I'd like is code without heavy use of custom UDFs that basically produces a DataFrame that, given some alpha double value, blends those two distribution. I can write this with custom UDFs but I'm wondering if there's some pure Spark SQL based code that does this with only built-in functions.
item_id |  probability
--------|---------------
  item1 |      0.1 * alpha + 0.0 * (1 - alpha)
  item2 |      0.2 * alpha + 0.3 * (1 - alpha)
  item3 |      0.7 * alpha + 0.5 * (1 - alpha)
  item4 |      0.0 * alpha + 0.2 * (1 - alpha)

A: I think this is totally doable with SQL.  The secret is an "outer" join with some coalesce magic to handle nulls.
import org.apache.spark.sql.types._

val someData = Seq( ("item1", 0.1 ), ("item2", 0.2),("item3", 0.7) )
val alpha = 1.1

val someMoreData = Seq( ("item2", 0.3 ), ("item3", 0.5),("item4", 0.2) )

val df1 = spark.sparkContext.parallelize(someMoreData).toDF( "item_id","probability" )
val df2 = spark.sparkContext.parallelize(someData).toDF( "item_id","probability" )
val prob = df2
  .join(df1, df1("item_id") === df2("item_id"), "outer" )
  .select(
    coalesce( df1("item_id"), df2("item_id") ).alias("item_id"),
    coalesce( df1("probability"),lit(0.0)).alias("probability1"),
    coalesce( df2("probability"),lit(0.0)).alias("probability2"),
    lit(alhpa).alias("alpha") )
prob.show()
+-------+------------+------------+-----+
|item_id|probability1|probability2|alpha|
+-------+------------+------------+-----+
|  item3|         0.5|         0.7|  1.1|
|  item2|         0.3|         0.2|  1.1|
|  item1|         0.0|         0.1|  1.1|
|  item4|         0.2|         0.0|  1.1|
+-------+------------+------------+-----+

prob.select( prob("probability1") * prob("alpha") +  prob("probability2").multiply( lit(1.0) - prob("alpha")), prob("item_id") ).show();
+---------------------------------------------------------+-------+
|((probability1 * alpha) + (probability2 * (1.0 - alpha)))|item_id|
+---------------------------------------------------------+-------+
|                                                     0.48|  item3|
|                                                     0.31|  item2|
|                                     -0.01000000000000...|  item1|
|                                      0.22000000000000003|  item4|
+---------------------------------------------------------+-------+

A: It can be solved with a full-join and simple operation. Here you have a snippet. Just bear in mind, that for clarification I changed prob names in both dataframes to prob1 and prob2 respectively. Then it's just something like:
alpha = 0.5
df = df1 \
    .join(df2, how='full', on='item_id') \
    .fillna(0) \
    .withColumn('prob', alpha * F.col('prob1') + (1-alpha) * F.col('prob2'))

Your data sample:
df1 = spark.createDataFrame(data=[
    ('item1', 0.1),
    ('item2', 0.2),
    ('item3', 0.7)
], schema=['item_id', 'prob1'])

df2 = spark.createDataFrame(data=[
    ('item2', 0.3),
    ('item3', 0.5),
    ('item4', 0.2)
], schema=['item_id', 'prob2'])


text:
Q: GraalVM does not discover DMN Camunda resources I am developing an application in Quarkus Framework that uses the embedded Camunda DMN engine, but I have problems in the native compilation using GraalVM.
The problem is that at runtime it is not able to find some XSD files that the camunda library does not place in the resources folder, it places them in a package as seen in the image.

I used the command so that it will generate the configuration files during the execution of the application to be able to compile in native.
$JAVA_HOME/bin/java -agentlib:native-image-agent=config-output-dir=native-config -jar target/quarkus-app/quarkus-run.jar
This generated the following structure in the resources-config.json file
{
    "resources":{
            "includes":[
                    {"pattern":"\\QMETA-INF/services/io.smallrye.config.ConfigSourceFactory\\E"},
                    {"pattern":"\\QMETA-INF/services/io.smallrye.config.SmallRyeConfigFactory\\E"},
                    {"pattern":"\\QMETA-INF/services/io.vertx.core.spi.BufferFactory\\E"},
                    {"pattern":"\\QMETA-INF/services/io.vertx.core.spi.FutureFactory\\E"},
                    {"pattern":"\\QMETA-INF/services/javax.script.ScriptEngineFactory\\E"},
                    {"pattern":"\\QMETA-INF/services/org.eclipse.microprofile.config.spi.ConfigSource\\E"},
                    {"pattern":"\\QMETA-INF/services/org.eclipse.microprofile.config.spi.Converter\\E"},
                    {"pattern":"\\Qapplication.properties\\E"},
                    {"pattern":"\\Qorg/camunda/bpm/model/dmn/schema/DMN11.xsd\\E"},
                    {"pattern":"\\Qorg/camunda/bpm/model/dmn/schema/DMN11_Alternative.xsd\\E"},
                    {"pattern":"\\Qorg/camunda/bpm/model/dmn/schema/DMN12.xsd\\E"},
                    {"pattern":"\\Qorg/camunda/bpm/model/dmn/schema/DMN13.xsd\\E"},
                    {"pattern":"\\Qorg/jboss/threads/Version.properties\\E"}
    ]},
    "bundles":[{"name":"com.sun.org.apache.xerces.internal.impl.xpath.regex.message"}]
}

As you can see, the access to resources is deduced with the pattern "\\Qorg/camunda/bpm/model/dmn/schema/DMN13.xsd\\E".
My resource configuration file looks like this
      {
    "bundles": [
      {
        "name": "com.sun.org.apache.xerces.internal.impl.msg.XMLSchemaMessages"
      },
      {
        "name":"com.sun.org.apache.xerces.internal.impl.xpath.regex.message"
      }
    ],
    "resources": {
      "includes": [
        {"pattern":"\\QMETA-INF/services/io.smallrye.config.ConfigSourceFactory\\E"},
        {"pattern":"\\QMETA-INF/services/io.smallrye.config.SmallRyeConfigFactory\\E"},
        {"pattern":"\\QMETA-INF/services/io.vertx.core.spi.FutureFactory\\E"},
        {"pattern":"\\QMETA-INF/services/javax.script.ScriptEngineFactory\\E"},
        {"pattern":"\\QMETA-INF/services/org.eclipse.microprofile.config.spi.ConfigSource\\E"},
        {"pattern":"\\QMETA-INF/services/org.eclipse.microprofile.config.spi.Converter\\E"},
        {"pattern":"\\Qapplication.properties\\E"},
        {"pattern":"\\Qorg/camunda/bpm/model/dmn/schema/DMN11.xsd\\E"},
        {"pattern":"\\Qorg/camunda/bpm/model/dmn/schema/DMN11_Alternative.xsd\\E"},
        {"pattern":"\\Qorg/camunda/bpm/model/dmn/schema/DMN12.xsd\\E"},
        {"pattern":"\\Qorg/camunda/bpm/model/dmn/schema/DMN13.xsd\\E"},
        {"pattern":"\\Qorg/jboss/threads/Version.properties\\E"}
      ]
    }
  }

When compiling the quarkus application natively with the command ./mvnw package -Pnative.
This generates the native executable and perform the deployment well, but when I make a request which uses camunda it generates the error
    Caused by: org.camunda.bpm.model.dmn.DmnModelException: Unable to parse model
  at org.camunda.bpm.model.dmn.impl.DmnParser.parseModelFromStream(DmnParser.java:79)
  at org.camunda.bpm.model.dmn.Dmn.doReadModelFromInputStream(Dmn.java:245)
  at org.camunda.bpm.model.dmn.Dmn.readModelFromStream(Dmn.java:158)
  at org.camunda.bpm.dmn.engine.impl.transform.DefaultDmnTransform.setModelInstance(DefaultDmnTransform.java:111)
  ... 33 more
Caused by: org.camunda.bpm.model.xml.ModelParseException: SAXException while parsing input stream
  at org.camunda.bpm.model.xml.impl.util.DomUtil.parseInputStream(DomUtil.java:245)
  at org.camunda.bpm.model.xml.impl.parser.AbstractModelParser.parseModelFromStream(AbstractModelParser.java:131)
  at org.camunda.bpm.model.dmn.impl.DmnParser.parseModelFromStream(DmnParser.java:76)
  ... 36 more
Caused by: org.xml.sax.SAXException: Error: URI=null Line=1: schema_reference.4: Failed to read schema document 'jar:file:/home/jonathanch/Documents/workspace/trabajo/servicio-motor/target/servicio-motor-1.0.0-SNAPSHOT-native-image-source-jar/lib/org.camunda.bpm.model.camunda-dmn-model-7.14.0.jar!/org/camunda/bpm/model/dmn/schema/DMN13.xsd', because 1) could not find the document; 2) the document could not be read; 3) the root element of the document is not <xsd:schema>.
  at org.camunda.bpm.model.xml.impl.util.DomUtil$DomErrorHandler.error(DomUtil.java:202)
  at com.sun.org.apache.xerces.internal.util.ErrorHandlerWrapper.error(ErrorHandlerWrapper.java:138)
  at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:396)
  at com.sun.org.apache.xerces.internal.impl.XMLErrorReporter.reportError(XMLErrorReporter.java:306)
  at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.reportSchemaErr(XSDHandler.java:4257)
  at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.reportSchemaError(XSDHandler.java:4240)
  at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.getSchemaDocument1(XSDHandler.java:2531)
  at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.getSchemaDocument(XSDHandler.java:2238)
  at com.sun.org.apache.xerces.internal.impl.xs.traversers.XSDHandler.parseSchema(XSDHandler.java:588)
  at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.processJAXPSchemaSource(XMLSchemaLoader.java:844)
  at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaLoader.loadSchema(XMLSchemaLoader.java:606)
  at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.findSchemaGrammar(XMLSchemaValidator.java:2710)
  at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.handleStartElement(XMLSchemaValidator.java:2069)
  at com.sun.org.apache.xerces.internal.impl.xs.XMLSchemaValidator.startElement(XMLSchemaValidator.java:829)
  at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:374)
  at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:613)
  at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3063)
  at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:836)
  at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:605)
  at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:112)
  at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:534)
  at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:888)
  at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:824)
  at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
  at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:246)
  at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:339)
  at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:122)
  at org.camunda.bpm.model.xml.impl.util.DomUtil.parseInputStream(DomUtil.java:240)

Checking the path to the file, I see that in the jar are the files. What is the error?
Here I get into the confusion of how GraalVM discovers resources and how the pattern should be written to include resources at compile time.
I have also tried with the pattern {"pattern":".*/DMN1.*xsd$"},  but the problem persists.
Note:
This is the trace of accesses to those resources generated in the execution of the application with the command $JAVA_HOME/bin/java -agentlib:native-image-agent=trace-output=native-config/trace-file.json -jar target/quarkus-app/quarkus-run.jar
      [...{"caller_class":"java.util.Arrays", "result":true, "args":["[Ljava.lang.Class;"], "function":"newInstance", "tracer":"reflect", "class":"java.lang.reflect.Array"},
  {"caller_class":"java.lang.invoke.InnerClassLambdaMetafactory", "result":true, "args":["get$Lambda",["java.io.File"]], "function":"findMethodHandle", "tracer":"reflect", "class":"jdk.xml.internal.SecuritySupport$$Lambda$258/0x0000000840325840"},
  {"caller_class":"org.camunda.bpm.model.xml.impl.util.ReflectUtil", "result":true, "args":["org/camunda/bpm/model/dmn/schema/DMN13.xsd"], "function":"getResource", "tracer":"reflect", "class":"io.quarkus.bootstrap.runner.RunnerClassLoader"},
  {"caller_class":"java.lang.ClassLoader", "result":false, "args":["org/camunda/bpm/model/dmn/schema/DMN13.xsd"], "function":"getResource", "tracer":"reflect", "class":"jdk.internal.loader.ClassLoaders$AppClassLoader"},
  {"caller_class":"java.lang.ClassLoader", "result":false, "args":["org/camunda/bpm/model/dmn/schema/DMN13.xsd"], "function":"getResource", "tracer":"reflect", "class":"jdk.internal.loader.ClassLoaders$PlatformClassLoader"},
  {"caller_class":"org.camunda.bpm.model.xml.impl.util.ReflectUtil", "result":true, "args":["org/camunda/bpm/model/dmn/schema/DMN12.xsd"], "function":"getResource", "tracer":"reflect", "class":"io.quarkus.bootstrap.runner.RunnerClassLoader"},
  {"caller_class":"java.lang.ClassLoader", "result":false, "args":["org/camunda/bpm/model/dmn/schema/DMN12.xsd"], "function":"getResource", "tracer":"reflect", "class":"jdk.internal.loader.ClassLoaders$AppClassLoader"},
  {"caller_class":"java.lang.ClassLoader", "result":false, "args":["org/camunda/bpm/model/dmn/schema/DMN12.xsd"], "function":"getResource", "tracer":"reflect", "class":"jdk.internal.loader.ClassLoaders$PlatformClassLoader"},
  {"caller_class":"org.camunda.bpm.model.xml.impl.util.ReflectUtil", "result":true, "args":["org/camunda/bpm/model/dmn/schema/DMN11.xsd"], "function":"getResource", "tracer":"reflect", "class":"io.quarkus.bootstrap.runner.RunnerClassLoader"},
  {"caller_class":"java.lang.ClassLoader", "result":false, "args":["org/camunda/bpm/model/dmn/schema/DMN11.xsd"], "function":"getResource", "tracer":"reflect", "class":"jdk.internal.loader.ClassLoaders$AppClassLoader"},
  {"caller_class":"java.lang.ClassLoader", "result":false, "args":["org/camunda/bpm/model/dmn/schema/DMN11.xsd"], "function":"getResource", "tracer":"reflect", "class":"jdk.internal.loader.ClassLoaders$PlatformClassLoader"},
  {"caller_class":"org.camunda.bpm.model.xml.impl.util.ReflectUtil", "result":true, "args":["org/camunda/bpm/model/dmn/schema/DMN11_Alternative.xsd"], "function":"getResource", "tracer":"reflect", "class":"io.quarkus.bootstrap.runner.RunnerClassLoader"},
  {"caller_class":"java.lang.ClassLoader", "result":false, "args":["org/camunda/bpm/model/dmn/schema/DMN11_Alternative.xsd"], "function":"getResource", "tracer":"reflect", "class":"jdk.internal.loader.ClassLoaders$AppClassLoader"},
  {"caller_class":"java.lang.ClassLoader", "result":false, "args":["org/camunda/bpm/model/dmn/schema/DMN11_Alternative.xsd"], "function":"getResource", "tracer":"reflect", "class":"jdk.internal.loader.ClassLoaders$PlatformClassLoader"},
  {"caller_class":"java.util.Arrays", "result":true, "args":["[Ljava.lang.Class;"], "function":"newInstance", "tracer":"reflect", "class":"java.lang.reflect.Array"}...]

This is how amunda accesses resources:

I clarify that GraalVM is reading the configuration file created because it takes the configuration of "bundles".


text:
Q: Output Javascript array into HTML with better readability I'm trying to output the data in an array (produced by this code) to a div in a simple web page, using this jquery:
$('#submit').click(function(e) {
        e.preventDefault();
        var num = $('#userInput').val();
        var primes = sieve(num);          // sieve() produces array of prime numbers
        console.log(primes);
        $('#answer').html(primes);
    });

The console is logging the array as I would like to see it, (i.e. 2, 3, 5, 7, 11, 13, etc.) but the content in #answer is displaying without any formatting (23571113 etc.).
How can I get the data to display in a more readable format? I've tried using .split and .join to add commas or line breaks but no joy...

A: Just join the array into a string using whatever separator you want to use. Also, when filling in text that isn't HTML, don't use html, use text:
$('#answer').text(primes.join(", "));

You (and lurkers) may be wondering why you didn't get the default Array#toString behavior, which is to do .join() (where join defaults to the separator ","). The reason is that the html function is appending each element of the array to the target element individually, as a new text node, instead of calling toString on the array. (This doesn't appear to be documented behavior.) Surprising, but true:

var answer = $("#answer");
answer.html([1, 2, 3, 4, 5]);
console.log(answer[0].childNodes.length); // 5

text applies toString, but the default separator used (",", no space after ,) probably isn't what you want:

var answer = $("#answer");
answer.text([1, 2, 3, 4, 5]);
console.log(answer[0].childNodes.length); // 5

A: An easy way would be to use .text() instead of .html() to set the contents of the #answer element.  You must also join the values of the array using the .join() method.
$('#submit').click(function(e) {
        e.preventDefault();
        var num = $('#userInput').val();
        var primes = sieve(num);          // sieve() produces array of prime numbers
        console.log(primes);
        $('#answer').text(primes.join(", "));
    });

Or, if you really want to add it as HTML, wrap it in a pre element, which preserves whitespace:
$('#submit').click(function(e) {
        e.preventDefault();
        var num = $('#userInput').val();
        var primes = sieve(num);          // sieve() produces array of prime numbers
        console.log(primes);
        $('#answer').html('
' + primes.join(", ") + '
');
    });


text:
Q: SSO(Single Sign On) in java web applications I have multiple java web applications all having their login functionalities. I want to apply SSO(Single Sign On) on them irrespective by any method.
I have spent last 2 days on finding a solution to it, but I have no result.
Please anyone can help me on that.
My requirement is:
           1.If user logs onto a single application he would be automatically logged onto other applications.
Sorry for my English and Thanks in advance.

A: If applications are in a Windows intranet and use windows logins, Waffle will do the job. Otherwise develop your own simple ticket granting service to provide SSO among your applications.
Update:
All of your apps have to have filters. Filter sends the session/cookie data(if available) in order to verify, to your SSO service whether the incoming request with the principle is already granted or not. If the session or cookie is not associateed with a ticket, then you redirect to the login page. If the request is about to login, then filter sends them in to SSO service, verify user and password with your database, and add an entry to SSO MAP, saying "this user just logged in". So it will send a ticket for that login. Ticket means just a random generated id. If the SSO service could not able to validate the user, then no entry will be there in the SSO MAP and will send failure error to your filter.
So your user validation goes in to a separate service which I just named as SSO service.
You will have to remove idle entries from SSO MAP.
Read about how SSO works, you will understand.


text:
Q: GitHub - Pushed a change to master, but appears as different user than me? I have a GitHub repo located here. I just commited a change to my repo and pushed to master branch, as I always do. I entered my account name and password, and the commit was pushed to GitHub. However, when I checked my GitHub commits page, I see a user that is not me.
Did I do something wrong? I'm on a new computer that just installed Git Bash. I usually use Git Bash on my laptop. Was I supposed to somehow identify myself on my Git Bash client before using repos? I'm so confused.

A: The issue is more clearly seen if you look at the raw commit, which can be done by adding .patch to the normal commit URL. It shows this line:

From: User <User>

So it looks like some generic defaults got picked up. You may have entered your username and password as Github credentials which are separate from your identity that goes into your commit.
Follow the official Github instructions for setting your name and email address, which boils down to this command to set it globally:
git config --global user.email "your_email@example.com"

And this command for the local repo:
git config user.email "your_email@example.com"


text:
Q: Primefaces filter datatable Hello guys I have a problem with my datatable I want to filter it, but if i put something into the text field nothing is shown and also if i clear the input also nothing.
It is possible if i have more than one statment in a column?
So I use primefaces 3.5 and jsf 2.1
Here is the code  and if you need more code post an comment. thx

            <f:facet name="header">

                    <h:outputText value="Suchen:" />

            </f:facet>

                <h:outputText
                    value="#{task.FROM_USER.FIRST_NAME} #{task.FROM_USER.LAST_NAME} (#{task.FROM_USER.EMAIL})" />

                    <h:panelGroup rendered="#{!task.IS_SEEN}" class="fa fa-envelope fa-2x" />
                    <h:panelGroup rendered="#{task.IS_SEEN}" class="fa fa-envelope-o fa-2x" />

                <h:outputText value="#{task.TASKTYPE.NAME}" />

                <h:outputText value="#{task.CREATE_TIMESTAMP}" />

A: It is not explicitely written in documentation, but as mentioned on PrimeFaces forum, you need to declare filterBy attribute on columns you want to make searchable via global filter.
It is also suggested here to add filterStyle="display:none" to columns if you don't want a filter to be visible on individual columns.
The example from documentation has filterBy:

    <f:facet name="header">

            <h:outputText value="Search all fields:" />
            <h:inputText id="globalFilter" onkeyup="carsTable.filter()" />

    </f:facet>

            <h:outputText value="#{car.model}" />

however, as typical for PrimeFaces documentation, it's not written that it won't work without filterBy.

A: You must add getter and setter of your taskboxInboxList in the taskboxBean class. But it filters just the first statement placed in the column.


text:
Q: gpg, one email address has two keys Let's say that a user has 2 keys listed in the gpg key ring (i.e., 2 keys with the same Email address). How does one set which key of the 2 to use? The only input that I have is the email, and it is the same for the 2 keys.Thanks

A: Assuming you're trying to encrypt to one of the keys, you can specify the recipient using the fingerprint or long key ID, for example
gpg --recipient A999B7498D1A8DC473E53C92309F635DAD1B5517 --armor --encrypt


text:
Q: How to use SSL in a Java Web project i want to use SSL in a Java Web Project, but i do not know anything about this. Is there anyone who could advise me about this? Thanks.

A: Depends on the servlet container you are using. I've found Setting up SSL on Tomcat to be a pretty good start for this. For other containers, searching for "ssl container-name" should do the trick.


text:
Q: Find operation (AJAX request) rejected, not seen in the wire In my application, I am doing several find operations. All of them are working, except one, which is being rejected. For debugging purposes, I am sending the requests during startup of the application:
preloadData : function () {
    SettingsApp.Node.find();
    SettingsApp.Locator.find();
    SettingsApp.Phonelocation.find();
    SettingsApp.User.find(CNST.ME_FAKE_DOC_ID);
    SettingsApp.Company.find(CNST.MY_ORG_FAKE_DOC_ID);
},

And this is how it looks in the console:

As you can see, all requests are isFullfilled except the last one which is isRejected. The rejectedReason says only "error".
What could be causing this? This is no backend problem, since the request is not being sent at all. The only thing I can think of is the adapter configuration, since companies has an irregular plural:
SettingsApp.Adapter.configure('plurals', {
    voice_menu : 'voicemenus',
    profile    : 'profile',
    company    : 'companies',
});

But this is being used properly, it seems. What could else be causing this?

A: I don't know the exact reason why your GET request is rejected, but as a quick workaround for debugging purposes you could do the following to get more info on the errors that are occurring:
Ember.RSVP.configure('onerror', function(error) {
  console.log(error.message);
  console.log(error.stack);
});

Hope it helps.


text:
Q: Is this a critical RAID error? If I do the following
/opt/MegaRAID/MegaCli/MegaCli -LDInfo -Lall -aAll -NoLog  > /tmp/tmp
/opt/MegaRAID/MegaCli/MegaCli -LDPDInfo     -aAll -NoLog >> /tmp/tmp

then I see these errors
Media Error Count: 11
Other Error Count: 5

Question
What does they mean? Are they critical?
Full output:
Adapter 0 -- Virtual Drive Information:
Virtual Disk: 0 (target id: 0)
Name:Virtual Disk 0
RAID Level: Primary-5, Secondary-0, RAID Level Qualifier-3
Size:951296MB
State: Optimal
Stripe Size: 64kB
Number Of Drives:5
Span Depth:1
Default Cache Policy: WriteBack, ReadAheadNone, Direct, No Write Cache if Bad BBU
Current Cache Policy: WriteBack, ReadAheadNone, Direct, No Write Cache if Bad BBU
Access Policy: Read/Write
Disk Cache Policy: Disk's Default

Adapter #0

Number of Virtual Disks: 1
Virtual Disk: 0 (target id: 0)
Name:Virtual Disk 0
RAID Level: Primary-5, Secondary-0, RAID Level Qualifier-3
Size:951296MB
State: Optimal
Stripe Size: 64kB
Number Of Drives:5
Span Depth:1
Default Cache Policy: WriteBack, ReadAheadNone, Direct, No Write Cache if Bad BBU
Current Cache Policy: WriteBack, ReadAheadNone, Direct, No Write Cache if Bad BBU
Access Policy: Read/Write
Disk Cache Policy: Disk's Default
Number of Spans: 1
Span: 0 - Number of PDs: 5
PD: 0 Information
Enclosure Device ID: N/A
Slot Number: 0
Device Id: 0
Sequence Number: 2
Media Error Count: 0
Other Error Count: 0
Predictive Failure Count: 0
Last Predictive Failure Event Seq Number: 0
Raw Size: 238418MB [0x1d1a94a2 Sectors]
Non Coerced Size: 237906MB [0x1d0a94a2 Sectors]
Coerced Size: 237824MB [0x1d080000 Sectors]
Firmware state: Online
SAS Address(0): 0x1221000000000000
Connected Port Number: 0
Inquiry Data: ATA     WDC WD2500JS-75N2E04     WD-WCANK9523610

PD: 1 Information
Enclosure Device ID: N/A
Slot Number: 1
Device Id: 1
Sequence Number: 2
Media Error Count: 11
Other Error Count: 5
Predictive Failure Count: 0
Last Predictive Failure Event Seq Number: 0
Raw Size: 238418MB [0x1d1a94a2 Sectors]
Non Coerced Size: 237906MB [0x1d0a94a2 Sectors]
Coerced Size: 237824MB [0x1d080000 Sectors]
Firmware state: Online
SAS Address(0): 0x1221000001000000
Connected Port Number: 1
Inquiry Data: ATA     WDC WD2500JS-75N2E04     WD-WCANK9507278

PD: 2 Information
Enclosure Device ID: N/A
Slot Number: 2
Device Id: 2
Sequence Number: 2
Media Error Count: 0
Other Error Count: 0
Predictive Failure Count: 0
Last Predictive Failure Event Seq Number: 0
Raw Size: 238418MB [0x1d1a94a2 Sectors]
Non Coerced Size: 237906MB [0x1d0a94a2 Sectors]
Coerced Size: 237824MB [0x1d080000 Sectors]
Firmware state: Online
SAS Address(0): 0x1221000002000000
Connected Port Number: 2
Inquiry Data: ATA     WDC WD2500JS-75N2E04     WD-WCANK9504713

PD: 3 Information
Enclosure Device ID: N/A
Slot Number: 3
Device Id: 3
Sequence Number: 2
Media Error Count: 0
Other Error Count: 0
Predictive Failure Count: 0
Last Predictive Failure Event Seq Number: 0
Raw Size: 238418MB [0x1d1a94a2 Sectors]
Non Coerced Size: 237906MB [0x1d0a94a2 Sectors]
Coerced Size: 237824MB [0x1d080000 Sectors]
Firmware state: Online
SAS Address(0): 0x1221000003000000
Connected Port Number: 3
Inquiry Data: ATA     WDC WD2500JS-75N2E04     WD-WCANK9503028

PD: 4 Information
Enclosure Device ID: N/A
Slot Number: 4
Device Id: 4
Sequence Number: 2
Media Error Count: 0
Other Error Count: 0
Predictive Failure Count: 0
Last Predictive Failure Event Seq Number: 0
Raw Size: 238418MB [0x1d1a94a2 Sectors]
Non Coerced Size: 237906MB [0x1d0a94a2 Sectors]
Coerced Size: 237824MB [0x1d080000 Sectors]
Firmware state: Online
SAS Address(0): 0x1221000004000000
Connected Port Number: 4
Inquiry Data: ATA     WDC WD2500JS-75N2E04     WD-WCANK9503793

A: actually smartctl can provide you detailed information about every disk in MegaRaid raid. to get information about physical disk #0 run:
smartctl -a -d megaraid,0 /dev/sda|less

as Pawel rightly points most probably it's reallocated sectors, but i had few cases when communication problems [visible in smartctl -l xerror -d megaraid,5 /dev/sda] were reported as
Media Error Count.

A: As long as your array is up and running, it should be ok.
Media error counter can increase from events such as a failing sector reallocation on one of the drives, while the other errors counter can be increased by any non-problematic event (bus device reset, power cycle, etc). However, if the error is critical, the drive will be automatically taken out of the array by the controller and reported as failed, in which case you will have to take an action.
It would be great if smartctl would be able to provide detailed SMART info on megaraid and individual unit status, but I don't think it supports it. Give it a try just in case.

A: You have problems with drive in slot 1. It's RAID 5, so your data is protected, but you've lost redundancy (one disk is not reliable). Media error means the drive run out of spare sectors to remap bad sectors to (http://kb.lsi.com/KnowledgebaseArticle15809.aspx http://mycusthelp.info/LSI/_cs/AnswerDetail.aspx?inc=7468). If it was my data I'd be doubly scrupulous when backing up, remove the drive, replace it with a new one and synchronise the array. Some vendors (e.g. IBM) will accept RMA based on predictive failure indicators, some won't. If your vendor does not accept a disk with bad, un-remappable sectors as faulty, then take it out of the array and exercise in a test system. It should fail in reasonable time.
Edit:
Media events were non-zero only for disk with slot ID 1. In the log you've provided there's slot ID for each entry.
The strange thing is, that the raid reports its state as optimal, despite media errors on the disk. Still', I wouldn't trust the disk.
RAID 5 made with n disks of the same size gives you capacity of (n-1) disks, because it stores one disks' worth of redundancy data. Therefore if you have six 250 GB disks and 1T of usable space, they are most likely divided into 5-disks RAID 5 (which gives you 4x250 GB of usable space) plus 1 spare disk.

A: Sometimes, drives will generate read errors and, in my experience, usually when that happens I can run "badblocks" on it to stress test the drive and the drive may report some errors early on, but then once the drive has been stressed a bit it will either continue reporting errors, in which case it's bad, or it will report no errors.
I've figured that this was due to some sectors of the drive being marginal, and badblock remapping can only kick in when you are writing to the disc, not reading from it.  If you write data to a sector that goes bad, the drive has to report an error reading it, because if it just silently remapped that sector to one of the spare sectors, it would give you back invalid data rather than an error.  But on a write, if it notices the sector is bad, it can write that data to a spare sector and remap it.
Unfortunately, you can't clear this error count, so if you have monitoring that reports media errors, you either have to replace the drive or make it so you can tell the monitoring to ignore this or that many errors and only report when it changes again.
You can check the drive SMART status with smartctl (thanks, @pQd, I didn't know about that) with:
MegaCli64 -PDList  -aALL | grep -e '^$' -e Slot -e Count
#  Find the slot number to use for "X".
#  For "Y" use the device name the system knows, such as "sda".
smartctl -a -d megaraid,X /dev/sdY

It's probably not entirely unreasonable to rebuild the drive and see if it continues to have problems.  With MegaRAID, you can do that with these commands:
#  WARNING: Make sure the array is "Optimal" first, this will degrade it.
MegaCli64 -LDInfo -Lall -aALL | grep State
#  NOTE: This assumes drive 3 of enclosure 32 for adapter 0
MegaCli64 -PDOffline -PhysDrv [32:3] -a0
MegaCli64 -PDRbld -Start -PhysDrv [32:3] -a0

#  Now check the rebuild status until it completes:
MegaCli64 -PDRbld -ShowProg -PhysDrv [32:3] -a0

# And the array status should go back to Optimal
MegaCli64 -LDInfo -Lall -aALL | grep State

I used to have drives fall out of the RAID array all the time (maybe once every month or two, across a sample of 100 to 200 drives).  But the drives weren't showing up as bad after I replaced them.
I started burning in all drives before putting them into production, using "badblocks" for around a week, and after I started doing that the number of these array drop-outs reduced dramatically.  Now it happens maybe twice a year, across 500 drives.
This is a destructive test, so make sure you have no data on the drive:
badblocks -svw -p 5 /dev/sdX

Were "sdX" is the device to test.  Be very careful here, picking the wrong drive will destroy your data.  I run my tests on a standalone machine on my testbench.


text:
Q: Cannot connect to Kubernetes using new context I am using Kubernetes on Minikube.
I created a user context for a new user with role and rolebinding, using
kubectl config set-context user1-context --cluster=minikibe --namespace=default --user=user1
When I try to see the runnig pods, target machine refuses it. But, in minikube context I can see the pods although both are running on the same cluster.
>kubectl config get-contexts
CURRENT   NAME             CLUSTER          AUTHINFO         NAMESPACE
          docker-desktop   docker-desktop   docker-desktop
          minikube         minikube         minikube
*         user1-context    minikibe         user1

>kubectl get pods
Unable to connect to the server: dial tcp [::1]:8080: connectex: No connection could be made because the target machine actively refused it.

>kubectl config use-context minikube
Switched to context "minikube".

>kubectl get pods
NAME         READY   STATUS    RESTARTS   AGE
myapp-test   1/1     Running   0          44m

Config for rolebinding:
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: read-pods
subjects:
  - kind: User
    name: user1
    apiGroup: rbac.authorization.k8s.io
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: pod-reader

Role config
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: pod-reader
rules:
  - apiGroups: [""]
    resources: ["pods"]
    verbs: ["get","watch","list"]

I also verified the creation of roles an rolesbinding
>kubectl get roles
NAME         CREATED AT
pod-reader   2020-10-20T05:59:43Z

>kubectl get rolebindings
NAME        ROLE              AGE
read-pods   Role/pod-reader   65m

A: Issue
There was a typo in a kubectl config set-context command.
Solution
Use this command with --cluster=minikibe typo fixed.
kubectl config set-context user1-context --cluster=minikube --namespace=default --user=user1


text:
Q: How to use float.h macros to enhance the floating point precision As I understood from this answer, there is a way to extend the precision using float.h via the macro LDBL_MANT_DIG. My goal is to enhance the floating point precision of double values so that I can store a more accurate number, e.g., 0.000000000566666 instead of 0.000000. Kindly, can someone give a short example of to use this macro so that I can extend the precision stored in the buffer?

A: Your comment about wanting to store more accurate numbers so you don't get just 0.000000 suggests that the problem is not in the storage but in the way you're printing the numbers.  Consider the following code:
#include <stdio.h>

int main(void)
{
    float f = 0.000000000566666F;
    double d = 0.000000000566666;
    long double l = 0.000000000566666L;

    printf("%f  %16.16f  %13.6e\n", f, f, f);
    printf("%f  %16.16f  %13.6e\n", d, d, d);
    printf("%lf  %16.16lf  %13.6le\n", d, d, d);
    printf("%Lf  %16.16Lf  %13.6Le\n", l, l, l);
    return 0;
}

When run, it produces:
0.000000  0.0000000005666660   5.666660e-10
0.000000  0.0000000005666660   5.666660e-10
0.000000  0.0000000005666660   5.666660e-10
0.000000  0.0000000005666660   5.666660e-10

As you can see, using the default "%f" format prints 6 decimal places, which treats the value as 0.0.  However, as the format with more precision shows, the value is stored correctly and can be displayed with more decimal places, or with the %e format, or indeed with the %g format though the code doesn't show that in use — the output would be the same as the %e format in this example.
The %f conversion specification, as opposed to %lf or %Lf, says 'print a double'.  Note that when float values are passed to printf(), they are automatically converted to double (just as numeric types shorter than int are promoted to int).  Therefore, %f can be used for both float and double types, and indeed the %lf format (which was defined in C99 — everything else was defined in C90) can be used to format float or double values.  The %Lf format expects a long double.
There isn't a way to store more precision in a float or double simply by using any of the macros from <float.h>.  Those are more descriptions of the characteristics of the floating-point types and the way that they behave than anything else.

A: The answer you cited only mentions that the macro is equal to the number of precision digits that you can store. It cannot in any way increase precision. But the macro is for "long doubles", not doubles. You can use the long double type if you need more precision than the double type:
 long double x = 3.14L;

Notice the "L" after the number for specifying a long double literal.

A: Floating-point types are implemented in hardware. The precision is standardized across the industry and baked into the circuits of the CPU. There's no way to increase it beyond long double except an extended-precision software library such as GMP.
The good news is that floating-point numbers don't get bogged down in leading zeroes. 0.000000000566666 won't round to zero. With only six digits, you only even need a single-precision float to represent it well.
There is an issue with math.h (not float.h), where the POSIX standard fails to provide π and e with long double precision. There are a couple workarounds: GNU defines e.g. M_PIl and M_El, or you can also use the preprocessor to paste an l onto such literal constants in another library (giving the number long double type) and hope for spare digits.


text:
Q: segFaut by allocating memory for pointer to pointer in struct I have a pointer to char pointer in a struct. so there is a struct poiter object that I will pass to thread but thats not relevant.
so this is my struct
struct shard
{
    sem_t *semaphore_o;
    char **input;
    char **image_o;
};

I am creating object like
struct shard *obj=malloc(sizeof(struct shard));

and I am allocating the input in shard struct
*(obj->input)=malloc(sizeof(char)+1);

but abocve line giving segFault

A: *(obj->input) dereferences input before input points to valid memory, invoking undefined behavior, where manifesting with a segfault is common.  You first have to malloc memory for it before dereferencing.  You don't provide enough details about what you're trying to do, but something like:
struct shard *obj=malloc(sizeof(struct shard));
if (obj == NULL)
{
  // handle error how you want, and make a check like this for every malloc
  exit(-1);
}

obj->input = malloc(howManyCharPtrsYouWant * sizeof(*(object->input));
for (int i=0; i<howManyCharPtrsYouWant; i++)
{
  obj->input[i] = malloc(howManyCharsYouWant); // sizeof(char) is guaranteed to be 1, so no need to include it in `malloc`
}

See my previous answer for an explanation of sizeof(*(object->input)) if you're unsure what's happening there.
*(obj->input)=malloc(sizeof(char)+1); only allocates space for 2 chars (sizeof char == 1, +1 == 2 total).  This is the smallest possible string you can have in C, one char followed by a NUL terminator.  So if you're trying to put more than 2 chars in that buffer, that's an overflow --> UB --> possible segfault.  If all you need is one char, better to bypass the malloc and simply use char c;, for example.
This is getting off topic, but the top two reasons you need dynamic memory allocation IMO are:

*

*You won't know how much memory you'll need until runtime

*You need "a lot" of memory (on your regular vanilla PC, I'd put this around 4+MB, but of course your mileage may vary depending on your needs and system).

SO has some good questions weighing the benefits of when to malloc or not, you can look them up.
If you know at compile time you'll need a max of 30 strings, only 30 chars long for example, then you can do something like
struct shard
{
    sem_t *semaphore_o;
    char input[30][30];
    // .. etc
};

and
struct shard obj; // you only need one of these, malloc makes little sense IMO
obj.semaphore_o = malloc(..); // this doesn't need to be a pointer either
strcpy(input[0], "hello there"); // fits in 29 chars plus NUL
strcpy(input[5], "I'm Jim");     // same

My preference is always to use automatic (stack) storage when possible, it's simpler because it relieves you of the burden of memory management.


text:
Q: Numpy vectorized zero-order interpolation I have an array
p = [[0.9, 0.95, 0.99],
     [0.89, 0.94, 0.98],
     [0.9, 0.95, 0.99],
     [0.91, 0.96, 0.97],
    ]

and a uniform random number for each row
r = [0.5,
     0.9,
     0.3,
     0.99]

I want to know the last column index where p is still smaller than r, i.e.
c = [0, 1, 0, 3]

For the last case, no value is smaller. If one places a column of 1s at the end of p, this would be 3. A -1 is also acceptable for me.
Naive solution:
c = []
for prow, ri in zip(p, r):
    ci = numpy.interp(ri, prow, arange(len(prow)))
    c.append(int(numpy.ceil(ci)))

print c
[0, 1, 0, 3]

But I am looking for a vectorised solution that is fast and works for large arrays (millions of rows, ~10 columns).
I looked into these solutions:

*

*scipy.interpolate.interp1d(kind=zero)

*

*this seems to require a outer python loop

*r > p and numpy.where

*

*also seems to require a outer python loop

*using numpy.random.choice

For the last one I would place (differential) probabilities instead of cumulative ones:
p = [[0.9, 0.05, 0.04],
     [0.89, 0.05, 0.04],
     [0.9, 0.05, 0.04],
     [0.91, 0.05, 0.01],
    ]

but numpy.random.choice does not support vectorization (1, 2).
Is numpy.vectorise the solution, or Cython? I am looking for a fast solution.

A: Here's one vectorized solution using broadcasting -
mask = (p > r[:,None])
out = np.where(mask.any(1),mask.argmax(1),p.shape[1])

Sample run -
In [50]: p
Out[50]:
array([[ 0.9 ,  0.95,  0.99],
       [ 0.89,  0.94,  0.98],
       [ 0.9 ,  0.95,  0.99],
       [ 0.91,  0.96,  0.97]])

In [51]: r
Out[51]: array([ 0.5 ,  0.9 ,  0.3 ,  0.99])

In [52]: mask = (p > r[:,None]) # 2D Mask of row-wise comparisons

In [53]: mask
Out[53]:
array([[ True,  True,  True],
       [False,  True,  True],
       [ True,  True,  True],
       [False, False, False]], dtype=bool)

In [54]: np.where(mask.any(1),mask.argmax(1),p.shape[1])
Out[54]: array([0, 1, 0, 3])


text:
Q: How to work successfully my ContainerAwareCommand using Job class? Here is my ContainerAwareCommand class,
class myCommand extends ContainerAwareCommand
{
   protected function configure()
   {
      $this
        ->setName('entity:new')
        ->setDescription('my command.')
        ->addArgument(
           'entity',
           InputArgument::REQUIRED,
           'entity ID'
        )
     ;
  }

  protected function execute(InputInterface $input, OutputInterface $output)
  {
     ...
  }
}

and below code is part of function of other class,
$job = New Job();
$job->setCommand('entity:new '.$entity->getId());

$this->em->persist($job);
$this->em->flush();

I expected to run a execute function of myCommand class after '$this->em->flush();' but I think it is not work.
Please tell me the reason in this situation or how to debug easily for me.
I am symfony2 beginner.
Regards

A: From looking at your code I assume that you use the JmsJobQueueBundle. The code you are showing is only responsible to schedule a job in the queue. For the queued jobs to be executed, you must either run the jms-job-queue:run command manually or make sure that it is executed in the background.
For the next time, please remember to provide more information about what other libraries you use so that people who do not that libraries will be able to help you too.


text:
Q: Hitachi hard drive with apple firmware - possible to install Windows on? My friend gave me a spare harddrive he had, a 320GB Hitachi HTS545032B9A302. I was hoping I could use this in place of my 70GB internal drive at home. However it says on the label that it has Apple HDD Firmware 2010. This raised my eyebrow - does this mean my non-Mac PC will be able to read and write from this harddrive (and, ergo, install Windows 8 to it) so long as I format it correctly? Or will my computer not be able to talk to it due to not having the right firmware?
I've tried using google to find an alternate firmware download just in case, but that's failed me.

A: Apple computers use the same standard hardware as any other manufacturer, although they may buy certain batches for different products.
The firmware still must talk to the OS the same as any other. I am not sure if Apple is back to their old game of restricting their OS only on specific hard drives, but that may be more of the reason for the re-label. The hard SN series and firmware might be to control where you buy a replacement drive for your MAC.
Either way, there should be no problem with installing another OS on the drive, or using it as a second drive. The firmware must remain standard otherwise a BIOS our UEFI would not be able to communicate with the drive. Macs can dual boot Windows or have another OS too, so this suggests nothing real odd is going on.


text:
Q: What are the pros and cons of multiple rows of POLYGON vs one MULTIPOLYGON field? So for the first time I'm gonna do a project that involves maps and layers on top of maps which have many points and many polygons on them.
I have the tendency to create separate tables for points and polygons and then create many-to-many relationships between them and the layers table. If I do that I end up with 5 tables: points, polygons, layers, layers_points and layers_polygons.
However, I see PostGIS also offers types called MULTIPOINT and MULTIPOLYGON. If I use those types then I could put it all in the layers table. I guess that would make queries faster, because I need less joins. However, I'm not sure if later I might regret it, if it means that working with the individual points and polygons becomes impossible. I'm not even sure yet if it will be necessary to work perform calculations on the individual points and polygons, but it would be nice to know whether that's possible or not in both approaches.
So basically I'm asking, what the pros and cons are of these different approaches?

A: In general, you would consider using multipolygons to represent entities that have disjoint surfaces (for example, the geometry of Alaska) or other topologies that you can't represent as polygons. The key here is that a single entity needs to be expressed with a multipolygon
What you wouldn't do is group unrelated polygons into a multipolygon, because you won't be able to perform queries at a child polygon level, unless you extract the rings into another geometry. If the polygons are unrelated, chances are you will need to query them individually. Even if they share a layer, you can manage that relation with business logic without merging them as they aren't representing the same entity.
Keep in mind that geometry tools in the frontend won't necesarilly treat multipolygons as a valid geometry or a multi object. Algorithms of point-in-polygon that looks like your use case, won't necesarilly work when checking if a point is contained in a multipolygon.
Tools like Wicket.js (transform from/to WKT/geojson/native objects) don't support multipolygons. Google maps api v3 doesn't support multipolygons except for the data layer (but you can't operate on the data layer as you would on a polygon feature). Turf.js has operations that would run on a Featurecollection containing several polygons, yet not over a multipolygon.
Without knowing your exact use case, that's the best I can tell you, and TL/DR: keep your polygons as they are.


text:
Q: Cucumber and Rspec sharing factory girl factories I'm designing a test around rails using Cucumber and Rspec and I was wondering if it is good practice sharing the Factory Girl factory code between the Cucumber acceptance test and Rspec unit tests.
And if it is good practice where would be the best place neutral location to place the factories for rspec and cucumber.
Thanks a lot

A: You can use factories anywhere you like. I generally use them in rspec and my Cucumber stories.
Factories are fixture replacements. General idea is to be able to right readable tests and move away from the "fixtures" hell scenario.
I think its fine if you place in spec/factories , there is no standard location. But I generally place it in my spec folder. No need to use a separate neutral location for it.

A: Yes, it is a good practice to not repeat the same factory definitions (if they are shared... which I would content there SHOULD be some overlap).  One way to do this is to create a new directory in your project called factories and then add the following to your rspec and cucumber configurations:
/features/support/app.rb
    Dir[Rails.root.join("factories/**/*.rb")].each {|f| require f}

/spec/spec_help.rb
    Dir[Rails.root.join("factories/**/*.rb")].each {|f| require f}


text:
Q: Data import macro from .txt file really slow I have written a macro to open a .csv, copy over a few cells, then open a .txt and copy a few more.
The .csv runs really quickly, but it really bogs down on the .txt and sometimes crashes.
I am getting the "Waiting for another application to complete an OLE action" message twice, and think that is probably the issue but don't know how to troubleshoot that.
It does work, but would like it to run much faster.
Thanks in advance!
Option Explicit

Sub Import_Racecutter()
'
' Import_Racecutter Macro
'
Application.ScreenUpdating = False
Application.IgnoreRemoteRequests = True

Dim source As Variant
Dim ws As Worksheet
Dim tbl As ListObject
Dim newrow As ListRow
Dim pasteCell As Range

Set ws = ThisWorkbook.Sheets(1)
Set tbl = ws.ListObjects.item("Table2")

MsgBox "Select the RACECUTTER file to Import"

source = Application.GetOpenFilename(FileFilter:="CSV Files (.csv), *.csv", MultiSelect:=False)

If source = False Then
    MsgBox "No file selected. Cannot continue."
    Exit Sub
End If

Workbooks.Open (source)

'On Error GoTo exit

Set newrow = tbl.ListRows.Add 'Insert new row at the bottom of the table

'Racecutter Data Merge
ActiveSheet.Range("B3").Copy Destination:=newrow.Range(1, 5) 'TWS
ActiveSheet.Range("B4").Copy Destination:=newrow.Range(1, 6) 'TWA
ActiveSheet.Range("B6").Copy Destination:=newrow.Range(1, 7) 'AWS
ActiveSheet.Range("B7").Copy Destination:=newrow.Range(1, 8) 'AWA
ActiveSheet.Range("B5").Copy Destination:=newrow.Range(1, 9) 'BS
ActiveSheet.Range("B8").Copy Destination:=newrow.Range(1, 10) 'HEEL
ActiveSheet.Range("B12").Copy Destination:=newrow.Range(1, 11) 'HS Load
ActiveSheet.Range("B19").Copy Destination:=newrow.Range(1, 12) 'MS Load
ActiveSheet.Range("B10").Copy Destination:=newrow.Range(1, 13) 'Mast Rotation
ActiveSheet.Range("B11").Copy Destination:=newrow.Range(1, 14) 'Traveler Position
ActiveSheet.Range("B15").Copy Destination:=newrow.Range(1, 15) 'V1 Port
ActiveSheet.Range("B16").Copy Destination:=newrow.Range(1, 16) 'V1 Stbd
ActiveSheet.Range("B17").Copy Destination:=newrow.Range(1, 17) 'D1 Port
ActiveSheet.Range("B18").Copy Destination:=newrow.Range(1, 18) 'D1 Stbd

ActiveWorkbook.Close
'Application.CutCopyMode = False

'Open Vspars File
MsgBox "Now select the VSpars file matching the Racecutter file you just opened"
source = Application.GetOpenFilename(FileFilter:="TXT Files (.txt), *.txt", MultiSelect:=False)
Workbooks.OpenText source, DataType:=xlDelimited, Tab:=True

'VSpars Data Merge
'12.5%
ActiveSheet.Range("C8").Copy Destination:=newrow.Range(1, 19) 'Camber
ActiveSheet.Range("D8").Copy Destination:=newrow.Range(1, 20) 'Draft
ActiveSheet.Range("E8").Copy Destination:=newrow.Range(1, 21) 'Front %
ActiveSheet.Range("F8").Copy Destination:=newrow.Range(1, 22) 'Back %
ActiveSheet.Range("A8").Copy Destination:=newrow.Range(1, 23) 'Entry
ActiveSheet.Range("B8").Copy Destination:=newrow.Range(1, 24) 'Exit
ActiveSheet.Range("G8").Copy Destination:=newrow.Range(1, 25) 'Twist
'25%
ActiveSheet.Range("C7").Copy Destination:=newrow.Range(1, 26) 'Camber
ActiveSheet.Range("D7").Copy Destination:=newrow.Range(1, 27) 'Draft
ActiveSheet.Range("E7").Copy Destination:=newrow.Range(1, 28) 'Front %
ActiveSheet.Range("F7").Copy Destination:=newrow.Range(1, 29) 'Back %
ActiveSheet.Range("A7").Copy Destination:=newrow.Range(1, 30) 'Entry
ActiveSheet.Range("B7").Copy Destination:=newrow.Range(1, 31) 'Exit
ActiveSheet.Range("G7").Copy Destination:=newrow.Range(1, 32) 'Twist
'50%
ActiveSheet.Range("C6").Copy Destination:=newrow.Range(1, 33) 'Camber
ActiveSheet.Range("D6").Copy Destination:=newrow.Range(1, 34) 'Draft
ActiveSheet.Range("E6").Copy Destination:=newrow.Range(1, 35) 'Front %
ActiveSheet.Range("F6").Copy Destination:=newrow.Range(1, 36) 'Back %
ActiveSheet.Range("A6").Copy Destination:=newrow.Range(1, 37) 'Entry
ActiveSheet.Range("B6").Copy Destination:=newrow.Range(1, 38) 'Exit
ActiveSheet.Range("G6").Copy Destination:=newrow.Range(1, 39) 'Twist
'75%
ActiveSheet.Range("C5").Copy Destination:=newrow.Range(1, 40) 'Camber
ActiveSheet.Range("D5").Copy Destination:=newrow.Range(1, 41) 'Draft
ActiveSheet.Range("E5").Copy Destination:=newrow.Range(1, 42) 'Front %
ActiveSheet.Range("F5").Copy Destination:=newrow.Range(1, 43) 'Back %
ActiveSheet.Range("A5").Copy Destination:=newrow.Range(1, 44) 'Entry
ActiveSheet.Range("B5").Copy Destination:=newrow.Range(1, 45) 'Exit
ActiveSheet.Range("G5").Copy Destination:=newrow.Range(1, 46) 'Twist
'87.5%
ActiveSheet.Range("C4").Copy Destination:=newrow.Range(1, 47) 'Camber
ActiveSheet.Range("D4").Copy Destination:=newrow.Range(1, 48) 'Draft
ActiveSheet.Range("E4").Copy Destination:=newrow.Range(1, 49) 'Front %
ActiveSheet.Range("F4").Copy Destination:=newrow.Range(1, 50) 'Back %
ActiveSheet.Range("A4").Copy Destination:=newrow.Range(1, 51) 'Entry
ActiveSheet.Range("B4").Copy Destination:=newrow.Range(1, 52) 'Exit
ActiveSheet.Range("G4").Copy Destination:=newrow.Range(1, 53) 'Twist

ActiveWorkbook.Close

Application.CutCopyMode = False
Application.ScreenUpdating = True
Application.IgnoreRemoteRequests = False
'exit_:

'Application.ScreenUpdating = True
'If Err Then MsgBox Err.Description, vbCritical, "Error"

End Sub

A: According to this website, the error can occur when reading data from non-excel files:
https://www.thewindowsclub.com/excel-is-waiting-for-another-application
My guess is the text file is loaded in a less-efficient manner than normal excel or csv files and each copy action is forcing Excel to parse the text file to determine what data should be copied. Perhaps it would be quicker to copy all of the required data in one go to the current workbook on a temporary worksheet, and then copy the required values from there into the table.
Try adding a new worksheet to your workbook called "Temp", then you can do something like:
Dim wsTemp as Worksheet
Set wsTemp = ThisWorkbook.Sheets("Temp")

Then after opening the text file:
wsTemp.Range("A1:G8").Value = Activesheet.Range("A1:G8").Value
ThisWorkbook.Activate
wsTemp.Select

The rest of the code should then work as is. (Although it would be better to use references to the wsTemp than activating it first.)
Hopefully this single copy action for all of the data from the text file takes around the same time as an individual copy action in your current code. The copy between sheets within the workbook should be much quicker.

A: Rather than copying and pasting, which includes all formatting, simply copy the values directly by assignment:
Instead of:
ActiveSheet.Range("C8").Copy Destination:=newrow.Range(1, 19) 'Camber

Use:
newrow.Range(1, 19) = ActiveSheet.Range("C8")


text:
Q: Why is using LIKE %value% giving my php page a 500 code? I have tried my best to google this issue and I think maybe I am just doing something wrong that I don't understand? I have a small PHP page that generates some JSON for me from a database for use in another system.
It works perfectly until I try and use LIKE in my SQL statement with the % wild card. The same query works perfectly testing in phpMyAdmin. I am a little confused.
my data looks something like this.
shop, region, mangoes, sales, more data.
I am trying to filter by region. Region currently has four values. Let's call them "My shop", "Clearance shop", "Franchise" and "Special"
I want to be able to eventually do a URL like data.php?ShopType=shops. this would bring up my query and filter for all regions with "shop" in the region
easy I thought. I constructed a quick test query.
SELECT * FROM `RetailSalesData` WHERE `Date` = '01/07/2019' AND `Region` LIKE '%shop%'

this works as expected in phpmyadmin but when I used it on my test server it was throwing a 500.
I was using $_GET to grab my values for filtering my query so I removed and commented that out and just tried the straight query in case I was going wrong there but still no luck.
if I do something like
"SELECT * FROM `RetailSalesData` WHERE `Date` = '01/07/2019' AND `Region` LIKE 'My shop'"

then it works. But then I might as well not be using LIKE and I don't get all the results I want because I am not using the % wildcard. It seems like I can't use "%" in the query in PHP and I don't understand why.
<?php
//setting header to json
header('Content-Type: application/json');

$servername = "server";
$username = "User";
$password = "password";
$dbname = "mangoes";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

//get the data range and type
//$ShopType = $_GET["ShopType"];

//query to get data from the table
$query = sprintf("SELECT * FROM `RetailSalesData` WHERE `Date` = '01/07/2019' AND 'Region' LIKE '%shop%'");

//execute query
$result = $conn->query($query);

//loop through the returned data
$data = array();
foreach ($result as $row) {
    $data[] = $row;
}

//free memory associated with result
$result->close();

//close connection
$conn->close();

//now print the data
print json_encode($data);
?>

From the above code, I expect a list of my shops with their respective data filtered out for the shops in "regions" with "shop" in the region values. What I get is a 500 error page if my SQL query contains "%" wildcard using LIKE.

A: In your query you're using:

LIKE = '%shop%'

however, you're passing that in sprintf function which has a special purpose for %s chars.
%s means that you'll provide the function with a string argument for sprintf to put in place of %s and since you're not providing the argument, it's giving 500 error.
You can get more information on sprintf on:
https://www.php.net/manual/en/function.sprintf.php

A: don't use quote around column name and use a proper conversion for string date
        $query = sprintf("SELECT * FROM `RetailSalesData`
            WHERE `Date` = str_to_date('01/07/2019' ,'%d/%m/%Y')
             AND Region LIKE concat('%', shop,'%')";

A: sprintf have the issue and also you're passing 'region' as string.. and looks like this is column name
use this code.
<?php
//setting header to json
header('Content-Type: application/json');

$servername = "server";
$username = "User";
$password = "password";
$dbname = "mangoes";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

//get the data range and type
//$ShopType = $_GET["ShopType"];

//query to get data from the table
$query = "SELECT * FROM `RetailSalesData` WHERE `Date` = '15/07/2019' AND Region LIKE '%shop%'";

//execute query
$result = $conn->query($query);
$data1 = $result->fetch_all();
//loop through the returned data
$data = array();
foreach ($data1 as $row) {
    $data[] = $row;
}

//free memory associated with result
$result->close();

//close connection
$conn->close();

//now print the data
print json_encode($data);
?>

Also you are not fetching the data and looping through the result.. updated the code to fix it.


text:
Q: How can I copy a single row/record from one MySQL instance to another? I have two MySQL instances running with the same schema.  One is in the cloud; one is on my local box.  The local-box version needs a couple of test rows in its main table.
Effectively I'd like to do something like a mysqldump or mysqlhotcopy of a single record on the production table, and then "restore" that record into the same table on the local instance.  I don't want to copy the whole table.  If there are rows on the local table, I want them left alone.
I'm fine with the PK of the copied row changing.  I don't care about foreign keys, if any.
The table is big and complex enough that it's nontrivial for me to print the record with a select statement and then format it for an insert.
What are my options?

A: If you're already familiar with mysqldump, I'll remind you that mysqldump has a --where option, so you can get a single row if you write the condition for that:
mysqldump databasename tablename --where "id=12345" --no-create-info --skip-add-locks --host=db1  | \
  mysql --host=db2

You could also use SELECT...INTO OUTFILE to dump the result of any query you want into a flat file, even a query of a single row. Then LOAD DATA INFILE to import that file on the other instance.
You could also write a simple script in your choice of language. Connect to both instances. SELECT a single row from the source instance, save it in a variable in the script. Then form an INSERT command to execute against the destination instance. This may not be the most efficient way to move a large amount of data, but for a single row it would be fine.


text:
Q: Spyder Ipython Console - code to automatically print to pdf and save to HTML file I am working in Spyder and would like to record the console output as either a html or pdf file. Currently the only way to achieve this is to right click on the console window and then choose 'save as'.
The problem with this approach is that the file path needs to be specified manually. It would be much more desirable to be able to set the working directory in the code and then save the pdf or html automatically to this location. Is this possible?
Or if this is not possible, is there any code that when the 'save as' option is right clicked, the file browser is opened on the current working directory?

A: (Spyder developer here) My answer:

Or if this is not possible, is there any code that when the 'save as' option is right clicked, the file browser is opened on the current working directory?

We can implement this in a future release. Please open an issue in our issues tracker so we don't forget to do it in the future.


text:
Q: Why Code Coverage in react app is empty? Tried using npm run test -- --coverage. But always showing empty code coverage I need help to find code coverage.
I have just created a new app using the latest create-react-app.
I am trying to find the code coverage using npm run test -- --coverage. this is showing empty code coverage. Can any please help me to find where I am missing.
 PASS  src/__tests__/App.test.js
  ✓ renders without crashing (2ms)

----------|----------|----------|----------|----------|-------------------|
File      |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
----------|----------|----------|----------|----------|-------------------|
All files |        0 |        0 |        0 |        0 |                   |
----------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        0.17s, estimated 1s
Ran all test suites.

Watch Usage: Press w to show more.

A: https://github.com/facebook/create-react-app/issues/6888
Just add flag --watchAll=false to your npm run test -- --coverage

A: Try adding following to your package.json under scripts
"test:coverage": "npm test -- --coverage --watchAll=false",

Then u can run command to check coverage 'npm run test:coverage'


text:
Q: java.io.IOException: Stream is corrupted while writing a Big file in Pyspark I am reading data from SQL server about 9 million rows and inserting it into a table already existing in my datalake(Parquet)
This process worked with less data around 1 million.
I am using the basic read write only for sql server :

My Spark Submit looks like this:

My Pyspark Config :

I have tried repartition and increasing the memory to 15 but still the same issue..
java.io.IOException: Stream is corrupted
Sorry but i dont have access to full logs

A: When you're reading data such way, it's really only one core is used, as JDBC connector doesn't automatically parallelize reads until it explicitly configured to do so. So most probably the connection is timed out during the read operation.
You need to look to the JDBC connector options like, partitionColumn, lowerBound, upperBound, etc. that will split the reads into multiple operations. (maybe also look to the fetchsize, etc.)


text:
Q: Extracting a single field in django-filter I have an application that uses django-filter.
I want to be able to add an external library select2 (jquery) only one field - user.
How can I "separate" user field to be able to then work on it using select2 (jquery) in template?
class MyForm(InlineForm):
    class Meta:
        model = MyModel

class FreeDaysFilter(django_filters.FilterSet):

    user = django_filters.ModelMultipleChoiceFilter(queryset=User.objects.all())
    date_from = django_filters.DateFilter(widget=DateInput(attrs={'class':'datepicker'}))
    date_to = django_filters.DateFilter(widget=DateInput(attrs={'class':'datepicker'}))

    class Meta:
        model = MyModel
        form = MyForm
        fields = ['user', 'country', 'date_from', 'date_to']


text:
Q: Showing that two matrices are similar by showing they are similar to the same diagonal matrix The exercise gives two matrices $A$ and $B$ and asks you to show they are similar by showing that they are similar to the same diagonal matrix, and then after that find and invertible matrix $P$ such that $P^{-1}AP=B$.
$$
A = \begin{bmatrix}
    1 & 0 & 2\\[0.3em]
    1 & -1 & 1\\[0.3em]
    2 & 0 & 1\\[0.3em]
    \end{bmatrix},
%
B = \begin{bmatrix}
    -3 & -2 & 0\\[0.3em]
    6 & 5 & 0\\[0.3em]
    4 & 4 & -1\\[0.3em]
    \end{bmatrix}
$$
I started with with calculating the eigenvalues of matrix $A$ like so:
$$
det(A) = det(\begin{bmatrix}
    1-\lambda & 0 & 2\\[0.3em]
    1 & -1-\lambda & 1\\[0.3em]
    2 & 0 & 1-\lambda\\[0.3em]
    \end{bmatrix})= \lambda^3-\lambda^2-5\lambda-3 = (\lambda-3)(\lambda+1)^2
$$
Which gives $\lambda = -1, 3$. Taking $\lambda = -1$ gives $$[A--1 \cdot I|0] =
\begin{bmatrix}
    2 & 0 & 2 & 0\\[0.3em]
    1 & 0 & 1 & 0\\[0.3em]
    2 & 0 & 2 & 0\\[0.3em]
    \end{bmatrix}=
%
\begin{bmatrix}
    1 & 0 & 1 & 0\\[0.3em]
    0 & 0 & 0 & 0\\[0.3em]
    0 & 0 & 0 & 0\\[0.3em]
    \end{bmatrix}
    $$
But this is where I get stuck, because $x_2$ is a free variable, and so this gives
$$
E_{-1}=\Bigg\{s
\begin{bmatrix}
0\\[0.3em]
1\\[0.3em]
0\\[0.3em]
\end{bmatrix}+
%
t\begin{bmatrix}
-1\\[0.3em]
0\\[0.3em]
1\\[0.3em]
\end{bmatrix}\Bigg\} = span
%
\Bigg(\begin{bmatrix}
0\\[0.3em]
1\\[0.3em]
0\\[0.3em]
\end{bmatrix},
%
\begin{bmatrix}
-1\\[0.3em]
0\\[0.3em]
1\\[0.3em]
\end{bmatrix}
\Bigg)
$$
right? I thought $P =\{E_{-1}, E_{-1}, E_{3}\}$ for example, so how does this work? I might be completely missing the mark, but I thought you had to calculate the eigenvalues of matrix $A$ and $B$, and if they are the same, then they are similar, then after this, calculate the eigenvectors of matrix $A$ to obtain matrix $P$, and then plug these matrices into the formula given above ($P^{-1}AP=B$) to see if it's true or not?
I uploaded pictures of how I've done it here, is that the correct way?

A: If you have an eigenvalue of multplicity, you will get multiple eigenvalues associated with that eigenvalue.
$\begin{bmatrix}
    1 & 0 \\
    1 & -1\\
    2 & 0\\
    \end{bmatrix}\begin{bmatrix}
    0&-1 \\
    1&0\\
    0&1\\
    \end{bmatrix} = \begin{bmatrix}
    0&1 \\
    -1&0\\
    0&-1\\
    \end{bmatrix}= \begin{bmatrix}0&-1 \\
    1&0\\
    0&1\\
    \end{bmatrix}(-I)$
Find the 3rd eigenvetor and you will have
$AP = P\begin{bmatrix} -1&\\&-1\\&&3\end{bmatrix}\\
P^{-1}AP = \begin{bmatrix} -1&\\&-1\\&&3\end{bmatrix}$


text:
Q: How to use hints when using like '%%' in Oracle?It use index but do not work I have a table called TB_STUDENT which has two fields called STUDENT_NAME,STUDENT_ID,STUDENT_NUMBER and have at least 100000 rows of data. Now I have created two indexes and I want to search the student according to student_name. I have use hint, but it seems that it still is TABLE ACCESS FULL.How to change my SQL?
 CREATE index  IDX_STUDENT_ID ON CUST (STUDENT_ID);
 CREATE index IDX_STUDENT_NAME ON CUST (STUDENT_NAME);
 SELECT  /*+ INDEX(IDX_STUDENT_ID ,IDX_STUDENT_NAME ) */STUDENT_ID,STUDENT_NAME FROM TB_STUDENT S WHERE STUDENT_NAME LIKE '%LUSY%';

A: An index stores the data in a sorted tree, making searching it easier. For varchar columns, this means the data is sorted lexicographically. It would make sense to use an index if you had a wildcard at the end (or even the middle) of the string, but here, you have a wildcard at the beginning of the string, meaning the value can be anywhere in the index. In such a case where using an index gives no benefit over scanning the entire table, the optimizer will choose not to use the index. Hints are just what their name suggests - hints - and cannot force the optimizer to use an index in an invalid usecase.


text:
Q: clang 8 linker error with static constexpr and arrays - what's the bug and how to work around it? When you declare a static class member that is an array constexpr, clang up to version 8 fails to link. This works in clang 9 and later, and it also works in MSVC 2019.
https://godbolt.org/z/oQ6iEf
Can someone tell me exactly what the clang bug is and what possible workarounds I could use to express the same idea (class-static const array) with clang < 9?

A: Compile with -O1 and it will work fine ;)


text:
Q: Using Git bash for python installations and task I have been given a windows laptop at work to work on a web app using flask which involves a little bit of computer vision and nlp as well. I wanted to take this chance to transition to the command style in linux. Since it is my office laptop I am not allowed to dual boot or install anything unless it is specified. So I was wondering if gitbash can be used to transition to linux commands instead of the windows cmd or the anaconda prompt?
I did try using gitbash but other than commits it is a hassle when using pip or sudo. Many times it does not recognize the command even though i have the python scripts added in PATH but it still isnt working with sudo and python. I felt i will face similar issues ahead so wanted to know if it is a good idea at all to use gitbash to practice transitioning to linux or is there any other alternate which is more smooth and hassle less.

A: In my experience the best way to learn Linux when you only have Windows installed is to use either Windows Subsystem for Linux (WSL) or to use Linux-based Docker containers.
gitbash won't offer the full functionality of Linux, since it is largely relies on the binary commands and various components of Windows.
Docker has a number of other benefits.
For example if your Flask application is Dockerised, it would make it easier to deploy on the server when needed.


text:
Q: Textview with Suggestions List in iOS I am trying to implement a textView in which when user starts typing(Let's say names) it would show up the suggestions and when they click them it gets added to the textView than user presses comma and again the same functionality for another name....
And at the end the text in the textView should look like this...
Aron,Maria,Alex,Cassie
Can any one suggest me How can I achieve this?
(Its somewhat similar to adding the "Tags" while posting this question!!!)
Thanks.

A: You can use a NSTokenField replacement there is some libraries here :
tokenField libraries

A: Following link may help you:
http://www.raywenderlich.com/336/how-to-auto-complete-with-custom-values
Follow the same flow. To get autocomplete suggestions after comma modify the delegate method as found below.
- (BOOL)textField:(UITextField *)textField
    shouldChangeCharactersInRange:(NSRange)range
    replacementString:(NSString *)string {
  autocompleteTableView.hidden = NO;

  NSString *names = [NSString stringWithString:textField.text];
  NSArray* arr = [names componentsSeparatedByString:@","];
  NSString *subString = [arr lastObject];
  substring = [substring
    stringByReplacingCharactersInRange:range withString:string];
  [self searchAutocompleteEntriesWithSubstring:substring];
  return YES;
}

Provide a NSMutableArray named 'allNames' which contains all the names you want to display in the suggestion list and use it as the following:
- (void)searchAutocompleteEntriesWithSubstring:(NSString *)substring {
  [autocompleteUrls removeAllObjects];
  for(NSString *curString in allNames) {
    NSRange substringRange = [curString rangeOfString:substring];
    if (substringRange.location == 0) {
      [autocompleteUrls addObject:curString];
    }
  }
  [autocompleteTableView reloadData];
}

When the user clicks the suggestions display the name by appending with previously entered names.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

  // set the textField.text by appending this name to already entered names

}

A: I didn't see anything like this in mobile app. You can look for libraries. But if you want to make it yourself I would advice you to use invisible tableView. When user starts typing name you should fetchData and show in tableView under textView. It's not hard.

A: A relatively easy way I can think of to achieve this functionality would be to add an input accessory view to your keyboard, which will offer suggestions.
You wouldn't have to tamper with the TextField itself, nor would you need to incorporate the suggestions into the remainder of your apps layout.
The accessory view could, for example, be given a reference to the textfield and listen to input by:
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textChanged) name:UITextFieldTextDidChangeNotification object:textFieldWithSuggestions];

It would feature a method -(void)textChanged; in which you would have the opportunity to split the existing text into components, using comma or whatever symbol as a separator, and then use the last text fragment to perform your search for possible completions.
It may present these suggestions as a row of buttons for example (maybe even in a side-scrolling scrollview to allow for many suggestions) and if one gets pushed, update the textfields text by replacing the last text segment with the completed string.
To keep track of which button stands for which suggestion, just give them tags according to the indices of your search results. This way, you'll need only one method as a target for the buttons, too.

A: If you want to some library code then you can go for this
https://github.com/hoteltonight/HTAutocompleteTextField which will help you


text:
Q: Not possible to install add-on on specifiek nodes We have installed Telegraf add-on for almost all the nodes in Jelastic paas environment.
But for couple nodes we get the following message when we are trying to install the add-on:

We have read the documentation of Jelastic but could not find why we are getting this message. We have tested with a basic hello world manifest but even that was not possible to install, we do get the same message.
We have this problem for the following nodes:

*

*Custom

*PostgresSQL

Does anyone have experience with this message an how to resolve it?

A: Telegraf add-on can be not supported by the type of node that it was tried to be installed on. That is why these node types could be absent in the manifest. In any way, if you want to try deploying the add-on on the mentioned node types (i.e. not to meet with the error "Add-on installation is not allowed for this node"), you may add along with already existing in the manifest node types these node types as well (more info from the Jelastic documentation is here):
targetNodes:
  nodeType:
  - postgresql
  - docker

In this case, there will be no such error as mentioned above, at least, but there are also no guarantees that the addon will be successfully installed and/or workable on these node types. For example, a custom node is based on the not supported by the add-on OS type

A: Your Jelastic provider doesn't allow Telegraf to be installed on this type of node. You can ask them to allow that.
Thanks


text:
Q: how to select rows based on two condition pandas I want to filter rows that are in df_1 that match the following two condition

*

*Row from df_1 should not be in df_2
OR

*If row from df_1 is in df_2 then it must have a value Yes in df_2
Code I tried, that does not work
import pandas as pd

df_1 = pd.DataFrame({'a': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]})
df_2 = pd.DataFrame({'a': [2, 4, 6, 8, 10], 'b': ['Yes', 'No', 'Yes', 'No', 'No']})

df = df_1[(~df_1.a.isin(df_2.a)) | (df_2.b=='Yes')]

Output
   a
0  1
2  3
4  5
6  7
8  9

Expected Output
   a
0  1
1  2
2  3
3  6
4  5
6  7
8  9

Explanation
Rows 1, 3, 5, 7, 9 are not in df_2 so they are part of the output
Rows 2 and 6 are in df_2 but the have column b as Yes so they are part of the output

A: You can use:
df = df_1.merge(df_2, how='left', on='a')
print(df[df.b.isin(['Yes', np.nan])][['a']])

OUTPUT
   a
0  1
1  2
2  3
4  5
5  6
6  7
8  9

A: I think you can create two frames and concat it as below.
import pandas as pd

df_1 = pd.DataFrame({'a': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]})
df_2 = pd.DataFrame({'a': [2, 4, 6, 8, 10], 'b': ['Yes', 'No', 'Yes', 'No', 'No']})

df = [df_1[(~df_1.a.isin(df_2.a))]['a'],df_2[df_2.b=='Yes']['a']]
result = pd.concat(df).sort_values()
print(result)

output

A: The problem in your calculation stems from the fact that df_1 and df_2 are not the same size and logical operators between their
columns does not make sense.  If you map your values in df_1 to Yes, No or NaN using df_2 then you will have equal length columns that can be compared
df_1[(~df_1["a"].isin(df_2["a"])) | (df_1["a"].map(df_2.set_index("a")["b"]) == "Yes")]

A: This won't be the fastest solution but the steps should be easy enough for you to follow. When the two dataframes are merged using a union, NaN values are added in place of missing data. Afterwards you want to retain those rows so you only need to remove those which have the value No.
import pandas as pd

df_1 = pd.DataFrame({'a': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]})
df_2 = pd.DataFrame({'a': [2, 4, 6, 8, 10], 'b': ['Yes', 'No', 'Yes', 'No', 'No']})

# Merge the dataframes using a union
df = df_1.merge(df_2, how='outer', on='a')
# Drop the rows where 'b' == 'No'
df.drop(df[df['b']=='No'].index, inplace=True)
# Drop column 'b'
df.drop('b', axis=1, inplace=True)


text:
Q: What do Abundant Luxuries actually do? According to the Effect it gives a -20% buyout bonus on the star system.
What does this mean? How can I tell if it's worth the -5$ on improvement?

A: Reducing the buyout cost means that, when you rush-build an improvement or ship, it will cost you less Dust. Thus, it's only valuable if you're going to be buying a lot of things in that system.
Is this system near the front lines of a war, and you're going to buy a large number of ships at it? Is this a brand-new system, and you've decided to rush-build most of the system improvements it needs? Do you have gobs of Dust lying around and nothing better to spend it on?
If you answered "yes" to one of the above questions, then this improvement is useful to you. If you're just rush-improving a colony, then you'll be better off dismantling Abundant Luxuries after you're done improving it, so that you don't have to pay its maintenance cost. If it's one of your major shipyards, keep it around for the next war. In all cases, if you don't keep enough Dust around to rush-build things, then don't build this improvement.

A: The "buyout cost" is the cost to press the coin symbol and rush a production. Subtracting out 1/5th of those large costs can save you money in the long run, especially if you have planets devoted to churning out fleets.


text:
Q: eventHandler, defining & accessing params (java Swing Netbeans) in short: How do I get access to a param passed into a GUI constructor within eventHandler?
more details:
I am using NetBeans and Swing to write a Plugin in Java.  I have created a Jframe with a GUI which includes a JTextField.  The eventHandler for JTextField writes the value entered to a variable.  Within the eventHandler I want next to call a method() which uses this variable and another, which was passed into the GUI's constructor.
?? How can I gain access to this variable? NetBeans wont let me change the auto-generated eventHandler signature to include the GUI variable I need. This eventHandler code below.
This is week 3 of Java for me so apologies if this is very basic question
thank you
B
PS thank for site, it has already answered many other questions.
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {  // *** no edit allowed to signature (greyed by NetBeans)
    System.out.println( "textField2: " +  jTextField1.getText() );
    String s = jTextField2.getText();
    try {
        numIter = Integer.parseInt(s.trim());
        testMethod(numIter, paramPassedIntoGUIconstructor);
// ?? how to get paramPassedIntoGUIconstructor?? <<-- key question
    } catch (NumberFormatException nfe) {
        JOptionPane.showMessageDialog(Cytoscape.getDesktop(),
                "That's not an integer!", "NumberFormatException",1);
    }
} // *** no edit allowed (greyed by NetBeans)

A: I'm not sure I understand the problem, but you should be able to add a member variable:
private final Integer answer;
// Variables declaration - do not modify
...
// End of variables declaration

Initialize it in your constructor:
public MyClass(Integer iWantAccessToThis) {
    initComponents();
    answer = iWantAccessToThis;
}

Access it, ad lib:
private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
    ...
    System.out.println(this.answer);
    ...
}

A: As @trashgod noted, it just works. However, if you attempt to use this to reference a variable, (eg. this.answer) it will fail.
When the listener is executing, this refers to the instance of the listener. To reference your outer class, you need to qualify the access by prepending the class name like so: Myclass.this.answer.
The JLS refers to it as a Qualified this