text:
Q: how to present active UIViewController I have a barButtonItem and I am performing an action from that to show another viewController(first in hierarchy), but it gets hard, cause if I try
self.dismissViewControllerAnimated(true, completion:nil)

it gets me not that viewController, that I need.
also, if I am doing
    var navigCont = UINavigationController(rootViewController: destinationViewController)
    navigCont.navigationBar.barTintColor = instaColor
    navigCont.navigationBar.tintColor = UIColor.whiteColor()
    navigCont.navigationBar.translucent = false
    navigCont.presentViewController(destinationViewController, animated: true, completion: nil)

it gets error, cause
Application tried to present modally an active controller

So I am stucked, and I don't know how to present my VC right. Any advices?

A: You are trying to present destinationViewController on a navigation controller with rootViewController set to destinationViewController itself.
Create a new rootViewController for your navigationController and try below code if it works:
var mainViewController = UIViewController(nibName: "MainViewController", bundle: nil)
var navigCont = UINavigationController(rootViewController: mainViewController)
navigCont.navigationBar.barTintColor = instaColor
navigCont.navigationBar.tintColor = UIColor.whiteColor()
navigCont.navigationBar.translucent = false
navigCont.presentViewController(destinationViewController, animated: true, completion: nil)

A: Answer was simply to create segue and make action for this segue in storyboard. The goal was - create a sequel without a storyboard item.
Actually this isn't a correct answer on my question, but this way of solving helped.
How to perform Unwind segue programmatically?


text:
Q: Javascript: How can I add two strings without converting into numbers? Given two numbers in string format (eg. '10.23' and '25.69') how can I get their sum without converting the string into numbers? (eg '35.92')
I do not want to convert the strings into numbers using things like parseInt, Number, parseFloat etc....

A: An old trick is to multiply by 1, as that forces numeric conversion. The * operator doesn't work on strings, so it forces a switch to numbers. It's an old trick though, as I said.
The unary plus operator is a more modern.
var num1 = '20',
    num2 = '30.5';

console.log(num1 * 1 + num2 * 1); // = '50.5'

If you want the output to definitely be a string, you can also:
console.log((num1 * 1 + num2 * 1)+"");

A: Disclaimer: I am not recommending you actually do this. However, you could implement your own add method using a pre calculated lookup table and a rough implementation of a "binary" adder (converted into decimal). The code below work for your example, but i leave no guarantee that it will work for any general cases.

const lookupTable = Array(10).fill(0)
  .map((_, i) => Array(10).fill(0)
    .map((_, j) => [`${i},${j}`, i+j+'']))
  .reduce((flatArr, innerArr) => [...flatArr, ...innerArr], [])
  .reduce((lookupTable, [k, v]) => ({...lookupTable, [k]: v}), {})

const addDigits = (a, b) => {
  const sum = lookupTable[`${a},${b}`];
  if (sum.length === 2) return [sum[1], '1'];
  else return [sum, '0'];
}

const strAdd = (a, b) => {
  const add = ([aH, ...aT], [bH, ...bT], carryBit='0') => {
    if (aH === undefined && aH === undefined) return '';
    if (aH === undefined) return add([], bT, carryBit) + bH;
    if (bH === undefined) return add(aT, [], carryBit) + aH;
    if (aH === '.' || bH === '.') return add(aT, bT, carryBit) + '.';
    const [partial_sum, partial_carryBit1] = addDigits(aH, bH);
    const [sum, partial_carryBit2] = addDigits(partial_sum, carryBit);
    const [newCarryBit] = addDigits(partial_carryBit1, partial_carryBit2);
    return add(aT, bT, newCarryBit) + sum;
  }
  const [whole_a, decimal_a] = a.split('.');
  const [whole_b, decimal_b] = b.split('.');
  const wholeMaxLength = Math.max(whole_a.length, whole_b.length)+1;
  const decimalMaxLength = Math.max((decimal_a || '0').length, (decimal_b || '0').length);
  a = whole_a.padStart(wholeMaxLength, '0') + '.' + (decimal_a || '').padEnd(decimalMaxLength, '0');
  b = whole_b.padStart(wholeMaxLength, '0') + '.' + (decimal_b || '').padEnd(decimalMaxLength, '0');
  return add([...a].reverse(), [...b].reverse(), '0')
    .replace(/^0+/, '') // remove leading 0
    .replace(/0+$/, '') // remove trailing 0
    .replace(/\.$/, '') // remove trailing .
}

const calc = (a, b, expected) => {
  const result = strAdd(a, b);
  console.log(result, result === expected);
}

calc('10.23', '25.69', '35.92');
calc('1', '2', '3');
calc('10.3', '2', '12.3');
calc('99999', '1.01', '100000.01');

A: Here's the solution for your problem:

const format_numStr = (num, no_of_digits, digits_Arr) => {

    outNum = 0

    no_of_digits-=1

    for (digit of num) {

        if (digits_Arr.includes(digit)) {

            // power of 10 decreases as digits progress from left to right i.e from 10^(len(num)-1) to 10^0

            // index() Method returns the exact number or digit we pass in type integer

            outNum+=(digits_Arr.indexOf(digit)*10**(no_of_digits))

            no_of_digits-=1
        }
    };

    return outNum
}

const numStr_Sum = (numStr_Arr) => {

    digits_Arr = Array.from(new Array(10), (_, i) => String(i)) //array contains digits from [0-9]

    num_Arr=[]  // Initialise an array to store the given str number as type integer

    numStr_Arr.forEach(num => {

        no_of_digits = num.length

        if (num.includes('.')) {

            decimal_val = num.split('.')[1].length      // Gives the Decimal point (.) position value

            //Since period(.) exists in the num, no_of_digits should be decreased by 1
            float_num = format_numStr(num, no_of_digits-1,digits_Arr)/10**decimal_val

            num_Arr.push(float_num)

        }
        else {
            num_Arr.push(format_numStr(num, no_of_digits, digits_Arr))
        }

    });

    total_sum = num_Arr.reduce((a,b)=>a+b,0)

    if (Number.isInteger(total_sum)) {
        return total_sum

    }
    else {
        return total_sum.toFixed(decimal_val)
    }

}

console.log(numStr_Sum(['22.22','22.22']))

A: You can use the unary plus operator (+), but in the background it is converting the string into numbers anyway.
Example:
+string1 + +string2

redpajama_set_name: RedPajamaStackExchange


text: Q: Certains users return little to no information with graph API or FQL I am using the graph API and for certain random users, normal graph calls such as <user_id>/feed or <user_id>/photos return little to no data, usually only 0-2 items.  I can see all these user's photos and posts easily on the facebook website.  I have full permissions for my app and I even tried equivalent queries with FQL.  It doesn't work in my app or in the Graph API Explorer.  Is there a way users can block their posts from the API perhaps?  I can't figure out why I can't get full results for about 20% of my friends.


text:
Q: Moving away from bower in 2.15.1 ember-cli version I'm trying to stop using bower dependencies in my Ember project. I updated ember-cli to 2.15.1 and moved bower dependencies to package.json. Maybe it will be helpfull to know which dependencies:
"font-awesome": "~4.7.0",
"jquery.inputmask": "
"moment": "~2.18.1",
"moment-timezone": "0.5.13"

We also used bootstrap-datepicker as a bower dependency, but due to the error message I swapped it for ember-bootstrap-datetimepicker hoping that it would solve my issue. I reinstalled node_modules, removed bower_components, cleared tmp and dist folders and run npm cache clean && bower cache clean. From the project, I removed bower.json and .bowerrc. I also explicitly defined in package.json bowerDirectory: null so that in ember-cli-build.js broccoli won't be looking for any bower components.
in my ember-cli-build.js :
const isProductionLikeBuild = ['production', 'staging', 'review', 'e2e-testing'].indexOf(env) > -1;
const app = new EmberApp(defaults, {
    fingerprint: {
      enabled: isProductionLikeBuild,
      prepend: envConf.assetsPrefix
    },
    sourcemaps: {
      enabled: !isProductionLikeBuild
    },
    minifyCSS: { enabled: isProductionLikeBuild },
    minifyJS: { enabled: isProductionLikeBuild },
    'ember-cli-babel': {
      includePolyfill: true
    },
    'ember-bootstrap-datetimepicker': {
       "importBootstrapCSS": true,
       "importBootstrapJS": true,
       "importBootstrapTheme": true
     },
    'ember-font-awesome': { fontsOutput: '/assets/fonts' },
    exportConfig: {
      environments: [
        'production',
        'staging',
        'review',
        'e2e-testing'
      ]
    }
  });

When I turn off sourcemaps, app is building correctly.
When I don't however, this is what I get after typing ember s:
The Broccoli Plugin: [BroccoliMergeTrees: TreeMerger (vendor & appJS)] failed with:
Error: ENOENT: no such file or directory, open '/Users/martagajowczyk/Desktop/Project/project-frontend/tmp/source_map_concat-input_base_path-S2ZmmRR0.tmp/bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.js'
    at Error (native)
    at Object.fs.openSync (fs.js:641:18)
    at Object.fs.readFileSync (fs.js:509:33)
    at SourceMap.addFile (/Users/martagajowczyk/Desktop/Project/project-frontend/node_modules/fast-sourcemap-concat/lib/source-map.js:75:31)
    at /Users/martagajowczyk/Desktop/Project/project-frontend/node_modules/broccoli-concat/concat.js:200:16
    at Array.forEach (native)
    at Concat.<anonymous> (/Users/martagajowczyk/Desktop/Project/project-frontend/node_modules/broccoli-concat/concat.js:198:24)
    at /Users/martagajowczyk/Desktop/Project/project-frontend/node_modules/fast-sourcemap-concat/lib/source-map.js:419:12
    at initializePromise (/Users/martagajowczyk/Desktop/Project/project-frontend/node_modules/rsvp/dist/rsvp.js:567:5)
    at new Promise (/Users/martagajowczyk/Desktop/Project/project-frontend/node_modules/rsvp/dist/rsvp.js:1039:33)

The broccoli plugin was instantiated at:
    at BroccoliMergeTrees.Plugin (/Users/martagajowczyk/Desktop/Project/project-frontend/node_modules/broccoli-plugin/index.js:7:31)
    at new BroccoliMergeTrees (/Users/martagajowczyk/Desktop/Project/project-frontend/node_modules/ember-cli/node_modules/broccoli-merge-trees/index.js:16:10)
    at Function.BroccoliMergeTrees [as _upstreamMergeTrees] (/Users/martagajowczyk/Desktop/Project/project-frontend/node_modules/ember-cli/node_modules/broccoli-merge-trees/index.js:10:53)
    at mergeTrees (/Users/martagajowczyk/Desktop/Project/project-frontend/node_modules/ember-cli/lib/broccoli/merge-trees.js:85:33)
    at EmberApp._mergeTrees (/Users/martagajowczyk/Desktop/Project/project-frontend/node_modules/ember-cli/lib/broccoli/ember-app.js:1832:12)
    at EmberApp.javascript (/Users/martagajowczyk/Desktop/Project/project-frontend/node_modules/ember-cli/lib/broccoli/ember-app.js:1307:17)
    at EmberApp.toArray (/Users/martagajowczyk/Desktop/Project/project-frontend/node_modules/ember-cli/lib/broccoli/ember-app.js:1689:12)
    at EmberApp.toTree (/Users/martagajowczyk/Desktop/Project/project-frontend/node_modules/ember-cli/lib/broccoli/ember-app.js:1711:38)
    at module.exports (/Users/martagajowczyk/Desktop/Project/project-frontend/ember-cli-build.js:46:14)
    at Builder.setupBroccoliBuilder (/Users/martagajowczyk/Desktop/Project/project-frontend/node_modules/ember-cli/lib/models/builder.js:56:19)

