text:
Q: codenvy.com - eclipse che - create a custom stack create a custom stack
i'm trying to run neo4j on codenvy, in order to achieve that i did  the following
1) created a new stack, adding a new machine with this configuration:
new-machine:
 image: neo4j/3.0
 mem_limit: 1073741824

2) create a new workspace with the runtime just created
3) imported a blank project into the workspace (just to import something)
making the workspace running no errors are displayed, so the questions are:

*

*is neo4j already running or i have to issue some command against that machine?

*what is the url to access to the neo4j console? knowing the port is 7474

A: According to the Dockerfile (see last line: CMD ["neo4j"]) the neo4j should be running after loading the image. The IP should be the one of your virtual machine, in my case:
macbook-pro:~ username$ docker-machine ls
NAME      ACTIVE   DRIVER       STATE     URL                         SWARM   DOCKER     ERRORS
default   -        virtualbox   Running   tcp://192.168.99.100:2376           v18.09.0

or simply run:
macbook-pro:~ username$ docker-machine ip
192.168.99.100


text:
Q: Why is the webcolors library giving me an atribute error when the function is specified in the documentation I am trying to create a color mixer-calculator type thing that will tell you the color name based on the RGB code you input. As in the webcolor database there are no 256^3 color names (niether in real life, I think) I included aproximations to the colors that didn't have names to the nearest similar color. The problem pops out when using the
webcolors.cc3_hex_to_name

It raises an atribute error:
AttributeError: module 'webcolors' has no attribute 'css3_hex_to_name'

This is very strange as the webcolor's documentation clearly includes this atribute:
Webcolors documentation extract
Here's the whole code for reference:
import webcolors
webcolors.css3_hex_to_name
def closest_colour(requested_colour):
    min_colours = {}
    for key, name in webcolors.css3_hex_to_names.items(): #Error line
        r_c, g_c, b_c = webcolors.hex_to_rgb(key)
        rd = (r_c - requested_colour[0]) ** 2
        gd = (g_c - requested_colour[1]) ** 2
        bd = (b_c - requested_colour[2]) ** 2
        min_colours[(rd + gd + bd)] = name
    return min_colours[min(min_colours.keys())]

def get_colour_name(requested_colour):
    try:
        closest_name = actual_name = webcolors.rgb_to_name(requested_colour)
    except ValueError:
        closest_name = closest_colour(requested_colour)
        actual_name = None
    return actual_name, closest_name

requested_colour = (119, 172, 152)
actual_name, closest_name = get_colour_name(requested_colour)

print ("Actual colour name:", actual_name, ", closest colour name:", closest_name)

A: try this webcolors.CSS3_HEX_TO_NAMES

redpajama_set_name: RedPajamaStackExchange


text:
Q: Docker - how to mount folder inside running container as volume to other running container? As the question says, is it possible, once a container is already running, to create a mount inside it as a volume or otherwise, and to make that available to another container instance?

A: Volumes that need to be mounted into other containers must be defined when you create the container image. i.e. in your docker file. Once a volume is defined in the image every time a container is created from the image the volume is created. You can then tell docker to mount the same volume into another container using the --volumes-from switch. You cannot attach or modify volumes while containers are running.
In fact even if you stop containers you cannot add volumes without deleting and recreating the container using the volumes-from switch. This seems very stringent but docker containers are meant to be stateless hence this should not be a problem if your containers are defined well.


text:
Q: Bigcommerce stencil product grid or card i need to get the grid of few products or card.html for a single product. I tried to use below two codes, but grid is coming blank and card doesn't getting product details inside it. Can you please help me here?
window.stencilUtils.api.product.getById(177, { template: 'products/card' }, (err, response) => {
  console.log(response);
});

window.stencilUtils.api.product.getById(177, { template: 'products/grid' }, (err, response) => {
  console.log(response);
});

Thank you.

