text:
Q: Present Perfect Tense With no PP? Tom has been to China
Am I right in thinking this sentence is present perfect?
When forming the present perfect we use Has/have + been + past participle.
In this sentence I cannot figure out what the past participle is?

A: This is present perfect. It is an unusual use of the verb "to be"
The present perfect is formed from "have" + PP.  In this case the past participle is
the word "been". What makes this structure unusual is that the verb "to be" in this sense is only used in perfect tenses.
The present perfect is not have+been+PP.  That does exist; it is a present perfect passive voice.  But "I have been to China" is active voice.
The meaning is idiomatic.

I have been to China = I have gone to China. = I have visited China.

But though you can say "I will go to China" or "I went to China", you can't say *"I will be to China" or "I was to China".  Those are not correct (not idiomatic).


text:
Q: Problem storing data I can't getting my stored data.... This is the code:
 if ([string isEqualToString:@""]) {
        //RECUPERO DATA
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *pathToDocuments=[paths objectAtIndex:0];
        pathToDocuments=[pathToDocuments stringByAppendingString:@"getSubscriptionsListShowOnlyWithUnreadFeeds.txt"];
        NSLog(pathToDocuments);
        dataReply=[[NSData alloc] initWithContentsOfFile:pathToDocuments];
        NSString *string = [[NSString alloc] initWithData:dataReply encoding:NSASCIIStringEncoding];
        NSLog(@"string recuperata %@",string);
    }
    if ([string isEqualToString:@""]==NO) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *pathToDocuments=[paths objectAtIndex:0];
        pathToDocuments=[pathToDocuments stringByAppendingString:@"getSubscriptionsListShowOnlyWithUnreadFeeds.txt"];
        NSLog(pathToDocuments);
        [dataReply writeToFile:pathToDocuments atomically:YES];}

