text:
Q: How to rate limit the fetch API in React? I have a Vite.js App, React Template. In one of my components I want to fetch some data from https://wheretheiss.at/w/developer
API. I am using useEffect. Now, the documentation mentions that the rate limiting is 1 request per second. And here is my code:
import { useState, useEffect } from "react";
import axios from "axios";

export default function Info() {
  const [info, setInfo] = useState({
    longitude: 0,
    latitude: 0,
    altitude: 0,
    velocity: 0,
    visibility: "",
  });

  const getCoords = async () => {
    const data = await axios({
      method: "get",
      url: "https://api.wheretheiss.at/v1/satellites/25544",
    });

    return data;
  };

  useEffect(() => {
    fetch("https://api.wheretheiss.at/v1/satellites/25544")
      .then((res) => res.json())
      .then((data) => {
        const lat = data.latitude;
        const long = data.longitude;
        const alt = data.altitude * 0.62137119;
        const vel = data.velocity * 0.62137119;
        const vis = data.visibility;

        setInfo({
          longitude: long.toFixed(4),
          latitude: lat.toFixed(4),
          altitude: alt.toFixed(4),
          velocity: vel.toFixed(2),
          visibility: vis === "daylight" ? "not visible" : "visible",
        });
      });
  }, [info]);

  return (

          Latitude:
          {info.latitude}°

          Longitude:
          {info.longitude}°

          Altitdude:
          {info.altitude} miles

          Velocity:
          {info.velocity} mph

          Visibility:
          {info.visibility}

  );
}

I know that setting the info state as the dependencies array for my useEffect hook will determine React re-rendering the component in an infinite loop. My question is: How can I limit the fecthing for one time per second?
I cannot set the dependecie array as [] because I want to constantly fetch data, because the latitude, longitude, etc., are changing every second. I cannot leave it like that either because the app will throw this error:

Uncaught (in promise): Object {..., message: "Request failed with status code 429"}

which means my app is making to many requests above the rate limit. When I get this error, my coordinates are not being re-rendered anymore and they remain the same.
Do you have any idea?

A: You can use the 'axios-retry' npm package in your environment. It has the capabilities you need to use in your environment.

A: step 1:
import the react-debouncing lib
npm i loadash

now use the loadash's debounce to debounce the function so the
function will run only for 1sec so the request will also get limited
to 1req per sec
here is the modified code:

import { useState, useEffect } from "react";
import axios from "axios";
import { debounce } from 'loadash';

export default function Info() {
  const [info, setInfo] = useState({
    longitude: 0,
    latitude: 0,
    altitude: 0,
    velocity: 0,
    visibility: "",
 });

  const getCoords = async () => {
    const data = await axios({
      method: "get",
      url: "https://api.wheretheiss.at/v1/satellites/25544",
    });

    return data;
  };

let debouncedReq = debounce(()=>{
 fetch("https://api.wheretheiss.at/v1/satellites/25544")
      .then((res) => res.json())
      .then((data) => {
        const lat = data.latitude;
        const long = data.longitude;
        const alt = data.altitude * 0.62137119;
        const vel = data.velocity * 0.62137119;
        const vis = data.visibility;

        setInfo({
          longitude: long.toFixed(4),
          latitude: lat.toFixed(4),
          altitude: alt.toFixed(4),
          velocity: vel.toFixed(2),
          visibility: vis === "daylight" ? "not visible" : "visible",
        });
      });
}, 1000) // now the function is debounced for 1000ms

  useEffect(() => {
   debouncedReq()
  }, [info]);

  return (

          Latitude:
          {info.latitude}°

          Longitude:
          {info.longitude}°

          Altitdude:
          {info.altitude} miles

          Velocity:
          {info.velocity} mph

          Visibility:
          {info.visibility}

  );
}

A: Your existing code relies on the fetch call succeeding to have another scheduled afterwards (triggered by setInfo being called with new data) and these are scheduled to run one after the other without any delay which quickly results in the rate limit quickly being hit.
wheretheiss.at rate limiting is roughly documented on their API page but they also indicate that you should check out the X-Rate-Limit-* headers returned by their server to know more info about it:
X-Rate-Limit-Limit: 350
X-Rate-Limit-Remaining: 193
X-Rate-Limit-Interval: 5 minutes

This means you can query slightly more often than every second so you can use setInterval to schedule your API calls:
useEffect(() => {
  const interval = setInterval(() => {
    fetch('https://api.wheretheiss.at/v1/satellites/25544')
        .then((res) => res.json())
        .then((data) => {
          const lat = data.latitude;
          const long = data.longitude;
          const alt = data.altitude * 0.62137119;
          const vel = data.velocity * 0.62137119;
          const vis = data.visibility;

          setInfo({
            longitude: long.toFixed(4),
            latitude: lat.toFixed(4),
            altitude: alt.toFixed(4),
            velocity: vel.toFixed(2),
            visibility: vis === 'daylight' ? 'not visible' : 'visible',
          });
        });
  }, 1_000);
  return () => { clearInterval(interval) };
}, [setInfo])

Stackblitz link


text:
Q: GNU strip to remove debug info in a .so (Android) I am trying to clean debug information in final .so file for Android.
Trying
strip.exe -s myLib.so

but it returns

strip.exe: Unable to recognise the format of the input file

Compiler is arm-linux-androideabi-g++ (under QtCreator)
Am I using the correct tool?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Meaning of unique_ptr Why unique_ptr can take owership of a const ptr?
What is the meaning of unique_ptr<const T>?
  std::unique_ptr<int> a(new int);
  // Only this is compile error.
  std::unique_ptr<int> b((const int*)new int);
  std::unique_ptr<const int> c(new int);
  // Why unique_ptr can take a const ptr, and delete it when deconstruct?
  std::unique_ptr<const int> d((const int*)new int);

Tested with g++ 4.8

A:
Why unique_ptr can take owership of a const ptr?

Because even constant variables need to be destructed and freed when they are not longer needed. memory and resources leak happens on un-finalized variables regardless the const or volatile keywords.

What is the meaning of unique_ptr < const T>

Any meaning that uniqe_ptr<T> has , except it's const T and not T.

// Why unique_ptr can take a const ptr, and delete it when
  deconstruct?

I have a feeling that you think that const object cannot be deleted, since they are const hence un-modifiable and un-destructable. this is wrong. the const kicks in after the variable has being constructed and "stop" taking affect on the variable destruction. otherwise, you couldn't create any const variable neither destroy them.


text:
Q: Can an instrumental variable equation be written as a directed acyclic graph (DAG)? Directed acyclic graphs (DAGs) are efficient visual representations of qualitative causal assumptions in statistical models, but can they be used to present a regular instrumental variable equation (or other equations)? If so, how? If not, why?

A: Yes.
For example in the DAG below, the instrumental variable $Z$ causes $X$, while the effect of $X$ on $O$ is confounded by unmeasured variable $U$.

The instrumental variable model for this DAG would be to estimate the causal effect of $X$ on $O$ using $E(O|\widehat{X})$, where $\widehat{X} = E(X|Z)$.
This estimate is an unbiased causal estimate if:

*

*$Z$ must be associated with $X$. Edit: And, (as in the above DAG) this association itself must be unconfounded (see Imbens).

*$Z$ must causally affect $O$ only through $X$

*There must not be any prior causes of both $O$ and $Z$.

*The effect of $X$ on $O$ must be homogeneous. This assumption/requirement has two forms, weak and strong:

*

*Weak homogeneity of the effect of $X$ on $O$: The effect of $X$ on $O$ does not vary by the levels of $Z$ (i.e. $Z$ cannot modify the effect of $X$ on $O$).

*Strong homogeneity of the effect of $X$ on $O$: The effect of $X$ on $O$ is constant across all individuals (or whatever your unit of analysis is).

The first three assumptions are represented in the DAG. However, the last assumption is not represented in the DAG.
Hernán, M. A. and Robins, J. M. (2020). Causal Inference. Chapter 16: Instrumental variable estimation. Chapman & Hall/CRC.

A: Yes, they surely can.
As a matter of fact, the SCM/DAG literature has been working on generalized notions of instrumental variables, you might want to check Brito and Pearl, or Chen, Kumor and Bareinboim.
The basic IV dag is usually represented as:

Where $U$ is unobserved and $Z$ is an instrument for the effect of $X$ on $Y$. Although this is the graph you usually see, there are several different structures that would render $Z$ an instrument.
For the basic case, to check whether $Z$ is an instrument for the causal effect of $X$ on $Y$ conditional on a set of covariates $S$, you have to check two conditions:

*

*$Z$ is connected to $X$ in the original DAG;

*$S$ d-separates $Y$ from $Z$, in the DAG where the arrow $X\rightarrow Y$ is removed.
The first condition requires $Z$ to be associated with $X$  (relevance condition, otherwise the numerator of the IV estimand is zero). The second condition requires $Z$ to not be connected to $Y$ if but for its effect on  $X$ (that is, we cannot have violations of the exclusion and independence restriction, after conditioning on $S$).
For example, consider the graph below, with $W$ and $U$ unobserved. Here, $Z$ is, conditional on $L$,an instrument for the causal effect of $X$ on $Y$. We can create more complicated cases where it might not be immediately obvious whether something does qualify as an instrument or not.

One final thing you should have in mind is that identification using instrumental variable methods needs parametric assumptions. That is, finding an instrument is not enough for identification of the effect: you need to impose parametric assumptions, such as linearity or monotonicity and so on.


text:
Q: Is it possible to have 2 profile models using django's AUTH_PROFILE_MODULE Is is possible to have 2 models to store extra user details. I ask because I'm currently writing an app which i want to plug into a few existing projects. However all these projects already use a profile model, and my new app needs to extend the user model through the profile model. If it isn't is there a way of extending the currently in use profile model set within AUTH_PROFILE_MODULE?

A: Shouldn't you just create a field in this other model that has a foreign key to the profile?
So assuming you have an already existent UserProfile model.
Class UserProfile(models.Model):
  user = models.OneToOneField(User)
  ...

You could extend the UserProfile model by adding a foreign key in your other model, linking to it.
Class OtherModel(models.Model):
  profile = models.ForeignKey(UserProfile, related_name="other_model")
  field1 = models.CharField(max_length=15)
  ...

And so you can access this other model from the User object:
user.get_profile().other_model.field1

HTH


text:
Q: Python exits without finishing script I keep getting The thread 'MainThread' (0x1) has exited with code 0 (0x0). before the script has even fully reached the end. I have some extra parts to my script after a while num < maxthreads loop but it seems like the interpretor is exiting right after this condition is met. I want it to continue after this, what am I doing wrong?
def creator():
    s = requests.session()
    email = randomName()
    password = randomPassword()
    name = names.get_full_name()

    data={
    "displayname":name,
    "creation_point":"https://login.app.igloo.com?utm_source",
    "birth_month":monthnumber,
    "email":email + "@gmail.com",
    "password":password,
    }

