text:
Q: I need to place a jQuery value or variable inside plugin options I need to place a jQuery value or variable inside plugin options
My script
$(document).ready(function() {
    // var bannerheight =  580;
    if ($(window).width() < 2100) {
      var bannerheight =  410;

      var opts = JSON.parse($('#revolutionSlider').attr('data-plugin-options'));
      opts.startheight = bannerheight; alert(opts.startheight);

      $('#revolutionSlider').attr('data-plugin-options', JSON.stringify(opts));
  }
});

I need to place the banner value that i got from jQuery script inside data-plugin-options='{"startheight": 430}'. That is instead of value "430" I need value from jQuery script

A: You will need to:

*

*Parse the options JSON to a JS object

*Change the value

*Serialize the object to JSON

*Set the JSON as attribute value.

The following should work. Do it after you calculate bannerheight.
var opts = JSON.parse($('#revolutionSlider').attr('data-plugin-options'));
opts.startheight = bannerheight;
$('#revolutionSlider').attr('data-plugin-options', JSON.stringify(opts));

A: This could be hackish way but works
1.get the current value
2. Change the value and set again
let raw_rev_options = jQuery('#revolutionSlider').attr('data-plugin-options');
let rev_options = JSON.parse(raw_rev_options);
rev_options.startheight = bannerheight;
jQuery('#revolutionSlider').attr('data-plugin-options', JSON.stringify(rev_options));

A: Try adding this to your script after your else condition and check if this works.
$("#revolutionSlider").attr('data-plugin-options',"{'startheight':"+bannerheight+" }");


text:
Q: Underscore loop 2 arrays and match values in template I have some dummy data with 2 arrays, the arrays will have some duplicated values. In my template I want to compare the 2 arrays and add a visibility class is-hidden to any that match as duplicates but I'm not sure how to loop both arrays and do the matching? Can I run isEqual against the 2 in some kind of each loop?
Handlebars Template

JS
var data = {
    "id": 1,
    "deleteSessions": ["X0101"],
    "mappedSessions": ["ABC123", "EDF092", "X0101"]
}

var template = _.template($('#tmpl').html());

$('.js-output').html(template(data));

A: In this case better format data before send it to template

var data = {
    "id": 1,
    "deleteSessions": ["X0101"],
    "mappedSessions": ["ABC123", "EDF092", "X0101"]
}

var template = _.template($('#tmpl').html());
var sessions = _.map(data.mappedSessions, function (session) {
  return {
    isHidden: _.indexOf(data.deleteSessions, session) >= 0,
    value: session
  }
});

$('.js-output').html(template({ sessions: sessions }));
.is-hidden {
  color: red;
}

A: You should use intersection...
var duplicates = _.intersection(a, b);

This name comes from set theory, where the intersection of two sets is the set of all elements that exist in both sets.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Local variables in static method and thread safety I have a question about variable scope.
For example:
class A {
    private static void test() {
        // do something with local variables
    }
}

Now I make two threads, and create one instance of A for each thread.

*

*When I call test() in each thread, can I guarantee that test() is thread safe?

*Where are the local varibles in test() stored? Each threads' stack? Heap space?
P.S. I know that static is totally pointless in this case. I found it in our legacy code; I just wanna make sure what I know!

A: Local variables are stored in each thread's own stack. That means that local variables are never shared between threads. That also means that all local primitive variables are thread safe.
Local references to objects are a bit different. The reference itself is not shared. The object referenced however, is not stored in each threads's local stack. All objects are stored in the shared heap. If an object created locally never escapes the method it was created in, it is thread safe. In fact you can also pass it on to other methods and objects as long as none of these methods or objects make the passed object available to other threads.
Object members are stored on the heap along with the object. Therefore, if two threads call a method on the same object instance and this method updates object members, the method is not thread safe.
Thread safety check: If a resource is created, used and disposed within the control of the same thread, and never escapes the control of this thread,the use of that resource is thread safe.
From: http://tutorials.jenkov.com/java-concurrency/thread-safety.html

A: When I call test() in each thread, can I guarantee that test() is thread safe?

Yes it would be thread safe if in test() method you are working on
  method local variables.

Where are the local varibles in test() stored? each threads' stack? heap space?

Method Local variable are stored each thread's own stack.

A: For number 1, I don't know what test() does, so I cannot answer. If they modify some static variable of the class A, then it may not be thread safe. If both threads along the way are given reference to the same object, depending on how the object is defined, it might not be thread safe.
For number 2, local variables are in the stack of each thread (or at least conceptually like that), so there is no worry about the local variables being modified by the other threads.


text:
Q: UIButton tapable area outside of subview So I have a UIView which I call ctrView and this ctrView is added to my UIViewController's view. It's basically just a smaller rectangular frame inside. And I added a UIButton on the top right corner of this container view, however it seems that when clicking on the UIButton area which is a bit outside of the ctrView doesn't trigger the action tied to the button. Only the UIButton area that is inside the container view triggers the action. How do I resolve this weird issue?
UIButton *closeButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    [closeButton setImage:[UIImage imageNamed:@"close.png"] forState:UIControlStateNormal];
    [closeButton setBackgroundColor:[UIColor clearColor]];
    [closeButton addTarget:self action:@selector(closeZoomedImageView) forControlEvents:UIControlEventTouchUpInside];
    [closeButton setCenter:CGPointMake(ctrView.frameX + ctrView.frameWidth - 30, ctrView.frameY - 15)];
    [ctrView addSubview:closeButton];
    [closeButton release];

A: This is the normal behavior, views outside the bound of the parent will not receive touch actions
In order to fix this, rearrange the views like following

*

*Main view will be big enough to accomodate the internal view and the closebutton, the backGroundColor of this view will be clear color

*Internal view will be the view that will the internal view that will have the image and or the content of your normal view

Main view will have both the internal view and the close button as its childern
Main view will be big enough to accomodate the button
Main view will have a clear color background so that it will not affect the layout
So you will add all the views you currently have inside the internal view,
The internal view and the button view will both be added to the main view
you present then the main view to the viewcontroller


text:
Q: Cannot perform NuGet pack I get the following error when trying to perform a NuGet pack.

The imported project "C:\Program Files
  (x86)\MSBuild\Microsoft\VisualStudio\v10.0\WCF\Microsoft.VisualStudio.ServiceModel.targets"
  was not found. Confirm that the path in the  declaration is
  correct, and that the file exists on disk.
  C:\Projects\MyProject.csproj

I am trying to perform the pack in my PostBuild event with the following command:

nuget pack "C:\Projects\MyProject.csproj" -Properties
  Configuration=Release -IncludeReferencedProjects -OutputDirectory
  ..\..\

I also tried to perform the pack from the command line and got the same error.
I am using NuGet 2.5.XXX.  I am using Visual Studio 2015 SP3.  My project is a WCF Service Library.  I use the Post Build command in many other projects with no problem.  Also, I have created other WCF services with no problem.
I suppose I should upgrade NuGet, but am slightly afraid it may break something else.

A: You can upgrade the nuget. That will upgrade all the references that you were using that will not break any of your functionalities.


text:
Q: Acces my Apache Server through nginx and VPN My local system (127.0.0.1) is running an nginx server listening to port 443 and port 80, both TCP.
The system is connected to my router (94.1.2.3), which forwards all requests from WAN to the two ports. nginx forwards it to my apache web server on port 8080 in my local system. Everything working fine!
Now I need to connect my local system to a VPN/proxy server (180.4.5.6). I am connecting via an OpenVPN configuration, which works fine as well.
But the problem now is that requests from WAN don't reach my local system anymore.
The VPN/proxy provider opened port 49850 TCP for me.
My question is now: How do I need to configure nginx in a way that all traffic goes over the VPN and also requests coming back to my local machine?
I read something about upstream in nginx, but I am not sure, if that is what I need?
Edit: Here is a sketch to better understand what I have and what I need:


text:
Q: Get line number clicked using jquery - (count of all  inside a  before a particular element clicked) I want to get the count of all the
 (i.e. the number of lines before the clicked line) inside the
.

Hello abc;

 com.demo;

    import org.junit.Test;

    import org.openqa.selenium.firefox.FirefoxDriver;

    import com.jkl;

Any help would be highly appreciated.

A: Assuming, that every line ends up with
:

    Hello abc;

    com.demo;

    import org.junit.Test;

    import org.openqa.selenium.firefox.FirefoxDriver;

    import com.jkl;

We can use something like this:
$(document).on("click", "#myTextFile", function(event)
{
    var thisEl = $(this);
    var clickOffset = event.pageY - thisEl.offset().top;
    var lineHeight = thisEl.height() / thisEl.find('br').length;
    var lineNumber = Math.floor(clickOffset / lineHeight);
    alert(lineNumber);
});

And fiddle with this.


