text:
Q: Chat.SE bug (typo) on Android When you aren't logged in, on the bottom of the screen there is a link that says "logged in" - this really confused me at first as I assumed, since I log into SE with Google, it automatically logged me in via my Google account (it is Android after all). Problem was... I couldn't figure out how to chat via my phone! I felt silly and even downloaded a different browser thinking maybe it was just a rendering problem since the menu button looks like its sitting on top of a text box.
I soon discovered this was a typo and that the "logged in" text was a link to the log in page so it should say "Log in" or something to that extent. (Once I logged in I could chat just fine)

A: As I said in a comment, the actual text is in fact correct, since the link is part of the whole sentence "You must be logged in to chat." The issue was that the styling in the gamedev.se chat theme was incorrectly set up, so that the non-link text appeared in black-on-black. And that's of course as good as not being there at all.
That's fixed now. Thanks!


text:
Q: Тестирование и проблема очередей в Laravel Имееться простой достаточно тест на Laravel. Ну примерно следующего содержания.
$this->json('post', route('...'))->assertOk();
После запуска получаю в консоле такую ошибку:
Fatal error: Uncaught Illuminate\Contracts\Container\BindingResolutionException: Target [Illuminate\Contracts\Bus\Dispatcher] is not instantiable. in ...\vendor\laravel\framework\src\Illuminate\Container\Container.php:1093
В контроллере который обрабатывает запрос после ответа идет еще сброс кэша. CacheClearJob::dispatch();
В самом Job классе просто вызов \Cache::forget('key')
Версия Laravel 8, PHP 7.4
UPD: вызов очистки кэша через register_shutdown_function() в конструкторе. Это и стало причиной проблеммы, добавляю в описание т.к. этот момент был только на скрине.

A: register_shutdown_function() запускается, когда свою работу завершает не только сам тест, но и PHPUnit. Я расставил в разных файлах вывод того, что сейчас выполняется:
echo sprintf("%s called\n", __METHOD__);

Затем запустил, и получилось так:
Tests\Feature\Order\OrderCreatedTest::testOrderCreated called
App\Domain\Order\Controllers\OrderController::order called
Illuminate\Foundation\Testing\TestCase::tearDown called

   PASS  Tests\Feature\Order\OrderCreatedTest
  ✓ order created

  Tests:  1 passed
  Time:   0.15s

App\Domain\Order\Controllers\OrderController::shutdown called

Получается, порядок такой:

*

*запуск теста

*запуск контроллера

*запуск tearDown()

*запуск метода shutdown(), который был зарегистрирован через register_shutdown_function() в контроллере

TestCase, от которого отнаследован тест, имеет 2 важных метода:

*

*setUp() - создает экземпляр приложения, бутсрапит его. На этом экземпляре, собственно, и прогоняются тесты.

*tearDown(), который "прибирается": $this->app->flush(). Что в этом flush() происходит?

public function flush()
{
    parent::flush();

    $this->buildStack = [];
    $this->loadedProviders = [];
    $this->bootedCallbacks = [];
    $this->bootingCallbacks = [];
    $this->deferredServices = [];
    $this->reboundCallbacks = [];
    $this->serviceProviders = [];
    $this->resolvingCallbacks = [];
    $this->terminatingCallbacks = [];
    $this->beforeResolvingCallbacks = [];
    $this->afterResolvingCallbacks = [];
    $this->globalBeforeResolvingCallbacks = [];
    $this->globalResolvingCallbacks = [];
    $this->globalAfterResolvingCallbacks = [];
}

А это - содержимое parent::flush():
public function flush()
{
    $this->aliases = [];
    $this->resolved = [];
    $this->bindings = [];
    $this->instances = [];
    $this->abstractAliases = [];
    $this->scopedInstances = [];
}

Как видите, происходит серьезная чистка экземпляра приложения, после которой мало что продолжает работать. Если закомментировать $this->app->flush();, ваш тест пройдет, но это также нарушит логику PHPUnit, в котором каждый тест должен быть независим, а значит "уборка" необходима.
Что можно посоветовать? Найти другой способ очистки кеша. Деструктор контроллера не подходит по этой же причине - выполняется после tearDown(). Попробуйте это:
public function __construct()
{
    CacheClearJob::dispatch()->afterResponse();
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Troubleshoot large number of TCP retransmits / dup ack / segment lost I have a problem with RDC slowing to a crawl or disconnecting entirely.  Client is XP SP3 w/ RDC 6, server is Win 2k8 R2.  Both have been scanned thoroughly and found to be virus free.
I downloaded and installed Wireshark on the client computer and ran a packet capture during an RDC session.  The log showed at least 10-20 retransmit / dup ack /segment losses per minute during normal usage.  Then, when I had a disconnect, it shot up to dozens of these per second.
FYI, I know very little about the Wireshark tool or how to do a full analysis of this problem.
** EDIT **
A little about my network architecture:
Client -

*

*12 Mb down, 1Mb up

*1 laptop directly connected to the modem -or- (I've tried it this way with no change) plugged in through a Linksys DSL phone box

*Located in Israel.  Telecom services are split into infrastructure and ISP there, infrastructure is provided by HOT, ISP is provided by Netvision.

Server -

*

*5 Mb down, 5 Mb up

*Medium web/data/app hosting network, routed with Allied Telesyn AR410

*Located in CA (US).  ISP is Call America.

Other remote clients have no issues connecting to the servers (either speed or disconnects).  Several other laptops have been used at the client location to verify it is not a hardware issue.  The cable modem has also been replaced.

A: Probably not enough information, but here is some general guidance:
If other remote clients are ok and do not experience the symptom, the problem probably is not with the server.  It may be the connection for that client.
A retransmit typically means that a packet was not acknowledged, so there usually will not be actual
"errors" in a packet capture.  It means that one end was sending the packets, and the other was not acknowledged.  You may want to perform the capture from both ends, to determine if the retransmit is one-way only, or both ways.
If you ping your host from the client, what is the response time?  If it is over 150 ms, you may have a suboptimal connection.
The server network adapter setting for Large Send Offload should be disabled.  Windows should be smart enough to know it cannot send large packets to machines on different subnets, but sadly this is not always the case.  If your server is a hyper-v guest, this is almost certainly the problem.
MTU.  Generally speaking, accessing a server remotely when you are not on the same subnet, the MTU should always be whatever the smallest MTU is between the two endpoints.  And that usually means the client.  For remote clients that connect over VPN, it is not uncommon to have an MTU of 1400 or even lower.  It can be beneficial to set the server MTU to match what the lowest MTU would be, to avoid issues where MTU cannot be discovered properly (sometimes referred to as black hole routers).  To find the MTU for your connection you can enter the following command from your client:
ping -f -l xxxx <server ip>

Where xxxx is the MTU size.  Start with 1400.  If it works, increase it until it displays the message "Packet needs to be fragmented but DF set".  If 1400 does not work, decrease it until it does.  The highest number that works is your payload size.  Add 28 to the payload size and that is your MTU.
You can set the server MTU at the following registry location:
HKLM\SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\{guid of the network adapter}

FYI - RDP packets are always sent with the "Do Not Fragment" bit set.

A: Be aware that Network Monitor will often errorneously flag packets as 'Segment Lost' at the beginning of a capture for any TCP conversation the had started prior to the capture.
That is because Netmanager will see Acknowledgements (Sequence Numbers) for packets that occurred prior to the start of capture.  Since it sees the ACK without seeing the corresponding packet, it assumes the packet is lost and flags it with 'Segment Lost'.  Be careful not to confuse this start of capture lost segment with actual lost seqments.  If you sort a conversation by individual IP flow these should sort to the top.
Alternatively you can save the capture to a file and then reload it back into Netmanager.  I noticed it will not longer flag the start of capture acknowledgements as 'Segment Lost' after reload.

A: You are receiving the following packages:

*

*TCP Retransmits

*Duplicate ACK

*Segment lost

If you receive a TCP retransmit, this is because the ACK you have sent was not received by the server. The server was not aware the TCP packet was received, thinks it was lost underway and will send it again.
The duplicate ACK is typically received at the Sender in the following scenario:

*

*Receiver receives packet 1

*Receiver sends ACK for packet 1

*Receiver receives packet 3

*Receiver sends ACK for packet 1 (maximum packet sequence number received). This is a Duplicate ACK for the Sender.

*Receiver receives packet 4

*Receiver sends ACK for packet 1 (maximum packet sequence number received). This is a Duplicate ACK for the Sender.

The third error (Segment Lost) is exactly this scenario, but at the Receiver side. It indicates packet 3 was received before packet 2.
All these errors indicate congestion: somewhere along the way packets are dropped. This can have a lot of causes, so we really need a good indication of your network architecture to be able to tell you what the cause is.
Normally, congestion is not a bad thing. TCP is made to automatically adjust to this scenario, increasing transfer rate until packet drops / slowdown starts to occur. The fact that congestion poses problems here can have a number of different causes:

*

*Your network is so congested it cannot handle the minimum required transfer rate for RDP. This would be the case for a 2G cell phone connection.

*The algorithms in server or client are badly configured. Some ADSL "optimizer" programs can cause this, messing with the parameters of the Vegas TCP algorithm in Windows.

*There is some other error (very high load on server or client, bad firmware/driver for network card, ...)


text:
Q: Do I have to buy a CPU cooler separately? I bought the Intel i7 7700K Processor off eBay with the following picture:

And a GA-B250-D3H motherboard.
Is a brand CPU cooler/heat sink included in any of these packages or you always have to buy it separately?
How about thermal paste?

A: To me this looks like a "boxed CPU" which means that there is a cooler included. This so called "stock cooler" works fine but is very low quality and loud. I personally don't recommend using it.
Especially if you overclock your CPU (which I suppose because you bought the K version) I would invest into a tower cooler. They offer a way better cooling performance (→ lower temps, higher stability, more overclocking headroom etc) and are usually a lot quieter.
Personally (on a AMD FX-8350 which is "famous" for getting hot) I use a bequiet Shadow Rock 2 but something like a coolermaster Hyper 212 Evo might have been the better choice. But make sure it fits into your case (usually the case manufacturer mentions info like a "max. cooler height").
About thermal paste:
There might be some already on the heatsink. I'm not sure if intel does that. But I don't recommend using that either (probably you can't even use it because it's on the stock heatsink). There are good ones available on the internet, just search a little while (I guess you know linustechtips, he recommended some).
Just one little tip for that: Don't buy more because it's cheaper per gram. You need so little amounts of it, like 3 grams is enough.

A: Skylake (6xxx) and newer K-series Intel processors do not come with heat sinks. K-series processors are targeted at overclockers (that's the only thing the K designation really means) and Intel knows that including a cheapo heat sink in the box will result in an unfortunate amount of aluminum being discarded.
Nearly all of Iuppiter Zeus's answer is on the money except for the fact that your processor will include a heat sink and fan. It will not unless specified by the seller. The Hyper-212 outclasses all others in its price range. If you are looking to get heavily into overclocking and invest in something $100+ there are dedicated forums I'd suggest you look into; for anything short of that the 212 will serve you well.
I would also clarify that nearly all heat sinks will include thermal interfacing material (TIM; or "thermal paste"). What comes in the box is perfectly fine unless you plan to tinker with your overclock for max performance. 3 grams is a lot of paste, by the way. Use about a grain of rice.


text:
Q: Worker Threads and Using Multple Messages Queue Software? Good Idea? Problem: I have a program that will do a lot of post-processing on a file and then sending it ANOTHER web-service for more processing.  Does my design smell and is this the right way to 'tackle a problem'

*

*Rails Accepts file and kicks off a resque_job  to do work

*The resque job will sends work via REST to another web-service cluster(very slow.. does MORE work) && places the task to be monitored in a monitor_queue  within Rabbit MQ for completion . The Resque job will not wait another-webservice to complete task. It exits

There are some smell issues in my design, perhaps gut reactions that could be misguided?

*

*Is it good design to have TWO message queues. The rational is that Rabbit_MQ has a built in method for creating worker_queues (they even give sample code). Resque_Job uses redis, and seems to be the accepted method of having 'delayed jobs' with Rails.

*What I like about RabbitMQ: It has round-robin tasking  abilities (so all threats get tasked) , and guarantees work will not be removed from a QUEUE without a message acknowledgement.

*Resque seems to primary suggested solution for launching delayed_jobs within Rails.

Followup: When performing the polling, I was thinking a simple worker_queue of just iterating through the entire queue with seperate 'workers' makes the most sense? Do you agree.

A: I don't think this is a bad design. It's a type of Service Oriented Architecture, and even though you have separate queuing systems, they're completely separate applications and would only communicate through a specific interface, which has some pros and cons. I didn't quite understand the reasoning for using RabbitMQ, though. Also, a lot of new apps seem to be using Sidekiq; IMHO it is superior in every way to Resque.


text:
Q: How to identify whether sentence is passive voice or in simple tense? How to identify whether sentence is passive voice or in simple present tense?
I.e. does it mean habitual or repeated action or just simple passive tense?

This table is cleaned by John

Meanings

*

*Conveys status that table is cleaned because John has cleaned the table. (Passive)

*Every day this table is cleaned by John. (Present Tense)

Similarly for past tense sentence

This table was cleaned by John

Meanings

*

*Conveys status that table was cleaned because John had cleaned the table.(Passive)

*In the past every day this table was cleaned by John. (Past Tense)

A: When I, with my AmE ear, hear this phrase:

This table is cleaned by John.

I understand it to mean that the table is one that John cleans on a regular basis. Cleaning the table is his responsibility. When the verb is in the simple present tense, that is the only meaning.
However, some ambiguity does fill the vacuum when the tense shifts to simple past:

This table was cleaned by John.

It could mean that the table is one John cleaned on a regular basis. The table was his responsibility.  Or it could mean no more than that John cleared a mess from the table.
Context would resolve the ambiguity.


text:
Q: openGl / glut: seeing through blocks, I am writing a Programm, trying to display some kind of sphere consisting of independent blocks. Unfortunately, from some angles I can see through the blocks, seeing the ones behind them.
good angle: http://i.imgur.com/6o120KF.png
bad angle: http://i.imgur.com/DbB9iVO.png
I was checking some posts, but nothing helped. I cared for depth buffer, zNear but now I have no ideas.May someone halp?
My Code
int main(int argc, char** argv) {

//init world
world.init();
//configure GLUT
glutInit(&argc, argv);              // Initialize GLUT
glutInitDisplayMode(GLUT_DOUBLE);   // Enable double buffered mode
glutInitWindowSize(WIDTH, HEIGHT);   // Set the window's initial width & height
glutInitWindowPosition(50, 50);         // Position the window's initial top-left corner
glutCreateWindow(title);            // Create window with the given title
glutDisplayFunc(display);               // Register callback handler for window re-paint event
glutKeyboardFunc(keyboard);         // call keyboard() when key is hit
glutIdleFunc(display);              // if no rendering to be, call display
glutReshapeFunc(reshape);               // Register callback handler for window re-size event
initGL();                               // Our own OpenGL initialization
glutMainLoop();                         // Enter the infinite event-processing loop
return 0;
}

void initGL() {
glClearColor(0.0f, 0.0f, 0.0f, 1.0f); // Set background color to black and opaque
glClearDepth(1.0f);                   // Set background depth to farthest
glEnable(GL_DEPTH_TEST);   // Enable depth testing for z-culling
glDisable(GL_BLEND);
glDepthFunc(GL_LEQUAL);    // Set the type of depth-test
glShadeModel(GL_SMOOTH);   // Enable smooth shading
glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);  // Nice perspective corrections
glClear(GL_DEPTH_BUFFER_BIT);
}

void display() {

glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);     // Clear color and depth buffers
glMatrixMode(GL_MODELVIEW);                         // To operate on model-view matrix
glLoadIdentity();                 // Reset the model-view matrix

//formulas for camera changes
glTranslatef(translatex, 2.0f, -7.0f);  // Move right and into the screen
glRotated(rotAnglex, 1, 0, 0);  // rotate by rotAngle about y-axis
glRotated(rotAngley, 0, 1, 0);  // rotate by rotAngle about y-axis
glRotated(rotAnglez, 0, 0, 1);  // rotate by rotAngle about y-axis
glScalef(zoom ,zoom ,zoom);

glBegin(GL_LINES);
// draw line for x axis
glColor3f(1.0, 0.0, 0.0);
glVertex3f(0.0 - xmove, 0.0 - ymove, 0.0 - zmove);
glVertex3f(100.0 - xmove, 0.0 - ymove, 0.0 -zmove);
// draw line for y axis
glColor3f(0.0, 1.0, 0.0);
glVertex3f(0.0 - xmove, 0.0 - ymove, 0.0 - zmove);
glVertex3f(0.0 - xmove, 100.0 - ymove, 0.0 -zmove);
// draw line for Z axis
glColor3f(0.0, 0.0, 1.0);
glVertex3f(0.0 - xmove, 0.0 - ymove, 0.0 - zmove);
glVertex3f(0.0 - xmove, 0.0 - ymove, 100.0 -zmove);
glEnd();
glBegin(GL_QUADS);
//draw axes

if(it_counter++ < iterations){
//print world
 BOOST_FOREACH(std::Cell* now_cell, world.cells){
    BOOST_FOREACH(std::Voxel* now_voxel, now_cell->content){
        addVoxel(*now_voxel);
    }
 }
}

glEnd();  // End of drawing color-cube

glLoadIdentity();                  // Reset the model-view matrix
glTranslatef(-1.5f, 0.0f, -6.0f);  // Move left and into the screen
glScalef(3.0f ,3.0f ,3.0f);

glutSwapBuffers();  // Swap the front and back frame buffers (double buffering)
}

Is the order of adding blocks (voxels in code) important for rendering?

A: It seams as if you created a window without a depth buffer. Enabling the depth-test will only work if your window has such a buffer.
To solve your problem, you have to change
glutInitDisplayMode(GLUT_DOUBLE);

to
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE);