try:

    r = s.post("https://spclient.wg.igloo.com/signup/public/v1/account/",data=data,proxies=proxy1.FormatProxy())
    if '{"status":1,"' in r.text:
        open("creatediglooaccountsgen.txt", "a+").write(email + "@gmail.com:" + password + ":" + PROXY + "\n")
        created += 1
    else:
        errors += 1
except:
    pass
    print("DONE")
maxi = 4
maxthreads = 4
num = 0

while num < maxthreads:
    num += 1
    threading.Thread(target=creator).start()  # Start Checking Thread
chrome = webdriver.chrome(options=chrome_options)
driver.get("https://igloo.com/en/login")
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

#from selenium findElement
with open('creatediglooaccountsgen.txt') as f:
    credentials = [x.strip().split(':', 1) for x in f]
for username, password in credentials:
@type='text']")
@type='text'").send_keys(username)
    driver.find_element_by_id("login-username").send_keys(username)
    driver.find_element_by_id("login-password").send_keys(password)
try:
    time.sleep(10)
    element = WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//button[text()='Log In']"))).click()
except:
    print('exception occured')
time.sleep(3)

driver.close()

I've tried to cut out as much as I can to condense it but essentially the script stops after the while num < maxthreads line (after the specified 4 loops since maxi is set to 4) but I want it to continue after that.
Any ideas,
thanks


text:
Q: Spring mvc:resources access to outside folder I have stored medias (pictures and movies) in a folder (for example C:\test\tes.png) and I'm trying to access to pictures with an url like : http://localhost:8080/app/picture/test.png.
To do that, i have used resources tag (spring 3) as below :
<mvc:resources mapping="/picture/**" location="file:/test" />

When I try to access,  I have an error with no more details.

Requested Resource Not Found

I have in logs :

2011-11-07 20:48:55,241 [http-8080-2] DEBUG org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'Family' processing GET request for [/Family/photos/testImage2.png]
  2011-11-07 20:48:55,241 [http-8080-2] DEBUG org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Matching patterns for request [/photos/testImage2.png] are [/**]
  2011-11-07 20:48:55,241 [http-8080-2] DEBUG org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - URI Template variables for request [/photos/testImage2.png] are {}
  2011-11-07 20:48:55,242 [http-8080-2] DEBUG org.springframework.web.servlet.handler.SimpleUrlHandlerMapping - Mapping [/photos/testImage2.png] to HandlerExecutionChain with handler [org.springframework.web.servlet.resource.DefaultServletHttpRequestHandler@3a779f5e] and 4 interceptors
  2011-11-07 20:48:55,242 [http-8080-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Last-Modified value for [/Family/photos/testImage2.png] is: -1
  2011-11-07 20:48:55,242 [http-8080-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'Family': assuming HandlerAdapter completed request handling
  2011-11-07 20:48:55,242 [http-8080-2] DEBUG org.springframework.web.servlet.DispatcherServlet - Successfully completed request

I have certainly not all understand...
Another question : I'm not sure this is the good approach. What are others solutions to access to media on external folder ?
Thanks in advance !

A: First question: "the mapping"
I am not 100% sure, but I would guess, there is a final / missing for the location.
change it to:
<mvc:resources mapping="/picture/**" location="file:/test/" />

Another question : I'm not sure this is the good approach. What are others solutions to access to media on external folder ?
In my humble opinion, it is very bad practice to give an web site user full read access to an folder. Attention the access is not only limited to the folder, but the user can also access all sub folders.
*And even if you decided to ignore this warning, then you must test what happen if some use invoke http://localhost:8080/app/picture/../someFile.** I don't know what would happen, but **make 120% sure that nobody can access any file outside the picture Folder! -- I have had a look into the spring implementation, and it seams that spring already handle this issue.*Since Spring 3.2.12, 4.0.8, 4.1.2 the Resource Handler make sure that you an not access an folder outside the specified resource folder. (SPR-12354: Directory traversal with static resource handling (CVE-2014-3625))

A: If your .js/.css/.img files are stored in drive d:\\ext_resources then add <mvc:resources> in spring configaration file. e.g. mvc-dispatcher-servlet.xml.xml file...
<mvc:resources mapping="/ext/**" location="file:d://ext_resources/"/>

This means /ext will indicate folder d:\\ext_resources, which contains .html/.jsp/.ftl/.jsf files.

    <link rel="stylesheet" href="/ext/style.css">

you can have sub-folder too in ext_resources folder like image folder.
Then use subfolder in URL.


text:
Q: Python generator send() strange behaviour While I try to understand the mechanism of generator's send() method, I encountered a strange behaviour in my example. (VS Code Python 3.10)
def MultipleOfThree():
    num  = 1
    while True:
        if num % 3 == 0:
           yield num
        num += 1

#test
iter = MultipleOfThree()

for m3 in iter:
    print(m3)

This code is working as expected and prints
>>> 3,6,9,12,15,18,21.....

When I add the send() statement in for loop, and arrange the MultipleOfThree() func like below
def MultipleOfThree():
    num  = 1

    while True:
        if num % 3 == 0:
            i = yield num
            if i is not None:
                num = i
        num += 1

#test
iter = MultipleOfThree()

for m3 in iter:
    print(m3)
    iter.send(m3) #for simplicity send the m3 itself

it prints
>>> 3,9,15,21,27

I couldn't understand the mechanism of send() here, why escapes the for loop.
I study the subject from this page How to Use Generators and yield in Python.

A: The generator makes a stop at each yield of some value. It continues after the value is consumed by calling next on the corresponding iterator. It continues until the next yield (or generator exit).
A for loop uses this iterator protocol to consume the yielded values one at a time and runs the loop body with each one.
A send is similar to next. It consumes a value, makes the generator to advance, but in addition to next It also sends a value to the generator. The sent value becomes the value returned by the yield (in the generator).
Your code is interacting with the generator at two places: in the for statement and in the send statement. But you are printing only one of the values, that's why you see only every second.
Add a print and you'll see all values again:
for m3 in iter:
   print(m3)               # print 1 (yielded by for loop)
   print(iter.send(m3))    # print 2 (yielded by send)

A: First initialize the generator:
iter = MultipleOfThree()

Get the first value:
m3= next(iter)

Then continue in a while loop:
while True:
    print(m3)
    m3 = iter.send(m3)

You wish to get the first value using next(iter) or iter.send(None) in order to reach the first multiple of three, without any input.
Then, you want to send back the input and continue from there using iter.send(m3).
Overall code:
def MultipleOfThree():
    num  = 1
    while True:
        if num % 3 == 0:
            i = yield num
            if i is not None:
                num = i
        num += 1

iter = MultipleOfThree()
m3= next(iter)
while True:
    print(m3)
    m3 = iter.send(m3)


text:
Q: How to change css href using window.open in JavaScript? I want to change CSS href using window.open in JavaScript.
Launch Example

change into
window.open(/* url goes here */);

with all attributes in css href above.

A: You can accomplish what you want in two steps:
1) Change your  element's target to 'new-win' or any name you want.
Launch Example

2) Create an event listener for the click event of the  element wherein to use window.open. As arguments to window.open, pass the href and the target of the  element.
document.getElementById("Launch").addEventListener("click", function () {
  window.open(this.href, this.target);
});


text:
Q: Minimum bound involving a strongly monotone map Let $w:\mathbb{R}^m\rightarrow\mathbb{R}^m$ a strongly monotone map, that is, there exists a $\gamma>0$ such that
$$
h^\top [w(x+h)-w(x)]\geq \gamma\cdot \| h\|^2,
$$
for any $x,h\in\mathbb{R}^m$
Let $K=K^\top\in\mathbb{R}^{m\times m}$ a positive definite matrix. I'm interested in proving that the following inequality holds:
$$
y^\top [w(x+Kh)-w(x)]\geq \gamma\cdot y^\top Kh
$$
for any $x,h\in\mathbb{R}^m$.
For the scalar case, i.e. $m=1$, the proof is pretty easy. From strong monotonicity, we have that
$$
(Kh)\cdot[w(x+Kh)-w(x)]\geq \gamma\cdot (Kh)^2,
$$
which implies
$$
w(x+Kh)-w(x)\geq \gamma\cdot Kh.
$$
Then, we can use the latter to get:
$$
y[w(x+Kh)-w(x)]\geq \gamma\cdot yKh.
$$
Is it possible to generalize for $m>1$?

A: Discussing only the 1D case:
Note that $K = 1$ may always be assumed (in dimensions 1 or higher), and you may write $h = ah_0$ and assume $y \in \{-1,1\}$ in 1-D.
If $y$ and $h$ are further restricted to have the same sign, the assumption $y(w(x+h)-w(x)) \ge \gamma yh$ for all $h, y, x$ implies $\frac{w(x+h)-w(x)}{h} \ge \gamma$ for all $x, h>0$ which is equivalent to $w'(x) \ge \gamma$ as soon as $w$ is smooth.
If $y, w$ are restricted to have opposite signs, the equivalent statement is $w'(x) \le - \gamma$.
If $y$ and $h$ are not restricted, no such $w$ exists, since this would imply $0 < \gamma \le - \gamma$.


text:
Q: Mac Catalyst UICollectionViewCompositionalLayout error I have the following UICollectionViewCompositionalLayout:
public lazy var layout: UICollectionViewLayout = {
    let layout = UICollectionViewCompositionalLayout {
        (sectionIndex: Int, layoutEnvironment: NSCollectionLayoutEnvironment) -> NSCollectionLayoutSection? in
        let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
                                             heightDimension: .fractionalHeight(1.0))
        let item = NSCollectionLayoutItem(layoutSize: itemSize)

        let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0),
                                              heightDimension: .absolute(115))

        var count: Int = 2
        if self.view.traitCollection.horizontalSizeClass != .compact {
            if self.view.frame.size.width > 900 {
                count = 5
            } else {
                count = 3
            }
        }

        let group = NSCollectionLayoutGroup.horizontal(layoutSize: groupSize, subitem: item, count: count)
        let spacing = CGFloat(10)
        group.interItemSpacing = .fixed(spacing)

        let section = NSCollectionLayoutSection(group: group)
        section.interGroupSpacing = spacing
        section.contentInsets = NSDirectionalEdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0)
        return section
    }
    return layout
}()

When I run this on iOS it works fine, but when I run this on Mac using Catalyst, it will throw the following error:
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Cannot solve for a non-group item.'

Any ideas on how to fix this?


