text:
Q: Regex.Split on two chars Input string is: name = valu\=e;
I want to split it with Regex to: name and valu\=e;.
So split expresion should split on char = which is not prefixed by \.
I want to keep spaces after name or before valu\=e etc. Couldn't it show here because SO trims ``.
EDIT: Input string can contains many name=value pairs. Example: name=value;name2=value2;.

A: You can use this pattern:
@"(?<!\\)="

(?<!..) is a negative lookbehind assertion and means:"not preceded by"
Heinzi question is interesting. If you choose that an even number of backslashes doesn't escape the equal sign, you must replace the pattern by:
@"(?<![^\\](?:\\{2})*\\)="

A: (?<name>[^=]+)=(?<value>[^;]+;)

then use the named groups "name" and "value" to retrieve each part separately.
e.g:
var matches = System.Text.RegularExpressions.Regex.Matches("myInput", @"(?<name>[^=]+)=(?<value>[^;]+;)");
        foreach(Match match in matches)
        {
            var name = match.Groups["name"];
            var value = match.Groups["value"];
            doSomething(name, value);
        }

EDIT:
I don't know why you say it won't work, here is what I get in LinqPad using the input you gave me in the comments:
void Main()
{
var matches = System.Text.RegularExpressions.Regex.Matches(@"zenek=ben\\\;\\ek;juzek=jozek;benek2=true;krowa=-2147483648;du-pa=\\\\\\3/\\\=3\;3\;;", @"(?<name>[^=]+)=(?<value>[^;]+;)");
        foreach(Match match in matches)
        {
            var name = match.Groups["name"].Value;
            var value = match.Groups["value"].Value;
            ("Name: "+name).Dump();
            ("Value: "+value).Dump();
        }
}

Results:
Name: zenek
Value: ben\\\;
Name: \\ek;juzek
Value: jozek;
Name: benek2
Value: true;
Name: krowa
Value: -2147483648;
Name: du-pa
Value: \\\\\\3/\\\=3\;

A: Instead of using regular expressions, you might use 'regular' code. :)
string items = "name=value;name2 = valu= = e2";

// Split the list on items.
var itemlist = items.Split(';');
// Split each item after the first '='.
var nameValueArrayList = itemlist.Select(s => s.Split("=".ToCharArray(), 2));
// Convert the list of arrays to a dictionary
var nameValues = nameValueArrayList.ToDictionary(i => i[0], i => i[1]);

MessageBox.Show("<<<" + nameValues["name2 "] + ">>>");

Or in short:
string items = "name=value;name2 = valu= = e2";

var nameValues = items
    .Split(';')
    .Select(s => s.Split("=".ToCharArray(), 2))
    .ToDictionary(i => i[0], i => i[1]);

MessageBox.Show("<<<" + nameValues["name2 "] + ">>>");

I personally think that code like this is easier to maintain or pull apart and modify when the specs change. And it gives you an actual dictionary from which you can pull values by their key.
Maybe it's possible to write this even a little shorter, but I'm still practicing with this. :)


text:
Q: Add detail text on label of custom UITableViewCell There are other similar questions here but none of those answer what I'm looking for.
I have a settings screen that should look like this:

I have added new UITableViewCell class and connected it to main table with this code:
static NSString *cellIdentifier = @"settingCellIdentifier";
SettingsTableViewCell *cell = (SettingsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

if (cell == nil){

    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SettingsTableViewCell" owner:self options:nil];
    cell = [nib objectAtIndex:0];
}

I know we set table style to UITableViewCellStyleSubtitle to add detail text, but the only way I know to do that is this:
cell = [[UITableViewCell alloc]
            initWithStyle:UITableViewCellStyleSubtitle
            reuseIdentifier:SimpleTableIdentifier];

I can't use this code in my case.
Currently I'm using two labels, and it has brought the following mess:

Following is cellForRowAtIndexPath code:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"settingCellIdentifier";
SettingsTableViewCell *cell = (SettingsTableViewCell *)[tableView dequeueReusableCellWithIdentifier:cellIdentifier];

if (cell == nil){

    NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"SettingsTableViewCell" owner:self options:nil];
    cell = [nib objectAtIndex:0];
}

NSInteger row = indexPath.row;

switch (row) {
    case 0:
        cell.settingLabel.text = @"Settings";
        cell.subText.text = @"";
        break;
    case 1:
        cell.settingLabel.text = @"Account Info";
        cell.subText.text = @"Display your Home Business account information";
        break;
    case 2:
        cell.settingLabel.text = @"Sign Out";
        cell.subText.text = @"Signed in as ";
        break;
    case 3:
        cell.settingLabel.text = @"Send Feedback";
        cell.subText.text = @"Send comments, requests or error reports to Home Business";
        break;
    case 4:
        cell.settingLabel.text = @"Terms of User";
        cell.subText.text = @"";
        break;
    case 5:
        cell.settingLabel.text = @"Privacy Policy";
        cell.subText.text = @"Your privacy and security are our top priorities";
        break;
    case 6:
        cell.settingLabel.text = @"Like us on Facebook";
        cell.subText.text = @"";
        break;
    case 7:
        cell.settingLabel.text = @"Follow us on Twitter";
        cell.subText.text = @"";
        break;
    case 8:
        cell.settingLabel.text = @"About Us";
        cell.subText.text = @"";
        break;

    default:
        break;
}

return cell;
}

I need to know how I can add detail text with only one label.

A: Why do you need a custom cell? Just use normal tableview cell and its textLabel & detailTextLabel. This will serve your need. You can even set the number of line for detailTextLabel. Try this:
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:@"Cell"];
    }
    if (indexPath.row == 0) {
        cell.textLabel.text = @"Profile";
        cell.detailTextLabel.text = @"Lorem ipsum dolor sit amet, vix id debet libris. Quem oblique blandit ne vix, repudiare prodesset an mel. At libris tacimates accusata has, eum at ignota cotidieque. Pro malorum nominati ei.";
    }
    else if (indexPath.row == 1){
        cell.textLabel.text = @"Server";
        cell.detailTextLabel.text = @"Lorem ipsum dolor sit amet, vix id debet libris. Quem oblique blandit ne vix, repudiare prodesset an mel. At libris tacimates accusata has, eum at ignota cotidieque. Pro malorum nominati ei.";
    }
    else if (indexPath.row == 2){
        cell.textLabel.text = @"Security";
        cell.detailTextLabel.text = @"Lorem ipsum dolor sit amet, vix id debet libris. Quem oblique blandit ne vix, repudiare prodesset an mel. At libris tacimates accusata has, eum at ignota cotidieque. Pro malorum nominati ei.";
    }
    else if (indexPath.row == 3){
        cell.textLabel.text = @"Forget Password";
        cell.detailTextLabel.text = @"Lorem ipsum dolor sit amet, vix id debet libris. Quem oblique blandit ne vix, repudiare prodesset an mel. At libris tacimates accusata has, eum at ignota cotidieque. Pro malorum nominati ei.";
    }
    else if (indexPath.row == 4){
        cell.textLabel.text = @"About";
        cell.detailTextLabel.text = @"Lorem ipsum dolor sit amet, vix id debet libris. Quem oblique blandit ne vix, repudiare prodesset an mel. At libris tacimates accusata has, eum at ignota cotidieque. Pro malorum nominati ei.";
    }
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    return cell;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Table Simplex method: 1) why do we need to have identity matrix? 2) Nonexistance of optimal solution 3) Stop iteration condition Recently I have read this superb Simplex method tutorial: http://www.tutor.ms.unimelb.edu.au/simplex_intro/index.html . While explaning things in very clear fashion, some obscurity still left.

*

*From here you may read (identity matrix):

So, what is the reason our table should have identity matrix in it? What if it does not have identity matrix?

*From here (non-negativity):

Once again, please explain why this is so, don't simply tel that it is so, explain it.

*From here (stop iterations condition):

Guarantee is very good, but I don't believe, please explain it! Also it would be very cool if your explanations be clear and logical - prove the concepts, use as much math as required, but make it clear and easy to understand, similarly as in the article! Thanks!


text:
Q: What is the opposite of this terminal keyboard action? Open terminal > preferences > keyboard
I have control cursor right as \005.  I like it! When inside Vim, it moves the page down 1 line while keeping my cursor unmoved.
Try it.
My question is: how do I do the same with control cursor left?  I want vim to move the page 1 line up, but keep cursor unmoved.
What is the "action" for it? I tried \004 and nothing worked.

A: \005 or \x05 is the equivalent of CtrlE in ASCII (see C0 control codes, which represent both a control character and a keypress). The opposite, in Vim, would be CtrlY, which is \031 in octal or \x19 in hex.
See also :help ^E, :help ^Y and :help :map in Vim.


text:
Q: how to use SSRS email subscription in asp.net application? I am using SSRS in my asp.net application. Now I want to use SSRS email subscription as part of the project. Does anyone knows how can i do that?

A: You will need to create a shared folder which has write access for the account which you will provide when the subscription is being created. Also make sure that SQL Server Agent is running before the subscription is created.
Ref: http://www.sqlservercurry.com/2009/07/programmatically-create-data-driven.html
OR http://www.codeproject.com/Articles/36009/Programmatically-Playing-With-SSRS-Subscriptions


text:
Q: how can I decrease the size of the final package of the Oracle MAF applications? i'm developing oracle MAF Applications for mobile devices. the initial size of the packages r about 20 MB..
the MAF architecture has a built-in lightweight JVM (ORACLE MOBILE APPLICATION FRAMEWORK DATA SHEET) for business logic...
can I choose which libraries should b exported in final package to decrease the size?

A: You should deploy in Release mode - for Android the instructions are here.
Speed up ADF Mobile Deployment to Android with Keystore and "Release" Packaging.

A: It's not possible to choose which libs should be exported.
The only thing you can do is deploy to production instead of debug (initial size is minimum 15mb).


text:
Q: BigQuery: Arrange columns from 2 table to get a single table but only get unique rows from table2 I have two tables and in the output, I want a single table with rows from both the tables one below the other.

*

*Requirement is: Get all the rows from table1 but exclude rows from table2 with condition that email or productname is not present in table1.

Refer image. Yellow cells in table2 should not be present in the output, since they are present in table1, as highlighted. So only sr.no. 2,4,5,7 from table-2 should be present in output table.