text:
Q: many elements of a listbox to another This is the first time I use this medium to ask for help. I wanted to know how , in my code , include two listbox . One that makes querying the database and , through a button , send it to the other, and to do so with more than one option , and then , as in the php code to put the data from the second listbox on a table database. Thank you.
<?php
include("server.php");
$conexion = mysql_connect($server,$user, $pass) or die ("
 No se puede conectar con la base de datos");
$conectarbase = mysql_select_db ($bd);

$consulta = mysql_query("SELECT * FROM modalidad")

?>

    <meta charset = "iso-8859-1"/>
    <meta name = "description" content = "Ejemplo de HTML5"/>
    <meta name = "keywords" content = "HTML5, CSS3, Javascript"/>
    <title>PRECEPTORÍA</title>
    <link rel="shortcut icon" href="./style/favicon.png" />
    <link rel = "stylesheet" href = "./style/style.css">

        <form>
          <fieldset id = "fieldsetalum">
            <legend id = "legendalum">Registro de nuevos alumnos</legend>
            <select name="combo1" multiple size="8">
              <?php
while ($fila = mysql_fetch_row($consulta))
{
echo "<option value='".$fila['0']."'>".$fila['1']."</option>";
}
?>
            </select>
            <select name="combo2" multiple size=></select>
          </fieldset>
        </form>

A: Your form needs an action to submit to itself:
     <form name="form" id="form" action="<?php echo echo htmlspecialchars($_SERVER["REQUEST_URI"]); ?>" method="post">

You could add an onChange(); event to your select1 dropdown
     <select name="combo1" multiple size="8" onChange="submit_this();">

and have a JavaScript script in your

Then you would have to use php to collect the values from the submitted page
      $combo1 =  mysqli_real_escape_string( $_POST['combo1'] );

and then you could return the page with the second dropdown, constructed in much the same way as you made the first one, using the data you get back from the first one to set up the second one. You could wrap the first dropdown in an isset():
        if( !isset( $combo1 ) ){
        // make your first select boxes
        }

and the second one in
        if( isset( $combo1 ) ){
        // make your second select boxes if combo1 returned a value
        }

so that they will only appear when needed.
As @NanaPartykar says, mysqli is the only way to go.
It will be dependent on JavaScript, so, if you prefer, you could have a submit button instead of the JavaScript function:
     <input type="submit" name="submit" value="Pick Sizes" />

This looks a handy referenc e for how to use select boxes: PHP code to get selected text of a combo box
I hope this will give you an idea of how it could be done - the SESSION variables remain to be properly defined in the loop for the second dropdown but they will probably come directly from your database at that point rather than from the session array used for demo purposes.
All values are set as numbers;
intval(); converts whatever is submitted to an integer to clean it up.
Then you can get back the corresponding value of what was submitted from the session variable you set from your database originally.
That way you will only be getting a single number value from your dropdowns which you can use to look up to get the answer you want
  <?php session_start(); ?>
  <!DOCTYPE html>

  <title>PRECEPTORÍA</title>

    <form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post">
    <?php
    $main_opt = array();
    $_SESSION['opt_vals'] = array();
    $main_opt[0] = "Select Item";
    $main_opt[1] = "Ice Cream";
    $main_opt[2] = "Trousers";
    $main_opt[3] = "Tee Shirts";
    $_SESSION['opt_vals'][1][0] = "Select Flavour";
    $_SESSION['opt_vals'][1][1] = "Vanilla";
    $_SESSION['opt_vals'][1][2] = "Chocolate";
    $_SESSION['opt_vals'][1][3] = "Strawberry";
    $_SESSION['opt_vals'][1][4] = "Tuttifrutti";
    $_SESSION['opt_vals'][2][0] = "Select Colour";
    $_SESSION['opt_vals'][2][1] = "Black";
    $_SESSION['opt_vals'][2][2] = "Red";
    $_SESSION['opt_vals'][2][3] = "Green";
    $_SESSION['opt_vals'][2][4] = "Blue";
    $_SESSION['opt_vals'][3][0] = "Select Size";
    $_SESSION['opt_vals'][3][1] = "Small";
    $_SESSION['opt_vals'][3][2] = "Medium";
    $_SESSION['opt_vals'][3][3] = "Large";
    $_SESSION['opt_vals'][3][4] = "X Large";
    $i = 0;
    if(!isset($_POST['combo1']) && !isset($_POST['combo2'])){
        echo '<select name="combo1" onChange="submit();">' . "\n";
        //while ($fila = mysqli_fetch_row($consulta)){
        while($i < count($main_opt)){
        echo "<option value='".$i."'>".$main_opt[$i]."</option>\n";
             $o = 0;
             // load your sub options array here
             if(!$_SESSION['opt_vals'][$i]) $_SESSION['opt_vals'][$i] = array();
             while($i < count($_SESSION['opt_vals'][$i])){
             $_SESSION['opt_vals'][$i] = $o;
             if(!$_SESSION['opt_vals'][$i]) $_SESSION['opt_vals'][$i] = array();
             $_SESSION['opt_vals'][$i][$o] = $_SESSION['opt_vals'][$i][$o];
             $o++;
             }
         $i++;
         }
     echo '</select>'  . "\n";
     }else{
         if(intval($_POST['combo1']) >= 1) $_SESSION['combo1_val'] = $combo1_val =intval($_POST['combo1']);
         if(intval($_POST['combo1']) >=1){
             $i = 0;
             echo '<select name="combo2" onChange="submit();">' . "\n";
             while($i < count($_SESSION['opt_vals'][$combo1_val])){
             echo "<option value='".$i."'>".$_SESSION['opt_vals'][$combo1_val][$i]."</option>\n";
             $i++;
             }
         }
     echo '</select>'  . "\n";
     }
     if(intval($_POST['combo2']) >= 1) $_SESSION['combo2_val'] = $combo2_val =intval($_POST['combo2']);
     if($_SESSION['combo1_val'] >=1 && $_SESSION['combo2_val'] >=1){
     // use the result to do  whatever you want
     echo 'Thank you! You have selected ' . $_SESSION['opt_vals'][$_SESSION['combo1_val']][$_SESSION['combo2_val']] . " " . $main_opt[$_SESSION['combo1_val']] . '.';
     }
     // Do any mysqli adjustments to your database here
     // reset to go again
     if($_SESSION['combo2_val'] >= 1){
     $_SESSION['combo1_val'] = 0;
     $_SESSION['combo2_val'] = 0;
     }
     ?>
             </form>
             <a href="<?php echo htmlspecialchars($_SERVER['REQUEST_URI']); ?>">Click to start a new selection

You could remove onChange="submit();" and replace it with a normal submit button on the form if you prefer.


text:
Q: Win32 Named pipe behavior Win7, x64, C++, Win32 API, Console app, Visual Studio Community 2015
I've scoured all the SO questions on named pipes and can't find the answer I need.
I'm writing a server to broadcast data one way via named pipe to multiple identical clients on the same machine.  The sever and each client is in its own process (.exe).  The data is sent when all the clients have somehow signaled back to the server that they are ready (via named event or other mechanism).
The documentation says multiple clients can connect to a single pipe instance, but then proceeds to talk about multiple instances.
I have a few questions about the pipe on the server side:

*

*For a small number of clients and low throughput, which is the simplest: 1 thread, 1 pipe instance; 1 thread and multiple pipe instances; multiple threads and one instance per thread?

*If a single thread does ConnectNamedPipe multiple times on the same instance of a pipe, does this mean a single WriteFile is broadcast to all clients that have connected to that particular instance of the pipe?

*If multiple clients can connect to a particular instance of a pipe, does writing to that pipe from the server side block until all the clients have read the previous message?

*Is doing a one-to-many situation uncommon?  Why?

A:
The documentation says multiple clients can connect to a single pipe instance

No, it doesn't.  You misread what it actually said.

but then proceeds to talk about multiple instances.

Each pipe instance can only communicate with one client at a time.  When the client is finished, the server can either disconnect the instance and reuse it for a new client, or it can destroy the instance and create a new instance.  Either way, the server must create a separate pipe instance for each client that connects.

1.For a small number of clients and low throughput, which is the simplest: 1 thread, 1 pipe instance; 1 thread and multiple pipe instances; multiple threads and one instance per thread?

The first way only allows for 1 client at a time.
The second way allows the server to create multiple instances for handling simultaneous connections, but requires overlapped I/O be used so 1 thread can manage the multiple connections.
The third way also allows the server to create multiple instances for handling simultaneous connections, but is the simplest as the server can run each instance in its own thread, servicing whichever client is currently connected to that instance. Overlapped I/O is not needed.

2.If a single thread does ConnectNamedPipe multiple times on the same instance of a pipe, does this mean a single WriteFile is broadcast to all clients that have connected to that particular instance of the pipe?
3.If multiple clients can connect to a particular instance of a pipe, does writing to that pipe from the server side block until all the clients have read the previous message?

No and no, because multiple clients cannot be connected to a single instance at the same time.

4.Is doing a one-to-many situation uncommon?

One-to-many is not possible with named pipes.  But you can have multiple simultaneous one-to-one connections, and it is not uncommon to broadcast data amongst multiple connections.  In this case, you are best of using a separate thread with each connection, or overlapped I/O.  This way, if one client does block, other clients are not blocked waiting on it.


text:
Q: How to check variable against a set of values in XSLT 1.0? I have the following condition to test
<xsl:if test="   $Occupation='5'
              or $Occupation='7'
              or $Occupation='N'
              or $Occupation='M'
              or $Occupation='J'
              or $Occupation='V'
              or $Occupation='W'">
  <xsl:value-of select="'Accounts'"/>
</xsl:if>

Is there a way to check like this?
<xsl:if test="$occupation contains('5','7','N','W','J','M')">

A: Assuming everything in your list is a single character:
<xsl:if test="string-length($occupation) = 1 and contains('57NWJM', $occupation)">
    <xsl:value-of select="'Accounts'"/>
</xsl:if>

If the entries are longer than one character, you can use a separation character.  This character must of course not appear in any of the values in your list.  With a space as separation character, things might look like:
<xsl:if test="not(contains($occupation, ' ')) and contains(' foo bar baz ', concat(' ', $occupation, ' '))">
    <xsl:value-of select="'Accounts'"/>
</xsl:if>

Make sure you don't forget those padding spaces before foo and after baz.

A: You could use:
<xsl:if test="contains('57NMJ', $Occupation)">

but this would also return true when $Occupation = "7N", for example.
To protect against that, you can use:
<xsl:if test="contains('|5|7|N|M|J|', concat('|', $Occupation, '|'))">

A: The other way round might work...
<xsl:if test="contains('57NWJM',$Occupation)">

A: XSLT 2.0
You can do this much more cleanly in XSLT 2.0:
$occupation = ('5','7','N','M','J','V','W')

XSLT 1.0
For single-character value cases such as yours, this XPath 1.0 expression,
translate($occupation,'7NMJVW','555555')='5'

will return true when $occupation is 5, 7, N, M, J, V, or W as requested.
For single- or multi-character value cases, see Thomas W's answer or michael.hor257k's answer, which employ a technique often used to test @class attribute values safely:
contains(concat(" ", normalize-space(@class), " "), " target ")]


text: Q: Окружение/среда выполнения отличия Изучая программирование, столкнулся с концепцией окружения. При поисках информации на эту тему встречал также термин среда выполнения. Объясните тождественны ли эти два понятия.


text:
Q: Radix Tree, how many children maximum? http://en.wikipedia.org/wiki/Radix_tree
So instead of a function i used an integer value instead for isLeaf. But how many elements should an array of edges have? How many children max for each node?

A: That depends on your radix. The maximum number of children of a node is the number of possible unique values of the chosen discriminator; if you use a character for the discriminator, then the maximum number of children will be the number of valid characters.
You can implement this data-structure with a radix of two, by discriminating on each bit; in this case, your trees will be deeper but each non-leaf node will have exactly two children, which might simplify the implementation.


text:
Q: How to get all deprecations in project I'm working on the project that uses a lot of deprecated classes. Now, when the time has come to refactor it, I was "given the honor" to do it. But, we decided not to remove all the deprecated classes, we still gonna use old android.app.Fragment class and few others. But the problem is that Fragment deprecation warnings are simply overflowing the build stack(when I clean/build) and I cannot see other warings. So, my question is: can I see all the deprections somehow, or maybe I can suppress specific warnings for the entire project?

A: Hope this will help you..

*

*First GOTO Analyze  ->

*Select Inspect Code.. ->

*After code has been inspected. Select JAVA -> Code maturity ->    Depricated API usage "List of depricated class will be displayed"

You can find all depricated class in your project easily..


text:
Q: Checking for error in foreach with valid but changed json with different stucture I am pulling data from a 3rd party web service and when the api goes under maintenance the json document no longer has the same structure (but is still a valid json document). So when I go to parse, I get an error: "Invalid argument supplied for foreach()" Makes sense, but how do I test for this and then call a separate function to log the error with the contents of the json document?
I tried adding set_error_handler("customError");    and that works but I don't know how to access the contents of $response or $json from the error function
$response = file_get_contents($url);
$json = json_decode($response, TRUE);

foreach($json['workers'] as $item) {
    echo $item['address']; //address does not exist when in maintenance mode!
}

function customError($errno, $errstr) {
    $link=Connection();
    echo "<b>Error:</b> [$errno] $errstr ";
    $sql="Insert into myErrors (response, description) values ('".$response."','.$errstr.');";
    //echo $sql;
    $result = mysqli_query( $link,$sql) or die('Error; ' . mysqli_error($link));
  }

A: Test the result to see if the array exists before trying to loop over it.
$response = file_get_contents($url);
$json = json_decode($response, TRUE);

if (isset($json['workers'])) {
    foreach($json['workers'] as $item) {
            echo $item['address']; //address does not exist when in maintenance mode!
    }
} else {
    // insert something into myErrors table
}


