text:
Q: Dictionary within another dictionary + Multiple values for one key I want to do a dictionary which contains another dictionary. And I want that my dictionary have multiple values for only one key but I get a error : "An element with the same key already exists". I already did it in JAVA with HashMap and it's ok but in C# ...
Something like this:
static Dictionary<int, Dictionary<double, double>> _dict = new Dictionary<int, Dictionary<double, double>>()
        {
            { 1, new Dictionary<double,double>{ { 0.990, 0.0316 } } },
            { 1, new Dictionary<double,double>{ { 0.975, 0.0398 } } },
            { 1, new Dictionary<double,double>{ { 0.950, 0.0239 } } },
            { 1, new Dictionary<double,double>{ { 0.9  , 0.0158 } } },
            { 1, new Dictionary<double,double>{ { 0.1  , 2.71 } } },
            { 1, new Dictionary<double,double>{ { 0.050, 3.84 } } },
            { 1, new Dictionary<double,double>{ { 0.025, 5.02 } } },
            { 1, new Dictionary<double,double>{ { 0.010, 6.63 } } },

            { 2, new Dictionary<double,double>{ { 0.990, 0.02 } } },
            { 2, new Dictionary<double,double>{ { 0.975, 0.05 } } },
            { 2, new Dictionary<double,double>{ { 0.950, 0.10 } } },
            { 2, new Dictionary<double,double>{ { 0.9  , 0.21 } } },
            { 2, new Dictionary<double,double>{ { 0.1  , 4.60 } } },
            { 2, new Dictionary<double,double>{ { 0.050, 5.99 } } },
            { 2, new Dictionary<double,double>{ { 0.025, 7.38 } } },
            { 2, new Dictionary<double,double>{ { 0.010, 9.21 } } },

            { 3, new Dictionary<double,double>{ { 0.990, 0.12 } } },
            { 3, new Dictionary<double,double>{ { 0.975, 0.22 } } },
            { 3, new Dictionary<double,double>{ { 0.950, 0.35 } } },
            { 3, new Dictionary<double,double>{ { 0.9  , 0.58 } } },
            { 3, new Dictionary<double,double>{ { 0.1  , 6.25 } } },
            { 3, new Dictionary<double,double>{ { 0.050, 7.81 } } },
            { 3, new Dictionary<double,double>{ { 0.025, 9.35 } } },
            { 3, new Dictionary<double,double>{ { 0.010, 11.34 } } },
};

I try the solution of LordTakkera.
I do that because I have to represent KHI2 Table. I do this in JAVA and my soft works perfectly but I don't know how to use REF in .NET.

A: Where you have duplicate keys, like below, you want all these values in a single inner dictionary.
{ 1, new Dictionary<double,double>{ { 0.990, 0.0316 } } },
{ 1, new Dictionary<double,double>{ { 0.975, 0.0398 } } },
{ 1, new Dictionary<double,double>{ { 0.950, 0.0239 } } },
{ 1, new Dictionary<double,double>{ { 0.9  , 0.0158 } } },
{ 1, new Dictionary<double,double>{ { 0.1  , 2.71 } } },
{ 1, new Dictionary<double,double>{ { 0.050, 3.84 } } },
{ 1, new Dictionary<double,double>{ { 0.025, 5.02 } } },
{ 1, new Dictionary<double,double>{ { 0.010, 6.63 } } },

becomes:
{ 1, new Dictionary<double,double>{
    { 0.990, 0.0316 }, { 0.975, 0.0398 }, { 0.975, 0.0398
    }, ........ }}

A: As your error suggests, you cannot have multiple values with the same key in a C# dictionary. This is good, what value would be returned by a duplicate key? It would be undefined behavior at best.
However, the code you are writing would work fine with one tweak:
static Dictionary<int, List<Dictionary<double, double>> = new Dictonary<int, List<Dictionary<double, double>>()
{
    {1, new List<Dictionary<double, double>()
        {
            new Dictionary<double,double>{ { 0.990, 0.0316 } },
            new Dictionary<double,double>{ { 0.975, 0.0398 } }
        }
    },
    ...
}

Keys can map to collections (which can hold collections themselves). From the code you posted, this looks like the most likely solution. Let me know if I can clarify anything!
UPDATE: If you are guaranteed that each of these "nested" dictionaries only has one element, you could use the other answer, or a KeyValuePair:
static Dictionary<int, List<KeyValuePair<double, double>> = new Dictonary<int, List<KeyValuePair<double, double>>()
{
    {1, new List<KeyValuePair<double, double>()
        {
            { 0.990, 0.0316 },
            { 0.975, 0.0398 }
        }
    },
    ...
}


text:
Q: No schema, tables after sucessful restore of PostgreSQL database I backed up the stack exchange archive database hosted on an RDS instance of PostgreSQL like so:
pg_dump stackexchange -h <host> -U postgres -password -o > stack.dmp

...A couple of hours later, I have a nice 151GB dump file.
Next, I restored this puppy to a different instance:
psql --set ON_ERROR_STOP=on -h <otherhost> -U postgres -d stackexchange -f stack.dmp

...and an hour or so later it completed with no errors. Happiness.
Weird thing is, pgadmin4 doesn't show the schema that should have been created, nor any of the tables, views, etc. Connecting with psql and issuing \dn returns only the public schema.
For giggles, I looked at the size of the database, and it looks right(ish):
stackexchange=> SELECT pg_size_pretty( pg_database_size('stackexchange') );
 pg_size_pretty
----------------
 145 GB
(1 row)

I used head to grab the first 50-ish rows from the dump, and all looks fine:
--
-- PostgreSQL database dump
--

-- Dumped from database version 11.10
-- Dumped by pg_dump version 11.11

SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;

--
-- Name: stackoverflow; Type: SCHEMA; Schema: -; Owner: postgres
--

CREATE SCHEMA stackoverflow;

ALTER SCHEMA stackoverflow OWNER TO postgres;

SET default_tablespace = '';

SET default_with_oids = false;

--
-- Name: posthistory; Type: TABLE; Schema: stackoverflow; Owner: postgres
--

CREATE TABLE stackoverflow.posthistory (
    id integer NOT NULL,
    posthistorytypeid integer,
    postid integer,
    revisionguid text,
    creationdate timestamp without time zone NOT NULL,
    userid integer,
    posttext text,
    jsonfield jsonb
);

ALTER TABLE stackoverflow.posthistory OWNER TO postgres;

So I'm sorta stumped. All this stuff executed correctly. Database is about the right size...but no objects.
Next, I got curious and tried to recreate the schema ("stackoverflow") that SHOULD have already been created:
stackexchange=> create schema stackoverflow;

It's 5 minutes later and I'm getting no response in the console. psql is just sitting there.

Does this sound at all familiar to anyone? I'm puzzled. Ideas on next steps?
EDIT: I did a CTRL-BREAK on psql. Results:
stackexchange=> create schema stackoverflow;

^CCancel request sent
ERROR:  canceling statement due to user request
CONTEXT:  while inserting index tuple (0,12) in relation "pg_namespace_nspname_index"

A: The pg_dump command you show cannot be the one you used, because there is no -o option, and assword is not a valid port number.
Anyway, your problem is a different one: there is an open transaction that holds a lock on pg_namespace that prevents you from creating a schema.
Debug as follows:

*

*In a psql session, run
SELECT pg_backend_pid();  -- to figure out your process ID
\i stack.dmp

*When the first session hangs, start a second one and run
SELECT pg_blocking_pids(12345);  -- use the pid of the blocked session

Now you know which sessions are blocking you. Look at pg_stat_activity to learn more about these transactions. If necessary, terminate them with pg_terminate_backend.
In the case where the culprit is a prepared transaction, look for entries in pg_prepared_xacts and undo them with ROLLBACK PREPARED.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to implment a GCM Server in C# that supports CCS I'm trying to write a 3rd party server application for sending and receiving notifications from Android devices using GCM's CCS as outlined here. I'm leveraging PushSharp for handling the sending of notifications from my server app, but I can't seem to find any documentation on how to receive messages at the server level. Is this supported or is there another 3rd party XMPP library for .NET that handles this cleanly?

A: I dont think you can receive messages at server level, this is not the point in push notifications. if you want to send information to the service from the app, i would suggest writing a webservice. i've implemented this myself, and had to do a little digging to find some code that could communicate with the webservice as it was written in c# and the app was java, but i can paste some code that might help if you think that would help you communicate.
Long story short though, if you want an app to talk to a server, then write a web service. if you want a server to talk to an app, use push notifications.


text:
Q: JSoup. I am trying to get text from a span that has multiple classes with strange names the compiler is not liking Here is what I have for the code:
enter code here text = text.toUpperCase();
        Document doc = Jsoup.connect("https://finance.yahoo.com/quote/" + text + "?p=" + text).userAgent("Safari").get();

        Element temp = doc.selectFirst("span.Trsdu(0.3s).Fw(b).Fz(36px).Mb(-4px).D(ib)");

        System.out.println(temp);

Here is the span I am trying to get:
1,119.50

I am trying to get 1119.50 but have been unable to. Please help! I am using netbeans as my java IDE. I am new to JSoup so please help me if I am doing something ignorant.

A: This code should get you the value you are looking for by selecting the first span the data-reactid you are looking for:
Element test = doc.select("span[data-reactid='35']").first();
System.out.println(test.text());


text:
Q: Saber quais checkboxs estão selecionadas no adapter e fazer operações na activity baseado nas checks selecionadas Olá, eu tenho uma lista (ListView) e quando eu seleciono a opção 1 no meu spinner ele da visible no framelayout para mostrar na tela uma checkbox para cadad item da lista com status 0p, eu queria saber quais checksboxs estão selecionadas no adapter para que na activity eu possa incluir numa lista e mudar status.
Esta é minha activity:
spinnerSync.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(final AdapterView<?> parent, final View view,  final int position, long id) {

            //Guardo na variavel estatica para no adapter fazer a verificação se mostra ou não a check
            POSITION=position;
                //Cria a lista na activity
                adapter2= new SyncAdapter2(listaForm, getApplicationContext());
                listView.setAdapter(adapter2);

                buttonSync.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //Verificar quais itens da listView estão checkados(checkbox)
                        // Pegar a posição dos itens checkado

                        //inclui form no SQLite e consequentemente na lista agenda
                        if (listaForm.get(position).getStatus()==0) {
                            dao.incluir(listaForm);
                        }

                        Handler handler = new Handler();
                        handler.postDelayed(
                                new Runnable() {
                                    public void run() {
                                        load.setVisibility(View.GONE);
                                    }
                                }, 3000L);
                        load.setVisibility(View.VISIBLE);
                    }
                });
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    });