Can someone suggest solution?
The logic I tried is UNION to first get all rows one below the other. However I'm not getting logic to exclude matching rows from table2 after UNION. I tried multiple options as commented below in my code:
  with a AS (
  SELECT
    email AS leademail,
    website AS leadwebsite,
    productname AS leadproductname,
    source AS leadsource,
    detail AS leaddetail,
    leaddate
  FROM
    `table1`),
  b AS (
  SELECT
    email AS contactemail,
    website AS contactwebsite,
    productname AS contactproductname,
    source AS contactsource,
    detail AS contactdetail,
    contactdate
  FROM
    `table2`)
SELECT
  *
FROM
  a union all
SELECT
  *
FROM
  b
  --option1 except distinct select * from b
  --option2 union all select * from b
  --option3 except distinct select * from b
  --option4 left join
  --(select * from b where contactemail not in (select leademail from a))
ON
  leademail=contactemail
  AND leadproductname=contactproductname

A: I was able to perform this query by using the UNION ALL operator to append filtered rows from the table2 to the table1 and I used the operator NOT IN to filter the rows from table2.
SELECT
  *
FROM
  table1
UNION ALL (
  SELECT table2.*
  FROM
    table2
  WHERE
    table2.email NOT IN (SELECT email FROM table1)
    OR table2.productname NOT IN (SELECT productname FROM table1)
)

Also, I made the following executable query based on your example data so more people can play with:
WITH table1 AS (
  SELECT
    "abc@abc.com" AS email,
    "abc.com" AS website,
    "msoffice" AS productname,
    "abc" AS source,
    "one" AS detail,
    "12-Dec-19" AS leaddat
  UNION ALL SELECT "pqr1@pqr1.com","pqr1.com","chrome","pqr1","two","12-Dec-19"
  UNION ALL SELECT "xyz@xyz.com","xyz.com","iphone","xyz",NULL,"12-Dec-19"
  UNION ALL SELECT "zzz@zzz.com","zzz.com","macbook","zzz","three","12-Dec-19"
  UNION ALL SELECT "xyz1@xyz.com","xyz1.com","itunes","xyz1",NULL,"12-Jan-20"
  UNION ALL SELECT "google@google.com",NULL,"googlecloud","xyz2",NULL,"12-Jan-20"
  UNION ALL SELECT "123@123.com","123.com","yahoomail","123","xyz","12-Jan-20"
), table2 as (
  SELECT
    NULL AS email,
    "abc.com" AS website,
    "msoffice" AS productname,
    "abc" AS source,
    "one" AS detail,
    "11-Nov-19" AS leaddat
  UNION ALL SELECT "pqr@pqr.com","pqr.com","playstore","pqr1","two","12-Jan-20"
  UNION ALL SELECT "123@123.com","123.com",NULL,"123","xyz","12-Oct-19"
  UNION ALL SELECT "abc1@abc1.com","abc1.com",NULL,"xyz",NULL,"12-Jan-20"
  UNION ALL SELECT "itunes@apple.com",NULL,"ipod","zzz","three","12-Jan-20"
  UNION ALL SELECT NULL,NULL,"googlecloud","xyz2",NULL,"12-Jan-20"
  UNION ALL SELECT "yahoo@yahoo.com",NULL,"yahoomail",NULL,NULL,"12-Jan-20"
)

SELECT
  *
FROM
  table1
UNION ALL (
  SELECT table2.*
  FROM
    table2
  WHERE
    table2.email NOT IN (SELECT email FROM table1)
    OR table2.productname NOT IN (SELECT productname FROM table1)
)

Hope it helps.


text:
Q: I don't understand the Perl Taint mode error message I have some old Perl code I have been told is vulnerable to Cross site scripting attacks or SQL injection attacks.  I figured I'd turn on taint mode by changing the shebang from #!/usr/local/bin/perl to #!/usr/local/bin/perl -T and now I get this error message:
Insecure dependency in require while running with -T switch at <big long path>/main.cgi line 26.

The code looks like this:
  1 #!/usr/local/bin/perl  -T
.
.
.
 12 use strict;
 13
 14 use vars qw( %opt $VERSION );
 15
 16 use CGI qw/:standard *table start_ul/;
 17 use CGI qw(:debug);
 18 use CGI::Carp qw( fatalsToBrowser );
 19 #use CGI::Pretty qw( :html3 );
 20 $CGI::Pretty::INDENT = "    ";
 21 use Tie::IxHash;
 22 use FindBin qw($Bin);
 23 use lib "$Bin/../../lib";
 24 use lib "$Bin/../lib";
 25
 26 use Common::Config;

The Common::Config is has this ownership and permissions:
$ ls -l lib/Common/Config.pm
-r--r--r--. 1 someguy example 5840 Oct  9 20:08 lib/Common/Config.pm

I tried changing the ownership to apache but I still get the taint error message.
UPDATE:
I have tried to untaint my $Bin variable like so:
use FindBin qw($Bin);           # Where are we ?
if ($Bin =~ /^([-\@\w.]+)$/) {
        $Bin = $1;                      # $data now untainted
} else {
        die "Bad data in '$Bin'";       # log this somewhere
}

But I still get the taint error about use Common::Config;

A: Do you have a use lib statement where an insecure variable is added to the include path?
https://perldoc.perl.org/perlsec.html

Note that if a tainted string is added to @INC, the following problem will be reported:
Insecure dependency in require while running with -T switch


