text:
Q: CUDA kernel strange behavior, generating random values I'm trying to simulate a spring-mass system with CUDA. Below is the kernel that updates the position of the particles:
__global__ void timestep(float3 *pos, float3 *pos_antiga, float3 *aceleracao, int numParticulas) {

    int index = threadIdx.x + blockIdx.x * blockDim.x;

    if(index > (numParticulas - 1))
        return;
t
    float3 temp = pos[index];

    pos[index].x = pos[index].x + (pos[index].x - pos_antiga[index].x) * (1.0f - DAMPING) + aceleracao[index].x * TIMESTEP;
    pos[index].y = pos[index].y + (pos[index].y - pos_antiga[index].y) * (1.0f - DAMPING) + aceleracao[index].y * TIMESTEP;
    pos[index].z = pos[index].z + (pos[index].z - pos_antiga[index].z) * (1.0f - DAMPING) + aceleracao[index].z * TIMESTEP;

    pos_antiga[index] = temp;

}

The pos represents the 3D vector of the actual position, pos_antiga is the position in the previous time step, the DAMPING is 0.01 and TIMESTEP is 0.25. I'm using Verlet integration. In a system without any force, aceleracao is zero, so the pos and pos_antigo are the same before and after the kernel calls.
However, after the first iteration, CUDA returns crazy values for some axes, like 1.QNAN and -1.6241e+016. I think it's something related to block and thread sizes. The kernel call is below:
timestep<<<16, 16>>>(pos_d, pos_antiga_d, aceleracao_d, numParticulas);

So, what am I missing?
EDIT: Below is the caller code:
void timestepGPU(vector<Particula> *p) {

// vector<Particula> has all the particles of the system.

      // CPU
    float *pos;
    float *pos_antiga;
    float *aceleracao;

    // GPU
    float *pos_d;
    float *pos_antiga_d;
    float *aceleracao_d;

    // Number of particles
    int numParticulas = p->size();

    // Init
    pos = new float[numParticulas * 3];
    pos_antiga = new float[numParticulas * 3];
    aceleracao = new float[numParticulas * 3];

    // Transfering the values from the class to a plain vector
    vector<Particula>::iterator p_tmp;
    int i = 0;
    for(p_tmp = p->begin(); p_tmp != p->end(); p_tmp++)
    {
        pos[i] = (*p_tmp).getPos().f[0];
        pos[i + 1] = (*p_tmp).getPos().f[1];
        pos[i + 2] = (*p_tmp).getPos().f[2];

        pos_antiga[i] = (*p_tmp).getPosAntiga().f[0];
        pos_antiga[i + 1] = (*p_tmp).getPosAntiga().f[1];
        pos_antiga[i + 2] = (*p_tmp).getPosAntiga().f[2];

        aceleracao[i] = (*p_tmp).getAceleracao().f[0];
        aceleracao[i + 1] = (*p_tmp).getAceleracao().f[1];
        aceleracao[i + 2] = (*p_tmp).getAceleracao().f[2];

        i += 3;
    }

    // Here, I print the particle data BEFORE moving it to GPU
      cout << "PRINT PARTICLE DATA" << endl;
    for(i = 0; i < numParticulas * 3; i += 3) {
        cout << i/3 << " - Pos: " << pos[i] << " " << pos[i + 1] << " " << pos[i + 2] << " | Pos Ant: " << pos_antiga[i] << " " << pos_antiga[i + 1] << " " << pos_antiga[i + 2] << " | Acel: " << aceleracao[i] << " " << aceleracao[i + 1] << " " << aceleracao[i + 2] << endl;
    }
    cout << "END" << endl;

    // GPU
    ErroCUDA(cudaMalloc((void**) &pos_d, numParticulas * 3 * sizeof(float)));
    ErroCUDA(cudaMalloc((void**) &pos_antiga_d, numParticulas * 3 * sizeof(float)));
    ErroCUDA(cudaMalloc((void**) &aceleracao_d, numParticulas * 3 * sizeof(float)));

    // Moving data
    ErroCUDA(cudaMemcpy(pos_d, pos, numParticulas * 3 * sizeof(float), cudaMemcpyHostToDevice));
    ErroCUDA(cudaMemcpy(pos_antiga_d, pos_antiga, numParticulas * 3 * sizeof(float), cudaMemcpyHostToDevice));
    ErroCUDA(cudaMemcpy(aceleracao_d, aceleracao, numParticulas * sizeof(float), cudaMemcpyHostToDevice));

    // Setting number of blocks and threads per block
    unsigned int numThreads, numBlocos;
    calcularGrid(numParticulas, 64, numBlocos, numThreads);
    //cout << numBlocos << "----------" << numThreads << endl;

    // Kernel
    timestep<<<numBlocos, numThreads>>>((float3 *) pos_d, (float3 *) pos_antiga_d, (float3 *) aceleracao_d, numParticulas);
    ErroCUDA(cudaPeekAtLastError());
    cudaDeviceSynchronize();

    // Moving data back to the CPU
    ErroCUDA(cudaMemcpy(pos, pos_d, numParticulas * 3 * sizeof(float), cudaMemcpyDeviceToHost));
    ErroCUDA(cudaMemcpy(pos_antiga, pos_antiga_d, numParticulas * 3 * sizeof(float), cudaMemcpyDeviceToHost));

      // Printing the particles' data AFTER Kernel call. At my GT 4xx, close to the 48th particle, it starts to show crazy values
    cout << "PARTICLE DATA" << endl;
    for(i = 0; i < numParticulas * 3; i += 3) {
        cout << i/3 << " - Pos: " << pos[i] << " " << pos[i + 1] << " " << pos[i + 2] << " | Pos Ant: " << pos_antiga[i] << " " << pos_antiga[i + 1] << " " << pos_antiga[i + 2] << " | Acel: " << aceleracao[i] << " " << aceleracao[i + 1] << " " << aceleracao[i + 2] << endl;
    }
    cout << "END" << endl;

    system("pause");

    i = 0;
    for(p_tmp = p->begin(); p_tmp != p->end(); p_tmp++)
    {
        if((*p_tmp).getMovel())
        {
            (*p_tmp).setPos(Vetor(pos[i], pos[i + 1], pos[i + 2]));
            (*p_tmp).setPosAntiga(Vetor(pos_antiga[i], pos_antiga[i + 1], pos_antiga[i + 2]));
(*p_tmp).setAceleracao(Vetor(0, 0, 0));
        }

        i += 3;
    }

    ErroCUDA(cudaFree(pos_d));
    ErroCUDA(cudaFree(pos_antiga_d));
    ErroCUDA(cudaFree(aceleracao_d));

    free(pos);
    free(pos_antiga);
    free(aceleracao);
}

In my example, attribute p has 100 items (10 x 10 particles). It's a mesh starting at (0, 0, 0) and goes to (20, 20, 20) in 3D space.
Thanks again everyone for the help!

A: I think your problem is in this line..
 ErroCUDA(cudaMemcpy(aceleracao_d, aceleracao, numParticulas * sizeof(float), cudaMemcpyHostToDevice));

should be ..
  ErroCUDA(cudaMemcpy(aceleracao_d, aceleracao, numParticulas * 3 *sizeof(float), cudaMemcpyHostToDevice));


text:
Q: VSTO Outlook 2013 third party dll not being found I am trying to add third party lib to my Outlook 2013 adding written in C#. It consists from 2 components: .Net wrapper and C++ dll itself.
I have referenced .net wrapper in the adding project and added C++ lib as a copy on build resource.
Apparently, Office runtime puts every .Net lib referenced by a plugin in a separate folder excluding C++ lib as it not referenced. And plugin fails to locate C++ lib because it should be in a same folder with the executing dll.
Sample plugin's dll location :
C:\Users\UserName\AppData\Local\assembly\dl3\TMGBBYEC.3JC\QE21JQR6.YRW\4a3206fe\4acfc661_ccc6cf01\SomeLibName.dll

Any ideas how to fix this?

A: Try something like the following to figure out the dll location.
string codebase = Assembly.GetExecutingAssembly().CodeBase;
var vUri = new UriBuilder(codebase);
string vPath = Uri.UnescapeDataString(vUri.Path + vUri.Fragment);
string directory = Path.GetDirectoryName(vPath);
if (!string.IsNullOrEmpty(vUri.Host)) directory = @"\\" + vUri.Host + directory;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Idiom Meaning "Ready to Correct One's Mistake" I'm looking for a concise way to describe this situation:

Person A compliments B's team at a competition. But B does not respond to this compliment gracefully, even though it means a lot to him. B senses that doing this has hurt A, but pride or shyness get in the way of him clearing the air with A about this for a while. When B works up what's needed to talk to A, unforeseen circumstances change B's plans and he loses touch with A. Years pass, but B continues to feel an urge to fix his mistake. B does not actively seek to fix it (aside from learning from it), but if the opportunity to do so presents itself he has told himself to take it.

One idiom I've considered is turning over a new leaf. But this phrase seems better for a personality overhaul than for repairing one mistake.
Is there a word/idiom/phrase (WIP) to describe a person who would leap if given the chance to correct a specific mistake he made?
Edit: I have received some great answers, but I've realized I have one more condition I'm looking for: I'd prefer a casual/conversational WIP. Thanks!

A: He wants to "atone" for past behavior
Definition of "atone" from Google

Verb
Make amends or reparation: "he was being helpful, to atone for his past mistakes".
Synonyms
expiate - redeem

EDIT:
Another idiomatic alternative is "to make amends":
From Merriam-Webster Online Dictionary:

Make amends: compensation for a loss or injury : recompense
Origin of AMENDS
Middle English amendes, from Anglo-French, plural of amende
reparation, from amender First Known Use: 14th century

Example - step 8 from the 12 steps in a 12-step program:
8. Make a list of all persons we had harmed, and became willing to make amends to them all.

A: Not quite sure if this is what you're looking for, but the word "repentant" is the first that comes to mind. Other possibilities for single words might be "contrite", "penitent", "rueful", "compunctious" or simply "regretful". Not really sure about phrases or idioms, though. Hope I've been at least some help!


text:
Q: Why to build own CMS? On my first job interview, I was asked why did I build my own CMS? Why not to use one of existing CMS, Wordpress, Joomla, Drupal...? At first, I was stunned. I couldn't immediately recall all of my reasons for building my own CMS, but this was definitely one of the main reasons: It's my code and if I want to change something in that CMS (which I often have to do, because each website I build needs CMS with different functions) it's not a big problem. For some time I've been using Wordpress and one of the main things that distracted me from using it was discovering bugs in code that wasn't written by me and this bugs were often, especially if I made some changes to CMS or added a plugin...
Here, I can find these 8 reasons why NOT to build own CMS:

*

*It won't meet users' needs

*It's too much work

*It won't be a standard solution

*It won't be extendible fast enough

*It won't be tested well enough

*It won't be easily changeable

*It won't add any value

*Create content, not functionality
Quote from the same page:

So the main question to ask yourself
  is: 'Why am I really trying to
  re-solve a problem that has already
  been solved before?'

Well, I definitely agree that it's hard to invent CMS that hasn't been already invented, but on other hand, I think every CMS is (or should be) individual... it maybe won't have  a million of functions, it will have 3 functions but their usage will be clear (to a user) and do all that one site needs to have. I think also that it is not good to give to a client a CMS with a lot of functions that are never used and it looks probably more professional when website and CMS together look like one product.
I would also like to comment some quote parts:
 "It's too much work" - I agree, but when using existing CMS and customizing it to website needs and can sometimes be very hard job or mission impossible.
