text:
Q: Loop through elements by class name, click any element within the array, but only affect the element clicked? I am working on a WordPress site and I have a snippet of html that iterates with repeating classes.
I am attempting to create a click function but only affect the element that is clicked. All in JavaScript.
As of right now my function is affecting all elements with the class name. Test code can be found at my CodePen or below.
I can accomplish this without nested loops as seen here. So my assumption is the problem lies within the second forEach loop. I would appreciate any light on the matter.
Thank you in advance.

/**
 *Constructors
 **/
const carousel = document.getElementsByClassName("carousel");
const btns = document.getElementsByClassName("btns");

/**
 *Execute
 **/

Array.from(btns).forEach((i) => {
  i.addEventListener("click", (e) => {
    Array.from(carousel).forEach((n) => {
      if (i.classList.contains("slide-left")) {
        n.scrollLeft -= 20;
      } else if (i.classList.contains("slide-right")) {
        n.scrollLeft += 20;
      } else {
        alert("ut oh");
      }
    });
  });
});
/*
**Utilities
*/

/*containers*/

.feed-container {
  position: absolute;
  height: 200px;
  width: 100%;
  display: grid;
  grid-template-columns: 1;
  grid-template-rows: 1;
}

.carousel {
  grid-row: 1;
  grid-column: 1/5;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-template-rows: 1;
  grid-gap: 15px;
  align-self: center;
  border: 1px solid #ccc;
  overflow-x: scroll;
  overflow-y: hidden;
}

/*div-buttons*/

div[class*="slide-"] {
  /*opacity: 0;*/
  position: sticky;
  grid-row: 1;
  z-index: 5;
  place-self: center;
  transition: 0.5s;
  padding: 15px;
}

.slide-left {
  grid-column: 1;
}

.slide-right {
  grid-column: 4;
}

/*items*/

div[class*="item-"] {
  grid-row: 1;
  width: 400px;
  height: 200px;
}

.item-1 {
  background: blue;
}

.item-2 {
  background: red;
}

.item-3 {
  background: grey;
}

.item-4 {
  background: yellow;
}

/*scrollbar*/

::-webkit-scrollbar {
  display: none;
}

/*chevrons*/

[class*="chevron-"] {
  box-sizing: border-box;
  position: relative;
  display: block;
  transform: scale(var(--ggs, 1));
  width: 22px;
  height: 22px;
  border: 2px solid transparent;
  border-radius: 25px;
}

[class*="chevron-"]::after {
  content: "";
  display: block;
  box-sizing: border-box;
  position: absolute;
  width: 40px;
  height: 40px;
  border-bottom: 8px solid;
  border-left: 8px solid;
  bottom: 0;
}

.chevron-left::after {
  transform: rotate(45deg);
  left: 15px;
}

.chevron-right::after {
  transform: rotate(-135deg);
  right: 15px;
}

/*
**Exceptions
*/

.btns:hover {
  cursor: pointer;
}

.opaque {
  opacity: 1 !important;
}

.show {
  display: block;
}

Header

Header

A: It's because you're getting all the elements with class name carousel and then looping through them with each click.
   const carousel = document.getElementsByClassName("carousel");

Instead what you need to do is get the carousels only under the button's parent when you trigger the click event
eg something like this:
Array.from(btns).forEach((i) => {
    i.addEventListener("click", (e) => {
        const targetElement = e?.target || e?.srcElement;
        const parent = targetElement.parentElement();
        const carousel = Array.from(parent.getElementsByClassName("carousel"));

        carousel.forEach((n) => {
            if (i.classList.contains("slide-left")) {
                n.scrollLeft -= 20;
            } else if (i.classList.contains("slide-right")) {
                n.scrollLeft += 20;
            } else {
                alert("ut oh");
            }
        });
    });
});

A: I took a look at the following as recommend and it seems to do the trick.

*

*I created a variable that calls the parentNode "forEach()" button clicked. Oppose to looping through each element.

Working example, codePen

const carousel = document.querySelectorAll(".carousel");
const btns = document.querySelectorAll(".btns");

 btns.forEach((i) => {
  i.addEventListener("click", () => {
    var x = i.parentNode;
    var y = Array.from(x.querySelectorAll(".carousel"));
    y.forEach((n) => {
      if (i.classList.contains("slide-left")) {
        n.scrollLeft -= 20;
      } else {
        n.scrollLeft += 20;
      }
    });
  });
});


text:
Q: Hazelcast Multimap performance I'm using Hazelcast Multimap client in Python. In my case, I have to update thousands of key-value at the same time. I tried to put multimap value in the while loop but it took more time to update the values (around 30 - 40 seconds to complete). How to improve performance of put data?
multi_map = client.get_multi_map('test').blocking()
keys = list(range(1, 20000))
while(len(keys)>0):
    multi_map.put(keys.pop(),"Test Data")

A: The best way to achieve that would be to use put_all method, but it is not implemented in the Python client yet. I have created an issue for it, and we will try to have it in the future.
For now, you might achieve a better put performance by making non-blocking requests in batches.
multi_map = client.get_multi_map("test")  # get a non-blocking multimap

max_size = 256  # adjust the parallelism level according to your application
futures = []

for i in range(20000):
    if i % max_size == 0:
        while futures:
            # Clear the in-flight invocations
            futures.pop().result()

    future = multi_map.put(i, "Test Data")
    futures.append(future)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Monitoring Power on Dell Cluster using SNMP I have to monitor/collect Power Values of a dell cluster remotely using SNMP . I have very little experience regarding this. Could anybody guide me through , step by step on how to collect or maybe get a logfile of power values from the dell cluster at an interval of say 1 second ?
EDIT : OK, I learnt that , to get power values , we have to submit the appropriate set of OIDs with SNMP, to be able to access power values.
But any pointers on  what the OID for accessing Power values in a cluster are ? I believe it is manufacture dependent ?

A: If you install the Dell Open Manage Server Administrator (Dell Linux OMSA Repo) it includes an SNMP agentX module that the net-snmp daemon and allow you to query all of the Dell specific vendor information. You can get all the MIBs from Dell which will enable you to translate the numeric OIDs to human-readable text that can assist you in easily identifying the ones you're looking for as well as what the values returned mean.
This information can then be monitored by any SNMP-enabled system like Cacti, Nagios, etc to provide trending, tracking and alert notifications.

A: You can use a monitoring system like Cacti, Zenoss, Zabbix (there are many others) to make the hard work to you. On most of them all you would need is to learn how to use the data they gather to provide you with graphs.
The other solution is using snmpwalk, snmpget and other net-snmp tools to make a shell script and run it with cron from time to time to get data and log.
The advantage of tools like the ones I first mentioned is that they already do the hard work for you, but they can be a little too much for small setups, in those cases the script may be better.
Remember that you will need a Read-Only community (SNMP v2) to get data from each of the members of the cluster, and that you will have to decode exactly what value snmp is getting that you need (the snmp values sometimes have strange names, worse yet when it's an unknown MIB).


text:
Q: Loading images from a URL into a UITableViewCell's UIImageView I have the following code: (Note: newsImageURL is an NSArray)
NSString *imagesURL = @"http://aud.edu/images/newsimage01.png,http://aud.edu/images/newsimage04.png,http://aud.edu/images/newsimage02.png,http://aud.edu/images/newsimage03.png,http://aud.edu/images/newsimage01.png,http://aud.edu/images/newsimage04.png,http://aud.edu/images/newsimage01.png,http://aud.edu/images/newsimage04.png,http://aud.edu/images/newsimage01.png,http://aud.edu/images/newsimage04.png,";
newsImageURL = [[NSArray alloc] initWithArray:[AllNewsHeadLine componentsSeparatedByString:@","]];

I am trying to load these images into a cell using the code below:
NSData* imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString: [newsImageURL objectAtIndex:indexPath.row]]];
cell.image = [UIImage imageWithData:imageData];

The image loads fine when I use this line instead:
cell.image = [UIImage imageNamed:@"imagename.png"];

What am I doing wrong?

A: You should use an existing framework which supports caching, default place holders and lazy loading of images.
https://github.com/rs/SDWebImage is a good and simple framework
#import "UIImageView+WebCache.h"

...

- (UITableViewCell *)tableView:(UITableView *)tableView
         cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *MyIdentifier = @"MyIdentifier";

    UITableViewCell *cell =
        [tableView dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:MyIdentifier] autorelease];
    }

    // Here we use the new provided setImageWithURL: method to load the web image
    [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://aud.edu/images/newsimage01.png,http://aud.edu/images/newsimage04.png"]
                   placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

    cell.textLabel.text = @"My Text";
    return cell;
}

A: You can load data this way:
NSData *data = [NSData dataWithContentsOfURL: [NSURL URLWithString: [newsImageURL objectAtIndex:indexPath.row]]];

And you can instantiate the array of URLs this way too:
NSArray *newsImageURL = [imagesURL componentsSeparatedByString:@","];

However, if someone scrolls around on the table a great deal, you may end up loading the images many times over as the cells are recycled.

A: Maybe you can have a try https://github.com/SpringOx/ALImageView.git.It is much simpler than SDWebImage.You only need two source files(ALImageView.h/ALImageView.m).You can reuse the image view to reload different urls in a tableview cell.

*

*Support local and memory cache;

*Support place holders;

*Support tap touch(target-action);

*Support corner for the image view;

A: You Can Easily load all the images with the Help of Following code ,Details Array is a Main Array
Details Array :-  {
        "item_code" = 709;
        "item_desc" = Qweqweqwe;
        "item_name" = AQA;
        "item_photo" = "http://toshaya.com/webapp/snap&sell/api/img_items/709.png";
        "item_price" = "0.00";
        "item_till" = "20-25";
        "item_type" = Orange;
        latitude = "";
        longitude = "";
    }

