text:
Q: How to debug angular [$injector:modulerr] errors I have a growing angular application. From time to time, I mess things up and get an error of the type:
[$injector:modulerr] Failed to instantiate module App due to:

It is often very difficult to find the error based on the error message, especially if there are many files with various controllers etc.
Is there a way to debug these errors in either Chrome or Firefox ?

A: Just to illustrate.
This is what you get when you load minified version of Angular (angular.min.js):
Error: $injector:modulerr
Module Error
Failed to instantiate module eduApp due to:
Error: [$injector:modulerr] http://errors.angularjs.org/1.4.7/$injector/modulerr?p0=e...)
    at Error (native)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:6:416
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:38:184
    at m (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:7:322)
    at h (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:37:275)
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:37:444
    at m (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:7:322)
    at h (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:37:275)
    at fb (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:41:35)
    at d (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.7/angular.min.js:19:463

And this is what you get when you use unminified version (angular.js):
Error: $injector:nomod
Module Unavailable
Module 'ui.bootstrap' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

The first error is really painful to solve. The second one is much more easier.
Happy coding!

A: Minified AngularJS gives me unreadable errors

... Use the unminified version in development to make it easier to debug.

A: I found the following approach to be somewhat helpful.  Use local angular.js file so you can modify it:

*

*Open your angular.js file

*Go to lines with the following code:
message = message + '\nhttp://errors.angularjs.org/1.3.5/' +
  (module ? module + '/' : '') + code;

*After these two lines add:
console.log(message);

Taken from here: http://www.chrisgmyr.com/2014/08/debugging-uncaught-error-injectormodulerr-in-angularjs/


text:
Q: Create SVG With Text only, width and height based on text size using librsvg? I am trying to create an svg with one single text element. The size of the svg should be determined solely by the font size of the text, and it should fit the text perfectly. The closest I have come to what I am looking for is this:
             txt_img = Vips::Image.svgload_buffer %(
              <svg height="#{font_size}*2">
                <g>
                <text
                    font-family="some value"
                    font-size="#{font_size}"
                    font-weight="some value"
                    fill="some value"
                    fill-opacity="some value"
                    stroke="some value"
                    stroke-width="some value"
                    dominant-baseline="hanging"
                    text-anchor="start"
                    x="0"
                    y="#{font_size}"
                  >
                  #{txt}
                  </text>
                </g>
               </svg>
             )

But, as you can see in the attached image, the bottom of the text gets cut off, particularly the letters that hang below the baseline. How can I size the svg to perfectly fit the text? Since this is not being rendered in a browser environment, the solution must not involve css.
Also note that the output is being rendered with Vips, which does not offer an svg saver option, which is why the output is in png format.
[!][text rendered to png][1]][1]
[1]: https://i.stack.imgur.com/Bx7gJ.png

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I make certain functions that can be subscribed to without events (like Unity does)? In Unity, when you make a new MonoBehaviour class, it comes with a whole load of functions that you can hook onto easily - for example Update(), FixedUpdate() and Awake(). I'm making my own component-entity system and I'm trying to add a range of functions that can easily be hooked onto by the components I create. I've made my base class abstract and have Update and Draw as abstract functions that can then be inherited. This works fine, apart from the fact that all my components have to implement all of those functions; something like Initialize would be useful for some components but not others and I'm not sure how to emulate this behaviour.
Is it done with reflection?

A: Instead of defining your methods as abstract, you can define them as virtual and override them only when necessary.
class BaseComponent : MonoBehaviour
{
    public virtual void OnAwesomeEvent()
    {
        // do nothing or implement default behaviour
    }
}

class ShinyComponent : BaseComponent
{
    public override void OnAwesomeEvent()
    {
        Debug.Log("I've been waiting for this!");

        // If you need the default implementation you can call it with
        // base.OnAwesomeEvent()
    }
}

class LazyComponent : BaseComponent
{
    // I do nothing and no one cares
}

A: Disclaimer:

I'm making my own component-entity system and I'm trying to add a
  range of functions that can easily be hooked onto by the components I
  create.

I don't particularly like the unity's "magic methods" approach on this. I think that implementing interfaces or overriding virtual functions could be often a cleaner solution.
I used Unity's approach once, for an AI plugin which should call user defined methods without forcing to extend a class (basically because I had to avoid recompiling the code while modifying AI's behaviours)
In any case, for what concern the implementation:
1) Send Message
SendMessage use a pure reflection implementation: the target method name can be know only when SendMessage is called.
This seems convenient (and might be perhaps, I still never used nor I felt the need to), but has several drawbacks:

*

*Performance: reflection is costly (check some benchmarks, it ends up to be hundred of times slower than a direct method call)

*Not Type Safe: can't check at compile time if the argument passed is of the right type.

2) MonoBehaviour Messages
Those methods (like Awake, Update, OnCollision, ...) are slightly different, because Unity can know the signature and compile the delegates. (I'm not sure of the implementation, but I've done something similar).
The way to go, to implement something similar is well described in this article.
Basically you use reflection only in initialization, but once obtained the MethodInfo, you can compile the method as a delegate with Delegate.CreateDelegate.
Results:

*

*You still use reflection, but only in initialization

*Once compiled, the delegate is almost as fast as a standard method call (or event).


text:
Q: ng-repeat + Filter + ng-switch I have the following ng-repeat that gets 3 items at a time:

                                  {{posts[(posts.indexOf(post))]}}

                                  {{posts[(posts.indexOf(post + 1))]}}

                                  {{posts[(posts.indexOf(post + 2))]}}

My problem is that if the search or customFilter apply to one post, I will get all three items even though the second and third ones don't apply.
PLNKR
In that PLNKR if you search for "1", you will get three items instead of just one.
Is there a way to filter one item at a time as opposed to all 3 at a time?

A: Store the filtered values in a variable like this
post in filteredPosts = (posts | filter:search | filter:customFilter)

the use the filteredPosts.length plus ng-show / ng-hide to hide the extra items
Edit: Apparently just using a filtered variable, and using it to get the posts in the {{}} (like filteredPosts[(filteredPosts.indexOf(post))]) works just fine.
Is this what you want? Plunker