What can be the reason of linking to bower_components?
Thanks
Output from ember version --verbose && npm --version && yarn --version:
ember-cli: 2.15.1
http_parser: 2.7.0
node: 6.10.3
v8: 5.1.281.101
uv: 1.9.1
zlib: 1.2.11
ares: 1.10.1-DEV
icu: 58.2
modules: 48
openssl: 1.0.2k
os: darwin x64
3.10.10
0.24.6

Here's part of my package.json with dependencies and dev-dependencies listed:
"devDependencies": {
    "broccoli-asset-rev": "^2.5.0",
    "ember-ajax": "^3.0.0",
    "ember-bootstrap-datetimepicker": "^1.1.0",
    "ember-buffered-proxy": "^0.7.0",
    "ember-can": "^0.8.4",
    "ember-cli": "^2.15.1",
    "ember-cli-app-version": "^3.0.0",
    "ember-cli-autoprefixer": "0.8.0",
    "ember-cli-babel": "^6.8.2",
    "ember-cli-bootstrap-datepicker": "^0.5.6",
    "ember-cli-code-coverage": "^0.4.1",
    "ember-cli-content-security-policy": "1.0.0",
    "ember-cli-dependency-checker": "^2.0.1",
    "ember-cli-eslint": "^4.2.0",
    "ember-cli-htmlbars": "^2.0.3",
    "ember-cli-htmlbars-inline-precompile": "^1.0.2",
    "ember-cli-inject-live-reload": "^1.6.1",
    "ember-cli-mirage": "^0.3.1",
    "ember-cli-moment-shim": "^3.5.0",
    "ember-cli-page-object": "1.11.0",
    "ember-cli-polyfill-io": "^1.2.2",
    "ember-cli-qunit": "^4.0.0",
    "ember-cli-sass": "^7.0.0",
    "ember-cli-shims": "^1.1.0",
    "ember-cli-sri": "^2.1.1",
    "ember-cli-uglify": "^1.2.0",
    "ember-cli-yuidoc": "0.8.8",
    "ember-cp-validations": "^3.3.0",
    "ember-data": "^2.13.1",
    "ember-deep-set": "^0.1.2",
    "ember-exex": "^0.1.12",
    "ember-export-application-global": "^2.0.0",
    "ember-feature-flags": "3.0.0",
    "ember-font-awesome": "4.0.0-alpha.3",
    "ember-inflector": "^2.0.0",
    "ember-inputmask": "0.4.0-beta.5",
    "ember-intercom-io": "^0.1.3",
    "ember-intl": "^2.23.1",
    "ember-intl-cp-validations": "^3.0.1",
    "ember-load-initializers": "^1.0.0",
    "ember-math-helpers": "^2.0.5",
    "ember-modal-dialog": "^2.3.0",
    "ember-moment": "7.4.1",
    "ember-multiselect-checkboxes": "^0.10.3",
    "ember-power-select": "^1.8.2",
    "ember-promise-helpers": "^1.0.3",
    "ember-radio-button": "1.1.1",
    "ember-resolver": "^4.1.0",
    "ember-responsive": "2.0.4",
    "ember-rl-dropdown": "^0.10.1",
    "ember-route-action-helper": "^2.0.3",
    "ember-simple-auth": "1.4.0",
    "ember-sinon": "1.0.1",
    "ember-sinon-qunit": "2.0.0",
    "ember-sliding-sticky": "^1.0.0",
    "ember-source": "^2.13.0",
    "ember-svg-jar": "^0.11.1",
    "ember-test-selectors": "0.3.7",
    "ember-truth-helpers": "1.3.0",
    "ember-uploader": "^1.2.2",
    "ember-watson": "^0.9.1",
    "eonasdan-bootstrap-datetimepicker": "~4.17.42",
    "loader.js": "^4.4.0",
    "modal-dialog": "1.6.3",
    "yuidoc-ember-theme": "^1.3.0"
  },
  "dependencies": {
    "bootstrap-sass": "^3.3.7",
    "broccoli-funnel": "^2.0.1",
    "font-awesome": "~4.7.0",
    "jquery.inputmask": "3.3.4",
    "moment": "~2.18.1",
    "moment-timezone": "0.5.13"
  }

A: I strongly assume your problem is ember-cli-bootstrap-datepicker. This addon does add the bootstrap-datepicker bower package during installation and probably should not be used without it.
Personally if you're looking for an ember DatePicker I recommend ember-pikaday.
If you need recommendations about addons I recommend ember observer, or ask in the slack channel references on the community page..


text:
Q: preg_replace issue on multiple Currently I'm getting this result https://puu.sh/zvWLl/1db4614184.png
from this set of code:
$CheckArrays = [
"QUOTE" => "/\[quote=?(.*)\](.*)\[\/quote\]/",
"BOLD" => "/\[b\](.*)\[\/b\]/",
"ITALIC" => "/\[i\](.*)\[\/i\]/",
];

$FanceString = $UglyString;

// QUOTES
do {
    $FanceString = preg_replace_callback(
        $CheckArrays['QUOTE'],
        function($match) {
            if (is_numeric($match[1])) {
                $TPID = GetThreadPoster($match[1]);
                $TPUN = GetUsernameS($TPID);
                $statement = ('

'.$match[2].'
- '.$TPUN.'

');
            } elseif (!is_numeric($match[1])) {
                $statement = ('

'.$match[2].'

');
            }
            return $statement;
        },
        $FanceString,
        -1,
        $count
    );
} while ($count > 0);

With my test string being:
[quote=82][quote=76]Isn't that the true ultimate question?[/quote]
[b]I suppose, if that [b]test[/b] makes you feel better[/b][/quote]

This is a test

Basically, this is what I'm attempting to achieve.. https://puu.sh/zvWVs/c27663e0ac.png

A: I'll present my solution here but you should really use a parser instead. For your specific situation, you could use a recursive approach:
\[b[^][]*\]
(?:[^][]*|(?R))*
\[/b\]

See a demo on regex101.com.

The PHP code would be:

<?php

$data = <<<DATA
[quote=82][quote=76]Isn't that the true ultimate question?[/quote]
[b]I suppose, if that [b]test[/b] makes you feel better[/b][/quote]

This is a test
DATA;

$outer = '~
                \[b[^][]*\]
                (?:[^][]*|(?R))*
                \[/b\]
                ~x';

$inner = '~\[/?[^][]*\]~';
$data = preg_replace_callback(
    $outer,
    function($match) use ($inner) {
        return "" . preg_replace($inner, '', $match[0]) . "";
    },
    $data);

echo $data;
?>

Which yields
[quote=82][quote=76]Isn't that the true ultimate question?[/quote]
I suppose, if that test makes you feel better[/quote]

This is a test


text:
Q: Reverse list order without increasing complexity I wanted an alternative to filter that would, instead of discarding the false cases, keep them in a separate place.  I came up with the below, but unfortunately it reverses the list.
Obviously I could append x to ys or zs instead of cons, but this would dramatically increase complexity.
Is there a way to keep it in order without increasing complexity?
splitBy :: (a -> Bool) -> [a] -> ([a],[a])
splitBy f xs = splitBy' f xs ([],[])
            where
                splitBy' :: (a -> Bool) -> [a] -> ([a],[a]) -> ([a],[a])
                splitBy' _   []   result  = result
                splitBy' f (x:xs) (ys,zs) = if f x then splitBy' f xs (x:ys,zs)
                                                   else splitBy' f xs (ys,x:zs)

A: As others have said, the function is called partition, and it works something like this
partition :: (a -> Bool) -> [a] -> ([a], [a])
partition f = foldr (\x ~(yes,no) ->
                         if f x
                         then (x:yes,no)
                         else (yes,x:no))
                    ([], [])

except that the real version adds an explicit xs parameter, perhaps to help fusion rules work properly. If that funky lazy pattern match makes you nervous, you can write it like this instead:
partition f = foldr (\x r ->
                         if f x
                         then (x:fst r,snd r)
                         else (fst r,x:snd r))
                    ([], [])

If the foldr seems mysterious to you, you can do it like this:
partition f [] = ([], [])
partition f (x:xs)
  | f x       = (x:fst r, snd r)
  | otherwise = (fst r, x:snd r)
  where r = partition f xs


text:
Q: Update NSTableView based on Menu Item I'm trying to update a Table View with something selected from a Menu Item. This is my AppDelegate class tied to NSArrayController.
@implementation AppDelegate

- (id) init {
    self = [super init];

    // An NSMutableArray to hold several Package objects
    self.allPackages = [[NSMutableArray alloc] init];

    Package *package = [[Package alloc] init];
    // Objective-C setters
    [package setName:@"Installation Core"];
    [package setCreator:@"Messi"];

    [self.allPackages insertObject:package atIndex:[self.allPackages count]];

    return self;
}

The NSArrayController is updating the NSTableView as expected upon init. Now I have a Menu Item which is calling a method to get some Package objects in a NSArrayController.
- (IBAction)open:(id)sender{

    NSOpenPanel* openDlg = [NSOpenPanel openPanel];
....
    // If OK Button was pressed
    if([openDlg runModal] == NSOKButton){

        NSURL *url = [openDlg URL];

        PackageHelper *packageHelper = [[PackageHelper alloc] init];

        NSMutableArray *files = [packageHelper getFilesFromDirectory: url];

        NSLog(@"Received %li",files.count);
        // This is actually listing all the files I need.

    }
    else {
        NSLog(@"Pressed Cancel");
    }

}

Now my question is How do I get this NSMutableArray files show up on the TableView ? In other words, can the Array Controller get the data from the init method in the AppDelegate class and the open method on different class ?
Thanks for your time.


text:
Q: how to define multivariete normal distribution on sphere In Euclidean vector space, we can parameterize multivariate normal distribution by its mean vector and covariance matrix.
On a general sphere $S^n$, starting from a dirac delta and simulate the heat equation, one can also obtain an gaussian-like distribution, as answered in this question.
Now that I wonder if its possible to define a "spherical multivariate normal distribution". Obviously, the "mean vector" on a sphere would be an unit vector. However, how should one properly define "covariance matrix" on $S^n$?

A: Take a loot at 5-parameter Fisher–Bingham distribution/Kent distribution.


text:
Q: Powershell - Using Where-object, find strings (emails addresses) with numbers We are using Office 365 and came across an issue where duplicate accounts were created. This cause a numerical addition to the users address (john.doe@c0mpany.onmicrosoft.com would also be john.doe5826@c0mpany.onmicrosoft.com and a full seperate user).
Get-MsolUser -All | where {$_.proxyaddresses -like "smtp:*'$(\d)'@C0mpanyName.onmicrosoft.com"} | select userprincipalname, proxyaddresses,displayname

I've run out of ideas and this sample I've added was the best I could up with to search for a proxyaddress with numbers in the address.
I believe this would work if we didn't use a domain with numbers in it (note the 0 in C0mpany, but instead add 4 more numbers, so I can't use the {4} to dictate that it can only be 4 numbers that we are searching for).
Any help would be really appreciated. Thanks!

A: You're mixing wildcard and regex matching.
Try this:
Get-MsolUser -All | where {$_.proxyaddresses -match "smtp:.+\d@C0mpanyName\.onmicrosoft\.com"} | select userprincipalname, proxyaddresses,displayname

And see:
Get-Help about_Regular_Expressions
Get-Help about_Wildcards


text:
Q: get method in restful service , return {} I want to pass an JSONObject from restful service to a restful client . Here is pice of my service code :
@GET
@Path("/getJson")
@Produces(MediaType.APPLICATION_JSON)
public JSONObject getJson() {
    try {
        JSONObject json=new JSONObject();
        json.put("PoprocessingCode", "123456789");
        json.put("TransactionAmount", "0000000");
        System.out.println(json);
        return json;
    } catch (Exception e) {
        System.err.println(e.getMessage());
        return null;
    }
}

and here is pice of my restful client :
    Client c = Client.create();
    WebResource resource = c.resource("http://localhost:8080/TestJsonService/jaxrs/JsonService/getJson");
    JSONObject json=new JSONObject();
    json=resource.accept(MediaType.APPLICATION_JSON_TYPE).get(JSONObject.class);
    try {
        System.out.println("json.getString = "+json.getString("PoprocessingCode"));
    } catch (JSONException e1) {
        e1.printStackTrace();
    }

when I ran it , I get this error :

org.json.JSONException: JSONObject["PoprocessingCode"] not found.
      at org.json.JSONObject.get(JSONObject.java:459)
      at org.json.JSONObject.getString(JSONObject.java:640)
      at JsonClient.main(JsonClient.java:30)

I tested my service by Test with "REST Web Service Explorer" in myeclipse and recognized get method in service T returned just this

{}

and there isn't anything in it and it is empty , I don't know why?!
please guide me in order to solve it.
thanks...

A:     Please pass the JsonObject in this form, this will work :
        @Path("Excel")
        @POST
        @GET
        @Consumes(MediaType.APPLICATION_JSON)
        @Produces(MediaType.APPLICATION_JSON)
        public String ExportToExcel(String jsonString)

    And post this using REST Console.

In case of :
JsonObject then use this --->

@Path("/rename")
    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Event renameEvent(Event newEvent)

And the object that you pass from the REST CONSOLE should be of following pattern :

{"measures":null,"eventScenarioId":2016,"timeId":20378,"promoPrice":1.979734,"oiAllowancePerunit":0.0,"productId":7158,"scanAllowancePerUnit":0.0,"eventProductStrategy":[{"name":"FND","tsId":4,"tsACV":10.0,"eventProductScenarioId":5069,"id":3},{"name":"TPR","tsId":1,"tsACV":0.0,"eventProductScenarioId":5069,"id":4},{"name":"DISPLAY","tsId":3,"tsACV":2.0,"eventProductScenarioId":5069,"id":2},{"name":"FEATURE","tsId":2,"tsACV":9.0,"eventProductScenarioId":5069,"id":1}],"addEstimatedIncrementalUnits":0.0,"shippedBaseUnits":4365.000000000001,"edShelfPrice":1.979734,"eventFixedCost":0.0,"shippedUnitPct":100.0,"edlpPricePerUnit":0.0,"manuFixedCost":0.0,"customerId":null,"id":5069}


text:
Q: Should WSUS show a server as requiring an update that has been approved for removal? I have marked an update in WSUS for removal from all machines.
After the update has been removed from the machines, in WSUS they still show that they require 1 update. When checking what the update is, it is the one that I marked for removal.
It's approval status is "Removal" and its status is "Not Installed".
Is that expected behaviour? I would have imagine it would show as not needed, and thus not throw out my update compliance percentages?

A: Yes, that is expected behavior. The "removal" update looks and is treated just like an normal update scheduled to be installed (i.e. it can be declined by the user if they have permissions to do so, a reboot may be required after the update is "installed", etc.).


text:
Q: metric space incomplete Good day, please how show that C[a,b] with norm $\left \| f \right \|=(\int_{a}^{b}f^{p}(x)dx)^{\frac{1}{p}}$ is not complete, $p\geq 1$. Can I do it with $g_{n}=(\int_{a}^{t}f_{n}^{p}dt)^{\frac{1}{p}}$ adecuate?

A: I'll give you a hint for the case $[a,b]=[-1,1]$. Consider $g_n\in C[-1,1]$ such that $g_n(t)=nt$ for $t\in [-1/n,1/n]$ and $g_n(t)=-1$ on $[-1,-1/n)$ and $g_n(t)=1$ on $(1/n,1]$. Show that
1). $\{g_n\}$ constitute a Cauchy sequence as to the $p$-norm.
2). If $g_n\to g\in C[-1,1]$ in the $p$-norm, then there is no way to define the value of $g(0)$.


