text:
Q: I am want to use Spring Data + Phonixdriver to perform SQL like operation on HBSE I can able to perform SQL using simple spring JDBCTemplate using Phonix driver.
Is there any way to use spring-Data-jpa to perform same operation.
Phonix driver help me for SQL operation on HBSE nosql database.
As per my understanding As long as I can perform SQL using JdbcTemplate I should able to use spring data too.
I am getting below error

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path
  resource
  [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]:
  Invocation of init method failed; nested exception is
  org.hibernate.service.spi.ServiceException: Unable to create requested
  service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628)
  ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]     at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555)
  ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]     at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483)
  ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]     at
  org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306)
  ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]     at
  org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
  ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]     at
  org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
  ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]     at
  org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197)
  ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]     at
  org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1078)
  ~[spring-context-4.3.11.RELEASE.jar:4.3.11.RELEASE]   at
  org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:857)
  ~[spring-context-4.3.11.RELEASE.jar:4.3.11.RELEASE]   at
  org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:543)
  ~[spring-context-4.3.11.RELEASE.jar:4.3.11.RELEASE]   at
  org.springframework.boot.SpringApplication.refresh(SpringApplication.java:693)
  ~[spring-boot-1.5.7.RELEASE.jar:1.5.7.RELEASE]    at
  org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:360)
  ~[spring-boot-1.5.7.RELEASE.jar:1.5.7.RELEASE]    at
  org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
  ~[spring-boot-1.5.7.RELEASE.jar:1.5.7.RELEASE]    at
  org.springframework.boot.test.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
  [spring-boot-test-1.5.7.RELEASE.jar:1.5.7.RELEASE]    at
  org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98)
  [spring-test-4.3.11.RELEASE.jar:4.3.11.RELEASE]   at
  org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
  [spring-test-4.3.11.RELEASE.jar:4.3.11.RELEASE]   at
  org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:83)
  [spring-test-4.3.11.RELEASE.jar:4.3.11.RELEASE]   at
  org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
  [spring-test-4.3.11.RELEASE.jar:4.3.11.RELEASE]   at
  org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
  [spring-test-4.3.11.RELEASE.jar:4.3.11.RELEASE]   at
  org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
  [spring-test-4.3.11.RELEASE.jar:4.3.11.RELEASE]   at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:228) [spring-test-4.3.11.RELEASE.jar:4.3.11.RELEASE]  at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
  [spring-test-4.3.11.RELEASE.jar:4.3.11.RELEASE]   at
  org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
  [junit-4.12.jar:4.12]     at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:289)
  [spring-test-4.3.11.RELEASE.jar:4.3.11.RELEASE]   at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
  [spring-test-4.3.11.RELEASE.jar:4.3.11.RELEASE]   at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
  [spring-test-4.3.11.RELEASE.jar:4.3.11.RELEASE]   at
  org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
  [junit-4.12.jar:4.12]     at
  org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
  [junit-4.12.jar:4.12]     at
  org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
  [junit-4.12.jar:4.12]     at
  org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
  [junit-4.12.jar:4.12]     at
  org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
  [junit-4.12.jar:4.12]     at
  org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
  [spring-test-4.3.11.RELEASE.jar:4.3.11.RELEASE]   at
  org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
  [spring-test-4.3.11.RELEASE.jar:4.3.11.RELEASE]   at
  org.junit.runners.ParentRunner.run(ParentRunner.java:363)
  [junit-4.12.jar:4.12]     at
  org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
  [spring-test-4.3.11.RELEASE.jar:4.3.11.RELEASE]   at
  org.junit.runner.JUnitCore.run(JUnitCore.java:137)
  [junit-4.12.jar:4.12]     at
  com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
  [junit-rt.jar:na]     at
  com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
  [junit-rt.jar:na]     at
  com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
  [junit-rt.jar:na]     at
  com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
  [junit-rt.jar:na] Caused by:
  org.hibernate.service.spi.ServiceException: Unable to create requested
  service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]   at
  org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:264)
  ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]   at
  org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:228)
  ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]   at
  org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207)
  ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]   at
  org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:51)
  ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]   at
  org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:94)
  ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]   at
  org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
  ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]   at
  org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:207)
  ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]   at
  org.hibernate.boot.model.process.spi.MetadataBuildingProcess.handleTypes(MetadataBuildingProcess.java:352)
  ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]   at
  org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:111)
  ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]   at
  org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:847)
  ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]  at
  org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:874)
  ~[hibernate-entitymanager-5.0.12.Final.jar:5.0.12.Final]  at
  org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
  ~[spring-orm-4.3.11.RELEASE.jar:4.3.11.RELEASE]   at
  org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:353)
  ~[spring-orm-4.3.11.RELEASE.jar:4.3.11.RELEASE]   at
  org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:370)
  ~[spring-orm-4.3.11.RELEASE.jar:4.3.11.RELEASE]   at
  org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:359)
  ~[spring-orm-4.3.11.RELEASE.jar:4.3.11.RELEASE]   at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1687)
  ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]     at
  org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1624)
  ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]     ... 39 common
  frames omitted Caused by: org.hibernate.HibernateException: Access to
  DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
    at
  org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:100)
  ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]   at
  org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:54)
  ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]   at
  org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137)
  ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]   at
  org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
  ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]   at
  org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:88)
  ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]   at
  org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:254)
  ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]   ... 55 common frames
  omitted


text:
Q: Mutating a dioxus UseState struct that doesn't implement clone I'm using Dioxus to build a UI. This UI relies heavily on a struct from a third-party library. This struct doesn't implement clone. The struct needs to be modified on button press. Consider this simplified example:
use dioxus::prelude::*;

struct ThirdPartyStruct(i64);

impl ThirdPartyStruct {
    fn add_one(&mut self) {
        self.0 += 1;
    }
}

fn app(cx: Scope) -> Element {
    let third_party_struct = use_state(cx, || ThirdPartyStruct(0));

    cx.render(rsx! {
        button {
            onclick: move |_| third_party_struct.make_mut().add_one(),
            "Click me!"
        }
        p {
            "{third_party_struct.get().0}"
        }
    })
}

This does not compile, since make_mut requires clone to be implemented for ThirdPartyStruct. The real ThirdPartyStruct isn't nearly as simple and the real equivalent of add_one has to be used (so solutions like "use + 1 instead" are invalid). Implementing clone by hand would also be infeasible.
I have tried many things, including most of the methods for the UseState struct meant for modifying the contained struct. All of them either require the struct to be modified by value (like calling + 1 instead of += 1) or need to have clone implemented.

A: The only way I can think of resolving this is wrapping the struct in a RefCell. It might not be the most memory safe way, but it works.
The side effect of this is the state does not know it has changed, so you will need to manually mark the component as dirty each time you call a mutating function with cx.needs_update().
fn app(cx: Scope) -> Element {
    let third_party_struct = use_state(cx, || RefCell::new(ThirdPartyStruct(0)));

    cx.render(rsx! {
        button {
            onclick: move |_| {
                third_party_struct.borrow_mut().add_one();
                cx.needs_update();
            },
            "Click me!"
        }
        p {
            "{third_party_struct.get().borrow().0}"
        }
    })
}

It's worth noting I have not tried this with the sysinfo crate, but it works with your MRE.

A: Dioxus has a separate hook called use_ref for values that are not clone. It is possible to use interior mutability like RefCell inside of a use_ref hook, but it is not recommended because it can easily break updates
use dioxus::prelude::*;

struct ThirdPartyStruct(i64);

impl ThirdPartyStruct {
    fn add_one(&mut self) {
        self.0 += 1;
    }
}

