text:
Q: Is it safe to write an unsigned byte array in network order directly to ip.ip_dest? In netinet/ip.h there is struct "ip" which is used to transmit IP packets. The address fields are "ip_src"  and "ip_dest".
If I have my IPv4 addresses in network order in an unsigned byte array, am I safe copying this array directly to ip_src and ip_dest?
For example, if I am sending a packet to 23.45.167.92 and I have the following unsigned char[4]:
destination_ip[0] = 23;
destination_ip[1] = 45;
destination_ip[2] = 167;
destination_ip[3] = 92;

Can I then safely do this:
struct ip my_packet_header;
my_packet_header.ip_dest = *((ip_addr*)destination_ip);

By "safely" I mean it will work on both big endian and little endian machines.

A: from man ip

The s_addr member of struct in_addr
         contains the host interface address in network byte order.

So you are ok copying bytes, but it's better to use a memcpy instead of the cast.
memcpy(&my_packet_header.ip_dest.s_addr, destination_ip);

A: Aside from endian, at least one concern exists: Alignment.
struct ip my_packet_header may have a more stringent alignment requirement than unsigned char destination_ip[]

A pointer to an object type may be converted to a pointer to a different object type. If the resulting pointer is not correctly aligned  for the referenced type, the behavior is
  undefined.   C11 §6.3.2.3 7

memcpy() handles that issue and eliminates woes @wildplasser
assert(sizeof my_packet_header >= sizeof destination_ip);
memcpy(&my_packet_header, destination_ip, sizeof destination_ip);

An optimizing compiler can be expected to analyze this memcpy() call and emit efficient code - possible without a true function call.


text:
Q: Issue while Unit Testing ASP.Net Core with Mediatr I am using ASP.Net Core 3.1 Repository Pattern and Unit of Work Using Dapper .
I have use mediator as
using MediatR;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;

namespace TaskManagementApp.Api.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ApiController : ControllerBase
    {
        private IMediator _mediator;
        protected IMediator Mediator => _mediator ??= HttpContext.RequestServices.GetService<IMediator>();
    }
}

i am facing issue how can i write unit test to set value for HttpContext.RequestServices.GetService
here is my controller to be unit tested
namespace OneCubeCoaching.API.WebApi.Controllers
{
    [Route("api/[controller]")]
    public class ContactController : BaseApiController
    {
        [Authorize]
        [HttpGet("GetAll")]
        public async Task<IActionResult> Index()
        {
            return Ok(await Mediator.Send(new GetAllClientQuery()));
        }
    }
}

A: Just depend on IMediator in the constructor.
Assuming your code you meant ApiController was in fact BaseApiController (per your second code segment) something like this will work:
[Route("api/[controller]")]
[ApiController]
public class BaseApiController : ControllerBase
{
    protected ApiController(IMediator mediator)
    {
        _mediator = mediator;
    }

    protected IMediator {get; private set;}
}

Then your ContactController can pass IMediator to base:
[Route("api/[controller]")]
public class ContactController : BaseApiController
{
    public ContactController (IMediator mediator)
        :base(mediator)

    [Authorize]
    [HttpGet("GetAll")]
    public async Task<IActionResult> Index()
    {
        return Ok(await Mediator.Send(new GetAllClientQuery()));
    }
}

Now, you can Mock IMediator as you normally would.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Windows shutdown not working as expected I'm trying to remotely shutdown computers in my lab with the commands:
shutdown /s /m 192.168.1.57
shutdown /s /m 192.168.1.56

Shutdown occurs properly when I run each command separately.  But when I combine them via:
shutdown /s /m 192.168.1.57 & shutdown /s /m 192.168.1.56

only one machine shuts down, then Windows gives an error:
The entered computer name is not valid or remote shutdown is not supported on the target computer. Check the name and then try again or contact your system administrator.(53)

Any ideas how to troubleshoot/resolve?

*

*same issue occurs when I combine the commands in a batch file.

*systems all running Win 7, connected to the same workgroup.

*bear in mind that I am not an IT professional.

Thanks in advance.

A: Another forum pointed me to a workaround/correct implementation.  I just need to put a "cmd /k" between the & and the 2nd command.  Still not sure why my ampersand combination didn't work.

A: there is nothing like (&) to combined the command.. I don't think you can do it like this.
You have to write the address with separate shutdown command.  CMD doesn;t provide such a way to concatenate or pass array or arguments..


text:
Q: How do I test whether a tree has a perfect matching in linear time? Give a linear-time algorithm to test whether a tree has a perfect matching,
that is, a set of edges that touches each vertext of the tree exactly once.
This is from Algorithms by S. Dasgupta, and I just can't seem to nail this problem down. I know I need to use a greedy approach in some manner, but I just can't figure  this out. Help?
Pseudocode is fine; once I have the idea, I can implement in any language trivially.
The algorithm has to be linear in anything. O( V + E ) is fine.

A: I think I have the solution. Since we know the graph is a tree, we know of the existance of leaf nodes, nodes with one edge and no children. In order for this node to be included in the perfect matching, that edge MUST exist in the final solution.
Ergo, we can find all edges connecting to a leaf node, add to the solution, and remove the touched edges from the graph. If, at the end of this process, we are left any remaining nodes untounched, there exists no perfect matching.

A: In the case of a "graph",
The first step of the problem should be to find the connected components.
Since every edge in the final answer connect two vertices, they belong to at most one of the connected components.
Then, the perfect matching could be found for each connected component.

A: Linear in what?  Linear in the number of edges, keep the edges as an ordered incidence list, ie, every edge (vi, vj) in some total order.  Then you can compare the two lists in O(n) of the edges.

A: The working algorithm would be something as follows:
For each leaf in the tree:
  add edge from leaf to its parent to the solution
  delete edge from leaf to its parent
  delete all edges from the parent to any other vertices
  delete leaf and parent from the tree

If the tree is empty then the answer is yes. Otherwise, there's no perfect matching.

A: I think that it's a simplified problem of finding a Hamiltonian path in a graph:
http://en.wikipedia.org/wiki/Hamiltonian_path
http://en.wikipedia.org/wiki/Hamiltonian_path_problem
I think that there are many solutions on the internet to this problem, but generally finding Hamilton cycle is a NP problem.


text:
Q: Django web application Taking user input and processing it I am building a web application using django. I need to take a string input from the user and process it using a method I have written myself. How to achieve this in Django? Here are the things I need to do

*

*Get User Input userinput = (string) On start page

*Put this string as an argument in my method MyMethod(userinput) and Run it in the backend

*Display what MyMethod() returns on another page.

A: I suggest that you start from django tutorial: https://docs.djangoproject.com/en/1.9/intro/tutorial01/
Basically, what you are going to need is form with one text field, HTML template that will render the form, view that will render HTML template with instance of a form when GET request arrives and call your MyMethod with value from form when POST request arrives and URL rule to call your view function on some URL.
Without additional data or any attempt to solve it and concrete problem you encounter - I can hardly offer more help.

A: You need to create a model with fields which you want to update by user input, then create a form based on this model. Then import this in a view and render it in a template
simple example:
forms.py:
class InputForm(forms.ModelForm):

    class Meta:
        model = YourModel
        fields = ['fields_from_YourModel']

views.py:
from .forms import InputForm

def user_input(request):
    input = CustomUser.objects.get(pk=request.user.pk)
    if request.POST:
        form = ProfileForm(request.POST, instance=input)
        if form.is_valid:
            form.save()
    else:
        form = ProfileForm()
    return render(request, 'input.html', {'form':form})

Other steps more easier for beginner, you'll find examples in docs


text:
Q: global React functions that utilize hooks I have a function called scheduleShortcut that gets used in a couple places throughout an application. Initially, this function was local to the specific components but since it is being used multiple times, I want to refactor this function into a global function.
At first, I tried to do the following:
const history = useHistory();
const dispatch = useDispatch();

export const scheduleShortcut = (jobId: number) => {
  dispatch(jobGanttFocus(jobId));
  dispatch(focusJobScheduleFilter(jobId));
  dispatch(toggleScheduleView('jobs'));

  history.push('/schedule');
};

However, when I do this, I get an error that says I can't use useHistory or useDispatch unless they are inside a React component or a custom hook. Then, I tried to convert scheduleShortcut into a custom hook in the following way:
export const useScheduleShortcut = (jobId: number) => {
  const history = useHistory();
  const dispatch = useDispatch();

  dispatch(jobGanttFocus(jobId));
  dispatch(focusJobScheduleFilter(jobId));
  dispatch(toggleScheduleView('jobs'));

  history.push('/schedule');
};

This allowed me to utilize useDispatch and useHistory. However, when I try to call this function inside the specific components I need it in, I get a similar error. Basically, it says that I cannot use my custom hook (i.e. useScheduleShortcut) inside a callback.
<Roster
  jobId={job.id}
  assignWorkers={canAssignWorker ? handleAssignWorkers : undefined}
  scheduleShortcut={() => useScheduleShortcut(jobId)}
/>

Is there a way I can get around these errors and use scheduleShortcut as a recyclable function? Or is this in fact not possible since I am using the hooks?

A: Hooks in fact must be called on top level, you are breaking that rule
You could expose(return) a function from hook that could be called as callback afterwards.
i.e.
export const useScheduleShortcut = () => {
  const history = useHistory()
  const dispatch = useDispatch()

  const dispatchScheduleShortcut = (jobId) => {
    dispatch(jobGanttFocus(jobId))
    dispatch(focusJobScheduleFilter(jobId))
    dispatch(toggleScheduleView('jobs'))
    history.push('/schedule')
  }

  return {
    dispatchScheduleShortcut
  }
};

and then use it as
const { dispatchScheduleShortcut } = useScheduleShortcut()

return (
  <Roster
    jobId={job.id}
    assignWorkers={canAssignWorker ? handleAssignWorkers : undefined}
    scheduleShortcut={() => dispatchScheduleShortcut(jobId)}
  />
)


text:
Q: html email with inline images not rendered properly in iphone I was hoping someone could help me out what I'm doing wrong in the below code - my email get sent, with the image inlined properly in most email client (gmail web, android), but it does not render properly on an iphone/ipad: only the last attached picture is displayed, without any html content or text content displayed. I understand every email client interprets and renders the payload differently, I don't know how to make it work on an iphone.
Any help appreciated!
ruby code:
require 'mail'