text:
Q: Android Cocos2dx Crash I have made game in cocos2dx for ios device. Now I want to port it for android but, the code which works fine for ios is crashing for android. The eclipse shows 3 types of logCat outputs which are as follows.
///////////////////////////////////////////////////////////////////////////////////////////////////////
1) 11-27 10:41:05.168: W/SharedBufferStack(4417): waitForCondition(LockCondition) timed out (identity=302, status=0). CPU may be pegged. trying again.

///////////////////////////////////////////////////////////////////////////////////////////////////////
2) 11-27 10:41:36.448: D/lights(248): set_light_backlight: brightness=255
11-27 10:41:41.518: I/InputDispatcher(248): Application is not responding: Window{2b452080 org.cocos2dx.Saburbia_android/org.cocos2dx.Saburbia_android.Saburbia_android paused=false}. 5000.4ms since event, 5000.4ms since wait started
11-27 10:41:41.518: I/WindowManager(248): Input event dispatching timed out sending to org.cocos2dx.Saburbia_android/org.cocos2dx.Saburbia_android.Saburbia_android
11-27 10:41:41.528: I/Process(248): Sending signal. PID: 4417 SIG: 3
11-27 10:41:41.528: I/dalvikvm(4417): threadid=4: reacting to signal 3
11-27 10:41:41.728: I/Process(248): Sending signal. PID: 248 SIG: 3
11-27 10:41:41.728: I/dalvikvm(248): threadid=4: reacting to signal 3
11-27 10:41:41.748: I/dalvikvm(248): Wrote stack traces to '/data/anr/traces.txt'
11-27 10:41:41.748: I/Process(248): Sending signal. PID: 355 SIG: 3
11-27 10:41:41.748: I/dalvikvm(355): threadid=4: reacting to signal 3
11-27 10:41:41.758: I/dalvikvm(355): Wrote stack traces to '/data/anr/traces.txt'
11-27 10:41:41.758: I/Process(248): Sending signal. PID: 320 SIG: 3
11-27 10:41:41.758: I/dalvikvm(320): threadid=4: reacting to signal 3
11-27 10:41:41.758: I/dalvikvm(320): Wrote stack traces to '/data/anr/traces.txt'
11-27 10:41:41.968: D/dalvikvm(248): GC_EXPLICIT freed 952K, 49% free 6943K/13447K, external 3286K/4888K, paused 78ms
11-27 10:41:42.518: E/ActivityManager(248): ANR in org.cocos2dx.Saburbia_android (org.cocos2dx.Saburbia_android/.Saburbia_android)
11-27 10:41:42.518: E/ActivityManager(248): Reason: keyDispatchingTimedOut
11-27 10:41:42.518: E/ActivityManager(248): Load: 7.93 / 7.92 / 7.79
11-27 10:41:42.518: E/ActivityManager(248): CPU usage from 27270ms to 0ms ago:
11-27 10:41:42.518: E/ActivityManager(248): 99% 4417/org.cocos2dx.Saburbia_android: 99% user + 0% kernel / faults: 2 minor
11-27 10:41:42.518: E/ActivityManager(248): 0% 3877/com.google.android.apps.maps: 0% user + 0% kernel / faults: 418 minor
11-27 10:41:42.518: E/ActivityManager(248): 0% 3957/com.svox.pico: 0% user + 0% kernel / faults: 678 minor
11-27 10:41:42.518: E/ActivityManager(248): 0% 248/system_server: 0% user + 0% kernel / faults: 8 minor
11-27 10:41:42.518: E/ActivityManager(248): 0% 1679/com.sonyericsson.customization: 0% user + 0% kernel / faults: 283 minor
11-27 10:41:42.518: E/ActivityManager(248): 0% 3647/com.sonyericsson.devicemonitor: 0% user + 0% kernel / faults: 179 minor
11-27 10:41:42.518: E/ActivityManager(248): 0% 121/rild: 0% user + 0% kernel / faults: 1 minor
11-27 10:41:42.518: E/ActivityManager(248): 0% 320/com.android.systemui: 0% user + 0% kernel / faults: 3 minor
11-27 10:41:42.518: E/ActivityManager(248): 0% 3731/com.sonyericsson.android.datamonitor: 0% user + 0% kernel / faults: 25 minor
11-27 10:41:42.518: E/ActivityManager(248): 100% TOTAL: 100% user + 0% kernel
11-27 10:41:42.518: E/ActivityManager(248): CPU usage from 461ms to 976ms later:
11-27 10:41:42.518: E/ActivityManager(248): 98% 4417/org.cocos2dx.Saburbia_android: 98% user + 0% kernel
11-27 10:41:42.518: E/ActivityManager(248): 96% 4418/HeapWorker: 96% user + 0% kernel
11-27 10:41:42.518: E/ActivityManager(248): 3.8% 248/system_server: 1.9% user + 1.9% kernel
11-27 10:41:42.518: E/ActivityManager(248): 1.9% 291/InputDispatcher: 0% user + 1.9% kernel
11-27 10:41:42.518: E/ActivityManager(248): 1.9% 442/er$SensorThread: 1.9% user + 0% kernel
11-27 10:41:42.518: E/ActivityManager(248): 100% TOTAL: 98% user + 1.9% kernel
11-27 10:41:42.518: I/InputDispatcher(248): Dropping event because the pointer is not down.

////////////////////////////////////////////////////////////////////////////////////////////////
3) and third reason is unknows as it shows meny memory address in logCat.
////////////////////////////////////////////////////////////////////////////////////////////////
I am using libcurl for web calls and pThread for threading. This game also have Facebook Integration which is done using Facebook API for mobile (Hackbook).
After facebook login, the native code connects to the server using libcurl and makes about 30 http calls using pThread so that rendering thread should not be paused for getting the response from server. Still while this loading is going on the logcat shows any of these 3 logs and restarts loading from the start. There are http request present in game also which are executed using pThreads but in game also it shows any of this 3 log and crashes randomely.
The same code works fine for the ios build. I am not able to find why its not running properly for Android. Please suggest if any rules have to be followed for android porting.
I am using versions as follows.
Android NDK : r8b
Cocos2dx : 2.0.3
Eclipse : 3.6.2
Android version : 2.2
System : Ubuntu 10.0.4
Devices : SonyEricsson NeoV (android2.3.4), Samsung Galaxy SII (android4.0.3).
Thanks in advance..

A: Try to find memory issue in iPhone,because auto-release code might not working correctly.
  Also use the NDK stack for more detail error.
Update:Another way to track ndk stack on remote use the https://www.crittercism.com
Thank you.


text:
Q: How can you insert more than one data tag on a /summon spider command? So, I tried
/summon spider 100 20 100 {Health:16.0f}{CustomName:Webby}
then evreything that I could put in the middle with commas and full stops but it won't work, it'll let me use only one data tag but I am making a map that requires several of them for each mob. Obviously I am using Command Blocks in 1.12.2.
Thank you.

A: Tags are separated by commas. In general, you can look up example commands for things like this.
/summon spider 100 20 100 {Health:16.0f,CustomName:Webby}


text:
Q: Get node position in Irrlicht I played a bit around with Irrlicht and C++, and got the following MWE:
#include <iostream>
#include <Irrlicht/irrlicht.h>
#include <Irrlicht/driverChoice.h>
#include <cstdio>
#include <Irrlicht/EDriverTypes.h>
#include <Irrlicht/irrTypes.h>
#include <Irrlicht/IrrlichtDevice.h>

class MyEventReceiver : public irr::IEventReceiver
{
private:
    bool KeyIsDown[irr::KEY_KEY_CODES_COUNT];

public:
    virtual bool OnEvent(const irr::SEvent &event)
    {
        if(event.EventType == irr::EET_KEY_INPUT_EVENT)
            this->KeyIsDown[event.KeyInput.Key] = event.KeyInput.PressedDown;
        return false;
    }

    virtual bool IsKeyDown(irr::EKEY_CODE keyCode) const
    {
        return this->KeyIsDown[keyCode];
    }

    MyEventReceiver()
    {
        for(irr::u32 i = 0; i < irr::KEY_KEY_CODES_COUNT; ++i)
        {
            this->KeyIsDown[i] = false;
        }
    }
};

int main(void)
{
    MyEventReceiver receiver;
    irr::IrrlichtDevice *device = irr::createDevice(irr::video::EDT_OPENGL, irr::core::dimension2d<irr::u32>(1024, 800), 16, false, false, false, &receiver);
    irr::video::IVideoDriver* driver = device->getVideoDriver();

    irr::scene::ISceneManager* scmg = device->getSceneManager();
    irr::scene::ICameraSceneNode *camera = scmg->addCameraSceneNodeFPS();
    getchar();

    const double pref_pos = 2.5;
    irr::core::vector3df sphere_cur_pos = irr::core::vector3df(0, 0, 0);
    irr::core::vector3df sphere_position = irr::core::vector3df(0, 0, 0);
    std::cout << "Set initial vectors\n!";
    irr::scene::ISceneNode *cur_node = nullptr;
    cur_node = scmg->addSphereSceneNode(1.0f, 16, 0, -1, irr::core::vector3df(10, 0, 0));
    std::cout << "Set node\n";
    sphere_cur_pos = (*cur_node).getPosition();
    std::cout << "New sphere is at (" << sphere_cur_pos.X << ", " << sphere_cur_pos.Y << ", " << sphere_cur_pos.Z << ')' << '\n';
    std::cout << "Hello World\n";
    getchar();
    return 0;
}

Compilation line is
g++-5 -std=c++14 irrlicht_vector_test.cpp -o irrlicht -lIrrlicht `pkg-config --libs x11` `pkg-config --libs xxf86vm` `pkg-config --libs gl`  && ./irrlicht

The output of the program is
Set initial vectors
!Set node
New sphere is at (2.70951e-35, 37135.9, 2.83893e-29)
Hello World

If I exchange
sphere_cur_pos = (*cur_node).getPosition();

with
sphere_cur_pos = (*cur_node).getAbsolutePosition();

I get as output
Set initial vectors
!Set node
New sphere is at (1, 1, 1)
Hello World

Both outputs are regardless of the vector settings in addSphereSceneNode(). What am I doing wrong?


text:
Q: Would dual saberstaffs offer a greater advantage to other lightsabers? General Krell demonstrates in Star Wars: The Clone Wars that the use of two saberstaffs is plausible:

However, is it advantageous in battle, as opposed to dual lightsabers or a single saberstaff?

A: This is far from practical. The reason that General Krell was able to wield dual saberstaves was because he had four arms. It requires two arms to wield a saberstaff effectively, watch the episode where the clones arrested him. So unless you have two bonus arms . . .
Also, for those arguing even Krells ability to wield them, this is a fictional universe, and he was a Jedi. Force-sensitives can do a lot most normal people can't.

