text:
Q: Htaccess rewrites causing infinite loop I am trying to write a redirect for a PDF file in my wordpress install that has shown up in my google webmaster tools with a load of query strings after it, what I want is to have the redirect match any number or query stings after the pdf filename and just redirect directly to the file.
     RewriteRule ^(.*) http://www.example.com/wp-content/uploads/2014/08/test\.pdf$ [R=301,L]

and this also (as well as numerous different iterations)
    RedirectMatch 301   ^/wp-content/uploads/2014/08/test\.pdf(.*)$ /wp-content/uploads/2014/08/test.pdf?

However they either result in a continuous redirect loop, 404 error, or still leave part of the query string
the url has any number of random query strings so something that would catch anything after the filename and just redirect to the bare file is percisely what I am looking for. here is an example of the url:
http://www.example.com/wp-content/uploads/2014/08/test.pdf?test=324234234.ffdsfewrgfdgdfg.234234.234324.2333333&fsdf=3432423.1.34234324&wer=werewrewr
or
http://www.example.com/wp-content/uploads/2014/08/test.pdf?test=324234234.ffdsfewrgfdgdfg.234234.234324.2333333&fsdf=3432423.1.34234324&wer=werewrewr&fsdf=3432423.1.34234324&wer=werewrewr&fsdf=3432423.1.34234324&wer=werewrewr
and what I want to get is just
http://www.example.com/wp-content/uploads/2014/08/test.pdf
Thanks

A: Try something like this with mod_rewrite.
RewriteEngine On
RewriteCond %{QUERY_STRING} .
RewriteCond %{REQUEST_URI} (.+)\.pdf$
RewriteRule ^(.*) /$1? [R=301,L]


text:
Q: How to obtain location based on device unique ID? Well I know this is very inefficient and can be done using Network Providers/GPS but I wanted to know whether location (latitude and longitude) can be obtained from a devices unique ID i.e. WIFI Mac Address, IP address etc.
So coding in Android Studio, I want to provide the unique ID in the code and obtain location based on the unique ID I provide.
Thanks

A: You can't get location from the unique ID. You can however get an approximate latitude and longitude from an IP Address by using a third party lookup service such as IP Find.
The location will be accurate to the city at best, will not give an exact location.
<?php
$request_uri = 'https://ipfind.co';
$ip_address = "8.8.8.8";
$url = $request_uri . "?ip=" . $ip_address;
$document = file_get_contents($url);
$result = json_decode($document);
?>