fn app(cx: Scope) -> Element {
    let third_party_struct = use_ref(cx, || ThirdPartyStruct(0));

    cx.render(rsx! {
        button {
            onclick: move |_| third_party_struct.write().add_one(),
            "Click me!"
        }
        p {
            "{third_party_struct.read().0}"
        }
    })
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Discerning slew rate and bandwidth limitations What I get is that, considering a 2 stage OTA, we have 2 effects that limit the amplitude and frequency of the amplified signal:

*

*Bandwidth of the amplifier: as the frequency of the input signal gets higher exceeding the bandwidth, the gain at which it is amplified gets lower

*Slew rate of the amplifier: when an input signal has a higher voltage slope than what the amp is able to provide, the output is pinned to the maximum rate of change

I get that both are caused by the dominant capacitor not charging/discharging fast enough, so how are they different in their effect?

A: Slew rate limiting occurs when the input signal amplitude (the difference voltage between the inputs) gets large enough to result in all the input stage tail current being sunk alternately down one side of the input differential pair and then down the other over 1 complete cycle of the input signal.
When this occurs the current being pushed and pulled between the first stage and the second stage's compensation capacitor reaches a limiting maximum and so the compensation capacitor charges and discharges in a linear manner.
If the input sine-wave signal amplitude is small enough to ensure that there is spare input stage tail current then the capacitor will charge and discharge in a manner approximating a sine-wave.
The above assumes the usual design situation where the input stage tail current current source is designed to source less current than the second stage current source and therefore the input stage tail current is the limiting factor and in this situation slew-rate could be improved by increasing the input stage tail current.
In the unusual design situation where the second stage current source is supplying less current than the input stage tail current source, then the second stage current source would be the limiting factor for the maximum rate of charge of the compensation capacitor.
The above description is a fairly basic view of the causes of slew rate limitation and in a real amplifier other factors can come into play causing effects such as unequal positive going and negative going slew rates..

A:
so how are they different in their effect?

*

*The bandwidth of the amplifier affects small signals as well as large signals

*The slew rate limit affects large amplitude output signals and may not affect smaller amplitudes

Basically, what you implied (to me) in your question.
Using the example of an op-amp, the transistor that is responsible for BW limiting has only so-much current it can use in its collector. This limit of current dictates the maximum dv/dt across the miller feedback capacitor associated with that transistor. Because \$i=C\cdot\frac{dv}{dt}\$ and, because \$i\$ is limited and \$C\$ is constant, dv/dt has to be limited hence, slew rate limiting occurs.


text:
Q: Store items in SESSION from array on link click I currently have a table populated from an array.
The issue i'm having is storing the products on "Add to Cart"
    <?php
session_start();
$products = array(
array('SKU'=>'test1', 'name'=>'ProductTest1', 'Price'=>10.00),
array('SKU'=>'test2', 'name'=>'ProductTest2', 'Price'=>11.00),
array('SKU'=>'test3', 'name'=>'ProductTest3', 'Price'=>12.00)
);

if(isset($_GET['action' && $_get['action'] == "addToCart"))
{
$id = $_GET['product']);
if(isset($_SESSION['cart'][$id])){
$_SESSION['cart'][$id]['quantity']++;
}
else
{

?>

Below is also the table php which populates correctly.
<?php foreach ($products as $key => $product) {
echo '
';
echo '' . $product['SKU'] . '	';
echo '' . $product['name'] . '	';
echo '' . '£'. number_format($product['Price'],2) . '	';
echo 'Add To Cart 	';
echo '
';
}
?>

I can't figure out how to store the name and price of the items using the GET function, which should take the value from the URL.
Any help would be great!

A: Copy the element from $products into the session variable to get the name, SKU, and price.
if(isset($_SESSION['cart'][$id])){
    $_SESSION['cart'][$id]['quantity']++;
} else {
    $_SESSION['cart'][$id] = $products[$id];
    $_SESSION['cart'][$id]['quantity'] = 1;
}

Now other scripts can access $_SESSION['cart'][$id]['name'] and $_SESSION['cart'][$id]['Price'].
Another option would be to put the $products definition in an include file, which is loaded by the other page to get this information.
Eventually you'll probably want to put your product information in a database, which could be accessed by both pages.


text:
Q: SQL Server Connection Timeout Not working I've changed the Connection Timeout to 10 seconds.
'...;Connection Timeout=10;..."
The code uses EF 6, .Net 4.5.1.
SQL Server Client has both tcp/ip and Named Pipes enabled.
Disconnected from the Network and then start debugging.
The timeout error happens at the 1 minute mark.
This seems to indicate the error happens when the sql server is not located.
Is SQL Server Ado.net client code is setting the network timeout?
I had thought this was fixed a while ago, like back in 2.0 days.


text:
Q: Does kafka-client 0.8.2.1 support ssl We have kafka broker with SSL configured with the version 0.10.2.1, but we need to write producer using Kafka client 0.8.2.1. Does this client version support SSL security?

A: No. Kafka 0.8.2.1 does not support SSL. SSL was added in 0.9.
You should consider upgrading your clients if you can as there are many new features, enhancements and security improvements since the March 11, 2015 release of 0.8.2.1
The current release (as of September 2017) is 0.11.0.1 and Kafka 1.0 is scheduled for release next month in October.

A:
Does this client version support SSL security?

No. SSL was introduced in 0.9+ version.

but we need to write producer using Kafka client 0.8.2.1

That is a questionable practice. If I were you, I would try to keep my clients as close as possible to the brokers, irrespective of whether you want SSL or not. Especially kafka, I have had my hands burnt couple of times because of the broker-client compatibility issues.


text:
Q: Detox android : Tap action has effect but the test timeouts Tap action has an effect on the emulator by showing next screen. But the test timeouts.
This issue is similar to github issue https://github.com/wix/Detox/issues/1699

A: link : https://github.com/wix/Detox/issues/2652
The issue was with animation which blocks from going idle. Please take a look at the above issue.


text:
Q: Homogeneity degree one functions of a matrix argument I am interested in homogeneity degree one (scalar-valued) functions of a matrix argument. The simplest setup is as follows. Let $X$ be a symmetric $3\times 3$ matrix with real entries. Let $f$ be a real-valued function $f(X)\in{\mathbb R}$ that takes the same value on the matrices related by an orthogonal transformation, i.e. $f(O X O^T)=f(X), \forall O\in {\rm SO}(3)$. In addition, let $f$ be a function of homogeneity degree one, i.e. $f(\alpha X)=\alpha f(X)$. As  such, these functions can be thought of as (symmetric) homogeneity degree one functions of the eigenvalues $X=O \,{\rm diag}(\lambda_1,\lambda_2,\lambda_3) O^T$, $f(X)=f(\lambda_1,\lambda_2,\lambda_3)$, or as functions on (a quotient of) the real projective space ${\mathbb RP}^2$ with $\lambda_1,\lambda_2,\lambda_3$ being the homogeneous coordinates. However, this way of thinking about these functions is not very well suited for practical manipulations, e.g. for the problem of computing the matrices of partial derivatives $\partial f^k/\partial X\partial X \ldots \partial X$.
Question 1: Is there some representation (e.g. some sort of integral transform) of such functions that makes computations of partial derivatives easy?
Question 2: What is special (e.g. as an object in ${\mathbb RP}^2$) about the following function (this time defined only for definite matrices):
$$f(X) = \left( \sqrt{\lambda_1}+\sqrt{\lambda_2}+\sqrt{\lambda_3}\right)^2$$


text:
Q: Recent posts per category loop? I need a loop/plugin/widget to display latest posts from the category the user is browsing and at the same time if he visits the home page, it should show posts from all categories (not a specific one)
Any Ideas ???

A: here is a quick one: (edit: I updated some forgotten punctuation).
<?php
/*
Plugin Name: Recent posts per category loop
Plugin URI: http://en.bainternet.info
Description: answer to http://wordpress.stackexchange.com/questions/16616/recent-posts-per-category-loop
Author: Bainternet
Version: 1.0
Author URI: http://en.bainternet.info
*/

  // Initialization function
  function WP_Widget_display_widget_init()
  {
    new WP_Widget_display_widget();
  }

  // Your Class
  class WP_Widget_display_widget extends WP_Widget
  {
    // Constructor
    function WP_Widget_display_widget()
    {
      $widget_ops = array('description' => __('recent-posts-per-category-loop', 'display_widget'));
      $this->WP_Widget('display_widget', __('Display_widget'), $widget_ops);
    }

    // Display Widget
    function widget($args, $instance) {
        extract($args);
        $title = attribute_escape($instance['title']);
        echo $before_widget.$before_title.$title.$after_title;
        display_widget();
        echo $after_widget;
    }

    // When Widget Control Form Is Posted
    function update($new_instance, $old_instance)
    {
        if (!isset($new_instance['submit']))
        {
            return false;
        }
        $instance = $old_instance;
        $instance['title'] = strip_tags($new_instance['title']);
        return $instance;
    }

    /* Your custom code starts here */
    /* ---------------------------- */

    /* Your Function */
    function display_widget()
    {

      /* Your Code ----------------- */

      function display_widget(){
    //only run on home or category
    $args['post_status'] = 'published';
    $args['posts_per_page'] = 5;
    if (is_front_page()||is_home()|| is_category())
        return '';
    if (is_category()){
        $args['cat'] = (int)get_query_var('cat');
    }
    $po = new WP_Query( $args );
    $out = '
';
    while ($po->have_posts()){
        $po->the_post();
        $out .= '
ID).'" title="'.get_the_title($post->ID).'">'.get_the_title($post->ID).'
';

    }
    $out .= '
';
    echo $out;
}

    }
  }

  add_action('widgets_init', 'WP_Widget_display_widget_init');

A: you may try this plugin if you are not knowing about code.. Latest Post from Each Category Plugin.it'll help you:)


text:
Q: Drools Decision Table Action Execution Order I have a Drools decision table (see below) whereby Rule 2 has a condition that checks whether a nutrient score is between a certain threshold and executes an action based on this condition.  There is an initial rule (RULE 1) that performs a check and performs its action, which updates the overall scores that i want Rule2 to use when executing its conditions.
What i expect/need:
Rule 1 to run, if the condition is met then update the overall score on $model (by executing its action) and then rule 2 run and for it's conditions to use the updated score value that was updated by Rule 1's action running.
What's actually happening
Rule 1 runs it's condition, Rule 2 runs its condition, Rule 1's action is run, Rule 2's action is run.  Rule 2 is running it's condition before Rule 1's action has run, and therefore uses an outdated score.
I've proven (i think) by changing the priority/salience value that i can change the order in which the rules run their conditions, but it seems that all rule conditions are running before actions.  I expected Rule 1's action to run before the next rule.
Have i fundamentally mis-understood the concept? An obvious mistake?  Or if anyone has a suggested workaround that would be great.
To clarify this is a stateless ki session.
Thanks in advance, this is driving me mad!

A: Drools works by taking all of the rules up front and evaluating whether their conditions are satisfied. Each of these rules is called a "match". When you fire the rules, Drools collects all of the matches, orders them (either naturally or by salience), and then iterates through and executes them one by one.
As the rules are executed, they might change working memory like your example does. Unless you explicitly tell Drools that you're doing so, however, it won't re-evaluate the matches. The match phase has already been completed by the time the rules are executed.
It is possible to tell Drools that you are modifying working memory and that you need it to re-evaluate its rules based on the new data. To do this, you need to use one of the built-in methods:

Method
Explanation

insert
Put a new fact into working memory.

delete or retract
Removes some information (object/s) from working memory.

update
Update/replace a fact in working memory.

modify
Change fields inside of a fact in working memory.

Which one you choose depends on what you're trying to do. Note that calling 'update' will call all matches to be re-evaluated ... it's the equivalent of calling "fire rules" a second time with the new data (so the same rule might hit multiple times, which may or may not be intentional). In comparison, insert will only evaluate subsequent rules to determine if they now match or don't based on the new conditions.
So if your intention is to cause other rules to fire or not by changing the data in working memory, you'll need to use one of these built-in methods to tell Drools that you're making a change that it should re-evaluate its matches for.
I discuss this concept in more detail in this answer specifically about DRL. The same concepts apply to decision tables.


text:
Q: How to get from a string array? an array of server:

Array ( [28.01.2015] => Array ( [03] => 2 [02] => 4 ) )

was converted into a string using the json_encode.
The result was a string:
{"28.01.2015":{"03":2,"02":4}}

How to use Javascript to convert this string into an array ?

A: JSON.parse('{"28.01.2015":{"03":2,"02":4}}');

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

A: You can turn that into a JavaScript object by using JSON.parse():
var my_object = JSON.parse('{"28.01.2015":{"03":2,"02":4}}');

A: For achieve this, you need use JSON.parse.
JSON.parse('{"28.01.2015":{"03":2,"02":4}}');

Or you could organize better:
var string = '{"28.01.2015":{"03":2,"02":4}}';
var object = JSON.parse(string);


text:
Q: Automorphism of a graph which is like Kneser graph Thanks for any help or comment.
Consider the following graph:
$X=\{1,2,\dots,6\}$ and a vertex of graph is the following set $Y=\{a,b\}\cup\{c,d\}$, where $a,b,c,d\in X$. There exist an edge between to vertices $Y_1=\{a,b\}\cup\{c,d\}$ and $Y_2=\{a',b'\}\cup\{c',d'\}$ if and only if $Y_1\cap Y_2=\{a,b\}$ or $\{c,d\}$. So this graph has 45 vertices and for example if $Z_1=\{1,2\}\cup\{3,4\}$ and $Z_2=\{1,3\}\cup\{2,4\}$ and $Z_3=\{1,2\}\cup\{5,6\}$, then there exist an edge between $Z_1,Z_3$ and there is no edge between
$Z_1,Z_2$ and $Z_2,Z_3$.
What is the structure of automorphism group of this graph?


text:
Q: OpenCL OpenGL interop kernel argument for read+write I am trying to do OpenCL/OpenGL interop using an OpenGL texture as described at this Intel tutorial. I want to keep my host code as simple as possible, so I wanted to go with "Method 1", thus creating an OpenCL image from an OpenGL texture with clCreateFromGLTexture. The tutorial also states the following:

Note the CL_MEM_WRITE_ONLY flag that allows fast discarding of the data. Use CL_MEM_READ_WRITE if your kernel requires reading the current texture context. Also, remove the _write_only qualifier for the image access in the kernel in that case.

However, this does not seem to work. As soon as I remove __write_only from the kernel, I get a compile error, using platform Nvidia OpenCL 1.2 CUDA 10.0.132 (driver 417.71):

Error: Invalid image type in sust.

Whatever that means. Using the platform Intel OpenCL 2.1 UHD Graphics 620 (driver 24.20.100.6286) I get the following:

CTHeader.h:1333:38: note: candidate function not viable: no known conversion from 'read_only image2d_t' to '__write_only image1d_array_t' for 1st argument   void __attribute((overloadable)) write_imagef(write_only image1d_array_t image_array, int2 coord, float4 color);

Seems like image2D_t defaults to __read_only?
Anyways, I found that the specification clearly states that what is proposed in the tutorial is not supported, at least not using image objects:

read_image and write_image calls to the same image memory object in a kernel are not supported

So I am wondering, since the tutorial does not go into detail in how to set up the kernel argument, maybe using image2d_t is wrong in the first place. Since the argument is of type cu_mem at host side, I tried around with float*, but without success so far.
I realize I could do double buffering or go with other methods like using a PBO for interop, but as I said, I want to keep things as simple as possible, plus I'm just wondering why that is. Any ideas?

A: A kernel image parameter must be qualified with __write_only or __read_only, up to OpenCL 2.0, which allows images to be __read_write but special rules must be followed (such as barriers) to get correct results. Note that an image also has qualifier which indicate how the host may access it (read only, write only, or read/write). A given image may be __write_only in one kernel and then __read_only in the next, which allows for the results of one kernel to feed into the next.


text:
Q: Bootstrap 4 - 3 divs, 1 left, 2 right In Bootstrap 4, I have three divs:

A

B

C

Is there a way, without placing div B and C inside another div, to achieve this:
A  B
   C

A:
Is there a way, without placing div B and C inside another div, to achieve this:

A  B
   C

Yes, you can achieve this by using offset classes like so:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

A

B

C

Note: The column classes and the offset class are not responsive in the example shown above. To make them responsive, you need to add the appropriate infixes.
Reference:
https://getbootstrap.com/docs/4.0/layout/grid/#offsetting-columns
https://getbootstrap.com/docs/4.0/layout/grid/#responsive-classes

Now say div A is 600px heigh, B and C are both 50px heigh. I don't want A to push C down. I want C to go right below B. What now?

In this case, you'd want to use the d-block clearfix and float-left + float-right classes like so:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

A

B

C

In this case, d-block switches from the default flexbox to "display:block" for the row and the float-left/float-right classes tell the columns where to float.
Reference:
http://getbootstrap.com/docs/4.0/utilities/float/
https://getbootstrap.com/docs/4.0/utilities/clearfix/

A: What you can do is assign a class to A and put a float-left in css, then its just a matter of margins etc.

A

B

C

Css code
.left{
float:left;
}


text:
Q: Using webpack-i18n-plugin with CommonsChunkPlugin The requirement is to create app bundle per each language and also split vendor modules. The following webpack.config.js
// webpack.config.js
var webpack = require('webpack')
var path = require('path')
var I18nPlugin = require("i18n-webpack-plugin")

var locales = {
    "en": require("./m1/js/en.json"),
    "ja": require("./m1/js/ja.json")
}

module.exports = Object.keys(locales).map(function (locale) {
    return {
        name: locale,
        entry: "./m1/js/main.js",
        output: {
            filename: 'app-' + locale + '.js',
            path: path.resolve(__dirname, 'm1/js/build')
        },
        plugins: [
            new I18nPlugin(
                locales[locale],
                {
                    functionName: '_t',
                }
            ),
            new webpack.optimize.CommonsChunkPlugin({
                name: 'vendor',
                minChunks: function (module) {
                    return module.context && module.context.indexOf('node_modules') !== -1;
                }
            })
        ]
    }
})

throws following errors:
ERROR in chunk vendor [entry]
app-en.js
Conflict: Multiple assets emit to the same filename app-en.js

ERROR in chunk vendor [entry]
app-ja.js
Conflict: Multiple assets emit to the same filename app-ja.js

Can someone help me with this?

A: Well, I changed my web.config.js like below:
...
        new webpack.optimize.CommonsChunkPlugin({
            name: 'vendor',
            filename: 'vendor.js',
            minChunks: function (module) {
                return module.context && module.context.indexOf('node_modules') !== -1;
            }
        })
...

and it worked. I'm just not sure whether it is efficient or correct. My concern is map function. Is it writing to vendor.js for each locale?


text:
Q: Is there a checklist out there for when I launch a node.js based site? I'm finishing up building my first site with node.js and I'm curious if there is a checkoff list for all the things that I should complete before I get it up. In development when certain values are not expected in my database calls, (using Mongoose), my site will just die (e.g. node segfaults).
I'll also be using this on a VPS of mine that already have Apache installed on it, so will I be able to run both or do I need to look into something else for that?
Basically once it's up, I want to keep it up, and I'd like to know of any standard precautions I should know of before doing so.
Thanks!

A: I'm currently in a similar situation (about to deploy my first app on a private VPS), and here is the list I came up with:
1- Error logging: I used a simple WriteStream here, nothing too fancy.
var fs = require('fs');
//You might want to specify a path outside your app
var file = './log.log';
var logger = fs.createWriteStream('./log.log');
app.configure(function(){
    //...
    app.set(express.logger({stream:logger}));
    /...
});

2- Use Forever to ensure that your script will run continuously. Yes, they are plenty of other solutions (using a daemon, for example), but I've been using forever for a while now, and never had any problems.
3- Consider setting up an admin interface. This was actually a requirement in my case, so I went ahead with smog, which will look very nice, especially for your client :).
4- If you use forever, you can monitor its state using Monit. Check out this blog post for a basic setup.
5- If you are using Mongo, consider developing a backup strategy of your data. This page is a very good starting point.

Note that this list does not contain any information regarding multi-app, multi-machine or multi-core support.
If multi-app support interests you, nginx seems to be a trusted solution. This (brilliant) SO answer will help you get set up.
If you have many spare machines to use, node-http-proxy was developed by nodejitsu, and allows you to expose only one machine and reverse-proxy the rest.
If you are looking for multi-core support, cluster comes bundled with node, so you can spawn N different processes (N being the number of cores you have) and have them listen to the shared port.
And, since we all love to hear a nice story, here a few posts about nodejs/mongodb use in production and the lessons learned:
1- Lessons learned from launching i.TV
2- Using Mongodb for 2+ billion documents on craigslist

A: Given that Node.js is not a web server like Apache or IIS, there's no checklist of configuration settings to follow.  Also, given that the modules and/or frameworks you use can vary widely based upon the project you are creating, checklists would always miss something...especially as the Node.js ecosystem continues to evolve and grow.
As such, I'd suggest reviewing the material here as they answer your questions and are generally useful no matter what you are doing with Node.js:

*

*What should every programmer know about web development? - list you should run through to be sure you didn't forget anything generally relevant.

*Node Express Mongoose Demo - example code that can show you how to handle errors gracefully, structure your code, use require statements to break up code, add environment-specific configuration, etc.

*Node.js Best Practice Exception Handling - additional info on handling problems

*Apache and Node.js on the Same Server - the most simple answer is "sure, just make sure you are using different ports".  If you want both to run and answer on port 80, then things are more complicated.

I am concerned that your app dies "when certain values are not expected in my database calls".
Mongoose is a nice tool because it allows for custom data validations on individual fields, can filter out data that doesn't fit into the Schema you have defined (keeping your documents consistent), and with the right settings can throw errors when there is 'bad data' passed to it rather than send bad data to the database, and more...
I'm wondering what you are doing that an unhandled error is making it pass Mongoose and past any callback function knowing that callbacks usually take the format function(err, data) and present the opportunity to deal with the error immediately.


text:
Q: Connecting Apache and Tomcat using mod_proxy_ajp works but JDBC then fails I have a working Apache 2.2.16 on Debian Squeeze that serves some PHP applications from /var/www/ using different domains (e.g. phpApp1.com, phpApp2.com).
I also have a working Tomcat 7.x that lives in /opt/tomcat/ and servers a JSF+JPA application that lives in /opt/tomcat/webapps/MyApp/.
So MyApp can be accessed through e.g. myapp.com:8080/MyApp/home.html or phpApp1.com:8080/MyApp/home.html (because of the port). Since I wanted this to be myapp.com/home.html instead, I connected Apache and Tomcat using mod_proxy_ajp using the following config files:
An Apache virtual host in /etc/apache2/sites-available/MyApp
<Virtualhost *:80>
    ServerName myapp.com
    ServerAlias *.myapp.com
    ProxyPass / ajp://localhost:8009/
    ProxyPassReverse / ajp://localhost:8009/
</Virtualhost>

And a Tomcat virtual host in /opt/tomcat/conf/server.xml
<Host name="myapp.com" appBase="webapps" unpackWARs="true" autoDeploy="true">
    <Context path="" reloadable="true" debug="0" docBase="MyApp" />
    <Alias>www.myapp.com</Alias>
</Host>

This works to the point that I cann access http://myapp.com/home.html and get a correct html page including css, images and js. So the AJP connector in tomcat should work.
BUT the app fails to establish a JDBC connection that otherwise works fine. It does not matter whether i use myapp.com or myapp.com:8080, it fails either way. However, it works if I access my app throug http://phpapp1.com:8080/MyApp/home.html. It only fails when I use the proxy-domain "myapp.com".
Has anyone experienced similar problems when using AJP and JDBC? How can I solve this? I had the same problem when using mod_jk, which makes use of AJP, too. Thanks in advance.
Update 1
@Mark Rotteveel: What do you mean by "connecting directly"? I mean the JDBC connection is working if I use one of the domains that are not listed as virtual hosts in tomcats server.xml.
Here is the connection error:
ERROR: HHH000231: Schema export unsuccessful
org.apache.tomcat.dbcp.dbcp.SQLNestedException: Cannot create JDBC driver of class '' for connect URL 'null'
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1452)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createDataSource(BasicDataSource.java:1371)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.getConnection(BasicDataSource.java:1044)
at org.hibernate.service.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:141)
at org.hibernate.tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.prepare(SuppliedConnectionProviderConnectionHelper.java:51)
at org.hibernate.tool.hbm2ddl.DatabaseExporter.<init>(DatabaseExporter.java:52)
at org.hibernate.tool.hbm2ddl.SchemaExport.execute(SchemaExport.java:367)
at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:304)
at org.hibernate.tool.hbm2ddl.SchemaExport.create(SchemaExport.java:293)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:492)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1744)
at org.hibernate.ejb.EntityManagerFactoryImpl.<init>(EntityManagerFactoryImpl.java:94)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:905)
at org.hibernate.ejb.Ejb3Configuration.buildEntityManagerFactory(Ejb3Configuration.java:890)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:57)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:63)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:47)
at com.myapp.util.database.Database.<init>(Database.java:70)
at com.myapp.util.database.Database.<clinit>(Database.java:38)
at com.myapp.controller.file.UploadBacking.ajaxUpload(UploadBacking.java:89)
at com.myapp.controller.file.UploadBacking$Proxy$_$$_WeldClientProxy.ajaxUpload(UploadBacking$Proxy$_$$_WeldClientProxy.java)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.el.parser.AstValue.invoke(AstValue.java:264)
at org.apache.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:278)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:39)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at org.apache.myfaces.view.facelets.el.ContextAwareTagMethodExpression.invoke(ContextAwareTagMethodExpression.java:96)
at org.apache.myfaces.view.facelets.tag.jsf.core.AjaxHandler$AjaxBehaviorListenerImpl.processAjaxBehavior(AjaxHandler.java:495)
at javax.faces.event.AjaxBehaviorEvent.processListener(AjaxBehaviorEvent.java:57)
at javax.faces.component.behavior.BehaviorBase.broadcast(BehaviorBase.java:74)
at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:405)
at javax.faces.component.UICommand.broadcast(UICommand.java:103)
at javax.faces.component.UIViewRoot._broadcastAll(UIViewRoot.java:1028)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:286)
at javax.faces.component.UIViewRoot._process(UIViewRoot.java:1375)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:752)
at org.apache.myfaces.lifecycle.InvokeApplicationExecutor.execute(InvokeApplicationExecutor.java:38)
at org.apache.myfaces.lifecycle.LifecycleImpl.executePhase(LifecycleImpl.java:170)
at org.apache.myfaces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:117)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:197)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.ocpsoft.rewrite.servlet.RewriteFilter.doFilter(RewriteFilter.java:183)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:225)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:472)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:168)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:407)
at org.apache.coyote.ajp.AjpProcessor.process(AjpProcessor.java:200)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:579)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:310)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.NullPointerException
at sun.jdbc.odbc.JdbcOdbcDriver.getProtocol(JdbcOdbcDriver.java:507)
at sun.jdbc.odbc.JdbcOdbcDriver.knownURL(JdbcOdbcDriver.java:476)
at sun.jdbc.odbc.JdbcOdbcDriver.acceptsURL(JdbcOdbcDriver.java:307)
at java.sql.DriverManager.getDriver(DriverManager.java:253)
at org.apache.tomcat.dbcp.dbcp.BasicDataSource.createConnectionFactory(BasicDataSource.java:1437)
... 60 more