text:
Q: Why I get unexpected end of file in my script when using gzip? I have one doubt with this:
for i in ./*.gz
do
gunzip -c $i | head -8000 | gzip > $(basename $i)
done

I get an "unexpected end of file" error for gzip, and I don't get the 8000 at all, only a few tens of lines. I've checked the integrity of my files and they are fine. Curiously, if I run for individual files:
gunzip -c file1.gz | head -8000 | gzip > file1.gz

I get the expected result. With this script I can obtain the first 8000 lines from a compressed file with 10708712 lines, and compress again. The new file overwrites the original file, but that's ok.

A: You should write the output to a temporary file and then rename:
for i in ./*.gz
do
  gunzip -c "$i" | head -8000 | gzip > "$i.tmp"
  mv -f "$i.tmp" $(basename "$i")
done

That your version sometimes works is if you gunzip buffers enough while reading.


text:
Q: How can I add text to SVG elements in D3 using the example below Using D3 version 3, I'm trying to get text (in this case names from the json) to appear in the centre of the circles in a bubble chart.
I followed various tutorials. In the Chrome Developer Tools Elements window my text elements are visible as children of the SVG circle but are still not visible on screen.
I've put together an example on Codepen.
https://codepen.io/_d_v_/pen/MQyONV
const json = { companyA: 500, companyB: 200, companyC: 150, companyD: 100, companyE: 50 };
const colors = [ '#FF0000', '#03900F', '#0000FF', '#FF00FF', '#00FF00' ];
const diameter = 400;

const processData = data => {
  const obj = data;

  const newDataSet = [];
  for(let prop in obj) {
    newDataSet.push({name: prop, size: obj[prop]});
  }
  return {children: newDataSet};
}

const svg = d3.select('#graph').append('svg')
.attr('width', diameter)
.attr('height', diameter);

const bubble = d3.layout.pack()
.size([diameter, diameter])
.value( d => d.size )
.padding(30);

// generate data with calculated layout values
const nodes = bubble.nodes(processData(json)).filter(function(d) { return !d.children; }); // filter out the outer bubble
const vis = svg.selectAll('circle').data(nodes);

vis.enter().append('circle')
  .attr('transform', d => 'translate(' + d.x + ',' + d.y + ')')
  .attr('r', d => d.r)
  .attr('fill', (d, i) => `${colors[i]}`);
vis.append('text')
  .attr('dx', d => -20)
  .attr('text-anchor', 'middle')
  .attr('font-size', d => d.r / ((d.r * 10) / 100))
  .attr('dy', d => d.r / ((d.r * 25) / 100))
  .text(d => d.name)

Please can anyone show me where I'm going wrong? I just want text to appear in the centre of the SVG circle.
Many thanks in advance

A: As I commented. <text> should be inside <svg> not inside <circle> .. then position it accordingly..
I have transformed text as you have transformed circle ... making inside circle. given color red. You can now edit your code as you wish.
Modified js code.
const json = { companyA: 500, companyB: 200, companyC: 150, companyD: 100, companyE: 50 };
const colors = [ '#FF0000', '#03900F', '#0000FF', '#FF00FF', '#00FF00' ];
const diameter = 400;

const processData = data => {
  const obj = data;

  const newDataSet = [];
  for(let prop in obj) {
    newDataSet.push({name: prop, size: obj[prop]});
  }
  return {children: newDataSet};
}

const svg = d3.select('#graph').append('svg')
.attr('width', diameter)
.attr('height', diameter);

const bubble = d3.layout.pack()
.size([diameter, diameter])
.value( d => d.size )
.padding(30);

// generate data with calculated layout values
const nodes = bubble.nodes(processData(json)).filter(function(d) { return !d.children; }); // filter out the outer bubble
const vis = svg.selectAll('circle').data(nodes);

vis.enter().append('circle')
  .attr('transform', d => 'translate(' + d.x + ',' + d.y + ')')
  .attr('r', d => d.r)
  .attr('fill', (d, i) => `${colors[i]}`);
vis.enter().append('text')
  .attr('dx', d => 20)
.attr('transform', d => 'translate(' + d.x + ',' + d.y + ')')
.attr('fill',"red")
  .attr('text-anchor', 'middle')
  .attr('font-size', d => d.r / ((d.r * 10) / 100))
  .attr('dy', d => d.r / ((d.r * 25) / 100))
  .text(d => d.name)


text:
Q: Reorderings in java memory model re-read the JMM, find that there is one sentence I do not understand:

We consider here only variables that are readable and writable as an
atomic unit -- that is, no bit fields, unaligned accesses, or accesses
larger than word sizes available on a platform.

Anyone can explain the cases shown above which the words are bold.

A: On some architectures, the processor can do in a single command multiple memory accesses:

*

*bit fields: setting certain bits of a memory; this is usually implemented using read-modify-write, with separate accesses for read and write.

*unaligned access: on some CPU architectures, the processor imposes constraints on the addresses you can use when you access multibyte values, especially if you cross word boundaries. Most modern processors do no have this issue because they can execute multiple reads to cover the required address range; if you read from 0x01 to 0x05, it gets split into a 0x01-0x04 and a 0x05 read. This is compounded if you will need to write there; the same areas will get first read, then written, doing 3 times as many memory operations as necessary when compared to an address that is aligned (the address is a multiple of 4). (keep in mind that on modern CPUs the issue is more complex, as you have a very deep memory hierarchy with different per-layer alignment constraints).

In these cases, an operation will need to cross several memory accesses, thus tehre is potential for race conditions, thus no atomicity guarantees.


text:
Q: Compare AVR programming tools I am dealing with PICs for some time and now I want to learn how to use an AVR. I have 2 MCUs in here, the AT32UC3C2512C-A2UT and the ATXMEGA32A4U-AU but I still dont have any programming tools.
In the PIC, things are pretty simple: You just buy PIC Kit 3 and you can program and debug all PICs for a cheap price. But in AVR I can see so many options in Atmel's website, and not just in products but in technologies (PDI, JTAG etc..).
Since I am pretty noob in this subject, I wanted a quick comparison of the options out there and not just the programmers and debuggers but also about the technologies inside them. The DIY options will be most welcome.
In the internet there are some quick reference guides, like this one, but they are years old and they do not compare the technologies inside them (in that link they don't say for example the difference between TPI and PDI or JTAG and the benefits of each one of them), just what they do, so it's hard to choose one.
Please bear in mind I need a programming board for the MCUs I mentioned. I appreciate all the help!
EDIT: I think this link might help.

A: There are dozens of different programmers, but they all fall into one or more of these categories:

*

*JTAG. any JTAG programmer can program any device (not just AVRs, and not even just micros) that accepts JTAG. I have several JTAG programmers (Olimex AVR-JTAG-USB, Terasic's Blaster, Abatron BDI2000). Requires 4 or 5 lines.

*PDI. AVR-specific, 2-wire protocol for programming and debugging. Many AVR programmers support PDI (Dragon, AVRISP, JTAGMkII, etc.)

*ISP. AVR-specific, 5 wire protocol built on top of SPI. Most AVR programmers support this and I believe that every AVR supports this. The bus pirate also works as an AVR ISP programmer.

*HVPP. This mode uses a lot of pins and uses 12V to program the device (as opposed to the normal 1.8-5V supply). I have never used this.

*HVISP. AVR-specific 5 wire protocol which can be used on the ATTiny parts or other AVRs which have had their reset pin disabled. Uses 12V like HVPP, but with much fewer pins. The Dragon is one of very few programmers which support this option.

*TPI. I don't know much about this method, it looks very similar to PDI to me. Used on the ATTiny devices.
For my own stuff, I use JTAG or ISP since they both work well in-circuit, but on a recent design I am using the ATTiny13A and need every pin, so I use a Dragon and HVISP for that design. HVISP isn't really meant for in-circuit programming and there are some caveats that I've had to incorporate into the design to make it work.
Which programmer is right for you? Look around for an inexpensive USB ISP programmer with a case. Get a Dragon if you really need the HV programming modes, but you probably don't need them at this point. Digikey or Mouser are the usual sources but you can build your own, use ebay or any number of sites like ladyada or sparkfun. Definitely don't spend more than $50, you can get the Dragon for $56 from Digikey.
You want a case to protect the programmer because one thing you don't want to is to start guessing whether it's your design or the programmer that's causing you grief. :-)

Edit 1
Which programmer to use for AVR32 and XMEGA? Both can use JTAG, so I'd look for a JTAG programmer. JTAG programmers can be built out of pretty much anything, there are homebrew/"free" designs available, and you could even make one out of a parallel port. I suggest looking at something like a AVR-JTAG-USB or ByteBlaster since they're both about USD$50 and well supported by avrdude (the software which programs AVRs under Linux and OSX), but as I said, any JTAG cable will work. If you're using AVR Studio then I'd check their list of supported programmers (a link to which I could not find, sadly). I know it does support the AVR-JTAG-USB, and I believe Atmel's official recommendation is the JTAGICE3.
You may want to take a look at LadyAda's AVR Tutorial -- the link goes to their "choosing a programmer" section but the whole tutorial is good.

Edit 2
Why the cost disparity between programmers? Features mostly. Some programmers can only do ISP or JTAG. Some programmers only work with a specific VCC, or make assumptions about whether the device you're programming is powered by the programmer or not. Some programmers do not take care to protect themselves against misconnection, or have "dumb" power supplies which don't shut down in the case of short circuits or overcurrent. I already mentioned that most programmers DO NOT support the high voltage (12V) programming that you may need in some cases.
For starting out with XMEGA and AVR32, I'd recommend the Olimex AVR-JTAG-USB or Terasic ByteBlaster as menitoned above. They're reasonably rugged, have level shifters to match the power supply of the device you're going to program, and reasonably priced.

A: XMEGA and UC3 (AVR32) aren't really 'AVR', so most AVR programmers won't work with them.
XMEGA needs PDI (or JTAG). UC3, I'm not even sure. surely JTAG, possibly another method though.
There's a PDI programmer in the LUFA library, that will run on any USB AVR (like one on teensy, or chinese dongle for uh.. Playstation).


text:
Q: Given $n$ identical things need to distribute among $r$ objects such that each object can have at least 1 thing $\dbinom{n+r−1}{r−1}$ is the answer for the distribution of $n$ identical objects among $r$ persons. Not for the groups, because groups are considered as identical it do not have name. Ex. two identical balls can to be distributed among two persons $[(2,0)(0,2)(1,1)]$ in three ways. But when we go for groups $(2,0)$ and $(0,2)$ considered as the same, so now the answer will be only two.
What will be the formula if we want to remove the same groups ex. in the above example if we want $(2,0)$ and $(0,2)$ to be considered same and want the answer $2$ so what will be the formula in that case?

A: There are the partitions of $n$ into $r$ or fewer parts.
There is no pleasant "closed form" formula.


text:
Q: Magento: need to export items from order to file I have custom observer.php file, that create xml file after the order is created. there are all informations about invoice and shipping adresses, but I need to export items too. I tryed more styles to make it work, but still nothing work for me. what I have to add to observer.php to include all items informations?
<?php

class JULEC_Model_Observer extends Mage_Core_Model_Abstract {

    public function exportObjednavky(Varien_Event_Observer $observer) {
        $orderIds = $observer->getOrderIds();
        for($i = 0; $i < count($orderIds); $i++) {
            $order = Mage::getModel('sales/order')->load($orderIds[$i]);
            $billing = $order->getBillingAddress();
            $shipping = $order->getShippingAddress();
            $fileContent = '<?xml version="1.0" encoding="utf-8" ?>
                 <mrpEnvelope>
                  <body>
                    <mrpRequest>
                      <request command="IMPEO0" requestId="' . date("Y-m-d-H-i-s") . '">
                      </request>
                      <data>
                        <params>
                          <paramvalue name="cisloSkladu">1</paramvalue>
                          <paramvalue name="stredisko">0</paramvalue>
                          <paramvalue name="cisloZakazky">0</paramvalue>
                        </params>
                        <objednavka formaUhrady="Dobierka" puvodniCislo="' . $order->getIncrementId() . '" datum="' . date("Y-m-d") . '" cenySDPH="F">
                          <mena kod="EUR" kurz="1" mnozstvi="1"/>
                          <adresa id="A' . $order->getIncrementId() . '" ulice="' . implode(' ', $billing->getStreet()) . '" mesto="' . $billing->getCity() . '" psc="' . $billing->getPostcode() . '">
                            <firma nazev="' . $billing->getLastname() . ' ' . $billing->getFirstname() . '" ico="X' . $order->getIncrementId() . '" dic=""/>
                            <osoba jmeno="' . $billing->getCompany() . '" prijmeni=""/>
                            <email>' . $billing->getEmail() . '</email>
                            <tel>' . $billing->getTelephone() . '</tel>
                          </adresa>';

            $sameAddress = $this->compareAddresses($billing, $shipping);
            if(!$sameAddress) {
                $fileContent .= '
                          <adresa_dod id="" ulice="' . implode(' ', $shipping->getStreet()) . '" mesto="' . $shipping->getCity() . '" psc="' . $shipping->getPostcode() . '">
                            <firma nazev="' . $shipping->getLastname() . ' ' . $shipping->getFirstname() . '" ico="X' . $order->getIncrementId() . '" dic=""/>
                            <osoba jmeno="' . $shipping->getCompany() . '" prijmeni=""/>
                            <email>' . $shipping->getEmail() . '</email>
                            <tel>' . $shipping->getTelephone() . '</tel>
                          </adresa_dod>
                ';
            }

                 //need to get here list of items with its values  //

            $fileContent .= '<ITEMS><item =" ???SKU???   "text="   ???  ITEM NAME ???   "price="  ??? ITEM  PRICE ????  "qty=" ???  ITEM QTY ???  "tax=" ??? ITEM TAX RATE ??? " /></ITEMS>
                        </objednavka>
                      </data>
                    </mrpRequest>
                  </body>
                </mrpEnvelope>

            ';

            file_put_contents('var/export_objednavky/' . date("Y-m-d-H-i-s") . '-' . $order->getIncrementId() . '.xml', $fileContent);

        }
    }

    public function compareAddresses($address1, $address2) {
        if (!is_null($address1) && !is_null($address2)) {
            if ($address1->getFirstname() != $address2->getFirstname())
                return false;

            if ($address1->getLastname() != $address2->getLastname())
                return false;

            if ($address1->getCompany() != $address2->getCompany())
                return false;

            if (implode(' ', $address1->getStreet()) != implode(' ', $address2->getStreet()))
                return false;

            if ($address1->getCountryId() != $address2->getCountryId())
                return false;

            if ($address1->getPostcode() != $address2->getPostcode())
                return false;

            if ($address1->getCity() != $address2->getCity())
                return false;
        }
        return true;
    }

}

A: If I understand you correctly, then you can try something like:
foreach ($order->getAllItems() as $item) {
  $itemSku = $item->getSku();
  $itemName = $item->getName();
  $itemPrice = $item->getPrice()
  /* etc */
}


text:
Q: How to get InnerText of XML Document? I'm using XML Reader to read an XML document that looks like this
<?xml version="1.0"?>
<profile username="666">
  <purchases>
    <purchase id="221">
      <price>5599</price>
      <quantity>22<quantity>
      <description>This is some placeholder text</description>
    </purchase>
  <purchases>
    <purchase id="621">
      <price>234</price>
      <quantity>5<quantity>
      <description>This is some placeholder text</description>
    </purchase>
  </purchases>
</profile>