Result:
{
ip_address: "8.8.8.8",
country: "United States",
country_code: "US",
continent: "North America",
continent_code: "NA",
city: null,
county: null,
region: null,
region_code: null,
timezone: null,
owner: null,
longitude: -97.822,
latitude: 37.751,
currency: "USD",
languages: [
"en-US",
"es-US",
"haw",
"fr"
]
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to validate mat-datepicker input using pattern? I'm using mat-datepicker and the user is able to manually enter in a date. I would like to be able to do something like this to validate the date and make sure it follows the pattern of MM/DD/YYYY:
const dobRegex: RegExp = /((?:0[1-9])|(?:1[0-2]))\/((?:0[0-9])|(?:[1-2][0-9])|(?:3[0-1]))\/(\d{4})/;
public dob: FormControl = new FormControl(null, Validators.compose( [ Validators.required, Validators.pattern(dobRegex)]));

However, when I do the above it doesn't work because mat-datepicker is converting any input with numbers into a Date object. Any other input that aren't numbers will convert it to null.
public date(c: FormControl) {
   console.log(c.value) // This value is already a Date object or null
}

Is there a way in which I can validate the manually entered text using pattern?

A: You can solve the error by setting the minimum Value of input to be 10 characters long and the maximum value of Input to be 10 characters.Then when you enter a numeral, the date-picker will validate the date and also whether it is 10 characters long.
Another method is by overriding the mat-date pickers parsing method by providing
a custom component in your module.
providers: [{ provide: DateAdapter, useClass: UserDateAdapter },]

Then in the component
import { NativeDateAdapter, DateAdapter } from '@angular/material';

export class UserDateAdapter extends NativeDateAdapter {
parse(value: any): Date | null {
 //Your custom parse method
 if ((typeof value === 'string') && (value.indexOf('/') > -1) &&
      value.length == 10) {
        const str = value.split('/');
        const year = Number(str[2]);
        const month = Number(str[0]) - 1;
        const date = Number(str[1]);
        return new Date(year, month, date);
  } else {
         return new Date(undefined);
  }
}

A: Hacky solution that I used switching to Moment.
import { AbstractControl } from '@angular/forms';
import * as moment from 'moment';

import { RegEx } from 'app/consts/regex.const';

export class DateValidator {
  public static isValidFormat(control: AbstractControl) {
    if (moment.isMoment(control.value)) {
      const input = control.value.creationData().input;
      if (typeof input === 'string' && (RegEx.DATE).test(input)
          || typeof input === 'object' && input.hasOwnProperty('year') &&
          input.hasOwnProperty('month') && input.hasOwnProperty('date')) {
        return null;
      }
    }

    if (!control.value && control.errors && control.errors.matDatepickerParse) {
      const datePickerText = control.errors.matDatepickerParse.text;
      if (!datePickerText) {
        return null;
      }
    }

    return { pattern: true };
  }
}


text:
Q: Disable Emacs' auto indentation for JavaScript mode completely I have tried to disable the auto indentation in Emacs in JavaScript for three hours now and could not find a (good) solution.
My Emacs version is 23.3.1 (i486-pc-linux-gnu, GTK+ Version 2.24.3), at least it says that. It is a standard package from Debian Linux (Wheezy), the GUI one.
I found emacs javascript auto indentation (and others), but did not want to install another mode just for removing auto indentation (and there's no garantuee it would work with it), the fundamental mode disables syntax highlighting as well, which I want to keep, C-c C-l does nothing, setting javascript-auto-indent-flag to nil does nothing.
What I want exactly: Insert a tab if and only if I press the TAB key. The "if" part works, but the "only if" part does not. I wonder why it's so hard?

A: In Emacs' Javascript mode, the character } is bound to function js-insert-and-indent.  You can bind it to just insert itself by putting this code into your .emacs startup file:
(defun my-js-mode-hook ()
  "My personal Javascript mode hook."
  (local-set-key (kbd "TAB") 'tab-to-tab-stop)
  (local-set-key (kbd "RET") '(lambda () (interactive) (newline 1)))
  (local-set-key (kbd "SPC") 'self-insert)
  (local-set-key (kbd "}") 'self-insert))

(add-hook 'js-mode-hook 'my-js-mode-hook)

and restarting Emacs.  If you find other characters like that, you can add more calls to local-set-key in your hook function, each with a different character passed to the kbd function.


text:
Q: Entering Unicode data in Visual Studio, C# Is there a good way to type Unicode symbols in a C# file?
I'm looking for something to the effect of:

*

*Press ALT

*Type Unicode Hex

*Release Alt

Currently, I'm having to type the symbol into word and copy-paste it into my source file.

A: The answer of Neutrino activated the Alt+Numpad input method (Microsoft Glossary), but I had to search for the correct registry path. It is:

*Navigate to HKCU\Control Panel\Input Method

I tried to write a Unicode-char within my comments in source (.
Unfortunately I cannot enter a Unicode code point, like shown in charmap, to get the corresponding character.

*

*Using [Alt]+[+]+<xxxx>, where the hexadecimal Unicode code point (4-figure) replaces the xxxx, does not enter any character (neither [Numpad +] nor regular [+] key), when using the regular numeric keys.

*Meanwhile using Numpad for the 4-figured code (it has digits only), it is irrelevant to hit [+] before entering the Unicode code point. It just writes the same character like without preceding [+] (or in my case with preceding zero [0]). The entered character is the one defined in the codepage.

*Just for curiosity I have tried also using the decimal code (0x2192 = 8594) or switching the codepage via chcp. But it does not change anything.

Unluckily I find no way to convince Windows to enter the char with its U+xxxx code presented  within Windows' own charmap.
Luckily, there people share this problem over multiple programs, not just Visual Studio. So the folks at http://www.fileformat.info provide several tipps in an article for Windows, among them a self written UnicodeInput Utility which solves it.
Though I still think, Windows should have an built-in solution.
(PS: I would have added a comment, but my reputation is still too low.)

A: It appears that Visual Studio, by default, does not allow the use of many of the ALT codes.  The work around is to just paste in the Unicode symbol.
1) run charmap.exe.
2) click advanced view.
3) search for the symbol you want (by name or code number).
4) copy the symbol you want.
5) paste it into your document.

charmap.exe comes standard with windows.  You can use it to insert any Unicode symbol.

A: I have to say that I don't think the selected answer actually answers the question at all. Entering the Unicode code point as a escape sequence in a string literal does not result in the Unicode symbol appearing in the file. Adding an escape sequence to a literal and typing the symbol are two different things.
A better answer is:

*

*Open RegEdit

*Navigate to HKCR\Control Panel\Input Method

*Create string key EnableHexNumpad with value "1" (no quotes).

*Reboot.

Now in any source file to type a Unicode symbol hold down ALT and type numpad plus followed by the hexadecimal code point then release ALT.
E.g. For © hold ALT and enter +00a9.
Works in most windows apps, including Firefox :)

A: You can copy paste from the Unicode article on Wikipedia:
http://en.wikipedia.org/wiki/List_of_Unicode_characters

A: \uFFFF
\UFFFFFFFF

C# Unicode character escape sequences.

A: Just in case someone is looking how to do this in Linux, Ctrl+Shift+U, then type the code, and finally press Space or Enter, then the character will appear. Works with every application.

A: Another way to use Unicode hex in the Visual Studio code window is to type the HTML entity hex (for example ⚫ ), then select the text, right click (or use Edit menu), and choose "Encode Selection > HTML Decode". It will convert the text into the specified character.

A: In Visual Studio you can enter ALT+dddd where dddd is the four digits of the unicode character number in decimal. For example, pressing 0170 while holding down the ALT key results in entering ª.


text:
Q: Show that $U$ commutes with $T$ if and only if $U$ commutes with each $T_i$ Let $T$ be a normal operator on a finite-dimensional complex inner product space $V$. Use the spectral decomposition $T=\lambda_1T_1+\dots+\lambda_kT_k$ to prove that if $U$ is a linear operator on $V$, then if $U$ commutes with $T$, $U$ commutes with each $T_i$.
$UT=TU$
$U(\lambda_1T_1+\dots+\lambda_kT_k)=(\lambda_1T_1+\dots+\lambda_kT_k)U$
Couple things I have tried are to plug in an orthonormal basis of eigenvectors and to use the fact that $g(T)=\sum_{i=1}^k g(\lambda_i)T_i$ if $g$ is a polynomial but neither led anywhere.
Other post said that because a polynomial $g_i$ such that $g_i(T)=T_i$ can be defined for each $i$, then $g_i(T)U=Ug_i(T)$ however I fail to see why you can ignore the $U$ when taking the $g_i$ of both sides?

A: \begin{split}
g(T)U&=(\alpha_nT^n+\dots+\alpha_0)U\\
&=U(\alpha_nT^n+\dots+\alpha_0)\\
&=Ug(T)
\end{split}
Then let $g(T)=g_i(T)=T_i$ for all $i$ (as each $T_i$ is a polynomial in $T$, $g_i(T)$)


text:
Q: GridView Docking Issue I have a gridview and textbox control in my form. Textbox is on left top and under gridview anchored left, right and bottom. I want it saves the distance with textbox above it. This is my code below and it doesn't save the distance between textbox. when i make the window full screen there are so much distance between them as image.
dataGridView1.Anchor = (AnchorStyles.Left | AnchorStyles.Right | AnchorStyles.Bottom);

A: this is what you need
  private void Form2_Load(object sender, EventArgs e)
        {
  //just setting panel color to red. so you can see the panel.
 var panel = new Panel() {  BackColor= Color.Red};
            this.Controls.Add(panel);
            panel.Dock = DockStyle.Top;
            var textBox = new TextBox() {  Top = 20, Left = 20, Height=10, Width=330};
            panel.Controls.Add(textBox);

            var dataGridView = new DataGridView() ;

            dataGridView.Columns.Add("Name","Text");
            this.Controls.Add(dataGridView);
            dataGridView.AutoGenerateColumns = true;
            dataGridView.DataSource = Enumerable.Range(0, 10).ToList();
            dataGridView.BringToFront();
            dataGridView.Dock = DockStyle.Fill;
}


text:
Q: IOS 5.0 - NSURLConnection works but returns Null before completing I have a class file called functions where I keep repetitive tasks.  One of the functions in there is called GetPrice which connects to an XML web service, parses the XML and returns a CarPrice object.  Everything works great until it's time to return the CarPrice object.  It is NULL even though in my connectionDidFinishLoading, the object is not null.
Here is my GetPrice function:
-(CarPrice*)GetPrice:(NSString *)m
{
    NSString *url =[@"http://myUrl.com"];

    dataWebService = [NSMutableData data];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString: url]];
    NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
    [conn start];
    return mp;  //mp is declared as a CarPrice in the @interface section of my funcs class

    //when it gets returned here it is NULL even though....(see below)
}

//Connection Functions=======================

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{

    [dataWebService setLength:0];
}

-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {

    [dataWebService appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection{

    NSString *responseString = [[NSString alloc] initWithData:dataWebService encoding:NSUTF8StringEncoding];
    ParserMetal *pmr = [ParserMetal alloc];
    mp = [pmr parseMetal:responseString];
    //at this point, the mp is fully populated
    //an NSLOG(@"%@", mp.displayPrice); here will show that the mp object is populated
    //however as stated above, when it returns, it is null.
}

-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    NSLog(@"Error during Connection: %@", [error description]);
}

//End Connection Functions ==================

Is the return mp; happening before the mp gets populated?  Do I need to use a Synchronous connection here to make sure the data is populated before the return?

A: If I understand your code correctly, you are going to call GetPrice:m: and then start the connection from there. After you start the connection by using [connection start], you immediately return mp.
This means that the connection is started, but before it has received all its data, you already return mp. You should wait for the data to be received, and then return mp.
You could use a Synchronous method for this, or you could implement a method in your main class, which is going to be called from within the connectionDidFinishLoading:connection: method, defined in your 'other class file'. Like this:

*

*Start connection

*Receive data...

*Call [mainClass didReceiveAllData:mp]
Hope this helps.


text:
Q: SendResponse fails when using a Promise In the extension I am building, on click of a button, a request is sent from ChromeUtils.js
 return new Promise(function(fulfill,reject){
            var request = {
                type : "background.twitterRequestToken",
            };
            chrome.runtime.sendMessage(request, function(response) {

                if (response)
                {
                    fulfill(response);
                }
                else
                {
                    reject(response);
                }
            });
        });

to the background.js which in turn calls an oauth Api to send a request to the remote server.
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {

    console.log("background.js: " + JSON.stringify(request));

    var type = request.type;

    if (type == "background.twitterRequestToken")
    {
        oauth.authorize().then(function(token,secret,userId,screenname){
            console.log("Sending Response on Authorize");
            sendResponse({success:true,userId:userId,screenName:screenname});
        });
        console.log("Before Return true");
        return true;
    }

I am using the oauth scripts from the example given at https://developer.chrome.com/extensions/tut_oauth but due to a requirement have modified the oauth to use promise. When implemented as a promise, the sendResponse fails but when using the default implementation using callbacks. the sendResponse goes through.
Default implementation using callbacks:
if (type == "background.twitterRequestToken")
    {
        oauth.authorize(function(token,secret,userId,screenname){
            console.log("Sending Response on Authorize");
            sendResponse({success:true,userId:userId,screenName:screenname});
        });
        console.log("Before Return true");
        return true;
    }

Error message in the background console when implemented as a promise is
Uncaught (in promise) Error: Attempting to use a disconnected port object

The reason I want to use a promise is that when sending signedRequests using Oauth, I want to include part of the xhr response in the sendResponse, e.g. as shown below.
if (type == "background.tweet")
{
    var status = request.tweet.text;
    var url = "https://api.twitter.com/1.1/statuses/update.json";
    var request = {
        'method':'POST',
        'parameters': {
            'status':status
        }
    }

    oauth.sendSignedRequest(url,request).then(signedRequestCallback).then(function(resp,xhr){
        console.log("signedRequestCallback success");
        console.log("Sending response");
        sendResponse({success:true,status_id:resp.id});
    });

    return true;

}

I have already included return true in my code and as I explained it works fine when not using Promise. It fails when using Promise because the of the error message I included.
===============Update========
To repro this I created a simpler example but I do not face the issue there when I use a Promise. So this may not have anything to do with Promise.


text:
Q: Recording composite video to an audio file I'm trying to record raw composite video siganl to an audio file by connecting the yellow rca cable from a player to the mic input in my pc so I can then put the cable in my audio output and connect it with the video input in an old crt tv and play back the signal to the tv so that I can view the original video.
But that didn't work and I can only see random white lines.
Is that due to frequency limits in the audio format or in the onboard audio chip, or is analog-digital conversion and the other way when recording and playing back damaging the signal?

A: Video signals operate in ranges above 1 Mhz, where high-quality audio signals only max out at ~96Khz. Video signals would likely need to be be encoded in a format that an audio recorder could pick up, then decoded back into a video signal before a television could render it properly. This answer on the Sound Design exchange may be of interest to you.

A: A very high bitrate uncompressed audio file may be able to store a low-fidelity video signal, a black and white signal could be stored at sub-vhs quality, but could be at least a resolvable image, recording component video may be possible even though syncing the seperate tracks would be hard.

A: I tried it.
Sampling rate is 192KHz. It can record up to 192/2=96KHz.
I succeed to capture part of luminance signal.
Color signal is in very high frequency.
So we can't record color signal using soundcard.
Video is very distorted.
However we may can caputure more clearly using soundcard more highter sampling rate.
https://m.youtube.com/watch?v=-Q_YraNAGhw&feature=youtu.be


text:
Q: Cannot edit Initiation Form of Designer Workflows with InfoPath I've got a reusable SP Designer workflow in SharePoint 2010, and I'm trying to edit the Initiation Form for it. I can open the workflow within SP Designer, click the form, and it opens in InfoPath. I then make the changes that I want, and try to Save/Publish it back to the server. When I do so, I get the following error:

The following URL is not valid: http://myserver.domain.com/sites/mysite/Workflows/My Workflow Name/My Workflow Name.xsn

I've tried looking in the SP logs, and don't see anything relevant at the time I try to publish the form. I can make the changes to forms on my dev box that has InfoPath installed locally. But when I take a site backup and restore onto the production server, then try to make any form edits using InfoPath on my client, I get the same error.
Any thoughts on what the cause might be and how I can resolve it?

A: As far as I could understand the problem is how to migrate and relink workflow to another URL/location/server
That is there is no OOTB possibility to change publish location in Infopath form templates of types/compatibility Sharepoint List Form and WorkFlow Form and one needs to use workarounds for this, i.e. hack Infopath form template source files.

A: Can you remove the initiation form from the workflow by selecting the form and pressing 'del' key. And then try to make your changes.


text:
Q: How to query all spatial trajectories that go from one region to another Consider a mongo db where each document corresponds to a spatial trajectory. That is, there is a field that contains an array for each document. Each array is a sequence of latitude/longitude pairs representing a geographical trajectory. Given two geographical regions R1, R2 defined by geojson polygones, find all trajectories that intersect first R1 and second R2. Given the size of the db, computational time is highly important.
My first attempt works but does not consider direction. Moreover, it is extremely slow. I use an aggregate framework (regions gjs[i]). My current pipeline contains the following.
{"$match":{"location.lonlat":{'$geoIntersects':{'$geometry':gjs[0]}}}}, {"$match":{"location.lonlat":{'$geoIntersects':{'$geometry':gjs[1]}}}}

A: From the MongoDB manual :
$geoIntersects uses spherical geometry. $geoIntersects does not require a geospatial index. However, a geospatial index will improve query performance. Only the 2dsphere geospatial index supports $geoIntersects.
So you have a problem:  your query works because $geoIntersects does not require an index but it is slow because there is no index.  To speed it up, you must create a 2dsphere index because that is the only index (i.e. NOT a 2d index) used by $geoIntersects -- which unfortunately will not work on legacy arrays of coordinate points (your "trajectories").
My recommendation is to go full GeoJSON:

*

*Convert your location.lonlat array of points to GeoJSON LineString object, e.g.

{location: {
        "trajectory" : {
            "type" : "LineString",
            "coordinates" : [ [10,60] , [10,61] , [10,62] ]
        }
    },

You could do this with a non-destructive update to create a new field trajectory as a peer to lonlat in the location object.  Note the use of the array form of update() that permits pipelines and thus the $location.lonlat array can be copied into the new field:
db.foo.update({}, [ {$set: {"location.trajectory": {type: "LineString", coordinates: "$location.lonlat"}}} ], {multi:true});

*Create a 2dsphere index on location.trajectory:

db.foo.createIndex({"location.trajectory":"2dsphere"});

Your queries will now be performant.


text:
Q: Popup screen position change in blackberry application when i click on Buttonfield i want to show Popup screen .everything working fine .but that PopupScreen open by default at the center of the Mainscreen.
i have already try this code.setMargin and setPosstion method to change the possition. but its not working as my requrement .
i want to open that Popupscreen at the top of Mainscreen with Animation(top to bottom).
and another issue is that in this popup screen there is one Edittextfield ..when i click on edittext field keyboard open fine but at that time device Menu button not working and i cant access keyborad hide functionality ..
how to set popup screen at the top of the mainscreen ?

A: Have you tried overriding the sublayout() method in the popupScreen class ?

protected void sublayout(int width, int height) {

        super.sublayout(width, height);

       // replace x,y with your values //

        setPosition(x, y);

    }
HOWEVER, if you are trying to animate the popup screen from top to bottom, you are better off using EyelidFieldManager, it does the animation for you :)
Try:
EyelidFieldManager Sample
EyelidFieldManager API


text:
Q: stored procedure - function performance difference i have a table valued function with quite some code inside, doing multiple join selects and calling sub-functions and returns a result set. during the development of this function, at some point, i faced a performance degradation when executing the function. normally it shouldn't take more than 1 sec but it started taking about 10 sec. I played a bit with joins and also indexes but nothing changed dramatically.
after some time of changes and research, I wanted to see the results with another way. I created the same exact code with same exact parameters as a stored procedure. then i executed the sp. boom! it takes less then 1 sec. the same exact code takes about 10 sec with a function.
i really cannot figure out what this all about and i have no time to do more research. I need it as a function for some reasons but i don't know what to do at this point. I thought i could create it as a proc then call it within the function but then i realized it's not possible to do it for functions.
i wanted to hear some good views and advice here from experts.
thanks in advance
ps:i did not add any code here as the code is not in a good format and quite dirty. i would share it if anybody is interested. server is sql 2014 enterprise 64 bit
edit: i saw the possible duplicate question before but it did not satisfy me as my question is specifically about performance hit. the other question has many answers about general differences between procedures and functions. i want to make it more clear about possible performance related differences.

A: These are the differences from my experience:

*

*When you first started writing the function, you are likely to run it with the same parameters again & again until it works correctly. This enables page caching in which SQL Server keeps the relevant data in memory.

*Functions do not cache their execution plans. As you add more data, it takes longer to come up with a plan. SET STATISTICS TIME ON to see query compilation time vs. execution time.

*Functions can only use table variables and there's no stats on those. That can make for some horrendous JOIN decisions later.

Some people prefer table-valued functions because they are easier to query:
SELECT * FROM fcn_myfunc(...) WHERE <some_conditions>

Instead of creating a temp table, exec the stored procedure then filter off that temp table. If your code is performance critical, turn it into a stored procedure.


text:
Q: how to sort multidimensional array in code igniter i have a array and i want to sort it according to created field, i tried to sort it by some code but i can't do this so please help me, for this i have some code my code is not working...                  ,
Array
(
[0] => stdClass Object
    (
        [status_id] => 26
        [message] => this is test
        [created] => 2013-03-05 23:11:54
        [uid] => 1
        [first_name] => sandeep
        [last_name] => singh
    )

[1] => stdClass Object
    (
        [status_id] => 27
        [message] => this is sisfd
        [created] => 2013-09-10 22:28:46
        [uid] => 1
        [first_name] => sandeep
        [last_name] => singh
    )

[2] => stdClass Object
    (
        [status_id] => 28
        [message] => nvcbncvnbcvnbvcnb
        [created] => 2013-09-25 22:29:12
        [uid] => 1
        [first_name] => sandeep
        [last_name] => singh
    )

[3] => stdClass Object
    (
        [status_id] => 29
        [message] => this is time test
        [created] => 2013-09-10 23:08:52
        [uid] => 1
        [first_name] => sandeep
        [last_name] => singh
    )

[4] => stdClass Object
    (
        [status_id] => 30
        [message] => thuiso9safdasdfasdfasdfasdf
        [created] => 2013-09-26 00:41:15
        [uid] => 1
        [first_name] => sandeep
        [last_name] => singh
    )

)

A: Try this
 $yourarray = array(array(...), array(....),.....);

 function myFieldSort($a, $b)
 {
   return $b['created'] - $a['created'];
 }

 usort($yourarray, "myFieldSort");

A: function array_multi_subsort($array, $subkey)
{
    $b = array(); $c = array();

    foreach ($array as $k => $v)
    {
        $b[$k] = strtolower($v[$subkey]);
    }

    asort($b);
    foreach ($b as $key => $val)
    {
        $c[] = $array[$key];
    }

    return $c;
}

// sorting through "created" element in the arrays
$data = array_multi_subsort($array, 'created');
print_r($data);

Also reference on PHP.net manual:
http://php.net/manual/en/function.array-multisort.php

A: Please try this :
function array_multi_subsort($array, $subkey)
{
    $b = array(); $c = array();

    foreach ($array as $k => $v)
    {
        $b[$k] = strtolower($v->$subkey);
    }

    asort($b);
    foreach ($b as $key => $val)
    {
        $c[] = $array[$key];
    }

    return $c;
}

// sorting through "created" element in the arrays
$data = array_multi_subsort($array, 'created');
print_r($data);


text:
Q: How can I replace a block of text inside another file I edited the post and I follow your advice, I splitted my work in more files.
I want to replace a text block inside a file but after a delimiter
<-FROM NEXT LINE->
code to be replaced
code to be replaced
code to be replaced
<-TO THE LINE ABOVE->

Because I collect online data, time by time the data is different, so the code that have to be replaced is different too.
This's the portion of the script:
#!/bin/bash

set -x

########## CONFIGURATIONS ##########
live_data_url='https://www.somedata.com/api/url'

live_data_list_file=~/jjjjjjjj
file_to_modify=~/kkkkkkk
########## CONFIGURATIONS ##########

########## FUNCTIONS ##########
function upgrade() {
    echo "Downloading/Upgrading traker data ..."

    wget -O $live_data_list_file $live_data_url
    if [[ $? -ne 0 ]]; then
        echo "I can't download the data, I'll use a static one"
        exit 9
    fi

    echo "Downloading/Upgrading done."
}
########## FUNCTIONS ##########

upgrade

sed -i -ne '/STARTINGPOINT+1LINE/ {p; r $live_data_list_file' -e ':a; n; /ENDINGPOINT-1LINE/ {p; b}; ba}; p' $file_to_modify

The goal is to upgrade the block inside the $file_to_modify section:
<-FROM NEXT LINE->
code to be replaced
code to be replaced
code to be replaced
<-TO THE LINE ABOVE->

so I searched a bit and I found a good starting point, but I don't know how to modify it. Is not a requisite the use of sed, maybe exist a better way to do this
Actually I've 2 difficulty
1. I need to start after the line that contain <-FROM NEXT LINE-> and I need to stop the line above <-TO THE LINE ABOVE->
2. The expansion of $live_data_list_file inside the sed phase is not working, so I can't take data from file.
Do you have a better idea to do this?

A: Instead of storing the data in your script, leave the live data file alone. That is, download the data to $live_data_list_file, have wget download to a temporary file, and, if wget succeeds, then copy the temporary over the live data file. Also, then you don't edit that file elsewhere - it must be left pristine for the next run in case wget fails.
Perhaps something like this:
function upgrade() {
    echo "Downloading/Upgrading tracker data ..."

    # grab the current data into a temporary file
    wget -O ${live_data_list_file}.temp $live_data_url
    if [[ $? -ne 0 ]]; then
        echo "I can't download the data, I'll use the last one"
    else
        # succeeded, so the temp file is our real file.
        mv ${live_data_list_file}.temp ${live_data_list_file}
    fi

    echo "Downloading/Upgrading done."
}

upgrade()

# don't modify ${live_data_list_file} in the rest of your code - use another temporary file if you need to modify it.
# and just use ${live_data_list_file}, not the data "inside" your code


text:
Q: Actionscript 3 - How do I remove the menu bar, scrollbar, to just have a blank popup? I have a auto open popup using Actionscript 3 and I don't want it to have any of the menu bars, scroll bars none of that, can anyone help me, here is my code:
var url:String = "https://www.google.co.uk/?gws_rd=ssl";

var request:URLRequest = new URLRequest(url);
try {

 navigateToURL(request, '_blank'); // second argument is target
} catch (e:Error) {

trace("Error occurred!");
}

A: You need to use ExternalInterface. Call JS function window.open with next arguments:
ExternalInterface.call("window.open", 'http://stackoverflow.com','winname',
'directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=400,height=350');


text:
Q: Why does connecting to a cluster constantly loop in IoRedis? I am currently trying to connect to my Redis cluster stored on another instance from a server running my application. I am using IoRedis to interface between my application and my Redis instance and it worked fine when there was only a single Redis node running. However, after trying to setup the cluster connection in my Node application, it constantly loops on the connection. My cluster setup works correctly.
As of now, I have tried the following configuration in my application to connect to the cluster. The issue is that the 'connect' even constantly loops printing out 'Connected to Redis!'. The events for 'ready' and 'error' are never fired.
const cache: Cluster = new Cluster([{
   port: 8000,
   host: REDIS_HOST
}, {
   port: 8001,
   host: REDIS_HOST
}, {
   port: 8002,
   host: REDIS_HOST
}]);

cache.on('connect', () => {
    console.log('Connected to Redis!');
});

In the end, the 'connect' event should only fire once. Does anyone have any thoughts on this?

A: This kind of error, as I discovered it today, is not related to ioredis but to the redis instance setup. In my case, the problem I had with p3x-redis-ui, which use ioredis, it was the cluster that was not initialized.
See https://github.com/patrikx3/redis-ui/issues/48
maybe you'll find any clues to help you resolve your bug.


text:
Q: How can I properly get the height of a UIViewController's subview? I can't understand this, should be an easy question tho.
I have a ViewController in a navigation controller. 2 views more or less. Top view is a tableview that takes up 95% of the view, and has top/leading/trailing. 2nd view is a fixed 44 height UIView at the bottom, with leading/trailing/bottom... and vertical spacing to tableView.
On viewDidLoad, I print out the CGRect's for the tableview, the fixed 44 height uiview, and the main view. I get this...
tableViewRect: {{0, 64}, {600, 492}}
fixedHeightViewRect: {{0, 556}, {600, 44}}
self.view: {{0, 0}, {375, 667}}

However, I look at it on my device and the fixed 44 height view is CLEARLY at the very bottom of my phone.
Something is wonky here. If the entire height of the display is 667, yet the fixedHeightView is starting at 556 and is 44 high, therefore its on screen vertically between 556 and 600... how am I able to see it at the very bottom of my screen, a screen which is 667 in height.
I would expect fixedHeight would start at Y: 623 (going to 667). I would then in turn expect the height of my tableView to be 559.
However, I'm not getting this. Why is that?


text:
Q: Integrating ASP.NET Page With MS Excel as DB I want to create a ASP.NET application which will fetch and store data from excel. For eg. currently i have automated excel reports using VBA and Macros, and user have to oem all the excels to get the data/charts/tables. All i want to let them open an asp.net application and from there only they can fetch reports, edit the reports and save the data and my excel will be used as DB. Please suggest is it's possible and if possible.

A: As far as extracting the excel spreadsheet data you can take a look at this post to see a couple alternatives.
As far as getting around the concurrent access issue, you can store the excel information in some form of multi-user concurrent persistant storage - could be on disk or in-memory store (sql server, couchbase, memcache, etc...) and then access information from that store on user request.


text:
Q: Neo4j Complex Queries (DARK TV SERIES) I have a Java project with Neo4j that links the different characters in the Dark(Netflix) series.
I now have to create different "complex" queries in Cypher.
A complex query is defined by the fact that we don't know what kind of data will be returne, but I'm not sure I understand what that means.
Is there anyone who can give me an example of a complex query for my project?
Here is my Java Code :
package dao;

import domaine.Personnage;
import org.neo4j.driver.GraphDatabase;
import org.neo4j.driver.*;
import org.neo4j.driver.Record;
import org.neo4j.driver.types.Node;

import java.util.List;

public class BDD {
    public static Session connect_db() {
        return GraphDatabase.driver("bolt://localhost:7687").session();
    }
    public static void import_base(Session bdd) {
        delete_all(bdd);
        List<Personnage> persos = Data.get_liste_personnages();
        //Create the SicMundus node
        bdd.run("CREATE (s:SicMundus {name: 'Sic Mundus Creatus Est'})");
        //Creation of the
        for (Personnage p : persos) {
            try {
                Result res = bdd.run("MATCH (p:Personne) WHERE p.nom='" + p.getLastname() + "' AND p.prenom='" + p.getName() + "' RETURN p");
                bdd.run("MERGE (f:Famille {famille: $famille})", Values.parameters("famille", p.getLastname()));

                Value p1 = res.next().get("p");
                //verifie si l'année existe déjà
                Result res2 = bdd.run("MATCH (a:Annee) WHERE a.annee=" + p.getYears() + " RETURN a");
                Value a1 = res2.next().get("a");
            } catch (Exception e) {
                //bdd.run("CREATE (p:Personne {nom:'" + p.getName() + "', genre:'" + p.getGender() + "', aliases: '" + p.getAlias() + "',
                // marriedTo:'" + p.getMarried() + "', parentOf:'" + p.getParentOf() + "', childOf:'" + p.getParents() + "', siblings:'" + p.getSiblings() + "',
                // killedby:'" + p.getKilledBy() + "', sicMundus:'" + p.getSicMundus() + "'})");
                bdd.run("CREATE (p:Personne {nom: $name, genre: $gender, aliases: $aliases, lastname: $lastname})", Values.parameters("name", p.getName(), "gender",
                        p.getGender(), "aliases", p.getAlias(), "lastname", p.getLastname()));
                //Create the nodes for each year
                for (int i = 0; i < p.getYears().size(); i++) {
                    bdd.run("MERGE (a:Annee {annee: $annee})", Values.parameters("annee", p.getYears().get(i)));
                }
            }
        }
        for (Personnage p : persos){
            //match les personne avec leur famille via lastname seulement une fois
            bdd.run("MATCH (p:Personne {nom: $name, lastname: $lastname}), (f:Famille {famille: $famille}) MERGE (p)-[:FAMILY]->(f)",
                    Values.parameters("name", p.getName(), "lastname", p.getLastname(), "famille", p.getLastname()));

            //Match les personnes entre elles via leur attribut parentof
            if(p.hasParents()){
                for (int i = 0; i < p.getParents().size(); i++) {
                    bdd.run("MATCH (p:Personne {nom:'" + p.getName() + "'}), (p2:Personne {nom:'" + p.getParents().get(i) + "'}) CREATE (p)-[:CHILDOF]->(p2)");
                }
            }
            if(p.hasKids()){
                for (int i = 0; i < p.getParentOf().size(); i++) {
                    bdd.run("MATCH (p:Personne {nom:'" + p.getName() + "'}), (p2:Personne {nom:'" + p.getParentOf().get(i) + "'}) CREATE (p2)<-[:PARENTOF]-(p)");
                }
            }
            if(p.isMarried()){
                bdd.run("MATCH (p:Personne {nom:'" + p.getName() + "'}), (p2:Personne {nom:'" + p.getMarried() + "'}) CREATE (p)-[:MARRIED]->(p2)");
            }
            //Match les personnes entre elles via leur attribut siblings
            if(p.hasSiblings()){
                for (int i = 0; i < p.getSiblings().size(); i++) {
                    bdd.run("MATCH (p:Personne {nom:'" + p.getName() + "'}), (p2:Personne {nom:'" + p.getSiblings().get(i) + "'}) CREATE (p)-[:SIBLINGS]->(p2)");
                }
            }
            //Match les personnes entre elles via leur attribut killedby
            bdd.run("MATCH (p:Personne {nom:'" + p.getName() + "'}), (p2:Personne {nom:'" + p.getKilledBy() + "'}) CREATE (p)-[:KILLEDBY]->(p2)");
            //Create sic mundus relations
            if(p.getSicMundus())
                bdd.run("MATCH (p:Personne {nom:'" + p.getName() + "'}), (s:SicMundus) CREATE (p)-[:SICMUNDUS]->(s)");
            //match personnes et années
            for (int i = 0; i < p.getYears().size(); i++) {
                bdd.run("MATCH (p:Personne {nom:'" + p.getName() + "'}), (a:Annee {annee:" + p.getYears().get(i) + "}) CREATE (p)-[:LIVEIN]->(a)");
            }
        }
    }
    public static void delete_all(Session bdd){
        bdd.run("match (a) -[r] -> () delete a, r");

        bdd.run("match (a) delete a");
    }

}

Here is the graph :
Neo4j Dark Graph
Here is an exemple of a query i've made :
public static void afficher_personnes_saut(Session bdd){
Result res2 = bdd.run("MATCH (c:Personne)-[r:LIVEIN]->(y:Annee)\n" +
                "WITH c AS personne, y\n" +
                "ORDER BY y.annee\n" +
                "WITH personne, reverse(collect(y.annee)) AS annees\n" +
                "WITH personne, annees, range(0, size(annees)-1) AS is\n" +
                "WITH personne, annees, is, annees + (last(annees) - 33) AS isa\n" +
                "WITH personne, annees, reduce(total=0, n IN is | (total + toInteger((isa[n] - isa[n+1]) / 33 - 1))) AS sum\n" +
                "WHERE sum > 0\n" +
                "RETURN personne.nom AS nom, annees AS Annees");
        System.out.println("Liste des personnes ayant sauté des années de façon anormale :");
        //print les personnes ayant sauté des années
        while (res2.hasNext()){
            Record record = res2.next();
            System.out.println(record.get("nom").asString() + " : " + record.get("Annees").asList());
        }

        System.out.println();

    }

The problem is that I know what to expect from this query and don't understand the difference with a complex one.
Here is a query i've made and considered as "complex" :
public static Personnage getRelationsPersonne(Session bdd, String nom) {
        Result res = bdd.run("MATCH (p:Personne)-[r]->(x) WHERE p.nom = '" + nom + "' RETURN p, x, type(r)");
        Personnage perso = new Personnage(nom);
        while (res.hasNext()) {
            Record r = res.next();
            String type = r.get("type(r)").asString();
            switch (type) {
                case "FAMILY":
                    perso.addFamily(r.get("x").asNode().get("famille").asString());
                    break;
                case "PARENTOF":
                    perso.addKid(r.get("x").asNode().get("nom").asString());
                    break;
                case "LIVEIN":
                    perso.addYear(r.get("x").asNode().get("annee").asInt());
                    break;
                case "MARRIED":
                    perso.addSpouse(r.get("x").asNode().get("nom").asString());
                    break;
                case "CHILDOF":
                    perso.addParent(r.get("x").asNode().get("nom").asString());
                    break;
                case "KILLEDBY":
                    perso.addKiller(r.get("x").asNode().get("nom").asString());
                    break;
                case "SIBLINGS":
                    perso.addSibling(r.get("x").asNode().get("nom").asString());
                    break;
                case "SICMUNDUS":
                    perso.addSicMundus(r.get("x").asNode().get("nom").asString());
                    break;
            }
        }
        return perso;
    }

Personnage jonas = BDD.getRelationsPersonne(bdd, "Jonas Kahnwald");
        jonas.ToStringClean();
        System.out.println("-------------------");
        Personnage ulrich = BDD.getRelationsPersonne(bdd, "Ulrich Nielsen");
        ulrich.ToStringClean();

This allows me to get all the nodes to which a given character is connected (French):
Code Printed
I'm now having trouble creating functions similar to this one.


text:
Q: How to use SLIM by default template language instead ERB in Ruby on Rails I need to use Slim-rails in all my Rails projects. How to use Slim-rails by default?

A: use this to generate your rails project
rails new myapp -m https://raw.github.com/RailsApps/rails-composer/master/composer.rb

choose 3 option at beggining of wizard and later will be option about Template engine
besides slim it has many neat options to speedup your rails project setup

A: This is what you want:
http://edgeguides.rubyonrails.org/rails_application_templates.html
Rails Application Templates


text:
Q: PIVOT with selected MONTH() How can I pivot for a column with dates which is MONTH as the parameter?
Example:
Data:
|-----------------------------------|
| def_kstnr | def_zeit | def_datum  |
|-----------------------------------|
| 100       | 3.2      | 2011-11-02 |
| 110       | 2.8      | 2011-02-03 |
| 120       | 5.4      | 2011-11-04 |
| 130       | 2.4      | 2011-08-05 |
| 140       | 4.9      | 2011-09-06 |
| 150       | 1.5      | 2011-10-07 |
| 160       | 2.6      | 2011-12-08 |
|-----------------------------------|

Query:
SELECT
    def_kstnr,
    [1] AS Jan,
    [2] AS Feb,
    [3] AS Mrz,
    [4] AS Apr,
    [5] AS Mai,
    [6] AS Jun,
    [7] AS Jul,
    [8] AS Aug,
    [9] AS Sep,
    [10] AS Okt,
    [11] AS Nov,
    [12] AS Dez
FROM
(Select
def_kstnr,
def_zeit,
 MONTH(def_datum) as TMonth
  from
    dbo.def) source
PIVOT
(
    SUM(def_zeit)
    FOR TMonth
    IN ( [1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12] )
) AS pvtMonth

Result should look like this if the parameter month = 2 (February):
| def_kstnr  |  Feb |
   110          2.8

and if the parameter month = 11 (November)
| def_kstnr  |  Nov |
   100          3.2

I'm already googling, but I don't know what is the keyword for this my case. I haven't find it yet. Thank you..

A: If you're using SQL Server, you can create a dynamic sql like this
DECLARE @Month Int = 11,
        @MonthName VARCHAR(20),
        @Sql NVARCHAR(MAX)

SET     @MonthName = CONVERT(VARCHAR(3), DATEADD(Month, @Month, -1), 107)
SET     @Sql = N'   SELECT  def_kstnr,
                            def_zeit AS ' + QUOTENAME(@MonthName) + '
                    FROM    DataTable
                    WHERE   MONTH([def_datum]) = @Month'

EXEC sp_executesql @Sql, N'@Month INT', @Month = @Month

You can add your SUM(def_zeit) and GROUP BY def_kstnr to the dynamic sql if that is the result you are after.. hard to tell by your expected result


text:
Q: 'Right off the bat' I found that it means fast. But it is not clear in which specific cases it is possible to use it. How to use this expression correctly? Curiously, what is its etymology?
Example: when I see her, I'll know right off the bat. Or. I need it right off the bat.

A: Right off the bat =right from the git-go [sic]= straight out of the gate...
that is right away, or more precisely the incident that follows this introductory phrase was the first significant incident to occur in an experience or series of incidents.

A: "Right off the bat" is what I think you mean.

Immediately; at once; without delay.

(thefreedictionary.com)
As in: "Tom didn't even need to think about the question. He knew the answer right off the bat."

A: Christine Ammer, American Heritage Dictionary of Idioms, second edition (2013) has this brief account of the idiom:

right off the bat Instantly, immediately, as in I can't tell you how many right off the bat, but I can find out. This term alludes to a baseball being hit by a bat. {First half of 1900s}

However, an Elephind search of newspaper databases finds literal instances of "right off the bat" from as early as 1868. From "The Championship: Mutuals vs. Atlantics," in the New York Clipper (October 31, 1868):

Wolters went out on a foul ball taken by Mills. McMahon, after a foul and one strike, put the ball beautifully low to left field, making his base. Swandel[l] then hit to to left field, Chapman made a brisk run for it, but dropped it, and Swandell got to first, McMahon to second. Mills, after two strikes, was taken on a wonderfully sharp tip, right off the bat by his namesake. Then Zettlein hit high to centre field, and Hunt disposed of him nicely; McDonald sending another ball toward Mills, ended the "jig."

and figurative instances from as early as 1888. From the "Where He Got It," in the [Clarksville, Texas] Standard (September 20, 1888):

"Well it is a vice you'd better get rid of then. Refined conversation is a mark of culture. Let me hear that kid use slang again and I'll give it to him right off the bat. I'll wipe up the floor with him. I'll—"

The joke here is that the father is the source of the slang that he criticizes his son for using and suspects his wife of encouraging. Elsewhere in the article, the father uses two other slangy baseball-related expressions: "he'll make a home run of the liveliest kind" and "You are entirely off your base." The latter is still popular as an idiom in the United States in the form "You are off base."
In any case, "right off the bat" meaning literally "glancing, bounding, or moving in a line or arc off a baseball player's bat" dates to at least 1868, and "right off the bat" meaning figuratively "at once" or "right away" dates to at least 1888.


text:
Q: Importing a subfolder from a package I'm trying to use gtfs-realtime-bindings' node module.
The published module on npm is outdated so I'm downloading directly from github. However, gtfs-realtime-bindings is a super repo has subfolders for a lot of different environments.
How can I specify a subfolder in my require?

A: Are you downloading the repo and inserted on your source code? You should be able to use import or require from anywhere, example.
code
__src
____index.js
__gtfs-realtime-bindings
____nodejs
____java

You should be able to get the nodejs files from the index.js using
import nodejs from "../gtfs-realtime-bindings/nodejs";

or
const nodejs = require("../gtfs-realtime-bindings/nodejs");

Obviously, this depends on what you are trying to get, I don't know that repo, but this should work

A: After downloading and extracting the zip file, you can npm install the relative path to your dependencies by running it in the root of your project like this:
npm i ../gtfs-realtime-bindings/nodejs --save

This is assuming that you've extracted the git repository zip adjacent to the project root directory. In your code you can then require('gtfs-realtime-bindings') like you would any other dependency installed via npm.


text:
Q: Is there a python function to catch UDP traffic a machine is forwarding I am running a system with the following configuration:
NODE A   <->   PROXY   <->   SWITCH   <->   PROXY   <-> NODE B
Where node A and its proxy share a common private network, node b and its proxy share a common private network, and the proxy's are connected to the switch.
I have configured each as such:
#nodeA
#!/bin/sh
#Aliases
alias ip='sudo ip'
alias iptables='sudo iptables'

#interfaceconfiguration
ip link set enp0s8 up
ip addr add 192.168.0.1/29 dev enp0s8

iptables -t nat --flush

sudo route add default gw 192.168.0.2 enp0s8

iptables --policy INPUT ACCEPT
iptables --policy FORWARD ACCEPT
iptables --policy OUTPUT ACCEPT

#proxy a
#!/bin/sh
#Aliases
alias ip='sudo ip'
alias iptables='sudo iptables'

#interfaceconfiguration
ip link set enp0s8 up
ip link set enp0s9 up
ip addr add 192.167.0.1/26 dev enp0s9
ip addr add 192.168.0.2/29 dev enp0s8

sudo sysctl net.ipv4.ip_forward=1

iptables -t nat --flush

sudo route add default gw 192.167.0.2 enp0s9
sudo ip route add 192.168.0.0/29 via 192.168.0.2 dev enp0s8

iptables --policy INPUT ACCEPT
iptables --policy FORWARD ACCEPT
iptables --policy OUTPUT ACCEPT

#proxy B
#!/bin/sh
#Aliases
alias ip='sudo ip'
alias iptables='sudo iptables'

#interfaceconfiguration
ip link set enp0s8 up
ip link set enp0s9 up
ip addr add 192.167.0.2/26 dev enp0s9
ip addr add 192.168.0.10/29 dev enp0s8

sudo sysctl net.ipv4.ip_forward=1

iptables -t nat --flush

sudo route add default gw 192.167.0.1 enp0s9
sudo ip route add 192.168.0.8/29 via 192.168.0.10 dev enp0s8

iptables --policy INPUT ACCEPT
iptables --policy FORWARD ACCEPT

#node B
#!/bin/sh
#Aliases
alias ip='sudo ip'
alias iptables='sudo iptables'

#interfaceconfiguration
ip link set enp0s8 up
ip addr add 192.168.0.9/29 dev enp0s8

iptables -t nat --flush

sudo route add default gw 192.168.0.10 enp0s8

iptables --policy INPUT ACCEPT
iptables --policy FORWARD ACCEPT
iptables --policy OUTPUT ACCEPT

iptables --policy OUTPUT ACCEPT

I then have this simple server client code running on NODE A and NODE B just to have some traffic going through the network:
import socket
import sys
#NODE A - SERVER
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('192.168.0.1', 10000)
sock.bind(server_address)

while True:
    data, address = sock.recvfrom(4096)
    print(data.decode())

import socket
import sys
#NODE B - CLIENT
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_address = ('192.168.0.1', 10000)

while True:
    sock.sendto(input("Message to send:").encode(), server_address)

My question is, how can I, at the proxy level intercept these messages to bring them up to the application level so that I can work with them as to add a layer of encryption for example then send them back out to their destination so that the proxy on the other side can decrypt the message.
Thank you

A: This is a perfectly good debugging loop:
while True:
    data, address = sock.recvfrom(4096)
    print(data.decode())

Once you see that the right datagrams are arriving,
that loop will be a natural place to forward datagrams
to your favorite destination.
Ensuring that your listening socket was properly bound can be a tricky thing,
given that you have several addresses and interfaces to worry about.
Consider using $ sudo tcpdump -i en0 udp port 10000 to examine
datagrams in flight, before you even run that debugging loop.
You can use the command on the sending host,
on an intermediate transit host,
and on the destination host.
By viewing $ ifconfig -a you may find that an interface besides en0,
perhaps a tunnel interface, is relevant for reading the packets you're interested in.
Once you know certain packets are flowing,
that tends to make it easier to correctly specify the bind() parameters.

A: I think you're approaching this from the wrong way around. Namely, if you want to "work with" packets on the proxy, then you don't want to be telling the kernel to do any IP level forwarding
the Linux tun/tap interface would let you do this, see here for an example of how this is used with a VPN.  although there are Python packages that help if you really want Python code to be doing the work
as a minor side note, I've generally found it an anti-pattern to put sudo onto basically every line of a script as you have.  I'd just run the entire script via sudo and just have the code in it assume this is the case.


text:
Q: SQL 2014 windows 10 This alert appears, when I want to open any (.sql-) file where I want to create new database or new query.

Class not registered.
  Looking for object with CLSID
  {D8CB03CB-A124-4E7F-9EB2-788F351367A2}


text:
Q: How do you count occurrences in multiple columns and order results by calculation of counted columns in MySQL? I am trying to count occurrences in multiple columns and then output the results and order them based on a calculation.
Count how many times a killer_uid has occurred. Then count how many times their ID occurs in victim_uid. Then output the results based on the count of killer_uid / victim_uid. Please see example tables and desired output below.
Table = kill_feed
+------------+------------+
| killer_uid | victim_uid |
+------------+------------+
|          1 |          2 |
|          2 |          3 |
|          2 |          3 |
|          2 |          1 |
|          2 |          1 |
|          1 |          1 |
+------------+------------+

Desired Output:
killer_uid as player_id,
count instances of killer_uid AS player_kills and victim_uid AS player_deaths,
then divide player_kills / player_deaths (return 0 if divide by 0) and order by those results DESC.
+-----------+--------------+---------------+
| player_id | player_kills | player_deaths |
+-----------+--------------+---------------+
|         2 |            4 |             1 |
|         1 |            2 |             3 |
|         3 |            0 |             2 |
+-----------+--------------+---------------+

Order by player_kills / player_deaths
1st = 2 since 4/1 = 4
2nd = 1 since 2/3 = 0.66
3rd = 3 since 0/2 = 0

The statement I have tried using but throws a syntax error.
SELECT killer_uid as player_id,
       Count(killer_uid) AS player_kills,
       Count(victim_uid) AS player_deaths
FROM   kill_feed
GROUP  BY player_id
ORDER  BY player_kills / player_deaths DESC

A: E.g.:
DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,killer_uid INT NOT NULL
,victim_uid INT NOT NULL
);

INSERT INTO my_table (killer_uid,victim_uid) VALUES
(1,2),
(2,3),
(2,3),
(2,1),
(2,1),
(1,1);

SELECT player_id
     , SUM(x) player_kills
     , SUM(y) player_deaths
  FROM
     ( SELECT killer_uid player_id
            , 1 x
            , 0 y
         FROM my_table
        UNION ALL
       SELECT victim_uid
            , 0
            , 1
         FROM my_table
     ) x
 GROUP
    BY player_id
 ORDER
    BY COALESCE(SUM(x)/SUM(y),SUM(x)) DESC;
+-----------+--------------+---------------+
| player_id | player_kills | player_deaths |
+-----------+--------------+---------------+
|         2 |            4 |             1 |
|         1 |            2 |             3 |
|         3 |            0 |             2 |
+-----------+--------------+---------------+


text:
Q: UILabel is nil- canot update text of UILabel So this a beginner's question, I have to admit, to you guys, but I really have no idea what I should do ,and it have taken me several hrs to try to fix it.
So:  My question is that why the UILabel is nil when I want to update its text?
Details:
1:I have two Views and DetectionView is the initial View where there is a UILabel and a bar button item named "Setting" in the toolbat at the button of this view, and second View is the EnterCommandView where there is a UITextField and a bar button item named "save" in the toolbar at the top of this view.
2: After I enter a String, After the app finish launching, I click Setting, then I segue form first View to second View. In second, I enter some string in the UITextField and then click "Save" button, the second View is dismissed, and then I go back to the Initial View,
3: When I go back to the InitialView, the String just entered should appear in the UILabel, but , right it does not, which is exactly my problem, And then I set a breakpoint at the place where I update the UILabel, I have the info at the end of this post, saying UILabel is nil
Code:
EnterCommnadViewController.h
#import <UIKit/UIKit.h>
#import "RscMgr.h"

@protocol EnterCommandDelegate <NSObject>
@optional
-(void) commandEntered:(NSString*)command;
@end
@interface EnterCommandViewController : UIViewController  <RscMgrDelegate,EnterCommandDelegate>
{
RscMgr* rscMgr;
IBOutlet UITextField *inputTextField;
}
-(void)sendMessage:(NSString*)message;
-(id)initWithDelegate:(id)delegateToBe;
- (IBAction)cancelPressed;
- (IBAction)savePressed;
@property (nonatomic,weak) id<EnterCommandDelegate> delegate;
@end

EnterCommandViewController.m
#import "EnterCommandViewController.h"
#import "DetectionViewController.h"
@interface EnterCommandViewController () <UITextFieldDelegate>
{
@private
BOOL connected;
}
@end
@implementation EnterCommandViewController
@synthesize delegate;

- (void)viewDidLoad {
[super viewDidLoad];
[inputTextField becomeFirstResponder];
}

-(void) viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
inputTextField.delegate = self;
}

-(void) viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
inputTextField.delegate = nil;
}

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
- (IBAction)cancelPressed {
[self dismissViewControllerAnimated:YES completion:^{}];
}