def inline_body_with_attachments(html, attachments)
    attachments.each do |attachment|
        if (html =~ /#{attachment.filename}/)
            html = html.sub(attachment.filename, "cid:#{attachment.cid}")
        end
    end
    return html
end

mail = Mail.new({
    :from    => "foo@bar.com",
    :to      => "you@gmail.com",
    :subject => "html email with inline images"
})

text_part = Mail::Part.new do
    body "some text"
end

mail.text_part = text_part

# Load the attachments
attachment = "image.png"
mail.attachments[attachment] = File.read(attachment)

inline_html = inline_body_with_attachments("An inline image", mail.attachments)

html_part = Mail::Part.new do
    content_type 'text/html; charset=UTF-8'
    body         inline_html
end

mail.html_part  = html_part
mail.deliver!

The email looks like:
Date: Fri, 24 May 2013 13:58:02 +0000
From: foo@bar.com
To: you@gmail.com
Message-ID: <519f71eab9175_2a1d9e0764742c@foo.com.mail>
Subject: test mail with attachment- raw
Mime-Version: 1.0
Content-Type: multipart/alternative;
 boundary="--==_mimepart_519f71eab2260_2a1d9e076471d6";
 charset=UTF-8
Content-Transfer-Encoding: 7bit

----==_mimepart_519f71eab2260_2a1d9e076471d6
Date: Fri, 24 May 2013 13:58:02 +0000
Mime-Version: 1.0
Content-Type: text/plain;
 charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-ID: <519f71eab3e04_2a1d9e076472b9@foo.com.mail>

some text

----==_mimepart_519f71eab2260_2a1d9e076471d6
Date: Fri, 24 May 2013 13:58:02 +0000
Mime-Version: 1.0
Content-Type: text/html;
 charset=UTF-8
Content-Transfer-Encoding: 7bit
Content-ID: <519f71eab692b_2a1d9e076473d4@foo.com.mail>

An inline image

----==_mimepart_519f71eab2260_2a1d9e076471d6
Date: Fri, 24 May 2013 13:58:02 +0000
Mime-Version: 1.0
Content-Type: image/png;
 charset=UTF-8;
 filename=image.png
Content-Transfer-Encoding: base64
Content-Disposition: attachment;
 filename=image.png
Content-ID: <519f71eab047e_2a1d9e07647047@foo.com.mail>

iVBORw0KGgoAAAANSUhEUgAAASwAAABaCAYAAAACcWsdAAAXUUlEQVR4nGJk
[.... more image encoding ...]
DhwFowAXGE0go2CQAAAAAAD//wMAFOkCtHNhXPkAAAAASUVORK5CYII=

----==_mimepart_519f71eab2260_2a1d9e076471d6--

A: In order to wrok on the iphone, I had to wrap the html content with the image into their own multipart/related part.
require 'mail'

def inline_body_with_attachments(html, attachments)
    attachments.each do |attachment|
        if (html =~ /#{attachment.filename}/)
            html = html.sub(attachment.filename, "cid:#{attachment.cid}")
        end
    end
    return html
end

mail = Mail.new({
    :from    => "demo@etsy.com",
    :to      => "nkammah@etsy.com",
    :subject => "test mail with attachment- raw4",
    :content_type => 'multipart/alternative'
})

text_part = Mail::Part.new do
    body "some text"
end

mail.add_part( text_part)

other_part = Mail::Part.new do
  content_type 'multipart/related;'
end

# Load the attachments
attachment = "image.png"
#mail.attachments[attachment] = File.read(attachment)
other_part.add_file(attachment)

inline_html = inline_body_with_attachments("An inline image", other_part.attachments)
html_part = Mail::Part.new do
    content_type 'text/html; charset=UTF-8'
    body         inline_html
end
other_part.add_part(html_part)

mail.add_part(other_part)

mail.deliver!

A: I'm not sure if this is helpful, but I pretty much followed your code, and it works on my iPhone 5. I'm sending to a Microsoft Exchange server.
require 'mail'

mail = Mail.deliver do
    to 'myaddress@domain.com'
    from 'test@domain.com'
    subject 'Inline Image test'

    add_file './banner.png'

    pic = attachments['banner.png']

    html_part do
        content_type 'text/html; charset=UTF-8'
        body ""
    end

end

Hope this helps.


text:
Q: Spring Boot, Cors and Spring Security I am using Spring Boot version 2.0.8.RELEASE and the spring-boot-start-security module.
I am trying to protect my swagger endpoints with basic authentication and so far everything is going good.
However, requests from javascript in my code have started failing with the following error
Access to XMLHttpRequest at 'http://my-service.com.com/search/api/getQuery' from origin 'http://myui.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.

I have the following configuration class defined
@Configuration
@EnableWebMvc
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        //See https://docs.spring.io/spring/docs/current/spring-framework-reference/web.html#mvc-cors-global-java for configuring cors
        registry.addMapping("/**").allowedOrigins("*").allowedMethods("*").allowedHeaders("*");
    }

}

I have the @CrossOrigin annotation on my API Class.
And I have the following class to configure my security
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    protected void configure(HttpSecurity http) throws Exception {
        http.cors()
             .and()
             .csrf().disable()
                .authorizeRequests()
                    .antMatchers("/v2").authenticated()
                    .antMatchers("/swagger-resources").authenticated()
                    .antMatchers("/swagger-ui.html").authenticated()
                    .and()
                    .httpBasic()
                    .and()
                    .authorizeRequests()
                        .antMatchers("/**").permitAll()
                        .and();

    }

    }

I tried creating a CorsConfiguration in the security class and removing the @CrossOrigin annotation but that didnt work either.
Any idea what I need to do in order to get cors working correctly on Spring Boot 2.0.8.RELEASE?
Thanks
Damien

A: In my experience the Spring Annotations never successfully resolve the CORS issue.
The solution that I have preferred is routing both servers (in my case Node and Tomcat) through a virtual host.
In my Apache httpd-vhosts config file, I have the following setup.
    ProxyRequests Off
    ProxyPreserveHost Off
    <Proxy *>
        Order deny,allow
        Allow from all
    </Proxy>

    <Location /FrontEndServer>
        ProxyPass        http://localhost:8080/FrontEndServer connectiontimeout=333 timeout=999
        ProxyPassReverse http://localhost:8080/FrontEndServer
    </Location>

    <Location />
        ProxyPass        http://localhost:3000/ connectiontimeout=333 timeout=999
        ProxyPassReverse http://localhost:3000/
    </Location>

In this setup, my two servers are running on different ports, but Apache is rerouting them so that they can share my localhost and be differentiated simply by "/" or "/FrontEndServer".
Obviously this is specific to Apache, and that may not be the setup you are using. You should however be able to use these principles to find a solution for your specific situation. Hope this helps.


text:
Q: Enabling Smart Touch remote as mouse/touch pad input In the web browser that comes with the Samsung ES8000, mouse/touch pad support is possible through the Smart Touch remote.
I'm developing a Flash-based app and need to support mouse input. The TV allows for external mouse input, which I can get working through <mouse>y</mouse> in config.xml.
It also, apparently, exposes an external mouse input API, which I haven't played with:

*

*http://www.samsungdforum.com/Guide/View/Developer_Documentation/Samsung_SmartTV_Developer_Documentation_3.1/API_Reference/JavaScript_APIs/Interactive_Remote_API/mousepad
Telling my users they have to connect an external mouse to use the app is obviously not nice. Is it possible to enable the Smart Touch remote as a mouse/touch pad in other apps? I've searched the Samsung Guide docs and Google but cannot find any reference to it.


text:
Q: How to change only the maximum value of a group which only have sum of certain number in pandas dataframe I have following dataset
Item Count
A    60
A    20
A    21
B    35
B    33
B    32
C    40
C    40
C    10

Code to reproduce:
import pandas as pd
df = pd.DataFrame([
    ['A', 60],
    ['A', 20],
    ['A', 21],
    ['B', 35],
    ['B', 33],
    ['B', 32],
    ['C', 40],
    ['C', 40],
    ['C', 10],
],
    columns=['Item', 'Count'])

so here we can see Sum of Item column is: A: 101, B: 100, C:90
Now I want sum of all group of column "Item" to be 100 or less than 100 and reduce the extra number from the highest value of group.
The output should be like this:
Item Count
A    59
A    20
A    21
B    35
B    33
B    32
C    40
C    40
C    10

I tried.
idx = df.groupby("Item")["Count"].idxmax()
df.loc[idx, "Count"] -= ((df.groupby(['Item'])['Count'].transform(lambda x: x.sum())) - 100)

but all the groups highest value was subtracted by 100. I was unable to use IF condition only for group which has sum of more than 100

A: The code checks each row to see if the grouped sum is greater than 100, and if it is it looks for the maximum value in the group and reduces it by the difference between the sum and 100. All this is captured within the assign method.
(
    df.assign(
        counter=df.groupby("Item").Count.transform("sum"),
        maximum=df.groupby("Item").Count.transform("max"),
        Count=lambda x: np.where(
            x.counter.gt(100) & (x.Count.eq(x.maximum)),
            x.Count.sub(x.counter.sub(100)),
            x.Count,
        ),
    ).iloc[:, :2]
)

  Item  Count
0   A   59
1   A   20
2   A   21
3   B   35
4   B   33
5   B   32
6   C   40
7   C   40
8   C   10

A: Use df.transform with groupby:
>>> df.assign(
              Count=
                     df.groupby('Item',as_index=False)
                       .transform(lambda x:
                                  x.where(x!=x.max(), x-(x.sum()-100)) if x.sum()>100
                                                                      else x)
              )
  Item  Count
0    A   59.0
1    A   20.0
2    A   21.0
3    B   35.0
4    B   33.0
5    B   32.0
6    C   40.0
7    C   40.0
8    C   10.0


text:
Q: WPF binding not working in Windows XP I have the following class:
public abstract class TestBase<T> : INotifyPropertyChanged where T : class
{
    private static T _instance;
    public event PropertyChangedEventHandler PropertyChanged;

    public static T Instance
    {
        get
        {
            lock (Lock)
            {
                var instance = _instance ?? (Activator.CreateInstance<T>());

                _instance = instance;
                return instance;
            }
        }
    }

    // ReSharper disable once StaticMemberInGenericType
    public static object Lock = new object();

    protected virtual void OnPropertyChanged(string propertyName)
    {
        var handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

public class Test : TestBase<Test>
{
    private bool _isDone = true;

    public bool IsDone
    {
        get
        {
            return _isDone;
        }
        set
        {
            _isDone = value;
        }
    }
}

Then, I have this declared in the xaml:
<lib:Test x:Key="Test" />

And used like this:
IsChecked="{Binding Source={StaticResource Test}, Path=Instance.IsDone}"

This is working fine on Vista and higher, but not on XP, it just doesn't bind (falls back to the default value). We wish we could ditch XP but this isn't the case. I tried to find a little more information with Snoop but it crashes on all our XP machines. I'm shooting blanks here and run out of ideas so I'm curious if anyone here has any ideas about this problem.
As a workaround I can add something like this to the Test class:
public static Test InstanceXP
{
   get
   {
       return Instance;
   }
}

But this is a terrible workaround.

A: I magically stumbled upon another workaround that does work on Windows XP.
Instead of declaring it in a <...Resources>, use the following notation instead:
 {Binding Source={x:Static lib:Test.Instance}, Path=IsDone}

This is working correctly on all Windows versions.


text:
Q: Firebase auth and sign out My app uses both e-mail and Google Auth. The problem appears if the user signs out and tries logging in. App closes and, when clicked again, opens with the user logged in. If I press the back button from the login screen and exit the app, when launched again works as expected.
Here is the code I use for signing out:
@Override
public boolean onOptionsItemSelected(MenuItem item) {

    int id = item.getItemId();

    if (id == R.id.getOut) {
        mFirebaseAuth.getInstance().signOut();
        DetachReadListener();
        finishAffinity();
        return true;
    }

    return super.onOptionsItemSelected(item);
}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == RC_SING_IN) {
        if (resultCode==RESULT_CANCELED) {
            finishAffinity();
        }
    }

}