text:
Q: Preventing HTTP request spam I've recently released a game using the Unity game engine. Part of the game is a level editor where players can submit level data to an online SQL database via HTTP POST requests.
However, people have discovered the URL used to send requests and have been constantly uploading thousands of levels using some sort of spam bot.
For clarification, the server code is a php file that takes four POST inputs and adds a new row to a database using those inputs.
Is there any way to prevent spammers from repeatedly sending HTTP POST requests?
Is there a better way to do this?
Thanks!


text:
Q: DataGridView bound to a Dictionary I have a Dictionary that contains items and prices. The items are unique but slowly get added and updated through the lifetime of the application (that is, I don't know the item strings in advance). I would like to bind this structure to a DataGridView, so I can show updates on my Form, something like:
Dictionary<string, double> _priceData = new Dictionary<string, double>();
BindingSource _bindingSource = new BindingSource();
dataGridView1.DataSource = _bindingSource;
_bindingSource.DataSource = _priceData;

But cannot, since Dictionary does not implement IList (or IListSource, IBindingList, or IBindingListView).
Is there a way to achieve this? I need to keep a unique list of items, but also update the price for an existing item, so a Dictionary is the ideal data structure I think, but I cannot find a way to display the data on my Form.

Update:
Marc's suggestion below works very nicely, but I'm still not sure how to update the DataGridView during execution.
I have a class-level variable:
private DictionaryBindingList<string, decimal> bList;

Then instantiate that in Main():
bList = new DictionaryBindingList<string,decimal>(prices);
dgv.DataSource = bList;

Then during program execution if a new entry is added to the dictionary:
prices.Add("foobar", 234.56M); bList.ResetBindings();

I thought that would refresh the DataGridView. Why not?

A: Probably this is easiest way:
Dictionary<char, double> myList = new Dictionary<char, double>();

        dataGridView1.Columns.Add("Key", "KEY");
        dataGridView1.Columns.Add("Values", "VALUES");

        foreach (KeyValuePair<char,double> item in , myList)
        {
            dataGridView1.Rows.Add(item.Key, item.Value);
        }

If use this you datagridview shall be sortable.

A: Or, in LINQ, it's nice and quick:
var _priceDataArray = from row in _priceData select new { Item = row.Key, Price = row.Value };

That should then be bindable, to the columns 'Item' and 'Price'.
To use it as a data source in a grid view, you just have to follow it with ToArray().
dataGridView1.DataSource = _priceDataArray.ToArray();

A: i thing this will resolve your problem which i faced few months ago.
use dictionay as you want to update item prices and just when u finish updation and want to show in datagrid just do this. hope will help you
Grd.DataSource=null;
Grd.DataSource = Dictionary.Values.ToList();

A: There are a couple of issues with Dictionary; the first is (as you've found) it doesn't implement the necessary IList/IListSource. The second is that there is no guaranteed order to the items (and indeed, no indexer), making random access by index (rather than by key) impossible.
However... it is probably doable with some some smoke and mirrors; something like below:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows.Forms;

static class Program
{
    [STAThread]
    static void Main()
    {
        Dictionary<string, decimal> prices =
            new Dictionary<string, decimal>();
        prices.Add("foo", 123.45M);
        prices.Add("bar", 678.90M);

        Application.EnableVisualStyles();
        Form form = new Form();
        DataGridView dgv = new DataGridView();
        dgv.Dock = DockStyle.Fill;
        form.Controls.Add(dgv);
        var bl = prices.ToBindingList();
        dgv.DataSource = bl;
        Button btn = new Button();
        btn.Dock = DockStyle.Bottom;
        btn.Click += delegate
        {
            prices.Add(new Random().Next().ToString(), 0.1M);
            bl.Reset();
        };
        form.Controls.Add(btn);
        Application.Run(form);
    }

    public static DictionaryBindingList<TKey, TValue>
        ToBindingList<TKey, TValue>(this IDictionary<TKey, TValue> data)
    {
        return new DictionaryBindingList<TKey, TValue>(data);
    }
    public sealed class Pair<TKey, TValue>
    {
        private readonly TKey key;
        private readonly IDictionary<TKey, TValue> data;
        public Pair(TKey key, IDictionary<TKey, TValue> data)
        {
            this.key = key;
            this.data = data;
        }
        public TKey Key { get { return key; } }
        public TValue Value
        {
            get
            {
                TValue value;
                data.TryGetValue(key, out value);
                return value;
            }
            set { data[key] = value; }
        }
    }
    public class DictionaryBindingList<TKey, TValue>
        : BindingList<Pair<TKey, TValue>>
    {
        private readonly IDictionary<TKey, TValue> data;
        public DictionaryBindingList(IDictionary<TKey, TValue> data)
        {
            this.data = data;
            Reset();
        }
        public void Reset()
        {
            bool oldRaise = RaiseListChangedEvents;
            RaiseListChangedEvents = false;
            try
            {
                Clear();
                foreach (TKey key in data.Keys)
                {
                    Add(new Pair<TKey, TValue>(key, data));
                }
            }
            finally
            {
                RaiseListChangedEvents = oldRaise;
                ResetBindings();
            }
        }

    }
}

Note that the use of a custom extension method is entirely optional, and can be removed in C# 2.0, etc. by just using new DictionaryBindingList<string,decimal>(prices) instead.

A: For Dictionary<TKey, TValue> you can use these keywords for binding: Key and Value.
Here is example for ComboBox Binding, but it's possible to bind dictionary to DataGridView (set DataPropertyName for column to Key or Value).
    ComboBox1.DataSource =
        new BindingSource(Pricelevel.GetPricelevels(), null); // GetPricelevels() returns Dictionary<string, string>

    ComboBox1.ValueMember = "Key";
    ComboBox1.DisplayMember = "Value";

A: Make a class like so:
class MyRow
{
    public string key;
    public double value;
    public string Key {get {return key;}}
    public string Value {get {return value;}}
}

Then make a list of them:
List<MyRow> rows = new List<MyRow>();

Then insert them into that list, and databind to the list.
As an aside, if you've got LINQ, I think there's a ToArray method that'll simplify all this...

A: As an extension to Marc's suggestion, I would like to propose the following solution that will also allow run-time manipulation of the dictionary:
public class DictionaryBindingList<TKey, TValue> : BindingList<KeyValuePair<TKey, TValue>>
{
    public readonly IDictionary<TKey, TValue> Dictionary;
    public DictionaryBindingList()
    {
        Dictionary = new Dictionary<TKey, TValue>();
    }

    public void Add(TKey key, TValue value)
    {
        base.Add(new KeyValuePair<TKey, TValue>(key, value));
    }

    public void Remove(TKey key)
    {
        var item = this.First(x => x.Key.Equals(key));
        base.Remove(item);
    }

    protected override void InsertItem(int index, KeyValuePair<TKey, TValue> item)
    {
        Dictionary.Add(item.Key, item.Value);
        base.InsertItem(index, item);
    }

    protected override void RemoveItem(int index)
    {
        Dictionary.Remove(this[index].Key);
        base.RemoveItem(index);
    }

    public int IndexOf(TKey key)
    {
        var item = this.FirstOrDefault(x => x.Key.Equals(key));
        return item.Equals(null) ? -1 : base.IndexOf(item);
    }
}

A: As an extension of Bleiers DictionaryBindingList I made a small alteration to allow Add values to overwrite existing values.
I'm using the method with a WAMP websocket so it would allow me to keep values updated just by updating the collection, next I need to tie events onto the values.
    public void Add(TKey key, TValue value)
    {
        if (Dictionary.ContainsKey(key))
        {
            int position = IndexOf(key);
            Dictionary.Remove(key);
            Remove(key);
            InsertItem(position, new KeyValuePair<TKey, TValue>(key, value));
            return;
        }
        base.Add(new KeyValuePair<TKey, TValue>(key, value));
    }


text:
Q: Send info every 2 seconds to database I made a program where Yolov3 send info to my database.
But I want it to send it every 2 seconds otherwise it fills up my database too fast.
This is my code
           def findObjects(outputs, img):
        hT, wT, cT = img.shape
        bbox = []
        classIds = []
        confs = []
        for output in outputs:
            for det in output:
                scores = det[5:]
                classId = np.argmax(scores)
                confidence = scores[classId]
                if confidence > confThreshold:
                    w, h = int(det[2] * wT), int(det[3] * hT)
                    x, y = int((det[0] * wT) - w / 2), int((det[1] * hT) - h / 2)
                    bbox.append([x, y, w, h])
                    classIds.append(classId)
                    confs.append(float(confidence))

        indices = cv.dnn.NMSBoxes(bbox, confs, confThreshold, nmsThreshold)

        for i in indices:
            i = i[0]
            box = bbox[i]
            x, y, w, h = box[0], box[1], box[2], box[3]
            cv.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
            cv.putText(img, f'{classNames[classIds[i]].upper()} {int(confs[i] * 100)}%',
                       (x, y - 10), cv.FONT_HERSHEY_SIMPLEX, 0.6, (255, 0, 0), 2)

            DetectedName = (f'{classNames[classIds[i]].upper()}')
            DetectedProcent = (f'{int(confs[i] * 100)}%')
            print(DetectedName)
            print(DetectedProcent)
            current_datetime = datetime.now()
            print(current_datetime)
            ***insert = "INSERT INTO DetectedObjects (WayOfDetection, ObjectName, Certainty, TimeOfDetection, LoggedInUser) VALUES (%s,%s,%s,%s,%s)"
            mycursor.execute(insert, ("webcam", DetectedName, DetectedProcent, current_datetime, self.username))
            conn.commit()***

I want to execute the last 3 lines every 2 seconds so my database is not overfull.
can somebody pls help me?

A: you can use time.sleep() such as:
   while True:
        ***insert = "INSERT INTO DetectedObjects (WayOfDetection, ObjectName, Certainty, TimeOfDetection, LoggedInUser) VALUES (%s,%s,%s,%s,%s)"
        mycursor.execute(insert, ("webcam", DetectedName, DetectedProcent, current_datetime, self.username))
        conn.commit()***
        time.sleep(2)

A: Use time.sleep function. Pass required time as the parameter in seconds.

A: Use time.sleep(time_in_seconds).
while True:
    //run last 3 lines
    time.sleep(2)


text:
Q: attempting to push updates to bitbuckets hangs I am attempting to push updates to git using bitbucket and it hangs at this point
Total 349 (delta 84), reused 1 (delta 0)

EDITTED
here is the command I run
git add .
git commit --m "infor..."
git push

This is the complete thing of what I get>>>>
Counting objects: 398, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (382/382), done.
Writing objects: 100% (398/398), 176.64 MiB | 48.07 MiB/s, done.
Total 398 (delta 121), reused 1 (delta 0)

Please what could be wrong

A: Check first if this is not a case of very long upload, as in this instance.
For that, as I described in this answer, try (with Git 2.10 or more recent) the --progress option:
 git push --progress


text:
Q: how to display data in listview from database using raw query in my project there are 2 activities; in one Activity the user enters 2 symptoms and presses a button, which opens the next Activity. I want the next activity to display all names of possible diseases as per the symptoms, in listview format. Can anyone tell me how to do this? I had tried, but its showing nullpointer exception. I'm using a Sqlite database.
public class LstView extends Activity {
private Database db;
private Auto ato;
 public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listname);
        ListView lstv =(ListView) findViewById(R.id.listView1);
        db=new Database(LstView.this);
        db.openDB();
        String a=ato.selected;
        String b=ato.selected1;
       // String[] lst=db.getName(a, b);
        String[] from=new String[]{db.COLUMN_1_NAME};
       int[] to= new int[]{R.id.text};
       Cursor csr=db.getName(a, b);
      // ArrayAdapter<String> adt= new ArrayAdapter<String>(getBaseContext(),R.layout.list_view,lst);
       SimpleCursorAdapter adt =new SimpleCursorAdapter(this, R.layout.list_view, csr, from, to);
      // SimpleCursorAdapter adt = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_1, db.getName(a,b), new String[] { "Name" }, new int[] { android.R.id.text1 });
        lstv.setAdapter(adt);
 }

}

