text:
Q: Java / MongoTemplate Aggregation, Group and Sum not grouping as expected I have a mongo collection which has many documents containing information about credits / gifts given to our users.
I would like to be able to run an Aggregated Query to get all the users who have received a credit / gift within the last x number of days and sum the total value of those credits for each user.
I think I have the correct Aggregation, group and sum code but I'm getting back more than one object per user, which shouldn't be the case since I'm grouping and then summing the values(?)
Here is what my document structure looks like:
    _id: ObjectId("61c36a8a21047124c4181271"),
    transactionId: UUID("6fbf536e-7a53-442c-9615-53e32362608b"),
    userId: 'xxxxx',
    transactionMessage: 'Account credited with: 1',
    transactionType: 'CREDIT',
    transactionAction: 'GIFT',
    inComingPaymentFromUserId: 'xxxx',
    transactionAmount: Decimal128("1"),
    customMessage: "blah'",
    createdDate: ISODate("2021-12-22T18:12:26.812Z"),
    lastUpdatedAt: ISODate("2021-12-22T18:12:26.812Z"),

And here is my query code:
    @Override
    public List<RecentlyRewardedUsers> findRecentlyRewardedUsers(Integer range, Pageable pageable) {
        Aggregation agg = Aggregation.newAggregation(
                match(Criteria.where("createdDate").gt(LocalDate.now().minusDays(range))
                        .andOperator(Criteria.where("transactionAction").is("GIFT"))), sort(Sort.Direction.DESC, "createdDate"),
                group("userId", "_id").sum("transactionAmount").as("totalValueAwarded"),
                project("userId", "totalValueAwarded"),
                skip((long) pageable.getPageNumber() * pageable.getPageSize()),
                limit(pageable.getPageSize()));
        try {
            return mongoTemplate.aggregate(agg, "Transactions", RecentlyRewardedUsers.class).getMappedResults();
        } catch (Exception ex) {
            throw new ServiceUnavailableException("Unable to perform Mongo Operation {" + ex.getLocalizedMessage() + "}", "User");
        }
    }

Here is also my mapped class:
@Getter
@Setter
public class RecentlyRewardedUsers {

    @Field("userId")
    private String userId;
    private String totalValueAwarded;
    private String userDisplayName;
    private String profilePicUrl;
}

Like I said above, when the the results of the query are mapped to the RecentlyRewardedUsers class, I see multiple entries for the same userId (see image below). I would have thought it should be all rolled up / summed up into one entry for that userId

If anyone can shed some light on what I've done wrong that would be great!!
Thank you
** EDIT **
Based on the answer below from
user Eskandar Abedini, I've updated my code to be the following:
Criteria operator = new Criteria();
operator.andOperator(
        Criteria.where("createdDate").gt(LocalDate.now().minusDays(2))
                .andOperator(Criteria.where("transactionAction").is("GIFT")));

MatchOperation matchOperation = Aggregation.match(operator);

GroupOperation groupOperation = Aggregation.group("userId").sum("transactionAmount").as("totalValueAwarded");
List<String> sortOptions = new ArrayList<>();
sortOptions.add("createdDate");
Sort sort = new Sort(Sort.Direction.DESC, sortOptions);
SortOperation sortOperation = Aggregation.sort(sort);

Aggregation aggregation = Aggregation.newAggregation(Transaction.class, matchOperation, groupOperation, sortOperation);

AggregationResults<RecentlyRewardedUsers> aggregationResults = mongoTemplate.aggregate(aggregation, Transaction.class, RecentlyRewardedUsers.class);

When I now execute the above I get this error:
java.lang.IllegalArgumentException: Invalid reference 'createdDate'!

If for the moment I remove the sort options. The code will execute. However I'm not getting the userId mapped into my RecentlyRewarded class.
Criteria operator = new Criteria();
operator.andOperator(
        Criteria.where("createdDate").gt(LocalDate.now().minusDays(2))
                .andOperator(Criteria.where("transactionAction").is("GIFT")));

MatchOperation matchOperation = Aggregation.match(operator);

GroupOperation groupOperation = Aggregation.group("userId").sum("transactionAmount").as("totalValueAwarded");
Aggregation aggregation = Aggregation.newAggregation(Transaction.class, matchOperation, groupOperation);

AggregationResults<RecentlyRewardedUsers> aggregationResults = mongoTemplate.aggregate(aggregation, Transaction.class, RecentlyRewardedUsers.class);

Any help would be amazing.
Thank you
Edit
Adding image to show what I mean by userId not being mapped in the MappedResponse. However in the Raw response of the query the userId is getting mapped to the documentId _id

A: Remove _id from group("userId", "_id")
This is somehow similar to yours, its implementation is clear too.
public BaseResponse getErrorLogGroupByAppName() throws BaseException {

    Criteria operator = new Criteria();
    operator.andOperator(
            Criteria.where("execDate").is(DateUtil.today())
    );

    MatchOperation matchOperation = Aggregation.match(operator);

    GroupOperation groupOperation = Aggregation.group("serUrl", "serPort", "appName", "appSer", "reqUrl", "execDate").count().as("count");

    Sort sort = new Sort(new Sort.Order(Sort.Direction.DESC, "count"));
    SortOperation sortOperation = Aggregation.sort(sort);

    Aggregation aggregation = Aggregation.newAggregation(ErrorInfo.class, matchOperation, groupOperation, sortOperation);

    AggregationResults<Map> aggregationResults = template.aggregate(aggregation, ErrorInfo.class, Map.class);

    return new BaseResponse(aggregationResults.getMappedResults());
}

GitHub Source


text:
Q: Writing "\r" with std::cout to file saves previously overwritten lines I'm running simulations using C++, and to track the simulation progress I'm writing outputs as std::cout << "\rSimulation progress: " << progress;, as per this answer https://stackoverflow.com/a/3057994/4237753. So with "\r" I thought I was overriding the previous line, but when I save the output to log files, the previously overridden lines are saved as well, with a ^M before each instance of the "overridden" lines. Now I have log files that are around 100MB when they would only need to be a few KB.
An example of what the file looks like:
^MSimulation progress: 66.500^MSimulation progress: 66.600^MSimulation
progress: 66.700^MSimulation progress: 66.800^MSimulation progress:
66.900^MSimulation progress: 67.000^MSimulation progress: 67.100^MSimulation
progress: 67.200^MSimulation progress: 67.300

What I want for this line is only the last instance
Simulation progress: 67.300

Is there a good way or a standard way to remove the lines for real?
Thanks!

A: \r is an an output control symbol. When you write \r to file it is only an additional symbol in it.
You can't override the line in a file with \r.

A: There is none. Terminals are not standardized in any way. Just as a file they take a stream of bytes, but they can react differently to the input you give them.
I.e. some are able to color using escape syntax. It just happens, that a terminal you are using treats \r to go back to beginning of the line and start over writing. For the file output it's just a byte to write with out any special meaning. You are not even guaranteed that \r will reset line on every terminal you run it. It is system depended.
My best advice it to decouple your UI and your log. Those are generally a different things. You don't have to put the same information into the file and the screen.
To be able to make the file stream behaviour coherent with terminal, would require to write custom fstream buffer, which would recognize \r and seek-back to last \n. It does not sound too reasonable.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where does the energy within atoms come from? Most kinds of energy I know about involve a finite measurement and are transferred. In other words, energy in the universe is finite and is not lost or gained but only transferred through space one way or the other.
I was contemplating how an object, a table for instance, in order to apply enough outward force to hold an object off of the ground must have a sort of energy keeping all of its atoms together.
Atomic bonds involve energy, I assume.
My question is how does this energy work?

*

*where does it come from?

*is it infinite?

*how/why is that energy different from other kinds of energy?

After-thought:
I notice there are some things in physics, such a gravity, that we know a whole lot about how it behaves but close to nothing about why it behaves in the first place. Perhaps this is one of those things.

A: First of all I recommend you to see in Internet Richard Feynman's WHY". It is exactly what he discusses, our questions about why.
An electron in an atom has two major types of energy, kinetic and potential. The first one is due to the fact that the electron performs a motion, e.g. if we calculate the average of the absolute square of the linear momentum of the electron in the ground state of a Hydrogen atom we find $< \hat {P^2} > \ = \ \frac {\hbar ^2}{a_0^2}$,
where $a_0$ is the Bohr radius.
The potential energy comes from the fact that between the electron and proton there exists an electrostatic field.
Now, why does the electron have a movement inside the atom? If the electron were localized at some time to a fix position, the uncertainty principle tells us that its linear momentum could have any value and it is not clear if the electron would remain in the atom.
Where from comes the potential energy: there are a couple of fundamental interactions with which is endowed our universe, and the e.m. interaction is one of them, see in Internet Richard Feynman's WHY. The types I recall are e.m. interaction, strong, weak, and gravitational. As Feynman explains, the existence of these interactions are fundamental axioms of our universe.
By what the energy in atoms (molecules) differs from other energies? Gravitational energy is due to just another type of interaction with which our universe is endowed. Strong interaction is what keeps together the components that constitute the hadrons (protons and neutrons) and the residual strong interaction keeps the hadrons together in the nuclei.


text:
Q: Wrong section LMA address when using LD file I need to load the data sections in different address from VMA.
so I defined 2 typed of memory and updated the LD file,
for example bss section:
.bss : ALIGN(0x20) {
        PROVIDE(__bss_start = ABSOLUTE(.));
        *(.bss .bss.*)
        PROVIDE(__common_start = ABSOLUTE(.));
        *(COMMON)
        PROVIDE(__common_end = ABSOLUTE(.));
        PROVIDE(__bss_end = ABSOLUTE(.));
        PROVIDE(__common_size = ABSOLUTE(+__common_end - __common_start));
        PROVIDE(__bss_size = ABSOLUTE(+__bss_end - __bss_start));
    } >MY_EXTERNAL AT>INTERNAL_DATA

so the load addrees is mapped to INTERNAL_DATA .
after bss section I have __STACK_SECT:
__STACK_SECT : ALIGN(0x10) {
      PROVIDE( __stack_start = ABSOLUTE(.));
       . = . + __stack_size;
       *(.stack .stack*)
      PROVIDE( __stack_end = ABSOLUTE(.));
     PROVIDE( __stack_size = ABSOLUTE(__stack_end - __stack_start));
   } >MY_EXTERNAL AT>INTERNAL_DATA

and in the elf file I see:
Idx Name          Size      VMA       LMA       File off  Algn
  3 .bss          0000020c  20000d20  00000d20  00005e80  2**5
                  ALLOC
  4 __STACK_SECT  00004000  20000f30  00000d20  00005e80  2**4

the bss address looks good (0x20000000 is my offset) while __STACK_SECT isn't, the LMA should be 0xf30, and for some reason I got the same LMA as bss, seems like the pointer in INTERNAL_DATA isn't increased after defining the bss section.
why is that? and how to fix it?
note 1: previous sections works fine and I did the same defintion.
note 2: orginally I have  (NOLOAD)  after bss and __STACK_SECT , I tried to delete this and didn't help


text:
Q: How do I feed data to a pipe until it's full, no more no less? I want to use pipes on Linux as a synchronization primitive between a master process and a slave process. The classic way is to create two pipes, but I believe there's a way to use a single fd instead. Consider:

*

*The slave creates r-w pipe.

*Read end r is passed to the master.

*When the slave is ready, it writes to w N bytes, then N bytes again, then 1 byte, where N is the pipe buffer size. The first write(2) returns immediately, the second blocks because the buffer is full.

*Master blocks and reads from r. The second write(2) returns, the third write(2) blocks.

*After the master has read data, it does whatever stuff it has to.

*When the slave is to be resumed, master reads once more from r. The third write(2) returns and the slave proceeds.