A: This could be approached with the {{#each}} Handlebars Helper as seen in the grid.html template: https://github.com/bigcommerce/cornerstone/blob/master/templates/components/products/grid.html
Consider the context of the grid.html template, it is called through product-listing.html which could have a different context than where this script is being called. The Product Card Model can be found on the Dev Center here as well: https://developer.bigcommerce.com/stencil-docs/reference-docs/common-objects#common-product-card-model


text:
Q: PowerBI REST API - Failed to create a new datasource on the specified gateway I'm following this page in order to create a new PowerBI datasource.
And used this kind of body for the POST request:
{
  "connectionDetails": "{\"server\":\"aaa\",\"database\":\"bbb\"}",
  "credentialDetails": {
    "credentialType": "Basic",
    "credentials": "{\"credentialData\":[{\"name\":\"username\", \"value\":\"ccc\"},{\"name\":\"password\", \"value\":\"XoZT6aM1r0puO\"}]}",
    "encryptedConnection": "Encrypted",
    "encryptionAlgorithm": "RSA-OAEP",
    "privacyLevel": "None",
    "useEndUserOAuth2Credentials": "False"
  },
  "datasourceName": "ddd",
  "dataSourceType": "Sql"
}

But getting the below error for the POST request:
{
  "error": {
    "code": "DM_GWPipeline_UnknownError",
    "pbi.error": {
      "code": "DM_GWPipeline_UnknownError",
      "parameters": {},
      "details": [
        {
          "code": "DM_ErrorDetailNameCode_UnderlyingErrorMessage",
          "detail": {
            "type": 1,
            "value": "The input is not a valid Base-64 string as it contains a non-base 64 character, more than two padding characters, or an illegal character among the padding characters. "
          }
        },
        {
          "code": "DM_ErrorDetailNameCode_UnderlyingHResult",
          "detail": {
            "type": 1,
            "value": "-2146233033"
          }
        }
      ]
    }
  }
}

Any advice would be appreciated!
Thanks in advance.
BTW, as an alternative I would be happy to know if there is a powershell code that was found as working.


text:
Q: Gaps between adjacent light rays from a light source I can not seem to grasp light rays FILLING space like air and liquid in an enclosure.
Two rays adjacent to each other coming from Sun, - do they not diverge as they go into space? If so is there not dark space gap between them, constantly increasing? How come when the sun is up in the sky, we do not perceive these dark spaces as night, as we travel around the sun while facing it, like an interference pattern? I hope my Q is clear.

A: The photon density for 1370 Watts per square meter is high enough that there are no gaps. If we move far enough away, the the photons are few and far between--except one must account for the Hanbury-Brown Twiss effect--which would manifest as "gap filling" correlations. Weird.


text:
Q: $f,g$ are Riemann integrable over $[a,b]$ $h:[a,b]\rightarrow \mathbb{R}$, $h(x)=\max(f(x),g(x))$ Prove that $h(x)$ is integrable over [a,b]$ The problem states:
Let $f(x),g(x)$ be Riemann integrable over $[a,b]$.
Define $h:[a,b]\rightarrow\mathbb{R}$ as:
$$h(x)=\max(f(x),g(x))$$
Prove that $h(x)$ is Riemann integrable over [a,b]
-I know that because $f$ and $g$ are integrable, then:
$\forall \epsilon>0$, there exists a partition P so that: $U(f,P)-L(f,P)<\epsilon$
$\forall \epsilon\prime>0$, there exists a partition P$\prime$ so that: $U(g,P\prime)-L(g,P\prime)<\epsilon\prime$
I also know that: $maxf(x)\le\sup f(x)$ and $maxg(x)\le\sup g(x)$ where both functions are defined.
Any hints on how should Iaproach this proof? Thanks

A: You can use the fact that for any two $a,b \in \mathbb R$, we have the identity
$$(*)\quad \max(a,b) = \frac{a+b+|a-b|}{2}  $$
to say that
$$ \max(f(x),g(x)) = \frac{f(x) + g(x) + |f(x)-g(x)|}{2}. $$
The absolute value, the sum, and the difference, and the multiplication by a constant of Riemann integrable functions are all Riemann integrable, hence the max is also integrable.
Proof of $(*)$ :
If $a\ge b$, we have that |a-b| = a-b and the identity is $\frac{a+b + a - b}{2} = a $, which is the max. If $a< b$, then $|a-b| = b-a$ and the computation is similar.


text:
Q: How to cache data publicly from firebase function? I'm a little bit lost on how firebase functions work with authentication,
Suppose I have a function that pulls 100 documents and sets the cache header for 24 hours.
res.set('Cache-Control', 'public, max-age=0, s-maxage=86400' // 24 * 60 * 60
By default, does that apply to all users or is it cached per user? There's some instances where the 100 documents are unique to the user - while other functions where the 100 documents are available to any user that's authenticated.
I see in the docs that you can set a __session which implies it's for individual users data, however there isn't much documentation for how to set that (or where). Is it set by default?
My goal is to have a function that requires the user be authenticated, then return 100 documents from a non-user specific collection - aka not have to read 100 documents per user. However, I don't think thats feasible because it would need to check if each user is authorized (not cacheable). So is there a way to just make a publicly available cache?
Any light that can be shared on this is greatly appreciated!

A: The Cache-Control header is used to instruct a user's browser and any CDN edge server on how to cache the request.
For requests requiring authentication, making use of the CDN is not really possible for this as you should be using Cache-Control: private for these responses (the default for Cloud Functions).
While you could check that your users are authenticated and then redirect them to a publically cached resource (like https://example.com/api/docs?sig=<somesignature>), this URL would still be accessible if someone got hold of that URL/cached data.
Arguably the best approach would be to store your "cached" responses in a single Cloud Firestore document (if it is less than 1MB in size and is JSON-compatible) or store it in Cloud Storage.
The code included below is an example of how you could do this with a Cloud Firestore cache. I've used posts where the authenticated user is the author as an example, but for this specific use case, you would be better off using the Firebase SDK to make such a query (realtime updates, finer control, query API). A similar approach could be applied for "all user" resources.
If attempting to cache HTML or some other not JSON friendly format, I would recommend changing the caching layer to Cloud Storage. Instead of storing the post's data in the cache entry, store the path and bucket to the cached file in storage (like below). Then if it hasn't expired, get a stream of that file from storage and pipe it through to the client.
{
  data: {
    fullPath: `/_serverCache/apiCache/${uid}/posts.html`,
    bucket: "myBucket"
  },
  /* ... */
}

Common Example Code
import functions from "firebase-functions";
import { HttpsError } from "firebase-functions/lib/providers/https";
import admin from "firebase-admin";
import hash from "object-hash";

admin.initializeApp();

interface AttachmentData {
  /** May contain a URL to the resource */
  url?: string;
  /** May contain Base64 encoded data of resource */
  data?: string;
  /** Type of this resource */
  type: "image" | "video" | "social" | "web";
}

interface PostData {
  author: string;
  title: string;
  content: string;
  attachments: Record<string, AttachmentData>;
  postId: string;
}

interface CacheEntry<T = admin.firestore.DocumentData> {
  /** Time data was cached, as a Cloud Firestore Timestamp object */
  cachedAt: admin.firestore.Timestamp;
  /** Time data was cached, as a Cloud Firestore Timestamp object */
  expiresAt: admin.firestore.Timestamp;
  /** The ETag signature of the cached resource */
  eTag: string;
  /** The cached resource */
  data: T;
}

/**
 * Returns posts authored by this user as an array, from Firestore
 */
async function getLivePostsForAuthor(uid: string) {
  // fetch the data
  const posts = await admin.firestore()
      .collection('posts')
      .where('author', '==', uid)
      .limit(100)
      .get();

  // flatten the results into an array, including the post's document ID in the data
  const results: PostData[] = [];
  posts.forEach((postDoc) => {
    results.push({ postId: postDoc.id, ...postDoc.data() } as PostData);
  });
  return results;
}

/**
 * Returns posts authored by this user as an array, caching the result from Firestore
 */
async function getCachedPostsForAuthor(uid: string) {
  // Get the reference to the data's location
  const cachedPostsRef = admin.firestore()
      .doc(`_server/apiCache/${uid}/posts`) as admin.firestore.DocumentReference<CacheEntry<PostData[]>>;

  // Get the cache entry's data
  const cachedPostsSnapshot = await cachedPostsRef.get();

  if (cachedPostsSnapshot.exists) {
    // get the expiresAt property on it's own
    // this allows us to skip processing the entire document until needed
    const expiresAt = cachedPostsSnapshot.get("expiresAt") as CacheEntry["expiresAt"] | undefined;
    if (expiresAt !== undefined && expiresAt.toMillis() > Date.now() - 60000) {
      // return the entire cache entry as-is
      return cachedPostsSnapshot.data()!;
    }
  }

  // if here, the cache entry doesn't exist or has expired

  // get the live results from Firestore
  const results = await getLivePostsForAuthor(uid);

  // etag, cachedAt and expiresAt are used for the HTTP cache-related headers
  // only expiresAt is used when determining expiry

  const cacheEntry: CacheEntry<PostData[]> = {
    data: results,
    eTag: hash(results),
    cachedAt: admin.firestore.Timestamp.now(),
    // set expiry as 1 day from now
    expiresAt: admin.firestore.Timestamp.fromMillis(Date.now() + 86400000),
  };

  // save the cached data and it's metadata for future calls
  await cachedPostsRef.set(cacheEntry);

  // return the cached data
  return cacheEntry;
}

HTTPS Request Function
This is the request type you would use for serving Cloud Functions behind Firebase Hosting. Unfortunately the implementation details aren't as straightforward as using a Callable Function (see below) but is provided as an official project sample. You will need to insert validateFirebaseIdToken() from that example for this code to work.
import express from "express";
import cookieParserLib from "cookie-parser";
import corsLib from "cors";

interface AuthenticatedRequest extends express.Request {
  user: admin.auth.DecodedIdToken
}

const cookieParser = cookieParserLib();
const cors = corsLib({origin: true});
const app = express();

// insert from https://github.com/firebase/functions-samples/blob/2531d6d1bd6b16927acbe3ec54d40369ce7488a6/authorized-https-endpoint/functions/index.js#L26-L69
const validateFirebaseIdToken = /* ... */

app.use(cors);
app.use(cookieParser);
app.use(validateFirebaseIdToken);

app.get('/', async (req, res) => {
  // if here, user has already been validated, decoded and attached as req.user
  const user = (req as AuthenticatedRequest).user;

  try {
    const cacheEntry = await getCachedPostsForAuthor(user.uid);

    // set caching headers
    res
      .header("Cache-Control", "private")
      .header("ETag", cacheEntry.eTag)
      .header("Expires", cacheEntry.expiresAt.toDate().toUTCString());

    if (req.header("If-None-Match") === cacheEntry.eTag) {
      // cached data is the same, just return empty 304 response
      res.status(304).send();
    } else {
      // send the data back to the client as JSON
      res.json(cacheEntry.data);
    }
  } catch (err) {
    if (err instanceof HttpsError) {
      throw err;
    } else {
      throw new HttpsError("unknown", err && err.message, err);
    }
  }
});

export const getMyPosts = functions.https.onRequest(app);

Callable HTTPS Function
If you are making use of the client SDKs, you can also request the cached data using Callable Functions.
This allows you to export the function like this:
export const getMyPosts = functions.https.onCall(async (data, context) => {
  if (!context.auth) {
    throw new functions.https.HttpsError(
      'failed-precondition',
      'The function must be called while authenticated.'
    );
  }

  try {
    const cacheEntry = await getCachedPostsForAuthor(context.auth.uid);
    return cacheEntry.data;
  } catch (err) {
    if (err instanceof HttpsError) {
      throw err;
    } else {
      throw new HttpsError("unknown", err && err.message, err);
    }
  }
});

and call it from the client using:
const getMyPosts = firebase.functions().httpsCallable('getMyPosts');
getMyPosts()
  .then((postsArray) => {
    // do something
  })
  .catch((error) => {
    // handle errors
  })


text:
Q: Implementing debugDescription for DebugPrintable in Swift I'm trying to write my own debug description for a Swift class. My code looks like the following:
class SceneData : DebugPrintable {
    var fileName : String
    var scene : Scene
    var uuid : String

    var debugDescription: String = {
        return String(format: "<SceneData: {\n  fileName: %s\n  scene: %@\n}>", fileName, scene)
    }
    /*
     * More methods, etc.
     */
}

I'm getting the error 'SceneData.Type' does not have a member named 'fileName', but SceneData very clearly does have a variable fileName declared above. I'm also having similar issues when trying to use self within the string, and believe that this is related.
How can I make references to instance variables/self in the debugDescription string properly? I am pretty sure it is possible, both because other people have said it is, and because it seems ridiculous to have an object's debug description not have any actual specifics about itself. What am I doing wrong here?

A: remove =, because it should be a computed property.
var debugDescription: String{
        return String(format: "<SceneData: {\n  fileName: %s\n  scene: %@\n}>", fileName, scene)
}


text:
Q: Raw string encoding from input() I'm trying to scan a variable directory, said variable is defined by an input(), yet the program throws out this issue:
(unicode error) 'unicodeescape' codec can't decode bytes in position 320-321: truncated \UXXXXXXXX escape
Current code: Not Working
import os
import time

print("Enter directory name.\nDirectory name example:\nC:\Users\example\Documents")

dirname = input()

with os.scandir(dirname) as dir_entries:
    for entry in dir_entries:
        info = entry.stat()
        file_name = os.path.basename(entry)

        my_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(info.st_ctime))
        rawmb = (info.st_size/(1024*1024))
        truncated = round(rawmb, 3)

        print(file_name)
        print(my_time)
        print(truncated,"MB")
        print('===========================')

I considered using \\ or / instead of \ during the input, but that makes copying the directory from the file explorer impossible.
I have no idea how to include an r in front of the input() string.
.decode,.encode didn't seem to work for me either, but I most likely just used them wrong.

Edit #1
Tried the solution from J_H

Do this after input(): for ch in dirname: print(ch, ord(ch))

Result:
Same error.


text:
Q: Component gets re-initialized on props update I have a component inside formik -based step wizard.
I make use of useField, useEffect and useState hooks as below:
const [counts, countsMeta, countsHelpers] = useField('counts');
const [visible, setVisible] = useState(false);
useEffect(() => {
  countsHelpers.setValue(
    Array(event.book && event.book.length ? event.book.length : 0).fill(0)
  );
  // eslint-disable-next-line
}, [event.book]);

I understand that my useEffect should only be called once, no matter what as long as event.book never changes.
I also have a way to apply coupons as below:

          <FontAwesomeIcon
            icon={faPlusSquare}
            onClick={() => setVisible(!visible)}
          />{' '}
          coupon code
          {visible && (

              <input
                id='coupon'
                type='text'
                value={values.coupon || ''}
                onChange={onChange}
                placeholder='Coupon code'
                className={errors.coupon ? styles.error : ''}
              />

 loadPromo(values.coupon)}
              >
                Apply

          )}

For some reason I cannot pinpoint, when I call loadPromo() my component re-initializes. Once it happens, state and fields are reset e.g. visible is again set to false and counts array reinitialized with zeros. After that, everything is working fine.
What am I missing?


text:
Q: Android- Chat application - Convert editbox emoticons in string ;) format to save in database I have developed a chat application in android and I want to add the Emoctions feature with my application. Till now i have implement this feature with gridview, in which when i enter emoji with text it appears in editText. but what i want to save this in database with :) formate. Hv created mapping of image & :) string But cant get how to save by changing it.
For edittext i hv used following code:
    ImageGetter imageGetter = new ImageGetter() {

        @Override
        public Drawable getDrawable(String source) {
            Drawable d = getResources().getDrawable(emojis.images[index]);
            d.setBounds(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
            return d;
        }
    };
    cs = Html.fromHtml(
            "<img src ='"
                    + getResources().getDrawable(emojis.images[index])
                    + "'/>", imageGetter, null);
    writeboard.setText(cs);

Plz help me to perform database saving and showing it in textview.
Thanks.

A: I got answser by spannable method.
With in spanable method i am comparing string with pattern so whenever that pattern matches in text, it will show emoji of relavent pattern.
I called this method when ever i selected emoji from gridview, on msg recieved, and ontextchanged so whenever it found pattern it will changed to emoji. so like this  it is saving data in text formate of :) and showing emoji as icon.
Hope this will be helpful.


