text:
Q: For every real number there are exactly two isometries of the real line that leave it fixed I have some preliminary questions before I attempt this problem in my book.

If $M$ is the metric space of all the real numbers and $x_0 \in M$, prove that there exist exactly two isometries of $M$ that leave $x_0$ fixed.

For completeness, an isometry is a mapping between two metric spaces that preserves distance.
I have two questions.

*

*Am I to assume that the trivial isometry (mapping each point onto itself) "counts" as an isometry in the context of this question?

*Are the two isometries the trivial one and the one which will reflect the entire real line over the point $x_0$? Meaning the value of $x_0 + \epsilon$ is swapped with the value of $x_0 - \epsilon$ for $\epsilon > 0$.
I still have to prove that they are the only ones but I want to make sure I am on the right track.

A: An isometry $f$ on the line satisfies $|f(x) - f(y)| = |x - y|$ for any two real numbers $x$ and $y$.
If $f(x_0) = x_0$, you get $|f(x) - x_0| = |x - x_0|$. This leads to only two possible isometries: either $f(x) = x$ or $f(x) = 2x_0 - x$ which are the two you describe.


text:
Q: How to custom sort an array in C++, but leave a portion of it unsorted? I want to sort an array, but leave a part of it out. The part that is left out shall be specified by a start index (n) and an end index (m). All fields between those two indices, including the two specified ones, shall not be sorted. All others, including the ones before the interval and the ones after it, shall be sorted together.
For example:

*

*Input serial {10 , 4 , 11 , 7 , 6 , 20}

*Non-sort interval start index n = 1

*Non-sort interval end index m = 3 ,

*Output: { 6 , 4 , 11 , 7 , 10 , 20 }
The fields from index 1 to 3 with the values 4, 11, 7 are not sorted.
#include <iostream>
#include <algorithm>
using namespace std;

int main () {
    int arr[5] = {10, 4, 11, 7, 6, 20};
    sort (arr,arr+5);
    for (int i = 0; i < 5; i++){
        cout << arr[i] << " ";
    }
    return 0;
}

How can I do that?

A: Here is a way to do it using std::rotate and std::sort.
It rotates the elements that should not be sorted to the end, then sorts the beginning part and then rotates back the ones we moved.
#include <iostream>
#include <iterator>
#include <array>
#include <algorithm>

int main() {
    std::array<int, 6> arr = {10, 4, 11, 7, 6, 20};

    unsigned from = 1;
    unsigned to = 3;

    unsigned distance = to - from + 1;

    if (to + 1 != arr.size())
        std::rotate(arr.begin(), arr.begin() + to + 1, arr.end());

    std::sort(arr.begin(), arr.end() - distance);

    std::rotate(arr.begin() + from, arr.end() - distance, arr.end());

    for (auto v : arr)
        std::cout << v << ' ';
}

I used a std::array instead of a c-style array. Works on a std::vector as well.

A: This is a nice show case for a range library, e.g. Boost.Range.
We first create a slice range for the parts to be sorted left and right to the fixed part.
auto left = arr | sliced(0, n);
auto right = arr | sliced(m, 6);

Then we create a new range which joins these two slices
auto s = join(left, right);

and sort it
auto r = sort(s);

Together with output this gives us the following code using Boost.Range:
#include<iostream>
#include<algorithm>
#include <boost/range/adaptors.hpp>
#include <boost/range/algorithm.hpp>
#include <boost/range/adaptor/sliced.hpp>
#include <boost/range/algorithm/copy.hpp>
#include <boost/range/join.hpp>

using namespace boost;
using namespace boost::adaptors;

int main(){
  //define original and temp arrays
  int arr[6] = {10, 4, 11, 7, 6, 20};
  auto n = 2;
  auto m = 4;

  auto left = arr | sliced(0, n);
  auto right = arr | sliced(m, 6);
  auto s = join(left, right);

  auto r = sort(s);

  std::cout << "sorted range: ";
  boost::copy(r, std::ostream_iterator<int>(std::cout, ","));
  std::cout << std::endl;

  std::cout << "array: ";
  boost::copy(arr, std::ostream_iterator<int>(std::cout, ","));
  std::cout << std::endl;

  return 0;
}

Running the code prints
sorted range: 6,7,10,20,
array: 6,4,11,7,10,20,

It should also be very efficient since there is no extra moving or copying of data involved. I also find it very expressive.

A: You can take out the elements that you want to sort and store them in a temp array, then restructure the array in the form you need. I've provided a crude code solution; however, you should look into using std::vector or another std container (also array lengths are hardcoded, if you want to change the length of the orignal array you would need to use something like sizeof(a)/sizeof(a[0])).
#include<iostream>
#include<algorithm>

int main(){
  //define original and temp arrays
  int arr[6] = {10, 4, 11, 7, 6, 20};
  int temp[3] = {0};

  //cycle through arr, remove the static elements, and store in temp array
  int k = 0;
  for(int i = 0; i < 6; i++)
  {
    if(i > 0 && i < 4)
    {
      continue;
    }
    temp[k] = arr[i];
    k++;
  }

  //sort the temp array
  std::sort(temp, temp + 3);

  //restructure the array by placing the static elements back into the original array
  k = 0;
  for (int i = 0; i < 6; i++)
  {
    if (i > 0 && i < 4)
    {
      continue;
    }
    arr[i] = temp[k];
    k++;
  }

  //print out the sorted array with static elements
  for(int i = 0; i < 6; i++)
  {
    std::cout << arr[i] << " ";
  }

  return 0;
}

A: I provide two solutions:

*

*sort a temporary copy and put the sorted items back into the original list

*create several views of the data, and sort one of the views of the data

Solution One - Make a temporary array with entries 1 - 3 missing. Sort the temporary and put the temporary back into the original array. To make this "elegate", I use an index array which is a lookup into my original array for where to pull the values from and push the values back to:
#include <iostream>
#include <algorithm>

using namespace std;

int main(int argc, char* argv[]) {
  int arr[6] = { 10, 4, 11, 7, 6, 20 };
  int index[3] = { 0, 4, 5 };
  int tmp[3];

  for (int i = 0; i < 3; i++)
    tmp[i] = arr[index[i]];

  sort(tmp, tmp + 3);

  for (int i = 0; i < 3; i++)
    arr[index[i]] = tmp[i];

  for (int i = 0; i < 6; i++)
    cout << arr[i] << " ";

  cout << "\n";

  return 0;
}

Solution Two - Use a custom comparator to sort a the subset of the array:
#include <iostream>
#include <algorithm>

using namespace std;

bool compare(int *a, int *b) {
  return *a < *b;
}

int main(int argc, char* argv[]) {
  int arr[6] = { 10, 4, 11, 7 , 6, 20 };
  int* sorted[3] = { &arr[0], &arr[4], &arr[5] };
  int* skip[3] = { &arr[1], &arr[2], &arr[3] };
  int** arr2[6] = { &sorted[0], &skip[0], &skip[1], &skip[2], &sorted[1], &sorted[2] };

  sort(sorted, sorted + 3, compare);

  for (int i = 0; i < 6; i++)
    cout << **arr2[i] << " ";

  return 0;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Right join multiple dataframe by one column I have these three dataframes df1, df2, df3.
df1<- structure(list(ControlRate = structure(c(1L, 1L, 1L), .Label = c("24000",
"26000", "28000", "30000"), class = "factor"), Mean = c(92.914223793805,
125.810174859037, 152.350610715905)), row.names = c(NA, 3L), class = "data.frame")

df2 <- structure(list(ControlRate = structure(c(1L, 1L, 1L), .Label = c("24000",
"26000", "28000", "30000"), class = "factor"), SD = c(19.7498590603068,
33.5137097117632, 40.4792131612947)), row.names = c(NA, 3L), class = "data.frame")

df3 <- structure(list(ControlRate = structure(c(1L, 1L, 1L), .Label = c("24000",
"26000", "28000", "30000"), class = "factor"), Count = c(36L,
117L, 198L)), row.names = c(NA, 3L), class = "data.frame")

Instead of using cbind(df1,df2$SD, df3$Count), I wanted to use merge as below but it doesn't work. What am I doing wrong here?
Reduce(function(dtf1, dtf2) merge(dtf1, dtf2, by = "ControlRate", all.x = TRUE),
       list(df1, df2, df3))

A: library(tidyverse)

list(df1,df2,df3) %>%
  map(rowid_to_column) %>%
  reduce(left_join, by = c("rowid","ControlRate")) %>%
  select(-rowid)

#>   ControlRate      Mean       SD Count
#> 1       24000  92.91422 19.74986    36
#> 2       24000 125.81017 33.51371   117
#> 3       24000 152.35061 40.47921   198


text:
Q: Error download file PDF in Yii2: Unknown Method I want to download file PDF from frontend/web/uploads. And I have an error in the controller (maybe):

Calling unknown method: frontend\controllers\BukuController::findModel()

This is my source code:
BukuController.php
public function actionDownload($id)
{
    $model = $this->findModel($id);
    $file ='../frontend/uploads/'.$model->file_buku;

    if(file_exists($file))
    {
        return Yii::$app->response->sendFile($file);
        exit;
    }
}

And this is function in views, views/buku/index.php:
<?= Html::a('Download', ['download','id'=> $buku->file_buku]); ?>

(Solved)

A: As the error state, you missing in your BukuController method called findModel.
This method should search the model in the DB.
Something like this:
protected function findModel($id)
{
    if (!is_null($model = Buku::findOne($id))) {
        return $model;
    }
    throw new NotFoundHttpException('The requested page does not exist.');
}

Of course if your model is not Buku, you need to change it relatively, and also import it in the top of the controller file:
use app\models\Buku; // Basic application.
use common\models\Buku; // Advanced application when models store in common folder.
use frontend\models\Buku; // Advanced application when models store in frontend folder.

A: Change $file variable to this.
$file =Yii::$app->getBasePath().'/web/uploads/'.$model->file_buku;


text:
Q: How to transform SSE assembly code to AVX1/2 assembly code? I'm trying to convert a function from AVX to AVX2, in NASM or MASM (Intel syntax). In particular:
vmovapd xmm0, XMMWORD PTR [rax]

works like a charm.
vmovapd ymm0, YMMWORD PTR [rax]

throws an exception:

Exception levée à 0x00007FF73F7818EC dans x64asm.exe : 0xC0000005 :
  Violation d'accès lors de la lecture de l'emplacement
  0xFFFFFFFFFFFFFFFF.

I don't understand what I did wrong.

A: It's OK, it was due to misaligned arrays.
Thank you for your time and your explanation.


text:
Q: What's the difference between "insight of something" and "insight into something"? I use the phrase insight of for the sentence "It gives me an insight of what college life should like." but Grammarly change it into "an insight into". Under which content we use them?

A: The noun insight does not take the preposition of.
Grammarly is right.

A: Beware of Grammarly and other sites providing software that purports to give advice on how to write English. Grammarly provides no credentials for its staff and purports to be AI driven, a technique that fails to capture the complexity of English idiom.
The Corpora of Contemporary American English finds 46 prepositions that can follow the word insight. Note that the preposition into contributes 75% of the text examples. This is actually an underestimate since what we're really talking about is a preposition that introduces the area illuminated by the insight. The preposition of, for instance, usually reports who has had the insight:

The insight of the researchers into the mechanism of the chemical interactions.

But not always. See example 8 below, from the following list.

*

*ON

*IN

*TO

*ABOUT

*REGARDING

*CONCERNING

*TOWARD

*OF

[1] By reminding us that the [Republican P]arty was not always broken, such a history might offer some insight on how to make repairs. (New York Times, 1/4/15)
[2] Longer follow up data in Syrian refugees will provide more insight in the outcome of these patients. (Kidney Blood Pressure Research, 3/1/19)
[3] [S]everal businesses that worked on the reservation before moving their operation over to the WMSP [White Mountain Stewardship Project] provided insight to the Tribe's contributions. (Journal of Forestry, Vol. 115, Iss. 6, Nov 2017)
[4] Sylvia Plath gave mental illness an aura of nonconformity, creativity, and even acute insight about social and political affairs. (Journal of American Culture, March 2014, Vol 37, Issue 1)
[5] Those models may provide insight regarding quantitative changes one might expect on multiple time scales. (Physics Today, 2011)
[6] Analyzing this pre-post measure provides valuable insight concerning the state-of-mind of the individual prior to entering the student experience (Education, Vol 114, Issue 2, Winter 1993)
[7] Educators who value the input from parents providing unique insight toward their children will likely be able to create effective programs.... (Education, Vol 127 Issue 1, Fall 2006)
[8] In order to gain full insight of the informant's perspective and understanding of the course, his journals, midterm examinations, and term papers were examined. (Journal of Instructional Psychology, Vol 41 Issue 1-4, 2014)


text:
Q: How can I get values from two observables sequentially? I'm a newbie with RxJs.
My purpose is : (1) make a first call backend and get value, then (2) based on the returned value, make an other call backend and return both values as an array.
When I subscribe, I would like get both values : building and buildingUnit.
This is the way of I trying to achieve this purpose :
this._buildingsService.loadBuilding(1).pipe(
  mergeMap((b: Building) => {
    if (b) {
      return this._buildingUnitsService.loadBuildingUnit(b);
    }
  })
).subscribe((bu: BuildingUnit) => {

});

The kind of result that I would like to get back :
this._buildingsService.loadBuilding(1).pipe(
  mergeMap((b: Building) => {
    if (b) {
      return this._buildingUnitsService.loadBuildingUnit(b);
    }
  })
).subscribe((b: Building, bu: BuildingUnit) => {

});

Thank you

A: You could use forkJoin to pass both values back:
this._buildingsService.loadBuilding(1).pipe(
  mergeMap((b: Building) => forkJoin({
    b: of(b),
    bu: b ? this._buildingUnitsService.loadBuildingUnit(b) : of(null)
  }))
).subscribe((result: { b: Building, bu: BuildingUnit  }) => {

});

DEMO: https://stackblitz.com/edit/angular-p5vtej

A: You can just map the second value into an array.
this._buildingsService.loadBuilding(1).pipe(
  mergeMap((b: Building) => {
    if (b) {
      return this._buildingUnitsService.loadBuildingUnit(b).pipe(
        map(c => [b, c]),
      );
    }
    return of([b]); // or `[b, undefined]` to be more obvious
  })
  .subscribe(([b, c]) => {
    // ...
  })


text:
Q: Href links inside my mobile menu bar doesn't work $(document).click(function (event) {
    if ($("#sidenav").width() != 0) {
        $("#sidenav").css({ 'width': '0' });

    }
});

