text:
Q: How to create separate in memory database for each test? I'm writing a test with xunit on .NET Core 3.0 and I have a problem with the in-memory database. I need a separate database for each test but now I create a single database that causes problems, but I have no idea how to create a new database for each test.
public class AccountAdminTest : IClassFixture<CustomWebApplicationFactory<Startup>>
{
    private readonly HttpClient _client;
    private IServiceScopeFactory scopeFactory;
    private readonly CustomWebApplicationFactory<Startup> _factory;
    private ApplicationDbContext _context;

    public AccountAdminTest(CustomWebApplicationFactory<Startup> factory)
    {
        _factory = factory;
        _client = _factory.CreateClient(new WebApplicationFactoryClientOptions
        {
            AllowAutoRedirect = true,
            BaseAddress = new Uri("https://localhost:44444")
        });

        scopeFactory = _factory.Services.GetService<IServiceScopeFactory>();
        var scope = scopeFactory.CreateScope();
        _context = scope.ServiceProvider.GetService<ApplicationDbContext>();
    }
}

public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureTestServices(services =>
        {
            var descriptor = services.SingleOrDefault(
                d => d.ServiceType ==
                    typeof(DbContextOptions<ApplicationDbContext>));

            if (descriptor != null)
            {
                services.Remove(descriptor);
            }

            services.AddDbContext<ApplicationDbContext>((options, context) =>
            {
                context.UseInMemoryDatabase("IdentityDatabase");
            });
        });
    }
}

Now it's look like this but still dosen't work. When i change lifetime on AddDbContext it doesn't change anything.
public class AccountAdminTest : IDisposable
{
    public AccountAdminTest(ITestOutputHelper output)
    {
        this.output = output;

        _factory = new CustomWebApplicationFactory<Startup>();

        _client = _factory.CreateClient(new WebApplicationFactoryClientOptions
        {
            AllowAutoRedirect = true,
            BaseAddress = new Uri("https://localhost:44444")
        });

        scopeFactory = _factory.Services.GetService<IServiceScopeFactory>();
        _scope = scopeFactory.CreateScope();
        _context = _scope.ServiceProvider.GetService<ApplicationDbContext>();

        var _user = User.getAppAdmin();
        _context.Add(_user);
        _context.SaveChanges(); //Here i got error on secound test. It says "An item with the same key has already been added"
    }

    public void Dispose()
    {
        _scope.Dispose();
        _factory.Dispose();
        _context.Dispose();
        _client.Dispose();
    }

I can't get token when use Guid as db name. It says that username/password is not valid. I use IdentityServer for authentication
public async Task<string> GetAccessToken(string userName, string password, string clientId, string scope)
        {
            var disco = await _client.GetDiscoveryDocumentAsync("https://localhost:44444");
            if (!String.IsNullOrEmpty(disco.Error))
            {
                throw new Exception(disco.Error);
            }
            var response = await _client.RequestPasswordTokenAsync(new PasswordTokenRequest
            {
                Address = disco.TokenEndpoint,
                ClientId = clientId,
                Scope = scope,
                UserName = userName,
                Password = password,
            });
            return response.AccessToken;
        }

A: All you need to change is this code here:
services.AddDbContext<ApplicationDbContext>((options, context) =>
{
    context.UseInMemoryDatabase("IdentityDatabase");
});

Instead of the constant value "IdentityDatabase", use something like Guid.NewGuid().ToString():
context.UseInMemoryDatabase(Guid.NewGuid().ToString());

Then, every time the context is fetched, it will be using a new in-memory database.

A: Edit: You must specify an unique name for every test run to avoid sharing the same InMemory database as slightly mentioned here and already answered here and here.
Nonetheless the suggestion below to switch to "Constructor and Dispose" still applies.

IClassFixture is not the right tool to use, the documentation says:

When to use: when you want to create a single test context and share it among all the tests in the class, and have it cleaned up after all the tests in the class have finished.

In your case you have to use "Constructor and Dispose", the documentation says:

When to use: when you want a clean test context for every test (sharing the setup and cleanup code, without sharing the object instance).

So your test will be:
public class AccountAdminTest
{
    private readonly HttpClient _client;
    private IServiceScopeFactory scopeFactory;
    private readonly CustomWebApplicationFactory<Startup> _factory;
    private ApplicationDbContext _context;

    public AccountAdminTest(CustomWebApplicationFactory<Startup> factory)
    {
        //
        _factory = new CustomWebApplicationFactory<Startup>();

        _client = _factory.CreateClient(new WebApplicationFactoryClientOptions
        {
            AllowAutoRedirect = true,
            BaseAddress = new Uri("https://localhost:44444")
        });

        scopeFactory = _factory.Services.GetService<IServiceScopeFactory>();
        _scope = scopeFactory.CreateScope();
        _context = scope.ServiceProvider.GetService<ApplicationDbContext>();
    }

    //Tests...

    public void Dispose() {

        _scope.Dispose();
        _factory.Dispose();

        //Dispose and cleanup anything else...
    }

}

Alternatively you can specify a lifetime of ServiceLifetime.Transient for your DbContext using this overload of .AddDbContext


text:
Q: Changing SQL server compatibility Level I have a database which was upgraded from 2000 to 2005. Is there any issue using sp_dbcmptlevel to change compatibility level to 90. Will this cause any issues with old queries or stored procedures

A: Did you run the SQL Server upgrade adviser on the old database?  It will tell you if there is any obvious problems.  Be sure to test on a development database.
Here is the tool
http://www.microsoft.com/downloads/details.aspx?FamilyID=1470e86b-7e05-4322-a677-95ab44f12d75&displaylang=en

redpajama_set_name: RedPajamaStackExchange


text:
Q: Interpretation/Mechanics of eigenvectors/eigenvalues of covariance matrix (PCA) 1st Q: Can someone explain the connection between the covariance and the eigenvectors?
2nd Q: How do dependencies in the data effect my PCA and how is the "best" component then chosen?
This could happen with easy detectable things like height, weight and BMI or less obvious things.
Maybe someone can recommend a video or explain clearly how to think about the eigenvectors extracted from the covariance matrix.
I understand them as the characteristic components which stay the same after applying matrix transformation.
But here we don't apply any transformation so how to interpret them now.
I read so far that eigenvalues are the "amount" of how much the extracted eigenvector spans/explains space. 3rd Q:Is this wrong ?
# Testing something for us !

import numpy as np
import pandas as pd

x = np.array((range(1,11)))
y = np.array((range(20,220,20)))
z = x*y

data = np.array([x,y,z])

test_matrix = np.cov(data)
#print(test_matrix)
eigenval, eigenvect = np.linalg.eig(test_matrix)

print(eigenval)
#sorting
sorting_indices = eigenval.argsort()[::-1] # not needed in our case
eigenval = eigenval[sorting_indices]
eigenvect = eigenvect[sorting_indices]

print(eigenval)
print(eigenvect_test)

# mapping
result = np.dot(eigenvect.transpose(), data)

# first component explanation amount
first_comp_perc =eigenval[0]/sum(eigenval)

print(f'The first component makes up for {round(first_comp_perc*100, 2)}% of the data variance')


text: Q: Как в c# преобразовать строку с шаблонным html-кодом в объект класса? У меня есть некоторое количество html-кодов, соответствующих одному шаблону (как на картинке 1). Я хочу преобразовывать его в объект моего класса без использования сторонних библиотек. Подскажите, пожалуйста, алгоритм того, как это можно реализовать. Мой класс будет выглядеть примерно так, как показано на картинке 2.


text:
Q: Error installing watir-classic Hi I tried to install the watir-classic but I got the following error
My system configurations
Windows 7
ruby 1.8.7
Building native extensions.  This could take a while...
ERROR:  Error installing watir-classic:
    ERROR: Failed to build gem native extension.

    D:/Ruby_version/bin/ruby.exe extconf.rb
    checking for ffi.h... no
    checking for ffi.h in /usr/local/include,/usr/include/ffi... no
    checking for rb_thread_blocking_region()... no
    checking for rb_thread_call_with_gvl()... no
    checking for rb_thread_call_without_gvl()... no
    checking for ffi_prep_cif_var()... no
    creating extconf.h
    creating Makefile

