text:
Q: Can a horcrux hold the souls of two different people? According to Harry Potter Wikia, A Horcrux is an object in which a Dark wizard or witch has hidden a fragment of his or her soul for the purpose of attaining immortality.
So the question is, is it possible for two Dark Wizards to split their soul and place the broken piece into the same object (e.g. a diary).
We have seen that more than one soul can exist in a body, as Harry had his own soul along with a piece of Voldemort's soul inside his body, and when Voldemort possessed Quirrell, Quirrell had his own soul along with Voldemort's mangled soul.
So can more than one fragment of a soul live in one object. Could multiple people make the same object their horcrux?

A: We... don't know.
This isn't specifically mentioned in the books, and I can't find anything on Pottermore or any other various canon works (Fantastic Beasts etc).
My guess is that it's possible, but nobody would want to. Why?
Take the scene with Ron and the locket. The Horcrux tries to take him over, turn him against Harry and Hermione. If you have two fragments in the same thing, which peice of soul would it do that for? If the two wizards who put the soul in have conflicting interests, how would it decide?
If someone is going after the Horcruxes of the other person, your Horcrux gets destroyed also if they find it.
More people know where your Horcruxes are if you share containers.
Why do I think it's possible? Because of the examples in the question - there are several instances of more than one soul in one body. Why should it be different for other objects?
Tl:dr:
It's not confirmed, but my guess is that it's possible but nobody would do it.