$("#sidenav").click(function (e) {
    e.stopPropagation();
    return false;

});

$("#navHome").click(function () {
    $("#navHome").attr("href", "/public/templates/default/index.html");
    $("#sidenav").css({ 'width': '0' });
});

1) The $(document).click(function (event) function closes the nav bar if user click anywhere outside the navbar
2)  The $("#sidenav").click(function (e) function prevents nav bar from closing if user click anywhere inside the navbar
3)  Now because of the e.stopPropagation(); in the second function, when I click on the navHome it did close the navBar but didn't take me to the index page. In other words, $("#navHome").attr("href","/public/templates/default/index.html"); doesn't work.
Is there a work around for this? Thanks!

A: Do not cancel the click if the target is a link
$("#sidenav").click(function (e) {
  if(!$(e.target).closest("a").length) {
    e.stopPropagation();
    return false;
  }
});


text:
Q: Disabling an extension manually in Chrome Im trying to disable the extension StayFocused, because it is blocking me after a reinstall of my system and it didn't save my settings for some reason.
Im trying to remove this extention altogether now but I can't remove it because it blocks me when I go to chrome://extensions. I will wait until tomorrow and try removing it, but there should be a way to remove extensions in any case, be it manually?!
Windows 10 64-Bit, Chrome Version 53

A: it's
chrome://extensions
and you are typing
chrome://extentions ,which is wrong.
Alternatively, press Ctrl+H and on the left hand side, select extensions.

A: The solution that worked for me is to delete the folder of the StayFocused extension. They seem to be saved on Win10 at: C:\Users\%%USERNAME%%\AppData\Local\Google\Chrome\User Data\Default\Extensions
Inside each folder seems to be a folder with the extension version. Currently this was 1.5.7 for StayFocused, so I looked through each folder and found the one with this version number. Delete then restart the computer and remove the extension from Chrome inside the now working extensions tab.


text:
Q: Android: ACTION_TIME_TICK in AppWidget I've got a clock in my widget that I'm making and I want it to update every minute in sync with the system clock. ACTION_TIME_TICK seems like the perfect solution however much of my research says it's impossible in an AppWidget while others say there are workarounds but their very vague.
I'd prefer not to do an AlarmManager as I'd have to update very frequently to make sure that it changes minutes when the system clock changes minutes and that would drain the battery more.
Is there a workaround for ACTION_TIME_TICK or what's the best way to update every minute in sync with the system clock with minimal battery drain?

A:
Is there a workaround for ACTION_TIME_TICK

ACTION_TIME_TICK can only be registered via registerReceiver() from something that is already running. In your case, that "something" would need to be a constantly-running Service, and that's generally an anti-pattern. Users and the OS can get rid of that service when desired.
I would find a way to lightly relax the "in sync with the system clock" requirement, then use AlarmManager. After all, Android is not a RTOS, so nothing will be "in sync with the system clock" in any guaranteed sense.
Using AlarmManager, you would specify the first alarm to be the "top" of the next minute, with a period of 60 seconds and setRepeating(). Or, you would set(), scheduled for the "top" of the next minute, then schedule the next one via set() as part of your own processing, if you think you can manually correct for drift better that way.

A: if you just need to display it when your app runs then just update it using asyncTask
but if you need it's value even in the background then using service would be the best idea


text:
Q: Unable to Connect to Mongo Atlas from GCP App Engine I am trying to connect a nodejs app running on GCP App Engine to Mongo Atlas but I am receiving network errors. I have set up VPC Peering and have enabled a Serverless VPC connector and added the vpc_access_connector property in the app yaml and have whitelisted the IP range of the connector within Atlas. The exact error that I am seeing is
> MongoNetworkError: failed to connect to server [testcluster-shard-00-00-fbyja.gcp.mongodb.net:27017] on first connect
> [MongoNetworkError: connection 4 to testcluster-shard-00-00-fbyja.gcp.mongodb.net:27017 closed]

and the code I have is
var express = require("express");
var app = express();
require('dotenv').config();
var cors = require('cors');
const BodyParser = require('body-parser');
const MongoClient = require("mongodb").MongoClient;
const ObjectId = require('mongodb').ObjectID;
const CONNECTION_URL = process.env.DB_CONNECTION;

app.use(cors());
app.use(BodyParser.json());
app.use(BodyParser.urlencoded({extended: true}));

var database, collection;

app.listen(process.env.PORT, () => {
    MongoClient.connect(CONNECTION_URL, {useNewUrlParser: true}, (error, client) => {
        if(error){
            throw error;
        }
        database = client.db("test");
        collection = database.collection("test");
    })
});

A: Unfortunately, you cannot configure a peering connection for M0/M2/M5 in Atlas.

Network Peering Connections   You cannot configure Set up a Network Peering Connection on M0 Free Tier or M2/M5 shared clusters.

Moreover, since you are using App Engine, your application is behind GCP's load balancers and you won't be able to whitelist a stable set of static IP.
Possible solutions at this point:

*

*Upgrade your Atlas cluster to an M10 to get access to the peering feature. This could cost you ~60USD/month

*If it is not for production and you don't want to put money into this, I would suggest you using a free tier instance to deploy your app, then whitelist its IP for the Atlas clustier tier

A: Although you can not use GCP VPC Network Peering for Mo/M2/M5 clusters in Atlas.
You can set up a Cloud NAT with a static IP that connects with the VPC Network. You can add the static IP of your Cloud NAT to Atlas IP whitelist.


text:
Q: How can I include templates from one of my dependencies as part of my bundle using Rollup? I'm trying to create a bundled app using rollup and one of my dependencies have a reference to an internal templates directory. When I run rollup -c I can see the following line:
xi(Ni(__dirname, "./templates/footer.hbs"), "utf-8") ])

which references this (btw this is the node_modules structure):

I've tried using a handlebars plugin but can't seem to make it work.
Files that might be useful
rollup.config.ts
// rollup.config.js
import typescript from "@rollup/plugin-typescript";
import { terser } from "rollup-plugin-terser";
import { nodeResolve } from "@rollup/plugin-node-resolve";
import json from "@rollup/plugin-json";
import commonjs from "@rollup/plugin-commonjs";
import handlebars from 'rollup-plugin-handlebars';

export default {
  input: "src/main.ts",
  output: {
    dir: "dist",
    format: "cjs",
    sourcemap: true,
  },
  plugins: [
    typescript(),
    json(),
    nodeResolve({ preferBuiltins: true, mainFields:  ["main", "module"] }),
    commonjs({
      defaultIsModuleExports: true,
      include: 'node_modules/**',
    }),
    terser({
      format: {
        beautify: true,
      },
      module: true,
      compress: {
        join_vars: false, // If true, this gives an error during runtime
      },
      mangle: {
        keep_classnames: true, // If false, Shows "unknown target" error during runtime
      },
    }),
    handlebars(),
  ],
};


text:
Q: How to get a Fisherman Villager in Minecraft I need to know which Profession and Career number it is.

A: /summon villager ~ ~ ~ {Profession:0,Career:2}

list of profession and career IDs:

Assign CareerLevel to unlock more trades at start.

