text:
Q: PHP Class modeling issue I've written a few classes and have come to a fork in the road about what I should do. My base question is, how do I avoid duplicating my code across classes with very similar functionality? Traits are not an option for me right now, and I don't think they would help too much here anyway.
I have the following classes implemented.

    //either a directory or a file on the file system
    class FileSystem_Object{
        //the size of the class in bytes
        public function getSize(){}

        //same as phps native realpath
        public function getRealPath(){}
    }

    //a zip file on the file system, e.g. files that end in .zip extension.
    class FileSystem_Object_Zip extends FileSystem_Object{
        //returns size of all files if they were to be uncompressed, in bytes
        public function getUncompressedSize(){}
    }

    //a singleton file that keeps track of only one object copy of a file
    class FileSystem_Manager{}

These classes sortof provide me with some SPLFileObject type functionality. I can do the following kind of stuff

    $object =
        FileSystem_Manager::getInstance()
        ->getFileSystemObjecT( '/some/path/to/file/or/directory/' );

Every time I call the getFileSystemObject method it will either return a new class object or return an object that was assigned to that path already, thus avoiding me creating multiple objects that point to the same path on the filesystem. ( maybe not the best idea but that's what I went with. )
Here's where we get to the issue a bit.
I have another set of classes that I use to 'lock' objects. Right now the only objects that I'm locking are filesystem_objects, regardless of whether they're directories or files. This works simply enough by creating a lock file for the file based on the process id of the php process trying to lock it.

    inteface Lockable_Object{

        public functon getLockableIdentifier();
    }

    class Lockable_FileSystemObject implements Lockable_Object{

        /**
         * I return a false here if the file doesn't exist
         * so any other processes trying to lock this file will
         * know they can no longer lock it because it has moved
         * or been renamed for some reason.
         */

        public functon getLockableIdentifier(){
            if( file_exists( $this->_fullFilePath ) ){
                return $this->getRealPath();
            }
            return false;
        }
    }

The problem I face now is that I'd like to create a Zip file object that can be locked as well, and I'd like to be able to lock pretty much any file/directory but I DON'T want to have to duplicate code. Which of the following should I do

    //Option 1
    class Lockable_Object_Zip extends FileSystem_Object_Zip
                              implements Lockable_Object{
        //In here I would have to duplicate the getLockableIdentifier method and do that
        //for every file type i decide to make in the future
    }

    //Option 2
    class Lockable_Object_Zip extends Lockable_FileSystemObject
        //In here I would have to duplicate all the zip functionality coded into
        //FileSystem_Object_Zip
    }

    //Option 3
    class FileSystem_Object implements Lockable_Object{
         //build in the 'lockablity' into the base class
    }

Right now I'm leaning towards option 3 but the only reason I would not like to do that is because then I would HAVE to have the 'Locker' part of my library whenever I want to use the file system stuff; it would be more tightly coupled.
I'm sure you'll have comments about the design and some will say "SplFileObject does all/most of this". I've included methods in here for examples and not all the methods I implemented are here so this isn't the only functionality I've written. All these comments and more are welcome, however, because they might land me on a design that will avoid this whole issue.
Thank you

A: I think you should look into the Strategy pattern. Consider using composition of a Lockability strategy rather than trying to inherit it.

A: In case the type of the locked classes doesn't matter, you could go with a Decorator pattern, e.g.
class Lockable
{
    protected $lockable;

    public function __construct($lockable)
    {
        $this->lockable = $lockable;
    }

    public function lock()
    {
        // .. your code to lock $this->lockable
    }

    public function __call($method, $args)
    {
        return call_user_func_array(array($this->lockable, $method), $args);
    }
}

This way you are not duplicating logic. The drawback is that you cannot use the decorated instance in methods requiring the decorated type (unless you add appropriate interfaces and delegate all calls).
The Strategy pattern would be another option:
class LockingStrategy
{
    public function lock($fileSystemObject)
    {
        // your code to lock $fileSystemObject
    }
}

class ZipFile
…
    public function __construct(LockingStrategy $strategy)
    {
        $this->lockingStrategy = $strategy;
    }
    public function lock()
    {
        $this->lockingStrategy->lock($this);
    }
}


text:
Q: Converting a TeX document to SE markdown? Portions of my masters thesis work, which was never published officially, could be pretty easily adapted to a very comprehensively answer to a question on Programmers about Particle Swarm Optimization.
However, I foolishly wisely1 chose to write it in LaTeX which means I cannot just copy/paste it into the "Answer" text box there, at least (I could copy... the entire document I guess and tell people to use TeX to read it?).
The main concerns I have relate to the mathematical notation and references. Text/headings could be pretty straightforward to modify into markdown syntax.
Something like:
\begin{align*}  \labeltarget{eq:opproblem}
    &\operatorname{Minimize}& & F_p(\bar{x})  \quad & &p=1,\dots,l & &\text{\nameref{sec:objectivefunction}}\\
    &\operatorname{Subject\;To} & &g_j(\bar{x}) \leq 0, \quad & &j= 1,\dots,m & &\text{\nameref{sec:inequalityconstraints}} \\
    &&&h_k(\bar{x}) = 0, \quad & &k= 1, \dots,p  & &\text{\nameref{sec:equalityconstraints}} \\
    &&&x_{low,i} \le x_{i} \le x_{up,i}, \quad & &i = 1, \dots,n  & &\text{\nameref{sec:sideconstraints}}
\end{align*}