With the Help of Following Code Retrieve The Photo-URL into String
 NSString * result = [[DetailArray objectAtIndex:indexPath.row]objectForKey:@"item_photo"]; //componentsJoinedByString:@""];

 NSLog(@"%@",result);

NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:result]];
cell.icon.image = [UIImage imageWithData:imageData];


text:
Q: showing a different component on state change and for loop React js I am getting started with react js, and I am facing 2 problems.
1) I am trying to show a table which is in a different class, by clicking show button , a table should show up. The problem is that, the table doesnt show up even if the state is true for showing the table.
2) In the table I am passing an array with information like this
Object {1: Object, 2: Object, 3: Object, 4: Object, 5: Object, 6: Object}

1 capital_payment :"100",
    currency: "2"
    dudedate : "2017-08-20"

But I am not sure how to use a for loop and render those information. I am using a console.log to see whats inside but my code doesnt even go till showing the new class to show the table.
Here are the codes.
var Heading = React.createClass({
  getInitialState: function() {
      return {
        data : [],
         amount : 1000,
         firstMonth : 0,
         showtable : false <--------- HERE IS THE SHOW TABLE STATE
      };
  },
    showTable : function(){
      console.log('I am here');
      this.setState({showtable : !this.state.showtable}); <----CHANGING STATE HERE
      console.log(this.state.showtable);
    },
    render : function(){
      var amount = this.state.amount;
      var firstMonth = this.state.firstMonth;
      return(

                How much {amount}
                <input type="text" className="form-control" placeholder="Amount" value={amount} onChange={this.handleChange} />

                <button type="submit" className="btn btn-success" onClick={this.loadCommentsFromServer} >Submit</button>
                <button type="submit" className="btn btn-success" onClick = {this.showTable} > Show table </button>

                { this.state.showtable ? <tableView data={this.state.data}/> : null }

      );
    }
});
// HERE IS THE TABLEVIEW, AND I HAVE NO CLUE HOW TO DO A FOR LOOP TO RENDER INFORMATION TO THE TABLE
var tableView = React.createClass({
    render: function() {
      console.log(this.props.data);
        return (

                amount
                duedate
                currency

              {this.props.data.map(function(info) {
                return (

                    {info.capital_payment},
                    {info.currency},
                    {info.duedate}

                  );
                })}

        );
    }
});

ReactDOM.render(

    <Heading
    name="React JS"
    >
    </Heading>
    <tableView />

, document.getElementById('reactBinding'));

A: When you create a react component with small letters starting, they are treated as HTML elements, your component will not get rendered in that case, so its a rule that all React components must starts with a upper case letter, so always use Upper Case.
instead of tableview use TableView.
One more thing data that you pasted in ques, showed that your data is not an array, its an object with keys 1, 2, 3, 4, 5, 6:
Object {1: Object, 2: Object, 3: Object, 4: Object, 5: Object, 6: Object}
To use map it should be like this:
[{}, {}, {}, {}...]
or if you data is like this only then you need to use map on the keys of the object, like this:
Object.keys(this.props.data).map((key,i)=>{
     console.log(this.props.data[key])
})

When you use Object.keys() it will return an array of all the keys: [1,2,3,4,5,6].
After that you can use map on that.
Check the working code with data as an object:

var Heading = React.createClass({
  getInitialState: function() {
      return {
        data : {1: {a:1,b:1,c:1}, 2: {a:2,b:2,c:2}, 3:{a:3,b:3,c:3}},
         amount : 1000,
         firstMonth : 0,
         showtable : false
      };
  },
    showTable : function(){
      this.setState({showtable : !this.state.showtable});
    },
    render : function(){
      var amount = this.state.amount;
      var firstMonth = this.state.firstMonth;
      return(

                How much {amount}
                <input type="text" className="form-control" placeholder="Amount" value={amount} onChange={this.handleChange} />

                <button type="submit" className="btn btn-success" onClick={this.loadCommentsFromServer} >Submit</button>
                <button type="submit" className="btn btn-success" onClick = {this.showTable} > Show table </button>

                { this.state.showtable ? <TableView data={this.state.data}/> : null }

      );
    }
});

var TableView = React.createClass({
    render: function() {
      let data = this.props.data;
        return (

                amount
                duedate
                currency

              {Object.keys(data).map((key) =>                            {
                return (

                     a: {data[key].a}
                     b: {data[key].b}
                     c: {data[key].c}

                  );
                })}

        );
    }
});

ReactDOM.render(

    <Heading
    name="React JS"
    >
    </Heading>

, document.getElementById('app'));

How to use Object.keys and its meaning:
When we use Object.keys it returns an array that contains all the keys of that object. Run this snippet and check the output:

obj = {a:1 , b:2 , c:3 , d:4};

keys = Object.keys(obj);

console.log('keys', keys);

values = Object.values(obj);

console.log('values', values);


text:
Q: Remove scroll bar while keeping scroll functionality I need to remove the scroll bar in my site.
But when I use overflow: hidden my page won't scroll anymore. Is there any other solution?
I couldn't find one with Google.

A: I have tried to use overflow:hidden; but it does exactly what you said.. So you should try to add this to your css.
body::-webkit-scrollbar{
    display: none;
}

A: elementary than you can hide an element on the page is to assign display: none; or visability: hidden;
Even invisible elements take up space on the page. Use the "display" property to create invisible elements that do not take up space!

A: I don't think there is a cross-browser solution to hide the scrollbar while preserving scroll functionality.
Although, you can easily simulate this behaviour, with help from a full-body wrapper that takes on the dimensions of the body but is padded on the right to hide the scrollbar.
Yes, you must give the overflow:hidden property to body, but your wrapper becomes your new scrollable element. Something like the following should work for you:
HTML

Lots of text.....

CSS
html{
    height:100%;
}
body{
    margin:0;
    overflow:hidden;
    height:100%;
}
#wrapper{
    width:100%;
    height:100%;
    overflow:auto;
    padding-right:20px;
}

JSFiddle

A: Try :
Overflow : auto

if scroll is required, it will display automatically.
You can also try
Overflow-X : auto
Overflow-Y : auto

Let me know if this fixes your problem.

A: If you need to remove the scrollbar you can use these property. please check and share if works for you. check the DEMO.
#container{
    width:100%;
    height:100%;
    overflow:auto;
    position:fixed;
    padding-right:20px; /*will give a Illusion of removing the scrollbar because browser scrollbar width is 20px*/
}


text:
Q: Grab DB values and display For Each - Codeigniter Having a bit of trouble getting my For Each function to display all the values from a DB into a view. Where am I going wrong? Not a back-end pro, nor did I write it. Database table is extremely simple, one column named id. I want to display each of the rows in my for each.
I have a custom MY_Controller.php file and in the _construct I have this, which fills in variables globally across the site.
$this->country_zones = $this->Studios_model->get_studios();

Model:
function get_studios()
{
    //this will alphabetize them
    $this->db->order_by('id', 'ASC');

    $query  = $this->db->get('gc_studio_zones');

    foreach ($query->result() as $row)
    {
        $countries = $row->id;
    }
    return $countries;
}

In my view:
<?php foreach($this->$country_zones as $country):?>

<?php echo $country['countries']->id;?>

<?php endforeach;?>

Error:
Cannot access empty property...etc

A: I think you have a typo in your view regarding your loop variable, it should be this->country_zones:
<?php foreach($this->country_zones as $country):?>

<?php echo $country->id;?>

<?php endforeach;?>

Besides, your Model isn't returning an array, but only the last id. You need to push the values to your result array:
function get_studios()
{
    //this will alphabetize them
    $this->db->order_by('id', 'ASC');

    $query  = $this->db->get('gc_studio_zones');

    $countries = array();
    foreach ($query->result() as $row) {
        $countries[] = $row;
    }
    return $countries;
}


text:
Q: Z Score Values Used and Interpretation I have been working on a time series-like data set from using calcium indicators (waveform data). A script I was given transforms the voltages (x values) into Z-scores. However, the mean and standard deviation used in calculating these scores are from a baseline period before the trial, which makes it look something like this:
$$
x_{trial} - \mu_{baseline} \over \sigma_{baseline}
$$
I know that the "x - mu" represents the difference between voltages during the trial and mean voltages at baseline, but how would using a baseline standard deviation affect the interpretation? Similarly, how would using a mu value from the trial and sigma value from the baseline period be interpreted?
Thanks in advance!

A: This can be interpreted from the hypothesis testing point of view. The null hypothesis is to assume that your x follows the same  normal distribution as your baseline (given $\mu$ and $\sigma$). The z-score tells how many standard deviations your observation deviates from the assumed mean. From it you can estimate the probability of observing such a great deviation if your null assumption was true. However, you may also use z-score just to scale the result and see if you observation is like baseline (near 0 or maybe in range [-2,2]) or exceptional.
It is hard to see what you could test if you assumed the null distribution with the observed mean but the baseline standard deviation.


text:
Q: Drop-down TabControl I've been trying to create a custom skin/template for a TabControl in WPF.
I want the tabs to be displayed in a ComboBox. When you select the item from the ComboBox, I want the content area of the tab control to display the TabItem contents.
Here's an image showing what I'm looking for:

I could do this using some sort of master-detail setup with data objects and templates, but the problem is I want to set up the controls using the TabControl XAML format, like this:
<TabControl Style="{DynamicResource ComboTabControlStyle}">
   <TabItem Header="TabItem1">
      <TextBlock Text="TabItem1 Content!" FontSize="18.667" HorizontalAlignment="Center" VerticalAlignment="Center"/>
   </TabItem>
   <TabItem Header="TabItem2">
      <TextBlock Text="TabItem2 Content!" FontSize="18.667" HorizontalAlignment="Center" VerticalAlignment="Center"/>
   </TabItem>
   <TabItem Header="TabItem3">
      <TextBlock Text="TabItem3 Content!" FontSize="18.667" HorizontalAlignment="Center" VerticalAlignment="Center"/>
   </TabItem>
</TabControl>

Any thoughts or suggestions?
It is very easy to change the layout of the tab items using a different Panel, but a ComboBox is an ItemsControl, not a Panel.
I tried putting the ComboBox in the TabControl template and binding the ItemsSource of the ComboBox to the TabControl.Items property, but it didn't seem to work correctly.
I also tried creating a custom panel that only shows one "selected" item at a time and shows all of the items in a drop-down when you click on it (basically a "ComboBox" panel). I ran into trouble because visuals can only be in one place in the visual tree. So putting the children of the panel into a popup caused an exception to be thrown.
Anybody have any other ideas?
Thanks for the help!

A: It's surprisingly difficult to do what you're trying to do.  This comes very close:
<DockPanel>
    <ComboBox x:Name="ItemSelector" DockPanel.Dock="Top">
        <ComboBox.ItemTemplate>
            <DataTemplate DataType="{x:Type TabItem}">
                <TextBlock Text="{Binding Header}"/>
            </DataTemplate>
        </ComboBox.ItemTemplate>
        <TabItem Header="TabItem1">
            <TextBlock Text="TabItem1 Content!" FontSize="18.667" HorizontalAlignment="Center" VerticalAlignment="Center"/>
        </TabItem>
        <TabItem Header="TabItem2">
            <TextBlock Text="TabItem2 Content!" FontSize="18.667" HorizontalAlignment="Center" VerticalAlignment="Center"/>
        </TabItem>
        <TabItem Header="TabItem3">
            <TextBlock Text="TabItem3 Content!" FontSize="18.667" HorizontalAlignment="Center" VerticalAlignment="Center"/>
        </TabItem>
    </ComboBox>
    <ContentPresenter Content="{Binding SelectedItem.Content, ElementName=ItemSelector}" DockPanel.Dock="Top"/>
    <TextBlock/>
</DockPanel>

Where it breaks down, oddly, is displaying the selected item in the ComboBox:  the ItemTemplate is ignored when rendering the item, so the selection box contains a TabItem.  To fix this, you have to subclass ComboBox and implement a read/write SelectionBoxItemTemplate dependency property, because, for some reason that I'm sure is not as stupid as it seems to me at this moment, that property's read-only.

A: Create a new class, inherit from panel, put a combo box inside, do a lot of parent binding, and use it. it'll do the trick.
You must use custom class to write the tabs as they are regular tab items.

A: I found a solution.
I created a custom Control class (MasterDetailControl).
This class has two template parts:
[TemplatePart(Name = "PART_MasterSelector", Type = typeof(Selector))]
[TemplatePart(Name = "PART_DetailPresenter", Type = typeof(ContentPresenter))]

The control has an items dependency property:
public IList Items { ... }

I added a helper class:
[ContentProperty("Detail")]
public class MasterDetail
{
   public object Master { get; set; }
   public object Detail { get; set; }
}

Items that are placed in the Items DP are processed by the MasterDetailControl. If they are of type MasterDetail, the master is added to the selector items list. For other child item types, a new MasterDetail object is created with the object assigned to the master and detail fields. A separate list maintains all of the generated MasterDetail objects with indexes that correspond to those in the Selector control.
When the SelectionChanged event fires on the Selector object, I set the ContentPresenter's Content property to the Detail field of the item corresponding to the selected master object.
If anyone wants more details, feel free to comment.
In the end, I can now use this control with a simple control template specifying any selector object (ListBox, ComboBox, etc) and a ContentPresenter.


text:
Q: Get selected radio button in kotlin I have following code and I this error:

Code
xml file
<RadioGroup
        android:id="@+id/paymentMethod"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="10dp"
        android:layout_marginTop="55dp">

        <RadioButton
            android:id="@+id/Cash"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:checked="true"
            android:text="@string/cash" />

        <RadioButton
            android:id="@+id/Online"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="@string/online" />
</RadioGroup>

fragment
val payment_method: RadioButton = root.findViewById(R.id.paymentMethod)
val weight: EditText = root.findViewById(R.id.kilo)
val item: EditText = root.findViewById(R.id.item)
val updateButton: Button = root.findViewById(R.id.update_btn)

updateButton.setOnClickListener{
    // val mPayment = payment_method.text.toString().trim()

    val selectedRadioButtonId: Int = payment_method.checkedRadioButtonId
                                                    ^^^^^^^^^^^^^^^^^^^^
    if (selectedRadioButtonId != -1) {
        selectedRadioButton = root.findViewById(selectedRadioButtonId)
        val string: String = selectedRadioButton.text.toString()

        val mPayment = string.trim()
        val mWeight = weight.text.toString().trim()
        val mItem = item.text.toString().trim()

        Log.d("test1:", mPayment + "," + mWeight + "," + mItem)

        if(mWeight.isNotEmpty()){
            UpdateOrder(mPayment.toString(), mWeight, mItem)
        } else {
            payment_method.error = "Payment is required."
            weight.error = "Weight is required."
        }
    } else {
        Toast.makeText(context, "Select Payment.", Toast.LENGTH_SHORT).show()
    }
}

A: Hey you are using RadioGroup for paymentMethod and casting it to RadioButton in your code which does not have the method you are trying to use,
val payment_method: RadioGroup = root.findViewById(R.id.paymentMethod)


text:
Q: How can I store a Backslash character in a String variable? I'm trying to escape the character \ in a String variable.
I've tried all escape methods I know of for special characters, but nothing works:
-use the  backslash \
-use the \Q and \E
-use the Pattern.quote(String) Method
Every time I try it my IDE Eclipse says that I need to finish the String with " quotes (I've already put those quotes, but I think that means java stills recognize my \ character as a special code)
Any help to escape that \ character?


text:
Q: How to access the serialized data in PHP file in the following scenario? How to access the serialized data in a PHP file in following situation?
The code and the serialized data is as follows:
$(document).ready(function() { $(document).on('click', '#delete_url', function (e) {
e.preventDefault();

var items = new Array();
$("input:checked:not(#ckbCheckAll)").each(function() {
  items.push($(this).val());
});

var str = $("#user_filter").serialize();

$.ajax({
  type: "POST",
  url: "manage_users.php?op=delete_bulk_users&items="+items,
  data: str,
  dataType: 'json',
  success: function(data) {
    //var message       = data.success_message;
    var redirect_link = data.href;
    alert(redirect_link);
      window.location.href = redirect_link;
  }
});

});
    });
The data I'm getting in after serialize in str is as follows:
op=group_filter&page=1&from_date=11%2F10%2F2000&social_login=&to_date=11%2F10%2F2013&login_criteria=all&user_name=&user_state=&user_email_id=&user_city=

Now the PHP file(manage_users.php) is as follows:
/*The code is actually one of the switch casees*/
prepare_request();
  $request = empty( $_GET ) ? $_POST : $_GET ;
$op         = $request['op'];
switch( $op ) {
case "delete_bulk_users":
print_r($request);/*For printing the received array of values after form submission
                    Here I'm not getting serialized data */
}

Thanks in advance.

A: The serialize function is intended to be used to create a query string for a URL from a collection of inputs (or an entire form), and will out of necessity encode characters such as / (which denotes a directory in a URL). There's no way to tell .serialize() to convert to the "proper" format because it already is.
If you're using the result of .serialize() as part of an AJAX request it's fine to do that like so:
$.ajax({
    url: 'yourpage.php',
    data: str, // the string returned by calling .serialize()
    ... // other options go here
}).done(function(response) {
    // do something with the response
});

Your server should handle decoding those characters when it receives the request and provide the correct values to you.
If you're using it for something else you could try using the native JavaScript decodeURIComponent function to convert those encoded characters back, like so:
str = decodeURIComponent(str);

Note that calling decodeURIComponent and then trying to use it for an AJAX request won't work.
For more information on URI encoding take a read through the MDN entry for encodeURIComponent.


text:
Q: PHP - List of Excel files to download from Intranet Site? I have a intranet site running PHP 5 that needs to list a folder containing only Excel files.
Ideally the user needs to be able to input some search criteria (ie date) and the files would be filtered into a list of hyperlinks.  These hyperlinks could then be selected to download the excel file.
What I have so far is:
//get search parameters (from a form)
$s_Date = $_GET['s_Date'];
$s_Shift = $_GET['s_Shift'];
$s_Name = $_GET['s_Name'];

//search folder
foreach(glob("c:\folderA\folderB\*".$s_Date."*".$s_Shift."*".$s_Name."*.*") as     $FileName)
{
    echo basename($FileName);
    echo"Download"."
";
}

This returns list of files but selecting hyperlinks doesn't prompt for download.
How do I get the hyperlink to force a content-type of msexcel?

A: Assuming you are using a PHP script to deliver the file conent, the script needs to set the Content-Type header:
<?
    header('Content-Type: application/excel');
    header('Content-Disposition: attachment;filename=myfile.xls');
    // send file content
?>

Note you can also set the name to use for the file using the Content-Disposition header.
You might also want to consider a more well-formed  tag that points to your download script:
echo 'Download
';