- (IBAction)savePressed {
if([[[UIDevice currentDevice]systemVersion] compare:@"7.0"  options:NSNumericSearch] != NSOrderedAscending){
    NSLog(@"SYStem version > 7.0");
}
if(delegate&&[delegate respondsToSelector:@selector(commandEntered:)]){
    [delegate commandEntered:inputTextField.text];
}
[self dismissViewControllerAnimated:YES completion:nil]; //commened: ^{}
}
@end

DetectionViewController.h
#import <UIKit/UIKit.h>
#import "EnterCommandViewController.h"
@interface DetectionViewController : UIViewController <EnterCommandDelegate>{
}
- (IBAction)showSettings:(UIBarButtonItem *)sender;
@property (nonatomic, strong) EnterCommandViewController* enterCVC;
@property (nonatomic, strong) IBOutlet UILabel *showReceivedCommand;
@end

DetectionViewController.m
#import <Foundation/Foundation.h>
#import "DetectionViewController.h"

@implementation DetectionViewController
@synthesize showReceivedCommand;
@synthesize enterCVC;

- (IBAction)showSettings:(UIBarButtonItem *)sender {
}

-(void) viewDidLoad{
    [super viewDidLoad];
}

#pragma mark - EnterCommandDelegate function(s)

-(void)commandEntered:(NSString *)command{
 dispatch_async(dispatch_get_main_queue(), ^{
    showReceivedCommand.text = command;
   });
}
#pragma mark -sugue
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
 enterCVC = (EnterCommandViewController*)segue.destinationViewController;