I want to get the elements purchase id, price, quantity, and description, then add them to my profile method.
Here is my current code
using (XmlReader reader = XmlReader.Create(doc))
{
    while(reader.ReadToFollowing("purchase"))
    {
        var id = reader.GetAttribute("id");

        while(reader.ReadToFollowing("price"))
        {

        }
    }
}

What I'm struggling with is how can I fetch the inner contents of price, quantity etc.

A: Instead of attribute etc you just have to use VALUE
while(reader.ReadToFollowing("price"))
{
  Console.WriteLine(reader.Value);
}

A: You can use LINQ to XML.
Below example will get all price nodes on the XML
var xml = XElement.Load(YourXMLDocumentPath);

var allPriceNodes = xml.Elements()
    .Where(el => el.Name.LocalName == "purchases")
    .Elements()
    .Where(el => el.Name.LocalName == "purchase")
    .Elements()
    .Where(el => el.Name.LocalName == "price");

also you can get a specific value like the first price tag value you can add .FirstOrDefault().Value;


text:
Q: Effectively getting the root domain from url without the tld without using a predefined tld list My question is simple. How does one go about remove the tld from a domain using regex for example, without a predefined list of every possible tld known to existence. It seems simple enough, but yet I've not found a single one on stackoverflow nor on google without the use of a list or it not working with diverse tlds such as .co.uk or com.au with using the pop method simply rendering it useless. For this, the http://www. or http:// is already removed for this scenario.
google.com --> google
google.co.uk --> google

stackoverflow.com --> stackoverflow

Thank you

A: Its impossible (if you care about subdomains)
If you dont care about subdomains:
domain=url.split(".").shift();

If you care about subdomains,
The most correct way, (sth about 80% correct) would be removing everything short from.the url, then take the last:
domain=url.split(".").filter(e=>e.length>3).pop();
if(domain==undefined){
  domain=url.split(".").pop();
 }

That would fail with account.db.de stadt.hamburg etc, but without a tld list, this isnt possible.