In this example, you need to replace dl.php with your actual script.

A: Also append Content-Length header:

header('Content-Length : ' . filesize('myfile.xls'));

Client would like to know how big file is and how much of it has already been downloaded.


text:
Q: What exactly is iodepth in fio? Is iodepth of fio and queue depth of storage both same? Then, how is it possible to control queue depth with an iodepth parameter from fio command? Will that be creating parallel jobs, but then again there is an option to run jobs in parallel also (will that not be a trivial or conflicting?)
I am struggling to understand how fio is controlling it's workloads (especially about this iodepth). Can someone please explain the iodepth parameter in detail.
UPDATE #1
My question was also asked in the Flexible I/O Tester's forum. This is the answer that I received there.

Hi,

On 28 July 2018 at 14:26, Jeevan Patnaik  wrote:
    Hi,
Is Iodepth of fio and queue depth of storage both same? Then, how is
    it possible to control queue depth with an iodepth parameter from fio

fio iodepth and the depth I/O your OS achieves submitting I/O down to
  storage are linked but most certainly do not have to be the same and
  the relationship is highly dependent on your operating
  system/storage/fio ioengine used/fio parameters. Basically fio submits
  I/O a particular way to your operating system. Depending on how you
  submit your I/O to your operating system it can choose to submit it
  further down in a more optimal/different fashion (e.g. by batching
  requests together, breaking requests that are too big into smaller
  pieces, delaying I/O etc). Additionally and as stated in the HOWTO, iodepth only affects asynchronous ioengines (and note that text
  includes warnings about the need to use direct=1 on Linux).

command? Will that be creating parallel jobs, but then again there is
    an option to run jobs in parallel also (will that not be a trivial or
    conflicting?)

I'm going to give a brief summary but note I'm not trying to cover
  caching/readahead/plugging/block device layers (e.g. RAID/LVM) etc:
A synchronous fio I/O engine submits a single I/O to the OS, waits for
  it to be "acknowledged" as having been received and then sends another
  I/O etc.
If an fio I/O engine is able to submit I/O to the OS in a truly
  asynchronous fashion (see link above) then the key is that it does NOT
  have to wait for earlier I/O to be "acknowledged" before submitting
  new I/O. If the iodepth is only 1 it will have to behave in a fashion
  similar to a synchronous I/O engine. However, let's say a jobs
  specifies an iodepth of 32. In that case up to 32 I/Os to be
  outstanding before fio will choose to wait before submitting any more
  I/O (just what the watermarks are and how much is submitted at a time
  is controlled by the iodepth_batch_* options. This can be more
  efficient and achieve higher throughputs but often comes with a cost
  of higher latency.
fio will not create parallel fio jobs just because of iodepth BUT
  using parallel fio jobs is another way of increasing the amount of
  simultaneous I/O being submitted at any given time (by using different
  threads/processes) and using both on the same device will act in
  tandem (so if you have two fio jobs submitting asynchronous I/O at an
  iodepth of 16 each your OS could be be actually receiving 32 I/Os at
  any given time). There can be reasons for combining the two (e.g. you
  have multiple devices and they are so fast that one CPU can't keep up
  even when submitting I/O asynchronously).

I am struggling to understand how fio is controlling it's workloads
    (especially about this iodepth). Can someone please explain the iodepth
    parameter in detail.

I will note you've also asked this question over on stackexchange
  (What exactly is iodepth in fio?). You may want to link to
  https://www.spinics.net/lists/fio/msg07190.html from there to help
  others who may have a similar question...

A:
will that not be a trivial?

Assume direct IO, as required for iodepth= to work.
A sequential job with iodepth=2 will submit two sequential IO requests at a time.
A sequential job with numjobs=2 will have two threads, each submitting sequential IO.
These are different IO patterns. The latter will generate 2x the bandwidth across the IO bus, even if the physical IO reduces back to 1x due to device caches.  (I suspect the two jobs would tend to remain in lockstep due to device caches, unless you used multiple files and a randomized file_service_type=).  If the IOs are synchronous writes (sync=true), the physical IO would not be reduced at all, unless the device is doing an unusual amount of optimization (perhaps a de-duplicating SSD controller).

A: Per the Linux kernel docs:

.. option:: iodepth=int
Number of I/O units to keep in flight against the file.  Note that
      increasing iodepth beyond 1 will not affect synchronous ioengines (except
      for small degrees when :option:verify_async is in use).  Even async
      engines may impose OS restrictions causing the desired depth not to be
      achieved.  This may happen on Linux when using libaio and not setting
      :option:direct\=1, since buffered I/O is not async on that OS.  Keep an
      eye on the I/O depth distribution in the fio output to verify that the
      achieved depth is as expected. Default: 1.

This tutorial titled: Fio Output Explained had this example:

Fio has an iodepth setting that controls how many IOs it issues to the OS at any given time. This is entirely application-side, meaning it is not the same thing as the device's IO queue. In this case, iodepth was set to 1 so the IO depth was always 1 100% of the time.
    submit    : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, >=64=0.0%
    complete  : 0=0.0%, 4=100.0%, 8=0.0%, 16=0.0%, 32=0.0%, 64=0.0%, >=64=0.0%

submit and complete represent the number of submitted IOs at a time by fio and the number completed at a time. In the case of the thrashing test used to generate this output, the iodepth is at the default value of 1, so 100% of IOs were submitted 1 at a time placing the results in the 1-4 bucket. Basically these only matter if iodepth is greater than 1.


text:
Q: Most Lite-Weight XML Parser with XPath and Wide-char Support I want a lite-weight C++ XML parser/DOM that:

*

*Can take UTF-8 as input, and parse into UTF-16.  Maybe it does this directly (ideal!), or perhaps it provides a hook for the conversion (such as taking a custom stream object that does the conversion before parsing).

*Offers some XPath support.

I've been looking at RapidXML, the Kranf xmlParser, and pugiXML. The first two of those might permit requirement #1 by way of a hook.  The third, pugiXML, supports the #2 requirement.  But none of those three fulfill both requirements.
What is the smallest (free) library that can handle both requirements?

A: I'd really go for TinyXML + TinyXPath... Tiny, fully UTF-8 compilant and zlib/MIT licensed. If you want a more C++'s like interface there's also TinyXML++

A: pugixml has an UNICODE branch. I guess UNICODE will be officially supported in the next version (0.6)


text:
Q: UITableView row order I have a strange behavior my tableView
I make dropdown section on my tableView. It's look like:

but if I reopen my section rows order was ather like this:

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        NSLog(@"CURRENT ROW = %ld", (long)indexPath.row);
        UILabel *titleLable = [[UILabel alloc] initWithFrame:CGRectMake(90, 20, cell.frame.size.width - 90, 20)];
        titleLable.text = [NSString stringWithFormat:@"урок %ld", (long)indexPath.row];
        [cell addSubview:titleLable];
        UILabel *percentLable = [[UILabel alloc] initWithFrame:CGRectMake(cell.frame.size.width - 40, 20, 50, 20)];
        LessonModel *lesson = [self.lessonsArray objectAtIndex:indexPath.section];
        NSArray *childrenArrey = [[NSArray alloc] initWithArray:(NSArray *) lesson.childrenArray];;
        percentLable.text =[NSString stringWithFormat:@"%@ %%", [childrenArrey[indexPath.row] valueForKey:@"percent"]];
        [cell addSubview:percentLable];
    }
}
return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
[self.tableView deselectRowAtIndexPath:indexPath animated:YES];
LessonModel *lesson = [self.lessonsArray objectAtIndex:indexPath.section];
NSArray *childrenArrey = [[NSArray alloc] initWithArray:(NSArray *) lesson.childrenArray];
NSString *uid =  [childrenArrey[indexPath.row] valueForKey:@"id"];
[self makeLessonWithId:uid];
}

- (void)sectionHeaderTapped:(UITapGestureRecognizer *)gestureRecognizer{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:gestureRecognizer.view.tag];
if (indexPath.row == 0) {
    BOOL collapsed  = [[self.arrayForBool objectAtIndex:indexPath.section] boolValue];
    collapsed       = !collapsed;
    [self.arrayForBool replaceObjectAtIndex:indexPath.section withObject:[NSNumber numberWithBool:collapsed]];
    [self updateLabelFrame:gestureRecognizer.view.tag];

    NSRange range   = NSMakeRange(indexPath.section, 1);
    NSIndexSet *sectionToReload = [NSIndexSet indexSetWithIndexesInRange:range];
    [self.tableView reloadSections:sectionToReload withRowAnimation:UITableViewRowAnimationFade];
}
}

A: Try by putting values in else part too:
    if (cell == nil){
          //your code as it is
    }
    else{
          titleLable.text = [NSString stringWithFormat:@"урок %ld", (long)indexPath.row];
          NSArray *childrenArrey = [[NSArray alloc] initWithArray:(NSArray *) lesson.childrenArray];;
          percentLable.text =[NSString stringWithFormat:@"%@ %%", [childrenArrey[indexPath.row] valueForKey:@"percent"]];
    }