    nmake
   'nmake' is not recognized as an internal or external command,
    operable program or batch file.


text:
Q: Zend Action Controller - refactoring strategy I've built a first-run web service on Zend Framework (1.10), and now I'm looking at ways to refactor some of the logic in my Action Controllers so that it will be easier for me and the rest of my team to expand and maintain the service.
I can see where there are opportunities for refactoring, but I'm not clear on the best strategies on how. The best documentation and tutorials on controllers only talk about small scale applications, and don't really discuss how to abstract the more repetitive code that creeps into larger scales.
The basic structure for our action controllers are:

*

*Extract XML message from the request body - This includes validation against an action-specific relaxNG schema

*Prepare the XML response

*Validate the data in the request message (invalid data throws an exception - a message is added to the response which is sent immediately)

*Perform database action (select/insert/update/delete)

*Return success or failure of action, with required information

A simple example is this action which returns a list of vendors based on a flexible set of criteria:
class Api_VendorController extends Lib_Controller_Action
{
    public function getDetailsAction()
    {
        try {
            $request = new Lib_XML_Request('1.0');
            $request->load($this->getRequest()->getRawBody(), dirname(__FILE__) . '/../resources/xml/relaxng/vendor/getDetails.xml');
        } catch (Lib_XML_Request_Exception $e) {
            // Log exception, if logger available
            if ($log = $this->getLog()) {
                $log->warn('API/Vendor/getDetails: Error validating incoming request message', $e);
            }

            // Elevate as general error
            throw new Zend_Controller_Action_Exception($e->getMessage(), 400);
        }

        $response = new Lib_XML_Response('API/vendor/getDetails');

        try {
            $criteria = array();
            $fields = $request->getElementsByTagName('field');
            for ($i = 0; $i < $fields->length; $i++) {
                $name = trim($fields->item($i)->attributes->getNamedItem('name')->nodeValue);
                if (!isset($criteria[$name])) {
                    $criteria[$name] = array();
                }
                $criteria[$name][] = trim($fields->item($i)->childNodes->item(0)->nodeValue);
            }

            $vendors = $this->_mappers['vendor']->find($criteria);
            if (count($vendors) < 1) {
                throw new Api_VendorController_Exception('Could not find any vendors matching your criteria');
            }

            $response->append('success');
            foreach ($vendors as $vendor) {
                $v = $vendor->toArray();
                $response->append('vendor', $v);
            }

        } catch (Api_VendorController_Exception $e) {
            // Send failure message
            $error = $response->append('error');
            $response->appendChild($error, 'message', $e->getMessage());

            // Log exception, if logger available
            if ($log = $this->getLog()) {
                $log->warn('API/Account/GetDetails: ' . $e->getMessage(), $e);
            }
        }

        echo $response->save();
    }
}

So - knowing where the commonalities are in my controllers, what's the best strategy for refactoring while keeping it Zend-like and also testable with PHPUnit?
I did think about abstracting more of the controller logic into a parent class (Lib_Controller_Action), but this makes unit testing more complicated in a way that seems to me to be wrong.

A: Two ideas (just creating an answer from the comments above):

*

*Push commonality down into service/repository classes? Such classes would be testable, would be usable across controllers, and could make controller code more compact.

*Gather commonality into action helpers.

A: Since you have to do this step every time a request is made, you could store that receive, parse and validate the received request in a Zend_Controller_Plugin which would be run every PreDispatch of all controllers. (Only do-able if your XML request are standardized) (If you use XMLRPC, REST or some standard way to build requests to your service, you could look forward those modules built in ZF)
The validation of the data (action specific) could be done in a controller method (which would then be called by the action(s) needing it) (if your parametters are specific to one or many actions of that controller) or you could do it with the patterns Factory and Builder in the case that you have a lot of shared params between controllers/actions
// call to the factory
$filteredRequest = My_Param_Factory::factory($controller, $action, $paramsArray) // call the right builder based on the action/controller combination

// the actual Factory

class My_Param_Factory
{
    public static function factory($controller, $action, $params)
    {
        $builderClass = "My_Param_Builder_" . ucfirst($controller) . '_' . ucfirst($action);

        $builder = new $builderClass($params);

        return $builder->build();
    }
}

Your builder would then call specific parameters validating classes based on that specific builder needs (which would improve re-usability)
In your controller, if every required params are valid, you pass the processing to the right method of the right model
$userModel->getUserInfo($id) // for example

Which would remove all of the dataprocessing operations from the controllers which would only have to check if input is ok and then dispatch accordingly.
Store the results (error or succes) in a variable that will be sent to the view
Process the data (format and escape (replace < with < if they are to be included in the response for example)), send to a view helper to build XML then print (echo) the data in the view (which will be the response for your user).
public function getDetailsAction()
{
    if ($areRequestParamsValid === true) {
        // process data
    } else {
        // Build specific error message (or call action helper or controller method if error is general)
    }

    $this->view->data = $result
}


text:
Q: Playing Connect 6? Say I'm playing Connect 6, a variation of Connect 4, and I get to go first. For a $n \times n$ board, which position should I place my chip on to maximize my odds of winning?
Note than unlike Connect 4, Connect 6 requires 6 chips in a row. Additionally, the chips are placed on a board, so you can place a chip on any unoccupied position, regardless of if theres a chip below it or not.
Does it matter?


text:
Q: How to determine parameters for t-SNE for reducing dimensions? I am very new to word embeddings. I want to visualize how the documents are looking after learning. I read that t-SNE is the approach to do it. I have 100K documents with 250 dimensions as size of the embedding. There are several packages available as well.
However, for t-SNE, I don't know how many iterations or the value of alpha or the value of perpexility I should keep to learn better.
Are these hyper-parameters or can these be determined by some attributes?

A: I will cite the FAQ from t-SNE website.
First for perplexity:

How should I set the perplexity in t-SNE?
The performance of t-SNE is fairly robust under different settings of
  the perplexity. The most appropriate value depends on the density of
  your data. Loosely speaking, one could say that a larger / denser
  dataset requires a larger perplexity. Typical values for the
  perplexity range between 5 and 50.

For all other paremeters I would consider reading this:

How can I asses the quality of the visualizations that t-SNE
  constructed?
Preferably, just look at them! Notice that t-SNE does not retain
  distances but probabilities, so measuring some error between the
  Euclidean distances in high-D and low-D is useless. However, if you
  use the same data and perplexity, you can compare the Kullback-Leibler
  divergences that t-SNE reports. It is perfectly fine to run t-SNE ten
  times, and select the solution with the lowest KL divergence.

In other words it means: look at the plot, if the visualization is good don't change the parameters. You can also choose the run with the lowest KL divergence for each fixed perplexity.

A: I highly reccomend the article How to Use t-SNE Effectively. It has great animated plots of the tsne fitting process, and was the first source that actually gave me an intuitive understanding of what tsne does.
At a high level, perplexity is the parameter that matters.  It's a good idea to try perplexity of 5, 30, and 50, and look at the results.
But seriously, read How to Use t-SNE Effectively.  It will make your use of TSNE more effective.
For packages, use Rtsne in R, or sklearn.manifold.TSNE in python


text:
Q: PHP: Regular expression / preg_match() until EOL In an HTML page is a line like this:

State: Ohio

What I'm looking for is a regex which gets the content between State: and the EOL.
I've tried this but it doesn't work because it ignores the
-"end"
preg_match('/State:(.*)<\/a><\/p>/',$html,$format);

A: Description
This regex will find the
State: and return everything from  to the end of the line into group 1. Note by including the $ symbol you'll also want to include the m option to force the regex to allow the $ to match end of lines.
With your sample text:
State: Ohio

Regex:
State:(.*?$)

Group 1 will have  Ohio

If you really want to just capture the anchor tag directly after the strong tag group not including the close
, then try this:
Regex:
State:\s*(.*?)
$

Group 1 will have Ohio
Disclaimer
Parsing HTML with regex may not be the easiest thing to maintain in the long run. However if you have control over your input text, the text remains pretty much uncomplicated, and you're willing to have the periodic edge case where a regular expresion might fail then regex will work for you.
PHP Html Parse
Enough of the soap box. If you're ready to investigate html parsing in PHP then have a look at this  example of pulling all the anchor tags on a page and returning their href attribute and link text:
$dom = new DOMDocument;
$dom->loadHTML(file_get_contents('http://www.YourPageHere.com/'));

// echo Links and their anchor text
echo '
';
echo "Link\tAnchor\n";
    foreach($dom->getElementsByTagName('a') as $link) {
    $href = $link->getAttribute('href');
    $anchor = $link->nodeValue;
    echo $href,"\t",$anchor,"\n";
    }
echo '
';


text:
Q: Why did Batman do so much better in his second fight with Bane? In The Dark Knight Rises, Batman's first encounter with Bane goes rather badly.

In short, Batman gets utterly destroyed, and does no apparent damage to Bane.
Later, they meet again, and Batman manages to hold his own, and even come out ahead until Talia intervenes.  Bane's skills have deteriorated so thoroughly that he spends a good second or two punching a pillar where Batman used to be.

Batman still doesn't look good, but he gets the job done.
Is the disparity between these two performances from Batman entirely the result of the fact that he broke Bane's mask in the second fight, or is there something else going on here?

A: Your question:
Is the disparity between these two performances from Batman entirely the result of the fact that he broke Bane's mask in the second fight, or is there something else going on here?
has the answer:
Indeed, it is breaking the mask because Bane was vastly superior. Your video of the second fight is highly misleading because it is already near the end of the fight.
Bane: "So you came back to die within your city".
Batman: "No. I came back to stop you".
Bane attacks with straight punch slightly from above.
Batman blocks the punch down with both hands and counterattacks with moving both arms up. No reaction from Bane.
Bane connects with a strong left hook.
Bane continues with a vicious right punch, Batman staggers.
Bane lands another punch with the left hand, Batman staggers back.
cut scene
Bane punches Batman strongly with the left hand.
Bane punches Batman in the midsection with an uppercut.
Bane punches Batman again in the midsection, Batman goes back.
Bane punches Batman's head with the left, Batman must roll with the punch.
Bane punches Batman's head with the right and really throw Batman back.
Bane takes a run and kicks Batman in the midsection, Batman stumbles on the stairs and goes up.
Batman awaits Bane and attacks with a strong left.
Bane blocks it and counters with a strong right into Batman's side.
Bane continues with a left swing to Batman's head and connects.
Bane punches with the right, Batman blocks with arms up.
Both are going into clinching, Batman tries to pinch Bane with the right
arm and tries to hit him with the left.
Bane catches the left arm and both are going into a contest of strength
which goes on for some time.
Until now Bane has hit Batman 11 times, Batman has only achieved one hit and it did not show any effect so far. Bane is vastly superior.
Now the key scene: Batman is able to break the fist lock by moving the arm down and finally connects with a surprise punch right into Bane's mask.
Bane is surprised and for a moment stunned.
Batman lands a second strong hit on Bane's mask with the left hand.
Batman uses his chance and connect with a third hit to Bane's mask.
Batman connects with the left elbow, Bane goes down.
Batman holds Bane's head in a arm lock with the left arm.
Bane punches Batman with his head into the upper torso.
Batman goes back, Bane moves an idiot in his path out of the way.
Bane attacks with a weak left, Batman blocks and lands two
terrific blows with the left and the right, the mask audibly
snaps.
Bane holds a moment and the first time his look says: "Oh crap!"
Batman tries to go into the clinch, Bane throws him back and frantically
tries to fix the mask.
Batman attacks and Bane hits him with an outward punch with the right, throwing Batman back.
Bane attacks Batman with the right, Batman blocks it.

Now Bane realizes that he needs to go to full attack and dishes out
uncontrolled, vicious punches to put Batman down. This is the scene in
the shown video.
It is now evident that the control and the agility of Bane had suffered
greatly, he attacks 6 times and Batman easily dodges the blows and hits
Bane again with two powerful blows on the mask.
Bane attacks and misses two times, Batman diverts the third blow, attacks
with the right, Bane blocks, Batman puts Bane's defense down.
Again Batman hits Bane two times on his mask and kicks him into the hall.
Bane is defeated.
So the story is: yes, only the lucky hit on the mask put Bane on the defensive, before that he acted exactly like the first time: as unstoppable juggernaut.

A: In his first fight with Bane, 1) Batman subconsciously wants to die, and 2) Bane is more motivated.
Others have noted some of the tactical reasons why Batman lost the first fight and won the second.  That's definitely part of it, but I'm going to argue for a more fundamental reason.
At the beginning of the film, Gotham is at a point where it apparently does not need Batman (the Dent Act led to the end of organized crime in that city).  That is what Bruce wanted, since if he could stop being Batman he could pursue a relationship with the woman he loves, Rachel.  With Rachel's death, he no longer has a reason to not be Batman, but Gotham also does not need Batman (at least it appears this way at the beginning of the film).
Given those things, Bruce no longer has a sense of purpose, which is evidenced by his reclusiveness and neglect of Wayne Enterprises.
Bane's emergence seems to give Bruce a reason to be Batman again, but he doesn't have an "exit plan," as his did before.

WAYNE: Rachel died knowing we'd decided to be together. That was my life beyond this cave and I can't just move on. She didn't. She couldn't.

Alfred also worries about this:

WAYNE: That's what you're afraid of - that if I go back out there I'll fail.
ALFRED: No. I'm afraid that you want to.

So, my theory is that Bruce subconsciously wants to die.  I don't think that he wants Bane specifically to kill him, but he's okay with being killed as Batman in one way or another.  Bane even notes this:

BANE: You don't fear death. You welcome it. Your punishment is to be more severe.

After Bruce loses to Bane and is in prison, he is annoyed by the fact that he wasn't killed. He asks Bane:

WAYNE: Why didn't you just kill me?

He even asks the other prisoners to kill him:

PRISONER: He asks if you would pay us to let you die. I told him you have nothing.
WAYNE: Do it for the pleasure.

At this point in the film he really wishes he would have just been killed in his fight with Bane.
So that explains the first part of the question.
As to the second part...
Batman wins the second fight because 1) he learns to fear death, 2) his desire to save Gotham as Batman is rekindled, 3) "falling" and "rising again" made him stronger.
In prison, the TV images of what's occurring in Gotham motivate Bruce to recover from his injuries and train.  He's noticeably more driven than before.  He sees Ra's al Ghul in a hallucination, who taunts him about his failure to save Gotham.  This gives him additional motivation and purpose:

PRISONER: Why build yourself?
WAYNE: I'm not meant to die in here.

The film makes it clear that Bruce needs to learn to fear death.  Batman can't make the "jump" without fear.  With the safety rope, he doesn't have the appropriate fear of death.  Without it, he does have the right amount of fear, which motivates him to make the jump.

WAYNE: I do fear death. I fear dying in here while my city burns with no one there to save it.

Presumably this fear of death, his anger over what Bane did to Gotham, and his training let Bruce beat Bane the second time around.

A: The first fight is an ambush set up by Bane. He set the time, and the place. He knows things about Batman that Batman did not think he knew - that he is Bruce Wayne for example, off the bat (I would say that pun is unintentional, but I'd be lying). Batman is mentally thrown off. His tricks don't work:

Theatricality and deception are powerful agents to the uninitiated...
but we are initiated, aren't we Bruce? Members of the League of
Shadows!
....
Oh, you think darkness is your ally. But you merely
adopted the dark; I was born in it, moulded by it. I didn't see the
light until I was already a man, by then it was nothing to me but
BLINDING!

There's also the discussion with Alfred that occurs earlier in the movie:

Bruce Wayne: If this man is everything that you say he is, then this
city needs me.
Alfred: This city needs Bruce Wayne, your resources,
your knowledge. It doesn't need your body, or your life. That time has
passed.
Bruce Wayne: You're afraid that if I go back out there I'll
fail.
Alfred: No. I'm afraid that you want to.

The Batman in the second fight turns up at Gotham, and Bane is completely blindsided - "I broke you". This time he's not thinking clearly, and as the fight goes on, Batman manages to trigger his rage. That punching the pillar scene isn't a loss of "skill"; it's a disoriented, extremely violent ball of rage punching with extreme strength as Batman is focused on staying out of the way of those fists. Bane's also distracted elsewhere - the vehicle with the nuke is the important part of his plan, and there's a strong sense that he means to be consumed by the nuke as well.
Batman has changed also - previously, even if he wasn't suicidal, his entire thing was about not fearing death. He has now learned a lesson about using his own fear to empower himself.
And so, the tables have turned.

A: A big influence on the Nolan trilogy is The Dark Knight Returns and this battle looks highly influenced by Batman's fights with the mutant leader.
The mutant leader has similar physical attributes to Bane, he's younger, stronger, fitter, and has a driven savagery:

and indeed Batman comes off rather badly after their first fight:

Later Batman rematches with the mutant leader, having taken stock of the situation.
He realizes:

My mistake was to try to match his savagery

He had tried to fight the mutant leader (as he did with Bane) as a straight one-on-one, where Bane had the advantage of youth, strength and drive.
This time though Batman uses his experience, and his skills, as we can see in the question above neatly avoiding Bane's attacks, wearing him down.
Eventually having worn him down he can take him on straight, to a win this time

Of course in the Dark Knight Rises, Miranda intercedes, but you get the idea.

A: So, for your question, there are many answers, but I will provide you the main reasoning for why Batman gets exterminated by bane in the first fight, and wins the second.
Why Batman lost his first fight:
As seen at the start of the movie, Bruce Wayne is holding a stick and walking helplessly, depressed, with anxiety because he was accused for the cause of death of Harvey Dent, 8 years ago in "The Dark Knight". Now he decides to take on his role as the caped crusader once again after Bane poses a serious threat to the city, with starting a "fire" as mentioned briefly while he was hijacking the plane. It became clear that Bane's intentions for Gotham were terroristic to the city, especially with the nuclear bomb near the climax of the movie. However, let's talk about Batman's first encounter with Bane, and why that went wrong. The city was in need of a savior, and Batman noticed that, and decides to find Bane and end this, despite being warned of Bane's skills and tactics by Alfred. Now he was not ambushed but surprised in the fact that Cat Woman turned on him, as she did not want to threaten her own life. Batman hears Bane interrupting his talk with Catwoman and turns to face him on a bridge like structure, with Bane right across. Now before this fight even started there was already a major flaw that Batman had not realized with fighting Bane, and that was his overconfidence. He only saw Bane as a mercenary under the league of shadows and R'as al ghul. He thought that since he defeated Ra's Al ghul himself, there was no way he would lose his fight with Bane. He underestimated Bane's power and right as the fight had begun, you could tell that this would not end well for the dark knight:

I mean, just look at how slow and weak his punches at the start were, Bane wasn't doing anything at the beginning, he wasn't even trying. Batman literally starts off with holding Bane's vest and it takes him a whole 2 second from him holding his vest to his first punch. After he uppercuts and swings a right at bane, and as Bane catches his hand, he reveals what Batman is really missing. This was just an exhausted and weak dark knight, I mean he is supposed to know all 127 martial arts, and as seen he is just making a fool of himself. And this relates to the second reason for why he lost, it had been 8 whole years since he has taken the role as Batman, he is weak and merely lost his skill. He was not at all ready to fight Bane. Bane even says: " Peace has cost you your strength, victory has defeated you " he is highlighting how his exhaustion and inexperience lead to a loss of strength and power. He didn't listen to Alfred, and that ended up costing him his back. He invited death in the hands of bane, despite knowing the city needed him. This was an unmotivated, weak, powerless, unskilled, overconfident, broken dark knight. I mean he lost so much skill, that later in the same fight, he was grabbing Bane with his right and was punching with his left continuously while deprived of strength and energy.
Now let's talk about why he won his second fight with Bane:
After losing his fight, he gained his motivation by prisoners and watching Gotham on a TV, he knew they needed a hero. He worked out, trained, rose back up again. R'as al ghul, came in his dream to wake him up, and remind him of his defeat, which motivated him even more. After successfully making the jump with fear, he overcame his biggest weakness. He grew stronger, and was ready for Bane. He fought with more skill and power and more intelligence, as he figured Bane's weakness and abused it to his advantage. Batman was not weak and was in better shape and grew stronger after the climb, he fought his fears with intense motivation as the caped crusader.

A: Batman was the hottest fighting commodity when he was properly involved in his aim of destroying Joker and thugs in the Dark Knight but when he appeared in the Dark Knight Rises, he got confronted with the doctor saying to him that: "You are Physically wrecked MR Wayne".
Bane encountered with the old and out of practice Batman that is why he remained dominant. When Alfred warned him that Bane could deliver you a surprise damage, Bruce showed a non serious reply to his warnings and at the first dual he discovered that why Alfred was worrying about his feud with Bane.
In the pit, when Batman met with the vision of his biggest dysfunction, Du Card RAS AL GHUL. He got his self triggered again and somehow not so comprehensively, betrayed bane by hitting couple of punches on his mask. If Bane gets an encounter with the well trained and ferocious Batman as he was in The Dark Knight, Bane could be troubled.
So the sum up is, Chris Nolan portrayed that even by facing decline physically, mentally and economically, a man can rise and grip the things up.

A: Talia obviously knew Batman was going to meet Bane that night (their first fight): she and Bane were partners and in communication with each other, and an important part of their plan would be to eliminate Batman as a threat, so she would be aware of the trap Bane was setting. It's probably not coincidental that she chose that time to seduce Bruce; she was trying to deplete him of as much energy as she could so he'd be exhausted later when fighting Bane. (This is in addition to all the factors mentioned in the other answers.)

A: Another factor is simply because he feared the bat. When he saw the bat logo burned on the bridge, he was terrified of the man he dealt with.

A: I'll give my view by sharing another Hollywood example. In his first fight with Bane, Batman had lost his fire, his "eye of the tiger" if you will. He appeared to have spent his years of solitude(following Harvey's death) wallowing in self pity and depression, welcoming death and allowing his mind and body to deteriorate to a state reminiscent of Howard Hughes(which is referenced by peeing in "mason jars" "When the man approaches with the bag of cookies I want him to hand them to me with his left hand..." Soon after his reemergence Batman battles his toughest foe to date and understandably loses.
Which brings me back to Rocky 3. Rocky became complacent and did not heed Micky's warnings of how dangerous Clubber is. He didn't have the "eye of the tiger" and loses spectacularly. He and Batman undergo similar character redemptions complete with training montages and they both come back and defeat their greatest challenge after suffering strife and growing from their failure, and they both become stronger after their journeys.


text:
Q: How to adapt bound text to div I have two divs side by side. The problem is, when I have long bound text in one div, it overflows to the second.
here is an example:
http://jsfiddle.net/hjZ8F/1/
How to adapt?

A: Here is working version of your jsFiddle: http://jsfiddle.net/hjZ8F/2/
Just add word-wrap: break-word; to the style attribute of the long span


text:
Q: how to get the label element's position which in the list, about flex mobile i want to get the label element's position which in the list ,
but i get 8 0 8 0 (Global position)x:8,y:0
that is not right , so what can i do , thanks
this is my code :
<?xml version="1.0" encoding="utf-8"?>
<!-- http://www.myflexhero.com/share/flex-hero-flex4/flex-hero-components/flex-hero-graphics/822 -->
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
               xmlns:s="library://ns.adobe.com/flex/spark"
               xmlns:mx="library://ns.adobe.com/flex/mx"
               >
    <fx:Script>
        <![CDATA[
            import mx.core.UIComponent;

        protected function getListChildAt(part:List,n:int):Label {
            var child:UIComponent = part.dataGroup.getChildAt(n) as UIComponent;
            var child_1:Label =  child.getChildAt(0) as Label;
            return child_1;
        }

        protected function show():void
        {
            var item:Label = getListChildAt(myList,0) as Label;
            var item2:Label = getListChildAt(myList,2) as Label;
            var p:Point = new Point(item.x,item.y);
            p = item.localToGlobal(p);
            var p2:Point = new Point(item2.x,item2.y);
            p2 = item.localToGlobal(p2);

            //globalLabel.text = "(Global image)x:"+p.x+",y:"+p.y;
            trace(p.x,p.y,p2.x,p2.y,"(Global position)x:"+p.x+",y:"+p.y);

        }
        protected function myList_changeHandler(event:Event):void{

        }
    ]]>
</fx:Script>
<s:List id="myList"
        width="100%" height="100%"
        labelField="firstName"
        change="myList_changeHandler(event)">

    <s:layout>
        <s:TileLayout requestedColumnCount="4" columnWidth="80" horizontalAlign="center" verticalAlign="middle"  />
    </s:layout>
    <s:dataProvider>
        <s:ArrayCollection>
            <fx:Object firstName="Bill" lastName="Smith" companyID="11233"/>
            <fx:Object firstName="Dave" lastName="Jones" companyID="13455"/>
            <fx:Object firstName="Mary" lastName="Davis" companyID="11543"/>
            <fx:Object firstName="Debbie" lastName="Cooper" companyID="14266"/>
        </s:ArrayCollection>
    </s:dataProvider>

    <s:itemRenderer>
        <fx:Component>
            <s:ItemRenderer>
                <s:Label   text="{data.lastName}"/>
            </s:ItemRenderer>
        </fx:Component>
    </s:itemRenderer>
</s:List>

    <s:VGroup >
        <s:Label id="image1" text="ssss" />
        <s:Button click="show()" label="show Global x、y"/>
    </s:VGroup>

</s:Application>

A: <?xml version="1.0" encoding="utf-8"?>

        protected function getListChildAt(part:List,n:int):UIComponent {
            var child:UIComponent = part.dataGroup.getChildAt(n) as UIComponent;
            var child_1:UIComponent =  child.getChildAt(0) as UIComponent;
            trace(child_1.parent == child)
            return child_1 ;
        }

        protected function show():void
        {
            var item:UIComponent = getListChildAt(myList,2);
            var item2:UIComponent = getListChildAt(myList,0);
            p = new Point(item.parent.x,item.parent.y);
            p = myList.localToGlobal(p);
            p2 = new Point(item2.parent.x,item2.parent.y);
            p2 = myList.localToGlobal(p2);

            mover.play()
        }
        protected function myList_changeHandler(event:Event):void{

        }

    ]]>