text:
Q: "Ember Simple Auth" invalidateSession from component Trying to execute this code within a component's template
// components/my-component.js
{{#if session.isAuthenticated}}
  <a {{action 'invalidateSession'}}>Sign out</a>
{{else}}
  {{#link-to 'signin'}}Sign in{{/link-to}}
{{/if}}

However, when clicking "Sign out" button I get this error
Error: <...@component:my-component::ember381> had no action handler for: invalidateSession

How do I make "invalidateSession" available from a component?

A: You can just implement your own invalidateSession action:
actions: {
  invalidateSession: function() {
    this.get('session').invalidate();
  }
}

or simply forward the action from the component to the route:
{{my-component invalidateSession='invalidateSession'}}

A: You need to add the Simple Auth ApplicationRouteMixin to your ApplicationRoute.  For example if you are using ES6 modules do
import ApplicationRouteMixin from 'simple-auth/mixins/application-route-mixin';

ApplicationRoute = Ember.Route.extend ApplicationRouteMixin,

The action should bubble up to the application route, where it will be handled.
See the documentation here


text:
Q: August 2015 - Redirect loop - Can't log in to any Stack Exchange site with Opera Latest I've searched many questions but none have helped so far.
I'm posting this question with Opera 12.17 because it works. I'm starting to use Opera Latest (currently 31) because many of the features that were lost when changing the engine to Chromium have been re-implemented.
However, trying to log into any Stack Exchange site with Opera Latest gives the following error:

This webpage has a redirect loop
The webpage at [address] has resulted in too many redirects. Clearing your cookies for this site or allowing third-party cookies may fix the problem. If not, it is possibly a server configuration issue and not a problem with your computer.

It works fine in Firefox Latest but I don't have Chrome installed to try it. Is this a site issue or a browser issue?


text:
Q: What do you think?
I think of this place as my home. (OALD)

Consulting the sentence above, can I make an interrogative as these?:
[a] As what do you think of this place?
[b] What do you think of this place as?
Or is this alone, what do you think of this place, possible? Or none?

A: You wouldn't normally include "as":

What do you think of this place?

The answer to the question would include the "as":

I think of this place as my home.

You could ask about that specifically:

Do you think of this place as your home?

And you could technically get away with:

What do you think of this place as?

But it is informal and not highly recommended.


text:
Q: deasync in node takes time to return I am using deasync module to make functions synchronized in Node.js. But program takes more time to finish. However data is returned quickly to console.
var storeintodrive = function moveFileTo (filename){
    var hash;
    var sync = true

    //do some operation
    hash = XXXXXXXXXXXXX
    sync = false;

    while (sync) {
        require('deasync').sleep(10);
    }
    return hash;
}

var hexifydata = function(array,filedata){

    var sync = true;

    // do some opration
    Records.push(record[0]);
    sync = false;

    while (sync) {
        require('deasync').sleep(10);
    }
    return Records;
}

Due to late in response from these functions,frond end JS is not getting correct response from NodeJs. Please suggest me how do I get response faster from both functions.


text:
Q: Far-field distance of antenna and a wave phase In a following reference [David M. Pozar 2012, 4ed, Microwave Engineering, p 661], it is told that the far field distance of a relatively large antenna is given from the formula
\begin{equation}
R_{ff}=\frac{2D^2}{\lambda}
\end{equation}
where D is a maximum dimension of an antenna, $\lambda$ is a wavelength. And it is told that:"This result is derived from the condition that the actual spherical wave front radiated by
the antenna departs less than $\pi/8 =22.5^\circ$ from a true plane wave front over the maximum
extent of the antenna". Does this mean that we have to compare the "far-field" component of electric field with a "near-field" component and at phase $\pi/8$ they are equal or something else? I think that I miss the point.

A: The condition on the far field in the free space is obtained from wave equations. First of all, the equation on the retarded potentials is
\begin{equation} \label{eq:dAlembert}
 \Box{\vec{A}=-\mu_0 \vec{j}}
\end{equation}
where the temporal part of of potential is $e^{j \omega t}$, so we can get the following equation assuming $k = \omega /c$
\begin{equation} \label{eq:Helmholtz}
 \Delta\vec{A}+  k^{2}\vec{A} = -\mu_0\vec{j}
\end{equation}
Next we solve this equation assuming Green function formalism.
\begin{equation}
 G(\vec{r}) = \frac {-e^{\pm ikr}}{4\pi r}
\end{equation}
After a long calculation and using Laurenz jauge, we can achieve precise equations on electric and magnetic field. For exemple, for the electric field we have
\begin{equation}
 \vec{H} = -\frac{1} {4 \pi}
 \int \ e^{ik|\vec{r}-\vec{r}\,'|} \frac {1} {|\vec{r}-\vec{r}\,'|^2}  (-\frac{\vec{r}-\vec{r}\,'} {|\vec{r}-\vec{r}\,'|}  + ik (\vec{r}-\vec{r}\,') ) \times \vec{j}(\vec{r}\,') \, d^3\vec{r}\,'
\end{equation}
We are interested in the term $ e^{ik|\vec{r}-\vec{r}\,'|} $, where the Taylor series of the following function is
\begin{equation} \label{Eq:Abs_r-r'}
 |\vec{r}-\vec{r}\,'| = \sqrt{(\vec{r}-\vec{r}\,')\cdot(\vec{r}-\vec{r}\,')}\approx r (1-\vec{e}_r \vec{r}\,'/r +\frac{{\vec{r}\,'}^2} {2 r^2})
\end{equation}
In order to decrease the last term in the previous equation we have the far field criteria:
\begin{equation}
  \frac{{r\,'}^2} {2 r^2} < \lambda/16
 \end{equation}
or equally, $$phase = k\frac{{r\,'}^2} {2 r^2}  < \frac{\pi}{8}$$.
It is well explained in [p83, A.B. Smolders, H.J. Visser, U. Johannsen, Modern Antennas and Microwave Circuits, September 2020, Eindhoven University of Technology].


text:
Q: Remove multiple DOM nodes at once I have a row of images and I want to remove all the ones that are cut off from the page. I wrote this function:
var pawLineImages = document.querySelectorAll('#paw-line > img');
var pawImages = Array.prototype.slice.call(pawLineImages);
var cutOffIndex = 0;
var viewWidth = Math.max(document.documentElement.clientWidth, window.innerWidth);
for (var i=0; i<pawImages.length; i++) {
    var elm = pawImages[i];
    var rect = elm.getBoundingClientRect();
    if (rect.right - viewWidth >= 0) {
        cutOffIndex = i;
        break;
    }
}
if (cutOffIndex > 0) {
    // Here I want to remove all children [cutOffIndex ... pawImages.length]
}

Does anyone know how I'd remove all the images that are after the cutoffIndex at the same time? I'm hesitant to do it in a for loop because then things might be more expensive then doing it all at once.

A: Change "if" condition in the loop as below to remove the image. No need to break from the loop and then process again.
if (rect.right - viewWidth >= 0) {
   elm.parentNode.removeChild(elm);
}

OR
If there is an option of using jQuery then keep the current loop as is and after the loop use jQuery to remove all images at once.
// After the loop
$("#paw-line img").slice(cutOffIndex).remove();


text:
Q: .NET Security attribute. Is it possible to make a custom security model? Common problem: How to implement user access rights differentiation system in any .NET application (for example, WCF application) by using class/method attributes?
So, we have:

*

*A set of users

*A set of roles (for example, enum Role)

*Every user have his own set of his roles.

*Every class/method could be specified for particular role.
[AuthorizationAttribute(Roles = new Role[] { Role.Admin })]
 public class UserService : IUserService
 {
}

*If user's set of roles doesn't contain this role, user mustn't have access to the method.
Update. I've tried to make the problem description more clear. The Akton's solution is good for this problem.

A: It is possible to create an attributed security model like you suggest but it is not easy. Your securable objects have to inherit from ContextBoundObject and your security attribute from ContextAttribute (or implement the IContextAttribute interface). Then:

*

*Implement the IContextAttribute.GetPropertiesForNewContext(IConstructionCallMessage) method. You create an object, call it MySecurityProperty, that implements the IContextProperty and IContributeObjectSink interfaces and add it to the IConstructionCallMessage.ContextProperties collection.

*In the implementation of MySecurityProperty.GetObjectSink(MarshalByRefObject, IMessageSink) construct an object, call it MySecurityAspect, that implements the IMessageSink interface.

*In the implementation of MySecurityAspect.SyncProcessMessage(IMessage), you actually check the call to see whether it is valid. If it casts to IMethodMessage, indicating a method call, you can query the properties of IMethodMessage to see whether it is calling a method or class with your security attribute and do the appropriate checks. If the call is unauthorized, throw an exception of the appropriate type.

It will take you a few hours to get it working but, once it does, it makes sense. It is just a very undersupported part of the .Net framework. The big problem, beyond the complexity, is that it forces your securable classes to inherit from ContextBoundObject rather than any other library classes. ContextBoundObject also inherits from MarshalByRef, which can interfere with serialization.
See http://www.developerfusion.com/article/5307/aspect-oriented-programming-using-net/3/ for a more in depth explanation.


text:
Q: Why the number '0' (number, not char) doesn't displaying? The problem is that I cannot see 0 in an array.
I run my program and see 2D array. But instead of 0 (the first element) I see nothing.
Here is the code:
#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i;
    int *Ptr;

    scanf("%d%d", &M, &N); /* Size of array. */

    Ptr = malloc(M*N*sizeof(int));

    for (i = 0; i < M * N; i++) /* Filling in. */
    {
        *(Ptr + i) = i;
    }

    for (i = 0; i < M * N; i++) /* Displaying. */
    {
        if (i % N == 0)
            printf("\n");
        printf("%2.d  ", *(Ptr + i));
    }

    return 0;
}

What is the problem?
Is there any way to fix it?

A: The number after the dot is the precision. If the precision is 0 (or does not exist) then printf does not print out 0. In your case you do not need the dot:
printf("%2d ", ...)

A: change
printf("%2.d  ", *(Ptr + i));

to
printf("%2d  ", *(Ptr + i));


text:
Q: Warning about redeclaration of friend function I've got A.h where I have
#ifndef _FOO_
#define _FOO_
namespace FOO {
    const std::string& getName();
}
#endif

In B.h I have
#ifndef _BAR_
#define _BAR_
namespace FOO {
    //forward declaration
    const std::string& getName();
}

namespace BAR {
class Baz {
private:
   static std::string& get();
public:
   friend const std::string& FOO::getName();
}
}
#endif

In B.cpp
#include "B.h"
namespace BAR {
       std::string& Baz::get() {
            static std::string s;
            return s;
       }
}

In A.cpp:
#include "A.h"
#include "B.h"
namespace FOO {
const std::string& getName() {
    return BAR::Baz::get();
}
}

When I compile I have the following warning from GCC:

redundant redeclaration of 'const string& FOO::getName()' in the same
scope. [-Wredundant-decls]

The warning is for A.h during compilation of A.cpp. How come?

A:
The warning is for A.h during compilation of A.cpp. How come?

The warning message explains the reason for its existence. You've unnecessarily declared FOO::getName twice. The second declaration is called a redeclaration.
Solution: Instead of manually redeclaring the content of the other header, #include  A.h into B.h. The include guard will prevent the redundant redeclaration.

P.S. The header guard macros that you use are reserved to the language implementation. As a consequence, the behaviour of the program will be undefined.


text:
Q: Arch Linux OpenVPN DNS-Problem I can´t successfully connect with OpenVPN or maybe I´ll connect successfully and something is wrong with my network-settings...
this is the Output of OpenVPN while connecting:
Thu Feb 13 23:21:13 2014 OpenVPN 2.3.2 x86_64-unknown-linux-gnu [SSL
(OpenSSL)] [LZO] [EPOLL] [eurephia] [MH] [IPv6] built on Nov 13 2013
Thu Feb 13 23:21:13 2014 WARNING: file
'/home/mak/openvpn-config/mkirchweger.p12' is group or others
accessible Thu Feb 13 23:21:13 2014 Attempting to establish TCP
connection with [AF_INET]83.164.xxx.xx:xxxx [nonblock] Thu Feb 13
23:21:14 2014 TCP connection established with
[AF_INET]83.164.xxx.xx:xxxx Thu Feb 13 23:21:14 2014 TCPv4_CLIENT link
local: [undef] Thu Feb 13 23:21:14 2014 TCPv4_CLIENT link remote:
[AF_INET]83.164.xxx.xx:xxxx Thu Feb 13 23:21:14 2014
[bricks.softpoint.at] Peer Connection Initiated with
[AF_INET]83.164.xxx.xx:xxxx Thu Feb 13 23:21:17 2014 TUN/TAP device
tun0 opened Thu Feb 13 23:21:17 2014 do_ifconfig, tt->ipv6=0,
tt->did_ifconfig_ipv6_setup=0 Thu Feb 13 23:21:17 2014 /usr/bin/ip
link set dev tun0 up mtu 1500 Thu Feb 13 23:21:17 2014 /usr/bin/ip
addr add dev tun0 local 10.10.x.xx peer 10.10.x.xx Thu Feb 13 23:21:19
2014 Initialization Sequence Completed
UPDATE:
I´m pretty sure it as an DNS-Issue, ping via IP works but Hostnames can´t be resolved...

A: I've found this Github-Repo and now it works :-)
https://github.com/masterkorp/openvpn-update-resolv-conf
when I add this to my openvpn-client config
# This updates the resolvconf with dns settings
script-security 2
up /etc/openvpn/update-resolv-conf.sh
down /etc/openvpn/update-resolv-conf.sh


text:
Q: Jenkins Pipeline-How to use release plugin? I want to use Jenkins release plugin in my job.
I am able to config Jenkins release in any job without Jenkins pipeline.
With Jenkins pipeline as this build environment Tab is missing, how to configure release in Jenkins file?

A: You can use the release step in your Jenkins file.


text:
Q: Error when calling biosphere flows an activity in ecoinvent v.3.5 I happen to face an error when I try to call the biosphere flows of activity. And When I call the technosphere for different activities, it works fine.
However, for the biosphere:
[in] clinker_bio_exchange = [exc for exc in clinker.biosphere()]
clinker_bio_exchange

Error:

        ActivityDatasetDoesNotExist: <Model: ActivityDataset> instance matching query does not exist:
        SQL: SELECT "t1"."id", "t1"."data", "t1"."code", "t1"."database", "t1"."location", "t1"."name", "t1"."product", "t1"."type" FROM "activitydataset" AS "t1" WHERE (("t1"."database" = ?) AND ("t1"."code" = ?)) ORDER BY Random() LIMIT ? OFFSET ?
        Params: ['biosphere3', 'fc1c42ce-a759-49fa-b987-f1ec5e503db1', 1, 0]

Should I update any part or am I missing something? Thank you.

A: There is something wrong with your biosphere3 database - your clinker object has an exchange with the biosphere flow (activity) ('biosphere3', 'fc1c42ce-a759-49fa-b987-f1ec5e503db1') (which is Water, cooling, unspecified natural origin on my machine). However, you are either missing the biosphere3 database entirely, or have deleted or otherwise modified this specific flow.
The easiest way to fix this is to reinstall it:
import bw2io
bw2io.create_default_biosphere3()


text:
Q: Прерывание многопоточности пишу программу, работающую с несколькими модемами. Для ускорения работы использую async await методы и запускаю их асинхронно.
Открытие порта проходит нормально. Далее инициализирую модем
    int ModemConnect(string modemNum)
    {
        Thread.Sleep(1000);
        _port.Write("+++\r\n");
        _port.Write("ATE1\r\n");
        Thread.Sleep(500);
        _port.Write("ATH0\r\n"); // установка режима ожидания
        Thread.Sleep(500);
        _port.Write("AT+IFC=0,2\r\n"); // устанавливается режим контроля над передачей
        Thread.Sleep(500);
        _port.Write("at+cbst=7,0,1\r\n"); // устанавливается прозрачный режим
        Thread.Sleep(500);
        if (!Regex.IsMatch(modemNum, @"(8|\+)9[0-9]{9}"))
            return 11;
        _port.Write("ATDT " + modemNum + "\r\n" + " ");
        return 0;
    }

Дело доходит до набора номера, соответствующая AT команда на модем уходит. Дальше приложение вываливается с ошибкой
"Дескриптор SafeHandle был закрыт".
Тут я не знаю, в чем дело.. Может быть из-за того, что установление связи с модемом - длительная операция (до 1 минуты). Но как в этом убедиться и что делать дальше?

A: private async Task<int> ModemConnect(string modemNum)
    {
        //проверку входных параметров
        //нужно делать в самомом начале метода
        //а не в середине работы,
        //когда вы начали дергать модем
        //и вставать в ожидание
        if (!Regex.IsMatch(modemNum, @"(8|\+)9[0-9]{9}"))
            return 11;

        //Thread.Sleep() - блокирует поток,
        //CPU совсем "не обращает на него внимание".
        //Thread.Sleep(1000);

        //Если вы хотите "подождать" в методе, который
        //выполняет input/output то надо использовать Task.Delay()
        await Task.Delay(1000);
        _port.Write("+++\r\n");
        _port.Write("ATE1\r\n");

        await Task.Delay(500);
        _port.Write("ATH0\r\n"); // установка режима ожидания

        await Task.Delay(500);
        _port.Write("AT+IFC=0,2\r\n"); // устанавливается режим контроля над передачей

        await Task.Delay(500);
        _port.Write("at+cbst=7,0,1\r\n"); // устанавливается прозрачный режим

        await Task.Delay(500);
        _port.Write("ATDT " + modemNum + "\r\n" + " ");

        //возвращать int в качестве
        //ответа на невычисляемые задачи,
        //а с целью отражения успеха/неуспеха/ошибки
        //фиговая практика (вы не на С пишите в конце концов).
        //для этого нужно использовать enum или спец.класс,
        //на худой конец константное строковое значение
        return 0;
    }

Вызывать такой метод надо так
int result = await ModemConnect("1234567");


text:
Q: Adding bibliographic reference to ipe image Is there a way to add a hyperlink to a reference from a bibliography (bib/bbl) in an image (created using IPE)?
I want to create an image with text that when clicked directs to a reference in the bibliography in the document.

A: From http://comments.gmane.org/gmane.comp.graphics.ipe.general/1113
You can use the \psfrag commands to do what you want.
Create the figure  and put placeholders for the \ref
or \cite commands you want
(eg, cite1, ref1 etc) in IPE.
Then in your latex document when
including the figure you can
replace the instances of cite1, ref1 etc
 using psfrag with whatever latex command you choose.

A: When you create the IPE figure, just put in \cite{}, \ref{}, the same way as you do in the LaTeX file.
After finishing your LaTeX main file, open main.aux, copy \newlabel{sec:section}{II} or \bibcite{article}{1} to the Edit->Document properties->Latex preambles. Run LaTeX again for IPE, then it works.


text:
Q: iOS Safari background image sometimes white until touch/move/resize I'm currently working on an app for Android & iOS with Sencha Touch.
The problem occurs occasionally on Safari OSX (latest versions) and more frequently on iPhones.
On a page/view called "product detail page" we have a slideshow with rectangular product pictures in JPG format, 100vw by 100vw large. The images themselves are around 800 by 800 pixels big, so not really large. Sencha Touch implements the slides using div background images. No anchor tags at all are involved.
The issue is that often - on a product detail page of which the images are not yet in the cache - the first product picture to be displayed is being loaded from the server (Amazon S3) - I can see that in the network tab in the devtools - but displayed completely white. Until I move the image slightly or use the console to change the style of the div, e.g. changing the width from 100vw to 100%.
I hacked a "fix" for this on the desktop by calling a timeout function after 1 second that will change the width as described, and that seems to fix the issue on Safari desktop (in the iPhone emulation). But in the iPhones the issue still occurs and regardless of my not-so-satisfying hack I'd like to understand what's going wrong here.
Why is the image only being shown after a layout change?
The same issue sometimes occurs with regular <img> images on our website under Safari on iPhones...


text:
Q: Is it possible to have the transaction log file write to a disk on a remote machine? For the SQL server transaction log file, it is possible to set its target file to a disk on a remote machine?
I am working on a BI project.  In its current iteration, when the data warehouse loading processes run, the transaction log can balloon (>100 GB) in size before it has a chance to truncate.  There isn't any room to add more disks to this server, and future data loading operations will involve substantially more data and so I don't think there will be enough disk space for the log.  But we have a development server in the same rack with 900+ GB free and I was thinking we could use that free disk space so that bigger loads will work.

A: It is supported to have database files on network share, but Its inviting a disaster as any network blip might corrupt your database.

Microsoft recommends that you store database files either on Local Disk or on Storage Area Networks (SANs).

You have to tune your data warehouse loading process. There are many parameters that can be tuned to have minimally logged operations and fast loading of data in sql server. e.g.

*

*Trace Flag 610 - controls minimally logged inserts into indexed tables.

*I have listed few items in this answer.
Also, if you want to be proactive, then create an alert for Transaction log full, so you get notified when the log is about to get filled up.
Read up on :

*

*The Data Loading Performance Guide

*Load 1TB in less than 1 hour

A: You should focus on breaking your ETL process in chunks to manage transaction log growth. There are other options like setting recovery model to bulk log selective transactions but with bulk logged recovery model you loose point in time recovery. And I do agree setting log file on remote storage is not a suggested practice and it will make operations
slow.

A: Yes it is possible...
I want to call out a few points before offering the solution:

*

*You must configure permissions so that the appropriate applications have the full control over the directory and files in the destination. This includes:

*

*SQL Server Service Account or whichever account you are running the SQL Server process under.

*If batch jobs run under a different account, and you perform full transaction log backups, this account must also have permissions.

*Beware of the latency of committing across a remote drive will impact performance

*Remote drives can be bottlenecks if the remote server is using the drive for other purposes (such as page files, or a enterprise file share).

*Performance test this scenario!!

With those concerns out of the way (plus more that were highlighted by @James in the comments).... here is a possible solution.

As a pre-requisite - this example assumes that you have a mapped drive to the E:\. The access is available to the appropriate SQL accounts.
To quote a referenced site entitled Move SQL Server transaction log files to a different location via TSQL and SSMS:

In a nutshell, the three main steps involved in moving a log file to
  new location are:

*

*Detach the database

*Move log file to new location

*Attach the database by referencing the new location of the transaction log file

Detach script is as follows:
Use MASTER
GO

-- Set database to single user mode
ALTER DATABASE adventureWorks
SET SINGLE_USER
GO

-- Detach the database
sp_detach_db 'AdventureWorks'
GO

Once the detach has completed, move the file manually via whatever means necessary. Then re-attach with the following T-SQL:
USE master
GO

sp_attach_DB 'AdventureWorks',
'D:\Program Files\Microsoft SQL Server\MSSQL\Data\AdventureWorks_Data.mdf', -- Data File
'E:\Move LogFile here through T-SQL\AdventureWorks_Log.ldf'  -- Transaction Log File
GO


text:
Q: KeyBoard error on boottime When I Boot my computer boot screen says that there is an "KeyBoard error".But when my
computer started the KeyBoard is working properly.
And also when machine boot the three LED bulbs blink twice.
When error comes motherbord makes three beep sounds.
I dont think there is an error with my KeyBoard.What can I do to fix this...
Pls anyone help me.
OS:Windows 7
Processer:Intel Pentium DualCore

A: 3 Beeps usually mean an memory error.
But at first you should look up the beep codes for your mainboard like the ones explained here: http://www.intel.com/support/motherboards/desktop/sb/cs-010249.htm

A: Alternatively its possible (depending on your hardware/BIOS config) that your BIOS is configured to expect a PS2 keyboard, and that you are using USB. In this case the Power On check might error, but the USB keyboard would work once you got into the operating system.
If this is the case you may be able to change the BIOS config to ignore errors when no PS2 keyboard is found.
The reason I suggest this is that I note that your machine is a dual core pentium, which is a few years old now, whereas the OS is windows 7. I'm guessing that you're not using the original OS/Peripherals for the PC.


text:
Q: SharePoint 2013 search result is trimmed even user has access I hope there's someone who can help me about SharePoint 2013 search.
One of my customer has an issue when searching a document by document id, the result is trimmed somehow.
Here are the things I have verified:

*

*This user does have access to the document (He can open it directly by document URL)

*Other users, like me, can search the document by doc id, such as xxx-12-23, without any problem

*When the user search the document: docid:xxx-12-23, nothing returned

Does anyone had come across such issue before?


text:
Q: Android Expandable text view with "View More" Button displaying at center after 3 lines I want to display description in a text view, if the description is more than 3 lines i want to display a View more button that expands the text view with complete description (or a dialog with complete description)
I have referred some links
1) How can I implement a collapsible view like the one from Google Play?
The above solution has an arrow like image view at end of third line of text view but i want a button displaying below the text view if description crosses 3 lines.
2) Add "View More" at the end of textview after 3 lines
The above solution has "View More" unaligned( "View" at 3rd line and "More" at 4th line)
I am looking for something like this.

A: This is how i have achieved the desired output,
MytextView which i want to expand is: tvDescription
I have a see more button with name: btnSeeMore
To check if the textview has more than 4 lines i had a listener for it as follows,
tvDescription.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if(expandable) {
                        expandable = false;
                        if (tvDescription.getLineCount() > 4) {
                            btnSeeMore.setVisibility(View.VISIBLE);
                            ObjectAnimator animation = ObjectAnimator.ofInt(tvDescription, "maxLines", 4);
                            animation.setDuration(0).start();
                        }
                    }
                }
            });

I have kept a boolean value to check if textview is already expanded so that there will not be any hickups while collapsing it.
if textview has more than four lines, boolean flag will be true and the button will be visible so this is the code for expanding and collapsing animation.
btnSeeMore.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                if (!expand) {
                    expand = true;
                    ObjectAnimator animation = ObjectAnimator.ofInt(tvDescription, "maxLines", 40);
                    animation.setDuration(100).start();
                    btnSeeMore.setImageDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.ic_collapse));
                } else {
                    expand = false;
                    ObjectAnimator animation = ObjectAnimator.ofInt(tvDescription, "maxLines", 4);
                    animation.setDuration(100).start();
                    btnSeeMore.setImageDrawable(ContextCompat.getDrawable(getActivity(),R.drawable.ic_expand));
                }

            }
        });

Comment below for further information

A: Easy and Simple way to achieve this is.
sample.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:id="@+id/tvSongDes"
        android:layout_marginStart="@dimen/dimen16"
        android:layout_marginEnd="@dimen/dimen16"
        android:layout_marginTop="@dimen/dimen16"
        android:maxLines="3"
        android:text="Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy Dummy dummy "
        android:layout_width="match_parent"
        android:layout_height="wrap_content"

        />

    <Button
        android:id="@+id/btShowmore"
        android:layout_width="wrap_content"
        android:layout_marginStart="@dimen/dimen16"
        android:text="Showmore..."
        android:textAllCaps="false"
        android:textColor="@android:color/holo_blue_light"
        android:background="@android:color/transparent"
        android:layout_height="wrap_content" />
</LinearLayout>

and inside your Activity onCreate..
 TextView tvSongDes;
    Button btShowmore;
          @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_devotional_songs_play);
                tvSongDes=(TextView)findViewById(R.id.tvSongDes);
                btShowmore=(Button)findViewById(R.id.btShowmore);
                btShowmore.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

               if (btShowmore.getText().toString().equalsIgnoreCase("Showmore..."))
                        {
                            tvSongDes.setMaxLines(Integer.MAX_VALUE);//your TextView
                            btShowmore.setText("Showless");
                        }
                        else
                        {
                            tvSongDes.setMaxLines(3);//your TextView
                            btShowmore.setText("Showmore...");
                        }
                    }
                });

            }

