text:
Q: how to stop stopwatch during debugging C# and vs2012 So i have some code that depends upon stopwatch for some calculations.
However once stopwatch starts it doesn't stop even during debugging and it is creating problems for me when i try to debug the code.
Is there any way that i can stop stopwatch from running during debugging. I am using VS2012.

A: No you can't. Because a stopwatch isn't actually running like a thread that you could pause and resume. It's simply taking the time at start and the time at stop and calculating the difference.
Maybe if you post your code or concept, we could find a way to solve your problem without a stopwatch?

A: It's probably not what you were hoping for, but you can temporarily do this:
stopwatch.Stop();
Debugger.Break();
stopwatch.Start();

you could wrap it in #if DEBUG block if you don't want to worry about accidentally leaving it in.

A: You could use the following, if you run using the Debug profile in VS2012:
#if DEBUG
sw.Stop();
#endif

A: use System.Diagnostics.Debugger.Break(); for this.

Debugger.Break: If no debugger is attached, users are asked if they
  want to attach a debugger. If yes, the debugger is started. If a
  debugger is attached, the debugger is signaled with a user breakpoint
  event, and the debugger suspends execution of the process just as if a
  debugger breakpoint had been hit.

Hope Its Helpful.


text:
Q: How to fix Android Studio terminal to be same as linux terminal? I have recently installed Android Studio on my linux machine. It's terminal shell was set to \bin\sh, which starts something like this:
sh@5.1~

So, I changed the shell to \bin\bash. And, now, when I launch the terminal, it looks similar to how linux's terminal looks:
username@computername:~$

So, I thought everything is set now. But, when I tried to use gpg, I noticed some issues:
echo "test" | gpg --clearsign

Linux terminal succeeds. But, Android Studio terminal fails with:
gpg: signing failed: No pinentry
gpg: [stdin]: clear-sign failed: No pinentry

For which gpg & gpg --version commands:
Android Studio terminal says:
/app/bin/gpg
gpg (GnuPG) 2.2.27
libgcrypt 1.8.9

Linux terminal says:
/usr/bin/gpg
gpg (GnuPG) 2.2.19
libgcrypt 1.8.5

How can I fix this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to attach different indices to an html element with jinja? I am creating a simple html questionnaire document, as a base template I am using the following jinja code:
from jinja2 import Template

title = ['1 title', '2 title']
message = ['1 message', '2 message']

template = Template(
"""
{% macro create_block(title, message) %}

 {{title}}

question?

<input type="radio" value="val1" name="question1_{{ i }}">option A</input>
<input type="radio" value="val2" name="question1_{{ i }}">option B</input>

question 2?

<input type="radio" value="one" name="question1_{{ i }}">a</input>
<input type="radio" value="two" name="question1_{{ i }}">b</input>
<input type="radio" value="three" name="question1_{{ i }}">c</input>

{% endmacro %}

{% for title, message in list %}
{{ create_block(title, message) }}
{% endfor %}

""")

print_html(template.render(list=zip(title, message)))

The above template creates questions sets for the number of elements in title and message lists. For example, for two elements in title, the above code will generate two different questionnaire sets. However, to produce a valid html document I would like to vary the {{i}} parameter in name="question1_{{ i }}. For the above template, the expected output looks like this:

 1 title

 question?

<input name="question1_1" type="radio" value="val1"/>
option A
<input name="question1_1" type="radio" value="val2"/>
option B

 question 2?

<input name="question1_2" type="radio" value="one"/>
a
<input name="question1_2" type="radio" value="two"/>
b
<input name="question1_2" type="radio" value="three"/>
c

 2 title

 question?

<input name="question2_1" type="radio" value="val1"/>
option A
<input name="question2_1" type="radio" value="val2"/>
option B

 question 2?

<input name="question2_2" type="radio" value="one"/>
a
<input name="question2_2" type="radio" value="two"/>
b
<input name="question2_2" type="radio" value="three"/>
c

In Jinja, what is the correct way to get the above output with the indices of the checkboxes names varying?

A: You would pass the index as an argument just like you did for the others.
from jinja2 import Template

title = ['1 title', '2 title']
message = ['1 message', '2 message']
indices = list(range(len(title)))

template = Template(
"""
{% macro create_block(title, message, i) %}

 {{title}}

question?

<input type="radio" value="val1" name="question1_{{ i }}">option A</input>
<input type="radio" value="val2" name="question1_{{ i }}">option B</input>

question 2?

<input type="radio" value="one" name="question1_{{ i }}">a</input>
<input type="radio" value="two" name="question1_{{ i }}">b</input>
<input type="radio" value="three" name="question1_{{ i }}">c</input>

{% endmacro %}

{% for title, message, i in list %}
{{ create_block(title, message, i) }}
{% endfor %}

""")

print_html(template.render(list=zip(title, message, indices)))


text:
Q: Как поменять местами объекты в массиве? Есть заполненный массив объектов
MyObject[] array = new MyObject[100];
for (int i = 0; i < 100; i++){
    array[i] = new MyObject();
}

Программа должна в цикле (в зависимости от логики) часто менять местами объекты находящиеся в элементах массива(не создавая при этом новых объектов). Я создаю один объект MyObject, по-порядку копирую в него значения всех полей первого объекта(для временного хранения). После этого из второго объекта в первый копирую значения всех полей. А потом из временного объекта копирую значения полей во второй объект. Получается довольно длинный код. Может быть есть более короткий и быстрый способ? Подскажите.

A: Объекты - это ссылки. Поэтому достаточно сделать так
MyObject tmp = array[0];
array[0] = array[1];
array[1] = tmp;


text:
Q: ASP.NET: Does Response.Redirect() end the current session? I'm in the middle of trying to fix my session timeout code, and have run into an interesting problem. I've taken the recommendations here and here to assume I've hit a timeout when Session.IsNewSession is true and a session cookie already exists. According to multiple posts, these are signs that a timeout has occurred. All of these checks I have on my homepage before the user logs in (they're redirected to this page in timeout and logout situations).
So let's assume that's all correct. When the user clicks LogOut in the application, I run my necessary database code to end the session, then I run this:
//abandon session
Global.Session.Abandon();

//redirect
Response.Redirect(FormsAuthentication.LoginUrl, false);

What I noticed immediately in my homepage, when I'm performing the session timeout checks, was that Session.IsNewSession was true, eventually leading to the logic that thinks there's a session timeout. Obviously it wasn't; the user just clicked Log Out. By putting a breakpoint in Session_End in my Global file, I was able to see that Session_End is fired after I do the Response.Redirect() statement when the user logs off.
So I'm wondering if that's supposed to happen? Originally I thought that it had something to do with Session.Abandon(), but that doesn't seem to be causing Session_End to fire. Any ideas?
Thanks.

A: The Session_End event is fired only after the current request completes.  The redirect is the end of your request, so the event fires at that time.   A Redirect by itself does not end the current session.


text:
Q: Delete data from API with Axios and ReactJS I am fetching data from the jsonplaceholder API into my state. How can I remove the data with the deleteContact() method? My greatest struggle is how to get the deleteContact() method right.
Is this approach wrong?

class RemoveFromAPI extends Component {

    state = {
        users: []

    }

    componentDidMount() {
        axios.get(`https://jsonplaceholder.typicode.com/users`)
            .then(res => {
                const users = res.data;
                this.setState({ users });
            })
    }

    deleteContact () {
        axios.delete(`https://jsonplaceholder.typicode.com/users/${id}`);
        .then(res => {
            const users = res.data;
            this.setState({ users });
        })

    }

    render() {

        const {users} = this.state

        return (

                    { this.state.users.map(user =>
{user.name}
)}

                <button
                    onClick={deleteContact}
                   >
                    Remove
                </button>

        );
    }
}

RemoveFromAPI.propTypes = {};

export default RemoveFromAPI;

A: A few things to revise here - first, it seems you need to pass the user.id to the deleteContact() function, given that your axios request requires the user id as part of the request URL. This typically means moving the "Remove" button into the map() render callback so that each user id can be passed through the buttons click handler:
render() {

    const {users} = this.state

    return (

            {
              this.state.users.map(user => (

{user.name}
                  <button onClick={ () => this.deleteContact(user.id) } >Remove</button>

))
            }

);
}

Also, note the use of the "arrow function" passed on onClick:
() => this.deleteContact(user.id)

Arrow functions provide a convenient way to call a class methods that are bound to the current component instance. This is important to ensure methods like setState() work as expected from inside the class method being called.
Finally, the deleteContact() method itself needs some minor revisions. Ensure the id parameter is declared as a function argument and also remove the ; following your axios.delete() to avoid a syntax error, like so:
deleteContact (id) { // <-- declare id parameter
    axios.delete(`https://jsonplaceholder.typicode.com/users/${id}`) // <-- remove ;
    .then(res => {
        const users = res.data;
        this.setState({ users });
    })
}

Hope that helps!
Update
Another note; your code is expecting the API at https://jsonplaceholder.typicode.com/ to return list of items after a DELETE request according to the documentation this doesnt seem to be the API's behavior. One way to address this would be to update deleteContact() to first issue the DELETE request, followed by a GET request like so:
deleteContact (id) {

    // Issue DELETE request
    axios.delete(`https://jsonplaceholder.typicode.com/users/${id}`)
    .then(() => {

        // Issue GET request after item deleted to get updated list
        // that excludes user of id
        return axios.get(`https://jsonplaceholder.typicode.com/users`)
    })
    .then(res => {

        // Update users in state as per-usual
        const users = res.data;
        this.setState({ users });
    })
}

Note also, this placeholder API does not actually remove data from the server which will mean the delete operation will appear to have no effect.