Android Monitor shows no error so I don't have any clue on this. Please help me solve this bug.
Thank you!
My login code:
 public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {

            FirebaseUser user = mFirebaseAuth.getCurrentUser();

            if (user!=null) {

                 uid = user.getUid();

                if (user.getPhotoUrl()!=null) {
                    avatarurl = user.getPhotoUrl().toString();
                    RoundedBitmapDrawable drawable = RoundedBitmapDrawableFactory.create(getApplicationContext().getResources(),getImageBitmap(avatarurl));
                    drawable.setCircular(true);
                    imgavatar.setImageDrawable(drawable);
                 //   imgavatar.setImageBitmap(getImageBitmap(avatarurl));
                } else
                    imgavatar.setImageResource(R.drawable.ic_account_black_48dp);

                mUsername = user.getDisplayName();
                username.setText(mUsername);
                AttachReadListener();
                DatabaseReference usruid = usersref.child(uid).child("flag");

                usruid.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {

                        while (!dataSnapshot.exists()) {
                            pb.setContentView(R.layout.activity_progress_bar);
                            pb.requestWindowFeature(Window.FEATURE_NO_TITLE);
                            pb.show();
                        }
                        val = dataSnapshot.getValue(String.class);
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {

                    }
                });

            } else {
                startActivityForResult(
                        AuthUI.getInstance()
                        .createSignInIntentBuilder()
                                .setIsSmartLockEnabled(false)
                                .setTheme(R.style.LoginTheme)
                                .setLogo(R.drawable.firstlogo)
                        .setAvailableProviders(Arrays.asList(new AuthUI.IdpConfig.Builder(AuthUI.EMAIL_PROVIDER).build(),new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build()))
                        .build(), RC_SING_IN

                );

            }
        }
    };

A: As you said you are using both e-mail and google sign in. So, if the user is signed in with e-mail method then use FirebaseAuth.getInstance().signOut().
If the user is signed in using google sign in then sign out the user from both Google Sign-In and Firebase like:
 googleSignInClient.signOut().addOnCompleteListener(this,
            new OnCompleteListener<Void>() {
                @Override
                public void onComplete(@NonNull Task<Void> task) {
                    // firebase sign out
                    FirebaseAuth.getInstance().signOut();

                    Intent intent = new Intent(SignOutActivity.this, MainActivity.class);
                    startActivity(intent);
                    finish();

                }
            });


text:
Q: How do query all documents of a collection in Fire Store I am trying to display information from Cloud Firestore on Google maps. I am able to apply a marker from a document using the below code, however I have multiple documents that I need to display the data from.
Below is the current code and as I said it successfully displays a marker with info from one document, however every document contains a different location that needs to be displayed on the map.
    private void addMapMarkers(){

    FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
    CollectionReference pointsRef = rootRef.collection("notes");
    DocumentReference docRef = pointsRef.document("u20UmWSrlP0EiZH9CNP3");
    docRef.get().addOnCompleteListener(new
    OnCompleteListener<DocumentSnapshot>() {
        @Override
        public void onComplete(@NonNull Task<DocumentSnapshot> task) {
            if (task.isSuccessful()) {
                DocumentSnapshot document = task.getResult();
                if (document.exists()) {
                    String latitude = document.getString("Latitude");
                    String longitude = document.getString("Longitude");
                    String name = document.getString("Attraction Name");

                    float lat = Float.parseFloat(latitude);
                    float lng = Float.parseFloat(longitude);

                    LatLng latLng = new LatLng(lat, lng);
                    mMaps.addMarker(new
                    MarkerOptions().position(latLng).title(name));
                }
            }
        }
    });
}

Database Structure like below :

A: If You want to all document data you can try this:-
db.collection("Chat").addSnapshotListener(new EventListener<QuerySnapshot>() {
            @Override
            public void onEvent(@Nullable QuerySnapshot queryDocumentSnapshots, @Nullable FirebaseFirestoreException e) {
                for (DocumentChange dc : queryDocumentSnapshots.getDocumentChanges()) {
                    switch (dc.getType()) {
                        case ADDED:
                            //  Log.d("TAG", "New Msg: " + dc.getDocument().toObject(Message.class));

                            break;
                        case MODIFIED:

                            //      Log.d("TAG", "Modified Msg: " + dc.getDocument().toObject(Message.class));
                            break;
                        case REMOVED:
                            //     Log.d("TAG", "Removed Msg: " + dc.getDocument().toObject(Message.class));
                            break;
                    }
                }
            }
        });

A: To get the values of your latitude and longitude properties of all documents, simply use the following lines of code:
FirebaseFirestore rootRef = FirebaseFirestore.getInstance();
CollectionReference notesRef = rootRef.collection("notes");
notesRef.get().addOnCompleteListener(new OnCompleteListener<QuerySnapshot>() {
    @Override
    public void onComplete(@NonNull Task<QuerySnapshot> task) {
        if (task.isSuccessful()) {
            for (QueryDocumentSnapshot document : task.getResult()) {
                float lat = Float.parseFloat(document.getString("Latitude"));
                float lng = Float.parseFloat(document.getString("Longitude"));
                String name = document.getString("Attraction Name");
                LatLng latLng = new LatLng(lat, lng);
                mMaps.addMarker(new MarkerOptions().position(latLng).title(name));
            }
        }
    }
});

So the key for solving this problem is the use of task.getResult() that can help you iterate through the QueryDocumentSnapshot object.


text:
Q: How to add a reference to C:\Windows\Microsoft.NET\assembly How can I reference a .NET assembly deployed in c:\windows\microsoft.net\assembly from Visual Studio IDE?
If i do right click on References/Add Reference, it only shows the c:\windows\assembly content.
How do I add a reference to new GAC path (c:\windows\microsoft.net\assembly)?

A: *

*Go to the location via CMD C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0A\bin\NETFX 4.0 Tools

*Type Gacutil -i {Path of the dll}
OR
Open visual studio commond promt and type Gacutil -i {Path of the dll}

A: It's working by adding a reference to:
C:\Windows\Microsoft.NET\assembly\GAC_MSIL\\
I don't know if it is the better way to do it but it seems to do the job.
For registering the DLL in another environment, I used the following sentence:
"%ProgramFiles(x86)%\Microsoft SDKs\Windows\v8.1A\bin\NETFX 4.5.1 Tools\gacutil.exe" /i  /f
Hope it helps.


text:
Q: How to render WebBrowser to device context? i want to render a web-page (i.e. TWebBrowser) to a device context. i want to use Internet Explorer's layout engine to render content to a device context (i.e. metafile, pdf metafile).

Starting with Internet Explorer 9 the IHTMLElementRender interface is no longer supported:

IHTMLElementRender interface
Use this interface to draw the contents of an element to a specified device context, normally a printer.
Members
  The IHTMLElementRender interface inherits from the IUnknown interface but does not have additional members.

To the point that they no longer mention that the DrawToDC method even exists:

IHTMLElementRender::DrawToDC Method
Deprecated. Draws the contents of the element to the specified device context.
Syntax
HRESULT DrawToDC(
     HDC hDC
);

Parameters

*

*hDC
   [in] An HDC specifying the device to be drawn to, typically a printer.

  Return Value
Returns S_OK if successful, or an error value otherwise.
Remarks
As of Windows Internet Explorer 9, this method is deprecated and should not be used.
With some printers, running IHTMLElementRender::DrawToDC may cause problems. You can ensure that IHTMLElementRender::DrawToDC works properly on all printers by running IHTMLElementRender::SetDocumentPrinter method first, and then passing the modified device context to IHTMLElementRender::DrawToDC.

Note: I'm quoting all the documentation so that it can still be found when Microsoft finally removes it from MSDN altogether. Along with the interface declaration:
IHTMLElementRender = interface(IUnknown)
   ['{3050F669-98B5-11CF-BB82-00AA00BDCE0B}']
   function DrawToDC(hdc: HDC): HResult; stdcall;
   function SetDocumentPrinter(const bstrPrinterName: WideString; hdc: HDC): HResult; stdcall;
end;

Use the IViewObject interface
i've tried converting to use the IViewObject (e.g. How to render HTML element without using web browser?):
procedure RenderWebBrowserToMetafile(Browser: TWebBrowser; Metafilename: string);
var
    view: IViewObject;
    m: TMetafile;
    mc: TMetafileCanvas;
    w, h: Integer;
    r: TRect;
    dpix: Integer;
    dpiy: Integer;
    dc: HDC;
begin
    w := WebBrowserScrollWidth(Browser);
    h := WebBrowserScrollHeightStrict(Browser);

    //96dpi screen to 300dpi metafile (destined for printer)
    dc := GetDC(0);
    try
        dpix := GetDeviceCaps(GetDC(0), LOGPIXELSX);
        dpiy := GetDeviceCaps(GetDC(0), LOGPIXELSY);
    finally
        ReleaseDC(0, dc);
    end;
    w := MulDiv(w, 300, dpix);
    h := MulDiv(h, 300, dpiy);

    view := Browser.Document as IViewObject;

    m := TMetafile.Create;
    try
        m.Width := w;
        m.Height := h;
        r := Rect(0, 0, w, h);

        mc := TMetafileCanvas.Create(m, 0);
        try
            view.Draw(
                    DVASPECT_CONTENT, //draw aspect
                    1, //index
                    nil, //pAspectInfo
                    nil, //pDVTargetDevice
                    0, //Target Device Context
                    mc.handle, //hdcDraw
                    @r, //target Bounds
                    @w, //window bounds (for metafiles)
                    nil, //continue function
                    0); //continue value
        finally
            mc.Free;
        end;
        m.SaveToFile(Metafilename);
    finally
        m.Free;
    end;
end;

The problem with this code is that it only renders the visible area of the browser (i.e. without scrolled content):
i need to render the entire web-page (e.g. for printing).
i tried changing the draw aspect from DVASPECT_CONTENT (as this example does), to DVASPECT_DOCPRINT:

DVASPECT_DOCPRINT
  Provides a representation of the object on the screen as though it were printed to a printer using the Print command from the File menu. The described data may represent a sequence of pages.

With the same result; rather than rendering the page, only the visible portion is rendered:
How can i ask the IE9 rendering engine to render?

i also tried using different indexes along with DVASPECT_DOCPRINT. Although IViewObject is not documented, maybe that's how you print different "pages":
view.Draw(DVASPECT_DOCPRINT, 1, ...);
view.Draw(DVASPECT_DOCPRINT, 2, ...);
view.Draw(DVASPECT_DOCPRINT, 3, ...);
...
view.Draw(DVASPECT_DOCPRINT, n, ...);

But the WebBrowser doesn't care what the index is; only rendering the current View (which i suppose makes sense when using IViewObject).
How do i render a browser to a device context?
Note: The question is tagged with delphi, but there's nothing in this question that is delphi specific.