String[] Sympt= db.getSymptom();

    ArrayAdapter<String> adapter=new ArrayAdapter<String>(this,R.layout.list_view,Sympt);
    textView.setAdapter(adapter);
    textView.setThreshold(1);
    textView.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView arg0, View arg1, int arg2,
                long arg3) {

             int    idn=arg0.getId();
              selected = arg0.getItemAtPosition(arg2).toString();
                System.out.println("newww "+idn);
                System.out.println("newww1 "+selected);
                String[] Sympt1=db.getSymptom1(selected);
                for(int i=0;i<Sympt1.length;i++)
                {
                    System.out.println("value array "+Sympt1[i]);
                }
                ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(getBaseContext(), R.layout.list_view,Sympt1);
                textView1.setAdapter(adapter1);
                textView1.setThreshold(1);
            // TODO Auto-generated method stub
            //Toast.makeText(getApplicationContext(), "HI", Toast.LENGTH_SHORT).show();
        }
    });
textView1.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) {
        // TODO Auto-generated method stub
        int idn1=arg0.getId();
        selected1=arg0.getItemAtPosition(arg2).toString();
        System.out.println("neww2"+idn1);
        System.out.println("neww3"+selected1);

    }
});
search.setOnClickListener(new OnClickListener(){

    public void onClick(View arg0) {
        // TODO Auto-generated method stub
        Intent i = new Intent(getApplicationContext(),LstView.class);
        startActivity(i);
    }

});

}

here is the which im geting after clicking on button

03-16 09:49:33.993: W/dalvikvm(331): threadid=1: thread exiting with uncaught exception (group=0x40015560)
03-16 09:49:34.003: E/AndroidRuntime(331): FATAL EXCEPTION: main
03-16 09:49:34.003: E/AndroidRuntime(331): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.autocmplt/com.example.autocmplt.LstView}: java.lang.NullPointerException
03-16 09:49:34.003: E/AndroidRuntime(331):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
03-16 09:49:34.003: E/AndroidRuntime(331):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
03-16 09:49:34.003: E/AndroidRuntime(331):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
03-16 09:49:34.003: E/AndroidRuntime(331):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
03-16 09:49:34.003: E/AndroidRuntime(331):  at android.os.Handler.dispatchMessage(Handler.java:99)
03-16 09:49:34.003: E/AndroidRuntime(331):  at android.os.Looper.loop(Looper.java:123)
03-16 09:49:34.003: E/AndroidRuntime(331):  at android.app.ActivityThread.main(ActivityThread.java:3683)
03-16 09:49:34.003: E/AndroidRuntime(331):  at java.lang.reflect.Method.invokeNative(Native Method)
03-16 09:49:34.003: E/AndroidRuntime(331):  at java.lang.reflect.Method.invoke(Method.java:507)
03-16 09:49:34.003: E/AndroidRuntime(331):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-16 09:49:34.003: E/AndroidRuntime(331):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-16 09:49:34.003: E/AndroidRuntime(331):  at dalvik.system.NativeStart.main(Native Method)
03-16 09:49:34.003: E/AndroidRuntime(331): Caused by: java.lang.NullPointerException
03-16 09:49:34.003: E/AndroidRuntime(331):  at com.example.autocmplt.LstView.onCreate(LstView.java:22)
03-16 09:49:34.003: E/AndroidRuntime(331):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-16 09:49:34.003: E/AndroidRuntime(331):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
03-16 09:49:34.003: E/AndroidRuntime(331):  ... 11 more
03-16 09:49:37.643: I/Process(331): Sending signal. PID: 331 SIG: 9

A: What is Database? There's no android class for it, so if you're using SQLite then you're using something other than the version provided with the Android platform.
Anytime you get an exception, you must post a logCat. Most people following this list are pressed for time, so we can't spend an hour searching through your code to find things that might cause a problem. Conversely, a logCat immediately identifies the statement that's causing the error.
You should also consider adding comments to your code and giving more mnemonic names to your classes, methods, and variables. Reading code from scratch is hard to do anyway, and it gets worse when we have to look through the code to figure out what "a" is supposed to be.


text:
Q: How to use OR operator in PHP? I have a code in which i check a variable value and try to applying OR operator but i failed. My file have edit code. In my scenario i use 4 submit button Like Save, Submit, Approve and Re-Submit. Now on Edit File i start a session and apply condition if there is user then show Save and Submit Button but if there is Manager then show Approve and Re-Submit Button. On Manager Condition i want to apply another if condition that if previous status is Approve then show only Re-Submit Button, if previous status is Save or Submit then Show Both Approve and Re-Submit Button
Below is my code
<?php
include ("session1.php");
?>
<?php
    require 'database.php';
    $id = null;
    if ( !empty($_GET['id'])) {
        $id = $_REQUEST['id'];
    }

    if ( null==$id ) {
        header("Location: index.php");
    }

    //------------------------------------------Update--------------------------------
    if ( !empty($_POST)) {
$editor1 =mysql_real_escape_string(trim($_POST['editor1']));
$editor2 =mysql_real_escape_string(trim($_POST['editor2']));
$editor3 =mysql_real_escape_string(trim($_POST['editor3']));
$editor4 =mysql_real_escape_string(trim($_POST['editor4']));
$editor5 =mysql_real_escape_string(trim($_POST['editor5']));
$editor6 =mysql_real_escape_string(trim($_POST['editor6']));
$editor7 =mysql_real_escape_string(trim($_POST['editor7']));
$editor8 =mysql_real_escape_string(trim($_POST['editor8']));
$editor9 =mysql_real_escape_string(trim($_POST['editor9']));
$editor10 =mysql_real_escape_string(trim($_POST['editor10']));
if($_POST['submit'] == "Submit"){
$status=$_POST['submit'];}

if($_POST['submit'] == "Save"){
$status=$_POST['submit'];}

if($_POST['submit'] == "Approve"){
$status=$_POST['submit'];}

if($_POST['submit'] == "Re-Submit"){
$status=$_POST['submit'];}

$valid = true;
        if ($valid) {
            $pdo = Database::connect();
            $sql = "UPDATE test1  set editor1 ='$editor1', editor2 ='$editor2', editor3 ='$editor3',
                                        editor4 ='$editor4', editor5 = '$editor5', editor6 ='$editor6',
                                        editor7 ='$editor7', editor8 ='$editor8', editor9 ='$editor9',
                                        editor10 ='$editor10', status='$status'  WHERE id ='$id'";
            $q = $pdo->prepare($sql);
            $q->execute(array($editor1,$editor12,$editor3,$editor4,$editor5,$editor6,$editor7,$editor8,$editor9,
            $editor10,$status,$id));
            Database::disconnect();
            header("Location: index.php");
        }
}
    else {
          }

    $con=mysqli_connect("localhost","root","","pacra1");

         $id2 = $_GET['id'];
        $sql = "SELECT * FROM test1 where id='$id2'";

            $result=mysqli_query($con,$sql);

            $row= (mysqli_fetch_array($result,MYSQLI_ASSOC));

$editor1 =($row['editor1']);
$editor2 =($row['editor2']);
$editor3 =($row['editor3']);
$editor4 =($row['editor4']);
$editor5 =($row['editor5']);
$editor6 =($row['editor6']);
$editor7 =($row['editor7']);
$editor8 =($row['editor8']);
$editor9 =($row['editor9']);
$editor10 =($row['editor10']);
$status =($row['status']);

    ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="newstyles.css">
<link rel="stylesheet" href="../../jqwidgets/styles/jqx.base.css" type="text/css" />
 <link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">

    The Pakistan Credit Rating Agency Limited

    <form action="edit.php?id=<?php echo $id; ?>" method="POST" >

<textarea name="editor1" id="editor1"><?php echo(nl2br($editor1));?></textarea>

<textarea name="editor2" id="editor2"><?php echo(nl2br($editor2));?></textarea>

<textarea name="editor3" id="editor3"><?php echo (nl2br($editor3));?></textarea>

<textarea name="editor4" id="editor4"><?php echo(nl2br($editor4));?></textarea>

<textarea name="editor5" id="editor5"> <?php echo(nl2br($editor5));?></textarea>

<textarea name="editor6" id="editor6"><?php echo (nl2br($editor6));?></textarea>

<textarea name="editor7" id="editor7"><?php echo(nl2br($editor7));?></textarea>

<textarea name="editor8" id="editor8"><?php echo (nl2br($editor8));?></textarea>

<textarea name="editor9" id="editor9"><?php echo(nl2br($editor9));?></textarea>

    <textarea name="editor10" id="editor10"><?php echo(nl2br($editor10));?></textarea>

    <?php

 if($_SESSION['UserName']=='User')
{
?>
    <input type="submit" name="submit" value="Save">
    <input type="submit" name="submit" value="Submit">
<?php

    }
    if($_SESSION['UserName']=='Manager')
{
    $_POST['submit']="";

if($_POST['submit'] == "Save" || "Submit")
    {
?>
    <input type="submit" name="submit" value="Approve">
    <input type="submit" name="submit" value="Re-Submit">

<?php
    }
    }
    else
    {
?>
<input type="submit" name="submit" value="Re-Submit">
<?php
    }
    ?>

    </form>

 Awami Complex FB-1, Usman Block, New Garden Town, Lahore-54600, Pakistan

PABX: 92(42)35869507 Fax: 92(42)35830425 Email: pacra@pacra.com

www.pacra.com

Here is code in which i face problem
<?php

if($_SESSION['UserName']=='User')
{
?>
    <input type="submit" name="submit" value="Save">
    <input type="submit" name="submit" value="Submit">
<?php

    }
    if($_SESSION['UserName']=='Manager')
{
    $_POST['submit']="";

if($_POST['submit'] == "Save" || "Submit")
    {
?>
    <input type="submit" name="submit" value="Approve">
    <input type="submit" name="submit" value="Re-Submit">

<?php
    }
    }
    else
    {
?>
<input type="submit" name="submit" value="Re-Submit">
<?php
    }
    ?>

A: You are changing $_POST['submit'] to blank here. Use the code below.

remove this line $_POST['submit']="";
And change the following to

<?php
if($_SESSION['UserName']=='Manager')
{

    if($status == 'Approve')
    {
?>
    <input type="submit" name="submit" value="Re-Submit">

<?php
    }
    else
    {
?>
    <input type="submit" name="submit" value="Approve">
    <input type="submit" name="submit" value="Re-Submit">
<?php
    }
}
?>

A: First remove the line
$_POST['submit'] = ""

and change
if($_POST['submit'] == "Save" || "Submit")

to
if(isset($_POST['submit']) && ($_POST['submit'] == "Save" || $_POST['submit'] == "Submit"))