text:
Q: Does intensity increase if we increase energy of photons? I've been told that the definition of intensity of any radiation is 'the energy crossing unit area in unit time.'
So, I understand that if we increase the number of photons passing through an area by keeping their energy constant, the intensity increases.
But, my doubt is let's say if we kept the number of photons passing through a fixed area constant and increased their energy (by increasing frequency), will the intensity increase?
I think it should increase according to the definition. But in books, it says it doesn't increase.
What's the correct explanation for this?

A: Intensity is the total amount of energy falling (or going through) per unit area per unit time i.e, $\frac{J}{m^2.s}$.
For monochromatic radiation,
$Total\space energy = Number\space of\space photons\space \times Energy\space  of\space  one\space \space photon$
and $E_{photon}=h\nu$
$Intensity = \frac{Number\space of\space photons\space \times Energy\space  of\space  one\space \space  photon}{At}$
$I=\frac{nh\nu}{At}$ $\tag{1}$
For constant area and time,
$I \propto n.\nu$
This is a very important result. You can increase the intensity of the radiation by either increasing the number of photons in it or increasing energy of each photon, or both.
As for option (C), if you increase energy of each photon but  decrease the number of photons emitted by the source per unit time by the same factor then the intensity will remain the same as before. For instance, if the number of photons emitted by the source per unit time is halved, doubling the intensity will give you the same intensity as before.
This is evident from equation (1). Therefore, option (C) is not necessarily correct but (A) and (B) are.

A: There are many ways of defining the intensity of light, but if you are just measuring the energy per unit time per unit area then yes increasing the frequency while keeping the number of photons constant will increase the intensity. If your book says otherwise you need to provide us with a link to the book so we can check it, or maybe post a photo of the relevant part of the book.

A: Perhaps it is not mentioned in books that with increase in frequency of radiation intensity does not increase. In fact increasing frequency of radiation means we have taken a source of radiation of higher power and with increase in power of the source, intensity of radiation will increase. I think that you have a confusion that with increase in frequency and keeping the number of photons srtiking a given area of the surface, photoelectric current with increase or not. It will not increase because during Photoelectric effect photons o suffer one-to-one perfect inelastic collision with electrons. So one Photon can eject only one electron in spite of its large energy content and hence photo electric current will not increase.


text:
Q: Display first record in rails Assuming I have a comments model and a posts model,
What code can I use in a view to display the first comment of the post being linked?

A: assuming:
post = Post.find(params[:id])

and post model contains:
has_many :comments

then you can:
comments = post.comments
first_comment = comments.first

A: Post.find(123).comments.first

Where 123 is your post ID.

A: @post.comments.first will normally work. (@post should be set up in your controller method)
However it is good to realise that 'first' means first in the association, which is normally ordered by id. Since ids autoincrement, this happens to be the same as 'first added' or 'earliest comment'. But it doesn't have to be.
If your association for comments specified a different ordering, then first will use this, e.g. if your association looked like this:
has_many :comments, :order=>'rating desc'

Then (assuming the 'rating' field is set up somehow to be some value that represents the average rating) post.comments.first would give you the highest rated comment, not the first to be added.
In that case, assuming your comments model has timestamps, then you'd need to do something like
@post.comments.find(:first, :order=>'created_at asc')


text:
Q: CORS for httaccess to web.config how do I convert this htaccess codes to webconfig?
My wordpress site ultilize a REST api: "wp-json". The configuration for cross-origin resources sharing are configured in a way that any website is able to make request to the rest api. So I have to disallow. I found out that in htaccess, it should look something like this.
<Directory "/path/to/wp-json">
   <IfModule mod_headers.c>
 Header set Access-Control-Allow-Origin "*"
   </IfModule>
</Directory>

But how do I do it for plesk hosting, web.config?

A: I believe what you want to do is simply add a response header of Access-Control-Allow-Origin:* to any request that goes to http://hostname/path/to/wp-json/.  The following should do that.
Add-WebConfigurationProperty -pspath 'MACHINE/WEBROOT/APPHOST/Default Web Site' -location 'path/to/wp-json' -filter "system.webServer/httpProtocol/customHeaders" -name "." -value @{name='Access-Control-Allow-Origin';value='*'}


text:
Q: Laravel : My app doesn't get routed I'm running my first laravel app for the first after hours struggling with dependencies installation errors.
Sorry it might be tiny mistake but seems I couldn't find out.
Picture are darker, computer is being broken.

app/Http/routes.php
<?php

// view('helloworld') ==> helloworld.blade.php
Route::get('/', function () {
   return view('helloworld');
});

resources/view/helloworld.blade.php
<!DOCTYPE html>

 Yo test....test..

when I hit http://localhost:8000/, it gaves me (even after refreshing) :

Why doesn't '/' get routed ? It's laravel 5, the latest one.

A: can you check in incognito or maybe you should remove the welcome.blade.php file

A: In Laravel 5.3, the Http routes file was switched to the routes/ directory.
https://laravel.com/docs/5.3/routing#basic-routing

All Laravel routes are defined in your route files, which are located in the routes directory. These files are automatically loaded by the framework. The routes/web.php file defines routes that are for your web interface. These routes are assigned the web middleware group, which provides features like session state and CSRF protection. The routes in routes/api.php are stateless and are assigned the api middleware group.

A: you should have your web page routes in routes/web.php in laravel 5.3 !


text:
Q: Alignment problems in the Extension Library Application Layout Placebar in IE but not Firefox Got an interesting CSS problem. The first graphic shows the buttons on the PlaceBar in IE where the "Views" button is pushed up. This button has children if this makes a difference. In FireFox everything lines up perfectly. Does anyone know if this is adjustable in the CSS and if so where?

A: I've found another fix. Add this to the CSS:
.lotusPlaceBar .lotusBtnContainer {
    float: right;
}

A: You can force IE not to use compatibility mode by using the X-UA-Compatible meta tag to control the version of IE to render the page for.
Add the following meta tag to enable IE8 Standards Mode:
<meta http-equiv="X-UA-Compatible" content="IE=8" >

You can add the meta tag in a theme using:
<resources>
  <metaData>
    <httpEquiv>X-UA-Compatible</httpEquiv>
    <content>IE=8</content>
  </metaData>
</resources>


text:
Q: Belongs_to and has_and_belongs_to_many to the same table in Rails Users create Programs. These can be followed/liked by other Users. However, the Program will ALWAYS have one creator.
So I need a ProgramsUsers table to map the like/follow. Would the "creator" also go as a type of relationship in that table, or could a Program also belongs_to a single specific User?
So in essence:
Program.rb
class Program < ActiveRecord::Base
  has_and_belongs_to_many :users    #Likes/Follows
  belongs_to :user                  #Creator

Is this acceptable or is this poor modeling?

A: I believe you can do something like this
class Program < ActiveRecord::Base
  has_and_belongs_to_many :users    #Likes/Follows
  belongs_to :creator, ::class_name => 'User', :foreign_key => 'creator_id'

This way, you can have a creator_id field on your programs table, and access it using @program.creator. Oh, and btw, it is not poor modeling.

A: Something like this:
class Program < ActiveRecord::Base
  has_many :followings
  has_many :followers, :class_name => 'User', :through => :followings
  belongs_to :creator, :class_name => 'User', :foreign_key => 'creator_id'