text:
Q: Swapping modulus and argument in polar coordinates Let $y=f(x)$ in Cartesian coordinates. Swapping the $x$ coordinate with the $y$ coordinate has the effect of reflection about the axis $y=x$.
But if $r=f(\theta )$ in polar coordinates (where $r$ is the modulus and $\theta$ is the argument), what happens when we swap $r$ with $\theta$?
For example, what's the difference between the polar graphs of $r=\theta ^2$ and $\theta =r^2$? Do they look the same? Or is there some kind of reflection as well?

A: Polar coordinates we call well known mapping $\mathbb{R}^2 \to \mathbb{R}^2$, from $(x,y)$ to $(\theta, r)$ using formulas
$x = r\cos \theta$, $y = r\sin \theta$, $r \geqslant 0,\theta \in [0, 2\pi) $.
As to plane $(\theta, r)$, then it is usual cartesian coordinates, usual $\mathbb{R}^2$, and you can think about it exactly as you think about $(x,y)$. $r=\theta^2$ is exactly parabola. $\theta=r^2$ is both branches of square root.
We use polar coordinate, when some function/ curve looks "difficult" for $(x,y)$ and by mapping it to $(\theta, r)$ plane we obtain more "easy" case. Most known example is circle $x^2+y^2=r^2$, which by polar coordinate moves to interval $[0, 2\pi) \times \{1\}$. Disk $x^2+y^2\leqslant r^2$ is mapped to rectangle $[0, 2\pi) \times [0,1]$.
Addition.
Now about swapping variables. By definition axial symmetry is not identical Orthogonal Transformation which have line of fixed points. This line is called symmetry axis. To obtain for point $M$ symmetrical point $M'$ with respect to symmetry axis one need to draw perpendicular line to symmetry axis from $M$ and take point $M'$ on this perpendicular on other side of symmetry axis on same distanse as $M$.
For example, if we consider $y=x$ as symmetry axis, then for point $(a,b)$ symmetrical point is $(b,a)$.
So, on $\mathbb{R}^2$ swapping coordinates i.e. having graph $y=f(x)$ and considering $x=f(y)$ is exactly creating symmetry with respect to line $y=x$. Same is, of course if we speak about $r=f(\theta)$ and considering $\theta=f(r)$ - they are symmetric with respect to line $r=\theta$.
Another question is what gives swapping variables for $(x,y)$ in $(\theta, r)$ and reverse. Let's consider firstly "polar plane". As is stated above, swapping variables there means symmetry with respect to line $r=\theta$. Last is well known Archimedean spiral on "cartesian plane". So swapping coordinates $\theta$ and $r$ gives on plane $(x,y)$ graphs "symmetric" with respect to spiral $r=\theta$ which is same as $\sqrt{x^2+y^2}=\arctan \frac{y}{x}$. For example parabola $r=\theta^2$, which is some type of spiral on $(x,y)$, after swapping gives $\theta=r^2$, or taking its one branch, $r=\sqrt{\theta}$ is again some spiral on $(x,y)$.
Summing up:

*

*parabola $y=x^2$ is axial symmetric with respect to square root $x=y^2$ using symmetry axis line $y=x$.

*In "polar" language spiral $r=\theta^2$ is "spirally" symmetric with respect to spiral $\theta=r^2$ using
symmetry "axis" spiral $r=\theta$
Second example. Let's take in polar plane $r=\tan\theta$ i.e. points $(\theta,\tan\theta)$. Swapping variables give $\theta=\tan r$ i.e. points $(\tan r,r)$. Obviously $(\theta,\tan\theta)$ is axially symmetrical to $(\tan r,r)$ with respect to symmetry axis $\theta=r$. Now if we consider corresponding points on $(x,y)$ plane, then symmetry axis $\theta=r$ creates spiral, while $r=\tan\theta$ and $\theta=\tan r$ create some corresponding curves on $(x,y)$: $\sqrt{x^2+y^2}=\frac{y}{x}$ and $\arctan \frac{y}{x}=\tan \sqrt{x^2+y^2}$. Obviously $(x,y)$ curves are not axially symmetrical.
If it sounds acceptable, we can call "spirally" symmetrical on plane $(x,y)$ such points, which preimages are axially symmetrical on plane $(\theta, r)$ with respect to symmetry axis $\theta=r$.
Using this term we can call $\sqrt{x^2+y^2}=\frac{y}{x}$ and $\arctan \frac{y}{x}=\tan \sqrt{x^2+y^2}$ "spirally" symmetrical on plane $(x,y)$.

A:
The polar plots of $r= \theta^2, \sqrt \theta, \theta$ are shown in blue,red and grey respectively.
The gray line does not reflect red/blue profiles in a way presently imaginable by me.
This is perhaps because $(r,\theta)$ do not have the same physical dimension and belong to a common type or genre.
$Z=r e^{i \theta}$ is a complex number. I do not know what $U = \theta e^{ir}$ really is.
A very good question, but my answer may be is no good. That is indirectly suggested geometric reciprocal requirement is not answered.


text:
Q: Socket.IO Handshake Authorization I have the following in my NodeJS server to ensure that foo=bar in the handshake of the connection request:
io.use(function(socket, next){
    console.log("Query: ", socket.handshake.query);
    // return the result of next() to accept the connection.
    if (socket.handshake.query.foo == "bar") {
        console.log("Got auth params.");
        socket.emit('chat message','Valid credentials.');
        return next();
    }
    // call next() with an Error if you need to reject the connection.
    console.log("Didn't get auth params.");
    socket.emit('chat message','Invalid credentials.');
    next(new Error('Authentication error'));
});

When foo=bar in the handshake data the chat message indicating 'Valid credentials.' is successfully emitted to the client.  However, when foo!=bar socket.emit does not emit the 'Invalid credentials.' chat message.
Is it possible send a message to the client that requested the connection in the event that foo!=bar?
I'm assuming it's likely that the only way to emit a message to the client in response to their connection request is by accepting the connection with return next(), sending a message in the connection event indicating the invalid credentials, then terminating the connection.

A: In order to catch the error message emitted via next(new Error('Authentication error')) simply create a handler for the error event on the client side as such:
socket.on('error', function(err){
  console.log('Connection Failed: ' + err);
});


text:
Q: The largest second number I searched everywhere for a solution to find the second largest number, but I got one solution in all sites, and it's wrong.
The code I found:
public static void main(String[] args) {
    int arr[] = { 1, 23, 47, 81, 92, 88, 52, 48, 56, 66, 65, 76, 71, 85,
                   49, 53, 56, 61, 65, 84 };
    secondLargeNumber(arr);
}

public static void secondLargeNumber(int[] arr) {
    int largest = arr[0];
    int secondLargest = arr[0];
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] > largest) {
            secondLargest = largest;
            largest = arr[i];
        } else if (arr[i] > secondLargest) {
            secondLargest = arr[i];
        }
    }
    System.out.println("second largest in array is:" + secondLargest);

}