However, the man page for fcntl says this:
   Changing the capacity of a pipe
       F_SETPIPE_SZ (int; since Linux 2.6.35)
              ...

              Note that because of the way the pages of the pipe buffer are
              employed when data is written to the pipe, the number of bytes
              that can be written may be less than the nominal size, depend‐
              ing on the size of the writes.

The man page seems to say that if the pipe buffer size is N bytes and I write M<=N bytes to the pipe, it is possible that the write will block. In what cases can that happen (except the simple case when there is already much data in the pipe)?
Additionally, "depending on the size of the writes" sounds odd. Can I get this strange behavior if I write exactly N bytes?

A: I would not rely on this element of behaviour.  Pipes are intended to be a continuous stream of data.  Reads and writes cannot be matched against each other easily, the only real guarantee you should rely on is that the first bytes in will be the first bytes out.
The reason for the manual comment regarding buffer paging is that pipes rely on a ring buffer.  From the manual I would infer that the "ring" is a ring of pages not a ring of bytes.  IE: pages fill up, when the page is full, the next page is used.  Pages are not re-used until they have been fully read.  This means a half-read page will not be available at all for writing.  That's just an inference from the manual, I've not checked the source code.
The biggest problem with relying on this behaviour is it's an implementation detail rather than an intended effect of the pipe.  Kernel developers may change this at any time and your code will suddenly have race conditions.

A: Being said that, if the only intention is synchronizing, the "classic way",as you call it, has never ever been using pipes.
Use semaphores or signals instead.
Because the pipe capacity changes depending on implementations and has actually changed several times since the first POSIX implementation... the documentation you refer to explicitly writes :

Applications should not rely on a particular capacity

If I understand it correctly then you should find the answer to your question as part of the man page for pipe :

POSIX.1-2001 says that write(2)s of less than PIPE_BUF bytes must be
atomic: the output data is written to the pipe as a contiguous
sequence. Writes of more than PIPE_BUF bytes may be nonatomic: the
kernel may interleave the data with data written by other processes.
POSIX.1-2001 requires PIPE_BUF to be at least 512 bytes. (On Linux,
PIPE_BUF is 4096 bytes.) The precise semantics depend on whether the
file descriptor is nonblocking (O_NONBLOCK), whether there are
multiple writers to the pipe, and on n, the number of bytes to be
written


text:
Q: Calc II - Definite integral of sqrt(t^2 + t) from 2x to 1? How do I find
$$\int_1^{2x}\sqrt{t^2 + t}$$
with only knowledge from a Calculus I course?
I've tried plugging this puppy into Wolfram Alpha and other integral solvers, which report it as solvable (looks really long and nasty), but I think this is outside the scope of my just-entered-Calc-II knowledge and that I need to solve it in a tricky way.
The problem is part of the linked green sheet. Since I don't know how to integrate this I've tried to solve the sheet without doing so, though on part D) it seems like my luck is about to run out. I doubt what I am trying to do is even legal. Please advise.

A: We have, by setting $t=2u$,
$$ F(x)=\int_{1}^{2x}\sqrt{t^2+t}\,dt = 2\int_{1/2}^{x}\sqrt{4u^2+2u}\,dt$$
so:
a) $$F'(x) = 2\sqrt{4x^2+2x}$$
b) The domain of $F(x)$ is $[0,+\infty)$, since $4u^2+2u$ is negative for any $u\in(-1/2,0)$.
c) $$\lim_{x\to 1/2}F(x)=0$$
since $\sqrt{4u^2+2u}$ is a continuous function in a neighbourhood of $u=1/2$.
d) $$L(\gamma)=\int_{1}^{2}\sqrt{1+F'(x)^2}\,dx = \int_{1}^{2}\sqrt{16x^2+8x+1}\,dx=\int_{1}^{2}(4x+1)\,dx=7.$$


text:
Q: Validating boolean with Laravel Validation I have a login form with
username, password and remember me
remember me is a checkbox (true or false).
How do I create the validation rule in Laravel?
http://laravel.com/docs/validation#basic-usage
The only relevant one it seems was in and you specify the values but the values in this case are booleans and using this method they would be specified as string?
in:true,false

A: You may try something like this:
$rules = array('email' => 'required|email', 'password' => 'required');
$inputs = array(
    'email' => Input::get('email'),
    'password' => Input::get('password')
);
$validator = Validator::make($inputs, $rules);

if($validator->fails()) {
    return Redirect::back()->withInput()->withErrorts($validator);
}
else {
    $remember = Input::get('remember', FALSE);
    if(Auth::attempt($inputs, !!$remember)) {
        // Log in successful
        return Redirect::to('/'); // redirect to home or wherever you want
    }
}

I've used email which is recommended but if you use username other than email then just change the email to username and in the rule for username use something like this:
'username' => 'required|alpha|min:6' // Accepts only a-z and minimum 6 letters

A: There's a validator for boolean. Assuming you're using one of the packages that simplifies model validation, e.g. EsensiModel, it's as simple as adding the following to your Model:
protected $rules = [
    'email'       => 'required|email',
    'password'    => 'required',
    'remember_me' => 'boolean',
];


text:
Q: Defining Dirac's Delta in one dimensional with two variable I have a problem in one dimension (x-axis) with two spatial variables $x_{1}$ and $x_{2}$ and I have an Dirac's Delta $\delta(x_{1}-x_{2})$. My question is: how can I properly define this $\delta$?
I thought about
$$\delta(x_{1}-x_{2}) \varphi(x) = \varphi(x_{2})$$ for all $\varphi \in C^{\infty}_{c}(\mathbb{R})$.
Is this definition mathematically precise? I don't know if this is correct (I thought maybe $\varphi(x_{1},x_{2})$ and $\delta(x_1 - x_2) \varphi(x_1, x_2) = \varphi(x_{2})$ but I'm not sure either).
Thanks.

A: Let $L=\{(x,y)\in\Bbb{R}^2\,|\,\,x=y\}$, i.e this is the "diagonal line" in the plane. We can now define a (tempered) distribution $\delta_L$ on $\Bbb{R}^2$ by setting for each Schwartz function $\phi\in\mathcal{S}(\Bbb{R}^2)$,
\begin{align}
\langle\delta_L,\phi\rangle&:=\int_L\phi(x,y)\,dl(x,y)=\int_{\Bbb{R}}\phi(t,t)\,dt\,\tag{$*$}
\end{align}
Here, $dl$ denotes the "volume element" on the submanifold $L$, or in this case simply the line element, which as the final equality shows is a very simple one-dimensional integral.
This should intuitively be a reasonably definition because the quantity $\delta(x-y)$, where $(x,y)\in\Bbb{R}^2$ should be $0$ if $x\neq y$, so if we "integrate" a function $\phi$ against $\delta(x-y)$, then
\begin{align}
\int_{\Bbb{R}^2}\delta(x-y)\phi(x,y)\,dxdy&\,\,\,\, ``="\int_{L}\phi(x,y),
\end{align}
and we should be integrating with respect to the line element on $L$, rather than the Lebesgue measure on $\Bbb{R}^2$, because otherwise we get a trivial $0$ (since a line $L$ in the plane has zero Lebesgue measure). Hopefully this heuristic reasoning motivates the precise definition $(*)$ above.


text:
Q: Sphinx search not giving id and text field information I am very new to sphinx and I have a small question. I have sphinx.conf file as follows
sql_query       = \
    SELECT id, user_id, title \
    FROM table

sql_attr_uint       = user_id
sql_query_info      = SELECT * FROM table WHERE id=$id

I have a php file that utilizes sphinxapi.php and contains the following code
  // connect to mysql database //
    require_once('sphinxapi.php');
    $s = new SphinxClient;
    $s->setServer("127.0.0.1", 9312);
    $s->setMatchMode(SPH_MATCH_ANY);
    $s->SetLimits(0, 2);
    $result = $s->Query('test words');

If I print $result it has user_id fields but doesn't contain id or title fields. Is there a way to retrieve those too?

A: It will have the id. Its jsut not in the 'attrs' array, its the key of the 'matches' array.
The 'text' of fields is not stored, so sphinx can't return it. To get the title, go back to your original database. It will be a very quick query as it can just use the list of ids in a IN(..) query.
(although you can opt to put the text in a string attribute, which sphinx will then store and return in the attrs array. Can use sql_field_string, to make a column, BOTH a field and an attribute)

A: try this
sql_query       = \
    SELECT id, user_id, title, title as title_str \
    FROM table

sql_field_string = title_str


text:
Q: How to override responsive features in Twitter Bootstrap 2? I have a site using twitter bootstrap and am using some of the responsive features.  It works fine on the desktop and the mobile devices.  Shrinking my window on the desktop cause the responsive grid to kick in, and the responsive grid is served to the mobile device appropriately.
However, is it possible for an iPhone user to access the 'non-responsive' version?  It's usually safe for iPhone and android phones to access the 'full' version of most sites, so I'd like to offer that as an option for the mobile users.
Back before 'responsive' was the hottest thing, this was typically handled via client browser detection and the backend routed the clients to two completely different sites, pages, or themes to render the content, and there was usually some kind of link or button afforded to the user to allow them to visit the full-site instead.  I'm trying to replicate that usage pattern.

A: If you don't want to reload your page after the change to the "desktop" version you could try to disable your repsonsive stylesheet(s).
See: Removing or replacing a stylesheet (a <link>) with JavaScript/jQuery and https://stackoverflow.com/a/15824131/1596547. Also Removing the stylesheet seems to work.
Some proof of concept with removing the responsive stylesheet:
css:
<link href="bootstrap-responsive.css" rel="stylesheet" id="responsivecss">

javascript:
    var responsivecss = true;

    $('#switch').click(

    function ()
        {
            if(responsivecss)
            {
        $('#responsivecss').remove();
      $(this).text('Mobile version');
              responsivecss = false;

            }
            else
            {
      $('head').append('<link href="bootstrap-responsive.css" rel="stylesheet" id="responsivecss">');
      $(this).text('Desktop version');
                responsivecss = true;
            }

        }

    );

Try it: http://plnkr.co/LdOUquuYPMnOOd5UrBtZ
Twitter's Bootstrap 3
TB3 don't have a separate responsive CSS file. To do the same you will have to create a css file without the responsive features (see: http://bassjobsen.weblogs.fm/compile-twitters-bootstrap-3-without-responsive-features/) an switch these files on click.


text:
Q: Syntax for retrieving data from GET, Host: function using APIs I am using a price API. On the developer guide, the request example for Iphone 6 is shown as :
GET /api/v1/compare/search?product=iphone%207&api_key=YOUR_API_KEY HTTP/1.1
Host: https://price-api.datayuge.com

I have the API Key, but how should I use this in order to retrieve data (JSON format). Do I use $.ajax(), $.getJSON() or something else completely?
This is the website that explains different formats, but I am not understanding how to put this all together:


text:
Q: Ionic 2: navigate using URLs I am very new in Ionic 2 framework. I would like to know, how can I navigate in ionic app using urls. Similar way as navigation is done in Angular 2 application.
Let's say I want to have IntroPage on localhost:8100/intro with login button and after pressing the button I want to be redirect to HomePage on localhost:8100/home.
localhost:8100/intro -> localhost:8100/home

A: You can use DeepLinker of ionic2.
In ionic2, you can navigate just with this.navigator.push(SomeComponent). But if you want the url change, you need define deeplinker for them like:
imports: [
 IonicModule.forRoot(MyApp, {}, {
  links: [
   { component: HomePage, name: 'Home', segment: 'home' }
  ]
 })
]