Update: i also tried other combinations of aspect and index:
view.Draw(DVASPECT_CONTENT, -1, ...);
view.Draw(DVASPECT_DOCPRINT, -1, ...);
view.Draw(DVASPECT_CONTENT, 0, ...);
view.Draw(DVASPECT_DOCPRINT, 0, ...);

A: Using IViewObject, you can create a screenshot of the current viewport. I use a trick to create a screenshot of a web page (without any frames) or a frame document.

*

*Calculate the full document size using scrollWidth/scrollHeight/scrollLeft/scrollTop (check IHtmlDocument2 and IHtmlDocument3 interfaces)

*Lock window update and adjust the document to calculated full size

*Use IViewObject to create a snapshot (your code above seems to be okay)

*Restore the document to its original size and unlock window update

Note that you should be careful of doing this when the document is extremely large.


text:
Q: How to move to a location in a web browser component? I have a .NET windows form page and a WebBrowser component inside. I load a page inside the web browser using the Navigate method as in:
webBrowser1.Navigate("http://www.stackoverflow.com");

The pages length is longer than the browsers height, so the vertical scroll bar appears. Now I want to move the scrollbar down to a specific position.
More specifically I want to search for a specific peace of text inside the page, and scroll to that position.
This behavior is implemented in the built-in "Find" function of the browser, but I can't figure out how to call the Find function from within my code, without the Find window appearing.
Although I don't want the Find window to appear, if the text matches are highlighted it is welcome.

A: You could do it using anchors.
webBrowser1.Navigate("http://www.stackoverflow.com#myAnchor");

and in your html define this:
<a id="myAnchor" />

This is in itself not very flexible, but if you consistently add anchor tags to key structural parts of the html, you can always jump to the section, block, or div that you want.


text:
Q: Matlab: How can I call object properties using a string? I am currently working on a data analysis program that contains two objects: Experiment and RunSummary. The Experiment object contains multiple instances of the RunSummary object. Each RunSummary object contains multiple properties (row matrices) each containing different data points for a given run.
For example: Experiment.RunSummary(5).Tmean is row matrix containing all of the average torque values for run 5 in my experiment.
I am currently trying to find a way to combine selected common properties from specific runs into a single matrix that can be used for further analysis. The current way I have had to do this is:
X(:,1) = [Drilling.Runs(1).Tmean,...
             Drilling.Runs(2).Tmean,...
                 Drilling.Runs(3).Tmean,...
                     Drilling.Runs(5).Tmean]';

X(:,2) = [Drilling.Runs(1).Fmean,...
             Drilling.Runs(2).Fmean,...
                 Drilling.Runs(3).Fmean,...
                     Drilling.Runs(5).Fmean]';

This code takes the average torque (Tmean) and average force (Fmean) from runs 1, 2, 3, and 5 and combines them in a single matrix, X, with Tmean for all runs in the first column and Fmean in the second. Although this method works, I have over 20 different properties and 15 different runs making this coding very tedious.
I have tried using code such as get(Experiment.RunSummary(i),'Tmean') to try and retrieve these property matricies, but was met with the error:

Conversion to double from RunSummary is not possible.

*

*Is there a way to easily combine all of these different properties
into a single matrix using strings to determine which properties are used?

Thanks,
  metro
Edit: Drilling is the name of the Experiment object. Runs is the name of the RunSummary object.

A: You can use dynamic fields.  The documentation is for structs, but the same principal works for classes (at least on my R2012a install).
You can also use the comma-separate nature of object array indexing to compress the code.
Example:
I      = [1,2,3,5]              ;
props  = {'Tmean','Fmean'}      ;
Nprops = length(props)          ;
X      = zeros(length(I),Nprops);

for k = 1:Nprops
    X(:,k) = [Drilling.Runs(I).(props{k})]';
end


text:
Q: Executing JavaScript when opening a page I am currently new with HTTP parsing, I am using python to send and Receive requests in HTTP. I just have a small problem as the website I am dealing with in sending requests does not just need Headers and POST. As when I click a button on the webpage there is a JavaScript code executed that tells the server to respond for my upcoming Request.
So if I normally open the page with same headers and POST request it will just open it as a normal GET and will not read any of the data I supplied in the POST.
My code :
import cookielib
import urllib
import urllib2

# Store the cookies and create an opener that will hold them
cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))

# Add our headers
opener.addheaders = [('User-agent', 'RedditTesting'),
                     ('Cookie', '')
                     ]

urllib2.install_opener(opener)

# The action/ target from the form
authentication_url = 'http://plapal.pla/Search.aspx'

# Input parameters we are going to send
payload = {
  '_EVENTTARGET': 'btnSearch',
  '_VIEWSTATE': 'plapla',
  'ctl04%24ddNavigate': 'plapla',
  'chkDate': 'on',
  '_EVENTARGUMENT': '',
  '_LASTFOCUS': '',
  'txtResvCode': '',
  'txtCustName': '',
  'txtFromDate': '27%2F01%2F2013',
  'txtToDate': '27%2F09%2F2013',
  'ddSearchType': '1',
  'ddChannel': '-1',
  'ddNetGross': 'NET'
  }

# Use urllib to encode the payload
data = urllib.urlencode(payload)

# Build our Request object (supplying 'data' makes it a POST)
req = urllib2.Request(authentication_url, data)

# Make the request and read the response
resp = urllib2.urlopen(req)
contents = resp.read()

print contents

but it doesn't work. and in the webpage when I hover the Search button I get :
javascript:WebForm_DoPostBackWithOptions(new%20WebForm_PostBackOptions("btnSearch",%20"",%20true,%20"",%20"",%20false,%20true))

So how to execute this JS so I can actually Enter my Post Data.

A: Using JavaScript with a headless browser
If you need to execute JavaScript, it will be easier if you have a JavaScript engine available.
Instead of Python, I would consider using a headless browser such as PhantomJS. Then you can scrape the page and execute any JavaScript you need to, either running your own JS or code from the page itself.
The examples page for PhantomJS has several examples in the Page Automation section that may be similar to what you need.
It looks like you want to run an existing function in the page: WebForm_DoPostBackWithOptions(). So I would take a look at the injectme.js example which injects a script into the page. That script could then in turn call any function in the page you want to.
Or depending on what you're doing, there may be an even simpler way to do it with PhantomJS. They have a lot of good examples and docs to look through.
Using Python and a JavaScript debugger
Of course, you may not actually need to directly execute the WebForm_DoPostBackWithOptions() function. From the name, that sounds like it's likely to be a fairly simple JavaScript function. Have you looked at its code and traced through it while interacting with the page manually in a web browser? Tracing through the code should make it easy to see what the function really does. (If you do that in the Chrome developer tools and find that the code is unreadable because it's been "minified", use the {} button to pretty-print it.)
Or to cut to the chase, the Network tab or equivalent in any of the browser debuggers should let you see exactly what POST request is generated by that function. Then you can do the same in your Python code.
If you're not familiar with the developer tools in the current browsers, you are in for a treat: they are really good these days. I like the one built into Chrome, but Firebug (for Firefox) and the Internet Explorer tools are also excellent.


text:
Q: Maven―Dependencies, static content from remote repository I am a bit new to maven, but I have some experiences with ant and the build process. I would like to do one thing that is kind of driving me nuts:
Given:

*

*A remote repository (git, svn, hg,…) that holds static content (like images),

*one maven project that uses/manages the mentioned repository in the same way as it does with all other dependencies (checkout on install, update whenever updates occur), in other words: the maven project depends on that repository

I finally want to be able to access the content (no *.svn or *.git) and copy it into my build, on build time*.
I want maven to store a local copy of that repository in maven`s local repository (~/.m2/repository) only once on each machine and manage it like all other dependencies.
*I am not trying to build a Java project
Thanks for help!

A: From what I've seen, Maven projects don't use version control repositories as external artifacts.  That's a little too fine-grained for what you want, I think.
I've done something similar, when Project A wanted to use resources from Project B.

*

*Project B, as part of its build procedure, collected it's resources into a ZIP file and deployed the ZIP file into a maven repository.

*Project A then references the ZIP file artifact, unpacking it when building to where it needs it.

Look into the dependency plugin for maven, especially the dependency:unpack and dependency:unpack-dependencies goal.
Have fun


text:
Q: PostgreSQL: How to SUM attributes including a JSONB field, and retain table shape? I am working with Postgres 9.4. I have a table with a JSONB field:
     Column      │         Type         │                             Modifiers
─────────────────┼──────────────────────┼────────────────────────────────────────────────────────────────────
 id              │ integer              │ not null default
 practice_id     │ character varying(6) │ not null
 date            │ date                 │ not null
 pct_id          │ character varying(3) │
 astro_pu_items  │ double precision     │ not null
 astro_pu_cost   │ double precision     │ not null
 star_pu         │ jsonb                │

I want to retrieve the summed values by date of various attributes, including anything in the JSONB array (which it is safe to assume has depth 1), and return the values in the same structure as in the original table.
This is the query I'm using right now:
SELECT date,
       SUM(total_list_size) AS total_list_size,
       json_object_agg(key, val)
FROM (
    SELECT date,
           SUM(total_list_size) AS total_list_size,
           key, SUM(value::numeric) val
    FROM frontend_practicelist p, jsonb_each_text(star_pu)
    GROUP BY date, key
    ) p
GROUP BY date
ORDER BY date;

It does not fail, and the JSON is presented as a dictionary which is how I want it. However, the summed value of total_list_size looks hugely too large. I think it must be being summed twice.
How can I get the correct summed value for total_list_size, while retaining the same shape results?

A: The function jsonb_each_text() in the subquery causes the column total_list_size is replicated as many times as number of items in star_pu, so avg() shows a proper result.
To get one total_list_size for a date you can use a parallel subquery that accumulates the value independently.
select *
from (
    select date, json_object_agg(key, val) total_star_pu
    from (
        select date, key, sum(value::numeric) val
        from frontend_practicelist, jsonb_each_text(star_pu)
        group by date, key
        ) s
    group by date
    ) s
    join (
        select date, sum(total_list_size) total_list_size
        from frontend_practicelist
        group by date
        ) t
    using(date)
order by date;

A: I've written a Postgres extension to sum jsons. Once you have it installed you can simply do:
select date, sum(total_size_list), jsonb_deep_sum(star_pu) from frontend_practicelist;


text:
Q: For GcmListenerService is onMessageReceived background? When I extend GcmListenerService, is onMessageReceived running in a background process or is it on the UI thread? I need to know if I may make network calls inside the method body without using an asyncTask or such.
I looked at the source code and sure enough it is a vanilla service with no handlers. But there is a bit of code about THREAD_POOL_EXECUTOR and a number of apparently obfuscated stuff.

A:
When I extend GcmListenerService, is onMessageReceived running in a
  background process or is it on the UI thread? I need to know if I may
  make network calls inside the method body without using an asyncTask
  or such.

Yes you can make network calls inside onMessageReceived() method because it is running in a background process. For example, you can download an image in this method before displaying it on notification using big image notification style.

A: Simple check to determine whether current thread is main UI thread
boolean isMain = Looper.getMainLooper().getThread() == Thread.currentThread();

placed inside onMessageReceived method indicates that it is running in background process (answer to the similar question).

A: Services aren't running on the Ui / main thread.
Service can also run (in the background) even when the app is closed, this way you can get push notification, listen to the intent invoked when receiving the push  and use it to wake your app.


text:
Q: How to cast a custom type to string in VS2012? I want to cast a custom class to a string which compiles in VS2005 very well. But in VS2012 I get the compiler error error C2440: 'type cast' : cannot convert from 'A' to 'std::string'. What do I have to change? This is my example:
    #include <string>

    using namespace std;

    class A
    {
    public:
      A& operator=(const char* c);
      operator string ();
      operator const char* ();

    private:
      string value;
    };

    A::operator string () { return string((const char*)(*this)); }
    A& A::operator = (const char* aValue)   { value = aValue; return *this; }
    A::operator const char *() { const char* wort = "Hello"; return wort; }

    int main()
    {
      A a;
      string s = (string)a; // C2440
    }

A: The problem is that there are two possible explicit conversions from A to string - via the conversion operator to string; or via the conversion operator to const char *, then via the conversion constructor to string.
Simply making the conversion implicit will resolve the ambiguity; the second conversion requires two user-defined conversions, and so cannot be chosen for an implicit conversion:
string s = a;

However, the class is still a bit flaky, since sometimes you might need an explicit conversion. I would consider removing at least one of the implicit conversion operators - perhaps replace them with explicit operators (if your compiler supports such things), or with named functions (like string itself does with c_str()).

A: The conversion is ambiguous.
Stay away from C style casts, and prefer to make the conversions explicit.
#include <string>

using namespace std;

class A
{
public:
  A& operator=(const char* c);
  explicit operator string ();
  explicit operator const char* ();

private:
  string value;
};

A::operator string () { return string(static_cast<const char*>(*this)); }
A& A::operator = (const char* aValue)   { value = aValue; return *this; }
A::operator const char *() { const char* wort = "Hello"; return wort; }

int main()
{
  A a;
  string s = static_cast<std::string>(a);
}

A: Your two conversion operators step on each others toes. Each of them works for implicit conversions. But an explicit cast is like a direct constructor call. In your code
string s = (string)a;

is equivalent to
string s = static_cast<string>(a);

which transforms to something like
string tmp(a);
string s(std::move(tmp)); // this move can be elided
// lifetime of tmp ends here

The crux is the direct initialization string tmp(a). There are two viable string constructors: string(const string&) and explicit string(const char *) and your two conversions allow calling either. As neither conversion sequence is better, the call is ambiguous.
By the way, the version using copy initialization without explicit cast is not ambiguous:
string s = a;

should work. Depending on that is very brittle, so not recommended.
You should make your conversion operators explicit (if you are using C++11) or drop one of them.


text:
Q: How to declare `#include` for a header file to avoid `error lnk2005` I created a new WIN32 C++ project. I didn't touch any of the code in the main file yet, and started to write my code in a different file objectsFW.cpp the definitions for the file are located in the file objectsFW.h.
objFW.h looks like:
#pragma once