text:
Q: Encoded picture to Byte[] in C# I'm running an xml request to get Item Picture in Quickbooks POS and it returns this response:
string response = <?xml version="1.0" encoding="windows-1252"?>
<QBPOSXML>
    <QBPOSXMLMsgsRs>
        <ItemInventoryPicturesQueryRs requestID="912873739" statusCode="0" statusMessage="Status OK" statusSeverity="Info">
            <ItemInventoryPicturesRet>
                <ListID>5523943659390533889</ListID>
                <ItemInventoryPicture>
                    <EncodedPicture>/9j/4AAQSkZJRgABAgEAAAAAAAD...</EncodedPicture>
                    <PictureName></PictureName>
                </ItemInventoryPicture>
            </ItemInventoryPicturesRet>
        </ItemInventoryPicturesQueryRs>
    </QBPOSXMLMsgsRs>
</QBPOSXML>

and I want to save the encoded picture section as a jpg file, I tried this approach but it didn't work at all!
public static byte[] StrToByteArray(string str)
{
  System.Text.ASCIIEncoding  encoding=new System.Text.ASCIIEncoding();
  return encoding.GetBytes(str);
}

//imageCode is the value of the EncodedPicture element in the xml
File.WriteAllBytes(@"C:\Temp\image.jpg",StrToByteArray(imagecodes));

This is a base64 of the image above
[encoded data, 11872 characters]

A: I suspect very few JPEG files are also printable ASCII text.
It seems much more likely that the content of EncodedPicture is a base64-representation of the data - which is confirmed by the text at the bottom of your question.
So assuming you've already extracted the value of the EncodedPicture element as a string, you just want Convert.FromBase64String:
File.WriteAllBytes(@"C:\Temp\image.jpg", Convert.FromBase64String(imagecodes));


text:
Q: unable to connect through SSH key to bluemix container I am currently trying to use the bluemix container service (in beta)
When I want to create a new container, I follow the steps, and just choose the name and the ports to open. I paste a SSH, and at the end I get the error :
"Unable to create container. Error message returned is: Bad Request".
Whereas if I do not paste my key, there is no problem.
I have tried with another key, created with puttygen, and I still get the same error.
I don't know what is wrong, as I basically chose the default options.
I have tried with the browsers firefox & opera on windows.
How can I solve this?

A: Use a public key of the form "ssh-rsa", space, 200+ characters ending in ==, space, username@hostname.  I generated mine using ssh-keygen -t rsa.  I pasted the entire contents of the generated .pub file.


text:
Q: STS is so slow on any operations I'm using STS-3.6.1.RELEASE on Win 8 and its performance is killing me. Opening files, saving changes, content assist feature or organizing imports are very slow and sometimes it crushes down.
I googled about slow performance and fasting solutions. Then applied them but result is same. Here some suggestions;

*

*Why is SpringSource Tool Suite (STS) so slow? And how can I fix it?

*http://philip.yurchuk.com/software/optimal-jvm-settings-for-sts/
Eclipse or Android Studio runs very well, just STS doesnt run properly. I dont know what to do. I tried anything; some .ini file settings, other STS versions (3.6.3), closing project validators etc. but same result. I think problem is on my pc because same STS version works very well with same projects on my co-worker's pc (Win 7-8, Mac).
My pc properties and STS
Win 8.1, i5 1.7ghz(4cpu), 64bit, 8gb ram
spring-tool-suite-3.6.1.RELEASE-e4.4-win32-x86_64
and sts.ini file
-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20140415-2008.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20140603-1326
-product
org.springsource.sts.ide
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
712M
-vmargs
-Dosgi.requiredJavaVersion=1.6
-Xms256m
-Xmx1536m
-XX:MaxPermSize=1024m
-Dorg.eclipse.swt.browser.IEVersion=10001
-XX:CompileThreshold=1000
-XX:MaxGCPauseMillis=10
-XX:MaxHeapFreeRatio=70
-XX:+CMSIncrementalPacing
-XX:+UnlockExperimentalVMOptions
-XX:+UseG1GC
-XX:+UseFastAccessorMethods
-Djava.net.preferIPv4Stack=true
-Dsun.lang.ClassLoader.allowArraySyntax=true

Any suggestion or are others having similar experiences?

A: Please do mem profiling of the JVM while using STS.
Try to increase the perm size to 1024M and try again.
Thnx,
Subhash

A: Do you have STS as well as your workspace located on disc? Having things on a shared network drive, for example, causes STS to slow down quite often. Just a wild guess, since you said that the same STS version performs well on a different machine while having the same projects the workspace.
If nothing helps, you could try to run JVisualVM to see what is going on inside while STS is being so slow - at least to get an idea where to look for more details.

A: I encountered the same problem,
i solved it by turning the build automatically option off,
it works..
you can turn the automatic content assist off as well
but just unchecking the build autimaticall option will be enough..
you can find the option in project -> build automatically
just uncheck it .. and you are good to go.


text:
Q: Module for executing postponed initialization code Where to put initialization code (connecting to databases, generating stuff, loading data files, etc)?
Here are some existing options:

*

*Put it into the module in question. This will execute the code in BEGIN{} when the module is used

(+) Good encapsulation.
(-) Everything is tied to databases, configuration, specific file locations etc. Hard to isolate unit tests, even harder to run code snippets to find bugs, as in perl -MFoo -d -we 'Foo->new'

*Put it into separate script (startup.pl etc)

(-) Code away from where it's used, easy to forget something.
(-) Initializing all-or-nothing.

*startup() (or other name) routine in every module in project.

(-) still easy to forget to run it.

*Use Perl's built in INIT block.

Here's the problem (same for Apache, of course):
 bash$ plackup -e 'use warnings; INIT{ warn "foo"; }; sub { warn "here"; return [200, [], []] };'
 Too late to run INIT block at (eval 7) line 1.
 HTTP::Server::PSGI: Accepting connections at http://0:5000/
 here at (eval 7) line 1.
 127.0.0.1 - - [20/Nov/2014:14:18:08 +0200] "GET / HTTP/1.1" 200 - "-" "Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:33.0) Gecko/20100101 Firefox/33.0"

Note the Too late to call INIT warning and no sign of "foo" in output.
Now I'd like to have a module which is used as follows:
In project's module:
use Init::Queue sub {
    get_dbh();
    load_file();
    build_cache();
}; # postpone till explicitly called

In production/initialization code:
Init::Queue->startup();
# this executes all startup blocks,
# in order of appearance

Is there such a module? If not, is it needed? Or is there a simpler approach which I've overlooked?

A: Well, the answer is 'it depends'. But personally, I tend to take an 'init on first use' approach. That's relatively easy when you're doing it Object Oriented - hook the constructor and get it to set things up.
For non OO perl, I actually tend to do something like:
{
    my $thing_to_init;
    sub init {
        $thing_to_init = 1;
    }

   sub call_some_function {
       init() unless defined $thing_to_init;

        #do everything else
    }
}

Because it's inside a closure, $thing_to_init isn't accessible from the module namespace, but you could either: manually call the init() sub, or just let the thing init itself when it fires up.


text:
Q: Use of maths in the Apple pARk sample code I'm studied the pARK example project (http://developer.apple.com/library/IOS/#samplecode/pARk/Introduction/Intro.html#//apple_ref/doc/uid/DTS40011083) so I can apply some of its fundamentals in an app i'm working on. I understand nearly everything, except:

*

*The way it has to calculate if a point of interest must appear or not. It gets the attitude, multiply it with the projection matrix (to get the rotation in GL coords?), then multiply that matrix with the coordinates of the point of interest and, at last, look at the last coordinate of that vector to find out if the point of interest must be shown. Which are the mathematic fundamentals of this?

Thanks a lot!!

A: I assume you are referring to the following method:
- (void)drawRect:(CGRect)rect
{
     if (placesOfInterestCoordinates == nil) {
         return;
     }

    mat4f_t projectionCameraTransform;
    multiplyMatrixAndMatrix(projectionCameraTransform, projectionTransform, cameraTransform);

    int i = 0;
    for (PlaceOfInterest *poi in [placesOfInterest objectEnumerator]) {
        vec4f_t v;
        multiplyMatrixAndVector(v, projectionCameraTransform, placesOfInterestCoordinates[i]);

        float x = (v[0] / v[3] + 1.0f) * 0.5f;
        float y = (v[1] / v[3] + 1.0f) * 0.5f;
        if (v[2] < 0.0f) {
            poi.view.center = CGPointMake(x*self.bounds.size.width, self.bounds.size.height-y*self.bounds.size.height);
            poi.view.hidden = NO;
        } else {
            poi.view.hidden = YES;
        }
        i++;
    }
}

This is performing an OpenGL like vertex transformation on the places of interest to check if they are in a viewable frustum. The frustum is created in the following line:
createProjectionMatrix(projectionTransform, 60.0f*DEGREES_TO_RADIANS, self.bounds.size.width*1.0f / self.bounds.size.height, 0.25f, 1000.0f);

This sets up a frustum with a 60 degree field of view, a near clipping plane of 0.25 and a far clipping plane of 1000. Any point of interest that is further away than 1000 units will then not be visible.
So, to step through the code, first the projection matrix that sets up the frustum, and the camera view matrix, which simply rotates the object so it is the right way up relative to the camera, are multiplied together. Then, for each place of interest, its location is multiplied by the viewProjection matrix. This will project the location of the place of interest into the view frustum, applying rotation and perspective.
The next two lines then convert the transformed location of the place into whats known as normalized device coordinates. The 4 component vector needs to be collapsed to 3 dimensional space, this is achieved by projecting it onto the plane w == 1, by dividing the vector by its w component, v[3]. It is then possible to determine if the point lies within the projection frustum by checking if its coordinates lie in the cube with side length 2 with origin [0, 0, 0]. In this case, the x and y coordinates are being biased from the range [-1 1] to [0 1] to match up with the UIKit coordinate system, by adding 1 and dividing by 2.
Next, the v[2] component, z, is checked to see if it is greater than 0. This is actually incorrect as it has not been biased, it should be checked to see if it is greater than -1. This will detect if the place of interest is in the first half of the projection frustum, if it is then the object is deemed visible and displayed.
If you are unfamiliar with vertex projection and coordinate systems, this is a huge topic with a fairly steep learning curve. There is however a lot of material online covering it, here are a couple of links to get you started:
http://www.falloutsoftware.com/tutorials/gl/gl0.htm
http://www.opengl.org/wiki/Vertex_Transformation
Good luck//


text:
Q: dynamic streaming file format is there any streaming file format that works like this :

*

*make an http post or get

*scrap html source

*get the url

*play

what i can do with python so far is this :
import sys
import requests
from bs4 import BeautifulSoup
import subprocess

# make request with requests
# scraping with BeautifulSoup
# get the url (url = http://streamsource)

# play it via media player classic
MPC_path = '\\Program Files\\MPC-HC\\mpc-hc.exe'
video_path = url
subprocess.call([MPC_path, video_path])

but is there a file format that is supported in kodi/xbmc and created to do this kind of work?
Unlike M3U, that uses the url directly


text:
Q: can somebody give example of using audio engine of cocos2d javascript port In cocos2d objective c port, we can easily play sound effects by:
[[SimpleAudioEngine sharekEngine] playEffect:@"xyz.wav"];

What am I supposed to use for javascript port of cocos2d?

A: As far as I can tell cocos2d for Javascript does not have audio functionality. See this thread from last year:
http://cocos2d-javascript.org/2010/Dec/10/site-launched-for-cocos2d-javascript
As stated, you can play sounds this way:
var crash = new Audio("crash.mp3");
crash.play();

That's it.


text:
Q: How could we deal with more than 60 tags for Azure Notification Hubs We are implementing push notification for a football app.
According to Azure documentation, any registration or installation can only associate up to 60 tags.
We understand that is not the server limit. It is "per device per app" limit.
Suppose we would like to send any football event news to the users (e.g. red cards, score update) based on the matches (user preference), then 60 tags are not sufficient because there could be more than 100 matches per day.
For more examples, the tags may look like

*

*team1-team2-redcard

*team1-team2-score

*team1-team2-corner

*team2-team3-redcard

*team2-team3-score

*team2-team3-corner
...

So, how could we do to deal with the case that some users may potential subscribe to more than 60+ tags?

A: Unfortunately, Azure Notification Hubs limits tags to 60. What we recommend to customers who need more than 60 tags is to store the device token in your backend along with any classification values, then build the audience on the backend and send notifications to all the devices that meet that criteria. That's the only way to do it.


text:
Q: 'require is not defined' in Meteor.js when including NPM package I'm trying to use a npm package from Meteor.js (Release 0.6.6.3) using Meteor.require. However it throws an error saying that require is not defined. Why is this and how can we solve it?
mrt add npm
npm install github

packages.json
{
    "github": "0.1.8"
}

github.js
var GITHUB = Meteor.require('github');

Error
ReferenceError: require is not defined

The npm package has lines such as
var https = require('https')
var url = require('url')
var crypto = require('crypto')

Must the package's code be manually edited to use Npm.require? Editing them manually got rid of the errors.
However theres a line:
module.exports = SOMETHING

How should we call module from within meteor?

A: Making comments above an answer.
Is Meteor.require() a typo? That is what is in your code though your question text refers to the correct Npm.require().
I think module.exports is there for non-meteor use of the same file.  Within meteor variables for export should be

*

*declared as globals inside the package

*exported with api.export() within the package.js file.

The documentation on this is a bit rough but look at namespacing and writing packages.  Also looking into the various meteor packages on github is very useful.

A: Meteor.require is a function added by the meteor npm smart package, which actually doesn't do much for using npm other than wrapping some asynchronous callbacks. It's a few months old, so you might want to try using Meteor's Npm.require directly in case something broke.
The monkey-patching of the Meteor global by this package is misleading.

A: Use Npm.require() in meteor.
Like this:
var fs = Npm.require("fs");

For that you need to have a Meteor package: meteorhacks:npm , npm-container

A: Make sure you're using the meteor-npm package.
https://www.npmjs.com/package/meteor-npm


text:
Q: Mongoose lookup across 3 collections using foreign key I have found a few questions that relate to this (here and here) but I have been unable to interpret the answers in a way that I can understand how to do what I need.
I have 3 collections: Organisations, Users, and Projects. Every project belongs to one user, and every user belongs to one organisation. From the user's id, I need to return all the projects that belong to the organisation that the logged-in user belongs to.
Returning the projects from the collection that belong to the user is easy, with this query:
const projects = await Project.find({ user: req.user.id }).sort({ createdAt: -1 })

Each user has an organisation id as a foreign key, and I think I need to do something with $lookup and perhaps $unwind mongo commands, but unlike with SQL queries I really struggle to understand what's going on so I can construct queries correctly.
EDIT: Using this query
const orgProjects = User.aggregate(
    [
        {
            $match: { _id: req.user.id }
        },
        {
            $project: { _id: 0, org_id: 1 }
        },
        {
            $lookup: {
                from: "users",
                localField: "organisation",
                foreignField: Organisation._id,
                as: "users_of_org"
            }
        },
        {
            $lookup: {
                from: "projects",
                localField: "users_of_org._id",
                foreignField: "user",
                as: "projects"
            }
        },
        {
            $unset: ["organisation", "users_of_org"]
        },
        {
            $unwind: "$projects"
        },
        {
            $replaceWith: "$projects"
        }
    ])

Seems to almost work, returning the following:
Aggregate {
  _pipeline: [
    { '$match': [Object] },
    { '$project': [Object] },
    { '$lookup': [Object] },
    { '$lookup': [Object] },
    { '$unset': [Array] },
    { '$unwind': '$projects' },
    { '$replaceWith': '$projects' }
  ],
  _model: Model { User },
  options: {}
}

A: assuming your documents have a schema like this, you could do an aggregation pipeline like below with 2 $lookup stages.
db.users.aggregate(
[
    {
        $match: { _id: "user1" }
    },
    {
        $project: { _id: 0, org_id: 1 }
    },
    {
        $lookup: {
            from: "users",
            localField: "org_id",
            foreignField: "org_id",
            as: "users_of_org"
        }
    },
    {
        $lookup: {
            from: "projects",
            localField: "users_of_org._id",
            foreignField: "user_id",
            as: "projects"
        }
    },
    {
        $unset: ["org_id", "users_of_org"]
    },
    {
        $unwind: "$projects"
    },
    {
        $replaceWith: "$projects"
    }
])