From Database.java:
private Database() {
    entityManagerFactory = Persistence.createEntityManagerFactory("myapp_persistence_unit");
}

MyApp/META-INF/context.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE Context>

<Context>

<Resource
    name="jdbc/db_myapp"
    auth="Container"
    type="javax.sql.DataSource"
    username="user_myapp"
    password="##########"
    driverClassName="com.mysql.jdbc.Driver"
    url="jdbc:mysql://localhost:3306/db_myapp?autoReconnect=true"
    validationQuery="select 1"
    maxActive="15"
    maxIdle="3" />

<Valve
    className="org.apache.catalina.valves.AccessLogValve"
    directory="logs/myapp"
    prefix="myapp_access_"
    suffix=".log"
    pattern="%h %l %u %t "%r" %s %b"
    resolveHosts="false" />

</Context>

From WEB-INF/web.xml
<resource-ref>
    <description>MySQL database</description>
    <res-ref-name>jdbc/db_myapp</res-ref-name>
    <res-type>javax.sql.DataSource</res-type>
    <res-auth>Container</res-auth>
</resource-ref>

And finally WEB-INF/classes/META-INF/persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
    xmlns="http://java.sun.com/xml/ns/persistence"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
    http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">

    <persistence-unit name="myapp_persistence_unit">
        <properties>
            <property name="hibernate.connection.datasource" value="java:comp/env/jdbc/db_myapp" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect" />
            <property name="hibernate.current_session_context_class" value="thread" />
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
            <property name="hibernate.hbm2ddl.auto" value="create-drop" />
        </properties>
    </persistence-unit>