A: as documentation says : (https://ionicframework.com/docs/v2/api/navigation/NavController/)
you cannot still use ui-sref like in ionic 1..but only this.navigation.push('home')... it means you have to do a function on a html (maybe a (click)="myfunc()" ) to call the navigation in ts file
import { Component, ViewChild } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
   template: '<ion-nav #myNav [root]="rootPage"></ion-nav>'
})
export class MyApp {
   @ViewChild('myNav') nav: NavController
   public rootPage = TabsPage;

   // Wait for the components in MyApp's template to be initialized
   // In this case, we are waiting for the Nav with reference variable of "#myNav"
   ngOnInit() {
      // Let's navigate from TabsPage to Page1
      this.nav.push('home');
   }
}


text:
Q: Building gatsby site on Netlify - err: Callback was already called I can't resolve issue with building gatsby site on netlify. Since a few days I'm getting following error:
3:17:52 PM: error UNHANDLED EXCEPTION Callback was already called.
3:17:52 PM:
3:17:52 PM:   Error: Callback was already called.
3:17:52 PM:
3:17:52 PM:   - async.js:16 throwError
3:17:52 PM:     [repo]/[neo-async]/async.js:16:11
3:17:52 PM:
3:17:52 PM:   - async.js:2818
3:17:52 PM:     [repo]/[neo-async]/async.js:2818:7
3:17:52 PM:
3:17:52 PM:   - next_tick.js:132 _combinedTickCallback
3:17:52 PM:     internal/process/next_tick.js:132:7
3:17:52 PM:
3:17:52 PM:   - next_tick.js:181 process._tickCallback
3:17:52 PM:     internal/process/next_tick.js:181:clock9

Package.json
{
  "name": "gatsby-starter-netlify-cms",
  "description": "Example Gatsby, and Netlify CMS project",
  "version": "1.1.3",
  "author": "Austin Green",
  "dependencies": {
    "bulma": "0.7.5",
    "gatsby": "2.17.0",
    "gatsby-image": "2.2.29",
    "gatsby-plugin-disqus": "1.1.4",
    "gatsby-plugin-google-tagmanager": "2.1.15",
    "gatsby-plugin-netlify": "2.1.22",
    "gatsby-plugin-netlify-cms": "3.0.18",
    "gatsby-plugin-offline": "2.2.10",
    "gatsby-plugin-purgecss": "2.4.0",
    "gatsby-plugin-react-helmet": "3.1.13",
    "gatsby-plugin-robots-txt": "1.5.0",
    "gatsby-plugin-sass": "2.1.20",
    "gatsby-plugin-sharp": "2.2.32",
    "gatsby-plugin-sitemap": "2.2.21",
    "gatsby-remark-autolink-headers": "2.1.16",
    "gatsby-remark-copy-linked-files": "2.1.28",
    "gatsby-remark-images": "3.1.28",
    "gatsby-remark-prismjs": "3.3.20",
    "gatsby-remark-relative-images": "^0.2.3",
    "gatsby-source-filesystem": "2.1.33",
    "gatsby-transformer-remark": "2.6.30",
    "gatsby-transformer-sharp": "2.3.0",
    "lodash": "4.17.15",
    "lodash-webpack-plugin": "0.11.4",
    "netlify-cms": "2.9.7",
    "node-sass": "4.12.0",
    "parcel-bundler": "1.12.4",
    "prismjs": "1.17.1",
    "prop-types": "15.7.2",
    "react": "16.10.2",
    "react-dom": "16.10.2",
    "react-helmet": "5.2.1",
    "uuid": "3.3.3"
  },
  "keywords": [
    "gatsby"
  ],
  "license": "MIT",
  "main": "n/a",
  "scripts": {
    "start": "npm run develop",
    "clean": "rimraf .cache public",
    "build": "npm run clean && gatsby build",
    "develop": "npm run clean && gatsby develop",
    "serve": "gatsby serve",
    "format": "prettier --trailing-comma es5 --no-semi --single-quote --write \"{gatsby-*.js,src/**/*.js}\"",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "devDependencies": {
    "prettier": "1.18.2",
    "rimraf": "2.7.1"
  }
}

Using Node 8.
Full deploy log available here: https://app.netlify.com/sites/gallant-mcnulty-8ac2d3/deploys/5e0a0637af09c64352a2e783
On localhost server all works well.
I tried build site on new netlify's instance but I'm getting the same error.
Thanks for any advice.
Cheers

A: I had the same issue. Updating gatsby-plugin-netlify-cms to latest version helped.

A: Recently saw the same build issue even after having the gatsby-plugin-netlify-cms. My issue was that netlify defaulted to node version 10. I had setup my project with node version 12.
To set the node version for deploy you can set a NODE_VERSION in the netlify UI or you can set one in the project root with .node-version or .nvmrc. Thus, adding v12 to .node-version in my project root fixed the build issue.
https://docs.netlify.com/configure-builds/manage-dependencies/#node-js-and-javascript


text:
Q: How to prove that a given set is recursively enumerable? I was given a set
$$
A = \{x \mid W_x \, \text{contains at least one prime number}\}
$$
where $W_x = \{y\mid \phi_x(y) \downarrow \}$ is the Dom of the function $\phi_x$
$\downarrow$ means that the function converges or halts.
Any hints on what to prove first?
I am not even sure how to tackle this kind of problem as it doesn't look like anything we have solved during the lessons so far.

A: I'll give the answer in Turing machines.
First, build a Turing machine R(x, y, z) with 3 inputs that does the following

*

*Check if x is a syntactically valid encoding of a Turing machine.

*Check if y encodes a number and the number is prime.

*Check if z is a valid encoding describing a run of the TM x on input y that stops and accepts.
If all steps succeed, R stops and accepts.  Else rejects.
R is a deterministic TM that halts on all inputs - therefore computable.
A is the set $\{x:\exists y \exists z R(x,y,z)\}$ so is computably enumerable.
Now translate to recursive functions.


text:
Q: How Can I connect to Amazon Linux instance using Remote Desktop from Windows 7? I created an EC2 Amazon Linux instance (yes, an amazon version of linux..)
it is launched but I can't connect using Remote Desktop...
am I trying to do something crazy here?
I got a message that Remote Computer is not available on the network

A: If you mean Windows RDP (Remote Desktop) that is your problem. Most likely you will need to use an SSH client to connect. I suggest Putty.
You should've received an SSH key when you setup your server. You will need to convert that key using PuttyGEN (same page as the Putty download) to convert it then use it with Putty to access the server.
Trying to walk you through the process of installing a GUI and VNC on the server is a bit much for here but give this video a shot. It seems pretty thorough and from skipping through it I saw no obvious errors in his process.

A: Try installing the vnc4server package. Then you can use a client such as TightVNC to connect from a Windows machine. You'll also need to open up port number 5900 in your firewall, which is the default for VNC.
You'll also have to have a desktop environment installed on your EC2 instance - by default you may only have the server packages which will not give you a GUI.

A: For your information, some folks posted remote desktop conf for EC2 instances.
http://activeintelligence.org/blog/archive/remote-graphical-linux-desktop-on-ec2/


text:
Q: LEFT OUTER JOIN conditions for two queries? I have the following two queries to find pageviews and orders for each week starting from Jan 2014.
select productid,
EXTRACT (week from dt)as WEEK,
count(productid)as PageViews
from PageView
where client = 'XYZ'
and dt between '2014-06-01' and '2014-06-30'
GROUP BY WEEK, productid
ORDER BY WEEK asc;

and
select
count(distinct t.orderid),
EXTRACT(week from t.dt) AS WEEK
FROM Transaction t
where t.client = 'XYZ'
and t.dt between '2014-01-01' AND '2014-06-30'
GROUP BY WEEK
ORDER BY WEEK asc;

In order to get the correct data, I need to create a condition on join which matched the week from Transaction and PageView Tables , something like Week from Transaction = Week from PageView. I however have no clue of what the syntax for this would be like .
Doing a simple
PageView pv LEFT OUTER JOIN Transaction t
ON pv.productid = t.productid
AND EXTRACT(week from t.dt) = EXTRACT(week from pv.dt)

does not give a correct output (i.e. the pageviews and Orders are coming significantly high). Can someone please shed some light on how to combine these two queries two get a desired output which is all the products from PageView table and corresponding Orders from the Transaction table grouped by week

A: select week, pid, pageviews, orders
from
    (
        select
            date_trunc('week', dt) as week,
            productid as pid,
            count(productid) as pageviews
        from pageview
        where client = 'XYZ' and dt between '2014-06-01' and '2014-06-30'
        group by 1, 2
    ) pv
    full outer join
    (
        select
            date_trunc('week', dt) as week,
            product_id as pid,
            count(orderid) as orders
        from transaction
        where client = 'XYZ' and dt between '2014-01-01' and '2014-06-30'
        group by 1, 2
    ) t using (week, pid)
order by 1, 2

A: I think the problem is ON pv.productid = t.productid AND EXTRACT(week from t.dt) = EXTRACT(week from pv.dt)
This can't be on the left join.  ID's between PV and T may match but the weeks may be null in some cases. so an AND would eliminate the left join.
So you just have to join on the ID's first so you have the resulting Cartesian.  Then you need to filter out the non-matching weeks but leave in the T.Null values..  However it assumes that t.dt can't be null if it can be null the counts may still be off depending on how you want to handle nulls in the transaction table date.
Additionally you may need to use inline views (but I think this is overkill)
SELECT *
FROM
(select productid,
  EXTRACT (week from dt)as WEEK,
  count(productid)as PageViews
  from PageView
  where client = 'XYZ'
  and dt between '2014-06-01' and '2014-06-30'
  GROUP BY WEEK, productid) PV
LEFT JOIN (
  SELECT
  count(distinct t.orderid),
  EXTRACT(week from t.dt) AS WEEK
  FROM Transaction t
  where t.client = 'XYZ'
  and t.dt between '2014-01-01' AND '2014-06-30'
  GROUP BY WEEK) T
ON pv.productid = t.productid  --The gold is in this and the next line
WHERE (T.Week = PV.Week OR T.Week is null)  --don't forget this one.

I don't think this will work...
ON (PV.ProductID=T.productID and T.Week=PV.Week)
 OR (PV.ProductID = T.ProductID AND T.Week is null)
because T.Week will not have been evaluated yet as the Cartesian will not have been generated. thus why I think it belongs in the where.


text:
Q: Django: removing item from many-to-many relation more efficiently My book class uses a many-to-many field to save its readers. If I want to remove a reader from some books, I can use a loop to go through all book objects to remove the reader. But it's too slow. Is it possible to do it in a bulk operation?
class Book(models.Model):
    readers = models.ManyToManyField(User, related_name='books')

#Remove reader 'foo' from book 1, 2, 3, 4, 5. However, it is slow.
for book in Book.objects.filter(id__in=[1, 2, 3, 4, 5])
    book.readers.remove(R)

A: Yes. You can access the underlying M2M model using the through attribute, and then use that model to do a delete in one query.
Book.readers.through.objects.filter(book_id__in=[1, 2, 3, 4, 5],
                                    user_id=foo_user)
                            .delete()


text:
Q: What controls the node connections when multiple access points with the same SSID are present? What would govern the nodes connected to a wireless network when I have multiple access points that use the same SSID for roaming? I believe there is a command that shows the associations in Cisco IOS that could help me find this but I do not know what it is.

A: The clients choose for themselves which AP to connect to.
The 802.11 standard leaves it up to the clients to decide which AP to join. It doesn't even specify what algorithm or criteria a client should use to pick an AP. That has always been left up to implementors as an implementation detail. Most client implementations just pick the AP with the strongest signal strength, of the ones that are publishing the desired SSID.
Some enterprise-class 802.11 network infrastructure gear (such as "thin" APs with separate "Wireless LAN Controller" boxes coordinating them, as you can buy from Cisco, Aruba, and others) tries to second-guess the clients and employ various proprietary, nonstandard tricks to try to get clients to join the APs that the WLAN infrastructure gear wants the clients to join. They'll do things like purposely have some APs not respond to Probe Requests from the clients, or have a busy AP refuse to let a client join, so that the client is forced to pick a different AP. These tricks are, again, proprietary and nonstandard, and vary from vendor to vendor.


text:
Q: Video not playing after deployment on vercel but locally it is running I am using a custom video player in react and it is working fine on localhost but when i deploy it on vercel it is not working. I need help about this and idk what to do, vimeo external links will work i guess but those are paid and i need a free solution.
Here's the GitHub repo I'm using for custom video player
https://github.com/PiotrBerebecki/custom-video-player-react
Deployed link of above repo: https://custom-video-player-react.herokuapp.com/
And below is my vercel link
https://saderino-dapp-plnhfmbis-blockeyfi.vercel.app/
Is there any other issue that i need to look in please do guide me. Thanks alot:)