text:
Q: How @EJB annotation is processed in EJB container 3.x from the moment when we deploy ejb components? Questions about ejb session bean behavior when used as injected bean instances.
I'm not 100% sure how this works. I guess it from practice and from reading documents on the subject.
I want to know how @EJB annotation is processed by container in detail.
Session bean have interfaces, impl class, deployment descriptor. We package them in ejb jar.

*

*What is putted in global JNDI by container? Static references to
business interfaces ?

*How and when global JNDI is read from ?

*When component JNDI ENC is populated with ejb reference ?

*Is this reference in JNDI ENC (java:comp/env/beanB) is reference to
session bean component interface, session bean instance proxy or
session bean instance ? Is there difference for SLSB and SFSB ?

*With @EJB annotation on field does every new ejb session bean
instance get new instance of injected ejb in the annotated field or
all ejb instances share the same injected ejb session bean instance
?

*Does ejb injection by lookup (on session context) provide always new
injected ejb instance, example: calling ctx.lookup(ejbReference) in
loop ?

A: *

*In EJB 3.0, the JNDI names are vendor-specific (if available at all; in theory, a container could support EJB references only), but vendors typically return an EJB reference/proxy.  In EJB 3.1, the specification requires the EJB container to make specific java:global, java:app, and java:module names available, and the object returned from these lookups must be an EJB reference/proxy.

*The global JNDI is accessed when you perform a JNDI lookup.  The container might access the global JNDI names in other cases (e.g., when resolving @EJB(lookup="java:app/...")).

*It's undefined when the container populates java:, but the contents must be available before lifecycle callback or business methods are invoked on the component instance.

*@EJB/<ejb-ref>/<ejb-local-ref> ensure lookups always return an EJB reference/proxy and never an actual bean instance.  The proxy ensures that all container services are performed (security, transaction, remoting, etc.) before invoking an actual bean instance.  For SLSB, an arbitrary bean instance will be invoked, and the same or different actual instance might be invoked depending on the thread, concurrency, timing, vendor-specific configuration, etc.  For SFSB, a bean instance with a specific identity will be invoked; you are likely to get the same bean instance, but you might not if the EJB container has passivated the actual bean instance, but reactivation should result in an instance with equivalent state.  For singleton session bean in EJB 3.1, you are guaranteed the singleton bean instance will be invoked.

*It's undefined whether you get the same proxy instance.  For SLSB and singleton beans, injection or lookup could return a single proxy that delegates to the actual bean instance as mentioned above.  For SFSB, the proxy is basically required to be a separate instance per injection or lookup since the proxy must store some state with the identity so it can invoke the specific actual bean instance.

*It's undefined what the container does, but injection is typically implemented by containers using Context.lookup followed by Field.set (or Method.invoke for setter method injection).  Regardless, the instance handling is as described above.


text:
Q: Machine learning models for time-series? I am trying to make prediction of univariate time series with functions from forecast package like: ets,auto.arima and nnetar.During modeling I divide data in traning and test set.So first I traning models with traning set and after with test set I calculate accuracy and so on so forth.
My goal is to make prediction with machine learning methods but I am little bit confused.Namely my question is does this models are machine learnig models?
I am askng this because I work wit time series which contain daily data.This data have sessonal patern,trend etc.So modelling data with other models (e.g random forest etc) maybe is not good choice because other models are maybe more for cross sectional data.


text:
Q: Are there functions $f:D\rightarrow\mathbb{R}$, with $0\in D$, indefinitelly differentiable in $0$ and such that for $n\in\mathbb{N}$, $f^{(n)}(0)=n$? Are there functions $f:D\rightarrow\mathbb{R}$, with $0\in D$, indefinitelly differentiable in $0$ and such that for any $n\in\mathbb{N}$, $f^{(n)}(0)=n$?. I have thought about holomorphic functions, but this case is excluded by the range of our function. Now, if I take a sequence of real numbers such that $f^{k}(0)=x_k$, I get that $x_n=n$ and $f^n(0)=(f^{n-1}(0))'=n$ and $f^{n-1}(0)=n-1=x_{n-1}$ and such $x_{n-1}=n-1$. Then, for a real $x$, $f^{n-1}(x)=\int f^{n}(x)$ and $\int f^{n}(x)=F(x)$ and so $F(0)=0=n-1\rightarrow n=1$ and this is a contradiction. I have a feeling that this is incomplete as I don't think I can integrate the expressions like that but it is the only ideea I have.Any help?

A: Let us first assume that such a function $f$ exists, and that $f$ can be developed into a Taylor series at $x=0$. Then
$$
 f(x) = \sum_{n=0}^\infty \frac{f^{(n)}(0)}{n!} x^n = \sum_{n=0}^\infty \frac{n}{n!} x^n = \sum_{n=1}^\infty \frac{x^n}{(n-1)!} = \sum_{n=0}^\infty \frac{x^{n+1}}{n!}  = x e^x \, .
$$
So we have a possible candidate: $f(x) = xe^x$ is indeed infinitely differentiable on $\Bbb R$ and equal to its Taylor series. That justifies the above calculations and shows that $f^{(n)}(0) = n$ holds for all $n$.
It is also straightforward to verify that
$$
 f^{(n)}(x) = (x+n)e^x \, .
$$
We can even extend the domain to the complex numbers: $f(z) = ze^z$ is an entire function.


text:
Q: Publishing Vb.net10 Application I developed this software application with VB.net and Microsoft Access. The software works fine. publishing this applciation has been a huge problem for me. even though it seem to have published fine, it does not seem to recognise my access Database and props up error everytime and everywhere the database is called and used within the program. How can i overcome this problem please.

A: I just got back from somewhere, anyways... I actually had problems with Microsoft.Jet.OLEDB.4.0 especially in a 64 bit machine. This is because Microsoft.Jet.OLEDB.4.0 is designed as a 32 bit component. If you compile your solution as AnyCpu, it shouldn't work since an x64 process cannot load x86 component. So you have 2 options.
1) Change the compiling to 32 bit mode.
2) Use Microsoft.ACE.OLEDB.12.0 provider instead of Microsoft.Jet.OLEDB.4.0. This uses .accdb instead of .mdb. This is more future proof since the last time I heard, 2003 office won't be supported anymore :)


text:
Q: How to get an OrderedSet of OccurrenceSpecifications from a Lifeline in QVTo? From the diagram on page 570 of the UML spec I concluded that a Lifeline should have the events property, holding an OrderedSet(OcurrenceSpecification). Unfortunately it is not there, at least in the QVTo implementation that I use.
All I have is the coveredBy property, serving me with an (unordered) Set(InteractionFragment). Since my transformation relies on the correct order of MessageOcurrenceSpecification I somehow need to implement myself what I expected to be implemented by the missing events property.
This is what I have so far:
helper Lifeline::getEvents (): OrderedSet(OccurrenceSpecification) {

    return self.coveredBy->selectByKind(OccurrenceSpecification)->sortedBy(true);
}

Obviously sortedBy(true) does not get me far, but I don't know any further. Who can help?
All I could find so far were other people struggling with the same issue years ago, but no solution:

*

*https://www.eclipse.org/forums/index.php/m/1049555/

*https://www.eclipse.org/forums/index.php/m/1050025/

*https://www.eclipse.org/forums/index.php/m/1095764/

A: I don't know if it is possible, using directly coveredBy to get an ordered collection. As coveredBy is unordered, if you access it directly by the feature, you will have an unpredictible order and if you try to access it using the eGet(...) stuff, the same result will occur.
However, if I understood correctly, there is a "trick" that could work.
It relies on the assumption that each OccurrenceSpecification instance you need is held by the same Interaction that contains the Lifeline and uses the way EMF stores contained elements. Actually, each contained element is always kind of 'ordered' relatively to its parent (and for each collection so EMF can find elements back when XMI references are expressed using the element position in collections). So, the idea would be to access all the elements contained by the Interaction that owns the lifeline and filter the ones that are contained in coveredBy.
Expression with Acceleo
This is easy to write in MTL/Acceleo. In know you don't use it, but it illustrates what the expression does:
# In Acceleo:
# 'self' is the lifeline instance
self.interaction.eAllContents(OccurrenceSpecification)->select(e | self.coveredBy->includes(e))->asOrderedSet()

with self.interaction we retrieve the Interaction, then we get all the contained elements with eAllContents(...) and we filter the ones that are in the self.coveredBy collection.
But it is way less intuitive in QVT as eAllContents(...) does not exist. Instead you have to gain access to eContents() which is defined on EObject and returns an EList which is transtyped to a Sequence (in QVT,eAllContents() returns a ETreeIterator which is not transtyped by the QVT engine).
So, how to gain access to eContents() in the helper? There is two solutions:
Solution 1: Using the emf.tools library
The emf.tools library give you the ability to use asEObject() which casts your object in a pure EObject and give you more methods to access to (as eClass() for example...etc).
import emf.tools;  -- we import the EMF tools library

modeltype UML ...; -- all your metamodel imports and stuffs
...
helper Lifeline::getEvents (): OrderedSet(OccurrenceSpecification) {
  return self.interaction.asEObject().eContents()[OccurrenceSpecification]->select(e | self.coveredBy->includes(e))->asOrderedSet();
}

Solution 2: Using oclAstype(...)
If for some reason emf.tools cannot be accessed, you can still cast to an EObject using oclAsType(...).
modeltype UML ...; -- all your metamodel imports and stuffs
modeltype ECORE "strict" uses ecore('http://www.eclipse.org/emf/2002/Ecore');  -- you also register the Ecore metamodel
...
helper Lifeline::getEvents (): OrderedSet(OccurrenceSpecification) {
  return self.interaction.oclAsType(EObject).eContents()[OccurrenceSpecification]->select(e | self.coveredBy->includes(e))->asOrderedSet();
}

Limitation
Ok, let's be honest here, this solution seems to work on the quick tests I performed, but I'm not a 100% sure that you will have all the elements you want as this code relies on the strong assumption that every OccurrenceSpecification you need are in the same Interaction as the Liteline instance. If you are sure that all the coveredBy elements you need are in the Interaction (I think they should be), then, that's not the sexiest solution, but it should do the work.
EDIT>
The solution proposed by hielsnoppe is more eleguant than the one I presented here and should be prefered.

A: Based on the answer by Vincent combined with input from a colleague of mine I came up with the following solution for QVTo:
-- -----------------------------------------------------------------------------
-- Polyfill for the missing Lifeline::events property

query Lifeline::getEvents (): OrderedSet(OccurrenceSpecification) {

    return self.interaction.fragment
            ->selectByKind(OccurrenceSpecification)
            ->select(os: OccurrenceSpecification | os.covered->includes(self))
            ->asOrderedSet();
}

A: You are correct. The Lifeline::events property is clearly shown on the diagram and appears in derived models such as UML.merged.uml.
Unfortunately Eclipse QVTo uses the Ecore projection of the UML metamodel to UML.ecore where unnavigable opposites are pruned. (A recent UML2Ecore enhancement allows the name to be persisted as an EAnnotation.) However once the true property name "events" has been pruned the implicit property name "OccurrenceSpecification" should work.
All associations are navigable in both directions in OCL, so this loss is a bug. (The new Pivot-based Eclipse OCL goes back to the primary UML model in order to avoid UML2Ecore losses. Once Eclipse QVTo migrates to the Pivot OCL you should see the behavior you expected.)


text:
Q: three.js weird artifacts overlapping box and plane I'm seeing the weird behavior when at certain zoom levels / angles.

