text:
Q: SSRS & SharePoint 2013 Does SSRS need to be installed on a separate server in a SharePoint 2013 production Farm?
If so what are the licensing implications for SQL Server?

A: Does SSRS need to be installed on a separate server in a SharePoint 2013 production Farm?

*

*From Performance perspective , it's recommended to install SSRS SharePoint integrated mode to a sperate SharePoint server then join it to the farm.

*From Design Perspective , SSRS SharePoint integrated Mode must be installed on the server that has SharePoint.

*From Cost Perspective , you can install it on the current SharePoint Servers and scale up the servers specification to avoid the performance issue rather than scale out a new server with an additional SharePoint License that leads to additional cost.
What are the licensing implications for SQL Server?
It's excluded from DB installation license and it requires SSRS SQL Server license on your SharePoint Server.

A: From a performance perspective, ideally SSRS runs on one or more FEs. This prevents user requests to SSRS from leaving the SharePoint FE. This may increase system requirements on the FE, however.
From a licensing perspective, you must license each SSRS instance installed with a SQL Server BI User CALs or SQL Server Enterprise CAL. This means if you have a SQL Server Database Engine for SharePoint on SQLSERVER1, an SSRS integrated with SharePoint on SPSERVER1 and SPSERVER2, you would need 3 SQL Server licenses.


text:
Q: Angular 9 force async pipe nested in ngIf async pipe <ng-container *ngIf="condition$ | async">
    {{ value$ | async }}
</ng-container>

How can I force the view to display latest value when condition$ emits true after false ?

Update
condition$ and value$ are both derived from the same formGroup.valueChanges and cannot be instances of BehaviorSubject.

A: What about combining those two and having one observable and subscription like this.
.ts
this.viewObservable$ = combineLatest(
      this.condition$,
      this.value$
    ).pipe(
      map(([condition, value]) => {
        return {
          condition,
          value
        }
      })
    )

and in your .html you can do this
<ng-container *ngIf="(viewObservable$ | async) as data && data.condition">
  {{ data.value }}
</ng-container>

Does this help?

A: You can do that by adding a shareReplay on your value$ observable:
<ng-container *ngIf="condition$ | async">
    {{ value$ | async }}
</ng-container>

value$ = obs$.pipe(
  shareReplay(1)
);

Or by using a BehaviorSubject or ReplaySubject

A: you can do as follow to prevent inner subtraction form unsubscribing
<ng-container *ngIf="{val: value$ | async} as source">
  <div *ngIf="condition$ | async">
   {{ source.val }}
  </div>
</ng-container>

example

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mariadb match against a view fails; succeeds in MySql The fulltext search query below fails in mariadb, but succeeds in mysql (mariadb database imported from mysql database using phpmyadmin).
If a base table is substituted, the query succeeds in both mariadb and mysql. So apparently mariadb cannot match against views.
Is there a solution to this? It's messing up my migration.
Thanks.
SELECTTitle FROM Nodes_View WHERE (MATCH(Title,Caption,Description,Location,Body) AGAINST('something'))


text:
Q: Is it possible to create a playback session with multiple groups? I would like to use the Sonos API to control which groups play music simultaneously (just like how you can select multiple groups to play music in the Sonos app). Is this possible? The createSession command looks like it only takes one groupId.

A: Yes, look at the groups namespace. Specifically, the createGroup command, using the musicContextGroupId parameter, which should contain the group that has the audio to use.


text:
Q: Git: How do I merge complex branches that have widely diverged with some missing history? I have two "branches", both of which started from the same code base, but both of which were imported to git after they diverged.  The prior history is lost, and additionally both branches have extensive changes recorded in their git history.
What is a good strategy to approach merging features and bugfixes between these two branches in a manageable way?
Is there a tool that will assist me in separating differences in the original imports into meaningful commits?

A: Sounds like you want to keep the history. I would use rebase --onto with --preserve-merges to move features/bugs to the branch you want to continue using. If they sit in a different structure for some reason, make a new branch then do a filter-branch with the tree operation to make the structure the same. Then rebase --onto --preserve-merges as you would in the first scenario.
Hope this helps.


text:
Q: PyParsing's searchString with StringStart() and StringEnd() I'm trying to make the following tests pass:
from pyparsing import Word, nums, StringStart, StringEnd
import pytest

def get_square_feet(string):
    area = Word(nums+",")("area").setParseAction(lambda s, l, t: [int(t[0].replace(',', ''))])
    expression = StringStart() + area + "sqft" + StringEnd()
    return expression.parseString(string).get("area")

def test_get_square_feet():
    assert get_square_feet("800 sqft") == 800
    assert get_square_feet("9,000 sqft") == 9000

def test_get_square_feet_with_prefix():
    assert get_square_feet("size: 12,000 sqft") is None

if __name__ == "__main__":
    pytest.main([__file__])

However, the second tests fails because it leads to a ParseError. Instead, I'd like use searchString, but if I replace parseString by searchString in the get_square_feet function I also get an error because the function returns None. Can someone point out to me what is wrong here?

A: Here is the corresponding code using pyparsing, catching the ParseException:
from pyparsing import Word, nums, StringStart, StringEnd, ParseException

def get_square_feet(string):
    area = Word(nums+",")("area").setParseAction(lambda s, l, t: [int(t[0].replace(',', ''))])
    expression = StringStart() + area + "sqft" + StringEnd()
    try:
        return expression.parseString(string).get("area")
    except ParseException:
        return None

A: Here is a solution that uses parsy, which is like pyparsing in many ways but with a nicer interface and implementation IMO.
from parsy import regex

def get_square_feet(s):
    area = regex(r'[0-9,]+').map(lambda s: int(s.replace(',', '')))
    return (area << string(" sqft") | regex('.*').result(None)).parse(s)

Here we use the | combinator to fallback to a regex that accepts anything, but then produces None as required. You could also implement it by catching the ParseError exception and returning None in that case.

A: Here is an implementation of get_square_feet which passes the tests using regular expressions:
def get_square_feet(string):
    match = re.match(r'^([\d,]+) sqft$', string)
    return int(match.groups()[0].replace(',', '')) if match else None

In principle, PyParsing should be easier to use than regular expressions, so I'm still interested in a solution using PyParsing.