double g;

typedef struct {
    double x;
    double y;
}Vector;

typedef struct {
    //...
}BoundingBox;

typedef struct {
    //...
}Ball;

Vector operator + (Vector a, Vector b) {
    //...
}

Vector operator - (Vector a, Vector b) {
    //...
}

There are some more operators defined, and the declarations of the functions.
I included the header file in the source file (objectsFW.cpp), and also, added it to the Resources.h file, so that my code will be useable in the main program.
I get linker errors:
Error   1   error LNK2005: "struct Vector __cdecl operator*(struct Vector,double)" (??D@YA?AUVector@@U0@N@Z) already defined in ObjectsFW.obj   C:\testC\ObjectsCollision\ObjectsCollision\ObjectsCollision.obj ObjectsCollision
...
Error   4   error LNK2005: "struct Vector __cdecl operator+(struct Vector,struct Vector)" (??H@YA?AUVector@@U0@0@Z) already defined in ObjectsFW.obj    C:\testC\ObjectsCollision\ObjectsCollision\ObjectsCollision.obj ObjectsCollision

and so on.
I know that this happens because the #include "objectFW.h" line appears two times (once in each .cpp file). The question is what is the right way to declare the header file to avoid linker errors?

UPDATE:
After turning the operator functions to inline most of the errors fixed, there is still a program with the line:
double g;

the error is:
Error   1   error LNK2005: "double g" (?g@@3NA) already defined in ObjectsCollision.obj C:\testC\ObjectsCollision\ObjectsCollision\ObjectsFW.obj    ObjectsCollision

(working on Visual Studio 2012)

A: About global variables:
1. Refrain from using them.  Think encapsulation and data hiding.
2. If you must use them, define the global in 1 source file and place the "extern" in a header file.
Example:
header_file.hpp:
  extern unsigned int deadly_global;

source_file.cpp:
  unsigned int deadly_global;

Better method for hiding global variables
A better method for controlling (hiding) global variables is to place all the code that uses the variable in the same source file and declare the variable as static:
  static unsigned int variable_shared_by_many_functions = 0;
  void f1(void)
  {
    variable_shared_by_many_functions = 42U;
  }

  void f2(void)
  {
    std::cout << "Value of shared variable: "
              << variable_shared_by_many_functions
              << "\n";
  }

Controlling Global Variables Using Getters and Setters
If you must share the variable among functions in more than one source file, a safer technique is to declare the variable as static in one source file and declare functions (interfaces) to access it.
  static int dangerous_variable = 0;

  int accessor(void)
  {
     // Return a copy of the varible.
     return dangerous_variable;
  }

  void setter(int new_value)
  {
    if ((new_value / 5) != 1)
    {
       dangerous_variable = new_value;
    }
  }

This technique allows you to place filters or other controls on setting the variable.

A: Put in your header:
extern double g;

And in a .cpp:
double g;

That way every file that includes the header will know that there is a variable g, but it will only be declared at one place.


text:
Q: JSF & Primefaces & IE Ajax does not work I am using JSF Mojarra 2.2.1 , Primefaces 4.0 Snapshot and IE 9. This problem happens in IE 9 and also a similar problem exists when I replace it with f:ajax unless I render using @all. When command button is rendered via ajax request, it fires a normal request in the following request. I created a simple code to illustrate the problem.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>

<h:head>

</h:head>
<h:body>

    <h:form id="testForm">

Test of IE9 Ajax

        Text: <h:outputText value="#{testBean.count}" />

    </h:form>

</h:body>

And my bean is,
package test;

import java.io.Serializable;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;

@ManagedBean
@ViewScoped
public class TestBean implements Serializable{

    /**
     *
     */
    private static final long serialVersionUID = 1L;
    private int count = 0;