A: I think the answer here is a clear 'no'.
The part below contains spoilers to multiple Harry Potter books.
Tom Riddle himself explained at the graveyard that after being hit by the rebound of his killing curse, he was torn out of his body and used to live in animals and later in Quirrel. He needed unicorn blood to stay alive at that time (as you may remember from Philosopher's Stone).
This points toward saying that two souls cannot live in one object (in these examples, living things) for a long time without hurting or even killing the weaker soul.
In the prophecy it is said that one cannot live without the other dying, this may (I repeat, may as I am merely speculating) mean that Harry or Tom's soul piece in Harry, would die either way even if Harry was to turn away. By giving in to Tom in the end he made sure the right piece, the weaker piece that could not give in, was killed.
This would suggest that Nagini would not be able to grow very old either unless if the horcrux would literally take over. To strengthen this claim, Dumbledore told Harry he suspected the snake of being a horcrux as Tom had exceptional control over the snake, even for being a parselmouth (HP and the halfblood prince). This would be the case if his soul was the one in control.
This same reasoning  could apply for Ginny getting weaker while Tom-in-the-diary became stronger and she would ultimately die in order to give him the strength to rise up again (Chamber of Secrets) in the chamber. But as this does not literally contain two souls in one object as Ginny was not split so far as we know (though she may have been partly drained into the diary, we know that Tom-in-the-diary could take over her body for short times at that point).
I am sorry for not using the specific quotes from the books but I hope this answers your question.


text:
Q: PythonOperator fails where normal python code succeeds for google Bigquery I have a custom pythonoperator in an airflow instance that supposed to pull a list of records from bigquery that i can reference in a API look up.
    os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "/home/airflow/airflow/keys/the_JSON.json"

    client = bigquery.Client()
    geoclient = GeocodioClient('apikey')

    bq_sql = "SELECT ATTOM_ID, ADDRESS, CITY, STATE, ZIP FROM `project.dataset.tbl` Where GEOCODE_DT < DATE_SUB(CURRENT_DATE(), INTERVAL 2 month)  and ATTOM_ID IN (1, 2)"
    query_job = client.query(bq_sql)
    print(f'query job: {query_job}')
    results = query_job.result()  # Waits for job to complete.

ERROR - 400 Syntax error: Expected end of input but got identifier "Sedgwick" at [4:37]

"Sedgwick" is part of a value in a record.
When I attempt to run this code in the python interpreter my airflow server is at, it works fine.  but in a dag pythonoperator, I get the error.
What can I do?
thanks!

A: I found the error.  The environment in airflow was set different then what I thought it was.  by pushing the right modules to the right venv, the code started working.  Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sampling by group without repetition using data.table I'll use a hypothetical scenario to illustrate the question. Here's a table with musicians and the instrument they play and a table with the composition for a band:
musicians <- data.table(
  instrument = rep(c('bass','drums','guitar'), each = 4),
  musician = c('Chas','John','Paul','Stuart','Andy','Paul','Peter','Ringo','George','John','Paul','Ringo')
)

band.comp <- data.table(
  instrument = c('bass','drums','guitar'),
  n = c(2,1,2)
)

To avoid arguments about who is best with which instrument, the band will be assembled by sortition. Here's how I'm doing:
musicians[band.comp, on = 'instrument'][, sample(musician, n), by = instrument]

   instrument     V1
1:       bass   Paul
2:       bass   Chas
3:      drums   Andy
4:     guitar   Paul
5:     guitar George

The problem is: since there are musicians who play more than one instrument, it can happen that one person is drawn more than once.
One can build a for loop that, for each subsequent subset of instruments, draws musicians and then eliminates those from the rest of the table. But I would like suggestions on how to do this using data.table. Mainly because the kind of problem I need to solve in real life with this logic involves data bases with hundreds of thousands of rows. And also because I'm trying to better understand the data.table syntax.
As a reference, I tried some tips from Andrew Brooks blog, but couldn't come up with a solution.

A: This can be a solution, first you select an instrument by musician and then you select the musicians of your sample. But it may be that when selecting an instrument per musician your sample size is larger than the population then you will get an error (but in your real data this may not be a problem).
musicians[, .(instrument = sample(instrument, 1)), by = musician][band.comp, on = 'instrument'][, sample(musician, n), by = instrument]

A: You could expand the band comp into sum(band.comp$n) distinct positions and keep sampling until you find a feasible composition:
roles = musicians[,
  CJ(posn = 1:band.comp[.BY, on=.(instrument), x.n], musician = musician)
, by=instrument]

set.seed(1)
while (TRUE){
  roles[sample(1:.N), keep := !duplicated(.SD, by="musician") & !duplicated(.SD, by=c("instrument", "posn"))][]
  if (sum(roles$keep) == sum(band.comp$n)) break
}

setorder(roles[keep == TRUE, !"keep"])[]

   instrument posn musician
1:       bass    1   Stuart
2:       bass    2     John
3:      drums    1     Andy
4:     guitar    1   George
5:     guitar    2     Paul

There's probably something you could do with linear programming or a bipartite graph to answer the question of whether a feasible comp exists, but it's unclear what "sampling" even means in terms of the distribution over feasible comps.

A: Came across a relevant post: Randomly draw rows from dataframe based on unique values and column values and eddi's answer is perfect for this OP:
#keep number of musicians per instrument in 1 data.table
musicians[band.comp, n:=n, on=.(instrument)]

#for storing the musician that has been sampled so far
m <- c()

musicians[, {
    #exclude sampled musician before sampling
    res <- .SD[!musician %chin% m][sample(.N, n[1L])]
    m <- c(m, res$musician)
    res
}, by=.(instrument)]

sample output:
   instrument musician n
1:       bass   Stuart 2
2:       bass     Chas 2
3:      drums     Paul 1
4:     guitar     John 2
5:     guitar    Ringo 2

Or more succinctly with error handling as well:
m <- c()
musicians[
    band.comp,
    on=.(instrument),
    j={
        s <- setdiff(musician, m)
        if (length(s) < n) stop(paste("Not enough musicians playing", .BY))
        res <- sample(s, n)
        m <- c(m, res)
        res
    },
    by=.EACHI]


text:
Q: Allow author to upload image via Media button without plugin I believe as default WordPress won't allow author to upload image via Media button on TinyMCE. It will give you You don't have permission to attach files to this post. error message if you do.
I'm working on a plugin that will allow authors to write and upload images from TinyMCE and looking for solution to grant permission to author to upload images.
How do I achieve this without using other plugins?
Update
I have added below code on my plugin file and it somehow made author to upload image from frontend via Add Media button. However, I'm not quite sure what it really did.
I remember seeing that WP stored role capability data in DB. I'm assuming one of below code save setting for Author and it works after that?
function wh_edit_roles(){
    if ( current_user_can( 'edit_posts' ) ){
        $user = new WP_User(get_current_user_id());
        $user->add_cap('edit_post');
        $user->add_cap('edit_others_pages');
        $user->add_cap('edit_published_pages');
    }
}
add_action('wp_head', 'wh_edit_roles');

A: in the basic configuration the user role contributor and subscriber do not have the capability upload_files. The user role author has this capability.
The capability upload_files gives the user the panels "Media" and "Media > Add New".
If you want another role to grant this capability, you can use the function add_cap(). Since such changes are written into the database, it makes sense to use this function at the moment your plugin gets activated in order not to write to the database with every page load (since you could also use this funtion in lets say the init hook). So you should also have a look into register_activation_hook(). Assuming, you place this code into the "root" file of your plugin this should work:
<?php
    function wpse210884_add_upload_files_cap() {
        $role = get_role( 'contributor' ); //The role you want to grant the capability
        $role->add_cap( 'upload_files' );
    }

    register_activation_hook( __FILE__, 'wpse210884_add_upload_files_cap' );
?>


text:
Q: What variant of using UnitOfWork in service is more proper? Good day!
My system has N-Layer architecture:

*

*DAL (Data Access Layer) (Entity Framework 6, Repositories,
UnitOfWork)

*BLL (Busisness Logic Layer)

*PL (Presentation layer) (ASP.NET MVC 4)

The question is as follows:
What variant of UnitOfWork using is more proper?
First variant (characteristic's use, explicitly call Dispose() in controller ASP.NET MVC):
namespace MyApp.BLL.Services
{
    public class MyService
    {
    private UnitOfWork _uow { get; set; }

    public MyService()
    {
      _uow = new UnitOfWork();
    }

    public List<SomeDTO> SomeGetMethod()
    {
      IEnumerable<Entity> entities = _uow.SomeRepository.Get(x => x.Id==1);
      ...
      return ...
    }

    public void SomeSetMethod(int value)
    {
      _uow.SomeRepository.Insert(new Entity { Value = value });

      _uow.Commit(); // SaveChanges();
    }

    public Dispose()
    {
      _uow.Dispose();
    }
  }
}

Second variant (using block):
namespace MyApp.BLL.Services
{
    public class MyService
    {
    public List<SomeDTO> SomeGetMethod()
    {
      using(UnitOfWork uow = new UnitOfWork())
      {
        IEnumerable<Entity> entities = uow.SomeRepository.Get(x => x.Id==1);
      }
      ....
      return ...
    }

    public void SomeSetMethod(int value)
    {
      using(UnitOfWork uow = new UnitOfWork())
      {
        uow.SomeRepository.Insert(new Entity { Value = value });

        uow.Commit(); // SaveChanges();
      }
    }
  }
}

And the second question:
For example we have a service, which is responsible for message module work in system - IMessagesService and we also have second service, which is responsible for  some module - ISomeService. In result of making a method in service ISomeService it's necessary to send a message in system. Will it be correct to call method of another IMessagesService for sending a message?
Example:
public interface IMessagesService
{
  void Send(int userFrom, int userTo, string message);
  // other methods...
}

public class MessageService
{
  public void Send(int userFrom, int userTo, string message)
  {
    // some logic here
  }
}

public interface ISomeService
{
  void SomeMethod(int somevalue);
}

public class SomeService: ISomeService
{
  public void SomeMethod(int somevalue)
  {
    // some logic here

    // после необходимо отправить сообщение
    messageService = new MessageService();
    messageService.Send(1, 2, "some text");
  }
}

In another words- is it correct to call from one service method of second service?
Thanks in advance!

A: The private variable unitofwork I think is a better approach, as it leans more towards Inversion of control but the control is not injected, and the Using block approach to me shoudn't be done in the services them selves.
The unitofwork object should be injected, and controlled elsewhere. IMO the entire point of a unitofwork pattern is to encapsulate a transaction scope. This transaction scope should be able to span services. Good encapsulation principle direct us into making atomic services, that are singular focused (SOLID). i.e. in your case, everything to do with Messages should be in the message service, and rightly so. But as you've seen, because of this principle, other services may need to send a message. So yes, I think it is not unreasonable for one service to call another, especially if there is business rules that need to be enforced. In fact multiple services going to the same repository to potentially do the same thing violates DRY IMO.
 I also think it would be desired behaviour to not send a message if there is a failure, or rollback the first action (what ever it may be) if the message sending fails. You could of course test for this (if.. then .. type pattern), and potentially manually write rollback code (ugly!) but wrapping up all of the services you are using with the same unitofwork means you have a rollback (and commit) type approach anyway (especially if you are using an ORM mapper, i.e. Entity Framework), and lots of embedded if statements can be a bit of a code smell IMO.
So you are not injecting the unitofwork into the services, so your transaction scope is limited only to the service it is created in. Also makes it more difficult to test. All of these issues are exactly the same things I am going through right now on another project, which follows the same code structure/approach, and I will be the first say, I haven't found a perfect approach yet either but I would approach it something more like this:
//Base service class to take the unit of work injection
public abstract class BaseService
    {
    private IUnitOfWork _uow { get; private set; }

    public BaseService(IUnitOfWork scope)
    {
      _uow = scope;
    }
}

and then service class implementations
public class SomeService: BaseService, ISomeService
{
    public MyService(IUnitOfWork scope) : base(scope)
    {

    }
  public void SomeMethod(int somevalue)
  {

    //Do something in this service
    //code here.....

   //then do something in the next service, passing though
    //the same unitof work

    messageService = new MessageService(_uow );
    messageService.Send(1, 2, "some text");
  }
}

This passes the responsiblity of controlling the unitofwork (scope) to the caller. In your case the PL presentation layer, or for ease of testing another test class if you wish. From PL something like:
//PL Controller that does something cool
public class BaseService : Controller
{

    public ActionResult DoSomething(int value)
    {
        using(IUnitOfWork scope = new UnitOfWork())
        {
            ISomeService theService = new SomeService(scope);
            theService.SomeMethod(value);
        }
        ...con
    }

}

I actually put another layer inbetween PL and BLL to control the scope, and Dependancy inject the services, sort of a unitofworkcontroller if you will.
Anyway my two cents


text:
Q: How do I get Cypress to return the window.it body in the softAssert patch? I have implemented the answer from this Does cypress support soft assertion? successfully and can softAssert(expression, 'message') like so. I won't repost the code below, it is included in the link.
However, I have noticed that when using the mochawesome-report generator it's report content uses the body from
'test:after:run', (result) => {
    result.body
}

Usually in Cypress this is given by the window.it where .it represents each it('test title') block in the spec file.
But when the softAssert is used, specifically in this part, where window.it is overwritten from commands.js:
// monkey-patch `it` callback so we insert `cy.then()` as a last command
// to each test case where we'll assert if there are any soft assertion errors
function itCallback ( func ) {
    func();
    cy.then(() => {
        if ( errors.length ) {
            const _ = Cypress._;
            let msg = '';

            if ( Cypress.browser.isHeaded ) {

                msg = 'Failed soft assertions... check log above ↑';
            } else {

                _.each( errors, error => {
                    msg += '\n' + error;
                });

                msg = msg.replace(/^/gm, '\t');
            }

            throw new Error(msg);
        }
    });
}

const origIt = window.it;
window.it = (title, func) => {
    origIt(title, func && (() => itCallback(func)));
};
window.it.only = (title, func) => {
    origIt.only(title, func && (() => itCallback(func)));
};
window.it.skip = (title, func) => {
    origIt.skip(title, func);
};

The issue is that my report is now showing the test body as:
return itCallback(func)

And I assume that it is because of this thing: origIt(title, func && (() => itCallback(func)));
How do I fix this and return the actual it() block body while keeping the softAssert functionality.
I have tried for the past few days to solve this and am having no luck. If https://stackoverflow.com/users/927631/dwelle or https://stackoverflow.com/users/5878476/jennifer-shehane or https://stackoverflow.com/users/4168257/gleb-bahmutov are online, I need a real pro to reach out, I'm stumped.

A: I guess they call it monkey-patch for a reason.
It looks like you are trying to run the error collection code after the it(), why not use afterEach()?
afterEach(() => {
  if ( errors.length ) {
    const separator = '\n\t';
    const msg = Cypress.browser.isHeaded ?
      'Failed soft assertions... check log above ↑' :
      seperator + errors.join(separator);
    throw msg;
  }
})

A better way to do soft assertions is given here How can i use soft assertion in Cypress.
It makes use of the soft-assert package (17000 downloads pw) and gives you a couple of simple custom commands to implement
const jsonAssertion = require("soft-assert")

Cypress.Commands.add('softAssert', (actual, expected, message) => {
  jsonAssertion.softAssert(actual, expected, message)
  if (jsonAssertion.jsonDiffArray.length) {
    jsonAssertion.jsonDiffArray.forEach(diff => {

      const log = Cypress.log({
        name: 'Soft assertion error',
        displayName: 'softAssert',
        message: diff.error.message
      })

    })
  }
});

Cypress.Commands.add('softAssertAll', () => jsonAssertion.softAssertAll())


text:
Q: How to filter the list based on generic property I am trying to remove the hardcoding here while using the LINQ.
Basically I have 10 properties and based on the selected property I want to filter the list.
Can someone help me removing this kind of hardcoding, is there a way to get the information of the property based on the "propertyName" string value and using the same while filtering the list.
Below is the code for reference
Please let me know if my question makes sense.
Thanks in advance for the help.
if (propertyName == "Property1")
                {
                    FilteredList = CurrentList.Where(x => x.property1== propertyValue.ToString()).ToList();
                }
                else if (propertyName == "Property2")
                {
                    FilteredList = CurrentList.Where(x => x.property2== propertyValue.ToString()).ToList();
                }

A: a. Reflection (if values of propertyName match actual property names)
var t = typeof(...your type...);
var pi = t.GetProperty(propertyName);

CurrentFilterList = AfterFilterList
      .Where(x => pi.GetValue(x).ToString() == propertyValue)
      .ToList();

b. If property names don't match, then you could try this:
var funcs = new Dictionary<string, Func<your_type, object>>
{
   {"Company", v => v.Company},
   {"InspectionUnit", v => v.InspectionUnit}
};

var f = funcs[propertyName];
CurrentFilterList = AfterFilterList
   .Where(x => f(x) == propertyValue.ToString()).ToList();

Code may be inaccurate but should show the idea. #2 should have better performance.
BTW funcs could be built dynamically using reflection as well -- just iterate through all props and create funcs / expressions on the fly.

A: Here's a function that creates the Where condition without reflection. Just for the sake of illustration, if the property name isn't recognized it returns a condition that always returns true - in other words, no filter. An exception might make more sense in response to unrecognized input.
private Func<Thing, bool> GetCondition(string propertyName, string propertyValue)
{
    switch (propertyName)
    {
        case "Company":
            return thing => thing.Company == propertyValue;
        case "InspectionUnit":
            return thing => thing.InspectionUnit == propertyValue;
        default: return thing => true;
    }
}

Here's a version that uses reflection. As long as we're going this route there's no need to restrict the property to string values. It could be anything as long as the Equals is implemented, which will be true for strings and value types.
private Func<Thing, bool> GetCondition<TSourceType, TPropertyType>
    (string propertyName, TPropertyType propertyValue)
{
    var property = typeof(TSourceType).GetProperty(
        propertyName, BindingFlags.Instance | BindingFlags.Public);
    if (property?.PropertyType != typeof(TPropertyType))
        return thing => true; // or throw an exception.
    return thing => property.GetValue(thing).Equals(propertyValue);
}

For performance it would be beneficial to store the reflected property in something like a Dictionary<Type, Dictionary<string, PropertyInfo>> so that for any given type and property name you can look it up instead of repeating the reflection.
Between the two, I would lean toward not using reflection in a your scenario if you're really just looking at a handful of possible values and you're dealing with known types.
Now the usage would be
Non-generic/non-reflection
var condition = GetCondition(propertyName, propertyValue);
var filtered = unfiltered.Where(condition);

generic/reflection
var condition = GetCondition<Thing, string>(propertyName, propertyValue);
var filtered = unfiltered.Where(condition);

When I mention storing properties in a dictionary, that's something like this:
private readonly Dictionary<Type, Dictionary<string, PropertyInfo>> _properties = new Dictionary<Type, Dictionary<string, PropertyInfo>>();

private PropertyInfo GetProperty(Type sourceType, string propertyName)
{
    if(!_properties.ContainsKey(sourceType))
        _properties.Add(sourceType, new Dictionary<string, PropertyInfo>());
    if (_properties[sourceType].ContainsKey(propertyName))
        return _properties[sourceType][propertyName];
    var property = sourceType.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public);
    _properties[sourceType].Add(propertyName, property);
    return property; // could be null;
}

But again, that's all just to give an example. It's massive overkill for the scenario you're describing.


text:
Q: Query for determining what UserRoles are available under a given UserLicense I am using Salesforce API to create new SF user accounts with a particular Profile and User role.  SF API provides a straight forward way of using the UserLicense to determine what Profiles apply under a given license.  However it is unclear to me how to determine what UserRoles are available under a given license. When creating a new user Account manually using the Salesforce portal, there is even a tip next to the Role field that says that user roles are determined based on the user license - how would you do this programmatically?

A: I might be reading your question wrong, but I don't think there is a direct relationship between UserRole and UserLicense like there is between Profile and UserLicense.
The User, Sharing, and Permission Objects data model might help here.


text:
Q: it needs too long time to take effect for adding root admin permission to other using az ClL use Azure CLI https://learn.microsoft.com/en-us/cli/azure/purview/account?view=azure-cli-latest#az-purview-account-add-root-collection-admin to  add root collection admin permisson to others for purview account. Actually ,the use was added after executing command line ,but it needs almost one hour to take effect. this doesn't make sense

A: I have been using purview for quite sometime but never faced the issue with collection admin permissions reflects in 1+hour. It happens instantly.
If you still having issues, I suggest you to raise a support ticket.


text:
Q: How do you display JSON API data in a table view? I am not able to display the JSON data in my table view. I don't know why. I tried to get the JSON data, but I am not able to display it on screen in a table format.
This is the model:
class PastTripsVC: UIViewController {
    var past = [PastRide]()
    @IBOutlet weak var mTable: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        let nibCell = UINib(nibName: "PastTableView", bundle: nil)
        mTable.register(nibCell, forCellReuseIdentifier: "cell")
        apiCalling()
    }

    func apiCalling(){
        if let url = URL(string: "https://pincood.com/pincood/public/api/user/trips") {
            var request = URLRequest(url: url)
            request.allHTTPHeaderFields = [
                "Content-Type": "application/json",
                "Session": "fb4e7f9b-0f31-4709-",
                "AUthorization":"<some key>"
            ]

            URLSession.shared.dataTask(with: request) { (data, response, error) in
                guard error == nil else { return }
                guard let data = data else { return }
                do{
                    let codabledata = try JSONDecoder().decode([PastRide].self, from: data)
                    print(codabledata)
                    DispatchQueue.main.async {
                        self.past = codabledata
                        self.mTable.reloadData()
                    }
                } catch {
                    print(error)
                }
            }.resume()
        }
    }

In the extension we try:
extension PastTripsVC : UITableViewDelegate, UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return past.count
        print(past.count)
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! PastTableView
        cell.usernm.text = past[indexPath.row].provider.firstName
        return cell
    }

    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let details : PastDetailView = self.storyboard?.instantiateViewController(withIdentifier: "PastDetailView") as! PastDetailView
        navigationController?.pushViewController(details, animated: true)

    }
}