E este meu adapter:
@Override
public View getView(final int position, final View convertView, ViewGroup parent) {
    View v = View.inflate(context, R.layout.sinc_item_listview2, null);

    checkBox = (CheckBox) v.findViewById(R.id.checkbox);

    checkBox.setVisibility(View.GONE);

    if (SincActivity.POSITION == 1) {

        if (listForm.get(position).getStatus() != 1)
            checkBox.setVisibility(View.VISIBLE);
            TextView tvDayNumber = (TextView) v.findViewById(R.id.tvDayNumber);
            tvDayNumber.setText(listForm.get(position).getDataForm());
            tvDayNumber.setTypeface(tf);
            TextView tvDayWeek = (TextView) v.findViewById(R.id.tvDayWeek);
            tvDayWeek.setText(listForm.get(position).getDataForm());
            tvDayWeek.setTypeface(tf);
            TextView tvLocation = (TextView) v.findViewById(R.id.tvLocation);
            tvLocation.setText("#" + listForm.get(position).getNomeLoja());
            tvLocation.setTypeface(tf);
            TextView tvHour = (TextView) v.findViewById(R.id.tvHour);
            tvHour.setText(listForm.get(position).getHora() + " | ");
            tvHour.setTypeface(tf);
            TextView tvForms = (TextView) v.findViewById(R.id.tvForm);
            tvForms.setText(listForm.get(position).getNomeFom());
            tvForms.setTypeface(tf);

            ImageView imageInfo = (ImageView) v.findViewById(R.id.imageInfo);
            if (listForm.get(position).getStatus() == 1) {
                imageInfo.setImageResource(R.drawable.checked);
            } else {
                imageInfo.setImageResource(R.drawable.exclamation);
            }
    } else {
        TextView tvDayNumber = (TextView) v.findViewById(R.id.tvDayNumber);
        tvDayNumber.setText(listForm.get(position).getDataForm());
        tvDayNumber.setTypeface(tf);
        TextView tvDayWeek = (TextView) v.findViewById(R.id.tvDayWeek);
        tvDayWeek.setText(listForm.get(position).getDataForm());
        tvDayWeek.setTypeface(tf);
        TextView tvLocation = (TextView) v.findViewById(R.id.tvLocation);
        tvLocation.setText("#" + listForm.get(position).getNomeLoja());
        tvLocation.setTypeface(tf);
        TextView tvHour = (TextView) v.findViewById(R.id.tvHour);
        tvHour.setText(listForm.get(position).getHora() + " | ");
        tvHour.setTypeface(tf);
        TextView tvForms = (TextView) v.findViewById(R.id.tvForm);
        tvForms.setText(listForm.get(position).getNomeFom());
        tvForms.setTypeface(tf);

        ImageView imageInfo = (ImageView) v.findViewById(R.id.imageInfo);
        if (listForm.get(position).getStatus() == 1) {
            imageInfo.setImageResource(R.drawable.checked);
        } else {
            imageInfo.setImageResource(R.drawable.exclamation);
        }
    }

    checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked){
                Toast.makeText(context,"Checkado",Toast.LENGTH_SHORT).show();
                Log.w("id",position+"");
                listaInteger.add(listForm.get(position).getIdForm());

            }else{
                Toast.makeText(context,"uncheck",Toast.LENGTH_SHORT).show();
                Log.w("id",position+"");
                listaInteger.remove(listForm.get(listForm.get(position).getIdForm()).getIdForm());
            }
        }
    });

    v.setTag(listForm.get(position).getIdForm());

    return v;
}


text:
Q: Umbraco 7: Create an object of type menu and edit it in the back-end's UI I've installed Umbraco 7.1.5 using NuGet in VS2013 and using Razor syntax in my Views. I know that we can create a navigation menu from the document tree, but:
Q: Is it possible to create an object of type menu and edit it in the back-end's UI so that a non-developer could add as many items or sub items to the menu as needed with properties like text, href and optional image, with a plus sign. How can this be done? / or is this possible using this property editor?

A: Yes of course and you already have answered half your own question, but no you wouldn't need a plugin. The solution is very straightforward.

*

*You create your MenuItem doc type, and in the "structure" tab allow MenuItem objects to be created under MenuItem objects.

*You create somewhere in your content tree to allow editors to create their menu structures. I like to have a "site settings" node that things like site config, promos and other non-content items can be grouped.

*Start creating your MenuItem tree.

*In your razor, look for the root of the MenuItem tree and traverse down the tree using  some self-referential code like you would to create a site map. Something like *:
@helper traverse(IPublishedContent node)
{

    @foreach (var item in node.Children)
    {

              @item.GetPropertyValue("menuItemText")

          @traverse(item)

    }

}

    @traverse(@parentOfrootMenuItem)

* Repurposed from our.umbraco.org


text:
Q: SHA1 hash producing different result in Objective-C and C#.NET Basically I want to write function that computes sha1 hash.
So far I have tried is as follows.
C#.NET
byte[] p2 = System.Text.Encoding.Unicode.GetBytes("password");
System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1CryptoServiceProvider();
byte[] result = sha.ComputeHash(p2);
string encodedPassword = Convert.ToBase64String(result);

Output : 6Pl/upEE0epQR5SObftn+s2fW3M=
Objective-C
I have added classes for Base64 from NSData_Base64 Classes reference.
NSString *password = @"password";
NSData *data = [password dataUsingEncoding:NSUTF8StringEncoding];
NSString *unicodePassword = [[NSString alloc] initWithData:data encoding:NSUnicodeStringEncoding];
data = [unicodePassword dataUsingEncoding:NSUnicodeStringEncoding];

unsigned char hash[CC_SHA1_DIGEST_LENGTH];
CC_SHA1([data bytes], [data length], hash);
NSData *result = [NSData dataWithBytes:hash length:CC_SHA1_DIGEST_LENGTH];
NSLog(@"Result: %@",[result base64EncodedString]);

Output : dYusXVhObIBzJMgg1E1FJ9cK1NY=
Can anyone please suggest what am I doing wrong ?
Why these two values differs ?
Please correct my mistakes.

A: This line is wrong, since you interpret UTF8 encoded data as if it was Unicode encoded:
NSString *unicodePassword = [[NSString alloc] initWithData:data encoding:NSUnicodeStringEncoding];

Replce the second line with:
NSData *data = [password dataUsingEncoding:NSUnicodeStringEncoding];
The 2 first bytes in data is a BOM (Byte order mark).
Remove these 2 bytes with
data = [NSData dataWithBytes:[data bytes] + 2 length:[data length] - 2];
...and then hash that data any you will have the same hash as in C#.

A: For further information I found that SHA1 function can have some results..
So I have implemented methods at this link: MD5 and SHA1 iOS implementation linked by this stackoverflow question
and I refine it with my integration that send as parameters if you send UTF8-encoding string or not (unicode one) and if you want hexadecimal string or decimal one
- (NSString*) sha1UTF8Encoding:(BOOL)utf8 andDecimal:(BOOL)decimal
{
    const char *cstr;
    if (utf8) {
        cstr = [self cStringUsingEncoding:NSUTF8StringEncoding];
    }else{
        cstr = [self cStringUsingEncoding:NSUnicodeStringEncoding];
    }
    NSData *data = [NSData dataWithBytes:cstr length:self.length];

    uint8_t digest[CC_SHA1_DIGEST_LENGTH];

    CC_SHA1(data.bytes, data.length, digest);

    NSMutableString* output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2];

    for(int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++){
        if (decimal) {
            [output appendFormat:@"%i", digest[i]];
        }else{
            [output appendFormat:@"%02x", digest[i]];
        }
    }

    return output;
}

(Note that I implemented this method in a NSString Category)
With this I tested that you can use it for many purpose sha1 operation, for example with this configuration:
NSString* sha1 = [stringToTest sha1UTF8Encoding:YES andDecimal:YES];

sha1 variable match with the one product by the C# method found at this link: Hashing using the SHA1 class


text:
Q: Regex: Sub expressions? I need to create a regex that will match this expression:
replace:sub\:str:new\:Substr

I have to be careful about not matching other similar looking strings though.  For example, this a different match:
slice:fromIndex[:toIndex]

Specifically:

*

*The string must begin with replace:.  If it does not, then nothing should match.

*It must match escaped colons: \: but not unescaped colons: :

*There must be two matches (the sub string and new substring). For example, in the example string the regex would match: sub\:str and new\:Substr.

*The point is to extract out the substring and it's replacement for use later.  The string will always be in the format replace:<subString>:<replacementString>.  However, both the subString and the replacementString can have escaped colons :, which is why the example includes them.

I've been unable to come up with a solution.  While I'm not an expert at Regex, I'm normally pretty competent.  But so far I've only been able to either ignore replace: and simply match on (?<=\:)(?:\\:|[^:])+ to include both substrings, but I end up matching other patterns as well.  If I change the look behind to (?<=replace:) I only match the first substring.  I just can't figure out how to get it to also match that second substring without including the : separator.  I suspect I need to nest the expression somehow but I've been completely unsuccessful at it.
Note:  I can solve this in the language.  I can simply check if the string has the prefix replace: as a separate check.  But I'd really like to do the match completely in Regex if it's possible.
Update (some examples)

*

*replace:sub\:str:new\:Substr matches: sub\:str, new\:Substr

*replace:subString:replacment matches: subString, replacement

*replace:UserId:user\:ID matches: UserId, user:ID

*replace:UserName:Aaron Hayman matches: UserName, Aaron Hayman

*replace:userId:uid90809y087 matches: userId, uid90809y087

*rep:userId:user matches: none

*replace:UserName matches: none

*slice:908:1098 matches: none

This should give you an example.  As background, after this string is parsed, it would be applied as a kind of filter for another template string.

A: The regex that will match all escape sequences you may have in a C string literal will look like
replace:([^:\\]*(?:\\.[^:\\]*)*):([^:\\]*(?:\\.[^:\\]*)*)

See the regex demo
NOTE: If it must appear at the start of the string, add ^ at the pattern staet.
Details:

*

*replace: - a literal char sequence

*([^:\\]*(?:\\.[^:\\]*)*) - Capturing group 1 matching

*

*[^:\\]* - 0+ chars other than : and \

*(?:\\.[^:\\]*)* - zero or more sequences of:

*

*\\. - any escaped char (a \ and any char)

*[^:\\]* - 0+ chars other than : and \

*: - an unescaped :

*([^:\\]*(?:\\.[^:\\]*)*) - see above.

A: How about:
^replace:(\w+\\:\w+):(\w+\\:\w+)