A: As discussed in this answer, dual lightsabers limit your balance and movement. Additionally, your mind must focus on more objects, something even a force-user will find more difficult than using a single lightsaber. Additionally, when you swing a double-bladed lightsaber, you have to be constantly aware of where the other blade is to avoid cutting your own limbs. This is going to limit the range of motion of your attacks and defenses. While it may look cool, using dual dual-bladed lightsabers is not very practical.

A: this is not exactly true. I have been practicing with the staff, and am on my way to being able to wield two. it is possible, it would just take lots of training and practice. I have already found a dual staff spin that is effective.


text:
Q: openFileChooser opening 2 times on selecting image from gallery I implemented openFileChooser of webchromeclient which is opening a PHP page. When i select image from gallery it again opens the gallery ie the gallery is opening two times.
Don't know how to get rid of this.
here is my code:
public class MyWebChromeClient extends WebChromeClient{
    public void openFileChooser(ValueCallback<Uri> uploadMsg) {

        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i,"File Chooser"), FILECHOOSER_RESULTCODE);

    }

    public void openFileChooser( ValueCallback<Uri> uploadMsg, String acceptType ) {
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("*/*");
        startActivityForResult(
                Intent.createChooser(i, "File Browser"),
                FILECHOOSER_RESULTCODE);
    }
}

this is onactivityresult:
protected void onActivityResult(int requestCode, int resultCode,
        Intent intent) {

    if (requestCode == FILECHOOSER_RESULTCODE) {
        if (null == mUploadMessage)
            return;
        Uri result = intent == null || resultCode != RESULT_OK ? null
                : intent.getData();
        mUploadMessage.onReceiveValue(result);
        mUploadMessage = null;

    }
}

A: Check in you manifest file that if you declared the activity as

single instance

then the Activity on result method will be called at wrong time.


text:
Q: Scroll Vertical y horizontal en un UITableView swift alguien me puede sugerir cual sería la mejor práctica para hacer una tabla que tiene scroll vertical y horizontal, con la primera columna fixed o fija cuando me desplazo horizontalmente hacia la derecha. Adjunto imagen de un ejemplo de como sería.

A: Como te indiqué en el comentario, no es posible el scroll horizontal.
Entonces agregando la celda quedaría así:

Puedes modificar el ancho y agregar los labels que necesites. En este ejemplo la celda es de tipo Subtitle.
Debes agregar un identificador a la celda:

Al agregar los datos si lo haces desde una API o SQLite lo haces de esta manera:
override func numberOfSections(in tableView: UITableView) -> Int {
        // Agregas el número de secciones.
        return 1
    }

    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // Agregas el número de filas.
        return 5
    }

override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        // Configuras los datos de tu celda
        cell.textLabel?.text = "John Smith"
        cell.detailTextLabel?.text = "10000000"

        return cell
    }

Al compilar tendrías así:

Tu diseño debes ajustarlo a como trabajan las celdas en iOS. Espero te sirva y recuerda revisar la documentación de Apple con respecto al User Interface.


text:
Q: NotWritablePropertyException when deploying the application Im getting the below exception when i deploy the application, Does anyone know the work around?
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'hibernateUtil' defined in class path resource [spring-hibernate-cfg.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'sessionFactory' of bean class [com.library.database.HibernateUtil]: Bean property 'sessionFactory' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1493)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1197)

A: add setSessionFactory(); method to com.go.database.HibernateUtil,
you have defined property sessionFactory and injected into HibernateUtil, Spring will use setter injection and you don't have setter method for this property so it is failing


text:
Q: In-line Styles not rendering properly after state change in ReactJS I am trying to apply a simple state change to a button in React.
'use strict';
class ReactButton extends React.Component {

  constructor(props) {
    super(props);
    this.state = {hovering: false};
  }

  onClick() {
    this.props.handleClick(this.props.text);
  }

  onHover() {
    this.setState({
        hovering: !this.state.hovering
    });
  }

  render() {
    const color = this.state.hovering ? 'blue' : 'default';
    const text = this.state.hovering ? 'Hover Text' : this.props.text;
    console.log(color, text);
    return (
        <button
            onClick={this.onClick.bind(this)}
            style={{color: color}}
            onMouseEnter={this.onHover.bind(this)}
            onMouseOut={this.onHover.bind(this)}>
                {text}
        </button>
    );
  }
}

ReactDOM.render(
  <ReactButton
    text={"Original Text"}
    handleClick={(e) => console.log('clicked')} />,
  document.querySelector('#container')
);

If you take a look at the demo you will notice that the text color changes to blue when the button is hovered, however when the mouse leaves the button the text color remains blue. The event is fired and the state does change triggering a re-render as evidenced by the text changing.
Why is react not updating the in-line style? What can I do to fix this?