text:
Q: Release/Build/Branching Management with Git (Version Control) I've ran into a common problem that I don't know how to properly solve. I do have a dev branch in which I've merging all of the branches (feature/hotfix) that are done, but suddenly, they want to release a specific feature or just to release the hotfixes only. How can I properly/orgnanize merge dev to master without including the feature/hotfix that they don't want if I've already merge it to the dev?
One solution that I've been thinking of is branching out from dev then exclude all the things they don't want, then release it on production, but I will not merge it to master. Then after they've accepted all of the features or hotfixes on the dev, that's only the time I will merge to master, and I will just simply ignore/delete the branch out from dev (which is the branch that have excluded the feature they don't want) that I've made.
Second Solution that I've been thinking is releasing an apk per feature or hotfix, but I don't think the testers will like to hold many apks on their phone with specific feature each. But with that, I can surely merge feature or hotfix that is accepted to dev because they mark it to be included on the next release.
Any other solutions or suggestions on how I manage branching?

A: Solution 1 is more reasonable.
Since the dev branch already contains merged features and hotfixes, you should exclude some features/hotfixes which are not required for release from dev branch (or branch created from dev).
But one thing for reminder, since you treat the branch from dev as production branch (instead of master branch), please make sure changes from master branch are included in the branch from dev.
Besides, .apk files are output files from your source code, it's unnecessary to manage the .apk files in your git repo.
And you can find more files which need to be ignored in this .gitignore file.


text:
Q: CRONTAB - Summer/Winder Time-Change Since there can be problems with the time change from summer/winter or winter/summer, I wanted to ask how I could solve the problem within the bash script-2?
I think in the winter time it should not come normally to problems since CRON acts here smartly and does not execute CRONS twice, nevertheless I would be grateful here for tips how I could configure the best in both time changes.
SUMMER-TIME-CHANGE-GERMANY (RUN AT SAME TIME)
2h - CRONTAB -> Bash-Script 1
3h - CRONTAB -> Bash-Script 2

WINTER-TIME-CHANGE-GERMANY (SHOULD NOT BE A PROBLEM?!)
2h - CRONTAB -> Bash-Script 1
3h - CRONTAB -> Bash-Script 2

A: One approach:
Have the system clock or at least cron run at UTC. UTC has no daylight savings time and you won't have any issues.
(And like many utilities and tools allow : only convert from UTC to the time zone most relevant to a person in the presentation layer.)
A second consideration:
Cron is a time based scheduler. If you have real job dependencies you can't really rely on cron to ensure they are met. If batch job B must always start after job A ; simply  use  a single batch job (with some more error checking and handling )
#!/bin/sh
/do/job-A
/do/job-B


text:
Q: Two members with same name in c# I am writing a Windows Store App (Win Phone 8.1).
I have a to send request to server and it gives response:
C#:
public class Request
{
    public PWSESSIONRS PWSESSIONRS { get; set; }
}

public class Response
{
    public List<PWSESSIONR> PWSESSIONRS { get; set; }
}

public class PWSESSIONRS
{
    public PWPROCESSRS PWPROCESSRS { get; set; }
}

public class PWPROCESSRS
{
    public PWERROR PWERROR { get; set; }

    public PWHEADER PWHEADER { get; set; }
    public PWDATA PWDATA { get; set; }
}

public class PWDATA
{
    public GETBIKEDETAIL GETBIKEDETAIL { get; set; }
    public MOBAUTH MOBAUTH { get; set; }

}

public class MOBAUTH
{
    //Request:
    public List<Row> Row { get; set; }

    //Response:
    public Row Row { get; set; }

}

It shows Error:

The MOBAUTH already contains a definition for Row

Now, If I do it like this:
public class MOBAUTH
{
    //Request:
    [JsonProperty("Row")]
    public List<Row> Row { get; set; }

    //Respnse:
    [JsonProperty("Row")]
    public Row Row_ { get; set; }

}

It shows runtime Error:

An exception of type 'Newtonsoft.Json.JsonSerializationException'
  occurred in Newtonsoft.Json.DLL but was not handled in user code
  Additional information: A member with the name 'Row' already exists on
  'MyApp.Model.Request.MOBAUTH'. Use the JsonPropertyAttribute to
  specify another name.

JSON REQUEST:
{"PWSESSIONRS":{"PWPROCESSRS":{"PWERROR":null,"PWHEADER":{"DEVICE_LONGITUDE":"77.044510","PROCESS_ID":"","LOGIN_ID":"FiZqnXB4y0u4WNTYG2UXxw==","USER_ID":"FiZqnXB4y0u4WNTYG2UXxw==","IMEI_NO":"64C267E1-545D-4A2B-B726-60F332B18F44","DEVICE_MODEL":"","VERSION_ID":"1.0","PW_SESSION_ID":"3tyEwspAMHj9FvWQzSecuq/7DQMDw0MalYiPIXWaFvg=","DEVICE_LATITUDE":"28.412745","INSTALLATION_ID":"8QO8FLBU1GGEUCIHI44R+A/7DQMDW0MALYIPIXWAFVG=~HCA~614","SESSION_EXPIRE_TIME":"","ORG_ID":"HCA","APP_ID":"HCA","PW_VERSION":"","LOCATION":"","USER_SESSION_ID":"FFv4JAm8bpHauIahnRgs9ZW2ypH7NE41Dz9OZBIXJWnBiR/VRj3yaAmRx+SeZtyc","OS_VERSION":"","SERVER_TIMESTAMP":"","DEVICE_MAKE":"","OUT_PROCESS_ID":"MOBAUTH","SIM_ID":"","PW_CLIENT_VERSION":"3.1","PASSWORD":"FiZqnXB4y0u4WNTYG2UXxw==","DEVICE_TIMESTAMP":"2016-07-23 16:54:09","IS_AUTH":"","LAC":"","MCC":"","MNC":"","CID":"","LAST_TRANSACTION_ID":"","IN_PROCESS_ID":null},"PWDATA":{"GETBIKEDETAIL":null,"MOBAUTH":{"Row":[{"x_VIN":null,"x_phone_no":null,"x_reg_no":null,"x_mobile_no":"9988887777","MessageSource":null,"DetailMessage":null,"DataElements":null,"Message":null,"MsgID":null,"RefID":null,"MessageType":null}]}}}}}

JSON RESPONSE:
{
  "PWSESSIONRS": [
    {
      "PWPROCESSRS": {
        "PWERROR": {
          "MOBAUTH": {
            "Row": {
              "MessageSource": "PLATWARE",
              "DetailMessage": "JSONObject[\"x_reg_no\"] not a string.",
              "DataElements": "",
              "Message": "Please pass valid JSON Data for Process.",
              "MsgID": "plat029",
              "RefID": "MOBAUTH",
              "MessageType": "Error"
            }
          }
        },
        "PWHEADER": {
          "DEVICE_MODEL": "",
          "IMEI_NO": "64C267E1-545D-4A2B-B726-60F332B18F44",
          "VERSION_ID": "1.0",
          "DEVICE_LATITUDE": "28.412745",
          "INSTALLATION_ID": "8QO8FLBU1GGEUCIHI44R+A/7DQMDW0MALYIPIXWAFVG=~HCA~614",
          "APP_ID": "HCA",
          "IS_AUTH": "Y",
          "PW_VERSION": "",
          "OS_VERSION": "",
          "DEVICE_MAKE": "",
          "OUT_PROCESS_ID": "MOBAUTH",
          "SIM_ID": "",
          "PASSWORD": "",
          "DEVICE_LONGITUDE": "77.044510",
          "LOGIN_ID": "FIZQNXB4Y0U4WNTYG2UXXW==",
          "USER_ID": "",
          "PW_SESSION_ID": "3TYEWSPAMHJ9FVWQZSECUQ/7DQMDW0MALYIPIXWAFVG=",
          "SESSION_EXPIRE_TIME": "",
          "ORG_ID": "HCA",
          "LOCATION": "",
          "IN_PROCESS_ID": "MOBAUTH",
          "USER_SESSION_ID": "FFV4JAM8BPHAUIAHNRGS9ZW2YPH7NE41DZ9OZBIXJWNBIR/VRJ3YAAMRX+SEZTYC",
          "SERVER_TIMESTAMP": "2016-07-23 18:46:01",
          "PW_CLIENT_VERSION": "3.1",
          "DEVICE_TIMESTAMP": "2016-07-23 16:54:09"
        },
        "PWDATA": {
          "MOBAUTH": ""
        }
      }
    }
  ]
}

A: I think you can just create two classes:
public class MOBAUTHRequest
{
    //Request:
    [JsonProperty("Row")]
    public List<Row> Row { get; set; }
}

public class MOBAUTHResponse
{
    //Request:
    [JsonProperty("Row")]
    public Row Row { get; set; }
}

And use the appropriate one for serialization - MOBAUTHRequest with request and MOBAUTHResponse with response. But as was stated in the comments, you should definitely consider changing the naming conventions to match C# and use JSON.NET attributes to "rename" for serialization.


text:
Q: Huntington Motors So i am doing a little advance exercise in VB.NET and i am a little froze to what i am doing. The task is "Each salesperson at Huntington Motors is assigned an ID number that consists of four characters. The first character is either the number 1 or the number 2. A 1 indicates that the salesperson sells new cars, and a 2 indicates that the salesperson sells used cars. The middle two characters are the salesperson's initials, and the last character is either the letter F or the letter P. The letter F indicates that the salesperson is a full-time employee. The letter P indicates that he or she is a part-time employee... The application should allow the sales manager to enter the ID and number of cars sold for as many salespeople as needed. The application should calculate and display the total number of cars sold by each of the following four categories of employees: full-time employees, part-time employees, employees selling new cars, and employees selling used cars."
this is my interface
This is my code so far:
Private Sub btnCalculate_Click(sender As Object, e As EventArgs) Handles
btnCalculate.Click
    'variables
    Dim strInput As String = ""
    Dim strOutput As String = ""
    Dim intFullTime As Integer = 0
    Dim intPartTime As Integer = 0
    Dim intNewCar As Integer = 0
    Dim intUseCar As Integer = 0
    Dim intNumSold As Integer
    strInput = txtId.Text
    ' changes the id number case to upper
    strInput = txtId.Text.ToUpper()
    ' sets the focus
      txtId.Focus()

   Integer.TryParse(txtNumberSold.Text, intNumSold)
    If strInput Like "[12][A-Z][A-Z][FP]" Then
        If strInput.Substring(0) = "1" Then
            intNewCar = intNewCar + intNumSold
            txtNewCar.Text = intNewCar.ToString
        Else
            intUseCar = intUseCar + intNumSold
            txtUsedCar.Text = intUseCar.ToString
        End If

        If strInput.Substring(3) = "F" Then
            intFullTime = intFullTime + intNumSold
            txtFullTime.Text = intFullTime.ToString
        Else
            intPartTime = intPartTime + intNumSold
            txtPartTime.Text = intPartTime.ToString
        End If
    End If

End Sub
End Class

Now my problem is, when is enter the ID with the first character as 1, the result does not print on the txt.NewCar.Text. Another question is, how do I calculate the numbers of car sold? Any tips would be greatly appreciated. I am not sure if I am doing it right.

A: For the first problem, you are using the Substring function incorrectly, by passing only one value, you are instructing it to give you the string from that point to the end. What you should be doing is:
strInput.Substring(0, 1) ' Get the first character

and
 strInput.Substring(3, 1) ' Get the fourth character

For the second problem, both intFullTime and intPartTime are local variables, they are created and initialised to 0 each time the button is clicked. You should move those two variables to be member variables of your class and then the totals should accumulate each time the button is clicked and the values parsed/processed.


text:
Q: Stopping the page refresh - not working with clear function This is code to display a spinner while image is loading and then show the image when it is done. Also, this page needs to be auto-refreshed every 5 seconds and the refreshing to be stopped at 11 seconds, ie refresh twice alltogether. But this doesn't work. The spinner code is in the css file. This does not work - keeps refreshing over and over - the timeout gets reset, tried using var to assign as well no joy. Any help appreciated highly.
<META HTTP-EQUIV="Cache-Control" CONTENT="max-age=0">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
<META http-equiv="expires" content="0">
<META HTTP-EQUIV="Expires" CONTENT="Tue, 01 Jan 1980 1:00:00 GMT">
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<html>
<head>
<link rel="stylesheet" href="/css/graph.css" type="text/css" media="screen, projection">
<script src="/javascript/jquery-latest.js" type="text/javascript">
</script>
<script type="text/javascript">
    var img = new Image(); img.height=600; img.width=2000;
    $(img).load(function () {
    $(this).css('display','none');
    $(this).animate({ opacity: 0.25 }).fadeIn("slow");
    $('#loader').append(this);
    $(this).animate({ opacity: 1 })
    }).error(function () {
    }).attr('src', 'xyz.png');
    var timer = function() { window.location.reload(true);};
        window["reload_timer"] = setTimeout(timer, 5000);
    var timer2 = function() {
        clearTimeout(window["reload_timer"]);
        clearTimeout(window["reload_timer2"]);};
        window["reload_timer2"] = setTimeout(timer2, 11000);
</script>
</head>
<body id = "page"><div id="loader" class="loading">
</div>
</body>
</html>

A: You could try reloading the page URL with a parameter attached to it.  Then you could read in the parameter with JavaScript and use that to know how many times the page has refreshed so you stop after 2 refreshes.
Otherwise the page is stateless - the same exact page will load as before, with no knowledge if it was already loaded or not.  By introducing this URL parameter you can track some sort of state.

A: When you reload the page, the page forgets it has already been reloaded, so in fact your code never reaches timer2


text:
Q: Can I do arithmetic with complex numbers in awk, and if so how? Does the AWK language support arithmetic for complex numbers? If yes, how do I define an imaginary unit?

A: You can always define complex numbers as an array of two numbers (the real and imaginary part). You'd need to define all the arithmetic operators by hand:
function cset(x, real, imaginary) {
  x["real"] = real
  x["imaginary"] = imaginary
}

function cadd(n1, n2, result) {
  result["real"] = n1["real"] + n2["real"]
  result["imaginary"] = n1["imaginary"] + n2["imaginary"]
}
function cmult(n1, n2, result) {
  result["real"] = n1["real"] * n2["real"] - n1["imaginary"] * n2["imaginary"]
  result["imaginary"] = n1["real"] * n2["imaginary"] + n2["real"] * n1["imaginary"]
}
function c2a(x, tmp) {
  if (x["real"]) {
    tmp = x["real"]
    if (x["imaginary"] > 0) tmp = tmp "+"
  }
  if (x["imaginary"]) {
    if (x["imaginary"] == -1) tmp = tmp "-i"
    else if (x["imaginary"] == 1) tmp = tmp "i"
    else tmp = tmp x["imaginary"] "i"
  }
  if (tmp == "") tmp = "0"
  return "(" tmp ")"
}

BEGIN {
  cset(i, 0, 1)
  cmult(i, i, i2)
  printf "%s * %s = %s\n", c2a(i), c2a(i), c2a(i2)
  cset(x, 1, 2)
  cset(y, 0, 4)
  cadd(x, y, xy)
  printf "%s + %s = %s\n", c2a(x), c2a(y), c2a(xy)
}

Which would output:
(i) * (i) = (-1)
(1+2i) + (4i) = (1+6i)

For languages with native support for complex numbers, see:

*

*python:
$ python -c 'print(1j*1j)'
(-1+0j)

*octave:
$ octave --eval 'i*i'
ans = -1

*calc (apcalc package on Debian):
$ calc '1i * 1i'
        -1

*R:
$ $ Rscript -e '1i*1i'
[1] -1+0i

A: No, awk does not currently support complex numbers natively.
I'll point to the POSIX specification for awk where it says:

Each expression shall have either a string value, a numeric value, or both. Except as stated for specific contexts, the value of an expression shall be implicitly converted to the type needed for the context in which it is used. A string value shall be converted to a numeric value either by the equivalent of the following calls to functions defined by the ISO C standard:
setlocale(LC_NUMERIC, "");
numeric_value = atof(string_value);
or by converting the initial portion of the string to type double representation ...

and

In case (a) the numeric value of the numeric string shall be the value that would be returned by the strtod() call ...

... and pointing out that atof and strtod both return a type of double.


text:
Q: How to show value inside the graph bars in amcharts I am using amcharts library for making graphs. i make column chart in which i will show value inside the graph. but some of the value are not properly adjust inside the bars in graphs. here is the screen shot of graph.

As you can see above some values are perfectly show inside the bars but some values are out of the bars.
Please help me to resolve this issue. Thanks. Here is the Graph code.
   <script>

          var chart8;

        var chartData8 = [

   <?php foreach ($result as $val) {
   ?>
            {

                "Division": '<?php echo $val['DIVISION_NAME'] ?>',
                 "Target": '<?php echo number_format($val['TARGET_QTY']/1000000,2) ?>',
                 "Actual": '<?php echo number_format($val['DISPATCH_QTY']/1000000, 2) ?>',
                 "Difference": '<?php echo number_format($val['BALANCE_QTY']/1000000, 2) ?>'

    },
<?php } ?>

        ];

        AmCharts.ready(function () {
            // SERIAL CHART
            chart8 = new AmCharts.AmSerialChart();
            chart8.dataProvider = chartData8;
            chart8.categoryField = "Division";
            chart8.startDuration = 1;
            chart8.depth3D = 50;
             chart8.angle = 45;
            chart8.marginRight = 80;
    chart8.plotAreaBorderColor = "#DADADA";
           // chart3.plotAreaBorderColor = "#DADADA";
            chart8.plotAreaBorderAlpha = 0;
    //chart8.responsive.enabled = true;
            // this single line makes the chart a bar chart
            //chart3.rotate = true;

            // AXES
            // Category
            var categoryAxis = chart8.categoryAxis;
            categoryAxis.gridPosition = "start";
            categoryAxis.labelRotation = 45; // this line makes category values to be rotated
            categoryAxis.gridAlpha = 0;
            categoryAxis.axisAlpha = 0;
    categoryAxis.color =  '';

            // Value
            var valueAxis = new AmCharts.ValueAxis();
            valueAxis.axisAlpha = 0;
            valueAxis.gridAlpha = 0.5;
            tickLength: 0;
    valueAxis.minimum = 0;
    valueAxis.maximum = 3.5;
            valueAxis.position = "bottom";
    valueAxis.color =  '';
            chart8.addValueAxis(valueAxis);

            // GRAPHS

            // second graph
            var graph9 = new AmCharts.AmGraph();
            graph9.type = "column";
            /*graph2.title = "PKR Value";*/
            graph9.valueField = "Target";
            graph9.balloonText = "Target:[[value]]";
            graph9.lineAlpha = 0;
            graph9.fillColors = ["#FFD244"];
            graph9.fillAlphas = 1;
    graph9.labelText =  '[[value]]';
    graph9.labelRotation = 90;
    graph9.labelPosition = 'right'; // change to inside
    graph9.color =  '#000';
    graph9.labelColorField =  '#FFFFFF';
            chart8.addGraph(graph9);
           // first graph

            var graph8 = new AmCharts.AmGraph();
            graph8.type = "column";

            graph8.valueField = "Actual";
            graph8.balloonText = "Actual:[[value]]";
            graph8.lineAlpha = 0;
            graph8.fillColors = ["#ee8989"];
            graph8.fillAlphas = 1;
    graph8.labelText =  '[[value]]';
    graph8.labelRotation = 90;
    graph8.labelPosition = 'right'; // change to inside
    graph8.marginRight = 10;
    graph8.color =  '#000';
    graph8.labelColorField =  '#FFFFFF';
            chart8.addGraph(graph8);

     var graph10 = new AmCharts.AmGraph();
            graph10.type = "column";
    graph10.valueField = "Difference";
            graph10.balloonText = "Difference:[[value]]";
            graph10.lineAlpha = 0;
            graph10.fillColors = ["#6acb5f"];
    graph10.labelText =  '[[value]]';
    graph10.labelRotation = 90;
    graph10.labelPosition = 'right';
     graph10.marginRight = 10;
            graph10.fillAlphas = 1;
    graph10.color =  '#000';
    graph10.labelColorField =  '#FFFFFF';
            chart8.addGraph(graph10);

            // LEGEND
            var legend = new AmCharts.AmLegend();
           // chart2.addLegend(legend);

            chart8.creditsPosition = "top-right";
            // WRITE
            chart8.write("dailyprod");
        });
    </script>

Please Help me to Solve this thing.


text:
Q: How to work out when WPF Storyboard has completed a Seek and has been drawn onscreen? I have a WPF storyboard that I want to step through frame-by-frame (for a variable framerate). At each frame my intention is to story a bitmap of the drawn storyboard state.
To this end I am trying to employ the following method:
this.CurrentStoryboard.Begin(this);
this.CurrentStoryboard.Pause(this);
//call a function (SEEKFUNC) which calls the following method for (increasing "frameNumber"s):
this.CurrentStoryboard.Seek(this, TimeSpan.FromSeconds(((double)frameNumber) / c_FrameRate), TimeSeekOrigin.BeginTime);
//wait for drawing to complete at point
SaveFrame(this.saveCanvas);
//call SEEKFUNC with frameNumber++

What I am struggling with however is finding out when the Storyboard has completed and been rendered. Can I assume that this will have been successfully completed by the second subsequent call to CompositionTarget.Rendering? Is there another, neater way?

A: Take a look at this: http://blogs.msdn.com/saveenr/archive/2008/09/22/wpf-xaml-saving-an-animation-as-an-avi-video-file.aspx
From that code it looks like calling UpdateLayout will finish seeking the animation.


text:
Q: Database design in lack of join-like query In MongoDB: how to use refs to documents in other collections I'm meddling with MongoDB to see how it would do in a real project as a platform for serious data storage, but I have a little problem with understanding the concept, or rather, how the data design should look like. I understand the idea of embedding objects, such as instead of what you would do in a RDBMS, like:
PEOPLE (Table):
id | Name
---------
 1 | John
 2 | Steve

PHONES (Table):
id | peopleId | phone
 1 |    1     | 555 66 77
 2 |    1     | 555 66 78
 3 |    2     | 555 11 22

In MongoDB, you would create two documents in a collection embedding the detail objects, like:
{
  name: "John",
  phones: [
    {phone: "555 66 77"},
    {phone: "555 66 78"}
  ]
},
{
  name: "Steve",
  phones: [
    {phone: "555 11 22"}
  ]
}

Now this approach is all good, and would work where detail objects are rather unique per master document (as in each phone belongs to one person only), but once you walk into the realm of (yes!) relations, where details are not strictly unique to their owners, you walk into trouble. Cosider a Book / Author relationship. There are many books, which may have more then one author, while many authors will have more than one book (a many-to-many relationship). If you embed author documents in books, you will have to duplicate authors data as many times as he has books. Same the other way around, if you embed books into authors, you will have duplicate data as many times as that book has authors, ie that same book will appear inside other author documents. Needless to say, this creates a hell of data consistancy issues.
{
  book: "A Nice Title",
  authors: [
    {name: "Jane", age: 30},
    {name: "Tom", age: 20}
  ]
},
{
  book: "Some Other Nice Title",
  authors: [
    {name: "Jane", age: 29},
    {name: "Tom", age: 21}
  ]
}

Like here, is Jane 30 or 29 years old ?
Now, as I understand reading here , the preferred method to solve this is to keep the sub-document in its own collection and use its _id instead of embedding it (anyone feel like we're back to an RDBMS at this point?), by either doing it manually and query for each document you get for the details (resulting in many many queries for each document, and if you have a list of documents multiply it with your document count!) or use DBRef's which are said to do the exact same thing on a DRIVER level, as opposed to on server level, which means the exact same, just not done by me, but by the driver, so same query number applies, ie: network overhead, server overhead, waiting, waiting... Here is an example:
people:
{
  _id: 1,
  name: "John",
  phones: [
    {phones_id: 1},
    {phones_id: 2}
  ]
},
{
  _id: 2,
  name: "Steve",
  phones: [
    {phone_id: 3}
  ]
}

phones:
{
  _id: 1,
  phone: "555 66 77"
},
{
  _id: 2,
  phone: "555 66 78"
},
{
  _id: 3,
  phone: "555 11 22"
}

Which means after the first query from which I get people documents, I'll have to do 3 more queries over phones collection to get the actual phones to produce a list of peoples phone numbers.
Right off the bat in today's data load I can tell you: that is NOT going to fly. Imagine that was a 50.000 long book list with 10 authors each ? I'm NOT sending 500.001 queries to a server just to get one list.
Constructs like:
bookLinks:
{ bookId: 1, authorId: 1}, {bookId: 2, authorId: 1}...

will only make matters worse: now you have to do one query for links, an equal number of queries as resulting documents to link them to books, and then a number of queries for authors, resulting in 550.001 queries (for 50000 books with 10 authors each).
So... As any real project will obviously have both embedable (phone book) and non-embedable (authors/books) models, and since MongoDB cannot at server level resolve dbrefs to documents in other collections and embed them, what is the way to go ? What is the correct or preferred way to design document collections in such a scenario ?
I hope I managed to describe my concerns accurate enough.
Note: Please don't advise local caching of details to decrease number of queries (no: I still will not send 300.001 queries to a server instead of 500.001). Such methods would be patches for a poor design, they wouldn't solve the problem.

A: In some cases, you can do it with aggregation pipeline and its $lookup operator. Something like this (sorry, doc example, not your example)
db.orders.aggregate([
    {
      $lookup:
        {
          from: "inventory",
          localField: "item",
          foreignField: "sku",
          as: "inventory_docs"
        }
   }
])

Essentially, this is a left-outer join, with a price to pay (more convoluted query syntax). In your case, you might have to $unwind your arrays first.

Also, can you use multiple lookups ?

Yes, it should be as simple as placing several $lookup steps in the pipeline.


text:
Q: JavascriptInterface for Webview on Android Jelly Bean and above I used to have a javascript interface on my mobile app that allows me to capture data from my webview back to the app, which used to work ,but recently when I upgraded the app to handle lollipop it started having issues regarding the javascriptInterface.
This is my current code for the javascriptInterface:
webView = (WebView)findViewById(R.id.webView);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new MyBrowser());
webView.getSettings().setBuiltInZoomControls(false);
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
webView.getSettings().setJavaScriptEnabled(true);
webView.setHorizontalScrollBarEnabled(false);

@JavascriptInterface
public boolean doSomething(String employeeID){

    RunSearch(employeeID);
    Log.d("runsearch", "running search");
    return true;
}
public class WebAppInterface {

    Context mContext;

    WebAppInterface(Context c) {
        mContext = c;
    }
}

My webpage is stored locally
The error says that :

None of the methods in the added interface have been annotated with
  @android.webkit.JavascriptInterface; they will not be visible in API
  17

I've looked into the documentation but What should I do to make it work with Jelly Bean and higher?

A: The problem is that you have not exposed any callable methods in your WebAppInterface.  I assume from the annotation that you intent for the doSomething method to be exposed?  If so, simply move it into the interface.
public class WebAppInterface {

    Context mContext;

    WebAppInterface(Context c) {
        mContext = c;
    }

    @JavascriptInterface
    public boolean doSomething(String employeeID){

        RunSearch(employeeID);
        Log.d("runsearch", "running search");
        return true;
    }
}


text:
Q: Timus Online Judge - 1001 Reverse Root, Runtime error (access violation) I have problems to submit my solution, with the error from my topic (Runtime error (access violation)). Could some one help with explanation where am I doing it wrong. The problem explanation can be found here:
http://acm.timus.ru/problem.aspx?space=1&num=1001
#include <iostream>
#include <iomanip>

using namespace std;
int main()
{
    double outputNumbers[100000];
    double number;
    int index;

    index = -1;
    while (cin.fail() == false)
    {
        cin >> outputNumbers[++index];
    }

    cout << fixed;
    cout << setprecision(4);

    while (index > 0)
    {
        cout << sqrt(outputNumbers[--index]) << endl;
    }

    return 0;
    }


text: Q: Can we test Grafana graphs using Selenium? We are automating a NMS Application (Network Management System) using Selenium. There are some monitoring graphs which are made using Grafana and InfluxDB. Is it possible to test those graphs using Selenium?


text:
Q: Adding text to a div in Android WebView dynamically using Javascript I am planning to fill up the text on this website using Javascript
http://customercare.indianrailways.gov.in/criscm/common/complaint_registration.seam
And here is the code for my WebView below
The problem is couple of input fields are dynamic in the WebPage and
I try to use .innerHTML and load some text/html into div but it's not loading.
public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.details1);

                    mWebView = (WebView)findViewById(R.id.webview);
                    String s2="http://customercare.indianrailways.gov.in/criscm/common/complaint_registration.seam";
                    mWebView = (WebView) findViewById(R.id.webview);
                    mWebView.getSettings().setStandardFontFamily("Arial");
                    mWebView.getSettings().setDefaultFontSize(17);
                    if(mWebView.getSettings().getBuiltInZoomControls())
                    {

                    }
                    else
                    {

                    }
                    mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
                    mWebView.getSettings().setJavaScriptEnabled(true);
                    mWebView.loadUrl(s2);

                    mWebView.setWebChromeClient(new WebChromeClient() {

                    });

                   WebViewClient yourWebClient = new WebViewClient()
                   {
                       // Override page so it's load on my view only
                       @Override
                       public void onPageFinished(WebView view, String url) {
                            // TODO Auto-generated method stub
                           //progressBar.setVisibility(View.GONE);
                            String Staffname = "cristian";
                            String mode="InTrain";
                            String date="27/09/2014 07:14";
                            String contactno="941432344";
                            String emailid="rdasdamn@gmail.com";
                            String address1="28 asdasdasdasd";
                            String address2="Siwerwerweradi";
                            String address3="Madurai";
                            String address4="werwer India";
                            String remarks="Shan asdasdasdas dasdasdas";
                            /*String html="
Sub Complaint :*
"
                                    +"

<input type='radio' name='complaintRegister:causeOfSubComplaint:subCatComplaint' id='complaintRegister:causeOfSubComplaint:subCatComplaint:0'"
                                    +"value='152' autocomplete='off'> Non availability of Manning Staff	"
                                    +"

<input type='radio' name='complaintRegister:causeOfSubComplaint:subCatComplaint' id='complaintRegister:causeOfSubComplaint:subCatComplaint:1'"
                                    +"value='153' autocomplete='off'> Gates not open during late night hours at the halting"
                                    +"stations

";*/

                            mWebView.loadUrl("javascript:"
                            + "document.getElementById('complaintRegister:nameOfStaff:nameOfStaff').value = '"+Staffname+"';"
                            + "document.getElementById('complaintRegister:complaintMode').value = '"+mode+"';"
                            +"document.getElementById('complaintRegister:decIncidentDate:incidentDateInputDate').value='"+date+"';"
                            +"document.getElementById('complaintRegister:contactNumber:contactNo').value='"+contactno+"';"
                            +"document.getElementById('complaintRegister:emailId:emailId').value='"+emailid+"';"
                            +"document.getElementById('complaintRegister:address1Id').value='"+address1+"';"
                            +"document.getElementById('complaintRegister:address2Id').value='"+address2+"';"
                            +"document.getElementById('complaintRegister:address3Id').value='"+address3+"';"
                            +"document.getElementById('complaintRegister:address4Id').value='"+address4+"';"
                            +"document.getElementById('complaintRegister:complaintModePanel:platformNumber').visible='True';"
                            +"document.getElementById('complaintRegister:complaintModePanel:stationName').visible='True';"
                            +"document.getElementById('complaintRegister:remarks').value='"+remarks+"';"
                            +"document.getElementById('complaintRegister:causeOfComplaint').innerHTML='"+"Shandsadas"+"';");
                            super.onPageFinished(view, url);

                        }

                   };
                   mWebView.setWebViewClient(yourWebClient);
                 // mWebView.setWebChromeClient(new HelloWebViewClient());
        }

}