But at other positions it looks fine.

Can anyone tell me what's going on here, and how to fix it?

A: Decreasing the far distance of the camera solved the problem:
THREE.PerspectiveCamera(50, aspect, 100, 15000)


text:
Q: Why do I get this error? The provider could not determine the Double value Why do I get this error:
The provider could not determine the Double value. For example, the row was just created, the default for the Double column was not available, and the consumer had not yet set a new Double value.
    ElseIf cb_Stat.Text = "Highest Goal/min" Then
        SQL = "SELECT Goals, Mins_Played, ((Mins_Played * 1.0) / Goals) AS gpm FROM PlayerDatabase"
        Dim da As New OleDbDataAdapter(SQL, Connection)
        da.Fill(ds, "PlayerDatabase")
        lbl_Result.Text = ds.Tables("PlayerDatabase").Rows(0).Item(2)
    End If

    Me.lbl_Result.Left = Me.ClientSize.Width \ 2 - Me.lbl_Result.Width \ 2
    Connection.Close()

A: Your column Goals contains a zero value. In this case the correct error message should be Division by Zero, but Access gives back that not very useful error message.
Try with this query text.
Dim cmdText = "SELECT Goals, Mins_Played, " & _
              "iif([Goals] = 0, 0, (([Mins_Played]*1)/[Goals])) AS gpm " & _
              "FROM PlayerDatabase;"

AND if you need and order by, then you should repeat the expression used to build the gpm field
....
"FROM PlayerDatabase " & _
"ORDER BY (iif([Goals] = 0, 0, (([Mins_Played]*1)/[Goals]))) DESC;"

instead if you want to sort your data from code (thus not having the calc for gpm executed two times by the database) you can write
da.Fill(ds, "PlayerDatabase")
ds.Tables("PlayerDatabase").DefaultView.Sort = "gpm DESC"
lbl_Result.Text = ds.Tables("PlayerDatabase").DefaultView(0).Item(2)

Not sure if this is better (performance wise) than having the sort performed by the database engine. This needs to be tested when you have many rows to order.


text:
Q: Amazon EC2 instance won't boot: Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,0) My instance was running for years and suddenly stopped responding Jun 1st. I tried to reboot it, but it would not boot. It gave errors in the system log: https://pastebin.com/rSxr1kLs

Linux version 2.6.32-642.11.1.el6.x86_64 (mockbuild@c1bm.rdu2.centos.org) (gcc version 4.4.7 20120313 (Red Hat 4.4.7-17) (GCC) ) #1 SMP Fri Nov 18 19:25:05 UTC 2016
      Kernel command line: root=/dev/xvde ro  LANG=en_US.UTF-8 KEYTABLE=us
      VFS: Cannot open root device "xvde" or unknown-block(0,0)
      Please append a correct "root=" boot option; here are the available partitions:
      Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,0)

I tried to detach the EBS volume and re-attach it as /dev/sda1 according to the documentation: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstances.html#FilesystemKernel
However, it gave an error Error attaching volume: Invalid value '/dev/sda1' for unixDevice. Attachment point /dev/sda1 is already in use and I was unable to attach it. I re-attached it as /dev/sda but it still won't boot and it still gives the error in the system log.

I was able to launch a new instance into the exact same availability zone and attached my EBS volume as /dev/sdf. It shows up inside the instance as /dev/xvdj. I mounted it with mount /dev/xvdj /xvdj. I can see the grub.conf file:
[root@ip-172-31-4-249 grub]# cat /xvdj/boot/grub/grub.conf
default=0
timeout=1

title CentOS (2.6.32-642.11.1.el6.x86_64)
        root (hd0)
        kernel /boot/vmlinuz-2.6.32-642.11.1.el6.x86_64 root=/dev/xvde ro crashkernel=auto LANG=en_US.UTF-8 KEYTABLE=us
title CentOS (2.6.32-504.30.3.el6.x86_64)
        root (hd0)
        kernel /boot/vmlinuz-2.6.32-504.30.3.el6.x86_64 root=/dev/xvde ro crashkernel=auto LANG=en_US.UTF-8 KEYTABLE=us
        initrd /boot/initramfs-2.6.32-504.30.3.el6.x86_64.img
title CentOS (2.6.32-504.3.3.el6.x86_64)
        root (hd0)
        kernel /boot/vmlinuz-2.6.32-504.3.3.el6.x86_64 root=/dev/xvde ro crashkernel=auto LANG=en_US.UTF-8 KEYTABLE=us
        initrd /boot/initramfs-2.6.32-504.3.3.el6.x86_64.img
title CentOS (2.6.32-504.el6.x86_64)
        root (hd0)
        kernel /boot/vmlinuz-2.6.32-504.el6.x86_64 root=/dev/xvde ro crashkernel=auto LANG=en_US.UTF-8 KEYTABLE=us
        initrd /boot/initramfs-2.6.32-504.el6.x86_64.img
title CentOS (2.6.32-431.29.2.el6.x86_64)
        root (hd0)
        kernel /boot/vmlinuz-2.6.32-431.29.2.el6.x86_64 root=/dev/xvde ro crashkernel=auto LANG=en_US.UTF-8 KEYTABLE=us
        initrd /boot/initramfs-2.6.32-431.29.2.el6.x86_64.img
title CentOS (2.6.32-431.23.3.el6.x86_64)
        root (hd0)
        kernel /boot/vmlinuz-2.6.32-431.23.3.el6.x86_64 root=/dev/xvde ro crashkernel=auto LANG=en_US.UTF-8 KEYTABLE=us
        initrd /boot/initramfs-2.6.32-431.23.3.el6.x86_64.img

This compares to the grub.conf of the running instance:
[root@ip-172-31-4-249 grub]# cat /boot/grub/grub.conf
default=0
timeout=1

title CentOS-6-x86_64-20130527-03 2.6.32-358.6.2.el6.x86_64
        root (hd0)
        kernel /boot/vmlinuz-2.6.32-358.6.2.el6.x86_64 root=/dev/xvde ro
        initrd /boot/initramfs-2.6.32-358.6.2.el6.x86_64.img

Does it matter that it doesn't have initrd line in the first option?
I tried to mount the EBS volume to the new instance with /dev/sda, but it still wouldn't boot with the same error Kernel panic - not syncing: VFS: Unable to mount root fs on unknown-block(0,0).
CentOS 6

A: I created a new instance by going to Images > AMIs > Private Images > Selecting the image the instance was started from > Launch. I launched in exactly the same availability zone, not just US or region, but the 2a, 2b, 2c must match as well. I stopped the new instance. I disconnected the EBS volume from the old instance. I re-attached the EBS volume to the new instance at /dev/sdf. I started the new instance. The EBS volume shows up inside the instance as /dev/xvdj so I mounted it with mkdir /xvdj; mount /dev/xvdj /xvdj. I edited /xvdj/boot/grub/grub.conf and changed default=0 to default=1. I saved the file, stopped the new instance, re-attached the EBS volume to the old instance and it started. I ran yum update in the old instance and double-checked /boot/grub/grub.conf and double-checked that it would reboot.
I also found this regarding updates to CentOS kernel: grub.conf missing initrd path after kernel update
I noticed after I ran yum update I now had 2 entries in grub.conf without initrd. Running # yum reinstall kernel.x86_64 works to fix that.

A: I've had this same issue on several occasions and had to solve it by restoring the instance from EBS snapshot backups. Today I had the same issue and was determined to resolve it without having to restore from backups. I did the following:

*

*Detach the root volume from the failed instance /dev/sda1.

*Attach the volume into a working instance and mount the volume (e.g. mount /dev/xvdh /xvdhmount)

*Back up the boot folder: mv /xvdhmount/boot /xvdhmount/boot-backup

*From a working instance with the same version of OS in my case RHEL 7.4
  copy the entire contents of the /boot folder via SCP or WinScp into
  /xvdhmount/.

*Detach the volume from the working instance and attach back to the failed instance.

*Start the failed instance .... the instance did boot and I am able to
  log in.

I hope this helps!

A: I had a similar problem with a CentOS instance. This AWS support article gives quite a good overview. Here's how I and managed to solve my problem:

*

*Shut down the original EC2 instance and then detach the /dev/sda1 disk

*Start a new, temporary EC2 instance, and attach the disk as /dev/sdp to the new EC2 instance

*SSH into the new EC2 instance and mount /dev/sdp to /data
Then I wanted to go back to a previous kernel. The instructions on the CentOS wiki were helpful:

*

*List all Grub entries with grep "^menuentry" /data/boot/grub2/grub.cfg | cut -d "'" -f2

*Picked the 2nd one from the top, in my case this was CentOS Linux (3.10.0-957.12.1.el7.x86_64) 7 (Core)

*Configure the boot default with grub2-set-default --boot-directory /data/boot/ 'CentOS Linux (3.10.0-957.12.1.el7.x86_64) 7 (Core)'
Then shut down the new EC2 instance, detach the volume, attach it back to the original instance (to /dev/sda1) and boot the initial instance.

A: Me Too!
The underlying cause was an interrupted yum upgrade and a junior staffer doing the work reconnected, and ran yum-complete-transactions to finish everything.
However, something didn't write a file into /boot/initrd....newver....  which was probably related to the latest kernel entry in grub2.cfg missing its initrd=/.... line completely.
The quick fix was to reattach the boot disk volume to a different instance, mount it, and edit /mountpoint/etc/grub2.cfg so that the instance starts up the older version of the kernel.  Then re-disconnect and reattach to /dev/sda1 of the original instance.

NOTE lately its been hard to attach a centos boot volume to a different centos machine, because the UUID is the same on the root volume.  Workaround is to use a different OS as your temp machine, like Debian for CentOS disk fixups.

Once you're in again, run yum reinstall kernel* to repeat the missing steps, and on completion reboot again to be sure it restarts properly this time and onto the newest kernel.

A: It looks to me like your kernel got upgraded in such a way that it doesn't understand your root filesystem anymore.  Your best bet is to create a new node and mount the EBS volume from the old one as a non-root / non boot device, and transfer the critical data over.

A: I came across similar problem, and it turns out, AWS EC2 defaults differ for launching instance vs. creating an AMI: hardware virtualization (HVM) is the default choice in first case, but paravirtual (PV) is the default for image creation.
I stumbled upon this when tried to move EC2 instance between availability zones by snapshotting its EBS volume and creating a new AMI, and this discrepancy in settings (which I did not pay attention too) wasted an hour for me.
tl;dr: just choose HVM when launching from a customized AMI and your instance should boot fine.


text:
Q: Is it valid to define a pure virtual signal in C++/Qt? I am making an abstract-base-class and was thinking I might  want a pure virtual signal. But when I compiled I get a warning for the pure virtual signals I have defined:
../FILE1.h:27: Warning: Signals cannot be declared virtual
../FILE1.h:28: Warning: Signals cannot be declared virtual

Is it valid to define a pure virtual signal in C++/Qt? Is it valid to define a virtual signal?
Qt's signal and slot documentation page says you can define virtual slots but doesn't talk about signals. I can't seem to find good information on pure virtual signals.

A: *

*Signals don't ever have an implementation[1] (i.e. you define the signal in your .h file and then there is no implementation in the .cpp).

*The main purpose of declaring a function pure virtual is to force the inheriting class to provide an implementation.

Given the above two statements here's my thinking:
Signals don't have an implementation but declaring it pure virtual will require the inheriting class to provide an implementation... which directly conflict with "signals don't have an implementation". It's like asking someone to be in two places at once it's just not possible.
So in conclusion it seems like declaring a "pure virtual" "signal" should be an error and thus not valid.

