text:
Q: .Net HMAC and base64 Encoding Issue I am trying to create a base64-encoded HMAC SHA512 hash using a secret of secret and a payload of foo. I am unable to make my .NET code produce the correct value. I am wondering if the encoding is the underlying issue.
Code:
UTF8Encoding encoding = new UTF8Encoding();
HMACSHA512 hmac = new HMACSHA512(encoding.GetBytes("secret")); // init the HMAC hash with "secret" as a byte array
byte[] hash = hmac.ComputeHash(encoding.GetBytes("foo")); // hash the payload
String result = Convert.ToBase64String(hash); // Base64 encode the payload

The incorrect hash & base64 result:
gt9xA96Ngt5F4BxF/mQrXRPGwrR97K/rwAlDHGZcb6Xz0a9Ol46hvekUJmIgc+vqxho0Ye/UZ+CXHHiLyOvbvg==
The expected hash & base64 result:
ODJkZjcxMDNkZThkODJkZTQ1ZTAxYzQ1ZmU2NDJiNWQxM2M2YzJiNDdkZWNhZmViYzAwOTQzMWM2NjVjNmZhNWYzZDFhZjRlOTc4ZWExYmRlOTE0MjY2MjIwNzNlYmVhYzYxYTM0NjFlZmQ0NjdlMDk3MWM3ODhiYzhlYmRiYmU=

A: Since second version is just Base64 of Hex representation you need to convert byte array to hex first and than Base64 ASCII version of the string.
Steps:

*

*How do you convert Byte Array to Hexadecimal String, and vice versa?

*C# Convert a string to ASCII bytes

*Conversion from byte array to base64 and back


text:
Q: How can I create an SCR using a PNP and NPN? Several times I have seen an SCR described as similar to a PNP and NPN transistor linked together. But any attempt to replicate the idea seems to fail. In the circuit below, for example, the LED is always on.

simulate this circuit – Schematic created using CircuitLab
What am I doing wrong?

A: This can be made to work as an SCR type circuit. There are couple of things to consider though.
One item, as pointed out by David Tweed, is the need to put bleeder resistors across the BE junctions of both transistors to keep leakage from instantly turning on the coupled PNP-NPN pair.
Another item is that a fast turn on rate of the supply voltage can couple through the transistor junction capacitance and cause the pair to come on. Real SCRs also have this same problem if the dV/dT is too fast.
Here is an LTSPICE simulation of the circuit working as expected. Note the gentle 100usec turn on of the power supply and the added BE resistors. Note I also replaced the switch with a transistor to simulate the switch.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Allowing line break at ',' in inline math mode? In the inline math mode ($...$), if the formula is too long, LaTeX will try to break it on operators, e.g.
very long text followed by a very long equation like $a+b+c+d+e+f+g+h+i+j+k+l$ etc

may be rendered as
very long text followed
by a very long equation
like a+b+c+d+e+f+g+h+i+
j+k+l etc

However, the break won't happen if they are separated by commas, e.g.
very long text followed by a very long equation like $a,b,c,d,e,f,g,h,i,j,k,l$ etc

will overflow the page like
very long text followed
by a very long equation
like a,b,c,d,e,f,g,h,i,j,k,l
etc

How to make LaTeX able to insert line breaks after a comma too?

A: You could take a look at the breqn package, which is aimed at solving this problem in a general sense.

A: In luatex you have a new possibility that does not involve active characters, you can declare , to be a mathbin (like +) so that line breaking is allowed and then set the mathord-mathbin spacing to zero so it gets no space before, like punctuation:

\documentclass{article}

\begin{document}