A: If you go to the "Network" tab in the browser dev tools, you will see that the HTTP requests the https://saderino-dapp-plnhfmbis-blockeyfi.vercel.app/videos/alienplants.mp4 video file.  This file is not being served correctly. Maybe look at hosting the video differently.
Take a look at this link:
https://vercel.com/support/articles/best-practices-for-hosting-videos-on-vercel-nextjs-mp4-gif


text:
Q: MySQL showing name insead of id from other table What I want to do is to show the name from the referred table and not the id that I'm obviously getting.
Here is the table I'm displaying on my website. "jid" is just for A_I so every new connection gets a new id.

This is how all other tables are set up.

So, from what I know I have to make JOINs to be able to show the name instead of the id, but I have been trying to make my own syntax from other suggestions but I haven't been able to figure it out.
This is one I've tried
$query = "SELECT joined.categoryid, category.name
FROM joined
INNER JOIN category
ON  joined.categoryid = category.categoryid";
$result = $mysqli->query($query);

A:  <?php

$result = mysql_query("SELECT joined.categoryid, category.name, category.categoryid
FROM joined
JOIN category
ON joined.categoryid = category.categoryid", $db);
 if (!$result) {
 die("Database query failed: " . mysql_error());
 }

 while ($row = mysql_fetch_array($result)) {
 echo "
";
 echo $row[1]."";
 echo "
";
 echo "
";
 echo $row[2]."";
 echo "
";
 }
?>

I tried this myself here is my Output
http://prntscr.com/7ohruc

A: Try this:
"SELECT joined.categoryid, category.name
FROM joined, category
WHERE joined.categoryid = category.categoryid";


text:
Q: Найти по собственному атрибуту и добавить css стиль? Всем привет. Есть ссылки:
Телефоны1
Телефоны2
Телефоны3
Телефоны4

У этих ссылок есть собственный атрибут rel.
При каждом клике на страницу у меня есть переменная c разными значениями telefony1, telefony2, telefony3 или telefony4.
Как мне найти ссылку с атрибутом rel равной переменной и присвоить ей какой-нибудь css.
Например, если переменная равна telefony2, я нахожу telefony2  и присваиваю ей какое-нибудь css свойство.
A: var selector = '[rel="telefony%d"]'.replace('%d', number)
$(selector);


text:
Q: line in iter(fp.readline, '') rather than line in fp: I read builtin function iter 's example in Built-in Functions — Python 3.7.0 documentation
with open('mydata.txt') as fp:
    for line in iter(fp.readline, ''):
        process_line(line)

I could not figure out what's the advantage over the following:
with open('mydata.txt') as fp:
    for line in fp:
        process_line(line)

Could you please provide any hints?

A: Both will iterate over a generator, without loading the whole file into memory, but the iter() version is demonstrating the use of the second argument of iter(), "sentinel".
From the docs:

if the value returned is equal to sentinel, StopIteration will be raised

So this code will read from the file, until a line equals '' and then stop.
This is a strange example, as all lines in the file will have a newline on the end, so this will only trigger at the end of the file anyway (if at all).

A: As wim and I discussed in the comments, there is no advantage for this particular case. For the 2nd code snippet to be equivalent to the first code snippet then it would look something like this:
with open('mydata.txt') as fp:
    for line in fp:
        if line == '':
            break
        process_line(line)

However, the only case an empty string can be returned by readline is at the end of the file (EOF) so it makes now difference here (other lines contain a newline '\n' character at least).
If rather than an empty string another value was used, then the difference would be meaningful though. Personally, I think the docs should use a better example to illustrate this, like as follows:
>>> f = open('test')
>>> f.read()
'a\nb\nc\n\nd\ne\nf\n\n'
>>> f = open('test')
>>> [line for line in iter(f.readline, 'b\n')]
['a\n']
>>> f = open('test')
>>> [line for line in f]
['a\n', 'b\n', 'c\n', '\n', 'd\n', 'e\n', 'f\n', '\n']

(Note I should really be closing the file handles)
EDIT: I raised this as a possible documentation bug in issue34764


text:
Q: How does IE11 populate window.location.origin? I have an issue in a non production environment in Internet Explorer 11 where
window.location.origin is undefined.
However, in the production environment this value actually returns
window.location.origin = http://www.myproductionwebsite.com
This issue only exists in Internet Explorer and works fine in Chrome and Firefox across production and non production environments, which has lead me to believe its the way that the Chakra JavaScript Engine in IE11 populates origin.
I have also looked at the request and response headers across production and non production environment and all the parameters are identical.
How does Internet Explorer 11 calculate window.location.origin differently to Chrome or Firefox?

A: Intranet sites are set to Compatibility View, which disables window.location.origin:

Pages will run in Compatibility View unless they explicitly specify another document mode. This option can be disabled using the Tools > Compatibility View Settings menu.

Sites are placed in the Intranet Zone based on the following criteria:

Direct Mapping. As with other Zones, users or network admins may map a list of URL patterns into the Local Intranet Zone. This list is viewable by clicking Tools > Internet Options > Security >  Local Intranet > Sites > Advanced.
The PlainHostName rule (aka "The Dot rule"). If the URI's hostname doesn't contain any periods (e.g. http://team/) then it is mapped to the Local Intranet Zone.
The fixed Proxy Bypass list. If the user has a fixed proxy specified inside Tools > Internet Options > Connections > LAN Settings, then sites listed to bypass that proxy will be mapped to the Local Intranet zone. The fixed proxy bypass list can be found by clicking the Advanced button; it's at the bottom of the screen in the box labeled Exceptions.
(WPAD) Proxy Script. If the user's proxy configuration is "Automatically detect settings" or "Use automatic configuration script" inside Tools > Internet Options > Connections > LAN Settings, the browser will run the FindProxyForUrl function in the specified WPAD proxy configuration script to determine which proxy should be used for each request. If the script returns "DIRECT", the browser will bypass the proxy and the site will be mapped into the Local Intranet Zone. When mapping a URL to a Zone, URLMon will call the FindProxyForUrl function to determine if the bypass rule applies. One interesting twist is that the proxy script may itself call dnsResolve to get a site's IP address and use that information as a part of its determination.

References

*

*[MS-IEDOCO]: Internet Explorer Standards Support Documentation Overview,
2.1.3.6 Compatibility View

*The Intranet Zone


text:
Q: Get last row name by column, then DESC I need to get the last username registered in my members table. The last registered has the highest ID number.
At the moment, I can get the highest ID with this code, but I need to get the lowest.
$resultlatestuser = mysql_query("SELECT * from $tbl_name ORDER BY 'id' DESC LIMIT 0,1;");
$row = mysql_fetch_row($resultlatestuser);
echo $row[1];
This echos the ID as john, but john has the lowest ID: 1.
This is what my database looks like, for example I need Dayancbro echo'd because he has the highest ID.
http://puu.sh/2k4Hh

*

*James

A: Time to use aggregate functions:
SELECT MAX(id) FROM $tablename


text:
Q: jQuery: remove certain elements from HTML document I'd like to strip certain elements from my HTML document.
It seems that removing some tags simply doesn't work.
For example - strip all stylesheets:
$("style",this._doc.body).remove();

I'd also like to remove comments or something like weird winword tags like:
<!--[if gte mso 9]>
How to do it?

A: To remove all stylesheets, try this:
$('link[rel=stylesheet]').remove();


text:
Q: como apertar o botão usando código, usando o mesmo efeito de quando o usuario aperta estou fazendo o jogo para java e ao iniciar a maquina vai dar uma sequecia de cliques aleatória em 4 botões e depois o usuario tem que apertar igual a maquina, mas não sei como fazer a maquina apertar o botão
package gênius;

import java.applet.Applet;
import java.applet.AudioClip;
import java.awt.AWTException;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingConstants;

public class tela extends JFrame {

    //nome do jogador e pontos
    int pontos = 0 ;
    String usuario = "";

    //varieaveis de jogadas
    String jjogador = "";
    String maquina ="";

    // janela de exibição
    public void janela(){
        JFrame  ftela = new JFrame();
        ftela.setTitle("Gênius");
        ftela.setSize(400, 600);
        ftela.setBackground(Color.white);
        ftela.setLocationRelativeTo(null);
        ftela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        ftela.setVisible(true);

        //boões de ção
        JButton b1 = new JButton("");
        b1.setBounds(100, 220, 80, 80);
        b1.setVisible(true);
        b1.setBackground(Color.BLUE);

        JButton b2 = new JButton("");
        b2.setBounds(200, 220, 80, 80);
        b2.setVisible(true);
        b2.setBackground(Color.red);

        JButton b3 = new JButton("");
        b3.setBounds(100, 320, 80, 80);
        b3.setVisible(true);
        b3.setBackground(Color.GREEN);

        JButton b4 = new JButton("");
        b4.setBounds(200, 320, 80, 80);
        b4.setVisible(true);
        b4.setBackground(Color.YELLOW);

        JButton b5 = new JButton("vermalho");
        b5.setBounds(200, 420, 80, 80);
        b5.setVisible(true);
        b5.getColorModel();
        b5.setBackground(Color.WHITE);

        JPanel p1 = new JPanel();
        ftela.add(b1);
        ftela.add(b2);
        ftela.add(b3);
        ftela.add(b4);
        ftela.add(b5);

        //ações dos botôes
        b1.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                play("b1");
                jjogador += " "+0;

            }
        });
        b2.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                play("b2");
                jjogador += " "+1;

            }
        });
       b3.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                play("b3");
                jjogador += " "+2;

            }
        });
       b4.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                play("b4");
                jjogador += " "+3;

            }
        });

       b5.addActionListener(new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                JOptionPane.showMessageDialog(null, jjogador);

            }
        });

    }
     // coloando som no botão
        public void play(String audio){
            URL url = getClass().getResource(audio+".wav");
            AudioClip  audioc = Applet.newAudioClip(url);
            audioc.play();
        }

        public void jlabe (){
            JLabel mPontos = new JLabel("pontos ");
            mPontos.setText("pontos :"+pontos);
            mPontos.setHorizontalAlignment(SwingConstants.CENTER);

        }

}

A: Há varias maneiras de se adicionar ação ao JButton, talvez a mais simples seja por classe anônima:
    b1.addActionListener(new ActionListener() {

        @Override
        public void actionPerformed(ActionEvent evt) {
            //evento aqui
        }
    });

Esta forma é muito usada quando não se tem nada de muito complexo na ação.
Se estiver usandojava 8, as coisas ficam bem mais fáceis:
b1.addActionListener(e -> {
            //ação aqui
        });

A: A maneira mais fácil é assim:
Adicionas a acção ao Button:
b1.addActionListener(this);