</fx:Script>
<s:List id="myList" x="40" y="55" width="400" height="100" change="myList_changeHandler(event)"
        labelField="firstName">

    <s:layout>
        <s:TileLayout requestedColumnCount="4" columnWidth="80" horizontalAlign="center" verticalAlign="middle"  />
    </s:layout>
    <s:dataProvider>
        <s:ArrayCollection>
            <fx:Object firstName="Bill" lastName="Smith" companyID="11233"/>
            <fx:Object firstName="Dave" lastName="Jones" companyID="13455"/>
            <fx:Object firstName="Mary" lastName="Davis" companyID="11543"/>
            <fx:Object firstName="Debbie" lastName="Cooper" companyID="14266"/>
        </s:ArrayCollection>
    </s:dataProvider>

    <s:itemRenderer>
        <fx:Component>
            <s:ItemRenderer>
                <s:Label  text="{data.lastName}" width="70" height="30"/>
            </s:ItemRenderer>
        </fx:Component>
    </s:itemRenderer>
</s:List>

<fx:Declarations>
    <!-- Place non-visual elements (e.g., services, value objects) here -->
    <s:Animate id="mover" target="{button}" duration="1000">
        <s:SimpleMotionPath property="x" valueFrom="{p.x}" valueTo="{p2.x}"/>
        <s:SimpleMotionPath property="y" valueFrom="{p.y}" valueTo="{p2.y}"/>
    </s:Animate>
</fx:Declarations>
<s:Button id="button"  click="mover.play()" label="" width="70"/>

<s:Label id="image1" x="0" y="0" text="ssss" backgroundColor="red"/>
<s:Button x="27" y="100" label="show Global x、y" click="show()"/>

A:             var item:UIComponent = getListChildAt(myList,2);
            var item2:UIComponent = getListChildAt(myList,0);
            p = new Point(item.parent.x,item.parent.y);
            p = myList.localToGlobal(p);
            p2 = new Point(item2.parent.x,item2.parent.y);
            p2 = myList.localToGlobal(p2);

            var a:Rectangle =  item2.getBounds(root);
            trace(a.x);


text:
Q: Subversion - add time stamp to file With subversion, when i commit a file, can it automatically append a commented out time stamp to the bottom of the file?

A: Are you looking for how to set an $Id$ comment, much like CVS does? It seems like it'll meet your needs, and there are instructions for doing so here:
http://www.startupcto.com/server-tech/subversion/setting-the-id-tag


text:
Q: Read specific files with Spark (exact match only) I need to read a specific set of text files using Spark:
df = spark.text.read(paths)

The problem is that Spark treats the path as either a directory or a file. This has two problems:

*

*If the file does not exist, it's skipped with just a warning in the log – "directory does not exist; was it deleted recently?"

*Trying to list the path as a directory takes additional processing time.

From the documentation, Spark uses partition discovery by default (which means it must try to list the path as a directory), but it can also operate in a different mode – enabled by the recursiveFileLookup option.
What I want is a third mode where it just reads each of the provided paths as an exact match file. Is there a way to achieve this without a change in Spark's read method?


text:
Q: C sharp Dapper ms access query like parameters I have a list of parameters : numericPartList : 029%, 035% for example.
As mentioned in the code, with only 1 parameter it works, but more, no...
public static List<tLicencie> GetDepartement(List<string> numericPartList)
{
    ConnectionStringSettings connex = ConfigurationManager.ConnectionStrings["MaConnection"];
    string connString = connex.ProviderName + connex.ConnectionString;
    using (OleDbConnection con = new OleDbConnection(connString))
    {
        string sql;
        if (numericPartList.Count < 2)
        {
            sql = "select * from tLicencie where NOCLUB like @numericPartList "; // Works !
        }
        else
        {
            sql = "select * from tLicencie where NOCLUB like @numericPartList "; // Does not Work
        }
        return (List<tLicencie>)con.Query<tLicencie>(sql, new { numericPartList });
    }
}

I get an error message :

Syntax error (comma) in expression 'NOCLUB like (@ numericPartList1, @ numericPartList2)'. "

How to solve this problem?
A solution for the moment: I add DapperExtentions then
var pga = new PredicateGroup { Operator = GroupOperator.Or, Predicates = new List<IPredicate>() };

                pga.Predicates.Add(Predicates.Field<tLicencie>(f => f.NOCLUB, Operator.Like, "029%"));
                pga.Predicates.Add(Predicates.Field<tLicencie>(f => f.NOCLUB, Operator.Like, "035%"));

                IEnumerable<tLicencie> list = con.GetList<tLicencie>(pga);

A: The dapper list expansion is only intended for use with in, i.e. it would expand:
where foo in @x

to
where foo in (@x0, @x1, @x2)

(or some other variants, depending on the scenario).
It cannot be used with like in this way, as it will give invalid SQL; you would need to compose your SQL and parameters in a more manual fashion, perhaps using DynamicParameters which works more like a dictionary; i.e. you would need to loop in such a way as to construct
where (foo like @x0 or foo like @x1 or foo like @x2)


text:
Q: Reduce boot time for windows update on server I have a server at home which runs Windows server 2008 R2. (I suppose this would work for any OS version. You do not have to keep this in mind while answering.) I seldomly install windows updates on it because the boot times are long, and I don't want to have the services I run on it be offline for too long.
If I normally reboot the server without windows updates, it takes some time, but its acceptable. But if I have to install, say... 100 windows updates, the boot time can be extended quite a bit.
Is there a way to minimize the boot time? I've considered running the server inside a Hyper-V but then the hyper-v server would still need to be updated and rebooted once in a while, which defeats the purpose. Upgrading the server's hardware is also out of the question.
Rebooting more frequently with less updates would of course work, but thats not what I want to know here.

A: I don't think there's a proper answer for this. 2008 R2 had its latest service pack four years ago. Windows Update is notoriously inefficient.. Cleaning up your updates folder might make it slightly faster:
http://blogs.technet.com/b/askpfeplat/archive/2014/05/13/how-to-clean-up-the-winsxs-directory-and-free-up-disk-space-on-windows-server-2008-r2-with-new-update.aspx
1) check if KB2852386 is installed. If not, download it here: http://www.microsoft.com/en-us/download/details.aspx?id=42739
2) turn on Desktop Experience via the Add Features Wizard -> requires reboot!
3) run Windows Cleanup and select Windows Update Cleanup
I tried these steps and they shaved off some time but it's still slow. erver 2012 is a lot faster in my experience.


text:
Q: ODatabaseException OrientDB Record Error I'm struggling to fix my orientdb database. I'm getting the error:

Error: com.orientechnologies.orient.core.exception.ODatabaseException: Error on retrieving record #58:65894 (cluster: cluster_name_here)

I'm running REPAIR DATABASE --fix-graph and that's when i get this error. Is there any other suggestions in approaching this? This is also the case when running CHECK DATABASE
I tried using this link as a resource: https://orientdb.com/docs/last/Console-Command-Repair-Database.html


text:
Q: Delete item from nested object array I'm working with AngularJS and have an object array like that in my controller :
$scope.folderList = [{
    name: 'root',
    path: 'uploads/',
    subs: [{
        name: 'pictures',
        path: 'uploads/pictures',
        subs: [{
            ...
        }]
    }, {
        name: 'videos',
        path: 'uploads/videos',
        subs: [{
            ...
        }]
    }]
}];

For this nested array, I have 2 directives set them up in a nested UL LI list with ng-repeat.
Now I have my nested list of folders, and I want to trigger a function to delete the selected folder.
So I trigger my function to delete with "folder" in parameter, for example, if I trigger the "delete" function on the pictures folder, the folder parameter will be like that :
folder = {
    name: 'pictures',
    path: 'uploads/pictures',
    subs: [{ ... }]
}

And I want to delete this object from the nested array.
With a 1 level object array, I use this :
var index = $scope.folderList.indexOf(folder);
delete $scope.folderList.splice(index, 1);

But it (obviously) doesn't work on a nested array !
How can I easily delete an entry from a nested array on JavaScript (or AngularJS ?)
I've heard that underscore.js was made for this, but I never used it, and after seeing their  documentation I wasn't able to find the proper function to do this !
Thanks for your help !


text:
Q: Adding multiple properties into nested JSON array I've done a lot of searching at it appears there is no article for this specific case.
I have some JSON (Note that it is a JArray, and not a JObject)
[
  {
    "Name": "Name 1",
    "Icon": "Icon 1",
    "Samples": [
      {
        "Name": "Sample 1",
      },
      {
        "Name": "Sample 2",
      },
      {
        "Name": "Sample 3",
      }
    ]
  },
  {
    "Name": "Name 2",
    "Icon": "Icon 2",
    "Samples": [
      {
        "Name": "Sample 1",
      },
      {
        "Name": "Sample 2",
      },
      {
        "Name": "Sample 3",
      }
    ]
  },
  {
    "Name": "Name 3",
    "Icon": "Icon 3",
    "Samples": [
      {
        "Name": "Sample 1",
      },
      {
        "Name": "Sample 2",
      },
      {
        "Name": "Sample 3",
      }
    ]
  },
]

So this has 3 levels. The root, which contains the "SampleCategories". The "SampleCategories" which contains some items and a "Samples" list, and the "Samples" list which contains many objects.
So, what I'm essentially trying to do here is to add an object into the Samples list, inside a specific SampleCategory. So for example:
I want to add "Sample 4" to the Samples array in "Name 1" so it looks like this:
  {
    "Name": "Name 1",
    "Icon": "Icon 1",
    "Samples": [
      {
        "Name": "Sample 1",
      },
      {
        "Name": "Sample 2",
      },
      {
        "Name": "Sample 3",
      },
      {
        "Name": "Sample 4",
      }
    ]
  },

I thought this would be fairly easy when I started out but it turns out there are lots of roadblocks that I can't seem to get my head around.
So I have two models for each level, "SampleCategory" for the top level that has the Name, Icon and Samples, which goes off to another model called "Samples[]"
So I'm afraid I'm at an embarrassing point in this process... Right at the start. I've de-serialised the json, and done some bits around finding my chosen SampleCategory, and created an object ready to add in, and that's as far as I've gotten...
var categories = JsonConvert.DeserializeObject<List<SampleCategory>>(json);
var applications = categories.Find(c => c.Name.Equals("Name 1"));

var sample = new Sample
{
    Name = "Sample 4",
};

I don't appear to be able to find any way of adding a new 'sample' into the Samples list of a chosen SampleCategory. I even tried adding to the object path directly, the path of which I got using this:
JObject jo = jsonArray.Children<JObject>().FirstOrDefault(o => o["Name"] != null && o["Name"].ToString() == "Name 1");