text:
Q: Java: Create method to print all multiples of 3 between 1 and n? So the question is asking to create a method that will take an integer x as a parameter and print out all integers from 0->x that are multiples of three.
I can print out the number of times three divides x like so:
  public int Threes(int x){

    int i = 0;
    for(int counter = 1; counter <= x; counter++){
        if (counter % 3 ==0){
            i ++;
        }

    }
        return i;

but I'm not sure how to print out each multiple of 3!?

A: for(int counter = 1; counter <= x; counter++){
    if (counter % 3 ==0){
        System.out.println(counter);
    }

}

A: An even quicker approach would be to increment by 3
public void Threes(int x) {
    for (int counter = 3; counter <= x; counter = counter + 3) {
        System.out.println(counter);
    }
}

This loop will jump right to the multiples of 3, instead of counting every single number and having to do a modulo check for each iteration. Since we know that 1 and 2 are not multiples of 3, we just skip right to 3 at the beginning of the loop. If the input happens to be less than 3, then nothing will be printed. Also, the function should be void since you're printing instead of returning anything.
(Your title says 1 to n, but your question says 0 to n, so if you actually need from 0 to n, then change the declaration of counter to int counter = 0;)

A: Jason Aller wow that was so simple and elegant. This one builds on it by counting down from 300 to 3, by 3's.
public class byThrees {

public static void main(String[] args) {
    for (int t = 100; t >= 0; t--) {
        System.out.println(t*3);

A: Best practice using the For-loop in Java.
public class MultiplesOfThree {

    public static void main(String []args){
        for (int m = 1; m<=12; m++){
            System.out.println(m*3);
        }
    }
}


text:
Q: How do I spectate a game I am in? I know that players can spectate other players matches if they are friends with them. What I want to know is, how I can spectate a game while in that game itself.
For instance, sometimes I see someone with a very cool hero skin that I want to see what it looks like in combat, so I'd like to spectate them. Or I'd like to spectate a player who looks like they know what they're doing and has good skills so I can learn from them.
How can I spectate a match in a game I am currently in?

A: According to this,

Considering it's an online multiplayer game, it's surprising to see at its launch lacks a dedicated spectator mode. But Blizzard does make it possible to spectate in Overwatch, although it isn't as convenient as a dedicated spectator mode.
One way to spectate a game is to attempt to join a game a friend is currently playing. If the game is full, you'll be forced to sit on the sidelines, but as a result, you can spectate your friend as well as all of the other players in the match. If your friend continues with the same group into another match, and there's no vacancies, you'll continue to sit in the new game as a spectator.
Another way to spectate a game is by joining a new game yourself which also has all team spots filled. When this happens, you'll be forced to enter spectator mode, although as soon as a spot frees up, you'll be thrown into the action. Unfortunately, there's no way to back out of the game to re-enter spectator mode.

and this is inline with what I have experienced through in-game testing.

A: Currently there is no official way to spectate a game, but it is being implemented soon. According to Jeff Kaplan here.
Although if you die while in game, I believe you can switch between watching the kill cam and other players on your team, which would be the closest thing to spectating, although you'd only have it for 6 seconds.


text:
Q: How to restrict access to file using htaccess How do I use the htaccess file on my ColdFusion server? I do not know how to use htaccess on my ColdFusion server to prevent direct access to files of attachment folder.
I am using ColdFusion 10 and have source code in the root directory of the ColdFusion server. I want to restrict direct access to files that are available in the Attachment folder. I placed two files inside this Attachment folder: .htaccess and .htpasswd.
. htaccess:
AuthUserFile "/StagingTicketSystem/Attachments/.htpasswd"
AuthName "Please Log In" AuthType Basic <Limit GET POST> required vaid-user </Limit>

.htpasswd:
admin:1234 root:4321


text:
Q: Calling a REST API from Transaction Processor Functions I'm trying to get data from the open sky api through a transaction processor function. I have been looking at the documentation: https://hyperledger.github.io/composer/integrating/call-out
Since I'm doing a GET request to this API I don't need to send any data with the request. This is why I have set the parameter data to an empty object:
var data = {};
But when I run this I get the following error:

Error: Serializer.toJSON only accepts instances of Resource.

This error is because the toJSON(resource, options) function is expecting a resource. This can be seen in the following link:
https://hyperledger.github.io/composer/jsdoc/module-composer-common.Serializer.html#toJSON__anchor
I also looked at the code for the post() function, which I will copy below: On line 224:
https://hyperledger.github.io/composer/jsdoc/composer-runtime_lib_api.js.html
/**
     * Post a typed instance to a HTTP URL
     * @method module:composer-runtime#post
     * @param {string} url The URL to post the data to
     * @param {Typed} typed The typed instance to be posted. The instance will be serialized to JSON.
     * @param {object} options The options that are passed to Serializer.toJSON
     * @return {Promise} A promise. The promise is resolved with a HttpResponse
     * that represents the result of the HTTP POST.
     * @public
     */
    this.post = function post(url, typed, options) {
        const method = 'post';
        LOG.entry(method, url, typed);
        const data = serializer.toJSON(typed, options);
        LOG.debug(method, typed.getFullyQualifiedType(), data);

        return httpService.post(url, data)
            .then((response) => {
                LOG.exit(method);
                return Promise.resolve(response);
            });
    };

But I could see any way around it..
My code:
    /**
 * Transaction to allow parties to Monitor planes
 * @param {org.****.MonitorPlane} monitorPlane
 * @transaction
 */
function monitorPlane(monitorPlane){
    var NS = 'org.****';
    plane = monitorPlane.plane
    var location
    return location = getLocation()
    .then(function(){
        plane.lat = lat
        plane.long = long
        if(plane.monitorPlane){
            plane.monitorPlane.push(monitorPlane)
        }else{
            plane.monitorPlane = [monitorPlane]
        }
    }).then(function(){
        return getAssetRegistry(NS + '.Plane')
    }).then(function(planeRegistry){
        return planeRegistry.update(plane);
    });

function getLocation(){

    var url = 'https://opensky-network.org/api/states/all?time=1458564121&icao24=3c6444';
    var data = {};

    return post(url,data)
      .then(function (resp) {
          console.log(resp);
          return resp;
    })
    .then(function(data) {
        console.log(data);

        lat = data.states[0][5]
        long = data.states[0][6]
        lat = lat.toString()
        long = long.toString()
        location = [lat,long]
        return location
      })
      .catch((err) => {
          console.log(err);
      });
    }
}

Is it possible to do this from a transaction processor function?

A: The post(url, data) usage only works if data is a resource (concept, transaction, asset or participant) in your modelling .cto file.
Have you tried using an empty concept? Maybe that will work (just a guess)
Ref: https://hyperledger.github.io/composer/integrating/call-out.html
I think you need to consider if the data you are trying to pull can be done at the client application level and then update onto the blockchain, which could be much easier.
You may also consider ways you can put a server in the middle to transform your HTTP post request to a get request for open sky.


text:
Q: How to find triangle height? I need to know the height ($h$) of a triangle with two unknown angles ($\alpha$ and $\beta$) and the known length of two sides $AB$ and $BC$.

Is it possible to have that value of $h$ (height)?

A: Your post says that the angles $\alpha$ and $\beta$ are unknown.  I assume this means that only $AB$ and $BC$ are known.  Remove the line $AC$ from your diagram. Then you can turn the line $BC$ around the "hinge" at $B$, changing the height.  So the answer is that the height cannot be determined.
The only thing you can say is that the height is greater than $0$ and less than or equal to $BC$.

A: If you let D denote the point of intersection of the perpendicular point C to segment AB (so that the length of CD = h), then we have a right triangle BCD ($\angle BDC = 90^\circ = \pi/2$ radians),
then you have that $\sin(\beta)$ = opposite side / hypotenuse = $\displaystyle \frac{h}{|BC|}$
Then solve for h: $h = \sin(\beta)\times |BC|$.
Since you have the values for $\beta$ and for $|BC|$ (the length of segment BC), simply compute h at those values.
Note: this answer was posted when the question stated $\alpha, \beta$ were known.
With only two sides of the triangle known (and that the line perpendicular to AB, and intersecting C, forms divides ABC into two right triangles), we still don't have enough information to determine height (h).
See Americo's comment above for a list of values (side lengths and/or angles) necessary to define a triangle. (And his subsequent comment re: "case 4")!

A: From the definition of $\sin$ function, $h = |BC|\sin\beta$.
Even if you know only $|AB| = a$ (which seems to be the case from your picture) then:
$h = ka\cos\alpha$ and $h = (1-k)a\cos\beta$ for some $k<1$. This $k$ is a proportion in which $h$ divides $AB$. So, we have to equation on two variables: Jejeje
$$
k = \frac{\cos\beta}{\cos\alpha+\cos\beta}
$$
and
$$
h = \frac{\cos\alpha\cos\beta}{\cos\alpha+\cos\beta}a.
$$


text:
Q: C# interaction with browser for simple check Alright so I got a big project which I will start from the beginning. I've only done PHP and other web languages (Javascript, Jquery, node) and I have no experience with any of the languages mentioned above.
What I need to achieve is to have a small program written in C# that will make a call to my website, and the website will simply give me an "Okay" if it did recieve the message.
This simply makes the browser checks if a certain local program is running or not.
Where would I need to start to achieve such thing?


text:
Q: Finding volume of a solid of revolution I need to find the volume of the solid that is formed when the (x>0, y< -1) region of the curve y= -1/x is rotated about the y-axis.
If I'm correct, this volume can be calculated by:
Evaluating the definite integral (upper bound = -1, lower bound = -infinity) of π*(1/y²) with respect to y.
In evaluating this integral, I got up to:
Volume = (-π/1) - (-π/infinity)
       = -π
But how can a volume be a negative value?
Please let me know if I've done anything wrong, and explain how to get the correct answer if you can.
Thank you x

A: (-1/y²) should instead be (-1/y)². That should fix it.


text:
Q: Is it possible to have screenshots in any other section rather than the screenshots section? At WordPress.org plugin, is it possible to have screenshots in any other section rather than the screenshots section? For example. Can I create a section called "Manual" and then have some screenshots there?

A: In the readme.txt file, the "Screenshots" section is a special section.  The WordPress plugin repository checks your Assets folder (or the folder containing readme.txt) for images named in a certain way and corresponds them to the entries in this section.  I don't believe it is possible to attach images in the same way in any other section.
Markdown does provide a syntax for including images:
![Alt text](/path/to/img.jpg)

However, I tried to make this work in the WordPress readme.txt validator, and I couldn't.  It looks like the plugin repo strips these out, but I haven't actually tried it in a plugin's readme.txt and committed it to see what would happen.


text:
Q: Not able to display checkbox in multiple select dropdown I have a select dropdown with multiselect checkbox option
Initial View

After selecting value

Selection of value is working fine, but in the first image the checkbox are not visible
I have used bootstrap select multiple select box  functionality.
code:
<select class="form-control fruits selectpicker" multiple  id="fruits" name="fruits" title="fruits">
    <option value="">apple </option>
    <option value="banana">banana</option>
    <option value="orange">orange</option>
    <option value="grapes">grapes</option>
  </select>

I want that in the first image the checkbox should be visible, can anyone tell me how to display it

A: I had the same problem with selectpicker.
Here is a solution:
<script src="https://kit.fontawesome.com/yourcode.js"></script>

....
.dropdown-item:not(.selected) span.check-mark::before {
    content: "\f0c8" !important;
    border:0;
    transform: rotate(0);
}
.bootstrap-select.show-tick .dropdown-item:not(.selected) span.check-mark {
    position: absolute;
    display: inline-block;
    right: 15px;
    top: 5px;
}

....
$('#selector').selectpicker({iconBase: 'fontawesome',tickIcon: 'far fa-check-square'});


text:
Q: CSS Background-Blend-Mode over two Elements Lets assume I have a div with a Gradient applied as a background-property.
I now want to overlay a black PNG (of smaller size) and set the PNG to have a background-blend-mode of overlay. Unfortunately I have no idea on how to achieve this.
I know I can have a working background-blend-mode when I render the Gradient into the CSS of the Div with the PNG image like:
background: url(../img/plus.png), linear-gradient(to bottom, #24cae4 0%, #1f81e3 100%);
background-blend-mode: overlay;

This however results in the Gradient being as small as the actual PNG, which is not a desired effect, like this:

What I want to achieve is this with pure CSS (if possible):

Here a Codepen to illustrate what I'm trying to do: http://codepen.io/anon/pen/zxOXGP
Notice the Black Icon. I wanna overlay this.

A: Try using mix-blend-mode instead of background-blend-mode and switch to simple text for the plus-sign or a webfont for more custom figures.
Example Codepen of the below:

.placeholder {
  position: relative;
  width: 400px;
  height: 300px;
  background-image: -moz-linear-gradient(#ff0000, #0000ff);
  background-image: -webkit-linear-gradient(#ff0000, #0000ff);
  background-image: linear-gradient(#ff0000, #0000ff);
}
.center {
  position: absolute;
  top: 25%;
  width: 100%;
  font-size: 120px;
}
.center span {
  display: block;
  text-align: center;
  color: red;
  mix-blend-mode: screen;
}

+

A: The gradient sandwich
Ingredients

*

*The :before forms the bottom z-layer with z-index: 1, it is full opacity

*The .content div forms the filling, central z-layer, with z-index: 2. It needs position: relative to take its z-index.

*The :after forms the top z-layer with z-index: 3 and completes our lunch item. It is half opacity.
This is the tasty result:

Full Example
I have removed all but the standard CSS3 gradient for simplicity. View in a supporting browser.

.gradient {
  position: relative;
  height: 200px;
  padding: 20px;
}
.gradient:before,
.gradient:after {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  content: '';
  display: block;
  background-size: 100%;
  background-image: linear-gradient(to bottom, #24cae4 0%, #1f81e3 100%);
  opacity: 0.5;
}
.gradient:before {
  opacity: 1;
  z-index: 1;
}
.gradient:after {
  z-index: 3;
}
.overlayed_image {
  position: relative;
  width: 64px;
  height: 64px;
  display: block;
  margin: auto;
  background-size: contain;
  background-repeat: no-repeat;
  background-position: 50% 50%;
  background-image: url(http://cdn.flaticon.com/png/256/9029.png);
}

.content {
  position: relative;
  z-index: 2;
}

    You can see me!


text:
Q: Why does Netbeans Ant compile with correct jar but builds with old jar? I have a project "A" that has another project "B"  in it's libraries.
Netbeans compiles project "A" and says there are no errors but when I go to clean and build project "A" goes to an old version of project "B".
I have cleaned and built project "B" and then cleaned and build project "A" but "A" still fails thinking it is using the old "B".
I am trying to figure out why Netbeans' Ant is compiling with the correct Project "B"-dist/jar but is building with the old Project "B" jar.
None of the other jars in "A"s library have "B" in their library.

A: The class-path specified in your build.xml is separate from the project class-path in Netbeans. Apparently the latter is correct and the former is wrong. You can fix it by editing your build.xml.

A: The way I found to solve this problem was to right click the library folder in netbeans and go to properties.  There was several projects and jars listed in red and that were not displayed in navigation I removed those then figured out which of those jars/projects I needed and added them back to project "A"s library.


text:
Q: ::before wrapper element blocks input ::before element of style .betInfo_rou blocks input area. I don't have access to the input because ::before over everything. When I delete it, it works. How can I fix this? Before displays background for the whole wrap.
.betInfo_rou{
  grid-area: 2/1/3/2;
  position: relative;
  &::before{
    display: inline-block;
    position: absolute;
    background: linear-gradient(
      90deg,
      rgba(255, 255, 255, 0.1) 0%,
      rgba(255, 255, 255, 0) 71.71%
      );
    content: '';
    width: 100%;
    height: 100%;
    left: -68 * $vert-1;
  }
 }

Bet

            <input
              type="text"
            />

A: Use pointer-events: none to make browsers ignore mouse and touch interactions on the pseudoelement and pass them to other elements.

.betInfo_rou {
  grid-area: 2/1/3/2;
  position: relative;
}

.betInfo_rou::before {
  display: inline-block;
  position: absolute;
  background: linear-gradient(
    90deg,
    rgba(255, 255, 255, 0.1) 0%,
    rgba(255, 255, 255, 0) 71.71%
  );
  content: '';
  width: 100%;
  height: 100%;
  left: -68 * $vert-1;
  pointer-events: none;
}

Bet

        <input type="text" />


text:
Q: Curl command is not freeing up server resources GoLang I am running a GO program in which I need to run a curl command to call some other url. After initiating curl command I dont need to wait for it to complete. Due to this, It is not freeing server resources and hence I need to restart the server every morning.
Here is the code:
var cmd *exec.Cmd
url := "https://www.google.com/"
cmd = exec.Command("curl", "-H", "Connection: close", "--no-keepalive", "--http2", url)
var out bytes.Buffer
var stderr bytes.Buffer
cmd.Stdout = &out
cmd.Stderr = &stderr
err := cmd.Start()
return err

From the above code, as you can see I only start the command but didn't wait for it to complete because I don't need to delay the program due to curl command.
Other Tries:
I have tried using Wait() along with Start() and Run() functions but all of these resulted in delay.
UPDATED:
I am running ps -faux command. its displaying following:
root     1109561  0.0  0.0      0     0 ?        Z    May26   0:00  \_ [curl] <defunct>
root     1109729  0.0  0.0      0     0 ?        Z    May26   0:00  \_ [curl] <defunct>
root     1157006  0.0  0.0      0     0 ?        Z    May26   0:00  \_ [curl] <defunct>

When I restart the server, then no such log found. So I guess curl is being an process in the history even after completing its job.
So is there a way to fulfill the requirement with freeing up resources ?

A: replace err := cmd.Start() with cmd.Start(); err := cmd.wait();

I have tried using Wait() along with Start() and Run() functions but all of these resulted in delay.

if you don't want to wait, run it in a dedicated thread (or goroutine as its called in Go), and have the thread wait while your main thread doesn't.


text:
Q: if query is not update I would like to know best way to make my query's into a if statement. because I would like to use one function for my codeigniter edit main function,
So it combines both query's and makes it if query is not a update then is a insert way is best way
public function addUserGroup($data) {
    $this->db->query("INSERT INTO " . $this->db->dbprefix . "user_group SET
    name = " . $this->db->escape($data['name']) . ",
    permission = " . (isset($data['permission']) ? $this->db->escape(serialize($data['permission'])) : '') . " ");
}

public function editUserGroup($user_group_id, $data) {
    $this->db->query("UPDATE " . $this->db->dbprefix . "user_group SET
    name = " . $this->db->escape($data['name']) . ",
    permission = " . (isset($data['permission']) ? $this->db->escape(serialize($data['permission'])) : '') . " WHERE user_group_id = '" . (int)$user_group_id . "'");
}

A: try to save values in variable  and pass var to query and try to add proper quoting to query vars
public function addUserGroup($data) {
  $perm = (isset($data['permission']) ? $this->db->escape(serialize($data['permission'])) : '');
  $this->db->query("INSERT INTO " . $this->db->dbprefix . "user_group SET name = '" . $this->db->escape($data['name']) . "', permission = '" .$perm. "' ");

}

A: You could do this with one query pretty neat:
"INSERT INTO " . $this->db->dbprefix . "user_group SET name = " .
$this->db->escape($data['name']) . ",
permission = " . (isset($data['permission']) ? $this->db->escape(serialize($data['permission'])) : '') .
" ON DUPLICATE KEY UPDATE ".
$this->db->dbprefix . "user_group SET name = " .
$this->db->escape($data['name']) . ",
permission = " . (isset($data['permission']) ? $this->db->escape(serialize($data['permission'])) : '') . "
WHERE user_group_id = '" . (int)$user_group_id . "'");

The only thing required is a primary key on the table

A: You can set if/else condition using "user_group_id". I think this must be coming from post array like $this->input->post('user_group_id').
So you can create one function which will check these conditions like below:
function my_function(){
   if($this->input->post('user_group_id')){
    // call update query
   }else{
    // call insert query
   }
}


text:
Q: Extending express.Request in typescript I can easily extend express.Request in typescript, e.g.:
interface MyRequest extends express.Request {
    userId: string;
}

However, if I write a middleware function that uses it, e.g.:
const myMiddlewareFn = (req: MyRequest, res: express.Response) => {
    req.userId; // <-- this works as a string
}
app.get('/user', myMiddlewareFn) // <-- this does NOT type-check because MyRequest is more narrow than express.Request.

I see a lot of discussions on how to extend express.Request. How can I do it in a way that will typecheck correctly in my route?
Currently I'm doing something like this:
/**
 * @param allowedRoles see HasuraCustomClaims
 * @param handlerFn the final business logic
 * @returns an array of middleware, correctly typed for the handlerFn
 */
export function addApiAuthMiddleware(
    allowedRoles: string[],
    ...handlerFns: (
        | ((req: OTApiAuthorizedRequest, res: Response) => Promise<void>)
        | ((req: OTApiValidatedAndAuthorizedRequest<any>, res: Response) => Promise<void>)
    )[]
): express.RequestHandler[] {
    return [
        decodeIdToken,
        guardRequestHandler(createRoleAuthMiddleware(allowedRoles)),
        ...handlerFns.map((handlerFn) => guardRequestHandler(handlerFn)),
    ];
}

/**
 * This typecasting is a *little* jank.
 *
 * @param middlewareOrHandlerFn either api middleware or a final api handler function
 * @returns
 */
export function guardRequestHandler<T extends Request>(
    middlewareOrHandlerFn:
        | ((req: T, res: Response, next: express.NextFunction) => Promise<void>)
        | ((req: T, res: Response) => Promise<void>),
): express.RequestHandler {
    return (middlewareOrHandlerFn as unknown) as express.RequestHandler;
}

// this below type-checks
app.get('/user', ...addApiAuthMiddleware(['admin'], userHandlerFn));

Is there a better way?

A: You can change app.get('/user', myMiddlewareFn) to app.get('/user', myMiddlewareFn as any) or app.get('/user',  myMiddlewareFn) these are identical and both are compile-time casts. Not runtime.

A: Set your custom attributes are optional attributes.
interface MyRequest extends express.Request {
    userId?: string; // userId is optional
}

In your middleware or request handler, you always need to make sure that the userId is not undefined.
const myMiddlewareFn = (req: MyRequest, res: express.Response) => { // missing next function ?
    if (req.userId) {
        // do something with userId
        req.userId; // <-- this works as a string
    }
}


text:
Q: SPI on Beagleboard Black I've been trying to make the serial communication work on my BBB for days now and I am running out of ideas.
When I use just the BBB and connect MISO/MOSI I get the signal transfer on MOSI, SCLK and CS (MISO is mainly at high level). However, when I connect the lines to my slave part it does not work. I checked the signals on the oscilloscope and they seem fine and the part which I am using as the slave is working well when I set it in parallel mode, so I believe some programming or configuration must be wrong.
This is basically what I do:
config-pin P9.17 spi_cs
config-pin P9.18 spi
config-pin P9.21 spi
config-pin P9.22 spi_sclk
python
from Adafruit_BBIO.SPI import SPI
spi = SPI(1,0) #I would expect SPI(0,0) here, but I get the signal on the above configured ports

Then I set the configurations (already tried in many ways):
spi.mode = 0
spi.cshigh = False
spi.msh = 10500000
spi.bpw = 16
spi.lsbfirst = False

After that I open it and try to send data:
spi.open(1,0)
spi.xfer2([1,254])

If anyone is interested, I am trying to program the LMH6517 as slave and I already tried to ask about this at the TI forum here:
https://e2e.ti.com/support/amplifiers/f/14/t/751415
Oscilloscope images:
CS and SCLK
MOSI and SCLK
MISO and SCLK
Thank you,
JPL


text:
Q: Algorithm to generate a crossword Given a list of words, how would you go about arranging them into a crossword grid?
It wouldn't have to be like a "proper" crossword puzzle which is symmetrical or anything like that: basically just output a starting position and direction for each word.

A: Why not just use a random probabilistic approach to start with. Start with a  word, and then repeatedly pick a random word and try to fit it into the current state of the puzzle without breaking the constraints on the size etc.. If you fail, just start all over again.
You will be surprised how often a Monte Carlo approach like this works.

A: Here is some JavaScript code based on nickf's answer and Bryan's Python code. Just posting it in case someone else needs it in js.
function board(cols, rows) { //instantiator object for making gameboards
this.cols = cols;
this.rows = rows;
var activeWordList = []; //keeps array of words actually placed in board
var acrossCount = 0;
var downCount = 0;

var grid = new Array(cols); //create 2 dimensional array for letter grid
for (var i = 0; i < rows; i++) {
    grid[i] = new Array(rows);
}

for (var x = 0; x < cols; x++) {
    for (var y = 0; y < rows; y++) {
        grid[x][y] = {};
        grid[x][y].targetChar = EMPTYCHAR; //target character, hidden
        grid[x][y].indexDisplay = ''; //used to display index number of word start
        grid[x][y].value = '-'; //actual current letter shown on board
    }
}

function suggestCoords(word) { //search for potential cross placement locations
    var c = '';
    coordCount = [];
    coordCount = 0;
    for (i = 0; i < word.length; i++) { //cycle through each character of the word
        for (x = 0; x < GRID_HEIGHT; x++) {
            for (y = 0; y < GRID_WIDTH; y++) {
                c = word[i];
                if (grid[x][y].targetChar == c) { //check for letter match in cell
                    if (x - i + 1> 0 && x - i + word.length-1 < GRID_HEIGHT) { //would fit vertically?
                        coordList[coordCount] = {};
                        coordList[coordCount].x = x - i;
                        coordList[coordCount].y = y;
                        coordList[coordCount].score = 0;
                        coordList[coordCount].vertical = true;
                        coordCount++;
                    }

                    if (y - i + 1 > 0 && y - i + word.length-1 < GRID_WIDTH) { //would fit horizontally?
                        coordList[coordCount] = {};
                        coordList[coordCount].x = x;
                        coordList[coordCount].y = y - i;
                        coordList[coordCount].score = 0;
                        coordList[coordCount].vertical = false;
                        coordCount++;
                    }
                }
            }
        }
    }
}

function checkFitScore(word, x, y, vertical) {
    var fitScore = 1; //default is 1, 2+ has crosses, 0 is invalid due to collision

    if (vertical) { //vertical checking
        for (i = 0; i < word.length; i++) {
            if (i == 0 && x > 0) { //check for empty space preceeding first character of word if not on edge
                if (grid[x - 1][y].targetChar != EMPTYCHAR) { //adjacent letter collision
                    fitScore = 0;
                    break;
                }
            } else if (i == word.length && x < GRID_HEIGHT) { //check for empty space after last character of word if not on edge
                 if (grid[x+i+1][y].targetChar != EMPTYCHAR) { //adjacent letter collision
                    fitScore = 0;
                    break;
                }
            }
            if (x + i < GRID_HEIGHT) {
                if (grid[x + i][y].targetChar == word[i]) { //letter match - aka cross point
                    fitScore += 1;
                } else if (grid[x + i][y].targetChar != EMPTYCHAR) { //letter doesn't match and it isn't empty so there is a collision
                    fitScore = 0;
                    break;
                } else { //verify that there aren't letters on either side of placement if it isn't a crosspoint
                    if (y < GRID_WIDTH - 1) { //check right side if it isn't on the edge
                        if (grid[x + i][y + 1].targetChar != EMPTYCHAR) { //adjacent letter collision
                            fitScore = 0;
                            break;
                        }
                    }
                    if (y > 0) { //check left side if it isn't on the edge
                        if (grid[x + i][y - 1].targetChar != EMPTYCHAR) { //adjacent letter collision
                            fitScore = 0;
                            break;
                        }
                    }
                }
            }

        }

    } else { //horizontal checking
        for (i = 0; i < word.length; i++) {
            if (i == 0 && y > 0) { //check for empty space preceeding first character of word if not on edge
                if (grid[x][y-1].targetChar != EMPTYCHAR) { //adjacent letter collision
                    fitScore = 0;
                    break;
                }
            } else if (i == word.length - 1 && y + i < GRID_WIDTH -1) { //check for empty space after last character of word if not on edge
                if (grid[x][y + i + 1].targetChar != EMPTYCHAR) { //adjacent letter collision
                    fitScore = 0;
                    break;
                }
            }
            if (y + i < GRID_WIDTH) {
                if (grid[x][y + i].targetChar == word[i]) { //letter match - aka cross point
                    fitScore += 1;
                } else if (grid[x][y + i].targetChar != EMPTYCHAR) { //letter doesn't match and it isn't empty so there is a collision
                    fitScore = 0;
                    break;
                } else { //verify that there aren't letters on either side of placement if it isn't a crosspoint
                    if (x < GRID_HEIGHT) { //check top side if it isn't on the edge
                        if (grid[x + 1][y + i].targetChar != EMPTYCHAR) { //adjacent letter collision
                            fitScore = 0;
                            break;
                        }
                    }
                    if (x > 0) { //check bottom side if it isn't on the edge
                        if (grid[x - 1][y + i].targetChar != EMPTYCHAR) { //adjacent letter collision
                            fitScore = 0;
                            break;
                        }
                    }
                }
            }

        }
    }

    return fitScore;
}

function placeWord(word, clue, x, y, vertical) { //places a new active word on the board

    var wordPlaced = false;

    if (vertical) {
        if (word.length + x < GRID_HEIGHT) {
            for (i = 0; i < word.length; i++) {
                grid[x + i][y].targetChar = word[i];
            }
            wordPlaced = true;
        }
    } else {
        if (word.length + y < GRID_WIDTH) {
            for (i = 0; i < word.length; i++) {
                grid[x][y + i].targetChar = word[i];
            }
            wordPlaced = true;
        }
    }

    if (wordPlaced) {
        var currentIndex = activeWordList.length;
        activeWordList[currentIndex] = {};
        activeWordList[currentIndex].word = word;
        activeWordList[currentIndex].clue = clue;
        activeWordList[currentIndex].x = x;
        activeWordList[currentIndex].y = y;
        activeWordList[currentIndex].vertical = vertical;

        if (activeWordList[currentIndex].vertical) {
            downCount++;
            activeWordList[currentIndex].number = downCount;
        } else {
            acrossCount++;
            activeWordList[currentIndex].number = acrossCount;
        }
    }

}

function isActiveWord(word) {
    if (activeWordList.length > 0) {
        for (var w = 0; w < activeWordList.length; w++) {
            if (word == activeWordList[w].word) {
                //console.log(word + ' in activeWordList');
                return true;
            }
        }
    }
    return false;
}

this.displayGrid = function displayGrid() {

    var rowStr = "";
    for (var x = 0; x < cols; x++) {

        for (var y = 0; y < rows; y++) {
            rowStr += "" + grid[x][y].targetChar + "	";
        }
        $('#tempTable').append("
" + rowStr + "
");
        rowStr = "";

    }
    console.log('across ' + acrossCount);
    console.log('down ' + downCount);
}

//for each word in the source array we test where it can fit on the board and then test those locations for validity against other already placed words
this.generateBoard = function generateBoard(seed = 0) {

    var bestScoreIndex = 0;
    var top = 0;
    var fitScore = 0;
    var startTime;

    //manually place the longest word horizontally at 0,0, try others if the generated board is too weak
    placeWord(wordArray[seed].word, wordArray[seed].displayWord, wordArray[seed].clue, 0, 0, false);

    //attempt to fill the rest of the board
    for (var iy = 0; iy < FIT_ATTEMPTS; iy++) { //usually 2 times is enough for max fill potential
        for (var ix = 1; ix < wordArray.length; ix++) {
            if (!isActiveWord(wordArray[ix].word)) { //only add if not already in the active word list
                topScore = 0;
                bestScoreIndex = 0;

                suggestCoords(wordArray[ix].word); //fills coordList and coordCount
                coordList = shuffleArray(coordList); //adds some randomization

                if (coordList[0]) {
                    for (c = 0; c < coordList.length; c++) { //get the best fit score from the list of possible valid coordinates
                        fitScore = checkFitScore(wordArray[ix].word, coordList[c].x, coordList[c].y, coordList[c].vertical);
                        if (fitScore > topScore) {
                            topScore = fitScore;
                            bestScoreIndex = c;
                        }
                    }
                }

                if (topScore > 1) { //only place a word if it has a fitscore of 2 or higher

                    placeWord(wordArray[ix].word, wordArray[ix].clue, coordList[bestScoreIndex].x, coordList[bestScoreIndex].y, coordList[bestScoreIndex].vertical);
                }
            }

        }
    }
    if(activeWordList.length < wordArray.length/2) { //regenerate board if if less than half the words were placed
        seed++;
        generateBoard(seed);
    }
}
}
function seedBoard() {
    gameboard = new board(GRID_WIDTH, GRID_HEIGHT);
    gameboard.generateBoard();
    gameboard.displayGrid();
}

A: I came up with a solution which probably isn't the most efficient, but it works well enough. Basically:

*

*Sort all the words by length, descending.

*Take the first word and place it on the board.

*Take the next word.

*Search through all the words that are already on the board and see if there are any possible intersections (any common letters) with this word.

*If there is a possible location for this word, loop through all the words that are on the board and check to see if the new word interferes.

*If this word doesn't break the board, then place it there and go to step 3, otherwise, continue searching for a place (step 4).

*Continue this loop until all the words are either placed or unable to be placed.

This makes a working, yet often quite poor crossword. There were a number of alterations I made to the basic recipe above to come up with a better result.

*

*At the end of generating a crossword, give it a score based on how many of the words were placed (the more the better), how large the board is (the smaller the better), and the ratio between height and width (the closer to 1 the better). Generate a number of crosswords and then compare their scores and choose the best one.

*

*Instead of running an arbitrary number of iterations, I've decided to create as many crosswords as possible in an arbitrary amount of time. If you only have a small word list, then you'll get dozens of possible crosswords in 5 seconds.  A larger crossword might only be chosen from 5-6 possibilities.

*When placing a new word, instead of placing it immediately upon finding an acceptable location, give that word location a score based on how much it increases the size of the grid and how many intersections there are (ideally you'd want each word to be crossed by 2-3 other words). Keep track of all the positions and their scores and then choose the best one.

A: I'd generate two numbers: Length and Scrabble score.  Assume that a low Scrabble score means it's easier to join on (low scores = lots of common letters).  Sort the list by length descending and Scrabble score ascending.
Next, just go down the list. If the word doesn't cross with an existing word (check against each word by their length and Scrabble score, respectively), then put it into the queue, and check the next word.
Rinse and repeat, and this should generate a crossword.
Of course, I'm pretty sure that this is O(n!) and it's not guaranteed to complete the crossword for you, but perhaps somebody can improve it.

A: I've been thinking about this problem.  My sense is that to create a truly dense crossword, you cannot hope that your limited word list is going to be enough.  Therefore, you might want to take a dictionary and place it into a "trie" data structure.  This will allow you to easily find words that fill the left over spaces.  In a trie, it is fairly efficient to implement a traversal that, say, gives you all words of the form "c?t".
So, my general thinking is: create some sort of relatively brute force approach as some described here to create a low-density cross, and fill in the blanks with dictionary words.
If anyone else has taken this approach, please let me know.

A: I was playing around crosswords generator engine, and I found this the most important :
0.!/usr/bin/python

*

*a. allwords.sort(key=len, reverse=True)
b. make some item/object like cursor which will walk around matrix for easy orientation
  unless you want to iterate by random choice later on.

*the first, pick up first pair and place them across and down from 0,0 ;
store the first one as our current crossword 'leader'.

*move cursor by order diagonal or random with greater diagonal probability to next empty cell

*iterate over the words like and use free space length to define max word length :

temp=[]
for w_size in range( len( w_space ), 2, -1 ) :
    # t
    for w in [ word for word in allwords if len(word) == w_size  ]  :
        #
        if w not in temp and putTheWord( w, w_space ) :
            #
            temp.append( w )

*to compare word against free space I used i.e. :
w_space=['c','.','a','.','.','.'] # whereas dots are blank cells

# CONVERT MULTIPLE '.' INTO '.*' FOR REGEX

pattern = r''.join( [ x.letter for x in w_space ] )
pattern = pattern.strip('.') +'.*' if pattern[-1] == '.' else pattern

prog = re.compile( pattern, re.U | re.I )

if prog.match( w ) :
    #
    if prog.match( w ).group() == w :
        #
        return True

*after each successfully used word, change direction.
Loop while all cells are filled OR you run out of words OR by limit of iterations then :
# CHANGE ALL WORDS LIST
    inexOf1stWord = allwords.index( leading_w )
    allwords = allwords[:inexOf1stWord+1][:] + allwords[inexOf1stWord+1:][:]
...and iterate again new crossword.

*Make the scoring system by easiness of filling, and some estimation calcs.
Give score for the current crossword and narrow later choice by append it into
list of made crosswords if the score is satisfied by your scoring system.

*After first iteration session iterate again from the list of made crosswords to finish the job.
By using more parameters speed can be improved by a huge factor.

A: This one appears as a project in the AI CS50 course from Harvard. The idea is to formulate the crossword generation problem as a constraint satisfaction problem and solve it with backtracking with different heuristics to reduce the search space.
To start with we need couple of input files:

*

*The structure of the crossword puzzle (which looks like the following one, e.g., where the '#' represents the characters not to be filled with and '_' represents the characters to be filled with)

`
###_####_#
____####_#
_##_#_____
_##_#_##_#
______####
#_###_####
#_##______
#_###_##_#
_____###_#
#_######_#
##_______#

`

*An input vocabulary (word list / dictionary) from which the candidate words will be chosen (like the one shown follows).
a
abandon
ability
able
abortion
about
above
abroad
absence
absolute
absolutely
...
Now the CSP is defined and to be solved as follows:

*

*Variables are defined to have values (i.e., their domains) from the list of words (vocabulary) provided as input.

*Each variable gets represented by a 3 tuple: (grid_coordinate, direction, length) where the coordinate represents the start of the corresponding word, direction can be either of horizontal or vertical and the length is defined as the length of the word the variable will be assigned to.

*The constraints are defined by the structure input provided: for example, if a horizontal and a vertical variable has a common character, it will represented as an overlap (arc) constraint.

*Now, the node consistency and AC3 arc consistency algorithms can be used to reduce the domains.

*Then backtracking to obtain a solution (if one exists) to the CSP with MRV (minimum remaining value), degree etc. heuristics can be used to select the next unassigned variable and heuristics like LCV (least constraining value) can be used for domain-ordering, to make the search algorithm faster.

The following shows the output that was obtained using an implementation of the CSP solving algorithm:
`
███S████D█
MUCH████E█
E██A█AGENT
S██R█N██Y█
SUPPLY████
█N███O████
█I██INSIDE
█Q███E██A█
SUGAR███N█
█E██████C█
██OFFENSE█

`
The following animation shows the backtracking steps:

Here is another one with a Bangla (Bengali) language word-list:

A: I just recently wrote my own in Python. You can find it here: http://bryanhelmig.com/python-crossword-puzzle-generator/. It doesn't create the dense NYT style crosswords, but the style of crosswords you might find in a child's puzzle book.
Unlike a few algorithms I found out there that implemented a random brute-force method of placing words like a few have suggested, I tried to implement a slightly smarter brute-force approach at word placement. Here's my process:

*

*Create a grid of whatever size and a list of words.

*Shuffle the word list, and then sort the words by longest to shortest.

*Place the first and longest word at the upper left most position, 1,1 (vertical or horizontal).

*Move onto next word, loop over each letter in the word and each cell in the grid looking for letter to letter matches.

*When a match is found, simply add that position to a suggested coordinate list for that word.

*Loop over the suggested coordinate list and "score" the word placement based on how many other words it crosses. Scores of 0 indicate either bad placement (adjacent to existing words) or that there were no word crosses.

*Back to step #4 until word list is exhausted. Optional second pass.

*We should now have a crossword, but the quality can be hit or miss due to some of the random placements. So, we buffer this crossword and go back to step #2. If the next crossword has more words placed on the board, it replaces the crossword in the buffer. This is time limited (find the best crossword in x seconds).

By the end, you have a decent crossword puzzle or word search puzzle, since they are about the same. It tends to run rather well, but let me know if you have any suggestions on improvement. Bigger grids run exponentially slower; bigger word lists linearly. Bigger word lists also have a much higher chance at better word placement numbers.

A: I actually wrote a crossword generation program about ten years ago (it was cryptic but the same rules would apply for normal crosswords).
It had a list of words (and associated clues) stored in a file sorted by descending usage to date (so that lesser-used words were at the top of the file). A template, basically a bit-mask representing the black and free squares, was chosen randomly from a pool that was provided by the client.
Then, for each non-complete word in the puzzle (basically find the first blank square and see if the one to the right (across-word) or the one underneath (down-word) is also blank), a search was done of the file looking for the first word that fitted, taking into account the letters already in that word. If there was no word that could fit, you just marked the whole word as incomplete and moved on.
At the end would be some uncompleted words which the compiler would have to fill in (and add the word and a clue to the file if desired). If they couldn't come up with any ideas, they could edit the crossword manually to change constraints or just ask for a total re-generation.
Once the word/clue file got up to a certain size (and it was adding 50-100 clues a day for this client), there was rarely a case of more than two or three manual fix ups that had to be done for each crossword.

A: I would get an index of each letter used by each word to know possible crosses. Then I would choose the largest word and use it as base. Select the next large one and cross it. Rinse and repeat. It's probably an NP problem.
Another idea is creating a genetic algorithm where the strength metric is how many words you can put in the grid.
The hard part I find is when to know a certain list cannot possibly be crossed.

A:
I have coded up a JavaScript/jQuery solution to this problem :
Sample Demo: http://www.earthfluent.com/crossword-puzzle-demo.html
Source Code: https://github.com/HoldOffHunger/jquery-crossword-puzzle-generator
The intent of the algorithm I used:

*

*Minimize the number of the unusable squares in the grid as much as possible.

*Have as many inter-mixed words as possible.

*Compute in an extremely fast time.

I will describe the algorithm I used:

*

*Group the words together according to those that share a common letter.

*From these groups, build sets of a new data structure ("word blocks"), which is a primary word (that runs through all other words) and then the other words (that run through the primary word).

*Start out the crossword puzzle with the very first of these word blocks in the very top-left position of the crossword puzzle.

*For the rest of the word blocks, starting from the right-bottom most position of the crossword puzzle, move upward and leftward, until there are no more available slots to fill.  If there are more empty columns upwards than leftwards, move upwards, and vice versa.

A: This algorithm creates 50 dense 6x9 arrow crosswords in 60 seconds. It uses a word database (with word+tips) and a board database (with pre-configured boards).
1) Search for all starting cells (the ones with an arrow), store their size and directions
2) Loop through all starting cells
2.1) Search a word
2.1.1) Check if it was not already used
2.1.2) Check if it fits
2.2) Add the word to the board
3) Check if all cells were filled

A bigger word database decreases generation time considerably and some kind of boards are harder to fill! Bigger boards require more time to be filled correctly!

Example:
Pre-Configured 6x9 Board:
(# means one tip in one cell, % means two tips in one cell, arrows not shown)
# - # # - % # - #
- - - - - - - - -
# - - - - - # - -
% - - # - # - - -
% - - - - - % - -
- - - - - - - - -

Generated 6x9 Board:
# C # # P % # O #
S A T E L L I T E
# N I N E S # T A
% A B # A # G A S
% D E N S E % W E
C A T H E D R A L

Tips [line,column]:
[1,0] SATELLITE: Used for weather forecast
[5,0] CATHEDRAL: The principal church of a city
[0,1] CANADA: Country on USA's northern border
[0,4] PLEASE: A polite way to ask things
[0,7] OTTAWA: Canada's capital
[1,2] TIBET: Dalai Lama's region
[1,8] EASEL: A tripod used to put a painting
[2,1] NINES: Dressed up to (?)
[4,1] DENSE: Thick; impenetrable
[3,6] GAS: Type of fuel
[1,5] LS: Lori Singer, american actress
[2,7] TA: Teaching assistant (abbr.)
[3,1] AB: A blood type
[4,3] NH: New Hampshire (abbr.)
[4,5] ED: (?) Harris, american actor
[4,7] WE: The first person of plural (Grammar)

A: Although this is an older question, will attempt an answer based on similar work i have done.
There are many approaches to solving constraint problems (which generallay are in NPC complexity class).
This is related to combinatorial optimization and constraint programming.  In this case the constraints are the geometry of the grid and the requirement that words are unique etc..
Randomization/Annealing approaches can also work (although within the proper setting).
Efficient simplicity might just be the ultimate wisdom !
The requirements were for a more or less complete crossword compiler and (visual WYSIWYG) builder.
Leaving aside the WYSIWYG builder part, the compiler outline was this:

*

*Load the available wordlists (sorted by word length, ie 2,3,..,20)

*Find the wordslots (ie grid words) on the user-constructed grid (eg word at x,y with length L, horizontal or vertical) ( complexity O(N) )

*Compute the intersecting points of the grid words (that need to be filled)  ( complexity O(N^2) )

*Compute the intersections of the words in the wordlists with the various letters of the alphabet used (this allows to search for matching words by using a template eg. Sik Cambon thesis as used by cwc )  ( complexity O(WL*AL) )
Steps .3 and .4 allow to do this task:
a. The intersections of the grid words with themselves enable to create a "template" for trying to find matches in the associated wordlist of available words for this grid word (by using the letters of other intersecting words with this word which are already filled at a certain step of the algorithm)
b. The intersections of the words in a wordlist with the alphabet enable to find matching (candidate) words that match a given "template" (eg 'A' in 1st place and 'B' in 3rd place etc..)
So with these data structures implemented the algorithm used was sth like this:
NOTE: if the grid and the database of words are constant the previous steps can just be done once.

*

*First step of the algorithm is select an empty wordslot (grid word) at random and fill it with a candidate word from its associated wordlist (randomization enables to produce different solutons in consecutive executions of the algorithm)  ( complexity O(1) or O(N) )

*For each still empty word slots (that have intersections with already filled wordslots), compute a constraint ratio (this can vary, sth simple is the number of available solutions at that step) and sort the empty wordslots by this ratio  ( complexity O(NlogN) or O(N) )

*Loop through the empty wordslots computed at previous step and for each one try a number of cancdidate solutions (making sure that "arc-consistency is retained", ie grid has a solution after this step if this word is used) and sort them according to maximum availability for next step (ie next step has a maximum possible solutions if this word is used at that time in that place, etc..)  ( complexity O(N*MaxCandidatesUsed) )

*Fill that word (mark it as filled and go to step 2)

*If no word found that satisfies the criteria of step .3 try to backtrack to another candidate solution of some previous step (criteria can vary here)  ( complexity O(N) )

*If backtrack found, use the alternative and optionally reset any already filled words that might need reset (mark them as unfilled again)  ( complexity O(N) )

*If no backtrack found, the no solution can be found (at least with this configuration, initial seed etc..)

*Else when all wordlots are filled you have one solution
This algorithm does a random consistent walk of the solution tree of the problem. If at some point there is a dead end, it does a backtrack to a previous node and follow another route. Untill either a solution found or number of candidates for the various nodes are exhausted.
The consistency part makes sure that a solution found is indeed a solution and the random part enables to produce different solutions in different executions and also on the average have better performance.
PS. all this (and others) were implemented in pure JavaScript (with parallel processing and WYSIWYG) capability
PS2. The algorithm can be easily parallelized in order to produce more than one (different) solution at the same time
Hope this helps


text:
Q: the paypal payment page price calculation I want to create a price calculation for my Paypal payment option. I am using javascript to do it. But it doesn't work. So can anyone  help me? Below is the code:

number of licenses (US$59.99 per license):

<form name="calcform" action="https://www.paypal.com/cgi-bin/webscr" method="post">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="sample@paypal.com">
<input type="hidden" name="lc" value="MY">
<input type="hidden" name="item_number" value="abc">
<input type="text" name="quantity1" size="50" ONCHANGE="calculate()">
<input type="hidden" name="amount" ONCHANGE="calculate()" value="59.99">
<input type="hidden" name="item_name" value = "J-2011">

</form>

enter to process payment

A: add the hidden box with the name "total1" inside the form tag.
<input type="hidden" name="total1" value = "">


text:
Q: How to generate AQIAAAAAAAUgAAAAIAIAAA== out of 'BUILTIN/Administrators' or 0x01020000000000052000000020020000 I'm playing with automatically granting permissions to SSRS users using ReportServer.dbo.SetPolicy stored procedure and I'm stuck with updating @XmlPolicy field which contains the following:
@XmlPolicy  = 'BUILTIN\AdministratorsAQIAAAAAAAUgAAAAIAIAAA==Content Manager'
The GroupUserId above is obviously the SID of BUILTIN\Administrators account which is 0x01020000000000052000000020020000.
The question is how can I convert (encode) 0x01020000000000052000000020020000 to the AQIAAAAAAAUgAAAAIAIAAA== format?
Or is there a better way to do this?
Thank you.

A: "AQIAAAAAAAUgAAAAIAIAAA==" is just the binary string 01 02 00 00 00 00 00 05 20 00 00 00 20 02 00 00 encoded in Base64.


text:
Q: upload / post stringIO as file I want to upload a stringIO as a file to a server.
I'm not using rails to make the request, just ruby and some gems.
I have created a stringIO like below:
require 'rest-client'
require 'zip'

... some code
stream = Zip::OutputStream::write_buffer do |zip|
  ... code that download files and packs them
end

stream.rewind

RestClient.post('somepath', { file: stream.read }, headers)

RestClient is just some handy gem that makes it a bit easier to send http request.
so my problem is that on the server side in the controller when I receive the request I get an error
ArgumentError - invalid byte sequence in UTF-8:
  activesupport (4.2.6) lib/active_support/core_ext/object/blank.rb:117:in `blank?'
  carrierwave (0.10.0) lib/carrierwave/sanitized_file.rb:127:in `is_path?'
  carrierwave (0.10.0) lib/carrierwave/sanitized_file.rb:93:in `size'
  carrierwave (0.10.0) lib/carrierwave/sanitized_file.rb:136:in `empty?'
  carrierwave (0.10.0) lib/carrierwave/uploader/cache.rb:119:in `cache!'
  carrierwave (0.10.0) lib/carrierwave/mount.rb:329:in `cache'
  carrierwave (0.10.0) lib/carrierwave/mount.rb:163:in `export='
  carrierwave (0.10.0) lib/carrierwave/orm/activerecord.rb:39:in `export='
  app/controllers/exports_controller.rb:17:in `upload'

(I'm using carrierwave to store the files)
I think that I'm not handling the stringIO properly but honestly don't exactly know how should I pass it to the post request so that it behaves like a file
any ideas?

A: turns out this was happening because I was not saving the zip as a file but used write_buffer that responds with stringIO.
stringIO read method returns a string that was uploaded to my controller and then I tried to save the file using carrierwave roughly like that:
... code in my controller
myObject = ObjectModel.find(params[:id])
myObject.fileUploader = StringIO.new(params[:file]) => this was the string i received from stringIO read method
myObject.save

but it won't work because StringIO objects don't have original_filename method anymore since Rails3 (As far as I understood from the carrierwave issue page)
The solutions was to create a wrapper around StringIO and add either an attribute or a method that is called original_filename afterwards file was being saved correctly.
I'm posting link to carrierwave wiki that deals with this:
https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Upload-from-a-string-in-Rails-3-or-later
and a sample wrapper like object
  class StringIOWrapper < StringIO
    attr_accessor :original_filename
  end

afterwards this will work
myObject.fileUploader = StringIOWrapper.new(params[:file])
myObject.save


text:
Q: How to remove or ignore control character \r or " " from cells in excel sheet? I am reading a csv file data and converting them into dictionary but the data in dictionary is coming with \r like 69\r, 79\r in putty or When I open the file, it is coming as "69" and these double quotes are hidden. How to remove these?
I tried many ways from stack overflow but didn't work out. I tried read.splitLines() or replace method as well but problem with that is if I remove \r then it will remove all the data after 1st line but that excel has lot of data.
Is there any other way where we can ignore control characters and get all the data in excel or putty. Please help!!!!!
Below is the code:
def fileToDict(filepath):
    dataInDict = {}
    with open(filepath) as f:
        data = f.readlines()
        for idx, d in enumerate(data):
            dlist = d.strip('\n').split('\t')
            dataInDict[idx] = dlist
        f.close()
    return dataInDict

Adding more details here... I am using this function to convert all the data from 2 files into 2 dictionaries using like
Dict1 =  fileToDict(file1)
Dict2 =  fileToDict(file2)

Now when I am comparing data between two dictionaries and printing dataInDict using above function, it gives me output with data from both dictionaries as shown below. I have highlighted the \r values and without \r values.
enter image description here
but when I try to remove \r from this, it gives me only 1st line and doesn't give all the lines. Because of this \r, comparison is failing
I am writing above output to excel sheet using xlsWriter

A: There's a couple of ways to solve this.
You could use the .strip method in a for loop.
Presume you have this code:
mydict = {'one': '69\r', 'two': '79\r'}

You could iterate over it and replace each value in every key with a stripped version of itself:
for i in mydict:
    mydict[i] = mydict[i].strip('\r')

Output:
{'one': '69', 'two': '79'}

EDIT
Since the author added a code snippet:
def fileToDict(filepath):
    dataInDict = {}
    with open(filepath) as f:
        data = f.readlines()
        for idx, d in enumerate(data):
            dlist = d.strip('\n').split('\t')
            dataInDict[idx] = dlist
        f.close()
    for i in dataInDict:                           # Iterate through your new dict
        dataInDict[i] = dataInDict[i].strip('\r')  # Strip each value after occurance of '\r'
    return dataInDict


text:
Q: border-radius only works on one side of the div I was trying to apply border-radius on a div, and I notice that border-radius will only work on one side if this side's radius value gets too big like below. How exactly can I solve this while keeping the border-radius value on both sides?

.wrapper1 {
  width: 250px;
  height: 150px;
  background-color: red;
  border-radius: 999px 2px 2px 999px;
}
.wrapper2{
  width: 250px;
  height: 150px;
  background-color: green;
  border-radius: 2px;
}

A: From the specification:

Corner curves must not overlap: When the sum of any two adjacent border radii exceeds the size of the border box, UAs must proportionally reduce the used values of all border radii until none of them overlap.

So yes, a border-radius on one corner affect adjacent corners. If you want to have accurate detail, check the specification to find all the formula and geometry behind border-radius
Here is a more trivial example:

.wrapper1 {
  width: 250px;
  height: 150px;
  background-color: red;
  border-radius: 9999px 100px 100px 9999px;
}
.wrapper2{
  width: 250px;
  height: 150px;
  background-color: green;
  border-radius: 100px;
}

A: Swap the values from PX to EM and it should work as intended:
border-radius: 9em 0.2em 0.2em 9em;


text:
Q: Merging Java objects and skipping nulls in java 7 I have a program that takes a flat csv file and using xsd, maps the content out to an XML document.
I currently have a process that looks like this
// A0797 and children as list
A0797 a0797Items = o.createELIXPRODUCTSCOREPRODUCTA0797();
a0797Items.setA0069(line[25]);
a0797Items.setA0070(line[26]);
if (line[27].length() > 0)
{
a0797Items.setA0074(new BigInteger(line[27]));
}
if (line[28].length() > 0)
{
a0797Items.setA0073(new BigInteger(line[28]));
}
a0797Items.setA0071(line[29]);
prd.getA0797().add(a0797Items);

Columns 25, 26, etc. are mapped to the XML document. The business are now sending through additional data in the csv file, columns 33-37. These also need to be set in A0069, A0074 and A0074.
I can easily pull back the objects, bust was wondering how best I can merge them onto one line in the above script.
For example, today, section A0069 will take the data from the CSV file, and create:
<A0069>50</A0069>

With the extra data in the file, it now needs to generate like this
<A0069>20,30,50</A0069>

In some cases, you might just have 20 and 50, or 20 and 50 etc. etc.
What would be the best way to merge these and skip null values?
If one of the values were missing (say, 20), this would be bad:
<A0069>,30,50</A0069>

Ideally, I'd want this:
<A0069>30,50</A0069>

Update 13/08/2015:
Because I need to use Java 7, I've gone with this approach so far:
StringBuilder tUnitSB = new StringBuilder();
if (line[25] != null) tUnitSB.append(line[25]);
if (line[33] != null) tUnitSB.append(line[33]);
if (line[36] != null) tUnitSB.append(line[36]);
// Display results.
String tradeUnits = tUnitSB.toString();
a0797Items.setA0069(tradeUnits);

What I can't work out, is how to now comma separate them, without additonal commas creeping in.


text:
Q: Is handling the `Imbalance` type mandatory after withdraw or deposit? When using any of the functions which mint/burn the base currency (e.g. Currency::withdraw()), you're given an Imbalance return value. Does Substrate expect me to do something with it?

A: You get back an Imbalance whenever you perform some "one-sided operation" within the Balances module (deposit, slash, withdraw, etc...).
The both PositiveImbalance and NegativeImbalance implement the Drop trait, which defines a destructor function that gets called when a variable goes out of scope.
In the case of an Imbalance, the drop function simply updates the total issuance of the balances module to ensure that the sum of all current account balances is equal to the total issuance.
So by default, no, you do not need to do anything with the imbalance returned to you. You can just place the result of a "one-sided operation" into an unused variable like so:
let _ = <balances::Module<T> as Currency<_>>::withdraw(...)?;

However, if you want to, you are also given a set of tools to manage imbalances returned to you:
impl<T: Trait<I>, I: Instance> Imbalance<T::Balance> for NegativeImbalance<T, I> {
    type Opposite = PositiveImbalance<T, I>;

    fn zero() -> Self {...}

    fn drop_zero(self) -> result::Result<(), Self> {...}

    fn split(self, amount: T::Balance) -> (Self, Self) {...}

    fn merge(mut self, other: Self) -> Self {...}

    fn subsume(&mut self, other: Self) {...}

    fn offset(self, other: Self::Opposite) -> result::Result<Self, Self::Opposite> {...}

    fn peek(&self) -> T::Balance {...}
}


text:
Q: RelativeLayout: Sharing screens height Here is my xml:
<RelativeLayout
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                >

            <LinearLayout android:layout_alignParentTop="true"
                          android:layout_height="wrap_content"
                          android:layout_width="fill_parent"
                          android:id="@+id/llRow1" />
            <LinearLayout android:layout_height="wrap_content"
                          android:layout_width="fill_parent"
                          android:layout_below="@+id/llRow1"
                          android:id="@+id/llRow2" />
            <LinearLayout android:layout_alignParentBottom="true"
                          android:layout_height="wrap_content"
                          android:layout_width="fill_parent"
                          android:id="@+id/llRow3" >
</RelativeLayout>

What i wanna have:
- Those 3 "rows" have to share the screens' height
- but with one extra: when i set the 3rd row (llRow3) visibility to GONE, only row1 and row2 have to share the screens height.
How is it possible to do this?

A: Set a the same layout_weight to all of them. So if you'll set visibility of the third one to GONE, they'll still have those weights.
Edit:
Change the ParentLayout to LinearLayout or if you need RelitiveLayout, then you can wrap those three LinearLayout in an other LinearLayout and set weights to them like this:
 <RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >

    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >

        <LinearLayout
            android:id="@+id/llRow1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:layout_weight="1" />

        <LinearLayout
            android:id="@+id/llRow2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/llRow1"
            android:layout_weight="1" />

        <LinearLayout
            android:id="@+id/llRow3"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_weight="1" >
        </LinearLayout>
    </LinearLayout>

</RelativeLayout>


text:
Q: How google bigquery calculate the memory needed before running the query? What is the algorithm that google bigquery uses to instantly calculate the memory needed to run the query even before running the query?

A: Possibly overkill for the question, but this research paper from 2021 has a lot of background information about BigQuery's metadata layer.


text:
Q: Opto Triac driver (moc3051) basic circuit problem I wanted to try the basic circuit of MOC3051 which is a random phase optoisolator triac driver.
I used this circuit from the datasheet:

with following parameters:

*

*Vcc : 3.3v

*Transistor : BD139

*R : 1K

*Triac : BTA40-700b

*Load :    Resistive 9.4K

*AC line : from a    rotary voltage converter    (from 0 -    300 VAC)

I've also implemented zero detection and firing angle handling by a pic microcontroller. The circuit works perfect when the AC LINE voltage is 24VAC and when I checked the signal across the load, it changes perfectly in response to firing angle.
The problem is when I increase the AC LINE voltage up to 90VAC the signal across the load started to vanished at some firing angle and above 100VAC it vanished completely. I've tried different values for R and re-assembled the moc3051 with the new one but nothing's changed.
Do you have any clue why is this happening when AC LINE voltage is increasing while the main purpose of these drivers are to work with 110 - 240vac voltage range?

A: Your issue may be with the particular load and trigger current pulse you are using for the higher voltage.
The current has to have sufficient time to build up to the holding current for the triac or it will not stay on for the remainder of the cycle (it will just momentarily conduct for the duration of the trigger pulse, much like a transistor). The triac is deliberately made a bit insensitive to keep from false triggering (eg. dv/dt).
Inductance in the load, too much series resistance in the gate circuit (1K is a bit on the high side) or a too-short trigger pulse can all contribute to this.
If a DC trigger level turns the main triac on reliably then your problem is related to the trigger pulse.

A: I don't think you need an additional transistor to drive the opto. Below circuit works fine at 220 VAC:


text:
Q: How can i manipulate date data before saving to the database in symfony2 I have a Clutch entity like this:
<?php

namespace Breedr\ClutchBundle\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * Clutch
 *
 * @ORM\Table()
 * @ORM\Entity
 */
class Clutch
{
    /**
     * @var integer
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var Breedr\BreedingPairsBundle\Entity\Pairs
     *
     * @ORM\ManyToOne(targetEntity="Breedr\BreedingPairsBundle\Entity\Pairs")
     * @ORM\JoinColumn(name="breeding_pair", referencedColumnName="id")
     */
    private $breedingPair;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="laid_date", type="date")
     */
    private $laidDate;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="estimated_hatch_start", type="date")
     */
    private $estimatedHatchStart;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="estimated_hatch_end", type="date")
     */
    private $estimatedHatchEnd;

    /**
     * @var \DateTime
     *
     * @ORM\Column(name="hatch_date", type="date")
     */
    private $hatchDate;

    /**
     * @var integer
     *
     * @ORM\Column(name="egg_amount", type="integer")
     */
    private $eggAmount;

    /**
     * @var Breedr\UserBundle\Entity\User
     *
     * @ORM\ManyToOne(targetEntity="Breedr\UserBundle\Entity\User")
     * @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     */
    private $user;

    /**
     * Get id
     *
     * @return integer
     */
    public function getId()
    {
        return $this->id;
    }

    /**
     * Set breedingPair
     *
     * @param integer $breedingPair
     * @return Clutch
     */
    public function setBreedingPair($breedingPair)
    {
        $this->breedingPair = $breedingPair;

        return $this;
    }

    /**
     * Get breedingPair
     *
     * @return integer
     */
    public function getBreedingPair()
    {
        return $this->breedingPair;
    }

    /**
     * Set laidDate
     *
     * @param \DateTime $laidDate
     * @return Clutch
     */
    public function setLaidDate($laidDate)
    {
        $this->laidDate = $laidDate;

        return $this;
    }

    /**
     * Get laidDate
     *
     * @return \DateTime
     */
    public function getLaidDate()
    {
        return $this->laidDate;
    }

    /**
     * Set estimatedHatchStart
     *
     * @param \DateTime $estimatedHatchStart
     * @return Clutch
     */
    public function setEstimatedHatchStart($estimatedHatchStart)
    {
        $this->estimatedHatchStart = $estimatedHatchStart;

        return $this;
    }

    /**
     * Get estimatedHatchStart
     *
     * @return \DateTime
     */
    public function getEstimatedHatchStart()
    {
        return $this->estimatedHatchStart;
    }

    /**
     * Set estimatedHatchEnd
     *
     * @param \DateTime $estimatedHatchEnd
     * @return Clutch
     */
    public function setEstimatedHatchEnd($estimatedHatchEnd)
    {
        $this->estimatedHatchEnd = $estimatedHatchEnd;

        return $this;
    }

    /**
     * Get estimatedHatchEnd
     *
     * @return \DateTime
     */
    public function getEstimatedHatchEnd()
    {
        return $this->estimatedHatchEnd;
    }

    /**
     * Set hatchDate
     *
     * @param \DateTime $hatchDate
     * @return Clutch
     */
    public function setHatchDate($hatchDate)
    {
        $this->hatchDate = $hatchDate;

        return $this;
    }

    /**
     * Get hatchDate
     *
     * @return \DateTime
     */
    public function getHatchDate()
    {
        return $this->hatchDate;
    }

    /**
     * Set eggAmount
     *
     * @param integer $eggAmount
     * @return Clutch
     */
    public function setEggAmount($eggAmount)
    {
        $this->eggAmount = $eggAmount;

        return $this;
    }

    /**
     * Get eggAmount
     *
     * @return integer
     */
    public function getEggAmount()
    {
        return $this->eggAmount;
    }

    /**
     * Set user
     *
     * @param \Breedr\UserBundle\Entity\User $user
     * @return Clutch
     */
    public function setUser(\Breedr\UserBundle\Entity\User $user = null)
    {
        $this->user = $user;

        return $this;
    }

    /**
     * Get user
     *
     * @return \Breedr\UserBundle\Entity\User
     */
    public function getUser()
    {
        return $this->user;
    }
}

And here is my ClutchType form:
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $currentUser = $this->currentUser;
    $builder
        ->add('breedingPair', 'entity', array(
            'class' => 'Breedr\BreedingPairsBundle\Entity\Pairs',
            'property' => 'getPairAsString',
            'placeholder' => 'Choose a breeding pair',
            'query_builder' => function(EntityRepository $er) use ($currentUser) {
                return $er->createQueryBuilder('br')
                    ->where('br.user = :currentUser')
                    ->orderBy('br.breedingPairDate')
                    ->setParameter('currentUser', $currentUser);
            }
        ))
        ->add('laidDate')
        ->add('estimatedHatchStart')
        ->add('estimatedHatchEnd')
        ->add('hatchDate')
        ->add('eggAmount')
    ;
}

Now, what I would like to do is not show estimatedHatchStart or estimatedHatchEnd on the front end, and use the data from laidDate to add 30 days and 40 days respectfully to give me the start and end hatch dates which will then be saved to database.
What is the best practice to do this? I have just read about the FormEvents::PRE_SUBMIT event, but i am unsure if this is the correct way to go about it?
EDIT:
setLaidDate function:
/**
 * Set laidDate
 *
 * @param \DateTime $laidDate
 * @return Clutch
 */
public function setLaidDate($laidDate)
{
    $this->laidDate = $laidDate;

    $estimatedHatchStart = $laidDate->modify('+30days');
    $estimatedHatchEnd = $laidDate->modify('+40days');

    $this->setEstimatedHatchStart($estimatedHatchStart);
    $this->setEstimatedHatchEnd($estimatedHatchEnd);

    return $this;
}

ClutchController:
<?php

namespace Breedr\ClutchBundle\Controller;

use Symfony\Component\HttpFoundation\Request;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Breedr\ClutchBundle\Entity\Clutch;
use Breedr\ClutchBundle\Form\ClutchType;

/**
 * Clutch controller.
 *
 */
class ClutchController extends Controller
{

    /**
     * Lists all Clutch entities.
     *
     */
    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();
        $user = $this->getUser();
        $entities = $em
            ->getRepository('BreedrClutchBundle:Clutch')
            ->findBy(array('user' => $user), array()
        );

        return $this->render('BreedrClutchBundle:Clutch:index.html.twig', array(
            'entities' => $entities,
        ));
    }
    /**
     * Creates a new Clutch entity.
     *
     */
    public function createAction(Request $request)
    {
        $entity = new Clutch();
        $entity->setUser($this->getUser());
        $form = $this->createCreateForm($entity);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $em->persist($entity);
            $em->flush();

            return $this->redirect($this->generateUrl('clutch_show', array('id' => $entity->getId())));
        }

        return $this->render('BreedrClutchBundle:Clutch:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Creates a form to create a Clutch entity.
     *
     * @param Clutch $entity The entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createCreateForm(Clutch $entity)
    {
        $currentUser = $this->getUser()->getId();

        $form = $this->createForm(new ClutchType($currentUser), $entity, array(
            'action' => $this->generateUrl('clutch_create'),
            'method' => 'POST',
        ));

        $form->add('submit', 'submit', array('label' => 'Create'));

        return $form;
    }

    /**
     * Displays a form to create a new Clutch entity.
     *
     */
    public function newAction()
    {
        $entity = new Clutch();
        $form   = $this->createCreateForm($entity);

        return $this->render('BreedrClutchBundle:Clutch:new.html.twig', array(
            'entity' => $entity,
            'form'   => $form->createView(),
        ));
    }

    /**
     * Finds and displays a Clutch entity.
     *
     */
    public function showAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('BreedrClutchBundle:Clutch')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Clutch entity.');
        }

        $deleteForm = $this->createDeleteForm($id);

        return $this->render('BreedrClutchBundle:Clutch:show.html.twig', array(
            'entity'      => $entity,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing Clutch entity.
     *
     */
    public function editAction($id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('BreedrClutchBundle:Clutch')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Clutch entity.');
        }

        $editForm = $this->createEditForm($entity);
        $deleteForm = $this->createDeleteForm($id);

        return $this->render('BreedrClutchBundle:Clutch:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
    * Creates a form to edit a Clutch entity.
    *
    * @param Clutch $entity The entity
    *
    * @return \Symfony\Component\Form\Form The form
    */
    private function createEditForm(Clutch $entity)
    {
        $currentUser = $this->getUser()->getId();
        $form = $this->createForm(new ClutchType($currentUser), $entity, array(
            'action' => $this->generateUrl('clutch_update', array('id' => $entity->getId())),
            'method' => 'PUT',
        ));

        $form->add('submit', 'submit', array('label' => 'Update'));

        return $form;
    }
    /**
     * Edits an existing Clutch entity.
     *
     */
    public function updateAction(Request $request, $id)
    {
        $em = $this->getDoctrine()->getManager();

        $entity = $em->getRepository('BreedrClutchBundle:Clutch')->find($id);

        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Clutch entity.');
        }

        $deleteForm = $this->createDeleteForm($id);
        $editForm = $this->createEditForm($entity);
        $editForm->handleRequest($request);

        if ($editForm->isValid()) {
            $em->flush();

            return $this->redirect($this->generateUrl('clutch_edit', array('id' => $id)));
        }

        return $this->render('BreedrClutchBundle:Clutch:edit.html.twig', array(
            'entity'      => $entity,
            'edit_form'   => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
        ));
    }
    /**
     * Deletes a Clutch entity.
     *
     */
    public function deleteAction(Request $request, $id)
    {
        $form = $this->createDeleteForm($id);
        $form->handleRequest($request);

        if ($form->isValid()) {
            $em = $this->getDoctrine()->getManager();
            $entity = $em->getRepository('BreedrClutchBundle:Clutch')->find($id);

            if (!$entity) {
                throw $this->createNotFoundException('Unable to find Clutch entity.');
            }

            $em->remove($entity);
            $em->flush();
        }

        return $this->redirect($this->generateUrl('clutch'));
    }

    /**
     * Creates a form to delete a Clutch entity by id.
     *
     * @param mixed $id The entity id
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm($id)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('clutch_delete', array('id' => $id)))
            ->setMethod('DELETE')
            ->add('submit', 'submit', array('label' => 'Delete'))
            ->getForm()
        ;
    }
}

A: There's nothing wrong with doing it straight in the entity.  For example
public function setLaidDate($date)
{
    $this->laidDate = $laidDate;

    $hatchDate = date('Y-m-d', strtotime($date . "+30 days"));
    $hatchDateEnd = date('Y-m-d', strtotime($date . "+40 days"));

    $this->setEstimatedHatchStart($hatchDate);
    $this->setEstimatedHatchEnd($hatchDateEnd);

    return $this;
}

It would just mean that anytime $this->setLaidDate() is called the other two fields will also be updated.  You could also do this manually in the controller when you handle the form submission and before actually persisting the entity to the database.
Or my favorite way is making an entity manager.  A service you use to help you create new empty entities and persist existing ones back to the database.
#services.yml
services:
    my_custom_manager:
        class: AppBundle\Entity\MyEntityManager
        arguments: [ "@doctrine.orm.entity_manager" , 'AppBundle\Entity\MyEntity']

AppBundle/Entity/MyEntityManager

namespace AppBundle\Entity;

use Doctrine\Common\Persistence\ObjectManager;
use AppBundle\Entity\MyEntity;

class MyEntityManager
{
    protected $class;
    protected $orm;
    protected $repo;

    public function __construct(ObjectManager $orm , $class)
    {
        $this->orm = $orm;
        $this->repo = $orm->getRepository($class);

        $metaData = $orm->getClassMetadata($class);
        $this->class = $metaData->getName();
    }

    public function create()
    {
        $class = $this->getClass();
        $myEntity = new $class;

        return $myEntity;
    }

    public function updateMyEntity(MyEntity $entity, $flush = true)
    {

        $date = $entity->getLaidDate();
        $hatchStart = date('Y-m-d', strtotime($date . "+30 days"));
        $hatchEnd = date('Y-m-d', strtotime($date . "+40 days"));

        $entity->setHatchStart($hatchStart);
        $entity->setHatchEnd($hatchEnd)

        $this->orm->persist($entity);
        if($flush)
        {
            $this->orm->flush();
        }
    }

    public function getClass()
    {
        return $this->class;
    }
}

And then in the controller
<?php

public function createAction(Request $request)
{
    $manager = $this->get('my_custom_manager');

    $newEntity = $manager->create();

    $form = $this->createForm(new MyType() , $newEntity);

    $form->handleRequest($request);

    if($form->isValid())
    {
        $manager->updateMyEntity($newEntity);
    }

    //The rest of the code
}

Or another easy way would be to just set it all by hand in the controller action.  There's nothing wrong with that as well.  All up to you really.
EDIT
If I'm to believe your FormType, you still have
->add('estimatedHatchStart')
->add('estimatedHatchEnd')

So what's happening when the form submits in the background $this->setLaidDate($date) runs and your estimated hatches get set.  But then $this->setEstimatedHatchStart($date) and $this->estimatedHatchEnd($date) are getting called and likely set to NULL if you're leaving those fields in your form blank.  At least this is my guess.  Try removing the fields from the form and see if that works.


text:
Q: How to optimize a laravel query, to find the average from another joined table My query (DB::raw(AVG('pt.progress'))) this part is throwing error at the moment
$query = DB::table('projects as p')
    ->leftJoin('projects_tasks as pt','pt.project_id', 'p.id')
    ->select(
        'p.id', 'p.project_name', DB::raw(AVG('pt.progress')) //this is where I need the average
    );
$query->orderBy($order, $dir);
if ($limit != -1) {
    $query->skip($start)->take($limit);
}
$records = $query->get();

Table structure:
projects:
========
id
project_name
...
...

projects_tasks:
===============
id
project_id,
parent, //0 or 1
progress //exmaple value 0.00 to 1.00

How to get the average of progress, where parent_id = 0 and project_id is the same?
The following query does work if I create a function and pass it in a loop, however, I want to optimize it and run it by joining on above query.
$data_row = DB::table('projects_tasks')
     ->select(DB::raw('(SUM(progress)*100)/count(progress) as project_progress'))
     ->where(['project_id' => $project_id, 'parent' => 0])
     ->get();

A: Seems that you have a syntax error on your query, the problem is in here DB::raw(AVG('pt.progress')).
Since you're using a raw query, the parameter there should be a string, so you must enclose that in quotes / double qoute.
$query = DB::table('projects as p')
    ->leftJoin('projects_tasks as pt','pt.project_id', 'p.id')
    ->select(
        'p.id', 'p.project_name', DB::raw("AVG('pt.progress')")
    );
$query->orderBy($order, $dir);
if ($limit != -1) {
    $query->skip($start)->take($limit);
}
$records = $query->get();


text:
Q: Creating a new subnet inside a classic azure vnet I am trying to create a new subnet inside an existing classic VNET on azure. Will creating a new subnet, take the VNET offline or will it cause downtimes to the apps that are present and working within other subnets inside the classic VNET?

A: Based on my knowledge, when you are creating a new subnet in an existing classic VNet, it does not affect your VNet. It will not cause your apps not worikng.
However, if you want migrate your apps from old subnet to new sunbnet, it will cause your apps downtime during the time.


text:
Q: Vagrant libvirt provider on Fedora 23 I need to install libvirt Vagrant plugin but it fails with the following error:
$ vagrant plugin install libvirt
The plugin(s) can't be installed due to the version conflicts below.
This means that the plugins depend on a library version that conflicts
with other plugins or Vagrant itself, creating an impossible situation
where Vagrant wouldn't be able to load the plugins.

You can fix the issue by either removing a conflicting plugin or
by contacting a plugin author to see if they can address the conflict.

Vagrant could not find compatible versions for gem "ffi":
In Gemfile:
  libvirt (>= 0) ruby depends on
    ffi (~> 0.6.3) ruby

  ffi (1.9.10)

I use only hostmanager plugin. The error remains even after removing this plugin so I guess it must conflict with Vagrant itself.
Is it possible to modify the Gemfile of libvirt plugin to depend on ffi 1.9.10? How would I do that?
I had no problems on Fedora 21.
Also I don't know Ruby whatsoever. I just need this running.

A: I found the solution for my problem.

*

*The plugin is called vagrant-libvirt NOT libvirt

*The installation of vagrant-libvirt fails too.
I found this line in ~/.vagrant.d/gems/extensions/x86_64-linux/ruby-libvirt-0.6.0/mkmf.log:

gcc: error: /usr/lib/rpm/redhat/redhat-hardened-cc1: No such file or directory

The solution for this problem is easy: dnf install redhat-rpm-config-36-1.fc23.noarch.
After this, the installation completed successfully.


text:
Q: underlying code for the node red modules In node red, each module has a javascript running in background. When I drop in a http module the corresponding javascript is run. (Please correct me if my understanding is wrong).Where would these codes reside? If I want to create a new module by modifying the existing where should i make changes?

A: node-red is an open source project available on github here: https://github.com/node-red/node-red
The code for the default palette of nodes is here: https://github.com/node-red/node-red/tree/master/nodes/core
If you want to find out more about how to write your own nodes, there as a guide in the documentation here: http://nodered.org/docs/creating-nodes/
If you have any questions, you are best served on the mailing list here: https://groups.google.com/forum/#!forum/node-red
Nick