[enterCVC setDelegate:self];
}

@end

Below is what I got when I set a breakPoint AT DetectionViewController.m --> -(void)commmandEntered:(NSString*)command{}  --> showReceivedCommand.text = command;
self    DetectionViewController *   0x1465132a0 0x00000001465132a0
command NSString *  @"testStringJustEntered"    0x000000017424ada0
showReceivedCommand UILabel *   0x1465149d0 0x00000001465149d0
UIView  UIView
UIResponder UIResponder
_layer  CALayer *   0x17409ae50 0x000000017409ae50
_gestureInfo    id  0x0 0x0000000000000000
_gestureRecognizers NSMutableArray *    nil 0x0000000000000000
_subviewCache   NSArray *   @"0 objects"    0x00000001740033b0
_charge float   0   0
_tag    NSInteger   0   0
_viewDelegate   UIViewController *  nil 0x0000000000000000
_backgroundColorSystemColorName NSString *  nil 0x0000000000000000
_countOfMotionEffectsInSubtree  NSUInteger  0   0
_viewFlags  <anonymous struct>

A: There is nothing Wrong with UILabel, the problem, I guess, is the format of the "commnad" is not compatible with the text in UILabel.
Try follow code for the delegate function:

-(void)commandEntered:(NSString *)command{
dispatch_async(dispatch_get_main_queue(), ^{
    NSString* str1=@"";
    NSString* str=[str1 stringByAppendingString:command];
    showReceivedCommand.text = str;
});
}