In the case of an abstract base class here's what I think is correct:
When one declares the function only "virtual" it still gives the warning. To avoid any warnings I think the solution is to not qualify the signal with any "virtual" or "pure virtual" and then the inheriting class will not declare any signals but can still emit the signals defined in the base class.
[1] when I say that "signals don't ever have an implementation" I mean that the person implementing the class doesn't provide the implementation. I understand that behind the scene Qt's moc provides an implementation in the moc_FILE1.cpp .

A: The warning is reported by moc, not by the C++ compiler, and it is valid except in the specific case of abstract interfaces.
The only valid use for virtual signals is when declaring abstract interfaces that don't derive from QObject, as detailed in this excellent answer. There's nothing wrong with that approach. Moc tries to be helpful, since in most cases a virtual signal is a mistake.
Even then, the simple workaround for not getting the warning is to skip the signals: keyword in the interface. It is completely unnecessary, since the interface doesn't derive from QObject and thus shouldn't be processed by moc at all:
// https://github.com/KubaO/stackoverflown/tree/master/questions/virtual-slot-10029130
#include <QtCore>

class IDogInterface {
public:
   // no signals: section since it's not a QObject!
   virtual void barks() = 0; // a signal
};

class ADog : public QObject, public IDogInterface {
   Q_OBJECT
public:
   Q_SIGNAL void barks() override; // implementation is generated by moc
};

class Monitor : public QObject {
   Q_OBJECT
   int m_count{};
   Q_SLOT void onBark() { m_count++; }
public:
   int count() const { return m_count; }
   void monitorBarks(IDogInterface * dog) {
      QObject * dogObject = dynamic_cast<QObject*>(dog);
      if (dogObject) {
         connect(dogObject, SIGNAL(barks()), SLOT(onBark()));
      } else {
         qWarning() << "cannot monitor barking on dog instance" << (void*)dog;
      }
   }
};

int main() {
   ADog dog;
   Monitor monitor;
   monitor.monitorBarks(&dog);
   emit dog.barks();
   Q_ASSERT(monitor.count() == 1);
}
#include "main.moc"

A: I think there's simply no point in having (pure) virtual signals. the signals macro provided to Qt simply expands to protected, so all the signals you're declaring are actually declarations of protected methods. The code generated by moc will provide the implementations of those functions.

A: there is a solution to create pure virtual function which will connect given slot to signal or vice versa. e.g.:
class IBaseInterface
{
  public:
    virtual bool connectToSignal1(QObject* pReceiver, const char* pszSlot, bool bConnect) const = 0;
};

class CDerived : public QObject, public IBaseInterface
{
  Q_OBJECT
  public:
    virtual bool connectToSignal1(QObject* pReceiver, const char* pszSlot, bool bConnect) const;
  signals:
    void signal1(const QString& msg);
};

bool CDerived::connectToSignal1(QObject* pReceiver, const char* pszSlot, bool bConnect) const
{
 if(bConnect)
   return connect(this, SIGNAL(signal1(QString)), pReciever, pszSlot);
 return disconnect(this, SIGNAL(signal1(QString)), pReciever, pszSlot);
}

further in clients code one may type:
class CSomeClass : public QObject
{
    Q_OBJECT
protected /*or public, or private*/ slots:
    void someSlot(const QString& msg);
};
void CSomeClass::somefunction()
{
    IBaseInterface* p = new CDerived;
    if (!p->connectToSignal1(this, SLOT(someSlot(QString)), true))
    QMessageBox::warning(this, tr("Warning"), tr("Cannot connect ...."), QMessageBox::Ok);
}

A: Two scenarios where a virtual signal makes sense:

*

*The derived class may want to selectively block the sending of a signal by skipping the base class implementation.

*The derived class may want to use it as an event mechanism and react to the signal before or after sending it to listeners.

Both scenarios can also be handled in other less-OOP ways.


text:
Q: AS3: resize handler stretching image I have an image loader that I am attempting to resize dynamically.
I would like to make sure that the aspect ratio is kept intact so that the image doesn't stretch.
When I reload the image (re-populate it with another image via the loader), there is a resize function that is called.  I would like to know what I might be doing wrong with this portion of the resize code:
var aspect:Number = width / height;
var cAspect:Number = _imageBoundary.width / _imageBoundary.height;

if (aspect <= cAspect)
{
    _ldr.height = _imageBoundary.height;
    _ldr.width = aspect * _ldr.height;
}
else
{
    _ldr.width = _imageBoundary.width;
    _ldr.height = _ldr.width / aspect;
}

_ldr.x = (_imageBoundary.width - _ldr.width) / 2 + _imageBoundary.x;
_ldr.y = (_imageBoundary.height - _ldr.height) / 2 + _imageBoundary.y;

Any thoughts would be greatly appreciated.
I am basing the larger portion of this on bhups's code.
Best

A: I believe the first line should be
var aspect:Number = _ldr.content.width / _ldr.content.height;

A: I think the most easy and reliable way is to use the Image class.
You can see a good example here: http://blog.flexexamples.com/2008/06/28/maintaining-an-images-aspect-ratio-on-an-image-control-in-flex/.
the Image class may get dynamically change in its source field and load the image accordingly.
Hope that helps.


text:
Q: Database query working fine on localhost but not working properly on server My Database query working fine on the localhost but now working on the server. I am using laravel 6.
function fetch_data(Request $request)
{
 if($request->ajax())
 {

  $sort_by = $request->get('sortby');
  $sort_type = $request->get('sorttype');
        $query = $request->get('query');
        $query = str_replace(" ", "%", $query);
  $data = DB::table('fontawesomeicons')
                ->where('id', 'like', '%'.$query.'%')
                ->orWhere('icon_name', 'like', '%'.$query.'%')
                ->orWhere('icon_code', 'like', '%'.$query.'%')
                ->orderBy($sort_by, $sort_type)
                ->paginate(50);
  return view('icons_table_data', compact('data'))->render();
 }
}


text:
Q: How to get value from each column of an sqlite record? My sql should return only one record that contains three columns. Funcioando is properly since I am debugging the code to better understand my problem. I need to get the value of each column to move to a ClienteVO class. But he brings the three columns but the first picks in the second when will the error Can1t read row # 0, col # -1 from CursorWindow
I checked debugging and column names are correct and the record returns.
SQLiteDatabase db = new DB(ctx).getReadableDatabase();

String sql = String.format("select limite,valor,nome from limite " +
            " INNER JOIN cliente ON cliente.id = limite.cliente_id " +
            "where cliente.id=1");

Cursor rs = db.rawQuery( sql, null);
ClienteVO vo = null;

if (rs != null){
    vo = new ClienteVO();
    rs.moveToFirst();

    vo.setLimite(rs.getFloat(rs.getColumnIndex("limite")));
    vo.setValor(rs.getFloat(rs.getColumnIndex("valor")));
    vo.setNome(rs.getString(rs.getColumnIndex("nome")));
}

Then read about researching iterate over the columns. And he traverses three columns normally. I wonder if it's the only way to get these values and what is the best way to get the attributes.
Cursor rs = db.rawQuery( sql, null);
ClienteVO vo = null;

if (rs != null){
    vo = new ClienteVO();
    rs.moveToFirst();

    for (Integer i=0; i <= rs.getColumnNames().length; i++ ){
       //How can I get the values of clean way
    }
}

A:     Cursor rs = db.rawQuery( sql, null);

    ClienteVO vo = null;

    vo = new ClienteVO();
    if (rs.moveToFirst()) {
            vo.setLimite(rs.getFloat(0));
            vo.setValor(rs.getFloat(1));
            vo.setNome(rs.getString(2));
    }

You can write this.
   Cursor rs = db.rawQuery( sql, null);