A: You need to set table view's delegate and datasource properties in viewDidLoad.
Update your viewDidLoad to look like this:
override func viewDidLoad() {
    super.viewDidLoad()
    let nibCell = UINib(nibName: "PastTableView", bundle: nil)
    mTable.register(nibCell, forCellReuseIdentifier: "cell")
    mTable.delegate = self
    mTable.datasource = self
    apiCalling()
}


text:
Q: Prove that a graph cannot have two distinct spanning trees
Prove that a graph cannot have two distinct spanning trees.

I'm confused with this proof. More so that I think I'm confused as what distinct in this context means? Initially I thought it was that these $2$ possible spanning trees cannot share the same edges, but in fact, distinct trees may still share some edges.
Any sort of clarification on this would help me a lot.
Thanks

A: Here's $K_4$ with two completely edge-disjoint spanning trees shown as red edges and green edges:

Here's $K_6$ with three edge-disjoint spanning trees:


text:
Q: How to use Up/Down arrows to navigate textboxes I have the following page:
          <head runat="server">
    <title></title>
    <script type="text/javascript">
        var current = "";

        function Tab(e) {
            var evtobj = window.event ? event : e;
            var unicode = evtobj.charCode ? e.charCode : evtobj.keyCode;

            var targ;
            if (evtobj.target) targ = evtobj.target;
            else if (evtobj.srcElement) targ = evtobj.srcElement;

            if (unicode == 37) {
                var elements = document.getElementsByTagName("input");
                for (var i = 0; i < elements.length; i++) {
                    if (elements[i].tabIndex == targ.tabIndex - 1) {
                        elements[i].focus();
                        return true;
                    }
                }
            }
            else if (unicode == 39) {
                var elements = document.getElementsByTagName("input");
                for (var i = 0; i < elements.length; i++) {
                    if (elements[i].tabIndex == targ.tabIndex + 1) {
                        elements[i].focus();
                        return true;
                    }
                }
            }
            else {
                return true;
            }
        }
    </script>
</head>
<body onkeydown="return Tab(event);">
    <form id="form1" runat="server">
    <asp:TextBox ID="TextBox1" TabIndex="1" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox2" TabIndex="2" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox3" TabIndex="3" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox4" TabIndex="4" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox5" TabIndex="5" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Button" />

        <br />
    <asp:TextBox ID="TextBox6" TabIndex="6" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox7" TabIndex="7" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox8" TabIndex="8" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox9" TabIndex="9" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox10" TabIndex="10" runat="server"></asp:TextBox>
    </form>
</body>

It works fine with Right/Left arrows navigation depending on the tab index for each textbox, I need to do the same with the Up/Down arrows, to navigate up and down by setting focus on the textbox above or under the current text box, for example, if focus is on textbox 3 and I press down arrow the focus should move to textbox 8 as it's under it, and vis versa.


text:
Q: maximum product of distances of a point and vertices of equilateral triangle If $ABC$ is an equilateral triangle. $P$ is a variable point inside the triangle or on its sides. We need to find the maximum product of $AP \cdot BP \cdot CP$.
This question is in a Complex Analysis homework.
I don't know how can I use the complex analysis (maybe, maximum modulus theorem ) to find the maximum product.
Updated work
Let $z_1$, $z_2$, $z_3$ and $z$ correspond to the vertices $A$, $B$, $C$, and variable point $p$, respectively, then the product function is given by
$f(z)=|z-z_1||z-z_2||z-z_3|$, clearly, $(z-z_1)(z-z_2)(z-z_3)$ is nonconstant holomorphic function in $\mathbb{C}$ and so in $\overline{T}$, where $T$ represents the region inside the equilateral triangle. Then by the Maximum modulus Theorem, $f$ attains the maximum on the boundary $\partial T$. To this point, is there a way to find $z$ explicitly that maximize $f$?

A: Up to a similitude $s(z)=az+b$, we can reduce the issue to equilateral triangle $T$ with vertices:
$$z_1=1, \ \ z_2=\omega, \ \ z_3=\omega^2=\overline{\omega} \ \ \text{with} \ \ \omega=e^{2i \pi/3} $$
Therefore: AP.BP.CP is the absolute value of :
$$(z-1)(z-\omega)(z-\omega^2)=z^3-1$$
The maximum value of this holomorphic function, call it $f(z)$, is reached for a $z$ belonging to the boundary (Maximum Modulus Theorem, as you have noticed). Let us parametrize the line segment from $1$ to $\omega$ in the following way:
$$z=(1-t)+t \omega, \ \ \ \ 0\le t \le 1\tag{1}$$
The image by $f$ of this line segment is the red "drop-like" cubic curve (see equation in the remark below).
The two other sides
$$z'=(1-t)\omega+t \omega^2, \ \  z''=(1-t)\omega^2+t$$
can be written under the form:
$$z'=\omega z, \ \  z''=\omega^2 z \tag{1}$$
Therefore, because $\omega^3=1$ and $(\omega^2)^3=1$, the image by $f$ of these two other sides obtained by taking to the third power expressions (1) gives the same curve!
This is the image $f(\partial T)$. The image by function $f$ of $T$ itself is the inside of the drop. The sister curve described as the image of $\partial T$ by $g(z):=z^3$ is magenta curve.
Considering the red curve, $f(z)=z^3-1$ reaches its maximal value for $z_m^3-1=I'$, which corresponds to:
$$z_m^3=-\tfrac18 \ \ \text{(point I')} \tag{2}$$
Cubic equation (2) has three solutions. As the argument of $I$ is $\pi+k 2 \pi$, the arguments of solutions $z_m$ must be $\pi/3 + k 2 \pi/3$. As the maximum must occur on the boundary, taking $k=0,1,2$ gives points $J_0, J_1, J_2$ resp., i.e., the midpoints of the sides of triangle $T$.

Fig. 1: The three maximizing solutions $J_0, J_1, J_2$.
Remark: The parametric equations of the "drop" obtained by taking the real and imaginary parts of $((1-t)+t \omega)^3$ are
$$(x=1-\tfrac92 t(1-t), \ \ \ y=\tfrac{3\sqrt{3}}{2}t(1-t)(1-2t))$$


text:
Q: jQuery onclick function is not executing I am finding the latitude and longitude of an address entered by a user. I am calling a jQuery function on button click of a form. But the controller method is executed before this jQuery function. What I want is when a user clicks the submit button, the jQuery function is called after the success controller function is called.
View:

    <input type="submit" value="submit"  onclick="getCoordinates()" id="sumbitBtn"/>

Loading this code and pressing submit button you will get message in console window:
onsubmit called!

To get it running properly and have second message displayed (it is instead of geocode() functions, you have to remove $("#sumbitBtn").click(function(){ and closing part. After that we will get two messages:
onsubmit called!
$("#sumbitBtn").click() deleted!

If your code doesn't work after changes that means there is another error.

A: First you have your function:
function getCoordinates() {
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode({ 'address': '#street' }, function (results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    alert("location : " + results[0].geometry.location.lat() + " " + results[0].geometry.location.lng());
                    $(selector).val(value)
                    var latitude = results[0].geometry.location.lat();
                    var longitude = results[0].geometry.location.lng();
                    $('latitude').val('latitude');
                    $('longitude').val('longitude');

                    $.ajax({
                        type: "POST",
                        dataType: 'json',
                        data: {

                            mylat: latitude,
                            mylang: longitude
                        },
                        url: "RentOutSpace/AddSpaces",
                        success: function (result) { success(result); }
                    });

                } else {
                    alert("Something got wrong " + status);
                }
            });

            return false;//prevent form submit
    }

Then you can attach it the javascript way on the element onClick:
<input type="submit" value="submit"  onclick="getCoordinates()" id="sumbitBtn"/>

Or the jquery way on a separate file/section:
$(function(){//when the document is ready
    $("#sumbitBtn").click(getCoordinates);
});


text:
Q: WordPress Audio Player Stops Video Background I am building a WordPress site and the home page needs:
1. A video background that autoplays.
2. A sound track that autoplays in sync with the video, but can be paused or muted by the user. Ideally the audio would autoplay already muted.
The problem I'm having is that as soon as the audio player autoplays or is played manually, the video background stops.
Is there a different plugin or some custom code I can use to ensure the video background continues to play when the separate audio track starts?
Any suggestions are greatly appreciated.
The site is available at: http://gsh.justprm.co.uk/
The theme is Salient: https://themeforest.net/item/salient-responsive-multipurpose-theme/4363266
The audio plugin I'm currently using is: https://www.wonderplugin.com/wordpress-audio-player/

A: I want to give you a simple solution that you can use. This solution wouldn't obviously work if you're keen to have both the video background and the audio as two separate elements on your site. But if otherwise, the solution I'm going to offer you will work perfectly.
1) Edit the homepage video you're using and add the music you want to play with it onto the video itself. So that the video's music will be the track you want to play.
2) Use slider revolution plugin to build your homepage slider and build the video slider.
3) Add an icon to mute/unmute the audio for the video playing on the slider. You can see how it's done here: https://www.themepunch.com/faq/add-a-muteunmute-button-for-video/
By these above steps, a) You will achieve perfect synchronization between the video and the audio b) You will load audio unmuted and STILL give the user to mute the audio and continue to play the video.
This is a non-technical, straight up easy solution.