Depois vais criar essa acção:
public void actionPerformed(ActionEvent e) {
        //O código que queiras
}

Porém, para que esta maneira seja possível, tens de implementar uma ActionListener:
public class NOME_DA_CLASSE implements ActionListener{
    //Código
}


text:
Q: Module Pattern: var module = new function() {...} vs. var module = (function () {...}()); The Title is a very shorthand to the actual comparison I will give below.
I'm delving into JavaScript and also read about the Module Pattern (JavaScript Module Pattern: In-Depth and Mastering the Module Pattern)
An implementation of my own of the Module Pattern was slightly different than the described pattern in the links above.
My implementation:

var smath1 = new function () {
 // "private fields"
 var answer = new Number(42);

 // "public fields"
 this.PI = new Number(3.141592653589793);

 // "private functions"
 function getHalfTheAnswer() {
  return answer / 2;
 };

 // "public functions"
 this.sum = function (a, b) { return new Number(a) + new Number(b) };
 this.mul = function (a, b) { return new Number(a) * new Number(b) };
 this.getTheAnswer = function () { return answer; };
 this.calcTheAnswer = function () { return getHalfTheAnswer() * 2 };
}

I'm interested in how this is different (technically/logically) from the Pattern described in the links...

var smath2 = (function () {

 var my = {};

 // "private fields"
 var answer = new Number(42);

 // "public fields"
 my.PI = new Number(3.141592653589793);

 // "private functions"
 function getHalfTheAnswer() {
  return answer / 2;
 };

 // "public functions"
 my.sum = function (a, b) { return new Number(a) + new Number(b) };
 my.mul = function (a, b) { return new Number(a) * new Number(b) };
 my.getTheAnswer = function () { return answer; };
 my.calcTheAnswer = function () { return getHalfTheAnswer() * 2 };

 return my;
}());

...and what makes the second approach superior/preferable to the first, if so at all?
The usage would be exactly the same as well as the behavior as far as I could see in my tests. See the fiddle: JS Module Pattern


text:
Q: Fetch the "Alias" field for Joomla menu item Is there a way to get the Alias field of a main menu item in Joomla 1.5 from mod_mainmenu module? I know you can access the menu using this code:
$menu = JSite::getMenu();

I need to use the Alias field to hold a sub-title for the menu item. Is it possible to fetch this from the modMainMenuXMLCallback() function in mod_mainmenu? Thanks.

A: $menu = JSite::getMenu();
$alias = $menu->getItem($id)->alias;  // if you have id of menu

$menu = JSite::getMenu();
$alias = $menu->getActive()->alias;  // alias of active menu


text:
Q: variable from batch file to python **Updated because of comments
I am trying to pass a variable from a batch file to my python files. I am getting a n unexpected result; my code:
In my batch file:
SET variablename = 'name'
python 01_preparing.py %variablename%

In my python file
import sys

print('Argument:', sys.argv[1])

Result is
Traceback (most recent call last):
File "01_preparing.py", line 5, in <module>
print('Argument:', sys.argv[1])
IndexError: list index out of range

Started out with this example: Sending arguments from Batch file to Python script


text:
Q: How do I install CLI tools "under Rosetta 2" on MacBook M1? After getting a MacBook M1 2020 - I found most of my command line tools could no longer be installed. I presume this was because the tools were compiled to run on an Intel based chipset, and not the new Apple Chipset (citation needed).
Here is an example:
APP is not (yet) supported on ARM processors!
Rerun the APP installer under Rosetta 2.

How do I install an app "under Rosetta 2"?

A: I found the solution here, which worked a treat.

In Terminal, use
arch -x86_64 zsh
to start a shell under Rosetta 2

Addendum: I created a rosetta alias, so I can switch in the future:
echo 'alias rosetta="arch -x86_64 zsh"' >> ~/.zshrc

A: install rosetta and skip the license agreement
softwareupdate --install-rosetta --agree-to-license


text:
Q: Postfix Root email forwarding to external address as bcc only I have set up postfix to relay proxmox messages through my gmail account and used aliases to forward all my root email to an outside address.  When using sendmail command the email can be seen in the sent folder of gmail with the To: field empty and Bcc: is my outside address.  When using mail -s the email is seen in gmail sent folder with the To: field as the original root email  and Bcc: is my outside address.
Shouldn't my forwarding address replace root@pve.home.com in the To: field instead of Bcc: and stop sending to root@pve.home.com altogether?
Test commands for root email
# echo -e "Subject:Hello World \n\n Testing email\n" | sendmail root
# echo "testing" | mail -s "test message" root

Log File
Dec 29 12:56:13 pve postfix/pickup[32080]: DB1E662DFA: uid=0 from=<root>
Dec 29 12:56:13 pve postfix/cleanup[32097]: DB1E662DFA: message-id=<20171229175613.DB1E662DFA@pve.home.com>
Dec 29 12:56:13 pve postfix/qmgr[32081]: DB1E662DFA: from=<root@pve.home.com>, size=390, nrcpt=1 (queue active)
Dec 29 12:56:13 pve postfix/cleanup[32097]: E13A162DF8: message-id=<20171229175613.DB1E662DFA@pve.home.com>
Dec 29 12:56:13 pve postfix/local[32099]: DB1E662DFA: to=<root@pve.home.com>, orig_to=<root>, relay=local, delay=0.04, delays=0.03/0.01/0/0, dsn=2.0.0, status=sent (forwarded as E13A162DF8)
Dec 29 12:56:13 pve postfix/qmgr[32081]: E13A162DF8: from=<root@pve.home.com>, size=515, nrcpt=1 (queue active)
Dec 29 12:56:13 pve postfix/qmgr[32081]: DB1E662DFA: removed
Dec 29 12:56:13 pve postfix/smtp[32100]: connect to smtp.gmail.com[2607:f8b0:4001:c1d::6c]:587: Network is unreachable
Dec 29 12:56:14 pve postfix/smtp[32100]: E13A162DF8: to=<someone@icloud.com>, orig_to=<root>, relay=smtp.gmail.com[74.125.126.109]:587, delay=0.85, delays=0/0.03/0.37/0.45, dsn=2.0.0, status=sent (250 2.0.0 OK 1514570174 f126sm11045770ioa.84 - gsmtp)
Dec 29 12:56:14 pve postfix/qmgr[32081]: E13A162DF8: removed

Dec 29 12:59:40 pve postfix/pickup[32080]: D6C9362DFA: uid=0 from=<root>
Dec 29 12:59:40 pve postfix/cleanup[32429]: D6C9362DFA: message-id=<20171229175940.D6C9362DFA@pve.home.com>
Dec 29 12:59:40 pve postfix/qmgr[32081]: D6C9362DFA: from=<root@pve.home.com>, size=280, nrcpt=1 (queue active)
Dec 29 12:59:40 pve postfix/cleanup[32429]: DDD4D62DF8: message-id=<20171229175940.D6C9362DFA@pve.home.com>
Dec 29 12:59:40 pve postfix/local[32431]: D6C9362DFA: to=<root@pve.home.com>, orig_to=<root>, relay=local, delay=0.05, delays=0.03/0.01/0/0.01, dsn=2.0.0, status=sent (forwarded as DDD4D62DF8)
Dec 29 12:59:40 pve postfix/qmgr[32081]: DDD4D62DF8: from=<root@pve.home.com>, size=405, nrcpt=1 (queue active)
Dec 29 12:59:40 pve postfix/qmgr[32081]: D6C9362DFA: removed
Dec 29 12:59:41 pve postfix/smtp[32432]: connect to smtp.gmail.com[2607:f8b0:4001:c1d::6c]:587: Network is unreachable
Dec 29 12:59:41 pve postfix/smtp[32432]: DDD4D62DF8: to=<someone@icloud.com>, orig_to=<root>, relay=smtp.gmail.com[74.125.126.109]:587, delay=0.93, delays=0.01/0.02/0.52/0.38, dsn=2.0.0, status=sent (250 2.0.0 OK 1514570381 a69sm13573861itc.18 - gsmtp)
Dec 29 12:59:41 pve postfix/qmgr[32081]: DDD4D62DF8: removed

aliases
root: someone@icloud.com

postmaster: root
nobody: root
hostmaster: root
webmaster: root
www:root

main.cf
# See /usr/share/postfix/main.cf.dist for a commented, more complete version

myhostname=pve.home.com

smtpd_banner = $myhostname ESMTP $mail_name (Debian/GNU)
biff = no

# appending .domain is the MUA's job.
append_dot_mydomain = no

# Uncomment the next line to generate "delayed mail" warnings
#delay_warning_time = 4h

alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = $myhostname, localhost.$mydomain, localhost
#relayhost =
mynetworks = 127.0.0.0/8 [::ffff:127.0.0.0]/104 [::1]/128
mailbox_size_limit = 0
inet_interfaces = loopback-only
recipient_delimiter = +

# sets gmail as relay
relayhost = [smtp.gmail.com]:587

#  use tls
smtp_use_tls=yes

# use sasl when authenticating to foreign SMTP servers
smtp_sasl_auth_enable = yes

# path to password map file
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd

# list of CAs to trust when verifying server certificate
smtp_tls_CAfile = /etc/ssl/certs/Equifax_Secure_CA.pem
smtp_tls_session_cache_database = btree:/var/lib/postfix/smtp_tls_session_cache
smtp_tls_session_cache_timeout = 3600s

# eliminates default security options which are imcompatible with gmail
smtp_sasl_security_options =

hosts
127.0.0.1 localhost.localdomain localhost
127.0.1.1 pve.home.com pve pvelocalhost

# The following lines are desirable for IPv6 capable hosts

::1     ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts

mailname
pve.home.com

A: Addresses are not rewritten by default; the Sendmail feature for this is genericstable which Postfix calls generic(5) so in theory adding
smtp_generic_maps = hash:/etc/postfix/generic

to your main.cf and then adding entries to /etc/postfix/generic such as
root@pve.home.com someone@icloud.com

and then running postmap /etc/postfix/generic and restarting Postfix should cause a rewrite of addresses. (This can be complicated by the distinction between envelope addresses used by mail transfer agents such as Postfix and body addresses present in the message itself...)
In the | sendmail case you should supply an appropriate To address header along with the Subject, or instead use a mail user agent (such as mail) that handles those details for you.


text:
Q: How to write a logger which holds data? I use the standard log module of rust. I'm trying to have a very simple logger that  records all that is sent to it via debug!, trace!, etc. Then from time to time, I want to read these records and do something else with them. I had something like this in mind (I have removed useless code):
struct SimpleLogger {
    records : Vec<String>
}

impl SimpleLogger {
    fn dump(&mut self) {
        for x in self.records.into_iter() {
            println!("{}", x);
        }
        self.records.clear();
    }
}

impl log::Log for SimpleLogger {
    fn log(&self, record: &Record) {
        if self.enabled(record.metadata()) {
            self.records.push(format!("{} - {}", record.level(), record.args()));
        }
    }
}

This is challenging for these reasons:

*

*Once the logger has been set as the global logger (using log::set_logger), I loose the ownership. So I can't call dump anymore (because I don't have a reference to it anymore, it has been captured by set_logger).

*In the  Log trait, the log method accepts a non mutable reference to self. Therefore, I can't update the vector of records there.

I've checked other loggers and they seem to use Write objects, but still it seems everything is thought to deliver the records and then throw them away. Moreover, it seems the loggers need to be thread safe so I'd have to use mutex...
How can I do ?