text:
Q: How can I upload file and send checkbox using java servlet? How can I upload multi file and send checkbox using java servlet?
What method is best way to use?
Post?
What about enctype in html form?
What will be the code in java servlet ?
<form method="post" action="" enctype="multipart/form-data">
<input type="checkbox"  name="notifi-user-via-email" id="notifi-user-via-email" value="notifi-user-via-email">
<input type="file" name="fileUpload" id="files" size="50" multiple/>
<input type="submit" value="Upload" />
</form>

Thank you for your explain!

A: enctype should be set to "multipart/form-data" as you have done. POST or GET doesn't matter. You should have a @Multipart annotation in your Servlet where you receive the HTTP Request. Refer this: JavaEE Tutorial


text:
Q: How can I keep the first row of a UITableView focused during a data update? I have a UITableView that presents a timeline of data on tvOS. It is dynamically updated via an NSFetchedResultsController.
When the table is updated, new cells are added at the top. However: the previously selected cell remains focused, but the behaviour I need is for the focus to shift to the 'newest' (i.e. topmost) cell after the data update.
How can I achieve this?

A: Not sure what your code looks like, but you can create a property to keep track of whether the table is actively updating.
var tableViewIsUpdating = false

You can use this to determine if you want the normal focus before or to return the first row of your table view:
override var preferredFocusedView: UIView?{
    get {
        if updating {
            return self.tableView.cellForRowAtIndexPath(NSIndexPath(forRow: 0, inSection: 0))
        }
        return super.preferredFocusedView
    }
}