"It won't be easily changeable" - I disagree with this one.
What is your opinion on this one, why did you develop or didn't develop your own CMS?
Ile

A: I've found it works when the context of the project is larger than just a 'content site'.  I've worked on a number of real estate sites where the bulk of the content is coming in from data feeds, or already existing in databases that have had their structure set up long before you were involved.  Really, we only had a handful of BS 'content' pages that made up the site that were rarely updated.  What they really needed was a simple interface to data entry.  It was far easier to build some one off components than try and shoehorn an existing system on top of an out of the box CMS.
Like others mentioned though, you must consider overall requirements.  Is there workflow involved?  Dynamic navigation?  Then I'd start leaning more towards out of the box CMS's, but many times people say they need a CMS, when they really just need a WYSIWIG interface to a database.  But sometimes not...

A: It seems to me that the biggest reason NOT to build your own CMS (besides security issues) is lack of support and upgrade path. I consider it a disservice to clients to put them on a custom CMS and then have to rely on you only support and updates. Even worse is having them pay for the development of the custom CMS - they are paying you to reinvent the wheel no matter how simple the site requirements are.
There are plenty of CMS options out there that will allow you to add your own custom extensions if your requirements are beyond what is built in.
The best reason (possibly only) to build a custom CMS is to learn a language well. Building a CMS is a great way to learn web development, but it's not a great way to service your clients.

A: As a team leader that is always being pushed to do more with less, I too ask the question "why would you write your own?" There are more CMS packages out there than there are programming languages and I find it difficult to believe that you cannot find one that meets most (if not all) customer, business and cost requirements.
If you find that code changes are needed, opt for an open source solution, make your changes and share as needed or desired.
I do know that many times a CMS systems is NOT what is needed. Many customers need a Content Editing System. What I mean is that someone technical puts a site in place and the customer adds/edits/removes pages. The pages are already well designed and formatted. In these cases, I can see where it may be quicker to design & implement something from scratch rather than chopping down a CMS with access rights or removing/hiding functionality.

A: Unless you're building one for the experience, there's only one real reason for building your own: It's cheaper and/or easier than using one on the market that meets your requirements.

A: This is an interesting question that applies to most development, not just when building a CMS.
In general, I would say that it's a bad idea to reinvent the wheel (and most of your 8 arguments are correct in most cases), but there are exceptions. The first one that comes to mind is one from Joel Spolsky, In Defense of Not-Invented-Here Syndrome:

If it's a core business function -- do
  it yourself, no matter what.

The point is, if you're making your money directly from building content management systems, you should not take one from someone else and tweak it until it fits you. You'd rather be in full control over your own product.
Edit:
Also, don't forget that the urge to reinvent things stems (among other things) from a fundamental law of programming:

It's easier to write code than it is to read it

This does not mean that we should take the road that appears to be easier but it explains why we fall for it. Take the challenge and actually read some code, rather than write it, from time to time.

A: I would build a CMS because it can be fun and a great learning experience.
However, any open source CMS can be customized to any client's need. The biggest problem is that you have to understand how that CMS works in order to be able to change it well.
Either way you would be faced with quite a big task, but I must agree with those who say that you shouldn't start from scratch (unless you are doing it to learn some new technology) exactly for the reasons stated in your question... As they say, don't reinvent the wheel unless you want to learn about wheels.


text:
Q: ActiveRecord relation one to one with belongs to rails Consider the following case. I want to restrict users to have at most one address, so my goal is to have at most one foreign key user_id in the address table set.
User has one address, which reflects the respective models :
class User < ActiveRecord::Base
  has_one :address, dependent: :destroy
end
class Address < ActiveRecord::Base
  belongs_to :user
  validates :user, presence: true
  validate :user_association

  def user_association
    unless Address.where(user_id: user.id).count == 0
      errors.add(:user_id, 'Only one address per user')
    end
  end
end

I'm creating address from the User model, here is that bit (first way):
def create_address_relation
    a = Address.create(address_type: @type.to_s, user_id: id)
    self.address = a
end

Second way :
def create_address_relation
    create_address(address_type: @type.to_s)
end

First way of creating address relation (User has no address relation):

*

*Invoke create_address_relation on user instance. The address relation gets created, great!

*Invoke create_address_relation on user instance which already has address relation. Another address gets created, not so great! I wonder what am I doing wrong with validations

Second way of creating address relation (User has no address relation):

*

*Invoke create_address_relation on user instance. The address relation gets created, great!

*Invoke create_address_relation on user instance which already has address relation. Here is the weird bit, the current address deleted_at field gets set to true. And now the user doesn't have address relation.

What am I doing wrong here? And what is the right way to ensure that there is at most one user per address?
Update:
I can add a unique index on user_id in the addresses table or I can check manually in the code if the address exists don't create another address record.
It's not as nice and clean as validations, so I'd prefer that solution, but for now I got temp solution in place.


text:
Q: Webpack 5 using UMD dependencies instead of ESM after upgrade I'm upgrading a huge angular application to Webpack 5 (coming from v4. No ng-cli). In the previous version, webpack was using the esm versions of dependencies, and now it is using the UMD version.
Since it is using the UMD version, it fails with following error:
Error: Error on worker #1: Error: Failed to find exported name of node (MyComponentHere = /** @class */ (function () {...

Any ideas what could be causing this?
Here is my tsconfig:
{
    "compilerOptions": {
        "target": "es5",
        "module": "esnext",
        "moduleResolution": "node",
        "sourceMap": true,
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true,
        "esModuleInterop": true,
        "importHelpers": true,
        "lib": [
            "es2017",
            "dom"
        ],
        "noImplicitAny": true,
        "noImplicitThis": true,
        "noImplicitReturns": true,
        "noUnusedParameters": true,
        "noUnusedLocals": true,
        "suppressImplicitAnyIndexErrors": true,
        "typeRoots": [
            "typings",
            "node_modules/@types/"
        ],
        "baseUrl": ".",
        "paths": {
            "@angular/*": ["./node_modules/@angular/*"],
        }
    },
    "compileOnSave": false,
    "exclude": [
        "node_modules/*",
        "**/*.ngfactory.ts"
    ],
    "angularCompilerOptions": {
        "enableIvy": false,
    }
}


text:
Q: A 2000 ish Chinese show about a kid's house who gets struck by lighting due to playing games late at night and gets transported in the game I remember watching about it about a long time ago.
The beginning was a kid playing some kind of game on his computer. His parents came to his room and told him to turn it off and go to sleep. He then fakes falling asleep and going back playing his game. Lightning strikes his house and he wakes in a desert wasteland setting.
He sees one of the character in the game defending some kind of fort and he somehow teaching him an ult. The people attacking were bootleg driodekas(I am pretty sure.) He somehow meets another character from the game defending something.
There was a helicopter base along with a big group of helicopter transformers. There was also a different kind of vehicle mech injured in there. The base falls somehow. I am pretty sure there was a mech group in a snowy biome. (I forgot the middle part)
The end of the season was them using pair ults to attempt to destroy the bosses. I am pretty sure there was a girl villain that gave the boss a strategy to switch locations so the pair ults don't do as much damage.
Characters
There were 6-8 good guys

*

*1 red car use some kind of moonlight ult

*1 blue car with (snow attack?)First pair

*1 bulldozer who can smack ground and a giant boulder pops up

*(Forgot his partner)

*1 (apache?) helicopter who uses his rotors as blades and some kind of twister ult

*Some kind of snow mech?(Not confident with this.)

*I forgot the last 2 guys.
Also was pretty sure the boy could combine with one mecha to perform an ult in the beginning of the show.

There were (I am pretty sure) 3-5 bad guys.

*

*One was a boss driodeka(Pretty sure) and rolled into a ball to use a bouncing ult

*One was a flying boss

*One was a (gorrila boss?) He was slow but hits hard

*(Forgot one)
And there was the girl villain

I am pretty sure it was this cartoon they were talking about in this other question.

A: I think " 洛洛历险记" is the show you are looking for.


text:
Q: Trying To Get Jekyll To Render Markdown in my Posts My files in my _posts folder end in .markdown (also tried .md) yet when they are processed they are displayed as html files and the markdown syntax is not processed.
I am sure I am doing something silly wrong but can't figure it out. I looked through example Jekyll blog and their markdown is rendering fine but I can't seem to see what my error is.
This SO post I tried but using {{ content }} rather than {{ page.content }} didn't seem to make a difference. My markdown in my post files still does not get converted and things like link or link just show up in the generated html.
Any help would be greatly appreciated.

A: If your posts are not processed by jekyll build or jekyll serve, you may have forgotten to add a front matter like :
---
title:  "The title!"
date:   2015-09-14 23:50:46
---


text:
Q: sqlite load data infile Syntax Error I'm working on importing a very large CSV file into SQLite. My understanding is that LOAD DATA INFILE is my best bet.  I've created a table for it to reside in, and am attempting to execute the following query
LOAD DATA LOCAL INFILE 'F:/Downloads/NielsonReport.csv'
INTO TABLE neilson;
IGNORE 1 LINES

but, I get the following error:
Error while executing SQL query on database 'test': near "LOAD": syntax error

I seem to be getting an error along these lines regardless of what I'm trying to execute.
I feel like I'm missing something very basic, and would appreciate any help resolving this problem (I've been referencing this page for information so far)

A: When you are using SQLite, it would be a good idea to reference the SQLite documentation instead.
Anyway, SQLite itself does not have a CSV import function. But the sqlite3 command-line shell allows to import CSV files with the .import command.

A: Use import command like this.
.import '/Users/haseeb/Desktop/names_data.txt' Names


text:
Q: How to get local storage data to controller with request Inserted form values to local storage as json.
Then set the data as hidden field before model submission , When I submit the form with serialize ajax, the data not getting in actual json array in Laravel Controller.
I tried json_decode and not working yet.
Console

Request

A: try:
return response()->json(); instead of json_decode.


text:
Q: sending email with PHP (preventing from being placed in spam folder) i am trying to send email using PHP scripts... however, the recipient is receiving it in his/her SPAM folder -this is not the desired result (I would like to have it sent directly to their inbox so that I don't have to warn them to look in their SPAM folder).
below is the code I use to send the email using PEAR... what changes can I make to prevent the emails from going into the SPAM folder?

send("test.user@gmail.com", $headers, $body);
?>

A: In general, email is classified as spam or not spam on the receiving end, not the sending end - otherwise, spammers would simply say that all of their messages aren't spam, completely defeating the purpose. Thus, you can't just force a message to go to a sender's inbox.
However, what you may need to do is see if the machine that you're using to send mail is currently listed on any spam blocklists, and if so, take the necessary steps to remove it from those blocklists. The most common is probably Spamhaus.

A: How to increase the chance that the receiver doesn't mark an email as spam has been discussed quite some times here on SO. E.g.
How do you make sure email you send programmatically is not automatically marked as spam?
But there may be some tips specific to pear's Mail package on how to implement these steps (so I wouldn't consider this a duplicate ...yet).

A: You can purchase a dedicated IP address for your domain to patch this problem almost. After installing a dedicated static IP,all your email will have unique permanent sender ID...
GMail and other top mail services will list your email in Inbox...But yahoo and some other won't mind it....


text:
Q: On convergent sequences Suppose that i have and open and surjective map between two metric spaces $\pi\colon X\to Y,$ and a sequence $(x_n)_{n\in \mathbb{N}}$ such that its image by $\pi$ converges.
Is it true that $(x_n)_{n\in \mathbb{N}}$ converges, if not under which condition it does?