text:
Q: Getting Firefox´s History (places.sqlite) with PowerShell i need powershell script (or help) for exporting data from places.sqlite in Mozilla Firefox. Also DATE from moz_historyvisits (from unixepoch to localtime), URL and TITLE (only with text, no blank) from moz_places to txt file with ;$ separator (date;$url;$title).
Export - for every launching of Firefox adds only new rows or missing or deleted links in txt file ((date;$url;$title). Thank You.

A: Here's a way to pipe csv from sqlite to powershell.  You can also google loading an sqlite library in powershell.  http://ramblingcookiemonster.github.io/SQLite-and-PowerShell/
sqlite3 -csv -header places.sqlite "select datetime(moz_historyvisits.visit_date/1000000, 'unixepoch', 'localtime') as datum, moz_places.url, moz_places.title from moz_places, moz_historyvisits where moz_places.id = moz_historyvisits.place_id and moz_places.title like '%' order by datum" |
  convertfrom-csv | select -last 3 | fl

datum : 2017-07-16 09:55:36
url   : http://www.microsoft.com/getsilverlight/get-started/install/default
title : Get Silverlight | Microsoft Silverlight

datum : 2017-07-16 09:55:57
url   : https://download.microsoft.com/download/0/3/E/03EB1393-4F4E-4191-8364-C641FAB20344/50901.00/Silverlight.dmg
title : Silverlight(1).dmg

datum : 2017-07-16 09:58:14
url   : https://channel9.msdn.com/Blogs/Charles/Scott-Hanselman-amp-Jeffrey-Snover-Discuss-Windows-PowerShell
title : Scott Hanselman & Jeffrey Snover Discuss Windows PowerShell | Charles | Channel 9


text:
Q: Combining Multiple SVG Transformations I'm new to Snap.svg and SVG and experimenting with transformations (an illustraiting plunk can be found here). Basically I'm trying to move, scale and rotate a shape according to its configuration. This is what I've found out so far:

*

*rotating around a point is possible with rotate(angle, x, y)

*there is no direct transform method to scale around a point but it can be done as described in "SVG Essentials"

However combining these transforms doesn't give me the expected result - my expected calculated center of the shape differs from the rendered one. Can anyone give me some pointers on how to correctly put these transforms together?
Regards,
Andi

A: To combine transforms, I would use Snaps own transformString format. I would first have a read of my previous answer on SO here, this is slightly different so posting a slightly different example and answer.
Whilst Snap can use SVGs transform strings (rotate() scale() transform()). They don't by default centre around itself for example, whereas Snaps (and Raphaels) do. This makes it a bit easier. For more complex situations, one may need to look into Matrix methods, but I think the following should be ok...
Snaps transformString uses string t (transform), s (scale), r (rotate), and you can add them repeatedly if wanted.
Here is an example of both methods, to highlight the difference.
jsfiddle here
s = Snap(400, 620);

var r1 = s.rect(0, 0, 100, 100).attr({
    fill : 'blue',
    stroke : 'black',
    opacity: 0.5
});
var r2 = r1.clone().attr({ fill: "red" });

r1.transform('t100,100s2,2r45');   //typical Snap way, rotation/scale around centre
r2.transform('translate(100,100) scale(2,2,) rotate(45)');   //SVG way

The getBBox() method should be pretty reliable as far as I know (maybe post up a separate question on SO if you find an example where it is wrong)


text:
Q: Printing PDFs with Puppeteer/Playwright and Flexbox Layouts If you open Chrome or Edge and visit a page with a flexbox layout, like this one, and choose Print/Save as PDF, the PDF includes the flex elements in the proper location. However, if you use Playwright and the Page object's pdf() method, flex elements are missing.
I'm fairly certain this isn't a bug with Playwright, or Puppeteer, but instead is an issue with how the headless chromium creates the pdf. Or, hopefully, it's some kind of option I'm missing somewhere. Does anyone have experience creating PDFs of pages with flexbox layouts using Playwright?

A: I had a similar issue where the height of the elements inside my flexbox was completely wrong in Puppeteer.
I was able to solve it by using display: inline-flex instead of display: flex


text:
Q: Esconder tudo menos o elemento clicado Tenho um script que faz o toggle em uma DIV,quando o icon e clicado a div fara o toggle, os demais DIVS ficaram fechados, inicialmente usei o accordian do Jquery, entretanto não foi útil, pois o parentesco e quebrado devido a uma div de titulo, preciso comportamento se mantenham so na div em questao.
     $(".taskIcon").on("click", function () {
                var taskElementDetail = $(".taskDetail");
                taskElementOthers = taskElementDetail.parent().siblings().not(taskElementDetail);

                taskElementOthers
                    .hide();
                taskElementDetail
                    .show();
            });

        <div class="panel-group" <%--id="accordion"--%>>

               Titulo

                        descricao

                        <a <%--data-toggle="collapse" data-parent="#accordion" href="#collapse1--%>">

                <div class="panel-collapse collapse taskDetail clearfix" <%--id="collapse1"--%>>

                           detalhes

                           descricao

                <div class="panel-collapse collapse taskDetail" <%--id="collapse2"--%>>

                          descricao

                            <input type="text" class="form-control" placeholder="Observacao">

               Titulo

                        descricao

                        <a <%--data-toggle="collapse" data-parent="#accordion" href="#collapse1--%>">

                <div class="panel-collapse collapse taskDetail clearfix" <%--id="collapse1"--%>>

                           detalhes

                           descricao

                <div class="panel-collapse collapse taskDetail" <%--id="collapse2"--%>>

                          descricao

                            <input type="text" class="form-control" placeholder="Observacao">

A: Acho que você está dificultado sua vida sem necessidade, tente classicar os elementos que deseja ocultar ou exibir, e utilize o $(this) para identificar o que foi clicado.
Entenda como funciona o this e qual sua diferença para $(this) do jquery.
Segue abaixo um exemplo:

//Ao clicar no elemento de classe detalhe entrará na função
$(".detalhe").on("click", function () {

    //Oculto todos elementos da classe grupo
    $(".grupo").hide();

    //Exibo o elemento da classe grupo mais proximo do clicado
    $(this).closest('.grupo').show();
});
.grupoFilho {
  border: 1px solid;
}

        Clique aqui para visualizar somente este grupo

blablabla - 1

        Clique aqui para visualizar somente este grupo

blablabla - 2

        Clique aqui para visualizar somente este grupo

blablabla - 3

A: Editei seu código pois como você deseja um funcionamento diferente do que o bootstrap oferece é melhor remover os atributos data-toggle, data-parent e href dos links.
Segue um exemplo do seu código editado e funcionando.
Para resolver foi necessário utilizar o $(this) do jQuery que é o elemento que está envolvido no evento quando existem muitos elementos com o mesmo seletor, que no seu caso foi o $('.taskDetail').
Foi necessário também selecionar a div que estava fora da div do ícone, por isso utilizei o closest.

$(".taskIcon").click(function () {
  $('.taskDetail').hide();
  $(this).closest('div').next('div').show();
});
.taskDetail {
  display: none;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

         Titulo

            descricao

               detalhes

               descricao

              descricao

              <input type="text" class="form-control" placeholder="Observacao">

         Titulo

            descricao

               detalhes

               descricao

              descricao

              <input type="text" class="form-control" placeholder="Observacao">


text:
Q: Minimum and Maximum temperature for a copper wire to work? Is there a minimum and maximum temperature that a copper wire/s will still work on. Meaning that current will still be able to go through them.  Let's say that I have battery that is heated or cooled depending on the environment, and that battery controls a light, that is also heated or cooled, and the wires connecting it are exposed to cold or hot environment. Is there a specific temperature, max / min, that will ensure that current still passes through the wires. I know this might depend on the size of the copper wire, and the specific gauge, but I am considering wires between 18 and 26 AWG. I also figured out that the melting point of cooper is about 1,085 °C, therefore that will in theory be the maximum temperature that a copper wire will be able to operate, I assume. And I am not sure about the minimum temperature.

A: 0 K to 1358.15 K
-273.15 °C to 1085 °C
-459.67 °F to 1984 °F
You can operate at higher temperatures if you can keep the wire-shaped puddle of molten copper where you need it, but it's usually easier to use platinum wire at that point. (2041 K, 1786 C, 3215 F) and tungsten after you can't use platinum any more (3695 K, 3422 C, 6191 F)
Insulated wires are a bit of a problem at extreme temperatures as insulation tends to melt, burn, or become brittle and crack.

A: Wire temperature limits sets first for safety reasons then to ensure circuit operation.
First priority is the insulation protection, not only in the particular cycle of operation (melt etc), but also in long term operation. Insulation degrade each time that the temperature over the specs maximum temperature, shorten their life.
Second is to prevent surrounding materials ignition. Hay for example ignites very easily.
IEC sets as maximum temperature increase the 35 degr Celsius above the environment temperature, which is can taken roughly to around 40 degr. C.
The environment (clima etc, earth/space), the orientation, the encapsulation, the operation cycle (ON/OFF period), the installation place characteristics (in-house, open-air, buried etc) of the conductor plays important role.
As an example in normal operation and for copper magnet wire (formvar coated), the above temperature limit for AWG18 reached when 10A passing the conductor and for AWG26 is 2.8A. However in adiabatic conditions (i.e short-circuit) current reduced to 3.5A for #18 and 0.9A for #26 (bare) suspended on air. In case of coil temperature increase and new calculations should be done.

A: The resistance of the wire changes with temperature. There is a given temperature coefficient of resistance for every material. For copper, it is 0.0039/°C. The new effective resistance of the wire is calculated by (deltaR)/(Ro)=(temperature coefficient of resistance)*(deltaT). So, if you know the resistance of the wire at ambient temperature, you can calculate its change in resistance at various temperatures. This will help you decide what size wires you need for a given temperature, or if the temperature is feasible at all.

A: So Copper melts at 1083°C.  But that has absolutely nothing to do with Minimum and Maximum temperature for a copper wire to work as a conductor.
Both are determined by the insulation and jacket materials.  Insulation breaks down if ambient temperature goes above 100°C.  The insulation goes through irreversible chemical changes and starts to burn typically causing fires.  Even if you have a jacket which is HOFR (Heat, Oil and Flame Retardant), XLPE and EPR, as insulation, act as wicks for fire and will spread a fire throughout the structure.
It is ultimately why residential wire insulation is colored white.  Discoloration means the wire has gotten to hot and the full wire must be replaced.  The portion that has burned is no longer an insulator, which means it is becoming a conductor.
Maximum

*

*PVC 75°C

*XLPE/EPR 85°C

*Silicon 95°C

These maximums are one of the factors which must be taken into account when derating maximum current for a given wire size and insulation material.
Minimum

*

*PVC -55°C

*XLPE -40°C

*EPR -60°C

*Silicon –80°C

Insulation becomes brittle below minimum.  Not a problem if you are dealing with buildings.
So copper will not melt at 200°C, but it is not much of a conductor if the insulation catches on fire.
Insulation and Jacket Materials


text:
Q: Is the following sentence correct? Is the following sentence right?
"There's a table stands in the corner."

A: It's unusual in modern speech, but you occasionally see this pattern in literature. It's as if "that" had been left out; the sentence can be understood as "There's a table [that] stands in the corner." Or you could think of "There's a table" as a way to say "that table". "That table stands in the corner."
There are many other cases where words can acceptably be left out of a sentence. A real linguist could tell you the name of this phenomenon, and its history, and other related or unrelated facts.

A: Syntactically, the only thing "not quite right" about OP's example is that a relative pronoun (that, who, which,) has been dropped.
As others have pointed out, in some cases this might be done for reasons of prosody/scansion in a "poetic" context (e.g. - Hamlet, Act IV, Scene 7: There is a willow grows aslant a brook). But in other contexts it's a perfectly natural "relaxed speech" usage...

"There's a man at the door [who/that] wants to speak to the lady of the house"

Having said that, my advice to non-native speakers would be not to discard the relative pronoun. The usage won't always work in either the "poetic" or the "colloquial" register - but it usually has to be interpreted as one or the other, and if you're not already confident which way your audience will see it, there's a good chance you'll get it wrong.

A: No, the sentence is incorrect. It looks like it can't decide on a main verb:

*There is a table stands in the corner.

Interestingly, the subject of both verbs is "a table." Compare the following correct sentences:

There is a table.
A table stands in the corner.

The second conveys all the information in your original incorrect sentence. There is no reason to use the preparatory subject "there" when the subject - i.e. the table - is already doing something. That is, you don't need to introduce it's mere existence (with "There is") if we understand it exists by virtue of the fact that it's standing in the corner.
However, we do sometimes introduce something's existence and give additional information, in which case we must subordinate the additional information, thus:

There is a table that stands in the corner.

Unfortunately, that sentence sounds somewhat stilted, and I believe a much more common utterance would be:

There is a table standing in the corner.


text:
Q: SQLQuery works on SQLite browser but not Qt5.11.2 Following command works for the sqlite browser, not sure why it fail with Qt5.11.2
    using namespace edatabase;

    QSqlQuery query;
    QString const command("with ab as (select a.* from recorded_face_whitelist_log a union all select "
                          "b.* from recorded_face_log b)SELECT ID, FaceID, Image FROM "
                          "(SELECT ab.*,ROW_NUMBER() OVER (PARTITION BY FaceID ORDER BY DATE DESC, TIME DESC) "
                          "as seqnum FROM ab) ab WHERE seqnum = 1 ORDER BY Date DESC, Time DESC LIMIT 5");
    //query.prepare(command);
    query.exec(command);

    if(!query.lastError().isValid()){
        //do something
    }else{
        QLOG_DEBUG()<<__func__<<query.lastError()<<"\ncommand:"<<command;
    }
}

Error message:
QSqlError("1", "Unable to execute statement", "near "(": syntax error")
How could I solve this bug?Thanks
Edit : I copy the command print by the QLOG_DEBUG to the sqlite browser, it works. The command do not has any special characters, so I should not need any "\", weird.


text:
Q: Is there any reason *to* upgrade the biochip in Deus Ex:HR? I know the reason not to upgrade the biochip, but is there any way upgrading the biochip will help you?

A: Yes. It prevents the glitch from occurring.

A: No. There are no upsides or benefits to upgrading - at all.
The purpose of this "upgrade" is to allow the Illuminati direct control over everybody with cybernetic augmentations by granting the ability to shut down a users' cybernetics remotely.
Visiting the LIMB clinics to get this upgrade will allow your augmentations (including your HUD) to be disabled, most notably during the Jaron Namir encounter.
The creation of this glitch is what is actually being discussed during the opening scene;

"I have spoken with Montreal. The broadcast satellites are ours when we need them. A few weeks of discomfort, and the public will be primed for our recall."

Additionally, there are several emails that you can find throughout the later stages of the game that discuss the creation of the glitch.


text:
Q: How to make jar file from command prompt I have been trying making jar file for my gradle project but always found error
could not find or load main class CalculatorServer
My compile (.class) files are in the following path in windows file system
D:\Projects\EclipseProjects\CalculatorGRPC\build\classes\main\com\grpc\calculator
When i trying to create jar file for Main class e.g CalculatorServer using folloiwng command
D:\Projects\EclipseProjects\CalculatorGRPC\build\classes\main\com\grpc\calculator>java -cp test.jar com.test.calc.CalculatorServer
Following error occur
could not find or load main class CalculatorServer
Edit
Sorry I have posted wrong commands here.
My command for creating jar file is as follows
D:\Projects\EclipseProjects\CalculatorGRPC\build\classes\main\com\grpc\calculator> echo Main-Class: CalculatorServer >manifest.txt
D:\Projects\EclipseProjects\CalculatorGRPC\build\classes\main\com\grpc\calculator>jar cvfm CalculatorServer.jar manifest.txt *.class
When i run this jar file
`D:\Projects\EclipseProjects\CalculatorGRPC\build\classes\main\com\grpc\calculator>java -jar CalculatorServer.jar

Getting same error
could not find or load main class CalculatorServer

A: You are in the wrong directory. No matter what are you trying to do, as long as that operation involves compiled class files, you should be in the output root, which is the XXXXX\build\classes\main folder.
The reason for this is that java classloaders
will try to find /com/foo/Bar.class in the jar if it is ordered to load class named com.foo.Bar. If you just pack a jar like that, the jar tool will place your classes right in the root directory of the output archive(you can confirm this by using a archive tool like 7z to investigate), which panic the classloader and gives you an error.
By the may, manifest should be named MENIFEST.MF adn placed under /META-INF directory, or same error would pop up again, if your manifest was written in a correct format.
PS: Why the heck you are doing these all by your bare fist? This is what gradle is supposed to do, or why is it called build automation? There should be your desired jar files somewhere under the /build/ directory, typically /build/lib/.


text:
Q: nftables named sets that match network prefixes though filter or variables I want to match a set of networks.
Anonymous sets works fine, but I want to create prefix set to reuse it when needed.
nft add set filter AllowedSSH { type ipv4_addr\;} // type for addreses
nft add element filter AllowedSSH { 10.0.0.0/8 } // not working
nft add element filter AllowedSSH { 10.0.0.1 } // works by IP

What correct type of filter I should use to perform this action?
Variables style don't work too:
nft define networks = { 10.0.0.0/8 }
nft add rule ip filter input ip saddr $networks tcp dport 22 accept
Error: syntax error, unexpected dport, expecting end of file or newline or semicolon
add rule ip filter input ip saddr tcp dport 53 counter accept
                                  ^^^^^

NFT version:
[root@foo ~]# nft -v
nftables v0.8 (Joe Btfsplk)

Thanks in advance.

A: If you want add the prefixes into the set, you should specify the interval flag.
In your example it will be look like:
nft add set filter AllowedSSH { type ipv4_addr\; flags interval\; }
nft add element filter AllowedSSH { 10.0.0.0/8 }
nft add element filter AllowedSSH { 192.168.0.0/24 }

nft list set filter AllowedSSH
table ip filter {
    set AllowedSSH {
        type ipv4_addr
        flags interval
        elements = { 10.0.0.0/8, 192.168.0.0/24 }
    }
}


text:
Q: How to filter the ManyToMany of a queryset in django I have two models, questions and their answers, and I want to fetch ALL questions along with a single answer to them, i.e, the answer which has the maximum count of upvoters for that question. How do I fetch this result in a Queryset(I'll be paginating the result so having a queryset will ease the process)
class Question(models.Model):
    question = models.CharField(max_length = 128)
    asker = models.ForeignKey(CustomUser, on_delete = models.CASCADE, related_name="asked_questions")
    requested = models.ManyToManyField(CustomUser, related_name="answer_requests")
    followers = models.ManyToManyField(CustomUser, related_name="followed_questions")
    topics = models.ManyToManyField(Topic, related_name="questions")
    url = models.CharField(max_length = 150)
    created_at = models.DateTimeField(auto_now_add = True, blank = True)

    def __str__(self):
        return self.question

class Answer(models.Model):
    answer = models.TextField()
    author = models.ForeignKey(CustomUser, on_delete = models.CASCADE, related_name="written_answers")
    question = models.ForeignKey(Question, on_delete = models.CASCADE, related_name="answers")
    upvoters = models.ManyToManyField(CustomUser, related_name="upvoted_answers")
    created_at = models.DateTimeField(auto_now_add = True, blank = True)

A: Try like this using subquery expression
from django.db.models import Count, Subquery, OuterRef

answer_subquery = Answer.objects.filter(question=OuterRef('pk')).annotate(upvotes=Count('upvoters')).order_by('-upvotes')

questions = Question.objects.annotate(answer=Subquery(answer_subquery.values('answer')[:1]))


text:
Q: default class path java my program is in C:\Users\Programs\x.java
X.java is using some files that are in y.jar, z.jar.
y.jar and z.jar are in C:\Users\Programs folder.
(1)
C:Users\Programs> javac x.java
(2)
C:Users\Programs> javac -classpath y.jar:z.jar x.java
I am not getting any errors when I do (2) but when I do (1) I am getting errors. Isn't that classpath is set to current folder. If so why is it not seeing y.jar and z.jar.

A: Contents of a jar residing on the classpath are not automatically added to the classpath itself. A proper classpath in your case would be what you specified in case (2).

A: The classpath includes the current folder.
However, it does not include subfolders of the current folder.
If you try to use com.example.MyClass, Java will look for a file named com/example/MyClass.class directly inside of each folder in the classpath.
It does not look in subfolders or JARs inside of folders in the classpath.

A: Yes, classpath should indeed be set to the current folder by default. However, setting it to a given folder is not the same as setting it to a specific JAR file.


text:
Q: margin bottom doesn't want to work I have an "outside" div which takes 100% of the page. With a higher z-index value, I have an "inside" div. I don't know why but margin-bottom doesn't seem to work with this "inside" div.
My code is:

here a fiddle: http://jsfiddle.net/malamine_kebe/EnHut/

A: Change position: absolute; to position: relative; for #inside
http://jsfiddle.net/EnHut/1/

A: Simple solution:
Change position to relative
http://jsfiddle.net/EnHut/2/
#inside{
  background-color:#f8f8f8;
  position: relative;
  top:0;
  left:20%;
  height: 700px;
  width:60%;
  margin-top:35px;
  margin-bottom:35px;
  z-index:3;
  border-radius: 7px;
  box-shadow: 6px 6px 20px black;
}

A: Try this:
#inside{
    background-color:#f8f8f8;
    position: relative;
    top:0;
    left:20%;
    width:60%;
    margin-top:35px;
    margin-bottom:35px;
    z-index:3;
    border-radius: 7px;
    box-shadow: 6px 6px 20px black;
}

It is your position — you're using absolute, and the element don't know where it is to give margin at the bottom.
To see the difference between relative and absolute, just click here.
And here is the resolution of the problem in practice. (FiddleJs)


text:
Q: java doesn't allow runtime-selectable-width format strings? I need a way to print a number as hex, as a zero-padded string of width N, where N is selectable at runtime.
This doesn't work:
System.out.println(String.format("%*x", 4, 0x123))

because evidently Java doesn't support the C-style use of %* for runtime-selectable width format strings.
Any suggestions for an alternative?

A: int width = 4;
String format = "%" + width + "x";
System.out.println(String.format(format, 0x123));

:wrysmile:

A: @fd also with printf
int width = 4;
String format = "%" + width + "x";
System.out.printf(format, 0x123);

System.out.printf("%4x", 0x123);

A: Use an appropriate NumberFormat.
EDIT
This is plain wrong..


text: Q: Regression analysis for Measurement values I'm in a situation where I'm provided with a signal and a couple of measurement values for that signal. Usually the signal will drift a little when the measurement start (i.e. because of heat). I want to determine whether my system is still drifting (at any given point) or not. Therefore I wanted to determine a regression line and used the equations for linear regressions (https://en.wikipedia.org/wiki/Simple_linear_regression), but the result is awkward and cannot be correct. So the question is, what am I missing?


text:
Q: Atiyah-Hirzebruch spectral sequence for a special kind of CW-complexes Let $X$ be a finite CW-complex such that its $K$-theory $K^*(X)$ is, as a $\mathbb{Z}$-algebra, generated by $a_1, \cdots, a_n$ which are represented by reduced line bundles $L_1-1, \cdots, L_n-1$ satisfying $L_i^{\otimes 2}\oplus 1\cong L_i^{\oplus 2}$ (implying that $a_i^2=0$) for $1\leq i\leq n$. Note that $a_i$ may be a torsion element. We say $a\in K^{-1}(X)$ is represented by a reduced line bundle if, through the identification $K^{-1}(X)=\widetilde{K}^0(SX)$, $a$ is represented by a reduced line bundle on $SX$. Examples of such finite CW-complexes include $S^2$ and $\mathbb{RP}^2$, any product of them, and $S^2\times_{\mathbb{Z}_2}S^2$ where $\mathbb{Z}_2$ acts on $S^2$ by antipodal map.

*

*Is it true that the Atiyah-Hirzebruch spectral sequence for $K^*(X)$ collapses on the $E_2$-page, and there are no extension problems? It seems that $\text{Sq}^1$ and $\text{Sq}^2$ vanish on $X$, and $d_3$, being the third integral Steenrod square, seems to vanish. I am not sure how to go about the higher differentials and the extension problems.

*Is it true that the `Chern character map'
\begin{align*}
\text{ch}: K^*(X)&\to H^*(X, \mathbb{Z})\\
a_i&\mapsto \text{ch}(a_i)=c_1(L_i)
\end{align*}
is a ring isomorphism?
Note that the condition $L_i^{\otimes 2}\oplus 1\cong L_i^{\oplus 2}$ implies that $c_1(L_i)^2=0$, and it still makes sense to define the `Chern character' of any generator $\text{ch}(a_i)=\text{ch}(L_i)-1=e^{c_1(L_i)}-1=c_1(L_i)$ and product of generators
\begin{align*}
\text{ch}(a_ia_j)&=\text{ch}(L_i\otimes L_j\oplus 1-(L_i\oplus L_j))\\
&=\left(1+c_1(L_i)+c_1(L_j)+\frac{(c_1(L_i)+c_1(L_j))^2}{2}+\cdots\right)+1-1-c_1(L_i)-1-c_1(L_j)\\
&=c_1(L_i)c_1(L_j)\\
&=\text{ch}(a_i)\text{ch}(a_j)
\end{align*}
even for those $a_i$ which are torsion $K$-theory classes.

A: This is not true. One of the main reasons is that, because you've only specified properties about $K^*(X)$, that leaves a lot of room for $H^*(X;\Bbb Z)$ to have information which doesn't ultimately contribute to $K$-theory.
Finding an example is a little more work. The mod-2 Moore space $M(\Bbb Z/2, n)$ is the $(n-1)$-fold reduced suspension of $\Bbb RP^2$; it has the property that its reduced homology is $\Bbb Z/2$ in dimension $n$ and $0$ elsewhere. These have the property that for sufficiently large $n$, there is a map
$$
v: M(\Bbb Z/2, n+8) \to M(\Bbb Z/2, n)
$$
which induces an isomorphism
$$
v: K^* M(\Bbb Z/2, n) \to K^* M(\Bbb Z/2, n+8)
$$
on $K$-theory (real or complex $K$-theory, in fact). These maps were constructed by Adams in his study of the $J$-homomorphism ("On the groups J(X) IV").
As a result, we can take the mapping cone
$$
M(\Bbb Z/2, n+8) \to M(\Bbb Z/2, n) \to Cv
$$
and get a finite complex $Cv$ whose integral cohomology is $\Bbb Z/2$ in dimensions $(n+1)$ and $(n+10)$ and zero elsewhere; this means that the Atiyah-Hirzebruch spectral sequence starts nontrivially. However, the fact that $v$ was an isomorphism on $K$-theory means that $Cv$ has the same $K$-theory as a point. The space $Cv$ then satisfies your criteria for not very interesting reasons.
The fact that $Cv$ has no $K$-theory means that the Atiyah-Hirzebruch spectral sequence has to erase everything except the $0$-line (in fact, there is a $d_9$ differential). This also means that the Chern character doesn't have a hope of being an isomorphism because the source ring has no torsion and the target does.


text:
Q: async Function in JavaScript I want to understand what Async function do in js.
If it actually runs code asynchronously then it should keep executing the code which is written after function call.
My code:
async function someWork(){

            let p=10;
            console.log("inside someWork");
            //Some calculations to spend time
            for(let i=0;i<100000000;i++){
                b=i**i;
                if(i==100000000-2){
                    console.log(i+" last Iteration, about to complete the calculation..");
                }
            }
            console.log(p+" I am done With Long work");
        }

        console.log("before calling somework async function");
        someWork();
        console.log("after calling somework async function");

output:
 before calling somework async function
 inside someWork
 99999998 last Iteration, about to complete the calculation..
 10 I am done With Long work
 after calling somework async function

However what I am expecting is:
 before calling somework async function
 after calling somework async function
 inside someWork
 99999998 last Iteration, about to complete the calculation..
 10 I am done With Long work

A:
If it actually runs code asynchronously...

An async function does not execute asynchronously. It runs synchronously, but returns a promise. Declaring a function with async only makes sense when it uses the keyword await, because that will be the point where the function returns to continue with the code after the function call, leaving the rest of its code for later, asynchronous execution.
For your desired output, there are many options:

*

*Insert the line await null; at the top of your async function.

*Don't use async and have your function called by setTimeout, requestAnimationFrame, queueMicrotask, or any other asynchronous API.

*Create a Web Worker, and have the function executed by it. This will have the function executed by a different thread, potentially giving more concurrency.


text:
Q: Is there a way to integrate Mercurial with Zend studio 5? My php dev team is using Zend Studio 5
We are about to start using a version control system and are seriously considering Mercurial - but after searching the web for a while, I can't find any solutions to integrate Mercurial with Zend 5.
I have a feeling that if the version control won't integrate with the IDE, then it will be too complicated / annoying to use.
So, anyone know a solution for this?
Alternatively, I am open to a suggestion for a lightweight IDE that integrates Mercurial and even better, a task/bug reporting system - all in one.
Thanks!
note - this version of Zend does not run on Eclipse, and therefore MercurialEclipse plugin cannot be used

A: I think that for someone who is used to using an IDE, the most annoying thing about all of the popular free version control systems is that they are command line based (at least out-of-the-box).
But there is a solution for that:
Every VCS out there has at least one decent GUI (Mercurial has TortoiseHG, for example), so you can use one of these to avoid typing the commands by hand.
Now for the IDE integration:
Yes, an integration into the IDE of your choice would be even more comfortable than just starting a separate program (TortoiseHG) for your VCS GUI.
But when there is a GUI available for your VCS, do you really need IDE integration as well?
I can only speak for myself, but I'm using TortoiseHG for nearly two years now (at work and at home), I never used IDE integration and I never missed it.
(my co-workers all use TortoiseHG without IDE integration as well)
I don't know if it's possible to integrate Mercurial with Zend Studio.
But I would suggest that you at least try to use TortoiseHG without integration first, and see if you can't just live with that.

A: MercurialEclipse works for Zend Studio 9... I'm not sure about older versions though.


text:
Q: Cognos Report Studio Crosstab drill thru I have a Crosstab report (10.2.2) which has 4 sub-reports that when you drill-through each report. I have drill-through on the row (TOS Level1) and would like to do that to the columns for (Emp Level 2 & 3). However when i go from prompt pages the Emp level works until i click on the TOS Level1. Then i get back all the Emp level data which if i only selected 1 value in prompt page i only want to see that 1 value i selected in prompt page not all the Emp Level data.
Report 1 and sub-reports are similar in layout. The sub-reports only add 1 column for the TOS level as you go down. TOS levels 1-5 for columns in rows for report. I can then drill back up by clicking next column in that row.
Report layout:
            columns
Revenue    | Emp Level2 |
           | Current period  | prior period  | Difference %  |Contrib to Trend %
Rows
(TOS Level1)
Ancillary
Facility
Inpatient
Outpatient
Services
Other
The 3 prompt pages are for Emp Level 1, Emp Levels 2 & 3 (same prompt page, both optional), TOS Level1
When i choose TOS levels it works fine for First report page. I have the correct TOS items and Emp levels present. When i click on 1 of the TOS rows i get all the Emp level data even though i chose only 1 group to show in first report. How can i get the Emp levels to show properly when i click on the TOS row item?
Thanks for the help. hope i explained this well enough.
Thanks VBnewbie


text:
Q: Handle AWS EC2 Traffic Peaks I have a EC2 instance running on AWS Free Tier on the Bitnami LAMP stack. During traffic peaks, the application becomes extremely slow due to large number of mySQL connections.
I receive these peaks very less frequently, but I still want to be able to handle them well, and don't have a problem paying for a better AWS instance as well.
What is the best practice to deal with this?


text:
Q: when I execute the docker command I get "invalid reference format" error How can I fix this problem?

docker: invalid reference format.

I have executed this command:
docker run -d --rm -p 3000:8000 -env port=8000 --name feedback-app -v feedback:/app/feedback -v "c:/workspace/d/data-volumes-07-added-dockerignore/data-volumes-07-added-dockerignore:/app:ro" -v /app/node_modules -v /app/temp feedback-node:env

A: I had forgotten something in my command!
I changed -env to --env
docker run -d --rm -p 3000:8000 --env port=8000 --name feedback-app -v feedback:/app/feedback -v "c:/workspace/d/data-volumes-07-added-dockerignore/data-volumes-07-added-dockerignore:/app:ro" -v /app/node_modules -v /app/temp feedback-node:env


text:
Q: unity3d shaders level of detail Maybe questions seems strange , but , please take a look at the summarized shader code listed below :
Shader "AngryBots/PlanarRealtimeReflection" {
    Properties {
        ...
    }

    SubShader {
        LOD 400

        Tags { "RenderType"="Opaque" }
        Fog { Mode Off }

        Pass {
            ...

        }
    }

    SubShader {
        LOD 200

        Tags { "RenderType"="Opaque" }
        Fog { Mode Off }

        Pass {

        ....

        }
    }
}

Every sub shader has a different LOD , I know the much bigger LOD has more details and wants more GPU Processing , So How should we number the LOD of our shaders ? how the device GPU understands the numbers !
So how Can I Find that my shader LOD is 500 or 700 or 300?
I had read the unity3d manual which tells me for example the BumpedMapDiffuse Shader For PC's are 500 ! But how can I convert it for mobile devices ?

A: Unity's ShaderLab level of detail (LOD)* is a convenience feature for developers that helps them support multiple platforms in a single shader.  The basic idea is that an application might have a SweetLightingShader that only works on PCs.  Suppose the iPad doesn't support SweetLightingShader but it does support SemiSweetLightingShader.  You could maintain two separate shaders or, even better, merge them in to a single shader and use LOD to decide what functionality to use.
*Do not confuse ShaderLab LOD with geometric LOD, they are independent topics.
Here is an example shader with 2 levels of detail:
Shader "Custom/ExampleLighting" {
    Properties {
        _MainTex ("Base (RGB)", 2D) = "white" {}
    }
    SubShader { // SweetLighting
        LOD 200
        Pass { Color (1,0,0,0) }
    }
    SubShader { // SemiSweetLighting
        LOD 100
        Pass { Color (0,1,0,0) }
    }
    FallBack "Diffuse"
}

The LOD can be set like so:
public class SwitchLod : MonoBehaviour {
    public Shader myShader;

    void Start() {
        myShader.maximumLOD = 100; //Use SemiSweetLighting -or-
        myShader.maximumLOD = 200; //Use SweetLighting
    }
}

The first subshader to meet the LOD requirements is the one used.  From the docs:

When Unity renders a shader, it will go over all subshaders and use
  the first one that the hardware supports.

Note that the documentation for Shader.globalMaximumLOD states that it is the Shader LOD level for all shaders.  This does not appear to be directly true, that's why my example sets the LOD for the shader directly.  The AngryBots demo that comes with Unity uses the following snippet to apply the global maximum LOD to all shaders:
Shader.globalMaximumLOD = quality;
for (var s : Shader in shaders.shaders) {
    s.maximumLOD = quality;
}

A: Shader LOD is extremely useful when you are need to support a range of GPUs with different performance. For example, if you want your game to run smoothly on both iPhone4 and iPhone5S.
Usual practice is to compose a shader as a set of several sub-shaders (consider them as a versions of the same shader) with different LODs. You may implement complex per-pixel lighting in sub-shaders with bigger LODs and rough per-vertex lighting in those with smaller LODs. Then you may enable appropriate versions of shaders in your code using Shader.globalMaximumLOD


text:
Q: Effect of Coriolis force Is Coriolis force fictitious in an inertial frame or not? If so can it be mathematically deduced using an inertial frame as reference?

A: Fictitious forces do not exist in inertial frames. Fictitious forces result from force-fitting Newtonian mechanics to non-inertial frames.


text:
Q: ASP.NET MVC 5 - Access localhost from phone/PC in same network I am building an ASP.NET MVC 5 application and I run the server locally and it works fine, but I can't seem to connect to it from an external device.
The URL is localhost:60884 . I navigate with my phone to <internal_IP_address>:60884 and I get a ERR_CONNECTION_TIMED_OUT error.
I have disabled the firewall and I have tried to connect the PC on my phone's WiFi HotSpot, but no success.
Can someone tell me how to solve this?

A: You should be able to do this by setting it up in project properties. In Visual Studio if you go into the Web tab on the right, there'll be a Start URL you can choose

Whatever address you put in there you should be able to navigate to on your phone, provided you're on the same network. You are likely getting the timeout error because your device can't connect to the server's address at all.

Hope that helps!


text:
Q: LEFT JOIN order and limit This is my query:
SELECT `p`.`name` AS 'postauthor', `a`.`name` AS 'authorname',
       `fr`.`pid`, `fp`.`post_topic` AS 'threadname', `fr`.`reason`
  FROM `z_forum_reports` `fr`
  LEFT JOIN `forums` `f` ON (`f`.`id` = `fr`.`pid`)
  LEFT JOIN `forums` `fp` ON (`f`.`first_post` = `fp`.`id`)
  LEFT JOIN `ps` `p` ON (`p`.`id` = `f`.`author_guid`)
  LEFT JOIN `ps` `a` ON (`a`.`account_id` = `fr`.`author`)

My problem is this left join:
SELECT `a`.`name`, `a`.`level`
[..]
LEFT JOIN `ps` `a` ON (`a`.`account_id` = `fr`.`author`)

Since, in case a has MANY rows and it'll return like in my case:
NAME  | LEVEL
Test1 | 1
Test2 | 120
Test3 | 2
Test4 | 1

I want it to select a.name with order of level desc and limit 1, so it'll return the name of higher level where (a.account_id = fr.author).
Hope you got me. If not, feel free to post a comment.

A: Try replacing:
LEFT JOIN ps a ON a.account_id = fr.author

with:
LEFT JOIN ps a
  ON a.PrimaryKey                         --- the Primary Key of ps
     = ( SELECT b.PrimaryKey
         FROM ps AS b
         WHERE b.account_id = fr.author
         ORDER BY b.level DESC
         LIMIT 1
       )

A: Replace the LEFT JOIN clause with something like:
...
LEFT JOIN (SELECT b.account_id, b.name
             FROM (SELECT c.account_id, MAX(c.level) AS level
                     FROM ps AS c
                    GROUP BY c.account_id) AS d
             JOIN ps AS b ON b.account_id = d.account_id AND b.level = d.level
          ) AS a
       ON (a.account_id = fr.author)
...

This will still return multiple rows if there were several rows in ps with the same account ID and the same level and that level was the maximum level:
NAME  | LEVEL
Test1 | 1
Test2 | 120
Test3 | 2
Test4 | 1
Test5 | 120

If this situation can arise, then you have to decide what you want to do - and tune the query appropriately.  For example, you might decide to use MAX(b.name) with a GROUP BY clause to arbitrarily select the alphabetically later of the two names.


text:
Q: How to pass Agent as argument How it is possible to Pass agent as argument to another agent?
I know that we should pass arguments as an Object to createNewAgent method But I don't know how to retrieve recently created agent which exists in agent controller.
/**
 * create Three Collector agents
 */
private void _createCollectorAgent(AgentContainer agentContainer, AgentController[] controller, Map<String, String> agentNames, GUI gui) {
    try {
        Object[] arg = new Object[1];
        arg[0] = gui;

        for (int i = 0; i <= 2; i++) {
            controller[i] = agentContainer.createNewAgent(agentNames.get(String.format("CollectorAgent%d", i)), CollectorAgent.class.getName(), arg);
            controller[i].start();
        }
    } catch (StaleProxyException e) {
        e.printStackTrace();
    }
}

private void _createSearcherAgent(AgentContainer agentContainer, AgentController[] controller, Map<String, String> agentNames, GUI gui) {
    try {

        List<AID> lstCollectors = new ArrayList<>(3);
        lstCollectors.add( ?);//How get recently created agent inorder to pass in argument
        lstCollectors.add( ?);
        lstCollectors.add( ?);
        Object[] args = new Object[2];
        args[0] = gui;
        args[1] = lstCollectors;
        controller[3] = agentContainer.createNewAgent(agentNames.get("SearcherAgent"), SearcherAgent.class.getName(), args);
        controller[3].start();
    } catch (StaleProxyException e) {
        e.printStackTrace();
    }

}

And here is Searcher Agent which needs argument:
public class SearcherAgent extends Agent implements AgentEntity {

    @Override
    protected void setup() {
        super.setup();
        System.out.println("Setup of SearcherAgent called ");
        GUI gui = (GUI) getArguments()[0];
        AID[] lstCollectors= (AID[]) getArguments()[1];//Here is Ok
        addBehaviour(new SearchingBehaviour(this, 1000,gui,lstCollectors));
    }

}

A: It's not needed to pass Agent as argument because you can have access to other agents from  any Agent class like this:
final AID[] otherAgents=
        {
           new AID("otherAgents0", AID.ISLOCALNAME),
           new AID("otherAgents1", AID.ISLOCALNAME),
           new AID("otherAgents2", AID.ISLOCALNAME),
           ...
        };

This will give you the agents that are existing .The first argument is the agent's name given while creating them.


text:
Q: How to to extract a javascript function from a javascript file I need to extract an entire javascript function from a script file. I know the name of the function, but I don't know what the contents of the function may be. This function may be embedded within any number of closures.
I need to have two output values:

*

*The entire body of the named function that I'm finding in the input script.

*The full input script with the found named function removed.

So, assume I'm looking for the findMe function in this input script:
function() {
  function something(x,y) {
    if (x == true) {
      console.log ("Something says X is true");
      // The regex should not find this:
      console.log ("function findMe(z) { var a; }");
    }
  }
  function findMe(z) {
    if (z == true) {
      console.log ("Something says Z is true");
    }
  }
  findMe(true);
  something(false,"hello");
}();

From this, I need the following two result values:

*

*The extracted findMe script
function findMe(z) {
  if (z == true) {
    console.log ("Something says Z is true");
  }
}

*The input script with the findMe function removed
function() {
  function something(x,y) {
    if (x == true) {
      console.log ("Something says X is true");
      // The regex should not find this:
      console.log ("function findMe(z) { var a; }");
    }
  }
  findMe(true);
  something(false,"hello");
}();

The problems I'm dealing with:

*

*The body of the script to find could have any valid javascript code within it. The code or regex to find this script must be able to ignore values in strings, multiple nested block levels, and so forth.

*If the function definition to find is specified inside of a string, it should be ignored.
Any advice on how to accomplish something like this?
Update:
It looks like regex is not the right way to do this. I'm open to pointers to parsers that could help me accomplish this. I'm looking at Jison, but would love to hear about anything else.

A: A regex can't do this.  What you need is a tool that parses JavaScript in a compiler-accurate way, builds up a structure representing the shape of the JavaScript code, enables you to find the function you want and print it out, and enables you to remove the function definition from that structure and regenerate the remaining javascript text.
Our DMS Software Reengineering Toolkit can do this, using its JavaScript front end.   DMS provides general parsing, abstract syntax tree building/navigating/manipulation, and prettyprinting of (valid!) source text from a modified AST.   The JavaScript front end provides DMS with compiler-accurate definition of JavaScript.  You can point DMS/JavaScript at a JavaScript file (or even various kinds of dynamic HTML with embedded script tags containing JavaScript), have it produce the AST.
A DMS pattern can be used to find your function:
  pattern find_my_function(r:type,a: arguments, b:body): declaration
     " \r my_function_name(\a) { \b } ";

DMS can search the AST for a matching tree with the specified structure; because this is an AST match and not a string match, line breaks, whitespace, comments and other trivial differences won't fool it.   [What you didn't say is what to if you have more than one
function in different scopes: which one do you want?]
Having found the match, you can ask DMS to print just that matched code which acts as your extraction step.  You can also ask DMS to remove the function using a rewrite rule:
  rule remove_my_function((r:type,a: arguments, b:body): declaration->declaration
     " \r my_function_name(\a) { \b } " -> ";";

and then prettyprint the resulting AST.  DMS will preserve all the comments properly.
What this does not do, is check that removing the function doesn't break your code.   After all, it may be in a scope where it directly accesses variables defined locally in the scope.  Removing it to another scope now means it can't reference its variables.
To detect this problem, you not only need a parser, but you need a symbol table with maps identifiers in the code to definitions and uses.   The removal rule then has to add a semantic condition to check for this.   DMS provides the machinery to build such a symbol table from the AST using an attribute grammar.
To fix this problem, when removing the function, it may be necessary to modify the function to accept additional arguments replacing the local variables it accesses, and modify the call sites to pass in what amounts to references to the local variables.    This can be implemented with a modest  sized set of DMS rewrite rules, that check the symbol tables.
So removing such a function can be a lot more complex than just moving the code.

A: If the script is included in your page (something you weren't clear about) and the function is publicly accessible, then you can just get the source to the function with:
functionXX.toString();

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/toString
Other ideas:
1) Look at the open source code that does either JS minification or JS pretty indent.  In both cases, those pieces of code have to "understand" the JS language in order to do their work in a fault tolerant way.  I doubt it's going to be pure regex as the language is just a bit more complicated than that.
2) If you control the source at the server and are wanted to modify a particular function in it, then just insert some new JS that replaces that function at runtime with your own function.  That way, you let the JS compiler identify the function for you and you just replace it with your own version.
3) For regex, here's what I've done which is not foolproof, but worked for me for some build tools I use:
I run multiple passes (using regex in python):

*

*Remove all comments delineated with /* and */.

*Remove all quoted strings

*Now, all that's left is non-string, non-comment javascript so you should be able to regex directly on your function declaration

*If you need the function source with strings and comments back in, you'll have to reconstitute that from the original, now that you know the begin end of the function

Here are the regexes I use (expressed in python's multi-line format):
reStr = r"""
    (                               # capture the non-comment portion
        "(?:\\.|[^"\\])*"           # capture double quoted strings
        |
        '(?:\\.|[^'\\])*'           # capture single quoted strings
        |
        (?:[^/\n"']|/[^/*\n"'])+    # any code besides newlines or string literals
        |
        \n                          # newline
    )
    |
    (/\*  (?:[^*]|\*[^/])*   \*/)       # /* comment */
    |
    (?://(.*)$)                     # // single line comment
    $"""

reMultiStart = r"""         # start of a multiline comment that doesn't terminate on this line
    (
        /\*                 # /*
        (
            [^\*]           # any character that is not a *
            |               # or
            \*[^/]          # * followed by something that is not a /
        )*                  # any number of these
    )
    $"""

reMultiEnd = r"""           # end of a multiline comment that didn't start on this line
    (
        ^                   # start of the line
        (
            [^\*]           # any character that is not a *
            |               # or
            \*+[^/]         # * followed by something that is not a /
        )*                  # any number of these
        \*/                 # followed by a */
    )
"""

regExSingleKeep = re.compile("// /")                    # lines that have single lines comments that start with "// /" are single line comments we should keep
regExMain = re.compile(reStr, re.VERBOSE)
regExMultiStart = re.compile(reMultiStart, re.VERBOSE)
regExMultiEnd = re.compile(reMultiEnd, re.VERBOSE)

This all sounds messy to me.  You might be better off explaining what problem you're really trying to solve so folks can help find a more elegant solution to the real problem.

A: I built a solution in C# using plain old string methods (no regex) and it works for me with nested functions as well. The underlying principle is in counting braces and checking for unbalanced closing braces. Caveat: This won't work for cases where braces are part of a comment but you can easily enhance this solution by first stripping out comments from the code before parsing function boundaries.
I first added this extension method to extract all indices of matches in a string (Source: More efficient way to get all indexes of a character in a string)
    /// <summary>
    /// Source: https://stackoverflow.com/questions/12765819/more-efficient-way-to-get-all-indexes-of-a-character-in-a-string
    /// </summary>
    public static List<int> AllIndexesOf(this string str, string value)
    {
        if (String.IsNullOrEmpty(value))
            throw new ArgumentException("the string to find may not be empty", "value");
        List<int> indexes = new List<int>();
        for (int index = 0; ; index += value.Length)
        {
            index = str.IndexOf(value, index);
            if (index == -1)
                return indexes;
            indexes.Add(index);
        }
    }

I defined this struct for easy referencing of function boundaries:
    private struct FuncLimits
    {
        public int StartIndex;
        public int EndIndex;
    }

Here's the main function where I parse the boundaries:
    public void Parse(string file)
    {
        List<FuncLimits> funcLimits = new List<FuncLimits>();

        List<int> allFuncIndices = file.AllIndexesOf("function ");
        List<int> allOpeningBraceIndices = file.AllIndexesOf("{");
        List<int> allClosingBraceIndices = file.AllIndexesOf("}");

        for (int i = 0; i < allFuncIndices.Count; i++)
        {
            int thisIndex = allFuncIndices[i];
            bool functionBoundaryFound = false;

            int testFuncIndex = i;
            int lastIndex = file.Length - 1;

            while (!functionBoundaryFound)
            {
                //find the next function index or last position if this is the last function definition
                int nextIndex = (testFuncIndex < (allFuncIndices.Count - 1)) ? allFuncIndices[testFuncIndex + 1] : lastIndex;

                var q1 = from c in allOpeningBraceIndices where c > thisIndex && c <= nextIndex select c;
                var qTemp = q1.Skip<int>(1); //skip the first element as it is the opening brace for this function

                var q2 = from c in allClosingBraceIndices where c > thisIndex && c <= nextIndex select c;

                int q1Count = qTemp.Count<int>();
                int q2Count = q2.Count<int>();

                if (q1Count == q2Count && nextIndex < lastIndex)
                    functionBoundaryFound = false; //next function is a nested function, move on to the one after this
                else if (q2Count > q1Count)
                {
                    //we found the function boundary... just need to find the closest unbalanced closing brace
                    FuncLimits funcLim = new FuncLimits();
                    funcLim.StartIndex = q1.ElementAt<int>(0);
                    funcLim.EndIndex = q2.ElementAt<int>(q1Count);
                    funcLimits.Add(funcLim);

                    functionBoundaryFound = true;
                }
                testFuncIndex++;
            }
        }
    }

A: I am almost afraid that regex cannot do this job. I think it is the same as trying to parse XML or HTML with regex, a topic that has already caused various religious debates on this forum.
EDIT: Please correct me if this is NOT the same as trying to parse XML.

A: I guess you would have to use and construct a String-Tokenizer for this job.
function tokenizer(str){
  var stack = array(); // stack of opening-tokens
  var last = ""; // last opening-token

  // token pairs: subblocks, strings, regex
  var matches = {
    "}":"{",
    "'":"'",
    '"':'"',
    "/":"/"
  };

  // start with function declaration
  var needle = str.match(/function[ ]+findme\([^\)]*\)[^\{]*\{/);

  // move everything before needle to result
  var result += str.slice(0,str.indexOf(needle));
  // everithing after needle goes to the stream that will be parsed
  var stream = str.slice(str.indexOf(needle)+needle.length);

  // init stack
  stack.push("{");
  last = "{";

  // while still in this function
  while(stack.length > 0){

    // determine next token
    needle = stream.match(/(?:\{|\}|"|'|\/|\\)/);

    if(needle == "\\"){
      // if this is an escape character => remove escaped character
      stream = stream.slice(stream.indexOf(needle)+2);
      continue;

    }else if(last == matches[needle]){
      // if this ends something pop stack and set last
      stack.pop();
      last = stack[stack.length-1];

    }else if(last == "{"){
      // if we are not inside a string (last either " or ' or /)
      // push needle to stack
      stack.push(needle);
      last = needle;
    }

    // cut away including token
    stream = stream.slice(stream.indexOf(needle)+1);
  }

  return result + stream;
}

oh, I forgot tokens for comments... but i guess you got an idea now of how it works...


text:
Q: cordova-plugin-firebase working in android but not in ios I'm developing a phonegap mobile app for ios and android and building it with phonegap cli.
I have installed cordova-plugin-firebase for push notifications.
Following instructions in https://www.npmjs.com/package/cordova-plugin-firebase
In Android:
I have downloaded google-services.json and placed it in platforms/android folder.
I'm testing the app in a device and push notifications are working.
In iOS:
I have downloaded GoogleService-Info.plist and placed it in platforms/ios/[My Project]/Resources folder.
I'm testing the app in a device but push notifications are not working.
Any help?
Thanks
EDITED
In my app.js now I have included window.FirebasePlugin.grantPermission() but still is not working:
var app = new Framework7({
root: '#app', // App root element
...
on: {
    init: function () {
        if (Framework7.device.ios) {
            window.FirebasePlugin.grantPermission();
        }
    },
},
...
});

Is that incorrect?

A: Ok, now it's working!
First, I had commentted in index.html this line:
<script src="cordova.js"></script>

Now, uncommentted, the next event handler works (before it wasn't working)
$$(document).on('deviceready', function () {
if (app.device.ios) {
    window.FirebasePlugin.grantPermission();
}
});

Now the app ask me for grant permission and if I accept push notifications works.
Thanks


text:
Q: Getting "not talking to master and retries used up" Exception at DBCursor.hasNext() I am getting "not talking to master and retries used up" Exception at statement DBCursor.hasNext().
When I searched, got the solution as set the preference. Still i am getting the issue.
My code is as below:
public void sampleTest() throws Exception
    {

MongoClient client = new MongoClient("192.168.20.117", 27017);

DB database = client.getDB("CLME2ECORE");

boolean auth = database.authenticate("tecnotree", ("tecnotree").toCharArray());

DBCollection collection = database.getCollection("RegistrationRequest");

collection.setReadPreference(ReadPreference.primary());

BasicDBObject andQuery = new BasicDBObject("serviceRequest.serviceRequestSubtype.masterCode","RETPOSTREG");
andQuery.append("serviceRequest.serviceRequestStatus.masterCode", "PYMTPEND");

BasicDBObject andFields = new BasicDBObject("serviceRequest.customer.profileDetails.basicDetails.customerCode",1);
andFields.append("_id", 0);

DBCursor dbCursor = collection.find(andQuery);
DBObject dbObject;

dbCursor.setReadPreference(ReadPreference.primary());

if(dbCursor.hasNext())
{
     dbObject = dbCursor.next();

     String value = dbObject.get("serviceRequest.customer.profileDetails.basicDetails.customerCode").toString();
}

client.close();

}
I am using maven dependencies as
<dependency>
    <groupId>org.mongodb</groupId>
    <artifactId>mongo-java-driver</artifactId>
    <version>2.13.0</version>
</dependency>
<dependency>
 <groupId>org.mongodb</groupId>
 <artifactId>bson</artifactId>
 <version>2.13.0</version>
</dependency>

Please help to resolve this issue.

A: Do these changes, then it will work.

*

*Pass the complete replica set string while connecting to the mongodb, do not pass an individual server IP.

*Change the readPreferance to PrimaryPrefferred, instead of Primary only.

A: I met the exactly the same problem as you. I'm using java spring connect to a slave mongo database. The following code should be helpful.

@Configuration
@PropertySource("classpath:param.properties")
public class MongoConfig {

    public @Bean MongoClientFactoryBean mongo() {

        MongoClientFactoryBean mongo = new MongoClientFactoryBean();
        mongo.setHost(mongoAddress);
        mongo.setPort(mongoPort);
        MongoClientOptions mco = new MongoClientOptions.Builder().readPreference(ReadPreference.secondaryPreferred()).build();

        mongo.setMongoClientOptions(mco);
        return mongo;
    }

    @Value("${mongo.address}")
    private String mongoAddress;

    @Value("${mongo.port}")
    private Integer mongoPort;
}

The key line is following:

            MongoClientOptions mco = new MongoClientOptions.Builder().readPreference(ReadPreference.secondaryPreferred()).build();

Which indicate the mongo client as secondard perferred.


text:
Q: A problems with refreshing DataGridView I'm using a DataGridView with bounded List of objects in my application. So I have:
grid.DataSource = Files.Instance.List;

in my form load event and than I want to have two buttons - for adding and removing items from the list (so also from the grid), I though it should be as simple as:
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
    Files.Instance.List.Add(new DelphiFile { FilePath = openFileDialog.FileName });
    grid.Refresh();
}

I'm only setting up the start path here, I wanted the rest parameters to be set by user in the grid view.
The item is added correctly but unfortunatelly it doesnt appear on the list, why?
I also have issues with deleting items:
foreach(DataGridViewRow row in grid.SelectedRows)
{
   Files.Instance.List.Remove(row.DataBoundItem as DelphiFile);
}
grid.Refresh();

items are deleted correctly but again the grid doesn't seem to refresh and I'm even getting an exception because the last item in the grid doesn't have a value than :O .
What am I doing wrong?

A: I guess you declared Files.Instance.List as of type List<DelphiFile>, so when the collection is changed, the dataGridView doesn't know about that, use BindingList<DelphiFile> instead.


text:
Q: iOS7 Autolayout Issues - Adding UIView Subview to UITableViewController I have been trying for a few hours. I am adding a subclass of UIView to the view of my UITableViewController. I am using the code at the bottom of the this post.
I get a crash that says:
2014-06-15 12:19:58.724 Block Party[4712:60b] *** Assertion failure in -[UITableView layoutSublayersOfLayer:], /SourceCache/UIKit/UIKit-2935.137/UIView.m:8794
2014-06-15 12:19:58.726 Block Party[4712:60b] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Auto Layout still required after executing -layoutSubviews. UITableView's implementation of -layoutSubviews needs to call super.'
*** First throw call stack:
(0x2e940f0b 0x390d7ce7 0x2e940ddd 0x2f2ede2f 0x311703c5 0x30dec31b 0x30de7b3f 0x311854a1 0x3e387 0x311a5a3b 0x311bb8a5 0x3e221 0x3d267 0x31174a53 0x31174811 0x31300c13 0x3121e48f 0x3121e299 0x3121e231 0x31170305 0x30dec31b 0x30de7b3f 0x30de79d1 0x30de73e5 0x30de71f7 0x30de0f1d 0x2e90c039 0x2e9099c7 0x2e909d13 0x2e874769 0x2e87454b 0x337e16d3 0x311d3891 0x3acb5 0x395d5ab7)
libc++abi.dylib: terminating with uncaught exception of type NSException
I attempted to resolve this by adding the layoutSublayerofLayer method but it didn't change anything. Also, if I comment out [self.locationNeededView setTranslatesAutoresizingMaskIntoConstraints:NO]; then it doesn't crash but my constraints are ignored because the autoresizingmaskconstraints take priority.
I'm totally out of ideas for how to solve this. Basically I want this view to appear on top of my table, centered horizontally and vertically.
Thanks in advance for any help you can offer.
-Jeff

- (void) layoutSublayersOfLayer:(CALayer *)layer {
    [super layoutSublayersOfLayer:layer];
}
- (void)loadLocationNeededView {
    UINib *nib = [UINib nibWithNibName:@"LocationNeededUIView" bundle:nil];
    self.locationNeededView = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0];
    [self.locationNeededView setTranslatesAutoresizingMaskIntoConstraints:NO];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem: self.view
                                                     attribute:NSLayoutAttributeCenterX
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self.locationNeededView
                                                     attribute:NSLayoutAttributeCenterX
                                                    multiplier:0
                                                      constant:0]];
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem: self.view
                                                     attribute:NSLayoutAttributeCenterY
                                                     relatedBy:NSLayoutRelationEqual
                                                        toItem:self.locationNeededView
                                                     attribute:NSLayoutAttributeCenterY
                                                    multiplier:0
                                                      constant:0]];
    [self.view addSubview:self.locationNeededView];
    [self.view layoutSubviews];
}

Edit - Update
I gave up on using constraints and I'm just using the frame. I got it to work pretty well with the following code. I also found if I add it to the view of the navigation controller, then it won't scroll with the tableview. Which is exactly what I wanted.

- (void)loadLocationNeededView {
    //allocate subview
    UINib *nib = [UINib nibWithNibName:@"LocationNeededUIView" bundle:nil];
    self.locationNeededView = [[nib instantiateWithOwner:self options:nil] objectAtIndex:0];

    //set frame for it offscreen so it can be animated in
    self.locationNeededView.frame = CGRectMake((self.view.frame.size.width / 2) - (self.locationNeededView.frame.size.width / 2), [[UIScreen mainScreen] bounds].size.height, self.locationNeededView.frame.size.width, self.locationNeededView.frame.size.height);

    //addsubview to navigation controller so that it does not scroll with the tableview
    [self.navigationController.view addSubview:self.locationNeededView];
    [self animateLocationNeededViewIn];
}

- (void) animateLocationNeededViewIn {
    [UIView animateWithDuration:0.35
                          delay:1
         usingSpringWithDamping:0.7
          initialSpringVelocity:1.0
                        options:UIViewAnimationOptionBeginFromCurrentState
                     animations:^ {
                         self.locationNeededView.frame = CGRectMake((self.view.frame.size.width / 2) - (self.locationNeededView.frame.size.width / 2), (self.view.frame.size.height / 2) - (self.locationNeededView.frame.size.height / 2), self.locationNeededView.frame.size.width, self.locationNeededView.frame.size.height);
                         [self.view layoutIfNeeded];} completion:^ (BOOL fin) {
                             if (fin) {
                                 NSLog(@"After Animating View Frame: Origin X = %f. Origin Y = %f. Width = %f. Height = %f", self.locationNeededView.frame.origin.x, self.locationNeededView.frame.origin.y, self.locationNeededView.frame.size.width, self.locationNeededView.frame.size.height);
                             }
                         }];
}

A: Issues: Constraint Multipliers should be 1, not 0. also, you shouldn't need to call layoutSubviews, just call layoutIfNeeded. Also your view needs width and height constraints unless you have defined intrinsiccontentSize in your view.


text:
Q: Unix command status is different for same parameter and same command Below is the set of command I tried consecutively. but $? returns different values each time,
:~/workspace/bitbucket_copy/linuximage$ pkg-config --cflags --libs libcurl-dev
Package libcurl-dev was not found in the pkg-config search path.
Perhaps you should add the directory containing `libcurl-dev.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libcurl-dev' found

:~/workspace/bitbucket_copy/linuximage$ pkg-config --cflags --libs libcurl-dev | echo $?
1
Package libcurl-dev was not found in the pkg-config search path.
Perhaps you should add the directory containing `libcurl-dev.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libcurl-dev' found

:~/workspace/bitbucket_copy/linuximage$ pkg-config --cflags --libs libcurl-dev | echo $?
0
Package libcurl-dev was not found in the pkg-config search path.
Perhaps you should add the directory containing `libcurl-dev.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libcurl-dev' found


text:
Q: How do I replicate this unlimited magicka glitch? I was fighting a Draugr Deathlord in a dungeon (where they are mostly found), and I'd been disarmed. I used unrelenting force to shout him onto a ledge. I took the opportunity to heal myself with some Magicka, and I realized that it was not depleting despite my having used the spell. The Draugr was stuck on the ledge for some reason, so I bombarded him with flames until he died, still having full Magicka despite having used flames.
Has anyone else experienced this? If so, have they figured out how to replicate it? I know it's a glitch, but some glitches can be enacted on purpose.

A: It is possible to reach 100% magic cost reduction with "Fortify" enchantments for up to two magic types. You need enchanting skill 100 with the final perk to do this.
For only one magic type you can reach 100% reduction via enchantments by using "Fortify Enchantment" potions to max out you skill.
What I think might have happened here is that you already had some fortify enchants on your gear (not necessarily enchanted by you, there is a lot of gear that already has that) and use of a potion pushed you over the edge for 100% cost reduction.
Another option would be that your mana regeneration rate has become high enough to offset the cost of you heal and flames almost immediately, making it seem like no mana was used. This could also be achieved by a mix of enchants and potions.
A third option would be a combination of the first two. Strong spell cost reduction combined with fast mana regeneration could also make it seem like there was no mana consumed.

A: I've been able to find a few glitches that can result in near-unlimited magicka and/or magicka regeneration. I have yet to confirm if the glitches are still in the game, however; so some (or all) of them may have been patched out.
While most of these glitches require deliberate exploitation, I have found reports of users running into the same glitch you appear to have experienced; that is, unlimited magicka seemingly out of nowhere. In these cases, I can not find any evidence of the exploits being easy to replicate.
Mass-Equip
By taking advantage of a friendly companion, you can mass-equip items while in werewolf or vampire form. This requires having a companion that will be friendly to you in this form. Activate the werewolf or vampire form, and immediately talk to the companion. If done quickly, you should turn into the werewolf or vampire, while also opening dialogue with your companion. Ask your companion to trade, and from the resulting trade screen, select to equip the items you wish to mass-equip. You will be permitted to equip as many items as you want. In this way, you can mass equip enough items to collectively give you near-infinite magicka or magicka regeneration.

Item Fortification Exploit
If you equip an item that gives you a boost to magicka, you will automatically replenish the bonus magicka points, even when empty. By hotkeying the item, you can unequip it and re-equip it on entry to automatically replenish the amount of given magicka points. You can then use this small pool of constantly-regenerating magicka to effectively have unlimited magicka.

Honourable Mentions

*

*I found this video on YouTube, where the user reports (and demonstrates) having unlimited magicka, specifically for the schools of destruction and restoration. They show off the results, but do not show the glitch first occurring. They report that it happened when they dual-cast lesser ward and sparks.

*I found this post on Reddit, where a user reports suddenly having unlimited magicka. Others have posted under it, reporting a glitch that can sometimes happen after completing the "Out of Balance" quest in the College of Winterhold. During this quest, you can sometimes receive a temporary buff that greatly increases your magicka. This buff can sometimes glitch out and become permanent.

*As others have mentioned, there are various ways to boost your enchanting skill that collectively allows you to enchant gear with enchantments that remove (or considerably reduce) the casting cost of individual schools. I have seen reports that the original method of doing this (fortifying four pieces of equipment for a 25% casting reduction, each) has been patched out; however, I found this video on YouTube that details another method, where you fortify enchanting with potions to allow the creation of single 100% cost reduction enchantments.

*If you're on PC, you could always just open the console with ~ and type in player.setav magicka 99999. This will give you a magicka level so high that it would be near impossible to deplete it.

*Depending on availability for your platform, you may be able to install a mod that provides the same benefits as unlimited magicka. As an example, there is the "Unlimited Magicka (Spells cost 0 MP)" mod on Nexus Mods.

*The Equilibrium spell restores magicka at the cost of health. By dual-casting Equilibrium with a restoration spell, it is possible to heal just as quickly as you regenerate magicka. This has no practical usage for providing unlimited magicka regeneration, but it can be a good way to quickly level your restoration skill.

A: My guess would be maybe you have an extremely high magic stat or maybe it just bugged out and didn't show the magic bar as moving. I've never heard off that glitch before. I wish you good luck friend, Talos be with you.


text:
Q: How to shutdown the computer when hitting the Power button? I have a Xubuntu Lucid 10.04 computer plugged in to my TV. I use the command line to administrate it.
Right now when I hit the power button it just opens a Logout screen.
How can I set it up so that I can shut it down by hitting the power button?
I know it has something to do with acpi or acpid.
I want answers to be command-line only as I do not have any keyboard or mouse connected to that computer.

Edit:
Isn't there a way to modify the default behavior of the xfce4 power manager when pushing the power button?
Also instead of using the GUI to do so, can I do it by creating/modifying a configuration file?
jbowtie had an interesting answer but I cannot find the xfce4-power-manager.xml file. If someone knows where to find that file or how to create it, I would be interested.

A: When you hit the power button, the script /etc/acpi/powerbtn.sh is called. So one option is to modify this script to just call the shutdown script, bypassing the power management daemon. This works across all distributions and environments that I know of.
Since you're using Xubuntu, you can however just change the setting 'power-switch-action' in xfce4-power-manager.xml to the shutdown action - the default value is the ask action.

A: I found a solution. jbowtie put me on the right tracks. Kudos to him.
The problem was I did not have any xfce4-power-manager.xml file and I did not know exactly where to find the file and how to modify the file, but I found that I needed to copy the file from /etc/xdg/xfce4/xfconf/xfce-perchannel-xml/xfce4-power-manager.xml and use xfconf-query to modify it properly.
The shutdown action for /xfce4-power-manager/power-button-action seemed to be 4.
Here's what I did:
cp /etc/xdg/xfce4/xfconf/xfce-perchannel-xml/xfce4-power-manager.xml $HOME/.config/xfce4/xfconf/xfce-perchannel-xml
DISPLAY=:0.0 xfconf-query -c xfce4-power-manager -p /xfce4-power-manager/power-button-action -s 4

A: You are indeed right about ACPI.
This forum post is exactly what you're looking for.
It details the steps you need to take far better than I ever could explain it :)
Edit: Basically, the solution was to install acpid.


text:
Q: RemoveChild Not Working AS3 Flash I'm having a problem here because I'm trying to remove any instances of the rectangle while the Congratulations message is on the the screen. Code is a bit messy but I've been messing around with it a lot to try to figure this out. If I change the addChild to stage.addChild this gives me errors due to the shooting and removing of them in the shootMob function. I've also referred to it as rectangle.parent.removeChild(rectange) but this also won't work. Any ideas?
function spawnMob1():void
{
    if (gameLevel==1)
    {
    var rectangle:MovieClip = new ball_mc();
        rectangle.x = randomRange(583);
    rectangle.y = randomRange(100);
    addChild(rectangle);

    var mobMoveX:Tween = new Tween(rectangle, "x", None.easeOut, rectangle.x, character_mc.x, 6, true);
    var mobMoveY:Tween = new Tween(rectangle, "y", None.easeOut, rectangle.y, character_mc.y, 6, true);

    rectangle.visible = true;

    rectangle.addEventListener(MouseEvent.CLICK, shootMob);
    function shootMob(e:MouseEvent): void
    {
        if (contains(rectangle))
        {
            removeChild(rectangle);
            score_txt.text = String(score);
        }
        score+=20;
        trace("Score:" + score);
    }

        if (score>=60)
        {
            trace("Congratulations!");
            congratulations1_mc.visible = true;

            trace("GameLevel:" + gameLevel);

            removeChild(rectangle);
//          rectangle.visible = false;

            gameLevel = 0;

        }

    character_mc.addEventListener(Event.ENTER_FRAME, charHit);

    function charHit(event:Event): void
    {
        if (rectangle.hitTestObject(character_mc))
        {
            if (contains(rectangle))
                        {
                       removeChild(rectangle);
            if (health>0)
            {
                health-=5;
                health_txt.text = String(health);
                trace("boop");
                trace("Health:" + health);
            } else if (health<=0) {
                    trace("You have died");
                    death_mc.visible = true;
                    gameLevel=0;

            }
    }

}
}

A: You've misplaced a }. shootMob should include the (score>=60) block.

A: Writing one function inside another function is a bad coding style. What about this instead:

    import flash.events.MouseEvent;
    import flash.events.Event;
    import fl.transitions.Tween;
    import flash.text.TextField;
    import flash.display.MovieClip;

 var score_txt:TextField = new TextField(50,50,0xFFFFF);
    var score:Number;
    var gameLevel:int = 1;

 var rectangle:MovieClip;

    //function spawnMob1():void
    //{
        if (gameLevel==1)
        {
   rectangle = new ball_mc()

    rectangle.x =  randomRange(583);
    rectangle.y =  randomRange(100);
    addChild(rectangle);

    var mobMoveX:Tween = new Tween(rectangle,"x",None.easeOut,rectangle.x,character_mc.x,6,true);
    var mobMoveY:Tween = new Tween(rectangle,"y",None.easeOut,rectangle.y,character_mc.y,6,true);
     rectangle.visible = true;

    rectangle.addEventListener(MouseEvent.CLICK, shootMob);

}

    function shootMob(e:MouseEvent):void
    {
        if (contains(rectangle))
        {
            removeChild(rectangle);
            score_txt.text = String(score);
        }
        score +=  20;
        trace("Score:" + score);

    if (score>=60)
    {
        trace("Congratulations!");
        congratulations1_mc.visible = true;
        trace("GameLevel:" + gameLevel);
        if(rectangle || congratulations1_mc.visible == true)
        removeChild(rectangle);
        gameLevel = 0;
    }
}

    character_mc.addEventListener(Event.ENTER_FRAME, charHit);

    function charHit(event:Event):void
    {
        if (rectangle.hitTestObject(character_mc))
        {
            if (contains(rectangle))
            {
                removeChild(rectangle);
                if (health>0)
                {
                    health -=  5;
                    health_txt.text = String(health);
                    trace("boop");
                    trace("Health:" + health);
                }
                else if (health<=0)
                {
                    trace("You have died");
                    death_mc.visible = true;
                    gameLevel = 0;

                }
            }
        }
    }


text:
Q: Joomla 2.5 display wrong custom form field in debian or linux server Please help me on this.
I recently created a new Component for Joomla 2.5.
In my component, I have a form and I defined my form using xml in administrator/component//models/form
In this form, I have a custom field. It extends JFormField. It display a list of checkboxes which are loaded from database.
the result is:
In my local computer (running window 7), It displays correctly a list of checkboxes.
However, when I install my component to my server which is running debian or linux, It only shows a text box (input type="text")
Have anybody has any solutions about this? Please ask me, if this is not clear enough.
Thanks in advance
Nathan

A: SOLVED
it is very simple. just change the name of the custom field form to all lowercase not case-camel


text:
Q: Why does MPI give segmentation fault when I allocate memory for a second time for a second array? So here is the code that works with // before the lines that cause the segmentation fault:
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[]) {
  float *delta;
  int size,rank,*arr;

  MPI_Init (&argc, &argv); //initialize MPI library
  MPI_Comm_size(MPI_COMM_WORLD, &size); //get number of processes
  MPI_Comm_rank(MPI_COMM_WORLD, &rank); //get my process id

    if (rank==0){
        //MPI_Alloc_mem(2*sizeof(int),MPI_INFO_NULL,arr);
        MPI_Alloc_mem(3* sizeof(float),MPI_INFO_NULL,delta);
        delta[0]=1;
        delta[1]=2;
        //arr[0]=1;
        for (int i=1; i<size; i++){
            MPI_Send(delta,3,MPI_FLOAT,i,4,MPI_COMM_WORLD);
            //MPI_Send(arr,2,MPI_INT,i,4,MPI_COMM_WORLD);
        }
    }
    else{
        MPI_Recv(delta, 3, MPI_FLOAT, 0, 4, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        //MPI_Recv(arr, 2, MPI_INT, 0, 4, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
  }
  printf("delta:%f from process: %d\n",delta[0],rank);
  //printf("arr:%d from process: %d\n",arr[0],rank);
  MPI_Finalize(); //MPI cleanup
  return 0;
}

And here is the code that doesn't work:
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[]) {
  float *delta;
  int size,rank,*arr;

  MPI_Init (&argc, &argv); //initialize MPI library
  MPI_Comm_size(MPI_COMM_WORLD, &size); //get number of processes
  MPI_Comm_rank(MPI_COMM_WORLD, &rank); //get my process id

    if (rank==0){
        MPI_Alloc_mem(2*sizeof(int),MPI_INFO_NULL,arr);
        MPI_Alloc_mem(3* sizeof(float),MPI_INFO_NULL,delta);
        delta[0]=1;
        delta[1]=2;
        arr[0]=1;
        for (int i=1; i<size; i++){
            MPI_Send(delta,3,MPI_FLOAT,i,4,MPI_COMM_WORLD);
            MPI_Send(arr,2,MPI_INT,i,4,MPI_COMM_WORLD);
        }
    }
    else{
        MPI_Recv(delta, 3, MPI_FLOAT, 0, 4, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        MPI_Recv(arr, 2, MPI_INT, 0, 4, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
  }
  printf("delta:%f from process: %d\n",delta[0],rank);
  printf("arr:%d from process: %d\n",arr[0],rank);
  MPI_Finalize(); //MPI cleanup
  return 0;
}

Why does allocating memory for a second time cause this?
I also tried this with malloc instead of MPI_Alloc_mem just in case but didn't really change anything.

A: You allocate your buffers only on process zero: on the other processes there is no buffer. Maybe you're confused how send/recv work: they don't send a buffer, but the contents. So the receiver needs to have space allocated to receive the data in. The receive call does not create the buffer, it only puts data in it.

A: I am not familiar with MPI_Alloc_mem so I am using malloc.
As @Victore Eijkhout mentioned, you need to allocate the same amount of memory for your array on every process. here is a working version of your code:
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *argv[]) {
  float *delta;
  int *arr;
  int size,rank;
  int tag;
  MPI_Status status;
  MPI_Init (&argc, &argv); //initialize MPI library
  MPI_Comm_size(MPI_COMM_WORLD, &size); //get number of processes
  MPI_Comm_rank(MPI_COMM_WORLD, &rank); //get my process id

    if (rank==0){
        arr = malloc(2 * sizeof(int));
        delta = malloc(3 * sizeof(float));
        //MPI_Alloc_mem(2*sizeof(int),MPI_INFO_NULL,arr);
        //MPI_Alloc_mem(3*sizeof(float),MPI_INFO_NULL,delta);

        delta[0]=1;
        delta[1]=2;
        arr[0]=10;
        arr[1] = 20;
        for (int i=1; i<size; i++){
            MPI_Send(delta,3,MPI_FLOAT,i, 4,MPI_COMM_WORLD);
            MPI_Send(arr,2,MPI_INT,i, 4, MPI_COMM_WORLD);
        }
    }
    else{
        arr = malloc(2 * sizeof(int));
        delta = malloc(3 * sizeof(float));
        MPI_Recv(delta, 3, MPI_FLOAT, 0, 4, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
        MPI_Recv(arr, 2, MPI_INT, 0, 4, MPI_COMM_WORLD, MPI_STATUS_IGNORE);
  }
  printf("Process %d: arr:[%d, %d] | delta:[%f, %f]\n", rank, arr[0], arr[1], delta[0], delta[1]);

  MPI_Finalize(); //MPI cleanup
  return 0;
}

output:
Process 3: arr:[10, 20] | delta:[1.000000, 2.000000]
Process 0: arr:[10, 20] | delta:[1.000000, 2.000000]
Process 2: arr:[10, 20] | delta:[1.000000, 2.000000]
Process 1: arr:[10, 20] | delta:[1.000000, 2.000000]


text:
Q: Full proof of this matrix propierty I have to prove the following question:
?
I asked yesterday and got answers like "Since $A=Y^{-1}XY, A^2=(Y^{-1}XY)(Y^{-1}XY)=Y^{-1}X^2Y$. So $\alpha A^2+\beta A+γI=Y^{-1}(\alpha X^2+\beta X+γI)Y=Y^{-1}\textbf{0}Y=\textbf{0}$." but i didn't understood it at all, could someone please explain this like you would explain it to a kindergardener, BTW this is on a matrices unit so the order of multiplication actually does matter

A: Oke start by substituting:
$$\alpha A^2+\beta A +\gamma I = \alpha(Y^{-1}XY)(Y^{-1}XY)+\beta (Y^{-1}XY) +\gamma I$$
Now you mention that order of multiplication matters. That is true in the sense that matrix multiplication is not commutative, however, it is associative. Knowing that we see that
$$\alpha(Y^{-1}XY)(Y^{-1}XY)+\beta (Y^{-1}XY) +\gamma I = \alpha Y^{-1}X(YY^{-1})XY+\beta (Y^{-1}XY) +\gamma I$$
$$=\alpha Y^{-1}X^2Y+\beta (Y^{-1}XY) +\gamma Y^{-1}IY$$
$$=Y^{-1}(\alpha X^2Y+\beta XY +\gamma IY)$$
$$=Y^{-1}(\alpha X^2+\beta X +\gamma I)Y$$
$$=Y^{-1}0Y=0$$


text:
Q: "Plotting" an equation I have an equation like
$$
(x - a)^2 + (y - b)^2 = r^2
$$
that represents a circle.
I need to "plot" it very basically with a programming language. Computer graphics coordinate generally use the "lower-right" quadrant of a Cartesian plane (0, 0 being top left).
I want my circle to have its center in (200, 200) and a radius of, say, 100. All measures given in pixels.
I need to do this step by step, within a loop. So, if the loop is 100 times, i need to know at each iteration at what x and y coordinate to draw a pixel. How to this? With my center and radius, the above equation is like this
$$
(x - 200)^2 + (y - 200)^2 = 1000
$$
but still I can't figure out how to express any "advancement" of my virtual plotting device. Thanks
EDIT
My question specifically asked for the equation of a circle, but it was just an example. I have the same problem with parabolas, sins...

A: Any reasonably correct method of plotting involves interval arithmetic. At a very rough level, it involves keeping track, for a given resolution, of intervals in which no pixel is part of the plot, intervals in which every pixel is, intervals yet to be analysed, and so on, updating and colouring pixels only when sure.
You can read this very readable paper:

*

*Jeff Tupper, Reliable Two-Dimensional Graphing Methods for Mathematical Formulae with Two Free Variables, SIGGRAPH 2001

Tupper is the author of the program GrafEq which when I used it many years ago impressed me by getting graphs correctly that most other graphing programs would have trouble with. (See e.g. its rogue's gallery. or other links on the site.) It's a very nice paper. There have presumably been improvements since 2001, but it's shocking how many graphers even today don't even do as much as this paper describes clearly.

A: Midpoint circle algorithm

A: I got it working this way:
loop i := 1..N
  i := i * 2π / N
  x = center_x + (radius * cos(i - rotation))
  y = center_x + (radius * sin(i - rotation))

A: If you want to plot curves given by generic equations $f(x,y)=0$, for which you cannot express $y$ as a function of $x$ or vice-versa, see One algorithm for drawing graph of implicit function.

A: Just find y as a function of x or x as a function of y manually. Then write a loop. For example if your equation is $ x = \sqrt{y}$ write a loop that finds x for each y and then plots it. This strategy usually works poorly for computer programs (simply because x and y can take up only discrete values and that finding one variable as a function of other might not be a simple task). That is why for plotting each there are usually specific algorithms, like bressenham for lines, midpoint circle algorithm for circles etc.

for y = 1 to 100
   x = sqrt(y)
   plot((int)x,y)