text:
Q: How to match set of strings that appear in radom order with regular expression There is a set of strings:
"foo","bar","baz", "boo", "123"

Which appear in text in random order, but numbers appear first:
Some text
     123 baz bar foo
     123 bar baz foo
     123 foo baz bar
Some other text

how can I match the line where they appear using regular expression?

A: To perform the task you may try the shielding method:

*

*Shield the lines containing duplicates as such lines should be excluded. You may then delete them if needed.

*Match all the lines containing the words from the set.

So, an example text:
Some text
     123 baz bar foo
     123 bar baz foo
     123 foo baz bar
     123 foo baz bar foo boo
     123 foo bar bar
     123 boo baz foo asdf
Some other text

At first we should search the duplicate containing lines using the following regex:
(^.*(foo|bar|baz|boo|123).*\2)

The previous means: take a text from the beginning of line containing at least one duplicate word among the set ending with the matched duplicate.
Then shield these lines with the replacement using regex:
#SHIELD#\1

We will get the following text:
Some text
     123 baz bar foo
     123 bar baz foo
     123 foo baz bar
#SHIELD#     123 foo baz bar foo boo
#SHIELD#     123 foo bar bar
     123 boo baz foo asdf
Some other text

Or delete these lines if needed.
Then we will be able to get needed lines from the rest. Let us mark them with the replacement:
Find: ^(?!#SHIELD#)(\s*123.*(baz|bar|foo|boo).*)$
(search only not shielded lines beginning with spaces, 123 and then any text with at least one match from the set).
Replace by: #MYLINE#\1
We get the text:
Some text
#MYLINE#     123 baz bar foo
#MYLINE#     123 bar baz foo
#MYLINE#     123 foo baz bar
#SHIELD#     123 foo baz bar foo boo
#SHIELD#     123 foo bar bar
#MYLINE#     123 boo baz foo asdf
Some other text


text:
Q: Почему не выделяется текст в слайдах? Как сделать, чтобы выделялся текст в слайдах и не было синего аутлайна при нажатии? Пример здесь
Вот сам JS-код:
$(document).ready(function () {
    $('.slider--preview-articles').slick({
        infinite: true,
        slidesToShow: 3,
        slidesToScroll: 1,
        dots: true,
        dotsClass: "slider__dots slider__dots--centered",
        arrows: false,
        speed: 500,
        autoplay: true,
        autoplaySpeed: 5000,
        draggable: false,
        responsive: [
            {
                breakpoint: 1599,
                settings: {
                    slidesToShow: 2,
                    slidesToScroll: 1
                }
            },
            {
                breakpoint: 991,
                settings: {
                    slidesToShow: 1
                }
            }
        ]
    });
});

A: /* Для выделения текста */
.slider--preview-articles {
    -webkit-user-select: text;
    -moz-user-select: text;
    -ms-user-select: text;
    user-select: text;
}
.slider--preview-articles.draggable {
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
}

/* Убираем outline */
.slider--preview-articles .slider__slide {
    outline: none;
}


text:
Q: controllers sub-folders inside area i have sub folder in controller folder in area
Controller

*

*api

*

*UserController

*Products

*

*product1Controller

I want to access product1 controller when the user requests http://mysite/api/products/product1/Index
and the views folder like

*

*Views

*

*api

*

*User

*products

*

*product1

my apiAreaRegistration.cs like this
public class apiAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "api";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "api_default",
                "api/{controller}/{action}/{id}",
                new { controller = "Offers", action = "Index", id = UrlParameter.Optional },
                new string[] { "TracerAPI.Areas.api.Controllers" }
            );
        }
    }