Is there something wrong?
EDIT
No bugs no crashes but the NSLog(@"string recuperata %@",string); prints an empty string! (data are stored in the device because I had running at least one time my app when string!= empty
Thanks

A: I think there is a else missing on the second if. I'm not sure if that is what you wanted or if it is a typo on your part. check if that is the problem.
 if ([string isEqualToString:@""]) {
        //RECUPERO DATA
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *pathToDocuments=[paths objectAtIndex:0];
        pathToDocuments=[pathToDocuments stringByAppendingString:@"getSubscriptionsListShowOnlyWithUnreadFeeds.txt"];
        NSLog(pathToDocuments);
        dataReply=[[NSData alloc] initWithContentsOfFile:pathToDocuments];
        NSString *string = [[NSString alloc] initWithData:dataReply encoding:NSASCIIStringEncoding];
        NSLog(@"string recuperata %@",string);
    } else if ([string isEqualToString:@""]==NO) {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *pathToDocuments=[paths objectAtIndex:0];
        pathToDocuments=[pathToDocuments stringByAppendingString:@"getSubscriptionsListShowOnlyWithUnreadFeeds.txt"];
        NSLog(pathToDocuments);
        [dataReply writeToFile:pathToDocuments atomically:YES];

A: Try changing to NSUTF8StringEncoding if you are unsure about the encoding, usually it works.

A:     if ([string length]<=0) {
            //RECUPERO DATA
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *pathToDocuments=[paths objectAtIndex:0];
        pathToDocuments=[pathToDocuments stringByAppendingString:@"getSubscriptionsListShowOnlyWithUnreadFeeds.txt"];
        NSLog(pathToDocuments);
        dataReply=[[NSData alloc] initWithContentsOfFile:pathToDocuments];
        NSString *string = [[NSString alloc] initWithData:dataReply encoding:NSASCIIStringEncoding];
        NSLog(@"string recuperata %@",string);
    }

    else {

        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *pathToDocuments=[paths objectAtIndex:0];
        pathToDocuments=[pathToDocuments stringByAppendingString:@"getSubscriptionsListShowOnlyWithUnreadFeeds.txt"];
        NSLog(pathToDocuments);
        [dataReply writeToFile:pathToDocuments atomically:YES];

    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS gradients in IE7 & IE8 is causing text to become aliased I'm attempting to use a CSS gradient in a div containing some text.  With Gecko and Webkit, the text displays fine.  In IE7 & IE8 the text appears aliased (jaggy).
I came across this blog stating: "we decided to disable ClearType on elements that use any DXTransform".
IE Blog:
http://blogs.msdn.com/ie/archive/2006/08/31/730887.aspx
That was back in 2006; 3.5 years later, I assume this bug would be fixed, but it's not.  Is there a way to do this in IE8 without resorting to stuffing a repeating background image in the div?
Here's an example of what I mean.

Hello World

Normal text

In IE, the text in the div is aliased (jaggy), and the text in the paragraph is not.
Any solution that doesn't involve images would be greatly appreciated.

A: You could try using an IE css 3 html component, like PIE (http://css3pie.com,) which does a fairly decent job of rendering gradients. (Though this is essentially using javascript)

A: Wrap the content with a DIV then add this to the DIV's css style...
position: relative;

http://cookbooks.adobe.com/post_IE8_clearType_fix_when_using_filters-16676.html

A: There's no good solution to this problem.
Worse yet: progid:DXImageTransform.Microsoft.gradient is horribly buggy so mouse events (hover, click, etc.) pass right trough it - a click on such an element also triggers a seperate click on whichever element that happens to be positions behind it. Beware!
Regardless, you better start considering which fallbacks/workarounds/NastyHacks feel acceptable to you.
Here are a few ideas off the top of my mind - in order of my personal preference:

*

*Just fall-back to a plain solid background-color in IE and move on with your life. (Be sure to place that background rule first for it to be safely overridden/ignored by FF and Webkit.)

*Use a background-image in IE. (Again place that CSS rule at first)

*Keep using the gradient hack and simply 'suck it up' and accept the jaggy text for IE.

*use Javascript (or IE's proprietary CSS expression() syntax) to inject an empty element, apply the gradient to it and place it behind the text.
div {
  background: -moz-linear-gradient(top, #fff, #ddd);
  background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#ddd));
  behaviour: expression( jQuery(this).wrapInner('
').prepend('
'); this.runtimeStyle.behaviour='none'); /* disable repeat runs */
  position: relative;
}
div div.ie-wrap {
  position: relative;
}
div div.ie-gradient {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: expression( this.runtimeStyle.height=this.parentNode.clientHeight+"px" );
  filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#ffffffff, endColorstr=#ffdddddd);
}

(Warning: above code is untested pile of crap. and will probably not work as is.)

*Keep using the gradient hack and use Cufon to replace the jaggy text with VML rendered text. (Rests on the assumption that your site is using a typeface that allows font-embedding.)

A: I had a situation where I wanted backgrounds of text areas to be certain colours fading horizontally to white and defined by hexadecimal in the CSS. I wanted to avoid making colour background images in case a non-developer member of my company wanted to add a new colour with hexadecimal only.
The solution I found was to make a 24-bit PNG of white gradienting into transparent set to the width of the area I was making.
I then used this IE-only hack to get the CSS to render a background colour of my choice that fades to white:
background /*\**/: #CCCED4 url('/white_to_transparent.png') repeat-y top left\9;

(the hack could be improved, but it works for me, including IE9)

A: I found another inexpensive (bit opaque) solution. The text becomes anti-alised back again, when wrapping the text node and setting each element to relative position. Do not ask why...
Lets assume:

  <title>IE8 filter problem causing jagged fonts</title>

I am wrapped, therefore not jagged

Hope that helps anyone out there. In this case it's not necessary to use background images or derivates.
Working example in jsfiddle: http://jsfiddle.net/SLZpE/2/

A: This may not count as elegant (or working) solution, but how about using Cufón for IE?

A: Yes, that's a problem with IEx.
Try using a solid background color:
/*replace #ccc with the color you want*/
background: url(images/gradient-image.png) top repeat-x #ccc

Now, no need to use the expression "...stuffing a repeating background image", since there's nothing wrong with using a background image and repeat it, we should be thankful that we can not only do that, but we can repeat it in X and Y.
Of course, you want to make your repeating background image as efficient as possible, so make it small/thin (depending on your design) and use it, rest assured, you are not doing anything wrong or against any standards or best practices.


text:
Q: GA: How to access Cohort Analysis via Analytics API? Cohort dimensions and metrics are listed here. Yet, when I try to query it using API (e.g. using Query Explorer) an error 400 occurs.
One of queries I've tried is: metrics = ga:cohortActiveUsers and dimensions = ga:cohortNthDay .
Is is possible to query Cohort Analysis report via API?

A: The problem you are having is because the Query explorer uses the v3 of the Google Analytics API. If you look at the Dimensions and Metrics Explorer you will notice that these dimensions were added in the Analytics Reporting API V4.
The error message you are getting is incorrect and should be corrected soon.  It should state something more like This metric cannot be used in Version 3 of the API.  You caught this while we where in the process of rolling out the new API. Which has now been officially released see change log
To make use of these new dimensions and metrics you must construct a V4 cohort request:
POST https://analyticsreporting.googleapis.com/v4/reports:batchGet
{
  "reportRequests": [{
    "viewId": "XXXX",
    # No date range is required in the request
    "dimensions": [{"name": "ga:cohort" },{"name": "ga:cohortNthDay" }],
    "metrics": [
      {"expression": "ga:cohortActiveUsers" },
      {"expression": "ga:cohortTotalUsers"}
    ],
    "cohortGroup": {
      "cohorts": [{
        "name": "cohort 1",
        "type": "FIRST_VISIT_DATE",
        "dateRange": { "startDate": "2015-08-01", "endDate": "2015-08-01"}
      },{
        "name": "cohort 2",
        "type": "FIRST_VISIT_DATE",
        "dateRange": {"startDate": "2015-07-01", "endDate": "2015-07-01"}
      }]
    }
  }]
}

A: It is possible to compose a cohort requests by using the Request Composer tool, in the Cohort Request tab.
As you select the options in the Set query parameters section, the request payload is shown below.
Hope it helps.


text:
Q: Show that all the zeros of $(az+1)^m-b (z+1)^m$ lie in $|z|<1,$ where $a>1$ and $|b|\leq 1.$ If $f(z)=(z+1)^m$ then $f(az)=(az+1)^m,$ where $m\in\mathbb{N}.$ I can prove that $|f(z)|<|f(az)|$ for $|z|=1$ and $a>1.$ Therefore, by Rouche's theorem, all the zeros of $(az+1)^m-b (z+1)^m$ lie in $|z|\leq (1/a)<1.$
But I don't want to use Rouche's theorem or any result from analysis to prove this result. I am looking for some elementary solution, like properties of Binomial theorem. Help appreciated in advance.

A: You can show that $|az + 1| > |z + 1|$ if $|z| > 1$.  Indeed, $|az + 1|^2 = a^2|z|^2 + 2a\Re z + 1$ and $|z + 1|^2 = |z|^2 + 2\Re z + 1$. Hence
$$
|az + 1| > |z + 1| \Longleftrightarrow |z|^2(a^2 - 1) + 2\Re z(a - 1) > 0 \Longleftrightarrow |z|^2(a + 1) > -2\Re z,
$$
which holds if $|z| > 2/(a + 1)$. Hence, for $|z| \ge 1$, $|(az + 1)^m| > |(z + 1)^m| \geq |b(z + 1)^m|$ and $z$ cannot be a root.


text:
Q: Can't get items in a ListView cross-thread My background worker needs to iterate through each item in a ListView. However I can't do this:
foreach (ListViewItem Item in List.Items)

because it's a cross thread operation.
I also can't put the items in a ListView.ListViewItemCollection and make the background worker read from that. This is still trying to access the ListView and creating a cross thread operation.
How can I make the ListView's items available to the background worker without putting them in a variable somewhere?

A: Try using this function.
private delegate ListView.ListViewItemCollection GetItems(ListView lstview);

private ListView.ListViewItemCollection getListViewItems(ListView lstview)
{
    ListView.ListViewItemCollection temp = new ListView.ListViewItemCollection(new ListView());
    if (!lstview.InvokeRequired)
    {
        foreach (ListViewItem item in lstview.Items)
        temp.Add((ListViewItem)item.Clone());
        return temp;
    }
    else
        return (ListView.ListViewItemCollection)this.Invoke(new GetItems(getListViewItems), new object[] { lstview });
}

Call it like this:
foreach(ListViewItem item in getListViewItems(List))

A: I agree with mdb, but have to mention that depending on importance of application,
Control.CheckForIllegalCrossThreadCalls = false;
can still be used as  a temp quick fix.

A: try this.
public Form1()
{
    InitializeComponent();

    Control.CheckForIllegalCrossThreadCalls = false;
}


text:
Q: Adding emoji is showing undefined when adding it for the first time only Here, I have shown just the part of the code where the emoji picker is implemented. When I pick any emoji for the first time it shows me undefined. How can I resolve this issue?
Here's the screenshot of the issue.

Code Implementation
import { Picker } from "emoji-mart";

const ChatMain = (props) => {
  const [messageToSend, setMessageToSend] = useState();
  const [isEmojiPickerVisible, setEmojiPickerVisibility] = useState(false);
  return (

      {isEmojiPickerVisible && (
        <Picker
          title=""
          showPreview={false}
          showSkinTones={false}
          color="#2189FF"
          onSelect={(emoji) => {
            setMessageToSend(messageToSend + emoji.native);
          }}
          style={{ position: "absolute", bottom: 85 }}
        />
      )}

        <button
          className={`p-0 btn btn-link outline-none shadow-none ${
            isEmojiPickerVisible ? "text-black" : "text-secondary"
          }`}
          onClick={() => setEmojiPickerVisibility(!isEmojiPickerVisible)}
        >

        </button>

  );
};

A: You do not give a default value so it is undefined.
const [messageToSend, setMessageToSend] = useState('');


text:
Q: json with C# in a WCF service? I am looking at adding SMS abilities to my WCF service.  I found a cheap SMS service called Penny SMS.
Their interface supports json.  But I have no idea how to call it in my WCF service.
Here is the interface/example:
Sample JSON-RPC Request
{ "method": "send",
  "params": [
            "YOUR_API_KEY",
            "msg@mycompany.com",
            "5551231234",
            "Test Message from PENNY SMS"
            ]
}

How would I call that with C# from a WCF service?   What I am looking for is a way to wrap this into a method call.  Something like:
StaticSMSClass.SendSMS("1234567890", "My Message to send");

Note they also support an XML-RPC API if that is more doable from C#.
UPDATE: I made a stab at creating a call myself, but it did not work.  I am going to post my attempt in a separate question and see if anyone has a way to do it.

A: You need to send a HTTP POST with the JSON message to the remote server. You can do this with HttpWebRequest. You either build the JSON manually (the messages seem simple), or define types for it and use a JSON serializer.
MSDN has an example, for your case it would look something like (untested):
string json = // Your JSON message
WebRequest request = WebRequest.Create ("http://api.pennysms.com/jsonrpc");
request.Method = "POST";
var postData = Encoding.UTF8.GetBytes(json);
request.ContentLength = postData.Length;
request.ContentType = "text/json";
using(var reqStream = request.GetRequestStream())
{
    reqStream.Write(postData);
}
using(var response = request.GetResponse())
{
    // Response status is in response.StatusCode
    // Or you can read the response content using response.GetResponseStream();
}

A: See my answer to the question "Client configuration to consume WCF JSON web service" for how the create a JSON client with WCF.

A: The answers so far are good, but one additional thing you can take advantage of (since you are within a WCF service) is the use of DataContractJsonSerializer.
In particular, I refer to how you actually populate your JSON in the first line of driis's example.
string json = // Your JSON message

Now, one of the best ways to do this may be to create a new class with these members:
[DataContract]
class SomeType
{
    [DataMember]
    string method;
    [DataMember]
    string[] params;
}

Then, just create an instance of SomeType every time and serialize it to JSON using the DataContractJsonSerializer every time you want to send over a piece of data. See http://msdn.microsoft.com/en-us/library/bb412179.aspx for how to use the DataContractJsonSerializer stand-alone.
Hope this helps!

A: Check the WCF REST API. They serve JSON, maybe they also can send JSON (in intra WCF solution it works). Maybe you have to construct the contract in wsdl to get the service running but maybe it works out.


text:
Q: angular input search field on an array of objects hey I'm new to angular and I have a problem
I have an array of objects :
holders: Holder[] = [
  { name: 'hanna', nationalId: 310, customerNumber: '123' },
  { name: 'jack', nationalId: 320, customerNumber: '124' },
  { name: 'sara', nationalId: 320, customerNumber: '125' },
];

in my search field I enter the customerNumber and if the holder exist it's name will be displayed under the field and if not it will display an error (the holder does not exist)
the component :
constructor(private holderService: HolderService) {
   this.holderService.searchfunc(this.searchTerm$)
       .subscribe(results => {
           this.result = results;
       });
}
searchHolder(term: string): void {
   this.searchTerm$.next(term);
}

and the service:
searchfunc(terms: Observable<string>) {
   return terms.pipe(
       debounceTime(500),
       distinctUntilChanged(),
       map(term => this.searchEntries(term)));
}
searchEntries(term) {
   if(term){
       this.searchResult = this.holders.filter(x => x.customerNumber === term);
       if(this.searchResult[0]){
           return this.searchResult[0].name;
       }else{
           return 'the holder does not exist';
       }
   }else{
       this.search = term;
   }
}

is there any solution to do it in a better way? and I wanna handle the existence of holder in the component rather than in the service

A: You can put the entire thing in the component if you want to, but it is better approach to do it this way.
If you want to write entire code in component, you can do it this way.
constructor(){
  this.searchTerm$.pipe(
    debounceTime(500),
    distinctUntilChanged(),
    map(term => this.searchEntries(term))
    .subscribe(results => {
       this.result = results;
     });
  )
}

searchEntries(term){
    if(term){
        this.searchResult = this.holders.filter(x => x.customerNumber === term);
        if(this.searchResult[0]){
            return this.searchResult[0].name;
        }else{
            return 'the holder does not exist';
        }
    }else{
        this.search = term;
    }
}


text:
Q: How to force user to take image via camera ( intent camera) or how to disable intent camera back button? I want to force user to click image once camera opened, he should not go back without clicking image via back button.
Please suggest me how to implement force click or disable intent camera back button in android.

A: That is not possible, sorry. If you need that degree of control over the camera, do not use an Intent to launch some third-party camera app. You will need to write your own camera logic, using the camera APIs or a library wrapper around them (CameraX, Fotoapparat, CameraKit/Android, etc.).


text:
Q: XtraGrid Cell Grouping I am using XtraGrid in my app. I want to group some cells togethere and replace them with group name. Following is the description.

I above image I have selected few cells from First columns. Now, from context menu when I will click on "Group", I will popup up a dialog for group name. Now here onwards the problem is.

*

*I want to replace the cell containts logically with the group name. So in grid, for first column's selected cells, but while viweing it should appear as single cell. I have tried the cell merging feature of the xtragrid but that disbales the row selection feature. How to do this?

*The grid shown above is bounded grid, so if I tried to do grouping for lets say Integer type of column, then how can I replace the group name which is string in integer column? is this possible in grid?

*Can I add the unbounded column in bounded grid?
Please help.
Thanks,
Omky

A: The question is 4 years old, but for those who googled this and have the same questions, you could try this:

*

*You are right: To show cells of the first column with same content as a single cell use merging: Set Column1.OptionsColumn.AllowMerge to true. You can influence the merging behaviour using the Views CellMerge Event. As you do not have a continouos row in case of a merged cell, you cannot use
RowSelect.

*To use Grouping you can call Column1.Group(). To specify the value wich is taken for comparison you can specify the Column1.GroupInterval to e.g. Value or DisplayText. The Cells DisplayText can be customized using the CustomColumnDisplayText event.

*As far as I know it is not possible to add an unbound colmn to a
BandedgridView. Why would you want to do this?

Generally there is a fast and qualified support at DevExpress you can contact.


text:
Q: TreeView Access: как добавить иконки? Не могу сделать, чтобы вместо стандартных обозначений в TreeView (крестик) были созданы иконки папок для родительских веток и другую картинку для детей.
Не понимаю, как заполнять ImageList, чтобы потом его можно было выбрать в свойствах (properties)?
И какие должны быть свойства картинки (будущей иконки)?
Спасибо за помощь!
A: вынесено из комментариев.

Нашел ответ! Добавил в форму ImageListCtrl через панель инструментов, дальше залил через нее иконки (получилось только формат ico 32x32), а дальше в прописании ветки указал индекс, который автоматически появляется в ImageListCtrl.

A: Не помню уже толком детали, но помню, что сначала надо создать список изображения в виде отдельного компонента. Его можно было заполнять либо через свойства, либо программно.
Потом у самого дерева надо выбрать имя списка изображений в каком-то из свойство компонента TreeView. И ещё надо выбрать Style во что-то типа picuture + text, иначе всегда будут отображаться знаки плюс-минус.
К сожалению, больше деталей не помню.


text:
Q: CSS Dynamic Positioning of Relative Elements How would I dynamically change the size of an element with position:relative;? I tried using a width:45%; to make it so it was always 45% of it's container, but when changing the browser size, I found that it remained the size it initially loaded, when I refreshed the page, it was smaller, but stayed smaller when I made the page bigger.
I will accept jQuery and/or Javascript solutions, but would highly prefer CSS. Also, if this seems to be an error with my code, and not due to the way position:relative; works fundamentally, let me know and I'll add my code to the post in a fiddle.
EDIT: Code Added

                This is the Caption's Title
                This is the caption's description

View the rest here
It seems to work in the fiddle, not sure why it won't work client side.

A: Your problem is because of the javascript that is getting executed on page load.
When it iterates over your .captions is sets an inline style to the .caption of a width and height.
This part:
...
     $(this)
        // Add the following CSS properties and values
        .css({
            // Height equal to the height of the image
            "height": $(this).children("img").height() + "px",
            // Width equal to the width of the image
            "width": $(this).children("img").width() + "px"
        })
...

jQuery .css sets inline styles, so when you resize your window nothing changes because the img has static width and height.
You are trying to override this in your CSS with the !important declaration but the inline styles are winning out.
Removing this block of code seems to fix the problem, but I don't know if it will introduce other problems.
I have also put this code in its own function called setCaptionSize() and fire it when the page loads and attach it to the window resize event.
$(function () {
   setCaptionSize();
   $(window).resize(setCaptionSize);
});

I also moved the hover event out of setCaptionSize so it wouldn't get bound multiple times.
See this Fiddle for a demo


text:
Q: jQuery: How to time an element's fadeOut while still in loop? I am looping an element with opacity yet I would like to stop it after 4.8 sec after the document is loaded.  The snippet of my loop is here:
var centor = $(".centeror");
centor.delay(1000);
function centorRun(){
    centor.animate({opacity:'1'}, 700);
    centor.animate({opacity:'0.2'}, 700, centorRun);

}
centorRun();

Every time I run  $(".centeror").delay(5800).fadeOut(); both out of function and in function scope I get bad results, and I'm thinking delay is not the function I should be using, am I right?
PS centorRun is within the $("document").ready(function() {}

A: Try setTimeOut instead of delay. Something like setTimeout(centorRun, 4800);

A: Try this
  setTimeout('$(".centeror").fadeOut()',5000);

Change the time 5000 as mil Second what you like best. 1 sec=1000

A: Toggle 2 funciton every 2 seconds
$(".centeror").toggle(
  function() {
    $(this).animate({opacity:'.3'});
  }, function() {
    $(this).animate({opacity:'1'});
  }
);

setInterval(function(){$(".centeror").trigger('click')}, 2000);


text:
Q: How to properly deploy django channels on windows? I need to design a Django based project with WebSockets on Windows server. It seems like Django Channels is the most elegant and pythonic way to do such thing. However I have issue with finding a proper way to deploy Channels and/or Daphne on Windows. It's suggested to use a process supervisor but all solutions I found so far are on Linux environment.
What is the most proper way to deploy Daphne on Windows? How to actually set it up as Windows service that can scale into multiple threads/processes, listening on the same port. Right now the project (without WebSockets) is deployed on Apache which handles such matters. In case of Daphne I do not know how to make it work that way.
Or maybe I should use something else than Daphne to deploy Channels on Windows?
EDIT: I'm using latest version of Channels 2.0.2, Django 1.10 on Python 3.6.


text:
Q: Delineating adverse/favourable areas adjacent to roads using ArcGIS Desktop? I have a client in the forestry sector that would like me to run some maps with criteria that I've never managed for.
These maps will delineate (using polygons) areas of slope (0-20%,20-40%,>40%), distance from road centreline (0-125m, 125-250m, 250-350m, >350m) and "adverse" and "favourable" skids for a given "block area".
The slope polys and distance buffers are easy enough to produce; I do this all the time.
The challenge for me will be figuring out how to identify the skid conditions. To give more insight on that, a "favourable" skid is defined as an area where harvested wood will be moved "downhill" to a road for decking. An "adverse" skid would be an area where the machine has to skid wood uphill. So this ultimately comes down to the location of the road, the +/- condition of the slope, and the aspect of the slope relative to the road.
It's a fairly complex condition to analyze, but I'm sure it can be done. My client is asking me to replicate another GIS contractor's version of this product… which I am fairly certain is generated with some sort of model or script.
Has anyone done anything similar, or have any insight on how I could achieve these results?
I am running ArcGIS 10.3 and use anything from 1m-20m DEM and LiDAR datasets, but each block has its own constraints.


text:
Q: Visual Studio Code make a keybind for a right-click menu button For example, in VS Code, I can right click on a variable, select Peek > Peek Type Definition.
How can I make a keybinding for this (currently there is no keybinding set)? How can I even find the appropriate command for the keybindings.json file, if the "Peek Type Definition" button is not mapped to anything?

A: Go to the Gear Icon in the lower right. click it and select Keyboard Shortcuts.  It will open the Keyboard Shortcuts editor.
In that editor's input box at the top, type peek type and you will get 2 entries shown.  One is:

Peek Type Definition
editor.action.peekTypeDefinition

That command does not have a default shortcut, but you can make one yourself.
If you hover over that entry, a + sign will appear to its left, click it and an input dialog opens where you can enter your chosen keybinding.
It will make a keybinding in your keybindings.json like
{
  "key": "alt+5",                 // whatever you chose here
  "command": "editor.action.peekTypeDefinition"
}

A: When you right click, the window that pops up is called the context menu. Some keyboards have a context menu button. Unfortunately, VSCode does not use this as the command in the keyboard shortcuts, so there is no way to do this through the keyboard shortcuts menu.
Alternatively, you could use SharpKeys, a utility that lets you remap keys on your keyboard. Personally, I have my right alt key mapped to the context menu button. In SharpKeys, the context menu button does not have a name, so it is just called Special: Application (E0_5D). This allows you to right click from the keyboard.
In the screenshot below, you can see the remap in the highlighted section.

A: The equivalent of right-clicking with a mouse a symbol in an editor panel has a keyboard shortcut
'Show Editor Context Menu on textInputfocus'
The default binding is [shift]+f10.
This will open the right-click menu, and you can navigate with arrows to your menu item.
strong text


text:
Q: Sys is undefined .net 4.0 I know it is missing the ScriptResource.axd but how do i add this handler in .net 4.0?
thanks

A: This is a problem when you try to call the sys before its defined.
2 ways for solve, ether make the sys call after the ScriptManager tag, ether call the sys functions after the page load and Dom is ready by using the onload from body, or if you use jQuery the ready() function

A: Add a ScriptManager.
<asp:ScriptManager runat="server" />


text:
Q: How do I use multiple copy commands in Grunt Build? I would like to copy some files, run other tasks, and then again copy some files:
copy:{....},
concat:{...},
copy:{...}

However, I get the following error when I run my grunt build:
SyntaxError: Duplicate data property in object literal not allowed in strict mode

Of course I understand, that I cannot use the same property (i.e. "copy") multiple times in the grunt json. But what is the solution to my problem? How can I copy at different positions of the gruntfile.js?
Many thanks!

A: Just split your copy comment in the desired subtasks:
copy: {
    task1: {
        files: [...]
    }
    task2: {
        files: [...]
    },
    task3: {
        files: [...]
    }
}

And then run Grunt like that:
grunt.registerTask('development', [ 'copy:task1', 'concat', 'copy:task2' ]);

A: I do the same job like this. Here is my task, right at the end of the Gruntfile:
grunt.registerTask('client', [
    'concat:app_js',
    'concat:lib_js',
    'uglify:app_lib_js',
    'concat:client_js',
    'concat:client_css',
    'includes',
    'concat:client_html',
    'copy:client_gfx',
    'copy:client_xml'
]);

This is referencing a structure higher up that looks like:
module.exports = function(grunt) {

grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),

    concat: { ... concat jobs here ... },

    // This is how to have multiple copy jobs
    copy: {
        client_gfx: {
            // spec here
        },
        client_xml: {
            // spec here
        }
    }
}
}


text:
Q: Apache Authorization for the Allowed Users? I have read the answer to this question:
https://stackoverflow.com/questions/4102763/apache-basic-authentication-except-for-those-allowed
It helped me understand how to not authenticate some users (according to the IP):
<Directory /var/www/files/>
    Order deny,allow
    Deny from all
    Allow from 192.168.1.2
    Satisfy Any
    AuthUserFile /etc/apache2/basic.pwd
    AuthName "Please enter username and password"
    AuthType Basic
    Require valid-user
</Directory>

Imagine I have this DB (Different from the DB used for authentication):
User        IP
Mark        192.168.1.2
Mike        192.168.1.3
Karl        192.168.1.4

1- can I allow all the IP addresses stored in the DB using a configuration in Apache?
2- another problem is the authorization of the allowed IP is lost, can Apache use this DB for authorization, if the user is allowed to get the pages without authentication?
Update:
to be clear:
1- I don't want a static solution, I want Apache to Allow all IPs from the mentioned table in the DB ( the DB is changing dynamically).
2- We know when Apache authenticate users, it knows the user name from authentication credentials, but with the Allowing, the user name will be lost, I want Apache to extract the user name of the IP its allowing from the same table it extract the IP address?

A: In answer to #1 you can have as many IP's allowed as you want... examples:
Allow from 192.168.1.2
Allow from 192.168.1.3
Allow from 192.168.1.4

or even
Allow from 192.168.1.2 192.168.1.3 192.168.1.4

and many others including ranges.
for #2, sorry but I'm not understanding what you're asking, perhaps an example?

A: You can try the answer suggested here of using mod_rewrite to blacklist from a file:
## WHITELIST IPS ##
RewriteMap ipslist txt:/path/to/whitelist.txt
RewriteCond %{REMOTE_ADDR} ^(.*)$
RewriteCond ${ipslist:%1|black} ^black$ [NC]
RewriteRule (.*) - [F]

You can try and use something dynamic like mod_authn_dbd to select the username and password from a database:
# mod_dbd configuration
DBDriver pgsql
DBDParams "dbname=apacheauth user=apache password=xxxxxx"

DBDMin  4
DBDKeep 8
DBDMax  20
DBDExptime 300

<Directory /usr/www/myhost/private>
  # core authentication and mod_auth_basic configuration
  # for mod_authn_dbd
  AuthType Basic
  AuthName "My Server"
  AuthBasicProvider dbd

  # core authorization configuration
  Require valid-user

  # mod_authn_dbd SQL query to authenticate a user
  AuthDBDUserPWQuery \
    "SELECT password FROM authn WHERE user = %s"
</Directory>


text:
Q: WMI on guest Windows account I develop program on Delphi XE3. Program should read hardware information by WMI. My code:
var
  SWbemLocator1: ISWbemLocator;
  Service:  ISWbemServices;
  ...
begin
  CoInitialize(nil);

  SWbemLocator1 := CoSWbemLocator.Create();
  Service:= SWbemLocator1.ConnectServer('.', 'root\CIMV2', '', '', '', '', 0, nil);
  ...

It works perfect, but in guest Windows account ConnectServer call an exception "Access denied" and it doesn't work. Administrator and user account works well. Testing on Windows Vista/7.
How can I fix it?

A:
How can I fix it?

This question pre-supposes that something is broken. That is not so and this behaviour is by design. The guest account is highly limited in what it is allowed to do.
If you wish to allow guest user access to WMI then you will need to modify the guest user's rights to grant it more power. You should think twice about doing so. This article discusses required WMI user rights in some detail: http://community.zenoss.org/thread/12048


text:
Q: Segmentation fault ( Recorded nucleus image) This is my project from shcool and i have this error and cant figure it out! if you can help i really appreciate!
This code is supposed to create an image of a circle with random points inside creating a square! i think i need to solve this with malloc but i cant understand how!
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
//Função que calcula o pi

void*calc_pi(void*parameters)
{
    //inicialização das variaveis

    double npoints=100000000;
    double x,y;
    int i, circle_count=0;
    double D; //diametro do circulo
    double pi;

    for (i=0; i < npoints; i++)
    {
    x=(double)abs(rand())/RAND_MAX;
    y=(double)abs(rand())/RAND_MAX;
    D=sqrt(pow((x-0.5),2)+pow((y-0.5),2));

    //confirmar pontos dentro do circulo

        if (D<=0.5)
        {

        pi=(double)4*circle_count/npoints;
        printf("pi=%f\n",pi);
        circle_count++;
        return NULL;
        }

    }

}

int main()

{
    //iniciar variaveis
    enter code here
    double npoints=100000000;
    double x,y;
    int circle_count=0;
    int i = 0 ;
    double D;
    double pi;
    int numerothreads=5;
    int numpontoscirculo;
    double*npontos_circulo;
    double oi=npoints/numerothreads;

    //id da thread

    pthread_t thread_id;

    //criar uma thread que vai correr a funcao calc_pi
    pthread_create(&thread_id, NULL, &calc_pi,&oi);

    //fazer funçao join para receber os dados threads, criar funçao join para cada thread

    pthread_join(thread_id,(void*)&npontos_circulo);
    printf("O numero de pontos dentro do circulo:\n");
//fazer um ciclo para chamar as threads

    for(i=0;i<5;i++)
    {
    printf("%lf\n",*(npontos_circulo+i));
    }
    return 0;
}


text:
Q: Adding a slideshow to the main page of wordpress I'm trying to create WordPress theme for a website, and want to add a slideshow to the index.php. Since I don't want to show posts on the index and only show the slideshow, can I just remove the WordPress Loop? Or I need to keep it? If I have to keep it, how can I do to only show the slideshow?
Thanks.

A: I wouldn't mess with the index.php page just to remove the loop for the front page. You should create a new file called home.php, copy all content from index.php and remove the loop there. home.php will be used as your homepage and if you ever want to use the normal index.php then you still have it available.
You can even create a custom page template which is very easy to do.

*

*Create a new file titled what ever you would like. I would use something like template-home.php

*add a comment /*Template Name: Home Page*/.

*Copy over content from another file such as page.php and make the preferred edits

*Create a new page and choose the page template under page attributes.

*Go to settings>Reading and choose a static page for you homepage and choose the page you just created.

A: You probably do not want to show posts in the home page.
If so then I suggest that you create a Static Front Page or Splash page instead.

A: You can remove the wordpress loop if you're not needing to retrieve posts or replies, etc.
** However, I don't recommend doing that as you may want to pull images from specific pages which would require the loop

A: You can add Your own HTML and JS one Just follow these steps
 1- Create a new HTML file using notepad (save it as slideshow.html) and past this code in it

          <title>Image Slideshow</title>

2- Then create  a new file with notepad and save it as swissarmy.js and past this in it  "here is the code "
3- create another file with notepad and save it as slideshow.js and replace the images urls with the urls inside it  Here is the Code
4- put all of these files in one folder and open the slideshow.js then replace the images with your own images and texts with the text you want
5- open the HTML file and it will work


text:
Q: sign up button disappear after page refreshing I have problem with sign up button while registering as user, Actually there is check box for T&c. After checking that check box only button should enable.
Everything is going well But, when I am refreshing page I am not able to see button, I able to see all other elements even check box.
here are Html tags I used for check box and Sign Up button and I also used flags.

<input type="checkbox" id="rd" name="check" class="flashadmin" ng-model="user.tnc" ng-click="setbuttonFlag(user.tnc)" class="flashadmin">

           I agree to the Terms of Use and Privacy Policy.

<button ng-if="buttonFlag==true" id="signup"class="btn btn-default btn-block btn-login" type="submit" >Sign up</button>
<button ng-if="buttonFlag==false" id="signup" class="btn btn-default btn-block btn-login" disabled  >Sign up</button>
here is validation i wrote for flag
$scope.buttonFlag=false;
$scope.setbuttonFlag =function(checkbox){
    if(checkbox == true){
        $scope.buttonFlag=true;
    }else{
        $scope.buttonFlag=false;
    }
};

I am getting in console
Error: $injector:unpr
Unknown Provider

A: First thing is your code looks clumsy!
Below mistake you did, you misunderstood the concept completely.
Why you required for two submit button in your html? Also no need separate click event for changing button flag.
Now coming to your question:

When I am refreshing page I am not able to see button

This is because your are using ng-if directive in button element at the same time while initiating your controller you set $scope.buttonFlag=false so obviously you can't see button while refresh..
Below snippet will work for you!

angular.module("app", []).controller("testCtrl", function($scope) {
 $scope.buttonFlag = false;
});

    <input type="checkbox" ng-model='buttonFlag'> I agree to the Terms of Use and Privacy Policy.
    <button ng-disabled='!buttonFlag' id="signup" class="btn btn-default btn-block btn-login">Sign up</button>

A: Well upon refresh you are manually setting buttonFlag to false hence the button disappears.Store buttonFlag in localStorage and check the state of buttonFlag unlike setting it to false as you have done.
if(localStorage.getItem('buttonFlag')){
    buttonFlag = localStorage.getItem('buttonFlag');
}
else{
    buttonFlag = false;
}

also instead of using two different button for signup use ng-disabled to disable or enable a button


text:
Q: List path with word match in bash script I have a string that contain a list of lines.I want to search any particular string and list all the path that contains the string.
The given string contains the following:
  755677 myfile/Edited-WAV-Files
  756876 orignalfile/videofile
  758224 orignalfile/audiofile
  758224 orignalfile/photos
  758225 others/video
  758267 others/photo
  758268 orignalfile/videofile1
  758780 others/photo1

I want to extract and list only the path that start from Orignal File. My output should be like this:
 756876 orignalfile/videofile
 758224 orignalfile/audiofile
 758224 orignalfile/photos
 758268 orignalfile/videofile1

A: That looks easy enough...
echo "$string" | grep originalfile/

or
grep originalfile/ << eof
$string
eof

or, if it's in a file,
grep originalfile/ sourcefile

A: A bash solution:
while read f1 f2
do
     [[ "$f2" =~ ^orignal ]] && echo $f1 $f2
done < file

A: If your string spans several lines like this:
755677 myfile/Edited-WAV-Files
756876 orignalfile/videofile
758224 orignalfile/audiofile
758224 orignalfile/photos
758225 others/video
758267 others/photo
758268 orignalfile/videofile1
758780 others/photo1

Then you can use this code:
echo "$(echo "$S" | grep -F ' orignalfile/')"

If the string is not separated by new lines then
echo $S | grep -oE "[0-9]+ orignalfile/[^ ]+"

A: egrep '^[0-9]{6} orignalfile/' <<<"$string"

note:

*

*the ^ matches the start of the string. You don't want to match things that happen to have orignalfile/ somewhere in the middle

*[0-9]{6} matches the six digits at the start of each line

A: Are you sure that your string contains linebreaks/newlines?
If it does then the solution of DigitalRoss will apply.
If it doesn't contain newlines then you must include them. In example if your code looks like
string=$(ls -l)

then you must prepend it with field separator string without linefeed:
IFS=$'\t| ' string=$(ls -l)

or with an empty IFS var:
IFS='' string=$(ls -l)

Docs for IFS from the bash man page:
IFS    The  Internal  Field  Separator  that  is  used for word splitting after
       expansion and to split lines into words with the read builtin command.  The
       default value is ``<space><tab><newline>''.


text:
Q: VBA : deleteing the information from sheet I'm wondering if there is more efficient way to clean my sheet. My code takes a long time to run (I have 5000 observations ):
Dim Num_Ligne As Long
 Num_Ligne = 8

 While Cells(Num_Ligne, 3) <> ""
  ActiveSheet.Cells(Num_Ligne, 3).Value = ""
  ActiveSheet.Cells(Num_Ligne, 4).Value = ""
  ActiveSheet.Cells(Num_Ligne, 5).Value = ""
  ActiveSheet.Cells(Num_Ligne, 6).Value = ""
  ActiveSheet.Cells(Num_Ligne, 7).Value = ""
  ActiveSheet.Cells(Num_Ligne, 8).Value = ""
  ActiveSheet.Cells(Num_Ligne, 9).Value = ""
  ActiveSheet.Cells(Num_Ligne, 10).Value = ""
    Num_Ligne = Num_Ligne + 1
Wend

Thank you for your help !

A: Clear Contents of a Range
Requirements

*

*Clear the contents of a range.

OP's Solution

*

*Loop through each cell and test if it is empty. Then loop through each column and clear its contents. For 5000 records it tests 5000 times a cell if it is blank and clears the contents of a cell 40.000 times which takes about 10s on my machine.

Solution

*

*Create a reference to all those cells and clear the contents in one go.

*The first solution is a 'flavor' of BigBen's solution in the comments which is widely used (popular) and is based on the End property. This (my) solution uses Resize ('flavor').

*The second solution is a more reliable version that uses the Find method which may only fail if the worksheet is filtered. The End solution will additionally fail if the last cell on the worksheet is occupied (highly unlikely), if the last row is less than the specified first row (unlikely), and if there are hidden rows (unlikely).

*The third solution is kind of a study of the second solution.

*For even more insights, study the legendary Siddharth Rout's answer to Error in finding last used cell in Excel with VBA.

The Code
Option Explicit

Sub RangeClearContentsEnd()

    Const Cols As String = "C:J"
    Const FirstRow As Long = 8

    With ActiveSheet.Columns(Cols)
        Dim LastRow As Long
        LastRow = .Columns(1).Cells(.Rows.Count).End(xlUp).Row
        .Rows(FirstRow).Resize(LastRow - FirstRow + 1).ClearContents
    End With

End Sub

Sub RangeClearContentsFind()

    Const Cols As String = "C:J"
    Const FirstRow As Long = 8

    With ActiveSheet.Columns(Cols).Rows(FirstRow)
        Dim cel As Range
        Set cel = .Resize(.Worksheet.Rows.Count - FirstRow + 1, 1) _
            .Find("*", , xlFormulas, , , xlPrevious)
        If Not cel Is Nothing Then
            .Resize(cel.Row - FirstRow + 1).ClearContents
        End If
    End With

End Sub

Sub RangeClearContentsFindStudy()

    Const Cols As String = "C:J"
    Const FirstRow As Long = 8

    ' Define the first row (range) of the range.
    Dim rrg As Range: Set rrg = ActiveSheet.Columns(Cols).Rows(FirstRow)
    Debug.Print "First Row of the Range    : " & rrg.Address(0, 0)
    ' Define the range referring to the first column from
    ' the specified first row to the bottom-most row of the worksheet.
    Dim frg As Range
    Set frg = rrg.Resize(ActiveSheet.Rows.Count - FirstRow + 1, 1)
    Debug.Print "First Column to the Bottom: " & frg.Address(0, 0)
    ' Attempt to find the last non-empty cell in it.
    Dim lCell As Range
    Set lCell = frg.Find("*", , xlFormulas, , , xlPrevious)
    ' Validate the last non-empty cell.
    If Not lCell Is Nothing Then
        Debug.Print "Last Non-Empty Cell:        " & lCell.Address(0, 0)
        ' Define the range from the first specified row
        ' to the last non-empty cell's row.
        Dim drg As Range: Set drg = rrg.Resize(lCell.Row - FirstRow + 1)
        Debug.Print "Delete Range:               " & drg.Address(0, 0)
        ' Clear its contents.
        drg.ClearContents
    Else
        Debug.Print "Nothing cleared."
    End If

End Sub

A: The Requirements: To clear the contents of a range.
The Data: The data involved contains a mix of cells (i.e:, some cells have content, others are empty), as could be understood from this line in the question code While Cells (Num_Ligne, 3) <>"".
The figure below represents a sample of the data. There we have cells with a constant value (X), cells with formulas (filled with a pattern), and all other cells are empty. In this sample data the Last Row is the Row 26.

Now let's look at some of the methods to obtain the last row in line with the data involved.
End(xlUp).Row method: In this case, I would suggest not using this method unless it is applied to each of the columns involved, but then it won't be practical.
When applied only to the first column, it returns row 25, instead of row 26.
Find method: In this case, this method will only be effective if it is applied to the entire range.
When applied only to the first column, it also returns row 25.
When applied to the entire range [C:J] it will return the correct row 26.
However, if the last time the Find method was utilized the SearchOrder applied was xlByColumns, then when we run our procedure the method will return row 25, if the SearchOrder was not set to xlByRows in our procedure.
Bear in mind that the LookIn, LookAt, SearchOrder and MatchByte* parameters are saved each time the Find method is applied, therefore these parameters should always be included (*if applicable) to ensure the expected return.
UsedRange: This is one of the few cases where this worksheet property could be used. As in this case, the objective is to set a range from an initial row to the last row with contents of specific columns and then clear the contents of that range. Actually utilizing the UsedRange simplifies the code a lot.
With ActiveSheet
    Range(.Rows(8), .Rows(.UsedRange.SpecialCells(xlCellTypeLastCell).Row)).Columns("C:J").ClearContents
End With

Last Row? However, each problem has its own peculiarities, and for this particular problem we should also ask ourselves the question:

*

*In this case, is the last row really necessary?
I think the answer is no. So let's simplify things even more.
With ActiveSheet
    Range(.Rows(8), .Rows(.Rows.Count)).Columns("C:J").ClearContents
End With

A: You have options:
Sub test()
Dim Num_Ligne As Long

Num_Ligne = 8

While Cells(Num_Ligne, 3) <> ""
   'ActiveSheet.Cells(Num_Ligne, 3).EntireRow.Clear
   ActiveSheet.Range("C" & Num_Ligne & ":J" & Num_Ligne).Clear
   Num_Ligne = Num_Ligne + 1
Wend

End Sub


text:
Q: Pulling images from folder, 403 error I'm getting a 403 forbidden error on this script. After talking on the phone with my service provider they said that my code is wrong and that I'm mapping it wrong. But I know I'm not, because if I was mapping it wrong I would get a 404 error and not a 403 error. Is this correct? Basically I'm pulling images from a folder and putting them into a slideshow. But Javascript gets a 403 error. Any help would be appreciated, thank you.
$(document).ready(function() {
  var dir = "Ads/";
  var fileextension = ".jpg";
  $.ajax({
    url: dir,
    success: function (data) {
      $(data).find("a:contains(" + fileextension + ")").each(function () {
        var filename = this.href.replace(window.location.host, "").replace("http://", "");
        var newimage = document.createElement('li');
        newimage.innerHTML = ('');
        document.getElementById("localAds").appendchild(newimage);
      });
    }
  });
});
$(function () {
  var change_img_time     = 5000;
  var transition_speed    = 100;
  var simple_slideshow    = $("#localAds"),
  listItems           = simple_slideshow.children('li'),
  listLen             = listItems.length,
  i                   = 0,
  changeList = function () {
    listItems.eq(i).fadeOut(transition_speed, function () {
      i += 1;
      if (i === listLen) {
        i = 0;
      }
      listItems.eq(i).fadeIn(transition_speed);
    });
  };
  listItems.not(':first').hide();
  setInterval(changeList, change_img_time);
});

Edit:
HTML:

CSS:
.crop {
  width: 353px;
  height: 206px;
  overflow: hidden;
}
.crop img {
  width: 353px;
  height: 206px;
}

The page looks like business card sized images running through a slideshow.


text:
Q: Extract text from specific columns in c#? I have been working on extracting text from a csv file and store the data in a string. But now, I would like to extract text from some of the specific columns  and store the data in a string.I would like the wordDocContents variable to contain the specific columns and the data in those specific columns  which is bank_account, bank_name, customer_name. Currently, my wordDocContents has the entire data from my csv file. Is there a way to filter out the specific columns and the data in those columns and store it in the variable wordDocContents. Thanks
Here is what I tried so far -
public void button1Clicked(object sender, EventArgs args)
{
    button1.Text = "You clicked me";

    var textExtractor = new TextExtractor();

    var wordDocContents = textExtractor.Extract("t.csv");
    Console.WriteLine(wordDocContents);
    Console.ReadLine();
}

The contents of wordDocContents:-
ACCOUNT_NUMBER,CUSTOMER_NAMES,VALUE_DATE,BOOKING_DATE,TRANSACTION,ACCOUNT_TYPE,BALANCE_TYPE,REFERENCE,MONEY.OUT,MONEY.IN,RUNNING.BALANCE,BRANCH,EMAIL,ACTUAL.BALANCE,AVAILABLE.BALANCE
1000000001,TEST,,2847899,KES,Account,,,10/10/2016,9/11/2016,15181800,UPPER HILL BRANCH,another@yahoo.com,5403.75,5403.75,
1000000001,,9/11/2016,9/11/2016,Opening Balance,,,,,,4643.22,,,,,
1000000001,,12/10/2016,12/10/2016,Mobile Mpesa Transfer,,,,1533,,3110.22,,,,,
1000000001,,17-10-2016,17-10-2016,ATM Withdrawal,,,6.29006E+11,1000,,2110.22,,,,,
1000000001,,17-10-2016,17-10-2016,ATM Withdrawal,,,6.29118E+11,2000,,110.22,,,,,
1000000001,,17-10-2016,17-10-2016,Mobile Mpesa Transfer,,,,2083,,-1972.78,,,,,
1000000001,,17-10-2016,17-10-2016,Transfer from Mpesa,,,,0,4000,2027.22,,,,,
1000000001,,18-10-2016,18-10-2016,Mobile Mpesa Transfer,,,,333,,1694.22,,,,,

A: From my knowledge on how csv files are constructed. (Maybe post the first 2 lines of your output?)
string[] lines = wordDocContents.Split("\n");
string[] columns = lines[0].Split(",");
string[][] data = new string[lines.Length][columns.Length];

Now let's say customer_name is under columns[2], you can try to:
List<string> customerNames = new List<string>();
for (int i = 1; i < lines.Length; i++) {
customerNames.Add(data[i][2]);
}

Edit just saw the output, this code might need some adjusting for your particular case. I am not 100% sure if string.Split(",") works for multiple commas in a row, but it's worth a shot. Just change the [2] to whichever column you need.
It should be going from [0],[1],[2] etc.


text:
Q: determine the address of the location using the Google Maps Geocoding API i had problem on saving the address in variable when i use google map api
i try to save it in global variable and then calling these variable with console.log
<script>
    var x;
    window.onload = function () {
        var mapOptions = {
            center: new google.maps.LatLng(27.191315760031543, 31.189079340815315),
            zoom: 14,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        var infoWindow = new google.maps.InfoWindow();
        var latlngbounds = new google.maps.LatLngBounds();
        var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);

        google.maps.event.addListener(map, 'click', function (e) {
            var latlng = new google.maps.LatLng(e.latLng.lat(), e.latLng.lng());
            var geocoder = geocoder = new google.maps.Geocoder();
            geocoder.geocode({ 'latLng': latlng }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[1]) {
                    alert("Location: " + results[1].formatted_address + "\r\nLatitude: " + e.latLng.lat() + "\r\nLongitude: " + e.latLng.lng());
                            x=results[1].formatted_address;
                }
            }
        });
    });
    }
    console.log(x);
</script>

Geocoding Service: You must use an API key to authenticate each request to Google Maps Platform APIs. For additional information, please refer to http://g.co/dev/maps-no-account For more information on authentication and Google Maps JavaScript API services please see: https://developers.google.com/maps/documentation/javascript/get-api-keyenter code here

A: It's required to include an API key to authenticate all Maps API requests. As per the error you provided, it indicates that there is no API key included in the script that loads the JavaScript API.
Kindly include the API key like this:
    <script async defer
      src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY">
    </script>

Then replace the text YOUR_API_KEY with your valid API key.
Please also note that it is recommended to initialize your map by specifying a callback parameter. Please see more info about that here.


text:
Q: Nginx proxy pass without the location url on proxy_pass I am trying to proxy pass in nginx. here is what the config looks like  :
location /amazon {
        proxy_pass http://amazon.com;
    }

when I open domain.com/amazon it takes me to amazon.com/amazon. How should I write it so that is opens only amazon.com, without /amazon.

A: You can rewrite the URL to cut the /amazon prefix. Example:
location /amazon/ {
  rewrite /amazon/(.*) /$1 break;
  proxy_pass https://www.amazon.com;

  # bonus configuration for this particular host
  # may be irrelevant in your case
  proxy_set_header Host "www.amazon.com";
  proxy_ssl_server_name on;
}


text: Q: subschemes of abelian scheme over artinian basis Let $R$ be an artinian thickening of a field $k$. Denote with $S=Spec(R)$. Let $A$ be an abelian scheme over $S$. Let $X$ be a closed, reduced, equidimensional subscheme of the special fiber $A_k$. I would like to know if there is an Hilbert schemes parametrizing $R$-flat subschemes $\mathcal{X}$ of $A$ such that $\mathcal{X}_k\cong X$ and if any property of this object is known (dimension, connectedness,...). I am sure that some other invariants of $\mathcal{X}$ have to be fixed in order to get a nice object, but I do not know which ones.


text:
Q: Launch different activities from the same WidgetProvider in ListWidget I have a list widget and I want to launch differnt activities from different rows, but it always launch the activity that is in the PendingIntent, How can I do this? I  have the following codes:
public class MyWidgetProvider extends AppWidgetProvider {

public void onUpdate(Context context, AppWidgetManager appWidgetManager,
        int[] appWidgetIds) {
            ....

        Intent startActivityIntent = new Intent();
             startActivityIntent.setClass(context, Principal.class);
        PendingIntent startActivityPendingIntent = PendingIntent.getActivity(context, 0, startActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        views.setPendingIntentTemplate(R.id.events_list, startActivityPendingIntent);

        appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds[i], R.id.events_list);
        appWidgetManager.updateAppWidget(appWidgetIds[i], views);
    }

    ....

}

In my WidgetFactory class
public RemoteViews getViewAt(int position) {

               ...

    Intent fillInIntent = new Intent();
    fillIntent.setClass(mContext, Activity2.class);
    views.setOnClickFillInIntent(R.id.ll1, fillInIntent);

               ...
}

I want to start to start different activity depending to the row that i clicked (Row1-->Activity1, Row2-->Activity2...), but It always launchs the Principal activity.


text:
Q: R ggplot2 Plotting Loop with Unequal Length Vectors I have an example dataframe with several unequal length vectors (i.e. some are 5 datapoints long, some are 3, etc. I have a loop that generates a ggplot for each column. However, I can't figure out how to dynamically shorten the plot when there are missing data.
Data Example:
        date        X1        X2        X3
1 1997-01-31 0.6094410        NA 0.5728303
2 1997-03-03 0.7741195        NA 0.0582721
3 1997-03-31 0.7269925 0.5628813 0.8270764
4 1997-05-01 0.5471391 0.5381265 0.8678812
5 1997-05-31 0.8056487 0.4129166 0.6582061

Code so far:
vars <- colnames(data[-1])
plots <- list()

for (x in 1:length(vars)) {
  plot[[x]] <- ggplot(data = data, aes_q(x = data[, 1], y = data[, x + 1])) +
    geom_line()
}

Plotting the first plot yields a good result:
Plot 1
But, plotting the second plot yields this short line:
Plot 2
How can I change my loop so that the second plot is this?:
Plot 3
Thank you in advance! Any help is appreciated

A: Before you specify which column you want for the y-axis, ggplot will prepare to map to the whole data frame. So if you just enter ggplot(data, aes(x = date)), you'll already get a blank plot with that range:

So if you don't want some series to print the whole range, you have to filter the data set first, to the rows that are defined for the column you're going to use for the y values. For instance, you could create the X2 plot using:
temp <- data[complete.cases(data[c(1,3)]), c(1,3)]
ggplot(temp, aes(x = date, X2)) + geom_line()

I like to do this using dplyr and tidyr:
library(dplyr); library(tidyr)
temp <- data %>% select(date, X2) %>% drop_na()
ggplot(temp, aes(x = date, X2)) + geom_line()

To do this for all variables, here's an approach using dplyr and tidyr with purrr:
library(purrr); library(dplyr); library(tidyr)
plots <- data %>%
  # Convert to long form and remove NA rows
  gather(var, value, -date) %>%
  drop_na() %>%

  # For each variable, nest all the available data
  group_by(var) %>%
  nest() %>%

  # Make a plot based on each nested data, where we'll use the
  #   data as the first parameter (.x), and var as the second
  #   parameter (.y), feeding those into ggplot.
  mutate(plot = map2(data, var,
                     ~ggplot(data = .x, aes(date, value)) +
                       geom_line() +
                       labs(title = .y, y = .y)))

# At this point we have a nested table, with data and plots for each variable:
plots
# A tibble: 3 x 3
  var   data             plot
  <chr> <list>           <list>
1 X1    <tibble [5 x 2]> <S3: gg>
2 X2    <tibble [3 x 2]> <S3: gg>
3 X3    <tibble [5 x 2]> <S3: gg>

# To make this like the OP, we can extract just the plots part, with
plots <- plots %>% pluck("plot")
plots

plots[[1]]
plots[[2]] # or use `plots %>% pluck(2)`
plots[[3]]


text:
Q: how to return two values from a method? I have class were I have method. now I want send two calculated values out from the method same time. how i can do that, that I can call method from main program? my program returns only first value now. Can i return somehow something like this: console.writeLine("first value" + x + "second value is:" + y?
my method code:
public static double calculate(double r)
{
    double x;
    double y;
    x = r * r;
    y = r * r * r;

    return x; // should i put something here or shuld i do somehow array?
}

A: use out parameters
double in1, in2;
double result = calculate(10, out in1, out in2);

public static double calculate(double r, out double x, out double y)
{
    x = r * r;
    y = r * r * r;

    return x;
}


text:
Q: java InputStreamReader / BufferedReader "read" behavior A related question is this one: Where is the specification that defines this behavior for InputStreamReader?, but I'm not sure if it answers mine...
Please note, I'm just experimenting with the language.
I have this code:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Capitalize {

    public static void main(String[] args) {

        try (BufferedReader br = new BufferedReader(new InputStreamReader(
                System.in))) {

            char c;
            do {
                c = Character.toUpperCase((char) br.read());
                System.out.print(c);
            } while (c != (char) -1);
        } catch (IOException e) {
            e.printStackTrace(System.err);
        }
    }

}

Using ubuntu linux, I was expecting the output to be like this:
fFoOoO  bBaArR

but instead, it's like this:
foo bar (line feed)
FOO BAR (waits for more characters or Ctrl + D)

Right now I'm not sure about what is the behavior in windows, probably it's different, but still, this confuses me a bit. Reading the documentation for the read method, I see it will only return -1 if the end of stream is reached. I kind of understand how that would work for reading a file, but how about, in this case, the console? Why does it have to wait until the Ctrl + D is typed? Is there any way to get to the end of the stream without having to type Ctrl + D? Is there a way to achieve what I was expecting?
Thanks in advance

A: *

*As EJP comments, this is nothing to do with InputStream / BufferedReader.  What you are seeing is the behaviour of the Linux "tty" input drivers and a typical console command.

*What you are seeing is normal "line editing" or "line buffering".  The input is only made available for Java to read (via the stdin file descriptor) when you press the <Enter> key.  The output you are seeing prior to that is the character echoing from the "tty" drivers.  (And notice that if you enter <Backspace> or whatever ... the characters get erased.  When you type <Enter>, Java doesn't see the backspaces, etc.   They have been edited out.)

*Input via the java.io.Console class behaves the same way.

*This is the same on Windows: the behaviour is portable.  (This is a good thing ...)

*If you want your Java application to see the characters as they are typed, when they are typed, you will need to use 3rd-party libraries (or native code) to implement this.  (In Linux, it entails switching the tty driver into "raw" mode ... and this functionality is non-portable, and not supported by standard Java SE.)


text:
Q: Metaclasses via global options Vision
I am making a small, custom LaTeX class for my organization. I want this class to support a couple different kinds of documents: articles, and reports. I want to actually inherit from the article, or report class, depending on provided global options.
I know this sounds a bit weird, but I think I have a good enough reason. The two documents will share common elements, like a common coverpage and other kinds of markings, and I want to share common code for those features. Still, there are other "category-specific" changes I'd like to make (default font size, shorter or longer form default settings, etc.)
I could accomplish this by just inheriting from one class, and overriding default options depending on what global options the user passes. But I'd like this to be modular and easily modifiable for the future (maybe a book format, etc.)
Attempt
This is what I've got so far.
%
% custom.cls
%

\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{custom}[...]

% Use key-value options for article/report specification
\RequirePackage{kvoptions}

\DeclareBoolOption{report}
\DeclareComplementaryOption{article}{report}

% I _hope_ this processes key-value options, and no others
\ProcessKeyvalOptions{custom}\relax

\ifcustom@report
    \input{custom-report}
\else
    \input{custom-article}
\fi

%
% custom-report.tex
%

\message{This is a report!}
\message{Class Options: \@classoptionslist}

\ExecuteOptions{11pt,letterpaper}
\DeclareOption*{\PassOptionsToClass{\CurrentOption}{report}}
\ProcessOptions\relax
\LoadClass{report}

%
% custom-article.tex
%

\message{This is an article!}
\message{Class Options: \@classoptionslist}

\ExecuteOptions{12pt,letterpaper}
\DeclareOption*{\PassOptionsToClass{\CurrentOption}{article}}
\ProcessOptions\relax
\LoadClass{article}

Problem
I get all kinds of weird errors doing this. I can successfully pass report or article to \documentclass[...]{custom}, and the proper "class" is loaded. But when I try to add other options, such as twocolumn, I'll get errors indicating a missing \begin{document}, even though I'll have a \begin{document}.
Is this kind of behavior supported? Is there a "right" way to do what I'm trying to do? I'd really prefer not to write separate .cls files...


text:
Q: Problems loading yahoo and others I have been having issues with several websites saying "server not found", and I have ruled out proxy issues as the cause.  From what I have found while looking for assistance, my problem likely lies with DNS.
If you have Ubuntu 12.04, and can both load and use Yahoo mail, please post the contents of the following folder so I can compare mine to yours and hopefully resolve my issue.  Also, please post the full text of the files within the folder as seen through the Text Editor App.
File System - etc - dhcp3

A: OK, figured it out, if unable to load Yahoo and similar sites, and unsure of DNS on own computer, set a static IP for your computer(which I did).  Now it all works, even after a reboot.


text:
Q: subset rows with unique combination in R > df1 = data.frame(v1=c('a','a','c','x','y','z'),v2=c('b','c','a','y','z','y'),v3=c('c','b','b','z','x','x'))
   v1 v2 v3
1  a  b  c
2  a  c  b
3  c  a  b
4  x  y  z
5  y  z  x
6  z  y  x

Desired o/p:
   v1 v2 v3
   a  b  c
   x  y  z

or  (order doesn't matter)
   v1 v2 v3
   c  a  b
   z  y  x

I am trying to find a unique combination of rows in a data frame.
I have tried
unique(df[,c('v1','v2','v3'))

But, I am not getting desired output. I have dataframe with multiple combinations and which also include NA.
Please help me.

A: The following works with your data example, and I believe that it will also work with larger datasets.
inx <- !duplicated(apply(df1, 1, function(x) paste(sort(x), collapse = "")))
df1[inx, ]
  v1 v2 v3
1  a  b  c
4  x  y  z


text:
Q: how can I store $data array for all methods in a controller I have some data array which I need for all method's in a controller.
          $data['project_ongoing_res_limit']=$this->admin_model->show_project_ongoing_residential_limit();
          $data['project_ongoing_com_limit']=$this->admin_model->show_project_ongoing_commercial_limit();

          $data['project_upcoming_res_limit']=$this->admin_model->show_project_upcoming_residential_limit();
          $data['project_upcoming_com_limit']=$this->admin_model->show_project_upcoming_commercial_limit();

          $data['project_completed_res_limit']=$this->admin_model->show_project_completed_residential_limit();
          $data['project_completed_com_limit']=$this->admin_model->show_project_completed_commercial_limit();

Problem is I cant DRY this. so I have paste this $data array in each method.

I have  a view page for this. so when I load this view , I have to
  load above $data array each time/method. this is disgusting when controller
  methods are too much.

I want 1 piece of this code like constructor. How can I do this.

A: you can use traits for this.
Define your methods in a trait, and then use the trait in the controllers.

A: You can make one helper class in which make a function and put your above code in it but make sure you can't access model using $this so, you need to create CI instance and than access it. after that in your controller in construct method you just need to call this function but don't forget to load the helper class and store it in a variable and pass it along with view.

A: Just create private data variable in your controller class. Than set your data in constructor. Now you can access your data in any method you want.
class Pages extends CI_Controller {
    // ...
    private $data;
    // ...
    public function __construct() {
        parent::_construct();

        $this->data = array();

        $this->data['project_ongoing_res_limit']=$this->admin_model->show_project_ongoing_residential_limit();
        $this->data['project_ongoing_com_limit']=$this->admin_model->show_project_ongoing_commercial_limit();

        $this->data['project_upcoming_res_limit']=$this->admin_model->show_project_upcoming_residential_limit();
        $this->data['project_upcoming_com_limit']=$this->admin_model->show_project_upcoming_commercial_limit();

        $this->data['project_completed_res_limit']=$this->admin_model->show_project_completed_residential_limit();
        $this->data['project_completed_com_limit']=$this->admin_model->show_project_completed_commercial_limit();
    }
    // ...
}


text:
Q: Propel paginate() method doesn't work as expected I'm trying to do a pagination in the website I'm developing. I found that Propel has a paginate() method that is useful for doing this but I cannot make it work.
Here's some code:
$pager = ElementQuery::create()->paginate($page = 1, $maxPerPage = 10);

$pager should have the following methods, by Propel's official documentation:
$pager->getNbResults();   // total number of results if not paginated
$pager->haveToPaginate(); // return true if the total number of results exceeds the maximum per page
$pager->getFirstIndex();  // index of the first result in the page
$pager->getLastIndex();   // index of the last result in the page

And I should be able  to do something like this:
$links = $pager->getLinks(5);

But I'm just getting Element class methods.
Am I missing something?
Here's where I got that information about pagination (to find it fast press Ctrl + F and type paginate())
Thanks.

A: If you let me auto-answer my question... It seems those methods I mentioned are there, but for some reason they don't appear on my Netbeans editor when I write $pager->
I don't know if this counts as an answer but the "problem" is "solved"...


text:
Q: DataReader or DataSet when pulling multiple recordsets in ASP.NET I've got an ASP.NET page that has a bunch of controls that need to be populated (e.g. dropdown lists).
I'd like to make a single trip to the db and bring back multiple recordsets instead of making a round-trip for each control.
I could bring back multiple tables in a DataSet, or I could bring back a DataReader and use '.NextResult' to put each result set into a custom business class.
Will I likely see a big enough performance advantage using the DataReader approach, or should I just use the DataSet approach?
Any examples of how you usually handle this would be appreciated.

A: *

*If you have more than 1000 record to bring from your DataBase.

*If you are not very interested with
custom storing and custom paging
"For GridView"

*If your server have a memory stress.

*If there is no problem to connect to
your DataBase every time that page
called.

Then i think the better is to use DataReader.
else

*

*If you have less than 1000 record to bring from your DataBase.

*If you are interested with
storing and paging "For
GridView"

*If your server haven't a memory
stress.

*If you want to connect to your
DataBase just one time and get the
benefits of Caching.

Then i think the better is to use DataSet.
I hop that i'm right.

A: Always put your data into classes defined for the specific usage. Don't pass DataSets or DataReaders around.

A: If your stored proc returns multiple sets, use the DataReader.NextResult to advance to the next chunk of data.  This way you can get all your data, load it to your objects, and close the reader as soon as possible.  This will be the fastest method to get your data.

A: Seeing that no answer has been marked yet even though there are plently of good answers already, I thought I'd add by two bits as well.
I'd use DataReaders, as they are quite a bit faster (if performance is your thing or you need as much as you can get). Most projects I've worked on have millions of records in each of the tables and performance is a concern.
Some people have said it's not a good idea to send DataReader across layers. I personally don't see this as a problem since a "DbDataReader" is not technically tied (or doesn't have to be) to a database. That is you can create an instance of a DbDataReader without the need for a database.
Why I do it is for the following reasons:
Frequently (in a Web Application) you are generating either Html, or Xml or JSON or some other transformation of your data. So why go from a DaraReader to some POCO object only to transform it back to XML or JSON and send it down the wire. This kind of process typically requires 3 transformations and a boot load of object instantiations only to throw them away almost instantly.
In some situations that's fine or can't be helped. My Data layer typically surfaces two methods for each stored procedure I have in the system. One returns a DbDataReader and the other returns a DataSet/DataTable. The methods that return a DataSet/DataTable call the method returning a DbDataReader and then uses either the "Load" method of the DataTable or an adapter to fill the dataset. Sometimes you need DataSets because you probably have to repurpose the data in some way or you need to fire another query and unnless you have MARS enabled you can't have a DbDataReader open and fire another query.
Now there are some issues with using DbDataReader or DataSet/DataTable and that is typically code clarity, compile time checking etc. You can use wrapper classes for your datareader and in fact you can use your DataReaders a IEnumerable with them. Really cool capability. So not only do you get strong typing and code readability you also get IEnumerable!
So a class might look like this.
public sealed class BlogItemDrw : BaseDbDataReaderWrapper
{
    public Int64 ItemId { get { return (Int64)DbDataReader[0]; } }
    public Int64 MemberId { get { return (Int64)DbDataReader[1]; } }
    public String ItemTitle { get { return (String)DbDataReader[2]; } }
    public String ItemDesc { get { if (DbDataReader[3] != DBNull.Value) return (String)DbDataReader[3]; else return default(String); } }
    public DateTime ItemPubdate { get { return (DateTime)DbDataReader[4]; } }
    public Int32 ItemCommentCnt { get { return (Int32)DbDataReader[5]; } }
    public Boolean ItemAllowComment { get { return (Boolean)DbDataReader[6]; } }
    public BlogItemDrw()
      :base()
    {
    }

    public BlogItemDrw(DbDataReader dbDataReader)
      :base(dbDataReader)
    {
    }
}

DataReader Wrapper
I have a blog post (link above) that goes into a lot more detail and I'll be making a source code generator for these and other DataAccess layer code.
You can use the same technique for DataTables (the code generator produces the code) so you can treat them as strongly typed DataTable without the overhead of what VS.NET provides out of the box.
Keep in mind that there is only one instance of the wrapper class. So you're not creating hundreds of instances of a class only to throw it away.

A: Map the DataReader to intermediate objects and then bind your controls using those objects. It can be ok to use DataSets in certain circumstances, but those are few and far between when you have strong reasons for "just getting data". Whatever you do, don't pass a DataReader to your controls to bind off of (not that you said that you were considering that).
My personal preference would be to use an ORM, but if you are going to hand roll your data access, by all means I think you should prefer mapping DataReaders to objects over using DataSets. Using the .NextResult as a way to limit yourself from hitting the database multiple times is a double edged sword however so choose wisely. You will find yourself repeating yourself if you try to create procs that always grab exactly what you need using only one call to the database. If your application is only a few pages, it is probably OK, but things can get out of control quickly. Personally I'd rather have one proc per object type and then hit the database multiple times (once for each object type) in order to maximize maintainability. This is where an ORM shines because a good one will generate Sql that will get you exactly what you want with one call in most cases.

A: If you are not interested in updating or deleting the records you fetched from database, I would suggest using DataReader. Basically DataSet internally uses multiple Datareaders, so DataReader should give you good performance advantage.

A: In almost every situation DataReaders are the best solution for reading from a database.  DataReaders are faster and require less memory than DataTables or DataSets.
Also, DataSets can often lead to situations in which the OO model is broken.  It's not very object oriented to be passing around relational data/schemata instead of objects that know how to manipulate that data.
So, for extensibility, scalability, modularity, and performance reasons, always use DataReaders if you consider yourself a Real Programmer™ ;)
Check the links for facts and discussion about the two in practice and theory.

A: Irrespective of whether you're fetching a single result-set or multiple result-sets, the consensus seems to be to use a DataReader instead of a DataSet.
In regards to whether you should ever bother with multiple result-sets, the wisdom is that you shouldn't, but I can conceive of a reasonable class of exceptions to that rule: (tightly) related result-sets. You certainly don't want to add a query to return the same set of choices for a drop-down list that's repeated on hundreds or even dozens of pages in your app, but several sets narrowly-used may be sensibly combined. As an example, I'm currently creating a page to display several sets of 'discrepancies' for a batch of ETL data. None of those queries are likely to be used elsewhere, so it would be convenient to encapsulate them as a single 'get discrepancies' sproc. On the other hand, the better performance of doing so may be insignificant compared to working-around the natural one-sproc-one-result-set architecture of your ORM or hand-rolled data-access code.

A: I have gone to a method that uses DataReaders for all calls, I have noticed a marked performance impovement, especially in cases when I am loading drop down lists, and other simple items like that.
Personally with multiple drop downs, I typically go to pullling individual chunks of data to get it, rather than say a stored procedure that returns 5 result sets.

A: Take a look into the TableAdapters that are available with .NET 2.0 and up. What they do is give you the strength of a strongly-typed DataTable and allow you to map a Fill method to it that will use a DataReader to load it up. Your fill method can be existing stored procedures, your own AdHoc SQL, or even let the wizard generate the AdHod or Stored Procedure for you.
You can find this by starting up a new XSD DataSet object within your project. For tables that are used for more than just lookup, you can also map insert/update/delete methods to the TableAdapter.


text:
Q: Am I using upstart correctly? I'm trying to write a startup script for my Ubuntu 12.04 desktop that pings my Netgear router every 30 seconds (this is necessary as a nasty workaround for a separate problem I'm having). I read this tutorial here, and it seems that I could accomplish this with a simple keep-alive.conf script:
script
    ping -i 30 192.168.1.1
end script

If that's correct, then I assume I just need to save this script to /etc/init.d/keep-alive.conf?
I'm also not seeing how I tie the execution of this script to a "startup" event...
Thanks in advance for help on placing the script, and connecting to startup events!

A: Salem's comment is correct. Upstart has job configurations at /etc/init. start on started network-manager is also a reasonable choice.
You might also need to put respawn stanza in case ping exits for some reason. Adding stop on stopping network-manager might also be reasonable so ping will exit at shutdown.
Complete script might looks like this:
start on started network-manager
stop on stopping network-manager
respawn
exec ping -i 30 192.168.1.1

and would be placed at /etc/init/keep-alive.conf.


text:
Q: Alternative to private setters in Automatic properties If you're not supposed to use private setters for automatic properties (bad practice) then how can I set it privately from within the class and still expose it with just a get to the public? (lets say I want to set it at the constructor level but still allow it to be public by get)?
example class:
public class Car
{
    //set the property via constructor
    public SomeClass(LicensePlate license)
    {
         License = license
    }

    public LicensePlate License{get; private set;} // bad practice
}

A: You convert the property to one with a backing field and no setter.
public class Car
{
    LicensePlate _license;

    public Car(LicensePlate license)
    {
        _license = license;
    }

    public LicensePlate License
    {
        get { return _license; }
    }
}


text:
Q: Integrating QT with CMAKE in Mac OS I am trying to integrate my QT project to my CLION project.
In this case I am having problems with the CMAKE and QT integration.
The content of my CmakeList.txt is:
    cmake_minimum_required(VERSION 3.12)
project(BD2_PROYECTO_1)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_PREFIX_PATH "/Users/jonathanprieto/Qt5.13.0/5.13.0/")

find_package(Qt5Widgets REQUIRED)

set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTORCC ON)

add_executable(BD2_PROYECTO_1 parser.cpp parser.h main.cpp statichashing.cpp statichashing.h randomfile.cpp randomfile.h record.cpp record.h transactions.cpp transactions.h ui/input.cpp ui/input.h ui/ui_dialog.h ui/mainwindow.h ui/mainwindow.cpp ui/mainwindow.ui ui/ui_input.ui ui/input.h ui/dialog.ui)
target_link_libraries(helloworld Qt5::Widgets)

But I am getting the following error:
CMake Error at CMakeLists.txt:8 (find_package):
  By not providing "FindQt5Widgets.cmake" in CMAKE_MODULE_PATH this project
  has asked CMake to find a package configuration file provided by
  "Qt5Widgets", but CMake did not find one.

  Could not find a package configuration file provided by "Qt5Widgets" with
  any of the following names:

    Qt5WidgetsConfig.cmake
    qt5widgets-config.cmake

  Add the installation prefix of "Qt5Widgets" to CMAKE_PREFIX_PATH or set
  "Qt5Widgets_DIR" to a directory containing one of the above files.  If
  "Qt5Widgets" provides a separate development package or SDK, be sure it has
  been installed.

Could someone help me?
Thank you

A: after some tries, I found the solution to my problem.
So I am posting my CMakeList.txt code in case you have the same problem.
cmake_minimum_required(VERSION 3.12)
project(BD2_PROYECTO_1)

set(CMAKE_CXX_STANDARD 17)
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_PREFIX_PATH "/Users/jonathanprieto/Qt5.13.0/5.13.0/clang_64/lib/cmake")

find_package(Qt5 COMPONENTS Widgets REQUIRED)

set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTOUIC ON)
set(CMAKE_AUTORCC ON)

add_executable(BD2_PROYECTO_1 parser.cpp parser.h main.cpp statichashing.cpp statichashing.h randomfile.cpp randomfile.h record.cpp record.h transactions.cpp transactions.h ui/input.cpp ui/input.h ui/ui_dialog.h ui/mainwindow.h ui/mainwindow.cpp ui/mainwindow.ui ui/ui_input.ui ui/input.h ui/dialog.ui ui/input.ui)
target_link_libraries(BD2_PROYECTO_1 Qt5::Widgets)

I hope this will helpful for you.


text:
Q: Weird problem with UInt8 in iPhone (EXC_BAD_ACCESS) I am developing an image processing application by converting image to bitmap. I am manipulating bits in bitmap to get the desired effect.
First time i process an image it gives the correct result on the second try it gives
EXC_BAD_ACCESS
debugger is showing:
dataref outofscope

My code is
CGImageRef img=previewImageView.image.CGImage;
NSLog(@" Image : %@ ", previewImageView);
CFDataRef dataref=CopyImagePixels(img);
CFDataRef dataref1=CopyImagePixels(img);
//UInt8 *data=(UInt8 *)CFDataGetBytePtr(dataref);
//UInt8 *original=(UInt8 *)CFDataGetBytePtr(dataref1);

UInt8 *data=nil;
data=(UInt8 *)CFDataGetBytePtr(dataref);
UInt8 *original=nil;
original=(UInt8 *)CFDataGetBytePtr(dataref1);
//original=data;
int length=CFDataGetLength(dataref);

Please help.........

A: A major cause of EXEC_BAD_ACCESS is from trying to access release objects.
To find out how to troubleshoot this, read this document: DebuggingAutoReleasePool
Even if you don't think you are "releasing auto-released objects", this will apply to you.
This method works extremely well.
In summary, this explains how to use Cocoa's NSZombie debugging class and the command line "malloc_history" tool to find exactly what released object has been accessed in you code.
It is useful to set a breakpoint on objc_exception_throw. That way the debugger should break when you get the EXC_BAD_ACCESS.
Instructions can be found here http://www.cocoadev.com/index.pl?DebuggingTechniques


text:
Q: Heroku dyno crashes with message app[web.1]: /usr/bin/env: ruby.exe: No such file or directory I have a basic rails application which works on my windows 8 desktop (rails_12factor, ruby 1.9.3, rails 4, postgres) - using rails server - I am able to navigate to the application website on my local browser and everything renders fine.
I push the application up to heroku via git push heroku master and everything seems to go fine. The only warning I see is "Removing Gemfile.lock because it was generated on Windows." The process ends with the following message - "Launching... done, v9".
However on running "heroku ps" I get the following:
=== web (1X): bin/rails server -p $PORT -e $RAILS_ENV
web.1: crashed 2013/07/12 00:42:20 (~ 4s ago)
On doing heroku logs --tail, I get the following being repeated in the log files - :
heroku[web.1]: Starting process with command `bin/rails server -p 16041 -e $RAILS_ENV`
app[web.1]: /usr/bin/env: ruby.exe: No such file or directory
heroku[web.1]: Process exited with status 127
heroku[web.1]: State changed from starting to crashed
heroku[web.1]: Error R99 (Platform error) -> Failed to launch the dyno within 10 seconds
heroku[web.1]: Stopping process with SIGKILL

...

heroku[web.1]: Process exited with status 127
heroku[web.1]: Error R99 (Platform error) -> Failed to launch the dyno within 10 seconds

I saw stuff on the web that had me check .gitignore to see if the contents of my local bin folder were getting excluded. They are not. I also saw suggestions to edit the contents of the bin folder and remove the word .exe after ruby - I tried that as well.
EDIT 1: My project has a subfolder bin, with 3 files bundle, rail and rake. These are the only files which start with #!/usr/bin/env ruby. I also edited the first line to read #!/usr/bin/env ruby*.exe* - the error was still seen. Here is the content of each file :
bundle
#!/usr/bin/env ruby
ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__)
load Gem.bin_path('bundler', 'bundle')

rails
#!/usr/bin/env ruby
APP_PATH = File.expand_path('../../config/application',  __FILE__)
require_relative '../config/boot'
require 'rails/commands'

rake
#!/usr/bin/env ruby
require_relative '../config/boot'
require 'rake'
Rake.application.run

A: It seems to me that some script is trying to load ruby.exe via a shebang.
Take a look at yourproject/script/rails, mine looks like this under Mac OS 10.6:
#!/usr/bin/env ruby
# This command will automatically be run when you run "rails" with Rails 3 gems installed from the root of your application.

APP_PATH = File.expand_path('../../config/application',  __FILE__)
require File.expand_path('../../config/boot',  __FILE__)
require 'rails/commands'

A: A guess here: you edited the source files on Windows, so the line endings are wrong. If they are, the Linux loader will try to load "ruby\n".
Run dos2unix on your files, re-commit and re-push to Heroku. It actually happened to me once.


text:
Q: Using PlayerCommandPreprocessEvent and java.lang.reflect I'm currently using PlayerCommandPreprocessEvent.
I use syntax like this:
@EventHandler(priority = EventPriority.HIGHEST)
public void PlayerCommandPreprocess(PlayerCommandPreprocessEvent event){
    String cmd;
    String args;
    if(event.getMessage().indexOf(" ") == -1){
        cmd = event.getMessage().substring(1);
        args = "";
        getLogger().info(String.format("%s used '%s'",event.getPlayer().getDisplayName(), cmd));
    }else{
        cmd = event.getMessage().substring(0, event.getMessage().indexOf(" ")).substring(1);
        args = event.getMessage().substring(event.getMessage().indexOf(" ")+1);
        getLogger().info(String.format("%s used '%s' with args '%s'",event.getPlayer().getDisplayName(), cmd, args));
    }

    switch(cmd){
        case "serverinfo":
            event.getPlayer().sendMessage("This server is running some sort of new plugin that is not finished yet.");
            event.setCancelled(true);
            break;
        case "spawn":
            event.getPlayer().sendMessage("So you wanted to teleport to spawn to save time, right?");
            event.getPlayer().sendMessage("This will teach you, cheater!");
            event.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.POISON,1200,1));
            event.setCancelled(true);
            break;
        default:
            event.setCancelled(false);
            break;
    }
}

I would like to use separate methods inside of class PlayerCommands.
As this will be the only plugin used on the server, I want to capture all commands, evaluate whether they have its PlayerCommands.cmd_<cmdname>() and invoke it.
I know this is possible to do via java.lang.reflect but right now I just don't know how to implement it on a Bukkit server.

A: I just used Class.forName() to iterate through the methods and register them.


text:
Q: pthread with intentional mutex passing I have a general question that may be easy to answer, but it might not be.  I'm not sure.  In my code I have four threads running, all working to work their way through a list, each popping a piece of it each time they run.  Below is the code for each thread, where they wait for the mutex to unlock, lock it themselves, do their thing, and then relock the mutex.
My question is this: Is there a way to pass the lock to a specific thread?\
For example: If I had four threads running this code (t1, t2, t3, and t4) and t1 just finished, is there a way that I can guarantee that t1 will pass the lock to t2, and t2 will pass the lock to t3, etc?
void *consumer(void *ptr){
    int i;

    // Print the thread ID
    printf("Consumer TID %lu\n", (unsigned long)gettid());

    // While the list isn't empty
    while (1){
    // Wait for the mutex
    pthread_mutex_lock(&mutex);
        // When you get it...

        // If the list is empty
        if (the_list.empty()){
            // Unlock the mutex
            pthread_mutex_unlock(&mutex);
            break;
        }

        // Otherwise remove an element from the list
        the_list.pop_front();

        // And unlock the mutex
        pthread_mutex_unlock(&mutex);
    }

    return NULL;
}

Thank you!
UPDATE - RANDOM THOUGHT:  I just had a thought.  Could there be four different functions that each took in a specific mutex only released by the previous function?

A: Your problem with the consumer is that it needs to stay ready even if the list gets empty.
I say this because it might be the case that the consumer is up-and-ready before the first producer comes. In that situation the consumer sees an empty list and exits, thus no produced elements will be consumed.
So I would suggest rather
pthread_mutex_lock(&mutex);
while(the_list.empty())
  pthread_cond_wait(&produced, &mutex);
pthread_mutex_unlock(&mutex);

And the producer(s) will signal you the signal pthread_cond_signal(&produced).
I think this also yields an answer to your question: you don't "pass the lock", but signal (and wait for the signal -- if you are interested in the "passing of the lock" you could do it with 3-4 different signals).

As for the locks: the locks are per-data not per-thread. So the lock is usually stored together with the data.
struct threadsafe_data_t {
  data_t data;
  pthread_mutex_t mutex;
  pthread_cond_t modified; // or produced or whatever
};


text:
Q: Can I use lists in Prometheus / Prometheues in Grafana? I am selecting a source / device via up{instance='$mac'} in Grafana from a Prometheus data source.
The Grafana variable $mac is a string representing the host name etc. which I generate depending on the user input from a (Postgre)SQL database.
This works. Now I want to do 2 things:

*

*Use a self set label (e.g. the location of the device instead of its mac address)

*Use a list / array of mac addresses for instance as well another variable for the labels in the legend.

The vectors mentioned on https://prometheus.io/docs/prometheus/latest/querying/basics/ seems to be for the time values only. Basically I am searching something equivalent to IN in SQL.

A: If I understood you correctly you are trying to retrieve from a given metric up some array of values. This is what you do some analogy with IN operator in SQL.
From the docs you can use =~: Select labels that regex-match the provided string. For instance, the query below uses it here.
up{job=~"(prometheus|alertmanager)"}

or you can use the analog of NOT IN: !~: Select labels that do not regex-match the provided string.
up{job!~"(prometheus)"}

Then I think you can replace the values with your $mac variables on Grafana.


text:
Q: Бит детектор звука с системы (py) и его обработка Как получить воспроизводящийся в системе звук и при обнаружении ~бита~ вызвать функцию? Python.
Как итог должна получиться пульсация подсветки в такт музыке на компьютере. С пульсацией проблем нет, но с получением звука и его спектра проблемы