Hoping it will be helpfull for someone.

A: Latest method , using MotionLayout  as the parent layout, no custom views requires, can be done only with xmls files.
'MotionLayout'  is a subclass of ConstrainLayout.
Steps are :-

*

*Create the entire layout with ConstraintLayout as the parent layout.

*Covert the parent layout to MotionLayout.

*Now we need to create a animation through a motionscene file that we will create
as motionscene.xml . It will contain the states of our textview and morebutton
before and after the click event of the morebutton. And it also contains the
transition information.
The code  for this step :-
<?xml version="1.0" encoding="utf-8"?>
<MotionScene xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto">

 <ConstraintSet android:id="@+id/start">
    <Constraint android:id="@+id/disc_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/discription_title">

        <CustomAttribute app:attributeName="maxLines"
            app:customIntegerValue="3"/>

    </Constraint>

</ConstraintSet>

<ConstraintSet android:id="@+id/end">
    <Constraint android:id="@+id/disc_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/discription_title">

        <CustomAttribute app:attributeName="maxLines"
            app:customIntegerValue="100"/>

    </Constraint>
    <Constraint android:id="@+id/more_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@id/disc_text">

        <CustomAttribute app:attributeName="alpha"
            app:customFloatValue="0.0"/>

    </Constraint>

</ConstraintSet>