</persistence>

A: I finally got it to work. If you create a virtual host in tomcat, you have to put an exact copy of your applications /META-INF/context.xml into /tomcat/conf/Catalina/domain.com/ and name it context.xml.default. Well, I don't know if this is always the case, but for my setting it was. So these are my current config files that do the job:
/etc/apache2/sites-enabled/domain.com
<Virtualhost *:80>
    ServerName domain.com
    ServerAlias *.domain.com

    ProxyRequests Off
    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>
    ProxyPass / ajp://my.server.ip:8009/
</Virtualhost>

/tomcat/conf/server.xml
<Host name="domain.com">
    <Context path="" docBase="MyApp" />
    <Alias>www.domain.com</Alias>
</Host>

I tried this after reading this thread on coderanch.com from 2006 (the authors solution is in the last post). I did not change the web.xml or context.xml since this was not a misconfiguration of the <Resource> element. Anyway, thanks for your attempts to help :)

A: Make sure you have your mysql-connector-j.x.y.z.jar file in exactly one place: Tomcat's lib directory. Make sure you don't have a stray copy in any of your webapps' WEB-INF/lib directories.
Two unrelated tips:

*

*Don't use autoReconnect

*Use /* ping */ SELECT 1 as your validation query: recent versions of Connector/J will use a lightweight "ping" instead of actually issuing a query in order to test a connection's validity