A: color: does not have default option,
change default to inherit (or default color name what you want like #000000),
const color = this.state.hovering ? 'blue' : 'inherit';

Example
Example-2


text:
Q: Relay Modern - Subscription updater(connection handler) method (no documentation on this matter) I am trying to perform a subscription for my query. So my suspicion is that the connection (from the ConnectionHandler) is not working. I cannot find any proper documentation on this one.
My subscription looks like:
  const LinkSubscription = graphql`
  subscription LinkSubscription {
    Link(filter:{
      mutation_in:[CREATED]
    }){
      node{
        id
      }
    }
  }
`;

export default () => {
  const subscriptionConfig = {
    subscription: LinkSubscription,
    variables: {},
    onCompleted: () => { alert('done!'); },
    updater: (Store, data) => {
      const newLink = Store.getRootField('Link').getLinkedRecord('node');
      const allLinks = Store.getRoot();
      const edge = ConnectionHandler.createEdge(Store, allLinks, newLink, 'allLinks');
      const userId = localStorage.getItem('user_id');
      const connection = ConnectionHandler.getConnection(allLinks, newLink, 'allLinks');
      if (connection) {
        ConnectionHandler.insertEdgeAfter(connection, newLink);
        console.log('DONE');
      }
      console.log('DEBUG', Store);
      console.log('DEBUG2', newLink);
      console.log('DEBUG3', allLinks);
      console.log('DEBUG4', edge);
      console.log('DEBUG5', connection);
      console.log('DEBUG6', ConnectionHandler);
      console.log('DEBUG7', userId);
      console.log('Debug8', data);
    },
    onError: error => console.log('An error occured:', error),
  };
  requestSubscription(Environment, subscriptionConfig);
};

As you may see in the code i ran a lot of logs to see  what i did wrong.
Log DEBUG fires: RelayRecordSourceSelectorProxy,
Log DEBUG2 fires:RelayRecordProxy // for the specific id(59f88d417fae441eb567c453) CREATED,
Log DEBUG3 fires: RelayRecordProxy// for client:root,
Log DEBUG4 fires: RelayRecordProxy// for client:root:59f88d417fae441eb567c453,
Log DEBUG5: undefined,
Log DEBUG6: ConnectionHandler methods,
Log DEBUG7: user.id who requested the query.
Question1:Can you please help with some connection suggestions?

A: Subscriptions: Updating the client on each response
const LinkSubscription = graphql`
  subscription LinkSubscription {
    Link(filter: { mutation_in: [CREATED] }) {
      node {
        id
      }
    }
  }
`;

export const test = () => {
  const subscriptionConfig = {
    subscription: LinkSubscription,
    variables: {},
    onCompleted: () => {
      alert('done!');
    },
    updater: (Store, data) => {
      const newLink = Store.getRootField('Link').getLinkedRecord('node');
      const viewerProxy = Store.getRoot().getLinkedRecord('viewer');

      const connection = ConnectionHandler.getConnection(
        viewerProxy,
        '<nameConnection>', // 'Viewer_links' or <Name_links>
        { mutation_in: ['CREATED'] }
      );
      const edge = ConnectionHandler.createEdge(
        Store,
        connection,
        newLink,
        'LinkEdge'
      );
      if (connection) {
        ConnectionHandler.insertEdgeBefore(connection, edge);
        console.log('DONE');
      }
    },
    onError: error => console.log('An error occured:', error)
  };

  requestSubscription(Environment, subscriptionConfig);
};


text:
Q: What qualifies for integration testing within Apex unit test We have ~5k unit test running for 6-8 hrs. I want to bring down the runtime. Main contributor is the DMLs in the testsetup and DMLs in the actual class. I want to replace it with Stubbing wherever possible to reduce the total runtime.
Example:
Case object has ~50 field updates done through trigger. I will write pure unit test for each field updates in trigger using stubbing and avoid DMLs.
But these field updates should also be tested as the whole trigger runs. At the same time Apex testing time should be reduced.
Questions:

*

*Does these field updates need to be Apex tested using unit tests with DMLs?

*Are there any guidelines for the scope of how much integration testing should be done through Apex testing in this scenario?

A: As Phil commented, this type of question is primarily opinion-based, so I think you will get multiple answers.

For me, a unit test should test a single piece of the code, like a specific method, regardless of its usage in the business process. The unit test serves the purpose of asserting that this unit of code works as intended given multiple inputs.
To exemplify, say that a method has a signature that allows the developer to call it with a list of Ids of a certain object type. The test would likely test the method for what happens when the method is called with a null parameter, an empty list, a single item on the list and multiple elements on the list. This could be a method to handle something that happens with a specific record, like an account or case, for example.
Now, this method does nothing on its own, it has to be applied somewhere (like a trigger). Then you have the integration test, to assert that the method is called by your trigger when your code does some DML operation on said object. This is when you test the integration between your business logic, trigger and method.
To be honest, I'm not a fan of testing an entire process in a piece of test. Think about a sales process starting from product registration, to opportunity, order and contract. I don't think it makes much sense to test the whole process at once, because the test can get really big and difficult to maintain (especially if there can be multiple scenarios for your app, imagine writing hundreds of lines just to set the scenario up, and then having to modify a couple of parameters just to test a slightly different scenario).

Applying this to your scenario, I would say to try to write the code in a way that you can specify which field and value are being changed, and then assert that the attribution of value happens as intended in a unit test. If it works for one field, it should work for all the others. You can write just a couple of tests to assert that the types work as intended (for string/number/date/datetime fields). This way, you don't need to test all 50 or more scenarios, because they will all call the same method that was previously tested.


text:
Q: When do functions of correlated r.v.s have a small correlation? For independent random variables $X$ and $Y$, $f(X)$ and $f(Y)$ are independent.
For uncorrelated random variables, functions of these are not necessarily uncorrelated: Are functions of uncorrelated random variables still uncorrelated?.
My question is a relaxed version of this one When will functions of two uncorrelated random variables be still uncorrelated?
If $X$ and $Y$ has $|Cov(X,Y)|\leq \epsilon$, when do we expect $|Cov(f(X),f(Y))|$ to be small?
I wonder if there is a well known class of functions.
For example if $f$ is linear, we can say this. But I wonder something like Lipschitzness for covariance, although Lipschitz functions do not seem to work.


text:
Q: Getting bad map relo error while trying to attach an eBPF program to tc When trying to run the command,
sudo tc filter add dev veth0 egress bpf direct-action obj a.o sec classifier

I'm getting this error,
libbpf: prog 'pdm_main': bad map relo against '.rodata.str1.1' in section '.rodata.str1.1'
ERROR: opening BPF object file failed
Unable to load program

The sections in my object file,
Sections:
Idx Name          Size      VMA               LMA               File off  Algn
  0 .text         00000000  0000000000000000  0000000000000000  00000040  2**2
                  CONTENTS, ALLOC, LOAD, READONLY, CODE
  1 classifier    00000638  0000000000000000  0000000000000000  00000040  2**3
                  CONTENTS, ALLOC, LOAD, RELOC, READONLY, CODE
  2 .maps         00000020  0000000000000000  0000000000000000  00000678  2**3
                  CONTENTS, ALLOC, LOAD, DATA
  3 .rodata.str1.1 0000002c  0000000000000000  0000000000000000  00000698  2**0
                  CONTENTS, ALLOC, LOAD, READONLY, DATA
  4 .rodata.str1.16 00000036  0000000000000000  0000000000000000  000006d0  2**4
                  CONTENTS, ALLOC, LOAD, READONLY, DATA
  5 license       00000004  0000000000000000  0000000000000000  00000706  2**0
                  CONTENTS, ALLOC, LOAD, DATA
  6 .debug_loclists 00000105  0000000000000000  0000000000000000  0000070a  2**0
                  CONTENTS, READONLY, DEBUGGING, OCTETS
  7 .debug_abbrev 000001c9  0000000000000000  0000000000000000  0000080f  2**0
                  CONTENTS, READONLY, DEBUGGING, OCTETS
  8 .debug_info   0000080f  0000000000000000  0000000000000000  000009d8  2**0
                  CONTENTS, RELOC, READONLY, DEBUGGING, OCTETS
  9 .debug_str_offsets 000002a4  0000000000000000  0000000000000000  000011e7  2**0
                  CONTENTS, RELOC, READONLY, DEBUGGING, OCTETS
 10 .debug_str    000006ec  0000000000000000  0000000000000000  0000148b  2**0
                  CONTENTS, READONLY, DEBUGGING, OCTETS
 11 .debug_addr   00000030  0000000000000000  0000000000000000  00001b77  2**0
                  CONTENTS, RELOC, READONLY, DEBUGGING, OCTETS
 12 .BTF          00001037  0000000000000000  0000000000000000  00001ba8  2**2
                  CONTENTS, RELOC, READONLY
 13 .BTF.ext      00000470  0000000000000000  0000000000000000  00002be0  2**2
                  CONTENTS, RELOC, READONLY
 14 .eh_frame     00000030  0000000000000000  0000000000000000  00003050  2**3
                  CONTENTS, ALLOC, LOAD, RELOC, READONLY, DATA
 15 .debug_line   00000220  0000000000000000  0000000000000000  00003080  2**0
                  CONTENTS, RELOC, READONLY, DEBUGGING, OCTETS
 16 .debug_line_str 000000f8  0000000000000000  0000000000000000  000032a0  2**0
                  CONTENTS, READONLY, DEBUGGING, OCTETS

How to fix this? When i don't use eBPF map in my code it doesn't give the same error.


text:
Q: Do orcs live like nomads or do they live underground waiting to be called up? Do orcs in the Lord of the Rings universe wander the world like nomads sometimes or just live underground until summoned by the one controlling them?
Also do the orcs have a tribal like society as opposed to a more structured one with laws and whatnot?

A: The goblins/orcs in The Hobbit live underground in caves in the Misty Mountains, and they have a rather structured society with a king rather than a chieftain. Tolkiens also mentions that there are 'many' goblin strongholds in the Misty Mountains. The Moria orcs obviously also live underground, led by first Azog and later his son Bolg (the two were conflated in the movies). The Mordor orcs seem to live as much aboveground as underground, but that may be due to Sauron's organisation. Underground, hence, seems to be the preferred habitat of orcs, which makes sense given that they hate the sun.

Orcs have some industry, making their own weapons and armor, and the Goblin King of the Misty Mountains also has elaborate machines to torture prisoners. This suggests some level of organization, though it seems doubtful that there are many laws except the will of the king or chieftain. There does, however, seem to be a law or code against orcs eating orc-flesh:  Grishnákh, leader of the Mordor Orcs, accuses Saruman's Uruks of eating Orc-flesh, which they angrily deny.


text:
Q: How to apply condition on column of type jsonb using spring data I have a table definition given below filled with random text. I wanted to fetch the records based on the collection of tags.
 Id (int) | tags (jsonb)
------------------------------
   1        | ['bookmarks','social','fashion']
   2        | ['kafka','key bert','stereotype']
   3        | ['social','kibana','fashion']

For example, I wanted to pick the records whose tags are 'social' and 'fashion'. Expected Results are
 Id (int) | tags (jsonb)
------------------------------
   1      | ['bookmarks','social','fashion']
   3      | ['social','kibana','fashion']

To get the above results, I have cross checked the below query in postgres and works as expected.
select * from random_table where tags @> cast('["social","fashion"]' as jsonb)

Now, how do i achieve the same using Spring data.
 @Query(value="""
                select
                       *
                from
                       random_table def
                where
                       def.tags = CAST((:filterTags) AS jsonb)
 """,nativeQuery = true)
 List<TagRecord> findRecordsByTags(Set<String> filterTags);

The definition of TagRecord
  @Data
  public class TagRecord {

    private int id;

    @Column(name = "tags",columnDefinition = "jsonb")
    @Type(type = "jsonb")
    private Set<String> tags;
}

When i execute the above function, I am facing casting error.  How to cast set of string into jsonb ?. Is there a better way to do same. If so, i wish to learn.


text:
Q: Managed array issue in C++/CLI compilng with /clr
array<Byte>^ byteArray =  gcnew array<Byte>(25);

Why would I get these compiler errors?
error C2065: 'array' : undeclared identifier
error C2065: 'gcnew' : undeclared identifier
error C2275: 'System::Byte' : illegal use of this type as an expression
error C3192: syntax error : '^' is not a prefix operator (did you mean '*'?)

I am calling this method inside a class with
using namespace System;

__gc class MyClass

This feels like I am missing something very basic here. Even this causes errors:
array<Byte>^ byteArray;

or
array<Byte> * byteArray;

Thank you!!

A: The syntax __gc class was used in the, now obsolete, Managed C++. In C++/CLI, use ref class.
For more information see the section Syntax changes in the Wikipedia article C++/CLI.


text:
Q: Readonly role c# mvc I have a customroleprovider.cs
I have a user table that has users and their roles. most users have role as user, there are only 3 admin, now i need to create 3 readonly users. these users can only view the whole website, and cannot edit any part of the website. in my views i have these:
 @{
        var simpleRoles = (RoleProvider)Roles.Provider;
    }
    @if (simpleRoles.IsUserInRole(User.Identity.Name, "admin"))
    {
}

to restrict some areas only for admin, do i need something like this for readonly users?

A: Since you have admin and users, you may want to create an "admin" area and a "user" area.  What I suggested below is only if you have a few views you want to hide from roles.  In the admin area you can add the authorize attribute to a base controller for that area so that only admins can update content.  Otherwise, you'll have to have if statements in the views if you wanted to hide the update buttons from different appearing for roles, and that could get messy.
UPDATE:
Below is a link for an overview of areas.  Areas are nice because you can create an area called "Admin" and inside that area you will have controllers/views/viewmodels, etc... that are separate from a different area.  Inside this area you can include the logic for updating content, whereas if you don't want a role to update content then don't include the logic inside their area.  Hopefully the link will do a better job explaining it than I can.
When I use areas for my project, I'll create a base controller that all of my controllers inherit from.  An example of what my base controller may look like is:
[Authorize(Roles="Admin")]
public class AdminBaseController : Controller
{
    ...
}

Then in all of my controllers in the area I'll inherit from the AdminBaseController so that only admins can access this section of the website.
public class HomeController : AdminBaseController
{
    ...
}

http://www.dotnet-tricks.com/Tutorial/mvc/a9P1010113-MVC-Areas-with-example.html
Adding an Authorize attribute on the view:
For example, if you only want admin's to view the view.cshtml file then you can do something like this on the controller action:
[Authorize(Roles="admin")]
public ActionResult View()
{
    ....
}

If user's aren't in that role then they will be be able to access that view.
For multiple roles, you can do:
[Authorize(Roles="admin, user")]
public ActionResult View()
{
    ...
}

This will allow anybody that is an admin OR user to view the page.  (They don't have to be in both roles).

A: Elaborating on my comment above. Decorating your controller actions with the Authorization Attribute will lock down it to the specific role(s). This does not solve the issue of a read-only type role. You will need some logic in the controller action to evaluate the role then return a different view. I recommend placing this in a BaseController. Have your other controllers inherit it:
public abstract class BaseController : Controller
{

    public bool IsReadOnly { get; set; }

    public BaseController()
    {
        this.IsReadOnly = Roles.IsUserInRole("readonly");
    }
}

public class HomeController : BaseController
{
    [Authorize(Roles = "admin, user, readonly")]
    public ActionResult Edit(int id)
    {
        if (!IsReadOnly)
        {
            return View("Details");
        }
        ... other stuff
    }
}

A: Try This in .cshtml
@if ( User.Identity.IsAuthenticated ){
    if ( User.IsInRole("Admin") ){
        @Html.ActionLink("Admin", "AdminController")
    }
}


text:
Q: How does a select2 widget gets populated with AJAX? When I enter a few characters in my widget, I get results like these from AJAX:
[{"id":550,"campName":"IB Resi Showtime Rebate Website"},{"id":60,"campName":"OB ACGBK EB"}]

However, I'm missing the part on how to populate the widget with those results.
Here is the code I use for the widget:
$this->widget
(
        'ext.ESelect2-master.ESelect2',
        [
            'selector'=>'#campaigns',
            'options'=>
            [
                'tags'=>$tags,
                'allowClear'=>true,
                'minimumInputLength' => 2,
                'width'=>'300px',
                'multiple'=>true,
                'placeholder'=>'Campaigns',
                'ajax'=>
                [
                    'url'=>Yii::app()->createUrl('CoxReports/autoCompleteCampaigns'),
                    'dataType'=>'json',
                    'data'=>'js:function(term,page){return{q: term, page_limit: 10, page: page};}',
                    'results'=>'js:function(data,page){ return {results:data};}'
                ]
            ]
        ]
);

What am I missing?

A: You're missing a formatResult and a formatSelection definition in your widget.
See this code for an example.
The results are handled by the formatResult function with custom markup, the structure is similar to yours.


text:
Q: an error about C struct array in formal parameter I have got the following code:
struct student_info;
void paiming1(struct student_info student[]);
struct student_info
{
    int num;
    char name[6];
};

The IDE gives an error
error: array type has incomplete element type 'struct student_info'
 void paiming1(struct student_info student[]);

But if I use void paiming1(struct student_info *student); it works OK. Why is that? I am using GCC.

A: С language unconditionally requires array element type in all array declarations to be complete. Period.

6.7.6.2 Array declarators
Constraints
1 [...] The element type shall not be an incomplete or function
  type. [...]

No exception is made for array declarations used in function parameter lists. This is different from C++ - the latter drops this completeness requirement for function parameter lists
struct S;
void foo(struct S[]); // OK in C++, invalid in C

Considering that in parameter list declaration type T [] is later adjusted to type T * anyway, this requirement might appear to be excessive. (And this is why C++ relaxed it.) Nevertheless, this restriction is present in C language. This is just one of the quirks of C language.
As you already know, you can explicitly switch to the equivalent
void paiming1(struct student_info *student);

form to work around the issue.

A: Careful reading of the standard makes it clear that in C99 and C11 the declaration is supposed to be a constraint violation. C11 6.7.2.6 Array declarations p1

*

*In addition to optional type qualifiers and the keyword static, the [ and ] may delimit an expression or *. If they delimit an expression (which specifies the size of an array), the expression shall have an integer type. If the expression is a constant expression, it shall have a value greater than zero. The element type shall not be an incomplete or function type. The optional type qualifiers and the keyword static shall appear only in a declaration of a function parameter with an array type, and then only in the outermost array type derivation.

Since this contains references to the * that is valid only in function declarations that are not definitions, and nowhere else, the constraints as whole needs to be taken as applying to parameters.

For C90 the case is more complicated. This is actually discussed in C90 Defect Report 47 from 10 December, 1992.
2 of the 6 declarations given there are
/* 1. */ struct S;
/* 3. */ struct S *g(struct S a[]) { return a; }

and the defect report asks if these are strictly-conforming. It must be noted that unlike the question, these are prototypes that are part of definition rather than just declaration.
Nevertheless, the standard committee responds by saying that

The struct S is an incomplete type (subclause 6.5.2.3, page 62, lines 25-28). Also, an array of unknown size is an incomplete type (subclause 6.5.4.2, page 67, lines 9-10). Therefore, arrays of either of the above are not strictly conforming (subclause 6.1.2.5, page 23, lines 23-24). This makes declarations 3, 4, and 6 not strictly conforming. (But an implementation could get it right.)
As an aside, array parameters are adjusted to pointer type (subclause 6.7.1, page 82, lines 23-24). However, there is nothing to suggest that a not-strictly-conforming array type can magically be transformed into a strictly conforming pointer parameter via this rule.
The types in question can be interpreted two different ways. (Array to pointer conversion can happen as soon as possible or as late as possible.) Hence a program that uses such a form has undefined behavior.

(emphasis mine)
Since this has not been clarified in writing since 1992, we must agree that the behaviour is undefined and therefore the C standard imposes no requirements, and a compiler that successfully compiles this this can still conform to C90.
The committee also states that there is no constraint violation in C90, therefore a C90 conforming compiler need not output any diagnostics.
I've edited the answer; I previously claimed that this would apply to C99 and C11 alike, but the text was changed in C99 as above, therefore this is a constraint violation in C99, C11.

A: Compiler doesn't know anything about size of struct student_info until it is declared. This should work:
struct student_info
{
    int num; //学号
    char name[6]; //姓名
    char sex[5]; //性别
    char adress[20]; //家庭住址
    char tel[11]; //电话
    int chinese,math,english,huping,pingde,jiaoping,paiming1,paiming2;
    double ave,zhongping;
};

void paiming1(struct student_info student[]);
void paiming2(struct student_info student[]);

When you declare it as a pointer using *, compiler knows the size of the argument (its an address).


text:
Q: Can't Identify the reason behind Null Pointer Exception I'm creating a home automation android application with my arduino uno and HC-05 Bluetooth Module. Everything works fine already. It can scan, connect, on/off bluetooth, control the bulb on and off using buttons and switch control but with a bad and plain design of the application. So I decided to use a Tab Widget. The problem is that when I change something it won't run and shows a NullPointerException problem and I don't have any idea why ots happening since its already a working app for this past few days.
Here are the list in the LogCat:
02-21 08:48:18.063: E/AndroidRuntime(25982): FATAL EXCEPTION: main
02-21 08:48:18.063: E/AndroidRuntime(25982): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.javac101/com.example.javac101.MainActivity}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.javac101/com.example.javac101.ControllerTab}: java.lang.NullPointerException
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2395)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.ActivityThread.access$600(ActivityThread.java:162)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1364)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.os.Handler.dispatchMessage(Handler.java:107)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.os.Looper.loop(Looper.java:194)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.ActivityThread.main(ActivityThread.java:5371)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at java.lang.reflect.Method.invokeNative(Native Method)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at java.lang.reflect.Method.invoke(Method.java:525)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at dalvik.system.NativeStart.main(Native Method)
02-21 08:48:18.063: E/AndroidRuntime(25982): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.javac101/com.example.javac101.ControllerTab}: java.lang.NullPointerException
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2343)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.ActivityThread.startActivityNow(ActivityThread.java:2186)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:749)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.widget.TabHost.setCurrentTab(TabHost.java:413)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.widget.TabHost.addTab(TabHost.java:240)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at com.example.javac101.MainActivity.onCreate(MainActivity.java:164)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.Activity.performCreate(Activity.java:5122)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
02-21 08:48:18.063: E/AndroidRuntime(25982):    ... 11 more
02-21 08:48:18.063: E/AndroidRuntime(25982): Caused by: java.lang.NullPointerException
02-21 08:48:18.063: E/AndroidRuntime(25982):    at com.example.javac101.ControllerTab.onCreate(ControllerTab.java:110)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.Activity.performCreate(Activity.java:5122)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1081)
02-21 08:48:18.063: E/AndroidRuntime(25982):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2307)
02-21 08:48:18.063: E/AndroidRuntime(25982):    ... 21 more