    public void increment()
    {
        count++;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

}

In the test, alert is given on only at odd numbers which is an other indicator of ajax call is not made smoothly.
Update:
I realized this is happening because IE9 ignores inputs' onclick="javascript" events when they are replaced jquery's replace all method.
Update 2:
This does not happen in my home computer IE 9 (same version), it happens only in office computer. I cannot see security settings, Do you know why this happens? Javascript works but does not function properly.
Any help is highly appreciated.
Thanks

A: Please try the following code inside the <h:head> tag:
<f:facet name="first">
    <meta http-equiv="X-UA-Compatible" content="edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
</f:facet>

Let's me know if it help.

A: Resetted the security settings of the browser (IE 11) resolved the issue in my case. Unfortunately, I don't know which setting is responsible for this.


text:
Q: dynamic programming algorithm for the minimum number of primes Develop a dynamic programming algorithm that calculates the minimum number of different primes that sum to x. Assuming the dynamic programming calculates the minimum number of different primes amongst which the largest is p for each couple of x and p.
Can someone help me?  Thanks.

A: Well, if you name $f(n)$ your function, consider this:
$
f(n)=
\begin{cases}
1 &\text{if $n$ is a prime}\\
min_{1\leq k<n}\{f(n-k)+f(k)\} &\text{otherwise }
\end{cases}
$
Edit:

$
f(n,p)=
\begin{cases}
\infty &\text{if $p>n$}\\
1 &\text{if $p=n$}\\
\min _{q<p, q \text{ prime}} f(n-p,q) &\text{otherwise }
\end{cases}
$


text:
Q: We are trying to redirect amp pages to non amp pages. But the redirect is not working We recently stopped using google AMP pages on our website. So we removed AMP plugin from our website.
And added redirect for all the AMP pages.
We have added this code inside the htaccess file.
# Redirect from AMP to non-AMP path
RewriteEngine On
RewriteCond %{REQUEST_URI} (.+)/amp(.*)$
RewriteRule ^ %1/ [R=301,L]

But now the redirect is working like this
https://example.com/some-blog-post/amp/
to
http://example.com/some-blog-post/
to
https://example.com/some-blog-post/
Why it is getting redirected to http:// version first?
We tried adding redirects but they are getting redirected to http://


text:
Q: Is a CAN enabled microcontroller sufficient to drive a CAN bus? There are a number of CAN modules built into microcontrollers these days. The PIC18F2480 is an example of that. Is that microcontroller (with built-in CAN) capable of driving a CAN bus on its own or is an external CAN transceiver/controller required?
I believe CAN has both a software and hardware layer and by the looks of it these CAN-enabled microcontrollers appear to have just the software, but it does not state that it can or cannot drive the CAN bus as is.
I'm looking to connect more than six microcontrollers through a CAN bus and would like to know if I need a transceiver across all of them or whether the built-in stuff can handle the communication from a software and hardware perspective.
Assume that I'll have necessary termination resistors and other small discrete components (caps, resistors, etc.)

A: You need a CAN transceiver chip between the CPU and the CAN bus.  Check out the MCP2551.
Update 17 Aug 2017:
I'm at the Microchip Masters conference right now.  I was told flat out by Microchip engineers that one of the new parts that resulted from the Atmel acquisition is both cheaper and better than the MCP2551.

A: Yes, you need a tranceiver.  The CAN pins on the micro are receive and transmit.  The CAN bus itself uses a twisted-pair with differential signalling on two wires called HIGH and LOW.
One of the transceiver's jobs is to take the logic level you present on the TX pin an turn it into CAN bus signals:

*

*a logic '1' is represented by not driving the bus, so the HIGH and LOW lines "float" to 2.5V - called a "recessive bit" in CAN terminology.

*a logic '0' is represented by driving the HIGH line high and the LOW line low - called a "dominant bit" as it will override any recessive bits being transmitted.

The other is to take what is on the bus, and turn it back into a logic-level to send back from the RX pin to your micro.

A: This is a very good question. As a general rule, CAN requires a transceiver for every node:

However, under certain circumstances, you can actually get away without any transceivers! Those circumstances are:

*

*Short bus length (much less than 1 meter)

*Preferably all microcontrollers are on the same PCB, or stack of PCBs.

*The bit rate is low

*The environment isn't too electrically noisy

These aren't hard rules. You might get away with maximum bit rate (1MB/s) if you have a really short bus (10cm).
To achieve this, you need to know a little about what the transceiver does. Like most transceivers, they can output a high or a low to the bus (representing 1 and 0), but the 0 can dominate a 1. I.E. If two transceivers try to speak at the same time, and one is saying 1 and the other is saying 0, then the 0 will win. We can re-create the same situation simply using diodes:

See the Seimens application note AP2921: On-Board Communication via CAN without Transceiver
But here's something even more interesting: The PIC actually has hardware support for transceiverless CAN!

You can configure the CAN TX pin so that is behaves in exactly the same way as the transceiver. This means you can wire up the CAN bus without the diodes. You'll still need the resistor though.

A: Analog devices has an example CAN transceiver circuit using a differential amplifier.I haven't tried this, am just aware of it. Also interested if it could be implemented with an op-amp

The advantages of using dedicated IC CAN transceiver is they will handle arbitration for you and you don't have to worry about interfering with the bus. If you are only observing the bus and it's not a fault critical environment, the circuit may be fine. While the mcp2551 is very popular, there are many options for interface chips.
A new evolution are the System Base type of chips which include voltage regulation, power modes, and ESD protection from the bus.
Like timorr said above, NXP's LCP11C24 is unique in that the processor includes CAN transceiver. A demo board with this is only $19. Another low cost solution is to use the $9.38 Cypress PSoC5 demo board, the CY8CKIT-059. The PSoC5 doesn't have a CAN controller; it goes one further: the controller is implemented in the FPGA-like universal blocks. The controller's registers are configured via the IDE's GUI, making filtering and R&D pretty easy.
A key method I have found when perusing data sheets is the mcu TTL is labeled CAN-Tx and CAN-Rx while the transceivers' data lines to the bus are always labelled CAN-H and CAN-L. I dislike the diagrams in the other answer where TxRx are shown connected to the bus; this goes against convention and contributes to confusion.

A: The LPC11Cxx family of microcontrollers (ARM Cortex-M0 based) include the CAN transceiver on-chip.


text:
Q: How to avoid 100% CPU utilization without removing while(true) I am working on a system where I need a while(true) where the loop constantly listens to a queue and increments counts in memory.
The data is constantly coming in the queue, so I cannot avoid a while(true) condition. But naturally it increases my CPU utilization to 100%.
So, how can I keep a thread alive which listens to the tail of queue and performs some action, but at the same time reduce the CPU utilization to 100%?

A: LinkedBlockingQueue.take() is what you should be using.  This waits for an entry to arrive on the queue, with no additional synchronization mechanism needed.
(There are one or two other blocking queues in Java, IIRC, but they have features that make them unsuitable in the general case.  Don't know why such an important mechanism is buried so deeply in arcane classes.)

A: usually a queue has a way to retrieve an item from it and your thread will be descheduled (thus using 0% cpu) until something arrives in the queue...

A: Based on your comments on another answer, you want to have a queue that is based on changes in hsqldb
Some quick googling turns up:
http://hsqldb.org/doc/guide/triggers-chapt.html
It appears you can set it up so that changes cause a trigger to occur, which will notify a class you write implementing the org.hsqldb.Trigger interface. Have that class contain a reference to a LinkedBlockingDequeue from the Concurrent package in Java and have the trigger add the change to the queue.
You now have a blocking queue that your reading thread will block on until hsqldb fires a trigger (from an update by a writer) which will put something in the queue. The waiting thread will then unblock and have the item off the queue.

A: Blocking queues were invented exactly for this purpose.
Also see this: What are the advantages of Blocking Queue in Java?

A: lbalazscs and Brain have excellent answers. I couldn't share my code it was hard for them to give them the exact fix for my issue. And having a while(true) which constantly polls a queue is surely the wrong way to go about it. So, here is what I did:

*

*I used ScheduledExecutorService with a 10sec delay.

*I read a block of messages (say 10k) and process those messages

*thread is invoked again and the "loop" continues.

This considerably reduces my CPU usage. Suggestions welcomed.

A: Lots of dumb answers from people who read books and only wasted time in schools, not as many direct logic or answers I see.
while(true) will set your program to use all the CPU power that's basically 'alloted' to it by the windows algorithms to run what is in the loop, usually as-fast-as-possible over and over. This doesn't mean if it says 100% on your application, that if you run a game, your empty loop .exe will be taking  all your OS CPU power, the game should still run as intended. It is more like a visual bug, similar to the windows idle process and some other processes. The fix is to add a Sleep(1) (at least 1 millisecond) or better yet a Sleep(5) to make sure other stuff can run and ensure the CPU is not constantly looping your while(true) as fast as possible. This will generally drop CPU usage to 0% or 1% in the visual queue as 1 full millisecond is a big resting time for even older CPU.
Many times while(trues) or generic endless loops are bad designs and can be drastically slowed down to even Sleep(1000) - 1 second interval checks or higher. Endless loops are not always bad designs, but usually they can be improved..
funny to see this bug I learned whe nI was like 12 learning C pop up and all the 'dumb' answers given.
Just know if you try it, unless the scripted slower language you have learned to use has fixed it somewhere along the line by itself, windows will claim to use a lot of CPU on doing an empty loop when the OS is actually having free resources to spend.


text:
Q: How to write a locator and get both the text present in a single tag in HTML code for selenium automation This is my html code
<h2>==$0
"How"
 "Are You"
</h2>

Writing locator like //h2/text()[1] for getting "How" text and writing //h2/text()[2] for getting "Are You" text doesn't works for me. Throws the below error
onException - WebDriver error:
<font color= 'red' size='3.5'>org.openqa.selenium.InvalidSelectorException: invalid selector: The result of the xpath expression "//h2/text()[2]" is: [object Text]. It should be an element.

A: text() doesn't return webelement node but the text content
use instead
//*[text()[contains(.,"Are You")]]

now find the text as
elem.text()

you have to use string operator to extract the specific text you want


text:
Q: Android web request to string I want to collect the text from a webpage, put it into a string and then show it on my device's screen.
This is my WebRequest activity:
package com.work.webrequest;

import java.io.IOException;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class WebRequest extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView txt = (TextView) findViewById(R.id.textView1);
        txt.setText(getPage());
    }

    private String getPage() {
        String str = "***";

        try
        {
            HttpClient hc = new DefaultHttpClient();
            HttpPost post = new HttpPost("http://zapmenow.co.uk/zapme/?getDetails=true&secret=zjXvwX5frK1po0adXyKJsbbyUe2ZY2PkW9M8r7sb1soIDppIWdTlgt1xmL5VM6g&UDID=401ceca29af68e4569a25e8c16a6987bb8cf1f5a&id=41");

            HttpResponse rp = hc.execute(post);

            if(rp.getStatusLine().getStatusCode() == HttpStatus.SC_OK)
            {
                str = EntityUtils.toString(rp.getEntity());
            }
        }catch(IOException e){
            e.printStackTrace();
        }

        return str;
    }

}

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView android:layout_height="wrap_content"
    android:id="@+id/textView1"
    android:text=""
    android:layout_width="wrap_content"></TextView>
</LinearLayout>

I don't have any errors in Eclipse, but the application crashes on my device.
PS: I've added the line
 <uses-permission android:name="android.permission.INTERNET" />

in manifest, so the Internet permission is not the problem.

A: This is the code that worked for me:
private String getPage(String url) {
    HttpURLConnection con = (HttpURLConnection) new URL(url).openConnection();
    con.connect();

    if (con.getResponseCode() == HttpURLConnection.HTTP_OK) {
        return inputStreamToString(con.getInputStream());
    } else {
        return null;
    }
}

private String inputStreamToString(InputStream in) throws IOException {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
    StringBuilder stringBuilder = new StringBuilder();
    String line = null;

    while ((line = bufferedReader.readLine()) != null) {
        stringBuilder.append(line + "\n");
    }

    bufferedReader.close();
    return stringBuilder.toString();
}

Later, you can use it by:
String response = getPage("http://example.com");


text:
Q: CSS Transition doesn't work with hamburger button I made a hamburger button and I'm trying to animate spans to create a cross.
My transition doesn't work and I don't know why...
I found that sometimes transitions doesn't work on chrome so I've used webkit prefix but it didn't help :(
This is my HTML code:

CSS code:
.main__box__nav__hamburger {
  min-width: 30px;
  height: 20px;
  margin: 45px 10px;
  position: relative;
  transition: all cubic-bezier(0.25, 0.1, 0.28, 1.54) .5s;
}
.line {
  position: absolute;
  min-width: 30px;
  height: 4px;
  border-radius: 2px;
  background: #000;
}
.line2 {
  top: 8px;
}
.line3 {
  top: 16px;
}
.main__box__nav__hamburger.close .line1 {
  transform: rotate(45deg);
  top: 50%;
}
.main__box__nav__hamburger.close .line2, .main__box__nav__hamburger.close .line3 {
  transform: rotate(-45deg);
  top: 50%;
}

A: That is because you are applying the transition to the parent element (the hamburger itself), instead of to its children. Remember that transition is not inherited.
Move the transition property to the .line selector and it will work:
.line {
  transition: all cubic-bezier(0.25, 0.1, 0.28, 1.54) .5s;
}

See proof-of-concept below (I have added some minimal JS, so clicking on the hamburger will toggle the close class needed to visualize the transition):

var burger = document.querySelector('.main__box__nav__hamburger');

burger.addEventListener('click', function() {
  this.classList.toggle('close');
});
.main__box__nav__hamburger {
  min-width: 30px;
  height: 20px;
  margin: 45px 10px;
  position: relative;
}
.line {
  position: absolute;
  min-width: 30px;
  height: 4px;
  border-radius: 2px;
  background: #000;
  transition: all cubic-bezier(0.25, 0.1, 0.28, 1.54) .5s;
}
.line2 {
  top: 8px;
}
.line3 {
  top: 16px;
}
.main__box__nav__hamburger.close .line1 {
  transform: rotate(45deg);
  top: 50%;
}
.main__box__nav__hamburger.close .line2, .main__box__nav__hamburger.close .line3 {
  transform: rotate(-45deg);
  top: 50%;
}


text:
Q: How to delete all textures made at once? How can I delete all the textures I've made? Suppose I load a few textures:
GLuint tx_wall,tx_floor,tx_tiles;
tx_wall=LoadTexture("tex_wall.raw",512,512),
tx_floor=LoadTexture("tex_floor.raw",512,512),
tx_tiles=LoadTexture("tex_tiles.raw",512,512);

then use them:
glBindTexture(GL_TEXTURE_2D,tx_wall);
  glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex3f(0,   0,  0);
    glTexCoord2f(1, 0); glVertex3f(0,  50,  0);
    glTexCoord2f(1, 1); glVertex3f(0,   0, 14);
    glTexCoord2f(0, 1); glVertex3f(0,  50, 14);
  glEnd();
glBindTexture(GL_TEXTURE_2D,tx_floor);
  glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex3f(0,   0,  0);
    glTexCoord2f(1, 0); glVertex3f(50,  50, 0);
    glTexCoord2f(1, 1); glVertex3f(50,  50, 0);
    glTexCoord2f(0, 1); glVertex3f(0,   0,  0);
  glEnd();
(and so on)

and when the game ends, delete them:
glDeleteTextures(1,&tx_wall);
glDeleteTextures(1,&tx_floor);
glDeleteTextures(1,&tx_tiles);

All works fine but if i have 10 or 20 textures than how will i terminate them all without taking their names?