Thanks and Regards.

A: It is against of asp.net mvc convention. It cannot be done without deep recoding of Asp.Net MVC Framework.


text:
Q: Can shared memory be read and validated without mutexes? On Linux I'm using shmget and shmat to setup a shared memory segment that one process will write to and one or more processes will read from.  The data that is being shared is a few megabytes in size and when updated is completely rewritten; it's never partially updated.
I have my shared memory segment laid out as follows:

    -------------------------
    | t0 | actual data | t1 |
    -------------------------

where t0 and t1 are copies of the time when the writer began its update (with enough precision such that successive updates are guaranteed to have differing times).  The writer first writes to t1, then copies in the data, then writes to t0.  The reader on the other hand reads t0, then the data, then t1.  If the reader gets the same value for t0 and t1 then it considers the data consistent and valid, if not, it tries again.
Does this procedure ensure that if the reader thinks the data is valid then it actually is?
Do I need to worry about out-of-order execution (OOE)?  If so, would the reader using memcpy to get the entire shared memory segment overcome the OOE issues on the reader side?  (This assumes that memcpy performs it's copy linearly and ascending through the address space.  Is that assumption valid?)

A: Modern hardware is actually anything but sequentially consistent. Thus, this is not guaranteed to work as such if you don't execute memory barriers at the appropriate spots. Barriers are needed because the architecture implements a weaker shared memory consistency model than sequential consistency. This as such has nothing to do with pipelining or OoO, but with allowing multiple processors to efficiently access the memory system in parallel. See e.g. Shared memory consistency models: A tutorial. On a uniprocessor, you don't need barriers, because all the code executes sequentially on that one processor.
Also, there is no need to have two time fields, a sequence count is probably a better choice as there is no need to worry whether two updates are so close that they get the same timestamp, and updating a counter is much faster than getting the current time. Also, there is no chance that the clock moves backwards in time which might happen e.g. when ntpd adjusts for clock drift. Though this last problem can be overcome on Linux by using clock_gettime(CLOCK_MONOTONIC, ...). Another advantage of using sequence counters instead of timestamps is that you need only one sequence counter. The writer increments the counter both before writing the data, and after the write is done. Then the reader reads the sequence number, checks that it's even, and if so, reads the data, and finally then reads the sequence number again and compares to the first sequence number. If the sequence number is odd, it means a write is in progress, and there is no need to read the data.
The Linux kernel uses a locking primitive called seqlocks that do something like the above. If you're not afraid of "GPL contamination", you can google for the implementation; As such it's trivial, but the trick is getting the barriers correct.

A: Joe Duffy gives the exact same algorithm and calls it: "A scalable reader/writer scheme with optimistic retry".
It works.
You need two sequence number fields.
You need to read and write them in opposite order.
You might need to have memory barriers in place, depending on the memory ordering guarantees of the system.
Specifically, you need read acquire and store release semantics for the readers and writers when they access t0 or t1 for reading and writing respectively.
What instructions are needed to achieve this, depends on the architecture. E.g. on x86/x64, because of the relatively strong guarantees one needs no machine specific barriers at all in this specific case*.
* one still needs to ensure that the compiler/JIT does not mess around with loads and stores , e.g. by using volatile (that has a different meaning in Java and C# than in ISO C/C++. Compilers may differ, however. E.g. using VC++ 2005 or above with volatile it would be safe doing the above. See the "Microsoft Specific" section. It can be done with other compilers as well on x86/x64. The assembly code emitted should be inspected and one must make sure that accesses to t0 and t1 are not eliminated or moved around by the compiler.)
As a side note, if you ever need MFENCE, lock or [TopOfStack],0 might be a better option, depending on your needs.


text:
Q: Download Email Attachment with Python from Gmail I try to fedge attachments from my company GMail Account.
When trying to run the following script it won't stop loading even after 3 Minutes.
Only explanation could be that my company uses "Okta" to authorize.
import imaplib
import base64
import os
import email

mail = imaplib.IMAP4_SSL('imap.gmail.com',993)
mail.login('something@gmail.com', 'xxxxxx')

mail.select('Inbox')

Any idea on why code wont run?


text:
Q: Trying to get unique source, medium, campaign using STRING_AGG function by visitNumber I am trying to get unique source, medium, campaign using STRING_AGG function partitioning by fullVisitorId and ORDER BY visitNumber.
However, I am getting a lot of repeated fields in Source, medium and campaign using STRING_AGG.
So I thought of using DISTINCT but it doesn't work with STRING_AGG.
Any advice appreciated.
Code:
SELECT
  CAST(concat(SUBSTR(date,0,4), '-', SUBSTR(date,5,2),'-',SUBSTR(date,7,2)) as date ) as date,
  fullVisitorId,
  trafficSource.keyword,
  trafficSource.adContent,

STRING_AGG(channelGrouping), ' > ') OVER (PARTITION BY fullVisitorId ORDER BY visitNumber) AS channelPath,
STRING_AGG(trafficSource.medium), ' > ') OVER (PARTITION BY fullVisitorId ORDER BY visitNumber ) AS medium_Path,
STRING_AGG(trafficSource.source), ' > ') OVER (PARTITION BY fullVisitorId ORDER BY visitNumber) AS source_Path,
STRING_AGG(trafficSource.campaign), ' > ') OVER (PARTITION BY fullVisitorId ORDER BY visitNumber) AS campaign_Path