But there doesn't appear to be a way to add to an array as I guess it's a static length?
What is best practice modifying JSON like this?
Documentation (https://www.newtonsoft.com/json/help/html/ModifyJson.htm) suggests there a few ways to do it when playing around with JObjects, but it doesn't suggest a way to do it with nested objects inside of JArrays.
Can anyone help or suggest some methods to do this? I'm sure it's probably simple, but I'm going through a loop trying to figure it out.

A: I'm not sure but it could be as simple as :
applications.Samples.ToList().Add(sample);

I have no privilege to comment it :(

A: I guess your model looks something like this:
public class Sample
{
    public string Name { get; set; }
}

public class SampleCategory
{
    public string Name { get; set; }
    public string Icon { get; set; }
    public List<Sample> Samples { get; set; }
}

If you are not sure how a model must look like to match a given json string you can make use of a tool like json2csharp which will generate the model for you.
To be able to add a new sample to a specific category you can find the specific category using LINQ after deserializing it:
var categories = JsonConvert.DeserializeObject<List<SampleCategory>>(json);
var category = categories.FirstOrDefault(c => c.Name == "Name 1");

Now (if a category with the name exists) just add the new sample to the list:
if(category != null)
{
    category.Samples.Add(new Sample{Name = "Sample 4"});
}

To serialize it back to json:
var json = JsonConvert.SerializeObject(categories);

Edit
If you cannot switch your model type for Samples to List<T> and you don't want to convert the array temporarily to List<T>, you can do something like this:
if(category != null)
{
    category.Samples = category.Samples.Concat(new Sample[]{new Sample{Name = "Sample 4"}}).ToArray();
}

If you are not bothered by an additional List<T> cast another approach would be:
if(category != null)
{
    var tmpList = category.Samples.ToList();
    tmpList.Add(new Sample{Name = "Sample 4"});
    category.Samples = tmpList.ToArray();
}


text:
Q: Extracting data from XML in parallel using R I have to process millions of xml files every week and I use a server that has 32 cores.  I run R on Ubuntu 14.04.   My current program extracts data using a for loop from these files and saves the output to MySQL. Since the processing is quite slow, I tried to parse data from xml in parallel.  The following are my codes so far:
//Function to parse data from xml

parse_xml <-function(FileName) {
  xmldata <- xmlParse(FileName)
  result_nodes = XML::getNodeSet(xmldata , "//IOTModellerLog/Event")
  if (!length(result_nodes)==0){
    abc <- rbindlist(lapply(result_nodes,function(x) data.frame(as.list(unlist(xmlToList(x))))),use.names = TRUE, fill = TRUE)

....do other calculations....

    abc <- data.frame(lapply(abc, as.character), stringsAsFactors = FALSE)
  }
}

//Function to merge two dataframes with NA fills for non matching columns
sbind = function(x, y, fill=NA) {
  sbind.fill = function(d, cols){
    for(c in cols)
      d[[c]] = fill
    d
  }
  x = sbind.fill(x, setdiff(names(y),names(x)))
  y = sbind.fill(y, setdiff(names(x),names(y)))

  rbind(x, y)
}

Path to all the xml files
path <- "/home/mycomp/Documents/xmls/xmlfrommtar"

Function to parsexml.
workerFunc <- function(file) {
    dat <- parse_xml(file)
      df <- sbind(df,dat)
    }

Codes for parallel processing
cl <- makeCluster(detectCores())
files <- dir(path, pattern="*.xml|*.XML", full.names = T)
part <- clusterSplit(cl, seq_along(files))
filesPart <- lapply(part, function(p) files[p])
results <- clusterApply(cl, filesPart, workerFunc)

When I run this, I get the following error:
Error in checkForRemoteErrors(val) :
  4 nodes produced errors; first error: could not find function "parse_xml"

This indicates two things to me, the files are getting distributed across all 4 cores of my machine.  The function clusterApply could not find parse_xml from within workerFunc.  However, I pretty much have the parse_xml file in my environment.
Sample XML data
IOTModellerLog xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" DeviceID="7430180" ClientID="12324" FileCreationDate="2017-03-01T22:40:03" FileVersion="2" EventClassID="65535" IOTLogCreationDate="2017-03-01T12:29:54" SampleID="1" xsi:noNamespaceSchemaLocation="/opt/nds/ams_proxy/webapps/ams_proxy/WEB-INF/amsXmlSchema.xsd">
   <Event EventTime="2017-02-27T18:33:58">
      <IOTEvent State="PowerOn" />
   </Event>
   <Event EventTime="2017-02-28T08:59:03">
      <DataEvent>
         <Model>1</Model>
         <DataType>1</DataType>
         <DataValue>0301</DataValue>
      </DataEvent>
   </Event>
   <Event EventTime="2017-02-28T08:59:13">
      <DataEvent>
         <Model>1</Model>
         <DataType>1</DataType>
         <DataValue>0401</DataValue>
      </DataEvent>
   </Event>
</IOTModellerLog>

A: You should initialize your cluster workers with something like:
clusterEvalQ(cl, library(XML))
clusterExport(cl, c('parse_xml', 'sbind'))


text:
Q: How to terminate early a functional computation Problem description: Given a list $A=\{1,2,0,7,0,-1,2,6,\ldots\}$ and a list $B=\{0,7,0\}$ write a program that determines whether $B$ appears in $A$ or not. Note: the order of $B$'s items does matter.
Functional way:
MemberQ[Partition[A, 3, 1], B]

The disadvantage of this way is that the whole list $A$ is processed even if $B$ is in the very start of $A$. Compare with the following code which terminates early if $B$ is found in $A$:
Procedural way:
found = False;
L = Length@A;
For[i = 1, i <= (L - 2) && !found, i++,
found = Take[A, {i, i + 2}] == B]

Question: Is there a functional way of solving the problem that does  not need to scan/process all of $A$'s elements ?
P.S. Feel free to edit the title.

A: More recent (10.1+) versions of Mathematica feature the SequencePosition function, which can be told to stop after the first match, like so:
SeedRandom[1337];
a = RandomInteger[{1, 10}, 10000];
b = {1, 7, 1};

SequencePosition[a, b, 1] // AbsoluteTiming
(* {0.000175, {{88, 90}}} *)

This is quite a bit faster than the MemberQ/Partition-based approach:
MemberQ[Partition[a, 3, 1], b, {1}] // AbsoluteTiming
(* {0.00199, True} *)

As a word of warning, you can use more general patterns with SequencePosition and similar functions, but as of version 10.3 the performance is only really good with fixed patterns like {1, 7, 1}.
EDIT to add: It seems to provide a similar speedup over other solutions, like in @belisarius' comment:
MatchQ[a, {___, PatternSequence @@ b, ___}] // AbsoluteTiming
(* {0.019747, True} *)


text:
Q: Mapping in configuration file when using Nhibernate's mapping by code I want to use mapping by code so I have a class Employee (namespace NHibernateTests.Classes) and a class EmployeeMappings (namespace NHibernateTests.Mappings)
My whole nhibernate configuration is set in an xml file hibernate.cfg.xml which currently goes like this:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
  <session-factory>
    <property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
    <property name="connection.driver_class">NHibernate.Driver.OracleClientDriver</property>
    <property name="connection.connection_string">User Id=NHIBERNATE;Password=NHIBERNATE;Data Source=XE</property>
    <property name="show_sql">false</property>
    <property name="dialect">NHibernate.Dialect.Oracle10gDialect</property>

    <mapping assembly="NHibernateTests"/>
  </session-factory>
</hibernate-configuration>

Which gives me the runtime error : No persister for: NHibernateTests.Classes.Employee

I tried (and error) some setting for mapping element but with no luck. I read how to set ressource for hbm.xml elements but couldn't find an answer for by code mapping.
namespace NHibernateTests.Classes
{
    public class Employee
    {
        public virtual Address Address { get; set; }
        public virtual string FirstName { get; set; }
        public virtual int Id { get; set; }
    }
}

namespace NHibernateTests.Mappings
{
    public class EmployeeMappings : ClassMapping<Employee>
    {
        public EmployeeMappings()
        {
            this.Id(e => e.Id, mapper =>
            {
                mapper.Generator(Generators.HighLow);
            });
        }
    }
}

A: With a mapping by code you should configure also your factory by code. There is one of few how-to:
NHibernate 3.2 Mapping by Code – Basic Mapping
cited code snippets (see above link for more details)
private static Configuration ConfigureNHibernate()
{
  var configure = new Configuration();
  configure.SessionFactoryName("BuildIt");

  configure.DataBaseIntegration(db =>
  {
    db.Dialect();
    db.Driver();
    db.KeywordsAutoImport = Hbm2DDLKeyWords.AutoQuote;
    db.IsolationLevel = IsolationLevel.ReadCommitted;

    db.ConnectionStringName = "NH3";
    db.Timeout = 10;

    // enabled for testing
    db.LogFormattedSql = true;
    db.LogSqlInConsole = true;
    db.AutoCommentSql = true;
  });

  var mapping = GetMappings();
  configure.AddDeserializedMapping(mapping, "NHSchemaTest");
  SchemaMetadataUpdater.QuoteTableAndColumns(configure);

  return configure;
}

thew way how to get HbmMapping
private static HbmMapping GetMappings()
{
  var mapper = new ModelMapper();

  mapper.AddMappings(Assembly.GetAssembly(typeof(ProvinceMap)).GetExportedTypes());
  var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();

  return mapping;
}


text:
Q: How can I change the plymouth booting animation on Ubuntu 19.04? I have downloaded a Plymouth theme from Gnome-loo.org. And since it was a deb package, I installed it through Ubuntu Software. Then, I typed "sudo update-alternatives --config default.plymouth" and selected the newly added theme. But it didn't work out at all, and Plymouth theme didn't change. If you know how to do it properly, please let me know. Thanks.

A: Seems to be its 2010 Created plymouth theme and the script is written to keep the plymouth theme directory under /lib/plymouth/themes/ as opposed to /usr/share/plymouth/themes/ for the recent versions..
by extracting the directory space-sunrise from the downloaded .deb file.. and editing the content like below in the space-sunrise.plymouth file it is possible to freshly install as a new theme under /usr/share/plymouth/themes/ directory.

ImageDir=/usr/share/plymouth/themes/space-sunrise
ScriptFile=/usr/share/plymouth/themes/space-sunrise/space-sunrise.script

*

*after editing the file at downloaded location.. copy the directory space-sunrise from downloaded location to /usr/share/plymouth/themes/

*the .deb file is really messing up the things with outdated path.. I could not remove the path with sudo update-alternatives so I removed the complete package of plymouth..

*sudo apt purge plymouth

*reboot..

*sudo apt install plymouth

*sudo update-alternatives --install /usr/share/plymouth/themes/default.plymouth default.plymouth /usr/share/plymouth/themes/space-sunrise/space-sunrise.plymouth 200

*sudo update-alternatives --config default.plymouth

*select the number of your choice

*sudo update-initramfs -u

*Reboot..


text:
Q: Django runserver não funciona O comando: python manage.py runserver 80
Retorna o seguinte:  (Pus screenshot, pois o texto fica desfigurado aqui)

O endereço localhost fica inacessível, independentemente da porta (8080, 8000, 80)
Pelo que entendi, é um erro de charset/encode, mas não achei solução para ele.

A: Está parecendo ser um bug conhecido do python, em que o runserver falha quando o nome da máquina contém caracteres "non-ASCII", tente uma das duas alternativas:
1) Chame runserver explicitando a porta e o host:
python manage.py runserver 127.0.0.1:8000

Ou:
2) Mude o nome do computador para uma string que contenha somente
    caracteres ASCII.