The line mentioned in the Logcat in my MainActivity:
tabHost.addTab(tabSpecController);

The line mentioned in the Logcat in my ControllerTab:
list.setOnItemClickListener(new OnItemClickListener()

It might be not clear to understand so here are my codes in MainActivity:
package com.example.javac101;
public class MainActivity extends TabActivity {

    //BLUETOOTH
        BluetoothAdapter            BTAdapter;
        //BluetoothDevice               BTDevice;

    //Layout view daw
        public static TextView title;
        public static ImageView status;

    //Intent
        private static final int    REQUEST_DEVICE_CONNECT = 1;
        private static final int    REQUEST_ENABLE_BLUETOOTH = 2;
        private static final int    REQUEST_ABOUTS = 3;

        //object for bluetooth command service
        public static BluetoothCommandService commandService = null;

        //
        private String connectedDeviceName = null;

        //Message types sent from the Handler
        public static final int MESSAGE_STATE_CHANGE = 1;
        public static final int MESSAGE_READ = 2;
        public static final int MESSAGE_WRITE = 3;
        public static final int MESSAGE_DEVICE_NAME = 4;
        public static final int MESSAGE_TOAST = 5;
        public static final int RECIEVE_MESSAGE = 6;

        //Will be used in BluetoothCommandSrvice jave file
        public static final String TOAST = "toast";
        public static final String DEVICENAME = "device name";

        public static final String HC05 = "20:13:06:19:34:54";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        String address = new String(DeviceList.EXTRA_DEVICE_MAC_ADDRESS);
        if (address.equals(MainActivity.HC05))
        {
            Intent login = new Intent (this, LoginActivity.class);
        }
        else
        {
            requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
            setContentView(R.layout.tabs);

            /**
             * DATABASE CRUD Operations
             * */

            DatabaseHandler db = new DatabaseHandler(this);

            // Inserting Devices
            Log.d("Insert: ", "Inserting ..");
            db.addDevice(new Device(1, "DB Device 1"));
            db.addDevice(new Device(2, "DB Device 2"));
            db.addDevice(new Device(3, "DB Device 3"));

        // Reading all devices
            Log.d("Reading: ", "Reading all devices..");
            List<Device> devices = db.getAllDevices();

            for (Device dv : devices) {
                String log = "Id: "+dv.getID()+" ,Name: " + dv.getName();
                Log.d("Name: ", log);
            }

            getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);
                title = (TextView) findViewById(R.id.title_left_text);  // Set up the custom title
                title.setText(R.string.app_name);                       // Set up the custom title
                title = (TextView) findViewById(R.id.title_right_text); // Set up the custom title
Resources ressources = getResources();
            TabHost tabHost2 = getTabHost();
            TabHost tabHost = tabHost2;

            // Controller Tab
            Intent intentController = new Intent().setClass(this, ControllerTab.class);
            TabSpec tabSpecController = tabHost
                    .newTabSpec("Controller")
                    .setIndicator("", ressources.getDrawable(R.drawable.icon_home_config))
                    .setContent(intentController);

            // Setting Tab
                    Intent intentSetting = new Intent().setClass(this, Settings.class);
                    TabSpec tabSpecSetting = tabHost
                      .newTabSpec("Setting")
                      .setIndicator("", ressources.getDrawable(R.drawable.icon_settings_config))
                      .setContent(intentSetting);

            // add all tabs
            tabHost.addTab(tabSpecController);
            tabHost.addTab(tabSpecSetting);

            //set Windows tab as default (zero based)
            tabHost.setCurrentTab(0);
// AUTO REQUEST OF ENABLING THE BLUETOOTH
            BTAdapter = BluetoothAdapter.getDefaultAdapter();

            //A code that will detect if BT is enabled otherwise will require it.
            if (BTAdapter == null)
            {
                //Toast.makeText(context, text, duration)
                Toast.makeText(this, "No Bluetooth adapter is available.", Toast.LENGTH_LONG).show();
                finish();
                return;
            }

        }
    }

    private void setVisible(int tabs, boolean b) {
        // TODO Auto-generated method stub

    }

    @Override
    protected void onStart()
    {
        super.onStart();
        //Requesting Bluetooth automatically when its not yet enabled.
        if (!BTAdapter.isEnabled())
        {
            Intent enableIntent = new Intent (BluetoothAdapter.ACTION_REQUEST_ENABLE);
            //startActivityForResult(enableIntent, 0);
            startActivityForResult(enableIntent, REQUEST_ENABLE_BLUETOOTH);
        }
        else
        {
            if (commandService == null)
                setupCommand();
        }
    }