<Transition
    app:constraintSetEnd="@id/end"
    app:motionInterpolator="easeIn"

    app:constraintSetStart="@+id/start"
    app:duration="200">

    <OnClick app:clickAction="transitionToEnd"
        app:targetId="@+id/more_text"/>

</Transition>
</MotionScene>

*Set this layout as the layoutDiscrition for the parent MotionLayout that we
created initially.
Enjoy the animation!!.


text:
Q: Solving a Cubic Equation with Linear Systems? I wish to solve a cubic equation on a computer as fast as possible. Yes, I could stick it into some gradient descent based solver but it is too slow. I am curious if the following equation can be solved with linear systems. What I have below is unwrapped form of a cubic bezier curve equation in 2D
$t^3(p_3 - 3p_2 + 3p_1 - p_0) + t^23(p_2 - 2p_1 + p_0) + t3(p_1 - p_0) + p_0 - p = 0$
Which I will simplify as two constraints with some new notation
$t^3(p_{0x}) + t^2(3*p_{1x}) + t^3(3*p_{2x}) + p_{3x} = px$
$t^3(p_{0y}) + t^2(3*p_{1y}) + t^3(3*p_{2y}) + p_{3y} = py$
I rewrite it as follows:
$\left[\begin{array}{ccc}
p_{0x} & p_{1x} & p_{2x}\\
p_{0y} & p_{1y} & p_{2y}\\
? & ? & ?
\end{array}\right]*\left[\begin{array}{c}
t^{3}\\
t^{2}\\
t
\end{array}\right]=\left[\begin{array}{c}
p_{3x}-p_{x}\\
p_{3y}-p_{y}\\
?
\end{array}\right]$
But I am not sure what to fill for the last column, or if i have to add any more columns. In my case when solving this Ax=b system, x is constraint by the fact that it is just square or cube of the same value. So i need to represent that in another set of numbers i can provide.

A: As said in the linked page, using the analytical formulae for the solutions of a cubic equation is extremely expansive in terms of CPU time.
Having spent (wasted ?) more then fifty years with cubic equations (in the are of applies thermodynamics), I shall try to summarize the method we used in my former research group.
Considering the equation
$$\alpha x^3+\beta x^2+\gamma x+\delta=0$$ first divide everything by $\alpha$ and consider that you look for the zero'(s) of function
$$f(x)= x^3+a x^2+b x+c$$
$$f'(x)=3 x^2+2a x+b$$
For the case where $f'(x)$ shows two real roots $x_-$ and $x_+$ : if $f(x_-)>0$ and $ f(x_+) <0$, there are three real roots. To estimate the starting point of Newton method,  starting of the left, select
$$x_0=x_- -\sqrt{-2\frac{f(x_-)}{f''(x_-)}}$$ If you prefer to start on the right, use
$$x_0=x_+ +\sqrt{-2\frac{f(x_+)}{f''(x_+)}}$$ Use Newton method to get the first root $x_1$ and, using deflation, what remains is to find $x_2$ and $x_3$ which are the solutions of
$$x^2+ (a+x_1)x-\frac{c}{x_1}=0$$


text:
Q: Is there any way to run spark scripts and store outputs in parallel with oozie? I have 3 spark scripts and every one of them has 1 spark sql to read a partitioned table and store to some hdfs location. Every script has a different sql statement and different folder location to store data into.
test1.py - Read from table 1 and store to location 1.
test2.py - Read from table 2 and store to location 2.
test3.py - Read from table 3 and store to location 3.

I run these scripts using fork action in oozie and all three run. But the problem is that the scripts are not storing data in parallel.
Once the store from one script is done then the other store starts.
My expectation is to store all 3 tables data into their respective locations parallely.
I have tried FAIR scheduling and other scheduler techniques in the sparks scripts but those don't work. Can anyone please help.I am stuck with  it from last 2 days.
I am using AWS EMR 5.15, Spark 2.4 and Oozie 5.0.0.

A: For Capacity scheduler
If you are submitting job to a single queue whichever job come first in the queue gets the resources. intra-queue preemption won't work.
I can see a related Jira for Intraqueue preemption in Capacity scheduler. https://issues.apache.org/jira/browse/YARN-10073
You can read more https://blog.cloudera.com/yarn-capacity-scheduler/
For Fair scheduler
Setting the "yarn.scheduler.fair.preemption" parameter to "true" in yarn-site.xml enables preemption at the cluster level. By default this is false i.e no preemption.
Your problem could be:
1 job is taking maximum resources. To verify this please check Yarn UI and Spark UI.
Or if you have more than 1 yarn queue (other than default). Try setting User Limit Factor > 1 for the queue you are using.


text:
Q: How to pass Pillow image data to scikit-learn? I am trying to train an image classifier in scikit-learn. I have a bunch of input images and I am using Pillow to process them. My question is about what shape to give the Pillow data to scikit-learn.
This is my code now:
training = glob.glob('./img/training/*/*.bmp')
data = []
classes = []
for imagefile in training:
    edges = Image.open(imagefile).filter(ImageFilter.FIND_EDGES).convert("L")
    in_data = np.asarray(edges, dtype=np.uint8)
    data.append(in_data[0])
    if 'class1' in imagefile:
        classes.append('class1')
    else:
        classes.append('class2')
clf = svm.SVC(gamma=0.001, C=100.)
clf.fit(data, classes)

This runs without errors, but I have put the code together fairly crudely and I am not sure it is correct.
In particular, I'm not sure whether I should be using in_data[0]. I just did this because using in_data gives me an error: ValueError: Found array with dim 3. Estimator expected <= 2.

A: Unless you want the first row of the image matrix ( in_data[0] returns you the first row ) of each image, you probably want to use flattening.
Flattening will take each row of the image matrix and put the rows behind eachother in a 1 dimensional vector.
So it becomes data.append(in_data.flatten())
You could resize your image to a smaller format first, to reduce the number of columns of your data matrix.


text:
Q: isDigit() returning true for letter When running the following program and inputing a letter, one of the output windows says that the letter is a digit when it is clearly not. Why?
import javax.swing.JOptionPane;

/**
 * This program demonstrates some of the Character
 * class's character testing methods
 *
 *
 */
public class CharacterTest {

public static void main(String[] args){
    String input;   //To hold the user's input
    char ch;    //To hold a single character

    //Get a character from the user and store
    //it in the ch variable
    input=JOptionPane.showInputDialog("Enter "+
            "any single character.");

    ch= input.charAt(0);

    //Test the character
    if(Character.isLetter(ch)){
        JOptionPane.showMessageDialog(null, "This is a letter.");
    }

    if(Character.isDigit(ch));{
        JOptionPane.showMessageDialog(null, "Thit is a digit.");
    }

    if(Character.isLowerCase(ch)){
        JOptionPane.showMessageDialog(null, "That is a lowercase"+
                " letter");
    }

    if(Character.isUpperCase(ch)){
        JOptionPane.showMessageDialog(null, "That is an uppercase"+
                " letter");
    }

    if(Character.isSpaceChar(ch)){
        JOptionPane.showMessageDialog(null, "That is an uppercase"+
                " letter");
    }

    if(Character.isWhitespace(ch)){
        JOptionPane.showMessageDialog(null, "That is an uppercase"+
                " letter");
    }

    System.exit(0);

}
}

A: if(Character.isDigit(ch));{
        JOptionPane.showMessageDialog(null, "Thit is a digit.");
    }

That means:
JOptionPane.showMessageDialog(null, "Thit is a digit.");

without any condition, so it will always print that it's a digit.
By the way, neither spaces nor white spaces (funny how Java distinguishes between the two) are "uppercase letters".


text:
Q: Embedded tweets not displaying properly in vue I am using django as my backend and vue frontend. I have a model that has a richtexteditor, and in my save method, it converts tweet links to embedded html tweets instead, I do not believe this part is important, just thought that I would need to provide some preface as to what my problems are. So within vue, I have a div with v-html set to the contents of the model. The contents of the div match everything else I have saved except the tweets won't display properly. The contents of the tweets are displayed without the container, profile image etc.
I have tried copying the embedded tweet html in the inspect tool in chrome and used w3schools tryit editor, and it loaded properly
HTML for embedded tweet:

Thank you all for replying to our tweets. I think I'll do just one more for the night... I have to go to prepare for tomorrow's festivities! .
— AMNotify (@AMNotify) September 10, 2019

How it is displayed:

Thank you all for replying to our tweets. I think I'll do just one more for the night... I have to go to prepare for tomorrow's festivities! .— AMNotify (@AMNotify) September 10, 2019

How it should be displayed:
https://jsfiddle.net/z7wgLqcb/

A: Solved, needed to add  to index.html


text:
Q: How to count the number of words in wysiwyg editor javascript? I am using WYSIWYG editor, written there and saved it.
I just want to count the number of characters I have written.
Suppose I have written "My Count is 4", Then it should show me the count as 13
and after marking it bold or Italic the count should remain same as 13.
The code I am using to count is jQuery(selector).text().length;
But its returning me the data, along with html tags.
and if I have written "My Count is 4" in Bold in editor. The count is increasing, because its counting the html <b></b> tags also.
Please help me to find the solution.

A: Try something like this:
// firstly we'll strip the html out
var myCode = jQuery('#getMe').html();
// strip out tags and line breaks
var cleanCode = myCode.replace(/<(?:.|\n)*?>/gm, '').replace(/(\r\n|\n|\r)/gm,"").replace(' ','');

// then count as normal
var numChars = cleanCode.trim().length;

Have a look at this fiddle


text:
Q: How to add text into input area with javascript radio button I am trying to achieve a function where-by a user would choose an option  via a radio button and the value would be added into an input text box.
I used the onClick but wasn't efficient enough.
/*
button
<div onClick="
document.forms['name_of_ the_form']['name_of_the_ input'].value += 'text you want to add to it'" > button </div>
*/

A: This is what you can do:
var radioArray = document.getElementsByName("radio");
for (i = 0; i < radioArray.length; i++) {
    radioArray[i].onclick = alertText;
}

function alertText () {
    document.getElementById("text").innerHTML = this.value;
}

Live version: http://jsfiddle.net/mankinchi/sL4cfj7r/
"this" in the alertText function will refer to the actual element that has been clicked on.

A: You can use a bit of jQuery to achieve this quite easily.
HTML:
<input type="radio" name="radio" value="Something">Something
<input type="radio" name="radio" value="Something 2">Something 2
<input type="radio" name="radio" value="Something 3">Somethign 3
<textarea id="target"></textarea>