The code works fine , but if I changed the input sequence to:
 int arr[] = { 11, 10, 11, 2, 3, 4, 5, 6, 7, 8};

the output will be:
second largest in array is:11

I really don't know what to do!

A: Just do:
else if (arr[i] > secondLargest && arr[i] != largest) {
    secondLargest = arr[i];
}

A:  public static void secondLargeNumber(int[] arr) {
          int largest = Integer.MIN_VALUE;
          int secondLargest = Integer.MIN_VALUE;
          for (int i = 0; i < arr.length; i++) {
                 if (arr[i] > largest) {
                       secondLargest = largest;
                       largest = arr[i];

                 } else if (arr[i] > secondLargest && arr[i] != largest) {
                       secondLargest = arr[i];

                 }
          }
          System.out.println("second largest in array is:" + secondLargest);

   }

A: The problem comes from here:-
int largest = arr[0];
int secondLargest = arr[0];

Try to initialize your variables with the least number like this:
 int secondlargest = Integer.MIN_VALUE;
 int largest = Integer.MIN_VALUE;

How about this:-
   int secondlargest = Integer.MIN_VALUE;
        int largest = Integer.MIN_VALUE;
        Scanner input = new Scanner(System.in);
        System.out.println("Enter array values: ");
        int arr[] = new int[5];
        for (int i = 0; i < arr.length; i++) {
            arr[i] = input.nextInt();
            if (largest < arr[i]) {
                secondlargest = largest;
                largest = arr[i];
            }
            if (secondlargest < arr[i] && largest != arr[i])
                secondlargest = arr[i];
        }

A: You need two additions:

*

*as other posts have suggested != largest check

*If both largest and secondlargest start off with same value, switch the secondlargest to a smaller value asap.
      for (int i = 0; i < arr.length; i++) {
             if (arr[i] > largest) {
                   secondLargest = largest;
                   largest = arr[i];

             } else if (arr[i] > secondLargest && arr[i]!=largest) {
                   secondLargest = arr[i];

             }else if(largest==secondLargest){
                 secondLargest = arr[i];
             }
      }


text:
Q: How to Create a Series of Webpages By series of pages I mean having pages that can be navigated to using Previous, Next, or 1,2,3, ... The content being a list of 10 songs, and to see more the user can just click Next. I'm planning to use PHP and MySQL. I need your opinions on how to go about it (Not explicitly asking for code but personal opinions that may be supplemented with code). Thanks!

A: MySQL offers the LIMIT X,Y keyword which does most of this work already. X is always the starting position and Y the amount of rows to select.
If you have, for example, a search form, and the user searches for a song of the genre pop, you could do something like SELECT name, artist, ... FROM songs WHERE genre = 'pop' LIMIT 0,10. This will return 10 songs of the search result starting at position 0. That would be your page 1. For page 2 you simply run the same query again but with LIMIT 10,10.
Using this you can create your Previous and Next buttons:
HTML
Previous
Next

PHP
$page = isset($_GET['page']) ? intval($_GET['page'] : 1;
$start = ($page - 1) * 10;
$query = "SELECT name, artist, ... FROM songs WHERE genre = 'pop' LIMIT $start,10";

A: The technique is called pagination. Here's a PHP helper class that can help you with pagination:
<?php

// This is a helper class to make paginating
// records easy.
class Pagination {

  public $current_page;
  public $per_page;
  public $total_count;

  public function __construct($page=1, $per_page=20, $total_count=0){
    $this->current_page = (int)$page;
    $this->per_page = (int)$per_page;
    $this->total_count = (int)$total_count;
  }

  public function offset() {
    // Assuming 20 items per page:
    // page 1 has an offset of 0    (1-1) * 20
    // page 2 has an offset of 20   (2-1) * 20
    //   in other words, page 2 starts with item 21
    return ($this->current_page - 1) * $this->per_page;
  }

  public function total_pages() {
    return ceil($this->total_count/$this->per_page);
    }

  public function previous_page() {
    return $this->current_page - 1;
  }

  public function next_page() {
    return $this->current_page + 1;
  }

    public function has_previous_page() {
        return $this->previous_page() >= 1 ? true : false;
    }

    public function has_next_page() {
        return $this->next_page() <= $this->total_pages() ? true : false;
    }

}

?>

USE IN CONSTRUCTING THE SQL
$total_count = $db->get_var( "SELECT COUNT(*) FROM songs" );
$per_page = 10;
$current_page = $page;
$pagination = new Pagination($current_page, $per_page, $total_count);
$all = $db->get_results("SELECT * FROM songs ORDER BY id DESC LIMIT {$per_page} OFFSET {$pagination->offset()}");


text:
Q: How to exclude current directory from executable search in Windows? When typing a command in Windows shell, it first looks for the program in current directory and then from PATH directories. Is it possible to somehow (eg by a environment variable) exclude current directory from the search? Something like SafeDllSearchMode but for executables instead of DLL-s?
In other words -- if I have one foo.exe in current directory and second one in another directory in PATH, how can I execute the one in PATH directory without specifying its full path?

A: I don't know of any way to make cmd exclude the current path. As a close approximation, though, you could use mkdir to make an empty directory in the current directory, cd into it, run your command, cd back up and remove the directory:
SET _tempdir=%date%%time%
MKDIR %_tempdir%
CD %_tempdir%
REM run commands
...
CD ..
RM %_tempdir%

The empty directory can be anywhere you have write access, of course; if it's somewhere other than in that same directory, though, it will probably be easier to use pushd to go into it and popd to get back out before removing it. Using an empty directory you just created seems like a better idea than cd-ing to a random directory, though--the new directory will still be first on the path, so it's better to use one you know is empty.


text:
Q: Problem with HtmlPanelGrid.setRowClasses() I have one more question! I am trying to configure HtmlPanelGrid from bean. I bound panelGrid to this bean and want to set css row classes.
Here is me stylesheet.css:
.list-row-even {
background-color: silver;
}

.list-row-odd {
 background-color: red;
}

my jsf page:
   <rich:tab label="Top-List" id="screenTop">
     <h:panelGrid id="topListTable" binding="#{chartBean.topListTable}" />
   </rich:tab>

and my bean:
public TopListChartWrapper(Iterator<Entry> treeIt) {
    this.grid = new HtmlPanelGrid();
    //this.grid.setBgcolor("yellow");
    this.grid.setColumns(2);
    this.grid.setBorder(0);
    this.grid.setCellpadding("0");
    this.grid.setCellspacing("0");
    this.grid.setWidth("100%");
    this.grid.setRowClasses("list-row-even, list-row-odd");
    this.treeIterator = treeIt;
    this.prepareGrid();
}

Any ideas? maybe somewhere I need register my stylesheet?
Thanks!

A: Sorry - about forget the question)
I figure out what was wrong:
I need replace the line:

     link href="./css/default.css" rel="stylesheet" type="text/css"
with this one:

 link href="#{facesContext.externalContext.requestContextPath}/css/default.css" rel="styleSheet" type="text/css"/

Thanks!


text:
Q: Android AllJoyn : How do I discover devices that are running my app? Is there any way in AllJoyn for Android through which I can get the number of devices across a Wi-Fi router that are using my app?

A: If your app uses the About feature, then on your monitor app you have to count the number of about announcement received, filtered by additional about field that identifies your app and not other Alljoyn devices.

A: Depends on how your app is being used. This question is a little ambiguous, since "devices using my app" could mean your app running within other folks devices (they are using your app by having installed it), or could mean your app is providing a service that other devices in the wifi network are connecting to (they are using your app by connecting to it as a remote client).
I assume you mean the second.
In your service app, when you bind the session port you can specify a SessionPortListener. Implement its sessionJoined() method to track the remote peers that join and leave a session with your app.
mBus.bindSessionPort(contactPort, sessionOpts, new SessionPortListener() {
    @Override
    public boolean acceptSessionJoiner(short sessionPort, String joiner, SessionOpts sessionOpts) {
        return true;
    }
    @Override
    public void sessionJoined(short sessionPort, int id, final String joiner) {
        mPeers.add(joiner);
        mBus.setSessionListener(id, new SessionListener() {
            @Override
            public void sessionLost(int sessionId, int reason) {
                mPeers.remove(joiner);
            }
        });
    }
});


text:
Q: Geometry: showframe + landscape I'm using \usepackage[showframe]{geometry} and I'm seeing that when I use a landscape environment (added by pdflscape package) the frame doesn't seem to be OK.
Is this an erratum?  Is there any way to correct this?
Here is my MWE:
\documentclass[a4paper,twoside,11pt,openright]{report}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage[outer=25mm,inner=35mm,vmargin=20mm,includehead,includefoot,headheight=15pt,showframe]{geometry}
\usepackage{pdflscape}

\begin{document}
Hello.  First page.  Everything ok.

\begin{landscape}
Why is the frame off?
\end{landscape}

\end{document}

And this is the result:

A: There is a "design comprimise" in package lscape (in other packages it would be called "design flaw" ;-), of course). Environment landscape only rotates \textheight and \textwidth remains unchanged. However package geometry expects unchanged values, thus it gets surprised with \textheight having the old value of \textwidth.
The following example fixes this in package geometry's \Gm@vrule that draws the vertical lines. The fixed version uses \gmshow@textheight instead of \textheight. Outside environment landscape the macro \gmshow@textheight expands to \textheight. Inside it expands to \gmshow@@textheight that is initialized with the text height (available in \hsize) at the begin of environment landscape:
\documentclass[a4paper,twoside,11pt,openright]{report}

\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[english]{babel}
\usepackage[
  outer=25mm,
  inner=35mm,
  vmargin=20mm,
  includehead,
  includefoot,
  headheight=15pt,
  showframe
]{geometry}
\usepackage{pdflscape}

\makeatletter
\newcommand*{\gmshow@textheight}{\textheight}
\newdimen\gmshow@@textheight
\g@addto@macro\landscape{%
  \gmshow@@textheight=\hsize
  \renewcommand*{\gmshow@textheight}{\gmshow@@textheight}%
}
\def\Gm@vrule{%
  \vrule width 0.2pt height\gmshow@textheight depth\z@
}%
\makeatother

\begin{document}
\noindent
Hello.  First page.  Everything ok.

\begin{landscape}
  \Huge
  \noindent
  top left\hfill top right\par
  \vfill
  \noindent
  bottom left\hfill bottom right
\end{landscape}
\end{document}


text:
Q: Lisp print a tree level by level I have in LISP a tree represented as list as follows:
(A 2 B 0 C 2 D 0 E 0)
That means A have 2 childrens (B and C), B have 0, and so on...
My task is to write each level of the tree.
I know about this post: LISP Displaying binary tree level by level , but how can I use my list representation instead of that on that post?