A: If you put all texture identifiers in an array, you can delete them all in one call using glDeleteTextures (just like you can generate them all in one call using glGenTextures).
GLuint textures[3];
glGenTextures(3, textures);

/* ... */

glDeleteTextures(3, textures);

A: Perhaps not exactly what you were intending, but RAII would be a sensible option:
class Texture
{
public:
    Texture( const std::string& name, int width, int height ) :
        m_id( LoadTexture(name.c_str(),width,height) )
    {
    }

    ~Texture()
    {
        if(m_id)
            glDeleteTextures(1,&m_id);
        m_id = 0;
    }

    GLuint id() const
    {
        return m_id;
    }

private:
    Texture( const Texture& );
    Texture& operator=( const Texture& );

    GLuint m_id;
};

Usage:
Texture tx_wall("tex_wall.raw",512,512);
Texture tx_floor("tex_floor.raw",512,512);
Texture tx_tiles("tex_tiles.raw",512,512);

and:
glBindTexture(GL_TEXTURE_2D,tx_wall.id());
  glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex3f(0,   0,  0);
    glTexCoord2f(1, 0); glVertex3f(0,  50,  0);
    glTexCoord2f(1, 1); glVertex3f(0,   0, 14);
    glTexCoord2f(0, 1); glVertex3f(0,  50, 14);
  glEnd();
glBindTexture(GL_TEXTURE_2D,tx_floor.id());
  glBegin(GL_QUADS);
    glTexCoord2f(0, 0); glVertex3f(0,   0,  0);
    glTexCoord2f(1, 0); glVertex3f(50,  50, 0);
    glTexCoord2f(1, 1); glVertex3f(50,  50, 0);
    glTexCoord2f(0, 1); glVertex3f(0,   0,  0);
  glEnd();

The benefit is that you can retain textures only for as long as you need them, the code is exception safe and texture release is automatic. The downside is that you can't copy Texture objects around without some kind of reference counting (for which I would recommend using boost::shared_ptr rather than rolling your own, because reference counting in multi-threaded environments is tricky). The latter is the reason for the private copy constructor and assignment operator.


text:
Q: Why does ${\rm cov}(Y_{ij}, Y_{ik}) = \sigma_u^2$ in the model $Y_{ij} = \mu + u_i + e_{ij}$? Consider $Y_{ij} = \mu + u_i + e_{ij}$ where $\mu$ is a constant and $u_i ∼ N(0,\sigma_u^2
)$ is the subject $i$ random effect which is independent of the error term $e_{ij} ∼ N(0,σ_e^2)$. I can't figure out why $${\rm cov}(Y_{ij}, Y_{ik}) = \sigma_u^2$$
Can anyone please explain?

A: Well,
$$ {\rm cov}(Y_{ij}, Y_{ik})
= {\rm cov}(u_{i} + e_{ij}, u_{i} + e_{ik})
$$
since the constant term, $\mu$, does not affect variances or covariances. By the bilinearity of covariance we have
$$ {\rm cov}(Y_{ij}, Y_{ik})
=
{\rm cov}(u_{i}, u_{i})
+ {\rm cov}(u_{i}, e_{ik})
+ {\rm cov}(e_{ij}, u_{i})
+ {\rm cov}(e_{ij}, e_{ik})
$$
By independence of $u_{i}$ and each $e_{ij}, e_{ik}$ and independence between $e_{ij}$ and $e_{ik}$ (which must be assumed for this model to make sense), the 2nd, 3rd and 4th terms are all zero above (since independence between two variables implies that their covariance is 0). So,
$$ {\rm cov}(Y_{ij}, Y_{ik})
=
{\rm cov}(u_{i}, u_{i})
= {\rm var}(u_{i}) = \sigma^{2}_{u}

$$


