text:
Q: Magento 2.2.5 - Admin Panel has 503 Service Unavailable page under Content. Changes made to it are not reflected Magento 2.2.5 - Admin Panel has 503 Service Unavailable page under Content=>Pages. I updated this page but the changes are not reflected. Is Magento using this page or not?

A: Magento's (admittedly lackluster) documentation suggests just intercepting the 503 at the server level and serving your own 503/maintenance page. https://devdocs.magento.com/guides/v2.2/comp-mgr/trouble/cman/maint-mode.html
I think common wisdom among Magento developers though, is to simply edit that file you already found: pub/errors/default/503.phml. When you enable maintenance mode, that is the file the Magento will load.


text:
Q: How to create multiple parent actors in Thespian Working on Actor Model-based system and using the Thespian library. I am trying to generate 100 instances of the actor and add it to the actor system, however, I can only pass in the class type instead of an instance of that class. Does it have to be recursive where a parent has to exist?
class Person(Actor):
    def __init__(self, name):
        pass

if __name__=='__main__':
    from thespian.actors import ActorSystem
    system = ActorSystem()
    for i in range(100):
        system.createActor(Person("*insert unique name*"))
    # Shutdown ActorSystem instance.
    system.shutdown()

It doesn't seem like this is allowed given the Thespian documentation, but couldn't find anything online about this use case.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Return from lambda forEach() in java I am trying to change some for-each loops to lambda forEach()-methods to discover the possibilities of lambda expressions. The following seems to be possible:
ArrayList<Player> playersOfTeam = new ArrayList<Player>();
for (Player player : players) {
    if (player.getTeam().equals(teamName)) {
        playersOfTeam.add(player);
    }
}

With lambda forEach()
players.forEach(player->{if (player.getTeam().equals(teamName)) {playersOfTeam.add(player);}});

But the next one doesn't work:
for (Player player : players) {
    if (player.getName().contains(name)) {
        return player;
    }
}

with lambda
players.forEach(player->{if (player.getName().contains(name)) {return player;}});

Is there something wrong in the syntax of the last line or is it impossible to return from forEach() method?

A: This what helped me:
List<RepositoryFile> fileList = response.getRepositoryFileList();
RepositoryFile file1 = fileList.stream().filter(f -> f.getName().contains("my-file.txt")).findFirst().orElse(null);

Taken from Java 8 Finding Specific Element in List with Lambda

A: I suggest you to first try to understand Java 8 in the whole picture, most importantly in your case it will be streams, lambdas and method references.
You should never convert existing code to Java 8 code on a line-by-line basis, you should extract features and convert those.
What I identified in your first case is the following:

*

*You want to add elements of an input structure to an output list if they match some predicate.

Let's see how we do that, we can do it with the following:
List<Player> playersOfTeam = players.stream()
    .filter(player -> player.getTeam().equals(teamName))
    .collect(Collectors.toList());

What you do here is:

*

*Turn your input structure into a stream (I am assuming here that it is of type Collection<Player>, now you have a Stream<Player>.

*Filter out all unwanted elements with a Predicate<Player>, mapping every player to the boolean true if it is wished to be kept.

*Collect the resulting elements in a list, via a Collector, here we can use one of the standard library collectors, which is Collectors.toList().

This also incorporates two other points:

*

*Code against interfaces, so code against List<E> over ArrayList<E>.

*Use diamond inference for the type parameter in new ArrayList<>(), you are using Java 8 after all.

Now onto your second point:
You again want to convert something of legacy Java to Java 8 without looking at the bigger picture. This part has already been answered by @IanRoberts, though I think that you need to do players.stream().filter(...)... over what he suggested.

A: You can also throw an exception:
Note:
For the sake of readability each step of stream should be listed in new line.
players.stream()
       .filter(player -> player.getName().contains(name))
       .findFirst()
       .orElseThrow(MyCustomRuntimeException::new);

if your logic is loosely "exception driven" such as there is one place in your code that catches all exceptions and decides what to do next. Only use exception driven development when you can avoid littering your code base with multiples try-catch and throwing these exceptions are for very special cases that you expect them and can be handled properly.)

A: The return there is returning from the lambda expression rather than from the containing method.  Instead of forEach you need to filter the stream:
players.stream().filter(player -> player.getName().contains(name))
       .findFirst().orElse(null);

Here filter restricts the stream to those items that match the predicate, and findFirst then returns an Optional with the first matching entry.
This looks less efficient than the for-loop approach, but in fact findFirst() can short-circuit - it doesn't generate the entire filtered stream and then extract one element from it, rather it filters only as many elements as it needs to in order to find the first matching one.  You could also use findAny() instead of findFirst() if you don't necessarily care about getting the first matching player from the (ordered) stream but simply any matching item.  This allows for better efficiency when there's parallelism involved.

A: If you want to return a boolean value, then you can use something like this (much faster than filter):
players.stream().anyMatch(player -> player.getName().contains(name));