text:
Q: Creating Vim like functionality with AutoHotKey (AHK) I've been using autoHotKeyrecently on a windows 8 machine and loving it. But I want to be able to press caps lock and turn the keyboard into a vim like command mode for moving the cursor, inserting and deleting easily in any program.
UPDATE (Thanks to @MCL for the help so far)
Im trying to use the following script but it wont change the behaviour based on the state
state := GetKeyState("Capslock", "T")
if state
  j::Send,{Left}
  l::Send,{Right}
  i::Send,{Up}
  k::Send,{Down}
return

A: Create context-sensitive hotkeys with #If:
#If GetKeyState("CapsLock", "T")=1

; The following hotkeys will only be effective if GetKeyState("CapsLock", "T")=1
j::Send,{Left}
l::Send,{Right}
i::Send,{Up}
k::Send,{Down}

#If ; end of #If


text:
Q: Controlar excepción de HttpHandler Estaba realizando una aplicación que se conecta a un servidor para obtener un json, el cual mostrará en un listview.
La aplicación me funciona correctamente, pero me gustaría saber como puedo controlar el error que devuelve el método doInBackground si el servidor no está disponible por el motivo que sea. Lo he intendado con un try pero cuando lleva un rato intentando conectarse al servidor la apliación se cierra
@Override
    protected Void doInBackground(Void... voids) {

        HttpHandler hh = new HttpHandler();

        String infoObtenida=null;

        //Solicito el listado de información al servidor
        try{
            infoObtenida = hh.SolicitarNoticias(ruta);
        }catch (Exception ex){
            ex.printStackTrace();
        }

        if (infoObtenida != null) {
            try {
                //Cogemos el objeto json
                JSONObject objetoJSON = new JSONObject(infoObtenida);

                //Cogemos la infomación de cada noticia
                JSONArray noticias = objetoJSON.getJSONArray("noticia");

                //Recorremos cada una de las noticias y la añadimos a la coleccion
                for (int i = 0; i < noticias.length(); i++) {

                    JSONObject n = noticias.getJSONObject(i);

                    int id = n.getInt("id");
                    String titulo = n.getString("titulo");
                    String imagen = n.getString("imagen");
                    String texto = n.getString("texto");

                    //Añado cada noticia a la coleccion
                    todasNoticias.add(new Noticia(id,titulo,imagen,texto));

                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        } else {
            Toast.makeText(getApplicationContext(),
                    "No se puede obtener la información del servidor, posiblemente el servidor esté caido",
                    Toast.LENGTH_LONG)
                    .show();

        }

        return null;
    }

----Método SolicitarNoticias
    public String SolicitarNoticias(String ruta) {
    String respuesta = null;

    try {
        //Conectamos con el servidor
        URL url = new URL(ruta);
        HttpURLConnection conexion = (HttpURLConnection) url.openConnection();
        conexion.setRequestMethod("GET");

        //Leemos la respuesta del servidor, y la almacenamos en formato texto en una variable
        InputStream is = new BufferedInputStream(conexion.getInputStream());
        respuesta=transformarFlujoACadena(is);
    } catch (MalformedURLException e) {
        Log.e(TAG, "MalformedURLException: " + e.getMessage());
    } catch (ProtocolException e) {
        Log.e(TAG, "ProtocolException: " + e.getMessage());
    } catch (IOException e) {
        Log.e(TAG, "IOException: " + e.getMessage());
    } catch (Exception e) {
        Log.e(TAG, "Exception: " + e.getMessage());
    }

    return respuesta;
}

-- Logcat


text:
Q: NEXTJS Error: Failed prop type: The prop `href` expects a `string` or `object` in ``, but got `undefined` instead When I imported the Link from next/link, trying to pass the dynamic endpoint in my components. it gave me an error like this.

I look around that someone suggest to add a  tag, it also gave an error. Any one can help? thanks.

I followed the tutorial, he didn't get any errors. what's the problem?

A: It's not the first <Link/> in your component, it's the second  . The second one has no href. It only has className="text-lg".


text:
Q: External USB hard drive ext4 partition mounts as read-only on Ubuntu 14.04.5 LTS, e2fsck recommended When I plug my 1-terabyte Seagate hard drive in a USB port on my desktop PC, it mounts NTFS filesystem /dev/sdc1 successfully
but fails to mount ext filesystem /dev/sdc2 because of an apparent error loading the filesystem journal.
Here is what appears in /var/log/syslog during the few seconds after I plug the drive in:
Jun 24 20:48:11 somehost kernel: [6670321.891087] usb 1-1.2: new high-speed USB device number 44 using ehci-pci
Jun 24 20:48:11 somehost kernel: [6670322.010683] usb 1-1.2: New USB device found, idVendor=0bc2, idProduct=2332
Jun 24 20:48:11 somehost kernel: [6670322.010689] usb 1-1.2: New USB device strings: Mfr=1, Product=2, SerialNumber=3
Jun 24 20:48:11 somehost kernel: [6670322.010693] usb 1-1.2: Product: Portable
Jun 24 20:48:11 somehost kernel: [6670322.010696] usb 1-1.2: Manufacturer: Seagate
Jun 24 20:48:11 somehost kernel: [6670322.010699] usb 1-1.2: SerialNumber: 2GHH43FZ
Jun 24 20:48:11 somehost mtp-probe: checking bus 1, device 44: "/sys/devices/pci0000:00/0000:00:1a.0/usb1/1-1/1-1.2"
Jun 24 20:48:11 somehost mtp-probe: bus: 1, device: 44 was not an MTP device
Jun 24 20:48:11 somehost kernel: [6670322.011257] usb-storage 1-1.2:1.0: USB Mass Storage device detected
Jun 24 20:48:11 somehost kernel: [6670322.011309] scsi50 : usb-storage 1-1.2:1.0
Jun 24 20:48:12 somehost kernel: [6670323.011231] scsi 50:0:0:0: Direct-Access     Seagate  Portable         SF04 PQ: 0 ANSI: 4
Jun 24 20:48:12 somehost kernel: [6670323.011508] sd 50:0:0:0: Attached scsi generic sg3 type 0
Jun 24 20:48:12 somehost kernel: [6670323.012501] sd 50:0:0:0: [sdc] 1953525164 512-byte logical blocks: (1.00 TB/931 GiB)
Jun 24 20:48:12 somehost kernel: [6670323.014587] sd 50:0:0:0: [sdc] Write Protect is off
Jun 24 20:48:12 somehost kernel: [6670323.014591] sd 50:0:0:0: [sdc] Mode Sense: 1c 00 00 00
Jun 24 20:48:12 somehost kernel: [6670323.017357] sd 50:0:0:0: [sdc] Write cache: enabled, read cache: enabled, doesn't support DPO or FUA
Jun 24 20:48:12 somehost kernel: [6670323.059605]  sdc: sdc1 sdc2
Jun 24 20:48:12 somehost kernel: [6670323.124689] sd 50:0:0:0: [sdc] Attached SCSI disk
Jun 24 20:48:15 somehost kernel: [6670325.576840] end_request: critical target error, dev sdc, sector 0
Jun 24 20:48:15 somehost kernel: [6670325.576848] JBD2: recovery failed
Jun 24 20:48:15 somehost kernel: [6670325.576852] EXT4-fs (sdc2): error loading journal
Jun 24 20:48:16 somehost ntfs-3g[508]: Version 2013.1.13AR.1 external FUSE 29
Jun 24 20:48:16 somehost ntfs-3g[508]: Mounted /dev/sdc1 (Read-Write, label "Expansion Drive", NTFS 3.1)
Jun 24 20:48:16 somehost ntfs-3g[508]: Cmdline options: rw,nosuid,nodev,uhelper=udisks2,uid=1000,gid=1000,dmask=0077,fmask=0177
Jun 24 20:48:16 somehost ntfs-3g[508]: Mount options: rw,nosuid,nodev,uhelper=udisks2,allow_other,nonempty,relatime,default_permissions,fsname=/dev/sdc1,blkdev,blksize=4096
Jun 24 20:48:16 somehost ntfs-3g[508]: Global ownership and permissions enforced, configuration type 7
Jun 24 20:48:16 somehost udisksd[2934]: Mounted /dev/sdc1 at /media/ps/Expansion Drive on behalf of uid 1000

In this case, the sdc2 partition is inaccessible, but other times, it gets mounted successfully, except that
it is read-only, and I see this:
Jun 24 20:56:21 somehost kernel: [6670811.293826] EXT4-fs (sdc2): warning: mounting fs with errors, running e2fsck is recommended
Jun 24 20:56:21 somehost kernel: [6670811.295543] EXT4-fs (sdc2): mounted filesystem with ordered data mode. Opts: (null)
Jun 24 20:56:21 somehost udisksd[2934]: Mounted /dev/sdc2 at /media/ps/f9940392-a20f-461d-a7c3-6c1132acf20b on behalf of uid 1000
Jun 24 20:56:26 somehost kernel: [6670816.539506] end_request: critical target error, dev sdc, sector 1218352432
Jun 24 20:56:26 somehost kernel: [6670816.539518] Aborting journal on device sdc2-8.

When I try "touch foobar" in the sdc2 mount point, I get "cannot touch 'foobar': Read-only file system".
I plugged this same drive on a ChromeBook, and the sdc2 partition is successfully mounted as read-write,
and I can create files on it.
Back on the PC, I tried "e2fsck/dev/sdc2" and got this:
e2fsck 1.42.9 (4-Feb-2014)
/dev/sdc2: recovering journal
/dev/sdc2 contains a file system with errors, check forced.
Pass 1: Checking inodes, blocks, and sizes
Pass 2: Checking directory structure
Pass 3: Checking directory connectivity
Pass 4: Checking reference counts
Pass 5: Checking group summary information
/dev/sdc2: 2131785/45793280 files (0.2% non-contiguous), 128417943/183154845 blocks

When I mount the partitions again, I still get this:
Jun 24 21:05:44 somehost kernel: [6671374.212541] end_request: critical target error, dev sdc, sector 1218352432
Jun 24 21:05:44 somehost kernel: [6671374.212568] Aborting journal on device sdc2-8.

fdisk says this:
Disk /dev/sdc: 1000.2 GB, 1000204883968 bytes
255 heads, 63 sectors/track, 121601 cylinders, total 1953525164 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0xa03cb026

   Device Boot      Start         End      Blocks   Id  System
/dev/sdc1              63   488281367   244140652+   7  HPFS/NTFS/exFAT
/dev/sdc2       488281368  1953520127   732619380   83  Linux

This problem did not happen before I upgraded Ubuntu from 12.04 to 14.04, but that is likely a coincidence.
Questions:

*

*Could this be a hardware problem with the drive?

*Should I try e2fsck with any command-line options to force it to fix the problem, if possible?

*Is the only solution to reformat sdc2 (with mke2fs)? (The data is
not very important, as it is a bunch of backups.)
Thanks.


text:
Q: How can I get my footnotes placed similarly in the columns of my document I just noticed that footnotes on the first and last page of a document get placed differently as demonstrated in this MWE.  In this particular example, the problem shows up in a two-column document where the second column is seen by LaTeX to act in the role
of the last page.
\documentclass{article}
\usepackage[landscape,
            twocolumn,
            margin=0.5in,
           ]{geometry}
\setlength{\columnsep}{3em}
\setlength{\columnseprule}{0.4pt}
\usepackage{lipsum}
\pagestyle{empty}
\begin{document}

This is a short section\footnote{Hello}

\pagebreak
\setcounter{footnote}{0}

This is a short section\footnote{Hello}

\end{document}

For the purposes of my document, the left and right columns should be identically typeset.  So, I'm not happy that the footnotes get placed differently.  What I would prefer is that both footnotes get placed as the first footnote in the left hand column.
Any ideas how to do this?

A: The \pagebreak command tells LaTeX to break the current page at the point of the command. With the optional argument, a number, you can convert the \pagebreak command from a demand to a request.  (For details refer  to this answer by egreg). If you don't specify the options, then number 4 is assumed and a page break is inserted immediately.
Coming to your mwe, the \pagebreak is called with only one line of text without any optional arguments. Hence, you have insisted (demanded) for a page break immediately whereas the second page/column gets shipped out naturally. If you want second column to be identical to first column, put a \pagebreak after the second column also.
\documentclass{article}
\usepackage[landscape,
            twocolumn,
            margin=0.5in,
           ]{geometry}
\setlength{\columnsep}{3em}
\setlength{\columnseprule}{0.4pt}
\usepackage{lipsum}
\pagestyle{empty}
\begin{document}

This is a short section\footnote{Hello}

\pagebreak
\setcounter{footnote}{0}

This is a short section\footnote{Hello}
\pagebreak %% put here
\end{document}

You may play with the optional arguments (\pagebreak[1], number from 0-4).
However using \newpage or \clearpage will give you different results as in these cases, the page is broken at the end.
May be useful:

*

*pagebreak-vs-newpage

*when-do-i-need-invoke-clearpage-manually


text:
Q: iterative algorithm for combination generation
Possible Duplicate:
Algorithm to return all combinations of k elements from n

Is there any iterative algorithm  to generate combinations of  N numbers taking 'r' at a time ?

A: Yes there is.
Here is code from the wrong answer Library.
void generate_combos(int n, int k) {
    int com[100];
    for (int i = 0; i < k; i++) com[i] = i;
    while (com[k - 1] < n) {
        for (int i = 0; i < k; i++)
            cout << com[i] << " ";
        cout << endl;

        int t = k - 1;
        while (t != 0 && com[t] == n - k + t) t--;
        com[t]++;
        for (int i = t + 1; i < k; i++) com[i] = com[i - 1] + 1;
    }
}

This generates the combinations in lexicographic order.


text:
Q: How to take user input and insert into http get request? I've been searching and can't find a solution for what I'm looking for.
I want to be able to add details to a http request that a user submits in a form.
eg:
User submits two pieces of data via a form
Then these strings of data get added to the http get request.
Is this possible with jQuery/JavaScript? If so, how?
I hope that makes sense, if it doesn't I can try wording differently.

A: Checkout http://api.jquery.com/serialize/
You can get the data that way and then send it through with an ajax request.

A: To add some more form data before submission do this:
$("form").on("submit", function(event) {
      event.preventDefault();
      //Do stuff to populate fields (hidden or not) with data
      form = $(this);
      $.post(form.attr("action"), form.serialize(), function( data ) {
        //Success callback
      });
});

A: The simplest way is to simply make your form's method be GET rather than POST (or leave the method off, as GET is the default):
<form action="/your/endpoint" method="get">
<label>Name: <input type="text" name="name"></label>
<input type="submit" value="Submit">
</form>

When you submit the form, the user will be redirected to /your/endpoint and the value they put in the name text box will be added to the URL as a query-string parameter. For example, if I entered my first name, I would be redirected to /your/endpoint?name=Sean when I clicked on the submit button.


text:
Q: Default language mix up in Windows 10 I added a language (in Region & Language) and then I changed the default display language to the new language. It worked. Now when I changed the display language back to "English" again, it didn't really happen for everything. I see non-English characters in start and search as shown below:
screenshot
Restarting the system and redoing the whole process don't fix it. How can this be fixed?

A: Did you also try changing the system locale? Try the following, if that fails, perhaps try a system restore to a point before you made changes (if the checkpoint is available):

*

*In search tab type "Region" and press enter.

*In new window select "Administrative"

*then click on "change system locale"

*Select the language.

A: Your user profile seems to be corrupted, as the problem does not arrive
on a new profile.
You may migrate data from the old profile by using some (or all)
of the commands below :
copy c:\users\oldprofile\Desktop c:\users\newprofile\Desktop
copy c:\users\oldprofile\documents c:\users\newprofile\documents
copy c:\users\oldprofile\music c:\users\newprofile\music
copy c:\users\oldprofile\video c:\users\newprofile\video
copy c:\users\oldprofile\pictures c:\users\newprofile\pictures
copy c:\users\oldprofile\appdata\roaming\microsoft\outlook c:\users\newprofile\appdata\roaming\microsoft\outlook

For Start Menu settings, copy
C:\Users\oldprofile\AppData\Local\TileDataLayer\Database.


text:
Q: Spring Boot Jersey static content with resources at "/" I have a project setup with Spring Boot and Jersey, and I need to serve static content. The main difference with other similar questions is the fact that "mywebsite.com/" has to be a Jersey resource. This is my current JerseyConfig:
@ApplicationPath("/")
@Configuration
public class JerseyConfig extends ResourceConfig {

    public JerseyConfig() {
        packages("com.mywebsite.services.rest",
                 "com.mywebsite.services.publication");

        property(ServletProperties.FILTER_FORWARD_ON_404, true);
    }
}

And my publication resource:
@Component
@Path("/")
@Produces(MediaType.TEXT_HTML)
public class PublicacionResource {

        @GET
        public Template index() throws Throwable {
            return generateTemplateWithParameters("instalaciones", null, null);
        }

       ...
}

Jersey doesn't seem to be forwarding the 404 requests, as I cannot access static content.

A: Throw an Exception in generateTemplateWithParameters and forward it via ExceptionMapper
@Provider
public class MyExceptionProvider implements ExceptionMapper<MyException> {
    @Override
    public Response toResponse(final MyException exception) {
        return Response.status(Response.Status.NOT_FOUND).build();
    }
}

Don't forget to register it in Jersey's ResourceConfig:
register(MyExceptionProvider.class);


text:
Q: GTK+ программа не изменяет стиль На Debian 9.8 c Gnome GTK+ программа не изменяет стиль

main.cpp

#include <gtk/gtk.h>

void myStyleCss(void);
void createWind(GtkWidget **window, gint width, gint height);
void createGrid(GtkWidget **grid, GtkWidget **window, const gchar *name);

void chngBkgrd(gpointer *data);

int main(int argc, char *argv[]){
  GtkWidget *window;
  GtkWidget *grid;
  GtkWidget *button;

  gtk_init(&argc, &argv);
  myStyleCss();
  createWind(&window, 350, 250);
  createGrid(&grid, &window, "myGrid");

  button = gtk_toggle_button_new_with_label("tgl_btn");
  g_signal_connect (button, "toggled", G_CALLBACK(chngBkgrd),(gpointer
    *)button);
  gtk_grid_attach (GTK_GRID (grid), button, 0 , 0, 1, 1);

  gtk_widget_show_all(window);
  gtk_main();
}

void myStyleCss(void){
  GtkCssProvider *provider;
  GdkDisplay *display;
  GdkScreen *screen;

  provider = gtk_css_provider_new ();
  display = gdk_display_get_default ();
  screen = gdk_display_get_default_screen (display);
  gtk_style_context_add_provider_for_screen (screen,
                                           GTK_STYLE_PROVIDER(provider),

  GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

  const gchar *myCssFile = "style.css";
  GError *error = 0;

  gtk_css_provider_load_from_file(provider,
                                g_file_new_for_path(myCssFile), &error);
                                g_object_unref (provider);
}

void createWind(GtkWidget **window, gint width, gint height){
  *window = gtk_window_new(GTK_WINDOW_TOPLEVEL);
  gtk_window_set_title(GTK_WINDOW(*window), "MyApp");
  gtk_window_set_default_size(GTK_WINDOW(*window), width, height);
  gtk_window_set_resizable (GTK_WINDOW(*window), TRUE);
  gtk_container_set_border_width(GTK_CONTAINER(*window), 5);
  g_signal_connect(*window, "destroy", G_CALLBACK(gtk_main_quit), NULL);
}

void createGrid(GtkWidget **grid, GtkWidget **window, const gchar *name){
  *grid = gtk_grid_new ();
  gtk_grid_set_row_homogeneous(GTK_GRID(*grid), TRUE);
  gtk_grid_set_column_homogeneous(GTK_GRID(*grid), TRUE);
  gtk_widget_set_name(*grid, name);
  gtk_container_set_border_width(GTK_CONTAINER (*grid), 50);
  g_object_set (*grid, "margin", 0, NULL);
  gtk_container_add (GTK_CONTAINER (*window), *grid);
}

void chngBkgrd(gpointer *data){
  if(gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(data))){
    g_print("On\n");
  }
  else{
    g_print("Off\n");
  }
}

style.css

GtkWindow {
  background-color: red;
  color: cyan;
  border-width: 3px;
  border-color: blue;
};

#myGrid {
  background-color: white;
  border-style: solid;
  border-width: 3px;
  border-radius: 15px;
  border-color: grey;
};

#myChild {
  background-color: red;
  border-style: solid;
  border-width: 3px;
  border-radius: 15px;
  border-color: grey;
};