A: The Fisherman is a subset of the brown coat villager, The brown coat's profession id is 0, while the fisherman subset (Career) is 2, so to summon one, you need to do this:
/summon villager <x y z coordinates> {Profession:0,Career:2}

Hopefully I Helped.
Ref: http://minecraft.gamepedia.com/Villager#Professions_and_careers

A: The Fisherman is a subset of the Brown Robed Villager and is listed as the second career number for the Brown Robed Villager.
via http://minecraft.gamepedia.com/Trading


text:
Q: How to subclass QMessageBox and run operation before closing I would like to launch a process within a QMessageBox subclass before it returns via the AcceptRole. It's not clear to me why the following does not work:
class Question(QtGui.QMessageBox):

    def __init__(self, text):
        QtGui.QMessageBox.__init__(self, QtGui.QMessageBox.Question,
           "title", text, buttons=QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel)
        self.text = text

    def accept(self):

        # run opertation
        print self.text

        QtGui.QMessageBox.accept(self)

dial = Question("text")
dial.exec_()

Since the buttonRole for QMessageBox.Ok is AcceptRole, I would expect accept() to be called. Is this not the case?
Any insight would be appreciated.

A: You have the right idea. You just need to reimplement the virtual done() slot, rather than the virtual accept() slot:
class Question(QtGui.QMessageBox):
    def __init__(self, text):
        QtGui.QMessageBox.__init__(
            self, QtGui.QMessageBox.Question, "title", text,
            buttons=QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel)
        self.text = text

    def done(self, result):
        print self.text
        QtGui.QMessageBox.done(self, result)

The result will be StandardButton value of the button that was clicked (i.e. QMessageBox.Ok or QMessageBox.Cancel, in the above example).


text:
Q: Convert 32 bit binary to a decimal in python how do I convert Convert 32 bit binary to a decimal in python
this
00011110001101110110110000001000

to
506948616
this

A: use in-built function int():
a = '00011110001101110110110000001000'
a_dec = int(a, 2)

A: use int for conversion of a string (just give the correct base as parameter):
int('00011110001101110110110000001000', 2)

Another way is to add 0b as a prefix for the number (same as 0x for hex values or 0o for octal values):
x=0b00011110001101110110110000001000

x will be an integer with decimal value of 506948616


text:
Q: what to do when two elements have same resource id in appium? what to do when the resource-id of two elements in list view in UIAutomator of appium is same??
here in the images below:-
both the elements have same resource id:-net.one97.paytm:id/smart_list_root

A: In this case, you can use xpath or name like below:
Way 1:
driver.findElement(By.xpath("//android.widget.TextView[@text='Mobile Prepaid']"));
driver.findElement(By.xpath("//android.widget.TextView[@text='Mobile Postpaid']"));

Way 2:
driver.findElement(By.name("Mobile Prepaid"));
driver.findElement(By.name("Mobile Postpaid"));

A: Get the text using xpath:
String text = driver.findElement(By.xpath("//android.widget.RelativeLayout")).getText();

Compare the text and select the correct UIElement to perform desired action.

if(text.equals("Mobile Prepaid")){
   ......
}

A: Take it with multiple elements for xpath for textview as
"//android.widget.TextView[@text='Mobile Prepaid']"

Hope it will work

A: You can use By.name like,
driver.findElement(By.name("Mobile Prepaid"));
driver.findElement(By.name("Mobile Postpaid"));

A: String ac = driver.findElement(By.xpath("(//*[@resource-id = 'account-balance-amount'])[1]")).getText();

String ac = driver.findElement(By.xpath("(//*[@resource-id = 'account-balance-amount'])[2]")).getText();


text:
Q: Create a TimeSerie using an index and values from different TimeSeries, with different indices I want to create a DataFrame or TimeSerie using an index of an existing TimeSerie and the values from another TimeSerie with different time indices. The TimeSeries look like;
 <class 'pandas.core.series.Series'>
DT
2018-01-02    172.3000
2018-01-03    174.5500
2018-01-04    173.4700
2018-01-05    175.3700
2018-01-08    175.6100
2018-01-09    175.0600
2018-01-10    174.3000
2018-01-11    175.4886
2018-01-12    177.3600
2018-01-17    179.2500
2018-01-18    180.1000
...

and
<class 'pandas.core.series.Series'>
DT
2018-01-02        NaN
2018-01-09    175.610
2018-01-16    177.360
2018-01-23    180.100
...

I want to use the index from the first TS and fill it with the values from the second TS. If an index can't be found in the first TS, it should use the next available date in this TS. Like;
<class 'pandas.core.series.Series'>
DT
2018-01-02   NaN
2018-01-03   NaN
2018-01-04   NaN
2018-01-05   NaN
2018-01-08   NaN
2018-01-09   175.610
2018-01-10   NaN
2018-01-11   NaN
2018-01-12   NaN
2018-01-17   177.360
2018-01-18   NaN
...

Thx

A: My idea is to use reindex twice:
second_ts.reindex(first_ts.index, method='ffill').drop_duplicates().reindex(first_ts.index)


text:
Q: Map doesn't insert where expected I have this block of text and I want to remove the ", :focus " from the line.
describe "#reminder_types", :focus do
end

Previously what I'd done is:
f,
d2t  " there is a space after the t

This is something I do often enough that I thought I'd set up a map. I enter:
:nmap ,s 0\|f,\|d2t

When I call my map, it deletes text from the start of the line, not from where the comma is. So my line ends up being:
 "#reminder_types", :focus do

The map does correctly position the cursor on the line if I change the map to:
    0\|f,
Thanks!

A: Get rid of all the \|, they don't do what you think they do.
:nmap ,s 0f,d2t

I'm actually not sure what it does but it as if you typed 0\|f,\|d2t in normal mode which isn't what you want. You just want 0f,d2t typed in normal mode.
Bar is used to separate commands on the command line, however nmap takes everything as a normal mode command and you don't need to separate normal mode commands.


text:
Q: Load python 2.7 class from python 3.4 jupyter notebook I'm using the Jupyter Notebook to write some Python 3.4 code, but I have to load a class that has been written in Python 2.7.
The class I'm trying to load was not written by me so I can't really (or want) to upgrade all the code to Python 3.4. The use of that class is very limited throughout the rest of the code and is just used to return some data that is compatible with Python 3.4.
I have 2 questions:

*

*Is there any way I can run a single cell in Python 2.7 and then use the output of that cell throughout the rest of the notebook script?

*If not do you have any suggestion?

Desired usage:
+++++ Python 2.7 cell +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
In[1]: #load the class
       my_class = MYCLASS()
       #use the class to get 3.4 compatible data
       data_list = my_class.produce_data()

+++++ Python 3.4 cell ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
In[2]: #use the data list in a 3.4 way
       for x in data_list:
           print(x)

I found a similar question, Calling Python 2 script from Python 3, but no real solution was provided besides a couple hacks in the comments.
NOTE: This question is completely unrelated to Using both Python 2.x and Python 3.x in IPython Notebook, which is about how to use both languages and not about how to reference one from the other.

A: Reposting as an answer:
If you have both versions of Python installed, you can put %%python2 at the top of a cell to run it in Python 2. However, that code will be run in a separate process, so you'll need to write the data out (e.g. using pickle) and then read it in again in your Python 3 code.
Docs for the %%python2 magic are here:
http://ipython.readthedocs.org/en/stable/interactive/magics.html#cellmagic-python2


text:
Q: Emacs calendar: show more than 3 months? In Emacs, when you display the calendar with M-x calendar, you get a three-month display – last month, this month, and next month – in a new window that's just 8 lines tall.
Is it possible to generate a twelve-month calendar in a full-size window?

A: 12-MONTH CALENDAR -- SCROLLS BY MONTH (FORWARDS / BACKWARDS)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;;                                                                            ;;;
;;; Scroll a yearly calendar by month -- in a forwards or backwards direction. ;;;
;;;                                                                            ;;;
;;; To try out this example, evaluate the entire code snippet and type:        ;;;
;;;                                                                            ;;;
;;;     M-x year-calendar                                                      ;;;
;;;                                                                            ;;;
;;; To scroll forward by month, type the key:  >                               ;;;
;;;                                                                            ;;;
;;; To scroll backward by month, type the key:  <                              ;;;
;;;                                                                            ;;;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