text:
Q: How to make a side bar with padding and margin with endless content? I've been trying to create a right side bar with a padding of 12px and a margin to the left of 10px, with flexible content, like the sidebar's height will expand with the text in it, if it was to be increased.
Problem is, I can't use flexbox, nor flow, or display.
Any help would be really appreciated :)
This is the fiddle https://jsfiddle.net/1azLec3d/
 side-bar {
  float: right;
  padding: 12px;
  width: 326px;
  margin-left: 10px;
  background: lightblue;

This is basically what I'm trying to achieve.

A: If you can't use flexbox, I would do it with traditional float: left with padding and negative margin trick to stretch the shortest column to be the same height as its sibling. See snippet below for demonstration:

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.head {
  background: teal;
  padding: 12px;
}

.sub-container {
  overflow: hidden;
}

.main-content,
.side-bar {
  float: left;
  width: 60%;
  padding: 12px;
  background: yellow;
  padding-bottom: 9999px;
  margin-bottom: -9987px; /* 12px less than padding-bottom since you want 12px padding bot */
}

.side-bar {
  width: 40%;
  background: pink;

}

.footer {
  background: green;
  padding: 12px;
}

Zombie ipsums

Mindless

Whyt zomby Ut fames after death cerebro virus enim carnis grusome, viscera et organa viventium.

Lucio

Zombie ipsum reversus ab viral inferno, nam rick grimes malum cerebro. De carne lumbering animata corpora quaeritis. Summus brains sit, morbo vel maleficia? De apocalypsi gorger omero undead survivor dictum mauris. Hi mindless mortuis soulless
            creaturas, imo evil stalking monstra adventus resi dentevil vultus comedat cerebella viventium. Qui animated corpse, cricket bat max brucks terribilem incessu zomby. The voodoo sacerdos flesh eater, suscitat mortuos comedere carnem virus.
            Zonbi tattered for solum oculi eorum defunctis go lum cerebro. Nescio brains an Undead zombies. Sicut malus putrid voodoo horror. Nigh tofth eliv ingdead.

Hi mindless mortuis soulless creaturas


text:
Q: TypeError: Cannot Read Property of Undefined Even Though I Defined It I'm a beginner to JavaScript. I've looked through a few questions on here regarding "TypeError: ... undefined even though the property is defined" but their examples are either too dense for me to grasp or they realize they've incorrectly assigned something downstream. Here I think my example is quite simple, and I don't think I've incorrectly assigned anything.
I've defined position in my class MoveableObjects and when I call player = new MoveableObject(position, other params ...) I don't get any errors.
When I change this to player = new Sprite(position, other params ...) where Sprite extends MoveableObjects and then try to call a function inside Sprite it tells me position.x is undefined. I put console.log(player) immediately after the declaration and it does in fact show position as undefined, but I don't understand why it does since I've clearly defined it.
Here is the constructor of MoveableObjects
class MoveableObject {

    constructor({ colorRGB, width, height, position, velocity}) {
        this.width = width;
        this.height = height;
        this.position = position;
        this.velocity = velocity;
        this.colorRGB = colorRGB;

        // If the side of the object is touching or beyond the side of the canvas it is flagged as bounded.
        this.inUpLimit = false;
        this.inDownLimit = false;
        this.inLeftLimit = false;
        this.inRightLimit = false;

        // Translate the velocity into directional words
        this.movingLeft = false;
        this.movingRight = false;
        this.movingUp = false;
        this.movingDown = false;
    }

Here is the constructor of Sprite and the draw() function it uses.
// Sprite represents moveable objects with an animated image.
class Sprite extends MoveableObject {

    constructor({ imageSrc, numRows = 1, numCols = 1, spacing = 0, margin = 0, animationSpeed = 10, position, velocity}) {

        super(position, velocity)

        this.image = new Image()                             // Image can be a single image or a spritesheet.
        this.image.src = imageSrc
        this.numRows = numRows                               // # animation sequences in the spritesheet
        this.numCols = numCols                               // # frames in an animation sequence
        this.spacing = spacing                               // # pixels between each frame
        this.margin = margin                                 // # pixels between image border and sprite border. Vertical and horizontal margins should be equal.
        this.animation = new Object()
        this.animation.speed = animationSpeed                // # times draw function is called before the next frame in the animation sequence is called.
        this.animation.counter = 0                           // # times the draw function has been called
        this.animation.enabled = false                       // Whether or not the animation sequence is currently running
        this.animation.row = 1;                              // The row of the current frame being drawn
        this.animation.col = 1;                              // The column of the current frame being drawn
        this.animation.firstRow = 1;                         // The row of the frame to initialize the animation loop on
        this.animation.firstCol = 1;                         // The column of the frame to initialize the animation loop on
        this.animation.lastRow = 1;                          // The row of the frame to restart the animation loop on
        this.animation.lastCol = 1;                          // The column of the frame to restart the animation loop on

        this.frame = new Object();
        this.frame.width = 0;                               // Init image.onload
        this.frame.height = 0;                              // Init image.onload
        this.image.onload = () => {                                 // Calculates width and height of animation frame based on numRows, numColumns, spacing, and margin

            let imageWidth = this.image.width;
            let spriteSheetWidth = imageWidth - (2 * this.margin);
            let widthNoSpacing = spriteSheetWidth - this.spacing * (this.numCols - 1);
            let frameWidth = widthNoSpacing / this.numCols;

            let imageHeight = this.image.height;
            let spriteSheetHeight = imageHeight - (2 * this.margin);
            let heightNoSpacing = spriteSheetHeight - this.spacing * (this.numRows - 1);
            let frameHeight = heightNoSpacing / numRows;

            this.frame.width = frameWidth;
            this.frame.height = frameHeight;
        }

    }

    draw() {

        // Draw the frame at the current row and column.
        context.drawImage(
            this.image,                             // the entire image being loaded
            this.animation.col * this.frame.width,  // sx, x coordinate to begin crop
            this.animation.row * this.frame.height, // sy, y coordinate to begin crop
            this.frame.width,                       // swidth, width of cropped image
            this.frame.height,                      // sheight, height of cropped image
            this.position.x,                        // x coordinate where to place image on canvas
            this.position.y,                        // y coordinate where to place image on canvas
            this.frame.width,                       // the width to stretch/shrink it to
            this.frame.height                       // the height to stretch/shrink it to
        )

Here I create a new MoveableObject with position defined and then console.log() it. It shows position to be what I set it to. I copy/paste that declaration and change "new MoveableObject" to "new Sprite" (with a new variable name of course) and print that, and it shows position is undefined:
// Initializers for main()
const gravity = 0.8;
const player = new Sprite({
    imageSrc: './lib/img/template.png',
    numRows: 21,
    numCols: 4,
    spacing: 0,
    margin: 0,
    position: {
        x: 0,
        y: 0
    },
    velocity: {
        x: 0,
        y: 0
    }
})
console.log(player)
const enemy = new MoveableObject({
    colorRGB: 'blue',
    width: 50,
    height: 150,
    position: {
        x: 150,
        y: 50
    },
    velocity: {
        x: 0,
        y: 0
    }
})
console.log(enemy)
const moveableObjects = [player, enemy];

// The main function of the script updates the game state every frame.
function main() {

    // When the game starts the canvas, then player, then enemy are rendered.
    context.fillStyle = 'black';
    context.fillRect(0, 0, canvas.width, canvas.height);
    player.draw();
    enemy.draw();

The error is raised on player.draw() and reads "Uncaught TypeError: Cannot read properties of undefined (reading 'x')"
Does anyone understand why this is the case? It seems to me like the error is maybe produced by not properly extending my class or using super() incorrectly to pass attributes, but I haven't found an example that proves that.


text:
Q: How do I convince Xcode and Git that my Asset Catalog has been updated? After adding new image sets and images to my asset catalog, Xcode doesn't seem to think it needs committing to Git.

Occasionally it'll notice the change if I quit Xcode and restart it, but that seems a little unreliable.
Or am I missing something obvious?
UPDATE: The 'M' has appeared! It seems performing a git pull has made it realise there's been a local change (?!).
I've cured the symptom, but can anyone explain the root cause?

A: Hit the build/run button. Sometimes git needs a little push to understand that things may have changed. If it's not working, try to rename something or even changing some variable name into your code.


text:
Q: iOS Extension kJavaScriptFinalizeArgumentKey The iOS 8 Extension SDK allows you to interact with a web pages using JavaScript.
The guide references a kJavaScriptFinalizeArgumentKey constant to use as a dictionary key when passing data back to the finalize() method in the JS.
Xcode doesn't recognise this, nor the other kJavaScriptResultsKey referenced in the docs.
Does anyone know if this is either not yet implemented, or if I need to import a module for this to work?

A: replace 'kJavaScriptFinalizeArgumentKey' with  'NSExtensionJavaScriptFinalizeArgumentKey'
so the SDK sample should be
   NSExtensionItem *extensionItem = [[NSExtensionItem alloc] init];
   extensionItem.attachments = @[[[NSItemProvider alloc] initWithItem: @{NSExtensionJavaScriptFinalizeArgumentKey: @{@"bgColor":@"red"}} typeIdentifier:(NSString *)kUTTypePropertyList]];

   [self.extensionContext completeRequestReturningItems:@[extensionItem]  completionHandler:nil];


text:
Q: QF_FPA? Does Z3 support IEEE-754 arithmetic? Browsing Z3 source code, I came across a bunch of files referring to QF_FPA, which seems to stand for quantifier-free, floating-point-arithmetic. However, I don't seem to be able to locate any documentation regarding its state, or how it can be used via various front-ends (in particular SMT-Lib2). Is this an encoding of IEEE-754 FP? If so, which precisions/operations are supported? Any documentation would be most helpful..

A: Yes, Z3 supports floating point arithmetic as proposed by Ruemmer and Wahl in a recent SMT-workshop paper. At the current stage, there is no official FPA theory, and Z3's support is very basic (only a bit-blaster). We're not actively advertising this yet, but it can be used exactly as proposed in the paper by Ruemmer/Wahl (setting logics QF_FPA and QF_FPABV). At the moment, we are working on a new decision procedure for FPA, but it will be some time until that is available.
Here's a brief example of what an FPA SMT2 formula could look like:
(set-logic QF_FPA)

(declare-const x (_ FP 11 53))
(declare-const y (_ FP 11 53))
(declare-const r (_ FP 11 53))

(assert (and
    (= x ((_ asFloat 11 53) roundTowardZero 0.5 0))
    (= y ((_ asFloat 11 53) roundTowardZero 0.5 0))
    (= r (+ roundTowardZero x y))
))

(check-sat)

A: The floating point logics are named QF_FP and QF_FPBV in v4.4.2. The link to the description of the theory in RELEASE_NOTES is broken. The correct page is http://smtlib.cs.uiowa.edu/theories-FloatingPoint.shtml. The proposed example above should be
(set-logic QF_FP)

(declare-const x (_ FloatingPoint 11 53))
(declare-const y (_ FloatingPoint 11 53))
(declare-const r (_ FloatingPoint 11 53))

(assert (and
    (= x (fp #b0 #b00000000010 #b0000000000000000000000000000000000000000000000000010))
    (= y (fp #b0 #b00000000010 #b0000000000000000000000000000000000000000000000000010))
    (= r (fp.add roundTowardZero x y))
))

(check-sat)


text:
Q: Apache Shiro salt hashed password I need to salt a hashed(SHA-256) password using Apache Shiro. I used the following method, but it uses plainText password as a parameter. But I need to get an alredy hashed password from the frontend and salt it and store in the server side. Otherwise if I use the following method I will have to pass the plain password all the way through frontend, which is not secure. So please suggest me a way to overcome this problem.
String hashedPassword = new Sha256Hash(plainTextPassword, salt);

A: You cannot salt the password after it has been hashed. Salting works by combining the salt with the plain text password, and hashing the entire thing. This is why Shiro's Sha256Hash requires you to give it the plain text password.
It is common to pass the plain text password from the front end to the service layer as long as this communication is secure (e.g. HTTPS for web UIs). The only thing you should not do is store the plain text password in a database (which a correctly configured Shiro will not do) because your database may be compromised.
When passing the plain text password from the front end to your service, it will only exist in memory for a short time before being garbage collected. To obtain the password someone would have to either break your SSL connection (in which case you are screwed anyway) or compromise your server and dump the memory (in which case you are screwed anyway).


text:
Q: Can I set up something to monitor Cron JOb/script Can I set up something to monitor Cron Job, a script running and if it fails it should restart the script and alert us? for the failure it may have to check the logs for keywords?

A: Instead of using a cron job you can use a similar function in monit and evaluate the return code. The monit will send a mail if the status fail.
For some additional information see https://www.mmonit.com/monit/documentation/monit.html#SERVICE-POLL-TIME
The monit program can not monitor the executed cron jobs. If error messages are written to a log file monit can use the messages to send a mail.


text:
Q: Motor to spin slowly, low torque I am trying to find a motor to use to spin a cardboard wheel to drop balls through a hole. I want this to happen pretty slowly, around 10rpm. It also needs almost no torque, as it is spinning cardboard. However, when trying to find a motor, all I can find is extremely fast motors with low torque  or slow motors with high torque. Both options are expensive. Does a very low cost, DC, low speed, low torque motor even exist? Thanks

A: If you drive the wheel with a belt driven by a 2mm toy motor shaft turning at 5000 RPM you would need the pulley to be 100mm in diameter.
That sounds feasible. If you need the pulley to be bigger, put a small pulley on the motor. Easy to make if you have a small lathe, should be easy to make by sandwiching bits etc. if you don't.

If you're not in too much of a hurry you can get DC gear motors for << $10 from China like the below 12VDC 10RPM model with a convenient 6mm shaft.

This, like most gear motors, will have relatively high stall torque- it is 5.6 kg-cm rated.. if you need it to stall without damage you may need to limit the current.

A: simple amazon search 10 seconds $4
https://www.amazon.ca/CNBTR-TYC-50-AC110V-Synchronous-Electric/dp/B01G8USUH0/ref=sr_1_2?ie=UTF8&qid=1504202443&sr=8-2&keywords=10+rpm+motor


text:
Q: Jest test setup - Plugin/Preset files are not allowed to export objects, only functions I am not sure how to approach this problem. I have read some of the responses to this kind of error and I have gathered that it seems to be a result of mixing Babel 6 and Babel 7. I think I have been careful not to mix the two and I am still getting this error. This is a Vue application.
babelrc
{
  "presets": [
    ["env", {
      "modules": false,
      "targets": {
        "browsers": ["> 1%", "last 2 versions", "not ie <= 8"]
      }
    }],
    "stage-2"
  ],
  "plugins": [
    "transform-vue-jsx",
    "transform-runtime"],
  "comments": false
}

package.json
  "scripts": {
    "dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
    "start": "npm run dev",
    "build": "node build/build.js",
    "test:unit": "jest"
  },
  "dependencies": {
    "@babel/runtime-corejs2": "^7.4.3",
    "babel-polyfill": "^6.26.0",
    "babel-runtime": "^6.26.0",
    "es6-promise": "^4.2.5",
    "moment": "^2.23.0",
    "vue": "^2.5.2",
    "vue-froala-wysiwyg": "^2.9.5",
    "vue-router": "^3.0.1",
    "vue-virtual-scroll-list": "^1.3.2",
    "vuex": "^3.0.1"
  },
  "devDependencies": {
    "@vue/test-utils": "^1.2.2",
    "autoprefixer": "^7.1.2",
    "babel-core": "^6.26.3",
    "babel-helper-vue-jsx-merge-props": "^2.0.3",
    "babel-jest": "^27.1.1",
    "babel-loader": "^7.1.1",
    "babel-plugin-syntax-jsx": "^6.18.0",
    "babel-plugin-transform-runtime": "^6.22.0",
    "babel-plugin-transform-vue-jsx": "^3.5.0",
    "babel-preset-env": "^1.3.2",
    "babel-preset-stage-2": "^6.22.0",
    "chalk": "^2.0.1",
    "copy-webpack-plugin": "^4.0.1",
    "css-loader": "^0.28.0",
    "exif-js": "^2.3.0",
    "extract-text-webpack-plugin": "^3.0.0",
    "file-loader": "^1.1.11",
    "friendly-errors-webpack-plugin": "^1.6.1",
    "html-webpack-plugin": "^2.30.1",
    "jest": "^27.1.1",
    "js-htmlencode": "^0.3.0",
    "linkifyjs": "^2.1.6",
    "node-notifier": "^5.1.2",
    "node-sass": "^4.9.0",
    "optimize-css-assets-webpack-plugin": "^3.2.0",
    "ora": "^1.2.0",
    "portfinder": "^1.0.13",
    "postcss-import": "^11.0.0",
    "postcss-loader": "^2.0.8",
    "postcss-url": "^7.2.1",
    "rimraf": "^2.6.0",
    "sass-loader": "^7.0.1",
    "sass-resources-loader": "^1.3.3",
    "semver": "^5.3.0",
    "shelljs": "^0.7.6",
    "style-loader": "^0.20.2",
    "uglifyjs-webpack-plugin": "^1.1.1",
    "url-loader": "^0.5.8",
    "vue-jest": "^3.0.7",
    "vue-js-modal": "^1.3.28",
    "vue-loader": "^13.3.0",
    "vue-style-loader": "^3.0.1",
    "vue-template-compiler": "^2.6.14",
    "vue-toasted": "^1.1.24",
    "webpack": "^3.6.0",
    "webpack-bundle-analyzer": "^2.9.0",
    "webpack-dev-server": "^2.9.1",
    "webpack-merge": "^4.1.0"
  },
  "engines": {
    "node": ">= 6.0.0",
    "npm": ">= 3.0.0"
  },
  "browserslist": [
    "> 1%",
    "last 2 versions",
    "not ie <= 8"
  ]
}

When I run 'npm run test:unit' I get
> cec-discussionboard@1.0.0 test:unit <HOME>\source\repos\DiscussionBoard
> jest

 FAIL  src/components/Common/__tests__/CecMessageCard.spec.js
  ● Test suite failed to run

    Plugin/Preset files are not allowed to export objects, only functions. In <HOME>\source\repos\DiscussionBoard\node_modules\babel-preset-stage-2\lib\index.js

      at createDescriptor (node_modules/@babel/core/lib/config/config-descriptors.js:211:11)
          at createDescriptor.next (<anonymous>)
      at evaluateSync (node_modules/gensync/index.js:251:28)
      at node_modules/gensync/index.js:31:34
          at Array.map (<anonymous>)
      at Function.sync (node_modules/gensync/index.js:31:22)
      at Function.all (node_modules/gensync/index.js:210:24)
      at createDescriptors (node_modules/@babel/core/lib/config/config-descriptors.js:142:41)
          at createDescriptors.next (<anonymous>)

Test Suites: 1 failed, 1 total
Tests:       0 total
Snapshots:   0 total
Time:        2.232 s
Ran all test suites.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! cec-discussionboard@1.0.0 test:unit: `jest`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the cec-discussionboard@1.0.0 test:unit script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     <HOME>\AppData\Roaming\npm-cache\_logs\2021-09-13T14_23_16_751Z-debug.log

The test code is
import { mount } from '@vue/test-utils'
import CecMessageCard from '../src/components/Common/CecMessageCard.vue'

describe('CecMessageCard mount', () => {
    test('mounts CecMessageCard', () => {
        const wrapper = mount(CecMessageCard, {
            propsData: { message: 'Test message', title: 'Test title' }
        });
        expect(wrapper.html()).toMatchSnapshot()
        return
    })
})

The obvious error in running the test stated after 'Fail'. Any suggestions on how to get testing configured for this Vue2 application?


text:
Q: sharepoint framework extensions: sorry something went wrong I am trying to learn SharePoint Framework Extensions and this is my first try. I created an application customer following the example in pluralsight. When I try to add the app, I get the error: Sorry, somethin went wrong with adding the app.
I can't seem to get other information from UI. Could someone help me figure out how to troubleshoot this error? How can I view the logs using Get-SPOTenantLogEntry as at this moment I get nothing back?

A: I think I am trying the exact same pluralsight course and was having the same issue.  I got mine working now and in my case it was just a typo in the elements.xml file when defining ClientSideComponentProperties.  this may not be your issue but here is what it should look like.
<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
    <CustomAction
        Title="Appcust"
        Location="ClientSideExtension.ApplicationCustomizer"
        ClientSideComponentId="d87f3988-5cae-4da0-bdfb-6882349b0d24"
        ClientSideComponentProperties="{"Top":"The top","Bottom":"The bottom"}">
    </CustomAction>
</Elements>


text:
Q: Powershell: Export-CSV and OutFile not doing what I expect Why am I getting a blank file here? When I run it before the export-csv I get PLENTY of records all showing up in the console.

So here's the code I'm using
$path = "C:\test"

Get-ChildItem -Path $path -Include *.edi, *.x12, *.filename, *.dat, *.log, *.mdn, *.req -Recurse -Force |
Where-Object {!$_.PSIsContainer -and ((get-date)-$_.LastWriteTime).days -gt 30 } |
Remove-Item -force -whatif | export-csv D:\output.csv #also I try out-file D:\output.txt

A: Common parameter -WhatIf - used for previewing a command's actions - never outputs data; instead, the preview information is printed straight to the console, meaning it can neither be sent through the pipeline, nor redirected to file, nor captured.
As an aside: Remove-Item without -WhatIf also never produces data output, so there is generally no point in trying to process its output in a subsequent pipeline segment.
Your best bet is to add an -OutVariable (-ov) common parameter to your Where-Object call, which allows you to export the collected file-info objects via Export-Csv in a separate command:
Get-ChildItem ... | Where-Object -OutVariable filesToRemove { ... } |
  Remove-Item -WhatIf ...
$filesToRemove | Export-Csv D:\output.csv

The above still prints the preview information to the console, but also collects the [System.IO.FileInfo] objects selected by Where-Object in variable $filesToRemove, which you can then export in CSV format.


text:
Q: Why do most/all languages not have a multi-loop break function? I haven't seen any programming language that has a simple function to break out of nested loops. I'm wondering:
Is there something at a low level making this impossible?
Here is an example of what I mean (C#):
while (true)
{
    foreach (String s in myStrings)
    {
        break 2; // This would break out of both the foreach and while
    }
}

Just break; would be like break 1;, and take you out of only the innermost loop.
Some languages have messy alternatives like goto, which work but are not as elegant as the above proposed solution.

A: No there's nothing on a low level that would prevent creating something like what you propose. And you also have a lot of languages implemented in a highlevel language that definitely would allow for this kind of behaviour.
There are however several considerations when designing a language that would talk against this sort of construct, at least there is from my point of view.
The main argument being that it opens up for a very complex structure in something that is probably allready overly complex. Nested loops are inherently hard to follow and figure out what is happening.
If you'd add your construct it could make them even more complex.
Unless you consider a return statement as a sort of break of course :)

A: Although this is more speculation, there are some arguments both for and against such a possibility.
Pro:

*

*Might be very elegant in some cases.

Con:

*

*Might result in a tempation to write deeply nested loops, which is seen as undesirable by some.

*The desired behaviour can be implemented with goto.

*The desired behaviour can be implemented with auxiliary variables.

*Nested loops can in most cases be refactored to use just one loop.

*The desired behaviour can be implemented using exception handling (although, on the other hand, controlling the expected flow of execution is not the primary task of exception handling).
That being said, I consider resposible usage of goto to be legitimate.

A: Perl does have something very similar to this feature.  Instead of the number of nestings, you use a label much like goto.
FOREVER:while (1) {
    for my $string (@strings) {
        last FOREVER;
    }
}

The feature is intended to remove ambiguities when using loop controls in deeply nested loops.  Using a label improves readability and it protects you should your level of nesting change.  It reduces the amount of knowledge the inner loops have about the outer loops, though they still have knowledge.
The nesting is also non-lexical, it will cross subroutine boundaries.  This is where it gets weird and more goto-like.
FOREVER:while (1) {
    for my $string (@strings) {
        do_something;
    }
}

sub do_something {
    last FOREVER;
}

This is not considered a good feature for all the reasons @Codor lays out in their answer.  This sort of feature encourages very complex logic.  You're nearly always better off restructuring deeply nested loops into multiple subroutine calls.
sub forever {
    while (1) {
        for my $string (@strings) {
            return;
        }
    }
}

What you're asking for is, essentially, a restricted goto.  It carries with it most of the same arguments for and against.
while (1) {
    for my $string (@strings) {
        goto FOREVER;
    }
}

FOREVER:print "I have escaped!\n"

The idea of saying "break out of the nth nested loop" is worse than a goto from a structural perspective.  It means inner code has intimate knowledge of its surroundings.  Should the nesting change, all of the inner loop controls may break.  It creates a barrier to refactoring.  For example, should you want to perform an extract method refactoring on the inner loop...
while (1) {
    twiddle_strings(@strings);
}

sub twiddle_strings {
    for my $string (@strings) {
        last 2;
    }
}

Now the code controlling the outer loop is in a completely different function from the inner loop.  What if the outer loop changes?
while (1) {
    while(wait_for_lock) {
        twiddle_strings(@strings);
    }
}

sub twiddle_strings {
    for my $string (@strings) {
        last 2;
    }
}

A: PHP has it since version 4. And IMHO it's not very good - it's quite easy to abuse it. Especially when you add levels to iterations or remove some or change code logic inside iterations. Code refactoring / optimization usually begins with iterations overview and trying to reduce cycles to conserve CPU usage. During this kind of optimization it's easy to miss a continue level and finding this kind of introduced bug is not an easy task if multiple people are working on a project.
I'd prefer any time goto since it's (usually) much safer. Unless you know exactly what you are doing. Also, goto keeps BASIC in my mind.


text:
Q: Extract values from particular JSON array Given the following example JSON:
{
   "results":{
      "first":[
         true,
         "Matthew"
      ],
      "second":[
         false,
         "Unapplied"
      ],
      "third":[
         false,
         "Invalid Code"
      ]
   },
   "unused":728
}

as response from the following ajax call:
    var code = 'RDMPT21';
    $.ajax({
        url: 'codecheck.php',
        type: "POST",
        dataType: 'json',
        data: {"redeem":code},
        success: function(data) {
            console.log(data);
        }
    });

How could I grab the first and the second values of each key and display them in the log console? I tried to use console.log(data[first]) in the success function as well, but I get undefined, why?

A: The error appeared to be coming from the JSON itself, which was formatted as Object instead, so I was able to grab the desired values by using:
data = JSON.parse(data);

to later be able to grab my value needed with:
console.log(data["results"]["first"][0]);
console.log(data["results"]["first"][1]);

Special thanks to CBroe for the heads up.


text:
Q: Crystal Reports ExportToDisk font size When using the ExportToDisk method of ReportDocument it shrinks all of the fonts to 0.5pt than they were specified in the report.  I'm creating a word document so specified the line of code as such:
myReport.ExportToDisk(CrystalDecisions.[Shared].ExportFormatType.WordForWindows, path)

I've also experimented with creating a RTF instead (using ExportFormatType.RichText) but to no avail.  I seem to remember coming across a reason with a registry fix - but I've lost it now.
Must warn you this is a legacy system (.NET 1)
Any ideas?

A: RTF format is a text file whose format is documented. You should easily be able to postprocess it to adjust any font properties. You can download the spec from Microsoft for further info.


text:
Q: C++ Smallest Number in Array Not Displaying #include <iostream>

using namespace std;

int main()
{
    double sixty = 0.0;
    double fiftyfive = 0.0;
    double height[10];
    double tallest = 0.0;
    double shortest = 0.0;
    double average = 0.0;
    double total = 0.0;

    for (int x = 0; x < 10; x = x + 1)
    {
        height[x] = 0.0;
    }

    cout << "Please enter the heights of ten students. "<< endl;
    for (int x = 0; x < 10; x = x + 1)
    {
        cout << "Enter height of a student: ";
        cin >> height[x];
    }

    for (int x = 0; x < 10; x = x + 1)
    {
        if (height[x] > 60)
        {
           sixty = sixty + 1;
          }
    }
    for (int x = 0; x < 10; x = x + 1)
    {
        if (height[x] < 55)
        {
           fiftyfive = fiftyfive + 1;
        }
    }
    cout << "The number of students over 60 inches in height: " << sixty << endl;
    cout << "The number of students under 55 inches in height: " << fiftyfive << endl;

    for (int x = 0; x < 10; x = x + 1)
    {
        if (height[x] > tallest)
        {
                      tallest = height[x];
        }
    }
    cout << "The tallest student is: " << tallest << endl;

    for (int x = 0; x < 10; x = x + 1)
    {
        if (height[x] < shortest)
        {
                      shortest = height[x];
        }
    }
    cout << "The shortest student is: " << shortest << endl;

    for (int x = 0; x < 10; x = x + 1)
    {
        total = total + height[x];
    }
    average = total / 10;
    cout << "The average student height is: " << average << endl;

    system("pause");
    return 0;
}

In the above, I need to spit out the # of students over 60in, the # of students over 55in, the average height, the tallest height, and the shortest height.
Everything works fine except for the shortest height. I return an output of zero for that portion of the code.
This is simple code so I imagine it's a simple problem which I'm overlooking. Any input is appreciated.

A:     if (height[x] < shortest)
    {
                  shortest = height[x];
    }

with shortest being zero there will never be a student smaller than that(unless you have students with negative height from outer realms ;) ). You need to init shortest with height[0];
Also in this case you can start iterating students from 1
shortest = height[0];
for (int x = 1; x < 10; x = x + 1)
{
    if (height[x] > tallest)
    {
                  tallest = height[x];
    }
}

A: Change your loop to
for (int x = 0; x < 10; x = x + 1)
{
    if (shortest == 0 || height[x] < shortest)
    {
                  shortest = height[x];
    }
}

or initialize shortest with first element from height array.
Your code will not work, since there is no height less that zero.

A: Initial value of shortest is zero
double shortest = 0.0;
and the loop can't find any height which is less than 0.

A: for (int x = 0; x < 10; x = x + 1)
{
    if (height[x] < shortest)
    {
         shortest = height[x];
    }
}

since shortest is initialized to 0.0, if your height elements are all not smaller than 0.0, then you will see shortest not changed. try the following:
shortest = height[0];
for (int x = 1; x < 10;  ++x)
{
    if (height[x] < shortest)
    {
         shortest = height[x];
    }
}

A: Unless you have students with negative height, you probably have your comparison wrong.
Set your "shortest" height to a much larger value or the comparison will never be true.

A: Initializa tallest and shortest to height[0] after you get height array as input...


text:
Q: Can't mount HOST folder into Amazon Docker Container? I'm using an EC2 instance to run docker. From my local machine using OSX, I'm using docker machine to create containers and volumes. However when I'm trying to mount a local folder to any container is not possible.
docker create -v /data --name data-only-container ubuntu /bin/true
docker run -it --volumes-from data-only-container -v $(pwd)/data:/backup ubuntu bash

With the first command I create a data only container and I'm executing the second command to get into a container that should have the data-only-container volumes and the one I'm trying to mount, however when access it the folder /backup is empty
What I'm doing wrong?
EDIT:
I'm trying to mount a host folder in order to restore backuped data from my PC to container. In that case what would be a different approach?
Shall I try to use Flocker?

A: A host volume mounted with -v /path/to/dir:/container/mnt mounts a directory from the docker host inside the container. When you run this command on your OSX system, the $(pwd)/data will reference a directory on your local machine that doesn't exist on the docker host, the EC2 instance. If you log into your EC2 instance, you'll likely find the $(pwd)/data directory created there and empty.
If you want to mount folders from your OSX system into a docker container, you'll need to run Docker on the OSX system itself.

Edit: To answer the added question of how to move data up to your container in the cloud, there are often ways to move your data to the cloud provider itself, outside of docker, and then include it directly inside the container. To do a docker only approach, you can do something like:
tar -cC /source . | \
docker run --rm -i -v app-data:/target busybox \
  /bin/sh -c "tar -xC /target"

This will upload your data with tar over a pipe into a named volume on your docker host. You can then include the named "app-data" volume in any other containers. If you need to do this multiple times with larger data sets, creating an rsync container would be more efficient.


text:
Q: Rxjs throw timeout error from pipe to observable error section I'm trying to throw timeout error from the observable pipe to the observer as an error but I am still getting the timeout error in the val callback (in subscribe) while I want to get it in the error callback:
For who is experimented, you can test this code easly and edit it in stackblitz in this link:
https://stackblitz.com/edit/typescript-eegqyz?file=index.ts&devtoolsheight=100
of(4000, 3000, 2000)
    .pipe(
        concatMap(duration =>
            makeRequest(duration).pipe(
                timeout(2500),
                catchError(error => {
                    //throwError('Valid token not returned');
                    return of(`Request timed out after: ${duration}`)
                })
            )
        )
    )
    .subscribe(
        val => console.log(val),
        error => console.log("error", error)
    );

A: Here's how I managed to solve it:
of(4000, 3000, 2000)
  .pipe(
    concatMap(duration =>
      makeRequest(duration).pipe(
        timeout(2500),
        catchError(err => throwError(`Request timed out after: ${duration}`))
      )
    ),
  )

So, basically you have a way to handle errors that come from timeout(which is why you were getting the error in the first cb from subscribe()) and now if throw another error(using throwError), there is no other place to handle the incoming errors, so you will get the error in its callback(from subscribe()).
Here is a StackBlitz example.


text:
Q: Facades: aliasloader not found I want to write my own classes in Laravel that I can use in my controllers. I'm trying this with facades.
This is my folder structure:
app
    classes
    facades
    serviceproviders

I autoloaded them in composer.json
    "app/facades",
    "app/classes",
    "app/serviceproviders"

My class (app/classes/DateRange.php)
<?php namespace myMethods;

class DateRange {
    public function doSomething()
    {
        echo 'Doing something!';
    }
}

My facade (app/facades/DateRangeFacade.php)
<?php namespace myMethods\Facades;
use Illuminate\Support\Facades\Facade;

class DateRangeFacade extends Facade {
    protected static function getFacadeAccessor() { return 'DateRange'; }
}

My Serviceprovider (app/serviceproviders/DateRangeServiceProvider.php)
<?php namespace myMethods;
use Illuminate\Support\ServiceProvider;

class DateRangeServiceProvider extends ServiceProvider {
    public function register()
    {
        $this->app['DateRange'] = $this->app->share(function($app)
        {
            return new DateRange;
        });

        $this->app->booting(function()
        {
            $loader = AliasLoader::getInstance();
            $loader->alias('DateRange', 'myMethods\Facades\DateRangeFacade');
        });
    }
}

Also added 'myMethods\DateRangeServiceProvider' to providers array in app.php
Opening the site, it displays 'Class 'myMethods\AliasLoader' not found'. Found a solution on stackoverflow to put a '\' before AliasLoader:: but that doesn't help.
What am I doing wrong ? Thanks in advance.

A: You have to use or namespace all the things:
<?php namespace myMethods;

use Illuminate\Support\ServiceProvider;
use Illuminate\Foundation\AliasLoader;

class DateRangeServiceProvider extends ServiceProvider {
    public function register()
    {
        $this->app['DateRange'] = $this->app->share(function($app)
        {
            return new DateRange;
        });

        $this->app->booting(function()
        {
            $loader = AliasLoader::getInstance();
            $loader->alias('DateRange', 'myMethods\Facades\DateRangeFacade');
        });
    }
}

This is required (and you cannot simply use \AliasLoader) because AliasLoader is not an Alias in Laravel, it's a class, so you need to tell PHP exactly where it is.


text:
Q: Docker Java Spring Boot RestFull MySql with Angular frontend I have 2 apps:

*

*A java Spring RestFull app with a MySql database

*Angular front end

Both app are running fine and i have them on Heroku. I needed to make changes to the Angular app in order to host on Heroku.
They use @CrossOrigin to communicate between each other.
I am now trying to host this stack on a VM, i use Digital Ocean and have set up a docker machine.
The ultimate goal is to use Kubernetes but i am still trying to get my head around Docker.
At the moment i think that Docker-compose generating the following:

*

*Java Spring Rest container app exposing a port

*MySql container exposing a port

*Angular conainer exposing a port

*nginx container exposing port 80. entry port for everything

is this the best approach?

*

*I think that there is a better way for the containers to communicate with each other.

*is it possible to test this stack locally before i try to host in the cloud.

*do all the containers need to be pushed to a repository like Docker hub which only allows one private repository before you can pull them down to use with digital ocean docker droplet.

*can the complete docker configuration be put in the one Private repository provided by docker hub


text:
Q: Integrating Django Rest Framework and Scrapy Both Scrapy and Django Frameworks are standalone best framework of Python to build crawler and web applications with less code, Though still whenever You want to create a spider you always have to generate new code file and have to write same piece of code(though with some variation.) I was trying to integrate both. But stuck at a place where i need to send the status 200_OK that spider run successfully, and at the same time spider keep running and when it finish off it save data to database.
Though i know the API are already available with scrapyd. But i Wanted to make it more versatile. That lets you create crawler without writing multiple file. I thought The Crawlrunner https://docs.scrapy.org/en/latest/topics/practices.html would help in this,therefor try this thing also
t Easiest way to run scrapy crawler so it doesn't block the script
but it give me error that the builtins.ValueError: signal only works in main thread
Even though I get the response back from the Rest Framework. But Crawler failed to run due to this error does that mean i need to switch to main thread?
I am doing this with a simple piece of code
spider = GeneralSpider(pk)
runner = CrawlerRunner()
d = runner.crawl(GeneralSpider, pk)
d.addBoth(lambda _: reactor.stop())
reactor.run()

A: I ran scrapy spider in django view, and sharing my code.
settings_file_path = "scraping.settings"  # Scrapy Project Setting
os.environ.setdefault('SCRAPY_SETTINGS_MODULE', settings_file_path)
settings = get_project_settings()
runner = CrawlerRunner(settings)

path = "/path/to/sample.py"
path = url.replace('.py', '')
path = url.replace('/', '.')
file_path = ".SampleSpider".format(path)

SampleSpider = locate(file_path)

d = runner.crawl(SampleSpider)
d.addBoth(lambda _: reactor.stop())
reactor.run()

I hope it's helpful.


text:
Q: Как сделать rtl в woocommerce price slider? Как сделать слайдер цены в rtl (изменить ползунок с маленького на большой)?
Я нашел, что это джейквери виджет, но где именно нужно его заменить?
Вот как думаю менять: keith-wood.name/rtlsliders.html

A: подключите новый js файл к теме, с помощью wp_enqueue_script. Потом найдите место в теме где у вас там идет инициализация слайдера, и как параметр допишите там isRTL: true. Если верить тому что написано по той ссылке что вы указали.
Цитата из вашего линка:
Connect the right-to-left slider functionality to your divisions.
$(selector).slider({isRTL: true});


text:
Q: How to remove columns from CDC (in SQL Server) I've enabled CDC on a table, using the code below, and by default it includes all of the columns. There is another way to enable CDC on a table while SPECIFYING the columns (code is given below). However, for me, that's too late - given my CDC was already created and includes ALL of the columns. How do I remove the columns I don't want from the CDC watch list (I searched everywhere in the meta data and couldn't find anything):
-- The following enabled the CDC on a table:
EXECUTE sys.sp_cdc_enable_table
            @source_schema = N'dbo',
            @source_name = N'TableName',
            @role_name = N'cdc_Admin',
            @supports_net_changes = 1

-- Now all of the columns are included in the CDC.

--Alternate (which is too late now given my CDC on table was already created/performed)
EXECUTE sys.sp_cdc_enable_table
@source_schema = N'dbo'    ,
@source_name = N'Orders'    ,
@role_name = N'cdc_Admin'    ,
@captured_column_list = N'OrderID,CustomerAccount,Product,SalesPerson'

A: CDC allows you to have up to two capture instances active for a given table at the same time (in order to accommodate schema changes on the underlying table). So, in order to migrate to a new capture instance where you specify the columns (as you do in your second call to sys.sp_cdc_enable_table), provide a value for the @capture_instance parameter in sys.sp_cdc_enable_table and migrate your ETL jobs to use it. Then, once you're sure that nothing is using the old capture instance, drop it using sys.sp_cdc_disable_table again providing a value for @capture_instance (this time, the old one).

A: In SSIS I can set the [CDC processing mode] on the CDC data source to 'Net with Update Mask' then see what columns were changed.
You could stage all the data and use the update mask to only process the changes you want to keep.


text:
Q: conditional probability in a family Let a family have two children. It is known that one of the children is a boy. What is the probability that both the children are boys.
So for this we build the sample space
$S=\{(b,b)(b,g)(g,g)\}$
Let our event E be the case where both children are boys
$E=\{ (b,b) \}$
Let the conditional be F
$F=\{(b,g),(b,b)\}$
Hence $P(E|F)=\frac{P(E\cap F)}{P(F)}=\frac{1/3}{2/3}=\frac{1}{2}$
But the answer in my book is given as $\frac{1}{3}$ and I can't seem to understand why.

A: Order matters, so your sample space should be $S=\{(b,b),(g,g),(b,g),(g,b)\}$. For example if we have $(g,b)$, then a girl was the first child and a boy was the second child.
Now, given that one of the children is a boy, our remaining possibilities are
$$(b,b),(b,g),(g,b).$$
Among these three options, only $(b,b)$ corresponds to the other child being a boy as well. Since there's only one favorable outcome out of the three possible outcomes, the probability you want is $1/3$, which agrees with what your book says.

A: The events in your sample space are not equiprobable.  $(b,g)$ has probability $\frac12$, because the oldest child might be a boy or a girl.  Alternatively, and perhaps more clearly, add the event $(g,b)$ to the sample space and make all events equiprobable.


text:
Q: Parametric System of differential equation, finally plotting against the parameter Below is the mathematica code for Parametric System of differential equations with parameter e. I want to find Re[g[[1]] for different values of e ..... But there is no syntax like table in Matlab.
  m = 3.5;
     pot[x_] := -(I*x)^m;
     d = 9;
     zaf = Table[
     sol1 =
          NDSolve[{sy''[x] + sy[x]*(e - (pot[x])) == 0, sy[0] == 1,
            sy'[0] == 0},
           {sy}, {x, 0, d}];
         u1 = sy[d] /. sol1; pu1 = sy'[d] /. sol1;
         sol2 =
          NDSolve[{fy''[x] + fy[x]*(e - (pot[x])) == 0, fy[0] == 0,
            fy'[0] == 1},
           {fy}, {x, 0, d}];
         v1 = fy[d] /. sol2; pv1 = fy'[d] /. sol2;
         sol3 =
          NDSolve[{ty''[x] + ty[x]*(e - (pot[x])) == 0, ty[0] == 1,
            ty'[0] == 0},
           {ty}, {x, 0, -d}];
         u2 = ty[-d] /. sol3; pu2 = ty'[-d] /. sol3;
         sol4 =
          NDSolve[{zy''[x] + zy[x]*(e - (pot[x])) == 0, zy[0] == 0,
            zy'[0] == 1},
           {zy}, {x, 0, -d}];
         v2 = zy[-d] /. sol4; pv2 = zy'[-d] /. sol4;
         f = v1/u1 - v2/u2;
         g = v1*u2 - v2*u1;
         {e, Re[g[[1]]]}, {e, 0.8, 30, .01}]


text:
Q: Reading Binary Plist files with Python I am currently using the Plistlib module to read Plist files but I am currently having an issue with it when it comes to Binary Plist files.
I am wanting to read the data into a string to later to be analysed/printed etc. I am wondering if their is anyway of reading in a Binary Plist file without using the plutil function and converting the binary file into XML?
Thank you for your help and time in advance.

A: Although you specified no plutil, a working solution with it may be useful to others as it's preinstalled on Macs:
import json
from subprocess import Popen, PIPE

def plist_to_dictionary(filename):
    "Pipe the binary plist through plutil and parse the JSON output"
    with open(filename, "rb") as f:
        content = f.read()
    args = ["plutil", "-convert", "json", "-o", "-", "--", "-"]
    p = Popen(args, stdin=PIPE, stdout=PIPE)
    out, err = p.communicate(content)
    return json.loads(out)

print plist_to_dictionary(path_to_plist_file)

A: Biplist https://github.com/wooster/biplist available via easy-install or pip.

A: I might be 10 years late to answer this question, but for anyone who is looking for this, plistlib is what you're looking for.

A: You can use the tool plutil (from libplist from http://www.libimobiledevice.org/) to convert binary to xml plist files (and vice-versa).

A: You may look at CFBinaryPList.c source file to see how it is implemented in C.
Based on the file, its format goes like:
HEADER
    magic number ("bplist")
    file format version (currently "0?")

OBJECT TABLE
    variable-sized objects

    Object Formats (marker byte followed by additional info in some cases)
    null    0000 0000           // null object [v"1?"+ only]
    bool    0000 1000           // false
    bool    0000 1001           // true
    url 0000 1100   string      // URL with no base URL, recursive encoding of URL string [v"1?"+ only]
    url 0000 1101   base string // URL with base URL, recursive encoding of base URL, then recursive encoding of URL string [v"1?"+ only]
    uuid    0000 1110           // 16-byte UUID [v"1?"+ only]
    fill    0000 1111           // fill byte
    int 0001 0nnn   ...     // # of bytes is 2^nnn, big-endian bytes
    real    0010 0nnn   ...     // # of bytes is 2^nnn, big-endian bytes
    date    0011 0011   ...     // 8 byte float follows, big-endian bytes
    data    0100 nnnn   [int]   ... // nnnn is number of bytes unless 1111 then int count follows, followed by bytes
    string  0101 nnnn   [int]   ... // ASCII string, nnnn is # of chars, else 1111 then int count, then bytes
    string  0110 nnnn   [int]   ... // Unicode string, nnnn is # of chars, else 1111 then int count, then big-endian 2-byte uint16_t
    string  0111 nnnn   [int]   ... // UTF8 string, nnnn is # of chars, else 1111 then int count, then bytes [v"1?"+ only]
    uid 1000 nnnn   ...     // nnnn+1 is # of bytes
        1001 xxxx           // unused
    array   1010 nnnn   [int]   objref* // nnnn is count, unless '1111', then int count follows
    ordset  1011 nnnn   [int]   objref* // nnnn is count, unless '1111', then int count follows [v"1?"+ only]
    set 1100 nnnn   [int]   objref* // nnnn is count, unless '1111', then int count follows [v"1?"+ only]
    dict    1101 nnnn   [int]   keyref* objref* // nnnn is count, unless '1111', then int count follows
        1110 xxxx           // unused
        1111 xxxx           // unused

OFFSET TABLE
    list of ints, byte size of which is given in trailer
    -- these are the byte offsets into the file
    -- number of these is in the trailer

TRAILER
    byte size of offset ints in offset table
    byte size of object refs in arrays and dicts
    number of offsets in offset table (also is number of objects)
    element # in offset table which is top level object
    offset table offset


text:
Q: Use PHP to edit a specific line in a file I have a php file that has an array in it. I'd like to be able to add an item to that array using a simple form.
Here is an example similar to my array:
$list = array("BA0UKSF","BA9IHHE","BAC8GMB","BAC8HMC","BAC8HMC","BAC8HMC","BACI60T","BAEIDFD","BAEIEFE","BAEIEFE","BAMB0","BAOUKSE","BAOUKSF","BAPQADL","BAPQADM","BUNDLE","CN3ICDC","CN3ICDCA","CN7IZDPA","CN8ID42","CN8ID72","CNECBCBA");

I'd like to add the new item to the array someplace either at the beginning or end of the array list.
I know how to pass the forms data to php but what I dont know is how to get php to open this file, locate the array and add something to it.

A: I'd just store your array data in JSON format what makes it very easy to operate on the array.
Reading array:
$list = json_decode(file_get_contents($file));

Saving array:
file_put_contents($file, json_encode($list));

Reasons:

*

*It is very bad practice to patch PHP code. (difficult to maintain; will possibly stop to work as you change the code in the file etc.)

*If your input you add to $list is user-input and not 100% validated, it may be malicious code in it...

A: You can parse the text file line by line and locate the array first. And then, you can simply use:

*

*array_push() -- if you want to add elements to the end of the array

*array_unshift() - if you want to add elements to the beginning of the array

Examples:
array_push($list, "CN7IZDPA"); //adding to the end

array_unshift($list, "CN7IZDPA"); //adding to the beginning

But reading your array definition from a text file seems like a bad idea. You really should use a database as it makes managing the stuff easier.
Hope this helps!


text:
Q: PIT test says Minion exited abnormally due to TIMED_OUT I have added mutation test plugin to Springboot app's pom. When I do mvn clean install, build passes but it is taking too long to complete install. Below are the logs and configuration for pit tests. I have same config for other apps and I don't have any issue with the other apps(it doesn't take more than 3-5 minutes)
[INFO] Tests run: 34, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO]
[INFO] --- pitest-maven:1.5.2:mutationCoverage (default) @ appName ---
[INFO] Found plugin : Default csv report plugin
[INFO] Found plugin : Default xml report plugin
[INFO] Found plugin : Default html report plugin
[INFO] Found plugin : Static initializer code detector plugin
[INFO] Found plugin : Static initializer filter plugin
[INFO] Found plugin : Excluded annotations plugin
[INFO] Found plugin : Try with resources filter
[INFO] Found plugin : Inlined finally block filter plugin
[INFO] Found plugin : Implicit null check filter
[INFO] Found plugin : Method reference null check filter
[INFO] Found plugin : For each loop filter
[INFO] Found plugin : Enum constructor filter
[INFO] Found plugin : Logging calls filter
[INFO] Found plugin : Infinite for loop filter
[INFO] Found plugin : Long running iterator loop filter
[INFO] Found plugin : For loop counter filter
[INFO] Found plugin : Kotlin junk mutations filter
[INFO] Found plugin : Max mutations per class limit
[INFO] Found plugin : Equals shortcut equivalent mutant filter
[INFO] Found plugin : Trivial return vals equivalence filter
[INFO] Found plugin : Mutant export plugin
[INFO] Found shared classpath plugin : Default mutation engine
[INFO] Found shared classpath plugin : JUnit 5 test framework support
[INFO] Found shared classpath plugin : JUnit plugin
[INFO] Found shared classpath plugin : TestNG plugin
[INFO] Adding org.pitest:pitest-junit5-plugin to SUT classpath
[INFO] Adding org.pitest:pitest to SUT classpath
[INFO] Mutating from C:\dev-workspace\appName\target\classes
8:54:12 AM PIT >> INFO : Verbose logging is disabled. If you encounter a problem, please enable it before reporting an issue.
8:54:14 AM PIT >> INFO : Sending 22 test classes to minion
8:54:14 AM PIT >> INFO : Sent tests to minion
8:54:14 AM PIT >> INFO : MINION : 8:54:14 AM PIT >> INFO : Checking environment

8:54:14 AM PIT >> INFO : MINION : 8:54:14 AM PIT >> INFO : Found  28 tests

8:54:14 AM PIT >> INFO : MINION : 8:54:14 AM PIT >> INFO : Dependency analysis reduced number of potential tests by 0

8:54:14 AM PIT >> INFO : MINION : 8:54:14 AM PIT >> INFO : 28 tests received

/8:55:13 AM PIT >> INFO : MINION : 8:55:13 AM PIT >> WARNING : More threads at end of test (14) com.org.xyz.controller.QuestionControllerIT than start. (6)

|8:56:22 AM PIT >> INFO : MINION : 8:56:22 AM PIT >> WARNING : More threads at end of test (27) com.org.xyz.controller.ResponseControllerIT than start. (14)

|8:56:22 AM PIT >> INFO : Calculated coverage in 129 seconds.
8:56:22 AM PIT >> INFO : Incremental analysis reduced number of mutations by 0
8:56:22 AM PIT >> INFO : Created  10 mutation test units
8:57:42 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
8:57:53 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
8:59:01 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
8:59:24 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
9:00:20 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
9:00:54 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
9:01:38 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
9:02:25 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
9:02:57 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
9:03:56 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
9:04:16 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
9:05:26 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
9:13:29 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
9:13:32 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
9:14:47 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
9:15:04 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
9:16:05 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
9:16:29 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
9:17:27 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
9:17:49 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
9:18:48 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
9:20:07 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
9:21:27 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
9:22:46 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
9:24:06 AM PIT >> WARNING : Minion exited abnormally due to TIMED_OUT
/================================================================================
-9:25:25 AM PIT >> INFO : Completed in 1872 seconds
- Mutators
================================================================================
> org.pitest.mutationtest.engine.gregor.mutators.BooleanTrueReturnValsMutator
>> Generated 3 Killed 2 (67%)
> KILLED 2 SURVIVED 1 TIMED_OUT 0 NON_VIABLE 0
> MEMORY_ERROR 0 NOT_STARTED 0 STARTED 0 RUN_ERROR 0
> NO_COVERAGE 0
--------------------------------------------------------------------------------
> org.pitest.mutationtest.engine.gregor.mutators.EmptyObjectReturnValsMutator
>> Generated 12 Killed 12 (100%)
> KILLED 10 SURVIVED 0 TIMED_OUT 2 NON_VIABLE 0
> MEMORY_ERROR 0 NOT_STARTED 0 STARTED 0 RUN_ERROR 0
> NO_COVERAGE 0
--------------------------------------------------------------------------------
> org.pitest.mutationtest.engine.gregor.mutators.VoidMethodCallMutator
>> Generated 36 Killed 24 (67%)
> KILLED 6 SURVIVED 12 TIMED_OUT 18 NON_VIABLE 0
> MEMORY_ERROR 0 NOT_STARTED 0 STARTED 0 RUN_ERROR 0
> NO_COVERAGE 0
--------------------------------------------------------------------------------
> org.pitest.mutationtest.engine.gregor.mutators.NullReturnValsMutator
>> Generated 14 Killed 14 (100%)
> KILLED 11 SURVIVED 0 TIMED_OUT 3 NON_VIABLE 0
> MEMORY_ERROR 0 NOT_STARTED 0 STARTED 0 RUN_ERROR 0
> NO_COVERAGE 0
--------------------------------------------------------------------------------
> org.pitest.mutationtest.engine.gregor.mutators.MathMutator
>> Generated 2 Killed 0 (0%)
> KILLED 0 SURVIVED 2 TIMED_OUT 0 NON_VIABLE 0
> MEMORY_ERROR 0 NOT_STARTED 0 STARTED 0 RUN_ERROR 0
> NO_COVERAGE 0
--------------------------------------------------------------------------------
> org.pitest.mutationtest.engine.gregor.mutators.BooleanFalseReturnValsMutator
>> Generated 2 Killed 1 (50%)
> KILLED 1 SURVIVED 1 TIMED_OUT 0 NON_VIABLE 0
> MEMORY_ERROR 0 NOT_STARTED 0 STARTED 0 RUN_ERROR 0
> NO_COVERAGE 0
--------------------------------------------------------------------------------
> org.pitest.mutationtest.engine.gregor.mutators.NegateConditionalsMutator
>> Generated 11 Killed 11 (100%)
> KILLED 9 SURVIVED 0 TIMED_OUT 2 NON_VIABLE 0
> MEMORY_ERROR 0 NOT_STARTED 0 STARTED 0 RUN_ERROR 0
> NO_COVERAGE 0
--------------------------------------------------------------------------------
================================================================================
- Timings
================================================================================
> scan classpath : < 1 second
> coverage and dependency analysis : 2 minutes and 9 seconds
> build mutation tests : < 1 second
> run mutation analysis : 29 minutes and 2 seconds
--------------------------------------------------------------------------------
> Total  : 31 minutes and 12 seconds
--------------------------------------------------------------------------------
================================================================================
- Statistics
================================================================================
>> Generated 80 mutations Killed 64 (80%)
>> Ran 120 tests (1.5 tests per mutation)
[INFO]
[INFO] --- maven-jar-plugin:2.6:jar (default-jar) @ appName ---
[INFO] Building jar: C:\dev-workspace\appName\target\appName.jar
[INFO]
[INFO] --- spring-boot-maven-plugin:1.5.5.RELEASE:repackage (default) @ appName ---
[INFO]
[INFO] --- maven-install-plugin:2.5.2:install (default-install) @ appName ---
[INFO] Installing C:\dev-workspace\appName\target\appName.jar to C:\Users\userId\.m2\repository\com\org\appName\1.0.8-SNAPSHOT\appName-1.0.8-SNAPSHOT.jar
[INFO] Installing C:\dev-workspace\appName\pom.xml to C:\Users\userId\.m2\repository\com\org\appName\1.0.8-SNAPSHOT\appName-1.0.8-SNAPSHOT.pom
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  34:03 min
[INFO] Finished at: 2021-01-15T09:25:28-06:00
[INFO] ------------------------------------------------------------------------

            <plugin>
                <groupId>org.pitest</groupId>
                <artifactId>pitest-maven</artifactId>
                <version>1.5.2</version>
                <executions>
                    <execution>
                        <phase>test</phase>
                        <goals>
                            <goal>mutationCoverage</goal>
                        </goals>
                    </execution>
                </executions>
                <dependencies>
                    <dependency>
                        <groupId>org.pitest</groupId>
                        <artifactId>pitest-junit5-plugin</artifactId>
                        <version>0.12</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <mutationThreshold>0</mutationThreshold>
                    <threads>2</threads>
                    <testPlugin>junit</testPlugin>
                    <outputFormats>
                        <outputFormat>XML</outputFormat>
                        <outputFormat>HTML</outputFormat>
                    </outputFormats>
                   //someClasses for test
                </configuration>
            </plugin>
            <!-- Mutation -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>3.0.0-M2</version>
                <configuration>
                    <includes>
                        <include>**/**IT.java</include>
                        <include>**/**Test.java</include>
                    </includes>
                </configuration>
            </plugin>


text:
Q: jQuery - Assign label text jQuery 1.7.1 - I have an array of input text elements (class - pr) and same number of array elements for label (class - err). I have some validation on blur of the text box and would like to assign a error message to the label associated with the text box. The following jQuery code is not working.
HTML

            <input type="text" class="pr" name="prd" />

jQuery
$("input.pr:text").blur(function(event){
    // .... validation code
    var index = $.inArray(this, $("input.pr:text"));
    $("label.err")[index].show();
    $("label.err")[index].text("Enter a number");
 });

A: One liner:
$('label.err').eq(index).show().text('Enter a number');

or probably better:
$("input.pr:text").blur(function(event){
     $(this).prev('label').show().text("Enter a number");
});

A: Once you reference a JQuery object using the index, it's no longer a JQuery object but a plain DOM element.  Use the following instead:
var el = $($("label.err")[index]);
el.show();
el.text("Enter a number");


text:
Q: Check if DB is available I need to check if a postgres db is available.
If the db is online, I get the timestamp.
If the db is offline, I get a laravel PDO Exception
But every time I get a Exception and the script execution stops
try
{
    $con = new PDO("pgsql:host=".$db->Host.";port=".$db->Port.";dbname=postgres", $db->Username, $db->Password, [PDO::ATTR_TIMEOUT => '5']);

    $dt = new \DateTime(null, new \DateTimeZone('Europe/Berlin'));

    return $dt->getTimestamp();
}
catch(Exception $e)
{
    return false;
}
catch(PDOException $e)
{
    return false;
}

A: Try to prepend \ infront of the exceptions:
try
{
    $con = new PDO("pgsql:host=".$db->Host.";port=".$db->Port.";dbname=postgres", $db->Username, $db->Password, [PDO::ATTR_TIMEOUT => '5']);

    $dt = new \DateTime(null, new \DateTimeZone('Europe/Berlin'));

    return $dt->getTimestamp();
}
catch(\Exception $e)
{
    return false;
}


text:
Q: Getting specific elements in selenium I am trying to get the elements displayed as N06D-X N07X R01A-C01 S01G-X01 in the following image:
Now, I got something like the WebDriver in this way:
 who = driver.find_element_by_tag_name("span").find_elements_by_tag_name("p")
and get an output like this:
[<selenium.webdriver.remote.webelement.WebElement (session="1c044455cf883fdedf6845bcd456bfab", element="0.23338884730774767-2")>]

I am working on Mac Catalina and when I type: who.text it returns an empty list for some reason. I got quite similar troubles with Bs but I solved them with .string rather than .text. Here .string does not work on WebDriver elements.
The question is: how can I get the items N06D and so on with selenium?

A: Seems you were pretty close enough.
[<selenium.webdriver.remote.webelement.WebElement (session="1c044455cf883fdedf6845bcd456bfab", element="0.23338884730774767-2")>]

represents the element where as you were looking for the text within the element.
To extract the texts e.g. N06D-X, N07X, etc from all of the <p> tags using Selenium and python you have to induce WebDriverWait for visibility_of_all_elements_located() and you can use either of the following Locator Strategies:

*

*Using CSS_SELECTOR and get_attribute("innerHTML"):
print([my_elem.get_attribute("innerHTML") for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.CSS_SELECTOR, "li.data-list__property#who-atc-codes span.data-list__property-value p")))])

*Using XPATH and text attribute:
print([my_elem.text for my_elem in WebDriverWait(driver, 20).until(EC.visibility_of_all_elements_located((By.XPATH, "//li[@class='data-list__property' and @id='who-atc-codes']//span[@class='data-list__property-value']//p")))])

*Note : You have to add the following imports :
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Outro
Link to useful documentation:

*

*get_attribute() method Gets the given attribute or property of the element.

*text attribute returns The text of the element.

*Difference between text and innerHTML using Selenium

A: you dont search in whole website but in previously found object
li_object = driver.find_elements_by_id('who-atc-codes')
lst = li_object.find_element_by_tag_name("span").find_elements_by_tag_name("p")

for p in lst:
    print(p.text)
    print(p.get_attribute('innerHTML'))

or you can try
span_object = li_object.find_element_by_tag_name("span")
print(span_object.get_attribute('innerHTML'))

A: Use following css selector to get list of items and then iterate.
To get the text You can use either .text or .get_attribute("innterHTML") or .get_attribute("textContent")
Code:
items=driver.find_elements_by_css_selector("span.data-list__property-value>p")
for item in items:
    print(item.text)
    print(item.get_attribute("innterHTML"))
    print(item.get_attribute("textContent"))
    #To get only value from string use spilt and take the first element.
    print(item.text.strip().split(" ")[0])
    print(item.get_attribute("innterHTML").strip().split(" ")[0])
    print(item.get_attribute("textContent").strip().split(" ")[0])


text:
Q: Anaconda 3 : Failed to create menus I am getting error "Failed to create menus" while installing Anaconda3 on windows 7 64-bit.
Error details is shown below:
Creating Anaconda3 menus...

Error loading Python DLL 'C:\Users\dell\AppData\Local\Temp_MEI29922\python36.dll'.
  LoadLibrary: The specified procedure could not be found.

A: I had the same issue and none of the usual troubleshooting (admin rights, path, etc.) worked. Apparently it is related to the latest version distributions (2019.7, 2019.10 and possibly others).
Installing version 2019.3 from Anaconda Installer Archive (https://repo.anaconda.com/archive/) worked for me. Hope this helps.


text:
Q: Pik not installing latest patch level for ruby version 1.9.3 I used RailsInstaller (for Windows) to set up my environment for my Rails 3 app.  I recently installed Pik so that I can update my ruby version as well.
According to the Pik docs https://github.com/vertiginous/pik/wiki/Usage, running 'pik install ruby 1.9.3' should install lastest version of ruby (or atleast the latest patch level for the version I am specifying).
However, this only installs ruby 1.9.3p429, but I understand that 1.9.3p545 is available.
Does anyone know how I can install 1.9.3p545?
Thanks!

A: Looks like you went with Pik from your previous question. I read on another thread that Pik only supports some of the 1.9.3 patch levels, but unfortunately nothing verifiable. The project has also been abandoned, no longer maintained, which might explain why that latest patch isn't supported...
Might just be my perspective, but seems like Windows is very poorly supported in the Rails/Ruby world? Our project requires Windows and Linux support which is causing us lots of grief. If you find a solid & reliable upgrade solution for Windows I would be very interested!


text:
Q: App crashes on other devices but work perfectly on my device I have made an android app that find atm, banks around your current location or custom location. but when I click on the button the app crashes on other devices not on my device
this is My logcat
FATAL EXCEPTION: main
                                                                                Process: com.example.udaygarg.locationplacedetailsv2, PID: 27580java.lang.NullPointerException
    at com.example.udaygarg.locationplacedetailsv2.StartActivity.onClick(StartActivity.java:158)
                                                                                at android.view.View.performClick(View.java:4438)
                                                                                at android.view.View$PerformClick.run(View.java:18439)
                                                                                at android.os.Handler.handleCallback(Handler.java:733)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                                at android.os.Looper.loop(Looper.java:136)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5146)
                                                                                at java.lang.reflect.Method.invokeNative(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:515)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:796)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:612)
                                                                                at dalvik.system.NativeStart.main(Native Method)

this is the layout file activity_start.xml
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:orientation="vertical" >

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="ATM"
            android:id="@+id/button"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:textSize="15dp"
            android:layout_centerVertical="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignRight="@+id/button4"
            android:layout_alignEnd="@+id/button4" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Airport"
            android:id="@+id/button2"
            android:layout_alignTop="@+id/button"
            android:layout_centerHorizontal="true"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:textSize="15dp" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Bank"
            android:id="@+id/button3"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:layout_alignTop="@+id/button2"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_alignLeft="@+id/button6"
            android:layout_alignStart="@+id/button6"
            android:textSize="15dp" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:text="Bus Station"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:id="@+id/button4"
            android:layout_below="@+id/button"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:textSize="15dp" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Doctor"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:id="@+id/button5"
            android:layout_alignBottom="@+id/button4"
            android:layout_alignRight="@+id/button2"
            android:layout_alignEnd="@+id/button2"
            android:textSize="15dp" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hospital"
            android:id="@+id/button6"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_alignTop="@+id/button5"
            android:textSize="15dp" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Find new location"
            android:id="@+id/button8"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:layout_below="@+id/editText"
            android:layout_toRightOf="@+id/button2"
            android:layout_toEndOf="@+id/button2"
            android:layout_marginTop="54dp" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Church"
            android:id="@+id/button9"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/button4"
            android:layout_alignRight="@+id/button4"
            android:layout_alignEnd="@+id/button4"
            android:textSize="15dp" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Gym"
            android:id="@+id/button10"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:layout_below="@+id/button4"
            android:layout_alignLeft="@+id/button5"
            android:layout_alignStart="@+id/button5"
            android:layout_alignRight="@+id/button5"
            android:layout_alignEnd="@+id/button5"
            android:layout_alignBottom="@+id/button9"
            android:textSize="15dp" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="School"
            android:id="@+id/button12"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:layout_below="@+id/button9"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignRight="@+id/button9"
            android:layout_alignEnd="@+id/button9"
            android:textSize="15dp" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Park"
            android:id="@+id/button13"
            android:layout_alignTop="@+id/button12"
            android:layout_alignLeft="@+id/button10"
            android:layout_alignStart="@+id/button10"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:layout_alignRight="@+id/button10"
            android:layout_alignEnd="@+id/button10"
            android:layout_alignBottom="@+id/button12"
            android:textSize="15dp" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Bar"
            android:id="@+id/button14"
            android:layout_alignTop="@+id/button13"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:layout_alignBottom="@+id/button13"
            android:layout_alignLeft="@+id/button6"
            android:layout_alignStart="@+id/button6"
            android:textSize="15dp" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Mosque"
            android:id="@+id/button11"
            android:layout_below="@+id/button6"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:textSize="15dp"
            android:layout_toEndOf="@+id/button10"
            android:layout_alignLeft="@+id/button14"
            android:layout_alignStart="@+id/button14" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText"
            android:hint="Enter prefered radius between 2 - 50 km"
            android:layout_alignParentTop="true"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/editText2"
            android:layout_alignBottom="@+id/button8"
            android:layout_toLeftOf="@+id/button8"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:hint="Enter location eg. sector-55,Noida/Delhi"/>

        <Button

            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Set to Current Location"
            android:id="@+id/button7"
            style="@style/Widget.AppCompat.Button.Borderless.Colored"
            android:layout_below="@+id/button8"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_toRightOf="@+id/editText2"
            android:layout_toEndOf="@+id/editText2" />

    </RelativeLayout>

manifestfile.xml
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.udaygarg.locationplacedetailsv2">

        <permission
            android:name="com.example.udaygarg.locationplacedetailsv2.permission.MAPS_RECEIVE"
            android:protectionLevel="signature"/>

        <uses-permission android:name="com.example.udaygarg.locationplacedetailsv2.permission.MAPS_RECEIVE"/>
        <uses-permission android:name="android.permission.INTERNET" />
        <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
        <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
        <uses-feature
            android:glEsVersion="0x00020000"
            android:required="true"/>

        <application
            android:allowBackup="true"
            android:icon="@mipmap/ic_launcher"
            android:label="@string/app_name1"
            android:supportsRtl="true"
            android:theme="@style/AppTheme">
            <activity android:name=".Splashscreen">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>

            </activity>
            <activity android:name=".StartActivity">

                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.DEFAULT" />
                </intent-filter>
            </activity>
            <activity android:name=".MainActivity">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
                    <category android:name="android.intent.category.DEFAULT" />
                </intent-filter>
            </activity>
            <activity
                android:name=".PlaceDetailsActivity">
                <intent-filter>
                    <action android:name=".PlaceDetails" />
                    <category android:name="android.intent.category.DEFAULT" />
                </intent-filter>
            </activity>
            <meta-data
                android:name="com.google.android.gms.version"
                android:value="@integer/google_play_services_version" />

            <meta-data
                android:name="com.google.android.maps.v2.API_KEY"
                android:value="AIzaSyBcL4XaHzcJCslvOq5Q9jfT2XIXf3TmVIo"/>
        </application>
    </manifest>

StartActivity.java
package com.example.udaygarg.locationplacedetailsv2;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import java.io.IOException;
import java.util.List;

public class StartActivity extends Activity implements View.OnClickListener, LocationListener {

    Button bt1, bt2, bt3, bt4, bt5, bt6, bt7, bt8, bt9, bt10, bt11, bt12, bt13, bt14;
    ConnectionDetector cd;
    Boolean isInternetPresent = false;
    int radius = 2;
    EditText et1, et2;
    double latitude, longitude;
    Intent in;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_start);

        bt1 = (Button) findViewById(R.id.button);
        bt1.setOnClickListener(this);

        bt2 = (Button) findViewById(R.id.button2);
        bt2.setOnClickListener(this);

        bt3 = (Button) findViewById(R.id.button3);
        bt3.setOnClickListener(this);

        bt4 = (Button) findViewById(R.id.button4);
        bt4.setOnClickListener(this);

        bt5 = (Button) findViewById(R.id.button5);
        bt5.setOnClickListener(this);

        bt6 = (Button) findViewById(R.id.button6);
        bt6.setOnClickListener(this);

        bt7 = (Button) findViewById(R.id.button9);
        bt7.setOnClickListener(this);

        bt8 = (Button) findViewById(R.id.button10);
        bt8.setOnClickListener(this);

        bt9 = (Button) findViewById(R.id.button11);
        bt9.setOnClickListener(this);

        bt10 = (Button) findViewById(R.id.button12);
        bt10.setOnClickListener(this);

        bt11 = (Button) findViewById(R.id.button13);
        bt11.setOnClickListener(this);

        bt12 = (Button) findViewById(R.id.button14);
        bt12.setOnClickListener(this);

        bt13= (Button) findViewById(R.id.button7);
        bt13.setOnClickListener(this);

        bt14= (Button) findViewById(R.id.button8);
        bt14.setOnClickListener(this);

        et1 = (EditText) findViewById(R.id.editText);
        et2 = (EditText) findViewById(R.id.editText2);

        cd = new ConnectionDetector(getApplicationContext());

    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.button) {

            isInternetPresent = cd.isConnectingToInternet();

            // check for Internet status
            if (isInternetPresent) {
                // Internet Connection is Present
                // make HTTP requests

                sendquerydata("atm", radius, latitude, longitude);

            } else {
                // Internet connection is not present
                // Ask user to connect to Internet
                showAlertDialog(StartActivity.this, "No Internet Connection",
                        "You don't have internet connection. Connect to the internet", false);
            }
        } else if (v.getId() == R.id.button8) {
            isInternetPresent = cd.isConnectingToInternet();
            if (isInternetPresent) {
                Geocoder geocoder = new Geocoder(this);
                String address = et2.getText().toString();
                List<Address> addresses = null;
                try {
                    addresses = geocoder.getFromLocationName(address, 1);
                } catch (IOException e) {
                    e.printStackTrace();
                }

                if (addresses.size() > 0) {
                    latitude = addresses.get(0).getLatitude();
                    longitude = addresses.get(0).getLongitude();
                }
                sendquerydata("", 2, latitude, longitude);
            }
            else{
                showAlertDialog(StartActivity.this, "No Internet Connection",
                        "You don't have internet connection. Connect to the internet", false);
            }

        }
        else if (v.getId() == R.id.button7) {

                LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
                if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    // TODO: Consider calling
                    //    ActivityCompat#requestPermissions
                    // here to request the missing permissions, and then overriding
                    //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                    //                                          int[] grantResults)
                    // to handle the case where the user grants the permission. See the documentation
                    // for ActivityCompat#requestPermissions for more details.
                    return;
                }
                Location location;
                location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

                latitude = location.getLatitude();
                longitude = location.getLongitude();

                sendquerydata("", 2, latitude, longitude);

            }

the app crashes on clicking button 7 and 8. please help with this, ty
ps: my first time asking a question here

A: Write a seperate function for block button 7 and button 8 and then check the permissions if not granted call requestPermissions and if user grant it call the function you privously written and if you have already granted the permission run the function immediately . Be aware you don't need check the permissions before api 23 write a if statement to check whether the SDK_INT is upper than 23 or not

A: Put the IF inside the Try above it, maybe the assignment to addresses is not working well inside the Try, so you have null addresses and here you are getting the exception


text:
Q: How to handle Platform Event while UI is being rerendered? Use case:
We have Digital Experience (i.e Community) where at first we perform the action and after it, we redirect to a new page.
This action also publishes Platform Event (Notification) which should be handled on UI. The issue is that this Event comes to the UI while new subscriber is not yet registered.
Question:
So how do you handle a Platform Event during rendering and show information from it?
Tried:
I tried using session storage to store info and then display it once the new page is loaded, but it does seem clunky.
My other ideas:
Maybe someone had similar problem and solved it via storing the last processed event id or something like that?


text:
Q: Launching system and third party apps in android I have searched ALOT now, i cant find a solid way to run apps like calendar, camera, facebook, twitter, insatgram, and all kinds of apps in android. I know that i need to use intents, but HOW can i do it? I really need help! Please help me and thanks alot!

A: There is no such concept in Android as "run apps". You start activities. Talented developers do not focus on specific apps (e.g., "facebook, twitter, insatgram"), because those apps may not exist on any given device. Instead, you focus on generic capabilities (e.g., use an ACTION_SEND Intent with startActivity() to share something, create a launcher by using PackageManager to find those activities that support ACTION_MAIN and CATEGORY_HOME).

A: If you want to launch some other application from your android application then you should know the package name for that particular application For example for launching facebook use
Intent intent = new Intent("android.intent.category.LAUNCHER");
intent.setClassName("com.facebook.katana", "com.facebook.katana.LoginActivity");
startActivity(intent);

Otherwise this can also be used
Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage("com.package.address");
startActivity(LaunchIntent);

If you want to launch the default android applications installed for some particular kind of operation then you can use implicit intents for that. For example to start a browser you can use
Uri webpage = Uri.parse("http://www.android.com");
Intent webIntent = new Intent(Intent.ACTION_VIEW, webpage);
startActivity(intent);

You should take also take a look at intents and intent filters and how to allow other apps to open your application.