text:
Q: The Code does not work successfully when the function is called I want to call method (close_ok()) in (main.py ) from method :close_call() in (module_b.py), but the Code does not work successfully when the function is called.
can anyone help me with this problem?
Here's the code for that :
@@@main.py
# -*- coding: utf-8 -*-
from PyQt4 import QtCore, QtGui
import sys
from GUI import Ui_MainWindow
class MainWindow(QtGui.QMainWindow,Ui_MainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        from module_c import class_c
        global b
        b=class_c()
        QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"), b.close_call )
    def close_ok(self):
        ##But it can not be done successfully.
        self.close()

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    global myapp
    myapp = MainWindow()
    myapp.show()
    sys.exit(app.exec_())

@@@ module_b.py
class class_c (object):
     def __init__(self, parent=None):
       self.parent=parent

 ### I want call method (close_ok()) in (menu class) from here
     def close_call (self):
          from main import MainWindow
          t=MainWindow()
          t.close_ok()

@@@GUIpy
# -*- coding: utf-8 -*-

from PyQt4 import QtCore, QtGui
try:
    _fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
    def _fromUtf8(s):
        return s
try:
    _encoding = QtGui.QApplication.UnicodeUTF8
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
    def _translate(context, text, disambig):
        return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
    def setupUi(self, MainWindow):
        super(Ui_MainWindow, self).__init__()
        MainWindow.setObjectName(_fromUtf8("MainWindow"))
        MainWindow.resize(800, 600)
        self.centralwidget = QtGui.QWidget(MainWindow)
        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
        self.pushButton = QtGui.QPushButton(self.centralwidget)
        self.pushButton.setGeometry(QtCore.QRect(340, 110, 75, 23))
        self.pushButton.setObjectName(_fromUtf8("pushButton"))
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtGui.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
        self.menubar.setObjectName(_fromUtf8("menubar"))
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtGui.QStatusBar(MainWindow)
        self.statusbar.setObjectName(_fromUtf8("statusbar"))
        MainWindow.setStatusBar(self.statusbar)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
        self.pushButton.setText(_translate("MainWindow", "PushButton", None))

A: you use diffrent instances of the class MainWindow() so it wont close the original window, change it like this:
class MainWindow(QtGui.QMainWindow,Ui_MainWindow):
    def __init__(self, parent=None):
        QtGui.QWidget.__init__(self, parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        from module_c import class_c
        global b
        b=class_c(self) #NOTICE THE CHANGE HERE
        QtCore.QObject.connect(self.ui.pushButton, QtCore.SIGNAL("clicked()"), b.close_call )

    def close_ok(self):
        self.close()

and change module b to do:
class class_c (object):
 def __init__(self, parent=None):
   self.parent=parent

 def close_call (self):
      from main import MainWindow
      self.parent.close_ok()# NOTICE THIS CHANGE, parent is now the original MainWindow

this way you pass your original MainWindow instancce to class_c and use it, instead of creating a new instance


text:
Q: java int toString() error Hey I am writing a program that calculates the words, sentences, vowels, characters..etc of a textfile. I want to use a toString() to concatenate all the classes and the end and return them in the format: {filename}: {character count}c {vowel count}v {word count}w {line count}l {sentence count}s. I am having trouble with the int classes. Ex (charCount.toString())'c' + .... Here is my code so far. Thanks
import java.io.FileInputStream;

public class TextFileAnalyzer {

    public static void main(String[] args) {
        try {
            TextFileAnalyzer mytfa = new TextFileAnalyzer("/Users/patrickmro/Desktop/text.txt");
            System.out.println(mytfa.getCharCount());
            System.out.println(mytfa.getSentenceCount());
            System.out.println(mytfa.getLineCount());
            System.out.println(mytfa.getVowelCount());
        }
        catch (Exception e) {

        }

    }

  // You'll probably want some private fields
    private java.lang.String filePath;
    private int sentenceCount;
    private int wordCount;
    private int charCount;
    private int lineCount;
    private int vowelCount;
    private java.lang.String textString;
  /**
   * Constructs a new TextFileAnalyzer that reads from the given file. All file
   * I/O is complete once this constructor returns.
   * @param filePath a path to the file
   * @throws Exception if any errors are generated by the Java API while reading
   *           from the file
   */
  public TextFileAnalyzer(String filePath) throws Exception {
    // This is your job...
      this.filePath = filePath;
      charCount = 0;
      int prevChar = -1;
      FileInputStream input = new FileInputStream(filePath);
      for(int c = input.read(); c != -1 ; c = input.read()) {
          charCount++;
          if (c == '.' && prevChar != '.') {
              sentenceCount++;
          }
          if(c == '\n') {
              lineCount++;
          }
          if(Character.isWhitespace(c) && (prevChar != -1 || !Character.isWhitespace(prevChar) )) {
              wordCount++;
          }
          prevChar = c;
          if(c == 'A' || c == 'E' || c == 'I'|| c == 'O' || c == 'U') {
              vowelCount++;
          }
          if(c == 'a' || c == 'e' || c == 'i'|| c == 'o' || c == 'u') {
              vowelCount++;
          }

      }

      lineCount++;
      input.close();
  }

  /**
   * Returns the number of single-byte characters in the file, including
   * whitespace.
   *
   * @return the number of characters in the file
   */
   public java.lang.String getfilePath() {
     return this.filePath;
     }

  public int getSentenceCount() {
      return  sentenceCount ;
  }
  public int getWordCount() {
      return wordCount  ;
  }

  public int getCharCount() {
      return charCount ;
  }

  public int getLineCount() {
      return lineCount ;
  }

  public int getVowelCount() {
      return vowelCount;
  }
  public java.lang.String toString() {

     // {filename}: {character count}c {vowel count}v {word count}w {line count}l {sentence count}s
      return (this.getfilePath())':' + (sentenceCount.toString())'s' + (wordCount.toString())'w';

  }

}

A: Easier one: change this methods as follows and it will work (due to string concatenation, during which non-Strings are automatically converted to strings.
public java.lang.String toString() {
   return this.getfilePath() + ":" + sentenceCount + "s" + wordCount + "w";
}

Alternatively, replace int (which is the primitive data type for integers and hence does not have methods like toString()) with Integer (which is a Java class for integers, wrapping the primitive int inside it and since it is a class, it has methods like toString()) everywhere in your code and you would be good.
For example replace:
private int sentenceCount;

with:
private Integer sentenceCount;

Also change the return types of the methods from int to Integer.

A: int is a primitive type in Java and as such has no methods associated with it. However you do not need to use a toString() this should work fine
return this.getfilePath() +':' + sentenceCount + 's' + wordCount + 'w';


text:
Q: How to configure mdadm.conf properly I have 2 mdadm arrays.
Long time ago, when there was only one raid, i wrote mdadm.conf and it looked like this:
# mdadm.conf written out by anaconda
MAILADDR root
AUTO +imsm +1.x -all
ARRAY /dev/md/pv00 level=raid1 num-devices=2 UUID=55dc183e:d7199ced:929f5f4a:123c24a3

Since there was no 2nd raid, i thought adding it to it would be a good idea. so I ran command mdadm --detail --scan >> /etc/mdadm.conf
But now, there are 2 entries for first raid
# mdadm.conf written out by anaconda
MAILADDR root
AUTO +imsm +1.x -all
ARRAY /dev/md/pv00 level=raid1 num-devices=2 UUID=55dc183e:d7199ced:929f5f4a:123c24a3
ARRAY /dev/md/pv00 metadata=1.2 name=server.local:pv00 UUID=55dc183e:d7199ced:929f5f4a:123c24a3
ARRAY /dev/md/25 metadata=1.2 spares=2 name=server.local:25 UUID=a883dfb5:1a8f32ce:fd20e5d8:156a01ff

*

*1st: Should I remove old entry and leave only new one? Which one is better?

*2nd: Why is there  a difference between old and new entry? Old one has level=raid1 num-devices=2 but new one has only metadata=1.2 instead.
Edit: Parially found answer

*3rd: Found information, that raid will not start without it. However, entry in fstab mounting this array seems to automatically start it. So it's needed or not?

Also found some people writing to upate mdadm.conf with mdadm --verbose --detail --scan > /etc/mdadm.conf source. Is it proper? It also outputs drive locations like:
ARRAY /dev/md/pv00 level=raid1 num-devices=2 metadata=1.2 name=server.local:pv00 UUID=55dc183e:d7199ced:929f5f4a:123c24a3
   devices=/dev/sdi2,/dev/sdj1
ARRAY /dev/md/25 level=raid6 num-devices=6 metadata=1.2 spares=2 name=server.local:25 UUID=a883dfb5:1a8f32ce:fd20e5d8:156a01ff
   devices=/dev/sda1,/dev/sdb1,/dev/sdc1,/dev/sdd1,/dev/sdf1,/dev/sdg1

Is it proper syntax? As far, as I know. Drive /dev/sd* may change. So is it safe to add devices to it? I recently had to replace SATA cables on system, and letters changed, as I did not put attention to connect them to same port.

A: The mdadm man page puts it this way (emphasis mine):

echo 'DEVICE /dev/hd*[0-9] /dev/sd*[0-9]' > mdadm.conf`
mdadm --detail --scan >> mdadm.conf

This will create a prototype config file that describes currently
active arrays that are known to be made from partitions of IDE or SCSI
drives.  This file should be reviewed before being used as it may
contain unwanted detail.

Now, to your question,

As far, as I know. Drive /dev/sd* may change. So is it safe to add devices to it?

It's not just that device names may change. Everything else may change, too!
mdadm supports growing arrays. So you can add more devices which changes num-devices=2, or change the raid level=raid1. Drives might fail which causes spares to automatically take over, which changes spares=2 as there will be fewer spares still available to your array. Even the name= is not protected as there are various issues around the way mdadm treats host and array names. The metadata version has changed in the past, if you used metadata=0.90 then mdadm could have updated it to metadata=1.0. If there is new metadata in the future, it might be possible to update it again.
The one thing that is constant for an array throughout its lifetime is the UUID=a883dfb5:1a8f32ce:fd20e5d8:156a01ff, hence my recommendation in the question you linked:
For each array, use just the UUID, nothing else.
The only purpose for all these variables is to identify the correct array, and the UUID does that perfectly fine by itself, nothing else needed. So just remove the other stuff.
Of course, if you really want, you can also change the UUID. But it's a much more deliberate action than the other changes that occur during normal operation of the array.
mdadm --detail --scan is just a starting point but should not be used literally as mdadm.conf. Like the manpage states, it's just too detailed, and too much detail can cause the assembly to fail.


text:
Q: SQL Server 2014 - Error 15281 on Linked Excel File I'm upgrading our reporting server from 2008 R2 32-bit to 2014 32-bit.
We have linked servers that are excel files. These are .xls files (although the problem persists when they are updated to .xlsm). The connects work fine (select & insert into); however, when we run a stored procedure to create a new tab in the excel file.
USE [SupplementaryReports]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

CREATE PROCEDURE [dbo].[spExecute_ADODB_SQL]
    @DDL VARCHAR(8000),
    @DataSource VARCHAR(500),
    @Worksheet VARCHAR(200)=NULL,
    @ConnectionString VARCHAR(255) = 'Provider=Microsoft.ACE.OLEDB.12.0;
    Data Source=%DataSource;
        Extended Properties=Excel 12.0'
        AS
        DECLARE
            @objExcel INT,
            @hr INT,
            @command VARCHAR(255),
            @strErrorMessage VARCHAR(255),
            @objErrorObject INT,
            @objConnection INT,
            @bucket INT

SELECT @ConnectionString =REPLACE (@ConnectionString, '%DataSource', @DataSource)
IF @Worksheet IS NOT NULL
    SELECT @DDL=REPLACE(@DDL,'%worksheet',@Worksheet)
    SELECT @strErrorMessage='Making ADODB connection ',
        @objErrorObject=NULL
EXEC @hr=sp_OACreate 'ADODB.Connection', @objconnection OUT
IF @hr=0
    SELECT @strErrorMessage='Assigning ConnectionString property "'
        + @ConnectionString + '"',
        @objErrorObject=@objconnection
IF @hr=0 EXEC @hr=sp_OASetProperty @objconnection, 'ConnectionString', @ConnectionString
IF @hr=0 SELECT @strErrorMessage ='Opening Connection to XLS, for file Create or Append'
IF @hr=0 EXEC @hr=sp_OAMethod @objconnection, 'Open'
IF @hr=0 SELECT @strErrorMessage ='Executing DDL "'+@DDL+'"'
IF @hr=0 EXEC @hr=sp_OAMethod @objconnection, 'Execute',
    @Bucket out , @DDL
IF @hr<>0
    BEGIN
    DECLARE
        @Source VARCHAR(255),
        @Description VARCHAR(255),
        @Helpfile VARCHAR(255),
        @HelpID INT

    EXECUTE sp_OAGetErrorInfo @objErrorObject, @source output,
        @Description output,@Helpfile output,@HelpID output
    SELECT @strErrorMessage='Error whilst '
        +COALESCE(@strErrorMessage,'doing something')+', '
        +COALESCE(@Description,'')
        RAISERROR (@strErrorMessage,16,1)
END
EXEC @hr=sp_OADestroy @objconnection

GO

I get the following error

Msg 15281, Level 16, State 1, Procedure sp_OACreate, Line 116
SQL Server blocked access to procedure 'sys.sp_OACreate' of component 'Ole Automation Procedures' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'Ole Automation Procedures' by using sp_configure. For more information about enabling 'Ole Automation Procedures', search for 'Ole Automation Procedures' in SQL Server Books Online.
Msg 15281, Level 16, State 1, Procedure sp_OADestroy, Line 116
SQL Server blocked access to procedure 'sys.sp_OADestroy' of component 'Ole Automation Procedures' because this component is turned off as part of the security configuration for this server. A system administrator can enable the use of 'Ole Automation Procedures' by using sp_configure. For more information about enabling 'Ole Automation Procedures', search for 'Ole Automation Procedures' in SQL Server Books Online.

This error often means that ad hoc distribtued queries are not enough. But they are (both 'show advanced options' and 'ad hoc distributed queries' are set to 1). We also have the provider Microsoft.ACE.OLEDB.12.0 with allow in process and dynamic paramteres enabled.
The excel files work perfectly with 2008 R2. The code itself hasn't been changed. All that's changed is upgrading to 2014. Does anyone have any suggestions? You know... besides not using SQL to connect to excel files since we don't have the resources to change that.
Much obliged!

A: The most likely answer is Ole Automation Procedures is not turned on.  You can check by running:
EXEC sp_configure 'Ole Automation Procedures';

This will return something along the lines of:
name                        minimum maximum config_value    run_value
Ole Automation Procedures   0       1       0               0

If the config_value is 0 you need to enable it.
sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ole Automation Procedures', 1;
GO
RECONFIGURE;
GO

Source.


text:
Q: The local project works correctly, but it does not find the url's server I created a project, it works perfectly in the local. It worked sometimes on the server.
but most of the time on certain pages does not find, for example:
on the login button that I clicked.
Is there a problem with the code or the host that I have provided?

A: You need to update composer on server thats why sometime button links not working
Composer update
php artisan key:generate
php artisan cache:clear

Delete all the cache file i.e.
 storage/framework/views

A: Kindly make sure that .htaccess file locatedin same directory where index.php is located

A: Maybe you miss .env file. You should check the .env file is exist and valid .


text:
Q: Create asp.net website with editable config file I want to create setup of my web application with editable web.config file content.
Any help?

A: You could use a tool like MS Web deploy. Read more about it here. http://learn.iis.net/page.aspx/578/package-an-application-for-the-windows-web-application-gallery/

A: If you are trying to change the config with your code, the following should help. Any time you execute the following code, your site will be restarted. So keep that in mind.
var config = (Configuration)WebConfigurationManager.OpenWebConfiguration("~");
var configSection = (MySectionTypeHere)myConfiguration.GetSection("system.web/section");

//make your edits here

myConfiguration.Save();

If this is not what you're looking for, perhaps you could provide some more information.


text:
Q: How to get URI of current request? I need to resolve URI of current request in Quarkus (I use Quarkus 1.13). I use RESTEasy as my rest framework. Current request URI is needed in my case to validate Mandrill webhook call.
Simplified my current implementation looks like:
@Produces(MediaType.TEXT_PLAIN)
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Path("/api/v1/webooks/mandrill")
public class MandrillWebhookResource {

    // code skipped for brevity

    @POST
    public Response mandrill(
            @HeaderParam("x-mandrill-signature") String mandrillSignature,
            @FormParam("mandrill_events") String mandrillEvents
    ) throws JsonProcessingException {
        final var mandrillSignatureValid = mandrillSignatureValidator
          .valid(/* here I need request URI */, mandrillSignature, mandrillEvents);

        // code skipped for brevity

        return Response.ok().build();
    }

A: RESTEasy is implementation of JAX-RS and it provides facilities for obtaining and processing information about the context of individual requests.
JAX-RS has UriInfo class for that context. It provides both static and dynamic, per-request information, about the components of a request URI. You just need to use @Context annotation with UriInfo class to inject that context into your POST method.
It could be done like below:
@POST
public Response mandrill(
        @Context UriInfo uriInfo,
        @HeaderParam("x-mandrill-signature") String mandrillSignature,
        @FormParam("mandrill_events") String mandrillEvents
) throws JsonProcessingException {
    final var requestUri = uriInfo.getRequestUri();

    final var mandrillSignatureValid = mandrillSignatureValidator
      .valid(requestUri, mandrillSignature, mandrillEvents);

    // code skipped for brevity

    return Response.ok().build();
}


text:
Q: How to get a handle to current spec from beforeEach in jasmine test? I understand that currentSpec reference is no longer available in beforeEach from jasmine 2.0.0
(Ref: https://github.com/pivotal/jasmine/issues/492)
Is there an alternative to find the current Spec or Suite(a nested suite) in beforeEach?
Thanks,
vj.

A: You can use a reporter
describe("outer", function() {

  var specDescription, specFullName;

  (function() {
    jasmine.getEnv().addReporter({
      suiteStarted: function(result) {
        specDescription = result.description;
        specFullName = result.fullName;
      }
    });
  })();

  beforeEach(function() {
    console.debug(specDescription);
    console.debug(specFullName);
  });

  describe("test1", function() {
    it("bla bla", function() {});
  });
  describe("test2", function() {
    it("bla bla", function() {});
  });
}