text:
Q: ActiveRecord::AssociationTypeMismatch when create new Got ActiveRecord::AssociationTypeMismatchComponent(#70354292616060) expected, got String(#70354278277000) when create object "Machine" below;
Objective: Try to assign "attributes" to a model that is referred to the other model.
Question: I would like to hear from expert that what is the best practice for this kind of operation.
Settings:
Rails 3.2.12 / Ruby 1.9.3-p194:
Models:
class Machine < ActiveRecord::Base
  attr_accessible :cpu, :name, :ram

  belongs_to :cpu, class_name: "Component", foreign_key: "component_id"
  belongs_to :ram, class_name: "Component", foreign_key: "component_id"
end

class Component < ActiveRecord::Base
  attr_accessible :name
  has_many :machines
end

Views for Machine:

    <%= f.label :name %>

    <%= f.text_field :name %>

    <%= f.label :cpu %>

    <%= f.collection_select :cpu, Component.all, :id, :name %>

    <%= f.label :ram %>

    <%= f.collection_select :ram, Component.all, :id, :name %>

    <%= f.submit %>

Procedure:

*

*Create few objects to Component such that id:1 name:"cpu1" & id:2 name:"ram1"

*Go to machines_path and create Machine with selecting cpu1 and ram1 from pull down

*Got following error when submit Component(#70354292616060) expected, got String(#70354278277000)
I tried to change :cpu and :ram in View with :cpu_id and :ram_id. Thereafter, I can create the model without error.  However I cannot access cpu & ram directly from machine;
1.9.3-p194 :001 > Machine.first
  Machine Load (0.1ms)  SELECT "machines".* FROM "machines" LIMIT 1
 => #<Machine id: 2, name: "test", cpu_id: 1, ram_id: 1, created_at: "2013-05-06     16:42:47", updated_at: "2013-05-06 16:42:47">
1.9.3-p194 :002 > Machine.first.cpu
  Machine Load (0.2ms)  SELECT "machines".* FROM "machines" LIMIT 1
 => nil
1.9.3-p194 :003 > Machine.first.ram
  Machine Load (0.2ms)  SELECT "machines".* FROM "machines" LIMIT 1
 => nil

So I had to create following model methods
  class Machine < ActiveRecord::Base

  (snip)

  def cpu
    Component.find_by_id(self.cpu_id)
  end

  def ram
    Component.find_by_id(self.ram_id)
  end

Then I can get expected output
1.9.3-p194 :002 > Machine.first.cpu.name
  Machine Load (0.2ms)  SELECT "machines".* FROM "machines" LIMIT 1
  Component Load (0.2ms)  SELECT "components".* FROM "components" WHERE "components"."id" = 1 LIMIT 1
  => "CPU1"

But I feel it's redundant and looking for a simpler way to do this.
Appreciate if any suggestions.

A: So, if i'm reading this right, you need to be able to set fields to the other model from within your form.
That's nested attributes.
do a form_for @components within the form_for @machines and give attr_accessible permissions to those fields from the Machine model
This is helpful http://railscasts.com/episodes/196-nested-model-form-part-1

A: First off, having your select boxes work with cpu_id and ram_id is the right thing to do. If you don't then rails will (simplifying slightly) do
machine.cpu = params[:machine][:cpu]

Params are always strings, so this is trying to assign a string to the association, hence the error about it expecting a component but getting a string.
Your second problem is in how you've declared your associations: you've set both ram and cpu associations to use the component_id column to store the id of the corresponding column, which clearly can't work. Instead you probably want the CPU association to use the cpu_id column and the ram association the ram_id column. This is actually the default - remove the foreign key option you're passing to those calls to belongs to and you should be ok.
You associations on component would need a foreign key option though. The simplest thing would be to have one association for the machines that the component acts as CPU for and another for the ram. You might consider setting up single table inheritance, in which case the CPU subclass would only have the association relating to cpu_id and the ram subclass would only have the association relating to ram_id


text:
Q: Open a directory using specific path How to open a location of file in local machine using a specific path in C++?
Path as input:
D:downloads/sample.txt
Output: after executing, file should be opened automatically.

A: Notice that directories (or "folders") are unknown to the C++11 or C++14 standards. C++17 has a std::filesystem namespace from <filesystem> standard header.
Notice also that on Windows the directory separator in file paths is a backslash \ (but on POSIX and Linux it is a forward slash /). Some runtime systems (and C++ standard libraries) might convert forward slashes / to backslashes \ in file paths on Windows. Check your documentation to see if your implementation does that conversion.
Many framework libraries (including Qt & POCO & Boost) provide abstractions related to directories, files, paths and file systems.
I don't have Windows (I'm happy to only use Linux both at work and at home), but I guess that you could pass D:downloads\sample.txt as a path for std::ifstream. Of course you'll need to escape the backslash in your literal string:
std::ifstream myinput("D:downloads\\sample.txt");

(I guess that the downloads should start with a capital Downloads, but I leave you to check that, also on French systems it might be a different directory Téléchargements but you should check; I would recommend using some absolute file path like D:\Downloads\sample.txt; of course you'll need to escape both backslashes in a literal string)
Notice that a file path is not an URL (but URLs starting with the file: scheme designate a local file thru its file path). AFAIK you need some external library to handle such URLs. If you insist on giving full URLs, you'll better in practice use some HTTP client library (e.g. libcurl), because most URLs are for HTTP.
You might later test that the input stream is correctly opened:
if (!myinput.is_opened())
    throw throw std::runtime("failed to open myinput");

Then you could parse from it using the operator >> for instance
int x=0;
myinput >> x;

You could later use the unary operator ! to check against input parsing failures.


text:
Q: Json not loading correctely in python I am getting followers on Twitter using Twython library, it returns a json to me. But the issue is that the json contains single quoted string inside like {"description":"i don't like this"}, so when i dump to json and try saving to mysql i get an error saying there is an error in mysql query near \'. However, if i try to reduce the number of followers am getting which removes the part that has the quotes, i am able to save it to mysql correctly, but trying to retrieve it back and load it as json again, i get an error: Expecting ',' delimiter. if i use json.dumps(eval(data)) i get error invalid syntax and if i try json.loads(data) i get Expecting ',' delimiter. below is a sample of my code
import json

def get_followers(self,count,cursor):
         result=None
         next_cursor=None
         if cursor=='' or cursor==0 or cursor=='0' or cursor==None:
            result=self.twitter.get_followers_list(count=count, screen_name=self.___twitter_handle___)
            next_cursor=self.get_next_cursor(result)
         else:
             result=self.twitter.get_followers_list(count=count, screen_name=self.___twitter_handle___,cursor=str(cursor))
             next_cursor=self.get_next_cursor(result)
         return result,next_cursor

def get_next_cursor(self,the_json):
        next_cursor=None
        if 'next_cursor' in the_json and not the_json['next_cursor']==None:
            next_cursor=the_json['next_cursor']
        return next_cursor

data,next_cursor=user.get_followers(2,next_cursor)
            print('returned cursor ',next_cursor)

            print(type(data))

            #save the result in database
            if data:
                #Get the data already in the db
                query2="select id,data from twitter_data where id={0}".format(id)
                cur.execute(query2)
                rows=cur.fetchall();
                db_data=''
                new_data=[]
                for row in rows:
                    db_data=row[1]
                    if db_data==None or db_data=='':
                        new_data.append(data)
                    else:
                        db_data=json.dumps(eval(db_data))
                        db_data=json.loads(db_data)

                        #check if it is correctely parsed
                        for item in db_data:
                            print(item)
                        print('db_data ',type(db_data))
                        db_data.append(data)
                        new_data=db_data

                    #Save back the result in the database
                    new_data=json.dumps(new_data,separators=(',', ': '))
                    print(type(new_data))
                    query3="update twitter_data set data='{0}',next_cursor='{1}',crawler_status=1 where id={2}".format(new_data,next_cursor,id)
                    cur.execute(query3)
                    db.commit()

I am trying to implement the next cursor so each time i call the function it should get me the data already in db and load it as json in order to append the next one am getting to it, and that is where am having the problem.


text:
Q: Unable to refresh the changed data in listview using notifyDataSetChanged I have a main activity which has a listview which loads first and from this main activity I am launching a new activity where I'm trying to get the edittext value to my main activity by passing intent. Everything is working fine but when I add the editext value to the listview its adding but when I go to the second activity and add again and comes back to the main activity the previous added data is no more seen and the newly added value is updating the listview.
Can anyone help me out with this?
This is my Adapter:
public class AdapterListViewData extends BaseAdapter{

    private LayoutInflater mInflater;
    private Context context;
    private ArrayList<DataShow> listData = new ArrayList<DataShow>();

    public AdapterListViewData(Context context,ArrayList<DataShow> listData) {

        this.context = context;
        this.mInflater = LayoutInflater.from(context);
        this.listData = listData;
    }

    public int getCount() {
        // TODO Auto-generated method stub
        return listData.size();
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public View getView(final int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        HolderListAdapter holderListAdapter;

        if(convertView == null)
        {

            convertView = mInflater.inflate(R.layout.adapter_listview, null);

            holderListAdapter = new HolderListAdapter();

            holderListAdapter.txtTitle = (TextView) convertView.findViewById(R.id.txtTitle);
            holderListAdapter.txtDetail = (TextView) convertView.findViewById(R.id.txtDetail);
            holderListAdapter.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);

            convertView.setTag(holderListAdapter);
        }else{
            holderListAdapter = (HolderListAdapter) convertView.getTag();
        }

        holderListAdapter.txtTitle.setText(listData.get(position).getTitle());
        holderListAdapter.txtDetail.setText(listData.get(position).getDetail());

        holderListAdapter.checkBox.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(context,"CheckBox "+ position +" check!!",Toast.LENGTH_SHORT).show();
            }
        });

        convertView.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                // TODO Auto-generated method stub
                Toast.makeText(context,"List "+ position +" click!!",Toast.LENGTH_SHORT).show();
            }
        });

        return convertView;
    }
}

MainActivity:
public class CustomListViewActivity extends Activity {

    private AdapterListViewData adapterListViewData;
    private ArrayList<DataShow> listData = new ArrayList<DataShow>();
    private ListView listViewData;
    String AddedTask ;
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Intent intent = getIntent();

        listViewData = (ListView)findViewById(R.id.listViewData);
        if (intent.hasExtra("NewTask")) {
             AddedTask = this.getIntent().getExtras().getString("NewTask");
            listData.add(new DataShow(AddedTask,""));

       }
        adapterListViewData = new AdapterListViewData(getBaseContext(),listData);
        listViewData.setAdapter(adapterListViewData);
        adapterListViewData.notifyDataSetChanged();
     }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar actions click
        switch (item.getItemId()) {
        case R.id.action_settings:
            return true;
        case R.id.action_add_task:
            Intent i = new Intent(CustomListViewActivity.this, AddTask.class);
            startActivity(i);
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

}

DataShow:
public class DataShow {
    private String title;
    private String detail;

    public DataShow(String title,String detail) {
        // TODO Auto-generated constructor stub
        this.title = title;
        this.detail = detail;
    }

    public String getTitle(){
        return this.title;
    }

    public String getDetail(){
        return this.detail;
    }
}

Holder:
public class HolderListAdapter {
    TextView txtTitle;
    TextView txtDetail;
    CheckBox checkBox;
}

Second Activity:
public class AddTask extends Activity {
Button addtask;
      @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.add_task);

            // get action bar
            ActionBar actionBar = getActionBar();

            // Enabling Up / Back navigation
            actionBar.setDisplayHomeAsUpEnabled(true);

            addtask = (Button) findViewById(R.id.btnaddlist);
            findViewById(R.id.btnaddlist).setOnClickListener(
                      new View.OnClickListener() {
                          public void onClick(View arg0) {
                              EditText edit = (EditText) findViewById(R.id.tskname);
                              Intent i = new Intent(AddTask.this,
                                      CustomListViewActivity.class);
                              //Bundle bundle = new Bundle();

                              String TaskName = edit.getText().toString();
                              //bundle.putString("NewTask", TaskName);
                              i.putExtra("NewTask", TaskName);
                              //i.putExtras(bundle);
                              startActivity(i);
                          }
                      });

          }

        }