@Override
    protected void onResume() {
        super.onResume();

        if (commandService != null)
        {
            if (commandService.getState() == BluetoothCommandService.stateNothing)
            {
                commandService.start();
            }
        }
    }

    private void setupCommand()
    {
        commandService = new BluetoothCommandService(this, bluetoothHandler);
    }

    @Override
    protected void onDestroy()
    {
        super.onDestroy();
        if (commandService != null)
            commandService.stop();
    }
public final Handler bluetoothHandler = new Handler()
        {
            @Override
            public void handleMessage(android.os.Message msg)
            {
                switch (msg.what)
                {
                    case MESSAGE_STATE_CHANGE:
                        switch (msg.arg1)
                        {
                            case BluetoothCommandService.stateConnected:
                                title.setText(R.string.title_connectedTo);
                                title.append(connectedDeviceName);
                                break;

                            case BluetoothCommandService.stateConnecting:
                                title.setText(R.string.title_connecting);
                                break;

                            case BluetoothCommandService.stateListen:
                            case BluetoothCommandService.stateNothing:
                                title.setText(getString(R.string.title_notConnected));
                                break;
                        }
                        break;

                    case MESSAGE_DEVICE_NAME:
                        connectedDeviceName = msg.getData().getString(DEVICENAME);
                        Toast.makeText(getApplicationContext(), "Connected to " + connectedDeviceName, Toast.LENGTH_SHORT).show();
                        break;

                    case MESSAGE_TOAST:
                        Toast.makeText(getApplicationContext(), msg.getData().getString(TOAST), Toast.LENGTH_SHORT).show();
                        break;

                    //case RECIEVE_MESSAGE:                                                 // if receive message
                    //  byte[] readBuf = (byte[]) msg.obj;
                    //  String strIncom = new String(readBuf, 0, msg.arg1);                 // create string from bytes array
                    //  sb.append(strIncom);                                                // append string
                    //  int endOfLineIndex = sb.indexOf("\r\n");                            // determine the end-of-line
                    //  if (endOfLineIndex > 0) {                                           // if end-of-line,
                    //      //String sbprint = sb.substring(0, endOfLineIndex);             // extract string
                    //        sb.delete(0, sb.length());                                        // and clear
                            //txtArduino.setText("Data from Arduino: " + sbprint);          // update TextView
                            //1/4/14
                    //      btn_d1_on.setEnabled(true);
                    //  btn_d1_off.setEnabled(true);
                        //   }
                        //Log.d(TAG, "...String:"+ sb.toString() +  "Byte:" + msg.arg1 + "...");
                        //break;

                }
                //return false;
            }
        };
        //});

        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            switch (requestCode) {
            case REQUEST_DEVICE_CONNECT:
                // When DeviceList Activity returns with a device to connect
                if (resultCode == Activity.RESULT_OK) {
                    // Get the device MAC address
                    //String address = data.getExtras().getString(DeviceList.EXTRA_DEVICE_MAC_ADDRESS);
                    String address = new String(data.getExtras().getString(DeviceList.EXTRA_DEVICE_MAC_ADDRESS));
                        if (address.equals(HC05))
                        {
                            // Get the BLuetoothDevice object
                            BluetoothDevice device = BTAdapter.getRemoteDevice(address);
                            // Attempt to connect to the device
                            commandService.connect(device);
                        }
                        else
                        {
                            Toast.makeText(this, "This device is not for JavaC101 Application. Please connect to HC-05 device.", Toast.LENGTH_LONG).show();
                        }
                }
                break;

            case REQUEST_ENABLE_BLUETOOTH:
                // When the request to enable Bluetooth returns
                if (resultCode == Activity.RESULT_OK) {
                    // Bluetooth is now enabled, so set up a chat session
                    setupCommand();
                } else {
                   // User did not enable Bluetooth or an error occured
                    Toast.makeText(this, R.string.notEnabledBluetooth, Toast.LENGTH_SHORT).show();
                    finish();
               }

            }
        }
@Override
    //Creating an Option Menu for connectivity and discoverability of a BT device
    public boolean onCreateOptionsMenu(Menu menu)
    {
        //MenuInflater is a class
        MenuInflater OptionMenu = getMenuInflater();
        //OptionMenu.inflate(menuRes, menu)
        OptionMenu.inflate(R.menu.main, menu);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item)
    {
        switch (item.getItemId())
        {
            case R.id.connect:
                connect();
                return true;
            case R.id.bton:
                bluetoothOn();
                return true;
            case R.id.btoff:
                bluetoothOff();
                return true;
            case R.id.abouts:
                abouts();
                return true;
            //default:
                //return super.onOptionsItemSelected(item);
        }
        return false;
    }

    //@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@

      private void connect()
      {
          Intent serverIntent = new Intent(this, DeviceList.class);
          this.startActivityForResult(serverIntent, REQUEST_DEVICE_CONNECT);
          //startActivityForResult(serverIntent, REQUEST_DEVICE_CONNECT);
      }

      private void bluetoothOn()
      {
          BTAdapter.enable();
          Toast.makeText(this, "Bluetooth is now turned on", Toast.LENGTH_SHORT).show();
      }

      private void bluetoothOff()
      {
          BTAdapter.disable();
          Toast.makeText(this, "Bluetooth is now turned off.", Toast.LENGTH_SHORT).show();
      }

      private void abouts()
      {
          Intent intentAbouts = new Intent(this, abouts.class);
          //startActivityForResult(intentAbouts, REQUEST_ABOUTS);
          startActivity(intentAbouts);
      }

Since there is also an error in my other class which is the ControllerTab so here are my codes of it:
    public class ControllerTab extends Activity implements OnItemClickListener {
    //BluetoothAdapter          BTAdapter;
    public static BluetoothAdapter          BTAdapter;
    //Intent
    private static final int    REQUEST_DEVICE_CONNECT = 1;
    private static final int    REQUEST_ENABLE_BLUETOOTH = 2;
    private static final int    REQUEST_ABOUTS = 3;
    //
    private String connectedDeviceName = null;
    //Message types sent from the Handler
    public static final int MESSAGE_STATE_CHANGE = 1;
    public static final int MESSAGE_READ = 2;
    public static final int MESSAGE_WRITE = 3;
    public static final int MESSAGE_DEVICE_NAME = 4;
    public static final int MESSAGE_TOAST = 5;
    public static final int RECIEVE_MESSAGE = 6;
  //Will be used in BluetoothCommandSrvice jave file
        public static final String TOAST = "toast";
        public static final String DEVICENAME = "device name";

    //@@@@@@@for the controller
    public static final String tagStateCTRL = "Controller";
    private OutputStream outStream = null;
    private static final UUID myUUID = UUID.fromString("fa87c0d0-afac-11de-8a39-0800200c9a66");
    private static String address = "00:00:00:00:00:00"; // Insert your bluetooth devices MAC address
    private StringBuilder sb = new StringBuilder();
    Button btn_d1_on, btn_d1_off, btn_d2_on, btn_d2_off;
    Switch switch_d1, switch_d2;
    TextView textDevice1;

        //for the switch
        private final static Integer[] ids = { R.id.switch1, R.id.switch2 };

        //object for bluetooth command service
        private BluetoothCommandService commandService = null;

        //listview, swtchcontrol
        private ArrayAdapter<String> switchControls;

        private TextView deviceID;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        DatabaseHandler db = new DatabaseHandler(this);
        List<Device> deviceList = db.getAllDevices();
        if (deviceList.size()!=0) {
            ListView list = getListView();
            list.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
                    deviceID = (TextView) view.findViewById(R.id.deviceId);
                    String valDeviceId = deviceID.getText().toString();
                    Intent objIndent = new Intent(getApplicationContext(), EditDeviceName.class);
                    objIndent.putExtra("deviceID", valDeviceId);
                    startActivity(objIndent);
                }
            });
// Initialize the BluetoothChatService to perform bluetooth connections
         commandService = new BluetoothCommandService(this, bluetoothHandler);
         BTAdapter = BluetoothAdapter.getDefaultAdapter();

        switch_d1 = (Switch) findViewById(R.id.switch1);
        switch_d2 = (Switch) findViewById(R.id.switch2);

            registerOnCheckedListener(ids);
 }}
    private ListView getListView() {
        // TODO Auto-generated method stub
        return null;
    }