text:
Q: ViewPager, но без перелистывания на другую страницу Как организовать слайдинг, но без анимации перехода на другую страницу. Мне надо задействовать смысл  реализации ViewPager, только не могу найти примеров.
A: Можно установить свой ViewPager.PageTransformer, который бы показывал смену view, как будто анимации нет:
    mViewPager.setPageTransformer(true, new ViewPager.PageTransformer() {
        public void transformPage(View view, float position) {
            int pageWidth = view.getWidth();
            if (position <= -1) { // [-Infinity,-1]
                view.setTranslationX(0);
            } else if (position < -0.5) { // (-1,-0.5)
                view.setTranslationX(pageWidth * (-1-position));
            } else if (position < 0.5) { // [-0.5,0.5)
                view.setTranslationX(pageWidth * -position);
            } else if (position < 1) { // (0.5,1)
                view.setTranslationX(pageWidth * (1 - position));
            } else { // [1,+Infinity]
                view.setTranslationX(0);
            }
        }
    });

Но возможно, вы просто хотите выполнять какие-то действия по свайпу, либо другим жестам. Т.е. установить GestureDetector.SimpleOnGestureListener и слушать события onFling, либо onScroll
В доокументации есть хорошая глава про жесты.


text:
Q: How to make ShowToastEvent working within visualforce I am working on migrating LWC into visualforce app.
Almost all functionalities working fine, but ShowToastEvent and dispatchEvent method are not working in Visualforce environmnent.
I walked throught instructions below. But it's not working.
https://developer.salesforce.com/docs/component-library/documentation/lwc/use_visualforce
How should I do for this?
ex. My code looks like below.
class SomeClass extends LightningElement {