#tgl_btn{
  background-color: red;
  color: red;
};

GtkButton {
  background-image: none;
  background-color: blue;
};

GtkButton:active {
  background-color: #00FF00;
};

GtkButton:checked{
  background-color: #000000;
};


text:
Q: How can I create a loop on an UPDATE statement that works until there is no row left to update? Assume that I have thousands of rows to update.
And I plan to do the update iteratively; by only updating 1000 rows per iteration.
And I want to iterate until there are no rows left to update.
How can I run the T-SQL script below until there is no row to update?
-- TODO: Create a loop so that it exists when there is no ROW left to be updated;
-- how can I do it?

UPDATE tableToUpdate
SET IsVegetable = 1
WHERE Id IN
               (SELECT TOP 1000 Id
                FROM tableToUpdate
                WHERE Date = '2011-07-23 14:00')

-- Loop ends

A: Try this loop
while 1 = 1
BEGIN
    UPDATE top (1000) tableToUpdate
    SET IsVegetable = 1
    WHERE
        Date = '2011-07-23 14:00'
    AND IsNull(IsVegetable, 0) = 0

    if @@ROWCOUNT < 1000 BREAK
END

Why ISNULL - because it is not clear - if the field IsVegetable is nullable or not, if not - then ISNULL not needed
When there no rows will left with IsVegetable  <> 1 - the loop will quit because the @@ROWCOUNT will be = 0 or < 1000 (for the last iteration)