A: You are checking using the OR condition wrongly and you are also resetting the $_POST['submit'] value.  It should be:
<?php

if($_SESSION['UserName']=='User')
{
?>
    <input type="submit" name="submit" value="Save">
    <input type="submit" name="submit" value="Submit">
<?php
}

if(isset($_POST['submit']) && $_SESSION['UserName']=='Manager')
{
    if($_POST['submit'] == "Save" || $_POST['submit'] == "Submit")
    {
?>
        <input type="submit" name="submit" value="Approve">
        <input type="submit" name="submit" value="Re-Submit">
<?php
    }
}
else
{
?>
    <input type="submit" name="submit" value="Re-Submit">
<?php
}
?>


text:
Q: Permission denied when try to write-open a c code file in perl script I got an error of  Permission denied when try to write-open a c code file in perl script. but if I try to read-open the c code file, it works. I check my permission with right clicking the  c file and then properties-security, see that I have both read and write permission. What`s more strange is that if I open the c file in notepad, I can read and write to it, but when I use notepad++, it does not work, it just can read, not write.
Thanks in advance.
help~~
Err.. you are right, it´s read only, seems that it´s a stupid question...anyway, thank you for all your help, nice day!

A: It sounds like the file may be locked by a process.  You can use Sysinternals Process Explorer to determine which process, if any, is locking the file.
Choose Find -> Find Handle or DLL... and search for the file name.

A: Did you check the file attributes?  When you right-click on the c file, look at the bottom of the 'General' tab, is "Attributes: Read-only" checked?  This will override your DACL security.
Read-only might be checked if you copied the file from a CD-ROM or DVD.


text:
Q: Как вызвать цифровую клавиатуру в андроиде? Сразу говорю, InpuType="date" мне не подходит, т.к. хочу вводить дату в формате "дд.мм.гггг", а в стандартном вводится через / и не дает вставить ничего лишнего.
У меня подключен TextWatcher, который подставляет точки в нужных местах, не хватает только цифровой клавиатуры(
A: Думаю подойдет
android:inputType="numberSigned"

A: Соглашусь с @KoVadim что надо использовать стандартные. По идее если указаны региональные настройки, то при вводе должен "подхватывать" правильный разделитель даты.
Если все равно не устраивает, то можно кастомизировать ввод через InputFilter - EditText.setFilters()
A: У меня есть поле для ввода, в котором нужны только цифры, и так же использую TextWatcher для подстановки пробелов между группами цифр. Добавил в EditText
android:inputType="number"
android:digits="0123456789"

При выборе поля выводится только цифровая клавиатура. И пробелы нормально пускает


text:
Q: Button name property not responding to .cs call Error is as follows:

The name "b4" does not exist in the current context

XAML:
<Button x:Name="b1" Click="MainBclick()" Tag="1" Content="Setting Names"/>
<Button x:Name="b4" Content="Setting Usages" Visibility="Collapsed"/>

C#:
private void MainBclick(object sender, RoutedEventArgs e)
{
    var y = ((Button)sender).Tag;
    int x = Convert.ToInt32(y);

    if (x == 1)
    {
        b4.Visibility = Visibility.Visible;
    }
    else { };
}

Basically if a certain button is pressed and its tag is equal to 1 then change the visibility of this other button.
The actual bit of code "b4" in XAML is giving me errors.

A: Below Line is what causing you a Problem:
 <Button x:Name="b1" Click="MainBclick()" Tag="1" Content="Setting Names"/>

you cannot have "()" in your event handler method name
instead use:
<Button x:Name="b1" Click="MainBclick" Tag="1" Content="Setting Names"/>

A: Check if your designer file is properly generated.

A: <Button x:Name="b1" Click="MainBclick" Tag="1" Content="Setting Names"/>

worked for me. Just remove the () from Click event.


text:
Q: Ошибка #1064 в работе с mysql запросом в планировщике событий
Ответ MySQL: #1064 - У вас ошибка в запросе. Изучите документацию по используемой версии MariaDB на предмет корректного синтаксиса около 'UPDATE `credit_cards` SET `dolg` = `dolg` + (`dolg` / 100 * 28)' на строке 7

SELECT @id = (SELECT id FROM `credit_cards` WHERE dolg > 0),
@name = (SELECT name FROM `users` WHERE id = @id),
@names = (SELECT names FROM `users` WHERE id = @id),
@nameo = (SELECT nameo FROM `users` WHERE id = @id),
@bill = (SELECT bill FROM `credit_cards` WHERE id = @id),
@dolg = (SELECT dolg FROM `credit_cards` WHERE id = @id);
UPDATE `credit_cards` SET `dolg` = `dolg` + (`dolg` / 100 * 28)


text:
Q: Dodged dumbbell plots with ggplot2 This question is based on this prior question.
Consider the following plot:

Domain = c("A", "B", "C", "D", "E", "F", "G",
           "A", "B", "C", "D", "E", "F", "G", "A", "B", "C", "D", "E", "F",
           "G", "A", "B", "C", "D", "E", "F", "G")

Area = c("State", "State",
         "State", "State", "State", "State", "State", "National", "National",
         "National", "National", "National", "National", "National", "State",
         "State", "State", "State", "State", "State", "State", "National",
         "National", "National", "National", "National", "National", "National")

race = c("White", "White", "White", "White", "White", "White",
         "White", "White", "White", "White", "White", "White", "White",
         "White", "Black", "Black", "Black", "Black", "Black", "Black",
         "Black", "Black", "Black", "Black", "Black", "Black", "Black",
         "Black")

pct_agreement = c(0.557610213756561, 0.735042750835419,
                  0.567375898361206, 0.633762538433075, 0.64091557264328, 0.750356614589691,
                  0.564539015293121, 0.651861846446991, 0.697574973106384, 0.653521358966827,
                  0.713940441608429, 0.680985689163208, 0.751584351062775, 0.642535984516144,
                  0.488484561443329, 0.581625580787659, 0.456939995288849, 0.580652594566345,
                  0.630399644374847, 0.711643815040588, 0.347775995731354, 0.627996683120728,
                  0.668737232685089, 0.610245823860168, 0.690373718738556, 0.705771028995514,
                  0.738830924034119, 0.550933301448822)

df <- data.frame(Domain, Area, race, pct_agreement)

library(tidyverse)

ggplot(df) +
  geom_point(
    aes(
      x = Domain, y = pct_agreement, color = Area, shape = race,
      group = Area
    ),
    position = position_dodge(width = 1)
  ) +
  coord_flip()

Now we want to turn it into a dumbbell plot by connecting each pair of points of the same domain and area. The obvious code would be the following:
df2 <- pivot_wider(df, names_from = race, values_from = pct_agreement)

ggplot(df) +
  geom_point(
    aes(
      x = Domain, y = pct_agreement, color = Area, shape = race,
      group = Area
    ),
    position = position_dodge(width = 1)
  ) +
  geom_segment(
    data = df2,
    aes(
      x = Domain, xend = Domain, y = White, yend = Black,
      color = Area
    ),
    position = position_dodge(width = 1)
  ) +
  coord_flip()

Created on 2019-11-08 by the reprex package (v0.3.0)
Yet, clearly, that didn't work, because position_dodge() didn't dodge the xend aesthetic. I consider this a bug in ggplot2 that probably should be fixed. However, in the mean time, what's the easiest way of making this plot? I can think of various ways to do it but they all seem cumbersome. Am I missing something?

A: I find nested groupings can often lead to difficulties with specific plots. In these situations I found the interaction() function to be very helpful since it allows for concise code and avoiding the data reformatting. We can define a new grouping for the line segments.
Importantly, the following solution works with position dodging because it uses geom_line() instead of geom_segment(). This avoids the xend aesthetic which position_dodge() can't handle.
ggplot(df) +
  geom_point(
    aes(
      x = Domain, y = pct_agreement, color = Area,
      shape = race, group = Area
    ),
    position = position_dodge(width = 0.5)
  ) +
  geom_line(
    aes(
      x = Domain, y = pct_agreement, color = Area,
      group = interaction(Area, Domain)
    ),
    position = position_dodge(width = 0.5)
  ) +
  coord_flip()

A: I'd define my own x values instead of dodge:
df <- data.frame(Domain, Area, race, pct_agreement) %>%
  mutate(myX = as.numeric(Domain) + ifelse(Area == "State", 0.25, -0.25))

df2 <- pivot_wider(df, names_from = race, values_from = pct_agreement)

ggplot(df) +
  geom_point(
    aes(
      x = myX, y = pct_agreement, color = Area, shape = race, group = Area
    )) +
  geom_segment(
    data = df2,
    aes(
      x = myX, xend = myX, y = White, yend = Black, color = Area
    )) +
  # fix the labels
  scale_x_continuous(name = "Domain", breaks = 1:7, labels = LETTERS[1:7]) +
  coord_flip()

It's also possible to mix the two approaches and dodge the points but use the calculated x values for the segments:
ggplot(df) +
  geom_point(
    aes(
      x = Domain, y = pct_agreement, color = Area, shape = race,
      group = Area
    ),
    position = position_dodge(width = 1)
  ) +
  geom_segment(
    data = df2,
    aes(
      x = myX, xend = myX, y = White, yend = Black, color = Area
    )) +
  coord_flip()

Created on 2019-11-08 by the reprex package (v0.3.0)

A: Using dumbbell (ver 0.11)
A slightly different way of doing this that might be (or might not be) useful to some folks
Thanks you for this challenging question.
##Reformat data
w<-df %>% filter(race=='White')
b<-df %>% filter(race=='Black')
e<-merge(w,b, by.x=c("Domain","Area"), by.y = c("Domain","Area")) %>% unite("id",Domain,Area, remove = FALSE)
e$pct_agreement.x<-as.numeric(format(e$pct_agreement.x, digit=3))
e$pct_agreement.y<-as.numeric(format(e$pct_agreement.y, digit=3))

##Plot
dumbbell::dumbbell(e, id="id",key="Area", column1="pct_agreement.x", column2 = "pct_agreement.y", shp="Area", pointsize = 2, pt_val = 1,delt=1, textsize=3, lab1 = "White", lab2="Black") + xlim(.34,.76)


text:
Q: Unwanted characters when appending a newline in python3 I am appending newline to file if it doesn't exist but it appending unwanted characters.
Input file:
abc

Code to append newline if it does exist:
with open(file_location, 'r') as file:
        data = file.read()
        if not data.endswith('\n'):
            with open(file_location, 'a') as newline_file:
                writer = csv.writer(newline_file)
                writer.writerow('\n')

or alternatively:
with open(local_file_location, 'r') as file:
        data = file.read()
        if not data.endswith('\n'):
            with open(local_file_location, 'a') as newline_file:
                writer = csv.writer(newline_file)
                writer.writerow("\n")

Giving the output below:
abc"
"

I do not want these:
""

I want the output below:
abc

How can I achieve this also let me know what I am doing wrong.

A: You wrote a newline as if it were a row of data, so it got quoted to keep it treated as part of the data, not the end of a row (it's treating the str as an iterable of its characters, where each character is a separate field, exactly as if you called writer.writerow(["\n"])). If you want to make it write the end of a row without writing any fields, pass an empty iterable, e.g.:
writer.writerow([])

Skipping the csv module is a naive solution you should avoid, as CSV is quite sensitive to how newlines are handled, so you do still want to use writerow here, rather than directly writeing to the underlying file.
On the subject of "CSV is quite sensitive to how newlines are handled" your code right now is wrong; the csv module is quite clear that you need to pass newline='' to the open calls so the csv.writer has complete control over how newlines are handled (for example, a newline in a field that's part of the data might be written as '\n', while a newline separating records is '\r\n' in common dialects).
So your code should be:
with open(file_location) as file:  # No newline='' needed since we want the translation
    data = file.read()[-1:]  # Don't store complete file data indefinitely; only care about last character
# May as well remove from with above, we don't need the file to remain open
if not data.endswith('\n'):
    # Use newline='' so csv module controls how end of record is written
    with open(file_location, 'a', newline='') as newline_file:
        writer = csv.writer(newline_file)
        writer.writerow([])  # [] can be replaced with () or '' or any empty iterable if you prefer; [] is easier to see, () is probably fastest by a hair


text:
Q: Select a row and lock it I need to select a row and lock it for a while until a external process ends.
The problem is that I have some threads running at the same time and if I do not lock it in anyway, other thread can take the same row, and that's what i need to prevent.
I've been thinking in update the selected row and set a new field called 'lock' to 1 and prevent others to select it.
Is there any way in making a select with an update?
Thanks.

A: If you're in a 'transaction' (and assuming you're not using any kind of snapshot isolation or other mechanism that either skips locks or reads previous versions), you could technically update any column to it's current value for the given id (or unique key) - that would prevent you from having to add an additional column for locking purposes.
Example: Table1 (Id int, col2 varchar(10), col3...)
BEGIN TRANSACTION
UPDATE Table1 SET col2=col2 WHERE ID = ?

That session would lock that row until a commit or rollback occurs.  The locking session is able to freely read the locked row.
You should be able to prototype that by creating a test table, insert a few rows, begin a transaction and update one of the rows without committing and then bring up another SSMS window and try to access that row.  The second session should remain blocked until the first session commits or rolls back.
Be aware that any processes (other than the locking process) that require table scans of this table will also be blocked until commit or rollback.

A: I found a better solution for my case.
The fact is that I did not know that from operations like insert, update and delete, you can request fields from affected rows using the operator OUTPUT.
In my case, this is the query that permits me to lock (using a field) a row from other queries:
UPDATE TOP (1) dbo.list_objects
SET locked=1
OUTPUT inserted.ID,
       inserted.url_image
WHERE linked=0 AND error=0 AND locked=0

That query, supply me the fields needed to work with and prevent other threads to getting such row while it being processed.


text:
Q: In GWT 2.5, how do I populate multiple parts of a cell based up AbstractCell I have a class ContactCell based on AbstractCell.
It has two Labels and one Image (defined in GWT 2.5's UiBinder).
How do I Column.addColumn() to add a this custom cell to a CellTable?
And If so, how do I use the method getValue() to populate the fields of ContactCell when getValue() only returns simple values (such as String).
Column<Contact, String> column = new Column<Contact, String>(
    new ContactCell()) {
  @Override
  public String getValue(Contact object) {
    return object... CAN ONLY RETURN ONE VALUE. HOW TO POPULATE 2 LABELS & IMAGE?
  }
};

A: You can change the render string by overridding the onrender mathod of the cell as follows.
Assuming 2 labels and a image can be computed from the value returned by getValue mathod.
ContactCell contactCell = new ContactCell()
{
    @Override
    public void render( com.google.gwt.cell.client.Cell.Context context, SafeHtml value, SafeHtmlBuilder sb )
    {

    // do value check and compute label1 and label2 and calso compute the image path.

    sb.appendHtmlConstant( "LABEL1" +"LABEL2"+"<image></image>" )
    }
});

Column<Contact, String> column = new Column<Contact, String>( contactCell )
{
  @Override
  public String getValue(Contact object)
  {
    return object... CAN ONLY RETURN ONE VALUE. HOW TO POPULATE 2 LABELS & IMAGE?
  }
};

A: You can either use an IdentityColumn instead of a normal Column  (will pass through the entire Contact object) or you use a normal Column like this:
Column<Contact, String[]> column = new Column<Contact, String[]>(
    new ContactCell()) {
  @Override
  public String[] getValue(Contact object) {
    String[] retvalue = new String[2];
    retvalue[0] = "SOMETHING";
    retvalue[1] = "SOME OTHER THING";
    return retvalue;
  }
};

A: If the cell based on AbstractCell is defined using UiBinder then it's not currently (GWT 2.5) possible to add such cells to a CellTable.


text:
Q: Use proposition 2 to prove proposition 1. Would you correct my proof? PROPOSITION 1:  If $f:U\subset \mathbb{R}^2\rightarrow \mathbb{R}$ is a differentiable map, where $U$ is an open subset of $\mathbb{R}^2$, then a graphic of $f$, given by $(x, y, f(x,y))$, where $(x,y)\in U$ is a regular surface.
PROPOSITION 2: If $f:U\subset \mathbb{R}^3\rightarrow \mathbb{R}$ is a differentiable map and $a\in f(U)$ is a regular value of $f$, then $f^{-1}(a)$ is a regular surface in $\mathbb{R}^3$.
DEFINITION: Given a differentiable map $F:U\subset \mathbb{R}^n \rightarrow \mathbb{R}^m$ defined in an open set $U$ of $\mathbb{R}^n$ we say that $p\in U$ is a critical point of $F$ if the differential $dF_p:\mathbb{R}^n\rightarrow \mathbb{R}^m$ is not a surjective (or onto) mapping. The image $F(p)\in \mathbb{R}^m$ of a critical point is called a critical value of $F$. A point of $\mathbb{R}^m$ which is not a critical value is called a regular value of $F$.
MY ATTEMPT:
Define $h:U\subset\mathbb{R}^3\rightarrow \mathbb{R}$ given by $h(x, y, z)= f(x, y)-z$ where $f$ is differentiable. Note that $$\nabla h = (h_x(x, y,z), h_y(x, y,z), h_z(x, y,z))= (f_x, f_y, f_z)=(f_x, f_y, -1) \implies \nabla h(p) \neq 0,\; \forall p.$$
Therefore, $(0,0,0)$ is a regular value of $h$. Now, note that
\begin{align*}
h^{-1}(0)&=\{(x, y, z); h(x, y, z)=0\}\\
&=\{(x, y, z); f(x, y)=z\}\\
&=\{(x, y, f(x, y))\}:=\text{graphic of}\; f
\end{align*}
Thus, by proposition 2, graphics of differentiable functions are regular surfaces.

A: MY ATTEMPT:
Define $h:U\subset\mathbb{R}^3\rightarrow \mathbb{R}$ given by $h(x, y, z)= f(x, y)-z$ where $f$ is differentiable. Note that $$\nabla h = (h_x(x, y,z), h_y(x, y,z), h_z(x, y,z))= (f_x, f_y, f_z)=(f_x, f_y, -1) \implies \nabla h(p) \neq 0,\; \forall p.$$
Therefore, $(0,0,0)$ is a regular value of $h$. Now, note that
\begin{align*}
h^{-1}(0)&=\{(x, y, z); h(x, y, z)=0\}\\
&=\{(x, y, z); f(x, y)=z\}\\
&=\{(x, y, f(x, y))\}:=\text{graphic of}\; f
\end{align*}
Thus, by proposition 2, graphics of differentiable functions are regular surfaces.


text:
Q: stream_resolve_include_path returning false? I have a fieldset that is implementing InputFilterProviderInterface. My getInputFilterSpecification function looks like this:
public function getInputFilterSpecification() {
    $validator = new \Zend\Validator\File\Extension([
        'jpg',
        'jpeg',
        'png',
        'gif',
    ]);
    return [
        [
            'name' => 'logo',
            'required' => false,
            'validators' => [
                $validator,
            ],
        ],
    ];
}

As you can guess, I am trying to validate the file upload by extension.
My problem is that the validator is giving the error message

File is not readable or does not exist

Looking into the Extension class I found the function that's causing the issue: stream_resolve_include_path($file). When I var_dump $file I get the following output:

C:\Windows\Temp\php6BE7.tmp

So... Why is stream_resolve_include_path failing to resolve this path? How do I fix it?
This is currently running on a Windows Virtual Machine. Is this part of the problem? i.e. the above function only works on compatible operating systems?

A: Short term solution - extend the validator and overwrite the isValid function.
Find the line:
if (empty($file) || false === stream_resolve_include_path($file)) {
and replace it with:
if (empty($file) || false === is_file($file)) {


text:
Q: module 'minisam' has no attribute 'DiagonalLoss' I am using PyICP github repo. I built the Sophus from this commit (commit a0fe89a323e20c42d3cecb590937eb7a06b8343a) Reference.
I am using Ubuntu 22 and used virtual environment (venv with python version 3.7.14) to build the PyICP repo, minisam and Sophus repo.
Finally when I run the command  python3 main_icp_slam.py it runs in this error.
(venv) shubham@shubhamubuntu:~/Lidar_Slam/minisam$ python3 main_icp_slam.py  Traceback (most recent call last): File "main_icp_slam.py", line 50, in <module> PGM = PoseGraphManager() File "/home/shubham/Lidar_Slam/minisam/utils/PoseGraphManager.py", line 9, in __init__ self.prior_cov = minisam.DiagonalLoss.Sigmas(np.array([1e-6, 1e-6, 1e-6, 1e-4, 1e-4, 1e-4]))  AttributeError: module 'minisam' has no attribute 'DiagonalLoss' (venv) shubham@shubhamubuntu:~/Lidar_Slam/minisam$ python3 main_icp_slam.py
The image view of this error is HERE
I am not sure is it caused by Sophus, Eigen, Venv or minisam.
Let me know if anymore information is needed.
Thanks, for any and all the help.

A: It is probably because you have multiple versions of python on your system and you have installed minisam on another python version. When you run cmake (for installing minisam) look at the version it shows for the python executable and also check your root python version (or environment that you are using), they should match.
If they don't match either make an environment with the python version your minisam is installed on or run your code as follows: (let say it is installed on python 3.6)
$ python3.6 main_icp_slam.py


text:
Q: Is "allopathy" pejorative? Is using the term "allopathy" to describe mainstream (i.e. real) medicine, pejorative?  I know the term was originally used by homeopaths to insult real medicine, but I have heard it being used more and more lately, and am curious if there is still a pejorative sense to the term.

A: In India, most usages of "allopathy" that I have seen are not pejorative. I don't think I have seen a pejorative use of "allopathy" in common usage so far. I have also seen it used by government officials non-pejoratively. For example, here are some articles from mainstream newspapers of India:

*

*90% of Indians prefer allopathy over AYUSH - The Times of India, July 8, 2015. ("AYUSH" comprises a bunch of alternative medicine systems: Ayurveda, Yoga, Unani, Siddha and Homoeopathy. There's even a ministry for it.)

*WHO report sounds alarm on 'doctors' in India
The Hindu, July 18, 2016:

Speaking to The Hindu, Dr. Reena Nayyar, Secretary of the Medical
  Council of India (MCI), said, "I don't think this report has
  officially come to the MCI yet. But in general, any person practising
  allopathic medicine who does not have a registered medical
  qualification comes under quackery."

The MCI establishes standards of medical qualifications in India.

*Now, unani, ayurveda practitioners can prescribe allopathy medicines, perform surgeries - The Indian Express, February 28, 2014.

*Army to throw open doors to alternative medicine - Hindustan Times, January 25, 2016:

"Mainstream doctors have traditionally resisted alternative medicine
  treatment. But let's be frank, we really don't have the domain
  knowledge to dismiss it. The idea behind the experiment is to see if
  alternative medicine can work where allopathy has no answers," said
  Lieutenant General BK Chopra, director general, Armed Forces Medical
  Services (AFMS).

You can safely use "allopathy" to talk about mainstream medicine in India without accidentally belittling it.

A: Consider conventional medicine (cancer.gov) as a more neutral alternative:

A system in which medical doctors and other healthcare professionals (such as nurses, pharmacists, and therapists) treat symptoms and diseases using drugs, radiation, or surgery. Also called allopathic medicine, biomedicine, mainstream medicine, orthodox medicine, and Western medicine.

A: The word has no real meaning outside of the context of homeopathy. It's rather pejorative in that context. It's rather irrelevant in any other.

A:
There are two kinds of practicing physicians in the United States:
  allopathic physicians (MD's) and osteopathic physicians (DO's). Both
  are fully licensed physicians, trained in diagnosing and treating
  illnesses and disorders, and in providing preventive care.

-Indiana University Bloomington web page

Modern medicine generally refers to clinical practice: the diagnosis,
  treatment and prevention of disease by a physician. That physician may
  be an allopathic physician (M.D.) or an osteopathic physician (D.O.).

-Explore Health Careers web page
It seems to me that these web pages intend to use neutral language.
Apparently, osteopathy is a later development than allopathy, and a reaction to allopathy, intended to promote whole-body health and preventive strategies and to reduce treatment with medicine. The distinction does still exist today, both in training and in practice; but in general allopaths and osteopaths perform the same roles (prescribing drugs, performing surgery, etc.) in every state, and they often make similar decisions.
In my personal experience in a family of MD's, the culture of medicine is like this: MD's and DO's consider each other to be equals in the first rank of competence. For example they would be likely to assume that an ophthalmologist (regardless of whether he is an MD or a DO) would be preferable to an optometrist. And they would generally consider in one category such people as acupuncturists, chiropractors or homeopaths, people who apparently have an occasional success for reasons that nobody really understands, and so are worth considering for a patient who cannot be treated successfully and wants to try that route.

A: Allopathy is mostly used pejoratively. But in the United States it sometimes is used non-pejoratively. The connotation depends on context.
In its literal sense, allopathy is not pejorative. It is a technical term, part of an unscientific disease theory that "like cures like". It was coined by Samuel Hahnemann (in German, later borrowed into English). It was part of his classification system of all drug treatments according to the symptoms the drugs would be expected to cause in a healthy person:

*

*homeopathic treatments produce symptoms resembling those produced by the disease (hómoios, "resembling")

*enantiopathic treatments produce symptoms opposite to those produced by the disease (enantíos, "opposing")

*allopathic treatments produce symptoms neither resembling nor opposite to those produced by the disease (állos, "other")
But in practice, allopathy is used by Hahnemann's disciples as a dismissive label for all medical practices that do not follow the "like cures like" theory, and therefore are supposedly useless or harmful. In the same way, someone might dismissively refer to surgery they consider useless or harmful as butchery or bloodletting. (At one time, bloodletting was common medical practice, based on the unscientific theory that the cause of disease is imbalance of bodily fluids.*)
Recently in the United States, the term allopathic medicine has begun to be used with no pejorative connotation as an antonym of osteopathic medicine. In this context, allopathic medicine means medicine as practiced by Doctors of Medicine, and osteopathic medicine means medicine as practiced by Doctors of Osteopathy. This is arguably a very loose or figurative usage, because osteopathic is not opposite to allopathic – it is not a Hahnemann classification at all. Osteopathic treatments were based on yet another unscientific theory, that disease is caused by problems in the bones and muscles and can be reversed by manipulating joints and tissues. Arguably Hahnemann would have considered osteopathy just another useless allopathic practice.
For more information, see the Wikipedia articles "Homeopathy", "Allopathic medicine", and "Osteopathic medicine in the United States".

* "You know, medicine is not an exact science, but we are learning all the time. Why, just fifty years ago, they thought a disease like your daughter's was caused by demonic possession or witchcraft. But nowadays we know that Isabelle is suffering from an imbalance of bodily humors, perhaps caused by a toad or a small dwarf living in her stomach." ("Theodoric of York, Medieval Barber", Saturday Night Live, season 3, episode 18)

A: About the only practical use for allopathic is to split the MDs off from the DOs.  Both groups practice essentially the same kind of medicine nowadays, but for historical reasons many U.S. states will have two Boards of Medicine (BOM), a Board of Allopathic Medicine and a Board of Osteopathic Medicine. Most DOs spend most of their time practicing allopathic medicine and, one could argue, that an MD physiatrist who uses massage to aid in recovery from a reconstructive procedure is practicing manipulative, i.e. osteopathic, medicine.
Not all states will have two BOMs, (e.g. Arizona) and in those states the term "Board of Medical Examiners" is often used. It would issue medical licenses to both MDs and DOs.
Just to put the final nail in this linguistic coffin, surgeons are not always addressed as "Doctor" in the UK.


text: Q: Amazon SP API - Failing to upload feed I am working on feeds API(SP API). I successfully finished calling createfeeddocument and in response I got the feeddocumentid and url, using the url I need to upload the feed document. so when I am trying to upload a xml, I get "The remote server returned an error: (403) Forbidden.." . I checked my developer profile and I have all the permissions checked. Not sure what I am missing, can some body please guide as to what this could be referring. I checked the contenttype.... it matches with what I sent in createfeeddocument.


text:
Q: suggested actions inside waterfall step
I am using Bot Framework .Net SDK v4 and direct line web chat client. I have my dialogs as waterfall steps. Is it possible to use a suggested action inside a waterfall step?   I am aware that a choice prompt will serve the purpose  but I want the buttons to disappear after user clicks any choice, hence want to use suggested actions.
What I have tried.

In the constructor :
AddDialog(new ChoicePrompt(nameof(ChoicePrompt)));

In waterfall step:

  public async Task<DialogTurnResult> FirstStepAsync(WaterfallStepContext stepContext, CancellationToken cancellationToken)
        {
            var promptOptions = new PromptOptions()
            {
                Prompt = MessageFactory.Text("What card would you like to see? You can click or type the card name"),
                RetryPrompt = MessageFactory.Text("That was not a valid choice, please select a card or number from 1 to 9."),
                Choices = GetChoices(),
                Style = ListStyle.SuggestedAction
            };

            return await stepContext.PromptAsync(nameof(ChoicePrompt), promptOptions);

        }

        private IList<Choice> GetChoices()
        {
            var cardOptions = new List<Choice>()
            {
                new Choice() { Value = "Card 1", Synonyms = new List<string>() { "adaptive" } },
                new Choice() { Value = "Card 2", Synonyms = new List<string>() { "animation" } },
            };
            return cardOptions;
        }

A: in the the prompt options you can specify you choices style :
var promptOptions = new PromptOptions {
  Prompt = (Activity) MessageFactory.Attachment(card.ToAttachment()),
  Style = ListStyle.SuggestedAction
};
return await stepContext.PromptAsync(nameof(ChoicePrompt), promptOptions, cancellationToken);

// Auto: Automatically select the appropriate style for the current channel.
// HeroCard: Add choices to prompt as a HeroCard with buttons.
// Inline : Add choices to prompt as an inline list.
// List : Add choices to prompt as a numbered list.
// None: Don't include any choices for prompt.
// SuggestedAction: Add choices to prompt as suggested actions.

source


text:
Q: Trying to make a fetch request to a XML link with React getting CORS error import './App.css';

function App() {

 fetch('https://basketball.realgm.com/rss/wiretap/0/0.xml')
.then(response => response.text())
.then(str => new window.DOMParser().parseFromString(str, "text/xml"))
.then(data => console.log(data))

return (
<div className="App">
</div>
);
}

export default App;

So I am trying to do a simple fetch request to this XML link and I keep getting this Error:
Access to fetch at 'http://basketball.realgm.com/rss/wiretap/0/0.xml' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

A: In order to make requests to any origin other than the current one, the server must return a Access-Control-Allow-Origin header with the requesting origin.
For example, a request from localhost to example.com:
GET / HTTP/1.1
Host: example.com

With the response:
HTTP/1.1 200 OK
Access-Control-Allow-Origin: localhost
...


text:
Q: WebView using Chart.js cannot convert to Bitmap I'm working on an application that, apart from other things, have a news section, where every new is a WebView, and you can share them by Intent in your social media.
Here's how I create the Bitmap from the WebView, it's working on most of the cases, but if the WebView uses the library Chart.js it only works in a few devices, in the other ones
the chart itself is completely blank (the other HTML views, like texts, are fine). If the WebView doesn't use the library Chart.js, it works on every device.
binding.wvContent.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
val contentBitmap = getBitmapFromView(binding.wvContent)

private fun getBitmapFromView(view: View): Bitmap? {
    val result = Bitmap.createBitmap(
        view.measuredWidth,
        view.measuredHeight,
        Bitmap.Config.ARGB_8888
    )
    val canvas = Canvas(result)
    view.layout(view.left, view.top, view.right, view.bottom)
    view.draw(canvas)
    return result
}

I have the android:hardwareAccelerated="true" line in the Android Manifest, and WebView.enableSlowWholeDocumentDraw() in the App init, as well as binding.wvContent.settings.javaScriptEnabled = true
before loading its Url.
Thanks!
Mauricio


text:
Q: Emulate FTP Connection for my program I'm writing a program in C# which will connect to an FTP location and read an XML file, and want to test this locally.
How might I go about creating an FTP site on my machine so that I can do this?
My program's code (probably not necessary to answer this question?) is:
    private string LoadFTPFile()
    {
        string xml = null;
        string ftpAddress = "ftp://" + ftpLocation + "/" + PrintMachineParameters_BaseName + ".xml";
        try
        {

            logging.Write("Info", "LoadFTPFile()", "XML loaded from PLC: " + ftpAddress);

            WebClient request = new WebClient();
            request.Credentials = new NetworkCredential(ftpUserName, ftpPassword);
            byte[] fileData = request.DownloadData(ftpAddress);

            xml = System.Text.Encoding.Default.GetString(fileData);

            try
            {
                XmlDocument xmlDoc = new XmlDocument();
                xml = xml.Substring(xml.IndexOf("<"));
                xmlDoc.LoadXml(xml);
                XmlNode xmlNode = xmlDoc;
                xml = xmlNode.InnerXml;
            }
            catch (Exception exception)
            {
                string message = "Error loading FTP file: " + ftpAddress + Environment.NewLine;
                DisplayException("Error loading FTP file", message, exception);
                xml = null;
            }

        }
        catch (Exception exception)
        {
            string message = "Error loading FTP file: " + ftpAddress + Environment.NewLine;
            DisplayException("Error loading FTP file", message, exception);
            xml = null;
        }

        return xml;
    }

Thanks.

A: Install an FTP server like FileZilla, it's a free FTP server and works well for me :)
https://filezilla-project.org/download.php?type=server

A: Create your own on your local machine.
If you don't want to install FTP software (for whatever reason), use IIS:
http://www.iis.net/learn/publish/using-the-ftp-service/creating-a-new-ftp-site-in-iis-7


text:
Q: Best strategy for backing up your own scripts? ---asked already on unix.StackExchange, but closed (too subjective)---
Rewritten for clarity.

*

*I want to write scrips for my own use

*I want to be able to back them up

*I haven't yet established the backup routine - gonna write a script.

*it will be my 4th script, and my first serious approach to backing up (so be gentle).

What is the most effective strategy, given that two factors seem to be in tradeoff:

*

*Among several options, /usr/local/bin is widely advocated as
most advantageous location for custom scripts, (but not uniquely; see ideas below)

*

*Where should I put my script so that I can run it by a direct command?

*Where should I put my script?

*Best directory to place my bash scripts?

*/usr/local/bin is full of other, automatically generated files, files (e.g. Dropbox, etc) that I would not want to take into a backup and hence would have to figure out a way to filter (not a trivial task for my skill level, though I'm willing to learn).
Do I attack this from the "directory end" (e.g. 'don't use that directory, use this one!') or from the "backup script end" (e.g. an effective filter I could use with tar or cp or whatever to extract my script files from the crowd in /usr/local/bin).
I can't find anyone talking about both of these things in the one place (but "backup" and "scripts" swamps results with "backup scripts" so maybe I've missed it.)
Cheers - thanks for the constructive answers so far.
PS - see also an earlier version of this question elsewhere for a couple of helpful replies before shutdown.

A: You mentioned two things, which I don't believe are good solutions:
"Created by":
Standard Linux file attributes include an owner user and group. I strongly recommend you make sure all files in /usr/local/bin (or actually almost all directories that contain stuff to be accessed by all users) are owned by root as user and group, and also only writable by the owner. This is a security measure that should prevent unprivileged modifications to the file, which might later be executed by someone else or with elevated privileges using sudo.
So as the owner of all those scripts in /usr/local/bin should be root, we can't use that to distinguish the scripts you want to back up.
"Subdirectory":
Executables inside subdirectories of /usr/local/bin would not be accepted by the system as commands which you can run directly without a path. The reason is that for this, an executable needs to be directly inside a directory listed in the $PATH environment variable. Subdirectories are not automatically included here, each location needs to be explicitly specified - again, as a security improvement to lower the risk of accidentally executing untrusted code.
Although it would be possible to add that subdirectory in all necessary locations, I'd refrain from changing all users' $PATH (and not to forget, the /etc/sudoers configuration's secure_path must include the new directory too, if you want it accessible when using sudo).

Now what could you do instead? Here are a few ideas:
User-specific bin directory:
If you don't need those scripts system-wide for all users, but only for your own account, simply put them into ~/bin (~ being your home directory). This location is only on your own user's $PATH, not of anyone else. For your personal scripts, this should be the simplest way.
Keep in mind that you need to restart your current shell once (close and reopen the terminal window, type source ~/.profile or log out and back in) if you just created the directory during your current session. This is because the directory is added only if it exists when the shell initializes itself. You don't ever have to do this again later on.
Keep a list of your scripts:
Simply have a text file somewhere listing the paths of all of your scripts/files which you want to back up. Then you can simply process this list with another script/command like the one below to copy them all to your backup directory:
#!/bin/bash
backupdir=~/backup/scripts
listfile=~/backup/script-list.txt
while read line ; do
    cp -- "$line" "$backupdir"
done < "$listfile"

You just have to keep the list file (here ~/backup/script-list.txt) updated and well formatted. In this simple version, you must make sure that each line contains exactly one absolute path to a file you want to back up, with no leading or trailing spaces and no empty lines. Of course the script could be improved to be able to handle such cases, but this is just a quick prototype.
Add a "signature" to your own scripts, and only back up those containing it:
Just think of a unique string you add to all of your own scripts, e.g. in a comment. That could look like *** CREATED BY BYTECOMMANDER *** or so, maybe even more unique. Then you can make a backup script that scans /usr/local/bin for files containing your signature line and only copies those, leaving others alone:
#!/bin/bash
backupdir=~/backup/scripts
signature="*** CREATED BY BYTECOMMANDER ***"
for scriptfile in /usr/local/bin/* ; do
    if grep -qF "$signature" "$scriptfile" ; then
        cp -- "$scriptfile" "$backupdir"
    fi
done


text:
Q: Variable as a suffix? I was trying out stuff in order to try using classes and i came up with this code to remember orders from tables.
But I got into a pickle trying to put too many variables inside a definition, and asked myself if it was even possible to have a variable as a suffix (so as a 'randomname'.variable)
class Nourriture:
    def __init__(self, entree, meal, dessert):
        self.entree = entree
        self.meal = meal
        self.dessert = dessert

John = Nourriture('poire à l\'anglaise','foie gras et entrecôte', 'creme brulée')
Marty = Nourriture('poire à la francaise','foie maigre et entrejambe', 'creme brulée')
Marie = Nourriture('rien','rien','rien')
Camille = Nourriture('rien','rien','crepe')

Tables = {
    'table1' : [John, Marty, Marie],
    'table2' : [Camille]
}

def repasorder (plat, tablenumber):
    return [Tables[tablenumber][i].plat for i in Tables[tablenumber]]

print(repasorder('meal','table1'))

(sorry some bits are in french)
I wanted to know how i could make this whole code work, I am aware there might be other problems in my code but I am pretty much stuck.
A bit of help is welcomed :D


text:
Q: error during the import of the files for MaaS with its stable release via ppa after I've added the stable release of Maas via ppa on my Ubuntu 14.04lts Svr and made the upgrade, during the import of its images file using the command:
$: sudo maas-import-pxe-files

I've received the following error:
Traceback (most recent call last):
  File "/usr/sbin/maas-import-pxe-files", line 18, in <module>
    from provisioningserver.import_images.boot_resources import (
  File "/usr/lib/python2.7/dist-packages/provisioningserver/import_images/boot_resources.py", line 35, in <module>
    from provisioningserver.boot import BootMethodRegistry
  File "/usr/lib/python2.7/dist-packages/provisioningserver/boot/__init__.py", line 30, in <module>
    from provisioningserver.kernel_opts import compose_kernel_command_line
  File "/usr/lib/python2.7/dist-packages/provisioningserver/kernel_opts.py", line 24, in <module>
    from provisioningserver.driver import ArchitectureRegistry
  File "/usr/lib/python2.7/dist-packages/provisioningserver/driver/__init__.py", line 27, in <module>
    from provisioningserver.utils.registry import Registry
  File "/usr/lib/python2.7/dist-packages/provisioningserver/utils/__init__.py", line 57, in <module>
    from crochet import run_in_reactor
ImportError: No module named crochet

while, without to make the upgrade it works perfectly.
its there someone who had the same my problem and resolved it?
thanks in advance for support and for any other suggests.

A: It is missing the dependency - python-crochet. Had similar problem and it was solved by doing this. More on the solution can be found on https://bugs.launchpad.net/ubuntu/+source/maas/+bug/1311765.


text:
Q: EXCEL Copy & Concatenate from one document to another I am having trouble figuring out how to reformat an exel sheet into 4 different sheets.
As of now, I have to documents, one with data and one that needs the others' data reformatted.
Here is the background:

*

*The first document has a 48 rows (groups of 4) for each (12)month of the year

*The according columns are from the years 2012-1950

*ex.--> First row is JANUARY with precipitation values for years 2012, then 2011, 2010, etc.

*ex.--> Second row is JANUARY with maxTemp values for the same years

*The third row is the same with minTemp and the fourth avgTemp; then these 4 are repeated 12 times

*I need to copy & concatenate all of the months for one data type

*(in reverse order so that the data is instead from Jan1950-Jan2012)

*And paste it into a new row in 1 of 4 excel docs (one for each data type)

*So that one final row will contain ex precipitation Jan1950, Feb1950, March1950 ... Nov2012, Dec2012

*This way, one row will have 12(months)*62(years) IN ORDER from Jan1950 to Dec 2012

*Basically there will be 4 excel documents each with one really long row

Here are my thoughts
(Unless there is a better way) I was wondering if there is a macro (or a formula) that will:

*

*Take part of a row in reverse order (ie. Z3-C3) corresponding to Precip of Jan1950-Jan2012

*Copy it and concatenate it with...

*The same part of another row in reverse order (ie. Z7-C7) corresponding to Precip of Feb1950-Feb2012

*Another row in reverse order (ie. Z12-C12) corresponding to Precip of Mar1950-Mar2012

*Repeat for all 12 months

*paste them into the precipitation excel document

*This needs to be done for all four data types (ie. Z4-C4 is minTemp Jan 1950-2012; Z8-C8 Feb; etc.)

which once again yields, one row with data from Jan1950-Dec2012 for just that data type

A: Update
I have tested the VBA Method below and it fails (for me) due to a column limitation, so unless you have a 64bit version (or possibly a version later than 2003) of excel you wont be able to do it using columns. I have modified the VBA version to use rows instead of columns and it works fine.
I've made a demo of both versions here : https://dl.dropbox.com/u/14854735/ptdata.xls
VBA Method (easy/quick)
The following is untested. Create a copy of your workbook to work on, open the code editor and paste the following into a new code module (not the workbook or worksheet code sections).
Const ROW_HEADER = 1 ' No Row Header - Set to 0
Const COL_HEADER = 1 ' No Column Header - Set to 0

Sub FormatDocument()
' This sub assumes the following
' Your source worksheet has column headers (row 1)
' Your source worksheet has row headers (column 1)
' So your data is bound by the range $B$2:$BL$49
' See above constants if this is not the case
' Your source sheet must be the active sheet when you run this sub (unless you edit below)
Dim Source As Worksheet
Dim Destination As Worksheet

Dim Pass As Integer
Dim CYear As Integer
Dim CMonth As Integer
Dim Column As Integer

Set Source = Thisworkbook.ActiveSheet ' If possible change this to the name of the source sheet

For Pass = 1 To 4
    Set Destination = ThisWorkbook.Worksheets.Add
    Column = 1
    For CYear = (63 + ROW_HEADER) To (1 + ROW_HEADER) Step -1
        For CMonth = 0 To 11
            Destination.Cells(Column, 1).Value = Source.Cells(COL_HEADER + Pass + (CMonth * 4), CYear).Value
            ' NOTE: I've switched the row and column
            ' It will now use many rows and a single column
            ' Destination.Cells(1, Column).Value = Source.Cells(COL_HEADER + Pass + (CMonth * 4), CYear).Value
            Column = Column + 1
        Next
    Next CYear
Next Pass

End Sub

Formula Method
the following formula should be pasted into your destination sheet(s) and copied across into all required cells (after modifying it to take the desired value type). this is essentially mapping a 2-d array (your data) onto a 1-d array.
=INDIRECT(ADDRESS(((((COLUMN()-1)-(12*INT((COLUMN()-1)/12))))*4)+2,64-INT(COLUMN()/12),1,TRUE,"SourceSheet"))

I've updated the formula and it should now work as expected, however is still limited by column count (Jan1950-Apr1971 is as much as I could get in)
This code should also take column and row headers into account, if you do not need them then +1+n becomes +0+n and 64-INT(COLUMN()/12)+1 becomes 64-INT(COLUMN()/12)+0
.
Hint for future questions: If you've tried to make a solution yourself (actual code or formula, not just an outline) you should include it in your question. so we can see you've had a go yourself :)