text:
Q: Instantiating a Multimap with a set? I have a Set<String> setOfStrings, and I want to place every string from the set into a MultiMap where each String in the set is its own key, and the corresponding value of each key is null. I could, of course, do this iteratively with:
Multimap multimap = HashMultimap.create();
for (String url : setOfStrings) {
    multimap.put(url, null);
}

However, is there any more shorthand/concise way to do this?
Thanks.

A: Given that:

*

*HashMultiMap has no constructors

*there is no create method that takes a set

*create(MultiMap) in this case only adds a layer of indirection

*none of the methods that return other Collection views (asMap, entries, keys, keySet, values) support add or put operations

I'd say you have the best solution.


text:
Q: Validation Application Block - Validation attributes multiple error order I'm playing with EL Validation Application Block.
When a validation is made using attributes, the validation order is not respected. For example:
public class Boat
{
    [Display(Name="License Plate")]
    [RequiredStringValidator]
    [RangeValidator(1,10)]
    public String RegistrationNumber
    {
        get;
        set;
    }

When i invoke the following code:
Validator vt = CreateValidator(typeof(Boat), ruleSet);
ValidationResults results = vt.Validate(instance);

results[0] - Error from StringLengthValidator
results[1] - Error from RequiredStringValidator(Custom Validator)
The problem is that the order is not always the same. It happens that RequiredStringValidator error is in 0 index position. It seems that .Net CLR does not guarantee Attributes position when retrieving it using Attributes.GetCustomAttributes, that is how VAB get properties attributes.
In this sample, in case of having 2 errors of the same property the first attribute error should be shown(RequiredStringValidator), but sometimes is StringLengthValidator attribute error that is shown because it stays in the ValidationResults first position.
This happen when using ASP.NET MVC model state.
@Html.TextBoxFor(a => a.RegistrationNumber)
@Html.ValidationMessageFor(a => a.RegistrationNumber)

In case of error the StringLengthValidator message should only appear if RequiredStringValidator validator has a valid result.
Any idea?

A: Just order the results:
var results = (
    from result in vt.Validate(instance)
    orderby result.Validator.GetType()
    select result)
    .ToArray();


text:
Q: How do I send email to files in ASP.NET? I remember reading somewhere that it's possible to configure your web.config to send email to files, instead of setting up a real SMTP server for development. How is this done?

A: Hidden Features of ASP.NET


text:
Q: BPF verifier throws error "expected=map_ptr" I'm writing a little eBPF program to set a flag whenever the tracepoint consume_skb is triggered. When I try to load it however, the BPF verifier complains, saying R1 type=inv expected=map_ptr when trying to access the map. I tried to follow the samples given in the linux kernel as closely as possible, but I am failing at even reading anything from the map.
eBPF program
#include <uapi/linux/bpf.h>
#include <bpf/bpf_helpers.h>

struct {
    __uint(type, BPF_MAP_TYPE_ARRAY);
    __type(key, u32);
    __type(value, u32);
    __uint(max_entries, 1);
} my_map SEC(".maps");

SEC("tracepoint/skb/consume_skb")
int bpf_sys(void *ctx)
{
    int index = 0;
    int *value;
    value = bpf_map_lookup_elem(&my_map, &index);
    if (!value)
    {
        return 1;
    }
    return 0;
}
char _license[] SEC("license") = "GPL";

loader, until point of failure
int main()
{
    int bfd;
    unsigned char buf[1024] = {};
    struct bpf_insn *insn;
    union bpf_attr attr = {};
    unsigned char log_buf[4096] = {};
    int pfd;
    int n;

    bfd = open("./test_bpf", O_RDONLY);
    if (bfd < 0)
    {
        printf("open eBPF program error: %s\n", strerror(errno));
        exit(-1);
    }

    n = read(bfd, buf, 1024);
    close(bfd);

    insn = (struct bpf_insn*)buf;
    attr.prog_type = BPF_PROG_TYPE_TRACEPOINT;
    attr.insns = (unsigned long)insn;
    attr.insn_cnt = n / sizeof(struct bpf_insn);
    attr.license = (unsigned long)"GPL";
    attr.log_size = sizeof(log_buf);
    attr.log_buf = (unsigned long)log_buf;
    attr.log_level = 1;

    pfd = syscall(SYS_bpf, BPF_PROG_LOAD, &attr, sizeof(attr));
    if (pfd < 0)
    {
        printf("bpf syscall error: %s\n", strerror(errno));
        printf("log_buf = %s\n", log_buf);
        exit(-1);
    }
...

llvm output
Disassembly of section tracepoint/skb/consume_skb:

0000000000000000 bpf_sys:
; {
       0:   b7 01 00 00 00 00 00 00 r1 = 0
;   int index = 0;
       1:   63 1a fc ff 00 00 00 00 *(u32 *)(r10 - 4) = r1
       2:   bf a2 00 00 00 00 00 00 r2 = r10
       3:   07 02 00 00 fc ff ff ff r2 += -4
;   value = bpf_map_lookup_elem(&my_map, &index);
       4:   18 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 r1 = 0 ll
       6:   85 00 00 00 01 00 00 00 call 1
       7:   bf 01 00 00 00 00 00 00 r1 = r0
       8:   b7 00 00 00 01 00 00 00 r0 = 1
;   if (!value)
       9:   15 01 01 00 00 00 00 00 if r1 == 0 goto +1 <LBB0_2>
      10:   b7 00 00 00 00 00 00 00 r0 = 0

0000000000000058 LBB0_2:
; }
      11:   95 00 00 00 00 00 00 00 exit

Error when loading
bpf syscall error: Permission denied
log_buf = 0: (b7) r1 = 0
1: (63) *(u32 *)(r10 -4) = r1
last_idx 1 first_idx 0
regs=2 stack=0 before 0: (b7) r1 = 0
2: (bf) r2 = r10
3: (07) r2 += -4
4: (18) r1 = 0x0
6: (85) call bpf_map_lookup_elem#1
R1 type=inv expected=map_ptr
processed 6 insns (limit 1000000) max_states_per_insn 0 total_states 0 peak_states 0 mark_read 0

Also, is there a better way to debug BPF error messages?

A: Issues
Parsing the bytecode
Your loader does not work, at least not directly on the object file compiled from your C code. It just reads from the file, does not parse for an ELF section where the bytecode would be contained. Apparently you're getting the verifier output for the correct eBPF bytecode, though; so I suspect you've been using it in a different way, or with some intermediate step.
Setting up the maps
With regards to your issue, your loader also misses the creation of a map and the ELF relocation of the FD for that map into the bytecode instructions, which would be why you get your error. Typically, when you load a program, several steps occur including:

*

*The loader program (often via libbpf) creates all eBPF maps needed by the eBPF program

*Alternatively, it reuses some existing maps. In both cases (existing or new maps), it retrieves a file descriptor for each map (e.g. via their pinned path for existing maps, or returned by the syscall when creating new maps).

*Then it inserts this file descriptor into the eBPF bytecode, as an argument to the helper functions used for map access.

*At last the loader program loads the updated bytecode into the kernel.

*The bytecode goes through the verifier, where the file descriptors are replaced with pointers to the map areas in the kernel memory space.

Your loader is not creating maps (or retrieving FDs for existing, compatible maps), and does not update the bytecode accordingly. So the eBPF program sent to the kernel doesn't say what map it tries to access: we just see, from the verifier logs, 4: (18) r1 = 0x0, where at this stage it should be a memory pointer, such as 4: (18) r1 = 0xffff8ca2c29e3200.
Workarounds
You can obviously extend your loader application to handle maps and ELF relocation. But here are a few other suggestions.
Adding new programs directly amongst the kernel samples is not always ideal. The build system for these samples is rather involved, and relies on a number of header inclusions that are not really standard outside of the kernel repository. On older versions it would also not rely on libbpf but would reimplement most of the loading components, although I think this has improved.
So I would suggest building outside of the kernel repository, if this is not what you have been doing already. In particular, if you're working with C, you should have a look at how libbpf can help handling (loading, attaching, etc.) eBPF programs and other objects.
One of the best starting point would also be libbpf-boostrap, which provides a framework with templates for building eBPF programs and corresponding user space applications very quickly. I would definitely recommend looking at it.
Alternatively, you should be able to load your program with e.g. bpftool prog load <object_file.o> /sys/fs/bpf/<some_path>, although you can't attach it to tracepoints with bpftool only.


text:
Q: How to build a tar archive using gradle on Windows without file owner information? I'm trying to build a tar archive from my project with gradle on Windows.
task buildTarball(dependsOn: filterResources, type: Tar) {
    from "${project.buildDir}/resources"
    destinationDir project.buildDir
    archiveName = project.ext.internetTarballName
    compression = Compression.GZIP
}

This works well, except that there are errors when unpacking the archive on an unix machine over an existing directory:
tar: config: Cannot utime: Permission denied
tar: Exiting with failure status due to previous errors

config is a directory inside the tarball. Invoking the unpack command with --no-overwrite-dir works.
Gradle uses my Windows user name as the owner of all files and directories in the generated archive. I suspect this is the cause of the error. How can I remove the owner information out of the tarball with gradle?

A: The root problem was not gradle, but the target environment. The config directory is owned by root, which forbids tar to overwrite creation, modification and access timestamps.
The message posted in the question above is not an error, though. Tar continues to unpack objects after this message. That message can be easily avoided by appending the --no-overwrite-dir switch to the tar -x command.


text:
Q: BeautifulSoup: How to get only one part of  output? I am trying to find the solution how to get only the price without text from the paragraph.
from bs4 import BeautifulSoup
import requests
headers = {"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36"}

p = requests.get(url = 'https://www.tia-mobiteli.hr/detaljan-prikaz.aspx?gid=11-appise_64wheu', headers = headers)
soup = BeautifulSoup(p.content,'lxml')
price = soup.find('div', class_='widget widget-info widget-price').p.text
price2 = price.strip()
print(price2)

My output is:
Naša najniža cijena za gotovinsko/virmansko plaćanje: 3.649,00 kn

I want to get only:
3.649,00 kn

Or if it is possible:
3649.00

A: The price is inside <b> tag:
import requests
from bs4 import BeautifulSoup

headers = {
    "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.131 Safari/537.36"
}

p = requests.get(
    url="https://www.tia-mobiteli.hr/detaljan-prikaz.aspx?gid=11-appise_64wheu",
    headers=headers,
)
soup = BeautifulSoup(p.content, "lxml")
price = soup.find("div", class_="widget widget-info widget-price").b.text
price = float(price.split()[0].replace(".", "").replace(",", "."))
print(price)

Prints:
3649.0

A: You can use parse module that acts like reverse format().
Usage:
import parse
...
float(parse.parse('Naša najniža cijena za gotovinsko/virmansko plaćanje: {} kn',price2)[0].replace('.','').replace(',','.'))


text:
Q: How to index array of pointers to arrays [queue]? I am trying program a queue with arrays in C++.
I used this approach https://stackoverflow.com/a/936709/7104310 as shown below.
My question: How can I index the arrays to fill them?
In a normal 2d-array it would be arr[3][2] for example. But I do not know how to do this with pointers. The question hat not been answered in the Solution upon.
Thank you!
#include <iostream>

#define MAX_SIZE 3

using namespace std;

// ary[i][j] is then rewritten as

//arr[rear*capacity + front]

// Class for queue
class msg_queue
{
    char **arr;     // array to store queue elements
    int capacity;   // maximum capacity of the queue
    int front;      // front points to front element in the queue (if any)
    int rear;       // rear points to last element in the queue
    int count;      // current size of the queue

public:
    msg_queue(int size = MAX_SIZE, int slot_length = MAX_SIZE);     // constructor

    void dequeue();
    void enqueue(char x);
    char peek();
    int size();
    bool isEmpty();
    bool isFull();
};

// Constructor to initialize queue
msg_queue::msg_queue(int size, int slot_length)
{
    arr = new char*[size];
    for (int i = 0; i < size; ++i) {
        arr[i] = new char[slot_length];
    }

    capacity = size;
    front = 0;
    rear = -1;
    count = 0;
}

// Utility function to remove front element from the queue
void msg_queue::dequeue()
{
    // check for queue underflow
    if (isEmpty())
    {
        cout << "UnderFlow\nProgram Terminated\n";
        exit(EXIT_FAILURE);
    }

    cout << "Removing " << arr[front] << '\n';

    front = (front + 1) % capacity;
    count--;
}

// Utility function to add an item to the queue
void msg_queue::enqueue(char item)
{
    // check for queue overflow
    if (isFull())
    {
        cout << "OverFlow\nProgram Terminated\n";
        exit(EXIT_FAILURE);
    }

    cout << "Inserting " << item << '\n';

    rear = (rear + 1) % capacity;
    arr[rear] = item;  //ERROR HERE
    count++;
}

// Utility function to return front element in the queue
char msg_queue::peek()
{
    if (isEmpty())
    {
        cout << "UnderFlow\nProgram Terminated\n";
        exit(EXIT_FAILURE);
    }
    return arr[front]; //ERROR HERE
}

A: Well, it's still arr[3][2].
Although arrays are not pointers, the way we use them is effectively using a pointer because of the way they work and the way their name decays.
x[y] is *(x+y), by definition.
That being said, I would recommend you drop the 2D dynamic allocation (which is poison for your cache) and create one big block of Width×Height chars instead. You can use a little bit of maths to provide 2D indexes over that data.
Also you forgot to free any of that memory. If you use a nice std::vector to implement my suggested 1D data scheme (or even if you hire a vector of vectors, but ew!) then it'll be destroyed for you. Of course if you could do that then you'd probably be using std::queue…


text:
Q: calling SCM via JAVA application Recently I am trying to write an java application to call SCM.exe to execute the code loading job. However, after I successfully execute the SCM load command via java, I found that I actually cannot really download the code (as using the command line, the password need to be entered after execute the SCM load command). May I know how can I enter this password just after I use the process to run the SCM in java? How can I get the output of the command line and enter something into the command line?
Thanks a million,
Eric

A: Since I don't know what exactly SCM.exe in your case is, I'm answering only what deals with the input/output redirection requirements in an abstract sense. I assume further that you are calling SCM.exe with whatever parameters it needs through System("...") and this is where you are unable pass any further input (stdin of the called process).
You need, instead, to be able to, upon receiving the request for password, pass it to the stdin of the other process, which is solved by using pipes in the classical sense (since you are presumably on Windows, YMMV). More generally, you are dealing with a very simple case of IPC.
In Java you may find an adequate solution by using ProcessBuilder [1] (never did myself, though -- i'd use things a lot simpler than java for this purpose, but I digress...).
An outline of a solution would be:

*

*call the process, having its input and output being handled as output/input streams from your caller java process.

*read the output of your process until you are queried the password

*write the password

*carry on as needed.

If you need further clarification you may need to give more details about your scenario.
[1] http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html

A: public class test {
    public static void main(String[] args){
    try {
        System.out.println("");
        String commands = "C:/swdtools/IBM/RAD8/scmtools/eclipse/scm.exe load -d C:/users/43793207/test -i test -r eric-repo";
        // load -d C:/users/43793207/test -i test -r eric-repo

        test test=new test();
        test.execCommand(commands);

    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void execCommand(String commands){
    //ProcessBuilder pb = new ProcessBuilder(Command);
    //pb.start();
     String line;

    try {
        //Process pp = Runtime.getRuntime().exec(commands);
        System.out.println(commands);
        Process process = new ProcessBuilder(commands).start();
        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);

        while ((line = br.readLine()) != null) {
            System.out.println(line);
                }
    } catch (IOException e) {
        e.printStackTrace();
    }
}


text:
Q: Easy circuit for "nested" triggering I need a trigger circuit that gives several high pulses for an "out_0". After 5-6 pulses from out_0, it then gives one high pulse for an "out_1".
I don't need any circuit that's large or has high component count... so 555 ICs in astable mode or microcontrollers are kind of a no, no...
I'm sure there's a special IC out there that only needs a single resistor and/or a capacitor to set the timings AND can do the triggering in a "looped" or "nested" way... and, if it's also very rare I could always order it online.
EDIT:
by a "single resistor/capacitor", i mean just one every nest.

A: Despite your "no MCU's" desire the obvious answer is a low pin-count example like a PIC10F or 12F.  Around 5sqmm of PCB space for a SOT23-6 case and an 0402 cap is all you would need.


text:
Q: proof of limit involving convergent sequence Let (a$_n$)$_{n \in N}$  be a convergent sequence in R with the limit a $\in$ R.
Furthermore, let  y$_n$ = $\frac 1n$$\sum_{i=1}^n$a$_n$.
Show that $\lim \limits_{n \to \infty}$ y$_n$ = a.
--
I thought that $\lim \limits_{n \to \infty}$ y$_n$ = 0 because $\lim \limits_{n \to \infty}$ $\frac 1n$ = 0, and I could apply the formulae for convergent sequences, but I guess I am wrong.

A: Take any $\varepsilon >0$ and let $k_0$ be such that for all $k\geqslant k_0$ we have $$|a_k -g|\leqslant \varepsilon$$
then
$$\left|\frac{1}{n} \sum_{k=1}^n a_k -g \right|\leqslant \frac{1}{n}\sum_{j=1}^{k_0 -1} |a_j -g| + \frac{1}{n}\sum_{j=k_0}^{n} |a_j -g|\leqslant \frac{1}{n}\sum_{j=1}^{k_0 -1} |a_j -g| +\frac{n-k_0 +1}{n} \varepsilon \leq 2\varepsilon$$
for sufficiently large $n.$


text:
Q: Create Hierarchy Recursive using multiple table SQL Server I want to make a query that shows employee below manager.
using 5 tables on SQL.
Here is the example of my databases.
Department Table
id         dept         parent
1          HR
2          Financial      1
3          Research       1
4          Loans          2
5          Marketing      3

Role Table
id         role         parent
1          Commissioner
2          Director       1
3          Manager        2
4          Supervisor     3
5          Staff          4

deptrole Table
id         iddept       idrole
1            1            1
2            1            2
3            1            3
4            1            4
5            1            5

Biography Table
id         name         regnumber
1          Bob             N1
2          John            N2
3          Roxy            N3
4          Ian             N4
5          Will            N5

Employee Table
id         IdBio       deptrole
1            1            3
2            2            1
3            3            2
4            4            5
5            5            4

when i input id on Query (WHERE EmpId = 1),its shows who's the employee below id 1,so it would be EmpId 5 and then 4.and when EmpId = 2,the child is EmpId 3-1-5-4.
how did i do that ?

A: Not sure to have understood the whole problem but you can try this.
Declare @empid as int;
SET @empid = 1;

With A as
(
    Select id as Subord_role
    from role
    WHERE role.parent = (Select deptrole.idrole
                            FROM Employee
                                INNER JOIN deptrole ON deptrole.id = Employee.id
                            WHERE Employee.id = @empid)
    UNION ALL

    Select Role.id
    from deptrole
        INNER JOIN Role ON deptrole.idrole = Role.id
        INNER JOIN A ON A.Subord_role = Role.parent
    Where deptrole.iddept = (Select deptrole.iddept
                            FROM Employee
                                INNER JOIN deptrole ON deptrole.id = Employee.id
                            WHERE Employee.id = @empid)
)

Select Employee.id
FROM Employee
    INNER JOIN deptrole ON deptrole.id = Employee.id
    INNER JOIN Role ON role.id = deptrole.idrole
    INNER JOIN A ON A.Subord_role = Role.id


text:
Q: search function in Laravel I'm trying to make a search function in laravel. But it is showing:

"undefined variable:q"

though I defined the variable. I am not getting any clue where I made mistake. I need help on that.
Here is my controller code:
public function postSearch(Request $request)
{
         $q = $request->input('q');
    $products = DB::table('products')
                        ->join('product_categories', function ($join) {
                            $join->on('category_id', '=', 'product_categories.id')
                                ->where('name','LIKE','%'.$q.'%')->orWhere('category_name','LIKE','%'.$q.'%');
                            })->get();
    if(count($products) > 0)
        return view('search')->withDetails($products)->withQuery ( $q );
    else return view ('search')->withMessage('No Details found. Try to search again !');
}

Here is my route:
Route::post('/search',[
   'uses' => 'HomeController@postSearch',
   'as' => 'search'
]);`

here is my view form:
<form action="{{ route('search') }}" method="post" role="search">
    {{ csrf_field() }}

        <input type="text" class="form-control" name="q" placeholder="Search    products">

            <button type="submit" class="btn-btn-primary">Submit</button>

</form>

A: Change the following code:
->join('product_categories', function ($join) {

to this code:
->join('product_categories', function ($join) use ($q) {

Note: you cannot use external variable inside it before you declare the variable to pass it.


text:
Q: Convert a torchscript model into Core ML I am trying to convert a Detectron 2 model into Core ML. I have scripted it and now I have a model of type 'torch.jit._script.RecursiveScriptModule'. If I try and convert it into Core ML using this code:
mlmodel = ct.converters.convert(
  torchscipt_model,
  inputs=[ct.TensorType(shape=(1, 3, 64, 64))],
)

I get the following error:

RuntimeError: Unknown type bool encountered in graph lowering. This
type is not supported in ONNX export.

I scripted the model using the following code (as illustrated in Detectron's documentation)
model = build_model(cfg)
model.eval()

fields = {"pred_boxes": Boxes, "scores": torch.Tensor, "pred_classes": torch.Tensor, "pred_masks": torch.Tensor, "proposal_boxes": Boxes, "objectness_logits": torch.Tensor}

torchscipt_model = scripting_with_instances(model, fields)

Do you know any other way to convert my Detectron2 model into Core ML?
Thank you so much for your help!


text:
Q: Bitbucket repository creations by api after reading the doc https://developer.atlassian.com/bitbucket/api/2/reference/resource/repositories .
Seems this API is for reading the info of existing repos.
Is there any API for repo creation?

A: Check out the POST of repo_slug
/2.0/repositories/{workspace}/{repo_slug}

With:

*

*repo_slug   string  : This can either be the repository slug or the UUID of the repository, surrounded by curly-braces, for example: {repository UUID}.

*workspace   string  : This can either be the workspace ID (slug) or the workspace UUID surrounded by curly-braces, for example: {workspace UUID}.

Creates a new repository.
Note: In order to set the project for the newly created repository, pass in either the project key or the project UUID as part of the request body as shown in the examples below:

$ curl -X POST -H "Content-Type: application/json" -d '{
    "scm": "git",
    "project": {
        "key": "MARS"
    }
}' https://api.bitbucket.org/2.0/repositories/teamsinspace/hablanding

or
$ curl -X POST -H "Content-Type: application/json" -d '{
    "scm": "git",
    "project": {
        "key": "{ba516952-992a-4c2d-acbd-17d502922f96}"
    }
}' https://api.bitbucket.org/2.0/repositories/teamsinspace/hablanding

The project must be assigned for all repositories. If the project is not provided, the repository is automatically assigned to the oldest project in the workspace.
Note: In the examples above, the workspace ID teamsinspace, and/or the repository name hablanding can be replaced by UUIDs.

For BitBucket server, that would be here, as illustrated in this gist:
/rest/api/1.0/projects/{projectKey}/repos

But V1 API was deprecated in 2018.


text:
Q: Postgres 11 docker container fails to start: Segmentation fault I am running a Postgres 11 instance in a docker-container started with docker-compose together with Wiki.js on a raspi.
A longer time ago, I pulled a new image which resulted in termination by signal 11: segmentation fault.
Doing some research revealed that it was related to a dependency of the alpine image to libseccomp.
I tried updating both docker and libseccomp these days, but the issue stayed,
so I guess the database is somehow corrupted now. Starting the container without using the existing db-files works fine, which support this guess.
Is there any way to restore the db without any backups?
It is not a critical system, but it is a rather academical question since I am wondering why the db is so susceptible at all.
Log:
db_1    | 2022-04-17 11:47:51.986 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
db_1    | 2022-04-17 11:47:51.986 UTC [1] LOG:  listening on IPv6 address "::", port 5432
db_1    | 2022-04-17 11:47:52.076 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
db_1    | 2022-04-17 11:48:17.075 UTC [1] LOG:  startup process (PID 20) was terminated by signal 11
db_1    | 2022-04-17 11:48:17.075 UTC [1] LOG:  aborting startup due to startup process failure
db_1    | 2022-04-17 11:48:17.160 UTC [1] LOG:  database system is shut down
db_1    | 2022-04-17 11:48:19.287 UTC [1] LOG:  listening on IPv4 address "0.0.0.0", port 5432
db_1    | 2022-04-17 11:48:19.288 UTC [1] LOG:  listening on IPv6 address "::", port 5432
db_1    | 2022-04-17 11:48:19.300 UTC [1] LOG:  listening on Unix socket "/var/run/postgresql/.s.PGSQL.5432"
db_1    | 2022-04-17 11:48:22.096 UTC [21] FATAL:  the database system is starting up
db_1    | 2022-04-17 11:48:25.112 UTC [22] FATAL:  the database system is starting up
db_1    | 2022-04-17 11:48:28.119 UTC [23] FATAL:  the database system is starting up

Docker version 20.10.14, build a224086
Except of the docker-compose.yml:
version: "3"
services:
        db:
                image: postgres:11.2-alpine
                environment:
                        POSTGRES_DB: wiki
                        POSTGRES_PASSWORD: ****
                        POSTGRES_USER: wikijs
                restart: unless-stopped
                volumes:
                        - ./db_data:/var/lib/postgresql/data
                networks:
                        - net

Libseccomp version:
libseccomp2/stable,now 2.5.1-1+rpi1+deb11u1 armhf [installed]
OS:
Linux raspberrypi 5.15.32-v8+ #1538 SMP PREEMPT Thu Mar 31 19:40:39 BST 2022 aarch64 GNU/Linux
Any help to debug / restore is appreciated.


text:
Q: Loading WCF RIA Services Query results to an ObservableCollection In my Silverlight app, after creating  ADO.NET Entity Data Model and WCF RIA Services Domain Service Class, in a corresponding ProductService class I have a query operation that returns a collection of Product entities to the client, as follows:
public IQueryable<Product> GetProducts()
{
   return this.ObjectContext.Products;
}

Now I'm trying to read it in the client Silverlight app and load results to an  ObservableCollection:
ProductContext pcontext = new ProductContext();
ObservableCollection<Prod> prAvs = pcontext.GetProductsQuery();

But getting an error:
Cannot implicitly convert type    System.ServiceModel.DomainServices.Client.EntityQuery<MyTestApp.Web.Product>
to System.Collections.ObjectModel.ObservableCollection<MyTestApp.Prod>
How could I fix that issue?

A: First problem:
You should be using the client-side Products class generated for you by RIA services, not another class you define yourself.
e.g you should have a collection of MyTestApp.Web.Product, not of MyTestApp.Prod objects.
You will find the generated domain context in a hidden Generated_Code folder in your client project. Within that will be a MyTestApp.Web.g.cs file containing the client side context and any data objects (like MyTestApp.Web.Product).
Second issue:
You can't just cast a query to a collection.
You need to use the query to load an entity change-set instead.
var loadOperation = pcontext.Load(pcontext.GetProductsQuery());

The result (when the load completes) is an entity collection in the returned loadOperation object. You can use the entity collection immediately, but it is initially empty.


text:
Q: Why isn't my attempted solution working? When I run the code in the console, the browser just stops working (am assuming stack overflow).
I've come up with several different algorithms for solving this problem, but I thought this one would not cause any SOs.
The problem:

The sequence of triangle numbers is generated by adding the natural numbers. So the 7th triangle number would be 1 + 2 + 3 + 4 + 5 + 6 + 7 = 28. The first ten terms would be:
1, 3, 6, 10, 15, 21, 28, 36, 45, 55, ...
Let us list the factors of the first seven triangle numbers:
1: 1
3: 1 3
6: 1,2,3,6
10: 1,2,5,10
15: 1,3,5,15
21: 1,3,7,21
28: 1,2,4,7,14,28
We can see that 28 is the first triangle number to have over five divisors.
What is the value of the first triangle number to have over five hundred divisors?

Failing solution:
function divisors(n){
    var counter = 0;
    var triangle = 3;
    var triangle_add = 2;
    while (counter < n){
        for (var i = 1; i = triangle; i++){
            if (triangle % i === 0){
                counter++;
            }
        };
        if (counter < n){
            triangle_add++;
            triangle = triangle + triangle_add;
            counter = 0;
        };
    };
    return triangle;
};

console.log(divisors(501));

A: Your solution is not working because, most probably, it is very slow. This problem can be solved much faster by the following method:

*

*Find all the prime numbers smaller than some N (put, for example, N=100'000) using Sieve of Eratosthenes. It is quite fast.

*As we know from elementary math each number can be written in the form X=p1^i1*p2^i2*...*pn^in where pj is prime number and ij is the power of corresponding prime number. The number of divisors of X is equal to (i1+1)*(i2+1)*...*(in+1) since that many different ways we can form a number which will be divisor of X. Having an array of prime numbers the number of divisors for X can be calculated quite fast (the code still has place to be optimized):
int divisorCount(long long X)
{
    int c = 1;
    for (int i = 0; PRIMES[i] <= X; ++i)
    {
        int pr = PRIMES[i];
        if (X % pr == 0)
        {
            int p = 1;
            long long r = X;
            while (r % pr == 0)
            {
                r = r / pr;
                ++p;
            }
            c *= p;
        }
    }
    return c;
}

*Iterate through all triangle numbers and count divisor numbers for them using the above function. The i-th triangle number is i * (i + 1) / 2, so no need to keep a variable, increment it and add it each time.


text:
Q: Why doesn't my rock, paper, scissors give the correct result? The following code is my implementation of rock, paper, scissors. However, the problem is that the moves of the user and computer are not synchronized.
Here's what happened when I executed it:
First there's a choice of the computer (it shows 'paper').
Then when I chose my move (rock) it displayed its move (rock).
This goes for second time (paper v/s rock).
Then at the third time when I gave my move (scissors) and it gave its move (paper) the result is displayed as 'tied', but I should have won.
I can't understand how the code does this as I had implemented the logic using c++ without the OpenGL part and it worked fine.
Can someone see the problem in the code?
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<GL/glut.h>

int a; //GLOBAL VARIABLE TO CHECK USER'S CHOICE IN menu()
int n=0,sa,sb; //n IS NO. OF MOVES WE WANT- WE HAVE 3 MOVES IN THIS PROGRAM. sa & sb ARE THE SCORES OF USER AND COMPUTER RESPECTIVELY
char ch;

int comp_move();//THIS CALCULATES COMPUTER'S MOVE
void check(int,int);//CHECKS WHO HAS WON/LOST IN ONE PARTICULAR MOVE

int comp_move()
{
    int c=0;
    c=rand()%3;
    if(c==1)drawrock(newrock);
    if(c==2)drawpaper(newpaper);
    if(c==3)drawscissor(newscissor);
    return c;
}

void check(int b)
{
    if(a==1) //rock is player's selection
    {
        if(b==2)sb++;
        if(b==3)sa++;
    }
    else if(a==2) //paper is player's selection
    {
        if(b==1) sa++;
        if(b==3) sb++;
    }
    else //scissor is player's selection
    {
        if(b==1)sb++;
        if(b==2)sa++;
    }
}

void menu(int id) //THE MENU FUNCTION
{
    switch(id)
    {
    case 1: a=1;n++;
            break;
    case 2: a=2;n++;
            break;
    case 3: a=3;n++;
            break;
    }
    glutPostRedisplay();
}

void display()
{
    //glClearColor(1.0,1.0,1.0,1.0);
    glColor3f(1.0,0.0,0.0);
glClear(GL_COLOR_BUFFER_BIT);

    if(a==1)drawrock(rock);
    if(a==2)drawpaper(paper);
    if (a==3)drawscissor(scissor);

    //for(int i=1;i<=n;i++)
    int b=comp_move();
    check(b);

    if(n==3)//3 rounds
    {
        if(sa>sb)
            sprint(150,450,a);//prints win
        else if(sa==sb)
            sprint(150,450,a);//prints loss
        else
            sprint(150,450,a);//prints tied
    }

    if(n>4) exit(0); //here i want to see the computer's third move
    glFlush();
}

void MYINIT()
{
    glClearColor(1.0,1.0,1.0,1.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluOrtho2D(0,500,0,500);
    glMatrixMode(GL_MODELVIEW);
}

int main()
{
    glutInitWindowSize(500,500);
    glutInitDisplayMode(GLUT_SINGLE|GLUT_RGB);
    glutCreateWindow("rock, paper, scissors");
    glutCreateMenu(menu);
    glutAddMenuEntry("Rock",1);
    glutAddMenuEntry("Paper",2);
    glutAddMenuEntry("Scissors",3);
    glutAttachMenu(GLUT_RIGHT_BUTTON);
    MYINIT();
    glutDisplayFunc(display);
    glutMainLoop();
}

A: The line
c=rand()%3;

will yeld a value between 0 and 2, not 1 and 3. Replace it with:
c = 1 + (rand()%3);