text:
Q: How to manage streams of bytes and when to close the streams I'm experiencing java.lang.OutOfMemoryError: Java heap space whenever I try to execute my code.  However, if I close my streams in certain instances the error goes away, but because my streams are closing prematurely I'm missing data.
I'm very new to Java and I'm clearly not understanding how to manage the streams.  How and when should I close streams?
private void handleFile(File source)
{
    FileInputStream fis = null;

    try
    {
        if(source.isFile())
        {
            fis = new FileInputStream(source);
            handleFile(source.getAbsolutePath(), fis);
        }
        else if(source.isDirectory())
        {
            for(File file:source.listFiles())
            {
               if(file.isFile())
               {
                   fis = new FileInputStream(file);
                   handleFile(file, fis);
               }
               else
               {
                   handleFile(file);
               }
            }
         }
     }
     catch(IOException ioe)
     {
         ioe.printStackTrace();
     }
     finally
     {
         try
         {
             if(fis != null) { fis.close(); }
         }
         catch(IOException ioe) { ioe.printStackTrace(); }
     }
}

private handleFile(String fileName, InputStream inputStream)
{
    try
    {
       byte[] initialBytes = isToByteArray(inputStream);
       byte[] finalBytes = initialBytes;

       if(initialBytes.length == 0) return;

       if(isBytesTypeB(initialBytes))
       {
          finalBytes = getBytesTypeB(startingBytes);
       }
       // Other similar method checks
       // .....

       map.put(fileName, finalBytes);
     }
     catch(IOException ioe)
     {
         ioe.printStackTrace();
     }
}

private byte[] isToByteArray(InputStream inputStream)
{
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    byte[] buffer = new byte[1024];

    int nRead;
    while((nRead = inputStream.read(buffer)) != -1)
    {
        baos.write(buffer, 0, nRead);
    }
    return baos.toByteArray();
 }

 private boolean isBytesTypeB(byte[] fileBytes)
 {
     // Checks if these bytes match a particular type
     if(BytesMatcher.matches(fileBytes, fileBytes.length))
     {
         return true;
     }
     return false;
 }

 private byte[] getBytesTypeB(byte[] fileBytes)
 {
     //decompress bytes

     return decompressedBytes;
 }

A: First of all, do not read the entire streams in memory. Use buffers when reading and writing.
Use ByteArrayInputStream and ByteArrayInputStream only if you're sure you'll be reading very small streams (whose data you will need to re-use for some operations) and it really makes sense to keep the data in memory. Otherwise, you will quickly (or unexpectedly) run out of memory.
Define the streams outside a try-catch block and close them in the finally block (if they are not null). For example:
void doSomeIOStuff() throws IOException
{
    InputStream is = null;

    try
    {
        is = new MyInputStream(...);
        // Do stuff
    }
    catch (IOException ioExc)
    {
        // Either just inform (poor decision, but good for illustration):
        ioExc.printStackTrace();
        // Or re-throw to delegate further on:
        throw new IOException(ioExc);
    }
    finally
    {
        if (is != null)
        {
            is.close();
        }
    }
}

This way your resources are always properly closed after use.
Out of curiosity, what should the handleFile(...) method really be doing?


text:
Q: How do I properly group polygons into arrays? I want to render a scene in OpenGL ES, but I have  a problem.
Because there is no immediate mode in ES, and simulating immediate mode with single-polygon buffers is slow, I can't just switch textures and skip invisible polygons, so I have to group my polygons.
Here are characteristics of different polygons:

*

*Diffuse texture (mipmapped, lots of them).

*Lightmap texture (packed, up to 64 textures).

*Visibility.

At first I thought to group the polygons only by visibility area, but I couldn't find a way to use texture index arrays.
So, how do I properly make buffers of polygons to render?

A: I will make visibility groups with texture subgroups. Quake uses 64 128x128 lightmaps, I'm going to replace them with a single 1024x1024 lightmap, since modern hardware supports textures of such size.


text:
Q: I have two regex in .net preRegex = "(?<=(^|[^A-Za-z0-9]+))" postRegex = "(?=([^A-Za-z0-9]+)|$)" . What is the alternate of it in python? I have two regex strings in .net
preRegex = "(?<=(^|[^A-Za-z0-9]+))"
postRegex = "(?=([^A-Za-z0-9]+)|$)"

I want their alternative in python. My problem is let say I have a string
s="I am in aeroplane."

What I need is to replace "aeroplane with aeroPlain" so I want to make regex like
newKey = preRegex + aeroplane + postRegex
pattern = re.compile(newKey,re.IGNORECASE)

new regex string look like
(?<=(^|[^A-Za-z0-9]+))aeroplane(?=([^A-Za-z0-9]+)|$)

but it is giving me error "look-behind requires fixed-width pattern".
I am new to python, Help would be appreciated. Thanks

A: You can use the following regex:
(^|[^A-Za-z0-9]+)aeroplane([^A-Za-z0-9]+|$)

and when you replace, you can call the back reference to the first and second part of your regex to fetch their value.
Replacement string will be something like '\1aeroPlain\2'.
For more information on backref in python:https://docs.python.org/3/howto/regex.html
Good luck!


text:
Q: How would I store these values into an object from a .txt file? I'm new to programming and I was wondering how I would store values into variables in a class using arrays if I'm getting the values from a .txt file. The values would be either strings or ints, how would you adjust to make this work? Here is the text from the txt. file.
Kobe Bryant

USA

4250000

25

21.03

NBA

Lebron James

USA

6450000

27

21.03

NBA

So I need to store each set of 6 values into 6 separate variables in a class using an array. The second index of the array will call the next 6 values.

A: *

*Create a Class which contains name, country, Salary, age etc.

*Create a List of yourClass instances.

*Read from file and store them in the list.