A: I believe you should call adapterListViewData.notifyDataSetChanged(); inside of
 if (intent.hasExtra("NewTask"))
{
      AddedTask = this.getIntent().getExtras().getString("NewTask");
      listData.add(new DataShow(AddedTask,""));
 }

That is,
if (intent.hasExtra("NewTask"))
{
     AddedTask = this.getIntent().getExtras().getString("NewTask");
     listData.add(new DataShow(AddedTask,"")); // you are adding new data here
     adapterListViewData.notifyDataSetChanged(); // just refresh the adapter here

 }

For debugging purpose, check what value you're getting for NewTask in MainActivity.class.
   Log.d("track",AddedTask);

DataShow class constructor expects a title and detail. Did you check whether it adds the value & you missed detail which is empty right?
listData.add(new DataShow(AddedTask,""));

Try supplying static data.
One more thing, check whether your adapter is null or not when adding new data send back from the secondActivity by,
  if (adapterListViewData != null) {
         AddedTask = this.getIntent().getExtras().getString("NewTask");
  listData.add(new DataShow(AddedTask,""));
        adapterListViewData.notifyDataSetChanged();
    }
  else
   {
      adapterListViewData = new AdapterListViewData(getBaseContext(),listData);
        listViewData.setAdapter(adapterListViewData);
   }

A: You are creating a new instance of adapterListViewData  everytime your
onCreate is called that is why the previous data has been wiped out.
Add a checking in your onCreate to prevent this from happening.
if ( adapterListViewData == null )
{
  adapterListViewData = new AdapterListViewData(getBaseContext(),listData);
  listViewData.setAdapter(adapterListViewData);
}

A: Your old data got removed becaus it is not transmitted to the new activity that you start after creating the new item.
You should use startActivityForResult to create new task and call Add the new task to the list adapterListViewData in onActivityResult and call notifyDataSetChanged in it.