A: One obvious approach is to first decode this flat-but-unweildy representation into a more obvious tree, and then print that tree, which I assume you know how to do.  One trick to doing this is to have a function which decodes a node from the representation and returns both the decoded node and the unconsumed tail of the representation.  Here is something which does that.
(defun decode-one-child (from)
  (destructuring-bind (head nchilds . children/more) from
    (iterate decode ((c nchilds)
                     (cm children/more)
                     (childs '()))
      (cond
       ((zerop c)
        (values (make-node head (nreverse childs))
                cm))
       ((null cm)
        (error "ran out of children to eat"))
       (t
        (multiple-value-bind (node remaining) (decode-one-child cm)
          (decode (1- c) remaining (cons node childs))))))))

(defun decode-tree (from)
  (multiple-value-bind (decoded tail) (decode-one-child from)
    (unless (null tail)
      (error "ran out of appetite before consuming all children"))
    decoded))

Note that this intentionally is not a complete answer, because I suspect this may well be homework.  You will need to write both make-node, and understand what iterate (not part of standard CL) does.  For the second, have a look at named let in Scheme, or consider that
(iterate name ((var val) ...)
  ...)

Can be translated as
(labels ((name (var ...)
           ...))
  (name val ...))

A: Someone, under a different account, fairly recently asked a question about this representation of lists, using the same example. I wrote an answer using TXR Lisp to parse that representation and convert to an ordinary nested list.
When multiple people ask questions about a very specific academic programming problem with identical inputs or other details, that is strong evidence that this is homework.
The parsing code from my original answer:
(defun parse (syntax)
  (labels ((rec (parsym n)
             (cons parsym
                   (collect-each ((i 0..n))
                     (match-case syntax
                       ((@sym 0 . @rest)
                        (set syntax rest)
                        (list sym))
                       ((@sym @(integerp @m) . @rest)
                        (set syntax rest)
                        (rec sym m))
                       (() (error "abrupt end in syntax"))
                       (@else (error "unhandled syntax: ~s" syntax)))))))
    (cadr (rec :root 1))))

Calculates like this:
1> (parse '(A 2 B 0 C 2 D 0 E 0))
(A (B) (C (D) (E)))

To print each level of the resulting, like, say:
A
B C
D E

and in various other ways, we need a breadth-first search. The easy depth-first search traversal won't do; that's what the ordinary printed representation is already doing.
The TXR Lisp manual, under the documentation of the build macro, gives an example breadth-first-search traversal in a few lines of code:
(defun bf-map (tree visit-fn)
  (buildn
    (add tree)
    (whilet ((item (del)))
      (if (atom item)
        [visit-fn item]
        (each ((el item))
          (add el))))))

That doesn't quite do what we want: it visits the atoms:
7> [bf-map (parse '(A 2 B 0 C 2 D 0 E 0)) prinl]
A
B
C
D
E

so we are certainly getting the names in level order, but we don't see the divisions between the levels.
We need to modify this function to recognize the special syntax of the tree which is (<name> [<tree>*]) and for each level, print just the name(s) on that level.
Maybe like this:
(defun bf-map (tree visit-fn)
  (buildn
    (add (cons 0 tree))
    (whilet ((item (del)))
      (tree-bind (level name . children) item
        [visit-fn level name]
        (each ((ch children))
          (add (cons (succ level) ch)))))))

The items in the BFS queue are now agumented (level . tree) cons pairs, and since a tree is (name . children), the queue items are therefore (level name . children).  We prime the queue by pushing such (level . tree) item into it, calculating that item as (cons 0 tree).
We also modify the protocol so that the callback function is invoked with two arguments: the level number, and the node name.
We might this function like so to print something directly:
11> (let ((oldlevel nil))
      [bf-map (parse '(A 2 B 0 C 2 D 0 E 0))
              (lambda (level name)
                (when (neql oldlevel level)
                  (put-line `\nlevel@level:`))
                (print name)
                (put-string " ")
                (set oldlevel level))]
      (put-line))

level0:
A
level1:
B C
level2:
D E

Or get the levels as a vector indexed on zero-based level:
13> (let ((level-vector (vec))
          (nlevels 0))
      [bf-map (parse '(A 2 B 0 C 2 D 0 E 0))
              (lambda (level name)
                (when (>= level nlevels)
                  (vec-push level-vector nil)
                  (upd [level-vector (pinc nlevels)] nreverse))
                (push name [level-vector level]))]
      level-vector)
#((A) (C B) (E D))


text:
Q: django template tag instance hard to word the question so ill go right to the point, i wrote the following template tag
def do_simple_tag(parser, token):
    try:
        tag_name, name = token.split_contents()
    except ValueError:
        raise template.TemplateSyntaxError("%r tag requires exactly one argument" % token.contents.split()[0])
    if not (name[0] == name[-1] and name[0] in ('"', "'")):
        raise template.TemplateSyntaxError("%r tag's argument should be in quotes" % tag_name)
    return SimpleTagNode(name[1:-1])

class SimpleTagNode(template.Node):
    def __init__(self, name):
        self.name = name
    def render(self, context):
        content = get_content(context, request, name)
        return content

register.tag('simple_tag', do_simple_tag)

then i wrote a function that scans for this tag in a template and gets all instances of this tag within said template in a list like so
def get_tags(template):
    compiled_template = get_template(template)
    simple_tag_instances = _scan_tag(compiled_template.nodelist)

def _scan_tag(nodelist, current_block=None, ignore_blocks=[]):
    tags = []
    for node in nodelist:
        if isinstance(node, SimpleTagNode):
            tags.append(node.get_name())

so, my question is why does the isinstance fail if node is infact an instance of SimpleTagNode ( or so i believe ) , i checked nodelist and saw that indeed there were instances of SimpleTagNode, but they would all return false in the isinstance condition, i have spent a long time trying to figure this one out, but found nothing, i even used the shell running the funcions above and still returned fals, any help is much a appreciated

A: So i finally solved it, basically in the module that contained the _scan_tag function at the top of the file i was importing the SimpleTagNode class like so
from simple_tag.templatetags.simple_tag import SimpleTagNode

simple_tag being the name of my app, and also the name of the template file, for some reason this was conflicted with isinstance , so i tried
from paulo.simple_tag.templatetags.simple_tag import SimpleTagNode

paulo being my project app, and it worked.


text:
Q: Error message when trying to install GTFSR library At the company I work for we are trying to advance our GTFS capabilities and I can across the GTFSR library, which got me very excited!
Being quite new to R it took me awhile to figure out I needed to install devtools, unfortunately, even after installing devtools, I get the following error:
devtools::install_github('ropenscilabs/gtfsr')

Downloading GitHub repo ropenscilabs/gtfsr@master
from URL
  https://api.github.com/repos/ropenscilabs/gtfsr/zipball/master
  Installing gtfsr Downloading GitHub repo rstudio/leaflet@master from
  URL https://api.github.com/repos/rstudio/leaflet/zipball/master
  Installing leaflet "C:/PROGRA~1/R/R-34~1.4/bin/x64/R" --no-site-file
  --no-environ --no-save --no-restore --quiet CMD INSTALL  \   "C:/Users/Username/AppData/Local/Temp/RtmpMr0ZUc/devtools2b9c242555c/rstudio-leaflet-6aa608f"
  --library="C:/Program  \   Files/R/R-3.4.4/library" --install-tests
In R CMD INSTALL Installation failed: Command failed (65535)
  "C:/PROGRA~1/R/R-34~1.4/bin/x64/R" --no-site-file --no-environ
  --no-save --no-restore --quiet CMD INSTALL  \   "C:/Users/Username/AppData/Local/Temp/RtmpMr0ZUc/devtools2b9c2a431852/ropensci-gtfsr-3af920a"
  --library="C:/Program  \   Files/R/R-3.4.4/library" --install-tests
In R CMD INSTALL Installation failed: Command failed (65535)
library(gtfsr)
  Error in library(gtfsr) : there is no package called 'gtfsr'

A: I never did determine what the issue was but I ended up uninstalling RStudio (and all packages) and reinstalled. I installed GTFSR by itself and it worked fine.
I wonder if maybe I had a conflicting package or an unsupported version.
Thanks everyone.


text:
Q: The greatest revenue? A theatre seats 2000 people and charges $10 for a ticket. At this price all the tickets can be sold. A survey indicates that if the ticket price is increased, the number sold will decrease by 100 for every dollar of increase. What ticket price would result in the greatest revenue?

A: Hint: If we have $x$ dollars of increase, we get: $$(2000-100x)(10+x)$$
We are attempting to maximize this value.

A: Hint. Let the price be increased by $x$ dollars. Then the number of people would be $2000-100x$, and the price per ticket would be $10+x$. What would be the revenue as a function of $x$?

A: To solve this problem, you need to use some simple calculus. Let $x$ be the price of the ticket. When $x=10$, we know that $2000$ seats are sold and that $100$ fewer seats are sold for every dollar increase in price. This nets us the equation:
seats sold $= 2000-100(x-10)$
If we multiply this by the price of the ticket, we can find the total revenue $R$:
$R=x(2000-100(x-10))$
$=2000x-100x(x-10)$
$=2000x-100x^{2}+1000x$
$=3000x-100x^2$
Since we're trying to find a maximum for this expression, we can run this function for revenue through any monotonically increasing analytic function and their maximum will occur at the same value of $x$. Therefore, we can divide the equation by $100$ to find:
$30x-x^{2}$
Taking the derivative with respect to $x$, we have:
$30-2x$
... and setting this to zero, we have:
$0=30-2x$
$2x=30$
$x=15$
Lastly, we can verify that this is a maximum and not a minimum because the second derivative of our revenue function is negative.
Therefore, you'll want to price your tickets at $15.


text:
Q: How to maintain session in java I know following are the ways to maintain or session tracking in java but looking for a good one

*

*URL rewritting

*Hidden form fields

*cookies

*Session object like setAttribitute() and session.getAttribute()

If the client browser has blocked accepting and storing cookies then last 2 ways are not valid.In hidden form fields I need to pass the hidden values in each and every page inside form.So suppose If I am just using response.sendRedirect() Then hidden form field is of not use.The remaining is URL rewriting in which I will pass JsessionID in the URl.So My question by knowing the sessionID isnt the unauthorized persons can able to access the pages.
For example There are 3 pages login,register,send.So after login user can register and/or send.So if any one knows the sessionID cant he/she go direct to register/send page.If yes Please tell me how to prohibit this

A: As of Servlet 3.0 (Apache Tomcat 7 onwards) if you use SSL then you can configure your application to track sessions based on the SSL session ID. The downside is that everything has to be over SSL. The advantages are that the session is strongly tied to the SSL connection. Only the user that created the connection to the server that has the correct SSL session has access to the session. Even if an attacker knows the session ID, they can't access the session.
One word of caution, this form of session tracking is the least widely used so it may not have been as heavily tested as the more usual cookie and URL re-writing mechanisms.

A: Have a look at this link which outlines Best practices for using HTTP sessions
Including

*

*javax.servlet.http.HttpSession.invalidate()

*Use HTTPS

A: With standard solutions you can't.
You can add some measure of security by adding request originator IP address verification, but that's also fooled easily. (to clarify some here means very tiny itsy bitsy little bit of)
So the secure route is to not use URL Rewriting to maintain session in secure application.
However you may be able to get some security by keeping the JSessionID as a separate encrypted attribute that which will be decrypted by a middle-ware or a load balancing server sitting between the client and your application servers. This of course is just a thought, I haven't, fortunately ever had to try something like that out :-)

A: Session tracking & authentication are two diff things don't club them.
Understanding your requirement I see you want to secure the sessionid of the user.

*

*Evasdroping: If someone is listing to the request & response in the middle he can take the sessionid and use it. The best way would be to use a SSL. This ensures no one is listening in the middle.

*Sessionid stolen from Client side: Normally this should be taken care by the browser and OS. So your user is as secure as the system he has.


text:
Q: Hide "No data available in table" This is my table , I get the data list using json and populate this table,

          <input type="checkbox" id="ChkboxClaimHeader" name="ChkboxClaimHeader" value="false">
          Claim #
          Client Name
          Amount
          Deduction
          Type
          Status

My jquery which has Json result, I get the result and append rows to table body based on my data,
$(document).ready(function () {
$.ajax({
            url: '@Url.Action("ClaimResultTest", "Claims")',
            data: { seacrhClaimNumber: claimNumberToBeSearched },
            type: 'POST',
            success: function (data) {
                   var dataClaims = data.Claims;//This has the complete list
                   for (i = 0; i < dataClaims.length; i++) {
                    alert(dataClaims[i].ClaimNumber);
                    $("#tblClaimSearch").find('tbody')
                            .append($('
')
                            .append($('<input type="checkbox">'))
                            .append($('').text(dataClaims[i].ClaimNumber))
                            .append($('').text(dataClaims[i].Client))
                            .append($('').text(dataClaims[i].Amount))
                            .append($('').text(dataClaims[i].Deduction))
                            .append($('').text(dataClaims[i].Type))
                            .append($('').text(dataClaims[i].Status))
                                )
                     }
                  }
              });
        });

The problem is when there is no data, I have a row displaying "No data available in table"..And even when there is data appended I still have first row as "No data available in table"..How do I hide this message row when new rows with data have been added??And secondly even though I have 16 entries it still shows "Showing 0 of o entries"?.What am I doing wrong?..

A: You can use Regex
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace ConsoleApplication28
{
    class Program
    {
        static void Main(string[] args)
        {
            string input = "Search Name=\"search1\" BasicString=\"\" SearchText=\"\" SearchNames=\"\" SearchFields=\"\" SearchAnnotations=\"\" SearchCustom=\"\"t";
            string pattern = "Name=\"(?'name'[^\"]+)";
            string value = Regex.Match(input, pattern).Groups["name"].Value;
        }
    }
}

A: I'd use Regex for this. Here's a small function that'll find the value after Name=
    public static string NameValueFromString(string input)
    {
        string returnValue = null;

        if (!String.IsNullOrWhiteSpace(input))
        {
            Regex nameValueExpression = new Regex(@"name=""[^""]*""", RegexOptions.IgnoreCase);
            Match match = nameValueExpression.Match(input);
            if (match.Success)
            {
                Regex valueExpression = new Regex(@"""[^""]*""");
                returnValue = valueExpression.Match(match.Value).Value.Trim('"');
            }
        }

        return returnValue;
    }

The first Regex should find the string Name="Something".
If it does then match.Success is true. The second Regex finds "Something" then trims the quotes off.


text:
Q: Calling model functions in CodeIgniter i am trying to work with CodeIgniter the same way as i work in RoR, and then use functions defined in the model in the views, and so on. Let me explain with some example:
My user controller
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class Users extends MY_Controller {

    public function __construct() {
        parent::__construct();
    }

    public function show($id) {
        $user = $this->user_model->get($id);
        $this->data['user'] = $user;
        $this->load_view('users/show');
    }

}

My user model
<?php defined('BASEPATH') OR exit('No direct script access allowed');

class User_model extends MY_Model {

    public function __construct() {
        parent::__construct();
    }

    public function who() {
        return ( $this->name ) ? $this->name : $this->email;
    }

}

And then i want to do this in my view
...

<?= $user->who() ?>

...

How can i achieve this?
NOTE: If i echo $user->email it works fine...

A: I think you're just missing the data passed into your view. There's also a typo on the $this->load->view().
$this->load->view('users/show', $this->data);

Also, are you using?
https://github.com/jamierumbelow/codeigniter-base-model

A: The problem here is that CI does not work the same way as rails. Here:
$user = $this->user_model->get($id);
You are assigning an object that is created dynamically by the ActiveRecord implementation of CI when you call get on the object, hence, that object would not have the who method. This, however, would work:
$this->user_model->who()
Because at that scope, in the controller, user_model is just an instance of your User_model class which is where who is declared.
My advice would be to use a custom helper for that kind of functionality. CI models don't work as Rails models


text:
Q: SetCookie header not stored I'm currently making a web app with node/express.js for the API and Vue.js for the front-end.
For the authentication, I set a JWT and send the value via a cookie (HttpOnly).
The "SetCookie" is in the response request in Chrome/Firefox debugger but apparently it is not stored anywhere !
When I try to make requests which need the cookie, the requests headers don't contain any cookie. I really don't understand why :/.
After some researches, I thought it was because I was working on localhost, so I moved my server on the cloud and set a false domain for the front by modifying the hosts file, but it still doesn't work.
here an example of response request :
Response header
Set the cookie on server:
res.cookie('token', token, {
     path: '/',
     domain: '.shareinfo.io',
     httpOnly: true,
     maxAge: 86400000 // 24h
});

If someone has an idea or a solution, it would be very nice !
Thank you, regards,
Alvyre

A: FINALLY, after some head bangs on my computer and researches on forums, I found the issue.
I ignored credentials on client request, thinking it was not important for authentication, but it was a huge mistake.
In fact credentials include cookies, so if you don't set credentials to 'true' when you make your request to your server/API, all returned cookies will be ignored. you have to authorize credentials both on your server and client.
so the final code was to add this option variable to my POST request : (with Vue.js)
//Request options (CORS)
    var options = {
        headers: {
        },
        credentials: true
    };

//Make your HTTP request:
    this.$http.post(<url>, payload, options).then((response) => {
        //success
    }, (response) => {
        //error
    });

A: I have this problem for almost a week as well and figured out that setting credential to true should do the trick.  If you are using Vue use an interceptor so that you don't need to call it per request
Vue.http.interceptors.push((request, next) => {
    request.credentials = true;
    next();
});


text:
Q: Windows 10 missing service I'm trying to use a smart card on my computer and I can't get it to read on one of my computers even though using the exact same reader works on the other. Both are running Windows 10 21H1. Plugging in the card reader into the non-working computer does install a device in Device Manager so the computer can detect the reader.
One thing I noticed that's different is that the working computer has a Smart Card service but the non-working does not have this service. My guess is I need that service to get it to recognize. But this is where I'm lost. So far, I've tried running the following:
DISM.exe /Online /Cleanup-image /Restorehealth
sfc /scannow

It did fix some things, but the Smart Card service still isn't showing up after a reboot.
Any pointers are much appreciated, thanks.

A: It would help to know the model of your card-reader.
You could look for a driver on the website of its manufacturer.
Use the regsvr32 command to re-register the following dll files
(whichever ones exist on your computer).
For example: regsvr32 scarddlg.dll.
scarddlg.dll   SCardDlg - Smart Card Common Dialog
scardssp.dll   Smart Card Base Service Providers
sccbase.dll    Infineon SICRYPT Base Smart Card CSP
sccsccp.dll    Infineon SICRYPT Smart Card Crypto Provider COM Objects
scredir.dll    Smart Card Redirection for TS
slbcsp.dll     Schlumberger Smart Card CryptoAPI Library
slbiop.dll     Schlumberger Smart Card Interoperability Library v2
slbrccsp.dll   Schlumberger Smart Card CryptoAPI Resource File

If the above steps do not help with the issue, try a
Repair Install of Windows 10 with an In-place Upgrade.
This is the same as doing a major upgrade of Windows,
so take the appropriate backups.

A: On both systems, in search box on task bar, type "services" and start it.
Look for: "Smart Card" "Manages access to smart cards read by this ..."
If no smart card reader is attached its "Status" should be blank and "Startup Type" should be "Automatic(Trigger Start)"
Close services and inset a reader.
Bring up Services again:
with reader inserted, the "Status" should be "Running".
You can also use Task Manager to see the Services with Name of "SCardSrv", PID, Description "Smart Card" and Status of "Running"
You did not say what reader you are using or if other readers have been used on the failing machine. When a new driver is installed, it should have turned on Automatic(Trigger Startup).
Right click on entry and then Properties and you can set "Automatic".


text:
Q: Python SSL wrap_socket failed with SSLError, Errno 336265218 I have simple client/server SSL code which worked fine on Python 3.2. However, I decided to switch over to 2.7 (due to abundance of third party modules), and now the code is failing. The code is as follows:
Client:
def connect(self):
    self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.sock.connect(('localhost', 4430))
    self.ssl_sock = ssl.wrap_socket(self.sock, cert_reqs = ssl.CERT_NONE, ssl_version = ssl.PROTOCOL_TLSv1)

Server:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    self.sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    self.sock.bind((self.hostname, 4430))
    self.sock.listen(5)
    while True:
        self.newsocket, self.fromaddr = self.sock.accept()
        self.ssl_sock = ssl.wrap_socket(
                            self.newsocket,
                            server_side = True,
                            certfile = "cert.pem",
                            ssl_version=ssl.PROTOCOL_TLSv1
        )

        self._handle_client(self.ssl_sock)

The cert.pem (located in same directory as server .py file):
-----BEGIN RSA PRIVATE KEY-----
(812 "random" characters here)
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
(1260 "random" characters here)
-----END CERTIFICATE-----

The failure is as follows:
1. server waits on self.sock.accept()
2. client connects with self.sock.connect()
3. server proceeds to wrap_socket, which fails with the following error:
Traceback (most recent call last):
  File "C:\Program Files\Python27\lib\multiprocessing\process.py", line 258, in _bootstrap
    self.run()
  File "C:\workspace\projectc\server\server\clientlistener.py", line 49, in run
    ssl_version=ssl.PROTOCOL_TLSv1
  File "C:\Program Files\Python27\lib\ssl.py", line 381, in wrap_socket
    ciphers=ciphers)
  File "C:\Program Files\Python27\lib\ssl.py", line 141, in __init__
    ciphers)
SSLError: [Errno 336265218] _ssl.c:351: error:140B0002:SSL routines:SSL_CTX_use_PrivateKey_file:system lib

P.S.
1) I have suspicions about the wrap_socket call because even when I use a non-existent file for certfile, the same error results.
2) I tried the alternative wrapping on the python documentation on ssl (i.e. with ssl.SSLContext) and it's odd that 'module' object has no attribute 'SSLContext', when it is part of the ssl module. This wasn't an issue when I tried it with Python 3.2.
Update:
I have found that the problem only occurs when I'm doing "run" from within Eclipse, not so when I run both files from separate command prompts. Still investigating the issue...
Update 2:
I tried a very simple client/server script with the SAME code and it works. Now, with the server code sitting inside a multiprocessing subprocess (launched by the main server process), it seems not to work. Related?

A: Problem solved. I believe Eclipse was holding some residual information, though I never figured out what information it was holding. It might have to do with the migration from python 3.2 to 2.7, though I previously already changed that in the run config. Resetting the Eclipse environment worked (simply rebooting the computer wasn't enough).

A: my solution was that when creating my .pem file i set a blank password and assumed it meant no pasword. so the server was still expecting to use a password. i had to manually remove the password.
here is a little how to guide if it helps anyone (also, please note i was coding python for a server side to an iOS app)
NOTE: need to follow directions from apple's developer website to create certificate first
 then export the .p12 file,
 by exporting the embedded private key that is created (in 'keychain access'),
 NOT the actual certificate
————————————————————————————————————
————————————————————————————————————
FOR DEVELOPMENT CERT:
After getting the p12 file, it needs to be converted to the PEM format by executing this command from the terminal:
$ openssl pkcs12 -clcerts -nokeys -out apns-dev-cert.pem -in apns_dev.p12
$ openssl pkcs12 -nocerts -out apns-dev-key.pem -in apns_dev.p12
If you wish to remove the passphrase execute the following:
   (NOTE: using a 'blank' password when exporting/converting, is still indeed setting a password,
     hence you should still execute the following if you intend to have no password)
$ openssl rsa -in apns-dev-key.pem -out apns-dev-key-noenc.pem
Finally, you need to combine the key and cert files into a apns-dev.pem file we will use when connecting to APNS:
$ cat apns-dev-cert.pem apns-dev-key-noenc.pem > apns-dev.pem
————————————————————————————————————
FOR PRODUCTION CERT:
After getting the p12 file, it needs to be converted to the PEM format by executing this command from the terminal:
$ openssl pkcs12 -clcerts -nokeys -out apns-prod-cert.pem -in apns_prod.p12
$ openssl pkcs12 -nocerts -out apns-prod-key.pem -in apns_prod.p12
If you wish to remove the passphrase execute the following:
   (NOTE: using a 'blank' password when exporting/converting, is still indeed setting a password,
     hence you should still execute the following if you intend to have no password)
$ openssl rsa -in apns-prod-key.pem -out apns-prod-key-noenc.pem
Finally, you need to combine the key and cert files into a apns-dev.pem file we will use when connecting to APNS:
$ cat apns-prod-cert.pem apns-prod-key-noenc.pem > apns-prod.pem


text:
Q: How Do You Configure IBM Worklight Studio to Build for ARM and MIPS devices? I'm using Worklight Studio Developer Edition plugin for the Eclipse IDE Juno JAVA EE to test building hybrid apps and I'm trying to build and deploy to an Android MIPS based device.  ARM devices and emulators work fine but the MIPS device will not install.
I receive the following errors from the console and logcat.
[2013-03-05 00:27:36 - Project1App1Android] Installation failed due to invalid APK file!
[2013-03-05 00:27:36 - Project1App1Android] Please check logcat output for more details.
[2013-03-05 00:27:36 - Project1App1Android] Launch canceled!
03-05 00:28:18.607: W/PackageManager(90): Native ABI mismatch from package file
I think the problem is the build is not including MIPS support for older device SDKs like Froyo 2.2.1 which is on the devce I'm having problems with. How can I configure Worklight to build for ARM and older MIPS? I have the MDS Eclipse plugin for PhoneGap installed as well and it builds and deploys to the same MIPS device without any problems.

A: Android applications are built and run with help of Android Development Tools. The unified support for all processor architectures is included in Release 21 of Android SDK. You can read the announcement here: Official Android SDK, Installation instructions

A: This is outside of the Worklight scope. You should open the Android SDK Manager, and make sure to install any support by Google related to MIPS and/or ARM.
The generated .apk is generated via Google's Android Developer Tools.


text:
Q: codimension of complementary subspace X is a linear space, and Y and N are complementary subspaces of X, i.e. $X = N \oplus Y.$ Show that when N has finite codimension, $dim Y = codim N$.
This is an exercise from Lax's functional analysis. My question is that why it supposes N has finite codimension.


text:
Q: Initials as Title Abbreviations: Should I Format Them as Titles? I am the webmaster/editor/curator for a website/e-magazine focussing on a game system. Reviews of scenarios published for the game system are a regular feature, and it's frequently the case that a required add-on product will be named. Often, the add-on is well-enough known that the review author will often just refer to it by its initials (e.g., a product called Guns of the World might be referred to as "GotW".
In the past, I've been less than entirely consistent in handling formatting in the magazine and on the website. I am starting to write a style guide for myself.
How should I handle these abbreviated titles? As I see it, my choices are:

*

*Expand the initials into the full title, and then format it as I would any title (italics, usually)

*Leave the initials as initials, but format them as I would the title (e.g., GotW)

*Do neither, leaving the initials as unformatted initials.

Which is most consistent with 'normal' practice?

A: It's normal to italicize the abbreviation of an italicized title. The MLA Style Center recommends that: Should the acronym of an italicized title be set in italics?
Some publications now recommend against italicizing titles at all (The Guardian), but if you are italicizing titles, you should do abbreviations too.
Looking at random video game websites, Kotaku italicizes both; IGN italicizes neither.
As to whether you expand them, it's normal to do that on first use, but use an abbreviation after: in formal texts you would say "The Last of Us (TLOU)" and then afterwards use TLOU, but in less formal texts you may rely on people to infer the abbreviation's meaning. The exception is very commonly known abbreviations which needn't be spelt out (something like CNN or IBM); you will have to judge what they are.


text:
Q: Find a line of text with a pattern using Windows command line or Python I need to run a command line tool that verifies a file and displays a bunch of information about it. I can export this information to a txt file but it includes a lot of extra data. I just need one line for the file:
"The signature is timestamped: Thu May 24 17:13:16 2012"
The time could be different, but I just need to extract this data and put it into a file. Is there a good way to do this from the command line itself or maybe python? I plan on using Python to locate and download the file to be verified, then run the command line tool to verify it so it can get the data then send that data in an email.
This is on a windows PC.
Thanks for your help

A: You don't need to use Python to do this. If you're using a Unix environment, you can use fgrep right from the command-line and redirect the output to another file.
fgrep "The signature is timestamped: " input.txt > output.txt

On Windows you can use:
find "The signature is timestamped: " < input.txt > output.txt

A: You mention the command line utility "displays" some information, so it may well be printing to stdout, so one way is to run the utility within Python, and capture the output.
import subprocess
# Try with some basic commands here maybe...
file_info = subprocess.check_output(['your_command_name', 'input_file'])
for line in file_info.splitlines():
    # print line here to see what you get
    if file_info.startswith('The signature is timestamped: '):
        print line # do something here

This should fit in nicely with the "use python to download and locate" - so that can use urllib.urlretrieve to download (possibly with a temporary name), then run the command line util on the temp file to get the details, then the smtplib to send emails...

A: In python you can do something like this:
timestamp = ''
with open('./filename', 'r') as f:
  timestamp = [line for line in f.readlines() if 'The signature is timestamped: ' in line]

I haven't tested this but I think it'd work. Not sure if there's a better solution.

A: I'm not too sure about the exact syntax of this exported file you have, but python's readlines() function might be helpful for this.
h=open(pathname,'r') #opens the file for reading
for line in h.readlines():
    print line#this will print out the contents of each line of the text file

If the text file has the same format every time, the rest is easy; if it is not, you could do something like
for line in h.readlines():
    if line.split()[3] == 'timestamped':
         print line
         output_string=line

as for writing to a file, you'll want to open the file for writing, h=open(name, "w"), then use h.write(output_string) to write it to a text file


text: Q: Are there any known problems using GPS connection in Android version of QGIS? I install QGIS both my netbook (windows win7 starter) and My tablet (android 4.0). I can used GPS option in windows version and I can save location points from GPS. However, I could not manage same operation in android verion of QGIS. Is there any problem on android version?


text:
Q: multiprocessing Pool without return value? I am trying to use a multiprocessing Pool without a return value for parallel calculation. It could be faster if there's no need to return and retrieve values from the subprocess. Is there a way to do that?
Here is a simple example:
from multiprocessing import Pool

def fun(a):
    # do something..
    a["1"]=100

a={
   "1":12
   }
multi = [a] * 10
p = Pool(4)
p.map(fun, multi)
data = [a["1"] for a in multi]
print(data)
>>> [12, 12, 12, 12, 12, 12, 12, 12, 12, 12]

[fun(a) for a in multi]
data = [a["1"] for a in multi]
print(data)
>>> [100, 100, 100, 100, 100, 100, 100, 100, 100, 100]

Does anybody know why? And is there a solution for that?

A: Your function fun
def fun(a):
    # do something..
    a["1"]=100

changes a mutable argument a. However when you call this using p.map(fun, multi) each item in the multi list is pickled, sent to a worker process and mutated there. This can't have any effect on the original items in the list in the calling process.
You can create data structures that can be shared between processes, so called proxy objects, using managers. You'd have to create 10 shared dictionaries. In your example you only have one dictionary, the list contains 10 references to it, data = [a["1"] for a in multi] will always only contain the same value because a is always the same object.
So this should work:
from multiprocessing import Pool, Manager
import random

def fun(a):
    # to show that the dictionaries are different
    a["1"] = random.random()

if __name__ == '__main__':
    m = Manager()
    p = Pool(4)
    multi = [m.dict() for _ in range(10)]
    p.map(fun, multi)
    data = [a["1"] for a in multi]
    print(data)

Note that multi = m.list([a] * 10) or similar would not work, because only list access is synchronized, not updates of the contained elements. But all of this creates additional IPC overhead and probably will be worse then just using the return value of the function if you can.


text:
Q: How to return specialized type from associated function in generic structs? I was trying to implement some kind of stack with a default type
pub struct Stack<T>(Vec<T>);

impl<T> Stack<T> {

  fn new() -> Self::<i32> {
    Self::<i32>(Vec::<i32>::new())
  }
}

However this won't compile, and gives an error like this:
error[E0109]: type arguments are not allowed for this type
 --> src\lib\stacks.rs:7:22
  |
7 |   fn new() -> Self::<i32> {
  |                      ^^^ type argument not allowed

error: aborting due to previous error

For more information about this error, try `rustc --explain E0109`.
error: could not compile `nullptr`

Did I made any errors in this piece of code? Thank you.

A: Well, if you declared a generic <T> type stack, why would you try to force your new() method to always use a i32?
To make it really generic you should wait to pass its type only when instantiating:
pub struct Stack<T>(Vec<T>);

impl<T> Stack<T> {

  fn new() -> Self {
    Stack { 0: Vec::new() }
  }
}

fn main() {
    let x = Stack::<i32>::new(); // <- here
}

Besides that, the short way you've declared your struct struct Stack<T>(Vec<T>); will need you to use 0 to access the internal stack reference because you didn't give its field a name. It's up to you, but this way it would look a bit better:
pub struct Stack<T> {
    value: Vec<T>
}

impl<T> Stack<T> {

  fn new() -> Self {
    Stack { value: Vec::new() }
  }
}


text:
Q: CMake with Qt: moc creates .cpp_parameters ending I am trying to integrate Qt in my project, especially QTimer.
Therefore, I have been trying to generate the moc files with cmake:
set(MOC_FILES
    ${CMAKE_CURRENT_SOURCE_DIR}/../headerfile.h
)
set(HEADER_FILES
    ...
    ${MOC_FILES}
)
...

ivw_qt_wrap_cpp(MOC_FILES ${MOC_FILES})

#--------------------------------------------------------------------
# Create module
ivw_create_module(${SOURCE_FILES} ${SHADER_FILES} ${MOC_FILES} ${HEADER_FILES})

As a result it creates a file moc_headerfile.cpp_parameters, but the file should be moc_volumeraycaster.cpp.
The content of the file is this:
-DINVIWO_ALL_DYN_LINK
-DGLM_SHARED_BUILD
-DWIN32
-o
C:/../moc_headerfile.cpp
C:/..headerfile.h

Any ideas?

A: You shouldn't use the same variable as input and output for qt_wrap_cpp.
You could get rid of this using AUTOMOC:
set(SOURCE_FILES
    ...
    ${CMAKE_CURRENT_SOURCE_DIR}/../headerfile.h
)
...

set(CMAKE_AUTOMOC ON)

#--------------------------------------------------------------------
# Create module
ivw_create_module(${SOURCE_FILES} ${SHADER_FILES} ${HEADER_FILES})


text:
Q: Best way to stress test a rails web app? Are there any good (preferably free) tools out there?
Can they give accurate estimates that reflect production results when the app goes live?

A: WebLoad is open source:
http://www.webload.org/

A: There's a good summary of tools here.

A: This is definitely not a free solution, but webmetrics will get the job done. (As well as any website monitoring company in general). They give thorough reports on your web site's performance, and when you schedule load tests you can specify how much load you want to simulate (e.g. simulate 2000 users using my site at once).
I don't think it will break it down and tell you your CPU usage and such, as they stress your website from their servers.

A: Rails comes with performance testing built in: http://guides.rubyonrails.org/performance_testing.html

A: You can try Trample, it is load simulation tool here

A: I would personally go with Apache Bench  http://httpd.apache.org/docs/2.0/programs/ab.html
It's free, straight forward to use and lightweight.
If you are looking for a something a little more robust then I think Apache JMeter might be worth looking at. http://jmeter.apache.org/. Again, it's free, a bit of a learning curve and has a GUI so a little heavier.
You might also want to take a look at this Q/A Performing a Stress Test on Web Application?

A: If you want to visualize performance instead of just look at the numbers you might try Engulf. It's Open Source Software, distributed, and high-performance. http://engulf-project.org/#usage Disclaimer: It's a project I work on.


text:
Q: CRUD delete using modal form I am creating a CRUD using PHP extension with PDO, and I want to create a confirmation for registry deletion using Bootstrap modals, but I don't know how I can pass the ID information to the modal to delete, how can I do it?
index.php

                <?php
                $pdo = DB::connect();
                $stmt = $pdo->query("SELECT * FROM people");
                while ($row = $stmt->fetch()) {
                    echo "
";
                    echo "" . $row["id"] . "	";
                    echo "" . $row["first_name"] . "	";
                    echo "" . $row["last_name"] . "	";
                    echo "" . $row["notes"] . "	";
                    if ($row["allowed"]) {
                        echo "" . "✔" . "	";
                    } else {
                        echo "" . "✗" . "	";
                    };
                    echo "";
                    // modal trigger
                    echo "<button type=\"button\" class=\"btn btn-danger\" data-toggle=\"modal\" data-target=\"#exampleModal\">Delete</button>";
                    echo "	";
                    echo "
";
                }
                ?>

Do you want to delete this registry?

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    ×
                </button>

                <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                <button type="submit" class="btn btn-danger">Yes</button>

A: In this section add your ID
echo "<button type='button' class='btn btn-danger' data-toggle='modal' data-target='#exampleModal' onclick='$(".delete_id").val('".$row["id"]."')'>Delete</button>";

Then in modal add an hidden input field like so:
<input type="hidden" name="delete_id" class="delete_id">

Include jQuery before this function. You also need to have a delete file to pass that variable. After the request was success you could re-render the HTML.
function deleteRecord() {
   var id = $(".delete_id").val();

    $.ajax({
    url:"/delete.php",
    method:"POST",
    data:{
      id: id,
    },
    success:function(response) {

   },
   });
}

After we have stored the value of the ID we can delete it
<button type="submit" class="btn btn-danger" onclick="deleteRecord()">Yes</button>

Hope this was helpful


text:
Q: Why does the pen does not move straight? If i put a pen on a table in its horizontal position and then i try to move it horizontally by giving it a small push, so that it would fall off a table, i expect it to move horizontally but my pen ( and all other pens too! ) moves diagonally when it starts moving down the table!When i remove the notebook , the pen moves like,its shown in the picture ( if i keep it horizontally also, it gives the same result)-

Why does this happen? Why does it not move horizontally ?

A: Because your pen is not a cylinder, but a portion of a cone. Since it is also rigid, both ends have to complete one cycle of rolling simultaneously. This means that for each cycle, if the narrow and thick ends are separated by the pen's length $L$ and have radii $r_1$ and $r_2$, respectively, they roll $2\pi r_1$ and $2\pi r_2$, respectively. The only way this can be accomplished (without skidding) is for the ends to roll in a cicrcular motion around a common center.
If I haven't miscalculated, then the distance $d$ from the "small" end to this center is
$$d = \frac{L}{r_2/r_1–1}$$.


text:
Q: getItem() of ViewPager Fragment called twice I am doing swiping application in android. But I got one problem that getItem() method
is calling twice initially. I tried to solve this but I didn't get solution. please help me
to find out solution. below snippets my code:-
public class DisplayEMIBOFQuestionActivity extends FragmentActivity {
private ViewPager pager;
private  int savePosition;
private Context context;
private String fragTag1;
private String fragTag2;

    /*
 * (non-Javadoc)
 *
 * @see android.support.v4.app.FragmentActivity#onCreate(android.os.Bundle)
 */
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    super.setContentView(R.layout.common_emi_bof_display_question);
    context = getLayoutInflater().getContext();
    if(Helper.isTablet)
    {
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    }else
    {
        this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
    }
    // Initialise the pager
    pager = (ViewPager) findViewById(R.id.viewpager);
    pager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));

    /**
     * on swiping the viewpager make respective tab selected
     * */
    pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

        public void onPageSelected(int position) {}

        public void onPageScrolled(int position, float arg1, int arg2) {}

        public void onPageScrollStateChanged(int arg0) {

         }

    });
            getPager().setPageTransformer(true, new SwipeAnimation());

}
public ViewPager getPager() {
    return pager;
}
public void setPager(ViewPager pager) {
    this.pager = pager;
}
public String getFragTag1() {
    return fragTag1;
}
public void setFragTag1(String fragTag1) {
    this.fragTag1 = fragTag1;
}
public String getFragTag2() {
    return fragTag2;
}
public void setFragTag2(String fragTag2) {
    this.fragTag2 = fragTag2;
}

public class MyPagerAdapter extends FragmentPagerAdapter {

    public MyPagerAdapter(FragmentManager fragmentManager) {
        super(fragmentManager);
    }

    @Override
    public Fragment getItem(int pos) {
        System.out.println("************** "+pos);

        Helper.currentQuestion = pos;
        if(Helper.randomQuestionList.get(pos).getSubQuestionType().equals(QuestionType.BOF.toString()))

        return new DisplayBOFQuestionFragment();
        else

            return new DisplayEMIQuestionFragment();

    }

    @Override
    public int getCount() {

        return Helper.NUMBEROFQUESTIONS;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return super.getPageTitle(position);
    }
}

public void setPagerPosition(int pos){
    pager.setCurrentItem(pos);
}

}

A: It gets one fragment and two adjacent ones (here you just have one), so initially will get Tab1 and Tab2 to get ready when you swipe to Tab2, at Tab2 selected will also call getItem for Tab3 to prepare for swipe.


text:
Q: Simulating population-level logistic regression model with pre-specified prevalence I'm interested in simulating the following prospective, population-based model for binary outcome $Y_i$, and independent subjects $i=1,\dots,N$:
$$
\Pr(Y_i=1\mid X_i,G_i)=\frac{1}{1+\exp(-(\alpha_0 + 0.5 X_i + G_i\beta))}
$$
where $X_i\sim N(0,1)$ is a continuous covariate with effect 0.5 (log OR scale), $G_i$ is an $m\times 1$ vector of binary covariates, with corresponding effects $\beta$. The value of $m$ can be large and is usuall around 1000. Each element of $G_i$ is generated independently with some probability $\pi_j$, $j=1,\dots,m$. That is $\mathbb{E}G_{ij}=\pi_j$. $\alpha_0$ is an intercept related to the prevalence, $p_0=\Pr(Y_i=1)$ of outcome in the population.
Question
When I run the following model below, I set $\alpha_0=\log p_0/(1-p_0)-\sum_{j=1}^m\pi_{j}\beta_j$ in the probability model above. The idea of subtracting out the second term is so that on average it can cancel out with $G_i\beta$, leaving just the log odds (first term).
However, I find that my estimated prevalence $\hat{\Pr}(Y_i=1)=\sum_{i=1}^N I(Y=1)/N$=0.27948 is not even close to the value of $p_0=0.01$. This happens because $\sum_{j=1}^m\pi_{j}\beta_j$ is a non-negligible term. How can I set my intercept to get the right estimate?
The probability model I have is a conditional probability and $p_0=\Pr(Y_i=1)$. Taking the expectation with respect to $X$ and $G$ would yield the marginal, but it can get quite messy. Is there a slightly adhoc way just for simulation purposes to get close to the desired $p_0$?
EDIT
Using gung's comments, I've modified the code below so that I fix $\pi_j$'s and $\beta$'s first. Then $\alpha_0$ is searched until the estimate $\hat{\Pr}(Y_i=1)\approx p_0$.
#Population size
N = 100000

#Prevalence of disease
p0 = 0.01

#Continuous covariate
X <- rnorm(N,0,1)

#Number of binary covariates
m = 1000

#Set pi_j to be the same for each binary covariate
pi_j = rep(0.01,m)

#Generate binary covariates for N subjects
#See below for genSpMat definition
G <- genSpMat(nrows=N,ncols=m,col_probs=pi_j)

#Generate betas for each binary covariate
betas <- runif(m,1,4)

#Generate probability model
#Guess alpha0 so that E(pr)~0.01
#Max alpha0 is log(p0/(1-p0))

alpha0 <- log(p0/(1-p0))

pr <- rep(1,N)
#Adjust intercept until population prevalence is reached (to a certain tolerance)
while(abs(mean(pr)-p0) > 2*10^(round(log10(p0))-1)){
  alpha0 <- alpha0 - 1
  pr <- plogis(alpha0 + 0.5*X + as.vector(G%*%betas))
}

Y <- rbinom(N,1,pr) #Outcome

#Generate sparse matrix of 0/1s
genSpMat <- function(nrows, ncols, col_probs) {
  require(Matrix)
  r <- lapply(1:ncols, function(x) {
    p <- col_probs[x]
    i <- sample.int(2L, size = nrows, replace = T, prob = c(1 - p, p))
    which(i == 2L)
  })
  rl <- lengths(r)
  nc <- rep(1:ncols, times = rl) # col indexes
  nr <- unlist(r) # row index
  ddims <- c(nrows, ncols)
  #ngTMatrix output
  sparseMatrix(i = nr, j = nc, dims = ddims,giveCsparse = FALSE)
}

A: If you want the resulting prevalence to have a specific (population) value, you will need to modulate both the distributions of your $X$ variables, and your betas.  You will also need to decide what rate you want for the intercept, and you need to take into account the pattern of correlations amongst your $X$ variables.  In essence, you have several moving parts, but fewer degrees of freedom (for a simpler, analogous example, it may help to read my answer here: How to simulate censored data).  Thus, you will need to stipulate some of these, and solve for the rest.  Note also that given some preferred values for the first few of these, it may not be possible to find values for the last that will get you to the result you want (for examples of this, see the prior answer or here: How to simulate data that satisfy specific constraints such as having specific mean and standard deviation?).  Lastly, note that with multiple $X$'s, there will be an infinite number of possible solutions, for example, possible betas for $X_1$ and $X_2$ could be:
\begin{align}
\beta_1\qquad &\beta_2  \\
\hline  \\[-10pt]
.5\qquad &.2  \\
.4\qquad &.3  \\
.3\qquad &.4  \\
.2\qquad &.5  \\
\!\vdots\qquad &\;\,\vdots
\end{align}
Your situation seems a little bit simpler, in that your $X$'s are all binary, and they are all independent.  You will still need to stipulate values for some of these moving parts, and solve for the last ones.  If I were doing this, I would start by specifying the rate you want for the intercept, and the prevalences of each $X$, then I would generate betas subject to some constraints (e.g., all positive, and must sum to a given limit).