Would be great to auto convert via [insert magical process I don't know]. I could take screenshots of them, I guess...
There are also a lot of pieces like:
    \noindent with $\bar{x}$ representing  \hyperref[sec:designvariables]{design variables} for the optimization problem \cite{vanderplaats}.

Which would be.. tedious at best to go through and change.
Is there any straightforward way to minimize the tediousness of converting a TeX document to SE markdown syntax?

1: My advisor also required a Word document during the process (???) and the amount of times I've tried to convert from TeX is making me sick. Fortunately it's more fun than going backwards!

redpajama_set_name: RedPajamaStackExchange


text:
Q: prevent resizing with option key Hardware: Macbook Pro 2017 (15")
OS: MacBook Mojave 10.14.6
While using iTerm, I noticed, I could not use alt/option commands with direction keys as I would on my Macbook Pro 2015. This prevents me from navigating around certain CLI utilities. Instead, my iTerm window gets resized as shown below using option+left and option+right. I noticed this is how all application windows behave and not just iTerm. How may I stop this behavior?
Aside: Another weird thing I've noticed on this newer macbook is that cmd + left and cmd + right do not work as Home and End buttons anymore. I now have to use ctrl + a and ctrl + e.

A: Since this is not standard macOS functionality, neither default nor optional, this is either functionality added by you (or someone acting as administrator) or a third-party app.
You can check what third-party apps have system-wide access to window manipulation in System Preferences → Security & Privacy → Privacy → Accessibility. One by one, try disabling suspect apps and attempting the shortcut again.
When you've narrowed down the specific app, you can either disable the app or research the possibility of changing/disabling the offending shortcut.


text:
Q: For storing answer in array and changing color of button This code should change the button color when answer gets saved in database but it is not saving. Kindly help am a beginner.
<?php
       $qpquery="SELECT COUNT(id) AS total FROM question WHERE FMid=$tid";
         $qprs=mysqli_query($conn,$qpquery) or  die("database error:". mysqli_error($conn));
         if ($qprs->num_rows > 0) {
             while($qpro = $qprs->fetch_assoc()) {
         $total=$qpro["total"];
         }
             echo $total;
         }
     for ($j = 1 ; $j <= $total; $j++)
         {
?>

<?php  echo $_SESSION['mark_ques'][$j];
     foreach($_SESSION['mark_ques'] as $storeanswer){
         $flag = 0;
         if ($storeanswer == $j){
             $flag = 1;
             break;
         }
     }
        if($flag == 1){?>

  <button type="button" class="button button5" style="background-color:Green;">
  <?php echo $j ; ?> </ton>

Link for the code-https://drive.google.com/file/d/108XgWQFwCqJz3y58g9SN1nu6NfbbjLKG/view?usp=sharing?

A: i suggest you to try it with javascrpit , try this :
  <button id="MyButton" type="button" class="button button5">

    <?php

        if($flag == 1){?>
            <script>
                document.getElementById("MyButton").style.background = "green";
            </script>
        <?php } ?>


text:
Q: Selecting data from one table via categoryID field and displaying in different areas whilst excluding categoryID for one area I have made a very simple CMS for the company I work for. We need to display articles on our index page as well as headlines above in a carousel.
All articles are setup with a table for articles and art_categories table to link articles to their respective categories. I have been able to create a query that selects all articles and that exclude the headlines like below.
SELECT SQL_CALC_FOUND_ROWS articles.*, art_categories.*
FROM articles, art_categories
WHERE articles.categoryID=art_categories.categoryID AND articles.categoryID NOT IN(8) AND art_categories.categoryID NOT IN (8)
ORDER BY publishdate DESC LIMIT {$start},5

{$start} is used for pagination. The above query functions 100% and excludes the headlines category from the general article display area.
Now the problem I have is not being able to display the headlines on the same page by selecting them from the same table via their respective categoryID
SELECT articles.*, art_categories.*
FROM articles, art_categories
WHERE articles.categoryID=art_categories.categoryID AND articles.categoryID=8 AND art_categories.categoryID=8
ORDER BY publishdate DESC LIMIT 5

Any advice would be greatly appreciated.
Thanks the issue has been resolved and question is closed

A: You can use LEFT JOIN for this:
SELECT
     articles.*,
     art_categories.*
FROM art_categories LEFT JOIN articles
ON articles.categoryID=art_categories.categoryID
WHERE art_categories.categoryID=8
ORDER BY publishdate DESC LIMIT 5

as advice - avoid use *, better to list all columns by name, it also allow avoid duplicates and/or arrange aliases for them


text:
Q: Hide extras with Javascript in Photoshop Is there any way to hide extras (specifically the selection/marching ants) using Javascript in photoshop? I have an action that I frequently use to make a selection, and inevitably always follow it up with Cmd + H to hide the selection. Curious if there's a way with a script I could reduce three keystrokes to just one. I've spent a while googling and it seems like it might not be possible, but I also didn't find anyone asking this specific question.
Thanks in advance!

A: As far as I am aware there is no way either via scriptlistener or JavaScript to do that.
// this is pseudo code
activeDocument.selection.selectAll().show(false);
// this doesn't work

There are few things that are beyond the scope of Photoshop scripting and that is (sadly) show extras is one of them. But by all means prove me wrong.

A: Toggling Extras (Cmd + H) can be scripted the following way:
app.runMenuItem (app.stringIDToTypeID ("toggleShowExtras"));

If you prefer to include this step in an action you're currently recording, don't directly select the View > Extra command, but use "Insert Menu Item..." from the contextual menu located at the upper right of the Actions palette/panel, then select the command while the dialog is displayed and click OK.


text:
Q: Why $f(x) = x^2$ has variable derivative but its tangent has constant slope? I'm taking Brilliant.org's calculus course, and I'm on the section called The Derivative.
My (mis)understanding:
A tangent line is a linear function that grazes a point, $a$, on the graph of a different function. The slope of that tangent line is the instantaneous rate of change at $a$. The way you find this is by taking the difference ratio, giving you the slope, and plugging in equal values for the input points. So, for the function $f(x) = x^2$, the slope would be:
$$\require{cancel} \frac{b^2 - a^2}{b-a} = \frac{\cancel{(b-a)}(b+a)}{\cancel{b-a}} = b+a$$
Now, considering the case as the difference between $b$ and $a$ gets smaller, or equivalently, as the secant line's two points become one and the same point, thus turning it to a tangent line:
$$\lim_{b \rightarrow a} b +a = 2b = 2a$$
Thus, the derivative of the square function is found, $f'(x) = 2x$. The slope of the tangent is $2x$, but apparently, the derivative isn't the slope of the tangent, it is only so the other way around (see this Math.SE answer). I could define any number of functions of the form $g(x) = ax$, which would be tangent to or intersect the function $f(x)=x^2$, when $x=a$. For any of these functions, $g'(x) = a$, as per the difference ratio. The slopes of these functions would be any arbitrary number $a$, not $2x$. So, it seems we're dealing with the slope of one particular tangent. However, I can't see how this tangent line is linear. If it is linear, its slope is a constant, but $2x$ contains a variable.
All of this leads me to think that we're talking about the tangent line in a very different sense than the one of "a linear line that grazes the function's graph". But I've only been made familiar with the latter sense, and this mysterious sense is very ill-defined in my head. What is it and what does it have to do with tangent lines? The trick with morphing a secant line into a tangent line doesn't really explain this, because one can do that anywhere on the graph and wind up with tangent lines that have differing slopes, none of which are equal to $2x$.

A: $f'(x)$ represents the slope of a tangent line of a function $f(x)$ at a particular point $x$.  Regarded as its own function of $x$, $f'(x)$ need not be constant or linear, i.e. the slope of the tangent line can vary nonlinearly in $x$.

A: It looks like you're misinterpreting what the derivative is. I'll explain this the way I would have if I was teaching calculus this year.
When we have functions, we may sometimes wish to see how the dependent variable changes. This change can be approximated by secant lines, but we may want to know how quickly a quantity changes at a single point. Think about looking at a speedometer at one moment in time.
Suppose $f(x)$ is a function we wish to look at. We can examine small changes in $f$ by taking a point nearby, say $x_0$. You've done this above for the particular function $f(x) = x^2.$ The slope of the line joining $(x, x^2)$ and $(x_0, {x_0}^2)$ is
$$ m = \frac{x^2-{x_0}^2}{x - x_0}$$
which approaches $2x_0$ as $x \to x_0$. This is limit, a fundamental concept you must examine before beginning differentiation.
The derivative is the slope of the tangent line, and itself may not be a linear function. Consider the classic example - let $g(x) = e^x,$ and so $g'(x) = e^x$. Certainly the slope function is nonlinear, but that doesn't matter. The derivative $g'$ gives us how quickly the function changes at a specific point.
I commonly refer to the derivative as the "slope function," since it tells us slope at a particular point. The tangent line is a line, yes, but its slope is determined by the derivative at a point.

A: For any point
$(a, a^2)$
on $y=x^2$,
the slope there is $2a$
so the equation of the tangent there is
$\dfrac{y-a^2}{x-a}=2a
$
or
$y
=a^2+2a(x-a)
=2ax-a^2
$.
Note that at $x=a$
we have $y=a^2$.

A: I agree that $f(x) = x^2$ has a lot of tangent lines.  In fact, for each point on its graph, there is a tangent line.  Let's plot a few of them

and then pick one out.

The one that is picked out is "the tangent to $f(x) = x^2$ at $x = 3/2$".
There are several ways to express an equation of a line.  One way is point-slope form,
$$  y - y_0 = m(x - x_0)  \text{,}  $$
where $(x_0,y_0)$ is a point on the line and $m$ is the slope of the line.  Point-slope form is convenient for tangent lines because we can use the function to get a point on the graph and the derivative to get the slope of the line tangent to that point of the graph.
For the one tangent line picked out above, $x = 3/2$.  We can quickly compute \begin{align*}
f(3/2) &= (3/2)^2 = 9/4  \\
f'(3/2) &= 2(3/2) = 3  \text{.}
\end{align*}
So an equation of that line is
$$  y - 9/4 = 3(x - 3/2)  \text{.}  $$
(Rearranging to slope-intercept form, which may be more familiar, we have $y = 3x - 9/4$.  The slope is $3$ any way we write it, but it is easy to see that the line meets the $y$-axis in the lower half-plane.)
So, what can we do?  For any choice of $x$, we can use the function to get a point on the graph and use the derivative of that function to get the slope of the tangent line to the graph at that point.  The first graph (reproduced here)

has the graph of $y = f(x)$ in blue.  Pick one of the green lines: it meets the blue curve at one point and is parallel to the curve at that point.  Each green line is a line, none of these are not lines.  Two things change as we pick different points on the graph: the coordinates of the point and the slope of the line through that point.  This means that the derivative has to be a function: for each point on the graph, we need a slope of the line tangent to that point.  The function you obtained was $f'(x) = 2x$.  And we can see this: for the green lines tangent to the left half of the curve, the slopes are negative because when $x$ is negative, so is $2x$.  On the right half, the slopes are positive.  Near $x =0$, $x$ is small, $2x$ is small, and the slopes are near zero (meaning close to horizontal).  As we run off to the left or right (allowing $x$ to have large magnitude) the slopes become steeper in both directions.
So, yes, the derivative is a function -- it has to be able to tell you about different slopes of lines at different points on the graph of the function.  If you draw all the tangent lines, you get a lot of tangent lines.
It is a coincidence that each tangent line in the above graphs meet the graph of $f$ exactly once.  (Blah blah, convex region, blah blah... not what we're here to talk about.)  A more general example is this: \begin{align*}
f(x) &= x^3 - x  \\
f'(x) &= 3x^2 - 1
\end{align*}
picking $x = 1/2$, \begin{align*}
f(1/2) &= (1/2)^3 - (1/2) = -3/8 \\
f'(1/2) &= 3(1/2)^2 - 1 = -1/4
\end{align*}
So we expect to see a line through $(1/2,-3/8)$ with slope $-1/4$ that is tangent to the curve at that point.

It also happens that the line meets the curve somewhere else.  This is not "important".  The required properties are "intersects the graph at the point with the $x$-coordinate we picked, $1/2$" and "is tangent to the graph at that point".  That this line also meets the graph again somewhere else is just what happens when you graph the line having those two properties.

A: I think I understand now. All of your answers and comments helped in this process, as well as the work I did before this; however, I think you all missed the point of confusion I had. I don't blame you for that, because I think I partly missed the point of confusion myself. I now see it, and wish to show it so that someone in a similar predicament might have their confusion resolved.
The main issue
I was conflating the function of the tangent line with the tangent line's slope. This is made evident when I said I didn't understand how $2x$ could be the slope of every tangent line grazing $x$ on the curve $f(x) = x^2$, since $2x\neq 3^2$ as an example. However, the tangent line's function, $t(x) \neq 2x$; this is instead true for it's slope, $t'(x) = 2x$. This was obvious, probably too obvious for you guys to spot as my issue, but it slipped past me and caused all this confusion. Thanks for the help.


text:
Q: ¿Como puedo poner el value de un input desde javascript? mi intencion es crear un radio button desde javascript al momento de apretar el botón, pero no puedo ponerle un valor de texto para que salga al lado del radio button, tengo entendido que modificando el value del boton solucionara el problema pero no se como hacerlo desde Javascript.

<button onclick="pregunta2();">Pregunta  V/F</button>

A: Creo que a lo que te estás refiriendo es el label del radio button. El value es el valor que va a devolver el campo del radio al hacer el submit. La estructura correcta del Radio button seria esto:

  <input type="radio" value="verdadero">
  Huey

Por lo tanto en tu código deberías crear el label con la propiedad for con el mismo valor que el value.
Espero haberte ayudado.


text:
Q: some programs not working after system restore so after I did windows updates after a long time (it's for a good reason that I am not updating!) the notebook (Windows 8) failed to start correctly. After the windows loading screen, only different tones of black were flashing - probably bad graphics driver.
Anyway, I managed to do a system restore. Although it said it wasn't successful, it works.
But now some programs won't start. From Adobe, AfterEffects starts without problems, but Photoshop and Illustrator has an error:

Microsoft Office won't open as well:

When I try to uninstall Office completely, the set-up window doesn't even come up. And what's worse... when I run a new installation from a disk, there's an error too.

I've never come across something like this.. I don't know what to do.
//Edit:
So I managed to uninstall Office through a 3rd party software.. but I still have trouble installing it back (a different error now). I run as administrator and have full user rights on the folder..

A: Seems like you restored your system to a restore point which was created prior to the installation of MS Office and Adobe products. As soon as you restored your system to that particular point, it deleted these programs, possibly. If that's the case, you unfortunately have to re-install these programs.
Generally, Windows 8 creates a restore point for you automatically during Windows Updates and other system maintenance events. If you noticed, there is an option of Scan for affected programs that allows to check which programs may be affected by the operation before changes are applied to your system. Did you click on that?


text:
Q: lua - return value if string match with wildcard I have never worked with lua before and am having a hard time trying to figure out how to return a value based on a string match with wildcard...thank you in advance for any help.
here is the script ive been tasked with modifying.   The last bit where I'm looking for Bob* is where I'm stuck.
if score < 3000 then
return 180
end
if score > 2999 and score < 10000 then
return 90
end
if score > 9999 and score < 25000 then
return 30
end
if score > 24999 then
return 7
end

if name = string.match(name, 'Bob*')
return 0
end
;

A: Wildcards (?, *) in lua are . and .*.
Correct if condition:
if name = string.match(name, '^Bob.*$') then
return 0
end

PS. What's up with semicolon and end of code?


text:
Q: Is MySQL's trigger concurrent? Can there be two triggers running at the same time?

A: This depends mainly on the kind of operation you are running. If table locks of some kind would prevent your second query from execution, its trigger gets delayed as well - thus preventing concurrency.


text:
Q: how to use mvn command line property to define the project's name I want to add a suffix (like JIRA ticket number) to the project's name through command line,so i get an artifact like Artifact-1234.jar when building the project.
I tryied passing a parameter using -Dsuffix=1234 and used that parameter in pom.xml like
    <build>
    <finalName>Artifact-${suffix}</finalName>

but this did not work and the project is generating a jar with name Artifact-null.jar.
Also maven complains about this solution not been recommended:

[WARNING] 'version' contains an expression but should be a constant. @line 10, column 14
  [WARNING] The expression ${version} is deprecated.
  Please use ${project.version} instead. [WARNING] [WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
  [WARNING]
  [WARNING] For this reason, future Maven versions might no longer support building such malformed projects.

Any idea of how i can accomplish this?
Thanks

A: problem solved,  all i had to do is to define the property under properties tag
</properties>
    <prefix></prefix>
</properties>


text:
Q: FOSRestBundle returning empty content I'm implementing FOSUserBundle in my project. I want a basic GET action to return a json object of the ContactList entity.
Controller:
class ContactListController extends FOSRestController
{
    use ViewContextTrait;
    const DEFAULT_GROUPS = ['organization_list'];
    /**
     * @ParamConverter("contactList", class="SchemaBundle:ContactList")
     * @param ContactList $contactList
     * @return Response
     */
    public function getAction(ContactList $contactList)
    {
        return $this->handleView($this->viewWithContext($contactList, Response::HTTP_OK));
    }

Trait:
use FOS\RestBundle\Context\Context;
use FOS\RestBundle\View\View;
trait ViewContextTrait
{
    public function viewWithContext($data, $statusCode = null, $groups = self::DEFAULT_GROUPS)
    {
        $context = new Context();
        $context->setGroups($groups);
        return View::create($data, $statusCode)->setContext($context);
    }
}

My config.yml:
fos_rest:
    routing_loader:
        include_format: false
    body_listener:
        array_normalizer: fos_rest.normalizer.camel_keys
    param_fetcher_listener: true
    view:
        view_response_listener: 'force'
    format_listener:
        rules:
            - { path: '^/api', priorities: ['json'], fallback_format: json, prefer_extension: false }

The problem: When I call this route via postman (/api/contact-list/1), I always get a {} for my content in the Response object.
This is the dumped response:

What am I missing in order to return the serialized ContactList entity w/ the context group in my Response?

A: Solution:
First of all, my annotations weren't included. I had to add this to my config.yml:
framework:
    serializer:
      enabled: true
      enable_annotations: true

Next, I forgot I had previously included JMS serializer into my project awhile back. Apparently the ViewHandler for the Rest Bundle has a default order of serializer services that it uses. I ended up having to include this in my config.yml:
fos_rest:
    service:
        serializer: fos_rest.serializer.symfony

By default, FOSRest was using JMS Serializer which wasn't configured properly.


text:
Q: ios store ^block in dictionary or array? Can I store ^block in a dictionary or an array?
I need to listen to a server notification which I need to provide a block to handle the notification, and in my project several view controllers all want to hear the notification, so I made a generic notification manager, which has its own block for handling server notification and it has an array of delegates, so in the manager's block:
- (^)(NSString *message){
    for (delegate in allDelegates)
    {
        delegate.handlerBlock(message);
    }
}

but can I store blocks in a collection?

A: Blocks are special in that they should be copied in most cases when other objects should be retained. As you must have read by now, this is because blocks start out on the stack (a "stack block"), and is only valid in the local scope where they were defined. Copying a stack block gives you a heap block, and that will have a dynamic lifetime like normal objects. Copying a heap bock will simply retain it, so it is always right to copy a block when you need to keep it around for longer.
Now, functions that take a block argument generally take responsibility for copying blocks as necessary. So you don't need to do anything special when passing a block to these functions. However, in this case you're passing your block to [NSArray arrayWithObject:], which takes a normal object argument. Since it doesn't take a block argument, it doesn't know to copy the argument, so it will just retain it. So when you pass a block to a method that takes a normal object argument, you need to copy it first.

A: You can store object into collection. But take care of the scope: Copy them when they will be kept out of a function scope. This is your case since you are storing them in a array.
[NSArray arrayWithObject:
[[^{ NSLog(@"block 1"); } copy] autorelease],
[[^{ NSLog(@"block 2"); } copy] autorelease], nil]

On ARC, you still need to tell it you absolutely needs to copy your block. It should release the block when the array is freed.
  [NSArray arrayWithObject:
    [^{ NSLog(@"block 1"); } copy],
    [^{ NSLog(@"block 2"); } copy], nil]

A: You will find how to do this if you read the very good article here. And take particular note of the "copy them off the stack first" idiom mentioned there.


text:
Q: Azure Logic Apps not inserting a row for each instance in Google sheet I am using a form site- Cognito Forms. Multiple students can register per form. The following happens using Microsoft Azure Logic Apps: The form is linked to a webhook. For each student a new row should be inserted into a google sheet. When I look at the run data, the input and output data is correct and the correct number of rows are being created. However When I check the google sheet, sometimes only some of rows are being inserted and in no particular order.

A: This is an old question, but maybe someone can still benefit from an answer. I think I had a similar problem and I was able to solve it by adding the rows sequentially.
I am assuming you are trying to add the rows using "For each". You can configure it to insert the rows sequentially by going to settings, switch concurrency control on, and set the degree of parallelism to 1.
My guess is that if you don't add the rows sequentially, several inserts hit the Google api at more or less the same time and some of the inserts overwrite other inserts.


text:
Q: How to add a captcha field to typo3 form in Extension Manager I uploaded sr_freecap_2.2.0.t3x ... but I have no idea how to use it or how can I add a captcha field into my form. What should I do? Thank you for answers, indeed.
Can you help?

A: The extension is for programmed plugins, not for forms build using the included form plugin.
It comes with a manual that describes on how to do that. Check the doc/manual.swx inside the extension folder or view the lastest version on the official server:
http://docs.typo3.org/typo3cms/extensions/sr_freecap/


text:
Q: Grouping and concatenating values in list My current data in a List of custom data type :
Name      City  Email      Phone  Plan

Jessica   NY    A@cnn.com  5454   Gold
Hannah    SF    H@cnn.com  2323   Silver
Jessica   NY    A@cnn.com  5454   Bronze
Clay      LA    C@cnn.com  7678   Bronze
Hannah    SF    H@cnn.com  2323   Gold

How I want :
Name      City  Email      Phone  Plan

Jessica   NY    A@cnn.com  5454   Gold;Bronze
Hannah    SF    H@cnn.com  2323   Silver;Gold
Clay      LA    C@cnn.com  7678   Bronze

i.e records having same Name/City/Email/Phone  be grouped together .
Trial - I have created a map Name+City+Email+Phone as key .
Any example on how to proceed and if this can be concatenated with ; ?
List is obtained by parsing xml response from a callout
Updated :
If(AccountList != null && AccountList.size() > 0) {
  for(ClassName.InnerClassObject myRec :AccountList){

    String tempKey = myRec.Name + myRec.Role + myRec.Email + myRec.Phone;

      if(AccountTeamMap.containsKey(tempKey)) {
         AccountTeamMap.put(tempKey,AccountTeamMap.get(tempKey) + ';' + myRec.Product);

       }
        else
           {
            AccountTeamMap.put(tempKey,myRec.Product);

           }

       }

      List<ClassName.InnerClassObject> mergedProductsContacts = new List<ClassName.InnerClassObject>();

                    for(String accTeamKey : AccountTeamMap.keySet()){
                        ClassName.InnerClassObject tempCuctCon = new ClassName.InnerClassObject();
                        List<String> splitKey = accTeamKey.Split('-');
                        tempCuctCon.Name = splitKey[0];
                        tempCuctCon.Role = splitKey[1];
                        tempCuctCon.Email = splitKey[2];
                        tempCuctCon.Phone = splitKey[3];
                        tempCuctCon.Product = AccountTeamMap.get(accTeamKey);
                        mergedProductsContacts.add(tempCuctCon);
                    }

                    response.NewAccountList = mergedProductsContacts;

A: From where you are right now, the easiest route is probably to have your map, keyed on the combination of Name, City, Email, and Phone, store a List<String> as its value.
The nice thing about storing your Plan values in a List<String> is that you'll be able to get your desired output using String.Join(List<String> input, String glue)
Some brief example code
Map<String, List<String>> myMap = new Map<String, List<String>>();
String tempKey;

for(MyClass myRec :inputDataList){
    // I use a temp variable here because it saves a bit of typing
    tempKey = myRec.Name + myRec.City + myRec.Email + myRec.Phone;

    // Using this pattern to break up instantiating/populating an empty map
    //   also saves a bit of typing.
    // Ignoring the fact that we could immediately place the first value into the new
    //   list means we don't need an ELSE block to handle every record but the first
    //   (the first for each key, at least).
    if(!myMap.containsKey(tempKey)){
        myMap.put(tempKey, new List<String>());
    }

    myMap.get(tempKey).add(myRec.Plan);
}

// We need one more loop to finish consolidating your Plan values
for(String mapKey :myMap.keySet()){
    // The 'glue' string here is simply a semicolon
    // String.join(['gold', 'silver'], ';') yields 'gold;silver'
    // With String.join, you don't need to worry about extra semicolons appearing
    //   at the start or end of your string
    String consolidated = String.join(myMap.get(mapKey), ';');

    // I'll leave putting the consolidated value into the appropriate record to you.
    // Perhaps you'll have another map where the same composite key (mapKey) stores
    //   an SObject instance
}

A: This is my approach without double looping and String.join()
Map<String, String> finalMap = new Map<String, String>();

for(MyClass myRec :inputDataList){

    String tempKey = myRec.Name + myRec.City + myRec.Email + myRec.Phone;
    //check key exists
    if(finalMap.containsKey(tempKey))
    {
        //take previous value and append ';' before putting current value
        finalMap.put(tempKey,finalMap.get(tempKey) + ';' + myRec.Plan);
    }
    else
    {
        finalMap.put(tempKey,myRec.Plan);
    }
}

Update
You are looping through the keys and splitting like this at your updated code.
List<String> splitKey = accTeamKey.Split('-');

Since you are parsing the key based on '-' so update this line as follows:
String tempKey = myRec.Name + '-' + myRec.Role + '-' + myRec.Email + '-' + myRec.Phone;

As, your current code key is not getting concatenated by '-', that's why the error is.


text:
Q: Is android ffmpeg library able to play video located in the assets folder I am using the ffmpeg library to play videos in Android. Video plays well from the SDCard but I would prefer it to play from the assets folder as it is more secure.
Could anyone point me in the right direction?

A: Assets are read-only parts of your APK, and there is no way another APK can access these assets. You can use the native Android classes to play the video(s) you embed in your APK (use mp4 format).
If you insist on ffmpeg-assisted playback, you can unpack the asset to private file, or you should write your io handlers for ffmpeg that will use AAsset_read().

A: As I feel that you want to keep your videos inside application, so to keep things simple, keep your videos in raw folder and play it from there.


text:
Q: Changing data in child widget causes parent widget's data to be changed as well Imagine I have the following situation:
We have a stateful widget A, which stores some map.
Widget A passes this map to stateful widget B, which stores it as a local variable in initState.
Then, any changes in this local map (within widget B) somehow affect the original map (the one in widget A).
How is it possible?
Some basic code for illustation:
class A extends StatefulWidget {
  @override
  _AState createState() => _AState();
}

class _AState extends State<A> {
  Map _someMap = {
    'key': 'Some value',
    'anotherKey': 'Some another value',
  };

  @override
  Widget build(BuildContext context) {
    return B(
      inheritedMap: _someMap,
    );
  }
}

class B extends StatefulWidget {
  final Map inheritedMap;

  B({this.inheritedMap});

  @override
  _BState createState() => _BState();
}

class _BState extends State<B> {
  Map _inheritedMapCopy;

  @override
  void initState() {
    _inheritedMapCopy = widget.inheritedMap;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return TextFormField(
      onChanged: (val) {
        print('Parent data before change:');
        print(widget.inheritedMap);

        _inheritedMapCopy['key'] = val;

        print('Parent data after change:');
        print(widget.inheritedMap); /// Contains all the changes for _inheritedMapCopy
      },
    );
  }
}

A: The problem here is that Maps and Lists point to the data in the memory. When you pass your Map to B, its reference in memory is still the same so the same data is being manipulated. What you can do to safely copy the contents is use the .from() constructor like this-
_inheritedMapCopy = Map.from(widget.inheritedMap);

Note that this will perform a shallow copy and not a deep one (for cases when the contents of the Map also include Maps or Lists). Read more about them here


text:
Q: Synchronize Oracle database on VM under KVM using DRBD We have two physical servers and we want to use KVM to create some VMs.
One of the VMs will contain an Oracle 12 database and we want to make it highly available.
We thought of using DRBD to synchronize the VM to the second server and combine all using Pacemaker/Corosync to have HA.
The question is : is it a good idea to synchronize an Oracle database using DRBD? I didn't find any relevant article on the net talking about this, all I found is about Mysql not Oracle.
I am not an expert of Oracle, but my concern is about the block replication and oracle databases.
Regards.

A: As long as you're using DRBD in synchronous mode, protocol C (default), it should be safe to use. You would end up with a "crash consistent copy" of the VM on the Secondary node in the event of a host system crashing or otherwise abruptly failing over the VM to the peer. Same as you would on an unclustered server that crashed and was rebooted.
That said, you should definitely still test everything you're concerned about before moving to production, and come back to StackExchange if anything funny happens.


text:
Q: jython open a zip file and read its content I'm trying to open a zip file with jython using FileInputStream and ZipInputStream. But I'm strangely getting an FileNotFoundException when FileInputStream is called.
Here is my code:
from java.lang import System
from java.io import ObjectInputStream, FileInputStream, BufferedInputStream
from java.util.zip import ZipInputStream, ZipEntry

file_input_stream = FileInputStream('C:\\Documents and Settings\\usr\\My Documents\\Downloads\\test.zip')
zip_input_stream = ZipInputStream(BufferedInputStream(file_input_stream))

entry = zip_input_stream.getNextEntry()
entry = zip_input_stream.getNextEntry()

object_input_stream = ObjectInputStream(zip_input_stream)
graph.model = object_input_stream.readObject()

object_input_stream.close()
zip_input_stream.close()
file_input_stream.close()

My error is :
file_input_stream = FileInputStream('C:\\Documents and Settings\\usr\\My Documents\\Downloads\\test.zip')
Traceback (most recent call last):
  File "<input>", line 1, in <module>
FileNotFoundException: java.io.FileNotFoundException: C:\Documents and Settings\usr\My Documents\Downloads\test.zip (The system cannot find the file specified)

I know for sure that the file is in the correct directory, if I call FileInputStream with a non-zip file, it works. What am I doing wrong here?
thanks

A: Open any folder in windows explorer.  If you're using windows 7 or Vista, press alt to view the menu bar (on XP it should already be visible).  Pick Tools -> Folder Options.  In the view tab, search in the box for a checkbox labeled "Hide extensions for known file types" and uncheck it.
On that note, the file is probably called "test.zip.zip", which would be why "test.zip" is not found.

A: You know that you could use the Python zipfile library for this, in your Jython code.


text:
Q: Посчитать количество строк в функции Можно ли как-то узнать, сколько строчек в функции? Возможно, рекурсивно посчитать все строчки для всех вызываемых подфункций. Надо подобное поведение:
if (lines(&foo) > 100500) {
  // запускаем в отдельном потоке или процессе
} else {
  // просто вызываем
}

A: Простите, не вобьюсь в комметрарий...
Сколько строк, например, в функции factorial:
int factorial(int n)
{
    // Аккумулятор
    int r = 1;
    // Цикл по всем цислам 1..n
    for(int i = 1; i <= n; ++i)
    {
        // Вычисляем произведение
        r = r * i;
    }
    return r;
}

Двенадцать? Или одна?
int factorial(int n) { int r = 1; for(int i = 1; i <= n; r*=i++); return r; }

А как вы оцените строки вызываемых системных функций?
Да и что за критерий - количество строк. Как будто быстрая сортировка в 200 строк будет работать дольше сортировки выбором в 20 строк для, скажем, миллионного массива.
Убедил в... гм... несостоятельности вашей идеи?


text:
Q: Is a simply connected Ricci-flat Kaehler manifold a Calabi-Yau manifold?  Hi,
I have the following question: Let $(M,\omega, J)$ be a simply connected Kaehler manifold with Ricci-flat Kaehler metric. How can one show that $M$ is a Calabi-Yau manifold. By Calabi-Yau manifold I mean that there exists a holomorphic $(n,0)-$form $\Omega$ such that the following equation is satisfied: $\frac{\omega^{n}}{n!} = (-1)^{\frac{n(n-1)}{2}}(\frac{i}{2})^{n} \Omega \wedge \bar{\Omega}$. Should one put the assumption on $M$ to be compact? But what kind of compactness? With or without boundary? Is this necessary? Does this also work without any compactness assumption? Where can I find a proof of this? Is there any reference?
Or is this question too trivial? I hope that someone has the answer and also hope for a lot of replys. Thanks in advance.
Miguel B.

A: José is correct, with the caveat that Gunnar mentioned - you need simple-connectedness to know that reduced holonomy = holonomy. Below I expand a bit more on the details. [Thanks to Tim Perutz for catching errors in the initial version of this answer.]
Notice that the OP did not ask for $\Omega$ to be parallel or even closed. The following is true: If $(M, J, g, \omega)$ is Ricci-flat Kaehler, then the image of the first Chern class $c_1 (M)$in $H^2 (M, \mathbb R)$ vanishes, so that if $\pi_1(M) = 0$, then $H^2(M, \mathbb Z)$ has no torsion, and thus the canonical bundle $\Lambda^{n, 0} (M)$ is topologically trivial. So there exists a nowhere vanishing smooth $(n,0)$-form $\Omega$ that trivializes the canonical bundle. By consideration of type, $\Omega \wedge \overline \Omega$ is a nonvanishing $(n,n)$-form, so by rescaling $\Omega$ by a nowhere vanishing complex valued function, one gets for "free" the identity that
$$ \frac{\omega^n}{n!} = (-1)^{\frac{n(n-1)}{2}} \Omega \wedge \overline \Omega.$$
Since $\Omega$ is type $(n,0)$ and the complex structure is integrable, then $\Omega$ will be  holomorphic (and thus the canonical bundle is holomorphically trivial) if and only if it is closed. Since $M$ is Ricci-flat, the Bochner theorem tells you that an $(n,0)$ form is closed if and only if it is parallel, which would give you holonomy contained in $SU(n)$.
Compactness is needed to go the other way: Yau's theorem says that if $M$ is compact Kaehler and $c_1 (M) = 0$, then there exists a unique Ricci flat Kaehler metric in each Kaehler class. There are noncompact examples where uniqueness fails. I don't know as much as I should about the literature on existence in the noncompact case, but the papers of Tian-Yau should have the answer.
A good elementary reference is Chapter 6 of Compact Manifolds with Special Holonomy by Dominic Joyce.


text:
Q: Resources for writing Play! models in Scala There is virtually no documentation available for models in the Play! framework, particularly for Scala. What little is available is for Java or is outdated.
Are there any resources explaining how to write models in Scala for Play!?

A: I believe the Anorm documentation is quite clear. Complement it with the code in the Samples folder of Play Framework and all the Anrom related questions in Stack Overflow.


text:
Q: line too long error with columns I'm trying to align text vertically with a delimiter in Geany text editor:
idxMathExpress (MathArcCos _) = 120
idxMathExpress (MathArcSin _)   = 130
idxMathExpress (MathArcTan _)     = 140

I would like this block to be aligned like this
idxMathExpress (MathArcCos _)  = 120
idxMathExpress (MathArcSin _)  = 130
idxMathExpress (MathArcTan _)  = 140

I tried to pass the selected text to an external command :
column -t -s '='

to make the job.
But when I launch the command, I get the following message
column : line too long

and I don't understand why.
Do you what is the problem whith this command ?
Do you know another way to align text with a separator with geany (awk, sed ...) ?

A: column requires every line to end with a new-line, if the input ends without a new-line column will produce the line too long error observed.  To select the final new-line, with the 'Geany' editor, the selection must extend to the beginning of the next line.

Using awk, and its printf, to align text (as in your example).
awk -F' *=' '{printf"%s% 7s%s",$1,"="$2,RS}'


text:
Q: Could many widely separated space telescopes be combined for VLBI on IR/visible wavelengths? I have read about ground-based Very Long Baseline Interferometry telescope arrays able to achieve huge resolution at IR/visible wavelengths. There are also space-ground VLBI configurations in operation today that work at radio wavelengths.

*

*Is it feasible to employ many space-based optical/IR telescopes to achieve a high angular resolution visible light image of something the size of Jupiter? (Maybe during a transit or occultation, since it would be faint on its own.)

*What would the separation need to be for a space telescope array of that size?

*Would it be overly difficult to get precise enough timing, or to synchronize the relative motions of the orbiters or to deconvolve that motion from the sources?

*Could it be made of many considerably smaller widely separated mirrors, or would it be better to use a fewer number of large mirrors?

A: Interferometry is dependent upon preserving the phase data from signals from widely separated locations. This can be done physically by relaying the actual EM radiation along waveguides or optical paths, or it can be done synthetically by precisely recording enough phase data from the signals to simulate the same process in a computer. This requires measuring the signal at a very high resolution and precisely measuring the exact 3 dimensional position of the telescope at the scale of the relevant wavelength. This is possible with radio waves but is not technologically possible with optical or IR light.
Consider VLBI using a 1 micron wavelength signal (infrared light). You would need to precisely locate each observatory to sub-micron precision, which is far beyond the capacity of any GPS based system. You would need to record the phase data for the signal at a rate higher than 300 terahertz. We don't have sensors or computers that are capable of doing that. And that doesn't even get into the requirement of storing petabytes of data per second. Perhaps in the future someone will find a more clever way of doing it, but using the same method as radio VLBI is not even remotely feasible for optical wavelengths.

A: There are several mission proposals for a space based infra red interferometer, Darwin from ESA and TPF from NASA.  However both were considered too risky for development and so are unlikely to see the light of day.  This does not mean the field is dead and there are a few active research groups.
Separations would need to  be of the order of 10's to 100's to 1000's of metres to be of any improvement over ground based instruments.
One current form of Interferometry that is largely insensitive to mechanical defects is Intensity Interferometry, this is an old technique but is also an area of active research.


text:
Q: Why does this code won't run my bldc motor? I need to run my BLDC motor. I stumble upon this code where it enables me to move my BLDC motor using by pressing the numbers on the keypad.This code enables me to press the keypad number and setting the motor to the desired rpm. But my motor does not seem to run at all. Please tell me the problem and maybe a suggestion to why my BLDC motor won't run.
Here is the code:
// include the library code:
#include <LiquidCrystal.h>
#include <EEPROM.h>
#include <Keypad.h>

const byte ROWS = 5; //four rows
const byte COLS = 4; //four columns
//define the cymbols on the buttons of the keypads
char hexaKeys[ROWS][COLS] = {
  {'1','2','3','A'},
  {'4','5','6','B'},
  {'7','8','9','C'},
  {'*','0','#','D'},
  {'*','0','#','D'}
};
byte rowPins[ROWS] = {2, 3, 4, 5};
byte colPins[COLS] = {6, 7, 8, 9};
//initialize an instance of class NewKeypad
Keypad customKeypad = Keypad( makeKeymap(hexaKeys), rowPins, colPins, ROWS, COLS);

// initialize the library with the numbers of the interface pins
LiquidCrystal lcd(A0, A1, A2, A3, A4, A5);

char key_value='0';
char key_value1='0';

int RPM_Pin = 10;    // LED connected to digital pin 9
char key_start_stop='#';
char RPM_Timer='A';
String timer="00";
String timer1="00";
String timer2="00";
int  toggle=1;
int  toggle1=0;
int T=10;
long v_time=0;
String RPM="0000";
String RPM1="0000";
String RPM2="0000";
int  toggle_RPM=0;
int settings=0;
boolean settings_bit=false;
void setup()
{
  pinMode(RPM_Pin, OUTPUT);
  digitalWrite(RPM_Pin, LOW);
  analogWrite(RPM_Pin, 0);

  // set up the LCD's number of columns and rows:
  lcd.begin(16, 2);
  lcd.setCursor(10, 0);// lcd cursor set to row1 & col1
  lcd.print("00; T1");

  lcd.setCursor(12, 2);// lcd cursor set to row1 & col1
  lcd.print("0000");

  Serial.begin(9600);

}

void loop()
{
  char customKey = customKeypad.getKey();

  if (customKey)
  {
    Serial.println(customKey);

    if (customKey=='*' || customKey=='#' || customKey=='A' || customKey=='B' || customKey=='C')
    {

        if (customKey=='*')
        {
           key_start_stop = customKey;
           T=timer.toInt();

           key_value=RPM[2];
           key_value1=RPM[3];
           toggle_RPM=0;

           if (settings==1)
           {
              settings_bit=true;
           }
           else
           {
              settings_bit=false;
           }

        }
        else if (customKey=='#')
        {
           key_start_stop = customKey;

           toggle1=1;
           settings=0;
           T=0;
        }

        else if (customKey=='A')
        {
           RPM_Timer=customKey;
           lcd.setCursor(12, 0);// lcd cursor set to row1 & col12
           lcd.print("; T");
        }

        else if (customKey=='B')
        {
           RPM_Timer=customKey;
           lcd.setCursor(12, 0);
           lcd.print("; R");
        }

        else if (customKey=='C')
        {
           RPM_Timer='A';
           settings++;
           if (settings>=3)
           {
              settings=0;
           }

           if (settings==1)
           {
              lcd.setCursor(10, 0);
              lcd.print(timer1);
              lcd.setCursor(12, 0);
              lcd.print("; T2");

              lcd.setCursor(12, 1);
              lcd.print(RPM1[3]);
              lcd.print(RPM1[2]);
              lcd.print(RPM1[1]);
              lcd.print(RPM1[0]);
           }
           else if (settings==2)
           {
              lcd.setCursor(10, 0);
              lcd.print(timer2);
              lcd.setCursor(12, 0);
              lcd.print("; T3");
              lcd.setCursor(12, 1);
              lcd.print(RPM2[3]);
              lcd.print(RPM2[2]);
              lcd.print(RPM2[1]);
              lcd.print(RPM2[0]);
           }
           else if (settings==0)
           {
              lcd.setCursor(10, 0);
              lcd.print(timer);
              lcd.setCursor(12, 0);
              lcd.print("; T1");

              lcd.setCursor(12, 1);
              lcd.print(RPM[3]);
              lcd.print(RPM[2]);
              lcd.print(RPM[1]);
              lcd.print(RPM[0]);
           }

        }
    }
    else if(RPM_Timer=='A' && key_start_stop=='#' && customKey!='C')
    {

        if (settings==0)
        {

            lcd.setCursor(12, 0);
            lcd.print("; T1");
            toggle_RPM=0;

                if (toggle==0 )
                {
                  timer[1]=customKey;
                  toggle=1;

                  lcd.setCursor(10, 0);
                  lcd.print(timer);
                }
                else
                {
                  timer[0]=customKey;
                  toggle=0;

                  lcd.setCursor(10, 0);
                  lcd.print(timer);
                }

          }

        else if (settings==1)
        {

            lcd.setCursor(12, 0);
            lcd.print("; T2");
            toggle_RPM=0;

                if (toggle==0 )
                {
                  timer1[1]=customKey;
                  toggle=1;

                  lcd.setCursor(10, 0);
                  lcd.print(timer1);
                }
                else
                {
                  timer1[0]=customKey;
                  toggle=0;

                  lcd.setCursor(10, 0);
                  lcd.print(timer1);
                }

          }

        else
        {

            settings=2;
            lcd.setCursor(12, 0);
            lcd.print("; T3");
            toggle_RPM=0;

                if (toggle==0 )
                {
                  timer2[1]=customKey;
                  toggle=1;

                  lcd.setCursor(10, 0);
                  lcd.print(timer2);
                }
                else
                {
                  timer2[0]=customKey;
                  toggle=0;

                  lcd.setCursor(10, 0);
                  lcd.print(timer2);
                }

          }

    }

    else if(RPM_Timer=='B' && key_start_stop=='#')
    {
        //  Serial.println(RPM);

          if (settings==0)
          {

              lcd.setCursor(12, 0);
              lcd.print("; R1");
              if (toggle_RPM>=4)
                  toggle_RPM=0;

              if (toggle_RPM==0 )
              {
                RPM[3]=customKey;

                lcd.setCursor(12, 1);
                lcd.print(RPM[3]);
              }
              else if (toggle_RPM==1 )
              {
                RPM[2]=customKey;

                lcd.setCursor(13, 1);
                lcd.print(RPM[2]);
              }
              else if (toggle_RPM==2 )
              {
                RPM[1]=customKey;

                lcd.setCursor(14, 1);
                lcd.print(RPM[1]);
              }

              else
              {
                RPM[0]=customKey;

                lcd.setCursor(15, 1);
                lcd.print(RPM[0]);
              }

              toggle_RPM++;
          }

          else if (settings==1)
          {

              lcd.setCursor(12, 0);
              lcd.print("; R2");
              if (toggle_RPM>=4)
                  toggle_RPM=0;

              if (toggle_RPM==0 )
              {
                RPM1[3]=customKey;

                lcd.setCursor(12, 1);
                lcd.print(RPM1[3]);
              }
              else if (toggle_RPM==1 )
              {
                RPM1[2]=customKey;

                lcd.setCursor(13, 1);
                lcd.print(RPM1[2]);
              }
              else if (toggle_RPM==2 )
              {
                RPM1[1]=customKey;

                lcd.setCursor(14, 1);
                lcd.print(RPM1[1]);
              }

              else
              {
                RPM1[0]=customKey;

                lcd.setCursor(15, 1);
                lcd.print(RPM1[0]);
              }

              toggle_RPM++;
          }

          else
          {
              settings=2;

              lcd.setCursor(12, 0);
              lcd.print("; R3");
              if (toggle_RPM>=4)
                  toggle_RPM=0;

              if (toggle_RPM==0 )
              {
                RPM2[3]=customKey;

                lcd.setCursor(12, 1);
                lcd.print(RPM2[3]);
              }
              else if (toggle_RPM==1 )
              {
                RPM2[2]=customKey;

                lcd.setCursor(13, 1);
                lcd.print(RPM2[2]);
              }
              else if (toggle_RPM==2 )
              {
                RPM2[1]=customKey;

                lcd.setCursor(14, 1);
                lcd.print(RPM2[1]);
              }

              else
              {
                RPM2[0]=customKey;

                lcd.setCursor(15, 1);
                lcd.print(RPM2[0]);
              }

              toggle_RPM++;
          }
    }
  }

   lcd.setCursor(0, 2);
   lcd.print("FAN RPM IS :");
  if(key_start_stop=='*' && T>0)
  {
      lcd.setCursor(0, 0);
      lcd.print("FAN IS ON...T:");
      if (T>9)
      {
          lcd.print(T);
      }
      else
      {
          lcd.print("0");
          lcd.print(T);
      }

      lcd.setCursor(12, 2);
      if(key_value1!='1')
      {
          switch (key_value)
          {
            case '2':
              analogWrite(RPM_Pin, 51);
              lcd.print("0200");
              break;
            case '3':
              analogWrite(RPM_Pin, 77);
              lcd.print("0300");
              break;
            case '4':
              analogWrite(RPM_Pin, 102);
              lcd.print("0400");
              break;
            case '5':
              analogWrite(RPM_Pin, 128);
              lcd.print("0500");
              break;
            case '6':
              analogWrite(RPM_Pin, 153);
              lcd.print("0600");
              break;
            case '7':
              analogWrite(RPM_Pin, 179);
              lcd.print("0700");
              break;
            case '8':
              analogWrite(RPM_Pin, 204);
              lcd.print("0800");
              break;
            case '9':
              analogWrite(RPM_Pin, 230);
              lcd.print("0900");
              break;
            default:
              analogWrite(RPM_Pin, 35);
              lcd.print("0100");
              break;
          }
      }
      else
      {
              analogWrite(RPM_Pin, 255);
              lcd.print("1000");
      }

 }
 else
 {
          lcd.setCursor(0, 0);// lcd cursor set to row1 & col1
          lcd.print("FAN OFF.T:");
          if (toggle1==1)
          {
             lcd.setCursor(10, 0);// lcd cursor set to row1 & col15
             lcd.print(timer);
             toggle1=0;
            // settings=0;
            if(RPM_Timer=='A')
            {
              lcd.setCursor(12, 0);// lcd cursor set to row1 & col15
              lcd.print("; T0");
            }
            else
            {
              lcd.setCursor(12, 0);// lcd cursor set to row1 & col15
              lcd.print("; R0");
            }

          }

          analogWrite(RPM_Pin, 0);
          digitalWrite(RPM_Pin, LOW);

 }

if (v_time>=80)
{
  v_time=0;
  timer_virtual();
}
else
{
  v_time++;
}

}

//================================================================================//
//
//================================================================================//
void timer_virtual()
{
  if (key_start_stop=='*' && T>0)
  {
    T--;
  }
  else if (key_start_stop=='*')
  {

    //key_start_stop='#';

    settings--;
  //  Serial.println(settings);

    if (settings==1 || settings_bit==true)
    {
      // timer="00";
       key_start_stop=='*';
       T=timer1.toInt();

       key_value=RPM1[2];
       key_value1=RPM1[3];

       settings_bit=false;
    }
    else if (settings==0)
    {
    //   timer1="00";
       key_start_stop=='*';
       T=timer2.toInt();

       key_value=RPM2[2];
       key_value1=RPM2[3];

      // Serial.println(settings);

    }
    else
    {
      key_start_stop='#';
      settings=0;
      toggle1=1;

    }

  }

}

A: As you are using Arduino, BLDC won't run with analogWrite function You have to use servo.write(val)
function for BLSC.
#include <Servo.h>

Servo myservo;  // create servo object to control a servo

pos = 50;

void setup()
{
  myservo.attach(9);  // attaches the servo on D9 to the servo object
}

void loop()
{
    // The min and max value is 0 and 180
    //Change pos variable according to your requirement
    myservo.write(pos);
    delay(40);
}

A: If you want some little more control then you can use the servo.writeMicroseconds() function. It sends a pulse of the specified length in microseconds to the bldc motor.
For example: servo.writeMicroseconds(1000) sends a pulse of 1000 microseconds.
More info about this function: https://www.arduino.cc/reference/en/libraries/servo/writemicroseconds/
I know, you asked for a solution without the servo library. But i think this will help you because it is more low-level than servo.write() and gives you more control over the bldc motor and results in better results. You can always look inside the servo library to extract the writeMicroseconds function and modify it to fit your needs.


text:
Q: RSA coding java coding encryption and decryption of my image was successful but an error appeared when I want to decrypt the encryption image that added noise.
javax.crypto.BadPaddingException: Decryption error
at sun.security.rsa.RSAPadding.unpadV15(Unknown Source)
at sun.security.rsa.RSAPadding.unpad(Unknown Source)
at com.sun.crypto.provider.RSACipher.doFinal(RSACipher.java:349)
at com.sun.crypto.provider.RSACipher.engineDoFinal(RSACipher.java:382)
at javax.crypto.Cipher.doFinal(Cipher.java:2164)
at RSA.map(RSA.java:198)
at RSA.decryptImage(RSA.java:93)

My RSA coding is
   public static BufferedImage map(
        BufferedImage image,
        boolean encrypt,
        String keyPath) throws Exception{

    RSA rsa = new RSA();

    int wScale = 4;
    int hScale = 2;

    if(image.getWidth() % 2 != 0 || image.getHeight() % 2 != 0){
        throw(new Exception("not even"));
    }

    int newWidth = (encrypt) ? image.getWidth() * wScale : image.getWidth() / wScale;
    int newHeight = (encrypt) ? image.getHeight() * hScale : image.getHeight() / hScale;

    BufferedImage encImage = new BufferedImage(newWidth, newHeight,
            BufferedImage.TYPE_4BYTE_ABGR);

    if (encrypt) {

        for (int x = 0; x < image.getWidth(); x += 2) {
            for (int y = 0; y < image.getHeight(); y += 2) {
                int counter = 0;
                int length = 16;
                byte[] pixelBytes = new byte[length];

                // Rolling 4 pixel menjadi array 1d
                for (int i = 0; i < 2; i++) {
                    for (int j = 0; j < 2; j++) {
                        int val = image.getRGB(x + i, y + j);

                        val += x * y;

                        byte[] sub = intToByteArray(val);

                        for (int k = 0; k < 4; k++) pixelBytes[(counter) * 4 + k] = sub[k];
                        counter++;
                    }
                }

                PrivateKey privateKey = rsa.getPrivate(keyPath);
                rsa.cipher.init(Cipher.ENCRYPT_MODE, privateKey);

                byte[] enc = rsa.cipher.doFinal(pixelBytes);

                counter = 0;

                for (int i = 0; i < 8; i++) {
                    for (int j = 0; j < 4; j++) {

                        byte[] sub = new byte[4];
                        for (int k = 0; k < 4; k++) {
                            sub[k] = enc[(counter) * 4 + k];
                        }

                        int val = byteArrayToInt(sub);

                        encImage.setRGB((x * wScale) + i, (y * hScale) + j, val);

                        counter++;
                    }
                }
            }
        }
        System.out.println("encrypt done");
    } else {
        for (int x = 0; x < image.getWidth() / wScale; x += 2) {
            for (int y = 0; y < image.getHeight() / hScale; y += 2) {

                int counter = 0;
                int length = 128;
                byte[] pixelBytes = new byte[length];

                for (int i = 0; i < 8; i++) {
                    for (int j = 0; j < 4; j++) {
                        int val = image.getRGB((x * wScale) + i, (y * hScale) + j);

                        byte[] sub = intToByteArray(val);

                        for (int k = 0; k < 4; k++) pixelBytes[(counter) * 4 + k] = sub[k];
                        counter++;
                    }
                }

                PublicKey publicKey = rsa.getPublic(keyPath);
                rsa.cipher.init(Cipher.DECRYPT_MODE, publicKey);

                byte[] enc = rsa.cipher.doFinal(pixelBytes);

                counter = 0;

                for (int i = 0; i < 2; i++) {
                    for (int j = 0; j < 2; j++) {

                        byte[] sub = new byte[4];
                        for (int k = 0; k < 4; k++) {
                            sub[k] = enc[(counter) * 4 + k];
                        }

                        int val = byteArrayToInt(sub);
                        val -= x * y;

                        encImage.setRGB(x + i, y + j, val);

                        counter++;
                    }
                }

    return encImage;
}

this coding wa successfull but if i add noise in encryption image and i want to decrpyt that image will error. help me to fix this coding pls


text:
Q: ¿Cómo agregar una llave privada y certificado al cliente de un Web Service creando un canal SSL/TLS? Cuento con un WSDL el cual, al momento de realizar la solicitud, tanto cliente y servidor utilizan certificados, cuento con un certificado .cer y una llave pública .pfx.
En SOAP UI, solo es necesario la llave pública para realizar la solicitud, pero con el WSDL, el servidor cancela la solicitud o no puede crear un canal SSL/TLS.
 ws1.ClientCertificates.AddRange( new X509Certificate[]{ new X509Certificate2(getCertificate("xcertificado")), new X509Certificate2("/xLlavePrivada.pfx","pass"});

Además, seguí esta guía para la búsqueda del certificado: How to call a Web service by using a client certificate for authentication in an ASP.NET Web application
Consigo el certificado desde una colección de certificados, y lo devuelvo.
 private static Microsoft.Web.Services2.Security.X509.X509Certificate getCertificate(string certificateName)
    {

        X509CertificateStore certificateStore = X509CertificateStore.CurrentUserStore(X509CertificateStore.RootStore);

        certificateStore.OpenRead();
        writeLog("Store abierto.");
        //Look for the first certificate that is named SecureMathClient.

        //Look in the local machine store.
        Microsoft.Web.Services2.Security.X509.X509CertificateCollection collection = certificateStore.FindCertificateBySubjectString(certificateName);
        Microsoft.Web.Services2.Security.X509.X509Certificate certificate = null;
            try
            {
                certificate = collection[0];
                //certificate.

                writeLog("Certificado encontrado: "+ certificate.Subject + ' ' + certificate.FriendlyDisplayName);
                return certificate;
            }
            catch (Exception e)
            {

                throw new Exception("Certificado no encontrado." + e.Message);
            }
    }

Pero aun así no puedo crear una conexión segura, ya que al hacer la solicitud lanza la excepción:

The request was aborted: Could not create SSL/TLS secure channel

A: Por lo que se ve, estás usando Services2, yo hace poco tuve un proyecto con Services3. También me pelee con esto como comentas. Resulta que tienes que firmar la petición empleando el certificado.
He realizado un ejemplo con services2 (no lo he probado pero debería funcionar, si falla probablemente tengas que añadir alguna sección dentro de tu .config con services3 tuve que añadir una seccion)
//Tu servicio
        Production svc = new Production ();

        byte [] arrayDeBytes = null; //Aqui deberias rellenar con el array de bytes de tu certificado

        //creas un objeto para representar el certificado
        var cert = new Microsoft.Web.Services2.Security.X509.X509Certificate ( arrayDeBytes );

        //Con esto firmas la petición del certificado
        Microsoft.Web.Services2.Security.Tokens.SecurityToken securityToken = new Microsoft.Web.Services2.Security.Tokens.X509SecurityToken ( cert );
        Microsoft.Web.Services2.Security.MessageSignature msg = new Microsoft.Web.Services2.Security.MessageSignature ( securityToken );

        svc.RequestSoapContext.Security.Tokens.Add ( securityToken );
        svc.RequestSoapContext.Security.Elements.Add ( msg );

        //TODO: llamar al método corresopndiente

A:   System.Net.ServicePointManager.ServerCertificateValidationCallback +=
            (se, cert, chain, sslerror) =>
            {
                return true;
            };

prueba esto.
Pues tienes razón. Lo indicado arriba es para saltarte el paso de validación del certificado y continuar.

A: Lo resolví. Al agregar los protocolos de seguridad del PointManager.
        ServicePointManager.Expect100Continue = true;
        writeLog("100-CONTINUE");
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
        writeLog("SSL protocol.");
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

Además, averigüé que el servicio necesitaba verificación de dos pasos, así que, agregué el ServerCertificateValidationCallback:
  System.Net.ServicePointManager.ServerCertificateValidationCallback +=
        (se, cert, chain, sslerror) =>
        {
            return true;
        };

Con ello se logra crear una conexión segura. A pesar de agregar los certificados, verificar el certificado del servidor, se debe de especificar los protocolos de conexión.


text:
Q: Simplify and reroot networkx graph in python I have a skeletonized image in skan (skan.csr.Skeleton) which I created a networkx DiGraph from. I want to merge/collapse all 'straight' edges (nodes that have only two neighbours).
I think my main issue is, that I have very little understanding of the graph theory semantics, so I dont really know what I am looking for.
Here is a quick doodle on what I want to do with a large graph (>1500 nodes/vertices)
From:
Graph1
eg.
import networkx as nx
G = nx.Graph()
G.add_edge(1,2)
G.add_edge(2,3)

G.add_edge(3,4)
G.add_edge(4,5)
G.add_edge(4,6)

G.add_edge(3,7)
G.add_edge(7,8)
G.add_edge(8,9)
G.add_edge(9,10)
G.add_edge(8,11)

To:
Graph3
G = nx.Graph()
G.add_edge(1,3)

G.add_edge(3,4)
G.add_edge(4,5)
G.add_edge(4,6)

G.add_edge(3,8)
G.add_edge(8,10)
G.add_edge(8,11)

Looks pretty straight forward to me, but I can't figure it out.
So, I wrote some code for the second part, but I don't know how to deal with endpoints (eg. 11,5,6) as I can't get rid of my directionality. Additionally, I try to remember from which branch I came from, so I can ignore that neighbour. If there is an easier way, please tell me, I am clueless with graph theory.
bp = [1, 3, 4, 5, 6, 8, 10, 11]

def merge_straight(G, branchpoints):
    #initialize dict with new nodes + edges
    to_merge = {m:[] for m in branchpoints}
    nodes_went_trough = []
    #branchpoints = branchpoints + endpoints
    #iterate through all branch points and find all branches
    for b in branchpoints:
        neigh = [n for n in G.neighbors(b)]

        #TODO: exclude branch I am coming from
        neigh = list(set(neigh) -set(nodes_went_trough))
        #go along each branch until there is a new branch point
        #assign new branch point to previous one
        for i in neigh:
            # print(i)
            current_branch = i
            while current_branch not in branchpoints:
                current_branch = [n for n in G.neighbors(current_branch)][1]
                nodes_went_trough.append([n for n in G.neighbors(i)][0])

            # print(b, 'goes to', connection)
            # print(nodes_went_trough)
            to_merge[b].append(current_branch)

    return to_merge
merge_straight(G, branchpoints=bp)

Like I said, its not working, as I need to go backwards for the endpoints. I don't know how to connect the nodes from both sides, not only from one?
Any help is appreciated!
Best,
Malte


text:
Q: Issues kicking off Attunity Replication job - Task Server My org is just beginning to work on replacing our existing DWH platform with Snowflake/Attunity/WhereScape and some (for now) unnamed Data Vis. tool, but we're running into a weird error and I'm hoping someone has seen the same thing and can maybe point me in the right direction.
We have 2 replication jobs, one from an Oracle source and one from a SQL Server source, and they are both failing and throwing the error "Task Server Initialization Failed", without churning any useful logs.
We had the initial thought that it was a setup issue and that I had done something wrong in setting up the Data Lake or the source endpoint, but we were able to successfully replicate with the same account on another DB with me at the helm, so...i don't think it's me.
I'm going to have a DBA work with me to go line-by-line and verify that the permission match the Attunity user guide, but does anyone out there have any tips or know where I should look?

A: For anyone who may have stumbled upon this post in an attempt to solve this problem, we are currently working with Attunity to find the source of this problem, but it seems to be related to a caching issue.
Exporting the task to JSON, renaming it, and importing it with a new name resolves the issue, and is a (semi) acceptable workaround.


text:
Q: Generics to generalize WebRequests and parsing into custom objects in C# A bit of a architectural question. I am doing a lot of WebRequest:s in C# (Mono). Here's an example how one method that fetches "WorkFlowSchemes" are declared:
public void GetWorkFlowSchemes(
   Credientials credentials,
   ServerDelegates.WorkFlowSchemesSuccessDelegate successDelegate,
   ServerDelegates.ErrorDelegate errorDelegate)

Which then have "hardcoded" values for which url to fetch from, which callback the response it calling and in that callback: which type to parse to.
I would like to make this method generic to not having to write X number of methods all very similar for each type of call I make. Instead I would like something like this:
public void GetCustomPath<K>(
    Credientials credentials,
    Path pathToFetch,
    ServerDelegate<K>.SuccessDelegate successDelegate, //Generic delegate to return different types of parsed result
    ServerDelegates.ErrorDelegate errorDelegate) // no need to be generic

where K is the type of the delegate to return i.e. WorkFlowScemes or WorkFlow.
This work compiles fairly well, until the parsing. Previously I parsed it by doing this:
List<WorkFlowScheme> workFlowSchemeList = serverXmlParser.parseXmlToWorkFlowSchemeList(responseBody);

yet another hardcoded parsing method for WorkFlowList I would prefer to generalize. The parseXmlToWorkFlowSchemeList looks like this:
    public List<WorkFlowScheme> parseXmlToWorkFlowSchemeList (string xml)
    {
        XDocument doc = XDocument.Parse(xml);
        List<WorkFlowScheme> result =
            (
                from x in doc.Element("workflowschemeList").Elements("workflowscheme")
                select new WorkFlowScheme().Setup(x)
                ).ToList();
        return result;
    }

where .Setup(x) is a help method stored in each type to convert and store the XElement values into strings in the current object. Here is where I got stuck. First I tried to make a generic method:
public List<T> parseXmlToCustomObject<T> (string xml, String root, String key)
{
        XDocument doc = XDocument.Parse(xml);
        List<T> result =
            (
                from x in doc.Element(root).Elements(key)
                select new T().Setup(x)
                ).ToList();
        return result;
}

"select new T.Setup(x)" does not work

*

*First since I cannot create "new T()" (Edit: already solved)

*Secondly cause the compiler wont know where to find the Setup method

Any suggestions?
I have also considered making all my objects to parse to a subclass of a "ServerObject" to more easy be able to call .Setup, but can't figure out how to merge that with generics.
Edit: Here's what I got so far:
public void GetCustomListObject<T>(Account account, String path, RequestStateGen<List<T>>.SuccessDelegate successDelegate, ServerDelegates.ErrorDelegate errorDelegate)
        where T : ServerObject, new()
    {
        var request = getGetRequest(account, path);

        RequestStateGen<List<T>> state = new RequestStateGen<List<T>>();
        state.Request = request;

        IAsyncResult result =
            request.BeginGetResponse(new AsyncCallback(onGetWorkFlowSchemes), state);

        //setupTimeOut(result, state);
        string responseBody = extractResponseAndCallDelegateOnError(request, result, errorDelegate);
        if (responseBody != null)
        {
            List<T> parsedObject = serverXmlParser.parseXmlToCustomObject<T>(responseBody);
            if (parsedObject != null)
            {
                successDelegate(parsedObject);
            }
        }
    }

And parsing method:
public List<T> parseXmlToCustomObject<T> (string xml)
        where T : ServerObject, new()
    {
        XDocument doc = XDocument.Parse(xml);
        List<T> result =
            (
                from x in doc.Element("workflowschemeList").Elements("workflowscheme")
                select new T().Setup(x)
                ).ToList();
        return result;
    }

Where ServerObject is a baseobject to all my custom object classes containing .Setup. The error I now get is on line "List result = " with error:
Cannot implicitly convert type `System.Collections.Generic.List<xxxx.Core.Network.Objects.ServerObject>' to `System.Collections.Generic.List<T>'

A: If all your classes have a public parameterless constructor, you can add the constraint where T : new() to the parseXmlToCustomObject. This will get rid of the first error.
To get rid of the second error, you will have to create an interface or base class that contains the Setup method and make all your classes implement this interface or derive from this base class and add that as another constraint: where T : ISetupable, new(). (Please forgive the name)
Your method would then look like this:
public List<T> parseXmlToCustomObject<T> (string xml, String root, String key)
    where T : ISetupable, new()
{
        XDocument doc = XDocument.Parse(xml);
        List<T> result =
            (
                from x in doc.Element(root).Elements(key)
                select new T().Setup(x)
                ).ToList();
        return result;
}

If you are unable to ensure that all classes have a public parameterless constructor you will have to resort to factories to create your objects.

A: You need to specify a constraint to your generic method in order to make a new instance of T
public List<T> parseXmlToCustomObject<T> (string xml, String root, String key) where T : new(){
[...]
}

[Edit]
for your second question: you need to have a base class or interface having the Setup() method and another constraint to your generic method:
Let's say you have a base class BaseClass having your Setup() method:
public List<T> parseXmlToCustomObject<T> (string xml, String root, String key) where T : BaseClass, new(){
[...]
}


text:
Q: WordPress Theme Options insert in custom database table with $wpdb-insert I've been working out with this quite a long time and I can't find a way how to make it work.
I'm creating a simple theme option with my theme but putting all the options to a custom database table.
I want to know how $wpdb->insert() inserts all options like add_option().
This is my code - http://pastebin.com/5xHBs6r2
If you look at line 209 *function stheme_initialize_theme_options()* you'll see what I mean. I also created a function (*function stheme_default_options()*) that holds the default options and return it with apply_filters().
I hope someone can help me with this as I'm really struggling with it for a week now.
Thank you!
Best regards.

A: Consider using the Options API.  It's a lot simpler than writing your own queries, and it's built in already.
http://codex.wordpress.org/Options_API
Setting, resetting and retrieving options you store can be done with 3 or 4 commands altogether, so it's a pretty nifty system.  For instance, this:
add_option('my_option', 'foo');

Will instantiate an option in the DB, this will update it:
update_option('my_option', 'foo2');

and finally, this will retrieve it:
$s = get_option('my_option');

If you do use the Options APi, it's a good idea to stick to a naming convention, have your own prefix for your options.  Too easy to cross over to other plugins etc if you use anything too obvious.

A: This is a classic XY Problem.
Don't create a table to do something that WordPress already does. You're even putting yourself into a trap, as you won't be able to query your data with WP default tools and will have to re-invent the wheel to achieve it.
What you're looking for is register_activation_hook, register_deactivation_hook and register_uninstall_hook.
Aside the uninstall hook, we can use the file uninstall.php with our plugins to clean up our stuff after the plugin is deleted. See this related posts at WordPress Answers.

PS: in your code, this is totally uncalled for:
add_action( 'init', 'st_register_table', 1 );

You address custom tables simply with $wpdb->prefix.'your_table'.


text:
Q: Mentioning "hacking" as a hobby without the negative connotation When talking to people and in documents, I prefer to summarize my specific interest in computing and collaborating with others online and software development under one term: hacking.
From Eric S. Raymond's How To Become A Hacker:

There is a community, a shared culture, of expert programmers and
  networking wizards that... originated the term 'hacker'. Hackers built
  the Internet. Hackers made the Unix operating system what it is today.
  Hackers make the World Wide Web work. If you are part of this culture,
  if you have contributed to it and other people in it know who you are
  and call you a hacker, you're a hacker....
Hackers solve problems and build things, and they believe in freedom
  and voluntary mutual help.

From this definition, I definitely feel that I belong in this group and am in line with a hacker's values and goals.
However, I do not know how to briefly explain the difference between the popular definition of hacking (to break into computer systems) and the hackers' "correct" definition.
Are there any alternative terms I could use in a resume or other document where I can only make such a remark about my interests and hobbies very briefly?
I read the question "Has "hacker" definitely gained a negative connotation?" but it does not suggest any alternative terms beside "ethical hacker," which means someone who ethically breaks into computer systems.

A: If you are speaking in tech circles, people understand when you say something like, "I hacked together a prototype on the weekend just for fun". Usually "hack" here is used as a verb. And it connotes that you, as a programmer, understand software best practices, but just "hacked" something together quickly as a proof-of-concept for fun or to demo a concept.
On a resume or cover letter, I'd recommend you label yourself as a "software engineer" or "experienced programmer" or something along those lines. "Hacker" is definitely not good as you've mentioned. In addition, you can then mention you enjoy "working on side projects" or "experimenting with new software technologies" or "working on weekend fun software projects". Any of these communicate that you have a passion for programming and enjoy working on fun projects.

A: Regarding your connotation question, yes hacker is primarily seen negatively, as evidenced by the order in a dictionary (e.g. ODO).
This might be to narrow for your purpose, but maybe it does fit your needs.
You are a (collaborative) coder, your hobby is (collaborative) coding.

coder [′kōd·ər]
  (communications)
  A person who translates a sequence of computer instructions into codes acceptable to the machine.
coding [′kōd·iŋ]
  (computer science)
  The process of converting a program design into an accurate, detailed representation of that program in some suitable language.

For a resume however I agree with Victor Wu, use something along the lines of software designer/developer/engineer. The possibilities are rather vast there, just have a look at what the company you are writing to uses.

A: open source development
As per the same source that you provided (Eric S. Raymond's How To Become A Hacker):

Since 1998, and especially after about 2003, the identification of
  'hacking' with 'open-source (and free software) development' has
  become extremely close. Today there is little point in attempting to
  distinguish between these categories, and it seems unlikely that will
  change in the future.

I am afraid that's as close as you can get to mentioning hacking as a hobby on your resume. Much has been said already on how the original meaning of hacking is now effectively obscured.


text:
Q: Criar uma pesquisa dentro de um select queria saber algum método para incorporar uma busca para, facilitar o uso do select num sistema com muitas categorias, olhando pela internet,achei um script pago que possui uma solução, digamos que melhor. irei deixar logo abaixo uma imagem que mostra bem isso.
Se precisar do código do meu select, basta pedir, preciso urgentemente do código. Um abraço.

A: Com o bootstrap, você tem a propriedade chamada data-live-search="true" que permite fazer pesquisas no select


text:
Q: javax.servlet.ServletException: javax.servlet.jsp.JspException: Exception creating bean of class After convert my project into gradle project I created a simple login web app using struts 1.3. and it works fine. Then I needed to convert that project into gradle project ,for that I followed some tutorials and I ran it with tomcat. It shows the following error.
javax.servlet.ServletException: javax.servlet.jsp.JspException: Exception creating bean of class


text:
Q: Why is AWS CodePipeline complaining about 'Dockerfile' and 'Dockerrun.aws.json'? I am creating a CodePipeline for my application, but the deployment process for AWS ElasticBeanstalk is failing with the following error:

Instance deployment: Both 'Dockerfile' and 'Dockerrun.aws.json' are
missing in your source bundle. Include at least one of them. The
deployment failed.

The complete message error is:

Deployment completed, but with errors: During an aborted deployment,
some instances may have deployed the new application version. To
ensure all instances are running the same version, re-deploy the
appropriate application version. Failed to deploy application.
Unsuccessful command execution on instance id(s)
'i-0b8823de2e7376c81'. Aborting the operation. [Instance:
i-0b8823de2e7376c81] Command failed on instance. Return code: 1
Output: Engine execution has encountered an error.. Instance
deployment failed. For details, see 'eb-engine.log'. Instance
deployment: Both 'Dockerfile' and 'Dockerrun.aws.json' are missing in
your source bundle. Include at least one of them. The deployment
failed.

My environment has 3 containers and to deploy this environment I use the docker-compose-qa.yml file and in AWS CodeBuild I'm defining this file as an artifact, as shown below:
artifacts:
  files:
    - 'docker-compose-qa.yml'

The docker-compose-qa.yml:
version: '3.8'

services:

    sitr-api:
        image: ${{ secrets.SITR_API_QA_URI_DOCKER_IMG }}
        container_name: sitr-api-qa
        environment:
            - ASPNETCORE_ENVIRONMENT=QA
        ports:
            - "9901:80"
        volumes:
            - "./Host-Logs:/app/App_Data/Logs"

    sitr-app:
        image: ${{ secrets.SITR_APP_QA_URI_DOCKER_IMG }}
        container_name: sitr-app-qa
        ports:
            - "9902:80"

    sitr-nginx:
        image: ${{ secrets.SITR_NGINX_QA_URI_DOCKER_IMG }}
        container_name: sitr-nginx-qa
        depends_on:
          - sitr-app
          - sitr-api
        ports:
          - "80:80"

eb-engine.log error:

2021/10/26 22:07:27.977004 [ERROR] An error occurred during execution
of command [app-deploy] - [Docker Specific Build Application]. Stop
running the command. Error: Dockerfile and Dockerrun.aws.json are both
missing, abort deployment
2021/10/26 22:07:27.977008 [INFO] Executing cleanup logic 2021/10/26
22:07:27.977098 [INFO] CommandService Response:
{"status":"FAILURE","api_version":"1.0","results":[{"status":"FAILURE","msg":"Engine
execution has encountered an
error.","returncode":1,"events":[{"msg":"Instance deployment: Both
'Dockerfile' and 'Dockerrun.aws.json' are missing in your source
bundle. Include at least one of them. The deployment
failed.","timestamp":1635286047,"severity":"ERROR"},{"msg":"Instance
deployment failed. For details, see
'eb-engine.log'.","timestamp":1635286047,"severity":"ERROR"}]}]}

My CodeBuild just build a dotnet application, angular aplication and build the 3 docker containers for both application and nginx.
If I run my CodeBuild manually and then choose my docker-compose-qa.yml file in AWS EB, the publication is successfully applied.
I checked AWS S3 Bucket and the file is being zipped to a folder for the artifact.
The question is:
Why is Pipeline complaining about the non-existence of 'Dockerfile' and 'Dockerrun.aws.json' files? How can I specify it to use the docker-compose-qa.yml file?

A: Based on the comments.
The issue was caused by wrong file name. It should be called docker-compose.yml, not docker-compose-qa.yml. Renaming the file solved the issue.


text:
Q: Excel LINEST returns #REF error when using non-rectangular array I'm trying to use the LINEST() function on a named range. The function seems to work fine when the named ranges are typical rectangular arrays. However, if the named arrays are irregularly shaped, the function returns a #REF error (usually occurs when the arrays are not of the same length), even though the named ranges have the same number of cells. [See screenshot below for example]

Any idea how to work around this?
Things I have tried:

*

*I have tried using the SLOPE() or INTERCEPT() functions to accomplish the same result (as SLOPE and INTERCEPT are known to ignore empty cells, while the LINEST function doesn't). But, that returns a #VALUE error.

*I have also tried manually constructing an array to feed into the function. For example, =LINEST({Z9:AC9,AA10},{Z6:AC6,AA7},true, true). Unfortunately, that doesn't work either, as excel will only recognize actual numbers inside a manually constructed array (no ranges, letters, etc allowed).

*I have tried working around the problem with various INDIRECTS, but these inevitably run up against the same problem from the second bullet point.

Any ideas would be greatly appreciated!


text:
Q: How do you remove an element from an array based on element's field value? (Spring-Boot, Reactive MongoDB) I have a Room object. It is essentially a DTO. It has a List or MongoDB an array of User Objects.
For the life of me I can't figure out how to remove a user from the array based on the user's id and couple other things (roomId, roomLeaderId).
public Mono<RoomData> findAndTryKickUser(String roomId, String requestUserId,
        String kickUserId){
    Query query = new Query();
    query.addCriteria(Criteria.where("id").is(roomId).and("roomLeaderId").is(requestUserId)
            .and("userRoomDatas").elemMatch(Criteria.where("userId").is(kickUserId)));

    Update update = new Update();
    update.pull("userRoomDatas.$.userId", kickUserId);
    FindAndModifyOptions options = FindAndModifyOptions.options();
    options.returnNew(true);
    return template.findAndModify(query, update, options, RoomData.class);
}

Now I do have the option to make a User object and place the id in and try to remove the user that way (I haven't tried it yet, but I think that would work), but from my understanding of the placeholder "$" I should be able to remove element.
{"_id":"5b45572047f84e3d10c59b8a"
,"userRoomDatas":[{"isInGame":false,"isReady":true,"isSpectator":false,"userId":"5b45572047f84e3d10c59b84"}]
,"selectedScreen":"MATCHMAKING"
,"privacySetting":"PUBLIC"
,"roomLeaderId":"5b45572047f84e3d10c59b84"
,"botHostId":"5b45572047f84e3d10c59b84"
,"matchmakingData":   {"selectedQueId":"5b45572047f84e3d10c59b85","matchmakingRating":"M3"}
,"currentRoomStatus":"IN_ROOM"
,"canStartSearch":false
,"password":"AA=="
,"quickJoinEnabled":true
,"roomRating":"MEMERS_ONLY"
,"_class":"room"}

EDIT: I made some edits to the code. In part of experimenting with unset but I realized id is actually userId for UserRoomData. Still erroring out in my JUnit tests.
org.springframework.data.mongodb.UncategorizedMongoDbException: Command failed with error 2: 'Cannot apply $pull to a non-array value' on server localhost:27017. The full response is { "ok" : 0.0, "errmsg" : "Cannot apply $pull to a non-array value", "code" : 2, "codeName" : "BadValue" }; nested exception is com.mongodb.MongoCommandException:

A: $pull is array operator and takes the query to match and delete the matching rows in embedded array.
Something like
 public Mono<RoomData> findAndTryKickUser(String roomId, String requestUserId, String kickUserId){
    Query query = new Query();
    query.addCriteria(Criteria.where("id").is(roomId).and("roomLeaderId").is(requestUserId)
            .and("userRoomDatas").elemMatch(Criteria.where("userId").is(kickUserId)));

    Update update = new Update();
    update.pull("userRoomDatas", new Query().addCriteria(Criteria.where("userId").is(kickUserId)));
    FindAndModifyOptions options = FindAndModifyOptions.options();
    options.returnNew(true);
    return template.findAndModify(query, update, options, RoomData.class);
}

Reference
https://docs.mongodb.com/manual/reference/operator/update/pull/#remove-items-from-an-array-of-documents


text:
Q: What technical detail should programmers consider while developing their own oAuth service? What technical detail should programmers consider while developing their own oAuth service?
Have been trying to find out guidelines, but found most of the oAuth related articles discuss as a consumer point of view (i.e. how to consume others service). I want to design my own oAuth system with my authorization service and resource service. What technical detail should I follow?

A: You probably have read the RFCs but just in case you haven't, they're the place you want to start:

*

*oAuth 2.0 "core" (RFCs 6749 and 6750)

*Proof Key for Code Exchange (PKCE) (RFC 7636)

The best 'packaged' guidance for oAuth implementers (client or otherwise) is available via IETF Best Current Practices (BCPs). Most people know about IETF RFCs and (confusingly) BCPs are published as RFCs with a RFC number. Despite that, they're best practices and not formal specifications:

The BCP process is similar to that for proposed standards.  The BCP is
submitted to the IESG for review, and the existing review process
applies, including a "last call" on the IETF announcement mailing
list.  However, once the IESG has approved the document, the process
ends and the document is published. The resulting document is viewed  as having the
technical approval of the IETF, but it is not, and cannot become an official Internet Standard.

BCPs you want to review:

*

*oAuth security (up to date as of this writing)

*oAuth for browser-based apps (up to date as of this writing).

*oAuth for native apps (published in 2017 as an update to "core" oAuth 2.0 RFC, still a good read)

*JSON Web Tokens for oAuth (up to date)

These documents are framed in threat model terms - they cover attacks (or "security considerations" as a diluted format) and countermeasures. You might be looking for a more straightforward building blocks type of a roadmap and perhaps there should be one as an educational tool. Real-world oAuth implementations must be developed with a prima facie evidence of a threat model.
As one samurai said: ...swordsmanship untested in battle is like the art of swimming mastered on land.

A: I would also be interested to hear why you want to develop your own auth solution.
But putting that aside, there is an open source project that does exactly what you ask - Identity Server. You can check out their source code or fork it and build something on top of it.
Also, please check "identigral" answer on various docs.


text:
Q: Finding an equation to the surface S that is bounded between $z=x^2-y^2$ inside the cylinder $x^2+y^2=1$ How to find a parametric equation to the surface S that is bounded between $z=x^2-y^2$ inside the cylinder $x^2+y^2=1$, and while C be the the Boundary of that surface.
While reading the solution of one of the questions they said that a parametric equation for surface S is:
$\vec r(\rho$,$\theta$) = $\rho$cos$\theta$$\hat i$ +  $\rho$sin$\theta$$\hat j$ + $\rho^2$cos$2\theta$$\hat k$   while $0\le$ $\theta \le 2\pi$ , $0\le$ $\rho$ $ \le 1$
and
a parametric equation for curve/boundary C is:
$\vec r(\theta$)=  cos$\theta$$\hat i$ + sin$\theta$$\hat j$ + cos$2\theta$$\hat k$  while $0\le$ $\theta \le 2\pi$
but how did they reach these equations? I would appreciate any kind of help.

A: any point inside the cylinder $x^2 + y^2 = 1$ can be represented by $$x = r \cos t, y = r \sin t,\space  0 \le r \le 1, 0 \le t \le 2\pi.$$  then $$z = x^2 - y^2 = r^2 (\cos^2 t - \sin^2 t) = r^2 \cos (2t). $$