A: class Person {
    private String name;
    private String country;
    private int salary;
    private int age;
    private double someValue;
    private String league;

    public Person() { }
    public Person(String name, String country, int salary, int age, double someValue, String league) { //set them }
    //add setX and getX methods

}
In you main class:
  List<Person> persons = new ArrayList<>();

A: Create a class which contains all the necessary details you want to store in the array list. Then write the details on the text file and using the file concept read the data from the file and create an Array list  object to store the data into an array list.


text:
Q: Simplest way to auth to Google API (Spreadsheet) I'm trying to add a new row to Spreadsheet every new firebase user.
So I created a function
const google = require('googleapis');
const GOOGLE_APIKEY = functions.config().google.apikey;

exports.saveNewGuest = functions.auth.user().onCreate((event) => {
  const sheets = google.sheets('v4');
  const request = {
    auth: GOOGLE_APIKEY, // Tryed this
    key: GOOGLE_APIKEY, // and this
    spreadsheetId: '<SPREADSHEET_ID>',
    range: 'Sheat!A:A',
    valueInputOption: 'RAW',
    insertDataOption: 'INSERT_ROWS',
    alt: 'json',
    resource: {
      values: [[user.displayName, user.email]],
    },
  };

  return new Promise((resolve, reject) => {
    sheets.spreadsheets.values.append(request, (err, response) => {
      // ...
    })
  });
})

But I got..

Error: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential.

I already created API keys on Credentials
I'm missing something ?


text:
Q: Unicode problem with JSF and HTML forms? I have an HTML form generated by JSF which maps an input element to a bean setter
and it looks to me like JSF is garbling unicode input on the way in.  In particular I put the following exception for testing purposes in the setter
public void setTitle(String title){
    System.out.println("title set with: "+title+"\n");
    if (title.startsWith("xxx")) {
        throw new RuntimeException("debug exception "+title);
    }
    this.title = title;
}

Then I put the following text into the form title input element: "xxxx 海陆". Then when I submit the form I see the log print
title set with: xxxx ?????

(on a unicode compatible mac terminal).
And I get an error message on the response HTML page:
Error setting property 'title' in bean of type
uk.ac.lancs.e_science.sakaiproject.api.blogger.post.Post:
java.lang.RuntimeException: debug exception xxxx ���??

Any clues on what's wrong?  Am I just full of it and have the wrong diagnosis?
I think I've eliminated all other possibilities.  Unicode seems to work fine in other components of the same application.

A: Questions I would be asking:

*

*How is the form encoding the request (application/x-www-form-urlencoded or multipart/form-data)? Multi-part data will be decoded using a 3rd party MIME parser, so there is scope for trouble there. If the data is url-encoded, is it being escaped properly?

*What charsets is the browser accepting?

*What encoding is the server detecting? Is it a Unicode character set?

*Is it just the logging that is writing as a lossy encoding (e.g. MacRoman)? What default charset is the server using?

Since what you see on a console isn't necessarily what is in the string, you can dump the Unicode code points using this code:
  public static void printCodepoints(char[] s) {
    for (int i = 0; i < s.length; i++) {
      int codePoint = Character.isHighSurrogate(s[i]) ? Character
          .toCodePoint(s[i], s[++i])
          : s[i];
      System.out.println(Integer.toHexString(codePoint));
    }
  }

A: A browser can't send unicode over the wire; it has to encode the unicode in some way. From the output of the exception (two kanji became five characters), I'm guessing the data was encoded as UTF-8 and the string title wasn't decoded correctly after reception in the server side of the component.
I suggest to set the accept-charset attribute for the form. That should tell everyone to behave.


text:
Q: git pull - will it fetch tags on remote by default? I know git fetch --tags will fetch all tags from remote to local.
I am not sure will git pull get tags from remote by default, so will it or not?

A: A git pull will by default only fetch tags that are reachable by the objects that are fetched.
From the git pull documentation

--no-tags
By default, tags that point at objects that are downloaded from the remote repository are fetched and stored locally. This option disables this automatic tag following. The default behavior for a remote may be specified with the remote.<name>.tagopt setting. See git-config[1].

So you should also take a look at the tagopt config to see what git does for your repository.

remote.<name>.tagopt
Setting this value to --no-tags disables automatic tag following when fetching from remote . Setting it to --tags will fetch every tag from remote , even if they are not reachable from remote branch heads. Passing these flags directly to git-fetch1 can override this setting. See options --tags and --no-tags of git-fetch1.

A: It should, since git pull does a git fetch and a git merge.
But it will do so only from git 1.9.0+, as I mentioned in "Does "git fetch --tags" include "git fetch"?".


text:
Q: Find out points outside the polygon I have a shapefile with geometries of different regions. Also I have a list of coordinate points(field_lonlat), I want to consider only those points of the list which are outside the polygon geometries using python.
Below is my code to check it but trying to find a simpler version of it.
from osgeo import ogr
from shapely.geometry import Point
from shapely.prepared import prep
from shapely.wkb import loads
import json
g = ogr.Open("Polygons.shp")
points = []
for layer in g.GetLayer(0):
    field = loads(layer.GetGeometryRef().ExportToWkb())
    fieldP = prep(field)
    for x,y in field_lonlat: //field_lonlat is my list of points
        item = Point(x, y)
        if fieldP.contains(item):
            pass
        else:
            points.append((x,y))

But my points list checks for a single polygon once and hence considers only those points which are not in it but which might be inside an another polygon.

A: I think this would make slightly more sense :
from osgeo import ogr
from shapely.geometry import Point
from shapely.prepared import prep
from shapely.wkb import loads
import json

g = ogr.Open("Polygons.shp")
list_to_remove = []
points = field_lonlat[:] # make a copy of the list
for x,y in field_lonlat:
    item = Point(x,y)
    for layer in g.GetLayer(0):
        field = loads(layer.GetGeometryRef().ExportToWkb())
        fieldP = prep(field)
        if fieldP.contains(item):
            # remove points that are in one of the polygons
            points.remove((x,y))
            # break to avoid checking every polygon if you're already inside of one
            break


text:
Q: Create a simple MatLab command to create a matrix I am incredibly new to MatLab (I only started looking at it today). I'm trying to do some sample questions and I'm stuck on this one. I;m sure it's very easy. The Q is: Write a Matlab command to create the following matrix (sArray), followed by the command to graph the 3rd row of the matrix. The grid of the graph should be set to visible and the x ('test') and y ('value') axis labels should be included.

No doubt this will take someone less than 30 seconds to do.
Thanks in advance!

A: A = [16 456 22 85 93; 11 78 310 62 36; 1 66 23 67 405]

figure
plot(A(3,:))
xlabel('test')
ylabel('value')

I suggest to take a look at this


text:
Q: Laravel fluent insert with multiple values only inserts the first value I am trying to run a single seeder class:
<?php

use Illuminate\Database\Seeder;

class CourseTableSeeder extends Seeder {

    public function run()
    {
        DB::table('courses')->insert(
            ['name' => 'PhD'],
            ['name' => 'Master'],
            ['name' => 'Bachelor'],
            ['name' => 'Foundation'],
            ['name' => 'ESL']
        );
    }

}

I execute the command with:
art db:seed --class CourseTableSeeder

and I expect to see the five values in the database, however, I only see the very first one 'phd'.
I have tried debugging this by running ->toSql() on the insert but I don't think it's possible and I receive the following error as insert most likely returns a boolean, so not chainable
[2018-07-23 15:35:45] local.ERROR: Call to a member function toSql() on boolean {"exception":"[object] (Symfony\\Component\\Debug\\Exception\\FatalThrowableError(code: 0): Call to a member function toSql() on boolean at C:\\laragon\\www\

eports\database\seeds\CourseTableSeeder.php:15)
As I couldn't easily figure out how the insert method worked via digging into the framework's source, I began to wonder if DB::table('table_name')->insert() accepted multiple inserts via an array and I managed to find examples of this in the framework's testing suite, for example:
DB::table('posts_tags')->insert([
    ['post_id' => $post->id, 'tag_id' => 200, 'flag' => ''],
    ['post_id' => $post->id, 'tag_id' => 300, 'flag' => 'exclude'],
    ['post_id' => $post->id, 'tag_id' => 400, 'flag' => ''],
]);

source: https://github.com/laravel/framework/blob/5.6/tests/Integration/Database/EloquentBelongsToManyTest.php#L539
So I am guessing I am not doing anything wrong. Any ideas on what the issue is and how I may debug what's going wrong as I have exhausted the options known to me. Also, while running the whole thing no errors show up in the console or log file.
Thanks!

A: Your insert() is missing some [] syntax in it. Compare yours
->insert(
  ["name" => "..."]
);

to the documentation
->insert([
  ["post_id" => "..."]
]);

So, the documentation is suggesting to pass a single array, containing an array for each record you want inserted, while your implementation is passing multiple arrays.


text:
Q: full img size in any screen size When I run my code in my laptop, then the img is showin full screen. But when I run it on a bigger screen size then it comes double: enter image description here
This is my css code I use:
body {

  background: url(pic.jpg);
  background-size: cover;
  background-position: center;
  font-family: Lato;
  color: white;
}

html {
height: 100%
}

Can someone help me fix the issue, that the img should go full screen on any screen size?

A: Add following style to your code to avoid repeating the image:
background-repeat:no-repeat;

A: Since you applied it as background you can use this property to avoid double occurrence in higher resolution
background-repeat: no-repeat;

even you can mention all it in a single line like
background: #fff url('pic.jpg') no-repeat center center;

and if you want to stretch the image, then
background-size: 100% auto;

A: body {
  background: url(pic.jpg);
  background-size: cover;
  background-position: center;
  font-family: Lato;
  color: white;
  width:100%;
  height:100%;
}

html {
  height: 100%;
}

A: use
background-repeat:no-repeat;

and you can reduce code by using
background: url('pic.jpg') no-repeat cover center;

A:

body {
  background-repeat: no-repeat;
  width:100%;
  height:100%;
}

A: This could solve your problem:
body {
    width: 100%;
    height: 100vh;
    margin: 0;
    padding: 0;
    background-image: url('PATH_TO_IMG');
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
}

You can see an example here https://codepen.io/Nacorga/pen/mjmBLp


text:
Q: Permission denied while binding socket It's me again from Running Python server forever. I did upload my file to the server, but I get this:
Traceback (most recent call last):
  File "./application", line 42, in <module>
    s.bind((TCP_IP, TCP_PORT))
  File "<string>", line 1, in bind
socket.error: [Errno 13] Permission denied

For your reference, the code is here:
...

TCP_IP = ''
TCP_PORT = 9090
BUFFER_SIZE = 256

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((TCP_IP, TCP_PORT))
s.listen(1)
while True:
    conn, addr = s.accept()
    ClientThread(conn, addr).start()

When the socket binds to port 9090, (or any other port for that matter), it just returns this exception. I don't need to be root, because port > 1024.
What should I change? Is the problem in TCP_IP or TCP_PORT?
~Chance

A: try using '0.0.0.0' as the bind address. In Linux, this means all interfaces.
TCP_IP = '0.0.0.0'

And make sure SELinux is disabled.

A: Set the host to "None" such that it binds properly to all adapter interfaces.
host = None
s.bind((host, TCP_PORT));

Reference: http://docs.python.org/library/socket.html

A: I'd suggest isolating the problem further, meaning you want to reproduce this problem using something that "should also work" but is not your code.
For example, try a canned (known-working) HTTP script server, and observe that if it also fails then the issue is nothing to do with the Python code you posted. This will get you on the right track... permissions.
FYI - On EC2 I don't think you log in as root -- MY EC2 doesn't support root (it's Ubuntu). Instead you "sudo" run the command, while logged in as you. I'm not prompted for a sudo password (although someone may have configured that before me, by adding NOPASSWORD=ALL to my /etc/sudoers user or group).
What I know about EC2 is you have a firewall and permissions BOTH on the OS itself, and in the Amazon EC2 control panel, and you can easily run into permissions issue and waste time looking in the wrong place.
Anyways, confirm that it's permissions not your Python code, and then take this problem to an EC2 forum for best results.


text:
Q: Hide a xml component from an inflated layout Does anybody know how to hide a component from an inflated layout?
I have the following code:
View tabLayout = LayoutInflater.from(this).inflate(R.layout.tab_layout, null);
FrameLayout profile_tab_selected_indicator =
      (FrameLayout)tabLayout.findViewById(R.id.profile_tab_selected_indicator);

and when I'm trying to hide it by using:
profile_tab_selected_indicator.setVisibility(View.GONE);

it doesn't work. It looks like I'm missing something or it's not possible to hide xml components from the inflated layouts. I've also tried to set the width and height to 0dp via the LayoutParams and it doesn't work as well.
In a custom function outside of the onCreate() like this:
public static View tabLayout;

protected void onCreate(){
   //some code here
buildTabLayout();
}

public void buildTabLayout(){
   tabLayout = LayoutInflater.from(this).inflate(R.layout.tab_layout,   null);
}

Then I'm trying to hide it here:
public void onTabChanged(String tabId) {
    FrameLayout profile_tab_selected_indicator = (FrameLayout)tabLayout.findViewById(R.id.profile_tab_selected_indicator);

    profile_tab_selected_indicator.setVisibility(View.GONE);
}

Here's the xml code of the inflated layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/profile_tab_bar_bg"
    android:gravity="center"
    android:orientation="vertical" >

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/profile_top_bar_shadow_xml" >
    </FrameLayout>

    <ImageView
        android:id="@+id/iv_tabIcon"
        android:layout_width="30dp"
        android:layout_height="30dp" />

    <TextView
        android:id="@+id/tv_tabTitle"
        style="@style/ProfileTabLabelsStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@drawable/profile_tab_label_selector" />

    <FrameLayout
        android:id="@+id/profile_tab_selected_indicator"
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:background="@color/ProfileTabSelected" >
    </FrameLayout>

</LinearLayout>

EDIT:
All the code responsible for my tab layout:
// tabs labels
    public static String[] tabsTitles = new String[] { "PROFILE", "CAMPAIGNS",
            "STATISTICS" };

    public static View tabLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.vw_profile);

        // initializing xml components
        init();

        // Tab Layut builder
        buildTabLayout();

    }