text:
Q: How to get airmon-ng on Kali Linux? I recently installed a Kali Linux distribution with default toolset. I try to use airmon-ng but have no success. I had aircrack-ng package installed (it was installed from the beggining but to be sure I did sudo apt update && sudo apt install aircrack-ng, it didn't help). The package is just not found. sudo apt install airmon-ng didn't help too. How do I install and start to use airmon-ng in my installation?
Upd: here's the contents of apt list --installed | grep aircrack:
aircrack-ng/kali-rolling,now 1:1.6-4 amd64 [installed]

A: Since aircrack-ng is installed, you already have airmon-ng, but it's in /usr/sbin so it's not on regular users' PATH. You typically need to run it as root:
sudo airmon-ng


text:
Q: How can assign multiple html element values in one call? I have a bunch of radio buttons with several duplicate attributes. Can I somehow assign all these in one place, maybe like [a, b, c] = (js)()? Thank you.
<input type="radio" value={`${index}-0`}
                      key={`${index}-0`}
                       id={`${index}-0`}
  checked={this.state.selections[index] === 0 }
  onChange={this.handleChange} />
<label htmlFor={`${index}-0`} className="pure-radio"> 0 </label>

A: Why not just assign them to the same variable? It's not quite what you are wanting, but better than your current situation.
var key = `${index}-0`;
...
<input type="radio" value={key}
                  key={key}
                   id={key}
                 checked={this.state.selections[index] === 0 }
                 onChange={this.handleChange} />
<label htmlFor={key} className="pure-radio"> 0 </label>

A: All the attributes of an element is saved in attributes.
const attrs = document.getElementById('your_id').attributes

You can loop through them to access the attributes. See the example in the provided link.
Or, you can use getNamedItem to access desired attribute:
attrs.getNamedItem('id') // to get id attribute


text:
Q: C++ problems returning from a function I've made a server application for my own personal use, but I've always had a problem when a client disconnects. I've just recently realized that this is caused by the item returned by the recv function not being recognized correctly.
For example:
char* mrecv(bool show, LPVOID pointerToObject) //Recieve a message
{
    int iResult2 = recv(ClientSocket, recvbuf, 512, 0);
    if (iResult2 > 0) {
        if ((strncmp(recvbuf,"/",1)) != 0) {
            printm(recvbuf, pointerToObject);
       }
    else if (iResult2 == 0) {
        printf("Connection closing...\n");
        closesocket(ClientSocket);
        WSACleanup();
        return "1";
    }
    else  {
        printm("recv failed with error: %d\n", WSAGetLastError());
        printm("Client must have disconnected. Please select a new client.");
        return "1";
    }
    return recvbuf;
}

When the client disconnects, the function returns "1" correctly to the parent function. However, when I check it as so...:
DWORD WINAPI recvfunc(LPVOID pointerToObject)
{
    while (true) {
        ClientSocket=client[currentclient].cs;
        char* p = mrecv(true, pointerToObject);
        std::cout<<p<<"\n";
        if ( p == "1") {
            client[currentclient].con=false;
            ClientSocket=client[lastclient].cs;
            return 1;
        }
    }
    return 0;
}

the if statement returns false whether or not the check returns "1", yet 1 prints to the screen flawlessly.
Anyone have any idea why this is happening?
I'm using winsock, if you haven't noticed.
Thanks in advance :)
EDIT::
All of the below answers as of this edit seem to be the same thing, and they all solve the problem. If you look at the first function listed up there ^, you'll see that I apparently even ran across this problem before and had to use this solution. So it looks like my brain just kind of gave up on me. Anyway, thanks for all the assistance. :)

A: Your mrecv returns a result of type char*.
Your comparison:
if (mrecv(true, pointerToObject)=="1")

is a pointer comparison, not a string comparison. It's true only if both instances of the string "1" happen to be stored at the same address.
To compare strings, use the strcmp function. Or, since you're using C++, consider using the std::string class (which has an overloaded == function that does string comparison) rather than using raw C-style strings.

A: Try:
if (strcmp(mrecv(true, pointerToObject), "1") == 0)

A: You're returning pointers to read-only char literals, those addresses are unreliable for a comparison as you're doing.
You might go for a string comparison using strcmp or any other C++ string comparison
if ( strcmp(p,"1") == 0) { ...

A: You are comparing char pointers, and there is no guarantee one pointer will be equal to the other:
Try this:
if (mrecv(true, pointerToObject)[0] == '1')

You are now comparing the first byte returned by mrecv to the character 1.
However, I highly recommend you return integer return codes, not characters.

A: Your problem is that you can't use the == operator in that fashion with C-style strings (char arrays) because what's being compared is not the contents of the string, but the value of the pointer to the first character, since you're really comparing a char* to a char*.  If you want to compare the actual value, you need to dereference the returned pointer and also compare it to a character value instead of a string literal (single quotes instead of double):
if (*mrecv(true, pointerToObject) == '1') {


text:
Q: Construct SimpleXMLelement with xml header only in PHP I have following code
$xml_start = new SimpleXMLElement('<?xml version="1.0" encoding="utf-8"?><xml></xml>');

and I need to get rid of the  tags. Any tag name works, but when I remove the tags I get an exception 'String could not be parsed as XML'. I can't figure out how to initialize the SimpleXMLelement with the header string <?xml version="1.0" encoding="utf-8"?> only. Also, is it possible to somehow initialize the SimpleXMLelement object without any input data and then append to it?

A: From the Docs
The SimpleXMLElement() constructor requires a well-formed xml document or a URL that points to an XML document. By only including a header, you are not defining the content of the document, and therefore it is by definition, not well defined.


text:
Q: Putting an inactive Meteor app to sleep on a DigitalOcean Ubuntu 14.04 server using nginx I have multiple Meteor apps running on a single DigitalOcean Ubuntu 14.04 droplet, using nginx.
Is it possible to have a similar result to Heroku's free app hosting where an app 'goes to sleep' after not being accessed a certain amount of time and then wakes up after being accessed again?


text:
Q: Scaling before multi-variate multi-output regression What happens if you apply scaling to your data before doing linear regression?

A: scaling required: to make gradient descent coverage more quickly (means make number of iteration or cycle less to reach local minima). to make gradient descent fast you need to make multiple features value on same range scale. like -1 < x < 1. not one value is 5 , other value is 0.1 .. and so on
why we need to do this : let's imagine you have two features x1 and x2. x1 value size in large is more compare to x2 , in that case your cost function will come in a very skewed elliptical shape. this means training will be longer to reach local minima.
for more clarity please follow this link : https://www.coursera.org/learn/machine-learning/lecture/xx3Da/gradient-descent-in-practice-i-feature-scaling


text:
Q: 'A / One / At least one student entered the room.' Are these the same? (truth-conditionally) I just wonder if the two following sentences are truth-conditionally the same. Sentence 1 essentially means there existed a student who entered the room, and this situation includes two, three or more students entering the room. Hence, I believe these two sentences are truth-conditionally the same. Are they?

*

*A student entered the room.

*At least one student entered the room.

How about

*One student entered the room

I gather this is different, as sentence 3 only means one student, not more and not fewer?
Any and all insights would be welcome.

A: Truth conditionally, each of the three sentences is the same. What is different is the implications of the different sentences when said out of context.
Generally speaking, we expect the maximum amount of relevance from our speakers. This means that we expect that - if this in keeping with what speakers actually want to and are able to do - they will give us the most informative information that we require, for the least amount of processing effort.
Sentence 1
In sentence (1) there is a relatively weak implication that only one student entered the room. The reason is that it takes just about the same time and effort to say some students entered the room as it does to say a student entered the room. The first sentence would enable the listener to make more inferences and add more items to their stock of beliefs (at the very minimum they would know that not only was it necessarily true  that a student entered the room, but it was also true that more than one student entered the room).
This implication may be cancelled out by the context. So for example, imagine there was rule that if even a single student entered a particular laboratory that room must be swept for bugging devices the same day. Now, if you're the person who's meant to do the bug sweeps, and there's been a student-staff meeting in that lab, then if your boss comes up to you and says "why haven't you done a bug sweep?" you might reply:

*

*Why? Oh, yes, sorry. That's right, a student's entered the  lab. I should have done a sweep.

Now because everyone knows that more than one student was in there and because the issue is not how many were in there, but that even one was in there, that sentence no longer carries an implication that less than two student entered. Notice that we still consider this sentence to be true. The fact that more than one student entered doesn't make it false.
Sentence 2
The second sentence implies that a minimum of one and maybe more students entered the room. The phrase at least takes more effort to process than the determiner a. It's a lexical phrase, it's two words and therefore longer and it's fairly likely to carry stress, thereby drawing our attention to it. The implication that at least communicates is that the speaker guarantees a minimum of one student entering, but has reason to believe that there were perhaps more.
This information is worth the extra processing effort on the part of the listener, because it is more informative than a student would be. By using this information together with our other background knowledge, we might be able to make more inferences from it than we would from a student entered the room. However, notice that there is no guarantee on the part of the speaker of more than one student having entered, but there is a guarantee of one student having entered. So, if one or more students entered then the sentence is true, exactly in the same way that sentence (1) would be.
Sentence 3
Sentence (3) carries a relatively strong implication that exactly one student entered the room and not more. The word one is usually stressed. It is often argued, in fact, that the word one is the stressed form of the indefinite article a (historically the two words derive from the same root). The fact that the speaker is using a stressed form here gives us reason to believe that they want to draw our attention to the actual quantity itself. Now, if there was more than one student, why would they emphasise the singular numeral? This would be increasing the processing effort with no benefit in terms of extra informativity.
However, there are many contexts in which we might want to do this. For example, if we know that student Bob was in the room, because he told us so, then if somebody else claimed that no students entered the room, we might say:

*

*One student entered the room!

Here we would be very likely to stress the word one. In this case, the numeral one is contrastive with the zero implied by the word nobody - which is why we use this form, and why it is stressed. However, in this context we are not implying that no other students entered the room. Our sentence would not be false if it turned out that Maria had also entered the room, for example. The reason that we only used one is that we cannot truthfully attest to more than one, not that there weren't more than one. So again, we have a guarantee that one student entered, but no guarantee that it was only one.
Conclusion
Many of the words that we use in speech are there to guide the reader to the best interpretation of the sentence, but do not actually affect the truth functional meaning of the sentence itself. They also help the reader make useful inferences about the speaker's communicative intentions. The three sentences in the Original Poster's examples use different quantifiers and discourse markers which may carry different implications, but which don't differ in terms of their truth values.

A: As an exercise in formal logic, all three are equivalent. In the case of #3, if N students entered the room, so did any subset of those students.
As English sentences, though, they differ. The first and third are close, the former emphasising the student and the latter, the number of students. Although other students might have entered the room as well, both sentences focus on the individual student referenced as the subject of the sentence. The second sentence makes it explicit that there could have been more than one student who entered the room, so is a little different from the other two.


text:
Q: Probability of $m_l=1$ if $l=1$? I am solving a problem asked to find $\left\langle\hat{L}_z\right\rangle$ given that $l=1$, $s=1/2$, $j=1/2$, and $m_j=1/2$. My approach is to solve it by $$\left\langle\hat{L}_z\right\rangle = \left\langle lm_l\left\vert\hat{L}_z\right|lm_l\right\rangle$$
but $m_l$ is not given.
To do this one must know what $m_l$ is of course, which can take values $-l,-l+1,\ldots,l$, but the problem does not give this information and I do not think it is something that can be computed.

However, the explanations up until this point were just context as to why I am asking my question, which is:

If we know that the azimuthal quantum number of our system is $l=1$, but I do not know what the magnetic quantum number is exactly, would we be able to say that there is a 33% chance that $m_l=1$? Since $m_l$ can only be one of the following three numbers: $-1, 0, 1$.

A: You have given not the product state ($|l,m_l\rangle \otimes |s,m_s\rangle$) but total angular momentum ket ($|j,m\rangle) $. You can use the Clebsc-Gordan coefficient to write these in terms of product state. You can find the table for CG coefficients here. Once you find the state in term of product state, the rest is quite trivial.

A: I'm assuming that $j$ and $m_j$ are the quantum numbers associated with the total angular momentum $\hat{\vec{L}}+\hat{\vec{S}}$. Consider the eigenstate
$$
\lvert j,m_j;l,s \rangle = \lvert 1/2,1/2;1,1/2 \rangle
$$
of the operators $\hat{J}^2$, $\hat{J}_z$, $\hat{L}^2$, and $\hat{S}^2$. Using Clebsch-Gordan coefficients, we can expand this state in the product basis
$$
\lvert l,m_l\rangle\lvert s,m_s \rangle
$$
of eigenstates of $\hat{L}^2$, $\hat{L}_z$, $\hat{S}^2$, and $\hat{S}_z$. The relevant Clebsch-Gordan coefficients are shown below, from which we discern that
$$
\lvert 1/2,1/2;1,1/2 \rangle =
\sqrt{\frac{2}{3}}\lvert 1,1\rangle\lvert 1/2,-1/2 \rangle
-
\sqrt{\frac{1}{3}}\lvert 1,0\rangle\lvert 1/2,1/2 \rangle
$$.
From here, a straight-forward calculation shows that
$$
\langle \hat{L}_z \rangle = \frac{2\hbar}{3}\,.
$$


text:
Q: $\int_E \frac{y^2}{x^2}d\lambda^2(x,y)$ for $E=\{ (x,y)\in\mathbb R^2 : x\le y, xy\ge 1, y\le2 \}$ $\int_E \frac{y^2}{x^2}d\lambda^2(x,y)$ for $E=\{ (x,y)\in\mathbb R^2 : x\le y, xy\ge 1, y\le2 \}$
I often struggle to find the boundaries of integration from a given area.
My approach was to use Fubini as the function is positive and compute the iterated integral
$\int_{-\infty}^{2}\int_{1/y}^{y} \frac{y^2}{x^2} dx dy=...=\infty$
My questions is whether the boundaries $\frac{1}{y} \le x\le y$ and $-\infty \le y\le 2$ are correct and if there is a general/elegant approach to find them from a given arbitrary area.

A: Wolfram Alpha produces this plot for x <= y, xy >= 1, y <= 2:

So it makes sense that you would need to break the integration up into at least two pieces. Since $xy > 0$, $x$ and $y$ are always of the same sign.
When $x > 0, y> 0$, then $y = 2$ is the top, $y = x$ is bottom and left, and $y = 1/x$ is bottom and right. $y = 1/x$ and $y = x$ cross at $(1,1)$, so if you integrate by $y$ first, you need $y \in [1/x, 2]$ for $x \le 1$ and $y \in [x, 2]$ for $x \ge 1$. $y = 1/x$ crosses $y = 2$ at $x = 1/2$, so you get $\int_{1/2}^1\int_{1/x}^2 \, dydx$ for the first and $\int_1^2\int_{x}^2 \, dydx$ for the second.
But if you integrate $x$ first, then this piece can be done in a single integration: $\int_1^2\int_{1/y}^y \, dxdy$
The lower left piece where $x < 0, y < 0$ is simpler, as $y \le 1/x$ implies $y \le 2$ here. The integral is $\int_{-\infty}^{-1}\int_{x}^{1/x}\, dydx$
So the simplest form is
$$\int_E \frac{y^2}{x^2}d\lambda^2(x,y) = \int_{-\infty}^{-1}\int_{x}^{1/x}\frac{y^2}{x^2}\,dydx + \int_1^2\int_{1/y}^y \frac{y^2}{x^2}\, dxdy$$


text:
Q: Are there any data-binding solution that works in C++ and GWT and supports structures polymorphism? I expect it should share a common description, like XmlSchema or IDL and should generate classes for target language.
I found Thrift and it's really nice solution, but it doesn't support structures polymorphism.
I would like to have collections of base class objects, where I could place instances of subclasses, serialize this and deserialize at the opposite side. Some mechanism of polymorphic behavior support, like Visitor, would be a perfect.
Does anybody know something suitable for these requirements?

A: I would suggest trying Protocol Buffers. It is a Google originated technology so I would imagine it is well supported by C++ and GWT.
http://code.google.com/apis/protocolbuffers/

A: As mentioned, something like Protocol Buffers would definitely be your best bet. It supports C++ and there are two separate projects that support GWT: protostuff and protobuf-gwt.
There are many comparisons between Protocol Buffers and Thrift, so if you're looking to use Thrift, it's possible to integrate with GWT as well, through the gwt-rpc-plus project.


text:
Q: How to change a color of one letter in JTextField? I have a JTextField where I enter black characters.
I want the color of one letter in the text field to change to red under a certain condition. If this condition is not met, then the color changes back to black.
I tryed to use a textField.setForegroung(new Color(237, 42, 42), but it changes a color of all text. I need to change a color of one character.

A: You can't define the color of individual chars in a JTextField. You need to use a JTextPane (or JEditorPane). With these components, you can use DefaultStyledDocument to define your text styles.
Here's an example:
public class MyApplication extends JFrame {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                MyApplication app = new MyApplication();
                app.setVisible(true);
            }
        });
    }

    private MyApplication() {
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(600, 600);

        StyleContext sc = new StyleContext();
        DefaultStyledDocument doc = new DefaultStyledDocument(sc);
        JTextPane textPane = new JTextPane(doc);
        textPane.setText("This is some colored text.");

        // Create a new style
        Style coloredCharStyle = sc.addStyle("ColorChars", null);
        coloredCharStyle.addAttribute(StyleConstants.Foreground, Color.red);

        // Define where the style should be applied
        doc.setCharacterAttributes(13,7,coloredCharStyle,false);

        // Add textPane to JFrame
        add(textPane, BorderLayout.CENTER);

        setVisible(true);
    }

}