JS:
$(document).ready(function(){
    $('input[name=radio]:radio').on('change', function() {
        $('#target').val( $(this).val() );
    });
});

http://jsfiddle.net/1an0p4z6/
----- Non jQuery -----
HTML:
<input type="radio" name="radio" class="radio" value="Something">Something
<input type="radio" name="radio" class="radio" value="Something 2">Something 2
<input type="radio" name="radio" class="radio" value="Something 3">Somethign 3

<textarea id="target"></textarea>

JS:
var buttons = document.querySelectorAll('.radio');

for( i=0; i<buttons.length; i++ ) {
    buttons[i].addEventListener('change',function(){
        document.querySelector('#target').value = this.value;
    });
}

http://jsfiddle.net/jh10nf5e/1/

A: Using javascript I can give you an example:
function myfunction() {
    var radios = document.getElementsByName('radname');
    if (radios[0].checked) {
        radvalue = radios[0].value
    } else if (radios[1].checked) {
        radvalue = radios[1].value
    }
    document.getElementById('txt').value = radvalue;
}

DEMO
Use this just as an reference, will help you.


text:
Q: Java inner class with the same name as other top level class I have question related to Java inner classes.
Is there a way to access top level class A from top level class Main that define inner class A?
Below is sample code demonstrating the problem:
class A {   // Outer Class A
  {
    System.out.println("A outer");
  }
}

class B {   // Outer Class B
  {
    System.out.println("B outer");
  }
}

public class Main {
  class A {  // Inner Class A
    {
      System.out.println("A inner");
    }
  }

  public void newA() {
    class A {   // Local Class A
      {
        System.out.println("A local");
      }
    }
    new A();
  }

  public static void main(String[] args) {
    new Main().newA();  // prints "A local"
    new Main().new A(); // prints "A inner"
    //new A();    // compiler error: No enclosing instance of type Main is Accessible.
    new B();      // but this works and prints "B outer"
  }
}

A: Use the fully qualified class name:
new com.mypackage.A();

A: If your classes are in packages, I'd expect that to be the simplest way of achieving this. I don't believe there's any equivalent of the C# global:: for Java, to force this sort of thing.
Ultimately though, I'd just try to change the class names to avoid the problem happening in the first place. That's usually a better approach than using workarounds.

A: You should provide different package names for your two As so that they are clearly different types, then you can reference them by their full names.
For example:
my.package.for.toplevel.A outerA = new my.package.for.toplevel.A(); // prints "A outer"
                                                                    // if this is the
                                                                    // package

Or even better, use two different names for two distinct classes.

A: The name of the inner class is said to shadow the name of the top-level class. The top-level class cannot be referenced by its simple name in the scope of the inner class; the top-level class can only be referenced via a qualified name.
If the top-level class is in the default package (in which case its canonical name is the same as its simple name), you can still access it via reflection.

A: Yep, just use packages or avoid naming them the same from the beginning. I wonder what's your reason to name them the same anyway?
To explain your error, it comes from the fact that it tries to access the inner A, but since that class is not declared as static and there's no Main instance available, it can't create a non-static inner A that requires a reference to parent Main instance.

A: Assumed the classes are in the default package. To resolve naming conflict in this case needs either rename the conflicting classes or use the named package. Then use FQCN to resolve the issue.


text:
Q: Как отправить сообщение в ВК с помощью POST запросов, избегая api Нашел код для авторизации, он вроде работает:
import lxml.html
import requests

login = 'логин'
password = 'пароль'
url = 'https://vk.com/'

headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 6.0; rv:14.0) Gecko/20100101 Firefox/14.0.1',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language':'ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3',
    'Accept-Encoding':'gzip, deflate',
    'Connection':'keep-alive',
    'DNT':'1'
}
session = requests.session()
data = session.get(url, headers=headers).content
page = lxml.html.fromstring(data)

form = page.forms[0]
form.fields['email'] = login
form.fields['pass'] = password

response = session.post(form.action, data=form.form_values())
print(response.text)

Помогите разобраться, как в будущем самому смотреть какие post запросы куда с сайта отправляются, и как их отловить, чтобы потом перенести в python.
P.S.
Сделал, как говорил пользователь Mr Morgan и получил такие вот значения
act:a_send
al:1
gid:0
guid:151773532908381
hash:1517735163_cd46fbd56673503461
im_v:2
media:
msg: test message
random_id:626404632
to: id того, кому я писал

Дальше Mr Morgan писал

Вы увидите значения переменных, их нужно указывать в качестве словаря(аналогично headers), но передавать в качестве data.

Но переменные guid, hash и random_id постоянно меняются, как их формировать?

A: Вот готовый код.
import lxml.html
import requests

login = ваш Логин
password = ваш пароль

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36',
    'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
    'Accept-Language':'ru-ru,ru;q=0.8,en-us;q=0.5,en;q=0.3',
    'Accept-Encoding':'gzip, deflate',
    'Connection':'keep-alive',
    'DNT':'1'}

def log_in(url, headers, session, login, password, proxy = None):
    data = session.get(url, headers=headers, proxies = proxy)
    page = lxml.html.fromstring(data.content)

    form = page.forms[0]
    form.fields['email'] = login
    form.fields['pass'] = password

    response = session.post(form.action, data=form.form_values())

def send_msg(msg, whom, headers, session, proxy=None):
    data_msg=f'act=a_send&al=1&entrypoint=&gid=0&hash={user_hash}&im_v=3&media=&msg={msg}&to={whom}'
    session.post('https://vk.com/al_im.php', data=data_msg)

session = requests.session()
log_in('https://vk.com/', headers, session, login, password)
send_msg(msg, whom, user_hash, headers, session)

Функция send_msg - собственно отправка сообщения, ее аргументы:
1. msg--сообщение, которое вы хотите отправить
2. whom - id пользователя, которому вы отправляете
3. user_hash - это hash в post запросе, его достаточно один раз для одного пользователя взять (как это сделать уже сказано Mr Morgan

A: Google Chrome
F12 -> Вкладка Network ->
делаете так, чтобы браузер отправил форму(нажимаете кнопку войти или подобные) ->
нажимаете красную кнопку(stop record) -> просматриваете запросы, которые Вы поймали.
В остальных браузерах нужно найти панель разработчика и сделать аналогичные действия.

Вы увидите значения переменных, их нужно указывать в качестве словаря(аналогично headers), но передавать в качестве data.

session.post(..., data={...})


text:
Q: Avoid memory leak with WeakReference Android I have this code example below and i want to make sure that no memory will happen. By passing the whole activity to an async task will lead to a memory leak if the task itself will have a bigger lifecycle than activity's. But if i declare a weakReference, means that if a rotation is about to happen, the activity will be destroyed without memory leak. Am right guys? Do i have to set something to null also?
Main .java
public class Main extends Activity {

  private TextView mMessageView;

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

    new Background(this /*getBaseContext()*/ ).execute();
  }
}

Background.java
 public class Background extends AsyncTask<String, Void, String>
{
    private WeakReference activity;

    public void Background(Activity act)
    {
          activity = new WeakReference(act);
    }

    @Override
    protected String doInBackground(String... params)
    {

    }

    @Override
    protected void onPostExecute(String result)
    {
            if(activity.get()!=null)
            //ToDo
    }
}

A: There is no need for explicit nulling when using WeakReference. Regarding the use of AsyncTask inside an Activity, just be careful not to create an anonymous instance because it will have an implicit reference to the enclosing class which can lead to memory leaks.
The code you posted seems ok, don't forget to terminate the AsyncTask gracefully when the activity is recreated.


text:
Q: How to use this.http.post multiple times? Using Angular10 and Typescript.
Actually, I can use this.http.post multiple times since I reload the page after calling it.
My questions is, how could I do that but no using 'window.location.relaod()'.
So, I am opening a Dialog to edit Parent's data. It only works if I use
dialog.afterClosed(){
window.location.reload()};

Function behind 'send button':
async onOkClick() {
var e = await this.groceryListCrudService.post(this.myData);
this.dialogRef.close('Ok');
}

This is my post function:
post(item: Partial<PortFolio>) {
    return this.http.post<any>(this.url, item, this.httpOptions).subscribe({
      next: (data) => {
        this.post = data.id;
      },
      error: (error) => {
        console.error('There was an error!', error);
      },
    });
  }

This is the Error I get when I click on it twice (even I wait it to be inserted on database):

ERROR Error: Uncaught (in promise): TypeError:
this.groceryListCrudService.post is not a function TypeError:
this.groceryListCrudService.post is not a function

I don't know what else should be useful to show here. If it is missing something, I can show more of the code.
Thanks!

A: Instead of this.post = data.id you have to use return data.id. You cannot assign a value to the function itself.


text:
Q: android - Cursor returning wrong values I'm querying some products in SQLite database, but same base in 2 differents android's versions return differents values.
Select result in database.db3 using SQLite Expert:

I create this code after select, to test:
        if(cursor.moveToFirst()){
            while(!cursor.isAfterLast()){
                log("CDPROD:" + cursor.getString(cursor.getColumnIndex("CDPROD")));
                cursor.moveToNext();
            }
        }

Log Result in android 2.2:
09-26 14:30:08.947: INFO/LOGG(20497): CDPROD:000000000000211934
09-26 14:30:08.967: INFO/LOGG(20497): CDPROD:000000000000211944
09-26 14:30:08.967: INFO/LOGG(20497): CDPROD:000000000000212020
09-26 14:30:08.967: INFO/LOGG(20497): CDPROD:000000000000212124
09-26 14:30:08.967: INFO/LOGG(20497): CDPROD:000000000000214280
09-26 14:30:08.967: INFO/LOGG(20497): CDPROD:000000000000212886

Log Result in android 2.1:
09-26 14:18:16.772: INFO/LOGG(1039): CDPROD:211934
09-26 14:18:16.772: INFO/LOGG(1039): CDPROD:211944
09-26 14:18:16.772: INFO/LOGG(1039): CDPROD:212020
09-26 14:18:16.772: INFO/LOGG(1039): CDPROD:212124
09-26 14:18:16.772: INFO/LOGG(1039): CDPROD:214280
09-26 14:18:16.772: INFO/LOGG(1039): CDPROD:212886

This is a bug in Android??
Ty

A: You need to use as the column type text not string or varchar when you create your SQLiteTables. It seems that if you put string it will trim your leading zeros. Also see SQLite Data Types.
EDIT: According to this answer: Versions of SQLite in Android, they have diffrent SQLite versions.