private void buildTabLayout() {
        // TODO Auto-generated method stub
        Resources res = getResources(); // Resource object to get Drawables
        TabHost tabHost = getTabHost(); // The activity TabHost
        tabHost.setOnTabChangedListener(this);
        TabHost.TabSpec spec; // Resusable TabSpec for each tab
        View tabLayout; // tabLayout
        Intent intent; // Reusable Intent for each tab

        // PROFILE TAB
        tabLayout = createTabLayout(this, tabsTitles[0]);
        intent = new Intent().setClass(this, VieweedsProfileTabActivity.class);
        spec = tabHost.newTabSpec(tabsTitles[0]).setIndicator(tabLayout)
                .setContent(intent);
        tabHost.addTab(spec);

        // CAMPAIGNS TAB
        tabLayout = createTabLayout(this, tabsTitles[1]);
        intent = new Intent()
                .setClass(this, VieweedsCampaignsTabActivity.class);
        spec = tabHost.newTabSpec(tabsTitles[1]).setIndicator(tabLayout)
                .setContent(intent);
        tabHost.addTab(spec);

        // STATISTICS TAB
        tabLayout = createTabLayout(this, tabsTitles[2]);
        intent = new Intent().setClass(this,
                VieweedsStatisticsTabActivity.class);
        spec = tabHost.newTabSpec(tabsTitles[2]).setIndicator(tabLayout)
                .setContent(intent);
        tabHost.addTab(spec);

        tabHost.setCurrentTab(0);

    }

    public void onTabChanged(String tabId) {
        // TODO Auto-generated method stub
        FrameLayout profile_tab_selected_indicator = (FrameLayout)tabLayout.findViewById(R.id.profile_tab_selected_indicator);
        FrameLayout campaigns_tab_selected_indicator = (FrameLayout)tabLayout.findViewById(R.id.campaigns_tab_selected_indicator);

        if (tabId.equals(tabsTitles[0])) {
            // profile tab
            Toast.makeText(this, tabId, Toast.LENGTH_LONG).show();
            profile_tab_selected_indicator.setVisibility(View.VISIBLE);
            campaigns_tab_selected_indicator.setVisibility(View.GONE);
        } else if (tabId.equals(tabsTitles[1])) {
            // campaigns tab
            Toast.makeText(this, tabId, Toast.LENGTH_LONG).show();
            profile_tab_selected_indicator.setVisibility(View.GONE);
            campaigns_tab_selected_indicator.setVisibility(View.VISIBLE);
        } else {
            Toast.makeText(this, tabId, Toast.LENGTH_LONG).show();
            // statistics tab

        }
    }

    // creating tab layout for each tab
    public static View createTabLayout(Context c, String tabTitleText){
        tabLayout = LayoutInflater.from(c).inflate(R.layout.tab_layout, null);
        TextView tabTitle = (TextView)tabLayout.findViewById(R.id.tv_tabTitle);
        tabTitle.setTypeface(arial);
        ImageView tabIcon = (ImageView)tabLayout.findViewById(R.id.iv_tabIcon);
        tabTitle.setText(tabTitleText);

        //assigning tab icons for each tab
        if(tabTitleText.equals(tabsTitles[0])){
            //profile tab
            tabIcon.setImageResource(R.drawable.profile_tab_bar_profile_tab_icon);
        }else if(tabTitleText.equals(tabsTitles[1])){
            //campaigns tab
            tabIcon.setImageResource(R.drawable.profile_tab_bar_campaigns_tab_icon);
        }else{
            //statistics tab
            tabIcon.setImageResource(R.drawable.profile_tab_bar_statistics_tab_icon);
        }

        return tabLayout;
    }

A: You've done some things wrong in your code. I don't know why you choosed to make tabLayout a field in your class, but by doing this tabLayout will point to the last tab indictor that you set(the one for the STATISTICS tab). Because the tabLayout points to the last tab only, in the onTabChanged callback nothing will happen(because you don't do anything for the last tab).
I would advise you to change your onTabChanged method and search for the tab views directly with the getChildTabViewAt to make sure you're searching for that FrameLayout in the right place:
public void onTabChanged(String tabId) {
        // the first tab view
        View tab1 = getTabWidget().getChildTabViewAt(0);
        FrameLayout profile_tab_selected_indicator = (FrameLayout)tab1.findViewById(R.id.profile_tab_selected_indicator);
        // the second tab view
        View tab2 = getTabWidget().getChildTabViewAt(1);
        // where does this come from?!?! it is in the second tab?!?!
        FrameLayout campaigns_tab_selected_indicator = (FrameLayout)tab2.findViewById(R.id.campaigns_tab_selected_indicator);
        // the third tab view
        View tab3 = getTabWidget().getChildTabViewAt(2);

        if (tabId.equals(tabsTitles[0])) {
            // profile tab
           Toast.makeText(this, tabId, Toast.LENGTH_LONG).show();
           profile_tab_selected_indicator.setVisibility(View.VISIBLE);
           campaigns_tab_selected_indicator.setVisibility(View.GONE);
        } else if (tabId.equals(tabsTitles[1])) {
            // campaigns tab
            Toast.makeText(this, tabId, Toast.LENGTH_LONG).show();
            profile_tab_selected_indicator.setVisibility(View.GONE);
            campaigns_tab_selected_indicator.setVisibility(View.VISIBLE);
        } else {
            Toast.makeText(this, tabId, Toast.LENGTH_LONG).show();
            // statistics tab

        }
    }


text:
Q: Is there a guaranteed width of the underlying int for an enum? In the example in N2347 one advantage if the new stongly typed enums (C++11) compared the current (C++03) is explained by an example with an "old" enum:
enum Version { Ver1 = 1, Ver2 = 2 };
struct Packet {
    Version ver;
    // ... more data ...
    // bad, size can vary by implementation
   Version getVersion() const { return ver; }
};

I wonder: means "varying" here that the compiler can even choose a 8bit representation, i.e. that the enum-elements occupy only one word? Or is there a minimum length guaranteed and the choice may only be between int and long?
In other words, if I have a Version enum like this:
enum VersionXyz { Ver1 = 100, Ver2 = 200 };
struct Packet {
    VersionXyz ver;
    // ... more data ...
};

Is it possible that this takes only 8bit in Packet. And after a software update to:
enum VersionXyz { Ver1 = 100, Ver2 = 200, Ver3=300 };

now Packet has not the same size anymore because the enum has grown?

A: The relevant paragraph of the C++03 standard is §7.2.5:

The underlying type of an enumeration is an integral type that can represent all the enumerator values
  defined in the enumeration. It is implementation-defined which integral type is used as the underlying type
  for an enumeration except that the underlying type shall not be larger than int unless the value of an enumerator cannot fit in an int or unsigned int. If the enumerator-list is empty, the underlying type is
  as if the enumeration had a single enumerator with value 0. The value of sizeof() applied to an enumeration type, an object of enumeration type, or an enumerator, is the value of sizeof() applied to the
  underlying type.

So it's implementation defined. The only thing you are guaranteed is that if you define an enum where all values fit into an int, then the enumeration type's size won't be greater than int. (But since int's size is also implementation-defined, that doesn't give you much.)

A: If you know that your enum list is only ever going to be a certain size it might be worth type casting it when used, and also have an assert for if that size is ever exceeded, at least thats how I use enums when sending packets


text:
Q: Months differenece between two dates How can i get the proper format.
Lets say i have date from 21.03.2010
                date to   21.05.2011
My date difference should return something like this
Months / Years
    3/2010
    4/2010
    5/2010
    ...
    12/2010
    1/2011
    ...
    5/2011

A: This should get you going:
Private Sub Button50_Click(sender As Object, e As EventArgs) Handles Button50.Click

    printDateRange(New Date(2010, 3, 21), New Date(2011, 5, 21))

End Sub

Private Sub printDateRange(startDate As Date, endDate As Date)

    Dim months As Integer = DateDiff(DateInterval.Month, startDate, endDate)

    For parser As Integer = 0 To months
        Dim newdate As Date = startDate.AddMonths(parser)
        Debug.Print(String.Format("{0}/{1}", newdate.Month, newdate.Year))
    Next

End Sub

You'll still need to add all the validation and error handling etc