FROM
  `tfa-big-query.74006564.ga_sessions_*`,UNNEST(hits) as hit
WHERE _table_suffix BETWEEN '20180801' and '201808015'

The results in the STRING_AGG column (channelgrouping, medium and source is the occurrence of repetitive fields which can be seen as follows:
Actual results:
Organic Search > Organic Search > Organic Search < Other <  Other < Direct < Owned <  email < email < (none) < (none)
Expected Output:
Organic Search < Other < Direct < Owned < email < (None)

A: Below is for BigQuery Standard SQL
#standardSQL
CREATE TEMP FUNCTION DeDup(arr ANY TYPE) AS ((
  SELECT STRING_AGG(str, ' > ') FROM (
    SELECT CONCAT(ANY_VALUE(x), ' (', CAST(COUNT(1) AS STRING), ')') str FROM (
      SELECT x, COUNTIF(flag) OVER(ORDER BY OFFSET) grp FROM (
        SELECT *,x!=IFNULL(LAG(x) OVER(ORDER BY OFFSET), x) flag FROM UNNEST(arr) x WITH OFFSET
      ))
    GROUP BY grp
)));
SELECT
  DATE,
  fullVisitorId,
  keyword,
  adContent,
  DeDup(channelPath) AS channelPath,
  DeDup(medium_Path) AS medium_Path,
  DeDup(source_Path) AS source_Path,
  DeDup(campaign_Path) AS campaign_Path
FROM (
  SELECT
    CAST(CONCAT(SUBSTR(DATE,0,4), '-', SUBSTR(DATE,5,2),'-',SUBSTR(DATE,7,2)) AS DATE ) AS DATE,
    fullVisitorId,
    trafficSource.keyword,
    trafficSource.adContent,
    ARRAY_AGG(channelGrouping) OVER(PARTITION BY fullVisitorId ORDER BY visitNumber) AS channelPath,
    ARRAY_AGG(trafficSource.medium) OVER(PARTITION BY fullVisitorId ORDER BY visitNumber ) AS medium_Path,
    ARRAY_AGG(trafficSource.source) OVER(PARTITION BY fullVisitorId ORDER BY visitNumber) AS source_Path,
    ARRAY_AGG(trafficSource.campaign) OVER(PARTITION BY fullVisitorId ORDER BY visitNumber) AS campaign_Path
  FROM `tfa-big-query.74006564.ga_sessions_*`,UNNEST(hits) as hit
  WHERE _table_suffix BETWEEN '20180801' and '201808015'
)

Above will return something like
Organic Search (3) > Other (2) > Direct (1) > Owned (1) > email (2) > (none) (2)
which is a little extension of your expected result Organic Search < Other < Direct < Owned < email < (None)

A: I thought STRING_AGG work with DISTINCT
try this sql from bigquery document
SELECT STRING_AGG(DISTINCT fruit, " & ") AS string_agg
FROM UNNEST(["apple", NULL, "pear", "banana", "pear"]) AS fruit;


text:
Q: iOS7 - UITabBar - Transparent doesn't work I m using custom UITabBar in my app and i set the translucency to NO:
if ([self.tabBar respondsToSelector:@selector(setTranslucent:)])
    [self.tabBar setTranslucent:NO];

I have UIViewController with this .xib:

In the white area i have a UIScrollView with UIEdgeInsetsMake(0, 0, 70, 0) as u can see.
My problem is that the UIViewController doesn't shrink because of the UITabBar, and the UIEdgeInsets is 70 points but starting from the point 480, rather then 410 (480-70).
I want that the 70 points will start from the highest UITabBar point (UITabBar high is 49 points), point 480-49 = 431.
Any help will be great!


text:
Q: When do we need to use non-capturing groups? According to the comments on this answer, (?:(?!ab).)* is more efficient than (?!.*ab).*.  Why?  Isn't a lookahead/lookbehind already non-capturing?
Basically, I'm trying to figure out if I need to do (\^(?:(?=(?:\d+=|\|$)))) or if I can just do (\^(?=\d+=|\|$)).  Both work to capture all ^ followed either by ###= or |..
Example:
1=5^2=A^3=6^|

I want to get three ^ matches (which I do).  So, the question is:  would I want to add the non-capturing groups if I'm already not capturing the contents of the lookahead?

A: In your case, you don't need a capturing group since the lookahead already limits the scope of the alternation:
(\^(?:(?=(?:\d+=|\|$))))

can be rewritten without change in functionality as
(\^(?=\d+=|\|$))

The example at the start of the string is something else because it's using repetition inside/outside a group. Here there is a difference, not only in efficiency but also in the possible matches:
(?:(?!ab).)*

matches xxx in "xxxab" whereas
(?!.*ab).*

matches b.

A: Using non-capturing groups is useful for handling repeating patterns that you don't necessarily want to keep individually.
For example, lets say you're parsing out people's full names.  A person can have any number of first and middle names, but only one last name.  You want to capture their full name as well as their last name.
You know you can match the name segments with repeated \w+\s+ but because you don't know how many first/middle names the person has, this presents a problem.
You consider something like ^(\w+\s+)*(\w+)$.  This will capture the last name... but what capture group is it in?  There's no way to know without already knowing how many first/middle names the person has.
That's where non-capturing groups come in.  You need to repeat the \w+\s+ pattern, but you don't necessarily care about the specific values it grabs.
Now your expression looks like ^(?:\w+\s+)*(\w+)$.
The full result is the person's whole name and capture group one is their last name.  No more guessing where results are stored!

In your case, a look-ahead should suffice, but that doesn't mean non-capturing groups don't have their uses.


text:
Q: Route public traffic to VPC I have an Aurora database on a VPC. Today I needed to connect to that database through Lambda. Not really an issue except I needed internet access in that Lambda and so I had to setup the following:

*

*I added a new subnet for the public NAT.

*I added a NAT Gateway and assigned it to a new EIP and the new subnet.

*I added a new route table that routed all traffic to the igw and associated that table with the new subnet I created in step 1.

*I modified the Main route table and routed all traffic to the NAT.

This gave me internet access in my Lambda, and by running the Lambda on the VPC, I also had access to my Aurora database.
However, I have now lost public access to this database through MySQL Workbench.
What do I need to configure to route the public traffic back to the VPC?

A: The fact that you could previously connect to the Amazon Aurora data base from your laptop suggests that Aurora was running in a Public Subnet. That is, a subnet that has a Route Table that sends Internet-bound traffic directly to the Internet Gateway.
You mention that you modified the Main routing table. It is likely that this routing table is associated with your Public Subnet (where Aurora is located), and that it was previously configured to send traffic to the Internet Gateway. However, it was probably modified to send traffic to the NAT Gateway. Therefore, the subnet was effectively changed into a Private Subnet (with no Route Table entry that points to the Internet Gateway).
If you really do want your database in the public subnet, then the configuration would be:

*

*One public subnet, which contains the Aurora database and to which the Lambda function connects

*A Route Table associated with the subnet that routes Internet-bound traffic (0.0.0.0/0) to the Internet Gateway

*Possibly an additional subnet to provide High Availability for both Aurora and Lambda

No private subnet is required since you want Aurora in a public subnet.
A more secure option would be:

*

*A public subnet with a jump box EC2 instance and the Lambda connection

*A private subnet with Aurora

To connect to Aurora from your laptop, you would SSH into the Jump Box and use port forwarding to access the Aurora database. This way, the database is not exposed to the Internet.
The public subnet would have a different route table than the private subnet (thus making them private/public).


text:
Q: PHP: Return if statements into HTML element How would you return a value of an if statement into a specific HTML element when using a combination of PHP and HTML in the same doc.
For example. With native JavaScript let's say I write this:
var myVariable = "This will get appended";
var div = document.querySelector('.mydiv');

if ( test != functionResult  ) {
div.innerHTML = myVariable;
}

I'm still learning PHP, but from what I understand, you might do this to achieve the same thing:
$myVariable = "This will get appended";

if ( $test != $functionResult  ) {
    $div = $myVariable;
}

<?php echo $div ?>

Is this the correct PHP syntax for this function?

A: This is what I interpreted as what you were looking for:

<? if($test!=$functionresult): ?>
    This will get appeneded
<? endif; ?>

Or if you don't want the div to show if it is false:
<? if($test!=$functionresult): ?>

 This will be appended

<? endif; ?>


text:
Q: Creating a slopy element I am trying to achieve this effect in my webpage..

The red box is where I will be placing a menu, I would like the bottom of the red box to be slanted. The section on the right of the slant needs to be transparent as there may be an image in the background where the grey color is.
The only thing I can come up with is to rotate the element but that would also rotate the contents of the element which I do not want.. Only the bottom bg of the red element (which will be a solid color) should be slanted.

A: you can do it like that, just highlighted the rotated part blue, that you see what happens ;)
you might have to play with the top: and left: values if you change the size
edit: added a small menu example (really small ^^)
jsfiddle link
here is the html part:

some

menu

here

and here the css part:
#menucontainer{
    position: relative;
    z-index: 100;
    background: red;
    height: 100px;
}

#menucontainer ul {
    position: absolute;
    bottom: 0px;
    left: 30px;
}

#menucontainer li {
    list-style: none;
    margin-left: 10px;
    background: #123;
    display: inline-block;
}

#rotatedDiv {
    z-index: 99;
    background: blue;
    position: absolute;
    top: 14px;
    left: -5px;
    height: 90px;
    width: 200%;
    -moz-transform: rotate(-2deg);
    -webkit-transform: rotate(-2deg);
    -o-transform: rotate(-2deg);
    -ms-transform: rotate(-2deg);
    transform: rotate(-2deg);
}

#background {
    background: green;
}

you might want to modify it in any way you can think of, but the main part should be clear i think ;)

A: You can do it with a transparent border:
html

This is where the menu would go.

css
.bgone {
    height: 100px;
    background: black;
    position: relative;
}

.bgtwo {
    height: 50px;
    border-top: 100px solid black;
    border-right: 1000px solid transparent;

}
.content {
    position: absolute;
    top: 10px;
    left: 10px;
    color: #FFF;
}


text:
Q: Why doesn't NetBeans know my javabean property? I'm working on a project where I need to create a "Switch Bean" that communicates with a "Bounce Bean". I have the Bounce Bean code provided to me, I just need to make my switch bean communicate with my bounce bean. In my program, whenever I click "on", the ball needs to bounce-- when I click "off", the ball needs to stop bouncing. I have created getter/setter methods, but whenever I put my bean into NetBeans, I see no "switchOn" property. On my teachers example switchBean, you can automatically see a property called "switchOn" whenever I move it onto a JFrame in NetBeans. My bean compiles and I am able to JAR it with no problem. Any help would be greatly appreciated!
package switchBean;

import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;

public class SwitchBean extends JPanel
{
    private static final int LENGTH = 200;
    private static final int WIDTH = 20;
    boolean switchOn;

    public SwitchBean()
    {
        //JPanel radioButtonPanel = new JPanel();
        final ButtonGroup group = new ButtonGroup();
        final JRadioButton on = new JRadioButton("On");
        final JRadioButton off = new JRadioButton("Off");
        group.add(on);
        group.add(off);
        this.add(on);
        this.add(off);
        off.isSelected();

        on.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {
                boolean currentStatusOfButton = isSwitchOn();
                if(currentStatusOfButton = false)
                {
                    setSwitchOn(false);
                }
            }
        });

        off.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {
                boolean currentStatusOfButton = isSwitchOn();
                if(currentStatusOfButton = false)
                {
                    setSwitchOn(false);
                }
            }
        });
    }

    public boolean isSwitchOn()
    {
        return switchOn;
    }

    public void setSwitchOn(boolean switchStatus)
    {
        this.switchOn = switchStatus;
        firePropertyChange("switchOn", switchOn, true);
    }
}

A: For bean you add implements Serializable
public class SwitchBean extends JPanel implements Serializable

After create .jar
In NetBeans in menu system do: tools -> palette -> Swing/AWT Components
 and remove old beans and add new


text:
Q: No native Aggregation of mongodb in Meteor? I have a monogodb collection which I can query like this:
meteor:PRIMARY> db.answers.aggregate([
     {$group: { _id: { owner: "$owner", locked: "$locked" } } }
]);
{ "_id" : { "owner" : "qCkecS4s8wjSRL4YS", "locked" : true } }
{ "_id" : { "owner" : "MQCMpT8xwh5ripBLA", "locked" : false } }

This works perfectly in meteor:
var result = Answers.find( {_id: id} )

But when I do this in meteor I get an error:
var result = Answers.find( {_id: id}).aggregate([ {$group: { _id: { owner: "$owner", locked: "$locked" } } }  ]);

I have seen that there are packages around to support aggregation but is that really needed. I use Meteor 1.1.0.1 with mongodb 3.x

Here is an other example:
var userSendin = Answers.find( {_id: id} );

var userSendin2 = Answers.aggregate([ { $match:{_id: id} }  ]);

Both should have the same result but only the .find() works for me ..
Any idea why? I have no usable error message just Error in line xx.

A: You need a package to support aggregation. There are a number out there, most are server-side only and nonreactive. One that is reliable is from meteorhacks. meteor add meteorhacks:aggregate.


text:
Q: How exactly should I escape the awk $ variables in a shell script function? I am trying to use awk inside a shell script function, but can't seem to find a reference that tells me how to properly escape the awk variable ($4). Inside the function it keeps getting replaced at the 4th item passed to the function (Null).

iHealthGetFile()
{
    fileID=$(cat qkViews/${dir}iHealth-Files.json|grep -B5 '${1}'|grep id|awk '{print $4}'|sed 's/,//g; s/\"//g')
    echo $fileID
    echo "Retrieving file $1 as $fileID from ID: $ID"
}

(disclaimer: Yes, I could probably do something differently with the piped commands... but my main goal is to figure out the escaping of the $4 first.)

A: As far as I can tell without any contextual data, the error is not in your awk code, but within your first grep, which is looking for the literal four characters ${1}. I suspect this was intended to be the first parameter passed to your function.
I've altered your code a little. If you really intended the echo $fileID to remove extraneous whitespace you'll want to remove the double quotes I've added around the variable there.
You're also using a couple of global variables. Mixing local variables ($1) and global variables ($dir and $ID) is not particularly good coding practice, but there are times in a script where pragamatism may need to win.
iHealthGetFile()
{
    fileID=$(
        grep -B5 "$1" "qkViews/${dir}iHealth-Files.json" |
        awk '/id/ {print $4}'|
        tr -d ',"'
    )
    echo "$fileID"
    echo "Retrieving file $1 as $fileID from ID: $ID"
}

A: In your question you claim that awk returns null as a result of $4 passed to the shell function is null.
The reason that your awk (or your whole pipe) returns null is not due to a kind of confussion with shell function parameters.
It is just because whatever is feeding awk with data (left part of your awk pipe) has not a valid 4th field .
This test will prove it:
$ function tt { echo "1:$1-2:$2-3:$3-4:$4"; echo "first second third fourth" |awk '{print $4}'; }
$ tt one two #call the function with only two parameters. 3 and 4 are null
1:one-2:two-3:-4: #Parameters passed to function
fourth #awk result

As you can see , awk result is not affected by function parameters . If the data provided to awk are valid, 4th field of these data will be returned.


text:
Q: Obtaining real and positive solution of a polynomial equation in wxMaxima I'd like to solve the following equation in wxMaxima:
k*A*((T_2-T_1)/L)=ε*σ*A*(T_1^4-T_a^4)

for T_1. The problem is that with regular Solve and Solve_to_poly I get extremely long outputs but not what I would expect. I need a real and positive solution since T_1 is a temperature in Kelvins. I can substitute the values but I'd prefer to get a symbolic formula as output. Is there a way to get such a solution in wxMaxima?