The first group will contain sub\:str  and the second new\:Substr
New version according to OP's edit:
^replace:([^:]+(?:\\:)?[^:]+):([^:]+(?:\\:)?[^:]+)

It works for all given test cases
If you don't want replace in the whole match, put it in lookbehind:
(?<=^replace:)([^:]+(?:\\:)?[^:]+):([^:]+(?:\\:)?[^:]+)

A: Quite convoluted, but you can nest lookarounds:
replace:(.+?(?!(?<=\\):)):(.+(?!(?<=\\):))
Demo
It will ensure that after replace: any character is not followed by a : not itself preceded by a \
Drawback:
In case of 3 parts (a third not escaped :), The second part will include everything, see the demo for what I mean.


text:
Q: Create custom column in Linq with sum total of column How to Create custom column using linq? coz i alway get error
Fig. 1

Sequence contains more than one element

Data from grid that i selected as context

My code seems right when removing custom column that iv'e created TotalAmount
var studentservices = from ser in result.ToList()
                                          where partStudentServices.Contains(ser.Description)
                                          group ser by ser.Description into gser
                                          select new
                                          {
                                              CCode = gser.FirstOrDefault().Code,
                                              CDescription = gser.FirstOrDefault().Description,
                                              CAmount = gser.Where(s => s.EducationLevel == "College").Select(ns => ns.Amount).Sum(),
                                              HAmount = gser.Where(s => s.EducationLevel == "High School").Select(ns => ns.Amount).Sum(),
                                              GAmount = gser.Where(s => s.EducationLevel == "Grade School").Select(ns => ns.Amount).Sum(),
                                              KAmount = gser.Where(s => s.EducationLevel == "Kinder").Select(ns => ns.Amount).Sum(),
                                              TotalAmount = gser.GroupBy(g => g.Description).Select(ns => ns.Sum(sumn => sumn.Amount))
                                          };

                    d.StudentServicesReport.DataSource = studentservices.ToList();
                    d.xTC_StudentServices_Code.DataBindings.Add("Text", null, "CCode");
                    d.xTC_StudentServices_Name.DataBindings.Add("Text", null, "CDescription");
                    d.xTC_StudentServices_College.DataBindings.Add("Text", null, "CAmount");
                    d.xTC_StudentServices_HS.DataBindings.Add("Text", null, "HAmount");
                    d.xTC_StudentServices_GS.DataBindings.Add("Text", null, "GAmount");
                    d.xTC_StudentServices_PS.DataBindings.Add("Text", null, "KAmount");
                    d.xTC_StudentServices_CollegeTotal.Text = studentservices.Select(sa => sa.CAmount).Sum().ToString();
                    d.xTC_StudentServices_HSTotal.Text = studentservices.Select(sa => sa.HAmount).Sum().ToString();
                    d.xTC_StudentServices_GSTotal.Text = studentservices.Select(sa => sa.GAmount).Sum().ToString();
                    d.xTC_StudentServices_PSTotal.Text = studentservices.Select(sa => sa.KAmount).Sum().ToString();
                    d.xTC_StudentServices_Total.Text = studentservices.Select(sa => sa.TotalAmount).ToString();

but get error see Fig. 1
coz im going to generate a report this should be the output. the red text should be the total amount of each row.

on printing the error shown on cell that i assign.

Anyone can help me? I'm stuck on this module about 1 hour.

A: Not 100% sure but it looks like your TotalAmount assignment may be incorrect.  Have you tried the following:
 TotalAmount = gser.Sum(sumn => sumn.Amount)

I believe that the way that you have it, .Select returns an IEnumerable  and you are attempting to assign that as the value of your label so it is just displaying the type.


text:
Q: What is NeRF(Neural Radiance Fields) used for? Recently I am studying the research NeRF: Representing Scenes as Neural Radiance Fields for View Synthesis(https://www.matthewtancik.com/nerf), and I am wondering: What is it used for? Will there be any application of NeRF?
The result of this technique is very impressive, but what is it used for? I keep thinking of this question over and over again. It is very realistic, the quality is perfect, but we don't want to see the camera swinging around all the time, right?
Personally, this technique has some limitations:

*

*Cannot generate views that never seen in input images. This technique interpolates between two views.

*Long training and rendering time: According to the authors, it takes 12 hours to train a scene, and 30s to render one frame.

*The view is static and not interactable.
I don't know if it is appropriate to compare NeRF with Panorama and 360° image/video, essentially they are different, only NeRF uses deep learning to generate new views, the others basically are just using smart phone/camera to capture scenes plus some computer vision techniques. Still, the long training time makes NeRF less competitive in this application area. Am I correct?
Another utility I can think of is product rendering, however, NeRF doesn't show advantages compare to using 3D software to render. Like commercial advertisement, usually it requires animation and special effects, then definitely 3D software can do better.
The potential use of NeRF might be 3D reconstruction, but that would be out of the scope, although it is able to do that. Why do we need to use NeRF for 3D reconstruction? Why not use other reconstruction techniques? The unique feature of NeRF is the ability of creating photo-realistic views, if we use NeRF for 3D reconstruction, then this feature becomes pointless.
Does anyone have new ideas? I would like to know.

A:
Why do we need to use NeRF for 3D reconstruction?

The alternative would be multi-view stereo, which produces point clouds of finite resolution and is susceptible to illumination changes. If you then render such point cloud without non-trivial post-processing, it will not look photorealistic.

I don't know if it is appropriate to compare NeRF with Panorama and 360° image/video,

Well, if you deal with exactly flat scene with simple lighting (i.e. ambient light and Lambertian objects), then you can use panorama techniques for new view synthesis. In general though, it won't produce the result you expect. You have to know the depth to interpolate correctly.
When it comes to practical limitations (slow; does not model deformations), NeRF should be considered a milestone that provided a proof of concept that representing surface as a level set of MLP-modelled function can result in sharp rendering. There is already good progress in addressing those limitations, and multiple works apply this idea for practical tasks.


text:
Q: Git: auto-fixup a commit in a feature branch When I am done with a feature, often what I would like is to auto-fixup a commit followed by a force-push to a remote origin before a merge to master.
I end up rebasing on top of master so I can fixup a commit, because I found a tiny thing I want to change and I don't want that change as a separate commit. So I rebase interactively, I fixup the last commit, then I force push. Is there a way to do that in one step?

A: You can save the step of editing the list of commits manually in rebase -i using git commit --fixup <commit> when making your fixup commit. Then, if rebase.autoSquash is set to true, git rebase -i will automatically turn the line containing this commit into a fixup line right below the commit to fix.

A: Assuming you want to fixup the last commit, you could just amend that commit. After authoring your changes, just issue:
$ git commit -a --amend --no-edit

You'll still have to force-push, though.
Here's a breakdown of git commit options used above:
-a, --all:
Tell the command to automatically stage files that have been modified and
deleted, but new files you have not told Git about are not affected.

--amend:
Replace the tip of the current branch by creating a new commit.

--no-edit:
Use the selected commit message without launching an editor.
For example, `git commit --amend --no-edit` amends a commit without changing
its commit message.

A: git commit -a --amend --no-edit && git push -f


text:
Q: Cloud Endpoint Authentication audiences I created a API in Python with Google Cloud Endpoint Framework and my Android Client is the only application which has the permission to talk with the API.
I followed the tutorials and guides on Google for Authentication and to protect the API one can give access to specific client ids:
WEB_CLIENT_ID = 'myApiClientId.apps.googleusercontent.com'
ANDROID_CLIENT_ID = 'myAndroidClientId.apps.googleusercontent.com'
ANDROID_AUDIENCE = [ANDROID_CLIENT_ID]
ALLOWED_CLIENT_IDS = [WEB_CLIENT_ID, ANDROID_CLIENT_ID, endpoints.API_EXPLORER_CLIENT_ID]

api_collection = endpoints.api(name='myApi',
                               version='v1',
                               allowed_client_ids=ALLOWED_CLIENT_IDS,
                               audiences=ANDROID_AUDIENCE,
                               auth_level=endpoints.AUTH_LEVEL.REQUIRED
                               )

On this site they say that "audiences" should contain the client id of the backend api

For Android clients, this mechanism is the audiences argument, in which you specify the client ID of the backend API.

But on this site, they tell that the "audiences" field should contain the Android client id:

Replace ALLOWED_CLIENT_IDS with the list of OAuth 2 client IDs generated from each client's Google Cloud Platform Console project, and replace ANDROID_AUDIENCE with the list of Android web client IDs. The web client ID is the client ID with .apps.googleusercontent.co appended, for example:YOUR-CLIENT-ID.apps.googleusercontent.com.

What is the correct way to protect the API for unauthorized access? I don't need the "user" account on backend side, I only want that the Android client is the only client which can access the API. My REST client can access the API too though the client ids are specified and AUTH_LEVEL is set on required.

A: It seems that ANDROID_AUDIENCE has to be the web client id of the backend server. Also, I had to add a new "web client id" for my android application but not of type "Android" but "Webapplication". This client id has to be in the google-services.json together with the Android client id and in the ALLOWED_CLIENT_IDS array at the backend server.
And in every method I have to check for get_current_user(). I don't understand why this is necessary but it works only this way.
I really hae to say that the documentation or better "guides" could be a little bit beteter on Google site and consistent.


text:
Q: Failed to find link or button, rspec I'm using rspec to test my rails app and i have some trouble with click on in Capybara:
This is my spec:
#!/bin/env ruby
# encoding: utf-8
require 'user'
require 'rails_helper'
describe User do
  before(:all) do
    shop = Shop.create(:shop_no => '2401', :shop_name => 'Yamaha')
    link = Link.create(:name => "location")
    @agent = User.create(:user_id => '1992112-1234', :password=> 'sa1234',
    :name => 'sa1234', :uid=> '0000000000002',
    :shop_no => '2401')
    login(@agent)
  end
...
  it "logout sucess in menu" do
    visit "welcome/menu"
    click_on('Button')
  end
...

And, this is my page where i looking for 'Button'

            発注

                仕入

                    Button

                    直接仕入

When i run spec, i have this error:

Please! help me to fix that :)

A: There is click_button option you can try that also, i hope this link would be helpful for you http://www.rubydoc.info/github/jnicklas/capybara


text:
Q: Model with "linked-list" type self-reference, how to get only those which are not referenced? Rails 5, ActiveRecord on PostgreSQL database. Have class with a previous_id column, like so:
class Event < ApplicationRecord
  belongs_to :previous, class_name: 'Event'
end

I would like to get all Events that have no other Events referencing them as a "previous" Event. How can I make a query to do this?
I can obviously do something like:
Event.where.not(id: Event.pluck(:previous_id))