Then in your NSFetchedResultsControllerDelegate set if it's updating or not:
func controllerWillChangeContent(controller: NSFetchedResultsController){
    self.tableViewIsUpdating = true
}

func controllerDidChangeContent(controller: NSFetchedResultsController) {
    self.setNeedsFocusUpdate()
    self.updateFocusIfNeeded()
    self.updating = false
}

You can find more information here on how to update focus programmatically.


text:
Q: Long to Float Conversion in Android How to covert a Long value to Float in Android?
Float
amt=NumberFormat.getNumberInstance(Locale.US).parse(products.get(i).getAmount().substring(0,products.get(i).getAmount().length() - 3));

This code arises the error
java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Float

A: For simplicity and readability's sake, first get the NumberFormat, then cast the parsed Number to a float with floatValue().
NumberFormat numberFormat = NumberFormat.getNumberInstance(Locale.US);
String amount = products.get(i).getAmount();
Number number = numberFormat.parse(amount.substring(0,amount.length() - 3));
Float amt = number.floatValue();

A: You can call floatValue() to get a float representation of your Long (or any Number for that matter). Then you can use the constructor Float(float)to create a Float object. This has the advantage of not relying on the Number returned by your code to be a Long.
Number amt = NumberFormat.getNumberInstance(Locale.US).parse(products.get(i).getAmount().substring(0,products.get(i).getAmount().length() - 3));
Float amtFloat = new Float(amt.floatValue());


text:
Q: Remote Desktop Site Issues I have an RDS site that's running Windows Server 2008 R2. Currently the site is getting hit with a ton of outside traffic trying brute forces attacks, and now while our remote users can access the site, they can't launch any of the apps within.
We're getting ready to move on from this set up but in the short time left does anyone have any suggestions as to how I can fix this situation? Thank you.

A: I fixed it. The answer was that the latest W10 update 'broke' something with IE, so the workaround is to use the RDP in the Microsoft store. We can then access the RDS site without issue.


text:
Q: How to pass Python variable to XPath expression? I am currently working on a script that prints the ID of an Web Element based on a given text. Up till now I managed to do this:
wait.until(lambda browser: browser.find_element_by_xpath("//*[contains(text(), 'my_text')]"))
ID = browser.find_element_by_xpath("//*[contains(text(), 'my_text')]").get_attribute("id")
print(ID)

The code works fine, but I want to change it so it can be used for strings other than "my_text".
How can I pass a variable to that function? Something like this:
variable = 'my_text'
wait.until(lambda browser: browser.find_element_by_xpath("//*[contains(text(), variable)]"))
ID = browser.find_element_by_xpath("//*[contains(text(), variable)]").get_attribute("id")
print(ID)

This way I could assign any text to the variable and use the same function every time.
Thanks!

A: Try to use the following code:
variable = "my_text"
your_needed_xpath = "//*[contains(text(), '{}')]".format(variable)

Hope it helps you!

A: You can format your xpath pattern first before feeding it to the method.
pattern = "//*[contains(text(), %s)]" % variable
ID = browser.find_element_by_xpath(pattern).get_attribute("id")

A: Do the following - just enclose the variable in {}, and add an "f" before the string:
variable = 'my_text'
wait.until(lambda browser: browser.find_element_by_xpath(f'//*[contains(text(), {variable})]'))
ID = browser.find_element_by_xpath(f'//*[contains(text(),{variable})]').get_attribute("id")
print(ID)

This is called string interpolation.

A: You can try this as well.Hope it will work.
 variable = 'my_text'
 wait.until(lambda browser: browser.find_element_by_xpath("//*[contains(text(),'" + variable + "')]"))
 ID = browser.find_element_by_xpath("//*[contains(text(),'" + variable + "')]").get_attribute("id")
 print(ID)


text:
Q: messageWhenBadInput not working on lightning input type email I am trying to display error messgae when email format entered is not correct.
<lightning:input type="email" value="{!v.userEmail}"
                 messageWhenBadInput="Please enter a valid Email Address"/>

But if I input something like abc in email field, it displays standard error You have entered an invalid format. and not the one I added in input tag.
Also, when I enter abc@gmail which is also not the correct format, it removes the error message.
Does messageWhenBadInput works correctly for lightning input type:email

A: added
As you mentioned email as type but when you enter asdf, it does not match email data type as it does not have @, it will consider that user entered Text data type.

You are mentioning type email and entering type Text, So it should be type mismatch and you should use messageWhenTypeMismatch. Below should work:
<lightning:input type="email" required="true"
                     messageWhenTypeMismatch="Not valid Email Address"
                     />


text:
Q: Did Voldemort want to control the whole world, or just the UK? Voldemort's plans all seemed to be focused on the wizarding world in the UK, mainly on trying to deal with Harry Potter and gain freedom.
Did Voldemort have ambitions beyond controlling the UK? If he had been successful at taking out Harry and taking over Hogwarts would he then have turned his eyes to Europe and beyond?

A: His ultimate plan was world domination.
The Dark Lord's ultimate plan was for wizards to rule over the Muggles. He never specifically limits this to the United Kingdom, and it seems most likely that he would want this to eventually reach the entire world rather than be confined to one region.