text:
Q: Render after getting props I can't see a proper reason for a LitElement WebComponent to be rendered before having its props/attributes available. If the template needs a prop, you are forced to render a second time the component, after the first useless one. Worse than that, if your component looks like:
class MyComp extends LitElement
    static get properties() {
        return {
            myBigProp: {
                type: Object
        }
    render() {
        return html`<p> ${this.myBigProp.nestedProp}</p>`
}

you get an error for accessing nestedProp when myBigProp is undefined. Is there a clean way to avoid rendering twice this component?

A: If you already are able to set the properties you can simply define them in the constructor. Then it should be accessible at the first render.
constructor() {
   super();
   this.myBigProp = {nestedProp:'nested value'}
}

However if you have to wait for them I usually make it clear that the component is loading visually by using an "initialized" property then handling it in the render function.
render() {
   if (!this.initialized) {
      return html`<div class='loading-reserved-zone'></div>`;
   } else {
      return html`<p>${this.myBigProp.nestedProp}</p>`
   }
}

Otherwise, "Optional Chaining Operator" are coming up to javascript in august 2020 which could handle your second scenario or you could technically use this babel plugin if you want to use it earlier.

A: There is a lifecycle callback shouldUpdate. Return false until you want to render the component.
shouldUpdate(changedProps) {
  return this.myBigProp != null;
}


text:
Q: Check if elements in a check list are ticked and send those via email? Intent next = new Intent(Intent.ACTION_SENDTO);
next.setData(Uri.parse("mailto:zuron7@gmail.com"));
next.putExtra(Intent.EXTRA_SUBJECT, "Attendance");
String message = "";
Resources r = getResources();
String name = getPackageName();
int[] ids = new int[3];
for(int i =0; i<3;i++){
    String x = "check"+i;
    ids[i]= r.getIdentifier(x,"id", name);
}
for(int i = 0; i<3;i++){
    CheckBox checkbox = (CheckBox) findViewById(ids[i]);
    if(checkbox.isChecked()){
        message=message+getResources().getString(R.string.Swag1);
    }
}
next.putExtra(Intent.EXTRA_TEXT,message);
if (next.resolveActivity(getPackageManager()) != null)
    startActivity(next);

When I run the app on my phone and hit the button which launches this method, it stops unexpectedly. I'm not really sure where the problem is. I basically want to take attendance for a group of students and send the names of those absent to the coordinator.

A: Maybe this will solve your problem: ACTION_SENDTO for sending an email
Basically you should try to pass your subject and message via the URI in setData.


text:
Q: PHP preg_replace text between two strings I have a string that would have a similar pattern as $string below (pulled from forum posts).
$string = "[quote=\"abc123\":27zslwh3]I don't agree with most of the statements made here.[/quote:27zslwh3] I don't think that is very nice of you.";
$pattern = "/\[quote\=.\*\[\/quote.*\]/";
$replace = "";

$updated_text = preg_replace($pattern,$replace,$string);
echo $updated_text;

I am trying to use preg_replace to remove all the text between the opening and closing [quote] tags and echo the remaining string: "I don't think that is very nice of you." only (from $string above).
The pattern I am using for the regular expression is supposed to look for the beginning of the opening [quote] tag, then search through until it finds the closing [quote] tag and the final ] of the tag.
The above doesn't seem to work properly though and I am not too proficient with reg expressions so am stuck here.  Any help would be appreciated.
.
NOTE: I tried both codes provided by drew010 and bsdnoobz (thanks for the code and explanations)
and it still didn't work.  The issue is that I did not capture the $string text correctly.  It should read as:
$string = '[quote="abc123":27zslwh3]I dont agree with most of the statements made here.

abc123[/quote:27zslwh3]
I dont think that is very nice of you.';

there are html chars for the double quotes and what appears to be either new line or carriage return characters as well which is probably what prevented the regular expressions submitted below not work for me.

A: $string = '[quote="abc123":27zslwh3]I don\'t agree with most of the statements made here.[/quote:27zslwh3] I don\'t think that is very nice of you.';
echo preg_replace('/\[quote.+?\].+?\[\/quote.+?\]/is', '',$string);
// will print: I don't think that is very nice of you.

Note: There are both single quote and double quotes in your input string. This example wraps the input string with single quote, and escape any single quote within the string.

A: Here is a pattern that works also:
$pattern = '/\[quote[^\]]*\].*?\[\/quote[^\]]*\]/is';

It will match formats like what you have, or simply bare quotes like [quote]Text...[/quote]
To break it down:
\[quote[^\]]*\] says match text [quote and any character except ] 0 or more times
\] matches the closing ] on the end of the opening [quote] tag.
.*? matches any character 0 or more times.  The ? in this context makes this match ungreedy (meaning it will stop when it matches the next part of the pattern first, rather than last.
\[\/quote[^\]]*\] then matches [/quote and any character except ] 0 or more times, and finally we consume the closing ]


text:
Q: How to access session from a custom RouteBase in MVC5? I am trying to implement the ability to relatively transparently encrypt ids in ASP.NET MVC5. I have a series of custom HTML helpers that emit encrypted ids, e.g:
http://url/CityDetails/Edit/Vb7B_slYoRdt1cQD5mNum
The html helper stores the key in session scope.
Then, I have a class that implements System.Web.Routing.RouteBase, and the method GetRouteData is supposed to replace the encrypted id with the decrypted id. This works if I hard code the key, but if I store the key in session scope, and try to access it, Session is always null.
public override RouteData GetRouteData(HttpContextBase httpContext){
     //Session is always null
     HttpSessionState session1 = System.Web.HttpContext.Current.Session;
     ...
     return routeData;
}

Is there a way to get to the Session? I am clearly not understanding something about the life cycle here.

A: In short, you can't.
In MVC, HttpContext.Session is not yet available during routing - it is too early in the application's lifecycle.
The first point where session state is available in MVC is during the Controller Creation stage.

See this MSDN article for more information about the MVC lifecycle.
If you line that up with the ASP.NET on IIS 7 Lifecycle documentation you can see that the routing handler gets called at the PostResolveRequestCache event. Session state is first populated at the AcquireRequestState event, and then the controller is instantiated and action executed in the BeginProcessRequest event.

*

*Validate the request, which examines the information sent by the browser and determines whether it contains potentially malicious markup. For more information, see ValidateRequest and Script Exploits Overview.

*Perform URL mapping, if any URLs have been configured in the UrlMappingsSection section of the Web.config file.

*Raise the BeginRequest event.

*Raise the AuthenticateRequest event.

*Raise the PostAuthenticateRequest event.

*Raise the AuthorizeRequest event.

*Raise the PostAuthorizeRequest event.

*Raise the ResolveRequestCache event.

*Raise the PostResolveRequestCache event. (Routing Executed)

*Raise the MapRequestHandler event. An appropriate handler is selected based on the file-name extension of the requested resource. The handler can be a native-code module such as the IIS 7.0 StaticFileModule or a managed-code module such as the PageHandlerFactory class (which handles .aspx files).

*Raise the PostMapRequestHandler event.

*Raise the AcquireRequestState event. (Session State Acquired)

*Raise the PostAcquireRequestState event.

*Raise the PreRequestHandlerExecute event.

*Call the ProcessRequest method (or the asynchronous version IHttpAsyncHandler.BeginProcessRequest) of the appropriate IHttpHandler class for the request. For example, if the request is for a page, the current page instance handles the request. (Controller Creation)

*Raise the PostRequestHandlerExecute event.

*Raise the ReleaseRequestState event.

*Raise the PostReleaseRequestState event.

*Perform response filtering if the Filter property is defined.

*Raise the UpdateRequestCache event.

*Raise the PostUpdateRequestCache event.

*Raise the LogRequest event.

*Raise the PostLogRequest event.

*Raise the EndRequest event.

*Raise the PreSendRequestHeaders event.

*Raise the PreSendRequestContent event.

Do note that it is generally not considered a good practice to use Session state with ASP.NET MVC.


text:
Q: onclick not working on Android Emulator (ionic framework) Steps:
1. ionic start Hello blank

*Add button to the index.html

 <ion-content>
        <button class="button" onclick="javascript:alert('x');">Try Click</button>
</ion-content>

*inside hello dir: ionic run android

*click the 'Try Click' button. Nothing happens.

Info:
Emulator: Android 4.4.2 API 19

A: change it to ng-click and in general it is better to call a function.
You should separate your logic from your views.
example HTML
<div ng-controller="LoginController">
   <ons-button ng-click="yourFunction()">Click Me!</ons-button>
</div>