A: Apparently, it's not possible to solve this equation in such a way that a symbolic solution in form of a formula for T1 is obtained. Thus, I had to substitute the values and then solve for unknown T1. Either using float(solve([...],[T1])) which gives 4 solutions (with only one being real and positive - the one of interest) or using find_root(...,T1,0,1000). Lower and upper bounds for T1 (0 K - 1000 K) can be selected based on the physics of the problem.


text:
Q: Discord bot look for message from user I am making a verification bot and the staff members have to accept or deny the user once the verification is sent with a reaction to the message. But if a staff member denies a user, The bot will ask for a reason which will be sent to the user. The issue is that when the bot is waiting for the staff member to send the reason if a message is sent in any other channel then the bot will use that message as the reason.
        elif str(reaction) == "❌":
            remove_id(member.id)
            await verif_channel.send(":warning: Please provide a reason :warning:")
            try:
                deny_channel = member.guild.get_channel(889690902359080970)
                msg = await self.bot.wait_for("message", timeout=600)
                why = msg.content
                embed_reason = discord.Embed(
                    title=":warning: You have been denied! :warning:",
                    description="You have been denied from the server for the following reason: (You are still allowed to reverify by reacting to the message in <#734570330064028002>) \n\n"
                    "{}".format(f"Reason: {why}"),
                    color=int(hex_color, 16))
                await member.send(embed=embed_reason)
                await verif_channel.send(f"❌ I have denied {member.mention}")

                embed2 = discord.Embed(
                    title="Verification Request",
                    description=f"Verification request of {member.mention}",
                    color=int(hex_color, 16)
                )
                embed2.set_thumbnail(url=member.avatar_url)
                embed2.add_field(name="How did you find this server?", value=found, inline=False)
                embed2.add_field(name="How old are you?", value=age, inline=False)
                embed2.add_field(name="This is a server related question", value=about, inline=False)
                embed2.add_field(name="What are you looking to get out of this server?", value=seek, inline=False)
                embed2.add_field(name="User was:", value=f"Denied for {why}", inline=False)
                embed2.set_author(name=member.name)
                embed2.set_footer(text=f"User ID: {member.id}")

                channel = member.guild.get_channel(863099566672707594)

                await channel.purge(limit=4)
                await deny_channel.send(embed=embed2)

            except discord.Forbidden:
                await verif_channel.send(f"❌ Denied {member.mention}\n"
                                         f"User has blocked DMs")

I am trying to change it so that the bot will look for a message in the channel from the user that reacted to the message. I tried a few different ways but I don't really know how I would get the id of the user that reacted to the message.

A: The best way to check if a message has been sent by a specific person is to use a check function. Please view the code below.
# Define the check function within your code
def check(msg):
    return msg.author == reaction.author and not msg.author.bot
    # This checks if the author of the message is the author of the ❌ reaction
    # AND checks if the message author is a bot or not

msg = await self.bot.wait_for("message", check=check, timeout=600)

Helpful link(s):

*

*client.wait_for - discord.py docs


text:
Q: How to stop waitpid from hanging on certain inputs waitpid hangs when the child "crashes" due to double free errors or memory corruption from freeing stack arrays? is there anyway to catch these types of errors?
int status;
errno = 0;
pid_t wait_status = waitpid(cpid, &status, WUNTRACED | WCONTINUED);
if (wait_status == -1) {
    fprintf(stderr, "Failed to wait for child id %d - error: %s", cpid, strerror(errno));
    exit(wait_status);
}
if (WIFEXITED(status)) {
    pm->process_status = WEXITSTATUS(status);
    pm->status_set = true;
    return;
}
else if (WIFSIGNALED(status)) {
    fprintf(stderr, "Child process was terminated by signal %d\n", WTERMSIG(status));
    pm->process_status = -1;
}
else if (WIFSTOPPED(status)) {
    fprintf(stderr, "Child process was stopped\n");
    pm->process_status = -1;
}
else {
    fprintf(stderr, "Unknown child error\n");
    pm->process_status = -1;
}

I want the blocking behavior of waitpid, and this works for all other cases, but when the child crashes due to a memory error as described above, it never exits, or lets waitpid return.

A: If waitpid hangs, this means your child has not exited yet. If your parent process has a main loop and you don't want waitpid to hang, call it with the WNOHANG option: waitpid(pid, &status_var, WNOHANG). As soon as waitpid doesn't return 0, your child has exited.
You can then eg. check for the exit cause with WIFEXITED, WIFSIGNALED and WCOREDUMP as described in the man page.

A: You can be more precise using waitid instead of waitpid and check si_status. Or you can install a signal handler in your childs.


text:
Q: Как работает "global" в Python? скажите пожалуйста как работает зарезервированное слово "global" в Python

A: Когда внутри функции создаются новые переменные, они имеют локальную область видимости. То есть такие переменные определены только в пределах тела функции, и они уничтожаются, когда функция возвращает управление вызывающей программе. Чтобы иметь возможность изменять глобальные переменные внутри функции, эти переменные следует определить в теле функции с помощью инструкции global
count = 0
...
def foo():
    global count
    count += 1  # Изменяет значение глобальной переменной count

A: При создании новой переменной в функции, они действуют только в пределе функции. Чтобы изменять глобальные переменные внутри функции, определите их с помощью global. (Пример у ответа выше)


text:
Q: Proof of a theorem in Hilbert System How to prove the following formula in Hilbert system:
$\vdash (A \to (B \to C)) \to ((A \land B) \to C)$
I have already proved out that
$\vdash (A \to (B \to C)) \to ((A \land B) \to (B \to C)) $
$\vdash (A \to C) \to ((A \land B) \to C) $
$\vdash (B \to C) \to ((A \land B) \to C) $
But I don't know how to continue.

A: As suggested by @MauroALLEGRANZA, the best solution is to show first that $A \to (B \to C), \, A \land B \vdash C$ is derivable. Indeed, the following is a derivation in Hilbert system of $C$ from the hypotheses $A \to (B \to C)$ and $A \land B$.
\begin{align}
1.& \quad A \to (B \to C) & \text{premise} \\
2.& \quad A \land B & \text{premise} \\
3.& \quad (A \land B) \to A & \text{axiom} \\
4.& \quad A &\text{modus ponens from 3 and 2} \\
5.& \quad B \to C & \text{modus ponens from 1 and 4} \\
6.& \quad (A \land B) \to B & \text{axiom} \\
7.& \quad B &\text{modus ponens from 6 and 2} \\
8.& \quad C &\text{modus ponens from 5 and 7} \\
\end{align}
By deduction theorem, from the fact that $A \to (B \to C), \, A \land B \vdash C$ is derivable it follows that $A \to (B \to C) \vdash (A \land B) \to C$ is derivable.
Again by deduction theorem, from the fact that $A \to (B \to C) \vdash (A \land B) \to C$ is derivable it follows that $\vdash (A \to (B \to C)) \to ((A \land B) \to C)$ is derivable.


text:
Q: Can we automate ETL in Azure? I am currently working on a very interesting ETL project using Azure to transform my data manually. However, transforming data manually can be exhausting and lengthy when I start having several source files to process. My pipeline is working fine for now because I have only a few files to transform but what if I have thousands of excel files?
So what I want to achieve is that I want to extend the project and extract the excel files that are coming from Email using the logic app then apply ETL directly on top of them. Is there any way I can automate ETL in Azure. Can I do ETL without modifying the pipeline for a different type of data manually? How can I make my pipeline flexible to be able to handle data transformation for various types of source data?
Thank you in advance for your help.

A:
Can I do ETL without modifying the pipeline for a different type of
  data manually?

According to your description, i suppose that you already knew the ADF connector is supported in the Logic App. You could execute ADF pipeline in the Logic App flow and even pass parameters into ADF pipeline.
Normally, the source and sink service should be fixed in one copy activity, but you could define dynamic file path in the datasets. So you don't need to create multiple copy activities.
If the data types are different, you could try to pass the parameter from Logic App into ADF. Then before the data transmission, you could use Switch activity to route the transmission into different branches.


text:
Q: Spring AMQP ensuring message order in multi-threaded environment RabbitMQ guarantees message order if the same Publish Channel->Exchange->Queue->Receive Channel is used. It appears Spring AMQP allows me to guarantee all those pieces except for the publish channel. This is causing messages to get out of order.  Below is the problem case:
1.) I have a single thread publishing messages in order on a single exchange
2.) I have a collection of other threads publishing messages on different exchanges and sometimes creating new consumers for different exchanges
Using the cached connection factory it has a cache of channels. Each time a publish is made it goes to the cache to get a channel. Because other threads are publishing and consuming there are no guarantees that the same channel will be used for successive publishes by my main thread. This is true even if I have a cache of one. Has anybody gotten around this issue?
Ideally I would like a dedicated channel for a publisher-exchange combination or at the very least a dedicated channel for publishing. I don't see a way of providing either. It seems a significant flaw in the Spring AMQP if there is no way to guarantee publish order when RabbitMQ has a mechanism for guaranteeing order.

A: You would have to use a dedicated connection (hence: connection factory) for each publisher.
Or, you could use RabbitTemplate.execute() and use the channel provided in the callback to publish al messages.


text:
Q: plotting data with two conditions I can plot data depending on the value in one column like this:
\documentclass{standalone}
\usepackage{pgfplots}
\usepackage{filecontents}
\begin{filecontents}{data.csv}
a,b,c,d
0,0,1,2
2,2,1,2
3,-3,1,3
2,1,2,4
\end{filecontents}
\begin{document}
\begin{tikzpicture}
  \begin{axis}
  \addplot+[only marks]
    table[x=a, y=b, col sep=comma,
      restrict expr to domain={\thisrow{c}}{1:1}]{data.csv};
  \end{axis}
\end{tikzpicture}
\end{document}

Is it possible to apply two conditions?  For example, I would like to plot data where both the value in c = 1 and the value in d = 2 without plotting data where only one applies.

A: You can use x expr to apply the conditions. If the result is not true, set the x value to nan:
\documentclass{standalone}
\usepackage{pgfplots}
\usepackage{filecontents}
\begin{filecontents}{data.csv}
a,b,c,d
0,0,1,2
2,2,1,2
3,-3,1,3
2,1,2,4
\end{filecontents}
\begin{document}
\begin{tikzpicture}
  \begin{axis}
  \addplot+[only marks]
    table[
      x expr={and(\thisrow{c}==1,\thisrow{d}==2)==1?\thisrow{a}:nan},
      y=b,
      col sep=comma,
      ]{data.csv};
  \end{axis}
\end{tikzpicture}
\end{document}

Result:


text:
Q: three dropdown box related to eachother i have three dropdown box each box is dependent to eachother
if i click one dropdown means heading want to display next dropdown box that heading related topics want to display in third dropdown box that topics reaming topics want to display
for.ex: first dropdown box i have fruit and anmials  if i click fruit means second dropdown box will display the fruit name like banana, apple, orange then i click banana means the third dropdown box display remains apple and orange want to display

A: I suggest using Vue to fill the next dropbox according to the prev one.
You have to read about:

*

*Writing vue components

*VueJs