A: Take $X=\mathbb{R},\, Y=\{0\}$ and $x_{n}=n$ . $\pi$ defined by
$\pi(x)=0$ for every $x\in\mathbb{R}$
Then $\pi$ is open and surjective
but $x_{n}$ is not convergent while $\pi(x_{n})\equiv0$ is

A: I claim that if $\pi$ is injective we get the result
Let $y\in Y$ be (a) limit of $\pi(x_n)$. Let $x=\pi^{-1}(y)$.
Let $U\subset X$ be an open neighborhood of $x$.
$\pi$ is open, and therefore $\pi(U)$ is a open neighborhood of $y$, so there is $N\in\mathbb N$ such that for every $n>N$ we have $\pi(x_n)\in \pi(U)$ so $x_n\in U$ for all $n>N$ as desiered.
the claim is not generally correct the way you claimed.


text:
Q: What does Logn actually mean? I am just studying for my class in Algorithms and have been looking over QuickSort. I understand the algorithm and how it works, but not how to get the number of comparisons it does, or what logn actually means, at the end of the day.
I understand the basics, to the extent of :
x=logb(Y) then
b^x = Y

But what does this mean in terms of algorithm performance? It's the number of comparisons you need to do, I understand that...the whole idea just seems so unintelligible though. Like, for QuickSort, each level K invocation involves 2^k invocations each involving sublists of length n/2^K.
So, summing to find the number of comparisons :
log n
Σ 2^k. 2(n/2^k) = 2n(1+logn)
k=0

Why are we summing up to log n ? Where did 2n(1+logn) come from? Sorry for the vagueness of my descriptions, I am just so confused.

A: If you consider a full, balanced binary tree, then layer by layer you have 1 + 2 + 4 + 8 + ... vertices.  If the total number of vertices in the tree is 2^n - 1 then you have 1 + 2 + 4 + 8 + ... + 2^(n-1) vertices, counting layer by layer.  Now, let N = 2^n (the size of the tree), then the height of the tree is n, and n = log2(N) (the height of the tree).  That's what the log(n) means in these Big O expressions.

A: below is a sample tree:
      1
    /   \
   2     3
  / \   / \
 4   5 6   7

number of nodes in tree is 7 but high of tree is log 7 = 3, log comes when you have divide and conquer methods, in quick sort you divide list into 2 sublist, and continue this until rich small lists, divisions takes logn time (in average case), because the high of division is log n, partitioning in each level takes O(n), because in each level in average you partition N numbers, (may be there are too many list for partitioning, but average number of numbers is N in each level, in fact some of count of lists is N). So for simple observation if you have balanced partition tree you have log n time for partitioning, which means high of tree.

A: 1 forget about b-trees for sec
here' math :  log2 N = k is same 2^k=N .. its the definion of log
, it could be natural log(e) N = k aka e^k = n,, or decimal log10 N = k is 10^k = n
2 see perfect , balanced tree
1
1+ 1
1 + 1 + 1+ 1
8 ones
16 ones
etc
how many elements? 1+2+4+8..etc , so for 2 level b-tree there are 2^2-1 elements, for 3 level tree 2^3-1 and etc.. SO HERE'S MAGIC FORMULA: N_TREE_ELEMENTS=  number OF levels^ 2 -1 ,or using definition of log :  log2 number OF levels=  number_of_tree_elements (Can forget about -1 )
3 lets say there's a task to find element in N elements b-tree, w/  K levels (aka height)
where how b-tree is constructed log2 height =  number_of_tree elements
MOST IMPORTANT
so by how b-tree is constructed you need no more then 'height' OPERATIONS to find element in all N elements , or less.. so WHAT IS HEIGHT equals : log2 number_of_tree_elements..
so you need log2 N_number_of_tree_elements.. or log(N) for shorter

A: To understand what O(log(n)) means you might wanna read up on Big O notaion. In shot it means, that if your data set gets 1024 times bigger you runtime will only be 10 times longer (or less)(for base 2).
MergeSort runs in O(n*log(n)), which means it will take 10 240 times longer. Bubble sort runs in O(n^2), which means it will take 1024^2 = 1 048 576 times longer. So there are really some time to safe :)

To understand your sum, you must look at the mergesort algorithm as a tree:
         sort(3,1,2,4)
        /            \
   sort(3,1)      sort(2,4)
    /     \        /     \
sort(3) sort(1) sort(2) sort(4)

The sum iterates over each level of the tree. k=0 it the top, k= log(n) is the buttom. The tree will always be of height log2(n) (as it a balanced binary tree).
To do a little math:
Σ 2^k * 2(n/2^k) =
2 * Σ 2^k * (n/2^k) =
2 * Σ n*2^k/2^k =
2 * Σ n =
2 * n * (1+log(n)) //As there are log(n)+1 steps from 0 to log(n) inclusive

This is of course a lot of work to do, especially if you have more complex algoritms. In those situations you get really happy for the Master Theorem, but for the moment it might just get you more confused. It's very theoretical so don't worry if you don't understand it right away.

A: For me, to understand issues like this, this is a good way to think about it.


text:
Q: Javascript collapse delayed functionality I want to achieve the functionality of replacing old collapsed content with another one when pushing a button. When I try doing it using bootstrap button data-toggle and data-taget attributes and in addition using javascript I get a delayed hide and show functionality.
My example code:

Column1	Column2

<button type="button" class="btn btn-danger text-center" data-toggle="collapse" href="#contentID" id="errorButton">SwapContent</button>	<button type="button" class="btn btn-info" data-toggle="collapse" data-target=".contentClass" id="noteButton">SwapContent2</button>

InfoTest  InfoContent

InfoTest  InfoContent

Test  Content

Test  Content

Test  Content

Test  Content

Test  Content

InfoTest  InfoContent

InfoTest  InfoContent

Column1	Column2

Column1Content	Column2Content

Bootply execution of the same code: http://www.bootply.com/fv4WsHXXlm to show that when pushing between the buttons the old content stays on the screen for a while before it gets hidden, I would like it to happen simultaneously.

A: Already found a solution. The trick was to use jQuery hide() and show() instead of collapse("hide") and collapse("show").


text:
Q: Access child component variables within ng-container I have a custom component called Suggestion List, which displays a list of Suggestions to the user from an observable. I have created this component as generic as possible so you can pass any array of data, so I'd like to be able to customize the display of it from the parent as I'll never know for certain what the objects will look like until implementing it. Unfortunaly I can't access the child components variables from the parent in ng-container.
Is this possible with ng-container or ng-template or should I be taking another route altogether?
Parent Component
    <suggestion-list (suggestionSelected)="selectSuggestion($event)" [$suggestions]="$suggestionSource">
      <ng-container>
        {{suggestion.firstname + ' ' + suggestion.lastname}}
      <ng-container>
    </suggestion-list>

Child Component
  <mat-list role="list">
    <mat-list-item *ngFor="let suggestion of $suggestions | async">
      <mat-icon mat-list-icon>person</mat-icon>
      <mat-card (click)="selectSuggestion(suggestion)">
        <ng-container></ng-container>
      </mat-card>
    </mat-list-item>
  </mat-list>

A: One approach would be to use ng-template. You can define a template for each element in the parent component and display the template in the child component for each element in the array:
Parent component:
<suggestion-list (suggestionSelected)="selectSuggestion($event)"
                 [suggestions]="$suggestionSource | async"
                 [suggestionTemplate]="suggestionTemplate">
</suggestion-list>

<ng-template #suggestionTemplate let-suggestion>
{{suggestion.firstname + ' ' + suggestion.lastname}}
</ng-template>