$
\mathcode`\,="213B % mathbin
\Umathordbinspacing\textstyle 0mu % no space before
a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,
a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a,a$
\end{document}

A: Here is a solution that doesn't make the comma globally active:
\documentclass{article}

\newcommand{\splitatcommas}[1]{%
  \begingroup
  \begingroup\lccode`~=`, \lowercase{\endgroup
    \edef~{\mathchar\the\mathcode`, \penalty0 \noexpand\hspace{0pt plus 1em}}%
  }\mathcode`,="8000 #1%
  \endgroup
}

\begin{document}

\setlength{\lineskiplimit}{2pt}\setlength{\lineskip}{3pt} % for this particular case

$\splitatcommas{
  \frac{1}{2},\frac{3}{5},\frac{8}{13},\frac{21}{34},\frac{55}{89},
  \frac{144}{233},\frac{377}{610},\frac{987}{1597},\frac{2584}{4181},
  \frac{6765}{10946},\frac{17711}{28657},\frac{46368}{75025},
  \frac{121393}{196418},\frac{317811}{514229},\frac{832040}{1346269},
  \frac{2178309}{3524578},\frac{5702887}{9227465},
  \frac{14930352}{24157817},\frac{39088169}{63245986},\frac{102334155}{165580141}
}$

\end{document}

The setting of \lineskiplimit and \lineskip are for the particular case where fractions are needed in the argument.

A variant that allows nesting:
\documentclass{article}

\newcommand{\splitatcommas}[1]{%
  \begingroup
  \ifnum\mathcode`,="8000
  \else
    \begingroup\lccode`~=`, \lowercase{\endgroup
      \edef~{\mathchar\the\mathcode`, \penalty0 \noexpand\hspace{0pt plus 1em}}%
    }\mathcode`,="8000
  \fi
  #1%
  \endgroup
}

\newcommand{\tuple}[1]{(\splitatcommas{#1})}
\newcommand{\set}[1]{\{\splitatcommas{#1}\}}

\begin{document}

\setlength{\lineskiplimit}{2pt}\setlength{\lineskip}{3pt} % for this particular case

$\splitatcommas{
  \frac{1}{2},\frac{3}{5},\frac{8}{13},\frac{21}{34},\frac{55}{89},
  \frac{144}{233},\frac{377}{610},\frac{987}{1597},\frac{2584}{4181},
  \frac{6765}{10946},\frac{17711}{28657},\frac{46368}{75025},
  \frac{121393}{196418},\frac{317811}{514229},\frac{832040}{1346269},
  \frac{2178309}{3524578},\frac{5702887}{9227465},
  \frac{14930352}{24157817},\frac{39088169}{63245986},\frac{102334155}{165580141}
}$

$\set{
  \tuple{a,b,c,d},\tuple{1,2,3,4,5,6},\tuple{11,22,33,44,55,66,77,88},
  \tuple{a,b,c,d},\tuple{1,2,3,4,5,6},\tuple{11,22,33,44,55,66,77,88},
  \tuple{a,b,c,d},\tuple{1,2,3,4,5,6},\tuple{11,22,33,44,55,66,77,88},
  \tuple{a,b,c,d},\tuple{1,2,3,4,5,6},\tuple{11,22,33,44,55,66,77,88}
}$

\end{document}

A: Just try inserting \allowbreak in between your inline equations.
$x_1, x_2,...\allowbreak, y_1,y_2,y_n$.
The line won't reach out and break at before y_1

A: If the expression contains many commas then consider to break it into several math expressions, separated by commas. It reads like a list of math expressions. This way TeX can break the line.
To achieve line breaks after a comma, you could insert \allowbreak after the comma and before the next math symbol. If necessary, leave a blank after \allowbreak.
If you would like to have a document wide solution, you could redefine the comma. One solution, following the tip here would be:
\makeatletter
\def\old@comma{,}
\catcode`\,=13
\def,{%
  \ifmmode%
    \old@comma\discretionary{}{}{}%
  \else%
    \old@comma%
  \fi%
}
\makeatother

A: If you can split the equation into several sub equation using $, and if you are using braces use \left. and \right. (with dot) to balance the braces.
Example:
 $X = \left\{\right.a$, $b$, $c$, $d\left.\right\}$

X = { a, b, c, d }
This should allow line breaks behind the commas.


text:
Q: Syntax error, unexpected ':', expecting ')' (SyntaxError) I have this code:
 19   context 'overriding at fabricate time' do
 20     let(:fabricated_object) do
 21       Fabricate(
 22         "#{fabricator_name}_with_children", do
 23         string_field: 'new content',
 24         number_field: 10,
 25         nil_field: nil,
 26         placeholder: 'is not invoked',
 27         dynamic_field: { 'new dynamic content' }
 28       end)
 29     end

Fabricator:
  1 class Fabrication::Fabricator
  2
  3   def self.build(name, overrides={}, &block)
  4     fail_if_initializing(name)
  5     schematic(name).build(overrides, &block)
  6   end
  7
  8   def self.fabricate(name, overrides={}, &block)
  9     fail_if_initializing(name)
 10     schematic(name).fabricate(overrides, &block)
 11   end
 12
 13   def self.to_attributes(name, overrides={}, &block)
 14     fail_if_initializing(name)
 15     schematic(name).to_attributes(overrides, &block)
 16   end
 17
 18   def self.to_params(name, overrides={}, &block)
 19     fail_if_initializing(name)
 20     schematic(name).to_params(overrides, &block)
 21   end
 22
 23   private
 24
 25   def self.fail_if_initializing(name)
 26     raise Fabrication::MisplacedFabricateError.new(name) if Fabrication.manager.initializing?
 27   end
 28
 29   def self.schematic(name)
 30     Fabrication::Support.find_definitions if Fabrication.manager.empty?
 31     Fabrication.manager[name] || raise(Fabrication::UnknownFabricatorError.new(name))
 32   end
 33
 34 end

but I keep getting
integration_spec.rb:23: syntax error, unexpected ':', expecting ')' (SyntaxError)
        string_field: 'new content',
                     ^
/home/durrantm/Dropbox/96_2013/work/code/ruby/fabrication_temp/spec/_seded/integration_spec.rb:23: syntax error, unexpected ',', expecting kEND
/home/durrantm/Dropbox/96_2013/work/code/ruby/fabrication_temp/spec/_seded/integration_spec.rb:25: Can't assign to nil
/home/durrantm/Dropbox/96_2013/work/code/ruby/fabrication_temp/spec/_seded/integration_spec.rb:26: syntax error, unexpected ':', expecting '='
        placeholder: 'is not invoked'
                    ^
/home/durrantm/Dropbox/96_2013/work/code/ruby/fabrication_temp/spec/_seded/integration_spec.rb:27: syntax error, unexpected ')', expecting kEND
...

How can I get around this?
I've tried formatting the hash in a number of ways but none worked.
Code used to work in this format (I am trying to move to expect):
  context 'overriding at fabricate time' do
    let(:fabricated_object) do
      Fabricate(
        "#{fabricator_name}_with_children",
        string_field: 'new content',
        number_field: 10,
        nil_field: nil,
        placeholder: 'is not invoked'
      ) do
        dynamic_field { 'new dynamic content' }
      end
    end

I also tried:
 19   context 'overriding at fabricate time' do
 20     let(:fabricated_object) do
 21       Fabricate(
 22         "#{fabricator_name}_with_children",
 23         { string_field: "new content",
 24         number_field: 10,
 25         nil_field: nil,
 26         placeholder: 'is not invoked',
 27         dynamic_field: { 'new dynamic content' }})
 28
 29     end

but got
integration_spec.rb:23: odd number list for Hash (SyntaxError)
    { string_field: "new content",

A: Try arranging that call to Fabricate(...) as follows:
  Fabricate("#{fabricator_name}_with_children".to_sym) do
    string_field  'new content'
    number_field  10
    nil_field     nil
    placeholder   'is not invoked'
    dynamic_field { 'new dynamic content' }
  end

Edit: I've done some local console experimentation to make sure it should work. I'm assuming those values are defaults for a fabricator, e.g.
2.0.0p195 :014 > Fabricator(:x) do
2.0.0p195 :015 >   string_field  'new content'
2.0.0p195 :016?>   number_field  10
2.0.0p195 :017?>   nil_field     nil
2.0.0p195 :018?>   placeholder   'is not invoked'
2.0.0p195 :019?>   dynamic_field { 'new dynamic content' }
2.0.0p195 :020?> end

I can fabricate an instance ok--
2.0.0p195 :032 > Fabricate(:x)
 => #<X:0x98c32c4 @string_field="new content", @number_field=10, @nil_field=nil, @placeholder="is not invoked", @dynamic_field="new dynamic content">

I can pass a block like above--
2.0.0p195 :055 > Fabricate(:x) do
2.0.0p195 :056 >   string_field  'alternate content'
2.0.0p195 :057?>   number_field  999
2.0.0p195 :058?>   nil_field     nil
2.0.0p195 :059?>   placeholder   'changed'
2.0.0p195 :060?>   dynamic_field { 'different dynamic content' }
2.0.0p195 :061?> end
 => #<X:0x948eff0 @string_field="alternate content", @number_field=999, @nil_field=nil, @placeholder="changed", @dynamic_field="different dynamic content">

Or use a mixed mode with params/block:
2.0.0p195 :062 > Fabricate(:x, string_field: 'new content', number_field: 37, nil_field: nil, placeholder: 'blah') do
2.0.0p195 :063 >       dynamic_field { 'new dynamic content' }
2.0.0p195 :064?>   end
 => #<X:0x92c4e54 @string_field="new content", @number_field=37, @nil_field=nil, @placeholder="blah", @dynamic_field="new dynamic content">

At this stage I'd guess the problem is an unclosed block somewhere.

A: Shouldn't this:
 21       Fabricate(
 22         "#{fabricator_name}_with_children", do
 23         # ...
 28       end)

Be more like:
 21       Fabricate(
 22         "#{fabricator_name}_with_children") do
 23         # ...
 28       end

As in, with the closing parenthesis before the do, rather than (incorrectly) wrapping it?
Another possible alternative, in the event it still spits out an error, to make sure that operator precedence is applied correctly:
 21       Fabricate(
 22         "#{fabricator_name}_with_children") {
 23         # ...
 28       }

Yet another option, seeing that the contents of that thing looks like a hash rather than a block:
 21       Fabricate(
 22         "#{fabricator_name}_with_children", {
 23         # ...
 28       })


text:
Q: Levenshtein distance between two columns of two different dataframes Let's say i have two dataframes
Dataframe 1:

ID1
NAME1

1
JUANA

2
LUCAS

3
PEDRO

4
MATIAS

Dataframe 2:

ID2
NAME2

1
JUAN

2
JUANA

3
JUANITA

4
MATIAS

5
MATIA

6
MATIAS

7
MATIAZ

Each one don't have the same numbers of rows. I would like to create a third dataframe that compares each value of the first dataframe with the second.
Dataframe 3:

ID1
NAME1
NAME 2
Levenshtein

1
JUANA
JUANA
0

1
JUANA
JUAN
1

1
JUANA
JUANITA
3

2
LUCAS

5

3
PEDRO

5

4
MATIAS
MATIAS
0

4
MATIAS
MATIA
1

4
MATIAS
MATIAZ
1

Is there a way to accomplish that?
Thanks!


text:
Q: Extraction of .gz files contained in a folder I have a folder containing approximately 320116 .pdb.gz files. I want to uncompress them all. If I use gunzip *.gz it gives me an error i.e. argument list too long. The folder is about 2GB. Please give me an appropriate suggestion.

A: Whenever you get "argument list too long" errors you can work around it by invoking the desired command multiple times, each time with a subset of the arguments you want to use. xargs is a tool that helps you do that automatically.
find . -type f -a -name \*.pdb.gz -print0 | xargs -0 gunzip

A: find . -name '*.pdb.gz' -exec gunzip {} +

-exec gunzip {} + will provide gunzip with many but not too many file names on its command line.  This is more efficient than -exec gunzip {} \; which starts a new gunzip process for each and every file.

A: Try this way:
find . -name '*.gz' -exec gunzip {} \;

A: I think this should work, it passes the path/name of each file individually to gunzip for processing:
find /my/dir -name "*.pdb.gz" -execdir gunzip "{}" \;

A: If you have a multi-core machine you will probably see that using gunzip is not going to max out the capabilities of your machine. For that you would need to run multiple gunzips in parallel. To keep track of which are done in which terminal by hand is is cumbersome, but you can easily do that with GNU parallel:
find . -name "*.gz" | parallel -X gunzip {}

A: It is unnecessary to use find for this, since you did not mention subfolders. What you need to do is:
for f in *.gz;do gunzip $f;done


text:
Q: send form elements over ajax with kinetic js I'm using kinetic js to create a canvas and it also saves the canvas to an image file using this ajax:
    stage.toDataURL({
      callback: function(dataUrl) {
        var url = 'export.php';
        $.ajax({
            type: "POST",
            url: url,
            dataType: 'text',
            data: {
            base64data : dataUrl
            }
        });

I need to also pass some form variables to export.php - whats the best way to do that?
Thanks!
Zoe

A: Your JS part is correct:
function upload() {
    stage.toDataURL({
        callback: function (dataUrl) {
            $.ajax({
                type: "POST",
                url: 'export.php',
                dataType: 'text',
                data: {
                    base64data: dataUrl
                }
            });
        }
    });
}

In PHP, data arrive with the following pattern: 'data:image/png;base64,...characters'; ... So you have to extract the image part.
<?php
$data = $_POST['base64data'];

list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);

file_put_contents('image.png', $data);

Note that this solution is not specific to kineticjs. It can be used with any HTML5 canvas, provided that you replace stage.toDataURL() call by canvas.toDataURL().


text:
Q: mouseenter rollover effect only works after second entry I've tried to find similar posts on this specific matter with little success so hopefully someone a little more experienced with JQuery could shed light on my problem.
I'm currently working on a portfolio site, i.e. alot of images. I wanted to make a Jquery rollover effect when you hover above one of the thumbnail images presented on the site.
The effect itself has been achieve but it comes with a sort of bug. Whenever I refresh the page or view the page anew, whenever I my mouse enters the image container element which should trigger the Jquery effect, it doesn't do so the first time, but when I try it a second time without refreshing the page, the effect is there.
Here is the basic html markup:

Title

Watch Project

So as you can see I've solved my "rollover effect" with a "display: none" solution which I later let my Jquery code "fadeIn" to make it visible on the mouseenter effect.
Below is the CSS for span class="over", probably not necessary to show but just incase.
.over {
    width: 300px;
    height: 300px;
    background-image:url(Images/over.png);
    position: absolute;
    top: 0px;
    left 0px;
}

And now for my JQuery
$(document).ready(function(){
    $(".ImageContainer").mouseenter(function(){
        $(this).children('a').children('span').fadeIn(200);
    });
    $(".ImageContainer").mouseleave(function(){
        $(this).children('a').children('span').fadeOut(200);
    });
});

It seems the problem only arise when viewing it in a browser, this jsfiddle seems to work without issue. I am at loss as to why. All my links to my other documents also work and I have jquery and jquery UI linked.
http://jsfiddle.net/LRdR9/
SOLUTION TO MY PROBLEM:
my .over class didn't have "display: block;" which caused the browser to not see it. Upon second mouseenter it automatically put it there itself. It tricked me thinking I had another issue.

A: Everything seems to work in jsFiddle.
Note that in your jsFiddle you are running your code onload - make sure you're doing that in your file itself (be sure to place your jQuery inside the body, not the head). Also, make sure you're testing it in multiple browsers.
P.s. You could shorten your code to the following.
$(document).ready(function(){
   $(document).on('mouseenter mouseleave', '.ImageContainer', function () {
        $('a > span', this).fadeToggle(200);
   });
}):

Example jsFiddle.


text:
Q: Facebook Marketing API - Cannot Create Ad-Set I'm new to the facebook marketing API.
I was able to create a campaign.
But it seems I cannot create Adset.
I've tried posting with Javascript to the Adset:
https://graph.facebook.com/v2.8/act_156221465583672/adsets
with this payload:
    var targeting = {
        "age_max": 43,
        "age_min": 18,
        "geo_locations": { "countries": ["US"] }
    };

   var campaignId = "520337003094784508";

    var promotedObject = {
        'application_id': 2242592062246511
    };

and post body:
    {
        "access_token": accessToken,
        "name": "testNirAd",
        "lifetime_budget": "8000",
        "autobid": "true",
        "start_time": new Date("October 13, 2017 00:00:00"),
        "end_time": new Date("November 13, 2017 00:00:00"),
        "optimization_goal": "POST_ENGAGEMENT",
        "billing_event": "IMPRESSIONS",
        "daily_budget": "2000",
        "campaign_id": campaignId,
        "targeting": JSON.stringify(targeting),
        "status": "PAUSED"
    }

But I get this error:
     {
         "error": {
         "message": "Invalid parameter",
         "type": "OAuthException",
         "code": 100,
         "error_data": {
         "blame_field_specs": [
             [
                "name"
             ]
         ]
       },
       "error_subcode": 2061015,
       "is_transient": false,
       "error_user_title": "Required Field Is Missing",
       "error_user_msg": "The name field is required. Please complete the
       field to continue.",
      "fbtrace_id": "HFg4HmwbQhG"
   }

}
Which is strange because I have a name field.
Then I've tried the same with the Javascript SDK
https://github.com/lucascosta/facebook-js-ads-sdk, with the same payload data,
and this time I get:
       {
             code:1
             fbtrace_id:"DcXmP0Wr82Q"
             message:"An unknown error has occurred."
             type:"OAuthException"
       }
Please can anybody help?

A: Tried also with different, less parameters, with Curl, and got the same results:
curl /
-F 'name=MyFirstTest'  /
-F 'billing_event=IMPRESSIONS' /
-F 'bid_amount=2' /
-F 'daily_budget=1000' /
-F 'campaign_id=120330000094784508' /
-F 'targeting={"geo_locations":{"countries":["US"]}}' /
-F 'start_time=2017-10-14T16:06:09+0000' /
-F 'end_time=2017-11-21T16:06:09+0000' /
-F 'status=PAUSED' /
-F 'access_token= EAAf0hSLb7osBAEgUpUtkGydJ9mmfZCzYumfNVxDFUjBFtx7C8aos3x
LbzjwkZBEbgXkWAT75OvIy6HXNTFBEqN1ca1aVvWT3RQAAKAAi6jYyncTG3m9ae0MkZAM9gZDZD'
/https://graph.facebook.com/v2.8/act_116221225224746/adsets

And got:
{"error":{"message":"Invalid
parameter","type":"OAuthException","code":100,"error_data":
{"blame_field_specs":[["name"]]},"error_subcode":2061015,"is_transient":
false,"error_user_title":"Required Field Is Missing","error_user_msg":"The
name field is required. Please complete the field to
continue.","fbtrace_id":"AeI4nngXTmj"}}

fbtrace_id:  AeI4nngXTmj
By the way, I'm using a sandbox account.
Thanks!

A: I would recommend not posting the access tokens on public forums.
The error is most likely a formatting issue.
Easiest way to debug is to use the Graph API explorer tool, which lets you pick you app, generate the token, and define the parameters.
You can then get the curl code once you know the syntax is correct.
https://developers.facebook.com/tools/explorer/
Also, the code sample for creating app ads might help you, though it's not JS.
https://www.facebookmarketingdevelopers.com/samples/app_install_ad


text:
Q: How to write test cases for Prisma Service file? I am working in a NestJS project and had a question about that.
I'm not that fluent yet in writing unit test cases, I have written some generic ones for my controllers such as users.controller.spec.ts and for the services users.service.spec.ts. I was wondering, how would I go about writing the test file for the prisma.service.spec.ts? I have a prisma.service.ts file  that looks like this:
import { PrismaClient } from '@prisma/client';
import { Injectable, OnModuleDestroy, OnModuleInit } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

@Injectable()
export class PrismaService
  extends PrismaClient
  implements OnModuleInit, OnModuleDestroy
{
  constructor(config: ConfigService) {
    super({
      datasources: {
        db: {
          url: config.get<string>('DATABASE_URL'),
        },
      },
    });
  }

  async onModuleInit() {
    await this.$connect();
  }

  async onModuleDestroy() {
    await this.$disconnect();
  }

  async cleanDatabase() {
    if (process.env.NODE_ENV === 'production') return;
    const models = Reflect.ownKeys(this).filter((key) => key[0] !== '_');

    return Promise.all(models.map((modelKey) => this[modelKey].deleteMany()));
  }
}

And NestJS CLI generates this generic spec.ts file when you create a service that looks like this:
import { Test, TestingModule } from '@nestjs/testing';
import { PrismaService } from './prisma.service';

describe('PrismaService', () => {
  let service: PrismaService;

  beforeEach(async () => {
    const module: TestingModule = await Test.createTestingModule({
      providers: [PrismaService],
    }).compile();

    service = module.get<PrismaService>(PrismaService);
  });

  it('should be defined', () => {
    expect(service).toBeDefined();
  });
});


text:
Q: What permissions are required to create a new work item type in TFS I am new to creating work item types in TFS and want to create a new Work Item type.
I looked at work item template option, but that is not sufficient for me.
I need to add few new fields and have a customized form.
From search I got information about Work Item Type definition but I am looking for some detailed example.
Also I would like to know the permissions needed to add a new work item type.
I got administrator privileges for my project, but not on TFS as a whole.
With that can I add a new template for my project.
Please provide me direction.

A: Firstly, to create a new work item type you have to change the process template that the project is using. This is not easy and there are basically two options as outlined in this MSDN article.
Quoting from that article:

account must be a member of the Team
  Foundation Administrators group or
  have the Create new projects
  permission set to Allow.
  Additionally, your user account must
  be a member of the Windows
  SharePoint Services Administrator
  role and a member of the SQL Server
  Reporting Services Content Manager
  role. So quite a few permissions are
  required.


text:
Q: How to authenticate with the right scope via OAuth in Django? I am trying to login to my Django API from my other web app. I setup a application with the Django OAuth Toolkit (Resource owner password-based). The login works fine and I get back an accessToken but the scope I requested is not right. I get back r:profile but wanted instead rw:serverAdmin.
The user is a superuser in my Django application and I also added the rw:serverAdmin scope to the oauth toolkit list.
So the problem is: How do I login and have the rw:serverAdmin scope assigned?
Can anybody help me with this?


text:
Q: Network Adapter & System Time Problems on my ROG GL552VX Laptop Every time I first boot my new laptop into 16.04 LTS, and then reboot into Windows 7 (needed for my work), I get those 2 problems :
1) System Time gets a 2 hours difference in Windows (5.14pm under 16.04 LTS and then 03.14pm under Win 7) ===> Only Solution : Set Manually the time ... Not nice but working :(
2) Network Adapter gets recognized and its fixed IP but nothing works, even a simple ping to another LAN device ===> Only Solution : Reboot into Windows 7
If anyone has an idea for one or both problems, feel free to send me a message ..
Albert E.

A: Albert,
This happens because Windows doesn't do GMT offset timing by default.  To fix this, open Registry editor.
Navigate to
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TimeZoneInformation
Right click anywhere in the right pane and hit New > DWORD (32-bit) Value. Name it RealTimeIsUniversal, then double click on it and give it a value of 1.
As for the networking.  I'm not sure off the top of my head, can you send a dump of ifconfig?
Thanks,
PC


text:
Q: How to append item to drop down and save I have the following drop down list which I am able to append new listings to.
<script>
function Add()
{
 var x = document.getElementById("MySelectMenu");
 var opt = document.createElement("option");
    opt.value= document.getElementById("url").value;
    opt.innerHTML = document.getElementById("name").value; // whatever property it has
  x.add(opt);

}    </script>

<select id="MySelectMenu">

</select>
<button onClick="newSrc();">Load</button>
Name: <input type="text" name="name" id="name">
URL: <input type="url" name="url" id="url">
<button onclick="Add()">ADD</button>

What currently happens (for obvious reasons) is once the user closes the browser page, the list obviously returns to its previou state. How do I make it so the list remembers the appended items?

A: You can use cookies to save local data for the user, whenever the user adds an item to the list update the local cookie and when the page loads for the first time after a user comes back use an onLoad event to load the items from the cookie into the list.
this ofcourse will only be saved on the BROWSER level for that user, meaning if the same user opens the page in a difrent browser or on a difrent device these changes will not be saved.
to save info on a global nature you will need server side proccessing.

A: Since javascript or jQuery are front-end scripting languages, the changes made to a page will not be saved.
You would have to explicitly save the newly added items either in Cookies or Session using the following add-on plugins,

*

*https://github.com/carhartl/jquery-cookie

*https://github.com/AlexChittock/JQuery-Session-Plugin
And then handle the newly added elements when the page loads at a later time.


text:
Q: AppleScript bug: I am unable to convert rich text to plain text I created an AppleScript (.scpt) file entitled "Type Clipboard As Single Line Plain Text." The script is triggered by a keyboard shortcut set by FastScripts.
Desired behavior:
I want this script to take the clipboard contents, remove all formatting, and then remove any line breaks or tabs from this text. Finally, I want the script to type the new text. I want to preserve -- not overwrite -- the original clipboard contents.
The specific problem:
The specific error is that my script fails to remove all formatting from some rich text.
I cannot include full rich text content in a Stack Exchange post. Therefore, to witness my exact issue, please download this .rtf file via Dropbox. Open this file up in TextEdit.app. Highlight the sentence and copy it to the clipboard. Then, trigger my script while your cursor is in a form that supports and shows rich text (so that you can see that the script will type rich text).
You will notice that the typed sentence is rich text content and still contains formatting elements. These elements include the original text font (Helvetica) and the original font size (12). These elements should have been discarded. Thus, either my code is negligent or I have found a genuine bug within AppleScript itself. I am assuming that it is the latter.
The shortest code necessary to reproduce the error:
use AppleScript version "2.4"
use scripting additions
use framework "Foundation"
use framework "AppKit"

-- Back up clipboard contents:
set savedClipboard to my fetchStorableClipboard()

(*
    Converting the clipboard text to plain text to remove any formatting:
    From: http://lifehacker.com/127683/clear-text-formatting-on-os-x
*)
set theClipboardTextWithoutAnyFormatting to (the clipboard as text)

(*
    Removing line breaks and indentations in clipboard text:
    From: http://stackoverflow.com/a/12546965
*)
set AppleScript's text item delimiters to {return & linefeed, return, linefeed, character id 8233, character id 8232}
set theClipboardTextWithoutAnyFormatting to text items of (theClipboardTextWithoutAnyFormatting as text)
set AppleScript's text item delimiters to {" "}
set theClipboardTextWithoutAnyLineBreaksOrFormatting to theClipboardTextWithoutAnyFormatting as text

set the clipboard to theClipboardTextWithoutAnyLineBreaksOrFormatting
tell application "System Events" to keystroke "v" using {command down}
delay 0.1 -- Without this delay, may restore clipboard before pasting.
-- Restore the original clipboard:
my putOnClipboard:savedClipboard

on fetchStorableClipboard()
    set aMutableArray to current application's NSMutableArray's array() -- used to store contents
    -- get the pasteboard and then its pasteboard items
    set thePasteboard to current application's NSPasteboard's generalPasteboard()
    -- loop through pasteboard items
    repeat with anItem in thePasteboard's pasteboardItems()
        -- make a new pasteboard item to store existing item's stuff
        set newPBItem to current application's NSPasteboardItem's alloc()'s init()
        -- get the types of data stored on the pasteboard item
        set theTypes to anItem's types()
        -- for each type, get the corresponding data and store it all in the new pasteboard item
        repeat with aType in theTypes
            set theData to (anItem's dataForType:aType)'s mutableCopy()
            if theData is not missing value then
                (newPBItem's setData:theData forType:aType)
            end if
        end repeat
        -- add new pasteboard item to array
        (aMutableArray's addObject:newPBItem)
    end repeat
    return aMutableArray
end fetchStorableClipboard

on putOnClipboard:theArray
    -- get pasteboard
    set thePasteboard to current application's NSPasteboard's generalPasteboard()
    -- clear it, then write new contents
    thePasteboard's clearContents()
    thePasteboard's writeObjects:theArray
end putOnClipboard:

First, can someone confirm that the stated issue occurs on their computer?
If so, how can I remove all formatting of rich text in AppleScript, accounting for this bug that I've discovered?

A: Testing with your code and then with my own simple AppleScript code, I can reproduce the (unwanted) behavior to a point I'd agree the behavior is not what's wanted and might be considered a bug, however the workaround is a bit of a kludge.
In this method, instead of setting theClipboardTextWithoutAnyLineBreaksOrFormatting directly to the Clipboard, because that's where the issue is, it's going to be written to a temporary file, then placed on the Clipboard using pbcopy in a do shell script command and then the temporary file is deleted. Then it can be pasted to the target insertion point.
To test the workaround code below, comment out the set the clipboard to theClipboardTextWithoutAnyLineBreaksOrFormatting line and then place the workaround code directly after it and before the tell application "System Events" to keystroke "v" using {command down} line.
set tempFileToRead to POSIX path of (path to desktop) & ".tmpfile"
try
    set referenceNumber to open for access tempFileToRead with write permission
    write theClipboardTextWithoutAnyLineBreaksOrFormatting to referenceNumber
    close access referenceNumber
on error eStr number eNum
    display dialog eStr & " number " & eNum buttons {"OK"} default button 1 with title "File I/O Error..." with icon caution
    try
        close access referenceNumber
    end try
    return
end try
do shell script "pbcopy<" & tempFileToRead & "; rm " & tempFileToRead

A: Because the clipboard command add others types automatically, test this script:
set the clipboard to "hello" as string
delay 1
return clipboard info

the result is --> {{Unicode text, 10}, {string, 5}, {scrap styles,
  22}, {«class utf8», 5}, {«class ut16», 12}, {scrap styles, 22}}

To avoid the styles, use the NSPasteboard's methods:
-- *** add the missing lines from your script here  ***
--- set the clipboard to theClipboardTextWithoutAnyLineBreaksOrFormatting -- don't use this command to avoid the scrap styles type.
my putTextOnClipboard:theClipboardTextWithoutAnyLineBreaksOrFormatting -- use this method to put some string in the clipboard.

tell application "System Events" to keystroke "v" using {command down}
delay 0.1 -- Without this delay, may restore clipboard before pasting.
-- Restore the original clipboard:
my putOnClipboard:savedClipboard

on putTextOnClipboard:t
    set thePasteboard to current application's NSPasteboard's generalPasteboard()
    thePasteboard's clearContents()
    thePasteboard's declareTypes:{current application's NSPasteboardTypeString} owner:(missing value)
    thePasteboard's setString:t forType:(current application's NSPasteboardTypeString)
    --> now the clipboard contains these types only: («class utf8», «class ut16», string and Unicode text)
end putTextOnClipboard:


text:
Q: ios pressure sensor API In android we can use Sensor TYPE_PRESSURE to measure the atmospheric pressure.
Is there any API that is available in iOS for the same purpose. How can this be achieved in iOS?
Any help appreciated

A: No, because no iOS device ships with a barometer. The best you could do would be find some site API that takes GPS co-ordinates and returns the current pressure at ground level there from normal weather observations.

A: iOS 8 introduces Core Motion Framework:

Core Motion provides two new classes (CMAltimeter and CMAltitudeData)
  which allow you to access the barometer on the iPhone 6 and iPhone 6
  Plus.


text:
Q: JSF 2: invoking managed bean directly I am new to JSF (2).
In Struts we can invoke an action from a URL like app.action. This invokes an action and returns a result page, say a JSP (initially there is no JSP/HTML).
How can the same thing be done in JSF? (I know how to invoke an action from an .xhtml)
I.e. invoking a managed bean directly from a URL and getting a result page.

A: If it's preparing data for an initial GET request, just do the job in (post)constructor of the request or view scoped managed bean associated with the page.
@ManagedBean
@RequestScoped
public class Bean {

    public Bean() {
        // Here.
    }

    @PostConstruct
    public void init(){
        // Or here, certainly if you rely on injected dependencies like @EJB.
    }

}

If it's controlling the request/response and may possibly redirect/navigate to another page, then do the job in preRenderView.
<f:event type="preRenderView" listener="#{bean.listener}" />

with
public void listener() {
    // ...

    // You want to redirect?
    externalContext.redirect(newURL);

    // Or you want to navigate?
    navigationHandler.handleNavigation(context, null, "newOutcome");
}

Or if you want to hook on all requests, then use a filter:
@WebFilter("/*")
public class MyFilter implements Filter {

    // ...

}

See also:

*

*Is there any easy way to preprocess and redirect GET requests?

*How to make a redirection in JSF

A: The pattern you're asking about is not really native to the way JSF works.
Request-based frameworks like Struts and Spring MVC, and the older Model-2 Servlet/JSP based approach did work like this.
In JSF, first and foremost it's the page (view) that's automatically mapped to a request URL. There's no notion of a bean that's directly mapped to a URL and also there's no notion of a bean that has a framework enforced 1:1 relation with a view. There is the concept of a backing bean though, but this is by convention. For JSF, all beans are "helper beans" that are merely referenced by the view.
BalusC outlined the popular ways that can be used today to get some of the behavior from request-based frameworks in JSF in his answer. JSF 2.2 will slightly expand on this support via the introduction of view actions, which formalizes a few of the typical use cases for the preRenderViewEvent.
That said, JSF is a very flexible framework and very few things are set in stone. A lot of JSF's behavior can be replaced or added to via an elaborate plug-in and decorator system.
For this use case, the fact that JSF binds URLs to (Facelets) views can be overridden, and you can in fact let beans directly react to requests. Although for a slightly different purpose, this is what I essentially did for JavaVDL, by overriding the so-called view handler.
You do have to ask yourself if this is really what you want to do, and if you want to work in this way whether JSF is the best choice for you. But via the methods outlined in JavaVDL (sourcecode here), you should be able to do this. Do note that this last method is not suited for beginners and requires quite a lot of JSF experience if you want to pull this off yourself. (If you, or anyone else would like to have this functionality, please consider creating an issue for it at the OmniFaces issues list).


text:
Q: Different arguments/return values for sinon expectation I'm writing unit tests for my module and use SinonJS to verify a couple of expectations regarding function calls to other modules. First, I register a mock for the other module:
var otherModule = {
    getConfig : function () {}
};

mockery.registerMock("otherModule", otherModule);

Later on, I run some tests and (successfully) verify some expectations such as:
var otherModuleMock = sinon.mock(otherModule);
otherModuleMock
    .expects("getConfig")
    .once()
    .withArgs("A")
    .returns(configValuesForA);

// run test

otherModuleMock.verify(); // <- succeeds

I run into a problem however, when the module calls the getConfig function twice, with different arguments:
otherModuleMock
    .expects("getConfig")
    .once()
    .withArgs("A")
    .returns(configValuesForA);

otherModuleMock
    .expects("getConfig")
    .once()
    .withArgs("B")
    .returns(configValuesForB);

From my understanding of the documentation, this should probably work. However, this results in the following error:
ExpectationError: Unexpected call: getConfig(A)
    Expectation met: getConfig(A[, ...]) once
    Expectation met: getConfig(B[, ...]) once

I tried replacing once() with atLeast(1) or removing it completely. I also tried capturing the expectation returned by otherModuleMock.expect("getConfig") and applying withArgs and returns on that instead. Both to no avail.
Pretty sure I'm using mock() in a way I'm not supposed to, but how should I go from here?

A: Turns out the module I was testing actually calls getConfig 3 times: Once with A, once with B and then with A again.
And apparently Sinon keeps track of the order of all expectations/calls, which is the reason the test even failed when using atLeast(1) instead of once(). Makes sense when I look at it now, but these cases are not really documented extensively in the Sinon docs (in my own defence).


text:
Q: Cannot perform routing with pushstate and various js routers I am not sure if I understand well the situation with pushstate and routing but I am stuck trying to route a single page app using either pagejs or grapnel or other similar javascript routers.
What I want is to be able to navigate through my program and through manually entering routes in the location bar (so I can send links to various parts of my spa to third parties). I cannot navigate manually to the /test route for example with the below code.
The following is an example with pagejs.
I have also made my nodejs backend to redirect to /#login if it gets a request for /login.
How can I utilize pushstate so that I can both enter a manual address in the location bar and navigate through it from the router and html links?
What am I missing here?
Some sample code:
page('/',index);
page('/signin',signin);
page('/test',test)
page();

function index() {
  console.log('in index')
  new WelcomeView();
  console.log('rerouting');
  page('/signin');
}

function signin() {
  console.log('in signin')
  //new SigninFormView();
}

function test() {
  console.log('in test');
}

in welcome.html
click lets see

in app.js (server side)
//router redirect to webapp
app.use(function(req, res, next) {
  const redirectUrl=(req.secure ? 'https://' : 'http://') + req.headers.host +'/#'+req.originalUrl.substring(1);
  res.redirect(redirectUrl);
});

This has the following outcomes:
1) navigating to / I get the welcome page and a console log that it has navigated to the signin route
2) writing the link manually /signin in the location bar I again navigate to the / route which redirects
3) writing the link manually /#signin in the location bar I again navigate to the / route which redirects
4) clicking the link in the welcome.html again redirects me through the / route
5) clicking the link in welcome.html and changing it to /test works.

A: Whenever you (manually or otherwise, usually by setting window.location = 'myurl') change anything in the address bar, the browser will always make a request for that, afaik there is no way around it, and if there was, it would be a security issue, as pages could hijack your browser, by not allowing to navigate away to any other url. If you want to be able to load a particular url in your SPA by typing it in the location bar, you need the server to respond with something. In an SPA, you would typically return the same html that loads your SPA. Now, it seems like pagejs doesn't' respect the url in the location bar, and keeps loading / (I believe I've seen that before), as a workaround, you can try setting page() to window.location.pathname when your app loads, and see if that will fix your second issue.
Also, hashbang urls, arent enabled by default with page, you need to enable them with page({hashbang: true}).


text:
Q: How do I write urilify string python Write a method to replace all spaces in a string with '%20'. You may assume that the string
has sufficient space at the end to hold the additional characters, and that you are given the "true" length of the string.
This is how I tried to solve, but I know I haven't addressed the question correctly where author asks us to assume the additional space at the end and the true length of the string. I am a beginner in programming trying to learn Algorithms and DS, quite a head bagging on this side.
def replace(astring):

    alist= list(astring)

    for i in range(len(alist)):
        if alist[i] == ' ':
            alist[i]= '%20'
    return (''.join(alist))

print(replace("Mr John Smith "))

A: You can use the following code :
import urllib.parse

urllib.parse.quote("Mr John Smith ")

A: Since you are trying to learn algorithms, I think it will be beneficial to leave two hints to help you forward instead of the answer

*

*"Mr John Smith ".rstrip() will strip any space at the end of a string. This means you will not have to worry about any logic for whitespace

*Even though the solution works, you are using extra space by creating alist. Maybe try replacing things in the string itself? In Python a string can already by accessed as a string. For example astring[:2] is valid. Also 'hello world!'.replace(' ', 'test') is your friend


text:
Q: SSH tunnel to browse localhost, super slow To visit sites/services like jupyter notebooks and rstudio-server on my server I make a ssh tunnel and then just browse them in my webbrowser on my local machine, however, since yesterday, all my services are loading so slow in my browser.
Not sure why or where to even start the troubleshooting. I can ssh into the server and look at file etc. I even tried reinstall one of the services yesterday before I realized that all of my services were slow...
Any ideas or recommendations how to troubleshoot this?
Edit: can add that if I manage to connect to one service in the browser, it seems that once i'm connected the service runs without delays in the browsers. So seems that it's "just" the connecting that takes forever. (several mins)
Can also add that the ports are open on both my remote and local machine.
I just now realized that in my terminal I get the following message:
channel 3: open failed: connect failed: Connection refused
channel 2: open failed: connect failed: Connection refused
channel 2: open failed: connect failed: Connection refused
channel 3: open failed: connect failed: Connection refused
channel 4: open failed: connect failed: Connection refused
channel 5: open failed: connect failed: Connection refused

The command I used to open up the tunnel:
ssh -N -f -L 8787:localhost:8787 myNick@192.168.1.xx

A: The problem seem to be with the DNS on the target server, changing from localhost to 127.0.0.1 works but do not really solve the DNS problem on the target machine.


text:
Q: cherrypick types in typescript when calling an external library function I am trying to use a helper function from a library with a strict type in typescript but I can't seem to get it to work.
For instance, the following code from chakraui.
export interface BaseBreakpointConfig {
  sm: string
  md: string
  lg: string
  xl: string
  "2xl"?: string
  [key: string]: string | undefined
}

export type Breakpoints<T> = T & { base: "0em" }

export const createBreakpoints = <T extends BaseBreakpointConfig>(
  config: T,
): Breakpoints<T> => {
  warn({
    condition: true,
    message: [
      `[chakra-ui]: createBreakpoints(...) will be deprecated pretty soon`,
      `simply pass the breakpoints as an object. Remove the createBreakpoint(..) call`,
    ].join(""),
  })
  return { base: "0em", ...config }
}

And I want to call the createBreakpoints function without supplying all the keys, how would I do that? Is that possible?
I tried using the Pick utility but that didn't help.
type Breakpoints = Pick<BaseBreakpointConfig, 'sm' | 'md' | 'lg'>

const breakpoints = createBreakPoints<Breakpoints>({
  sm: "...",
  md: "...",
  lg: "..."
});

I got the Property "xl" is missing in type "Breakpoints" but required in type BaseBreakpointConfig error

A: Using Partial<Type>, which returns a type where every property of Type is optional, we can make T extend Partial<BaseBreakpointConfig>. This will make createBreakpoints() accept arguments with types are subsets of BaseBreakpointConfig, like Pick<BaseBreakpointConfig, 'sm' | 'md' | 'lg'>:
export const createBreakpoints = <T extends Partial<BaseBreakpointConfig>>(
  config: T,
): Breakpoints<T> => {
  // ...
};

const breakpoints = createBreakpoints<Pick<BaseBreakpointConfig, 'sm' | 'md' | 'lg'>>({
  sm: "...",
  md: "...",
  lg: "..."
}); // works

TypeScript playground


text:
Q: Build FQCN from a string Sorry if this is a dup. Is there a native PHP function like ::class but for string variables or constants? I.e. from a string build the FQCN using the active namespace and use alias. E.g.:
namespace test;
use foo\bar;

echo fqcn_from_a_string("zip"); // should print 'test\zip'
echo fqcn_from_a_string("bar"); // should print 'foo\bar'
echo fqcn_from_a_string("\yap"); // should print 'yap'


text:
Q: Oversized Qt Fonts on OSX Why does Qt on OSX appear to default to overly large fonts? Even when you select the same font size manually the fonts appear slightly bigger. Does Qt on OSX use a different font rendering to OSX? Does this improve if you use Qt for Cocoa?
In addition, is there a qtconfig tool or equivalent to globally set the font settings for all Qt applications?
Thanks!

A: Max Howell is correct. In native OS X applications, you have got the option to set small and tiny sizes to your windows and widgets. These will then choose smaller fonts and also will resize some of the graphical elements.
Many OS X designers make use of this, and therefore an application which does not follow this conventions is very likely to look oversized on OS X.
As has been noted, Qt does provide widget attributes which can change this: Qt::WA_MacNormalSize, Qt::WA_MacSmallSize, Qt::WA_MacMiniSize, Qt::WA_MacVariableSize – but unfortunately, it seems that many people don't know about them and if they do, implementing them is a bit of a hack, as it will require the code to have quite a few #ifdefs (unless they're using a helper function for this to reduce the effort).
Particularly bad is that Qt does not use these attributes in their own Qt Creator or Qt Designer either, especially in widgets such as the property tables where the large row height makes it almost useless on smaller monitors, because you'll need to scroll forever to find the property you've been looking for.

A:
Why does Qt on OSX appear to default
  to overly large fonts?

It defaults to the same fonts in InterfaceBuilder and Qt Designer.

Even when you select the same font
  size manually the fonts appear
  slightly bigger.

Turns out this was just my imagination, they are exactly the same.

Does Qt on OSX use a different font
  rendering to OSX?

No, it uses the native rendering.

Does this improve if you use Qt for
  Cocoa?

Font's don't but other things do change. The font rendering between Carbon and Cocoa is seemingly identical.

In addition, is there a qtconfig tool
  or equivalent to globally set the font
  settings for all Qt applications?

There's no qtconfig tool for OSX or any way of globally setting font settings.
It seems the root of the above problems is that OSX applications tend to use slightly lower point fonts for many things compared to Windows or Linux. As a result the font sizes used in an Qt OSX application should be hand-tweaked to better match those use elsewhere on the platform.

A: AS explained in other answers, you can set widget attributes: Qt::WA_MacNormalSize, Qt::WA_MacSmallSize, Qt::WA_MacMiniSize, Qt::WA_MacVariableSize.
The easiest way I've found to do this for your entire application is it use a QProxyStyle and in the QProxyStyle::polish method set the attribute as you want.
I usually make sure I do NOT change the flags on QMenu widgets as it breaks the display of the keyboard shortcuts.
So for example, to make all widgets small, except menus and the ones I choose to remain large, I do:
void QMveStyle::polish ( QWidget * w )
{
#ifdef __APPLE__
    QMenu* mn = dynamic_cast<QMenu*>(w);
    if(!mn && !w->testAttribute(Qt::WA_MacNormalSize))
        w->setAttribute(Qt::WA_MacSmallSize);
#endif
}


text:
Q: How to capture group no of every group in a repeated capturing group My regex is something like this **(A)(([+-]\d{1,2}[YMD])*)** which is matching as expected like  A+3M, A-3Y+5M+3D etc..
But I want to capture all the groups of  this sub pattern**([+-]\d{1,2}[YMD])***
For the following example A-3M+2D, I can see only 4 groups. A-3M+2D (group 0),  A(group 1),  -3M+2D (group 2),  +2D (group 3)
Is there a way I can get the **-3M** as a separate group?

A: Repeated capturing groups usually capture only the last iteration. This is true for Kotlin, as well as Java, as the languages do not have any method that would keep track of each capturing group stack.
What you may do as a workaround, is to first validate the whole string against a certain pattern the string should match, and then either extract or split the string into parts.
For the current scenario, you may use
val text = "A-3M+2D"
if (text.matches("""A(?:[+-]\d{1,2}[YMD])*""".toRegex())) {
  val results =  text.split("(?=[-+])".toRegex())
  println(results)
}
// => [A, -3M, +2D]

See the Kotlin demo
Here,

*

*text.matches("""A(?:[+-]\d{1,2}[YMD])*""".toRegex()) makes sure the whole string matches A and then 0 or more occurrences of + or -, 1 or 2 digits followed with Y, M or D

*.split("(?=[-+])".toRegex()) splits the text with an empty string right before a - or +.

Pattern details

*

*^ - implicit in .matches() - start of string

*A - an A substring

*(?: - start of a non-capturing group:

*

*[+-] - a character class matching + or -

*\d{1,2} - one to two digits

*[YMD] - a character class that matches Y or M or D

*)* - end of the non-capturing group, repeat 0 or more times (due to * quantifier)

*\z - implicit in matches() - end of string.

When splitting, we just need to find locations before - or +, hence we use a positive lookahead, (?=[-+]), that matches a position that is immediately followed with + or -. It is a non-consuming pattern, the + or - matched are not added to the match value.
Another approach with a single regex
You may also use a \G based regex to check the string format first at the start of the string, and only start matching consecutive substrings if that check is a success:
val regex = """(?:\G(?!^)[+-]|^(?=A(?:[+-]\d{1,2}[YMD])*$))[^-+]+""".toRegex()
println(regex.findAll("A-3M+2D").map{it.value}.toList())
// => [A, -3M, +2D]

See another Kotlin demo and the regex demo.
Details

*

*(?:\G(?!^)[+-]|^(?=A(?:[+-]\d{1,2}[YMD])*$)) - either the end of the previous successful match and then + or - (see \G(?!^)[+-]) or (|) start of string that is followed with A and then 0 or more occurrences of +/-, 1 or 2 digits and then Y, M or D till the end of the string (see ^(?=A(?:[+-]\d{1,2}[YMD])*$))

*[^-+]+ - 1 or more chars other than - and +. We need not be too careful here since the lookahead did the heavy lifting at the start of string.


text:
Q: How to ensure a signal handler never yields to a thread within the same process group? This is a bit of a meta question since I think I have a solution that works for me, but it has its own downsides and upsides. I need to do a fairly common thing, catch SIGSEGV on a thread (no dedicated crash handling thread), dump some debug information and exit.
The catch here is the fact that upon crash, my application runs llvm-symbolizer which takes a while (relatively speaking) and causes a yield (either because of clone + execve or exceeding the time quanta for the thread, I've seen latter happen when doing symbolication myself in-process using libLLVM). The reason for doing all this is to get a stack trace with demangled symbols and with line/file information (stored in a separate DWP file). For obvious reasons I do not want a yield happening across my SIGSEGV handler since I intend to terminate the application (thread group) after it has executed and never return from the signal handler.
I'm not that familiar with Linux signal handling and with glibc's wrappers doing magic around them, though, I know the basic gotchas but there isn't much information on the specifics of handling signals like whether synchronous signal handlers get any kind of special priority in terms of scheduling.
Brainstorming, I had a few ideas and downsides to them:

*

*pthread_kill(<every other thread>, SIGSTOP) - Cumbersome with more threads, interacts with signal handlers which seems like it could have unintended side effects. Also requires intercepting thread creation from other libraries to keep track of the thread list and an increasing chance of pre-emption with every system call. Possibly even change their contexts once they're stopped  to point to a syscall exit stub or flat out use SIGKILL.

*Global flag to serve as cancellation points for all thread (kinda like pthread_cancel/pthread_testcancel). Safer but requires a lot of maintenance and across a large codebase it can be hellish, in addition to a a mild performance overhead. Global flag could also cause the error to cascade since the program is already in an unpredictable state so letting any other thread run there is already not great.

*"Abusing" the scheduler which is my current pick, with my implementation as one of the answers. Switching to FIFO scheduling policy and raising priority therefore becoming the only runnable thread in that group.

*Core dumps  not an option since the goal here was to avoid them in the first place. I would prefer not requiring a helper program aside from from the symbolizer as well.

Environment is a typical glibc based Linux (4.4) distribution with NPTL.
I know that crash handlers are fairly common now so I believe none of the ways I picked are that great, especially considering I've never seen the scheduler "hack" ever get used that way. So with that, does anyone have a better alternative that is cleaner and less riskier than the scheduler "hack" and am I missing any important points in my general ideas about signals?
Edit: It seems that I haven't really considered MP in this equation (as per comments) and the fact that other threads are still runnable in an MP situation and can happily continue running alongside the FIFO thread  on a different processor. I can however change the affinity of the process to only execute on the same core as the crashing thread, which basically will effectively freeze all other threads at schedule boundaries. However, that still leaves the "FIFO thread yielding due to blocking IO" scenario open.
It seems like the FIFO + SIGSTOP option is the best one, though I do wonder if there are any other tricks that can make a thread unschedulable short of using SIGSTOP. From the docuemntation it seems like it's not possible to set a thread's CPU affinity to zero (leaving it in a limbo state where it's technically runnable except no processors are available for it to run on).

A: This is the best solution I could come up (parts omitted for brevity but it shows the principle) with, my basic assumption being that in this situation the process runs as root. This approach can lead to resource starvation in case things go really bad and requires privileges (if I understand the man(7) sched page correctly) I run the part of the signal handler that causes preemptions under the OSSplHigh guard and exit the scope as soon as I can. This is not strictly C++ related since the same could be done in C or any other native language.
void spl_get(spl_t& O)
{
    os_assert(syscall(__NR_sched_getattr,
        0, &O, sizeof(spl_t), 0) == 0);
}

void spl_set(spl_t& N)
{
    os_assert(syscall(__NR_sched_setattr,
        0, &N, 0) == 0);
}

void splx(uint32_t PRI, spl_t& O) {
    spl_t PL = {0};

    PL.size = sizeof(PL);
    PL.sched_policy = SCHED_FIFO;
    PL.sched_priority = PRI;

    spl_set(PL, O);
}

class OSSplHigh {
    os::spl_t OldPrioLevel;

public:
    OSSplHigh() {
        os::splx(2, OldPrioLevel);
    }

    ~OSSplHigh() {
        os::spl_set(OldPrioLevel);
    }
};

The handler itself is quite trivial using sigaltstack and sigaction though I do not block SIGSEGV on any thread. Also oddly enough syscalls sched_setattr and sched_getattr or the struct definition weren't exposed through glibc contrary to the documentation.

Late Edit: The best solution involved sending SIGSTOP to all threads (by intercepting pthread_create via linker's --wrap option) to keep a ledger of all running threads, thank you to suggestion in the comments.

A:
upon crash, my application runs llvm-symbolizer

That is likely to cause deadlocks. I can't find any statement about llvm-symbolizer being async-signal safe. It's likely to call malloc, and if so will surely deadlock if the crash also happens inside malloc (e.g. due to heap corruption elsewhere).

Switching to FIFO scheduling policy and raising priority therefore becoming the only runnable thread in that group.

I believe you are mistaken: a SCHED_FIFO thread will run so long as it is runnable (i.e. does not issue any blocking system calls). If the thread does issue such a call (which it has to: to e.g. open the separate .dwp file), it will block and other threads will become runnable.
TL;DR: there is no easy way to achieve what you want, and it seems unnecessary anyway: what do you care that other threads continue running while the crashing thread finishes its business?


text:
Q: Autohotkey: How to unfocus a control without focusing another (unfocus all controls)? I am writing an Autohotkey script that fiddles with some Photoshop windows and controls.
I need to be able to unfocus the currently focused control (say, Edit3), so that no control has focus after that (I could explain why exactly I need to do that if necessary, but it seems irrelevant, I just really need all controls unfocused).
AHK's ControlFocus command doesn't provide such an option.
I tried using a Windows Message like this:
SendMessage, 0x8, 0, 0, Edit3, A  ; WM_KILLFOCUS = 0x08

but it doesn't do anything.
In comparison, the opposite one works as expected and focuses the control:
SendMessage, 0x7, 0, 0, Edit3, A  ; WM_SETFOCUS = 0x07

Perhaps I'm doing something wrong with the WM_KILLFOCUS message?
Just to clarify: I don't want to simulate clicks, switch windows, add new invisible controls which to focus etc. I just want to know how to unfocus a control.
So, any idea how to unfocus a control, without focusing another one?

A: last_active_win:=winexist("A") ;get the previous windows process before launching your gui
Gui +AlwaysOnTop
Gui Add, Button, x10 w100 h30 , % 1
Gui Show,, My GUI ;launch the gui which gets the focus
sleep 500
WinActivate ahk_id %last_active_win% ;reactivate previous windows to unfocus controls from gui
return

A: You can send #d and you will go to Desktop. Which is going to focus on the desktop but can work for you.
SendInput, #d


text: Q: Add Woocommerce order notes field to cart.php & single-product.php Is it possible to add the Woocommerce order notes field before the checkout form page? I would like to add it to the cart.php page and single-product.php if that's possible. It would be great if the content entered would be displayed in the checkout form so that the customer can update it if necessary.


text:
Q: how to normalize data 'with a sample range from -1 to 1 and a mean value of 0'? I am trying to pre-process data following a statement in a paper.
They said

for the normalization, each dataset is normalized on a per channel basis with a sample range from -1 to 1 and a mean value of zero.

$X_{rescaled} = a+(b-a)\frac{X - min(X)}{max(X)-min(X)}$, following this, it can rescale data $X$ into an arbitrary interval $[a \ b]$, but it can't promise the mean is zero.
Probably I didn't get the statement here, anyone has any idea about this?

A: I believe the intended application of this preprocessing technique is to first standardize the data with mean zero then change its range to $[-1,1]$ for a neural network input. To quote this referece :

You will get better initializations if the data
are centered near zero and if most of the data are distributed over an
interval of roughly [-1,1]

However, in all cases, applying first a standardization technique to get zero mean and then apply a new data normalization to map your features to a certain range is meaningless... it is equivalent to normalizing only $X$ since the standardization step does not change the min/max values (check this question).
What I would suggest is only standardization to zero mean and unit variance like so
$$
X_{i}{scaled} = \frac{X_{i} - \mu_{X_i}}{\sigma_{X_i}}
$$
where $\mu_{X_i}$ and $\sigma_{X_i}$ are computed for every feature $i$. Then if you really want to have a range of $[-1,1]$ and your data is Gaussian, you can simply filter them accordingly which according to a Gaussian distribution should give you about $68\%$ of your data. In the reference that I quote, they say 'most of the data' which in this case means $68\%$ if it is Gaussian. But this seems to me like an overkill since you loose too much data.
On the other hand, if your data is not Gaussian then clipping values will result in an even greater loss of data (and information). So one should choose a better mapping (e.g. logarithmic, box-cox, and so on...) to make data Gaussian-like first, then standardize to zero mean and unit variance, then clip to $[-1,1]$ if necessary. An example using a simple logarithmic transformation for non Gaussian features:
$$
X_i = log(X_i + \epsilon)
$$
then
$$
X_i = \frac{X_{i} - \mu_{X_i}}{\sigma_{X_i}}
$$
See scikit-learn's implementation of standard scaler here and their implementation of non-linear data transformers here.
Update:
I found this scikit-learn page that discusses tips to tackle deep learning data preprocessing very useful. They do indeed mention that it is recommended to either scale data to $[-1,1]$ or standardize it to have zero mean and unit variance. Applying both is meaningless as shown in this answer that @Tim so kindly provided.

A: The following code in R was my attempt of to solve the problem of finding an algorithm to convert a vector of values to a new vector of values with mean of 0 and range of [-1, 1].
After one pass, it doesn't quite work. (The result will have the specified range, but the mean will be off-zero, though usually not by too much).
However, it appears that if it's applied iteratively (feeding the results back through the algorithm), it will reach the desired result within a certain tolerance.
I doubt this transformation is practically useful.  And one could probably come up with a simpler process to arrive at a similar result.
Briefly, it centers A on mean of 0, and then divides this new A_center into those values above and below 0 (A1 and A2), adds a value of precisely 0 to each, and then applies a linear transformation to each of these to fit a range of [-1, 0] and [0, 1].
### RUN THIS ONCE, WITH A AS THE INPUT VECTOR ###

A = c(1,2,2,3,3,3,4,4,4,4,5,5,5,5,5,8,8,8,8,8,8,8,8,8,8,8)

A_trans = A

### RUN THIS ITERATIVELY UNTIL THE RESULTS ARE WITHIN TOLERANCE ###

A = A_trans

hist(A)

A_center = A - mean(A)

A1 = c(0, A_center [A_center < 0])

A2 = c(0, A_center [A_center > 0])

A1_scaled = ((A1 - min(A1) * (0 - -1))/(max(A1) - min(A1)) + -1)

A2_scaled = ((A2 - min(A2) * (1 - 0))/(max(A2) - min(A2)) + 0)

A_trans = c(A1_scaled[2:length(A1_scaled)], A2_scaled[2:length(A2_scaled)])

hist(A_trans)

Sum=data.frame(
  N    = c(length(A),length(A_center),length(A_trans)),
  Mean = c(round(mean(A), 2), round(mean(A_center), 2), round(mean(A_trans), 2)),
  Min  = c(round(min(A), 2), round(min(A_center), 2), round(min(A_trans), 2)),
  Max  = c(round(max(A), 2), round(max(A_center), 2), round(max(A_trans), 2)),
  CountLess0 = c(sum(A < 0),sum(A_center < 0),sum(A_trans < 0)),
  CountGreater0 = c(sum(A > 0),sum(A_center > 0),sum(A_trans > 0)),
  row.names=c("A", "A_center", "A_trans")
)

Sum


text:
Q: Moving a folder from one SVN repository to another I have a set of repositories with a structure similar to the following:
/Source
  /branches
  /tags
  /trunk
    /FolderP
    /FolderQ
    /FolderR

/Target
  /branches
  /tags
  /trunk
    /External
      /Library1
      /Library2
      /Library3
    /Internal
      /FolderA
      /FolderB
      /FolderC
      /FolderX
      /FolderY
      /FolderZ

I would like to move the folders /Source/trunk/FolderP, /Source/trunk/FolderQ and /Source/trunk/FolderR to /Target/trunk/Internal such that:

*

*/Source/trunk/FolderP becomes /Target/trunk/Internal/FolderP

*/Source/trunk/FolderQ becomes /Target/trunk/Internal/FolderQ

*/Source/trunk/FolderR becomes /Target/trunk/Internal/FolderR

I should then have the following repository structure:
/Target
  /branches
  /tags
  /trunk
    /External
      /Library1
      /Library2
      /Library3
    /Internal
      /FolderA
      /FolderB
      /FolderC
      /FolderP
      /FolderQ
      /FolderR
      /FolderX
      /FolderY
      /FolderZ

It is imperative that history be maintained during the move.
I have looked at the following 2 questions asked previously which seem to be similar:

*

*SVN move single directory into other repository (with history)

*How do I move a single folder from one Subversion repository to another repository?
I haven't had much luck with the suggested solutions. Specifically, I get an error when I run the svndumpfilter command, which states that:
svndumpfilter: Invalid copy source path `/branches/name-of-a-branch/.../File.cs`

What's going on and how can I get around this problem?
Edit:
One workaround that I am currently trying is to:

*

*Clone the /Source repository into another one called /Temp

*Delete the files and folders from /Temp which I do not need and checkin all changes

*Dump /Temp repository by calling "svnadmin dump X:\Repositories\Temp > X:\Dumps\Temp.dmp"

*Load Temp.dmp into /Target repository by calling "svnadmin load --parent-dir trunk\Internal\Temp X:\Repositories\Target < X:\Dumps\Temp.dmp"

*Checkout/update /Target repository

*Use TortoiseSVN to move folders out of /Target/trunk/Internal/Temp/trunk/** up into /Target/trunk/Internal (by highlighting the ones I want in Windows Explorer, pressing Control+X and then changing folder to /Target/trunk/Internal and issuing the pasting with TortoiseSVN

NB: The above assumes that svn is maintaining all repositories in X:\Repositories folder and one is using X:\Dumps folder as working folder.
This will clobber revision numbers obviously, but will maintain history. Hopefully, your commit comments do not include references to revision numbers.
Someone else has mentioned an svndumpfilter3 Python script, but I have never used Python and do not wish to learn to use Python, just for this.

A: Unless you also want to also change the history of FolderP, FolderQ, and FolderR, why don't you simply svn move them to Internal?
Note that svnadmin load takes an option --parent-dir arg, where arg is the parent folder where you want your imported dump to appear under. So

svnadmin load --parent-dir /trunk/Internal dump_of_source_repo target_repo

should import all of the source repo under /trunk/Internal in the target repo.

A: The following workaround is for the specific situation  that filipenf is in, i.e., no access to svnadmin on the Subversion server.
If you can physically move files into place on the Subversion server in the folder being used to store repositories, then you're sort of in luck.
Before you do any of the following, please take backups, in case of inadvertent corruption of data. Liberal usage of backup can never be over-emphasized. Now, the workaround:

*

*Stop the local Subversion server on your local repository so that the repository is flushed and no changes can be made.

*Stop the company Subversion server.

*Copy the directory representing the local repository into the repository folder of the company Subversion server alongside the folders representing other repositories.

*Restart the company Subversion server (and the local one if required).

This should give you new repository in the company Subversion server with all the history intact.
You can then use svn:external properties to bring in code from this new repository into other repositories on the company Subversion server.
Please note that this involves the ability to physically copy files onto the company Subversion server, rather than creating a new repository or folder using the user interface published by the Subversion server.

A: For this, I found a great support within TortoiseSVN version 1.9.4+:

*

*Open Log (TortoiseSVN > Show log)

*select all revisions that made up the project

*right-click into the selection, then Merge revisions to...

*select target folder (should be in a up-to-date working copy)

*wait for TSVN to copy your files, folders and properties...

*in Explorer window: commit target folder

Disclaimer
This method strips history and may work only under certain circumstances, but my situation obviously was exactly one of these (this is why I love TSVN: it really helps its users).
Background story:
I tried to convince a college to bring a small ("toy") project under version control, so I cleaned out our SVN "playground" repository. He then committed all he thought that was source code (naturally much more than that), I then added the appropriate ignore patterns, he immediately started to do productive work under VC (forgetting that this all takes place in the "playground" repo). Now I had to convince him to move to a persistent repository and searched for an easy-to-apply and easy-to-teach method, to enable him to do the first commit in the new site.


text:
Q: Is it best practice to create a variable if accessing a property of an object more than once in a routine? When I first began as a junior C# dev, I was always told during code reviews that if I was accessing an object's property more than once in a given scope then I should create a local variable within the routine as it was cheaper than having to retrieve it from the object. I never really questioned it as it came from more people I perceived to be quite knowledgeable at the time.
Below is a rudimentary example
Example 1: storing an objects identifer in a local variable
public void DoWork(MyDataType object)
{
    long id = object.Id;

    if (ObjectLookup.TryAdd(id, object))
    {
        DoSomeOtherWork(id);
    }

}

Example 2: retrieving the identifier from the Id property of the object property anytime it is needed
public void DoWork(MyDataType object)
{
    if (ObjectLookup.TryAdd(object.Id, object))
    {
        DoSomeOtherWork(object.Id);
    }
}

Does it actually matter or was it more a preference of coding style where I was working? Or perhaps a situational design time choice for the developer to make?

A: As explained in this answer, if the property is a basic getter/setter than the CLR "will inline the property access and generate code that's as efficient as accessing a field directly". However, if your property, for example, does some calculations every time the property is accessed, then storing the value of the property in a local variable will avoid the overhead of additional calculations being done.

A: All the memory allocation stuff aside, there is the principle of DRY(don't repeat yourself). When you can deal with one variable with a short name rather than repeating the object nesting to access the external property, why not do that?
Apart from that, by creating that local variable you are respecting the single responsibility principle by isolating the methods from the external entity they don't need to know about.
And lastly if the so-called resuing leads to unwanted instantiation of reference types or any repetitive calculation, then it is a must to create the local var and reuse it throughout the class/method.
Any way you look at it, this practice helps with readability and more maintainable code, and possibly safer too.

A: I don't know if it is faster or not (though I would say that the difference is negligible and thus unimportant), but I'll cook up some benchmark for you.
What IS important though will be made evident to you with an example;
public Class MyDataType
{
    publig int id {
        get {
            // Some actual code
            return this.GetHashCode() * 2;
        }
    }
}

Does this make more sense? The first time I will access the id Getter, some code will be executed. The second time, the same code will be executed costing twice as much with no need.
It is very probable, that the reviewers had some such case in mind and instead of going into every single one property and check what you are doing and if it is safe to access, they created a new rule.
Another reason to store, would be useability.
Imagine the following example
  object.subObject.someOtherSubObject.id

In this case I ask in reviews to store to a variable even if they use it just once. That is because if this is used in a complicated if statement, it will reduce the readability and maintainability of the code in the future.

A: A local variable is essentially guaranteed to be fast, whereas there is an unknown amount of overhead involved in accessing the property.
It's almost always a good idea to avoid repeating code whenever possible. Storing the value once means that there is only one thing to change if it needs changing, rather than two or more.
Using a variable allows you to provide a name, which gives you an opportunity to describe your intent.
I would also point out that if you're referring to other members of an object a lot in one place, that can often be a strong indication that the code you're writing actually belongs in that other type instead.

A: You should consider that getting a value from a method that is calculated from an I/O-bound or CPU-bound process can be irrational. Therefore, it's better to define a var and store the result to avoid multiple same processing.
In the case that you are using a value like object.Id, utilizing a variable decorated with const keyword guarantees that the value will not change in the scope.
Finally, it's better to use a local var in the classes and methods.


text:
Q: After scrolling in the listview, elements are swapped I writing time-tracking app, every row of listview has two buttons(Start and Stop) and some textView to display elapsed time.
After scrolling in the listview, elements are swapped.
I'm not sure in my solution, but i put in the model class, ViewHolder object for getting acces for changing view elements.
Here is the fragment of code model
private String name;
private  Boolean isStart=false;
private  Long elapsedTime=0L,seconds=0L,hours=0L,minutes=0L,lastPause=0L,updateTime=0L,startTime=0L,days=0L;
private Runnable updateTimeThread=new Runnable() {
@Override
public void run() {
    if(isStart && startTime!=0) {
        updateTime = ((System.currentTimeMillis() - startTime) + lastPause);
        seconds = updateTime / 1000;
        minutes = seconds / 60;
        hours = minutes / 60;

        seconds = seconds % 60;
        minutes = minutes % 60;
        hours = hours % 24;

        holder.days.setText(String.format("%04d", days));
        holder.hours.setText(String.format("%02d", hours));
        holder.minutes.setText(String.format("%02d", minutes));
        holder.seconds.setText(String.format("%02d", seconds));
        Log.d("myTag",name+" "+seconds);
        MainActivity.handler.post(this);
    }
}
             };

MyAdapter.ViewHolder holder;

    public MyAdapter.ViewHolder getHolder() {
return holder;
  }

   public void setHolder(MyAdapter.ViewHolder holder) {
    this.holder = holder;
   }

     public Runnable getRunnable() {
return updateTimeThread;
         }

Adapter's fragment code
public View getView(final int position, final View convertView, ViewGroup parent) {
View row = convertView;
final Tracker tracker = trackerList.get(position);
final Runnable updateTimeThread=tracker.getRunnable();

View.OnClickListener onClickListener;
ViewHolder holder;

if(row == null){
    holder = new ViewHolder();
    LayoutInflater inflater = ((Activity)context).getLayoutInflater();
    row = inflater.inflate(R.layout.row,parent,false);
    holder.name = (TextView)row.findViewById(R.id.tvName);
    holder.days = (TextView)row.findViewById(R.id.tvDays);
    holder.hours = (TextView)row.findViewById(R.id.tvHours);
    holder.minutes = (TextView)row.findViewById(R.id.tvMinutes);
    holder.seconds = (TextView)row.findViewById(R.id.tvSeconds);
    holder.start = (Button)row.findViewById(R.id.btStart);
    holder.stop = (Button)row.findViewById(R.id.btStop);
    row.setTag(holder);
}else {
    holder = (ViewHolder) row.getTag();
}
    holder.start.setEnabled(true);
    holder.stop.setEnabled(false);
    holder.name.setText(tracker.getName());
    final ViewHolder finalHolder = holder;

if(tracker.getIsStart()){
    holder.start.setEnabled(false);
    holder.stop.setEnabled(true);
}

 onClickListener = new View.OnClickListener() {
     @Override
     public void onClick(View v) {
         switch (v.getId()) {
             case R.id.btStart:
                 tracker.setStartTime(System.currentTimeMillis());
                 tracker.setIsStart(true);
                 tracker.setHolder(finalHolder);
                 MainActivity.handler.post(updateTimeThread);
                 finalHolder.start.setEnabled(false);
                 finalHolder.stop.setEnabled(true);
                 break;
             case R.id.btStop:
                 tracker.setLastPause(tracker.getUpdateTime());
                 MainActivity.handler.removeCallbacks(updateTimeThread);
                 finalHolder.stop.setEnabled(false);
                 finalHolder.start.setEnabled(true);
                 tracker.setIsStart(false);
                 break;
         }
     }
 };
holder.start.setOnClickListener(onClickListener);
holder.stop.setOnClickListener(onClickListener);
return row;
 }

static class ViewHolder{
TextView  name,days,hours,minutes,seconds;
Button start,stop;
}

A: I just add these two methods to my adapter)
  @Override
public int getViewTypeCount() {
    return getCount();
}

@Override
public int getItemViewType(int position) {
    return position;
}

UPDATE
But with Loader Callback problem is still the same. I press Start on last item and scroll down, values not visible, scroll up a bit and values visible. Pity.
UPDATE 2 This article solve my problem, i just change layout-height and laoyut-weight from "wrap_content" to "fill_parent" to avoid multiple calling getView() method.
http://gmariotti.blogspot.com/2013/06/tips-for-listview-view-recycling-use.html

A: Change this part
holder.start.setEnabled(true);
holder.stop.setEnabled(false);
holder.name.setText(tracker.getName());
final ViewHolder finalHolder = holder;

if(tracker.getIsStart()){
holder.start.setEnabled(false);
holder.stop.setEnabled(true);
}

to this
final ViewHolder finalholfder = holder;

finalholfder.start.setEnabled(true);
finalholfder.stop.setEnabled(false);
finalholfder.name.setText(tracker.getName());

if(tracker.getIsStart()){
finalholfder.start.setEnabled(false);
finalholfder.stop.setEnabled(true);
} else{
finalholfder.start.setEnabled(true);
finalholfder.stop.setEnabled(false);
}

And this
holder.start.setOnClickListener(onClickListener);
holder.stop.setOnClickListener(onClickListener);

to this
 finalholfder.start.setOnClickListener(onClickListener);
 finalholfder.stop.setOnClickListener(onClickListener);


text:
Q: Use QT to convert HTML into XML I saw a lot threads about converting html to XML but any thread contain QT subject.
I try to convert HTML into XML using this function:
static std::string CleanHTML(const std::string &html){
    QWebPage * tmp_webpage = new QWebPage();
    tmp_webpage->mainFrame()->setHtml(QString::fromStdString(html));

    QWebElement * tmp = &tmp_webpage->mainFrame()->documentElement();

    return tmp->toOuterXml().toStdString();
}

It doesn't working. This function return 99% the same code as HTML contain.
EDIT:: (sorry of unclear question)

*

*It is possible to convert HTML into XML using QT? (Output XML format must be supported by pugiXML - i want to use it to parse XML - (i know that by QT i can parse HTML))

*If YES, why my func dont work ? Could you fix that, or show me how to do it in other way?


text:
Q: Yii Fixtures Issue? I seem to be having a problem with fixtures in Yii. The problem seems to be the following,
public $fixtures=array('projects'=>'Project');

The model Project exists and I have the fixtures in a file name tbl_project.php in the fixtures folder of tests and my table name is called tbl_project. Inside the fixtures file is the following.
return array(
        'project1' => array(
            'name' => 'Test Project 1',
            'description' => 'This is test project 1',
            'create_time' => '',
            'create_user_id' => '',
            'update_time' => '',
            'update_user_id' => '',
         ),
        'project2' => array(
            'name' => 'Test Project 2',
            'description' => 'This is test project 2',
            'create_time' => '',
            'create_user_id' => '',
            'update_time' => '',
            'update_user_id' => '',
         ),
        'project3' => array(
            'name' => 'Test Project 3',
            'description' => 'This is test project 3',
            'create_time' => '',
            'create_user_id' => '',
            'update_time' => '',
            'update_user_id' => '',
         ),
    );

This is actually from the book "Agile Web Application Development with Yii". When I run the test case I get the following with no test result information.
PHPUnit 3.6.10 by Sebastian Bergmann.

Configuration read from ETC/protected/tests/phpunit.xml

If I remove the fixtures array from the top I get the following.
Time: 0 seconds, Memory: 9.25Mb

There was 1 error:

1) ProjectTest::testRead
Exception: Unknown method 'projects' for class 'ProjectTest'.

Which obviously makes sense. I dont know what Im doing wrong.

A: *

*Make sure the test class looks like this

    class ProjectTest extends CDbTestCase{

    protected $fixtures = array(
                'projects' => 'Project',
            );

    public function testRead(){

        $receivedProject = $this->projects('Project1');
        $this->assertTrue($receivedProject instanceof Project);
        $this->assertEquals($receivedProject->name,'test 1');
    }
    ...`

*

*Check the fixture configuration in protected/config/test.php ... Should look like ...

    ...
    'components'=>array(
            'fixture'=>array(
                'class'=>'system.test.CDbFixtureManager',
            ),
                        'db'=>array(
                            'connectionString' =>'mysql:host=localhost;dbname=your_db_name',
                            'emulatePrepare' => true,
                            'username' => 'username',
                            'password' => 'passwd',
                            'charset' => 'utf8',
                        ),
    ....

*

*Ultimately check the permissions on the fixture file making sure it can be read

A: Also be sure you are calling parents setUp() method in your own setUp()
class SomeTest extends CDbTestCase {

    public $fixtures = array(
        'somes' => 'Some',
    );

    protected function setUp() {
        parent::setUp();
        // your code....
    }

    // your tests .......................

}

A: Is your test class deriven from CDbTestCase instead of CTestCase?
your Test Class should look something like this:
class ProjectTest extends CDbTestCase{

protected $fixtures = array(
            'projects' => 'Project',
        );

public function testRead(){

    $receivedProject = $this->projects('Project1');
    $this->assertTrue($receivedProject instanceof Project);
    $this->assertEquals($receivedProject->name,'test 1');
}

A: class ProjectTest extends CDbTestCase
{

public function testCreate()
{
    //CREATE a new Project
    $newProject=new Project;
    $newProjectName = 'Test Project Creation';
    $newProject->setAttributes(array(
        'name' => $newProjectName,
        'description' => 'This is a test for new project creation',
        'createTime' => '2009-09-09 00:00:00',
        'createUser' => '1',
        'updateTime' => '2009-09-09 00:00:00',
        'updateUser' => '1',
    )
    );
    $this->assertTrue($newProject->save(false));
    //READ back the newly created Project to ensure the creation    worked
    $retrievedProject=Project::model()->findByPk($newProject->id);
    $this->assertTrue($retrievedProject instanceof Project);
    $this->assertEquals($newProjectName,$retrievedProject->name);
}
public function testRead()
{
    $retrievedProject = $this->projects('project1');
    $this->assertTrue($retrievedProject instanceof Project);
    $this->assertEquals('Test Project 1',$retrievedProject->name);
}
public function testUpdate()
{
    $project = $this->projects('project2');
    $updatedProjectName = 'Updated Test Project 2';
    $project->name = $updatedProjectName;
    $this->assertTrue($project->save(false));
    //read back the record again to ensure the update worked
    $updatedProject=Project::model()->findByPk($project->id);
    $this->assertTrue($updatedProject instanceof Project);
    $this->assertEquals($updatedProjectName,$updatedProject->name);
}
public function testDelete()
{
    $project = $this->projects('project2');
    $savedProjectId = $project->id;
    $this->assertTrue($project->delete());
    $deletedProject=Project::model()->findByPk($savedProjectId);
    $this->assertEquals(NULL,$deletedProject);
}

public function testGetUserOptions()
{
    $project = $this->projects('project1');
    $options = $project->userOptions;
    $this->assertTrue(is_array($options));
    $this->assertTrue(count($options) > 0);

}
public $fixtures=array(
'projects'=>'Project',
'users'=>'User',
'projUsrAssign'=>':tbl_project_user_assignment',
);

}

A: make sure that setup come with its parent
<i>public function setUp() {
    parent::setUp();
}</i>


text:
Q: Get Return Value from one function and use on another I'm trying to do something so seemingly basic in python, but i think im overthinking it.
Im trying to get the return value of password from create_password() and use it in store_password() where I put <<HERE>>
How can I accomplish this?
def create_password(self):
    characters = string.ascii_letters + string.punctuation  + string.digits
    password =  "".join(choice(characters) for x in range(self.pass_char) )
    return (password)

def store_password(self):
    try:
        connection = sqli.connect('pw.db')
    except:
        print("Error occurred!")

    with connection:
        cur = connection.cursor()
        cur.execute('''
                    CREATE TABLE IF NOT EXISTS my_passwords(
                    id INT PRIMARY KEY AUTOINCREMENT,
                    password text
                    '''
        )
        cur.execute('INSERT INTO my_passwords VALUES(?)', <<HERE>>)

Thank you.

A: This is basically using the function that you have already built create_password(self) and assuming that they both belong to the same class you should be able to call create_password(self) within the second function store_password(self)
So to return the password you created you can just call create_password(self) in place of <<HERE>>.
What tabac has suggested will also work, you will need to make sure, however that the method create_password(self) will have to be called before so that the self.password variable is assigned.
Your code would become
cur.execute('INSERT INTO my_passwords VALUES(?)', self.create_password(self))

A: I assume these methods both belong to the same class. If so you can attach the password to the class instance and use it in store_password. Use self for that.
def create_password(self):
    # code...
    self.password = password

def store_password(self):
    # Access password by doing self.password

A: This line should work, if you have defined both funtions within a class.
cur.execute('INSERT INTO my_passwords VALUES(?)', self.create_password())

If not, you need to remove the self, from both and then write
cur.execute('INSERT INTO my_passwords VALUES(?)', create_password())

A: Maybe this example might help in your situation?
import random
import sqli
import string

def main():
    password = create_password(20)
    store_password(password)

def create_password(length):
    characters = string.ascii_letters + string.punctuation + string.digits
    password = ''.join(random.choice(characters) for _ in range(length))
    return password

def store_password(password):
    try:
        connection = sqli.connect('pw.db')
    except:
        print('Error occurred!')
    else:
        with connection:
            cur = connection.cursor()
            cur.execute('''CREATE TABLE IF NOT EXISTS my_passwords (
                           id INT PRIMARY KEY AUTOINCREMENT,
                           password text)''')
            cur.execute('INSERT INTO my_passwords VALUES (?)', password)

if __name__ == '__main__':
    main()

If you provide more of your code (specifically more of the class that your methods are from and especially what calls the create_password method), it would be a lot easier to fix your code.

A: Assuming both function are inside the same class, called in this examples MyPasswordMaker.
You can pass the password as a parameter:
def store_password(self, password):
    try:
        connection = sqli.connect('pw.db')
    except:
        print("Error occurred!")

    with connection:
       cur = connection.cursor()
        cur.execute('''
                    CREATE TABLE IF NOT EXISTS my_passwords(
                    id INT PRIMARY KEY AUTOINCREMENT,
                    password text
                    '''
        )
        cur.execute('INSERT INTO my_passwords VALUES(?)', password)

myPasswordMaker = MyPasswordMaker()
password = myPasswordMaker.create_password()
myPasswordMaker.store_password(password)

Or you can store the password in a class variable
class MyPasswordMaker:
    def create_password(self):
        characters = string.ascii_letters + string.punctuation  + string.digits
        self.password =  "".join(choice(characters) for x in range(self.pass_char) )

    def store_password(self):
        try:
            connection = sqli.connect('pw.db')
        except:
            print("Error occurred!")

        with connection:
            cur = connection.cursor()
            cur.execute('''
                CREATE TABLE IF NOT EXISTS my_passwords(
                id INT PRIMARY KEY AUTOINCREMENT,
                password text
                '''
            )
        cur.execute('INSERT INTO my_passwords VALUES(?)', self.password)

Or call create_password() inside store_password():
cur.execute('INSERT INTO my_passwords VALUES (?)', self.create_password())


text:
Q: Why do my script paths get changed for my script app when I access it through the Finder's Script Menu? Why do my script paths get changed for my script app when I access it through the Finder's Script Menu and BBEdit is the frontmost application?
FWIW, the change happens because I access an external script .scptd file within my main script.
One other item, the actual app in the global Finder Script Menu is an alias.
If I run my script within Script Editor, no change in paths - regardless of BBEdit.
If I run my script app alias by double clicking on it in any folder, even the global Finder's Script Folder, no change in paths regardless of BBEdit.
If BBEdit is in the background, no change in paths.
Only when BBEdit is frontmost and I click on the Finder's Script Menu and select my app, then the script app produces an error that says the following about my external .scptd file:
Macintosh HD:Users:johnlove:Library:my_Project:Project_Support:Scripts:External_Script_Libraries:externalLibrary.scptd

... and I definitely did not place the original or any of these folders/sub-folders in my Library folder.
???


text:
Q: www url rewrite not working (Read All Other Threads) i want to rewrite
example.com to www.example.com

My Code in apache2.conf (Main config file of apache in Linux/ubuntu 32bit ):
try 1:
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

Restart Apache Code Doesn't Work !
try 2:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
</IfModule>

Restart Apache Code Doesn't Work !
try 3:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.example.com$ [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]

Restart Apache Code Doesn't Work !
Loaded Modules in apache displays:
rewrite_module (shared)

How can i solve this ?
And is there any other mod i have to enable(I don't think so).
I have to put this code in some other file ?
It is neccessary/must use .htaccess for url rewriting ?

A: Your rules are fine.

*

*Make sure the rules are in the virtualhost of the "example.com" domain. If you have no "example.com" vhost, then place the rules in the first vhost container. S
<VirtualHost *:80>
    ServerName example.com
    ....

    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^example.com [NC]
    RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]

    ....
</VirtualHost>

*Try putting the rules in a directory container:
<Directory "/var/www/path/of/your/document_root/">
    RewriteEngine On
    RewriteCond %{HTTP_HOST} ^example.com [NC]
    RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
</Directory>