text:
Q: Is taking a Taylor expansion of $x^{x^x}$ possible? Disclaimer: I do not know that much math, so there might be obvious mistakes that I make in this question.
As far as I can tell, taking the derivative of $x^{x^x}$ infinitely is possible. However, this does not mean a Taylor series is possible. So what I am asking is, is it possible. I see 5 possible outcomes:

*

*It is possible, and the answer is known/easy enough to figure out

*It has been proven to be possible, but we don't know what it is yet

*It has been proven to be impossible, and cannot be done

*It may or not be possible, we don't know yet

*Other

So, which one of these is it?

A: It is possible and it is the same for all tetrations. In this case, around $x=0$, it would be
$$x^{x^x}=x+\sum_{n=2}^p \frac {t^n}{(n-1)!} P_n(t)\, x^{n}+O(x^{p+1})\qquad \text{with} \qquad t=\log(x)$$ and the first polynomials are
$$\left(
\begin{array}{cc}
 2 & 1 \\
 3 & t+1 \\
 4 & t^2+3 t+1 \\
 5 & t^3+6 t^2+7 t+1 \\
 6 & t^4+10 t^3+25 t^2+15 t+1 \\
 7 & t^5+15 t^4+65 t^3+90 t^2+31 t+1 \\
 8 & t^6+21 t^5+140 t^4+350 t^3+301 t^2+63 t+1
\end{array}
\right)$$ where you can notice interesting patterns.
Have a look here for the next one.


text:
Q: Uncomment multiple lines in eclipse I want to uncomment multiple line of code in eclipse, but whenever i tried to use ctl+Shift+/ it recomment the whole line of code. can anybody tell the shortcut

A: You can use CTRL + SHIFT + C to toggle comments marks.
Or CTRL + SHIFT + \ to uncomment.
More info on the Source tab in the main menu. Or in the Key assistant: CTRL+ SHIFT+ L

A: You can use CTRL + SHIFT + C to add comments marks. And CTRL + SHIFT + \ to uncomment.


text:
Q: Get session from cordova webview In my cordova app i am loading a web application. In my app the login details are stored in session. When closing the app and re open it shows as logged in. I want to retrieve the stored sessions. My cordova code is shown below.
index.js
var app = {
    // Application Constructor
    initialize: function() {
    window.location.replace("http://xxx.xxx.xxx:30/");
    this.bindEvents();
    },
    bindEvents: function() {
        document.addEventListener('deviceready', this.onDeviceReady, false);
    },
    onDeviceReady: function() {
        app.receivedEvent('deviceready');
    },
    receivedEvent: function(id) {
        var parentElement = document.getElementById(id);
        var listeningElement = parentElement.querySelector('.listening');
        var receivedElement = parentElement.querySelector('.received');
        console.log('Received Event: ' + id);
    }
};
app.initialize();

In my web app $.session.set("username", $resData.username); is used for storing session. but when i am using $.session.get("username") in index.js. I didn't get value. How to retrieve the sesion values.


text:
Q: DoubleRenderError after send_file I have strange problem in this code snippet:
def export_csv
    user = User.find_by_u_token(params[:u])
    return render json: {status: 'error', descr: 'INVALID_U_TOKEN'} if !user
    return render json: {status: 'error', descr: 'INVALID_DELIMITER'} if !user.csv_del
    return render json: {status: 'error', descr: 'PARAMS_NOT_DEFINED'} if !params[:invoices]
    return render json: {status: 'error', descr: 'INVALID_USER_TYPE'} if !user.contractor? && !user.customer?

    invoices = invoices_for_user(user)
    pinvoices = params[:invoices].split(' ')

    return render json: {status: 'error', descr: 'INVALID_INVOICES'} if !check_invoices(invoices, pinvoices)

    export_invoices(pinvoices, user.csv_del)
    send_file("file.csv")

    return render json: {status: 'ok'}
end

My export_invoices method:
def export_invoices(pinvoices, delimiter)
    CSV.open("file.csv", "wb", {:col_sep => delimiter}) do |csv|
      Invoice.find(pinvoices).each do |i|
        csv << i.attributes.values
      end
    end
end

And I have Render and/or redirect were called multiple times in this action. error.
I've tried to comment the line send_file("file.csv") and everything works.
Where is the problem?

A: in above code remove the line return render json: {status: 'ok'} and create a template export_csv.js.erb here you write your success code

A: Basically, the error message you're getting is telling you you can only call render once.
send_file is actually doing a render. You get the error when you reach the last line in your code that does another render.
The question is, what do you expect the code to render in the end? is it the CSV file or the json response? you can't have both. So obviously, you want to remove the line in which you return the json response.

A: Try removing the
return render json: {status: 'ok'}

Reason it will work :
  cause send_file itself will render, so it doesn't make any sense to do that again.


text:
Q: Can not pull or merge git. "Working copy has uncommited changes" How can I fix pull issue.
When I pull from xcode then it is giving error "Can not pull working copy has uncommited changes"

A: You have to do commit or to stash your code.
1. Commit
If you have changes and you cant pull you can simply commit your changes.
# add the desired files to the index
git add .

# commit your changes
git commit -m "Message..."

# now pull your changes
git pull origin <branch>

2. Stash
# stash your changes and pull them back later on
# add the [-u] flag for untracked files if needed
git stash save <name>

# pull the new content
git pull origin <branch>

# get back the code which you stashed
git stash pop


text:
Q: Unity IOC, can't fix the parameterless constructor issue I have the following constructor (only one for the controller):
[Authorize]
public class AccountController : Controller
{
    public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager,
        IAccountService accountSrv)
    {
        UserManager = userManager;
        SignInManager = signInManager;
        AccountService = accountSrv;
    }

    private IAccountService AccountService { get; }

    private ApplicationSignInManager SignInManager { get; }

    private ApplicationUserManager UserManager { get; }

And I'd like MVC to call it with proper parameters, so I tried this:
Global.asax.cs
public class MvcApplication : HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        DALMapper.Mapping();
        LabMapper.Mapping();

        var container = new UnityContainer();
        container
            .RegisterType<IDALContext, DALContext>()
            .RegisterType<IConsultantService, ConsultantService>()
            .RegisterType<IProjectService, ProjectService>()
            .RegisterType<IAccountService, AccountService>()
            .RegisterType<AccountController, AccountController>()
            .RegisterType<ApplicationUserManager, ApplicationUserManager>()
            .RegisterType<ApplicationSignInManager, ApplicationSignInManager>()
            .RegisterInstance<IAccountService>(new AccountService(new DALContext()), new ContainerControlledLifetimeManager())
        ;

        DependencyResolver.SetResolver(new UnityDependencyResolver(container));