And in your child component you could just do (notice that we pass the suggestion var in the template through the implicit context of the ng-template:
<ng-container *ngFor="let suggestion of suggestions>
    <ng-container *ngTemplateOutlet="suggestionTemplate; context: {$implicit: suggestion}"></ng-container>
</ng-container>

In the .ts file of the child component, you declare the template passed in like:
@Input() suggestionTemplate: TemplateRef<any>;

PS: I've written this code right now, so it's not tested, but I think you can get an idea of what you can do!

A: Here is the working example
parent.component.html

     <suggestion-list (suggestionSelected)="selectSuggestion($event)" [$suggestions]="$suggestionSource">

{{suggestion.firstname + ' ' + suggestion.lastname}}

     </suggestion-list>

child.component.html

     <ng-content></ng-content>

Hello !


text:
Q: Word for a person who likes suffering due to the relief after it I am looking for a word to describe the kind of person who likes suffering or pain due to the relief that comes after it.

A: The closest word that I can think of is masochist.

masochist

*

*Psychiatry. a person who has masochism, the condition in which sexual or other gratification depends on one's suffering physical pain or humiliation.

*a person who is gratified by pain, degradation, etc., that is self-imposed or imposed by others.

*a person who finds pleasure in self-denial, submissiveness, etc.

Generally speaking, a masochist gets some kind of pleasure from experiencing pain.


text:
Q: Radical solution to a polynomial quartic equation Consider the following quartic equation:
$$x^4 + rx^3 + r^2x^2 + r^3x + r^4 - 1 = 0$$
By Lodovico Ferrari solution, this equation must possess four radical solution provided that $r$ is a rational number, my question is simply if we assume $r$ is an algebraic number (which is a more general set of numbers that contains all rational numbers), can this equation still possess four radical roots

A: The roots of the equation are radical if and only if $r$ itself can be expressed by radicals.


text:
Q: Creating sub-folders in Caching, Cakephp I have a Cache folder in tmp.
I want a sub-folder in the cache folder, to store cache files of a particular page ONLY in that folder.
What should I do?

A: Find bootstrap.php in your app/config
Replace the following lines
Cache::config('users_cache', array( // users_cache is the custom cache log name
  'engine' => File,
  'prefix' => 'cake_',
  'path' => CACHE . 'users' . DS, // added sub-directory in users in tmp/cache
  'serialize' => true,
  'duration' => '+360 minutes'
));

Now, create a directory  in your app/tmp/cache/users
Then use it as the following format
Cache::write('enter_name', $users,'users_cache');

For best reference read the following article  Cache::write


text:
Q: config.properties file with multiple urls I have a configuration file with multiple url's and needs to be sent depending on test scenario.
But in one scenario the url is being sent and in another it is not. Please suggest the change
Tried modifying the names , loops but could not find the correct solution.

the TPurl property is being returned as null either while running as testNG suite or as an individual test.


text: Q: SSIS Visual Studio IDE will not stay still Does anyone else have the problem with SSIS in Visual Studio 2019 (and earlier versions) where the screen bounces around and will not stay still as you make changes?  Is there a setting that you can off the (what I'm calling) active focus?


text:
Q: Breeze WebApi and Breeze Angular Working Sample I am really struggling to find a working example of a Breeze WebApi and Breeze Angular applications working together.  Heck, I can't even find examples of them working on their own.
I've downloaded the Breeze-Samples package, but the Todo-Angular app is missing a bunch of files and won't build.
I've got a decent understanding of how Breeze works once it's setup, but I can't get any working examples.  I just want to see what's under the hood for initializations, API calls, etc.
Any recommendations for good examples here?

A: Try John Papa's Building Apps with Angular and Breeze - Part 1 & 2 on Pluralsite
While you are there you can also checkout Brian Noyes's Building Data-Centric Single Page Apps with Breeze
Plus many, many more tutorials on both subjects.


text:
Q: Not able to import multiple css without applying in React App I have a react app where i have created two stylesheets, one with daylight light colors and other with night light dark colors. While i am trying to import both the later one gets applied automatically. I just want to import them and not apply by default. Based on some condition i'll be applying one of them .
Here is the code :
import Daylight from './daylight.css';
import Nightlight from './nightlight.css';

I tried require also, that also doesn't helps
const Daylight = require('./daylight.css');
const Nightlight = require('./nightlight.css');

A: Importing your CSS at all is applying it right away.
You'd probably be better off if you arranged your CSS in such a way that you could conditionally apply a single class to a parent element that would then apply styles from nightlight.css.
e.g. inside nightlight.css
.night button {
  /* styles for your buttons when they're in a night container */
}

.night p {
   /* styles for your ps when they're in a night container */
}

etc

and then have some code in your component to either add or remove the night class depending on whether or not darkmode is enabled.


text:
Q: mayavi mapping a discrete colorbar on a surface I want to change the color of a surface depending on another value (an ID) that takes discrete values (so I need a discrete colorbar).
In the simplified example below I have drawn a sphere with 3 different IDs:
0/red on the left
2/blue on the middle
1/Green on the left
But with the code below, I obtain some strange behaviours (green points) at the limit between red and blue.
It is probably because of an interpolation!
The Code:
from mayavi import mlab
import numpy as np

# my dataset -simplified-
x,y,z = np.mgrid[-3:3:100j, -3:3:100j, -3:3:100j]
values = np.sqrt(x**2 + y**2 + z **2)

# my color values : the volume is divided in 3 sub-volumes along x taking
colorvalues=np.empty(values.shape)
colorvalues[0:33,:,:]=0.
colorvalues[33:66,:,:]=2.
colorvalues[66:,:,:]  =1.

src = mlab.pipeline.scalar_field(values)
src.image_data.point_data.add_array(colorvalues.T.ravel())
src.image_data.point_data.get_array(1).name = 'myID'
src.image_data.point_data.update()

# the surface i am interested on
contour = mlab.pipeline.contour(src)
contour.filter.contours= [2.8,]

# to map the ID
contour2 = mlab.pipeline.set_active_attribute(contour, point_scalars='myID')

# And we display the surface The colormap is the current attribute: the ID.
mySurf=mlab.pipeline.surface(contour2)

# I change my colormap to a discrete one : R-G-B
mySurf.module_manager.scalar_lut_manager.lut.table = np.array([[255,0,0,255],[0,255,0,255],[0,0,255,255]])

mlab.colorbar(title='ID', orientation='vertical', nb_labels=3)
mlab.show()

I have also tried with this line before mlab.show():
mySurf.actor.mapper.interpolate_scalars_before_mapping = True

The rendering is better but green points become a green strip.

A: I have found my answer by using a scipy nearest-neighbour interpolation and using one color by cell of my object.
from mayavi import mlab
import numpy as np
import scipy.interpolate

# my dataset -simplified-
x,y,z = np.mgrid[-3:3:100j, -3:3:100j, -3:3:100j]
values = np.sqrt(x**2 + y**2 + z **2)

# my color values : the volume is divided in 3 sub-volumes along x taking
colorvalues=np.empty(values.shape)
colorvalues[0:33,:,:]=0.
colorvalues[33:66,:,:]=2.
colorvalues[66:,:,:]  =1.

src = mlab.pipeline.scalar_field(x,y,z ,values)

# the surface i am interested on
contour = mlab.pipeline.contour(src)
contour.filter.contours= [2.8,]

# I extract points that form my surface
PtsCoord = contour.outputs[0].points.to_array()

# then the variable that contains the indices of the points forming triangles.
PolyAndTriIDs = contour.outputs[0].polys.to_array()
PolyAndTriIDs = PolyAndTriIDs.reshape(PolyAndTriIDs.size/4,4)

# Coordinates of each triangle
x1,y1,z1 = PtsCoord[PolyAndTriIDs[:,1]].T
x2,y2,z2 = PtsCoord[PolyAndTriIDs[:,2]].T
x3,y3,z3 = PtsCoord[PolyAndTriIDs[:,3]].T

# I interpolate the color value at the center of triangles with the Nearest-neighbour interpolation method
interp0 = scipy.interpolate.NearestNDInterpolator( (x.ravel(),y.ravel(),z.ravel()), colorvalues.ravel() )
result0 = interp0((np.mean((x1,x2,x3),0),np.mean((y1,y2,y3),0),np.mean((z1,z2,z3),0)))

# Displaying with triangular_mesh and color given by cell scalar value
mesh = mlab.triangular_mesh(PtsCoord[:,0], PtsCoord[:,1], PtsCoord[:,2], PolyAndTriIDs[:,1:])
cell_data = mesh.mlab_source.dataset.cell_data
cell_data.scalars = result0
cell_data.scalars.name = 'Cell data'
cell_data.update()
mesh.actor.mapper.scalar_mode = 'use_cell_data'
mesh.module_manager.scalar_lut_manager.lut.table = np.array([[255,0,0,255],[0,255,0,255],[0,0,255,255]])
mesh.module_manager.scalar_lut_manager.use_default_range = False
mesh.module_manager.scalar_lut_manager.data_range = [ 0.,  2.]

mlab.colorbar(title='ID', orientation='vertical', nb_labels=3)

The result is less smoother but more relevant.


text:
Q: Plotting two lines with different length in a same plot in R I want to plot two lines in a same plot in R. The length of these two lines are different. What I did so far is:
L <- c(-1.87731736,-0.93904772, 0.09349034, 0.88211328, 1.62668827,
       2.45229737, 3.29279521, 4.16821441, 5.07816932, 5.98971301,
       6.92079292, 7.85341450, 8.74968222, 9.67036437, 10.59479955,
       11.51243444, 12.46106635, 13.44241394, 14.40218939)

D <- c(-4.9618451, -4.6051702, -4.6051702, -4.5098600, -4.1997051, -3.1010928,
       -1.5095926, 0.2207407, 1.6789640, 3.3577330, 5.1708419, 7.2888853)

leaves <- c(7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18)

plot(leaves, D, type = "l", xaxt = "n", yaxt = "n", xlab = "", ylab = "")
mtext("x-lab", side = 1, line = 3.5)
mtext("y-lab", side = 2, line = 2.5)
axis(1, xaxp = c(7,25,18), las = 0.1, labels = FALSE)
text(seq(7, 25, by = 1), par("usr")[3] -3, labels = lablist,
     srt = 45, pos =3, xpd = TRUE, offset = 1.2 , cex = 0.75)
axis(2, yaxp = c(-10, 15, 5), las = 2)
leaves = c(7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
           17, 18, 19, 20, 21, 22, 23, 24, 25)
lines(leaves, L, type = "l", pch = 22, lty = 2)
legend(7, 15, legend = c("D", "L"), lty = 1:2, cex = 0.8)
lablist = as.character(c("7-11", "8-23", "9-46", "10-98", "11-207", "12-451",
                         "13-983", "14-2179", "15-4850", "16-10905", "17-24631",
                         "18-56011", "19-127912", "20-293547", "21-676157",
                         "22-1563372","23-3626149", "24-8436379", "25-19680277"))

The problem is that the longer line would not appear in the plot completely. Does anyone know how to fix it?


text:
Q: PuLP: Check whether the solution satisfies the constraints So I ran CBC through pulp for 5 seconds and it gave out a solution but I am not sure it satisfies all the constraints. The value for each variable
is stored in prob.variables(). Is there a way I could run a similar code as the one below to check if the solutions satisfy the constraints given in prob.constraints - i.e. the solution is feasible ?
prob.solve(PULP_CBC_CMD(maxSeconds=5))

print 'Optimization status: %s' % LpStatus[prob.status]

for v in prob.variables():
    test whether 'v' satisfies prob.constraints

The setup of the problem and the constraints are very similar to the one given here: github_code
Cheers.


text:
Q: Change the color of the checkbox's check mark in css How can I change the color of the check mark using css?

  <input type="checkbox" name="remember" value="1" class="remember">

A: I think this is what you want (CSS only):
HTML:
<input type="checkbox" name="genres" value="adventure" id="adventure_id">
Adventure

CSS:
input[type="checkbox"]:checked + label::after {
    content: '';
    position: absolute;
    width: 1.2ex;
    height: 0.4ex;
    background: rgba(0, 0, 0, 0);
    top: 0.5ex;
    left: 0.6ex;
    border: 3px solid red;
    border-top: none;
    border-right: none;
    -webkit-transform: rotate(-45deg);
    -moz-transform: rotate(-45deg);
    -o-transform: rotate(-45deg);
    -ms-transform: rotate(-45deg);
    transform: rotate(-45deg);
}

input[type="checkbox"] {
    line-height: 2.1ex;
}

input[type="radio"],
input[type="checkbox"] {
    position: absolute;
    left: -999em;
}

input[type="checkbox"] + label {
    position: relative;
    overflow: hidden;
    cursor: pointer;
}

input[type="checkbox"] + label::before {
    content: "";
    display: inline-block;
    vertical-align: -25%;
    height: 3ex;
    width: 3ex;
    background-color: white;
    border: 1px solid rgb(166, 166, 166);
    border-radius: 4px;
    box-shadow: inset 0 2px 5px rgba(0,0,0,0.25);
    margin-right: 0.5em;
}


text:
Q: ExpressJS SSL on one domain only I'm using ExpressJS. My app is a https server which also contains a vhost.
app.use(express.vhost('api.example.com', require('./lib/subdomains/api').app));

Because my SSL certificate is for the root domain only, my api.example.com domain now fails to load the routes it's been given.
How can I only use SSL on my root domain and not on my other? I need to be able to share the app configuration between the domains, but not the SSL certificate.

A: Doh. I hadn't changed my NODE_ENV so the vhost was setup incorrectly in the live environment.


text:
Q: check whether a number is bleak or supported in efficient way
*

*Given a number how to recognize if it is bleak or supported by some number in efficient manner?

*Given an array of numbers, how to check efficiently whether each number is supported with in the
array or bleak if not supported with in the array?
Brute force : Find binary equivalent, count number of 1's and search for it in the array.
About Bleak and supported numbers:
For each number, count the number of ones in its own binary representation, and add this count to itself to obtain the value of the number it supports. That is, if j is the number of ones in the binary representation of m, then m supports m+j.
Example:number eight (1000 in binary) supports nine, whereas nine supports eleven.
However, in this way not all the numbers get supported; some are left without support, and these numbers  are called bleak. For example since one supports two, two supports three and three supports five, there is no number less than four, which would support four, so four is bleak.

A: If n is not bleak, it must be supported by a number in the range n-ceil(log2(n)) to n-1. This gives a very small range you have to check. For the array, first sorting the array then using the same principle should give you an efficient solution.

A: Denote a as the given array and count(x) as the number of 1 bits in x.
Question 2:

*

*Iterate through the array and save the the number a[i] + count(a[i]) into a binary search tree. Time: O(n log n)

*Iterate through the array and output "Supported" if a[i] is in the binary search tree and "Bleak" otherwise. Time: O(n log n)

Note: a[i] is the current element at the iteration.


text:
Q: No speex packages for freeswitch building on Ubuntu I am trying to build freeswitch on Ubuntu and getting numerous libraries absent. One of them is speex. configure says it is absent while dpkg says it is here:
checking for speex >= 1.2rc1 speexdsp >= 1.2rc1... Package speex was not found in the pkg-config search path. Perhaps you should add the directory containing `speex.pc' to the PKG_CONFIG_PATH environment variable No package 'speex' found Package speexdsp was not found in the pkg-config search path. Perhaps you should add the directory containing `speexdsp.pc' to the PKG_CONFIG_PATH environment variable No package 'speexdsp' found
configure: error: Library requirements (speex >= 1.2rc1 speexdsp >= 1.2rc1) not met; consider adjusting the PKG_CONFIG_PATH environment variable if your libraries are in a nonstandard prefix so pkg-config can find them.
dims@nebula2:~/src/freeswitch$ dpkg -l *speex*
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name                             Version                          Description
+++-================================-================================-================================================================================
ii  libspeex1                        1.2~rc1-3ubuntu2                 The Speex codec runtime library
ii  libspeexdsp1                     1.2~rc1-3ubuntu2                 The Speex extended runtime library
ii  speex                            1.2~rc1-3ubuntu2                 The Speex codec command line tools

why? and how to fix?

A: You need to install libspeex-dev
sudo apt-get install libspeex-dev

So, you will have below result :
saman@jack:~$ dpkg -l *speex*
Desired=Unknown/Install/Remove/Purge/Hold
| Status=Not/Inst/Conf-files/Unpacked/halF-conf/Half-inst/trig-aWait/Trig-pend
|/ Err?=(none)/Reinst-required (Status,Err: uppercase=bad)
||/ Name           Version      Architecture Description
+++-==============-============-============-=================================
ii  libspeex-dev:a 1.2~rc1.1-1u amd64        The Speex codec library developme
ii  libspeex1:amd6 1.2~rc1.1-1u amd64        The Speex codec runtime library
ii  libspeexdsp1:a 1.2~rc1.1-1u amd64        The Speex extended runtime librar
un  speex          <none>       <none>       (no description available)

A: You may also need to install the libspeexdsp-dev package (which depends on libspeex-dev):
sudo apt-get install libspeexdsp-dev


text:
Q: this is dangerous if i insert query in sql field this is not sql injection
for example imagine user fill my form application in web form, in one field of form user write (select * from users) or write dangerous sql script and send data and everything set in my db so my record in table e.g

id  |  title | desc
--------------------
1   |  first | select * from users

how to protect it of? or generally this is dangerous?
tnx

A:
this is not sql injection

This is SQL injection

how to protect it of? or generally this is dangerous?

since you have tagged asp.net always use Parameterized Queries.
See: Using Parameterized Queries with the SqlDataSource (C#) and
Parameterized SQL Queries in C#
EDIT:
Since the OP mentioned in the comments about the usage of Entity. Following points should be considered:
Prevent SQL injection attacks. - Entity Framework - MSDN

LINQ to Entities injection attacks:
Although query composition is possible in LINQ to Entities, it is
  performed through the object model API. Unlike Entity SQL queries,
  LINQ to Entities queries are not composed by using string manipulation
  or concatenation, and they are not susceptible to traditional SQL
  injection attacks.


text:
Q: If $f$ is an entire function and $f = f'$ then the is a constant $K$ such that $f(z) = Ke^z$ I need to prove that if $f$ is an entire function (holomorphic in all the complex space) and $f = f'$ then there is a complex constant $K$ such that $f(z)  = Ke^z$.
Moreover, I need to show that $e^z = \sum\limits_{n \ge 0} \frac{z^n}{n!}$.
Well I am not so sure what to do here. I see that $f-f' = $ constant, but I don't think it helps. I can clearly show that if $f(z) = Ke^z$ it satisfies the conditions, but I am not sure how to prove that $f$ is necessarily such a function.
Help would be appreciated.


text:
Q: Cross-referencing heading numbers in HTML I'm trying to used HTML to prepare a legal document and need to be able to number headings and then cross-references those numbers throughout the document. I have successfully sorted out the numbering as in the example below but how can I correctly create the 'h2ref' and 'h3ref' classes to cross-reference in the 'a' tag near the bottom. The output in this last line should be:
"this is some content referencing Section 1."
Here's my code

body {
  counter-reset: h2counter;
}

h1 {
  counter-reset: h2counter;
}

.countheads~h2:before {
  content: counter(h2counter) ".\0000a0\0000a0";
  counter-increment: h2counter;
}

h2 {
  counter-reset: h3counter;
}

.countheads~h3:before {
  content: counter(h2counter) "." counter(h3counter) ".\0000a0\0000a0";
  counter-increment: h3counter;
}

ol {
  #list-style-type: lower-alpha;
  list-style-type: lower-roman;
}

a.h2ref:after {
  content: "Section " attr(href);
}

a.h3ref:after {
  content: "Subsection " attr(href);
}

Numbering headings

About

Some text

Some more text

this is another line

Subheading

More text

One more subheading

Demonstration

this is some content referencing
  .

The code above is based on another question in Stackoverflow but have unfortunately lost track of the source. If you can point me in the right direction will be very happy to credit appropriately.


text:
Q: how to run my selenium script on multiple servers at the same time so that i would saved one by one execution time? how to run my selenium script on multiple servers at the same time so that i would save one by one execution time ?
Scenario: I have 1 hour of total testing time and 20 servers to test and 1 test script takes about 30mins to execute so i want to run my test script simultaneously on all 20 servers in order to save time.

A: The answer to your question is parallel execution
There are multiple ways to achieve this like 1> Creating a Jenkins Job, Registering all the server machines as slave and executing jobon servers
Or
2> A comparitively simpler and more widely used concept, using Selenium Grid
To Implement Selenium Grid ( for instance with java as a programming language and TestNG framework) we need to take care that
A. we have implemented Threading for our webdriver, so that each execution works on its own driver instance.
B. We have our Testng.xml with attribute set as parallel=tests
You can easily get step by step guide to establish selenium grid to summarize it, We have one machine as hub(master), we have multiple machines or nodes(slave) registered to the hub, your automation code is supplied to the hub, Hub routes test on multiple nodes keeps track of individual execution and gets you the result on the Hub machine itself


text:
Q: Find generating function created by $a_n=2^{n+3}$, for $n\geq3$,$ a_0=1$, $a_1=\frac{5}{2}$ $a_2=3$ I hope title is understandable, wasn't sure on how to translate this task from my language.
Below is my solution to this problem, is logic behind it correct?
$$A(z)=\sum_{n=0}^{\infty}a_nz^n=1+\frac{5}{2}z+3z^2+\sum_{n\geq3}^{\infty}a_nz^n$$
$$=1+\frac{5}{2}z+3z^2+2^3+\sum_{n\geq3}^{\infty}(2z)^n$$
$$=1+\frac{5}{2}z+3z^2+2^3+[(2z)^3+(2z)^4+(2z)^5...]$$
$$b_n=(2_z)^n$$
$$\frac{b_{n+1}}{b_n}=2z$$
$$q=2z$$
$$W_0=(2z)^3$$
$$|2z|<1|$$
$$=1+\frac{5}{2}z+3z^2+2^3+\frac{(2z)^3}{1-2z}$$
I need to make sure on test that I didn't make mistakes so if its correct, could any of you explain on how to check if answer is right?

A: I think your work is wrong:
$$\begin{align}
A_n(x)&=\sum_{n \in \mathbb {N}}a_n x^n\\
&=a_0x^0+a_1x^1+a_2x^2+\sum_{n \geqslant3}a_n x^n\\
&=19+x+a_2x^2+\sum_{n \geqslant 3}2^{n+3}x^n\\
&=19+x+a_2x^2+2^3\sum_{n \geqslant 3}(2x)^n\\
\end{align}$$


text:
Q: package installation error I was trying to install mysql server 5.6 via deb file and the software installer froze and force quited. After that when i tried to install mysql via the command
 sudo apt-get install mysql-server

its giving me this error
E: dpkg was interrupted, you must manually run 'sudo dpkg --configure -a' to correct the problem.

So i tried to remove mysql via this command
sudo dpkg --configure -a

After then when i was trying to setup mysql its giving me this errors
The package mysql needs to be reinstalled, but I can't find an archive for it.

Please help!!

A: dpkg --configure -a does not remove any software: (from the man page)
--configure package...|-a|--pending
          Configure a package which has been unpacked but not yet  config‐
          ured.   If  -a  or  --pending  is  given instead of package, all
          unpacked but unconfigured packages are configured.

That does not revert nor continue the work you triggered by apt-get, but continues and completes a substep carried out by dpkg. After you've done that you should issue the initial apt-get command again.
You may have to reinstall the packages with this command (reinstalls all direct dependencies):
apt-get --reinstall --purge install libaio1 libdbd-mysql-perl libdbi-perl libhtml-template-perl libnet-daemon-perl libplrpc-perl libterm-readkey-perl mysql-client-5.5 mysql-client-core-5.5 mysql-server-5.5 mysql-server-core-5.5

Also, an apt-get update does the trick sometimes.


text:
Q: Associative array that returns function in perl Is it possible to create associative array that returns function?
Something similar to this
%a = ('first' => sub first { $x = @_; sprintf("(first %s)", $x); });

Thank you

A: It is possible, but you probably want my ($x) = @_; instead of $x = @_; and drop function name as you're dealing with anonymous function.
You can then call function as $a{first}->([arg])
my %a = ('first' => sub { my ($x) = @_; sprintf("(first %s)", $x); });

A: So close... The one detail you missed is that you're defining an anonymous sub there, so you shouldn't give it a name:
$ perl -E '%a = (first => sub { $x = @_; sprintf("(first %s)", $x); }); say $a{first}->(3);'
(first 1)

(Note that, with $x = @_, you're setting $x to the number of items in @_, not the first item in the array, which is why the output is "first 1" instead of "first 3".)

A: You an either store a reference to an anonymous subroutine:
my %a = ('first' => sub { my ($x) = @_; sprintf("(first %s)", $x); });
Or a reference to a named subroutine:
sub first {
  my ($x)= @_;
  sprintf("(first %s)", $x);
}

my %a = ('first' => \&first);

In both cases, you dereference them the same way.
my @result = $a{first}->(@args);

This is usually called a 'dispatch table'.

A: First of all there is no associative array in perl. It is a hash
Yes you can store reference to a subroutine in a hash;
 my %hash=(
        'function'=>\&subroutine,
 );
 sub subroutine{
     print "hai";
 }

or you can create it inside the hash


text:
Q: Prove that $f(x)=(e^x-1)(x^2+3x-2)+x$ has exactly one positive root, exactly one negative root and one root at $x=0$. Prove that the function
$f(x)=(e^x-1)(x^2+3x-2)+x$
has exactly one positive root, exactly one negative root and one root at $x=0$.
My work so far:
$f(0)=0$
Thus, $x=0$ is a root.
For the positive root,
$f(\frac{1}{4})=(e^{\frac{1}{4}}-1)((\frac{1}{4})^2+3(\frac{1}{4})-2)+(\frac{1}{4})
               =(e^{\frac{1}{4}}-1)(\frac{1}{16}+\frac{3}{4}-2)+\frac{1}{4}
               =-\frac{19}{16}e^{\frac{1}{4}}+\frac{23}{16}
               <0$
$f(1)=(e^1-1)((1)^2+3(1)-2)+(1)
     =(e^1-1)(1+3-2)+1=2e^1-1
     >0$
Thus, there is at least one positive root, by the intermediate value theorem. I have also done the same thing for the negative root, as $f(-4)<0$ and $f(-2)>0$.
But how do I show that there is only one positive root and only one negative root?

A: (To state my solution more rigorously and clearly, I put my comment into an answer.)
First, it is easy to calculate:
$$
f'(x) = e^x (x^2+5x+1) - 2x -2 \\
f''(x) = (x+1)(x+6)e^x-2 \\
f'''(x)=e^x(x^2+9x+13)
$$
Second, we will check how many real roots $f''(x)=0$ has:

*

*Case $-\infty<x \leq -1$:
Calculate $f'''(x)=0$, we get the stationary points of $f''(x)$ are at
$$ x_{1} = \frac{-9 + \sqrt{29}}{2}, ~ x_{2} = \frac{-9 - \sqrt{29}}{2}$$
Then evaluate: $f''(x_1)\approx -2.55543$, $f''(x_2)\approx -1.99445$. Besides,
$$ \lim_{x \rightarrow -\infty} f''(x) = -2$$
and $f''(-1)=-2$. Thus,
$$\max_{-\infty < x \leq -1} f''(x)=f''(x_2)\approx -1.99445 < 0$$
That is, in this case, there's no real root for $f''(x)=0$.

*Case $x>-1$:
In this case, it is easy to check $f''(x)$ is monotone increasing and is able to go larger than 0. Thus, there's exactly one real root for $f''(x)=0, x>-1$.

Conclusion: $f''(x)=0$ has exactly one real root.

Finally, we will utilize Rolle's theorem:

(Given proper continuity and differentiability.) If $f'(x)=0$ has exactly $n$ real roots, then $f(x)=0$ at most has $n+1$ real roots.

Why? If we can find $n+2$ real roots for $f(x)=0$, say
$$x_1<x_2<\cdots<x_{n+2}$$
according to Rolle's theorem, there will exist $c_1 \in (x_1,x_2)$, $c_2 \in (x_2,x_3)$, ..., $c_{n+1} \in (x_{n+1},x_{n+2})$, such that
$$f'(c_1) = f'(c_2) = \cdots = f'(c_{n+1}) = 0$$
It will contradict "$f'(x)=0$ has exactly $n$ real roots".

Now, we can see because $f''(x)=0$ has exactly one real root, $f'(x)=0$ will at most have two real roots, and then $f(x)=0$ will at most have three real roots. And you have found the three roots for $f(x)=0$, so there're no more roots.

Note: Be careful of the "at most" statements above. It does NOT mean the equation must have such many roots.

A: I bet, you have to find any two positive numbers a and bsuch that f(a)<0 and f(b)>0. Thus, it will prove that there is one positive root that is between a and b.
Same logic applies for the negative root.

A: You can also use the fact that the function is differentiable (and continuous) at all $R$, to find a contradiction:
Suppose that $0 <a <b$ with $a$, $b$, roots of $f(x)$, with $0$, $a$, $b$, consecutive roots, then there exists $c_1\in[0,a]$ and $c_2 \in[a, b]$ such that $f(x)$ reaches maximum or minimum, as the function is twice differentiable we have:
$$f''(x)=e^x(x^2+5x+1)+e^x(2x+5)-2$$
$$f''(x)=e^x(x^2+5x+1)+2xe^x+5e^x-2$$
how $5e^x>2$, $f''(x)$  is always positive for all $x>0$ then $c_1$ and $c_2$ are both minimuns, but this implies that there is no tangent line at $a$ which contradicts the fact that $f(x)$ is differentiable at all $R$.
God bless


text:
Q: Java Biasing Random Numbers in a Triangular Array This question is an extension of Java- Math.random(): Selecting an element of a 13 by 13 triangular array. I am selecting two numbers at random (0-12 inclusive) and I wanted the values to be equal.
But now, since this is a multiplication game, I want a way to bias the results so certain combinations come up more frequently (like if the Player does worse for 12x8, I want it to come up more frequently). Eventually, I would like to bias towards any of the 91 combinations, but once I get this down, that should not be hard.
My Thoughts: Add some int n to the triangular number and Random.nextInt(91 + n) to bias the results toward a combination.
private int[] triLessThan(int x, int[] bias) { // I'm thinking a 91 element array, 0 for no bias, positive for bias towards
    int i = 0;
    int last = 0;
    while (true) {
                    int sum = 0;
                    for (int a = 0; a < i * (i + 2)/2; a++){
                        sum += bias[a]
                    }
        int triangle = i * (i + 1) / 2;
        if (triangle + sum > x){
            int[] toReturn = {last,i};
            return toReturn;
        }
        last = triangle;
        i++;
    }
}

At the random number roll:
int sum = sumOfArray(bias); // bias is the array;
int roll = random.nextInt(91 + sum);
int[] triNum = triLessThan(roll);
int num1 = triNum[1];
int num2 = roll - triNum[0]; //now split into parts and make bias[] add chances to one number.

where sumOfArray just finds the sum (that formula is easy). Will this work?
Edit: Using Floris's idea:
At random number roll:
int[] bias = {1,1,1,...,1,1,1} // 91 elements
int roll = random.nextInt(sumOfBias());
int num1 = roll;
int num2 = 0;
while (roll > 0){
    roll -= bias[num2];
    num2++;
}
num1 = (int) (Math.sqrt(8 * num2 + 1) - 1)/2;
num2 -= num1 * (num1 + 1) / 2;

A: You already know how to convert a number between 0 and 91 and turn it into a roll (from the answer to your previous question). I would suggest that you create an array of N elements, where N >> 91. Fill the first 91 elements with 0...90, and set a counter A to 91. Now choose a number between 0 and A, pick the corresponding element from the array, and convert to a multiplication problem. If the answer is wrong, append the number of the problem to the end of the array, and increment A by one.
This will create an array in which the frequencies of sampling will represent the number of times a problem was solved incorrectly - but it doesn't ever lower the frequency again if the problem is solved correctly the next time it is asked.
An alternative and better solution, and one that is a little closer to yours (but distinct) creates an array of 91 frequencies - each initially set to 1 - and keeps track of the sum (initially 91). But now, when you choose a random number (between 0 and sum) you traverse the array until the cumulative sum is greater then your random number - the number of the bin is the roll you choose, and you convert that with the formula derived earlier. If the answer is wrong you increment the bin and update the sum; if it is right, you decrement the sum but never to a value less than one, and update the sum. Repeat.
This should give you exactly what you are asking: given an array of 91 numbers ("bins"), randomly select a bin in such a way that the probability of that bin is proportional to the value in it. Return the index of the bin (which can be turned into the combination of numbers using the method you had before). This function is called with the bin (frequency) array as the first parameter, and the cumulative sum as the second. You look up where the cumulative sum of the first n elements first exceeds a random number scaled by the sum of the frequencies:
private int chooseBin(float[] freq, float fsum) {
// given an array of frequencies (probabilities) freq
// and the sum of this array, fsum
// choose a random number between 0 and 90
// such that if this function is called many times
// the frequency with which each value is observed converges
// on the frequencies in freq
    float x, cs=0; // x stores random value, cs is cumulative sum
    int ii=-1;     // variable that increments until random value is found

    x = Math.rand();

    while(cs < x*fsum && ii<90) {
    // increment cumulative sum until it's bigger than fraction x of sum
        ii++;
        cs += freq[ii];
    }
return ii;
}

I confirmed that it gives me a histogram (blue bars) that looks exactly like the probability distribution that I fed it (red line):

(note - this was plotted with matlab so X goes from 1 to 91, not from 0 to 90).
Here is another idea (this is not really answering the question, but it's potentially even more interesting):
You can skew your probability of choosing a particular problem by sampling something other than a uniform distribution. For example, the square of a uniformly sampled random variate will favor smaller numbers. This gives us an interesting possibility:
First, shuffle your 91 numbers into a random order
Next, pick a number from a non-uniform distribution (one that favors smaller numbers). Since the numbers were randomly shuffled, they are in fact equally likely to be chosen. But now here's the trick: if the problem (represented by the number picked) is solved correctly, you move the problem number "to the top of the stack", where it is least likely to be chosen again. If the player gets it wrong, it is moved to the bottom of the stack, where it is most likely to be chosen again. Over time, difficult problems move to the bottom of the stack.
You can create random distributions with different degrees of skew using a variation of
roll = (int)(91*(asin(Math.rand()*a)/asin(a)))

As you make a closer to 1, the function tends to favor lower numbers with almost zero probability of higher numbers:

I believe the following code sections do what I described:
private int[] chooseProblem(float bias, int[] currentShuffle) {
// if bias == 0, we choose from uniform distribution
// for 0 < bias <= 1, we choose from increasingly biased distribution
// for bias > 1, we choose from uniform distribution
// array currentShuffle contains the numbers 0..90, initially in shuffled order
// when a problem is solved correctly it is moved to the top of the pile
// when it is wrong, it is moved to the bottom.
// return value contains number1, number2, and the current position of the problem in the list
    int problem, problemIndex;

    if(bias < 0 || bias > 1) bias = 0;

    if(bias == 0) {
        problem = random.nextInt(91);
        problemIndex = problem;
    }
    else {
        float x = asin(Math.random()*bias)/asin(bias);
        problemIndex = Math.floor(91*x);
        problem = currentShuffle[problemIndex];
    }

    // now convert "problem number" into two numbers:
    int first, last;
    first = (int)((Math.sqrt(8*problem + 1)-1)/2);
    last = problem - first * (first+1) / 2;

    // and return the result:
    return {first, last, problemIndex};
}

private void shuffleProblems(int[] currentShuffle, int upDown) {
// when upDown==0, return a randomly shuffled array
// when upDown < 0, (wrong answer) move element[-upDown] to zero
// when upDown > 0, (correct answer) move element[upDown] to last position
// note - if problem 0 is answered incorrectly, don't call this routine!

    int ii, temp, swap;

    if(upDown == 0) {

        // first an ordered list:
        for(ii=0;ii<91;ii++) {
            currentShuffle[ii]=ii;
        }

        // now shuffle it:
        for(ii=0;ii<91;ii++) {
            temp = currentShuffle[ii];
            swap = ii + random.nextInt(91-ii);
            currentShuffle[ii]=currentShuffle[swap];
            currentShuffle[swap]=temp;
        }
        return;
    }

    if(upDown < 0) {
        temp = currentShuffle[-upDown];
        for(ii = -upDown; ii>0; ii--) {
            currentShuffle[ii]=currentShuffle[ii-1];
        }
        currentShuffle[0] = temp;
    }
    else {
        temp = currentShuffle[upDown];
        for(ii = upDown; ii<90; ii++) {
            currentShuffle[ii]=currentShuffle[ii+1];
        }
        currentShuffle[90] = temp;
    }
    return;
}

// main problem posing loop:

int[] currentShuffle = new int[91];
int[] newProblem;
int keepGoing = 1;

// initial shuffle:
shuffleProblems( currentShuffle, 0); // initial shuffle

while(keepGoing) {
    newProblem = chooseProblem(bias, currentShuffle);
    // pose the problem, get the answer
    if(wrong) {
        if(newProblem > 0) shuffleProblems( currentShuffle, -newProblem[2]);
    }
    else shuffleProblems( currentShuffle, newProblem[2]);
    // decide if you keep going...
}


text:
Q: shell_exec in PHP I have PHP code (setup.php) that execute bash-script, this is my code :
$hasil = shell_exec("./setup-srv.sh testajah mydomain.com");
echo "<pre>".$hasil."</pre>";

successfull when executed from commadline (setup-srv.sh), but failed when executed from browser (setup.php)
these 2 files at /var/www/html/
setup-srv.sh has several jobs :

*

*register subdomain to DNS server

*create and populate data to mysql database

*copy master folder and it's contents to new folder

*execute certbot to new subdomain

I chmod 2 files with 777, but still failed.
I need help, thank you at advance.

A: I'm assuming you're on a newer PHP than 5.3, or you have safe mode off.
This is likely to be an issue with the differences between your environment and the web server's environment.
Things to try:
Unlikely to be the problem, but ..
$hasil = shell_exec("/var/www/html/setup-srv.sh testajah mydomain.com");
SU to the webserver user and try to run the script, see what happens.
Make sure SELinux isn't interfering with the webserver's ability to execute external programs.


text:
Q: ThreadLocal HashMap vs ConcurrentHashMap for thread-safe unbound caches I'm creating a memoization cache with the following characteristics:

*

*a cache miss will result in computing and storing an entry

*

*this computation is very expensive

*this computation is idempotent

*unbounded (entries never removed) since:

*

*the inputs would result in at most 500 entries

*each stored entry is very small

*cache is relatively shorted-lived (typically less than an hour)

*overall, memory usage isn't an issue

*there will be thousands of reads - over the cache's lifetime, I expect 99.9%+ cache hits

*must be thread-safe
What would have superior performance, or under what conditions would one solution be favored over the other?
ThreadLocal HashMap:
class MyCache {
    private static class LocalMyCache {
        final Map<K,V> map = new HashMap<K,V>();

        V get(K key) {
            V val = map.get(key);
            if (val == null) {
                val = computeVal(key);
                map.put(key, val);
            }
            return val;
        }
    }

    private final ThreadLocal<LocalMyCache> localCaches = new ThreadLocal<LocalMyCache>() {
        protected LocalMyCache initialValue() {
            return new LocalMyCache();
        }
    };

    public V get(K key) {
        return localCaches.get().get(key);
    }
}

ConcurrentHashMap:
class MyCache {
    private final ConcurrentHashMap<K,V> map = new ConcurrentHashMap<K,V>();

    public V get(K key) {
        V val = map.get(key);
        if (val == null) {
            val = computeVal(key);
            map.put(key, val);
        }
        return val;
    }
}

I figure the ThreadLocal solution would initially be slower if there a lot of threads because of all the cache misses per thread, but over thousands of reads, the amortized cost would be lower than the ConcurrentHashMap solution. Is my intuition correct?
Or is there an even better solution?

A: use ThreadLocal as cache is a not good practice
In most containers, threads are reused via thread pools and thus are never gc. this would lead something wired
use ConcurrentHashMap you have to manage it in order to prevent mem leak
if you insist, i suggest using week or soft ref and evict after rich maxsize
if you are finding a in mem cache solution ( do not reinventing the wheel  )
try guava cache
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/cache/CacheBuilder.html

A:
this computation is very expensive

I assume this is the reason you created the cache and this should be your primary concern.
While the speed of the solutions might be slightly different << 100 ns, I suspect it is more important that you be able to share results between threads. i.e. ConcurrentHashMap is likely to be the best for your application is it is likely to save you more CPU time in the long run.
In short, the speed of you solution is likely to be tiny compared to the cost of computing the same thing multiple times (for multiple threads)

A: Note that your ConcurrentHashMap implementation is not thread safe and could lead to one item being computed twice. It is actually quite complicated to get it right if you store the results directly without using explicit locking, which you certainly want to avoid if performance is a concern.
It is worth noting that ConcurrentHashMap is highly scalable and works well under high contention. I don't know if ThreadLocal would perform better.
Apart from using a library, you could take some inspiration from Java Concurrency in Practice Listing 5.19. The idea is to save a Future<V> in your map instead of a V. That helps a lot in making the whole method thread safe while staying efficient (lock-free). I paste the implementation below for reference but the chapter is worth reading to understand that every detail counts.
public interface Computable<K, V> {

    V compute(K arg) throws InterruptedException;
}

public class Memoizer<K, V> implements Computable<K, V> {

    private final ConcurrentMap<K, Future<V>> cache = new ConcurrentHashMap<K, Future<V>>();
    private final Computable<K, V> c;

    public Memoizer(Computable<K, V> c) {
        this.c = c;
    }

    public V compute(final K arg) throws InterruptedException {
        while (true) {
            Future<V> f = cache.get(arg);
            if (f == null) {
                Callable<V> eval = new Callable<V>() {
                    public V call() throws InterruptedException {
                        return c.compute(arg);
                    }
                };
                FutureTask<V> ft = new FutureTask<V>(eval);
                f = cache.putIfAbsent(arg, ft);
                if (f == null) {
                    f = ft;
                    ft.run();
                }
            }
            try {
                return f.get();
            } catch (CancellationException e) {
                cache.remove(arg, f);
            } catch (ExecutionException e) {
                throw new RuntimeException(e.getCause());
            }
        }
    }
}

A: Given that it's relatively easy to implement both of these, I would suggest you try them both and test at steady state load to see which one performs the best for your application.
My guess is that the the ConcurrentHashMap will be a little faster since it does not have to make native calls to Thread.currentThread() like a ThreadLocal does. However, this may depend on the objects you are storing and how efficient their hash coding is.
I may also be worthwhile trying to tune the concurrent map's concurrencyLevel to the number of threads you need. It defaults to 16.

A: The lookup speed is probably similar in both solutions. If there are no other concerns, I'd prefer ThreadLocal, since the best solution to multi-threading problems is single-threading.
However, your main problem is you don't want concurrent calculations for the same key; so there should be a lock per key; such locks can usually be implemented by ConcurrentHashMap.
So my solution would be
class LazyValue
{
    K key;

    volatile V value;

    V getValue() {  lazy calculation, doubled-checked locking }
}

static ConcurrentHashMap<K, LazyValue> centralMap = ...;
static
{
    for every key
        centralMap.put( key, new LazyValue(key) );
}

static V lookup(K key)
{
    V value = localMap.get(key);
    if(value==null)
        localMap.put(key, value=centralMap.get(key).getValue())
    return value;
}

A: The performance question is irrelevant, as the solutions are not equivalent.
The ThreadLocal hash map isn't shared between threads, so the question of thread safety doesn't even arise, but it also doesn't meet your specification, which doesn't say anything about each thread having its own cache.
The requirement for thread safety implies that a single cache is shared among all threads, which rules out ThreadLocal completely.


text:
Q: Adding a negative lookahead to a URL matching Regex So I'm tryin to replace all text URLs in multiple elements on my page with that URL in anchor tags:
http://google.com => http://google.com
var titles = document.querySelectorAll(".title");
var l = titles.length, i, title;
    for(i = 0; i < l; i++) {
    console.log('foo')
    title = titles[i];
    title.innerHTML = title.innerHTML.replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,"$1")
}

The problem is I have to run the regex again after some AJAX comes back and it's re-applying the anchor tags to the urls in the href="" attribute of the anchor tags! So I need to add a negative lookahead to this regex that prevents it from matching any urls with a trailing " or '.
Do match http://google.com but don't match "http://google.com"
/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig

A: The general lookahead technique to assert that something is not inside double quotes is to check that there is an even number of them until the end of the string:
yourPatternHere(?=[\s\S]*(?:"[\s\S]*"[\s\S])*$)

But you are operating on HTML. This may cause all sorts of problems (unmatched quotes in text nodes, comments, single quote delimited attribute values and so on). Don't use regular expressions to parse HTML. Instead use JavaScript's built-in DOM manipulating capabilities as far as possible. Don't just find the .title elements, but traverse their text nodes instead and apply the replacement only to those.


text:
Q: getting Failed to load map. Error contacting Google servers I read all the post concering this issue and yet I wasnt able to solve it on my mechine.
I allways get:
06-23 20:04:30.011: E/Google Maps Android API(6623): Failed to load map. Error contacting Google servers. This is probably an authentication issue (but could be due to network errors).

when getting to the map activity.
my code:
    <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.mobwal"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="14" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <permission android:name="com.mobwal.permission.MAPS_RECEIVE" android:protectionLevel="signature"/>
    <uses-permission android:name="com.mobwal.permission.MAPS_RECEIVE"/>
    <uses-permission android:name="com.google.android.providers.gsf.permissions.READ_GSERVICES"/>

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/logo1small"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.NoTitleBar" >

        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="KEYFROM GOOGLES CONSOLE" />

        <activity
            android:name=".FacebookStart"
            android:label="@string/app_name"
            android:windowSoftInputMode="adjustResize" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name="com.facebook.LoginActivity"
            android:label="@string/app_name"
            android:theme="@android:style/Theme.Translucent.NoTitleBar" />

        <meta-data
            android:name="com.facebook.sdk.ApplicationId"
            android:value="@string/facebook_app_id" />

    </application>

</manifest>

I got my SHA1 fingerprint from eclipse preferences and it is the same as I had using key tool. the thing is that I had two .android folders(one on C:\Users\user_name.android and on my android sdk folder) I delete the one on the user's after trying to activate my app using it (without success and now it is not recreated) so I got left only with the one under my android sdk folder which is not helping much.
I need help I tried almost anything.

A: Go to https://code.google.com/apis/console
Once logged in, go to Services > Google Maps Android API v2 and switch on this toggle button.
Careful: it's "Google Maps Android API v2" and not "Google Maps API v2".

A: For those to whom none of the answers work, in my case the problem was, that there was another android app key registered for the same package name on another account's console, so the maps api was finding that, and failed to authenticate me (obviously). As soon as that has been removed (and the fingerprints added to the one I was using) after removing and installing the app again on the phone everything started to work.

A: This is keystore issue on 99%.
1) I use for release and debug the same file debug.keystore which I copy from C:/Users/EEfimenko/.android/debug.keystore to C:\Users\EEfimenko\Android\MyApp\app folder for access directly like to debug.keystore without C:/Users/... link
2) Then I add point to it from build.gradle(Module: app) file inandroid`:
signingConfigs {
    debug {
       storeFile file('debug.keystore')
     }
    release {
       storeFile file('debug.keystore')
     }
}

3) Run keytool -list -v -keystore debug.keystore command from cmd from C:\Users\EEfimenko\Android\MyApp\app folder and mix resulted SHA1 fingerprint with name of applet: FR:TY:CG.....YF:ER;com.myapp.nameofit
4) Go to https://code.google.com/apis/console/b/0/?noredirect to:
a) Services and enable "Google Maps Android API v2" to ON state
b) Put FR:TY:CG.....YF:ER;com.myapp.nameofit in "API Access" like Create new Android Key
Now you can see your map with key again like at beginning without key!:)

A: I tried to do almost everything like generating the key for 20 times, changing the order of the permissions, but there is nothing batter than just removing the project from workspace and importing it back again.

A: Problem is: work without key, but doesn't work with it, because you touch "app" file by your hand from editor. You must edit it and make changes only from: File -> Project structure

A: You need to find file \app\src\release\res\values\google_maps_api.xml
in your project and place there your Google API KEY because Android Studio show you only google_maps_api.xml from debug folder for debug version. Than all will work and map will show not only in debug mode;)


text:
Q: What is the difference between "I like hearing the song" and "I like listening to the song"? What is the difference between the following sentences?

I like hearing the song.
I like listening to the song.

I am sure that both sentences are valid but can't quite see the difference. Does the first imply that I like it when someboy else play the song?

A: In your question, it does not matter who is causing the sound.

I like hearing the song

has the feeling that it's background music which you are aware of but not concentrating on, somewhat passive, whereas

I like listening to the song

has the feeling that you are paying close attention to the song, like the lyrics, much more active.
Additional context is usually added to avoid ambiguity.

When I hike through the woods I can hear the birds singing, but I listen for the spotted owl's call.

A: Listening means paying attention to what someone is saying and hearing also means someone telling you something that is not important to you but because you don't leave that person you just stand to hear what he or she is saying

A:
Does the first imply that I like it when somebody else plays the song?

Yes, but it is okay to use listening to in that situation.
As you said both sentences are correct.
But I prefer to use listening to the song.


text:
Q: How to set semi-transparent image to Shell background? I am developping an SWT application, and  I want to give the application a background png,but setBackgroundImage is not support transparent. Is there any way to solve the problem? There are some semi-transparent pixels , I wish to see desktop on these positions.
ps  the shell is no-trim style

A: Have you tried looking around on the net? I found this, think it should help you
http://git.eclipse.org/c/platform/eclipse.platform.swt.git/plain/examples/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet180.java
You can also refer here for some more examples which can help you later on
http://www.eclipse.org/swt/snippets/


text:
Q: Problem requesting Bearer Token with Java HTTPRequest I try to receive a bearer token from salesforce to access the API but I got stucked.
My Request looks like
    HttpURLConnection con;
    con = (HttpURLConnection) obj.openConnection();
    if (con instanceof HttpsURLConnection)
    {
        Logger.log("HTTPS Post Request: " + authURL);
        ((HttpsURLConnection) con)
                .setHostnameVerifier(new MyHostNameVerifier());
    }

    String body = "grant_type=password" +
            "&username=" + user +
            "&password=" + password +
            "&client_id=" + client +
            "&client_secret=" + secret;

    // add request header
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
    con.setRequestProperty("user-Agent", "PostmanRuntime/7.3.0");
    con.setRequestProperty("Accept", "*/*");
    con.setRequestProperty("Cache-Control", "no-cache");
    con.setRequestProperty("Host", apiHost);
    con.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
    con.setRequestProperty("Connection", "keep-alive");
    con.setRequestProperty("Content-Length", "" + body.length());

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());

    wr.writeBytes(body);
    wr.flush();
    wr.close();

getting the response:
    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

    String inputLine;
    StringBuilder response = new StringBuilder();

    while ((inputLine = in.readLine()) != null)
        response.append(inputLine);

    return response.toString();

If I use this code with another API (not salesforce) it works absolutely perfect but on salesforce I got some strange binary response looking like
1FEFBFBD 08000000 00000000 5DEFBFBD 4F73EFBF BD3010EF BFBD3F4B EFBFBDEF BFBD4240 05EFBFBD 4C0F2842 EFBFBD1F EFBFBD2A 457AEFBF BD6442EF BFBD016C 1210EFBF BDEFBFBD 776FEFBF BDEFBFBD 71EFBFBD EFBFBDEF BFBDEFBF BDEFBFBD EFBFBD5E 34EFBFBD 311102EF BFBDEFBF BD484A6D EFBFBD01 EFBFBDEF BFBD7D70 2B7F576F 1FEFBFBD EFBFBDEF BFBDEFBF BD2E184C EFBFBDEF BFBD2C0E EFBFBDEF BFBD6076 EFBFBD7C 1AEFBFBD EFBFBDEF BFBDEFBF BD24EFBF BD606756 EFBFBD64 73EFBFBD EFBFBDEF BFBDEFBF BD45421C EFBFBDEF BFBDEFBF BD761570 23EFBFBD EFBFBDEF BFBDEFBF BD0E6EEF BFBDEFBF BDEFBFBD 2CEFBFBD 650037EF BFBD42CA B65A3665 0032EFBF BDEFBFBD 5CEFBFBD EFBFBD27 EFBFBDEF BFBD42EF BFBD1213 5873EFBF BD36C8A5 3CEFBFBD EFBFBD61 642427EF BFBDEFBF BD1C234E 7AEFBFBD EFBFBDEF BFBDEFBF BD0F32EF BFBDEFBF BDEFBFBD 0562447C 551C131D 57EFBFBD EFBFBD20 EFBFBD27 EFBFBD44 C8BB11EF BFBDEFBF BDEFBFBD EFBFBD5D EFBFBD1B 2B3404DD 8DEFBFBD EFBFBDEF BFBD2E73 EFBFBD50 79EFBFBD EFBFBD00 657722EF BFBD7342 5436EFBF BD260851 EFBFBD14 22EFBFBD EFBFBD69 EFBFBDEF BFBD65EF BFBDEFBF BDEFBFBD EFBFBDEF BFBD3BEF BFBD2768 562259EF BFBD383E EFBFBD2C 61E8A388 57EFBFBD 0760EFBF BD7B5F46 EFBFBDEF BFBD3DEF BFBD4C0B 4C47357B EFBFBD06 EFBFBD3E EFBFBD5E EFBFBDEF BFBD3F03 2B50007D 010000

So I also fetch the response header and all looks good for me
20201021 08:05:04 Request SM Token
20201021 08:05:04 Get token
20201021 08:05:04 HTTPS Post Request: https://xxxxx/oauth2/token
20201021 08:05:05 Message: OK
20201021 08:05:05 Transfer-Encoding
20201021 08:05:05 chunked
20201021 08:05:05 X-ReadOnlyMode
20201021 08:05:05 false
20201021 08:05:05 Public-Key-Pins-Report-Only
20201021 08:05:05 pin-sha256="9n0izTnSRF+W4W4JTq51avSXkWhQB8duS2bxVLfzXsY="; pin-sha256="5kJvNEMw0KjrCAu7eXY5HZdvyCS13BbA0VJG1RSP91w="; pin-sha256="njN4rRG+22dNXAi+yb8e3UMypgzPUPHlv4+foULwl1g="; max-age=86400; includeSubDomains; report-uri="https://xxxx/hpkp-report/00D4F00000018vXm";
20201021 08:05:05 Date
20201021 08:05:05 Wed, 21 Oct 2020 08:05:05 GMT
20201021 08:05:05 X-Robots-Tag
20201021 08:05:05 none
20201021 08:05:05 Strict-Transport-Security
20201021 08:05:05 max-age=31536002; includeSubDomains
20201021 08:05:05 Cache-Control
20201021 08:05:05 no-cache,must-revalidate,max-age=0,no-store,private
20201021 08:05:05 X-B3-SpanId
20201021 08:05:05 c337af7bac4552ae
20201021 08:05:05 Content-Encoding
20201021 08:05:05 gzip
20201021 08:05:05 X-B3-Sampled
20201021 08:05:05 0
20201021 08:05:05 Vary
20201021 08:05:05 Accept-Encoding
20201021 08:05:05 Set-Cookie
20201021 08:05:05 BrowserId=IQs6KxN0EeuvcP-sSWqJZQ; domain=.xxx.com; path=/; expires=Thu,21-Oct-2021 08:05:05 GMT; Max-Age=31536000
20201021 08:05:05 X-B3-TraceId
20201021 08:05:05 c337af7bac4552ae
20201021 08:05:05 Expires
20201021 08:05:05 Thu, 01 Jan 1970 00:00:00 GMT
20201021 08:05:05 Content-Type
20201021 08:05:05 application/json;charset=UTF-8
20201021 08:05:05 Expect-CT
20201021 08:05:05 max-age=86400, report-uri="https://a.forcesslreports.com/Expect-CT-report/00D4F00000018vXm"

Doing the same request with Postman or CURL is working fine.
Anyone has an idea how I can go further here?

A: Finally I could find out, that the response body is zipped (Which is shown in the Headers at all. So my fault I didn't see that). When I unzip the response body everything works fine.
Nevertheless I wonder if a tool like Postman or curl is autodetecting that and unzipping the body before showing it to the user?
Or is there any "flag" I can set to force the auth server not to zip the response body?

A: Check the Postman headers and compare them to the Request properties in your code. The problem might be this line:
    con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

try this instead:
    con.setRequestProperty("Content-Type", "application/json");


text:
Q: How to play an mp3 file in java I am trying to play a song (mp3 file) in java. I have been looking around for a few hours now and none of the ways I found worked properly.
public void play()
{
    String song = "song.mp3";
    Media track = new Media(song);
    MediaPlayer mediaPlayer = new MediaPlayer(track);
    mediaPlayer.play();
}

I have tried doing that but it gives me errors.
I have imported JMF and JLayer.
I have also read other questions that are like this one on this forum and none of them have helped me.
I just need a hand to help play an mp3 file.

A: The easiest way I found was to download the JLayer jar file from http://www.javazoom.net/javalayer/sources.html and to add it to the Jar library http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29
Here is the code for the class
public class SimplePlayer {

public SimplePlayer(){

    try{

    FileInputStream fis = new FileInputStream("File location.");
    Player playMP3 = new Player(fis);

    playMP3.play();

    }catch(Exception e){System.out.println(e);}
}

}

and here are the imports
import javazoom.jl.player.*;
import java.io.FileInputStream;

A: For this you'll need to install Java Media Framework (JMF) in your PC. One you have it installed,then try this piece of code:
import javax.media.*;
import java.net.*;
import java.io.*;
import java.util.*;
class AudioPlay
{
 public static void main(String args[]) throws Exception
 {

 // Take the path of the audio file from command line
 File f=new File("song.mp3");

 // Create a Player object that realizes the audio
 final Player p=Manager.createRealizedPlayer(f.toURI().toURL());

  // Start the music
  p.start();

  // Create a Scanner object for taking input from cmd
  Scanner s=new Scanner(System.in);

  // Read a line and store it in st
  String st=s.nextLine();

   // If user types 's', stop the audio
   if(st.equals("s"))
   {
   p.stop();
   }
 }
}

You may run into unable to handle formaterror, that is because Java took out the MP3 support by default (pirate copyright issue), you are required to install a "JMF MP3 plugin" in order to play MP3 file.
Go Java's JMF website to download it
http://java.sun.com/javase/technologies/desktop/media/jmf/mp3/download.html
To be sure that you are using a supported format file, check here:
http://www.oracle.com/technetwork/java/javase/formats-138492.html
If you are using windows7, you may have to read this as well:
https://forums.oracle.com/forums/thread.jspa?threadID=2132405&tstart=45

A: How about JavaFX application-
import java.net.URL;
import javafx.application.Application;
import javafx.scene.media.Media;
import javafx.scene.media.MediaPlayer;
import javafx.stage.Stage;

public class VLC extends Application {
    void playMedia() {
        String mp3 = "00- Tu Hi Mera.mp3";
        URL resource = getClass().getResource(mp3);
        System.out.println(resource.toString());
        Media media = new Media(resource.toString());
        MediaPlayer mediaPlayer = new MediaPlayer(media);
        mediaPlayer.play();
    }
    public static void main(String args[]) {
        new VLC().playMedia();
    }
    @Override
    public void start(Stage stage) throws Exception {
    }
}


text:
Q: How to receive data MQTT on AWS I have an external service that sends me data via MQTT. I need to receive this data on AWS then process it and then write it to an RDS instance. What services are recommended for this purpose? An Amazon MQ and a Lambda? A SQS and a Lambda? Any other?
Thanks for any help.

A: AWS IoT 'things' have a Message Broker that supports MQTT.

Traditionally, IoT and MQTT involves huge numbers of messages, which are normally stored in DynamoDB. However, you could write an AWS Lambda function to store the received messages in an Amazon RDS database.