But my sense is that there is a more performant way to achieve this.

A: Building off of @Craig Ringer's comment with some ruby code that will produce his recommended SQL, you can do something like this
Event.joins("left join events referencing on referencing.previous_id = events.id")
     .where("referencing.id is null")


text:
Q: Smoothly transitioning one mesh to another I have two meshes Mesh1 and Mesh2. Mesh1 does not necessarily have the same amount of vertices or faces as Mesh2.
What is the best way to "transition" between these two meshes smoothly?
Obviously, I could do a linear interpolation of some sort. But there are some problems beyond this that I need to solve. One problem that I'm facing is the "not necessarily have the same amount of vertices or faces" part. Maybe I need to bypass this restriction by taking one of my faces in one of the meshes and subdividing it until there's the same amount of faces in both meshes (would this adjust the result in a weird way, like an "explosion" in the subdivided part?)
However, the main problem is choosing which faces on Mesh1 correspond to Mesh2. Is there any algorithm that can accomplish this?


text:
Q: Why does this code has a time complexity of O(N*N)? int a = 0;
for (i = 0; i < N; i++) {
    for (j = N; j > i; j--) {
        a = a + i + j;
    }
}

Why does this code has time complexity of O(NN) ? Are all  nested loops with n,m,q,.... bounds have a complexity of O(nm*q....) even though few iterations of the loops will not happen?

A: The reason for this is that constant factors are ignored in Big-O notation.
Your outer loop runs N times, while the inner loop runs on average N/2 times for each of the outer iterations.
This gives O(N * 1/2 * N) executions of the statements within the inner loop. Since we ignore constant factors, we end up with O(N * N) which is O(N^2).
The reason for omitting constants is simple: Big-O notation is about what happens when N is big. If you look at it this way - O((N^2)/2) - you see that increasing N has much more influence in the term, than whether or not we omit the division by two.

A: I wouldn't say all nested loops have that complexity, but this one certainly does.  The number of iterations through the inner loop is something like this (there might be an off-by-one error):

*

*i = 0:  N times

*i = 1:  N - 1 times

*i = 2:  N - 2 times

*. . .

*i = N-1: 1 times

*i = N:  0 times

Let's count the total number of times the innermost code is called.  In this case, you can figure this out arithmetically. The innermost code is executed about N * (N + 1) / 2 times (this is the sum of elements from 1 to N).  This simplifies to 0.5 * N^2 + 0.5 * N and that has a complexity of N^2.


text:
Q: Use of "in" or "of the" In the sentence below would it be grammatically correct the use of "in" before "demand"?

The increase in stress rates has intensified my laughter amount from
  the increase in demand for job responsibility.

A: Using "in" before "demand" is just as correct as using "in" before "stress". The part to focus on is "increase in noun phrase", the noun phrases being "stress rates" and "demand for job responsibility".
The phrase "in demand" refers to something being desired. Note the difference between

...the increase in demand for job responsibility

and

...the increase, in demand, for job responsibility

The first one indicates the desire or demand for job responsibility is increasing or has increased. The second one, specifically using the phrase "in demand", indicates that it is the increase itself that is desired or demanded.
As an aside, your example sentence, while not incorrect, is as a whole bit awkward stylistically. It's also hard to tell what exactly you mean. It seems to me you mean something more like:

The increase in stress rates has intensified the amount of my laughter more than the increase in demand for job responsibility.

Another more natural way to say this would be:

The increase in stress rates has made me laugh more than the increase in demand for job responsibility.

The phrase "made me verb" means the same as "caused me to verb". If you wanted to keep the idea of intensity and intensifying in the sentence, I would phrase it like this:

The increase in stress rates has made me laugh intensely more than the increase in demand for job responsibility.

Apologies if I've distorted your intended meaning too much. =P


text:
Q: How do you use a fingerprint Scanner on 13.10 I have a ThinkPad T410s and I can't use the fingerprint scanner installed? Any Suggestion...

A: There are quite a few questions and responses to Fingerprint scanners on Ask Ubuntu.
Unfortunately these scanners appear to be quite proprietary and open-source support very limited.
There appears to only be the one Linux fingerprint scanner project.  I could not get this working on my laptop either.
Anyway give this a go http://www.omgubuntu.co.uk/2013/03/how-to-get-your-fingerprint-reader-working-in-ubuntu
and best of luck!!


text:
Q: Build a time out to load the page slower Is there a way to make the loading of a page go slower? There are some processes which happen to fast to get a grip on and I would like to see them a bit slower.
Is there anything I can do to slow down the loading-time of a page?
I need this because there is one CSS-selector on which I need to change something, but I can't catch him with firebug, cause the page is loading too fast.

A: You can just use sleep() in PHP to make it delay the loading.
Here is an example from the PHP Manual:
<?php

// current time
echo date('h:i:s') . "\n";

// sleep for 10 seconds
sleep(10);

// wake up !
echo date('h:i:s') . "\n";

?>

http://uk.php.net/sleep

A: You can use sleep(seconds); (see HERE), but I suspect your application design should be improved if you need it...

A: Solution 1 (seconds based)
You could use
sleep($seconds);

where $seconds, as the variable name explain, are the seconds that the script have to wait.
Solution 2 (microseconds based)
You can also use
usleep($microseconds);

to delay the execution in microseconds instead of seconds.
References

*

*sleep()

*usleep()

A: sleep().


text:
Q: Problem accessing robots.txt from search script I have been using the Perlfect Search Script http://www.perlfect.com/freescripts/search/ for several years on my sites. For reasons unknown it stopped working properly a few months ago. When I run the indexing script I get the following error:
Loading http://emetnews.org/robots.txt...
Error: Couldn't get 'http://emetnews.org/robots.txt': response code 403
Not using any robots.txt.
Error: Couldn't get 'http://emetnews.org/': response code 403

The robots.txt file is easily accessible by Google and even visitors to the site. It has the permissions set to 644. I have not changed anything prior to the script no longer working. I can't get in contact with the script developer (they haven't updated the script or the site for a few years now). My Web host doesn't work with "outside" scripts.
Anyone have any idea what's wrong? I like the layout of the script. It looks very professional when in use (and its free).

Result of running curl --user-agent libwww-perl/6.08 http://emetnews.org/robots.txt:
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">

<title>403 Forbidden</title>

Forbidden

You don't have permission to access /robots.txt
on this server.

Additionally, a 500 Internal Server Error
error was encountered while trying to use an ErrorDocument to handle the request.

curl http://emetnews.org/robots.txt:
User-agent: Mediapartners-Google
Disallow:

Sitemap: http://emetnews.org/sitemap.xml

# User-agent: Browsershots
# Disallow:

User-agent: NinjaBot
Allow: /