(eval-after-load "calendar" '(progn
  (define-key calendar-mode-map "<" 'lawlist-scroll-year-calendar-backward)
  (define-key calendar-mode-map ">" 'lawlist-scroll-year-calendar-forward) ))

(defmacro lawlist-calendar-for-loop (var from init to final do &rest body)
  "Execute a for loop.
Evaluate BODY with VAR bound to successive integers from INIT to FINAL,
inclusive.  The standard macro `dotimes' is preferable in most cases."
  `(let ((,var (1- ,init)))
    (while (>= ,final (setq ,var (1+ ,var)))
      ,@body)))

(defun year-calendar (&optional month year)
  "Generate a one (1) year calendar that can be scrolled by month in each direction.
This is a modification of:  http://homepage3.nifty.com/oatu/emacs/calendar.html
See also:  http://ivan.kanis.fr/caly.el"
(interactive)
  (require 'calendar)
  (let* ((current-year (number-to-string (nth 5 (decode-time (current-time)))))
         (month (if month month
           (string-to-number
             (read-string "Please enter a month number (e.g., 1):  " nil nil "1"))))
         (year (if year year
           (string-to-number
             (read-string "Please enter a year (e.g., 2014):  "
               nil nil current-year)))))
    (switch-to-buffer (get-buffer-create calendar-buffer))
    (when (not (eq major-mode 'calendar-mode))
      (calendar-mode))
    (setq displayed-month month)
    (setq displayed-year year)
    (setq buffer-read-only nil)
    (erase-buffer)
    ;; horizontal rows
    (lawlist-calendar-for-loop j from 0 to 3 do
      ;; vertical columns
      (lawlist-calendar-for-loop i from 0 to 2 do
        (calendar-generate-month
          ;; month
          (cond
            ((> (+ (* j 3) i month) 12)
              (- (+ (* j 3) i month) 12))
            (t
              (+ (* j 3) i month)))
          ;; year
          (cond
            ((> (+ (* j 3) i month) 12)
             (+ year 1))
            (t
              year))
          ;; indentation / spacing between months
          (+ 5 (* 25 i))))
      (goto-char (point-max))
      (insert (make-string (- 10 (count-lines (point-min) (point-max))) ?\n))
      (widen)
      (goto-char (point-max))
      (narrow-to-region (point-max) (point-max)))
    (widen)
    (goto-char (point-min))
    (setq buffer-read-only t)))

(defun lawlist-scroll-year-calendar-forward (&optional arg event)
  "Scroll the yearly calendar by month in a forward direction."
  (interactive (list (prefix-numeric-value current-prefix-arg)
                     last-nonmenu-event))
  (unless arg (setq arg 1))
  (save-selected-window
    (if (setq event (event-start event)) (select-window (posn-window event)))
    (unless (zerop arg)
      (let ((month displayed-month)
            (year displayed-year))
        (calendar-increment-month month year arg)
        (year-calendar month year)))
    (goto-char (point-min))
    (run-hooks 'calendar-move-hook)))

(defun lawlist-scroll-year-calendar-backward (&optional arg event)
  "Scroll the yearly calendar by month in a backward direction."
  (interactive (list (prefix-numeric-value current-prefix-arg)
                     last-nonmenu-event))
  (lawlist-scroll-year-calendar-forward (- (or arg 1)) event))

A: There doesn't seem to be an easy way to do this. I was able to knock up the following code, which will show all twelve months, in a row, in a separate frame.
(require 'cl)
(require 'calendar)

(defun twelve-month-calendar ()
  (interactive)
  (let ((calendar-buffer (get-buffer-create "12-month calendar"))
        (month 12)
        (year 2012))
    (set-buffer calendar-buffer)
    (setq calendar-frame (make-frame))
    (make-variable-buffer-local 'font-lock-face)
    (set-face-attribute 'default calendar-frame :height 70)
    (set-frame-width calendar-frame 300)
    (erase-buffer)
    (dotimes (i 12)
      (calendar-generate-month month year 0)
      (calendar-increment-month month year -1))
    (calendar-mode)))

You might need to tweak it a bit, depending on your screen/font size.

A: I modified "12-MONTH CALENDAR -- SCROLLS BY MONTH (FORWARDS / BACKWARDS)" answer and adapted it to Emacs post 23.3 version - no calendar-for-loop macro - and changed scroll from by one month to by one year. This version show entire calendar for current year. Going backwards which < and forwards > by one year. It doesn't show on full screen, but half screen, which make it easy to use when working which vertical splits and it's more like extended version of build in calendar.
;; https://stackoverflow.com/questions/9547912/emacs-calendar-show-more-than-3-months
(defun farynaio/year-calendar (&optional year)
  "Generate a one year calendar that can be scrolled by year in each direction.
This is a modification of:  http://homepage3.nifty.com/oatu/emacs/calendar.html
See also: https://stackoverflow.com/questions/9547912/emacs-calendar-show-more-than-3-months"
  (interactive)
  (require 'calendar)
  (let* (
      (current-year (number-to-string (nth 5 (decode-time (current-time)))))
      (month 0)
      (year (if year year (string-to-number (format-time-string "%Y" (current-time))))))
    (switch-to-buffer (get-buffer-create calendar-buffer))
    (when (not (eq major-mode 'calendar-mode))
      (calendar-mode))
    (setq displayed-month month)
    (setq displayed-year year)
    (setq buffer-read-only nil)
    (erase-buffer)
    ;; horizontal rows
    (dotimes (j 4)
      ;; vertical columns
      (dotimes (i 3)
        (calendar-generate-month
          (setq month (+ month 1))
          year
          ;; indentation / spacing between months
          (+ 5 (* 25 i))))
      (goto-char (point-max))
      (insert (make-string (- 10 (count-lines (point-min) (point-max))) ?\n))
      (widen)
      (goto-char (point-max))
      (narrow-to-region (point-max) (point-max)))
    (widen)
    (goto-char (point-min))
    (setq buffer-read-only t)))

(defun farynaio/scroll-year-calendar-forward (&optional arg event)
  "Scroll the yearly calendar by year in a forward direction."
  (interactive (list (prefix-numeric-value current-prefix-arg)
                     last-nonmenu-event))
  (unless arg (setq arg 0))
  (save-selected-window
    (if (setq event (event-start event)) (select-window (posn-window event)))
    (unless (zerop arg)
      (let* (
              (year (+ displayed-year arg)))
        (jarfar/year-calendar year)))
    (goto-char (point-min))
    (run-hooks 'calendar-move-hook)))

(defun farynaio/scroll-year-calendar-backward (&optional arg event)
  "Scroll the yearly calendar by year in a backward direction."
  (interactive (list (prefix-numeric-value current-prefix-arg)
                     last-nonmenu-event))
  (farynaio/scroll-year-calendar-forward (- (or arg 1)) event))

(define-key calendar-mode-map "<" 'farynaio/scroll-year-calendar-backward)
(define-key calendar-mode-map ">" 'farynaio/scroll-year-calendar-forward)

(defalias 'year-calendar 'farynaio/year-calendar)

A: It's not easy to do this, the code to generate calendar is:
(defun calendar-generate (month year)
  "Generate a three-month Gregorian calendar centered around MONTH, YEAR."
  ;; A negative YEAR is interpreted as BC; -1 being 1 BC, and so on.
  ;; Note that while calendars for years BC could be displayed as it
  ;; stands, almost all other calendar functions (eg holidays) would
  ;; at best have unpredictable results for such dates.
  (if (< (+ month (* 12 (1- year))) 2)
      (error "Months before January, 1 AD cannot be displayed"))
  (setq displayed-month month
        displayed-year year)
  (erase-buffer)
  (calendar-increment-month month year -1)
  (dotimes (i 3)
    (calendar-generate-month month year
                             (+ calendar-left-margin
                                (* calendar-month-width i)))
    (calendar-increment-month month year 1)))

Here, (dotimes (i 3) ...) generate 3 months in a row.
So if you want to generate more than 3 months in more than 1 row, you must override calendar-generate function by yourself, same as @Luke said.


text:
Q: Execute sql file on SQL Server using C# I have many files for procedures, views, functions, etc.
I want to execute these files (creating components) in appropriate database on SQL Server 2005/2008.
Also the point is I want to execute them using C#.
Another point to mention, I want the application to be such that I can execute this files on a remote SQL Server too. Also client machine may not have osql,sqlcmd command tool.
Can someone please guide me on this.

A: This depends on what sort of files they are. If, for example, they only contain actual T-SQL commands (and aren't batch files that you'd run in, say, SSMS, which would contain a batch separator like GO), then you just need to create a connection, a command, then read the contents of the file and use that to populate the CommandText property of the command.
For example:
void ExecuteFile(string connectionString, string fileName)
{
    using(SqlConnection conn = new SqlConnection(connectionString))
    {
        string data = System.IO.File.ReadAllText(fileName);

        conn.Open();

        using(SqlCommand cmd = conn.CreateCommand())
        {
            cmd.CommandText = data;
            cmd.ExecuteNonQuery();
        }
    }
}

If it's a batch file, you'll need to split the file into individual batches and process those individually. The simplest method is just to use string.Split, but bear in mind that it won't respect SQL parsing rules when it splits (for example, if GO appears within a SQL statement, it's going to split the command up into two batches, which will obviously fail).
More generally, you can see what you'd need to do here by modifying the code in this way:
string[] batches = SplitBatches(System.IO.File.ReadAllText(fileName));

conn.Open();

using(SqlCommand cmd = conn.CreateCommand())
{
    foreach(string batch in batches)
    {
        cmd.CommandText = batch;
        cmd.ExecuteNonQuery();
    }
}

The implementation of a function called SplitBatches is up to you.

A: Typically, the simplest way is to split the script on the "GO" statement and execute each item separately. This solution will not work if the script contains a GO statement within a comment.
private readonly Regex _sqlScriptSplitRegEx = new Regex( @"^\s*GO\s*$", RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled );
public void ExecuteSqlScript( string scriptText )
{
    if ( string.IsNullOrEmpty( scriptText ) )
        return;

    var scripts = _sqlScriptSplitRegEx.Split( scriptText );
    using ( var conn = new SqlConnection( "connection string" ) )
    {
        using ( var ts = new TransactionScope( TransactionScopeOption.Required, new TimeSpan( 0, 10, 0 ) ) )
        {
            foreach ( var scriptLet in scripts )
            {
                if ( scriptLet.Trim().Length == 0 )
                    continue;

                using ( var cmd = new SqlCommand( scriptLet, conn ) )
                {
                    cmd.CommandTimeout = this.CommandTimeout;
                    cmd.CommandType = CommandType.Text;
                    cmd.ExecuteNonQuery();
                }
            }

            ts.Complete();
        }
    }
}

A: Normally all you have to do is just execute them with SqlCommand.ExecuteNonQuery, one batch at a time. That leaves you the task of splitting the scripts into batches, using the currently set batch delimiter (usually GO). The free library dbutilsqlcmd can be used to handle SQL scripts, as it processes not only the delimiter, but SQLCMD extensions as well (:setvar, :connect etc).

A: Using standard ADO would "work" -- SQL DDL can be sent using SqlCommand.ExecuteNonQuery, for instance.
...but I'd recommend using a Database Project (with a remote staging deploy or VSDBCMD) or one of the tools such as SQLCMD (perhaps in conjunction with a PowerShell script :-) or SQL Management Studio, etc. They are designed for this sort of stuff.

A: You could read in the commands using a TextReader, then use ExecuteNonQuery with the TextReader results as the command.


text:
Q: Get JSon child with PHP echo from an API Okay so bascially I have this structure as JSon from an API:
{
    "tag": "8L9L9GL",
    "name": "Jo͛hͥn̽",
    "trophies": 5338,
    "rank": 291,
    "arena": {
        "name": "Master II",
        "arena": "League 5",
        "arenaID": 17,
        "trophyLimit": 5200
    },
    "clan": {
        "tag": "2U2GGQJ",
        "name": "Reddit Bravo",
        "role": "coLeader",
        "donations": 0,
        "donationsReceived": 0,
        "donationsDelta": 0,
        "badge": {
            "name": "A_Char_Rocket_02",
            "category": "03_Royale",
            "id": 16000167,
            "image": "https://cr-api.github.io/cr-api-assets/badges/A_Char_Rocket_02.png"
        }
    },

I'm trying to get the Clan -> Name but it isn't working with this code in PHP:
echo "
".$json->clan['name']."
";

How could I make it work?

A: Try this:
$json->clan->name

A: <?php
$json = '{
    "tag": "8L9L9GL",
    "name": "Jo͛hͥn̽",
    "trophies": 5338,
    "rank": 291,
    "arena": {
        "name": "Master II",
        "arena": "League 5",
        "arenaID": 17,
        "trophyLimit": 5200
    },
    "clan": {
        "tag": "2U2GGQJ",
        "name": "Reddit Bravo",
        "role": "coLeader",
        "donations": 0,
        "donationsReceived": 0,
        "donationsDelta": 0,
        "badge": {
            "name": "A_Char_Rocket_02",
            "category": "03_Royale",
            "id": 16000167,
            "image": "https://cr-api.github.io/cr-api-assets/badges/A_Char_Rocket_02.png"
        }
    }
}';

$json = json_decode($json);
echo $json->clan->name;

// Reddit Bravo
If you want to use $json['clan']['name']; then you have to set the assoc param like:
$json = json_decode($json, true);
echo $json['clan']['name'];

// Reddit Bravo

A: Depending on your particular call to json_decode(), if you've used...
$json = json_decode($jsonData,true);

then use
echo "
".$json['clan']['name']."
";

Else if you've used...
$json = json_decode($jsonData);

then use
echo "
".$json->clan->name."
";

If using the first call, then you create an associative array and so use array access method.  If you don't pass true as the second parameter, this creates the structure as objects and so use the second method of access.

A: You will have to json_decode the same and use it.
Following is the piece of code
echo json_decode($json)->clan->name;

Stitch it into your HTML as
echo "
".json_decode($json)->clan->name."
";

Tested this snippet. Should work for you too.


text:
Q: How can I pass parameters between two activities? I am trying to pass parameters between two activities which are tabs of tabhost. How do I send a value correctly from an activity (Active.java) to a second  activity (Active2.java)? What did I do wrong?

Active.java
public class Active extends Activity {

   private Intent intent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_active);

      // intent = new Intent(this,Active2.class);
      intent = getParent().getIntent();
    }
    public void Location(View view) {

    final LocationManager LocMgr = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        final LocationListener LocList = new LocationListener() {

            @Override
            public void onLocationChanged(Location location) {

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

                LatLng point = new LatLng(latitude, longitude);
                intent.putExtra("point", point);
                intent.putExtra("Active",1);
                TabActivity ta = (TabActivity) Active.this.getParent();
                ta.getTabHost().setCurrentTab(1);
           }
    };
}

Active2.java
public class Active2 extends Activit {

  private GoogleMap googleMap;
  private GoogleApiClient client;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_active2);

      getFragmentManager().findFragmentById(R.id.map)).getMap();
      client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
      updateGoogleMap();
    }
   void updateGoogleMap ()
   {

     Bundle extras = getIntent().getExtras();
      if(null !=extras) {

          LatLng point = (LatLng) extras.get("point");
          TextView text = (TextView) findViewById(R.id.GpsStat) ;
          text.setText("bylem");

          googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
          googleMap.addMarker(new MarkerOptions().position(point).title("point"));
      }
  }
}

A: Firstly i want to say that you have lots of error in your code. yo should make more improvement in its quality. read more.
now answer to your question.

*

*You have to start the activity in Active.java to send it to Active2.java activity.

*You have to give create new intent in Active.java and this will help you to put all the intent values into the intent.

*Then you can start the startActivity() and start the Active2.java.

*Then only you will have those values in the Active2.java and you can retrive all those values here.

so it would be like this
in Active.java
    Intent intent = new intent(Active.this,Active2.class);
    intent.putExtra("point", point);
    intent.putExtra("Active",1);
    startActivity(intent);

in Active2.java
    Intent intent=getIntent();
    String point=intent.getStringExtra("point");
    int Active=intent.getIntExtra("Active");


text:
Q: Basic compile issue with QT4 I've been trying to get a dead simple listing from a university textbook to compile with the newest QT SDK for Windows I downloaded last night. After struggling through the regular nonsense (no make.bat, need to manually add environment variables and so on) I am finally at the point where I can build. But only one of the two libraries seem to work.
The .pro file I use is dead simple:
SUBDIRS += utils \
           dataobjects

TEMPLATE = subdirs

In each of these two subfolders I have the source for a library. Running QMAKE generates a makefile and running Make runs through all the preliminaries and then fails on the g++ call:
g++ -enable-stdcall-fixup -Wl,-enable-auto-import -Wl,-enable-runtime-pseudo-reloc --out-implib,libdataobjects.a -shared -mthreads -Wl -Wl,--out-implib,c:\Users\Cobus\workspace\lib\libdataobjects.a -o ..\..\lib\dataobjects.dll object_script.dataobjects.Debug  -L"c:\Users\Cobus\Portab~1\Qt\2010.02.1\qt\lib" -LC:\Users\Cobus\workspace\lib -lutils -lQtXmld4 -lQtGuid4 -lQtCored4
c:/users/cobus/portab~1/qt/2010.02.1/mingw/bin/../lib/gcc/mingw32/4.4.0/../../../../mingw32/bin/ld.exe: cannot find -lutils

The problem seems to be right near the end of the command line, where -lutils is added, indicating that there is a library by the name of utils. While I would have expected to see that, you'll notice the library names after --out include lib in the name, so they become libutils and libdataobjects. I have tried to figure out why this is happening, to no avail.
Anyone have an idea what's going on?

A: Their seems to be another pro file as the generated Makefile is pulling QtXml which it wont do by default.
Please check the subdirs for any .pro or .pri files .. one of them will have answer to your confusion

A: You .pro file uses the SUBDIRS template which requires a .pro file matching the directory name for each subdir.  You should have a utils\utils.pro and dataobjects\dataobject.pro file as well.
Is c:\Users\Cobus\workspace\lib\libdataobjects.a built correctly?  If not, check the sub directory .pro files.
With what you posted, I would not expect anything to compile.  You need targets in the sub-directory .pro files to build anything.


text:
Q: Save User Data using SharedPreferences I am writing an app to save password with a login interface. The user can change the login password. First time, I use the following code to save the password, so that the password will not reset when the app relaunch:
@Override
public void onSaveInstanceState(Bundle savedInstanceState){
    savedInstanceState.putString("pwd", currentPwd);
    super.onSaveInstanceState(savedInstanceState);
}

@Override
public void onRestoreInstanceState(Bundle savedInstanceState){
    currentPwd = savedInstanceState.getString("pwd");
}

But after I asked that, someone in this website suggested me to use "SharedPreferences". So, I changed the code as follow:
@Override public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.main);
    SharedPreferences settings = getSharedPreferences("setting", 0);
    currentPwd = settings.getString("pwd", "abc");
}

@Override public void onStop(){
    super.onStop();
    SharedPreferences settings = getSharedPreferences("setting", 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putString("pwd", currentPwd);
    editor.commit();
}

After my experiment, I found that the password will be reset after one hour which the same as the first code. Have I changed it wrong for the second code? Or there are any suggested way to solve it? Thank you.

A: Not sure I'm following your code, but here is how I would do this:
To get password:
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
sp.getString("pwd", "abc");

To set password:
SharedPreferences.Editor editor = sp.edit();
editor.putString("pwd", currentPwd);
editor.commit();

Hope that helps

A: You can save value using bellow function.It contains only context, key and the value:
public void savePreferencesForReasonCode(Context context,
    String key, String value) {
    SharedPreferences sharedPreferences = PreferenceManager
    .getDefaultSharedPreferences(context);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
    editor.commit();
    }

To get more see this Answer


text:
Q: Mining a Dataframe for a Count of Unique Words I'm looking to take a set of strings in a dataframe and then break those strings up in order to get a count of distinct words in the strings. The ultimate idea is this:
Word 1: 5 times
Word 2: 3 times
Word 3: 10 times
...
Word n: 13 times
The ultimate goal is to take this set of strings, then extend the analysis into groupings of 2 words, 3 words, and so on.
I've tried multiple packages, including Pandas, re, collections and so on, but nothing seems to get me where I need.
import pandas as pd

import re

fPath = 'path\there'
fName = '\BuzzWords.xlsx'

importExcel = pd.read_excel(fPath+fName, sheetname = 'DATA')
importExcel.sort_index(inplace = True)

bWList = ['words','things']

pattern = '(?i)('+'|'.join(bWList)+')'

minerFrame = importExcel[0:0]

dFCounter = max(importExcel.index)

for i in range(0,dFCounter+1):

    temp = importExcel[i:i+1]

    checker = temp[temp['description'].str.contains(pattern)]

    checker2 = checker.isnull().sum().sum()

    if checker2 > 0:
        minerFrame = minerFrame.append(temp)

minerFrame = minerFrame.reset_index(drop = True)

That code should, ultimately lead to this kind of result:
Word 1: 10
Word 2: 20
Word 3: 14
...
2-Word-Combo: 10
2-Word-Combo: 15
...
3-Word-Combo: 30
3-Word-Combo: 40
...
etc.
I appreciate your help!

A: As @Chris mentioned, the Counter object from collections library will return a dictionary of unique words, with a count of them.  So you could do something like:
from collections import Counter

#...
bwDict = {}
for word in bwList:
    bwDict[word] = 0

for i in range(0,dFCounter+1):

    content = importExcel.loc[i, 'description']
    for key, val in Counter(content).items():
        if key in bwDict.keys():
            bwDict[key] += val

This won't return the combinations count, but your existing code using re library should return that.


text:
Q: Getting [: !=: unary operator expected in a shell script I am writing a simple shell script to send me an email in case my server has gone down, but for some reason I'm getting a syntax error, I'm not sure why..

./reverse-proxy-test.sh: line 26: [: !=: unary operator expected

status="$(curl -Is --connect-timeout 5 --max-time 5 http://192.168.1.11/ | head -1)"
validate=( $status )

if [ ${validate[1]} != "301" ]; then
  mail -s 'curl failed for - Reverse proxy!!' martin@gmail.com <<< 'Curl failed for reverse proxy to (192.168.1.11). Server is down!!'
fi

A: You need to quote your variables!
In case ${validate[1]} is empty, your test becomes:
[ != "301" ] # syntax error

Whereas if you added double quotes "${validate[1]}", it would be:
[ '' != "301" ] # valid comparison

Since you have tagged bash then you also have the option to use an extended test [[ instead of [, which handles this case better, meaning that the quotes aren't necessary:
[[ ${validate[1]} != "301" ]]

Although it doesn't do any harm to use quotes here either, and many would recommend that you did.


text:
Q: Understanding tcpdump output on a linux router  My router has an atm0 interface and a VLAN (atm0.1) interface, atm0.1 has the WAN IP address.
When using tcpdump -i atm0, the packets captured are only outgoing packet (LAN to WAN).
05:34:19.504895 IP 10.110.51.83 > 74.125.71.104: ICMP echo request, id 768, seq 29184, length 40
05:34:20.506885 IP 10.110.51.83 > 74.125.71.104: ICMP echo request, id 768, seq 29440, length 40
05:34:21.507868 IP 10.110.51.83 > 74.125.71.104: ICMP echo request, id 768, seq 29696, length 40

When using tcpdump -i atm0.1, the packets captured include both outgoing packets and incoming packets.
05:36:33.517705 IP 10.110.51.83 > 74.125.71.104: ICMP echo request, id 768, seq 30208, length 40
05:36:33.827969 IP 74.125.71.104 > 10.110.51.83: ICMP echo reply, id 768, seq 30208, length 40
05:36:34.519715 IP 10.110.51.83 > 74.125.71.104: ICMP echo request, id 768, seq 30464, length 40
05:36:34.685847 IP 74.125.71.104 > 10.110.51.83: ICMP echo reply, id 768, seq 30464, length 40
05:36:35.521643 IP 10.110.51.83 > 74.125.71.104: ICMP echo request, id 768, seq 30720, length 40
05:36:35.679061 IP 74.125.71.104 > 10.110.51.83: ICMP echo reply, id 768, seq 30720, length 40

Why?
linux version is 2.6.30, atm driver are from broadcom.

A: This is not uncommon. The point where libpcap sets up a hook to intercept network traffic may not be always the right one to capture all the traffic.
After all, virtual interfaces are just a set of functions - usually optimized for speed - not to create a perfect replica of a physical interface.
Asymmetric traffic capture may happen with vlans, tun/tap interfaces and bridges.
Always try capturing in promiscuous mode or normal mode.

A: This is happening because the path of the traffic is:
application -> atm0 -> atm0.1 -> destination
destination -> atm0.1 -> application


text:
Q: Is there any relation between LJU (Line Jack Unit) and broadband speed? My question is about LJU (Line Jack Unit) aka Rosette.
I am having BSNL (service provider company) copper line broadband in India.
In spite of having wired broadband, I get speeds of 6Mbps(download) / 0.75Mbps(upload). Upon raising the issue with officials, they checked & did not find any abnormality at their end. There are no cuts in wire running from DP.
What I did notice is -- there is no LJU (Line Jack Unit) to connect incoming copper line with telephone cable which goes to splitter.
What I wish to know is "Whether not having LJU can affect the internet speed?"
Thanks.
EDIT:- I am using ASUS DSL N10 E modem.
The first image shows incoming copper wire on left side, which is twisted with phone-wire for making connection, tape applied; phone wire (right side) has RJ11 jack on other end which goes to splitter. I have attached images.

A: Yes, there seems to be a lot of evidence that a proper NTU can affect the broadband speed.
I don't know what the rules are in India, but here in the UK it's BT's responsibility to provide and maintain the NTU that terminates the incoming phone line and consumers aren't allowed to interfere with it. The best results are reckoned to come from having a properly filtered faceplate as part of the NTU because this removes the effect of the telephone wiring as close to the entry point as possible. But in your case I wouldn't really expect a massive improvement in speed, if any, given the short length to the splitter.
But broadband speed is mainly dependent on distance to the DSLAM (either at the exchange or in a street cabinet) and the quality of cabling. Prior to rolling out street cabinets to make shorter connections, it was quite normal to get 6Mbps from broadband - and many people still can't even get that much. Have you asked your provider what speed you should be getting?

A: If your internet access is based on xDSL, any attenuation will impact the data rate you can accomplish. The data rate is usually handshaked between your xDSL Modem and the DSLAM (or whatever COE is used).
I would say it heavily depends on how you connect the copper wires to the splitter and how high quality the connection is.
I guess you're using either screw-terminals or other plugin-type direct wire terminals. Both should fit the purpose and I don't think it has great impact on the attainable data rate.
If you could share more info on your type of internet access and maybe a photo of your CPE, including the copper cables and the splitter unit and how it is connected, that might help to give a more detailed answer.


text:
Q: PHP: How to get the days of the week? I'm wanting to store items in my database with a DATE value for a certain day. I don't know how to get the current Monday, or Tuesday, etc. from the current week. Here is my current database setup.
menuentry
 id int(10) PK
 menu_item_id int(10) FK
 day_of_week date
 message varchar(255)

So I have a class setup that holds all the info then I was going to do something like this...
foreach ( $menuEntryArray as $item )
{
   if ( $item->getDate() == [DONT KNOW WHAT TO PUT HERE] )
   {
      // code to display menu_item information
   }
}

So I'm just unsure what to put in "[DONT KNOW WHAT TO PUT HERE]" to compare to see if the date is specified for this week's Monday, or Tuesday, etc.  The foreach above runs for each day of the week - so it'll look like this...
Monday
Item 1
Item 2
Item 3

Tuesday
Item 1

Wednesday
Item 1
Item 2

...

Thanks!

A: $day=date('l',strtotime($item['day_of_week']));

A: First thanks profitphp for your answer, but I was needing more. I don't think I was clear enough with my question perhaps. I finally got it working here is what I did...
function getCurrentWeek()
{
    $weekArray = array();

    // set current date1
    $date = date("m/d/Y"); //'04/30/2009';

    // parse about any English textual datetime description into a Unix timestamp
    $ts = strtotime( $date );

    // calculate the number of days since Monday
    $dow = date('w', $ts);
    $offset = $dow - 1;
    if ($offset < 0) $offset = 6;

    // calculate timestamp for the Monday
    $ts = $ts - $offset*86400;

    // loop from Monday till Sunday
    for ($i=0; $i<7; $i++, $ts+=86400){
        $temp_date = date("Y-m-d", $ts);  // here I set it to the same format as my database
        array_push( $weekArray, $temp_date );
    }

    return $weekArray;

}

Then I used that with this...
    foreach ( $menu as $item )
    {
        if ( $item->getDayOfWeek() == $weekArray[0] )
        {
            // do my stuff
        }
    }

Hope this helps someone, thanks again profitphp.


text:
Q: How do I install NetworkManager-wifi on Debian? I've been fighting my laptop for a few hours now trying to get the wifi to work. I have the drivers installed and iwlist scan manages to find the access points in the area, however NetworkManager isn't finding it.
Running nmcli shows wifi (iwlwifi), [REDACTED MAC ADDRESS], plugin missing, hw and running rpm -q NetworkManager-wifi says package NetworkManager-wifi is not installed.
Looking about online I found this https://pkgs.org/download/NetworkManager-wifi which lists the package for a number of distros to get the package for but not Debian.
What do?
EDIT
uname -a outputs
Linux TheLastMetroid 4.9.0-6-amd64 #1 SMP Debian 4.9.82-1+deb9u3 (2018-03-02) x86_64 GNU/Linux
lspci -knn | grep Net -A2 outputs
03:00.0 Network controller [0280]: Intel Corporation Wireless 3165 [8086:3165] (rev 81)
    Subsystem: Intel Corporation Dual Band Wireless AC 3165 [8086:4010]
    Kernel driver in use: iwlwifi

A: *

*You shouldn't be using rpm on Debian (the correct way to check would be apt-cache show network-manager

*If Network Manager isn't installed, you can install it using sudo apt-get install network-manager

*Network Manager is almost certainly installed since nmcli seems to be available (which is installed by the network-manager package)

*You almost certainly want to install network-manager-gnome instead, since that will give you a nice graphical interface.

*In Debian, the wifi plugin is provided by the main network-manager package as opposed to being in a separate package.

*The easiest way to install stuff in Debian is through deb files (through apt-get or aptitude), since that is what the repositories run off of. If you want to use rpms by default, you should not be using Debian (check out Fedora or similar, which use rpms by default and use a package manager such as yaourt or yum or whatever).

Hope that helps!

A: Ensure you have wireless-tools and wpasupplicant packages installed.


text:
Q: Starting with learning python on colab.google agetting error shown in screen shot i am getting this error when i am trying running this on "colab google". new to python so not exactly sure what could be the issue. it says display variable is missing.
error as below
TclError                                  Traceback (most recent call last)
<ipython-input-9-13bc468cf9c3> in <module>()
      1 import turtle
----> 2 toy = turtle.Pen()
      3 for i in range(1,40):
      4   toy.circle(100)
      5   toy.right(10)

4 frames
/usr/lib/python3.6/tkinter/__init__.py in __init__(self, screenName, baseName, className, useTk, sync, use)
   2021                 baseName = baseName + ext
   2022         interactive = 0
-> 2023         self.tk = _tkinter.create(screenName, baseName, className, interactive, wantobjects, useTk, sync, use)
   2024         if useTk:
   2025             self._loadtk()

TclError: no display name and no $DISPLAY environment variable


text:
Q: Hitting a line in a $d$ dimensional cube Let $F$ be a finite field of order $n$, and let $d$ be an integer. A line in $F^d$ is a function $\ell: F \to F^d$ given by $\ell(t) = x + t*h$, where $x,h \in F^d$, $h \neq 0$, and $t*h = (tx_1, \ldots, tx_d)$.
For $3 \le k \le n$, how many uniformly chosen points in $F^d$ are needed to be drawn such that with high probability (say $2/3$), the set of drawn points contains $k$ different points from (any) line?
Clarification: the last line refers to a set that contain at least one line (not all lines).
Edit: a rough estimation regarding the number of draws needed (e.g., $O(n^d)$, $O(n^{d/2})$, $poly(d \log n)$, $O(d \log n)$, etc.) would also be very helpful.

A: I think you need to consider arcs (when $d=2$) or caps (when $d>3$).  The normal definition of an cap is a collection of points, no three on a common line (an arc actually only coincides with this definition in a plane).  What you are interested in are the number of $(s,k-1)$-caps (common literature will refer to $(k,d)$-arcs in planes, this is a generalization); this will be a set of $s$ points such that no more than $k-1$ are on a common line. Any set of size $s$ will either be a $(s,k-1)$-cap, or else have the property you are interested in.
Unfortunately the best reference I can find is mangled in the postscript conversion (weak).
[Old answer refers to the problem of ensuring every line contains at least $k$ points]
This is not an easy problem at all. The first question would be, how many points do you need in a set $\mathcal{S}$ for it to even be possible that every line contains at least $k$ points of $\mathcal{S}$? Such a set is called a $k$-fold blocking set (with respect to lines).  You can see some details here.  I think this type of problem is more difficult in affine spaces than in projective spaces.  To do an analysis of the probability, you would need to know how many $k$-fold blocking sets of size $s$ there were, and you could compare that to ${q^d \choose s}$.
Unfortunately I can't give you an answer, just point out that these are well-studied objects (with lots of related open problems). Probably the most interesting (and well studied) area of research is on small blocking sets in projective planes (a search on google scholar for the term "blocking sets" will turn up lots of results).


text:
Q: materializecss read radio button New to materializecss, trying to read radio button and not having any luck.
<form class="main" id="sponsorform" novalidate="novalidate" style="max-width: 480px;margin: 40px auto;">
   :

Choose race to sponsor

          <input type="radio" name="race" id="wdf">
          Women's Distance Festival

          <input type="radio" name="race" id="msm">
          Market Street Mile

        <button class="waves-effect waves-light btn submit-btn" type="submit" onclick="nextOrSubmitPage(); return false;">Next</button>

When I click on one of the options, the circle gets highlighted but using chrome inspect I do not see any change to the dom.
And when I try to read I see either
$('input[name=race]:checked').val()
"on"

or I get an error `Cannot read property 'val' of null
Not sure what changes in between the two behaviors, though.`
Note: this is all within google apps script. Not sure if that is relevant or not.

A: Ok, after some hacking around, I found the following seems to work
$('input[name=race]:checked').attr('id')
Not sure if there's a better way to do this, but as I said it seems to work.

A: This may solve your problem.
$("input[name=group1]:checked").next().text();


text:
Q: JPEG-Decompression on RAW image in python When I try to JPEG-Decompress (old-style JPEG compression, not JPEG-LS and not JPEG2000) the RAW data, I get following error:
Traceback (most recent call last):
  File "raw-reader.py", line 766, in <module>
    raw_image_data = imageio.imread(io.BytesIO(raw_packed_image_data))
  File "/home/ian/.local/lib/python3.6/site-packages/imageio/core/functions.py", line 206, in imread
    reader = read(uri, format, 'i', **kwargs)
  File "/home/ian/.local/lib/python3.6/site-packages/imageio/core/functions.py", line 129, in get_reader
    return format.get_reader(request)
  File "/home/ian/.local/lib/python3.6/site-packages/imageio/core/format.py", line 168, in get_reader
    return self.Reader(self, request)
  File "/home/ian/.local/lib/python3.6/site-packages/imageio/core/format.py", line 217, in __init__
    self._open(**self.request.kwargs.copy())
  File "/home/ian/.local/lib/python3.6/site-packages/imageio/plugins/pillow.py", line 398, in _open
    pilmode=pilmode, as_gray=as_gray)
  File "/home/ian/.local/lib/python3.6/site-packages/imageio/plugins/pillow.py", line 122, in _open
    self._im = factory(self._fp, '')
  File "/home/ian/.local/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line 780, in jpeg_factory
    im = JpegImageFile(fp, filename)
  File "/home/ian/.local/lib/python3.6/site-packages/PIL/ImageFile.py", line 102, in __init__
    self._open()
  File "/home/ian/.local/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line 339, in _open
    handler(self, i)
  File "/home/ian/.local/lib/python3.6/site-packages/PIL/JpegImagePlugin.py", line 166, in SOF
    raise SyntaxError("cannot handle %d-bit layers" % self.bits)
SyntaxError: cannot handle 14-bit layers

The RAW data in the image is 14-bit JPEG data, and imageio isn't able to read it. When I tried using pillow, it didn't even recognize the data as JPEG. My question now is: How can I decompress the data without writing my own JPEG decompressor, while keeping in mind that the data is 14 bits?
My code:
import io
import imageio

allbytes = open("raw_data.dat", "rb").read()

raw_packed_image_data = allbytes
raw_image_data = imageio.imread(io.BytesIO(raw_packed_image_data))

The file raw_data.dat is a file containing purely the RAW-Image data compressed with JPEG. Link to raw_data.dat

A: raw_data.dat is a JPEG Lossless, Nonhierarchical file with 2 frames and a precision > 8-bit, a very rare format.
The imagecodecs package can read the file (assuming that the _imagecodecs Cython extension is present):
>>> from imagecodecs import jpegsof3_decode
>>> data = open('raw_data.dat', 'rb').read()
>>> image = jpegsof3_decode(data)
>>> image.shape
(3528, 2640, 2)
>>> image.dtype
dtype('uint16')

The LEADTOOLS SDK should also be able to read the file (not tested).

A: I believe the issue can be solved using a different library to load the image. Similar underlying issue has been posted here How to combine 3 high range JPEG2000 images into single RGB one?. You can use something along these lines:
import matplotlib.image as mpimg
img_red = mpimg.imread('raw_data.dat')

Then you can use the read bitmap for further manipulation as if it was loaded via PIL/Pillow/imageio.


text:
Q: Looking for a DR-like solution to enable full data warehouse re-load while having secondary copy live I am looking for suggestions/ideas to the following problem.  We have a number of data warehouses for each of our clients (on SQL Server 2014).  These data warehouses are maintained fairly fresh with continuous data loads every few minutes.  When DW needs to change, this will, more often than not, require a complete data re-load.  The challenge is that we can't afford to take DW offline for extended period of time and, consequently, make any applications, which use this data unavailable.  It is acceptable if the data is stale, but it has to be available.
Therefore, we are looking for a solution, which will enable us to maintain a secondary copy of the data warehouse.  Let's call these copies A and B.  The secondary copy (B) needs to be kept in-synch with the primary copy (A).  When the time comes to make significant DW changes, we would like for the following to happen:
1) stop synchronization between A and B
2) point our applications to the secondary copy (B)
3) perform our upgrade/maintenance/re-load of the primary copy (A)
4) point our applications back to the primary copy (A)
5) re-establish synchronization between A and B (we understand it will take some time)
So basically B acts as a temporary "fill-in" while A is being upgraded and reloaded.
The solution has to be automatable, meaning, we need to be able to do everything from a command-line/powershell.
We looked at some of the existing HA/DR technologies, for example SQL Server Always On, but it seems that breaking and re-establishing synchronization (as described above) may not be a good fit for it.  It seems that what we need is a 3rd party software, possibly capturing disk activity at the system level.
I appreciate any ideas, recommendations or experiences.
Thank you!


text:
Q: Reserved word issue with ActiveAdmin rails 3.2 I have made the following addition to my active admin interface:
action_item :only => :show do
   link_to('Approve this article', approve_admin_article_path(article)) if article.approved.nil?
end

member_action :approve, :method => :get do
  # do approval
  redirect_to :action => :show, :notice => "Approved!"
end

This throws the following error:
undefined method `approved' for
:Arbre::HTML::Article
What I think is happening is Active Admin thinks I'm passing an article tag in, not an article class?
Does anyone know of a work around for this? perhaps aliasing?
Thanks!
class Article < ActiveRecord::Base
attr_accessible :body
# Relations:
  belongs_to :articleable, polymorphic: true, :counter_cache => true
  has_many :comments, as: :commentable, order: 'created_at DESC', dependent: :destroy
# Validations
  validates_presence_of :body
  validates_length_of :body, maximum: 15000
end

A: Found a workaround
There is something fishy when you name your class as 'Article', ActiveAdmin relate to it when rendering as <article> HTML tag - The problem is somewhere in the controller of course because this is where the article object is being generated
So, I override the controller
ActiveAdmin.register Article do

  controller do
    def show
      # grabbing my desired Article and not the <article> tag into some global variable
      @@myarticle = Article.find(params[:id])
    end
  end

  sidebar :article_details , :only => :show do
    ul do
      # using the @@myarticle which I know should be initialized
      # (you can put .nil? checking here if you want)
      li link_to 'Article Images (' + @@myarticle.images.count.to_s + ')' , admin_article_article_images_path(@@myarticle)
      li link_to 'Article Clips ('+@@myarticle.clips.count.to_s + ')' , admin_article_article_clips_path(@@myarticle)
    end
  end
end

Enjoy

A: Assuming you're having the issue in the 'show' block, you could change the show block to the following:
show do |object|
end

Then you can call object.some_method without the clash. This way you don't need to override the controller.


text:
Q: why Google Ads showing less mobile page speed score? I have a website which is having 85 (Mobile) and 95 (desktop) page speed score on google page speed. But when I checked from Google ads landing page Mobile Page speed score its showing 1/10 and on few pages "-". What could be the possible reason for this issue?

A: Page speed score generates suggestions to make your page faster by recommending some of the best practises for specific page.
Where as testmysite is for entire content served from domain.
Also page speed data get updated every day where testmysite is for last month. So surely there will be difference. If you made performance improvement this month & can see changes in next month report.


text:
Q: I'm having an error first when i create a spring boot project pom.xml I ve been seeing that its a version related problem and i have tried all the solutions provided but none of them is seem to be working
here s my pom.xml

https://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

        org.springframework.boot
        spring-boot-starter-parent
        2.2.6.RELEASE

    com.finalapplication
    Fxykxll
    0.0.1-SNAPSHOT
    NewCopy
    Project copied from aicha's to make it work,the first one didnt work
<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
        <scope>runtime</scope>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>com.oracle.ojdbc</groupId>
        <artifactId>ojdbc8</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

A: Try this
<?xml version="1.0" encoding="UTF-8"?>
 <project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.7.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>test</groupId>
<artifactId>testweb</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>testweb</name>
<description>test</description>

<properties>
    <java.version>1.8</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-security -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
<dependency>
    <groupId>com.oracle.ojdbc</groupId>
    <artifactId>ojdbc8</artifactId>
    <scope>runtime</scope>
</dependency>

    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-jasper</artifactId>
        <version>8.5.20</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
        <groupId>org.hibernate</groupId>
        <artifactId>hibernate-ehcache</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
    </repository>
</repositories>
<pluginRepositories>
    <pluginRepository>
        <id>spring-milestones</id>
        <name>Spring Milestones</name>
        <url>https://repo.spring.io/milestone</url>
    </pluginRepository>
</pluginRepositories>


text:
Q: Variable popen calls in C I'm trying to execute MS-DOS DEL commands inside a Win32 C program, and I already know that system and popen can be used for this. However, the problem is that both require string literals (type const char) for the commands, and I need something like the DOS equivalent of this Perl code (more or less, don't know if it actually works):
my $user = $ENV{'USERNAME'};
my $directory = $ENV{'HOME'};
my $files = system("dir " . $directory);
my $pattern = "s/(\d{7,8})|(\"" . $user . "\")/";
$files ~= $pattern;
system("rm " . $files);

which obviously has to use string literals for the rm command. Is there some other subprocess function in C that allows for char arrays as arguments for process names?

A: Its a pain, but you will probably end up having to un-escape all the escape characters. "\blah" -> "\\blah", etc.  See a list of them here.
Based on your code, I would do something like (roughly):
pattern = "s/(\\d{7,8})|(\\\"%s\\\")/";
char buff[100];
sprintf(buff, getenv("HOME"));
system(buff);

The idea being specify the pattern with all the troubling characters escaped, i.e \\ and \", then use sprintf
to get the final format string.  The string from getenv will not have escape character problems, so you can use it directly.


text:
Q: Azure Service Bus pub/sub to multiple azure web app instances I am trying to achieve a pub/sub with azure service bus.
I started with this tutorial and it worked so far:
https://azure.microsoft.com/en-gb/documentation/articles/service-bus-dotnet-how-to-use-topics-subscriptions/
But in my dedicated case i am not exactly sure how i should do it exactly:
I have a web api running on azure web app that is scaled to three instances.
I have a console application client that triggers some messages to a dedicated topic.
What i want to achieve is, that all three instances of the web api get the messages delivered that is send to the message bus.
So it is a fire forget action:

*

*Client sends message to topic

*Every subscriber that is CURRENTLY subscribing to this topic should get the message

I am not interested in older messages that were sent when the subscriber was inactive/offline. I am just syncing an in memory cache over these instances so it is really a short living info when i need to know which keys i have to invalidate. but it is important that every subscriber gets the information to avoid stale data.
I am not exactly sure if i have to create a subscription dynamically in the startup code of the web api so that every instance has its own subscription or if i can subscribe all web app instances to the same subscription?
I would like not to dynamically create subscriptions since i don't know when to remove them again (e.g. scaled down to 2 instances instead of three).
but i was unable to find any documentation how to do this and if it is okey that multiple clients subscribe to the same subscription or if i need to create a subscription per client.

A:
I am not exactly sure if i have to create a subscription dynamically in the startup code of the web api so that every instance has its own subscription or if i can subscribe all web app instances to the same subscription?

Service Bus subscribers adopt the Competing Consumer pattern by default. You must create a unique subscription for each Web API instance in order each instance to receive a copy of the message. It will be easiest to do this when the Web API instance starts up.

I would like not to dynamically create subscriptions since i don't know when to remove them again (e.g. scaled down to 2 instances instead of three).

You can configure the subscription to be auto-deleted after being idle for some period of time. "Idle" in this case would mean that the Web API instance has spun down and is no longer attempting to receive messages on the subscription. When creating the subscription set the AutoDeleteOnIdle time span for a brief duration, currently a minimum of 5 minutes. Now you can create a new subscription when the Web API instance starts and know that it will be automatically deleted soon after the Web API instance stops.

I am not interested in older messages that were sent when the subscriber was inactive/offline.

When creating the topic, set the DefaultMessageTimeToLive for a brief duration e.g. 5 seconds. This will ensure that new subscribers don't see old messages.


text:
Q: Use of ConvertTo-ExcelXlsx (ImportExcel) to convert .xls to .xlsx Trying to convert .xls file to .xlsx
by ConvertTo-ExcelXlsx function of ImportExcel module
https://github.com/dfinke/ImportExcel/
Github documentation says
Thanks to Mikkel Nordberg. He contributed a ConvertTo-ExcelXlsx. To use it, Excel needs to be installed. The function converts the older Excel file format ending in .xls to the new format ending in .xlsx.
help ConvertTo-ExcelXls returns the following as syntax:
    ConvertTo-ExcelXlsx [-Path]  [-Force] []
So I am trying do it like:
ConvertTo-ExcelXls -path "C:\MyFolder\MyFile.xls"

but I am getting:
ConvertTo-ExcelXls : The term 'ConvertTo-ExcelXls' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try again.
At line:2 char:1
+ ConvertTo-ExcelXls -path 'C:\MyFolder\ ...
+ ~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (ConvertTo-ExcelXls:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

A: Well the answer is basically written in your question. The syntax is ConvertTo-ExcelXlsx but you invoked ConvertTo-ExcelXls which is not available in your shell (note the missing x at the end).
So here is the thing. Powershell adds Get- if it cannot resolve a command, so if you invoke help, it's actually Get-Help. Get-Help outputs any command that matches a part of your specified name. Get-Help -Name Excel would have given you the function as well (and probably some more). That's why you got help for ConvertTo-ExcelXlsx even though you looked up ConvertTo-ExcelXls. This makes it a littly bit tricky, but on the other hand, the help message was really helpful.


text:
Q: In the context of git (and diff), what is a "hunk" I was looking for a definition of "hunk" while reading some git documentation.
I know it means a description of the difference between two files and that it has a well defined format, but I couldn't call to mind a succinct definition.
I tried searching with google, but there were a lot of somewhat spurious hits.

A: And eventually I found this:

When comparing two files, diff finds sequences of lines common to both files, interspersed with groups of differing lines called hunks.

here:
http://www.gnu.org/software/diffutils/manual/html_node/Hunks.html
Which was exactly the kind of succinct definition I was looking for.  Hopefully this helps someone else out!

A: The term "hunk" is indeed not specific to Git, and comes from the Gnu diffutil format. Even more succinctly:

Each hunk shows one area where the files differ.

But the challenge for Git is to determine the right boundaries for a hunk.
The rest of the answer helps illustrates what a hunk looks like in Git:
After various heuristics (like the compaction one, which is gone in Git 2.12), Git maintainers settled on the indent one, which was introduced in Sept. 2016 with Git 2.11, commit 433860f.

Some groups of added/deleted lines in diffs can be slid up or down,
because lines at the edges of the group are not unique. Picking good shifts for such groups is not a matter of correctness but definitely has a big effect on aesthetics.
For example, consider the following two diffs.
The first is what standard Git emits:
--- a/9c572b21dd090a1e5c5bb397053bf8043ffe7fb4:git-send-email.perl
+++ b/6dcfa306f2b67b733a7eb2d7ded1bc9987809edb:git-send-email.perl
@@ -231,6 +231,9 @@ if (!defined $initial_reply_to && $prompting) {
 }

 if (!$smtp_server) {
+       $smtp_server = $repo->config('sendemail.smtpserver');
+}
+if (!$smtp_server) {
        foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
                if (-x $_) {
                        $smtp_server = $_;

The following diff is equivalent, but is obviously preferable from an
aesthetic point of view:
--- a/9c572b21dd090a1e5c5bb397053bf8043ffe7fb4:git-send-email.perl
+++ b/6dcfa306f2b67b733a7eb2d7ded1bc9987809edb:git-send-email.perl
@@ -230,6 +230,9 @@ if (!defined $initial_reply_to && $prompting) {
        $initial_reply_to =~ s/(^\s+|\s+$)//g;
 }

+if (!$smtp_server) {
+       $smtp_server = $repo->config('sendemail.smtpserver');
+}
 if (!$smtp_server) {
        foreach (qw( /usr/sbin/sendmail /usr/lib/sendmail )) {
                if (-x $_) {

This patch teaches Git to pick better positions for such "diff sliders" using heuristics that take the positions of nearby blank lines and the indentation of nearby lines into account.

With Git 2.14 (Q3 2017), that indent heuristic will be the default!
See commit 1fa8a66 (08 May 2017) by Jeff King (peff).
See commit 33de716 (08 May 2017) by Stefan Beller (stefanbeller).
See commit 37590ce, commit cf5e772 (08 May 2017) by Marc Branchaud.
(Merged by Junio C Hamano -- gitster -- in commit 53083f8, 05 Jun 2017)

diff: enable indent heuristic by default
The feature was included in v2.11 (released 2016-11-29) and we got no negative feedback. Quite the opposite, all feedback we got was positive.
Turn it on by default. Users who dislike the feature can turn it off
by setting diff.indentHeuristic.

With Git 2.24 (Q4 2019), the "indent heuristics" that decides where to split
diff hunks has seen its documentation corrected.
See commit 64e5e1f (15 Aug 2019) by SZEDER Gábor (szeder).
(Merged by Junio C Hamano -- gitster -- in commit e115170, 09 Sep 2019)

diff: 'diff.indentHeuristic' is no longer experimental
The indent heuristic started out as experimental, but it's now our
default diff heuristic since 33de716 (diff: enable indent heuristic
by default, 2017-05-08, Git v2.14.0-rc0).
Alas, that commit didn't update the documentation, and the description of the 'diff.indentHeuristic' configuration variable still implies that it's experimental and not the default.
Update the description of 'diff.indentHeuristic' to make it clear that it's the default diff heuristic.
The description of the related '--indent-heuristic' option has already
been updated in this answer.

The documentation will now read:

diff.indentHeuristic:
Set this option to false to disable the default heuristics that shift diff hunk boundaries to make patches easier to read.

With Git 2.25 (Q1 2020), you don't even have to specify --indent-heuristic anymore (since it is the default for quite some times now).
See commit 44ae131 (28 Oct 2019) by SZEDER Gábor (szeder).
(Merged by Junio C Hamano -- gitster -- in commit 532d983, 01 Dec 2019)

builtin/blame.c: remove '--indent-heuristic' from usage string
Signed-off-by: SZEDER Gábor
The indent heuristic is our default diff heuristic since 33de716387 ("diff: enable indent heuristic by default", 2017-05-08, Git v2.14.0-rc0 -- merge listed in batch #7), but the usage string of 'git blame' still mentions it as "experimental heuristic".
We could simply update the short help associated with the option, but according to the comment above the option's declaration it was "only included here to get included in the "-h" output".
That made sense while the feature was still experimental and we wanted to give it more exposure, but nowadays it's unnecessary.
So let's rather remove the '--indent-heuristic' option from 'git blame's usage string.
Note that 'git blame' will still accept this option, as it is parsed in parse_revision_opt().
Astute readers may notice that this patch removes a comment mentioning "the following two options", but it only removes one option.
The reason is that the comment is outdated: that other options was '--compaction-heuristic', and it has already been removed in 3cde4e02ee (diff: retire "compaction" heuristics, 2016-12-23), but that commit forgot to update this comment.

A: For your information, you can read this simple explanation also:
https://mvtechjourney.wordpress.com/2014/08/01/git-stage-hunk-and-discard-hunk-sourcetree/


text:
Q: Overloaded router, can't connect to the Internet? I was transferring about 30gb of files to my home server and streaming some music from soundcloud. I've never tried putting so much bandwidth through my router at once before, and basically everything stopped I couldn't connect to the network on any of my computers.
(I take it I overloaded my router?)
I did a hard factory reset and was able to reset my network and everything, got all of my settings back to normal, even did a firmware upgrade...but the router won't pick up the internet connection now. I can see other computers in my network and such, but the internet just doesn't work anymore.
I have tried connecting my modem directly to my computer, which does work.
Any ideas?

A: Okay, I spent a few hours fixing this, but overlooked the "Clone Mac Address" section. I cloned my main computer's Mac Address and got everything back up and working again.

A: Maybe your router has died. It's a common problem but also it's a common problem with high traffic that can kill a router. Basically it's very easy to kill a router connection. Linux makes it's easy to adjust the network stack.

A: Home firewall routers can have a little memory exhaustion issue. Power cycling is the quickest method of getting them back. Not sure if you tried that first, but it's sure a lot less inconvenient than wiping and starting from scratch.
I have this Netgear box here that will be drop kicked out the door when I get tired of the weekly power plug yank and can be bothered to replace it.


text:
Q: Undefined symbols argp_parse and arpg_usage when installing rng-tools on OSX I am currently trying to install rng-tools on OSX, as I have a specific need for it to speed up a certain simulator that I am currently using. At first, I faced the problem of not having argp, so I installed argp-standalone from Homebrew. However, I still receive the following error message when trying to make rng-tools:
gcc  -g -O2   -o rngtest stats.o rngtest.o librngd.a
Undefined symbols for architecture x86_64:
"_argp_parse", referenced from:
      _main in rngtest.o
  "_argp_usage", referenced from:
      _parse_opt in rngtest.o
ld: symbol(s) not found for architecture x86_64
collect2: ld returned 1 exit status
make[2]: *** [rngtest] Error 1
make[1]: *** [all-recursive] Error 1
make: *** [all] Error 2

I checked /usr/local/include/argp.h and it does seem to contain the correct function definitions referenced in rngtest.c, so any thoughts on what might be the problem?

A: I just needed rngtest which I managed to compile on OSX using this https://github.com/fproulx/rngtest (which also needs brew install argp-standalone). I made that into a homebrew formula which can be obtained here: https://github.com/oderwat/homebrew-experiments