(UnityDependencyResolver being:)
public class UnityDependencyResolver : IDependencyResolver
{
    private readonly IUnityContainer _container;

    public UnityDependencyResolver(IUnityContainer container)
    {
        _container = container;
    }

    public object GetService(Type serviceType)
    {
        try
        {
            return _container.Resolve(serviceType);
        }
        catch
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return _container.ResolveAll(serviceType);
        }
        catch
        {
            return new List<object>();
        }
    }
}

Where I register every types needed (the result feel weird though when in/from types are the same (I'm that new to Unity)).
But it doesn't work. (As far as I know, since MV3, the default controller factory will use the service locator, so one doesn't need to implement it's own factory).
What's wrong?
Current result:
Server Error in '/' Application.

No parameterless constructor defined for this object.

A: If I understand your problem correctly, there's a problem resolving the dependencies for ApplicationUserManager  and ApplicationSignInManager.
This is the code that solved the problem for me:
//for accountcontroller
        container.RegisterType<DbContext, ApplicationDBContext>(new HierarchicalLifetimeManager());
        container.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
        container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());
        container.RegisterType<IAuthenticationManager>(new InjectionFactory(o => HttpContext.Current.GetOwinContext().Authentication));

A: After digging it up more (downloaded the Unity source code, built it, added a reference to the dll, added the pdb to the symbols locations (debug))*, I could see the error was coming from another constructor which requirs parameters.
public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }

(I've yet to solve this, but that should be easy).
*is there an easier way to step into a third party library's code? Let me know in the comment.


text:
Q: error apache2 chmod 777 only works I have my first server and i don't undeststand many things.
First, i've created one user called guillaume and create a specific folder in /home/web and put my website in there and it works BUT...
i've created a second website and it's work but only with chmod 777
i've made chmod -R guillaume:guillaume *
and chmod -R 777 *
but if i do
chmod -R 755 *
i've an error 500, file cannot be writed...
So i don't understand why i don't change permissons to 755, on my first domain it works well.
there is my vhosts:

<VirtualHost *:80>
 ServerName bio.dev2prod.fr
 ServerAdmin guillaume.batier@gmail.com
 DocumentRoot /home/guillaume/web/bio.dev2prod.fr/public
 <Directory />
     Options Indexes FollowSymLinks Includes ExecCGI
     AllowOverride All
     Require all granted
     Allow from all
 </Directory>

 <Directory /home/guillaume/web/bio.dev2prod.fr>
  Options FollowSymLinks
  Require all granted
  Order allow,deny
  allow from all
  Options Indexes FollowSymLinks MultiViews
  AllowOverride All
 </Directory>
 ErrorLog ${APACHE_LOG_DIR}/error.log
 CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

what am i doing wrong ?
PS: i put my user to www-data group ? it that good ?
Thanks and sorry for my bad english, i'm french..
PS: i'm using laravel 5 so the document root is in /public folder

A: The problem could be caused by several issues. So let me ask a few questions.

*

*(if I'm not totally wrong) the first <Directory> directive points to the root directory. wich might not directly relate to your problem but are you sure to map any file? I guess it should be same as <DocumentRoot>

*The <DocumentRoot> should be the base directory for the particular vhost. So the <Directory> path should normaly belong to a sub directory of the DocumentRoot.

*If you wan't to use directories from outside the DocumentRoot mod_alias might be worth looking at.
Alias /somalias/  /path/to/somewhere/else
Hope this helps you a bit.


text:
Q: Validating whether PDF file Uploaded as part of Geoprocessing Service of ArcGIS for Server? I'm developing a Python Script that will be a Geoprocessing Service in ArcGIS Server.
The Script has a Button for Users to OPTIONALLY Upload a PDF.
If the PDF is Uploaded it gets inserted into the pack.
If no Upload I want the Code to Skip appending Page.
How would I perform the Check and pass if no Upload?


text:
Q: security risk? why ubuntu apply strange permissions in /boot/initrd* and /boot/vmlinuz*? the initrd.img are all 644, the vmlinuz in another hand is 600. This is reversed on many other distros if not all.  I think other distros actually do it correctly. the content in vlinuz is all public available there is no secrets in there. However, the initrd can contain all sorts of customized settings which can expose attack surface when other instead of root can read its content. Moreover, it is a trends that people will include luks key in initrd when they do full disk encryption. Thus it is absolutely no! no! to set the initrd globally readable.
What is the reason behind this design? Why ubuntu need the initrd.img to be globally readable? Is there any functionality depends on this?
I hope experienced user can tell me how to make the initrd.img permanently 600 in ubuntu. Since these files are automatically generated during kernel updates. Maybe add some script in /etc/kernel/postinst.d/ ?

A: I see a difference between 20.04 and 22.04 which I have both installed on my machine. In 20.04 I see the behaviour you describe in your question while in 22.04 the initrd.img* files have 600 permissions.
Stumbling about this bug I checked the files in /etc/initramfs-tools and found the relevant file which exists in 22.04 but not in 20.04:
~$ sudo cat /etc/initramfs-tools/conf.d/calamares-safe-initramfs.conf
[sudo] password for mook:
UMASK=0077
~$ ls -l /etc/initramfs-tools/conf.d/calamares-safe-initramfs.conf
-rw------- 1 root root 11 Apr 25 02:53 /etc/initramfs-tools/conf.d/calamares-safe-initramfs.conf

So I think, this is the file you need to add to get safe permissions for your initrd.img* files.
This will, of course not affect already existing initramfs images, use chmod to change their permissions to 600.

A: The kernel and symbols files are installed with permissions 0600 so exploits cannot read these files to learn what addresses or offsets to use in attacks. It's far from foolproof, since an attacker can download all the kernel packages ahead of time and build the necessary offset tables themselves, but it is additional work.
It might make sense to change the default initramfs permissions as described in @mook765's answer. If you feel strongly about it, please file a bug report. The help.ubuntu.com article on full disk encryption includes this step alongside the advice on how to embed keys into the initramfs.
The defaults should be safe for users that do not embed key material for other filesystems into their initramfs. (I believe this is a very rare configuration.)


text:
Q: React: how to pass props from child to parent to another child? I have a simple set up here:
I have a parent component which has 2 child components attached to this parent component. In the 1st child component: User changes the value of an input. The value of that change would then be a prop I'd like to pass from this child to the parent so that it can be passed to the other child attached to the same parent component.
Main (parent component)___|
                          |_Child 1
                          |_Child 2

this the set up currently, please view
The flow from user input to change in UI: 1. In "Child 1": adjust a slider, onChange pass value to parent component; 2. pass this prop (the new slider value) to the Parent component so that it can be available to the "Child 2" component; 3. That prop, the valueOfUserInput (the new slider value) would then be used in an if/else statement about styling the element of the "Child 2" component.
I've seen solutions and tutorials which are similar to my question, but they don't quite make sense to me. I've been hacking away at this all day, interspersed by meetings.
Any help or suggestions would be amazing. Thank you all for you patience with this React noob.

A: Your diagram sort of makes sense, and I think I know the key piece that you're missing. The idea of Child 1 passing the prop up to the parent is partially correct... but how you pass that prop is that you must pass a function down to Child 1 from parent. So in parent, you'd have something like...
handleChange(val) {
  this.setState({ blah: val }) // you are going to pass blah down to Child 2
}

and then in your render function in Parent, you're passing this function down...
<Child 1 onChange={this.handleChange} />

Inside of `Child 1, you need to call that function.
<input onChange={this.props.onChange(val)} />

Child 1 now goes "hey, Parent, I've been changed, and I got some value here, you do the rest". Parent handles the event by setting its state, and then it can pass it down to whoever. Hopefully that makes sense, but this should be a helpful start.

A: I would personally use react-redux to do this communication. Redux, on a high level, is a global state manager. You can modify and access the reducer values from any of your components. Feel free to take a look at the boilerplate I made: https://github.com/rjzheng/REWBoilerplate/. If you look under '/app', you can see how everything is set up in the '/reducer' and '/store' folders. To learn how to use them, there's a pretty comprehensive documentation on it at http://redux.js.org/docs/basics/UsageWithReact.html.

A: When you want 2 children to communicate or share some data, the way to do it in React is to lift state up (source).
This means that the state that the children use should live in the parent. Then the parent passes the state down to the children.
To update the state from an action in a child, the usual pattern is to pass down a function from the parent that gets called when the action is performed in the child.
Here's an example that should do what you want:
class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.state = { valueOfUserInput: '' };
  }

  handleUserInputChange = event => {
    this.setState({
      valueOfUserInput: event.target.value,
    });
  };

  render() {
    const { valueOfUserInput } = this.state;
    return (

        <Child1 valueOfUserInput={valueOfUserInput} onUserInputChange={this.handleUserInputChange} />
        <Child2 valueOfUserInput={valueOfUserInput} />

    );
  }
}

class Child1 extends React.Component {
  render() {
    const { valueOfUserInput, onUserInputChange } = this.props;
    return <input type="text" value={valueOfUserInput} onChange={onUserInputChange} />;
  }
}

class Child2 extends React.Component {
  render() {
    const { valueOfUserInput } = this.props;
    return (

        {valueOfUserInput}

    );
  }
}

A: You can pass a function down from the parent to both of the children, to allow setting of the value. You may want to pass the value as another property. The function in the parent should make a call to setState with this new value, which will cause re-rendering of itself and any children.
So in this way the value is updated and passed to the other child.
You can also do this if you are using redux, as it is designed to allow state management outside of a component.


text:
Q: Caching JSON response to use when the device is offline I am building a news app and I want to cache a JSON response to use when there is no network. I tried a lot of ways but it did not work for me.
My async task and my adapter are another side problem when the list loads new items it goes to the top of the screen and after that it adds the items. How can I fix this?
private class jsontask extends AsyncTask<String, String, List<newsmodel>> {
    @Override
    protected List<newsmodel> doInBackground(String... params) {
        BufferedReader reader = null;
        HttpURLConnection connection = null;
        try {
            URL url = new URL(params[0]);

            connection = (HttpURLConnection) url.openConnection();

            connection.connect();
            InputStream stream = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(stream));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            String finaljson = buffer.toString();
            JSONObject parentobject = new JSONObject(finaljson);

            JSONArray parentarray = parentobject.getJSONArray("articles");

            for (int i = 0; i < parentarray.length(); i++) {
                JSONObject finalobject = parentarray.getJSONObject(i);
                newsmodel newsmodel = new newsmodel();
                newsmodel.setAuthor(finalobject.getString("author"));
                if (finalobject.isNull("author")) {
                }
                newsmodel.setDescription(finalobject.getString("description"));
                newsmodel.setTitle(finalobject.getString("title"));
                newsmodel.setImage(finalobject.getString("urlToImage"));
                newsmodel.setUrl(finalobject.getString("url"));
                newsmodel.setPublishedAt(finalobject.getString("publishedAt"));

                moviemodelList.add(newsmodel);
            }

            return moviemodelList;

        } catch (MalformedURLException e) {
            e.printStackTrace();
return moviemodelList;
        } catch (IOException e) {
            e.printStackTrace();
            return moviemodelList;
        } catch (JSONException e) {

        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    @Override
    protected void onPostExecute(List<newsmodel> result) {

        super.onPostExecute(result);
        newsadapter adapter = new newsadapter(getApplicationContext(), R.layout.row, result);
        lvnews.setAdapter(adapter);
    }
}

public class newsadapter extends ArrayAdapter {
    private List<newsmodel> moviemodelList;
    private int resource;
    private LayoutInflater inflater;

    public newsadapter(Context context, int resource, List<newsmodel> objects) {
        super(context, resource, objects);
        moviemodelList = objects;
        this.resource = resource;
        inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        viewholder holder = null;
        if (convertView == null) {
            holder = new viewholder();
            convertView = inflater.inflate(resource, null);
            holder.newsimage = (ImageView) convertView.findViewById(R.id.imageView2);
            holder.title = (TextView) convertView.findViewById(R.id.textView2);
            holder.description = (TextView) convertView.findViewById(R.id.textView3);
            holder.author = (TextView) convertView.findViewById(R.id.textView4);
            holder.publishdate = (TextView) convertView.findViewById(R.id.textView5);
            holder.dotsmenu = (ImageButton) convertView.findViewById(R.id.dots);
            convertView.setTag(holder);
        } else {
            holder = (viewholder) convertView.getTag();
        }

        final ProgressBar progressBar;
        progressBar = (ProgressBar) convertView.findViewById(R.id.progressBar);
        ImageLoader.getInstance().displayImage(moviemodelList.get(position).getImage(), holder.newsimage, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {
                progressBar.setVisibility(view.VISIBLE);
            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                progressBar.setVisibility(view.GONE);
            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                progressBar.setVisibility(view.GONE);
            }

            @Override
            public void onLoadingCancelled(String imageUri, View view) {
                progressBar.setVisibility(view.GONE);
            }
        });
        holder.title.setText(moviemodelList.get(position).getTitle());
        holder.description.setText(moviemodelList.get(position).getDescription());
        holder.author.setText(moviemodelList.get(position).getAuthor());
        holder.publishdate.setText(moviemodelList.get(position).getPublishedAt());
        final viewholder finalHolder = holder;
        holder.dotsmenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupMenu popup = new PopupMenu(page.this, finalHolder.dotsmenu);
                //Inflating the Popup using xml file
                popup.getMenuInflater().inflate(R.menu.dots_menu, popup.getMenu());
                popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch (item.getItemId()) {

                            case R.id.share:
                                Intent sendIntent = new Intent();
                                sendIntent.setAction(Intent.ACTION_SEND);
                                sendIntent.putExtra(Intent.EXTRA_TEXT, moviemodelList.get(position).getUrl());
                                sendIntent.setType("text/plain");
                                startActivity(sendIntent);
                                return true;
                        }
                        return false;
                    }

                });
                popup.show();
            }
        });
        lvnews.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                Intent intent = new Intent(page.this, webview.class);
                intent.putExtra("Link", moviemodelList.get(position).getUrl());
                startActivity(intent);
            }
        });

        return convertView;
    }

A: Make a class for testing whether net connection is available or not .
ConnectionDetector.java
public class ConnectionDetector {
public  Context context;
public ConnectionDetector(Context context)
{
    this.context=context;
}
public boolean isConnecting() {
    ConnectivityManager check=(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (check!=null){
        NetworkInfo[] infos=check.getAllNetworkInfo();
        for (int i=0;i<infos.length;i++)
        {
            if (infos[i].getState()== NetworkInfo.State.CONNECTED)
                return true;
        }}

    return false;

}
}

Create an object ob of above class .
ConnectionDetector ob=new  ConnectionDetector(getApplicationContext());

Declare these variables as global variables :
  File httpCacheDir;
  long httpCacheSize = 5 * 1024 * 1024;// In place of 5 you can use size in mb
  HttpResponseCache cache;

Make a function cacher():
 public void cacher()
 {
    httpCacheDir = getExternalCacheDir();

    // Cache Size of 5MB

    try {
        // Install the custom Cache Implementation
        HttpResponseCache.install(httpCacheDir, httpCacheSize);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Just below the setContentView in onCreate ,add the following code :
   cacher();
   cache = HttpResponseCache.getInstalled();
    if(cache != null) {
        //   If cache is present, flush it to the filesystem.
        //   Will be used when activity starts again.
        cache.flush();
    }

And here comes the final thing , below the url.openConnection line put the    following snippet:
 if (ob.isConnecting()){
            connection.addRequestProperty("Cache-Control", "max-age=0");}
            else{
            connection.addRequestProperty("Cache-Control", "max-stale=" +  60*60*36);//In place of 36 , you can put hours for which cache is available
            connection.setUseCaches(true);
}


text:
Q: WinForms Customization we can change the background of buttons and menu items n other UI components etc but is there a way to also change the background image for hover, pressed and other states

A: I do not think that is a good idea as a standard guideline for user interfaces has been adopted. Think what would happen if the user made a system setting change for the width of a window frame, or the border for the icons, or even worse, apply a theme that makes your user interface pretty glarish as a result of the perception of the eyes of the user, this can have a knock-on effect - the user will end up not using your application as a result.
It would be prudence to just leave the natural colours of buttons etc as defined by the system settings such as gray buttons, white background on text boxes etc. Then later on, once the winform application is accomplished, then find out by asking the users for their feedback on the layout and colouring schemes.
The best advice is to leave it alone, because by chance, a user will have their customised settings for graphics display, larger fonts (instead of 96dpi, could have extra large fonts).
The place to look for this is in:

*

*Right click on the desktop

*A popup menu appears, select properties and click on it.

*A dialog box will appear, now click on the settings tab page.

It is on that tab page the font sizes, themes, borders and a whole host of customizations can take place.
Be wisse and practice safe caution here as I wouldn't go too far in making the application interface a colour playground as I have mentioned above. If you stick to my opinion of it, the application will be 'neutral' on the grounds that it will work with many themes and user settings as possible.

A: Anything is possible.
Override OnMouseHover, OnMouseEnter/Leave, OnPaint on the custom buttons... ;)


text:
Q: How to make the browser remember the last page shown in multi-tab paginated content generated via ajax and jquery? I have a tabbed content. based on the HTML below:

f_tab is the function that manages the content of this above HTML,including actions below:

*

*generating tabs.

*executing AJAX that fetches the php pages and return the result in the tab holder.

*paginating each content inside the content holder using jPaginator plugin (https://github.com/remylab/jpaginator):
 function f_tab(str){
$(document).ready(function(){

        var Tabs = {
        '1' : 'page1.php?p='+var,
        '2' : 'page2.php?p='+var,
        '3' : 'page3.php?p='+var,

    }

 var topLineColor = {
    blue:'lightblue',
    blue:'lightblue',
    blue:'lightblue',}

$.each(Tabs,function(i,j){

    var tmp = $('
'+i+'
');

    tmp.find('a').data('page',j);

    $('ul.tabContainer').append(tmp);
})

var the_tabs = $('.tab');

the_tabs.click(function(e){

    var element = $(this);

    if(!element.data('cache'))
    {

        $.get(element.data('page'),function(msg){
            $('#contentHolder').html(msg);
            element.data('cache',msg);
        });
    }
    else {
    $('#contentHolder').html(element.data('cache'));

    }
    e.preventDefault();

})

the_tabs.eq(2).click();    });       return false;        }

The pagination function (just for information) is:
 (function($){

    $.fn.extend({
        MyPagination: function(options) {
            var defaults = {
                height: 600,
                fadeSpeed: 1000
            };
            var options = $.extend(defaults, options);

            //Creating a reference to the object
            var objContent = $(this);

            // other inner variables
            var fullPages = new Array();
            var subPages = new Array();
            var height = 0;
            var lastPage = 1;
            var paginatePages=null;
            var numero=0;

            // initialization function
            init = function() {
                objContent.children().each(function(i){
                    if (height + this.clientHeight > options.height) {
                        fullPages.push(subPages);
                        subPages = new Array();
                        height = 0;
                    }

                    height += this.clientHeight;
                    subPages.push(this);
                });

                if (height > 0) {
                    fullPages.push(subPages);
                }

                // wrapping each full page
                $(fullPages).wrap("

");

                // hiding all wrapped pages

                objContent.children().hide();

                // making collection of pages for pagination
                paginatePages = objContent.children();

                numero=$(paginatePages).length;

                // show first page
                showPage(lastPage);

            };

            // show page function
            showPage = function(page) {
                i = page - 1;
                if (paginatePages[i]) {

                    // hiding old page, display new one
                    $(paginatePages[lastPage]).hide();
                    lastPage = i;
                    $(paginatePages[lastPage]).fadeIn(options.fadeSpeed);

                }
            };

            // show pagination function (draw switching numbers)

            // perform initialization
            init();

            //$(document).ready(function(){
            $("#pagination").jPaginator({
                nbPages:numero,
                marginPx:5,
                nbVisible:8,
                overBtnLeft:'#over_backward',
                overBtnRight:'#over_forward',
                maxBtnLeft:'#max_backward',
                maxBtnRight:'#max_forward',
                onPageClicked: function(a,num) {

                    showPage(num);
                }
            });
            //});

        }
    });
})(jQuery);

Question:
 How can I make the browser rememeber the last shown page in a tab while passing from a tab to another. For example, if the last page shown in tab1 is page5, after clicking on another tab and then returning to tab1, how can I see page5 of tab1?
Thank you for your time. Help is appreciated.

A: Because you are AJAX loading each of the tabs, it loses all state information.
As far as I see it, you have the following options:

*

*Don't AJAX load the tabs. This would mean a longer load time for the page but less wait between changing tabs.

*IDEAL: Change your tab change function to check if the content has already been loaded. Only AJAX in the content if it hasn't already been done.

*Save the page state in a variable and change the page to the variable value every time the tab is loaded.


text:
Q: How to overlay shapes or icon at the bottom of Tradingview price chart using Pinescript? What is a way to use Pinescript to add an overlay of icons or shapes at the bottom of the Tradingview price chart similar to how Event chart settings for dividends, splits, earnings, and news are displayed? Additionally, being able to mouse over the icon to display a brief summary of what that event is.

A: The closest thing you can do is using the location parameter with the plotshape() or plotchar() functions. For example:
//@version=5
strategy("Template strategy", overlay=true, margin_long=100, margin_short=100)

longCondition = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
if (longCondition)
    strategy.entry("My Long Entry Id", strategy.long)

shortCondition = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
if (shortCondition)
    strategy.entry("My Short Entry Id", strategy.short)

plotchar(longCondition, text = "Long", char='', location = location.bottom, size = size.small)
plotchar(shortCondition, text = "Short", char='', location = location.bottom, size = size.small)

A: The closest solution was not using an overlay and make the indicator right below the main chart and using label.new() and label.set_tooltip() to generate the popup text for different bars.
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © thomastthai
// @version=5

indicator('Events', overlay=false, scale=scale.right, max_lines_count=500)
event1UnixTime = 1651687200000
event1Label = label.new(x=event1UnixTime, xloc=xloc.bar_time, y=0, color=color.green, size=size.tiny)
label.set_tooltip(id=event1Label, tooltip="Event 1")
event2UnixTime = 1661687200000
event2Label = label.new(x=event2UnixTime, xloc=xloc.bar_time, y=0, color=color.red, size=size.tiny)
label.set_tooltip(id=event2Label, tooltip="Event 2")


text:
Q: Selecting from stored procedure output I am trying to explore the possibility of selecting from a stored procedure.
Something like this
SELECT name
FROM exec msdb..sp_help_job
WHERE name = 'SampleJob'

I understand SQL Server - SELECT FROM stored procedure that a user-defined function or view can be used, but these are not options for me.
Reason being I am not able to run the following SQL statement due to permission limitations on AWS-RDS.
SELECT name as Jobs
FROM msdb..sysjobs

This leaves me with no choice but to use msdb..sp_help_job.
What I am ultimately trying to achieve is this "If job is not created, then run create job script". The reason I need to select from the stored procedure is to see if the job exists.
Appreciate any advice / directions.

A: If you want to create something, but are concerned that it might already exist, then use try/catch blocks.
begin try
    exec dbo.sp_add_job . . .
end try
begin catch
    print 'Error encountered . . . job probably already exists'
end catch;

To be honest, I haven't done this with jobs/job steps.  However, this is one way of re-creating tables, views, and so on.

A: According to the documentation for sp_help_job on MSDN this stored procedure has a @job_name parameter and a simple return code (0 = success or 1 = failure).
If you set the @job_name parameter on your call to sp_help_job and get the return code you should be able to test the value of the return code to accomplish what you want.
Something like this should work:
DECLARE @return_value int

EXEC @return_value = msdb..sp_help_job @job_name = 'MyJobName'

-- @return_value = 1 means the specified @job_name does not exist
IF @return_value = 1
BEGIN
    --  run create job script
END


text:
Q: PHP / CodeIgniter- Undefined variable in class construct I have the following php errors :

A PHP Error was encountered
Severity: Notice
Message: Undefined variable: t

and

A PHP Error was encountered
Severity: Warning
Message: Missing argument 1 for myclass::__construct(), called in
  xxx on line 1011
  and defined

My controller contains :
    $this->load->model('mymodel');
    $i = $this->mymodel->func(1);
    print_r($i);

mymodel :
$test = new myclass("foo", "bar");
$myarray[] = $test;
return $myarray

myclass :
class myclass {

var $a;
var $b;

public function __construct($t, $l) // ERROR 2
{
    $this->a = $t; // ERROR 1
    $this->b = $l;
}

}

Note that print_r($a) in controller prints the correct object with content..
Thanks

A: Allright, that was caused by Codeigniter.
myclass is declared in a separate file and loaded by mymodel using :
    $CI =& get_instance();
    $CI->load->library('myclass', $params);

When loading the library, Codeigniter  creates an instance of myclass as a singleton, but it doesn't transmit any argument. To prevent this error, you have to give parameters before loading the lib :
    $params = array('type' => "a", 'loc' => "b");
    $CI =& get_instance();
    $CI->load->library('myclass', $params);

Note that it must be an array ($params), not a single argument.

A: another way is to copy-cat antelove answer.
with that way, you only need change the model file and the way you load the model.
P.S this is just to enrich this SO thread


text:
Q: Is there an easy way to order a large number of columns without using dplyr::select() in r? I'm working with a very large dataset with lots of columns (400+) and every time I create a new variable or add a new one I have to reorder it. I want it ordered so that all the related variables remain together so I've been using dplyr::select() to reorder things. Yet there are times when I have to go back into my script very early on and add a new variable. When I run the whole code after that, there tends to be one or two variables I forgot to put into preceding select() functions so it goes missing.
I use select() because selecting all the columns between two variables and referencing them by name is super easy (eg, Vfour:Vthreefifty). Do you have any tips for reordering datasets with lots of columns?

A: Given no reproducible example but using your 2 column names:
df %>%
select(., starts_with('V'))

You can then chain starts_with as needed.
Other options include:
ends_with, contains, matches