"For years he talked of the Dark Lord, who was going to bring the wizards out of hiding to rule the Muggles and the Muggle-borns … and when he was sixteen years old, Master Regulus joined the Dark Lord." - Harry Potter and the Deathly Hallows, Chapter 10 (Kreacher's Tale)

Furthermore, J.K. Rowling says in an interview that the Dark Lord eventually did plan on taking over the whole world, though he planned to gain domination over Europe to begin with.

Question: How does the Dark Lord affect American wizards and witches?
J.K. Rowling responds: He affects everyone, but his plan is European domination first. - Scholastic.com interview (October 16, 2000)

So yes, the Dark Lord ultimately planned to have wizards in power over the entire world, ruling over Muggles openly.


text:
Q: Issue transfering value using notifications | Swift 5 I have a view controller that contains a button that, when pressed, presents a camera view controller that allows the user to scan a barcode and  return to the first view controller that launched it with the value of the barcode.
Camera View Controller is presented:
let ScannerView = scanBarcode()
        let navigationController = UINavigationController(rootViewController: ScannerView)
        navigationController.modalPresentationStyle = .formSheet
        self.present(navigationController, animated: true, completion: nil)

Function executed when barcode scanned:
 func processScan() {
  print("Process Scanned")
  NotificationCenter.default.post(name: Notification.Name("scannedInfo"), object: nil,
  userInfo:["barcodeValue": "123","value2": "Yes"])

  dismiss(animated: true, completion: {
  viewController1().observeScanned()
 }

Function called on dismiss from ViewController1
func observeScanned() {
    NotificationCenter.default.addObserver(self,
                                           selector: #selector(
                                            self.ScanInfo(notification:)),
                                           name: Notification.Name("ScanInfo"),
                                           object: nil)
}

@objc func ScanInfo(notification: Notification) {
    print("ScanInfo")
    barcode = notification.userInfo?["barcodeValue"] as? String
    value2 = notification.userInfo?["value2"] as? String
    print(barcode)
    print(value2)
}

The issue is the function the notification observer does not seem to be triggered and the values for barcodeValue and value2 are not transfer to ViewController1. print(barcode) and print(value2) are never printed. While I understand I can easily rely on ViewDidAppear if I presented the modal as .fullscreen I much rather presenting as a formsheet or equivalent, where the screen is not full used.

A: You have a couple of problems here.
First, this code:
viewController1().observeScanned()

Creates a new instance of viewController1 and calls its observeScanned function - This view controller instance isn't on screen and will be thrown away as soon as this line executes.
Even if you were invoking the observedScanned() function on the correct instance, it is too late.
This is your second problem.  You posted the notification two lines earlier.  When a notification is posted it is delivered to observers that have registered for that notification. An observer after the notification has been posted won't get that notification, it will only get subsequent notifications.
It looks like you are mixing a delegation pattern and notifications. You only need one.
If you just want to use notifications then you can call observeScanned from viewDidLoad in viewController1 and then just post the notification in your scanBarcode view controller. There is no need for scanBarcode to explicitly invoke any method on viewController1 - The point of Notifications is to provide decoupling of senders and observers.
If you just want to use delegation then you can declare a protocol
protocol ScannerDelegate {
    func didScan(barcodeValue: String, value2: String) -> Void
}

Then ViewController1 can conform to this protocol and set itself as the delegate on the ScanBarcode instance:
class ViewController1: UIViewController, ScannerDelegate {

    // ...
        let scannerView = scanBarcode()
        scannerView.delegate = self
        let navigationController = UINavigationController(rootViewController: ScannerView)
        navigationController.modalPresentationStyle = .formSheet
        self.present(navigationController, animated: true, completion: nil)

   //...

    func didScan(barcodeValue: String, value2: String) -> Void {
        print("ScanInfo")
        print(barcodeValue)
        print(value2)
    }
}

Finally, your ScanBarcode needs to provide a delegate property and invoke the delegate method
class ScanBarcode: UIViewController {

    var delegate: ScannerDelegate?

    func processScan() {
        print("Process Scanned")
        self.delegate?.didScan(barcodeValue:"123", value2:"456")
        dismiss(animated: true, completion: {
    }
}

One last thing.  You should get into the habit of following Swift naming conventions.  It doesn't affect the way your code works but it makes your code more readable to others.

*

*Types (classes, structs, protocols, enums) use UpperCamelCase so ViewController1 not viewController1

*Variables & constants use lowerCamelCase so scannerView not ScannerView
I have made these changes in my version of your code in this answer so you can see what I am referring to.


text:
Q: Testar método de um controller do AngularJs com promise utilizando Karma, Mocha, Chai, Sinon Não estou conseguindo testar o código que é executado no then do promise
Tenho o seguinte controller:
class Product extends Controller
  constructor: ($scope, productService) ->
    $scope.product = productService.new()
    $scope.products = []

    $scope.create = ->
      productService.create($scope.product).$promise.then (res) ->
        $scope.products.unshift(res)
        $scope.product = productService.new()

E a seguinte classe de teste:
describe 'productsController', ->
  q = scope = controller = productService = productServiceMock = undefined

beforeEach module('e-city')

beforeEach ->
  productServiceMock =
    new: -> a: 'a'
    create: (p)->
      qq = q.defer()
      qq.resolve(p)
      $promise: qq.promise
  module ($provide) ->
    $provide.value 'productService', productServiceMock
    null

beforeEach ->
  inject (_productService_, $controller, $rootScope, $q) ->
    q = $q
    productService = _productService_
    scope = $rootScope.$new()
    controller = $controller 'productController', $scope: scope

describe 'should test the create method', ->
  it 'should set a new object on $scope.product',  ->
    spy = sinon.spy productService, 'create'
    scope.create()
    spy.should.have.been.called

No meu teste eu criei um Mock para o productService para executar os testes sem incomodar o banco. A questão de Mock está funcionando corretamente, só não consigo testar se productService.new() está sendo chamado quando o promise do productService.create($scope.product) é resolvido. O que poderia ser?

A: Para este problema relatado acima em específico o código abaixo já resolve o problema.
describe 'create', ->
  it 'should call "new"', inject ($timeout)->
    spy = sinon.spy productService, 'new'
    scope.create()
    $timeout.flush()
    spy.should.have.been.called
    productService.new.restore()

Obs: Para otimizar os testes e facilitar a criação dos mocks é recomendado utilizar o $httpBackend do AngularJs.


text: Q: what are Steps to add Article Search in community portal to search Knowledge Base Search I have already purchased license for my community portal than now i want to know all the steps where i can use it on my community portal.(I want to use Article Search in my community portal homepage as i used it on customer portal where any one can search only knowledgebase)


text:
Q: Java - No such file or directory I have been trying to get this program to run a class file that is located in /Library/Application Support/Adobe/Adobe PCD/cache/Main.class.
Yet every time I run the method below, It cannot find the file specified. I think that eclipse is looking for the file path above in the project folder. But the first command doesn't seem to work. Can Anyone help me? Is there another way to run the class file?
static Runtime r = Runtime.getRuntime();

public static void Run() {

      try {
       Runtime rt = Runtime.getRuntime();
       String run = "/Library/Application Support/Adobe/Adobe PCD/cache/";
       String[] command = {"java -cp " + run, "java Main"};
       Process pr = rt.exec(command);

       BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

       String line=null;

       while((line=input.readLine()) != null) {
           System.out.println(line);
       }

       int exitVal = pr.waitFor();
       System.out.println("Exited with error code "+exitVal);

   } catch(Exception e) {
       System.out.println(e.toString());
       e.printStackTrace();
   }
}

A: This tries to run a mythical program java -cp /Library/Application Support/Adobe/Adobe PCD/cache/ with argument java Main.  java Main is an illegal name for a class too. Instead, have your command array be:
String[] command = {"java", "-cp", run, "Main"};

However, unless you have a Main class in the default package, simply add the run directory to your application's class path, and then call Main.main(), possibly playing games with standard input and output.  There is no need to start a second JVM. Or, figure out what Main does, and call the classes it calls.  Is there Javadoc for the Adobe code?
When the Ant task <zip> runs, Ant does not start a new VM or a command-line zip utility.  Instead, the task's class calls methods in java.util.zip. You should do something similar.


text:
Q: Python Pandas isin return index I have a pandas DataFrame df with a list of unique ids id, and a DataFrame with master list of all known ids master_df.id. I'm trying to figure out the best way to preform an isin that also returns to me the index where the value is located. So if my DataFrame was
master_df was
index id
1     1
2     2
3     3

and df was
index id
1     3
2     4
3     1

I want something like (3, False, 1).
I'm currently doing an is in and then looking then brute forcing the lookup with a loop, but I'm sure there is a much better way to do it.

A: One way is to do a merge:
In [11]: df.merge(mdf, on='id', how='left')
Out[11]:
   index_x  id  index_y
0        1   3        3
1        2   4      NaN
2        3   1        1

and column index_y is the desired result*:
In [12]: df.merge(mdf, on='id', how='left').index_y
Out[12]:
0     3
1   NaN
2     1
Name: index_y, dtype: float64

* Except for NaN vs. False, but I think NaN is what you really want here. As @DSM points out, in python False == 0 so you may get into trouble with False as the representative for missing vs being found with id 0. (If you still want to do it then replace the NaN with 0 using .fillna(0)).
Note: it's possible it will be more efficient to just take the columns you care about:
df[['id']].merge(mdf[['id', 'index']], on='id', how='left')


text:
Q: Why does my Web API return 405 for everything? I have a ASP.NET Web API 2 controller in a custom Area.
(I also have some API controllers in the default route)
I have registered the route:
// Web API routes
config.MapHttpAttributeRoutes();

// NEW ROUTE FOR AREAS
config.Routes.MapHttpRoute(
    name: "API Area MyArea",
    routeTemplate: "api/MyArea/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional });

My controller and method:
 [RoutePrefix("myarea/api/accountapi")]
  public class AccountAPIController : ApiController
  {
...

    [System.Web.Http.HttpGet]
    [AcceptVerbs("GET")]
    [AllowAnonymous]
    [Route("emailexists")]
    public async Task<IHttpActionResult> EmailExsists([FromUri]string email)
    {
      var user = await UserManager.FindByEmailAsync(email).ConfigureAwait(false);
      return Ok(user != null);
    }
...
}

But I can't get this to work, no matter what I try I get:
https://localhost:44300/api/accountapi/emailexists?email=info@something.com

{"message":"The requested resource does not support http method
  'GET'."}

In fact, I can't get it to return an expected 404. For example, this:
https://localhost:44300/api/accountapi/jibberish
Also returns a 405.
My API controllers in the default route works as expected, i.e. returning a 404 when it should.
Any ideas ?

A: Let's analyze the endpoints you are calling.
The first URI:
https://localhost:44300/api/accountapi/emailexists?email=info@something.com

Looking at your routing configuration this will match only api/{controller}/{id} route template. That's because the first convention routing config will only match URI parts starting with api/MyArea, while the attribute routing prefix of your controller will only match paths starting with myarea/api/accountapi).
This will translate in the following route attributes:

*

*{controller}: accountapi

*{id}: emailexists

*?email: info@something.com (this will be ignored for routing purposes because is not included in the template)

Looking at your AccountAPIController I can't see any Action that allows GET and also has a string parameter called (explicitly) id: thus a 405 is returned.
The second URI:
https://localhost:44300/api/accountapi/jibberish

Will again only match the same route template as before:

*

*{controller}: accountapi

*{id}: jibberish
For the same reason a 405 response is returned.
What to do?
Your main problem is that you are mixing different routing methods without correctly matching the URI for your action. Without modifying the current route configuration the correct address for your EmailExsists method is the following one:
https://localhost:44300/myarea/api/accountapi/emailexists?email=info@something.com

This will match your RoutePrefix and Route attributes in the AccountAPIController.
The following URIs should also match your action method based on the two routing convention you configured (they should be equivalent):
https://localhost:44300/api/accountapi?email=info@something.com
https://localhost:44300/api/MyArea/accountapi?email=info@something.com

My suggestion is to avoid the use of too many different routing templates and configurations: if you need the maximum flexibility use only attribute routing and remove the convention-based routing configuration.


text:
Q: Adding numbers from text file in batch script I've got a problem with batch script. I have to make script which adds numbers located within a text file.
The numbers are in one line of the file and separated by spaces.
I have to do it using a for loop.
I've made this:
setlocal EnableDelayedExpansion
set /a wynik=0
for /f "tokens=1* delims= " %%a in (liczby.txt) do (set /a wynik+=%%a)
echo %wynik% > wynik.txt

The output is:
C:\Users\NuClear\Desktop\arch\2>setlocal EnableDelayedExpansion

C:\Users\NuClear\Desktop\arch\2>set /a wynik=0

C:\Users\NuClear\Desktop\arch\2>for /F "tokens=1* delims= " %a in (liczby.txt) do (set /a wynik+=%a )

C:\Users\NuClear\Desktop\arch\2>(set /a wynik+=1 )

C:\Users\NuClear\Desktop\arch\2>echo 1  1>wynik.txt

I've got no idea why it is not taking next tokens after 1.

A: A simpler method:
@echo off
setlocal

set /P "line=" < liczby.txt
set /A "wynik=%line: =+%"
> wynik.txt echo %wynik%

This method assumes that "The numbers are in one line of the file and separated by one space each", with no spaces at beginning or end of the line.

A: You didn't specify if you have to use for to read the file or just for the adding part.
REM read the (first line of the) file into a variable:
<liczby.txt set /p "line="
REM or using a FOR /F to read the file:
REM for /f "delims=" %%a in (liczby.txt) do set "x=%%a"
REM add them up:
set "y=0"
for %%a in (%line%) do set /a y+=%%a
echo Sum: %y%

for /f with tokens is extremely helpful, if you know beforehand, how many tokens there are. A plain for just executes for each token (using standard delimiters), how many there may be.

A: It appears to me, from the information you've provided, that the simplest idea would be to replace the single spaces with the addition operator.
Here's an example written for your batch-file tag:
@(
    For /F "UseBackQ Delims=" %%G In (
        "liczby.txt"
    ) Do @(
        Set "}=%%G"
        For /F "Delims=" %%H In (
            '%SystemRoot%\System32\cmd.exe /V /D /C "Set /A "!}: ^=+!""'
        ) Do @Echo(%%H
    )
) 1>"wynik.txt"

And for your cmd tag:
(For /F "UseBackQ Delims=" %G in ("liczby.txt") Do @Set "}=%G" & For /F "Delims=" %H In ('%SystemRoot%\System32\cmd.exe /V /D /C "Set /A "!}: ^=+!""') Do @Echo(%H) 1>"liczby.txt"

The current responses have possibly read into your question in a different way, due to its lack of clarity or examples, so my answer above assumes that liczby.txt looks a little like this:
1 2 3 4 5
6 7 8 9
10 11 12
13 14

…and the resultant wynik.txt would look something like this:
15
30
33
27

A: Here is another option if you want to do it with a single FOR command. The key to this option is using CMD.exe with the /U option.
 @echo off
 set "wynik=0"
 for /F "delims=" %%G in ('cmd /D /U /C type liczby.txt ^| find /V ""') do (
    set /A "wynik+=%%G" 2>nul
 )
 >wynik.txt echo %wynik%

A: I assume you have got a text file liczby.txt with a content like this:

1 2 3

When you read it with a for /F loop there is going to be one iteration because there is only a single line. Within this iteration all the tokens specified by the option string are returned in respective meta-variables.
But what you need is something else, you want to iterate through the individual numbers, which can be achieved using a standard for loop:
@echo off
setlocal EnableExtensions DisableDelayedExpansion
rem // Initialise sum:
set /A "wynik=0"
rem // Read the input text file line by line:
for /F "usebackq tokens=*" %%J in ("liczby.txt") do (
    rem // Loop through individual items/numbers:
    for %%I in (%%J) do (
        rem // Sum up the numbers:
        set /A "wynik+=%%I"
    )
)
rem // Write sum into output file:
> "wynik.txt" echo(%wynik%
endlocal
exit /B


text:
Q: bootsrap nav-bar collapse in small size width when the width gets < 768px it show the toggle icon on the right bottom but when I click on it it does not show the list items I defined. can anyone advise me on this? appreciated.
https://jsfiddle.net/fj0u49bj/

    <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#main-nav">
       Toggle navigation
    </button>
    title

        Link2

        Log In
        Sign Up

A: I think you are missing to load jQuery. Bootstrap.js is build on top of jQuery which means that can not work without it.
If you do have jQuery (before bootstrap.js) than probably your navigation formatting is not properly done.
Have a look at this fiddle (link in the comment below)  so you can see how a  correct nav-bar must be.


text:
Q: javascript - bluebird is not starting promises correctly I am having a problem with bluebird concurreny. Basically I want my promises to be fired one after an other. I found that this can be done using bluebird. This is my code:
var  getdep = Promise.promisify(
  function getdep(module, cb ) {
    console.log(module + " ...start ...")
    ls(module, function(data) {
      cb(null, data);
    });
  });

 Promise.all([0,1,2,3,].map(function(data){
   return getdep("uglify-js@2.4.24");
 }, {concurrency: 1}))
 .then(function(all){
   console.log(all);
 })
 .catch(function(err){
   console.log(err);
 });

What I respected is something like ({concurrency: 1}).
uglify-js@2.4.24 ...start ...
loading: uglify-js@2.4.24@latest
loading: uglify-js@2.4.24@latest
loading: uglify-js@2.4.24@latest
loading: uglify-js@2.4.24@latest
....
uglify-js@2.4.24 ...start ...
loading: uglify-js@2.4.24@latest
loading: uglify-js@2.4.24@latest
loading: uglify-js@2.4.24@latest
loading: uglify-js@2.4.24@latest

...
and so on
but what I am having is:
uglify-js@2.4.24 ...start ...
uglify-js@2.4.24 ...start ...
uglify-js@2.4.24 ...start ...
uglify-js@2.4.24 ...start ...
loading: uglify-js@2.4.24@latest

That means bluebird is starting all my promises at the same time.
Can you please tell me what is wrong in my code ? thanks

A: You are using Array#map not Promise.map
 Promise.all(
    [0,1,2,3,].map(function(data){
 //      array.map
         return getdep("uglify-js@2.4.24");
     }, {concurrency: 1}) // end of array.map
 )
 .then(function(all){
   console.log(all);
 })
 .catch(function(err){
   console.log(err);
 });

Array.map doesn't understand the {concurrency:1} argument - it uses that as the thisArg for the callback
To use Promise.map, use Promise.map like this
 Promise.map([0,1,2,3,], function(data){
     return getdep("uglify-js@2.4.24");
 }, {concurrency: 1}))
 .then(function(all){
   console.log(all);
 })
 .catch(function(err){
   console.log(err);
 });


text:
Q: Singleton implementation: Is a namespace approach often preferable over a singleton class? (This questions assumes that a global + unique object is the goal. I would like to clarify that this does not mean it is asking about or advocating the if/why/when of using/not-using singletons or globals.)
I am wondering if there's a technicality about C++ that I'm missing, so my question is:
Is a namespace implementation of the singleton pattern in C++ valid? And if so, is there a reason why it is not often suggested as the better approach?
From Google's style guidelines, we see namespace non-member functions recommended over static member function, but only when not sharing static data:

"Rather than creating classes only to group static member functions
  which do not share static data, use namespaces instead."

Why shy away from letting non-member functions share static data, declared in an unnamed namespace? Is there something wrong about this that explains why namespaces aren't generally suggested as a better alternative to writing a singleton class in C++?
Because I can't find recommendations of the namespace approach, but it is very easy to find the class approach despite C++ not enforcing the use of classes:
C++ Singleton design pattern
Can any one provide me a sample of Singleton in c++?
Singleton instance declared as static variable of GetInstance method
http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
Singleton: How should it be used
Using a named namespace with an unnamed namespace in its source file:

*

*You can have 'state' via static data

*You can gain the extra privacy of putting things in an unnamed namespace

*You can still control the construction order of its static objects by using static pointers, and constructing from function calls.

*You don't need to implement a singleton class

Edit - Example of namespace approach I was thinking:
SingleThing.h:
namespace single_thing   // The singleton (if this is actually valid)
{
    void GrowSomeCats(int amount); // Typical setter
    int GetNumCats();              // Typical getter
}

SingleThing.cpp:
#include "Balloon.h"

namespace // Acting like private members and functions
{
    int numCats = 4;        // POD
    Balloon* wilson = NULL; // Not POD (and not a singleton)

    // Contrived 'private' function
    bool CanGrowCats()
    { return wilson && wilson->LikesCats(); }

    // Contrived excuse to instantiate non-POD 'members'
    void RandomlyCreateOtherObjects()
    {
        if (!wilson /* && someRandomiserImTooLazyToType()*/ )
            wilson = new Balloon();
    }
}

namespace single_thing  // 'Public' functions
{
    void GrowSomeCats(int amount)
    {
        RandomlyCreateOtherObjects();
        if (CanGrowCats())
            numCats += amount;
    }

    GetNumCats()
    { return numCats; }
}

A: (I assume we can agree that global state is a dangerous thing that has to be used with special care.)
Technically your singleton namespace is equivalent to a singleton class. However it has one major drawback that makes it a no-go in my opinion: It hides the fact that it is stateful. Ever used std::strtok()? Remember what an atrocious mess it is? That's because it hides its statefulness, too.
Because global state is inherently dangerous, any piece of functionality that uses it should make that fact abundantly clear at the call site, preferrably by using language constructs – because nobody reads comments or documentation. A Foo::instance()->do_work(); is a known pattern that makes it quite clear that something special is going on; a foo::do_work(); does not.

A: Singleton design pattern is about creation the only instance of a useful class (there is no need in creation of useless objects). In C++ classes are defined with class and struct keywords. To be useful a singleton class, beside creation and destruction, should also implement some methods that operate with the instance. To ensure singularity, a singleton class should hide its constructors and expose a static method for accessing the instance.
Using only namespaces one would not be able to define useful methods of the singleton. Implementing the instance access method as a function in a namespace instead of the class itself is possible, but would require 'friending' that function, and does not make sense because the class is already defined.
Implementing a non-object singleton (e.g. of a plain data type) would assume that the instance does not require construction and thus there is no need for singleton.


text:
Q: Specifying a line type for grid.circle I am trying to draw circles using grid::grid.circle with dotted or dashed borders. The documentation references grid::gpar but the lty argument does not seem to do it.
grid::grid.circle(0.5, 0.5, 0.33, gp = grid::gpar(lty = 2))

gives

It does seem to process the argument, given that it can be used to turn borders off, like so:
grid::grid.circle(0.5, 0.5, 0.33, gp = grid::gpar(lty = 0, fill = "light blue"))

However, that seems to be the only choice. Is there any other way to get different line types for the borders of the circle using grid graphics?
Edit: I am using R on windows and if I use the pdf device I get the correct results. However, specifying lty to grid.rect works just as expected so I can't quite figure out what's going on.