text:
Q: Project screen position onto plane in OpenGL I'm currently struggling with a simple task: Given a mouse position on the screen, calculate the new position which is determined by calculating the intersection of the camera plane that goes through the selected object and the ray of the mouse click.
The math involved is not that tricky but still I can't seem to find the error.
        QVector3D cameraPosition = Rotation.rotatedVector(translation);
        QVector3D cameraDirection = Dir;
        QVector3D objectPosition = objectTranslation;
        QVector3D up = Rotation.rotatedVector(QVector3D(0,1,0));
        QVector3D Right = QVector3D::crossProduct(Dir, up);

As you can see, I'm using Qt to represent my data. First of all, I rotate my translation Vector by the Camera Rotation to obtain the cameraPosition. Otherwise I won't get the cameraPosition in Worldcoordinates. After that I calculate the Up and Right Vector. In order to calculate the ray-plane intersection I'm using this as a reference: http://softsurfer.com/Archive/algorithm_0104/algorithm_0104B.htm#Line-Plane Intersection
Afterwords I normalize the screen coordiantes
        float screen_x = 2*(float(pos.x())/width()-0.5);
        float screen_y = 2*((float(height()-1-pos.y())/height())-0.5);
        screen_x*= (1.0f/height())/(1.0f/width());

Finally, the actual computation:
        QVector3D P0 = cameraPosition;
        QVector3D n = cameraDirection;
        QVector3D V0 = objectPosition;
        QVector3D u = (screen_x*Right+screen_y*up)*0.5+cameraDirection;
        float s = QVector3D::dotProduct(n, V0-P0) / QVector3D::dotProduct(n, u);
        objectTranslation = P0+s*u;

I guess the problem lies withing the calculation of u or something beyond me. I get the Direction of the camera by evaluation the ModelView Transformation matrix and taking out the third row:
GLdouble modelview[16];
glGetDoublev( GL_MODELVIEW_MATRIX, modelview );
QMatrix4x4 mv = QMatrix4x4(modelview);
Dir = QVector3D(mv.row(2).x(), mv.row(2).y(), mv.row(2).z()).normalized();


text:
Q: Tableau Error "ORA-00972: identifier is too long" I'm attempting to add data to Tableau from Oracle but am getting the following error: Error "ORA-00972: identifier is too long. This error is because I'm attempting to use a column that is longer than 30 characters. I know that one fix for the issue to change the name in Oracle to shorter than 30 characters. Unfortunately, I can't do this myself and it will take the team that can do this longer than I'd like to wait so I was wondering if there are any workarounds to this issue.
I have already read the following page from Tableau: https://kb.tableau.com/articles/issue/error-ora-00972?signin=0f7d7b7f02b5d408316cdf9e3b03eef

A: An ORA-00972 means you are using a database column or object identifier name that is too long, as @tejash said in the comments. When you see this error in Tableau specifically, it only happens because the dimension or measure in Tableau has been renamed to be longer than 30 characters. It's an easy mistake to make because the Tableau UI doesn't prohibit the longer name.

I know that one fix for the issue to change the name in Oracle to
  shorter than 30 characters. Unfortunately, I can't do this myself.

Because Oracle would have never let the name be longer than 30 characters when the column was created, there is nothing to fix in Oracle. You must fix it in Tableau and this is something you can fix yourself: rename the dimension or measure. There are a number of places this is possible and all follow the same principle (just different screen layouts) so I will describe the one I'm most familiar with. On any worksheet, on the left-hand pane where you see the dimensions and measures, right-click on the dimension or measure you need to rename and choose the "Rename" menu option.


text:
Q: PyQGIS problem with QgsRasterCalculator CRS definition from qgis.analysis import QgsRasterCalculator, QgsRasterCalculatorEntry import processing
from osgeo import osr, gdal from gdalconst import *

dataset1 = gdal.Open(input1, GA_Update) band1 = dataset1.GetRasterBand(1) dataset1.SetProjection( srs.ExportToWkt() ) dataset1 = None

layer1=QgsRasterLayer(dataset1,'test1')
#layer1.setCrs( QgsCoordinateReferenceSystem(3003, QgsCoordinateReferenceSystem.EpsgCrsId) )

print('load first layer')

input2='D:\\ascii2grids\\dati_ascii\\PR_2018091500UTCplus1.txt'

dataset2 = gdal.Open(input2, GA_Update) band2 = dataset2.GetRasterBand(1) dataset2.SetProjection( srs.ExportToWkt() ) dataset2 = None

layer2=QgsRasterLayer(dataset2,'test2')

print('load II layer')

exp = "%s - %s" % (layer1,layer2)

output='C:\\Users\\assis\\test.tif'

entries=[layer1,layer2]

calc = QgsRasterCalculator(exp,
                    output,
                    'GTiff',
                    layer1.extent,
                    QgsCoordinateReferenceSystem("EPSG:3003"),
                    layer1.width,
                    layer1.height,
                    entries
                    )

res = calc.processCalculation(feedback) if res == QgsRasterCalculator.ParserError:
    raise QgsProcessingException(self.tr("Error parsing formula"))

This pyqgis script give me the following error:
Traceback (most recent call last):   File "C:\OSGEO4~1\apps\Python37\lib\code.py", line 90, in runcode
    exec(code, self.locals)   File "<input>", line 1, in <module>   File "<string>", line 57, in <module> TypeError: QgsRasterCalculator(): arguments did not match any overloaded call:   overload 1: argument 4 has unexpected type 'builtin_function_or_method'   overload 2: argument 4 has unexpected type 'builtin_function_or_method'   overload 3: argument 1 has unexpected type 'str'

I do not understand the error. Perhaps the CRS definition in the QgsRasterCalculator function. Unfortunately I do not find any example of how to define CRS

A: You're specifying the function instead of calling it. I.e.
layer1.extent

should be:
layer1.extent()

Do this with width and height:
calc = QgsRasterCalculator(exp,
                        output,
                        'GTiff',
                        layer1.extent(),
                        QgsCoordinateReferenceSystem("EPSG:3003"),
                        layer1.width(),
                        layer1.height(),
                        entries
                        )


text:
Q: PNaCl logging to stdout no longer working in Chrome 72 onwards? I'm currently working to maintain an existing PNaCl application for ChromeOS devices. Prior to Chrome 72, we were able to log to stdout and stderr and these logs would appear on the ChromeOS device inside the ui.LATEST file. Since our ChromeOS devices have upgraded to versions past Chrome 71 our logs do not appear any more. We've tried this on devices running both Intel and ARM chipsets with the same results. We are using Pepper 49 (the latest). Our development environments in Ubuntu are still outputting to the stdout and stderr.
Has there been a change in Chrome 72 to where stdout and stderr log to or how we log to the ui.LATEST file?
EDIT: We've tried a couple of other sites that we know log to the stdout and use PNaCl, namely this: https://gonativeclient.appspot.com/demo - this also does not log to the Chromebooks but does log in our development environments.


text:
Q: Image scale using aspect ratio coil using jetpack compose I need to display image from uri/filepath, big image 1300x1600 resolution.
Need to maintain aspect ratio.
i tried with coil but didn't give desirable result, still shows big image. not sure whats wrong
here what i tried
val painter =
    rememberAsyncImagePainter(imageUri.value)

Image(
    painter = painter,
    contentScale = ContentScale.Fit,
    contentDescription = null,
    modifier = Modifier
        .padding(16.dp, 0.dp, 16.dp, 0.dp)
        .fillMaxWidth()
        .aspectRatio(painter.intrinsicSize.height / painter.intrinsicSize.width)
)

A: You are getting size unspecified if one of view width/height is calculated as zero.
You can use something like:
Image(
    painter = painter,
    contentScale = ContentScale.Fit,
    contentDescription = "contentDescription",
    modifier = Modifier
        .padding(16.dp, 0.dp, 16.dp, 0.dp)
        .fillMaxWidth()
        .then(
            (painter.state as? AsyncImagePainter.State.Success)
                ?.painter
                ?.intrinsicSize
                ?.let { intrinsicSize ->
                    Modifier.aspectRatio(intrinsicSize.width / intrinsicSize.height)
                } ?: Modifier
        )
)


text:
Q: Webots Sim "ready" signal When using an external python script to start webots (or when restarting an environment) it would be necessary to know when the simulation is ready, for an external controller to (re-)run.
Is there any sort of "ready" signal that webots returns after starting from the commandline or when restarting a world ? Or other ways to probe when the external controller can start working ?

A: Webots doesn't provide such signal directly. However, when Webots is started, it will create in the temporary files a folder called webots-XXXX (one per instance of Webots, XXXX should be replaced by the PID of the Webots process) and in this folder, a file called WEBOTS_SERVER will be created as soon as the controllers are ready to be started