Above you have sql variable. What does it contain?
Okay, you should use next
if (rs.moveToFirst()) {//}

to check if your cursor has at least one row.


text:
Q: MOBILE SDK PAYPAL direct credit card payments - Outside UK, US I am using phonegap build to make an app. I have integrated a Paypal SDK Plugin but it only accepts credit cards from users in US or UK:
https://developer.paypal.com/docs/integration/direct/rest_api_payment_country_currency_support/#direct-credit-card-payments
Does anyone know when this will be extended to countries outside UK/US like australia?

A: I tried this last year and was on the phone with Paypal for the last two days. They said it is not working and even their card readers coupled with the app only works in the country where the account holder resides. I doubt this will ever be possible (most likely because they lose the control over where and who is making the payments outside these countries). I came across one option which is not ideal. You can use the web service from Paypal. If the payment goes through it will give a different URL than when it doesn't go through.


text:
Q: Audio drift in Premiere (not VFR) I'm getting audio drift in Premiere, and it's not related (or is it?) to VFR. I honestly really dont know where this is coming from, but, oh God, Premiere… Obviously, when I read the file in VLC or any other player, it's fine. But in Premiere…
Here's my media informations :
General
Complete name                            : /Users/petaire/Desktop/LCI-2019-10-16_10-00-00h.mp4
Format                                   : MPEG-4
Format profile                           : Base Media
Codec ID                                 : isom (isom/iso2/avc1/mp41)
File size                                : 831 MiB
Duration                                 : 2h 0mn
Overall bit rate                         : 968 Kbps
Writing application                      : Lavf57.83.100

Video
ID                                       : 1
Format                                   : AVC
Format/Info                              : Advanced Video Codec
Format profile                           : High@L3.1
Format settings                          : CABAC / 4 Ref Frames
Format settings, CABAC                   : Yes
Format settings, ReFrames                : 4 frames
Codec ID                                 : avc1
Codec ID/Info                            : Advanced Video Coding
Duration                                 : 2h 0mn
Bit rate                                 : 832 Kbps
Width                                    : 900 pixels
Height                                   : 720 pixels
Display aspect ratio                     : 16:9
Frame rate mode                          : Constant
Frame rate                               : 25.000 fps
Color space                              : YUV
Chroma subsampling                       : 4:2:0
Bit depth                                : 8 bits
Scan type                                : Progressive
Bits/(Pixel*Frame)                       : 0.051
Stream size                              : 715 MiB (86%)
Writing library                          : x264 core 152 r2854 e9a5903
Encoding settings                        : cabac=1 / ref=1 / deblock=1:0:0 / analyse=0x3:0x113 / me=hex / subme=2 / psy=1 / psy_rd=1.00:0.00 / mixed_ref=0 / me_range=16 / chroma_me=1 / trellis=0 / 8x8dct=1 / cqm=0 / deadzone=21,11 / fast_pskip=1 / chroma_qp_offset=0 / threads=16 / lookahead_threads=5 / sliced_threads=0 / nr=0 / decimate=1 / interlaced=0 / bluray_compat=0 / constrained_intra=0 / bframes=3 / b_pyramid=2 / b_adapt=1 / b_bias=0 / direct=1 / weightb=1 / open_gop=0 / weightp=1 / keyint=250 / keyint_min=25 / scenecut=40 / intra_refresh=0 / rc_lookahead=10 / rc=crf / mbtree=1 / crf=23.0 / qcomp=0.60 / qpmin=0 / qpmax=69 / qpstep=4 / ip_ratio=1.40 / aq=1:1.00
Codec configuration box                  : avcC

Audio
ID                                       : 2
Format                                   : AAC LC
Format/Info                              : Advanced Audio Codec Low Complexity
Codec ID                                 : mp4a-40-2
Duration                                 : 1h 59mn
Bit rate mode                            : Constant
Bit rate                                 : 129 Kbps
Channel(s)                               : 2 channels
Channel layout                           : L R
Sampling rate                            : 48.0 KHz
Frame rate                               : 46.875 fps (1024 SPF)
Compression mode                         : Lossy
Stream size                              : 111 MiB (13%)
Language                                 : French
Default                                  : Yes
Alternate group                          : 1

Premiere…
I think it might be related to this line :
Frame rate                               : 46.875 fps (1024 SPF)

I'm using this line for ffmpeg encoding :
ffmpeg -err_detect ignore_err -i $1 -preset veryfast -strict -2 -c:v libx264 -vf scale=-1:720 -threads $numberOfThreads $2

Do you know how to force SPF to 25FPS (of the SPF equivalent)?


text:
Q: How to extract information from nested arrays with multiple objects?? (AdminReport.Activities.list) Could anyone point me in the correct direction?
I searched plenty... I had no luck with mapping... or "find" nor extracting the data I need.
My code:
function checkMeetCode(meetCode, index, searchDate) {
  var ss=SpreadsheetApp.getActive().getSheetByName('AsistenciaMeet');
  var colB = ss.getRange("D3:D").getValues();
  var filasLlenasLengthB = colB.filter(String).length; //

  var userKey = 'all';
  var applicationName = 'meet';
  var emailAddress = colB[index];
                               Logger.log("Index / Alumno: "+index+" / " + emailAddress);
  var optionalArgs = {
      event_name: "call_ended",
      endTime: searchDate,
      startTime: fechaRestada(searchDate),
      filters: "identifier==" + emailAddress + ",meeting_code==" + meetCode
    };

      var response = AdminReports.Activities.list(userKey, applicationName, optionalArgs)
      Logger.log("RESPONSE: "+response);

      var actividad = response.items;

      if (actividad == null) {
         // do nothing
      }
      else {

        **// HERE IS WHERE I AM TRYING TO FIND / EXTRACT INFORMATION FROM "response"
        // READ BELOW PLEASE.**
      }

}

NEED HELP WITH:
I want to FIND/EXTRACT the intValue of "duration_seconds":
The results from:
Logger.log("RESPONSE: "+response);

RESPONSE: {"kind":"admin#reports#activities","etag":"\"JDMC8884sebSctZ17CIssbQ/IhilrSKVziEhoZ7URUpQ-NrztHY\"","items":[{"events":[{"parameters":[{"name":"video_send_seconds","intValue":"1829"},{"name":"screencast_recv_packet_loss_mean","intValue":"0"},{"name":"identifier_type","value":"email_address"},{"name":"video_send_packet_loss_max","intValue":"0"},{"name":"endpoint_id","value":"meet_android_4154513448557872"},{"name":"video_recv_long_side_median_pixels","intValue":"320"},{"name":"calendar_event_id","value":"44jr4vu3qo75q6bvkknq_20200421T213000Z"},{"name":"video_send_fps_mean","intValue":"29"},{"name":"video_recv_short_side_median_pixels","intValue":"180"},{"name":"network_estimated_download_kbps_mean","intValue":"351"},{"name":"duration_seconds","intValue":"1830"},{"name":"video_send_bitrate_kbps_mean","intValue":"762"},{"name":"network_recv_jitter_msec_max","intValue":"130"},{"name":"ip_address","value":"186.59.21.55"},{"name":"audio_send_seconds","intValue":"1829"},{"name":"screencast_recv_packet_loss_max","intValue":"0"},{"name":"video_recv_seconds","intValue":"1818"},{"name":"network_rtt_msec_mean","intValue":"36"},{"name":"video_send_long_side_median_pixels","intValue":"640"},{"name":"screencast_recv_seconds","intValue":"1829"},{"name":"product_type","value":"meet"},{"name":"video_recv_packet_loss_max","intValue":"0"},{"name":"is_external","boolValue":false}],"name":"call_ended","type":"call"}] ...

A: OK, after roughly 8 hours... I was able to make it work.
var insideParameters = response["items"][0]["events"][0]["parameters"];
Logger.log(insideParameters.length);

for (var i = 30; i<insideParameters.length;i++){ // its always located above i = 30...
  if(insideParameters[i].name === "duration_seconds"){
    var duration = insideParameters[i].intValue;
    Logger.log(duration);
  }
}


text:
Q: How to implement NSLog to trace CGPoint coordinates I'm trying  to find a simple way to call a NSLog to trace myPoint coordinates.
I figured out that I can define a macro like this:
#define NSLogPoint(__P__) NSLog(@"%s x:%f , y:%f", #__P__, __P__.x, __P__.y)

Using # before the parameter it will trace it as is,
so I could have:
 CGPoint myPoint = CGPointMake(3,4);
 NSLogPoint(myPoint);

that will trace:
myPoint x:3.000000 , y:4.000000

is there a better way to do that?

A: To have no decimal places:
#define NSLogPoint(__P__) NSLog(@"%s x:%.0f , y:%.0f", #__P__, __P__.x, __P__.y)

To have two decimal places:
#define NSLogPoint(__P__) NSLog(@"%s x:%.2f , y:%.2f", #__P__, __P__.x, __P__.y)


text:
Q: Ant failing to run handlebars.js I'm running an ant build.xml file that contains this:
<macrodef name="handlebars">
<attribute name="dir" default="" />
<attribute name="outfile" />
<element name="args" optional="true" />
<sequential>
    <exec executable="handlebars"
        dir="@{dir}"
        output="@{outfile}"
        logError="true"
        failonerror="true">
            <args />
    </exec>
</sequential>

and I'm calling it like this:
<handlebars outfile="${dev.dir}/js/templates/hbs.js">
<args>
    <arg value="-f" />
    <arg value="${dev.dir}/js/templates" />
</args>

This, I think, should work, but I'm getting the following error:

D:\build.xml:32: Execute failed: java.io.IOException: Cannot run program "handlebars" (in directory
  "D:\"): CreateProcess error=2, The system cannot find the file specified

I can run handlebars from the command line manually so it should work... I assume it's choking on  I'm doing this on a windows machine and handlebars is installed through node.js which is in my system path... I think I might need to add handlebars to the path, but, I'm not sure how I could do that.

A: Just in case someone else is hunting for this the answer was:
<exec executable="cmd.exe">
 <arg line="/c handlebars templates -f templates/hbs.js" />
</exec>

Needs to be cleaned up a bit, but that's it.


text:
Q: Brew doesn't work after terminal restart I installed brew using various tutorials and docs amd even from official site.
But brew works fine in the terminal tab that I used to install.
Then after I open a new terminal window or oprn a new tab brew is not recognized.
Anyone has any idea.
And I use ZSH


text:
Q: Opposite of Skip method in ObservableCollection I'm currently using the ObservableCollection method Skip to display the next n items in my list when a user presses the Next Button.
Is there a method or a simple to way to do the opposite? That is go backwards in the list?
This is what I'm using at the moment.
myObservableCollectionObject.Skip(5).Take(5);

So this would display items 6 - 10 if I had just seen 1 - 5. When another Button is pressed, I would like to display the previous 5 items (1 - 5).

A: You can keep an index, changed by the Forward/Backward button, increasing/decreasing the index by 5.
Than use that index in Skip(index) to skip the requested items.
int _index = 0;

void OnForwardButton(...)
{
   _index += 5;
}

void OnBackwardButton(...)
{
   _index -= 5;
}

Than use in your statement:
myObservableCollectionObject.Skip(_index).Take(5);

I didn't add safety statements to check the index and to make 5 into a constant.

A: Alternatives:

*

*How to paginate an ObservableCollection? (Paginated ObservableCollection @ CodePlex).

*Paged Collection View in WPF.

Custom ("manual") implementation:
It seems the "original" collection must be stored and "go to previous/next" commands should be implemented as calculating "filtered" collection since there is no way to rewind the "filtered" collection (it does not have previous items).
Use the "filtered" collection to display.

A: Im ny case I've prepared few simple extension methods for my self to protect "page" out of range:
public static int EnsurePageNo(
                        this int page,
                        int pageSize,
                        int totalItems)
{
    if (pageSize < 1)
         throw new ArgumentException("Page size should at least 1.", "pageSize");
    if (page < 1) return 1;

    return page > totalItems / pageSize
                ? totalItems / pageSize + 1;
                : page;
}

public static IEnumerable<T> Page<T>(
                this IEnumerable<T> source,
                int page,
                int pageSize)
{
    var toSkip = pageSize * page;
    var take = pageSize;

    return source.Skip(toSkip).Take(take);
}

public static IEnumerable<T> SafePage<T>(
                  this IEnumerable<T> source,
                  int page,
                  int? pageSize,
                  int totalItems)
{
    // no paging
    if (!pageSize.HasValue) return source;

    if (page < 1)
        throw new ArgumentException("Page number should be greater or equal 1.");

    var pgSize = pageSize.Value;
    page = page.EnsurePageNo(pgSize, totalItems);
    return source.Page(page - 1, pgSize);
}

Usage:
var totalCount = myObservableCollectionObject.Count();
var result = myObservableCollectionObject.SafePage(page, pageSize, totalCount);

Maybe it is too much for simple  paging, but it is reusable and I don't need to remember math expressions.


text:
Q: Enum field in JPA Entity I feel a little dumb asking this but I can't find any simple answer to the question.
Take this simple entity as example:
@Entity
@Table( name="clienti" )
public class Cliente implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    private String nome;

    private String cognome;

//...
}

It represents a person, so I want to add a "gender" property.
It will be "male" or "female". So what?
I can use a String, and keep in mind that "m" stands for male and "f" for female.
Or I can use a boolean "isMale", true or false.
However, I don't think in either case Hibernate purists would be happy :)
Googling a little bit I found that the best practice is using an enum.
I am a little confused on how to use it. Can you help me with an example?

A: public enum Gender{
    MALE, FEMALE
}

@Entity
@Table( name="clienti" )
public class Cliente implements Serializable {
...

// **1 case** - If database column type is number (integer)
// (some time for better search performance)  -> we should use
// EnumType.ORDINAL as @O.Badr noticed. e.g. inserted number will
// index of constant starting from 0... in our example for MALE - 0, FEMALE - 1.
// **Possible issue (advice)**: you have to add the new values at the end of
// your enum, in order to keep the ordinal correct for future values.

@Enumerated(EnumType.ORDINAL)
    private Gender gender;

// **2 case** - If database column type is character (varchar)
// and you want to save it as String constant then ->

@Enumerated(EnumType.STRING)
    private Gender gender;

...
}

// in all case on code level you will interact with defined
// type of Enum constant but in Database level

first case (EnumType.ORDINAL)
╔════╦══════════════╦════════╗
║ ID ║    NAME      ║ GENDER ║
╠════╬══════════════╬════════╣
║  1 ║ Jeff Atwood  ║    0   ║
║  2 ║ Geoff Dalgas ║    0   ║
║  3 ║Jarrod Jesica ║    1   ║
║  4 ║ Joel Lucy    ║    1   ║
╚════╩══════════════╩════════╝

second case (EnumType.STRING)
╔════╦══════════════╦════════╗
║ ID ║    NAME      ║ GENDER ║
╠════╬══════════════╬════════╣
║  1 ║ Jeff Atwood  ║  MALE  ║
║  2 ║ Geoff Dalgas ║  MALE  ║
║  3 ║Jarrod Jesica ║ FEMALE ║
║  4 ║ Joel Lucy    ║ FEMALE ║
╚════╩══════════════╩════════╝

A: You can map your enum to a String or to an ordinal number. Mapping to String is the more portable approach as the mapping will survive changing the enumeration order.
Using your example:
@Entity
@Table( name="clienti" )
public class Cliente implements Serializable {

...
    @Enumerated(EnumType.STRING)
    private Gender gender;
...
}

The string mapping will use the simple name of the enumeration type, so you would have two possible values in the DB - 'Male' and 'Female'
public enum Gender { MALE, FEMALE }

The persistence provider takes care of the mapping, so in your code, you can continue using the Gender enum and not worry about Strings or ordinals.


text:
Q: search function not working in my PHP MySQL query I have this mysql query using PHP and first part is working fine, but second part where have search function on site simply cannot get it workable to search properly.
Here is exact code:
<?
$qry = "
SELECT bidprice,timelive,match_title,
CASE
WHEN game.result LIKE '' THEN 'PENDING'
WHEN game.result LIKE 1 THEN 'WON'
END AS result
FROM game
ORDER BY timelive DESC
";
$searchText = "";
if($_REQUEST['search_text']!=""){
    $searchText = $_REQUEST['search_text'];
$qry .=" WHERE game.bidprice LIKE '%$searchText%' OR game.timelive LIKE '%$searchText%'";
}

//for pagination
$starting=0;
$recpage = 10;//number of records per page

$obj = new pagination_class($qry,$starting,$recpage);
$result = $obj->result;

?>

So this part of code from above code which is considering searching my 'game' table is not working:
$searchText = "";
if($_REQUEST['search_text']!=""){
    $searchText = $_REQUEST['search_text'];
$qry .=" WHERE game.bidprice LIKE '%$searchText%' OR game.timelive LIKE '%$searchText%'";

On my page I receive this error when open this page and try to search for word 'football':
You have an error in your SQL syntax; check the manual that corresponds to your MySQL    server version for the right syntax to use near 'game.bidprice like   '%football%' OR game.timelive like   '%football%' at line 9

This search function is working fine when put some simple SELECT statement something like:
SELECT * FROM game
but when done those more complex select query with CASE and WHEN statements which i need its not functioning...
Please help me with proper code for proper search function

A: The problem is that you can't have a WHERE clause after the ORDER BY. Your query currently looks like this:
SELECT bidprice,timelive,match_title,
CASE
WHEN game.result LIKE '' THEN 'PENDING'
WHEN game.result LIKE 1 THEN 'WON'
END AS finalization
FROM game
ORDER BY timelive DESC WHERE game.bidprice LIKE '%football%' OR game.timelive LIKE '%football%'
                      ^^^^^^^ error

But you need it to look like this:
SELECT
    bidprice,
    timelive,
    match_title,
    CASE
        WHEN game.result LIKE '' THEN 'PENDING'
        WHEN game.result LIKE 1 THEN 'WON'
    END AS finalization
FROM game
WHERE game.bidprice LIKE '%football%' OR game.timelive LIKE '%football%'
ORDER BY timelive DESC

You should add the ORDER BY afterwards in your PHP script. Try something like this:
$qry = "
SELECT bidprice,timelive,match_title,
CASE
WHEN game.result LIKE '' THEN 'PENDING'
WHEN game.result LIKE 1 THEN 'WON'
END AS result
FROM game
";

$searchText = "";
if ($_REQUEST['search_text']!="")
{
    $searchText = mysql_real_escape_string($_REQUEST['search_text']);
    $qry .= " WHERE game.bidprice LIKE '%$searchText%' " .
            " OR game.timelive LIKE '%$searchText%'";
}

$qry .= " ORDER BY timelive DESC";

A: You have several errors.
First: You're putting the WHERE after the ORDER BY.
Second: Using just $searchText = $_REQUEST['search_text']; you can receive an sql injection.


text:
Q: write game via php I new in php and i interested  at games like a poker.
I think when started new game,there must be created new  thread.
But I read that php does not support multithreading.
Can you advise what i must to do for support multithreading .
Thank`s

A: You don't need multithreading to write a game, especially not one like Poker which operates in distinct sequential steps.
Start small and worry about advanced topics like multithreading once you have worked out how to write a basic poker game.

A: Multithreading is only useful for splitting tasks in one single instance of a game or whatever php app into separated threads. Depending on your server's configuration a new apache / php thread is started whenever one starts the game. You don't have to implement this by yourself - every user get's his own script instance automatically.
For writing your own browser game you won't have to implement multithreading as long as the calculations won't get too time expensive.
As Jason already stated, just start small and worry about advanced topics later.

A: seems you did not understand what php is all about: php is a server side scripting language that will (in general) perform some server side actions and produce some (textual) output which is then sent back to the client - usually an html file.
thing is - the php script starts running once the webserver receives the POST or GET message from the client. when the response is sent to the client, the script stops. yes: it dies!
so there is no sense in opening a thread or so if a new game is started - since this thread (if threading would be possible in php) would die with the script.
the approach of keeping "persistent" data (if that is what you meant with threading) is somehow different with php/html/...: you start "sessions", where each client has a unique session assigned. sessions will store variables for your users and can be "repeated" after the php-script starts again...
try searching for
session_start();

and the php global
$_SESSION


text:
Q: Keychain always asks for password I am not on a network but my IT person at work set up my MacBook Pro for me to take home.
Nearly every time I try to make a move between apps or open up anything new I am asked to give a password for the Keychain. I have spoken to others in my group who use Macs at home and they think I am nuts.
What is the purpose of that? How can I disable Keychain asking me all the time?

A: I also had this problem.  I solved it by changing the 'settings for keychain 'login'. It was set to prompt after 5 minutes or upon screenlock...

A: You will have to set the password for the login-Keychain to the same password you use to log into the mac. Then on logging in the keychain will automatically be unlocked and you will not need to unlock the keychain everytime an application wants to read an entry from it.
To do so

*

*Open up /Applications/Utilities/KeychainAccess (I'm doing this out of the head, so please excuse translation issues or slight inaccuracies)

*Go to the Menu-Item Edit and select Change password for keychain 'login'.

You will have to give the current password and then the login-password for the mac.
Hope that helps.


text:
Q: LibGdx app Generate Signed APK got error I made a libgdx app and trying to build with Android studio and Proguard. The problem is that I can run it well in debug mode. But when I generate APK file, run it, it has this error :
Error reading file: ui/uiskin.json
            at com.badlogic.gdx.utils.Json.a(Unknown Source)
            at com.badlogic.gdx.scenes.scene2d.ui.Skin.a(Unknown Source)
            at com.badlogic.gdx.scenes.scene2d.ui.Skin.<init>(Unknown Source)
            at jangkoo.a.a.a.a(Unknown Source)
            at jangkoo.a.e.af.a(Unknown Source)
            at com.badlogic.gdx.backends.android.AndroidGraphics.onSurfaceChanged(Unknown Source)
            at android.opengl.GLSurfaceView$GLThread.guardedRun(GLSurfaceView.java:1520)
            at android.opengl.GLSurfaceView$GLThread.run(GLSurfaceView.java:1248)
     Caused by: com.badlogic.gdx.utils.SerializationException: Field not found: down (com.badlogic.gdx.scenes.scene2d.ui.Button$ButtonStyle)

Clearly the last line says Field not found: down in json file.
What's wrong? what should I do?


text:
Q: Pass JSON array to function in React as props and then count items in area Apologies.  Newbie here having problems with passing a JSON object into a function as props.  I'm obviously doing something wrong but I've searched and other people's posts seem more complex than mine.
I want to pass an array which may have zero or more rows into a function and then I want to count how many rows there are.  Finally I would return a string depending on that.  I've got the last part working but I can't pass the array without getting undefined.
App.js
const sampleTeams = [
  {
    team: "Jets",
    season: "2022/23",
    regfee: 35,
    feepaid: true,
  },
];

function App() {
  return (
    <Container className="my-4">
    <MemberCard
      forename="Bob"
      surname="Jones"
      playerNumber="154"
      registrations={sampleTeams}
    ></MemberCard>
    </Container>
  );
}

MemberCard.js
export default function MemberCard({
  forename,
  surname,
  memberNumber,
  registrations,
}) {
  return (
    <Card>
      <Card.Body>
        <Card.Title className="d-flex justify-content-between slign-items-baseline fw-normal mb-3">

            {forename} {surname}

            {memberNumber}

        </Card.Title>

{getNumberOfTeams({ registrations })} registered

        <Stack direction="horizontal" gap="2" className="mt-4">
          <Button variant="outline-primary" className="ms-auto">
            Register Team
          </Button>
        </Stack>
      </Card.Body>
    </Card>
  );
}

function getNumberOfTeams(registrations) {
  const numberOfTeams = registrations.length;
  // console.log(numberOfTeams);
  if (numberOfTeams === 1) return "1 team";
  return numberOfTeams + " teams";
}

A: In your example code, there is the object shorthand in the argument of the call to getNumberOfTeams
getNumberOfTeams({ registrations })

The function getNumberOfTeams(registrations) attempts to read registrations.length, but you passed it an object { registrations: registrations }. Object.length will always be undefined. Your code should work more correctly if you change it to

{getNumberOfTeams(registrations)} registered


text:
Q: How to set Solid label in bar chart using Chart JS How to set label like amount format (10,000) in bar chart using chat js (Without tooltip)

A: One way is to do it is showing label without necessarily having 'mouseover'. This can be done with options onAnimationComplete and tooltipevents.
Just pass empty array to tooltips, like below:
var options = {
  tooltipTemplate: "<%= value %>",

  showTooltips: true,

  onAnimationComplete: function() {
    this.showTooltip(this.datasets[0].points, true);
  },
  tooltipEvents: []
}

I hope this at least gives you an idea to proceed.


text:
Q: Python - Removing vertical bar lines from histogram I'm wanting to remove the vertical bar outlines from my histogram plot, but preserving the "etching" of the histogram, if that makes since.
import matplotlib.pyplot as plt
import numpy as np

bins = 35

fig = plt.figure(figsize=(7,6))
ax = fig.add_subplot(111)

ax.hist(subVel_Hydro1, bins=bins, facecolor='none',
        edgecolor='black', label = 'Pecuiliar Vel')
ax.set_xlabel('$v_{_{B|A}} $ [$km\ s^{-1}$]', fontsize = 16)
ax.set_ylabel(r'$P\ (r_{_{B|A}} )$', fontsize = 16)
ax.legend(frameon=False)

Giving

Is this doable in matplotlibs histogram functionality? I hope I provided enough clarity.

A: In pyplot.hist() you could set the value of histtype = 'step'. Example code:
import matplotlib as mpl
import matplotlib.pyplot as plt
import numpy as np

x = np.random.normal(0,1,size=1000)

fig = plt.figure()
ax = fig.add_subplot(111)

ax.hist(x, bins=50, histtype = 'step', fill = None)

plt.show()

Sample output:


text:
Q: Passing values between expression engine templates Any idea about How can I pass hidden values between 2 expression engine templates?
I don't want to use PHP code, is there any plugin or module?
Thanks

A: Highly recommend using Session Variables.
On your first page:
{exp:session_variables:set name="talking" value="nonsense"}

On your second page:
{exp:session_variables:get name="talking"}

Then you can always delete it afterwards:
{exp:session_variables:delete name="talking"}

If you want to deal with POST variables and set it on the first page via a form submission, then you can get it easily with Mo' Variables:
{post:talking}

A: What you may be looking for is an add-on called Stash .  I think that would do exactly what you need!