JS
.controller('SomeController', function () {
   $scope.yourFunction = function () {
      console.log("x is triggered");
      alert('x');
   }

}

A: Use
 <ion-content>
        <button class="button" ng-click="javascript:alert('x');">Try Click</button>
</ion-content>

ng-click instead of onclick..


text:
Q: Make a client to connect to a ftp server I'm trying to do a client in C witch connect to a FTP server, but there is some problems i can't solve, when i launch my client the connexion to the server works then i enter my login ("USER login"), I receive the answer from the server which ask to me my password and when i try to enter it i have this answer : "500 Invalid command: try being more creative". I don't know if I'm doing something wrong with select() function or something else.
Thanks for help.
void    receive_and_send(int sock)
{
   char buffer[1024];
   char buffer2[1024];
   fd_set rfds;
   int retval;
   int nb_recv;
   int nb_read;
   char *cpybuffer;

   memset(buffer, '\0', 1024);
   memset(buffer2, '\0', 1024);
   while (42)
    {
      FD_ZERO(&rfds);
      FD_SET(0, &rfds);
      FD_SET(sock, &rfds);
      if ((retval = select(sock + 1, &rfds, NULL, NULL, NULL)) < 0)
        {
          printf("Error with select\n");
          exit(0);
        }
      if (FD_ISSET(sock, &rfds))
        {
          if ((nb_recv = read(sock, buffer, 1024 - 1)) < 0)
            exit(0);
          if (nb_recv < 1024)
            {
              buffer[nb_recv] = '\0';
              fprintf(stderr, "[%s]", buffer);
              memset(buffer, 0, 1024);
            }
        }
     if (FD_ISSET(0, &rfds))
        {
          nb_read = read(0, buffer2, 1024);
          buffer2[nb_read - 1] = '\r';
          buffer2[nb_read] = '\n';
          buffer2[nb_read + 1] = '\0';
          fprintf(stderr,"buffer2 = %s\n", buffer2);
          cpybuffer = strdup(buffer2);
          write(sock, cpybuffer, nb_read + 2);
          memset(buffer2, '\0', 1024);
          free(cpybuffer);
        }
    }
}`


text:
Q: HTML How to pass two variables on a radio button press? How can I pass two variables on a button press? This may seem basic but I am completely stuck!
I am creating a table that has a radio button on the left side, and when you press it I want to retrieve two values. I am currently retrieving one value but I am missing the other.
Currently I am passing one value onto my onRadioButtonPress function like this:
 html += "

          <input type='radio'
             onclick='onRadioButtonPress(this.value)'
             name='siteChosen'
             value='"+siteIDArray[i]+"'>
           	";

And I am calling the function like this:
//function for on radio button press
   function onRadioButtonPress(val){

      //blah blah blah
 }

Which is working great, but how do I add a second value of

usagePlanArray[i]

to my on onClick function? How would I change my input?
Thank you in advance!!! :) Please let me know if you have any questions, or if I missed something that would help you out!

SOLVED!
Please see the marked answer from @mplungjan. I used his alternative method that is useful for jQuerys.

A: value='"+siteIDArray[i]+"|"+usagePlanArray[i]+"'>

but you need to remove the newlines from the HTML too
Then in the function you can use
var vals=val.split("|");
var siteID=vals[0], usagePlan=vars[1];

Alternative - especially useful in jQUery:
html += "

<input type='radio'"+
        " onclick='onRadioButtonPress(this)' name='siteChosen'"+
        " data-siteid='"+siteIDArray[i]+"'"+
        " data-usageplan='"+usagePlanArray[i]+"'>	";

and
function onRadioButtonPress(rad) {
  var siteID=rad.getAttribute("data-siteid"),
      usageplan=rad.getAttribute("data-usageplan"),
}

A: Pass an array in JSON:
   value='"+JSON.stringify(siteIDArray)+"'>

That would pass the entire Array as JSON Array string.
Passing to single values:
    value='["+siteIDArray[i] + "," + usagePlanArray[i] + "]'>

or, as an object:
    value='{ \"val1\":\""+siteIDArray[i] + "\",\"val2\":\"" + usagePlanArray[i] + "\"]'>

Now decode in the function
   values = JSON.parse(val);
   ...
   xyz = values[0];  // for the array
   ...
   xyz = values.val1; // for the object

code could even be optimized, if you direct pass that to the onclick instead of the value parameter, but that might have some additional purposes.

A: If you are using the same index for both arrays, why not just store the index as the value and look up the desired values in the click callback?
var html= "";

var siteIDArray = [1, 5, 2, 33];
var usagePlanArray = ["unlimited", "20gb", "10gb", "5gb" ]

function arrayCombo(index){
    return {siteId: siteIDArray[index], usagePlan: usagePlanArray[index]};
}

for(var i=0; i<siteIDArray.length; i++){
    html += "

<input type='radio' name='siteChosen' value="+i+">	";
}

$('#content').html(html);

$('input').on('click', function(event){
    //Do whatever you want with the values you are looking for here
    var x = arrayCombo(this.value);
    alert(x.siteId+", "+x.usagePlan);
});

Also, to demonstrate this tight-knit relationship between your arrays it would probably be better to store their values at shared indexes as properties of objects in an array.


text:
Q: Nested writable serializer to process flattened normalized request data I have a nested writable serializer.
class GamerSerializer(serializers.ModelSerializer):
  account= AccountSerializer()
  document = DocumentSerializer()
  class Meta:
    model = Gamer
    fields = [
      'chosen_game',
      'gamer_experience',
      'account',
      'document'

  ]

This serializers is supposed to create Account object, a Gamer object related to Account as well as Document object related to Gamer.
By default the nested serializer always accepts nested objects as data like this:
serializer = self.get_serializer(data= {  account: {...acount}, document: {...document}, chosen_game: "Minecraft", "gamer_experience": "1 year"  }  )

but I want the serializer to accept normalized flattened data( we assume that names of the model attributes do not overlap). Like this :
serializer = self.get_serializer(data= {  account_name: '', account_type:'', document_name: '', document_file: '', chosen_game: "Minecraft", "gamer_experience": "1 year"  })

How can I achieve this result ?


text:
Q: How do I reference a datatype defined in a different .swift file? I'm unable to access a datatype declared in a separate .swift file.

Scenario:
I have two .swift files: a) envSwift.swift and b) mySwift.swift

'envSwift.swift' has my assorted data types, including an enum (which are defined as themselves, outside of any class):

mySwift.swift:

I'm getting the compiler error: "Use of unresolved identifier 'FKPermission'".
How do I use (refer to) a public datatype defined in a different .swift file?

Hint: when I do a copy/paste of enum FKPermission into the top of mySwift.swift & compile, I get the following compiler error: "Invalid redeclaration of 'FKPermission'"; even though I can't access it.  So the original enum is detected, but 'unresolved'.

A: Although you say that both files are in the same target, maybe one of them is also in another target (e.g. your test target)?
That would be leading to exactly the errors you're describing:
1) the 'unresolved identifier' error (compiling the test target)
2) when copy/pasting the declarations - the 'redeclaration' error (compiling the main target).
So perhaps the solution is: add envSwift.swift to your test target, too.


text:
Q: Using the InjectMock annotation in Mockito with an object that hasn't been initialized I am attempting to use Mockito to unit test an Android application, specifically a fragment that gets initialized use newInstance(). I am having trouble injecting my Mock object into a private member variable of the object under test. All the examples I have seen show using new() instead of newInstance() and also show the @InjectMocks annotation on the same line as the initialization. Can I not declare the variable with the annotation but wait to initialize it later?
I have:
public class  MyFragmentTest extends TestCase {
    @Mock (name="memberVariableName") private MyObject mMyObjectMock;
    @InjectMocks private MyFragment mFragment;

    @Override
    protected void setUp() throws Exception {
       super.setUp();
       // Initialize mock objects that are being injected
       MockitoAnnotations.initMocks(this);

       // Work around for a known issue with Mockito and Dexmaker
       System.setProperty("dexmaker.dexcache", getInstrumentation().getTargetContext().getCacheDir().getPath());
    }
}


text:
Q: How to forbid Git messing with line endings while retaining diff capability? According to https://help.github.com/articles/dealing-with-line-endings/#per-repository-settings I can use .gitattributes to force a line-ending-handling policy.
I want to tell Git "don't touch my line endings, I'll decide the ending of each line in each file myself".
I tried following .gitattributes file:
* binary

Unfortunately now I couldn't view diffs of the changes anymore (in Github for Windows).
How can I force the "Don't ever change line endings, regardless of file type" policy, while retaining the ability to view diffs for text files?

A: If this is the policy for the entire repo, why not just git config core.autocrlf false?
btw, if you prefer attributes for some reason, the correct one would be -text.  (Alejandro suggests -crlf but that's only there for backwards compatibility.)

A: Try this gitattributes file instead:
# Ignore all differences in line endings
*        -crlf


text:
Q: How to store previous suite results(index.html)/ How to copy results(index.html) in a different folder with a different name I'm suing Selenium Webdriver + TestNG + ANT.
Everytime when I run my suite file: build.xml which is integrated with testNG.xml, the output file index.html overwritten by the new generated report file.
In short how can I save the results of TestNG+ANT without overwriting previous result in selenium?

A: You can solve this by creating a new test-ouput folder for each run. Refer to Cedric's reply in this post


text:
Q: How to use opencv in embedded system my question is related to the use of OpenCV in embedded systems. Instead of compiling the entire opencv library in my embedded platform, I would like to know if it is possible to copy only the libraries and call them from my .cpp main file.
Til now, what I usually do is to compile openCV in my embedded platform and in my main.cpp call
#include <opencv2/opencv.hpp>

Then in my cmake file I just put:
find_package( OpenCV REQUIRED )
target_link_libraries( main ${OpenCV_LIBS} )

This method works but I would like to save space and use only the .so or .a libraries. Is it possible to do that? if yes, how?
thanks

A: Yes, OpenCV will work fine, but you have to make sure a few things:

*

*libraries that are being copied should be previously compiled for the same platform.

*should be placed in the proper location.

*you also need .h files for compiling your code.


text:
Q: How can I add click event and go to other view? I am learning about WFM MVVM pattern.But I can't understand how can I add the click event to go to different view.
View
<UserControl x:Class="Paywall.Presentation.Views.Custom"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
             xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
             xmlns:cal="http://www.caliburnproject.org"
             xmlns:local="clr-namespace:Paywall.Presentation.Views"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800">
    <Grid>
        <DataGrid x:Name="dgData" AutoGenerateColumns="False" ItemsSource="{Binding GetCustomInvoicesVms}" >
            <DataGrid.Columns>
                <materialDesign:DataGridTextColumn Header="OrderDescription" Width="*" Binding="{Binding Description}"/>
                <materialDesign:DataGridTextColumn Header="CustomerName" Width="*" Binding="{Binding CustomerName}"/>
                <materialDesign:DataGridTextColumn Header="Amount" Width="*" Binding="{Binding Amount}"/>
                <materialDesign:DataGridTextColumn Header="PhoneNumber" Width="*" Binding="{Binding PhoneNumber}"/>
                <materialDesign:DataGridTextColumn Header="PartNumber" Width="*" Binding="{Binding PartNumber}"/>
                <DataGridTemplateColumn Header="#">
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Button Style="{StaticResource MaterialDesignFlatDarkBgButton}" ToolTip="MaterialDesignFlatDarkButton">Pay</Button>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
    </Grid>
</UserControl>

ViewModel
using Paywall.Application.Invoice.Queries;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Paywall.Presentation.ViewModels
{
    class CustomViewModel : ViewModelBase
    {
        private ObservableCollection<GetCustomInvoicesVm> _GetCustomInvoicesVms;

        public CustomViewModel()
        {
            var query = new GetCustomInvoicesQuery(_url, _accessKey);

            _GetCustomInvoicesVms = new ObservableCollection<GetCustomInvoicesVm>(query.GetData());
        }

        public ObservableCollection<GetCustomInvoicesVm> GetCustomInvoicesVms
        {
            get { return _GetCustomInvoicesVms; }
        }
    }
}

Please, help me out. Thanks :)


text:
Q: Duplicate id issue , cannot reuse an id I'm working on the following script :
http://www.andwecode.com/playground-demo/pop-up-login-signup-box-jquery/pop-up-demo.zip
it's a script that gives you a popup login form.
i would like that gmail and fb boxes (and any box i would add) to do the same action when I click on that login button in the bottom (action = the login form appears ).
I tried this in Gmail box :

Basically, I added the ID : (id="login_form") and it worked fine !
The problem is that you can use the ID just once.
for example when i used it on Gmail box the login button became useless ..
any idea how to make all the boxes do the same action (go to the login form) ?

A: Just use a class and have jQuery (if you're fine with using it, which I see you are) do something like this:
$('.selector').click(function() {
    //code
    alert('clicked!'); //just to test...
});

If I'm reading your question correctly, it should do what you want.

A: The reason the functionality works only for one scenario is that 'ID's have to be unique', if you have duplicate ID's it will recognize only the id for the first element and it will ignore the rest.
You can achieve your result in two ways
1) have same class for all the boxes fb box,google box etc.
Example: box-form class for all the boxes
HTML:

Jquery:
$('.box-form').click(function() {
    //code

});

2) Apply different id for each box and combine the id's in jquery
HTML:

Jquery:
$('#login-form, #fb-form').click(function() {
        //code

    });


text:
Q: HTML5 Video Player Progress Bar Accurate Tooltip Most video players allow you to click on the progress bar to jump to a particular point in the video by using the position of the mouse on the progress bar to roughly work out what point in the video the user will skip to if the progress bar is clicked at that point.
If the progress bar max value is small the calculation is correct.
This is an example:

$("#range").on("click", function(event){
    var tooltip = Math.round((event.offsetX / event.target.clientWidth) * parseInt(event.target.getAttribute('max')));
    if (tooltip < 0) {
        tooltip = 0
    }else if (tooltip > 10) {
        tooltip = 10
    }
    $(".calculated").text("Calculated Value: " + tooltip)
    $(".real").text("Real Value: " + $(this).val())
});
.main{
    position: relative;
    width: 100%;
    margin-top: 50px
}

/* Tooltip text */
.main .tooltip {
  width: 120px;
  background-color: #555;
  color: #fff;
  text-align: center;
  padding: 5px;
  border-radius: 6px;
}

input{
    width: 100%;
}

    5
    20
    <input type="range" min="0" max="10" value="20" id="range">

But if the progress bar max value is big the calculation will not be exact.
This is an example:

$("#range").on("click", function(event){
    var tooltip = Math.round((event.offsetX / event.target.clientWidth) * parseInt(event.target.getAttribute('max')));
    if (tooltip < 0) {
        tooltip = 0
    }else if (tooltip > 1000) {
        tooltip = 1000
    }
    $(".calculated").text("Calculated Value: " + tooltip)
    $(".real").text("Real Value: " + $(this).val())
});
.main{
    position: relative;
    width: 100%;
    margin-top: 50px
}

/* Tooltip text */
.main .tooltip {
  width: 120px;
  background-color: #555;
  color: #fff;
  text-align: center;
  padding: 5px;
  border-radius: 6px;
}

input{
    width: 100%;
}

    20
    20
    <input type="range" min="0" max="1000" value="20" id="range">

Is there any other solution to get more accurate calculation ? I'm happy to hear any suggestions.

A: Because of the width of the point.

In the picture above, the actual length of the input is (100% - point's width)
Although it is possible to calculate simply by excluding the length of the dot, it is not recommended because errors may occur depending on the screen width or browser type.
My solution is to use percentages.
$("#range").on("click", function(event) {
    var inputVal = parseInt(event.target.value);
    var inputMaxVal = parseInt(event.target.getAttribute("max"));
    var inputPercentage = inputVal / inputMaxVal * 100;

    var tmpVideo = document.getElementById("yourVideo");
    var videoDur = tmpVideo.duration;
    var videoCur = tmpVideo.currentTime;
    var videoPercentage = videoCur / videoDur * 100;

    $(".calculated").text("Calculated Value: " + inputPercentage);
    $(".real").text("Real Value: " + videoPercentage);
});

Now compare the inputPercentage and videoPercentage.
p.s. I may have misunderstood the problem because I am using a translator.

A: The reason why there is so much error in the calculation you attempted is everything but obvious.
You correctly identified an imprecision with a big maxValue on a short slider width.
The calculation error comes from the fact that the range slider knotches are not distributed in a linear way from left to right. So a simple division of the offsetX by the slider's width is... incomplete.
The "thumb" of the slider has a width. So in order to be able to get the minimum and maximum values while keeping the thumb inside the slider, the knotches are distributed in a way to gradually compensate that width from the extremes (+/-50% of thumb width) to the middle (0% of thumb width). In other words, the middle really is the middle value... But the exteme knotches are "offsetted" with a percentage of the thumb width.

To the span you used to show the calculated value versus the "real" one, I added a span for the difference in calculation and one for the error percentage. So as you can see below, I achieved a maximal error percentage of around 0.10% or less... I really doubt it is possible to get better than this! ;)
So to make sure that my calculation is tight here, I used a super huge range of ten millions (lol!)... And tried to come with the most accurate calculation possible. There always will be an error... But the idea is to keep it minimal AND "consistant" all over the slider width.
Since the key is about the thumb width, I added some CSS took from css-tricks just to make sure about that width. Removing that styling does not change anything (at least on Chrome). I did NOT found a way to retreive the slider's thumb width programmatically. So your simple solution is to define it.
I hope the calculations below are clear.

$("#range").on("click", function(event) {

  // Get the slider's params
  let maxValue = parseInt(event.target.getAttribute('max'))
  let sliderWidth = event.target.clientWidth

  // That is the key value causing offsets in calculations
  let thumbWidth = 16

  // I made a named function just to have the calculation logic apart from the rest.
  let thumbCorrection = getOffsetXcorrection(event.offsetX, sliderWidth, thumbWidth)

  // Using that "thumb correction" in the basic intuitive calculation anyone would expect
  let clickedKnotch = (event.offsetX-thumbCorrection) / sliderWidth

  // The demo outputs
  var calculatedValue = Math.round(clickedKnotch * maxValue)
  let realValue = $(this).val()
  let difference = calculatedValue - realValue
  let errorPercentage = Math.abs((difference / maxValue) *100)

  $(".calculated").text("Calculated: " + calculatedValue)
  $(".real").text("Real: " + realValue)
  $(".difference").text("Diff: " + difference)
  $(".percentage").text("Error: " + errorPercentage.toFixed(2) + "%")
});

function getOffsetXcorrection(clickedPosition, fullWidth, thumbWidth) {

  // The middle is the 0% correction point
  let middle = fullWidth/2

  // The "error" always is about half the thumb width
  let halfThumbWidth = thumbWidth/2

  // So where occured the click in that context?
  let percentageFromMiddle = (middle - clickedPosition) / middle

  // Return the correction about the click position to use in a "linear" calculation
  let correction = percentageFromMiddle * halfThumbWidth
  return Math.round(correction)
}
.main {
  position: relative;
  width: 100%;
  margin-top: 50px
}

/* Tooltip text */

.main .tooltip {
  width: 120px;
  background-color: #555;
  color: #fff;
  text-align: center;
  padding: 5px;
  border-radius: 6px;
}

input {
  width: 100%;
  margin-top: 1em;
}

/* From CSS-tricks */
input[type=range]::-webkit-slider-thumb {
  -webkit-appearance: none;
  border: 0px solid #000000;
  height: 16px;
  width: 16px;
  border-radius: 3px;
  /*background: #ffffff;
  cursor: pointer;
  margin-top: -14px;
  box-shadow: 1px 1px 1px #000000, 0px 0px 1px #0d0d0d; */
}

.main .percentage{
  background-color: tomato;
}

  20
  20
  0
  0
  <input type="range" min="0" max="10000000" value="20" id="range">


text:
Q: Searching location in a sentence I'm working on a location extraction algorithm but haven't achieved anything considerable yet. For example in this sentence

Riders on the B and Q lines will get some relief from construction as stations reopen, and a major project will soon begin at the Dyckman Street station.

"Dyckman Street" is location information. How we extract this information from a given sentence. (I tried to extract the words from a sentence starting with a Capital letter and search it against a db having city names, but it doesn't work always).
From where i can find an algorithm to extract this information?
Thanks..

A: I remember having seen this library when I was playing with Named Entity Recognition.
This Google search might be a useful source of information as well.

A: There are also a number of web services designed to parse geo-locations from text. For example Yahoo's PlaceMaker service at http://developer.yahoo.com/geo/placemaker/


text:
Q: Azure Search SDK orderby case sensitve results issue I need some assistant with Azure Search (AS) SDK settings. I have an index with a column that IsSortable in the index and I am using the default orderby of ascending (asc). Results return no problem and work as expected until the data in that column has a mix of case such as Title, upper and lower.
This is an example of what AS is giving me:

*

*Apple

*PEAR

*Peach

*apple

*peach

*pear

This is what I would expect to see:

*

*apple

*Apple

*peach

*Peach

*pear

*PEAR

This is my current search parameter setting:
SearchParameters sp = new SearchParameters()
            {
                OrderBy = new string[] { "sortcolumn" },
                IncludeTotalResultCount = true,
                SearchMode = SearchMode.Any,
                Top = 60
            };

Is there any way to set azure to ignore case in ordering as I can't find any documentation.
Thanks
Rob

A: Currently, there's no built-in way to do case-insensitive sorting. One way to do this is to add a field to your index with case-normalized values and sort by that field.
Please vote for this UserVoice suggestionto help us prioritize this work. Thanks!


text:
Q: Insert data to SWFfile I am a newer to swf file and asp.net. I want to know that the data from sql database value can be shown in swf file?If data can be shown in swf file, how can i do it? Please advice me a way to do. Thanks.

A: Here's a tutorial with some code snippets which demonstrates the principle:
http://keylimetie.com/blog/2007/12/18/how-to-communicate-between-aspnet-and-flash/


text:
Q: Thread Pool C++ I have the following for loop:
for (int i = 0; i < 100; i++) {
    someJob();
}

I want to run this function only with 5 threads, how can I do it?
I can't use any external library.
What I've tried is to make an array with 5 threads and if the index is equal to 5 to wait all threads and do it again, but I'm sure there is another way to do that:
std::thread t[THREAD_COUNT];
int j=0;

for (int i = 0; i < 100; i++) {
    t[j++] = std::thread(someJob);
    if (j == THREAD_COUNT)
    {
        for (int k = 0; k < THREAD_COUNT; k++)
        {
            if (t[k].joinable())
                t[k].join();
        }
        j = 0;
    }
}

Any suggestion? (I can't use boost)
Thanks!

A: You should use a Thread Pool.
Specifically, you might use the C++ Thread Pool Library CPTL, with which  your code would look like this:
ctpl::thread_pool p(2 /* two threads in the pool */);

for (int i = 0; i < 100; i++) {
    p.push(someJob, "additional_param");
}

A: You can simply use std::async for that.
If you want to execute this function 100 times in 5 different asynchronous actions , then each asynchronous function will execute the function 20 times:
std::vector<std::future> results;
results.reserve(5);
for (auto i = 0; i< 5 ;i++){
   results.emplace_back([]{
     for(auto j = 0; j < 20 ; j++){
       doSomeFunction();
     }
   });
}

for (auto& f : results){
    f.get();
}

the same code can be modified to use naked std::thread.

A: You could make a function that tests your thread array to find a vacant thread to run each successive job on. Something like this:
// synchronized output to prevent interleaving of results
#define sync_out(m) do{std::ostringstream o; o << m << '\n'; std::cout << o.str();}while(0)

void someJob(int id)
{
    sync_out("thread: " << id);
}

template<typename Job>
void start_thread(std::vector<std::thread>& threads, Job&& job)
{
    // find an ended thread
    for(auto&& thread: threads)
    {
        if(thread.joinable()) // still running or waiting to join
            continue;

        thread = std::thread(job);
        return;
    }

    // if not wait for one
    for(auto&& thread: threads)
    {
        if(!thread.joinable()) // dead thread (not run or already joined)
            continue;

        thread.join();
        thread = std::thread(job);
        return;
    }
}

int main()
{

    std::vector<std::thread> threads(5); // 5 threads

    for(int i = 0; i < 100; i++)
        start_thread(threads, [=]{someJob(i);});

    // wait for any unfinished threads
    for(auto&& thread: threads)
        if(thread.joinable())
            thread.join();
}

A: OpenMP will allow you to do this trivially, while hiding the entire threadpool. Most compilers have build in support, but consult your manual for the specific options. (gcc simply requires passing -fopenmp as an option).
#pragma omp parallel for num_threads(5)
for (int i = 0; i < 100; i++) {
    someJob(i);
}

will then split your work over 5 threads. If you leave out num_threads(5) it will choose a number of threads itselve.

A: Here's one way to implement a thread pool on the fly, while staying safe.
#include <thread>
#include <vector>
#include <algorithm>
#include <mutex>

void someJob() { /* some lengthy process */ }

int main()
{
    const size_t THREAD_COUNT = 5;
    std::vector<std::thread> threadPool;
    std::mutex mtx;               // to block access to the pool

    for (int i = 0; i < 100; i++)
    {
        {
            // add new thread to the pool.
            std::lock_guard<std::mutex> lock(mtx);
            threadPool.emplace_back(std::thread([&mtx, &threadPool]()
            {
                someJob();

                // task is done, remove thread from pool
                std::lock_guard<std::mutex> lock(mtx);
                threadPool.erase(
                    std::find_if(threadPool.begin(), threadPool.end(),
                    [](std::thread& x)
                    {
                        if (x.get_id() == std::this_thread::get_id())
                        {
                            x.detach();  // have to call detach, since we can't
                            return true; // destroy an attached thread.
                        }
                        return false;
                    })
                );
            }));
        }

        for (;;)
        {
            // wait for a slot to be freed.
            std::this_thread::yield();
            std::lock_guard<std::mutex> lock(mtx);
            if (threadPool.size() < THREAD_COUNT)
            {
                break;
            }
        }
    }

    // wait for the last tasks to be done
    for (;;)
    {
        std::this_thread::yield();
        std::lock_guard<std::mutex> lock(mtx); // works fine without.. but...
        if (threadPool.empty())                // <-- can't call join here, since detached
        {                                      // threads are not joinable()
            break;
        }
    }
    return 0;
}


text:
Q: Android: not getting proper google map only getting map icon on device I have developed a app in which i want to use the Google Map to show the location view,I have found many useful concepts from stack overflow and Google also,And successfully implemented my App by following these all.My App is running without any bug but not showing proper Map.
output that i am getting:

Here is my Java File:
    package com.mapactivity;

import java.util.List;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.KeyEvent;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;

public class MainActivity extends MapActivity implements LocationListener{

    MapView mapView;
    MapController mc;
    GeoPoint gp;
    MyLocationOverlay compass;
    long start;
    long stop;

    Drawable d;
    List<Overlay> overlayList;
    LocationManager lm;
    String towers;
    /*int lat;
    int longi;*/

    int x,y;

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

        mapView = (MapView) findViewById(R.id.mapView);

        mapView.setTraffic(true);
        mapView.setBuiltInZoomControls(true);
        mapView.setSatellite(true);

        mc = mapView.getController();

        String cordinate[] = {"28.636041","77.223957"};

        double lat = Double.parseDouble(cordinate[0]);
        double lng = Double.parseDouble(cordinate[1]);

        gp = new GeoPoint((int)(lat*1E6), (int)(lng*1E6));

        mc.animateTo(gp);
        mc.setZoom(13);

        MapOverlay mo = new MapOverlay();
        List<Overlay> list = mapView.getOverlays();
        list.clear();
        list.add(mo);

        mapView.invalidate();

    }

    public boolean onKeyDown(int keyCode,KeyEvent event)
    {
        mc = mapView.getController();
        switch (keyCode) {
        case KeyEvent.KEYCODE_3:
            mc.zoomIn();

            break;

        case KeyEvent.KEYCODE_1:
            mc.zoomOut();
        }
        return super.onKeyDown(keyCode, event);

    }
    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }
    private class MapOverlay extends com.google.android.maps.Overlay
    {

        @Override
        public boolean draw(Canvas canvas, MapView mapview, boolean shadow, long when) {
            // TODO Auto-generated method stub
            super.draw(canvas, mapview, shadow);

            Point screenPoint = new Point();
            mapview.getProjection().toPixels(gp, screenPoint);
            Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.marker_landmark);
            canvas.drawBitmap(bmp, screenPoint.x, screenPoint.y-50,null);

            return true;

        }

    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub

    }

}

And i have given all permissions in manifest file also but not getting the right things,Please let me know where i am doing wrong.

A: See code from given link. May it helps you.

A: Use V2. Google map v1 has been deprecated and key been no longer maintained on Feb-March 2013 itself
and for google map v2, you have two keys. Debug and release key. Debug key is common.But when you use signed apk, use release key or else map looks blank.
For release key procedure is here.

Google Map Android API v2 can't display map in play store application

A: You should move your map implementation to API V2 instead of API V1, because as been already said here the API version is deprecated, which means that you can no longer produce an API Key for this version. My quess would be that you have a key for V2 and you are trying to use it with V1 implementation.
To move your code to API V2 implementation please follow the following blog post I wrote on this matter:
Google Maps API V2

A: Google Map V1 API Documentation says that:

Version 1 of the Google Maps Android API has been officially
  deprecated as of December 3rd, 2012. This means that from March 18th,
  2013 you will no longer be able to request an API key for this
  version. No new features will be added to Google Maps Android API v1.
  However, apps using v1 will continue to work on devices. Existing and
  new developers are encouraged to use Google Maps Android API v2.

Now only those applications will work fine with old Google MAP API's whose keys were generated before March 18, 2013.
Since you're developing an app now using the old depreciated API, I guess you have generated the API key for newer version but you're trying to use it with the old API implementation.
The new API keys will not work with old API.
Recommended to use Google Map V2 for new applications.