text:
Q: You don't have permission to access /phpmyadmin/ on this server. To access another pc localhost in windows 7 I am trying to access another PC Localhost on my PC in same LAN using IP address of that PC, and I am use WAMP Server to connect phpmyadmin of another pc.
I am successfully connected to WAMP server(e.g URL http://192.168.1.8/), but if I try to click on phpmyadmin(http://192.168.1.8/phpmyadmin/) then following network error occurred.

Forbidden
  You don't have permission to access /phpmyadmin/ on this server.
  Apache/2.4.9 (Win32) PHP/5.5.12 Server at 192.168.1.8 Port 80"

Please note that I trying to access another PC Localhost not my PC Localhost.
I am tried each and every thing to solve this problem can not solve that problem.
I change httpd.conf file according to required changes
i.e Require local to Require all granted.
I also change in phpmyadmin.conf file
i.e Deny from all to Require all granted
but not improve the problem
Please tell me the solution of that problem.

A: phpMyAdmin is secured in its Alias definition in WAMPServer by default, to protect the beginner from accidentally giving access to things without understanding the consequences.
So to allow another PC on your internal network to access phpMyAdmin on the server PC you will need to edit  \wamp\alias\phpmyadmin.conf
It should look something like this :
Alias /phpmyadmin "c:/wamp/apps/phpmyadmin4.6.0/"

<Directory "c:/wamp/apps/phpmyadmin4.6.0/">
    Options Indexes FollowSymLinks MultiViews
  AllowOverride all
  <ifDefine APACHE24>
        Require local
    </ifDefine>
    <ifDefine !APACHE24>
        Order Deny,Allow
        Deny from all
        Allow from localhost ::1 127.0.0.1
    </ifDefine>

# To import big file you can increase values
  php_admin_value upload_max_filesize 128M
  php_admin_value post_max_size 128M
  php_admin_value max_execution_time 360
  php_admin_value max_input_time 360
</Directory>

Amend it to this to allow access
Alias /phpmyadmin "c:/wamp/apps/phpmyadmin4.6.0/"

<Directory "c:/wamp/apps/phpmyadmin4.6.0/">
    Options Indexes FollowSymLinks MultiViews
  AllowOverride all
  <ifDefine APACHE24>
        Require local
        Require ip 192.168.1                   <-- New Line
    </ifDefine>
    <ifDefine !APACHE24>
        Order Deny,Allow
        Deny from all
        Allow from localhost ::1 127.0.0.1
        Allow from 192.168.1                    <-- New Line
    </ifDefine>

# To import big file you can increase values
  php_admin_value upload_max_filesize 128M
  php_admin_value post_max_size 128M
  php_admin_value max_execution_time 360
  php_admin_value max_input_time 360
</Directory>

If you are using Apache 2.4.x you only need the first new line
If you are using Apache 2.2.x you only need the second new line

NOTE: Never use Require all granted or Allow from all unless that is actually what you intend to do i.e. give access to anyone in the universe!


text:
Q: jQuery set current Date to input type="datetime-local" I have the following html
<input type="datetime-local" id="startDate">

with the default format: dd.mm.yyyy mm:hh
I would like to set it`s default value to the current local time of my client with jQuery.
So far I have tried different solutions on this page but nothing worked.
For example
$("#startDate").val(new Date().getTime() / 1000 | 1);
$("#startDate").val(new Date().toDateString());

Can you please help me?

A: Assuming that you want to set the current date:
$("#startDate").val(new Date().toJSON().slice(0,19));


text:
Q: How to plot a legend for the color coded density scatter plot? I am making a scatter plot with color coded density with this code :
d1 = densCols(newData_cut,
          colramp = colorRampPalette(c("navy
         blue","yellow","firebrick","firebrick"),
                                     space = "Lab"))

ggplot(newData_cut) +
   geom_point(aes(x=green, y= blue, col = d1), size = 1) +
   xlim(0, 0.4)+
   ylim(0,2)

But when I get the image it looks like this:

Can somebody help me to plot a proper legend with a color representing the count / density of the points?
> dput(head(newData_cut))
structure(list(green = c(0, 0.229804, 0, 0, 0, 0), blue = c(0.080264,
0.204474, 0.04059, 0.040284, 0.042421, 0.041505), width = c(1317,
4529, 1, 10, 23, 5)), .Names = c("green", "blue", "width"), row.names =
c(NA,
6L), class = "data.frame")


text:
Q: To use break in a for loop or not? Just one quick question, say, Car class extends HashMap(String, String).
1.
for (Car car : carList) {
    if (car.isEmpty) {
        break;
    }
    doSomething();
}

2.
for (Car car : carList) {
    if (!car.isEmpty) {
        doSomethingElse();
    }
}

Which of the above two is better?
Thanks.
---- edited ----
Sorry I did not make my point clear.
The doSomething() method is actually doing different things.
I've changed them to doSomething() and doSometingElse().
My question is, will you put all the process in one if()? or first break the loop if the if() condition does not satisfy.
Thanks.

A: They do completely different things. The former will stop iterating as soon as the condition is true, whereas the latter will merely skip the processing during the iterations where the condition is false.
Changing the break to continue in the first will make them work the same way.

A: They do completely different things. First one will stope after seeing first empty car. Second version will 'do something' for each non-empty car. I think, you might want to use continue operator instead of break.

A: These 2 loops don't do the same thing

*

*will terminate the loop the first time it finds an empty car with isEmpty skipping any cars after the first empty one.  You can make this work like 2. if you change 'break' to 'continue'

*will doSomething for all not-empty cars.

A: Depends on what are you trying to do, the first loop will end as soon as the condition is meet, while the second one will iterate throuh all the hashmap.

A: If you actually meant "continue" and not "break", then I'd say not using continue or break is better.
It's not a huge deal, but statements like continue, break and return are all essentially goto statements that have been dressed up a little.  Instead of goto a line or goto a label they goto the top or bottom of a control structure--it makes the programmer have to think a little bit when they track it which means wasted time and additional chances for errors.
It's not a terribly big deal, and many times these structures will actually clarify your code, but if you have a choice and they seem to do essentially the same thing, go the way that doesn't involve sending control elsewhere.

A: If you want different behavior based on if the car is empty or not, you can use an if else statement.  Use break if you want to stop iterating carList.
for (Car car : carList) {
   if (car.isEmpty) {
      doSomething();
   }
   else {
      doSomethingElse();
   }
}

A: As everyone has pointed out, the break version will exit early.
The answer then depends on what you want it to do.
If you've finished doing what you need to do then break out as soon as you're done.  Why waste CPU cycles?  on the other hand if you must go through the whole list to dosomethingelse() then don't break out.
Were you meant to have two different named functions or should they both be called dosomething() ?

A: Is this what you're looking for?
for (Car car : carList) {
    if (car.isEmpty) {
         doSomething();
    }
    else {
         doSomethingElse();
    }
}

Or are you looking for
for (Car car : carList) {
    if (car.isEmpty) {
       break;
       //STOP ITERATING THROUGH THE REST OF THE LIST
       //(doSomething & soSomethingElse may have been called a few times already)
    }
    else {
        doSomething();
    }
    doSomethingElse();
}

There are other options as well, your clarification still isn't clear... to me anyway...


text:
Q: My website won't scroll on mobile in laravel I have already tested some small things but I can't figure it out.
The website is built in Laravel and uses the nicescroll.js script (I suspect this to be the problem), but I hasn't figured out how to correctly disable it. Simply removing the script will render the site unable to scroll so I think there is an event binder somewhere but I can't find it.
On regular browsers it works fine and scrolls, however on mobile you can only scroll a tiny bit and then if won't let you go further.
If you want to test, the domain is https://develop.fromdoortodoor.nl/
Any suggestions or tips with nicescroll plugin?

A: The niceScroll code is currently available in your custom.js file and is triggered on $(document).ready, as follows:
$('html').niceScroll({
        cursorcolor: "#000",
        cursorborder: "0px solid #fff",
        railpadding: {
            top: 0,
            right: 0,
            left: 0,
            bottom: 0
        },
        cursorwidth: "10px",
        cursorborderradius: "0px",
        cursoropacitymin: 0.2,
        cursoropacitymax: 0.8,
        boxzoom: true,
        horizrailenabled: false,
        zindex: 9999
    });

I suggest to disable that portion of code if you really do not need it to be triggered or add a conditional statement for mobile devices.

A: The website seems to actually scroll fine on my mobile and I don't see a trace of nicescroll.js implementation.
I suggest that you paste a portion of your code or send more information like images.


text:
Q: Break at spaces and select string contianing numbers In python, I want a to convert this with regex
"Something 19.28 else" -> "19.28"
"Someone 18.16-one-0 other" -> "18.16-one-0"
It means, break at whitespaces and select the one containing numbers.
SOLUTION:
After some research I figured it out myself.
string = "Someone 18.16-one-0 other"
string = re.search('(?<=\s)\d.*?(?=\s|\Z)', string).group()

__________________________________________

output => 18.16-one-0

the function from python module re searches for the match in the argument passed after the pattern and return match object, then the .group() convert the match object to a string.
The regex (?<=\s)\d.*?(?=\s|\Z) can be broken into three parts

*

*(?<=\s) => this matches all string which contain space before them.

*\d.* => this matches the string exactly after the space.

*?(?=\s|\Z) => this matches only if the previous match contains a space (denoted by /s) or (denoted by |) EOL (end of line denoted as /Z).

Note: An extra ? is used before ( here. It is used to create a non-greedy lookahead, which ends at the first occurence, otherwise, it will continue matching all.
so, this searches for digits preceded by a space and followed by a space or end of line.
Thanks to the community for help.

A: Something like this seems to fit your question:
foo = 'foo 19.29 bar'
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

terms = foo.split()
converted = None

for i in terms:
    for j in numbers:
        if j in i:
            converted = i
            break

print(converted)

Hope this helps!

A: you can simply split the string and search for numbers in the string
import re
text = "Someone 18.16-one-0 other"

print(''.join([i for i in text.split() if re.search(r'\d', i)]))

>>> 18.16-one-0


text:
Q: Calculate the amounts in table (td) I am creating a web app in which I am fetching the data (expense of the employee).
I want to calculate the amount of all the td and print the amount.
I am  using angularjs for fetching the data.
Here is my table:

                Payment Id
                Date Of Issue
                Date Of Trainer
                Training Id
                Payment Mode
                Cheque/ UTR no
                Amount

                {{i.paymentid}}
                {{i.dateofissue}}
                {{i.dateoftransfer}}
                {{i.trainingid}}
                {{i.paymentmode}}
                {{i.chequeno}}
                {{i.amount}}

the column {{i.amount}} is fetching the amount spent on expenses here is my controller for the same
$http.get('/paymentrpt.asmx/expenseinforpt', {
                params: {
                    datefrm: $scope.datefrm,
                    dateto: $scope.dateto,
                    empname: $scope.emp
                }
            }).then(function (response) {

                $scope.getexpenseinfo = response.data.info;
                $scope.pageload = false;
            });

and my webservice where I am fetching the data:
[WebMethod]
        [ScriptMethod(UseHttpGet = true)]
        public void expenseinforpt(string datefrm, string dateto, string empname)
        {
            List<object> expenseinfo = new List<object>();
            SqlCommand cmd = new SqlCommand("prolltexpense", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Connection = con;
            con.Open();
            SqlParameter[] param = {
                new SqlParameter("@from",datefrm),
                new SqlParameter("@to",dateto),
                new SqlParameter("@trainer",empname)
            };
            cmd.Parameters.AddRange(param);
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                expenseinfo.Add(new
                {
                    trainingno = dr["trainingno"].ToString(),
                    expenseno=dr["expenseno"].ToString(),
                    expensehead=dr["expensehead"].ToString(),
                    amount=dr["amt"].ToString(),
                    remark=dr["remark"].ToString(),
                    claim=dr["gigeraccount1"].ToString()
                });
            }
            var json = js.Serialize(expenseinfo);
            Context.Response.Write("{" + '"' + "info" + '"' + ":" + json + "}");
            con.Close();
        }

and this is my stored procedure from where I am getting the amount:
CREATE PROCEDURE prolltexpense (@from varchar(50),@to varchar(50),@trainer varchar(50))

AS
BEGIN
select expense.trainingno,expense.expenseno,expense.expensehead,expense.amt,expense.remark,(case when expense.gigeraccount=1 then 'YES' when expense.gigeraccount=0 then 'NO' end) as gigeraccount1 from instructoreexpense left outer join sonvininsert on son
vininsert.sonvinid=instructoreexpense.sonvinid left outer join finalinstructoreexpense on finalinstructoreexpense.sonvinid=instructoreexpense.sonvinid join expense on sonvininsert.trainingno=expense.trainingno  where sonvininsert.date between convert(date
time,@from,105) and convert(datetime,@to,105) and sonvininsert.trainer=@trainer  order by sonvininsert.date

END

What do I need to do if I want to calculate the amount of the table?
This is how my table looks:
Training Id Expense No. Expense Head    Amount  Remark  Claim
16100800002 16100800002001  Conveyance  20  Kurla to Mumbra Return by train NO
16100800002 16100800002002  Conveyance  80  Mumbra stn. to School by auto Patrick, Kishan & me  NO
16100800002 16100800002003  Conveyance  45  School to Mumbra stn. by auto Patrick, Kisan & me   NO
16111800006 16111800006001  F&B 110 Dinner in train on 17th NO
16111800006 16111800006002  Conveyance  18  Residence to Vile parle stn. by auto on 17th    NO
16111800006 16111800006003  Travelling  150 Hotel to Guru Nanak school by auto  NO
16111800006 16111800006004  Travelling  30  Guru nanak school to hotel by sharing auto and bus  NO
16111800006 16111800006006  Conveyance  18  Vile parle to residence by auto on 19th NO
16111800006 16111800006005  F&B 287 Breakfast, Lunch & dinner   NO

(B) Payable
0

A: i dont know about angularjs but u can do it easily from sql-server
select sum (expense.amt) as totalamt
 from instructoreexpense left outer join sonvininsert on
sonvininsert.sonvinid=instructoreexpense.sonvinid left outer join finalinstructoreexpense on
finalinstructoreexpense.sonvinid=instructoreexpense.sonvinid join expense
on sonvininsert.trainingno=expense.trainingno   where sonvininsert.date
between convert(datetime,@from,105)
and convert(datetime,@to,105) and sonvininsert.trainer=@trainer

let me know if it gives you error because i use your given code and i don't know expense is int or varchar in your sql


text:
Q: How do I encode an URL? When I run my project I get the url http://localhost:5973/PageToPageValuePass/Default.aspx  I want to Encode the URL since sometimes I need to transfer data from page to page. When the urls are encoded then it increases the reliability.
Server.UrlEncode("http://www.google.com/c#");

I get this, but how do I use it to help me encode the url?

A: try this

*

*in ASP.NET

    Server.UrlEncode("http://www.google.com/c#");

*

*in WinForms using System.Web.dll

HttpUtility.UrlEncode("http://www.google.com/c#");

A: If your encoding parts of the path:
System.Uri.EscapeUriString("c#")

If your encoding 'arguments':
String.Format( "http://something/?test={0}", System.Uri.EscapeDataString("c#") );

A: Url encoding is used to ensure that special symbols included in a url (most likely in a querystring) are not mistakenly interpreted as those used in the parsing and processing of a url.  For example, the + symbol is used to indicate a space in a url.  However, if you were intending for a + symbol to be a part of your querystring then you would want to encode that querystring before sending it to a browser.
For example.  Imagine you have written a page that receives a math equation on the querystring and displays that equation on the page.
The url might be: http://yoursite.com/displayMath.aspx?equation=3+5
The + symbol in this case is intended to be a meaningful part of the equation.  However, without a UrlEncode it would be interpreted as representing a space.  Reading this value from the querystring on the receiving page would yield "3 5", which is not what was intended.
Instead of redirecting to that url directly, you would want to URL encode the request first.  You might write the following code:
string equation = "3+5";
string url = String.Format(@"http://yoursite.com/displayMath.aspx?equation={0}", equation);
string encodedUrl = Server.UrlEncode(url);
Response.Redirect(encodedUrl);
This would ensure that a subsequent Request.Querystring["equation"] would receive the equation intact because any special symbols would first be encoded.
I'm not sure I understand your use case for encoding urls.  If you could perhaps provide more information on what you are trying to achieve I will attempt to answer more fully.  For now I hope that this information is useful.

A: say you want to create a link with some parameters you  can use it as follows:
aspx:
Click Here
code behind:
myLink.Href = Page.ResolveClientUrl("~/MyPage.aspx") + "?id=" +
   Server.UrlEncode("put here what ever you want to url encode");

Or as in your question:
myLink.Href = "http://www.google.com/")+Server.UrlEncode("C#");

this will put in html:
<a id="myLink" runat="server" target="_self" href="http://www.google.com/c+c%23">


text:
Q: How can I play multiple sounds in C# simultaneously? I'm currently using the SoundPlayer of System.Media in my Windows Forms application, but thereby I can't play multiple sounds simultaneously. I know, there are already answered questions for this topic, but if I'm trying to use the Windows Media Player:
using System.Windows.Media

I get an error:

The "System.Windows.Media" is not found ("the type or namespacename "Media" is not available in the namespace Windows.Media")

I think there is missing an assembly, but I don´t know how to add it. Isn't there an easy way to play multiple sounds at the same time?

A:
Where can I find the solution explorer?

Use the Quick search in the menu bar:

It will tell you where to find the entry in the menu or which shortcut to use.

How do I add a reference?

Use the quick search in the menu bar:

It will tell you where to find the action in the menu.

"System.Windows.Media" is not found

Can't find System.Windows.Media namespace: it's part of PresentationCore.dll. Use the search box to find it quickly:

A: If you want to play multiple sounds in C# simultaneously, you can refer to the following steps:
First, right click on References in Solution Explorer an choose Add Reference.

Second, choose Windows Media Player you can search in the upper right corner.

Finally, you can use the following code:
using System;
using WMPLib;
namespace ConsoleApp3
{
    class Program
    {
        static void Main(string[] args)
        {
            var sound1 = new WindowsMediaPlayer();
            sound1.URL = @"path of sound1";
            var sound2 = new WindowsMediaPlayer();
            sound2.URL = @"path of sound2";
            Console.ReadLine();
        }
    }
}


text:
Q: Displaying sublass model name in Rails form helper shared by subclasses Given these models:
class Person
end

class Man < Person
  def edit
    @person     = Man.find(params[:id])

    respond_to do |format|
      format.js { render :template => "man_form" } }
    end
  end
end

class Woman < Person
  def edit
    @person     = Woman.find(params[:id])

    respond_to do |format|
      format.js { render :template => "woman_form" } }
    end
  end
end

Then in each form I create a 'select' of 'characteristics' using this helper method that is shared by all:
def person_select(person, options)
  select :person, "characteristics", options
end

How would I make this so that when it's called by one of the subclasses (Man or Woman), it creates the select name with the that model name, instead of the parent 'person'?
So, I want to be able to call:
person_select(@man_object, {...})

and get:
<select name="man[age]" id="man_age">
...
</select>

The reason I need to do this is so that when the form is submitted I can get params[:man] form the man_controller or params[:woman] from the woman_controller and be able to work with those specific object types, and not 'person'.
I could get the class name and do:
select person.class.to_s.underscore but then it doesn't use the object anymore, so the passed object won't be selected in the list.
Thanks!

A: You can ask which class it belongs to and then call the name of that class.
$ Post.first
=> #<Post id: 1>
$ Post.first.class
=> Post(id: integer, title: string)
$ Post.last.class.name
=> "Post"

What confuses me is that you have a @man_object so obviously the object is a man and that means you could just have two helpers assuming you would also have a woman object:
man_select(@man_object, {...})
woman_select(@man_object, {...})

And then your select_fields
def man_select(person, options)
  select_tag :man, "characteristics", options
end

def woman_select(person, options)
  select_tag :woman, "characteristics", options
end

But if you did not know if it was a man or woman:
man_select(@person, {...})

Then your select_tag:
def person_select(person, options)
    if person.class.name = "Man"
        select_tag :man, "characteristics", options
    else
        select_tag :woman, "characteristics", options
    end
end