User-agent: *
Disallow: /_lee/
Disallow: /blosxom/flavours/
Disallow: /blosxom/plugins/
Disallow: /contact/
Disallow: /cgi-bin/
Disallow: /feedback/
Disallow: /img/
Disallow: /includes/
# Disallow: /javascript/
Disallow: /lastrss/
# Disallow: /media/
Disallow: /mp3s/
Disallow: /print/
Disallow: /r/
Disallow: /sendPage/
# Disallow: /style/
Disallow: /talkback/
Disallow: /trip/
# block any URL that includes a ?
Disallow: /*?

# Disallowing the robot from Alexa from listing files in the Internet Archive
User-agent: ia_archiver
Disallow: /

Thanks for your help. I did have this in my .htaccess file:
# Blocks access from libwww-perl user-agents and URLS which include the command "=http:"
RewriteCond %{HTTP_USER_AGENT} libwww [NC,OR]
RewriteCond %{QUERY_STRING} ^(.*)=http [NC]
RewriteRule ^(.*)$ - [F,L]

I commented it out and I now get the text of the robots.txt file when I run
curl --user-agent libwww-perl/6.08 http://emetnews.org/robots.txt

Now, however, when I run the indexer, instead of it saying can't get the robots.txt file, it now says it ignores the file. ???


text:
Q: Extract matching values from array of objects in javascript I have an array of objects and I am trying to create a filter where a user types few letters and gets the list of all the matching records.
users = [{office: "J Limited", contact: {first_name: "James", last_name: "Wilson", address: Canada}},{office: "Q Limited", contact: {first_name: "Quin", last_name: "Ross", address: Australia}},{office: "N Limited", contact: {first_name: "Nancy", last_name: "Mathew"}, address: "England"}]

I have a textfield where user types to get the results and lets suppose user types ja so the result should search fields office, contact first_name and last_name and if any such field contains matching letter should be the request like in this case the result output should be
J Limited, James, Wilson

Please help me achieve this.

A: To get the matching users, you can do something like:
const searchString = 'ja'

const matchingUsers = users.filter(user =>
  user.office.contains(searchString) ||
  user.contact.first_name.contains(searchString) ||
  user.contact.last_name.contains(searchString)
)

And then you can format that list of matching users however you like
EDIT: contains may not work on some JS versions (works on Chrome), so replace contains with includes:
const searchString = 'ja'

const matchingUsers = users.filter(user =>
  user.office.includes(searchString) ||
  user.contact.first_name.includes(searchString) ||
  user.contact.last_name.includes(searchString)
)

A: let users = [{
    office: "J Limited",
    contact: { first_name: "James", last_name: "Wilson", address: "Canada" }
}, {
    office: "Q Limited",
    contact: { first_name: "Quin", last_name: "Ross", address: "Australia" }
}, {
    office: "N Limited",
    contact: { first_name: "Nancy", last_name: "Mathew", address: "England"},
}];

// ig: i for case-insensitive, g for global
const regEx = new RegExp('ja', 'ig');

const result = users.filter(
    each =>
        each.office.match(regEx) ||
        each.contact.first_name.match(regEx) ||
        each.contact.last_name.match(regEx)
)
.map(
    each => [
        each.office,
        each.contact.first_name,
        each.contact.last_name
    ]
);

console.log(result);

A: You can loop through the array and search for objects.

users = [{
  office: "J Limited",
  contact: {
    first_name: "James",
    last_name: "Wilson",
    address: "Canada"
  }
}, {
  office: "Q Limited",
  contact: {
    first_name: "Quin",
    last_name: "Ross",
    address: "Australia"
  }
}, {
  office: "N Limited",
  contact: {
    first_name: "Nancy",
    last_name: "Mathew"
  },
  address: "England"
},
{
  office: "J Limited",
  contact: {
    first_name: "Jacob",
    last_name: "Wilson",
    address: "Canada"
  }
}
]

function search(searchKey) {
  searchKey = searchKey.toLowerCase();
  results = [];
  for (var i = 0; i < users.length; i++) {
    if (users[i].contact.first_name.toLowerCase().includes(searchKey) || users[i].contact.last_name.toLowerCase().includes(searchKey) || users[i].office.toLowerCase().includes(searchKey)) {
      results.push(users[i]);
    }
  }
  return results;
}

var resultObject = search("ja");
if (resultObject) {
  for(i in resultObject){
    console.log(resultObject[i].office, resultObject[i].contact.first_name, resultObject[i].contact.last_name)
  }
}

A: const filterUser = users.filter(user =>{           return user.office.toLowerCase().includes((searchField).toLowerCase())      });

your searchField is the value of input and the filteruser can now be used as it will return the user with office name contain in the search or return all if nothing is enter in searchField.

You can now map through filterUser to be able to use the user contain the input value which is your searchField.


text:
Q: Prove that $f(\Bbb C)=\Bbb C$ I need some help with the following problem:

Let $f:\Bbb C \to \Bbb C$ be continuous satisfying that $f(\Bbb C)$ is an open set and that $|f(z)| \to \infty$ as $z\to \infty$. Prove that $f(\Bbb C)=\Bbb C$.

My idea on this one is to prove by contradiction and assume that $S=f(\Bbb C)\ne\Bbb C$ to get some contradiction with the given two properties of the function. But I have no idea on how to proceed next.
Thanks in advance.

A: By your condition, the image of $f$ is closed (why? take a convergent sequence of points in the image, and their preimages. The preimages do not diverge to infinity, by assumption, so they have a limit point, which, by continuity, goes to the limit you want). So, $f(\mathbb{C})$ is open (by assumption) and closed. So, since $\mathbb{C}$ is connected, the image is all of $\mathbb{C}.$

A: Hint: Suppose $w$ is in the boundary of $f(\mathbb C)$.  Take a sequence $z_n$ with $f(z_n) \to w$.  There is a subsequence ...

A: Your conditions imply that we can continuously extend $f$ to give a continuous function $\hat{f}$ from the Riemann sphere to itself given below
$$ \hat{f}(x) = \begin{cases}
f(x) & x \neq \infty \\ \infty & x = \infty \end{cases}$$


text:
Q: Find largest set of lines which are parallel but not colinear I have a 5 lines below with each line representing a,b,c in ax+by+c = 0
1 0 0
1 2 3
3 4 5
30 40 0
30 40 50

I want to find the largest set of non colinear parallel lines from these lines. The result in the above case will be:-
set of 2 lines
3 4 5
30 40 0

The brute force approach would be to go through all the possible combinations which would be O(n*(n+1)/2) and update the largest possible set after each iteration.
Is there any way to find the set size faster?

A: A solution would be to transform the coordinates into (angle, distance from origin). Finding the largest set will then be O(nlogn).
Assuming that (a,b) are never both 0, find the distance to origin d using d = c/|(a,b)|. Then, find the angle θ using θ = atan2(b,a). You then have a list of coordinates that looks like this:
[[θ0,d0],
 [θ1,d1],
...
]

Sort this list using θ as the key.
Remove all elements that you consider colinear given a threshold. Simply parse the list to check if some pairs of consecutive elements have approximately the same value. Do not forget to test the last element with the first element to account for 360° = 0°. If you encounter a colinear pair, remove one of the element.
Using a minimum and maximum index starting at 0, increase the maximum index until the difference between the first angle (at min index) and the last angle (at max index) pass the angle tolerance that you can accept as being parallel (do not forget to consider that 359.999° is close to 0°). If the size of the set (max index - min index) is bigger than your current best set, note it as the current best. Then, increase the minimum index by one and continue increasing the maximum index until the angle difference test fail again. Continue to do so until the minimum index reaches the end of the list and do not forget to make the maximum index wrap to 0 to consider the cases close to 0° and 360°.
To make it easier to find the elements in the user provided list, you can add the original index to the transformed list, e.g., [[θ0,d0,0],[θ1,d1,1],...].
Some implementation details to consider to avoid making it accidentally O(n^2): Removing an element from an contiguous array is O(n), so instead of removing colinear elements every time you encounter one, note the index in a separate list and recreate the array in a second pass. If you instead use a linked list, the min/max index should be replaced by iterators to avoid the O(n) random access using an index to access an element.


text:
Q: Как получить перенаправяемую ссылку В твиттере ссылки имеют такой вид https://t.co/Lh2VMRvfqq.
Как в php получить ссылку, на которую ведет эта ссылка?

A: Если вы хотите это сделать с помощью функции file_get_contents то нужно указать параметры в контексте чтобы не было перенаправления, получить headers и найти нужный вам.
Сначала получим всем headers:
$context = stream_context_create(
    array(
        'http' => array(
            'follow_location' => false
        )
    )
);

file_get_contents('https://t.co/Sgw7gx9XUv', false, $context);

В итоге мы получим в зарезервированную переменную $http_response_header все headers.
Дальше проходимся по ним и находим тот что нам нужен:
$url = null;
foreach ($http_response_header as $header) {
    if (strpos($header, 'location: ') === false) {
        continue;
    }
    $url = substr($header, strpos($header, 'http'));
}
echo $url;

В итоге в переменной $url и будет оригинальный путь.


text:
Q: Whats wrong with this MYSQL query I have the following SQL query , it seems to run ok , but i am concerned as my site grows it may not perform as expected ,I would like some feeback as to how effective and efficient this query really is:
select * from articles where category_id=XX AND city_id=XXX GROUP BY user_id ORDER BY created_date DESC LIMIT 10;
Basically what i am trying to achieve - is to get the newest articles by created_date limited to 10 , articles must only be selected if the following criteria are met :

*

*City ID must equal the given value

*Category ID must equal the given value

*Only one article per user must be returned

*Articles must be sorted by date and only the top 10 latest articles must be returned

A: some potential improvements (for best query performance):

*

*make sure you have an index on all columns you querynote: check if you really need an index on all columns because this has a negative performance when the BD has to build the index. -> for more details take a look here: http://dev.mysql.com/doc/refman/5.1/en/optimization-indexes.html

*SELECT * would select all columns of the table. SELECT only the ones you really require...

A: You've got a GROUP BY clause which only contains one column, but you are pulling all the columns there are without aggregating them. Do you realise that the values returned for the columns not specified in GROUP BY and not aggregated are not guaranteed?
You are also referencing such a column in the ORDER BY clause. Since the values of that column aren't guaranteed, you have no guarantee what rows are going to be returned with subsequent invocations of this script even in the absence of changes to the underlying table.
So, I would at least change the ORDER BY clause to something like this:
ORDER BY MAX(created_date)

or this:
ORDER BY MIN(created_date)


text:
Q: Saving the result of print function as a figure I use Stanford coreNLP for generating dependency tree, but I cannot store the result as it uses print function to show the tree. For instance, the code and the dependency tree for "I ask a question in StackOverFlow" would be like this:
nlp = StanfordCoreNLP('.')
parser=nlp.parse("I ask a question in StackOverFlow")
tree=Tree.fromstring(parser.__str__())
tree.pretty_print()

Here I used Snipping Tool to take a screenshot of the generated tree manually, but in my code I will generate more than thousand trees, which is impossible to take screenshots from all of them. Any kind of help would be appreciated.

A: On a UNIX-based system you can do:
parse.py
nlp = StanfordCoreNLP('.')
for i in range(len(sentences)):
    sentence = sentences[i]
    parser=nlp.parse(sentence)
    tree=Tree.fromstring(parser.__str__())
    print(i, sentence)
    print('parse tree:')
    tree.pretty_print()
    print()

and do sth like python parse.py > parse_trees and your output file parse_trees will be structured as:
[index] [sentence]
parse tree:
[parse tree]

[index] [sentence]
parse tree:
[parse tree]

...


text:
Q: Fast algorithm to calculate Pi in parallel I am starting to learn CUDA and I think calculating long digits of pi would be a nice, introductory project.
I have already implemented the simple Monte Carlo method which is easily parallelize-able. I simply have each thread randomly generate points on the unit square, figure out how many lie within the unit circle, and tally up the results using a reduction operation.
But that is certainly not the fastest algorithm for calculating the constant. Before, when I did this exercise on a single threaded CPU, I used Machin-like formulae to do the calculation for far faster convergence. For those interested, this involves expressing pi as the sum of arctangents and using Taylor series to evaluate the expression.
An example of such a formula:

Unfortunately, I found that parallelizing this technique to thousands of GPU threads is not easy. The problem is that the majority of the operations are simply doing high precision math as opposed to doing floating point operations on long vectors of data.
So I'm wondering, what is the most efficient way to calculate arbitrarily long digits of pi on a GPU?

A: You should use the Bailey–Borwein–Plouffe formula
Why? First of all, you need an algorithm that can be broken down. So, the first thing that came to my mind is having a representation of pi as an infinite sum. Then, each processor just computes one term, and you sum them all in the end.
Then, it is preferable that each processor manipulates small-precision values, as opposed to very high precision ones. For example, if you want one billion decimals, and you use some of the expressions used here, like the Chudnovsky algorithm, each of your processor will need to manipulate a billion long number. That's simply not the appropriate method for a GPU.
So, all in all, the BBP formula will allow you to compute the digits of pi separately (the algorithm is very cool), and with "low precision" processors! Read the "BBP digit-extraction algorithm for π"

Advantages of the BBP algorithm for computing π
  This algorithm computes π without requiring custom data types having thousands or even millions of digits. The method calculates the nth digit without calculating the first n − 1 digits, and can use small, efficient data types.
  The algorithm is the fastest way to compute the nth digit (or a few digits in a neighborhood of the nth), but π-computing algorithms using large data types remain faster when the goal is to compute all the digits from 1 to n.


text:
Q: Column Total at the end of SQL Pivot query I have generated the following SQL Server 2008 pivot, and it gives me desire result.
I want to add total column at end of pivot, where I'm finding it difficult.
Please find the SQL I'm using for pivot
Select * from (
     Select Case when (podocstatus = 'CL') then 'Closed PO'
         when (podocstatus = 'OP') then 'Open PO'
         when (podocstatus = 'SC') then 'Short Closed PO'
    end as POStatus,
    YEAR(podate) as [Year], YEAR(podate) as [poyear] , LEFT (datename(Month,podate),3) as [pomonth]
    From PO_order_hdr
    Where podocstatus IN ('SC','CL','OP')
    ) as POnumber
PIVOT
(
    Count(poyear)
    FOR [pomonth]  IN (Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec)

)as PVT

Please help.

A: The easiest solution would be to simply do something like this:
Select *,
    Jan + Feb + Mar + Apr + May + Jun + Jul + Aug + Sep + Oct + Nov + Dec AS [Total]
from
    ...

An alternative solution for the general case, would be to use a subselect. Move your inner query into a CTE, to make things a bit easier to work with:
WITH POnumber (POStatus, [Year], [poyear], [pomonth]) AS
(
    Select sase when (podocstatus = 'CL') then 'Closed PO'
         when (podocstatus = 'OP') then 'Open PO'
         when (podocstatus = 'SC') then 'Short Closed PO'
    end as POStatus,
    YEAR(podate) as [Year], YEAR(podate) as [poyear] , LEFT (datename(Month,podate),3) as [pomonth]
    From PO_order_hdr
    Where podocstatus IN ('SC','CL','OP')
)
select *,
    -- Subselect that counts the total for the given status and year:
    (select count([Year]) from POnumber T
     where T.POStatus = PVT.POStatus and T.poyear = PVT.poyear) as [Total]
from POnumber
PIVOT
(
    Count(poyear)
    FOR [pomonth]  IN (Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec)
)as PVT


text:
Q: Interleave 2 Dataframes on certain columns I have 2 dataframes
df1:

StartLocation,StartDevice,StartPort,EndLocation,EndDevice,EndPort,LinkType,Speed
DD1,Switch1,P1,AD1,Switch2,P2,MTP,1000
DD2,Switch2,P3,AD2,Switch3,P2,MTP,1000
DD3,Switch3,P5,AD3,Switch4,P6,MTP,1000

df2:

StartLocation,StartDevice,StartPort,EndLocation,EndDevice,EndPort
AB11,RU15,P1,AJ11,RU25,P2
AB12,RU18,P2,AB11,RU35,P2
AB13,RU19,P3,AB11,RU40,P4

I want to interleave the two dataframes and I've tried a few options but can't seem to get it to work. I'm close to the functionality with the below code but it doesn't join on the appropriate columns
import pandas as pd
from toolz import interleave

df3 = pd.DataFrame(interleave([df1.values, df2.values]), columns=df1)

Expected Output would look like
StartLocation,StartDevice,StartPort,EndLocation,EndDevice,EndPort,LinkType,Speed
DD1,Switch1,P1,AD1,Switch2,P2,MTP,1000
AB11,RU15,P1,AJ11,RU25,P2,nan,nan
DD2,Switch2,P3,AD2,Switch3,P2,MTP,1000
AB12,RU18,P2,AB11,RU35,P2,nan,nan
DD3,Switch3,P5,AD3,Switch4,P6,MTP,1000
AB13,RU19,P3,AB11,RU40,P4,nan,nan

I think it should be pretty simple but I can't find the appropriate syntax. Can anyone give any ideas?
Thanks in advance for the help!

A: If columns names are same, only difference is some new columns names in one of DataFrame is possible use:
df3 = pd.DataFrame(interleave([df1.values, df2.values]), columns=df1.columns)
print (df3)
  StartLocation StartDevice StartPort EndLocation EndDevice EndPort LinkType  \
0           DD1     Switch1        P1         AD1   Switch2      P2      MTP
1          AB11        RU15        P1        AJ11      RU25      P2     None
2           DD2     Switch2        P3         AD2   Switch3      P2      MTP
3          AB12        RU18        P2        AB11      RU35      P2     None
4           DD3     Switch3        P5         AD3   Switch4      P6      MTP
5          AB13        RU19        P3        AB11      RU40      P4     None

    Speed
0  1000.0
1     NaN
2  1000.0
3     NaN
4  1000.0
5     NaN

More general solution working for any columns names is use DataFrame.align before for prevent correct align columns for each DataFrame:
print (df1)
  EndDevice EndLocation EndPort LinkType  Speed StartDevice StartLocation  \
0   Switch2         AD1      P2      MTP   1000     Switch1           DD1
1   Switch3         AD2      P2      MTP   1000     Switch2           DD2
2   Switch4         AD3      P6      MTP   1000     Switch3           DD3

  StartPort
0        P1
1        P3
2        P5

print (df2)
  EndDevice EndLocation EndPort  LinkType  Speed StartDevice StartLocation  \
0      RU25        AJ11      P2       NaN    NaN        RU15          AB11
1      RU35        AB11      P2       NaN    NaN        RU18          AB12
2      RU40        AB11      P4       NaN    NaN        RU19          AB13

  StartPort
0        P1
1        P2
2        P3

df3 = pd.DataFrame(interleave([df1.values, df2.values]), columns=df1.columns)
print (df3)
  EndDevice EndLocation EndPort LinkType   Speed StartDevice StartLocation  \
0   Switch2         AD1      P2      MTP  1000.0     Switch1           DD1
1      RU25        AJ11      P2      NaN     NaN        RU15          AB11
2   Switch3         AD2      P2      MTP  1000.0     Switch2           DD2
3      RU35        AB11      P2      NaN     NaN        RU18          AB12
4   Switch4         AD3      P6      MTP  1000.0     Switch3           DD3
5      RU40        AB11      P4      NaN     NaN        RU19          AB13

  StartPort
0        P1
1        P1
2        P3
3        P2
4        P5
5        P3

Another idea with Index.union and DataFrame.reindex:
cols = df1.columns.union(df2.columns, sort=False)

df1 = df1.reindex(cols, axis=1)
df2 = df2.reindex(cols, axis=1)
print (df1)
  StartLocation StartDevice StartPort EndLocation EndDevice EndPort LinkType  \
0           DD1     Switch1        P1         AD1   Switch2      P2      MTP
1           DD2     Switch2        P3         AD2   Switch3      P2      MTP
2           DD3     Switch3        P5         AD3   Switch4      P6      MTP

   Speed
0   1000
1   1000
2   1000

print (df2)
  StartLocation StartDevice StartPort EndLocation EndDevice EndPort  LinkType  \
0          AB11        RU15        P1        AJ11      RU25      P2       NaN
1          AB12        RU18        P2        AB11      RU35      P2       NaN
2          AB13        RU19        P3        AB11      RU40      P4       NaN

   Speed
0    NaN
1    NaN
2    NaN

df3 = pd.DataFrame(interleave([df1.values, df2.values]), columns=cols)
print (df3)
  StartLocation StartDevice StartPort EndLocation EndDevice EndPort LinkType  \
0           DD1     Switch1        P1         AD1   Switch2      P2      MTP
1          AB11        RU15        P1        AJ11      RU25      P2      NaN
2           DD2     Switch2        P3         AD2   Switch3      P2      MTP
3          AB12        RU18        P2        AB11      RU35      P2      NaN
4           DD3     Switch3        P5         AD3   Switch4      P6      MTP
5          AB13        RU19        P3        AB11      RU40      P4      NaN

    Speed
0  1000.0
1     NaN
2  1000.0
3     NaN
4  1000.0
5     NaN


text:
Q: How to implement different reward for rewaredvideo ads I have fortune wheel in my game which can be played on watching video ad. this wheel can give 4 type of rewards.(4 diamond, 8 diamonds, jackpot, bonus level) now i don't know how to get this done. along this i also have double coin button in my each level which also triggered on watching ad.
here is my admanager script which is linked to double coin button from which i call the ShowRewardedVideo()
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using admob;
using UnityEngine.SceneManagement;

public class AdManager : MonoBehaviour
{
    private static AdManager _instance;

    public static AdManager Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = GameObject.FindObjectOfType<AdManager>();
            }

            return _instance;
        }
    }
    public Admob ad;
    string appID = "";
    string bannerID = "";
    string interstitialID = "";
    string videoID = "";
    string nativeBannerID = "";

    void Awake()
    {
        DontDestroyOnLoad(gameObject);
        //Replace with your IDs here. These are test ids for you to check if the ads are implemented properly or not
#if UNITY_IOS
                 appID="ca-app-pub-6533984286287209~3970651947";
                 bannerID="ca-app-pub-3940256099942544/6300978111";
                 interstitialID="ca-app-pub-3940256099942544/1033173712";
                 videoID="ca-app-pub-3940256099942544/5224354917";
                 nativeBannerID = "ca-app-pub-3940256099942544/2247696110";
#elif UNITY_ANDROID
        appID = "ca-app-pub-1147416347412616~8130084612";
        bannerID = "ca-app-pub-3940256099942544/6300978111";
        interstitialID = "ca-app-pub-3940256099942544/1033173712";
        videoID = "ca-app-pub-3940256099942544/5224354917";
        nativeBannerID = "ca-app-pub-3940256099942544/2247696110";
#endif
        AdProperties adProperties = new AdProperties();
        adProperties.isTesting=true;
        adProperties.isAppMuted=false;
        adProperties.isUnderAgeOfConsent=false;
        adProperties.appVolume=100;
        ad = Admob.Instance();
        ad.bannerEventHandler += onBannerEvent;
        ad.interstitialEventHandler += onInterstitialEvent;
        ad.rewardedVideoEventHandler += onRewardedVideoEvent;
       // ad.rewardedVideoEventHandler -= onRewardedVideoEvent;

        ad.initSDK(appID,adProperties);//reqired,adProperties can been null
        ad.loadInterstitial(interstitialID);

        InvokeRepeating("CacheVideoAd", 1, 5);

    }

    void CacheVideoAd()
    {
        if (!ad.isRewardedVideoReady())
        {
            ad.loadRewardedVideo(videoID);
            ad.rewardedVideoEventHandler -= onRewardedVideoEvent;

        }
    }

    IEnumerator LoadGameScene()
    {
        yield return new WaitForSeconds(2);
        SceneManager.LoadSceneAsync("MainMenu");
    }

    public bool IsAdReady()
    {
#if UNITY_EDITOR
        return false;
#endif
        return ad.isRewardedVideoReady();
        ad.rewardedVideoEventHandler -= onRewardedVideoEvent;

    }

    public void ShowInterstitial()
    {
        //To give a call back to this use the code below
        //AdManager.Instance.ShowInterstitial();
#if UNITY_ANDROID
        print("touch inst button -------------");
        try
        {
            if (ad.isInterstitialReady())
            {
                ad.showInterstitial();
            }
            else
            {
                ad.loadInterstitial(interstitialID);
            }
        }
        catch (System.Exception e)
        {
            print(e);
        }
#endif
    }
    public void ShowBanner()
    {
        //To give a call back to this use the code below
        //AdManager.Instance.ShowBanner();
        Admob.Instance().showBannerRelative(bannerID, AdSize.SMART_BANNER, AdPosition.BOTTOM_CENTER);
    }

    public void DestroyBanner()
    {
        //To give a call back to this use the code below
        //AdManager.Instance.DestroyBanner();
        Admob.Instance().removeBanner();
    }

    public void ShowRewardedVideo()
    {
        //To give a call back to this use the code below
        //AdManager.Instance.ShowRewardedVideo();
        Debug.Log("touch video button -------------");
        if (ad.isRewardedVideoReady())
        {
            ad.showRewardedVideo();

        }
        else
        {
            ad.loadRewardedVideo(videoID);
            ad.rewardedVideoEventHandler -= onRewardedVideoEvent;

        }
    }

    void onInterstitialEvent(string eventName, string msg)
    {
        Debug.Log("handler onAdmobEvent---" + eventName + "   " + msg);
        if (eventName == AdmobEvent.onAdLoaded)
        {
            // Admob.Instance().showInterstitial();
        }
    }
    void onBannerEvent(string eventName, string msg)
    {
        Debug.Log("handler onAdmobBannerEvent---" + eventName + "   " + msg);
    }
    void onRewardedVideoEvent(string eventName, string msg)
    {
        Debug.Log("handler onRewardedVideoEvent---" + eventName + "  rewarded: " + msg);
        if(eventName == AdmobEvent.onRewarded)
        {
            //Add reward condition here
            SaveManager.Instance.DiamondReward();
            ad.rewardedVideoEventHandler -= onRewardedVideoEvent;
            Debug.Log("diamond reward which is (4 Diamonds)");
        }
    }
}

And this is SpinManager script attached to spinner wheel
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityStandardAssets.CrossPlatformInput;

public class SpiningManager : MonoBehaviour {

    int randVal;
    private float timeInterval;
    private bool isCoroutine;
    private int finalAngle;

    public Text winText;
    public int section;
    float totalAngle;
    public string[] PrizeName;
    // Use this for initialization
    private MenuScene g;
    private void Start () {

        isCoroutine = true;
        totalAngle = 360 / section;

        g = GameObject.FindObjectOfType<MenuScene>();

    }

    // Update is called once per frame
    private void Update () {
        float xRotate = CrossPlatformInputManager.GetAxis("Horizontal");
        if (xRotate == 1 && isCoroutine) {
            StartCoroutine (Spin ());
        }
    }

    private IEnumerator Spin(){

        isCoroutine = false;
        randVal = Random.Range (80, 150);

        timeInterval = Time.deltaTime*2;

        for (int i = 0; i < randVal; i++) {

            transform.Rotate (0, 0, (totalAngle/2)); //Start Rotate

            //To slow Down Wheel
            if (i > Mathf.RoundToInt (randVal * .2f))//0.2f
                timeInterval = 0.5f*Time.deltaTime;
            if (i > Mathf.RoundToInt (randVal * .5f))//0.2f
                timeInterval = 1f*Time.deltaTime;
            if (i > Mathf.RoundToInt (randVal * .7f))//0.2f
                timeInterval = 1.5f*Time.deltaTime;
            if (i > Mathf.RoundToInt (randVal * .8f))//0.2f
                timeInterval = 2f*Time.deltaTime;
            if (i > Mathf.RoundToInt (randVal * .9f))
                timeInterval = 2.5f*Time.deltaTime;

            yield return new WaitForSeconds (timeInterval);

        }

        if (Mathf.RoundToInt (transform.eulerAngles.z) % totalAngle != 0) //when the indicator stop between 2 numbers,it will add aditional step
            transform.Rotate (0, 0, totalAngle/2);

        finalAngle = Mathf.RoundToInt (transform.eulerAngles.z);//round off euler angle of wheel value

        print (finalAngle);

        //Prize check
        for (int i = 0; i < section; i++) {

            if (finalAngle == i * totalAngle)
            {
                winText.text = PrizeName[i];
                if(winText.text == "BONUS LEVEL")
                {
                    Debug.Log("Play Bonus Level");
                }
                else if(winText.text == "DIAMONDS X8")
                {
                    Debug.Log("Give DIAMONDS X8");

                }
                else if (winText.text == "DIAMONDS X4")
                {
                    Debug.Log("Give DIAMONDS X4");

                }
                else if (winText.text == "JACKPOT")
                {
                    Debug.Log("Give JACKPOT");
                }
            }
        }
        isCoroutine = true;
    }
}

A: SpiningManager.cs:
public enum RewardType
{PLAYBONUSLEVEL=0,
DIAMONDSX8,
DIAMONDSX4=2,
JACKPOT=3};
public static RewardType currentRewardType;

    for (int i = 0; i < section; i++)
    {

        if (finalAngle == i * totalAngle)
        {
            winText.text = PrizeName[i];
            if(winText.text == "BONUS LEVEL")
            {
                currentRewardType= RewardType.PLAYBONUSLEVEL;
                Debug.Log("Play Bonus Level");
            }
            else if(winText.text == "DIAMONDS X8")
            {
            currentRewardType= RewardType.DIAMONDSX8;
                Debug.Log("Give DIAMONDS X8");

            }
            else if (winText.text == "DIAMONDS X4")
            {
            currentRewardType= RewardType.DIAMONDSX4;
                Debug.Log("Give DIAMONDS X4");

            }
            else if (winText.text == "JACKPOT")
            {
            currentRewardType= RewardType.JACKPOT;
                Debug.Log("Give JACKPOT");
            }
        }
    }

A: AdManager.cs:
void onRewardedVideoEvent(string eventName, string msg)
    {
        Debug.Log("handler onRewardedVideoEvent---" + eventName + "  rewarded: " + msg);
        if(eventName == AdmobEvent.onRewarded)
        {

            Switch(SpiningManager.currentRewardType)
            {
            case SpiningManager.RewardType.PLAYBONUSLEVEL:
            //Reward for Bonus
            break;

            case SpiningManager.RewardType.DIAMONDSX8:
            //Reward for DIAMONDSX8
            break;

            case SpiningManager.RewardType.DIAMONDSX4:
            //Reward for DIAMONDSX4
             SaveManager.Instance.DiamondReward();
            break;

            case SpiningManager.RewardType.JACKPOT:
            //Reward for JACKPOT
            break;

            }

            //Add reward condition here

            ad.rewardedVideoEventHandler -= onRewardedVideoEvent;

        }
    }

A: I solved this by setting playerprefs key for each reward and checking if the playerprefs key is available to get reward in onrewarded() function and after claiming i delete the key.


text:
Q: nodejs variable inside express response.write Assume I have a dynamic way to set the value of toggle to true or false without restarting the app.
Is there a better way to achieve what I'm trying to do here? Namely print different results based on the value of toggle?
const express = require('express');
const app = express();
const port = 8080;

var toggle = true;

app.get('/', function (req, res) {

  res.write(`<!DOCTYPE html>
        <html>
        <head>
        <title>Demo Page</title>
        </head>
        <body>`);

  if (toggle) {
    res.write(`<p>Hello World. Toggle Value: true</p>`);
  }
  else {
    res.write(`<p>Hello World. Toggle Value: false</p>`);
  }

  res.write(`</body></html>`);
  res.end();
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

A: You can concat strings to write single line return
res.write(`<p>Hello World. Toggle Value: ` + true + `</p>`);

Or using ES6 features
res.write(`<p>Hello World. Toggle Value: ${true}</p>`);

I would recommend you using some view engine such as mustache or pug, where you would pass 'toggle' variable and handle rendering inside template.


text:
Q: Fixing a guest screen resolution in VirtualBox I was required to develop a Windows app UI for a fixed resolution - it doesn't matter if it makes sense or not, the customer requires it. I'm using a Windows Server 2003 VirtualBox VM as the development environment; my host machine has much higher resolution.
Is there any way to select and fix the OS resolution and stop VirtualBox changing it by any kind of scaling? I can't see the requested resolution when I open Display Properties on the guest OS.

A: For my setup, neither CustomVideoMode1 nor setvideomodehint nor MaxGuestResolution worked. So, I looked up
vboxmanage getextradata $YOUR_VM_NAME enumerate
and changed
Key: GUI/LastGuestSizeHint, Value: 800,600
to
Key: GUI/LastGuestSizeHint, Value: 1920,1080
with
vboxmanage setextradata $YOUR_VM_NAME GUI/LastGuestSizeHint 1920,1080

A: While the VM is running, define your custom resolution using this command:
vboxmanage setextradata "[VM NAME]" CustomVideoMode1 1600x900x32
While the VM is running, execute the following command to switch to your new resolution:
vboxmanage controlvm "[VM NAME]" setvideomodehint 1600 900 32
It should switch to the new resolution immediately.
For this to work you must have VirtualBox Guest Extensions installed in the VM.

A: Try installing Guest Additions. It provides lots more features to the guest OS. From there, you can leverage the resolution you want and lock the screen in that position.

A: Even with Guest Additions installed, my remote Windows is not able to give me my
wished 1920x1080 so I used this solution
vboxmanage startvm "mymachine";vboxmanage controlvm "mymachine" setvideomodehint 1920 1080 32

A: I was having the same problem as described above nothing was working even the manual setting of screen resolution, I solved my problem with checking some things:

*

*In VirtualBox Manager GUI checked my OS version: I have chosen Windows 8.1 64 bit, but guest OS was 32 bit which, was the main problem

*Solution: new machine with win 8.1 32 bit OS and linked to an old virtual hard drive

*Setting machine custom resolution with VBoxManage command line
VBoxManage.exe setextradata "[Virtual Machine Name]" CustomVideoMode1 1366x768x32

A: So I tried this, and might work for you. Under the Machine menu, there is an option to auto-resize the guest OS's resolution to fit the monitor you are using. I got the resolution you did by enabling this option, manually resizing the window to get the resolution I wanted, then DISABLING auto-resize. Then, it's "stuck" there and I can resize the window, move it around, resolution doesn't change. Only problem was the taskbar. While you are doing the resize, might help to minimize it to get the exact resolution

A: From with Vagrant file - see the last line with LastGuestSizeHint, I had to escape the slash after GUI in order for this to work:
Vagrant.configure("2") do |config|
    config.vm.box = "codeup/Ubuntu-20.04-GUI"
    config.vm.provider "virtualbox" do |vb|
        vb.gui = true
        vb.name = "Eclipse"
        vb.memory = 2048
        vb.cpus = 2
        vb.customize ["modifyvm", :id, "--vram", 256]
        vb.customize ["modifyvm", :id, "--clipboard", "bidirectional"]
        vb.customize ["modifyvm", :id, "--draganddrop", "bidirectional"]
        vb.customize ["setextradata", :id, "GUI\/LastGuestSizeHint", "1920,1080"]
    end


text:
Q: Backing to ListActivity causing undesirable behavior I've been messing with some layouts for my ListActivity's ListView and found a problem:
When I click a list item it starts a new Activity.  Unfortunately, when I click the back button to go back to my ListActivity, the scrollbar of the ListView is all the way at the top.
It used to be that, when I clicked the back button, the user would be scrolled to the same place in the list as they were before they selected the list item to launch a new screen.
I'm pretty sure I've removed all of the code I've changed, but the problem is still occurring.  Any ideas?

A: If you're hitting on create in your code your list most likely is recreated and therefore position is not saved. Try to rotate device while in the ListActivity ( scroll to the middle and rotate ) and see if you see the problem . I'd cache the postion of the list and scroll List to it.
Example of such things :
http://developer.android.com/resources/tutorials/notepad/notepad-ex3.html

A: I figured out why this is happening
    @Override public void onStop() {
    super.onStop();
    if (mCursor != null) {
        mCursor.close();
        mCursor = null;
    }
    mAdapter.changeCursor(null);
}

I was told this is something I'm "supposed" to do.  I think I can understand why.  However, it causes the undesirable behavior I'm seeing here.


text:
Q: Unobstructive client validation error I am using asp.net mvc 3 and I keep getting the following error.

Validation type names in unobtrusive
  client validation rules must be
  unique. The following validation type
  was seen more than once: number

I have no clue as I have this
@Html.TextBoxFor(x => x.Mark)

// my viewmodel
   [Required(ErrorMessage = "Message")]
        [Number(ErrorMessage = "Message")]
        public decimal Mark { get; set; }

If I change it from a decimal to string it will not complain. What is going on?
Edit
I think it is because of this the          [Number(ErrorMessage = "Message")] annotation. I am using this library  Data annotation extensions
It seems not not like that I am using decimals. Anyone know why?

A: If you are using type decimal, you do not need to use the [Numeric] attribute because MVC already sees you are using a numeric type and injects that in for you (which is causing the error).  When you change to a string, the [Numeric] is then needed to tell the validation how you want that string to work.
In the next version of DataAnnotationsExtensions, I'll change the [Numeric] attribute so it won't collide with the MVC version in this case.  But for now, removing the [Numeric] attribute will be just fine because [Numeric] on a numeric type is redundant anyway.

A: You probably have multiple model validators which are adding the same client rule twice, are you using a custom validatiOn provider?

A: Required will become duplicate since Mark is not nullable. I would change it to be decimal?


text:
Q: Bitmap font is not working For some reason my bitmap font won't draw when inside this if statement. If I put the font.draw on the outside of the if(correct) it will draw. I confirmed that correct was set to a value of either true or false.
if(state == "showingAnswer") {
    if(correct) {
        font.draw(batch, "correct", 340, 460);
    } else {
        font.draw(batch, "incorrect", card.bounds.x + 10, card.bounds.y - 260);
    }
}

A: It was drawing off screen.  I don't know how it drew the other stuff just fine, but that was the problem.


text:
Q: Which t-test should I go for? Newbie here. I'm wondering which t-test I should go for: a one-sample t-test or a paired-sample t-test? Happy to receive other suggestions.
A bit about my data:
I have data from 18 participants on how much time they planned to work on a Monday, and how much time they actually ended up working (from two different time-use diaries).
I checked and the data is normally distributed.
What I want to show with the data is that there is a difference between the amount of time people planned to work, and the amount of work they were eventually able to do (except for Diary Participant 11 who worked for exactly the amount of time they had planned).

My question is: which test would you say is more appropriate for this data, if any?

A: It can be a paired t test using columns 'Planned' and 'Actual', or (equivalently) a one-sample t test using column 'Difference'.
I wrote your differences into the vector d below. (Maybe check my
typing.)
d = c(140, -660, -60, -110,  195, 455, -140, -110,
      -210, -30, 0, 40,  -60, 230, 65, -55,
      -90, -235, - 35)

The first question is whether these differences are normally distributed.
A normal probability plot is "mainly" linear with a few exceptions, especially the lowest (-660) and highest (455) values .
qqnorm(d);  qqline(d, col="green2")

These extreme values show as 'outliers' in a boxplot of the differences.
boxplot(d, horizontal=T, pch="|")

Nevertheless, a Shapiro-Wilk test for normality does not (quite) reject the
null hypothesis (normal data) at the 5% level.
shapiro.test(d)

         Shapiro-Wilk normality test

data:  d
W = 0.91394, p-value = 0.08748

Various statisticians have different favorite ways of judging normality and tolerance for departure from normality in a one-sample t test.
A one-sample t test on the differences, does not find the average difference
$\bar D = -35.26$ in the sample mean to be significantly different from $0$
at the 5% level of significance. [If you had done a paired t test in R, the output would have looked much the same; the first step of the paired procedure would have been to find the differences used in the output below.]
t.test(d)

        One Sample t-test

data:  d
t = -0.68782, df = 18, p-value = 0.5003
 alternative hypothesis: true mean is not equal to 0
95 percent confidence interval:
  -142.97372   72.44741
sample estimates:
mean of x
-35.26316

If someone disbelieves the accuracy of the t test (on account of non-normality), they might say a nonparametric paired
Wilcoxon test (equivalently, one-sample Wilcoxon signed-rank test)
would be better. An objection to using this Wilcoxon test is that the
data are not symmetrical. (Look at the boxplot.) However, the Wilcoxon SR test also fails to reject the null hypothesis that subjects deviated
significantly from plan. (P-value above $0.05 = 5\%.$%
wilcox.test(d)

        Wilcoxon signed rank test with continuity correction

data:  d
V = 66.5, p-value = 0.4203
alternative hypothesis: true location is not equal to 0

As often happens in practice, neither test is perfect. But arguments
can be made for using either. And in the end, neither test finds a
significant difference from planned work time.
Pick one of the two tests
an use it. Neither test shows results anywhere near the borderline for rejection.
Some of your workers aren't very good at sticking to plan, but they do
not show a strong trend in either direction--above or below plan.
Note: For completeness: one possible additional test comes to mind. It's called a sign test.
Out of $n = 19$ observations, you have $n^\prime = 18$ non-zero results. Of these non-zero tests 6 are positive and 12 are negative. The probability of 6 or fewer positives or of 12 or more negatives
out of 18 is the P-value $0.2379$ of the sign test--nowhere near significant at the 5% level. There are also objections to the sign test because data are not symmetrical and because looking just at signs 'throws away' too much information.)
sum(dbinom(c(0:6,12:18), 18, .5))
[1] 0.2378845

By way of confirmation, Minitab statistical software shows the following results for
a sign test on your data:
Sign Test for Median: d

 Sign test of median =  0.00000 versus ≠ 0.00000

    N  Below  Equal  Above       P  Median
d  19     12      1      6  0.2379  -60.00


text:
Q: Difference between initWithData and initWithBytes of NSString I'm confused with the use of the following methods of NSString

*

*initWithData:encoding:

Returns an NSString object initialized by converting given data into
  Unicode characters using a given encoding.

*initWithBytes:length:encoding:

Returns an initialized NSString object containing a given number of bytes from a given  buffer of bytes interpreted in a given encoding.

And their usage is like:
NSMutableData *someData = //some data;
NSString *someString = nil;

*

*someString= [[NSString alloc] initWithData:someData encoding:NSUTF8StringEncoding];

*someString=[[NSString alloc] initWithBytes:[someData mutableBytes] length:[someData length] encoding:NSUTF8StringEncoding];
NSData class is a wrapper for byte buffers, then what is the difference between these similiar methods. Please help me to understand the difference.

A: Well, you may have some raw bytes not already wrapped in an NSData object. In that case you can use initWithBytes:length:encoding: without having to wrap it first.


text:
Q: How to write a python loop I have 2 tables in the database:
class User(db.Model):
  id = db.Column(db.String(80), primary_key=True)
  username = db.Column(db.String(80))
  ex_1 = db.Column(db.Integer)
  ex_2 = db.Column(db.Integer)
  .....
  ex_10 = db.Column(db.Integer)

class Ex(db.Model): #задания
  id = db.Column(db.String(80), primary_key=True)
  title = db.Column(db.String(80))
  text = db.Column(db.String(140))

If the user completed the task, then in the field ex_1, for example, the value is 1, if not completed, then 0.
How to check the tasks of the user from the beginning and send him the first failed task? Tasks also 10 and id from 1 to 10 How to implement such a cycle? Tell me please!

A: Use signal
from sqlalchemy import event

def after_update_listener(mapper, connection, target):
    # 'target' is the update object
    if not target.ex_1:
        send_fail_task(target.id)
    # if task also 10 or 1 to 10, Add a conditional statement, ps:
    if target.ex_1.id == 10:
        do_something()

event.listen(User, 'after_update', after_update_listener)


text:
Q: Рациональные операции при сравнении файлов Задача — получить 2 одинаковых файла в 2 местах (папках к примеру)
Решение 1 «в лоб» — удалить первый, скопировать на его место второй.
Решение 2 — «быстро» сравнить файлы и заменить, если они разные.
Вопрос 1 — какими методами можно «быстро» сравнить файлы?
На данный момент сравниваю размер. Однако один размер, не достаточное доказательство, что файлы равны. Как и разный размер, не достаточное доказательство, что файлы разные. (при необычных случаях можно наткнутся на неправильную оценку)
Появляется необходимость сравнить файлы как то дополнительно.
Предлагали сравнить по хешу. Но, как я понимаю, для такого сравнения нужно прочесть оба файла полностью, затем преобразовать информацию в хеш и уже после сравнить их. Такие манипуляции вряд ли заметно быстрее, чем удаление и копирование файла.
Предлагали просто сравнивать файлы по байтово. Тоже не самый рациональный способ, как мне кажется.
Как реализовать базу хешей заранее, которая будет обновляться на постоянной основе не знаю, поскольку файлы могут изменится в любом из 2 мест, а держать активной софтину может не быть возможности.
Вопрос 2 - Какими методами пользуются программы для синхронизации?


text:
Q: On the HTML5 Video Player, how can I tell the type of the source being played? I'm providing DASH, HLS, and MP4 (as a fallback) as sources to an HTML5 Video player element. I would like to log the source types that my users end up using, but I don't know where to get that information from.
What's the best way for me to get this source type? I expected to be able to at least parse the video element's currentSrc property to figure this out, but there's nothing in the value that indicates whether it's dash/hls/mp4.


text:
Q: Inbuilt feature of puppet Enterprose Is there any built in feature of Puppet Enterprise that we can use to have a push based mechanism, Apart from Mcollective and Bolt.

A: Assuming by 'push based' you mean triggering Puppet Agent runs, you can trigger a run in the PE console directly, or (as you mentioned) use Bolt in the PE console to run Puppet as part of a 'plan' or 'task'