@SuppressLint("NewApi")
    private void registerOnCheckedListener(Integer... ids)
    {
        for (int i=0; i<ids.length; i++)
        {
            Integer id = ids[i];
            Switch switchControl = (Switch) findViewById(id);
            switchControl.setOnCheckedChangeListener((OnCheckedChangeListener) this);
        }
    }

    //@Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
    {
        switch (buttonView.getId())
        {
            case R.id.switch1:
                    if (isChecked)
                        //ga error man sooooo "surround with try/catch" pra mwala.. ok? ^_^
                        try {
                            String address = new String(DeviceList.EXTRA_DEVICE_MAC_ADDRESS);
                            if (address.equals(MainActivity.HC05))
                            {
                                sendData("1");
                            }
                            else
                            {
                                Toast.makeText(this, "Your phone is not connected to HC-05.", Toast.LENGTH_SHORT).show();
                            }
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    else
                        try {
                            String address = new String(DeviceList.EXTRA_DEVICE_MAC_ADDRESS);
                            if (address.equals(MainActivity.HC05))
                            {
                                sendData("3");
                            }
                            else
                            {
                                Toast.makeText(this, "Your phone is not connected to HC-05.", Toast.LENGTH_SHORT).show();
                            }
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    return;
            case R.id.switch2:
                if (isChecked)
                    try {
                        String address = new String(DeviceList.EXTRA_DEVICE_MAC_ADDRESS);
                        if (address.equals(MainActivity.HC05))
                        {
                            sendData("2");
                        }
                        else
                        {
                            Toast.makeText(this, "Your phone is not connected to HC-05.", Toast.LENGTH_SHORT).show();
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                else
                    try {
                        String address = new String(DeviceList.EXTRA_DEVICE_MAC_ADDRESS);
                        if (address.equals(MainActivity.HC05))
                        {
                            sendData("4");
                        }
                        else
                        {
                            Toast.makeText(this, "Your phone is not connected to HC-05.", Toast.LENGTH_SHORT).show();
                        }
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
        }
    }
...

A: This is what you currently have:
list = getListView()

...

private ListView getListView() {
    // TODO Auto-generated method stub
    return null;
}

You need to implement getListView.


text:
Q: Why $d,f$ electrons are more localized than $s,p$ electrons? I'm reading Assa Auerbach's Interacting electrons and quantum magnetism.
In 1.3, it says

In contrast, transition metals and mixed valence rare earth compounds
contribute $d$ and $f$ electrons to the conduction band. There, the electrons are mostly localized within a small radius $\langle r_{ij}\rangle \ll a$ around the ions, where $a$ is the lattice spacing.

I wonder why are $d$ and $f$ electrons near to the ions?

A: Promoted from a comment:

The filling sequence order of orbitas: $1s, 2s, 2p, 3s, 3p, 4s, 3d, 4p, 5s, 4d, 5p, 6s, 4f, 5d, 6p, 7s$. The energy of orbital $4d$ is greater than that of $5s$, and $4f$ is greater than $6s$. The principle quantum number $n$ mainly determine the size of the orbital. Therefore, the size of $4f$ is much smaller than $6s$.


text:
Q: VS Code Dart extension: how do I disable Dart style warnings? I don't want to name .dart files using "lowercase_with_uderscores". How do I disable this warning in Dart VS Code extension? Moreover, when I rename my file to lowercase, it still shows the same warning each time I make changes to the file. Any idea on how to disable these warnings for good, not just for one file, but for the whole project? I know what's best for me, I'm just trying to code...
This is what I see:

A: Just comment this highlighted line of code in the analysis_options.yaml file...


text:
Q: Animation of an ImageView to move in a semi-circle (Android) I am trying to learn a little bit about animations and so decided to get an ImageView to go across the screen from left to right, which I achieved with:
TranslateAnimation mAnimation = new TranslateAnimation(0, 180, 0, 0);
            mAnimation.setDuration(1000);
            mAnimation.setFillAfter(true);
            mAnimation.setRepeatCount(-1);
            mAnimation.setRepeatMode(Animation.REVERSE);
            myImageView.setAnimation(mAnimation);

So, I decided to take on a new challenge. Once the image has gone from left to right, I wanted to try and get the image to return to the start position by arching back from right to left to its starting position (basically, a complete semi-circle). However, once the image has reached the end of the x-axis at position 180, I get stuck.
After reading about different methods for animation, I opted to try out ValueAnimator:
ValueAnimator animator = ValueAnimator.ofFloat(0, 1); // values from 0 to 1
            animator.setDuration(1000); // 1 seconds duration from start to end position
            animator.setRepeatCount(-1);
            animator.setRepeatMode(ValueAnimator.REVERSE);
            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener()
            {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {

                    float value = (Float) (animation.getAnimatedValue());

                    myImageView.setTranslationX((float)(180.0 * Math.sin(value*Math.PI)));
                    myImageView.setTranslationY((float)(80.0 * Math.cos(value*Math.PI)));

                }
            });
            animator.addListener(new AnimatorListenerAdapter()
            {
                @Override
                public void onAnimationEnd(Animator animation)
                {
                    // done
                }
            });
            animator.start();

However, I am unable to get the positioning correct. I do have a semi-circle (good), however, it is moving the image like a backward C rather than a straight line left to right and then arching back to its starting position (bad).
I am not sure if I should be using AnimatorSet to link the left to right movement and the arching back movement together to create one whole animation...
Can anyone give me some guidance on how to achieve what I have described?


text:
Q: Weird Value Oracle Insert Request So, my code got oracle error this.
ORA-01461: can bind a LONG value only for insert into a LONG column
But there is no long variable in the request.
After debugging, found out that one weird string value.
, lor
This causing of the problem, is there any way to parse that string back to normal?


text:
Q: Second form is not loading properly on Visual Builder? in the first form I have a text box where you can add your name, and then when you click Next window, the second form will pop up saying My name is : Your name . This is great, but how would I be able to change the name of the second form known as OtherForm to my name aswell so that when the second form pops up, on the top left corner my name would appear instead of OtherForm? Here is the code for the first and second form so far.
Main Form code:
Public Class MainForm

Private Sub MainForm_Load(sender As Object, e As EventArgs) Handles
MyBase.Load

End Sub

Public Sub Label1_Click(sender As Object, e As EventArgs) Handles
WindowName.TextChanged

End Sub

Public Sub WindowName_TextChanged(sender As Object, e As EventArgs)

End Sub

Public Sub OffButton_Click(sender As Object, e As EventArgs) Handles
OffButton.Click
    Me.Close()

End Sub

Public Sub NextButton_Click(sender As Object, e As EventArgs) Handles
NextButton.Click
    OtherForm.NameLabel.Text = WindowName.Text
    OtherForm.Show()
End Sub
End Class

Second form known as OtherForm
Public Class OtherForm

Public Sub CloseButton_Click(sender As Object, e As EventArgs) Handles
CloseButton.Click
    Me.Close()
End Sub

Public Sub OtherForm_Load(sender As Object, e As EventArgs) Handles
MyBase.Load

End Sub

Public Sub NameLabel_Click(sender As Object, e As EventArgs) Handles
NameLabel.Click

End Sub

Private Sub Label1_Click(sender As Object, e As EventArgs) Handles
Label1.Click

End Sub
End Class

A: Try
OtherForm.Text = WindowName.Text

to set the title of the form.  Or you can set the text to whatever you would like.  I'm not sure if you mean "my name" or the name you entered.
If you do mean "my name" then you can enter that in the form property for "Text" instead of in code as well.


text:
Q: problem in uninstall chrome. i got error so that i could open ubuntu software center too sir i installed chrome by typing following commands:
sudo add-apt-repository ppa:a-v-shkop/chromium-dev
sudo apt-get update
sudo apt-get install chromium-browser

then i got big error i can't uninstall chrome. i got one error when i open ubuntu software center and it is not at all opening and it is saying ubuntu experience internal error.the following is the type of error is showing in pop up menu.
Could not initialize the package information

An unresolvable problem occurred while initializing the package information.

Please report this bug against the 'update-manager' package and include the following error message:

'E:Type 'ain' is not known on line 3 in source list /etc/apt/sources.list.d/a-v-shkop-chromium-precise.list'

i tried to uninstall chrome using purge command in termaial...nothing is working. in terminal:
sudo apt-get purge google-chrome-stable
[sudo] password for dhinesh:
Reading package lists...
Done Building dependency tree
Reading state information...
Done E: Unable to locate package google-chrome-stable

A: The PPA you added is not intended for users, only for developers.
You don't need the PPA to install chromium-browser, it is in the standard repository.
You must remove the PPA. Normally this is done through synaptic packet manager but I assume you don't have that installed and you can't install anything at the moment.
in that case you can remove it manually like this:
sudo rm /etc/apt/sources.list.d/a-v-shkop-chromium-dev-precise.list

then clean the packet cache and run the update again:
sudo apt-get clean
sudo apt-get update

then you might like to have the normal chromium-browser from the standard repository:
sudo apt-get install chromium browser

If you encounter any errors, please add them to your question


text:
Q: Android permissions to view data I recently got interested in anything android.
I figured if you install apps on your android device, they have a lot of rights.
This is pretty scary, at least i think.
A program like whatsapp is able to view and store and sent pretty much all of the device its information.
However my questions is, how can whatsapp view and copy and edit contacts, if the whole contacts thing ( stored in /data ) is root ? If i try to access the folders from my computer it gives me an error, that i do not have permission to view it.
So what in the whatsapp apk is used to extract the contact information from a root folder ?
I am very thankful for help !
Greetings,

A:
So what in the whatsapp apk is used to extract the contact information from a root folder ?

Most likely, they use the ContactsContract API to read contact data. They hold the READ_CONTACTS permission, which allows them to use this API. They also hold the WRITE_CONTACTS permission, which allows them to modify contacts.

A: On Android, there are public APIs that allow you to read Contact data. These require permissions.
A list of permissions can be found here:
Android Manifest Permissions
The permissions I imagine you are referring to are READ_CONTACTS and WRITE_CONTACTS. The actual data is accessed by a Content Provider. Content providers allow you to access data on the phone such as contacts, music, photos etc.
In WhatsApp's case, they will not be accessing any root folders, but using the Content Provider API which exposes the user's contacts.


text:
Q: MCU on custom PCB suddenly stop working After nearly two weeks of testing, STM32L MCU suddenly stopped working.
It is not recognized by ST-LINKv2 debugger (tried connecting using stlink under Linux and STM's ST-LINK utility under Windows).
MCU power is OK, ground and SWD pins are connected.

*

*I did not do anything special with device when it suddenly stopped working

*software does not redefine SWD pins

*device is powered from battery, so do not expect that MCU was burned by some voltage spike

*MCU was bought from local reseller that seems to have original parts (but not sure)

*although present on schematic, quartz crystal and capacitors are not soldered. Device is driven from internal clock (HSI).

It seems that MCU is dead. The only explanation that come to my mind is EMI.
Please help to understand what could be the source of problem.

A: Assuming batt/MCP73831 is 4.2v, the TPS7361's R9 and R4 produce an output of 3.0v so this is Vdd. If PWR_OFF were an output (either state) while S1 were closed, even for an instant - that is a direct path back to the battery (4.2v, 1.2v more than Vdd.)
Edit: The STM32L152RBT6 does have many 5v-tolerable inputs (and no \$V_{DDIO}\$ pin to limit this), of which PB12 (pin 33) is one. So what must have happened is, the button was pressed while the micro was asserting an output on this pin, then more current than was allowable flowed into the device (from a pin higher than Vdd.)
Section 6.2, table 11, Absolute maximum current ratings, shows \$I_{INJ(PIN)}\$ is limited to -5/+0mA. My guess is that pressing the button while the output was asserted happened, and the chip failed from an over-current condition.
I'd use a mosfet or BJT to pull EN low instead of pulling the line directly from an output. As @Chris says in the comments, it may be possible to cut a trace and splice in an alteration, but this part of the circuit needs some more thought.


text:
Q: SQL Server Client Crash when viewing execution plan I need to optimize a legacy stored procedure, with over 2.000 lines, but I'm unable to view the execution plan, when I try to do so, the client crashes.
The procedure executes over 200 queries during the execution, if I mark the option to generate the actual execution plan, but I don't click on the execution plan tab, it finishes without errors, but when I try to see the execution plan itself, the client crashes, it doesn't display any errors, simply closes and opens again, the system messages also do not display any error message.
Is there another way to view the execution plan, or any other option, except rewrite the legacy code, that I am not familiar with? thank you.