  showToastOperation(operation) {
    let msgStr = '';
    switch (operation) {
      case Operation.GET:
        msgStr = message_operation_get;
        break;
      case Operation.CREATE:
        msgStr = message_operation_create;
...
      default:
        throw new Error('Unknown operation!');
    }
    this.dispatchEvent(
      new ShowToastEvent({
        title: 'Success!!',
        message: msgStr,
        variant: 'success',
      })
    );
  }

A: The ShowToastEvent() of LWC is not intended for Visualforce environments. The current support for this event is "Lightning Experience" only.
https://developer.salesforce.com/docs/component-library/bundle/lightning-platform-show-toast-event/documentation
Here is a documentation for ltng:outApp considerations with standard events.
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/lightning_out_considerations.htm
That being said - even the Aura Component version of "Show Toast Event" was supported only in one.app environments ie (Lightning Experience , Salesforce Mobile App & Lightning Communities).
Reference :
https://developer.salesforce.com/docs/atlas.en-us.212.0.lightning.meta/lightning/ref_force_showToast.htm?search_text=force:showToast


text:
Q: Wt with Qt, .pro settings I am trying to get Wt working with Qt. I have installed 1.47 boost library, compiled Wt (3.2.1) under Windows using cmake 2.8.8. Tired simple hello world but doesn't compile, getting undefined reference errors for example:
    undefined reference to `Wt::WApplication::WApplication(Wt::WEnvironment const&, Wt::WtLibVersion)'
Here is my .pro file:
QT       -= core

QT       -= gui

INCLUDEPATH += ../../../lib/Wt/include \
          ../../../lib/boost_1_47 \
          ../../../lib/Wt/src

LIBS += -L../../../lib/Wt/lib \
    -L../../../lib/boost_1_47/lib

win32:LIBS += -lwthttpd -lwtd -lboost_regex-vc100-mt-1_47

TARGET = HttpServerWt
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app

SOURCES += main.cpp

This is the program I am trying to compile:
http://www.webtoolkit.eu/wt/src/hello

A: Probably, your WT libraries will be added to /usr/loca/lib by default. so specify link libraries accordingly[after checking whether its present there, else check in /usr/lib and include accordingly].
Set LIBS Variable as follows
LIBS += -L/usr/local/lib -lwtd -lwthttpd -lboost_regex-vc100-mt-1_47

I don't see any Problem in setting the INCLUDEPATH variable in your post.
And also make sure that you are adding the module corresponding to Wt::WApplication::WApplication(Wt::WEnvironment const&, Wt::WtLibVersion) in LIBS Variable.
For more look here.

A: I think you need more libraries, because in Ubuntu you need to add more than two libraries to compile a wt code with qt creator.
Here is my *.pro file
QT       += core
QT       -= gui
TARGET = prueba3
LIBS += -L/usr/lib -lwt -lwthttp -I/usr/local/include
LIBS += -L/usr/local/lib -lwthttp -lwt -lboost_regex -lboost_signals
LIBS += -lboost_system -lboost_thread -lboost_filesystem -lboost_date_time
#QMAKE_CXXFLAGS += -DNDEBUG

CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app

SOURCES += main.cpp

and it compiles/Build great, finally you must add this line to run settings(ctrl+5)
--docroot . --http-address 0.0.0.0 --http-port 9090


text:
Q: How to better spot the right integration by parts I was having trouble integrating
$$
\int_0^{\pi/2}\sin^{n}\left(x\right)\cos^{2}\left(x\right)\,{\rm d}x
$$ and someone pointed out to me that it was a somewhat simple integration by parts. Does anyone have some tips for me to better spot integrations by parts? I feel like I often miss them. Do you just proceed by trial and error, looking for $dv$ and $u$?
One general tip I heard was in choosing $u$, use LIATE, that is, the best things to make $u$, in order, are 1. Logs 2. Inverse trig functions 3. Algebraic functions 4. Trig functions 5. Exponential. But that's if you already know you have to use integration by parts, and doesn't help you to recognize it.
Alternately, if someone has a reference for good practice, I'd love to hear it. Thanks!

A: $\newcommand{\+}{^{\dagger}}%
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}%
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}%
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}%
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}%
 \newcommand{\dd}{{\rm d}}%
 \newcommand{\ds}[1]{\displaystyle{#1}}%
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}%
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}%
 \newcommand{\fermi}{\,{\rm f}}%
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}%
 \newcommand{\half}{{1 \over 2}}%
 \newcommand{\ic}{{\rm i}}%
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}%
 \newcommand{\isdiv}{\,\left.\right\vert\,}%
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}%
 \newcommand{\ol}[1]{\overline{#1}}%
 \newcommand{\pars}[1]{\left( #1 \right)}%
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}%
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}%
 \newcommand{\sech}{\,{\rm sech}}%
 \newcommand{\sgn}{\,{\rm sgn}}%
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}%
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
$\ds{{\cal I}_{n} \equiv \int_{0}^{\pi/2}\sin^{n}\pars{x}\cos^{2}\pars{x}\,\dd x}$

\begin{align}
{\cal I}_{n} &=
{1 \over n + 1}\int_{x\ =\ 0}^{x\ =\ \pi/2}\cos\pars{x}
\,\dd\bracks{\sin^{n + 1}\pars{x}}
=
-\,{1 \over n+ 1}\int_{0}^{\pi/2}\sin^{n + 1}\pars{x}\bracks{-\sin\pars{x}}\,\dd x
\\[3mm]&={1 \over n+ 1}\int_{0}^{\pi/2}
\sin^{n}\pars{x}\bracks{1 -\cos^{2}\pars{x}}\,\dd x
={1 \over n+ 1}\int_{0}^{\pi/2}
\sin^{n}\pars{x}\,\dd x - {1 \over n + 1}\,{\cal I}_{n}
\end{align}

\begin{align}
{\cal I}_{n}&={1 \over n + 2}\int_{0}^{\pi/2}\sin^{n}\pars{x}\,\dd x
={n \over n + 2}\bracks{{1 \over n}\int_{0}^{\pi/2}\sin^{n - 2}\pars{x}\,\dd x}
-
{1 \over n + 2}\int_{0}^{\pi/2}\sin^{n - 2}\pars{x}\cos^{2}\pars{x}\,\dd x
\\[3mm]&=
{n \over n + 2}\,{\cal I}_{n - 2} - {1 \over n + 2}\,{\cal I}_{n - 2}
=
{n - 1 \over n + 2}\,{\cal I}_{n - 2}
\end{align}

$$\color{#0000ff}{\large%
{\cal I}_{n} = \int_{0}^{\pi/2}\sin^{n}\pars{x}\cos^{2}\pars{x}
\,\dd x = {n - 1 \over n + 2}\,{\cal I}_{n - 2}\,,\quad n \geq 2\,,\qquad
\left\vert%
\begin{array}{rcl}
{\cal I}_{0} & = & {\pi \over 4}
\\[2mm]
{\cal I}_{1} & = & {1 \over 3}
\end{array}\right.}
$$

A: As with so many things in Mathematics, the actual identification of the right way to figure something out is actually more of an art than a science (although trial and error will often get you there).
A good rule of thumb with integration of functions that are products of trig is that, if you can't see an obvious substitution, try integration by parts. Pattern recognition is also useful a lot of the time - for instance, how might you solve the case where $n=0$? $n=1$? $n=2$? Can you generalise the approach, either for all $n$, all integer $n$, or all even (or odd) integer $n$?

A: Here are three typical situations where you should try to use integration by parts.
You want to apply integration by parts if

*

*your integrand has one factor which gets simpler by differentiation and a second factor which can be easily integrated.

Typical examples: $\int_{a}^b x^ke^x dx$, $\int_{0}^1 x^a(1-x)^b dx$,

because powers of $x$ eventually disappear when differentiated.

*

*your integrand has one factor which stays the same or will eventually be the same upon differentiation and a second factor which can be easily integrated.

Typical example: $\int_{a}^{b}e^x\sin x dx$

because integrating (or differentiating) the sine twice essentially gets you back the same function which allows for combining it with the original integral on the left.

*

*your integrand has one factor whose derivative will cancel or combine with all or part of the rest of the integrand, and a second factor which can be easily integrated

Typical examples: $\int_{a}^b x\ln x dx$, $\int_{0}^{\frac{\pi}2}(\sin x)^n dx$.

because the derivative of the logarithm will cancel with the $x$ and give you a trivial integral. (Note especially that you will not derive the $x$ unless you already know the integral of the logarithm from somewhere else.) and because the derivative of a power of sine combines with the derivative of sine to give again only integrals of powers of sine.
Note that your example is of the third kind which is the most difficult to spot because you have to know identities for your functions to determine that they cancel/combine judiciously. However, there are not that many examples that one encounters regularly, so after some practice, you will just know typical situations.


text:
Q: How do you cleanly abort a Delphi program? I've got a program that's having some trouble during shutdown, raising exceptions that I can't trace back to their source.  It appears to be timing-related and non-deterministic.  This is occurring after all shared resources have been released, and since it's shutdown, memory leaks are not an issue, so that makes me wonder if there's any way to just tell the program to terminate immediately and silently after releasing the shared resources, instead of continuing with the shutdown sequence and giving an exception message box.
Does anyone know how to do that?

A: ExitProcess(0) ?

A: Halt(0) used to be the good old fashioned way of telling the program to end with immediate effect. There's probably a more Delphi-friendly way of doing that now, but I'm 95% sure halt(0) still works. :-)

A: In case HeartWare's suggestion of using ExitProcess() fails, it might be you are using some DLL's that do not respond well to the DLL_PROCESS_DETACH. In that case, try using a TerminateProcess( getCurrentProcess, 0 );
Once you resort to such measures, one might wonder if the "cleanly" part of the topic title still holds up to scrutiny.

A: After looking at the Delphi Run Time Library source code, and at the Microsoft documentation; I can corroborate Mason and Paul-Jan comments.
The hierarchy of shutdown is as follows
  Application.Terminate()
    performs some unidentified housekeeping of application
    calls Halt()

  Halt()
    calls ExitProc if set
    alerts the user in case of runtime error
    get rid of PackageLoad call contexts that might be pending
    finalize all units
    clear all exception handlers
    call ExitprocessProc if set
    and finally, call ExitProcess() from 'kernel32.dll'

  ExitProcess()
    unloads all DLLs
    uses TerminateProcess() to kill the process

A: The last time I had to hunt a problem like this was the shutdown was a causing an event (resize? It's been a while.) to fire on the dying window causing an attempt to redraw something that needed stuff that had already been disposed of.


text:
Q: Counting rows of table2 does not include all rows of table1 in MySQL I have table 1 that represents Items with column ItemID and column ItemInfo.
Then, I have table 2 that represents SubItems with column ItemID (the parent), column SubItemID and column SubItemInfo.
I'm trying to get the count of all subitems for each item with this :
select items.itemID, count(*) as count
from items, subItems
where subItems.itemID=items.itemID group by itemID

It works fine except for items that don't have sub-items. Instead of returning the item row with a sub-item count of 0, the row is simply not there.
Is there an efficient way to force all rows from the first table (Items) to be selected ?

A: You neet to use left outer join, than you'll get 0 for items having no subitems, like that:
SELECT items.itemid,
       Count(subitems.subitemid) AS count
FROM   items
       LEFT JOIN subitems
              ON ( subitems.itemid = items.itemid )
GROUP  BY items.itemid

If you wanted to have better performance, you could try this query:
SELECT itemid,
       Count(*) AS count
FROM   subitems
GROUP  BY itemid

BUT, with this one you will not get any info about the items, that have no subitems (they are simply not present within subitems table).

A: select items.itemID, count(*) as count
  from items
  left join subItems on (items.itemID=subItems.itemID)
group by itemID


text:
Q: Adding a button in Toolbar in Winedt 10 I am using Winedt 10 and in its Toolbar some icon is missed. For example, I would like to use "Insert Environment" directly in "Toolbar" by only clicking on its icon as it was in "Winedt 9", and I do not want every time to go to "Menu->Insert->Insert Environment" to use it.
The same question for Undo and Redo and many others as it was in Winedt 9.
Is there any way to add its icon again to Toolbar.
Thank you.

A: I found it :) . I did it by
"Options->Toolbar->Legacy Default"

A: Update for WinEdt 10.3 (2021)
Details will be added to Asad's correct 2017 answer. The change to another toolbar is done from Options  ==>  Options Interface
by a sequence of text edits in WinEdt. The steps:
Open Toolbar.ini
Open Options Interface and double-click Menus and Toolbar then
Double-click Toolbar which opens Toolbar.ini for editing.
This file is initially a copy of the file of the same name
located in C:/Program Files/WinEdt Team/WinEdt 10/ConfigEx/
That location is never edited, the edits being made to user XXXXX directory
C:\users\XXXXX\Application Data\WinEdt Team\WinEdt 10\ConfigEx\Toolbar.ini

Disable Default Toolbar
Cursor to line 106, then edit Toolbar.ini to look like:

// Default Toolbar
//
// %%INCLUDE="ConfigEx\Toolbars\Toolbar1d.ini" // 1-row Toolbar (Default)

The six alternative toolbars are on lines 127-133. The lines following an un-commented active string %%INCLUDE are not used in the toolbar.
Enable Legacy Toolbar
All %%INCLUDE lines in Toolbar.ini must be commented out, then lines after
line 136 (2-row Legacy Toolbar) can be edited to customize the
buttons and drop-down menus.
Important:  Save the file Toolbar.ini. To enable the changes, double-click on the icon far left on row 2 of the Options Interface.

This action writes the file Toolbar.ini to the user directory
and refreshes the toolbar.
Failure to do this step will cause the toolbar to remain unchanged.
Wizards might use a programming editor on Toolbar.ini in the
User directory, but the steps to invoke the new toolbar must
be completed in WinEdt as outlined above. Never edit
Toolbar.ini in the Program Files directory - it must remain the original unchanged file.

Editing the Legacy Toolbar
Assumed: both steps above were completed successfully. An example: add at the end of file ToolBar.ini this button:
BUTTON="Wordpad"   // Location: Toolbar.ini

Important: The inserted BUTTON (or MENU) must exist as an ITEM in MainMenu.ini. For instance:
ITEM="Wordpad"   // Location: MainMenu.ini

Editing MainMenu.ini
Example continued. In the Options Interface double-click on MainMenu.ini. This opens an editor window with the same file name, but destination in the User folder. The example inserts into MainMenu.ini about line 3429:
ITEM="Wordpad"
CAPTION="Wordpad"
IMAGE="Asymptote" // Later, use wordpad.png 16x16 transparent
MACRO="Run('c:\Program Files\Windows NT\Accessories\wordpad.exe','%!P',0,0,'Wordpad');"

The image Asymptote.png already exists in WinEdt. To use image wordpad.png instead requires learning how to add images to WinEdt, another project that can consume hours.
Important:  Save the file MainMenu.ini. To enable the changes, double-click on the icon far left on row 2 of the Options Interface.


text:
Q: Transfer from Heisenberg to Ising model It is well know, that ferromagnets can be described using Hamiltonian
$$
    H = -\sum\limits_{i<j}J_{ij}\, (\mathbf{s}_i \cdot \mathbf{s}_j).
$$
where (three dimensional) spins $\mathbf{s}_i$ corresponds to magnetic moments $\boldsymbol{\mu}_i$ of atoms which are usually placed in sites of lattice. One can treat them as spin operators $\hat{\mathbf{s}}_i$ and obtain Heisenberg model. Or one can just let spins to take values $\mathbf{s}_i = s_i\mathbf{e}_i$, where $s_i = \pm 1$ which corresponds to  spin $s=\frac12$, and $\mathbf{e}_i$ are fixed for each atom Ising axes. Them one will come up with Ising model.
Second approach, for example, is successfully used in that article to describe spin ice.
So it is clear that Ising model is simplified Heisenberg model. And my question is why is this simplification legitimate?
As it was once mentioned to me this reduction can be explained the following way. Actually crystalline lattice has some (local) direction $\mathbf{e}_i$ such that, roughly speaking, to interaction between spins also contributes such factor as
$$
    H = -\sum\limits_{i<j}J_{ij}\, (\mathbf{s}_i \cdot \mathbf{s}_j) - D\sum\limits_{i} (\mathbf{e}_i \cdot \mathbf{s}_i)^2.
$$
And if $D \gg J_{ij}$ then one can obviously disregard all states but $|m=\pm s\rangle$ when calculates the partition function.
Anyhow, there must be some transition from spin--operators description to Ising--like. So are there any related physical phenomena? Some transitions that occur at temperatures $T \gg T_c$?
P.S. I'm actually interested in such values of $D$ for Dysprosium and Holmium from the article mentioned above. They have $J\sim T_c\sim 1 K$.


text:
Q: Oracle - FAST REFRESH Materialized views with LEFT JOINS updates very slow I have a Materialized view in Oracle that contains a LEFT JOIN which takes a very long time to update. When I update the underlying table it takes 63914.765 s to run (yes that is almost 17 hours).
I am using a LEFT JOIN on the same table, because I want to pivot the data from rows to columns. The pivot command is not available in this Oracle version, and using a GROUP BY + CASE is not allowed on a FAST REFRESH Materialized View.
The Materialized View Log looks like this:
CREATE MATERIALIZED VIEW LOG ON Programmes_Titles
WITH PRIMARY KEY, rowid
INCLUDING NEW Values;

The Materialized View itself looks like this (it contains 700000 rows, the Programmes_Titles table contains 900000 rows):
CREATE MATERIALIZED VIEW Mv_Web_Programmes
REFRESH FAST ON COMMIT
AS

SELECT
    t1.ProgrammeId,
    t1.Title as MainTitle,
    t2.Title as SecondaryTitle,
    --Primary key
    t1.Title_Id as t1_titleId,
    t2.Title_Id as t2_titleId,

    t1.rowid as t1_rowid,
    t2.rowid as t2_rowid
FROM
    Programmes_Titles t1,
    Programmes_Titles t2
WHERE
    t1.Titles_Group_Type = 'mainTitle'
    AND t1.Programme_Id = t2.Programme_Id(+) AND t2.Titles_Group_Type(+) = 'secondaryTitle'

The UPDATE statement I use is this:
UPDATE Programmes_Titles
SET Title = 'New title'
WHERE rowid = 'AAAL4cAAEAAAftTABB'

This UPDATE statement takes 17 hours.
When using an INNER JOIN (remove the (+)'s) it takes milliseconds.
I also tried adding INDEXES on the Mv_Web_Programmes Materialized View, but that did not seem to help either. (It still runs for more than a minute, which is way to slow, I am not waiting 17 hours after every change, so it might improved the UPDATE)
So my question is: Why does is take such a long time to UPDATE the underlying table? How can I improve this?

A: I've managed to reproduce your problem on a 10.2.0.3 instance. The self- and outer-join seems to be the major problem (although with indexes on every column of the MV it finally did update in under a minute).
At first I thought you could use an aggregate MV:
SQL> CREATE MATERIALIZED VIEW LOG ON Programmes_Titles
  2  WITH PRIMARY KEY, ROWID (programmeId, Titles_Group_Type, title)
  3  INCLUDING NEW Values;

Materialized view log created

SQL> CREATE MATERIALIZED VIEW Mv_Web_Programmes
  2  REFRESH FAST ON COMMIT
  3  AS
  4  SELECT ProgrammeId,
  5         MAX(decode(t1.Titles_Group_Type, 'mainTitle', t1.Title)) MainTl,
  6         MAX(decode(t1.Titles_Group_Type, 'secondaryTitle', t1.Title)) SecTl
  7    FROM Programmes_Titles t1
  8   GROUP BY ProgrammeId;

Materialized view created

Unfortunately, as you have noticed, as of 10g a MV that contains MIN or MAX can only be fast-refreshed on commit after insert (so called insert-only MV). The above solution would not work for update/delete (the MV would have to be refreshed manually).
You could trace your session and open the trace file to see what SQL query gets executed so that you can find if you can optimize it via indexes.

A: We too faced this issue recently on Oracle 11.2.0.3
In our case, it was unavoidable to to remove an 'OUTER JOIN' due to functional impact.
On investigation, it was found that Oracle was adding a nasty HASH_SH (Hash Semi Join) hint with MV refresh DML.
Nothing worked including things mentioned in following blog-
http://www.adellera.it/blog/2010/03/11/fast-refresh-of-join-only-mvs-_mv_refresh_use_stats-and-locking-log-stats/#comment-2975
In the end, a hidden hint worked...(though in general, it should be avoided by making change in application if possible)
Oracle Doc ID 1949537.1 suggests that setting the hidden _mv_refresh_use_hash_sj parameter to FALSE should prevent it using that hint.
alter session set "_mv_refresh_use_hash_sj"=FALSE;

That stopped CBO using the HASH_SJ hint.
Posting it here in the interests of others.


text:
Q: Delimiter Matching using Stack I have a small problem here you might consider answering;
Here is the code;
public void analyze (String input, int length, int j){
    if (j == length){
        return;
    }
    if(input.charAt(j) == '{' || input.charAt(j) == '(')
        push(input.charAt(j));
    else
        pop();
    j++;

    analyze (input, length, j);
}

Output:
Original List: {()}

List: {

Well, the problem is the List should be empty but I couldn't seem to find the solution.
Thank you in advance.
Here is the full code:
http://pastebin.com/nXc79gHf

A:
Assuming your input contain only '}', '{' and '(', ')' characters.

replace by below code (assuming push() and pop() do work fine)...
public void analyze(String input, int length, int j){
        if (j >= length) return;
        if(input.charAt(j) == '{' || input.charAt(j) == '(')
            push(input.charAt(j));
        else if(input.charAt(j) == '}' || input.charAt(j) == ')')
            pop();
        analyze (input, length, ++j);
    }

call by using analyze(input, input.length(), 0);
Ex. {()}


text:
Q: Require authoritative answer for DNS resolution We have two forward lookup zones (intranet.com and mayberry.com) that aren't actually registered to us.  Sometimes, our MS DNS server forwards the queries for network resources within these domains to OpenDNS, who is our forwarder.
OpenDNS then responds with the IP address of their "Not Found" page, therefore creating a problem until we flush the client's DNS and try again.
Is there any way to insure that these domains are only resolved by our DNS server?  Perhaps a way to block forwards for these domains or only allow an authoritative answer for them?
Thanks for the help!

A: The Microsoft DNS server won't forward requests for domains it's authoritative for. I suspect that you've specified a "secondary" DNS server on your client computers that refers to another DNS server (like, say, OpenDNS) and you're periodically getting resolution from this secondary DNS server.
If you're in an Active Directory environment no domain-joined computer should have any DNS server specified in its NIC properties (either hard-set or delivered via DHCP) that refers to a DNS server that isn't running on one of your domain controllers. Your DNS servers running on your DCs should be resolving external-to-the-forest names either via forwarders to another DNS server, or via root hints.
Edit:
It sounds like you're saying that you have a DNS server specified on the clients that's not a domain controller (i.e. "my gateway").
It's unclear what you mean by "is a slave for DC". Assuming the IP address of the IP address of the DC is "X.X.X.X", the IP address of the "gateway" specified as a secondary DNS server is "Y.Y.Y.Y", and one of the internal domain names that isn't resolving properly is "foo.com", run the following commands and compare the output:
nslookup foo.com X.X.X.X
nslookup foo.com Y.Y.Y.Y

The output should match. If it doesn't, then the "gateway" is resolving the internal domain name differently than the domain controller and that's your problem.
As long as the "gateway" resolves names exactly like a domain controller it's not a problem to use it as a secondary DNS server. If it doesn't resolve names exactly the same way, though, you shouldn't be using it as a secondary DNS server. Every time you add an AD-integrated DNS zone to your DC you'll need to configure the "gateway" to resolve names in that zone the same way.

A: If OpenDNS is returning an answer (its "Not Found" page) instead of saying there's no answer then it is speaking lies, but you cannot control that.
If your DNS server is authoritative for a domain (a zone), it will only return what it knows. I've never seen any DNS server forward requests when it is authoritative.
If your client has multiple DNS servers that include your DNS servers and also other DNS servers, then it is possible for the client to pick one of those other servers and thus get back answers when your servers would have said "no name" or similar.
All of the above is true for all DNS servers, MSFT or otherwise.

A: You can turn that feature off (somewhat) in your OpenDNS control panel, or change to a forwarder that doesn't do that.  Google DNS works well (reportedly), or you could just run your own recursive server that doesn't rely on an upstream.

A: Whilst changing your forwarders to ones that don't do NXDOMAIN rewriting may achieve your ends, that would only be addressing the symptoms of the problem and not the root cause.
To fix the root cause you need to prevent MS DNS from forwarding queries for your internal domains offsite.
If that proves to be00 impossible, there are several nameservers that will happily (and reliably) serve local data authoritatively, whilst forwarding queries for other domain names offsite.
My personal favourites are BIND and Unbound, both of which are available for Windows servers.

A: This seems to be a name resolution issue in your DNS server. For some reason when someone queries your DNS Server for addresses in the two zones above, your DNS server is replying with 'I don't know, go ask Open DNS' this could be caused because your forward lookup zones are not completely current with all of the addresses in the two domains in your question. I would compare your zone listings with their domains to insure that your information is current.
You can do a bit of double redundancy to allow for multiple query paths for the domains in question. You have a couple of forward look-up zones, and that is good, but if those domains have their own DNS Servers you might also try putting forwarders into your DNS server specifically for those domains.
If you go to the forwarders tab in DNS you can hit the 'New' button under the 'DNS Domain' box and add a specific entry for the domains you are trying to hit. This will add those entries under the 'For all other DNS domain' listing. You can then go to each one and specify the IP address of a DNS server in those domains.

A: Yeah, use a real DNS server (instead of MS).


text:
Q: terraform remote state cannot find attribute Experiencing issue that the data.terraform remote state cannot find the attribute, but it exists under outputs.
Data code:
data "terraform_remote_state" "network" {
  backend = "azurerm"

  config = {
    storage_account_name = ""
    container_name       = ""
    key                  = ""
    resource_group_name  = ""
    access_key           = ""
  }
}

Trying to get vnet, tried with .outputs.vnet also!
  vnet = "${data.terraform_remote_state.network.vnet}" // Also tested outputs.vnet and vnet_id, outputs.vnet_id

From my remote statefile:
"outputs": {
                "resource_group": {
                    "sensitive": false,
                    "type": "string",
                    "value": "xxx"
                },
                "vnet": {
                    "sensitive": false,
                    "type": "string",
                    "value": "xxx"
                },
                "vnet_id": {
                    "sensitive": false,
                    "type": "string",
                    "value": "xxx"
                }
            },

Error:

*

*module.jenkins_service.var.vnet: Resource 'data.terraform_remote_state.network' does not have attribute 'vnet'
  for variable 'data.terraform_remote_state.network.vnet'

A: Earlier version of terraform azurerm you needed to rely on terraform_remote_state and generic outputs to pass data to downstream terraform runs.  The preferred method is to source data as a first class type. For example azurerm_virtual_network as data sources.


text:
Q: Complicated Group SQL Query here is my query and result;
select
DATEADD(dd, DATEDIFF(dd, 0, PostDate), 0) as Date,
Stores.Name StoreName,
SUM(PosCash + PosCredit + PosBillCash + PosBillCredit) as Revenue
from StoreRevenue
inner join Stores on Stores.ID = StoreRevenue.StoreID
group by DATEADD(dd, DATEDIFF(dd, 0, PostDate), 0), Stores.Name

result : http://prntscr.com/zaele
I want to create a table (result) that must be group by date and store names.
Date, Avcılar Mağaza, Ataşehir Mağaza
2013-03-04, 150, 200
2013-03-05, 200, 250
2013-03-06, 300, 150

rows of sub-group (these ones: 2013-03-04, 150, 200) are date and incomes of each stores
I want to get that kind of result
I have also tried "pivot" in sql but It doesnt work for me
sorry for my english. -Thanks

A: Try this:
WITH CTE
AS
(
    select
      DATEADD(dd, DATEDIFF(dd, 0, PostDate), 0) as Date,
      Stores.Name StoreName,
      PosCash + PosCredit + PosBillCash + PosBillCredit as Revenue
    from StoreRevenue
    inner join Stores on Stores.ID = StoreRevenue.StoreID
)
SELECT *
FROM CTE AS c
PIVOT
(
   SUM(Revenue)
   FOR StoreName IN ([Avcılar Mağaza],  [Ataşehir Mağaza], ...)
) AS p

A: You can use the PIVOT function to transform the data from rows to columns:
select *
from
(
  select
    DATEADD(dd, DATEDIFF(dd, 0, PostDate), 0) as Date,
    Stores.Name StoreName,
    (PosCash + PosCredit + PosBillCash + PosBillCredit) as Revenue
  from StoreRevenue
  inner join Stores
    on Stores.ID = StoreRevenue.StoreID
) d
pivot
(
  sum(Revenue)
  for StoreName in ([Avcılar Mağaza], [Ataşehir Mağaza]..)
) piv;

Or you can use an aggregate function with a CASE:
select DATEADD(dd, DATEDIFF(dd, 0, PostDate), 0) as Date,
  sum(case when Stores.Name = 'Avcılar Mağaza'
      then PosCash + PosCredit + PosBillCash + PosBillCredit end) as [Avcılar Mağaza],
  sum(case when Stores.Name = 'Ataşehir Mağaza'
      then PosCash + PosCredit + PosBillCash + PosBillCredit end) as [Ataşehir Mağaza]
from StoreRevenue
inner join Stores
  on Stores.ID = StoreRevenue.StoreID
group by DATEADD(dd, DATEDIFF(dd, 0, PostDate), 0)

If you have an unknown number fo stores, then you can use dynamic sql:
DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(name)
                    from Stores
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT Date, ' + @cols + '
            from
            (
                select
                  DATEADD(dd, DATEDIFF(dd, 0, PostDate), 0) as Date,
                  Stores.Name StoreName,
                  (PosCash + PosCredit + PosBillCash + PosBillCredit) as Revenue
                from StoreRevenue
                inner join Stores
                  on Stores.ID = StoreRevenue.StoreID
            ) x
            pivot
            (
                sum(Revenue)
                for StoreName in (' + @cols + ')
            ) p '

execute(@query)


text:
Q: Carrying an ID with strings to a next page I'm trying to carry the ID to the next page, but all i manage to get is review.php?ID= without the ID.
Here is the code:
html = html + "Name:" + name + "Type : " + type + "Location : " + location + '<input type="button" value="Write a review!" onclick=parent.location="review.php?ID=" ('+ ID +') />'  + "
";

Thanks in advance for any help.

A: There's a couple things wrong here.  You have mismatched quotes (single and double), and I'm pretty sure the id shouldnt have spaces round it with parens. The embeded quotes need to be escaped, too
something like this:
html = html + "Name:" + name + "Type : " + type + "Location : " + location +
"<input type='button' value='Write a review!' onclick='parent.location=\"review.php?ID=("+ID+")\" />"  + "
";


text:
Q: How to safely push to a local git repository? We have two git repositories a and b. Both are local repositories. How can I push repo b to repo a and repo a to repo b?
# remove and create new '/tmp/repos'
rm -rf /tmp/repos
mkdir -p /tmp/repos

# create (init) and config repo 'a'
git init /tmp/repos/a
git -C /tmp/repos/a config user.email "a@example.com"
git -C /tmp/repos/a config user.name "name_a"

# clone and config repo 'a' to repo 'b'
git clone /tmp/repos/a /tmp/repos/b
git -C /tmp/repos/b config user.email "b@example.com"
git -C /tmp/repos/b config user.name "name_b"

# create file './text.txt' in repo 'b', add it, and commit it
echo "first line" > /tmp/repos/b/test.txt
git -C /tmp/repos/b add ./test.txt
git -C /tmp/repos/b commit ./test.txt -m "add first line"

What I've tried so far is to set a as a bare repository, push from b to a, and reset a to a non-bare repository:
git -C /tmp/repos/a config --bool core.bare true
git -C /tmp/repos/b push origin master
git -C /tmp/repos/a config --bool core.bare false

But this is not a solution because both repositories must have a working dir and we cannot depend on the status of the other repository.
Please note that I wish to push from repo b to repo a (or something equivalent). I'm aware that I can pull repo b from repo a. But this is not what I need.
git -C /tmp/repos/a pull /tmp/repos/b

Btw, currently we're using an intermediary local repo c.
We are searching for a way to avoid such third (common) repository.
Kind of real distributed without a central repository.
I understand using the common repository is safe, robust and simple.
What I'm interested in is to understand how it could work without it,
and learn where the problems are when two repositories with working trees communicate directly.
In other words: if it is not safe, robust and simple, I would like to really understand exactly why.

A: If I understand you correctly, you have 2 repos locally which (simplifying) looks like this:
a
|- .git
|- foo.txt

and
b
|- .git
|- bar.txt

And now you want to push from repo A to repo B? This is unusual setup as in general you do not push to working repo, but to remote repo. So in this case you would create 3rd repo:
mkdir c.git && cd c && git init --bare

And you would use that repo as your "remote" by:
git remote add origin /path/to/c.git

And then you can work with it as with any other remote repo.
But if you really want to push to working repo then you need to push to .git folder, so your command would look like:
git push /path/to/b/.git master

However remember that this will only update Git dir and working tree will remain untouched until someone come and do git checkout master.