text:
Q: Spring boot and Akka cluster actor dependency injection not working I am trying to use Spring boot and akka. I have two processes and communicate with akka cluster. Only process A uses spring boot.
@Autowired
private ActorSystem springActorSystem;

@Autowired
private SpringExtension springExtension;

private ActorRef caActor;
caActor = springActorSystem.actorOf(springExtension.props("clientAgentActor"), "ca");

If I create the actor on process A, of course, using springExtension, all injections are working. However, the caActor is a cluster actor. If process B send a message to process A, the ClientAgentActor invoked somewhere, all injections are failed.
How to solve it?
@Component
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class ClientAgentActor extends AbstractActor {

private static final Logger logger = LogManager.getLogger(ClientAgentActor.class);

@Autowired
ClientAgentService caService;

@Autowired
LineService lineService;

@Override
public Receive createReceive() {
    //TODO
    return receiveBuilder().match(String.class, msg -> logger.debug(msg)).build();
}

A: Thought the same for almost whole day. And I think there is no way to integrate Spring into Akka cluster with full DI for cross-cluster calls without changing the core of Akka Cluster.
When you do call without cluster inside one JVM you use Akka wrapper instead of pure Akka.
But when you do call in cluster this call is recieved on other node by pure Akka infrastructure without Spring wrapper, so this infrastructure doesn't know about Spring actors proxies that's why you see no injections.
So if you need Spring in Akka Cluster you need to wrap the core of this library with Spring infrastructure. Except it would be not easy to implement it would be also hard to follow the Akka rules and conventions in application architecture. For example, it would be too easy to inject transitive dependency which has blocking calls or multithreading code.
If you need to use some Spring functionality I think the best way to do this is to fully separate Akka infrastructure from Spring's one. And after application initialization set global static field with created ApplicationContext and make applicationContext.getBean(...) calls where they are needed. Of course you can do comfortable method for this. Or for example class with public static fields with needed beans which are set once after Spring initialization completes.


text:
Q: How do I read the first line of lscpu? I am learning bash right now on my own.
I'm trying to write an if else statement for a small script I'm writing. I want the script to read lscpu command to check if the system is an x86 or 64 bit system. Think you can help me?
Basically my script installs my favorite programs to an ubuntu system. Some of the programs are not in the depository and therefore you have to install offsite. However, some of them have different installer files for different architectures.
Pseudo code:
if [firstlineoflscpu = Architecture:          x86_64]
then install Blahblah
else blahblahblah
fi

A: To answer your question:
if lscpu | grep Architecture | grep -q x86_64
then
  # install 64-bit version
else
  # something else
fi

However, notice the uname command, which may be more direct:
$ uname -i
x86_64

redpajama_set_name: RedPajamaStackExchange


text:
Q: RevTex Proceeding Style I'm using the asprev4-1 bibliography style and trying to follow the Physical Review style guide. This mostly works but I am having issues with Proceeding references. In the style it asks for "Author in Proceeding etc." however the style seems to ignore authors for proceedings.
This is pretty frustrating as I would have assumed the style guide and the apsrev4-1 default would match up.
Is there a default style I have to use that maybe I'm unaware of? Here is what I'm using at the moment.
@proceedings{Barrett_RotationReview,
  title = {\text{B. Barret et al. in} Proc.\ of the International School of
Physics "Enrico Fermi", Varenna, Italy
      (Varenna, Italy, July 2013)},
  author = {Barrett, B and Gominet, P.-A and Cantin, E and Antoni-Micollier,
L and Bertoldi, A and Battelier, B and Bouyer, P and Lautier, J and
Landragin, A},
  volume = 188,
  series = {Atom Interferometery},
  publisher = {IOS Press},
  address = {Varenna, Italy},
  year = {2014},
  pages = {493-555},
  doi = {10.3254/978-1-61499-448-0-493},
}

A: As if the universe wanted to paint me the fool, I found the solution just after posting my question, despite furious Googling before...
The below style using @inproceedings seems to work.
@inproceedings{label,
Author = {Smith J. and others},
Editor = {{Publisher}},
Title = {{Proceeding Title}},
Booktitle = {{Proceedings of Conference Title (Acronym YEAR)}},
Series = {},
Year = {{}},
Volume = {{}},
Pages = {{}},
Note = {{Conference Title (acronym),
   City, Country, Date, Year}},
Organization = {},
DOI = {{}},
ISSN = {{}},
}


text:
Q: Silex match GET but no POST Something extremely unusual is happening to me. I have a simple REST API application that handle everything with ControllerProviders. So, in controllers.php I defined
$app->mount('/login', new Portcontrol\Provider\Controller\LoginControllerProvider);
$app->mount('/board', new Portcontrol\Provider\Controller\BoardControllerProvider);
$app->mount('/group', new Portcontrol\Provider\Controller\GroupControllerProvider);

Next, for example I created the LoginControllerProvider in this manner:
public function connect(Application $app)
{
    $controllers = $app['controllers_factory'];

    $controllers->match('/', 'Portcontrol\Controller\Login\LoginController::indexAction');

    return $controllers;
}

The stranger thing is that when I request with a GET, the controller respons BUT when I request a POST the engine say to me that is not found. Is the same file and I actually need the POST method because I expect the idToken of Google to authenticate.
I try to change match to post, but is the same, the result of POST request is the default Silex Page not found.
This is a fragment of my LoginController:
    class LoginController{

        public function indexAction(Application $app, Request $request){
            Constants::resetlog("/login");

            $data = json_decode($request->getContent(), true);
            $request->request->replace(is_array($data) ? $data : array());

            if ($request->request->get('idToken')){
                Constants::log("/login: G");

                /*
                $client = new Google_Client(['client_id' => Constants::client_id()]);
                $payload = $client->verifyIdToken($request->request->get("idToken"));
                */

                //PAYLOAD TO TEST WITHOUT GOING TO GOOGLE
                $payload = Constants::test_payload();

                if ($payload) {
                    if ($this->toDatabase($payload, $request->request->get('serverAuthCode')))
                        return $this->loginSuccessResponse($request->request->get('serverAuthCode'));
                }
            }
            return Constants::failResponse();
        }


text:
Q: ng-repeat and compound filter in 1.3.6 I've only started learning angular. I decided to upgrade my 1.2 examples to the current version. I spotted that filter doesn't work anymore. It broke in 1.3.6.
I'm no longer able to filter by 2 fields of collection objects.
http://plnkr.co/edit/Mpo5UDvzjUWIToTZo142?p=preview
<li class="animate-repeat" ng-repeat="friend in friends | filter:{age:a,name:q }">

How to get this behaviour back? Ultimately I want ng-repeat to display custom directives enclosing content of each friend.
Will the filter work when I reformat my code?
thanks

A: Your code is perfectly working. You should simply not forget to initialize the variables used in the filter predicate, since they are supposed to be strings, according to the documentation:
// In the controller
$scope.a = '';
$scope.q = '';

As a side note, please use more meaningful names for your variables.


text:
Q: selecting rows which contain certain characters I am working with a product database and i need to select products that are greater than £150 also only entries that have "HP" in the third and forth position of the prod_id.
So far i have tried
SELECT * FROM products WHERE prod_id LIKE 'hp%';

Here is a pic of the table i need to query

A: SELECT * FROM products WHERE prod_id LIKE '__hp%' and price > 150;

"_" (underscore) is any symbol (there are 2 undrscores in this query)

A: An underscore will match a single character.
So:
SELECT * FROM products
WHERE prod_id LIKE '__hp%'
AND price > 150;

Should find all products whos 3rd and 4th character are hp and have a price of 150 or more


text:
Q: Utility for syntax validation I have very unique situation where the syntax needs to be validated only for the AND,OR,NOT without any value assignment using any programming language.Any direct utilities would be great.Any suggesstions are appreciated.
Example
q or not (p and r) -Valid
q not or p or q    -Not Valid
My starting point is this any suggestions on top this.It parses but I am trying to figure out a way to find valid vs not valid.
import pyparsing as pp

operator = pp.Regex("AND|OR|NOT").setName("operator")
number = pp.Regex(r"[+-]?\d+(:?\.\d*)?(:?[eE][+-]?\d+)?")
identifier = pp.Word(pp.alphas, pp.alphanums + "_")
comparison_term = identifier | number
condition = pp.Group(comparison_term + operator + comparison_term)

expr = pp.operatorPrecedence(condition,[
                            ("NOT", 1, pp.opAssoc.RIGHT, ),
                            ("AND", 2, pp.opAssoc.LEFT, ),
                            ("OR", 2, pp.opAssoc.LEFT, ),
                            ])

#x=expr.parseString("P AND Q OR X AND Y")
x=expr.parseString("P AND Q NOT X AND Y")

print(x)

A: I think you meant to define operator here as:
operator = pp.oneOf("< > = <= >= !=").setName("operator")

and to get your parser to match your input strings, condition must also accept just plain identifiers:
condition = pp.Group(comparison_term + operator + comparison_term) | identifier

Now you can run your parser using expr.runTests:
expr.runTests("""\
    P AND Q NOT X AND Y
    P AND Q AND NOT X AND Y
    P AND Q > 1000 OR NOT Z
    """, fullDump=False)

prints:
P AND Q NOT X AND Y
        ^
FAIL: Expected end of text, found 'N'  (at char 8), (line:1, col:9)

P AND Q AND NOT X AND Y
[['P', 'AND', 'Q', 'AND', ['NOT', 'X'], 'AND', 'Y']]

P AND Q > 1000 OR NOT Z
[[['P', 'AND', ['Q', '>', '1000']], 'OR', ['NOT', 'Z']]

EDIT: To capture parsing errors, you would not use runTests (though runTests is good for parser testing). Instead you would call parseString inside a Python try-except block, and capture ParseExceptions:
try:
    results = expr.parseString(user_input)
except ParseException as pe:
    print("error at", pe.loc)

ParseExceptions have helpful attributes like lineno, col, loc and line. You can read more about how to use them here https://pyparsing-docs.readthedocs.io/en/pyparsing_2.4.6/pyparsing.html?highlight=ParseException#pyparsing.ParseException .


text:
Q: Keras - Dense and Conv2D values Images that I would like to use to train the network are about the size of 4000px*3000px and about 40k of them, sorted in 250 classes.
I have made a CNN shown below:
model = keras.Sequential([
    layers.Input((imgHeight, imgWidth, 1)),
    layers.Conv2D(16, 3, padding = 'same'), # filters, kernel_size
    layers.Conv2D(32, 3, padding = 'same'),
    layers.MaxPooling2D(),
    layers.Flatten(),
    layers.Dense(250),
])

How do I figure out what layers.Conv2D(*16*, ...), a value I need?
How do I figure out what layers.Dense(*250*), a value I need?
Because I can't start the training process, I'm running out of memory.

A: The output shape of the Flatten() layer is 96 Million, and so the final dense layer of your model has 24 Billion parameters, this is why you are running out of memory. There are some steps you can take to fix this issue:
Try resizing your images to a smaller shape, if 4000x3000x1 isn't necessary, 160x160x1 would be a good choice.
Try using more Conv2D layers followed by a MaxPool2D layer to decrease the size of the input, and then finally at the end, use a Flatten layer followed by a Dense layer.
For example:
model = keras.Sequential([
    layers.Input((160, 160, 1)),
    layers.Conv2D(32, 3, padding = 'same'),
    layers.Conv2D(32, 3, padding = 'same'),
    layers.MaxPooling2D((2,2)),

    layers.Conv2D(64, 3, padding = 'same'),
    layers.Conv2D(64, 3, padding = 'same'),
    layers.MaxPooling2D((2,2)),

    layers.Conv2D(128, 3, padding = 'same'),
    layers.Conv2D(128, 3, padding = 'same'),
    layers.MaxPooling2D((2,2)),

    layers.Conv2D(256, 3, padding = 'same'),
    layers.Conv2D(256, 3, padding = 'same'),
    layers.MaxPooling2D((2,2)),

    layers.Flatten(),

    layers.Dense(512),
    layers.Dense(250),
])

This type of architecture will work well if you are doing a classification task, and will not run out of memory.


text:
Q: how to replace protocol in geoext.form.formpanel I've been scratching my head over this and I'm wondering if this is possible. I want to replace the protocol of the GeoExt.form.FormPanel in the following way:

*

*to render the formpanel, I defined a variable "proto" as null outside the formpanel (var proto = null).

*then "proto" goes inside the formpanel (protocol: proto).

*in the handler function of the button a new variable "proto" is defined. I want to replace this new variable inside the formpanel.

Since extjs, geoext, openlayers are javascript libraries, I've tried things such as "eval" to make the variable "proto" inside the handler accessible in the formpanel but no luck so far. Here it is a simplified example to show this:
var proto = null;

var formPanel = new GeoExt.form.FormPanel({
    protocol: proto,                # <--- replace with [1]
    items: [{
        xtype: "combo",
        id: "idcombo",
        etc...
    }, {
        xtype: "textfield",
        id: "idtext",
        etc...
    }],
    button:[{
        text: "search",
        handler: function() {
            formPanel.search();
            var combo = Ext.getCmp('idcombo').getValue();      # <--- this works and gets the value chosen in "xtype: combo"
            var proto: new OpenLayers.Protocol.HTTP({          # <--- [1] (ie. new variable "proto")
                url: "http://www.pub.pub/" + combo + "/somestuff/",    # <--- this works
                format: etc...
            })
        }
    }]
})

how could I do this? I'll appreciate your support, thanks in advance.
Best regards,
Gery

A: The solution was to use only "protocol.options.url = newUrl;" instead of protocol.destroy(); or protocol.read();, a complete explanation is here


text:
Q: Sufficient condition for Independence of two random variables $X$, $W$, and $Y=\frac{X}{\sigma_x}-\frac{ρ(x, w)*W}{\sigma_w}$ are normal random variables with probability density functions $f(x)$, $f(w)$ and $f(y)$.  $X$ and $W$ are bivariate normal,  $f(x) * f(y)$ has a bivariate normal distribution with $ρ(x,y)=0$. I'm wondering how I can conclude from above that X and Y are independent. Also is there a way to derive $f(x,y)$?

A: They need not be independent. For example if $X$ has $N(0,1)$ distribution and $Y=X$ then $f=g$ and  $f(x)g(y)$ is the density of $(U,V)$ where $U,V$ are i.i.d. standard normal variables. But $X$ and $Y$ are not independent.

A: Note that direct calculations give:
$$ {\rm cov}(Y,W) = 0 $$
$$ {\rm cov}(Y,X) = \sigma_{X}(1-\rho_{X,W}^2) $$
So, $X$ and $Y$ can't be independent for $\rho_{X,W} \not= \pm1$.
One general way to go after the joint pdf $f_{X,Y}$ is to compute the joint characteristic function:
$$\phi_{X,Y} (t,u)= \mathbf{E}\left[\exp\left( itX + iuY  \right)\right] $$
$$ = \mathbf{E}\left[\exp\left( i(t +u\sigma_X^{-1})X - i (u\rho_{X,W}\sigma_W^{-1} )W \right)\right]   $$
$$  = \phi_{X,W} \left(t +u\sigma_X^{-1}, -u\rho_{X,W}\sigma_W^{-1}\right)  $$
Note that $\phi_{X,W}$ is explicit for joint normal pairs like $(X,W)$.
Using inversion formula for Fourier transform, one can then recover the joint pdf:
$$ f_{X,Y} (x,y)= (4\pi^2)^{-1} \iint_{\mathbb{R}^2}  \phi_{X,Y} (t,u) \exp (-it x -i uy ) dt du.   $$
I'm not sure if last integral is explicit.


text:
Q: Trying to load data from a json file via http request So I have this Angular app, and right now we're just loading data from a json file until my friends get the database up and running, but I"m having an issue: the data never seems to load. Can anybody look at my code and tell me what I'm doing wrong? Here's my data service code:
export class DataService {
  public positionsData: Position = {
      id: 'empty',
      name: 'empty',
      title: 'empty',
      routing: 'empty',
      email: 'empty',
      children: []
  };
  public loaded = false;

  constructor(private http: HttpClient) {
    setTimeout(() => {this.loadData}, 15);
  }

  loadData(): void {
    this.http.get<Position>('./sponsorview_data_4_22.json').subscribe( (updatedPositions: Position) => { this.positionsData = updatedPositions; this.loaded = true;});
  }

and here's the component where I need that data:
ngOnInit(): void {
    this.authSubscription = this.accountService.getAuthenticationState().subscribe(account => (this.account = account));
    if(!this.dataService.loaded) {
        this.datasource = this.dataService.getPositions();
        setTimeout(() => {this.loadDatasource();}, 370)
    }

}

  loadDatasource(): void {
    console.log('one round in loadDatasource');
    if(this.dataService.loaded) {
        console.log("data loaded and initialized");
        this.datasource = this.dataService.getPositionsToDepth(this.dataService.getPositions(), 3);
        this.rootViewNodeId = this.datasource.id;
        this.focusedNodeId = this.datasource.id;setTimeout(this.loadDatasource, 37);

    } else {
        setTimeout(() => {this.loadDatasource()}, 370)
        console.log("data not yet loaded");
    }

  }

A: I don't think you should be calling an Http request on a JSON without a server. Alternatively, you can get the JSON data directly like this.
this.positionsData = JSON.parse('./sponsorview_data_4_22.json');


text:
Q: What are some examples of transverse waves which are not electromagnetic in nature? Electromagnetic waves are transverse in nature.What are some other kind of non electromagnetic waves which are also transverse in nature?

A: A violin string. Vibrating strings are typically the first time that physics students encounter waves. The (one-dimensional) wave equation emerges naturally from considering the acceleration of a small string segment due to its tension and curvature in the limit of small transverse displacement.

A: Transverse waves happen in elastic solids. The oscillations are made as the solid atoms/molecules are displaced away from their relaxed position, in directions perpendicular to the propagation of the wave. This sort of wave is also called shear waves, secondary waves or S-waves, esp. in seismology. The velocity of a shear wave is controlled by the shear modulus ($G$) as follows:
$$v_s=\sqrt{\frac{G}{\rho}}\space,$$
where $\rho$ is the density of the solid.

A: In addition to a string or a whip, transverse waves exist on a membrane of a drum, in elastic solids (shear waves, such as secondary or S-waves in seismology), waves on the surface of a liquid (e.g. a lake), waves on the surface of an inflated balloon (e.g. a soap bubble). Some of transverse waves can coexist with longitudinal waves. E.g., both types can propagate at the same time in elastic solids. Gravitational waves are also transverse.
Transvese wave


text:
Q: an api for searching packages/libraries in unpkg like the cdnjsAPI? pardon if it is a silly question, I am trying to make a Javascript code editor React app and I have come across the need to add external javascript libraries as dependencies to the editor(not for the app to run, but for the editor inside it). I found the cdnjs API https://api.cdnjs.com/ which would have been perfect except for the fact that certain libraries like ml5js are not to be found in here. However if there was some way I could search unpkg like this, I could add particular libraries according to the user's choice. So, is there some api like that which could return a json object containing the list of libraries with their unpkg cdns, matching the queries sent for the library names?
Or, is there any other way I could get search from a list of javascript libraries other than unpkg?

A: There is no official way to search for UNPKG packages but there is a third part website https://www.unpkgsearch.com/
You can search for packages and directly copy the unpkg link


text:
Q: Strange entry in Apache log in my previous post I got something weird in Apache log. Again, I found something strange, but what freaks me out is the response code. It's not 501 anymore, but 200. What do you say? Should I enable the paranoid-mode? Here's the entry:
***.***.***.*** - - [02/Feb/2011:00:42:51 +0100] "=\xa29)\x84\x11\xd0O\xa7@\xbd\x8f\xc4G\x96T\xf4" 200 25564

A: It wasn't a valid HTTP-request. You could get similar log entry doing something like telnet youserver 80 and then Entering 'HELLO'. I guess there's some index.php at the root of your server?

A: If memory serves 200 is a HTTP Status code for OK
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
From wikipedia

2xx Success
This class of status codes indicates
  the action requested by the client was
  received, understood, accepted and
  processed successfully.
200 OK
      Standard response for successful HTTP requests. The actual response
  will depend on the request method
  used. In a GET request, the response
  will contain an entity corresponding
  to the requested resource. In a POST
  request the response will contain an
  entity describing or containing the
  result of the action.


text:
Q: Unit testing strategy I have to admit I'm quite new to unit testing and there is a lot questions for me.
It's hard to name it but I think it's behaviour test, anyways let me go straight to the example:
I need to test users roles listing to make sure that my endpoint is working correctly and returns all user roles assigned to him.
That means:

*

*I need to create user

*I need to create role

*I need to assign created role to created user

As we can see there is three operations that must be excecuted before actual test and I believe that in larger applications such list can grow to much larger number of operations and even complex.
The question is how I should test such endpoints: should I just insert raw data to DB, write some code blocks that would do such preparations.

A: It's probably best if you test the individual units of your service without hitting the service itself, otherwise you're also unit testing the WebApi framework itself.
This will also allow you to mock your database so you don't have to rely on any stored data to run your tests or the authorization to your service.


text:
Q: Why does merely writing SeriesData[] with zeros give an error, even if it is never called? Bug introduced in 8.0 or earlier and fixed in 11.0.0

Why does the code
Function[t, SeriesData[t, 0, {0}, 0, 1, 1]]

give me the following error?
First::nofirst: {} has zero length and no first element.

First, why in the world is SeriesData even evaluated inside the Function?
Second, what exactly is the error? Can't a series be zero?

A: This is a formatting issue, that I think should be reported to WRI.
Quick and dirty workaround could be something like this:
Unprotect[SeriesData];
SeriesData /: MakeBoxes[
    ser : SeriesData[
        x_, x0_,
        {__?(Function[Null, MiscDump`effectiveSign@HoldComplete[#] === "0", HoldAllComplete])},
        nmin_Integer, nmax_Integer, den_Integer
    ],
    fmt_
] :=
    MakeBoxes[SeriesData[x, x0, {}, nmin, nmax, den], fmt]
Protect[SeriesData];

Now outputting held series data doesn't result in error messages.
SeriesData[t, 0, {0}, 0, 1, 1] // Hold
SeriesData[t, 0, {0.}, 0, 1, 1] // Hold
SeriesData[t, 0, {0 a}, 0, 1, 1] // Hold
SeriesData[t, 0, {Print["leak"] 0}, 0, 1, 1] // Hold
SeriesData[t, 0, {0, 0., 0 a, Print["leak"] 0}, 0, 1, 1] // Hold
(* Hold[O[t]^1]  (in all cases) *)

In Function[t, SeriesData[t, 0, {0}, 0, 1, 1]] expression SeriesData[t, 0, {0}, 0, 1, 1] is not evaluated, but when this expression is outputted in the FrontEnd it is formatted.
Rules used for formatting of SeriesData can be found in FormatValues[SeriesData]. We can see there two rules: first for empty list of coefficients, second for non-empty. In second rule we can find DeleteCases[MiscDump`signsAndTerms, {"0", _}] code followed by First[MiscDump`signsAndTerms], where MiscDump`signsAndTerms is list containing certain special representation of series terms. Above DeleteCases removes terms corresponding to 0 coefficients.
It seems that possibility that there will be only 0 coefficients was overlooked and in such case First[MiscDump`signsAndTerms] receives empty list which results in First::nofirst error.
Formatting of non-held SeriesData expression with zero-only coefficients does not result in error, because such expression evaluates to SeriesData with empty list of coefficients which is covered by first formatting rule.
SeriesData[t, 0, {0}, 0, 1, 1] // InputForm
(* SeriesData[t, 0, {}, 1, 1, 1] *)


text:
Q: wrap each custom post taxonomy term within an li - using a foreach loop I'm trying to display a number of custom post taxonomy terms - but each within their own specific list item.
I have a site which is about garages. (developing on localhost so don't have a link yet).
I have a custom post type called Cars. Within this I have a custom post taxonomy with the make of the Car 'Ford' in this case.
Within 'Ford' is a list of custom post taxonomy terms of all the ford cars at that garage. 'GT', 'Sierra', 'Orion'.
Instead of listing the terms: 'GT', 'Sierra', 'Orion'. I want to show a picture of the car within a ul list.
I've created a sprite with all the images and want to loop through these setting the background position for each li item.
The first lot of code below displays a list of of the terms which is all good, but not what I want. Right at the bottom is the code which I've tried to add the list items to but just getting a blank screen...
Any help, much appreciated. Thanks
<?php if ( get_post_type() == cars ) { ?>

            <?php
            $terms = get_the_terms( $post->ID, 'ford' );

            if ( $terms && ! is_wp_error( $terms ) ) :

                 $draught_links = array();

             foreach ( $terms as $term ) {
                 $draught_links[] = $term->name;
             }

              $on_draught = join( ", ", $draught_links );
              ?>

             <?php echo $on_draught; ?>

         <?php endif; ?>

 <?php } ?>

And here's where I've tried to add the list items.
<?php if ( get_post_type() == cars ) { ?>

            <?php
            $terms = get_the_terms( $post->ID, 'ford' );

            if ( $terms && ! is_wp_error( $terms ) ) :

                $draught_links = array();

            foreach ( $terms as $term ) {

                if ($term->name == 'gt') {
                    $term->name = '
' . $term->name . '
';
                 }
                 if ($term->name == 'sierra') {
                    $term->name = '
' . $term->name . '
';
                 }
                 if ($term->name == 'orion') {
                    $term->name = '
' . $term->name . '
';
                 }
                $draught_links[] = $term->name;
            }

            $on_draught = join( ", ", $draught_links );
            ?>

            <?php echo '
' . $on_draught . '
; ?>

        <?php endif; ?>

<?php } ?>

A: I worked it out. Below is the code for anyone that is looking to replace custom post taxonomy list terms with individual images which are link to the term archive.
Source http://codex.wordpress.org/Function_Reference/get_term_link
<?php if ( get_post_type() == cars ) { ?>

        <?php

        $terms = get_terms('ford');

        echo '
';

        foreach ($terms as $term) {
            echo '
name.'">slug, 'ford').'">
';
        }

        echo '
'; ?>

<?php } ?>


text:
Q: How do I implement card swipeup in RecyclerView,GridLayout? I have a recycler view and cards.I want a gesture like swipe-up to remove the card.My code is:
        recyclerView = (RecyclerView) findViewById(R.id.recycler_view);
        data_list = new ArrayList<>();
        load_data();
        gridLayoutManager = new GridLayoutManager(this, 1,LinearLayoutManager.HORIZONTAL,false);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setHasFixedSize(true);
        adapter = new CustomAdapter(this,data_list);
        recyclerView.setAdapter(adapter);

CustomAdapterClass:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {

private Context context;
private List<MyData> my_data;

public CustomAdapter(Context context, List<MyData> my_data) {
    this.context = context;
    this.my_data = my_data;
}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType)
{
    View itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.card,parent,false);
    itemView.setMinimumWidth(parent.getMeasuredWidth());
    itemView.setMinimumHeight(parent.getMeasuredHeightAndState());
    return new ViewHolder(itemView);
}

@Override
public void onBindViewHolder(ViewHolder holder, int position)
{
    holder.userstory.setText(my_data.get(position).getUserstory());
    holder.tasks.setText(my_data.get(position).getTask());
    holder.actual.setText(my_data.get(position).getActuals());
    holder.estimate.setText(my_data.get(position).getTodos());

}

@Override
public int getItemCount()
{
    return my_data.size();
}

public  class ViewHolder extends  RecyclerView.ViewHolder
{
    public TextView userstory,tasks,actual,estimate;
    public CircularSeekBar seekbar;

    public ViewHolder(View itemView)
    {
        super(itemView);
        userstory=(TextView) itemView.findViewById(R.id.tvUserStory);
        tasks=(TextView) itemView.findViewById(R.id.tvTask);
        actual=(TextView) itemView.findViewById(R.id.tvActual);
        estimate=(TextView) itemView.findViewById(R.id.tvEstimate);
    }
}
}

I am getting the cards in horizontal scroll view.I want to add swipe gesture to dismiss it
how do I achieve this?

A: Use ItemTouchHelper for recyclerview
Add these lines in onCreate() method of activty.
 ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleItemTouchCallback);
 itemTouchHelper.attachToRecyclerView(recyclerView);

And then define Callback for ItemTouchHelper..
ItemTouchHelper.SimpleCallback simpleItemTouchCallback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {

        @Override
        public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
            Toast.makeText(context, "on Move", Toast.LENGTH_SHORT).show();
            return false;
        }

        @Override
        public void onSwiped(final RecyclerView.ViewHolder viewHolder, int swipeDir) {

              Toast.makeText(context, "on Swipe", Toast.LENGTH_SHORT).show();
        }
    };

If you want to get back your swiped data/card then just use this line..
adapter.notifyItemChanged(viewHolder.getAdapterPosition());

you can visit :- https://developer.android.com/reference/android/support/v7/widget/helper/ItemTouchHelper.html


text:
Q: why load,render method is call when download png in highcharts when I export the PNG from Highcharts it call load and render function that means it reloads the chart.
can we restrict calls to load and render events of highcharts when we export the png?

A: Thanks @SebastianWędzel for your help I will try you solution as well.
but this Solved my problem exporting: { chartOptions: { chart: { event:null }, }


text:
Q: How to check if a c++ vector already contains and element with a specific value (in this case a struct)? I need to check if an element with a specific value already exists in a c++ vector before adding a new one (to avoid duplicates).
I checked everything and this solution (simplified code below) seems to be the most efficient, if only it did work.
The problem I'm having is specifically with this line:
"if(std::find(positions.begin(), positions.end(), pos) != positions.end())",
which gives me compile errors inside the  library, saying "Invalid operands to binary expression ('position' and 'const position')".
I know I am a bit of a newbie in c++ and I am sorry if this is e bit of a dumb question, but can anyone tell me what am I doing wrong?
Is it the fact that the value is a struct? Does it have anything to do with values vs. pointers/references (I suspect it does)?
struct position
{
    int column;
    int row;
};

int main ()
{
    std::vector<position> positions = {{0,0}, {0,1}, {0,2}, {1,0}, {1,1}, {1,2}};

    position pos = {2,1};

    if(std::find(positions.begin(), positions.end(), pos) != positions.end())
    {

        positions.push_back(pos);
    }
    else
    {
        std::cout << "Value is already present" << std::endl;
    }

    return 0;
}

I am clueless and really stuck with this, which is preventing me to advance in my project.
Does any one have an idea of what am I doing wrong or how should I do this?
Many thanks!

A: Two things are wrong here (there may be others but these are the relevant ones).
First, there is no equality operator in your structure that would allow find to compare items. This can be added with something like:
struct position {
    int column;
    int row;
    bool operator==(const position &other) const {
        return column == other.column && row == other.row;
    }
};

Second, the sense of your comparison is wrong. The find will return end if the item is not found, so your if section should be:
if (std::find(positions.begin(), positions.end(), pos) == positions.end()) {
    positions.push_back(pos);
} else {
    std::cout << "Value is already present" << std::endl;
}

For completeness, here's a full program that shows what happens when you try to add a non-existant element three times:
#include <iostream>
#include <vector>
#include <algorithm>

struct position {
    int column;
    int row;
    bool operator==(const position &other) const {
        return column == other.column && row == other.row;
    }
};

int main () {
    std::vector<position> vec = {};

    position pos = {2,1};
    for (int i = 0; i < 3; ++i) {
        if (std::find(vec.begin(), vec.end(), pos) == vec.end()) {
            std::cout << "Adding value" << std::endl;
            vec.push_back(pos);
        } else {
            std::cout << "Value is already present" << std::endl;
        }
    }

    return 0;
}

From the ouput, you can see only the first one actually inserts:
Adding value
Value is already present
Value is already present


text:
Q: javascript regex for special condition I am trying to create regex for below condition:
Allowed characters: letters (a-z) (not case sensitive), min-length: 1, max-length: 255.
Numbers and Special Characters (except @,$,%,^) are only allowed in combination with words (a-z texts).
Consecutive special characters are not allowed.
Numbers (up to 4 together) and/or 1 special character can appear in combination with words.
Ex:

9900Acres
Grey  Hound!
[Roy]Media
Cool,boy

are all allowed.
I can't seem to get the hang of it.
I tried creating this regex -
^(?:((([0-9]{0,4})[ ]{0,})([!#&*()<,>.?/{}\[\]_-]{0,1})([0-9]{0,4})[a-zA-Z]{1,255}(([0-9]{0,4})([ ]{0,})([0-9]{0,4}))([!#&*()<,>.?/{}\[\]_-]{0,1}))+){3,}$

but with no success

A: challenge accepted:
instead of one mega-regex, break it down:
function isValid(text = '') {
  if (!text.length || text.length > 255) {
    return false;
  }

  // check if there are more than 4 consecutive numbers
  if (/[0-9]{5,}/.test(text)) {
    return false;
  }

  // check if there are 2 consecutive special characters
  if (/[!#&*()<,>.?/{}[\]_-]{2,}/.test(text)) {
    return false;
  }

  return true; // should be fine ?
}

console.log(isValid('9900Acres')); // true
console.log(isValid('Grey Hound!')); // true
console.log(isValid('[Roy]Media')); // true
console.log(isValid('Cool,boy')); // true

A: Try with this:
^(?=.*[A-Za-z])(?!.*[^a-zA-Z\d\n]{2})(?!(?:.*[^\da-zA-Z\n])?\d+(?:[^\da-zA-Z\n].*)?$)[ !#&*()<,>.?\/{}\[\]\w-]{1,255}$

Explained:
^ # Start of line / String

    # Lookahead: whatever + some letter
    (?=.*[A-Za-z])

    # negative lookahead: whatever + 2 consecutive forbidden characters
    (?!.*[^a-zA-Z\d\n]{2})

    # negative lookahead to forbid numbers without letters on some of the sides:
    (?!
        (?:.*[^\da-zA-Z\n])?  # Optional: something + special character
        \d+                   # numbers
        (?:[^\da-zA-Z\n].*)?$ # Optional: special character + something + end of string
    )

    # All allowed characters 1 to 255 times
    [ !#&*()<,>.?\/{}\[\]\w-]{1,255}
$ # End of line / string

You have a demo here


text:
Q: What is the data type returned by getopt in Python I have following use of getopt in my code:
opts, args = getopt.getopt(sys.argv[1:], "", ["admit=", "wardName="])

Then I run the code from command line in the following matter:
Test.py --args --admit=1 --wardName="CCU"

When I print the contents of opts, I get the following output:
[('--admit', '1'), ('--wardName', 'CCU')]

The first question is what is the data type of this result? It seems to me like a list of tuples. Is that correct?
The second question - is there any convenient way to work with such tuple pairs (if these ARE tuples)? For example, how can I now say: if admit == 1 then do X?
I thought of converting the tuples to a dictionary, but is that a good practice?
P.S. It shouldn't make any difference this is actually Jython and not pure Python.

A: The front page of the Python docs describes the Python Library docs as "keep this under your pillow".  The page on getopt is at:
http://docs.python.org/2/library/getopt.html
You get two lists back from getopt: That list of tuples that you mentioned, followed by the list of remaining arguments after all the options have been parsed out.  Try this:
import getopt
args = ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2']
opts, args = getopt.getopt(args, "abc:d")
print ("opts=" + str(opts))
print ("args=" + str(args))
optdic = dict(opts) # convert options to dictionary
print ("optdic['-c'] = " + str(optdic['-c']))

output:
opts=[('-a', ''), ('-b', ''), ('-c', 'foo'), ('-d', '')]
args=['bar', 'a1', 'a2']
optdic['-c'] = foo

A: Yes, it is a list of tuplea. You can use type() to check.
A dictionary would work fine.
D = dict(opts)
print D['--admit']
print D['--wardName']

A: A convenient way to work with the options and values:
import getopt, sys

def main():
    try:
        opts, args = getopt.getopt(sys.argv[1:], "", ["admit=", "wardName="])
        print opts
    except getopt.GetoptError, err:
        # print help information and exit:
        print str(err)
        sys.exit(2)

    admitArg = False
    wardName = ""

    for o, a in opts:
        if o == "--admit":
            admitArg = a
        elif o == "--wardName":
            wardName = a
        else:
            assert False, "unhandled option"

    # do something with the argument values
    if admitArg:
        print "--admit is True"

    if wardName == "Foobar":
        print "wardName is Foobar!"

if __name__ == "__main__":
    main()


text:
Q: Why is Firefox (Vista) using 400MB RAM? Because of plugins/addons? Firefox on Vista has been grinding to a crawl and I just checked the RAM usage on this machine and found 400MB of RAM in use by Firefox.
Is this because of plugins/addons?

A: PLugins do play a major factor, yes. It could also relate to the number of tabs you have open, or the amount of Flash or JavaScript that is running on a page you have open.

A: Have you tried running Firefox in "safe" mode with no plugins and addons enabled?
Check the memory then and see if it makes a difference. If it does then your answer is "yes".
Also check memory with 1 tab open against your usual number. If you have lots of tabs open then you're going to have lots of pages in memory. It all adds up.

A: Not answering your actual question ("why?"), but suggesting a solution to high memory, the AFOM addon:

recovers Memory Leakage within a running instance of the Firefox browser application.

Works really well, reduced my average usage from 250MB to 80MB.

A: Here's a list of "problematic" plugins/extensions; maybe it is one of them.
This doesn't answer "why" but I thought it was an interesting comparison of how much memory the browser uses: http://www.dotnetperls.com/chrome-memory
Have any of you tried the memory managing/saving plugins for firefox?
Helps save memory from unused tabs: TooManyTabs Firefox Addon
I think there's a few more...

A: Plugins + # of Tabs + Content of Tabs


text:
Q: Why can not I place my custom textbox inside a panel or groupBox? I have a custom TextBox control defined as follows:
class PHTextBox : System.Windows.Forms.TextBox
{
    System.Drawing.Color DefaultColor;
    public string PlaceHolderText { get; set; }

    public PHTextBox(string placeholdertext)
    {
        // get default color of text
        DefaultColor = this.ForeColor;
        // Add event handler for when the control gets focus
        this.GotFocus += (object sender, EventArgs e) =>
        {
            this.Text = String.Empty;
            this.ForeColor = DefaultColor;
        };

        // add event handling when focus is lost
        this.LostFocus += (Object sender, EventArgs e) => {
            if (String.IsNullOrEmpty(this.Text) || this.Text == PlaceHolderText)
            {
                this.ForeColor = System.Drawing.Color.Gray;
                this.Text = PlaceHolderText;
            }
            else
            {
                this.ForeColor = DefaultColor;
            }
        };

        if (!string.IsNullOrEmpty(placeholdertext))
        {
            // change style
            this.ForeColor = System.Drawing.Color.Gray;

            // Add text
            PlaceHolderText = placeholdertext;
            this.Text = placeholdertext;
        }
    }
}

I am trying to add a custom textBox in the following way to a Panel:
this.tbNombresClienteConfirmarPago = new PHTextBox("Your name");
this.tbNombresClienteConfirmarPago.Location = new System.Drawing.Point(0,0);//(644, 485);
this.tbNombresClienteConfirmarPago.Name = "tbNombresClienteConfirmarPago";
this.tbNombresClienteConfirmarPago.Size = new System.Drawing.Size(203, 20);
this.tbNombresClienteConfirmarPago.TabIndex = 7;
this.tbNombresClienteConfirmarPago.MaxLength = 50;
this.panel1.Controls.Add(this.tbNombresClienteConfirmarPago);

But it does not work.
I add a textBox or a button that belong to Windows Forms and they are added correctly to the Panel without problems.
Any comment is welcomed.
Upgrade:
When I wanted to say that 'It doesn't work' I was referring to the fact that the object is not displayed inside the Panel.
A PHTextBox is displayed correctly within the form.


text:
Q: Is it possible to improve the execution performance of a query with 'simple' joins? The query is the following select statement:
select tbl1."DT_REF_TRANS", tbl1."VL_MTM",
       tbl1."VL_FUTURO", tbl1."DT_VENCIMENTO",
       tbl1."QT_PRAZODIASU", tbl1."ID_ATIVO_PASSIVO",
       tbl1."ID_CARTEIRA", tbl1."VL_MTM_ORIGEM",
       tbl1."ID_LOCAL_REGISTRO", tbl1."CD_NIVEL",
       tbl2."NO_ARQUIVO", tbl3."NO_PRODUTO",
       tbl3."ID_ENTRA_2804", tbl3."ID_ENTRA_VAR",
       tbl4."NO_MOEDA", tbl6."NO_SUBGRUPO",
       tbl5."NO_GRUPO_2804", tbl5."PERDA",
       tbl5."RENOVACAO", tbl5."PRZRENOV",
       tbl5."ANTECIPADU",
       tbl5."PRZANTECDU", tbl5."ANTECIPA",
       tbl5."DEPOSMAR", tbl5."RESERVA",
       tbl5."PERCATRASO",
       tbl5."PERCMORAM",
       tbl5."CALCATRASO", tbl5."NORMAL",
       tbl5."CODREGRA", tbl5."CODPRZAJU",
       tbl5."CD_NOVOMTM",
       tbl5."CD_DEPMARG",
       tbl5."ID_CONSOLIDA",
       tbl5."ID_TIPO_GRUPO",
       tbl7."NO_USUARIO_SIST",
       tbl8."NO_GRUPO_2804" as "GRUPOS_2804_NO_GRUPO_2804",
       tbl9."NO_GRUPO", "USUARIOS"."NO_USUARIO"
  from ((((((((("dbo".tbl1 tbl1
  left
  join "dbo".tbl2 tbl2
       on (tbl2."CD_ARQUIVO" = tbl1."CD_ARQ_ORIGEM"))
  left
  join "dbo".tbl3 tbl3
       on (tbl3."CD_PRODUTO" = tbl1."CD_PRODUTO"))
  left
  join "dbo".tbl4 tbl4
       on (tbl4."CD_MOEDA" = tbl1."CD_MOEDA"))
  left
  join "dbo".tbl6 tbl6
       on (tbl6."CD_SUBGRUPO" = tbl3."CD_SUBGRUPO"))
  left
  join "dbo".tbl5 tbl5
       on (tbl5."CD_GRUPO_2804" = tbl3."CD_GRUPO_2804"))
  left
  join "dbo".tbl7 tbl7
       on (tbl7."CD_USUARIO_SIST" = tbl5."CD_USUARIO_SIST"))
  left
  join "dbo".tbl8 tbl8
       on (tbl8."CD_GRUPO_2804" = tbl3."CD_GRUPO_2804"))
  inner join "dbo".tbl9 tbl9
       on (tbl9."CD_GRUPO" = tbl3."CD_GRUPO"))
  inner join "dbo"."USUARIOS" "USUARIOS"
       on ("USUARIOS"."CD_USUARIO" = tbl1."CD_NIVEL"))

You can see the execution plan here.
I've created and dropped indexes in columns inside the joins, have been testing with some hints ( like left loop join for example ( it helped me a lot in the past )). but, is there a way to improve a query that's not using where, or nothing else?
It's running in 30Seconds, returning 1M rows+.
Should I use IN somewhere? Exists? Some hint I don't know?
See, the question is not "hot to update THIS query". I would like to know tips to improve queries using this structure in general.

A: Many outer joins are not a best option when dealing with big tables. In a nutshell, your plan might not be as optimal as it could be when using outer joins.
Wrong RENDA_FIXA table estimation is the reason why you are getting Parallelism and Hash joins everywhere even though you are not expecting many rows in the first place.
You can try OPTION (MAXDOP 1) hint to see if that any helps.
Also you should check statistics on RENDA_FIXA and GRUPOS_USER_2804 tables.
The reason why you are getting that plan is because it expects 120,000 records, instead you're getting 1,800 that's why left loop joins helped you.
My advice is to try to deal with RENDA_FIXA table first, get the correct estimations out first, so the query optimizer could try to create a right plan.

A: Query hints can help but not always. For example, let's say you have many clients, with different data and DB size, and one with a very big database with lots of data.
The query hint you use to help improve performance on one client's database might decrease performance on another client's database.
You should always analyze the Execution plan. Look maybe for missing indexes. Are all the joins necessary? Can you change some LEFT JOIN for INNER JOIN? Are the statistics up to date?
Many factors can impact your query performance

Your query plan shows a clustered index scan of RENDA_FIXA.RENDA_FIXA_PK, with an estimanted number of rows of 128 662 and Actual number of Rows 1796.
I would check to see if statistics are up to date.
That scan takes 38% of your execution plan by itself.


text:
Q: Sorting files into folders So I have files that include time and date like this "05_14_2014_17_56_01". I want to sort them into folders by date and not time.
So what I was trying to do was get a for loop to make a directory using only the date, and putting the file in there. However the syntax of these batch files is killing me. It should be pretty simple but im having alot of trouble. Can anyone help me out with this.
I tried something like this initially
setlocal EnableDelayedExpansion
cd C:\Users\****\Downloads\test
for %%i in (*csv) do (set fileName= %%i & echo !fileName! & mkdir !fileName:~0,10%! & move %%i !fileName:~0,10%!)

pause

A: this not only works, but is even better to read:
setlocal EnableDelayedExpansion
for %%i in ("*.csv") do (
 set "fileName=%%i"
 echo !fileName!
 mkdir "!fileName:~0,10%!"
 copy "%%i" "!fileName:~0,10%!"
)
pause

I only extracted the command & command & command to individual lines.
Ah - and I removed a space, which would make trouble (with your setcommand)


text:
Q: Reading the public value of customdocumentproperties and making it selected in the ribbon
I can't read the value here when opening excel
 DocumentProperties properties;

            var wb = Globals.ThisAddIn.Application.ActiveWorkbook;
          or
            var wb = Globals.ThisAddIn.Application.ThisWorkbook;
            if (wb is null)
            {
                return "";
            }
            properties = ( DocumentProperties)wb.CustomDocumentProperties;

            foreach (DocumentProperty prop in properties)
            {
                if (prop.Name == propertyName)
                {
                    return prop.Value.ToString();
                }
            }

ActiveWorkbook and ThisWorkbook are both null when opening excel.
What I want to do is read the public value of the customdocumentproperties and make it selected in the ribbon.

A: It is not clear whether such values are known and predefined or not. Let's consider both cases then...

*

*If values are predefined you can design your custom UI based on the list of predefined controls. By using the getEnabled callback you could manage of the buttons state. For example, by default, controls are disabled and greyed out. As soon as users open a document with custom document properties you can read values and force your custom ribbon UI to refresh. The Invalidate or InvalidateControl methods of the IRibbonUI interface which allows invalidating the cached values for all of the controls (or particular one) of the Ribbon user interface.

*In the case of unknown values you can use controls that can be populated at runtime. So, when a document is opened and custom document properties are read you could populate controls at runtime by using the getContent callback from the dynamicMenu control. The callback's signature is shown below:
C#: string GetContent(IRibbonControl control)

VBA: Sub GetContent(control As IRibbonControl, ByRef content)

C++: HRESULT GetContent([in] IRibbonControl *pControl, [out, retval] BSTR *pbstrContent)

Visual Basic: Function GetContent(control As IRibbonControl) As String

Read more about the Fluent UI (aka Ribbon UI) in the following series of articles:

*

*Customizing the 2007 Office Fluent Ribbon for Developers (Part 1 of 3)

*Customizing the 2007 Office Fluent Ribbon for Developers (Part 2 of 3)

*Customizing the 2007 Office Fluent Ribbon for Developers (Part 3 of 3)


text:
Q: file to import not found or unreadable: util/util in my switch from foundation 5 to foundation 6 I used to use foundation 5 which uses compass to do the sass thing. but now i switch to foundation 6, I always cannot make it right. when running gulp,it show error:
file to import not found or unreadable: util/util

there is one answer i found here:http://foundation.zurb.com/forum/posts/36389-what-is-import-utilutil, which says foundation 6 use libsass, but i donot know libsass and do want to use compass since i have used commpass mixins and function the like in my project already.  and i tried the ways they said but not succeed.
anyone know how to use foundation 6 using compass? btw, i use command line to generate the foundation project with all the tools i need and then I copy and paste my old project using foundation 5 and grunt into the new foundation 6 Folder. Thanks.

A: Look in your settings file and double check the util import at the top is correct.


text:
Q: How many ways can I split up a string of length $n$ so that the length of the split strings add up to $n$? For example, if the string is abc, $n=3$,
then the different ways it can be split is
a/b/c($1+1+1$), a/bc($1+2$), ab/c($2+1$), abc($3$)
which is $4$ ways.
Similarly, if I have the string abcd, $n=4$, then it can be split into the following lengths:
$4,1+3,3+1,2+2,1+1+2,1+2+1,2+1+1,1+1+1+1$
which is $8$ different ways.
I can see the total number of ways is equal to $2^{n-1}$. I would like someone to explain/prove theoretically why it is so.

A: To see why it is $2^{n-1}$, represent all binary numbers from $0$ to $2^{n-1}$ (not included), say $n=3$ for "abc" we have $4$ values
00  => 0
01  => 1
10  => 2
11  => 3

with $0$ meaning "no separation", $1$ means "separation" between characters, $aS_1bS_0c$ that gives you
00  => abc
01  => ab|c
10  => a|bc
11  => a|b|c


text:
Q: Nested enumerate lists and missing \item errors When using nested enumerate environments, I am using the following syntax :
\documentclass{article}

\usepackage{enumitem}

\begin{document}
\begin{enumerate}[label*=\arabic*.]
\item A question
\stepcounter{enumi}
\begin{enumerate}[label*=\alph*.]
\item A subquestion.
\item Another subquestion.
\end{enumerate}
\end{enumerate}

\end{document}

which works just fine and displays exactly what I expect:

However, with this other example,
\documentclass{article}

\usepackage{enumitem}

\begin{document}
\begin{enumerate}[label*=\arabic*.]
\stepcounter{enumi}
\begin{enumerate}[label*=\alph*.]
\item A subquestion.
\item Another subquestion.
\end{enumerate}
\end{enumerate}

\end{document}

I have a missing \item error, despite of an output corresponding to my expectations.
What would be a correct way of proceeding in order to avoid such errors ?
And a related question (which would maybe deserve another topic): with TeXstudio, the second example does not display the PDF preview because of the compilation error, while with TeXmaker it does. Is there any way to display the PDF in case of (minor) compilation errors in TeXstudio ?

A: With a simple dummy item of no label \item[] {}, one can write this:
\documentclass{article}

\usepackage{enumitem}

\begin{document}

Some text ...
\begin{enumerate}[label*=\arabic*.]
\item[] {}
\stepcounter{enumi}
\begin{enumerate}[label*=\alph*.]
\item A subquestion.
\item Another subquestion.
\end{enumerate}
\end{enumerate}
\end{document}


text:
Q: Optimizing Cypher Query I am currently starting to work with Neo4J and it's query language cypher.
I have a multple queries that follow the same pattern.
I am doing some comparison between a SQL-Database and Neo4J.
In my Neo4J Datababase I habe one type of label (person) and one type of relationship (FRIENDSHIP). The person has the propterties personID, name, email, phone.
Now I want to have the the friends n-th degree. I also want to filter out those persons that are also friends with a lower degree.
FOr example if I want to search for the friends 3 degree I want to filter out those that are also friends first and/or second degree.
Here my query type:
MATCH (me:person {personID:'1'})-[:FRIENDSHIP*3]-(friends:person)
WHERE NOT (me:person)-[:FRIENDSHIP]-(friends:person)
AND NOT (me:person)-[:FRIENDSHIP*2]-(friends:person)
RETURN COUNT(DISTINCT friends);

I found something similiar somewhere.
This query works.
My problem is that this pattern of query is much to slow if I search for a higher degree of friendship and/or if the number of persons becomes more.
So I would really appreciate it, if somemone could help me with optimize this.

A: If you just wanted to handle depths of 3, this should return the distinct nodes that are 3 degrees away but not also less than 3 degrees away:
MATCH (me:person {personID:'1'})-[:FRIENDSHIP]-(f1:person)-[:FRIENDSHIP]-(f2:person)-[:FRIENDSHIP]-(f3:person)
RETURN apoc.coll.subtract(COLLECT(f3), COLLECT(f1) + COLLECT(f2) + me) AS result;

The above query uses the APOC function apoc.coll.subtract to remove the unwanted nodes from the result. The function also makes sure the collection contains distinct elements.
The following query is more general, and should work for any given depth (by just replacing the number after *). For example, this query will work with a depth of 4:
MATCH p=(me:person {personID:'1'})-[:FRIENDSHIP*4]-(:person)
WITH NODES(p)[0..-1] AS priors, LAST(NODES(p)) AS candidate
UNWIND priors AS prior
RETURN apoc.coll.subtract(COLLECT(DISTINCT candidate), COLLECT(DISTINCT prior)) AS result;

A: The problem with Cypher's variable-length relationship matching is that it's looking for all possible paths to that depth. This can cause unnecessary performance issues when all you're interested in are the nodes at certain depths and not the paths to them.
APOC's path expander using 'NODE_GLOBAL' uniqueness is a more efficient means of matching to nodes at inclusive depths.
When using 'NODE_GLOBAL' uniqueness, nodes are only ever visited once during traversal. Because of this, when we set the path expander's minLevel and maxLevel to be the same, the result are nodes at that level that are not present at any lower level, which is exactly the result you're trying to get.
Try this query after installing APOC:
MATCH (me:person {personID:'1'})
CALL apoc.path.expandConfig(me, {uniqueness:'NODE_GLOBAL', minLevel:4, maxLevel:4}) YIELD path
// a single path for each node at depth 4 but not at any lower depth
RETURN COUNT(path)

Of course you'll want to parameterize your inputs (personID, level) when you get the chance.


text:
Q: How to hide internal system in our task killer in android? I have a problem in our thesis, its all about the BATTERY DOCTOR SAVER what my problem is, the .api list, what i want is to get only the application that is running not the internal system because in my thesis it also show the internal system. Is there a way how to remove that internal system in our task killer? so far this is my code for getting the running application :
    public void loadRunningProcesses() {

            ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);

            List<RunningAppProcessInfo> appinfolist = activityManager
                    .getRunningAppProcesses();

            Log.d(TAG, "AppInfoList Size: " + appinfolist.size());

            for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : appinfolist) {
                TaskObject runningtask = new TaskObject();
                runningtask.setPid(runningAppProcessInfo.pid);
                runningtask.setProcessName(runningAppProcessInfo.processName);
                adapter.addTask(runningtask);
runningtask.setProcessName(runningAppProcessInfo.processName.substring(11));
            runningtask.setProcessName(runningAppProcessInfo.processName);

            }
        }

        class TaskObject {
            int pid;
            String processName;
            private boolean toKill;

            public int getPid() {
                return pid;
            }

            public void setPid(int pid) {
                this.pid = pid;
            }

            public String getProcessName() {
                return processName;
            }

            public void setProcessName(String processName) {
                this.processName = processName;
            }

            public boolean isToKill() {
                return toKill;
            }

            public void setToKill(boolean toKill) {
                this.toKill = toKill;
            }

        }

A: From Polo Ravales:

I already found a solution for this problem. I only use a substring and also make the first letter an uppercase for formality, look at my code :
for (ActivityManager.RunningAppProcessInfo runningAppProcessInfo : appinfolist) {
        TaskObject runningtask = new TaskObject();
        String ringgo = new String();

        ringgo = runningAppProcessInfo.processName.toLowerCase().trim();
        if (!ringgo.equals("system")){
            if (ringgo.length()>12){
            runningtask.setPid(runningAppProcessInfo.pid);
            runningtask.setProcessName(ringgo.substring(12).substring(0,1).toUpperCase()+ringgo.substring(13));
            adapter.addTask(runningtask);}
            else{
                runningtask.setPid(runningAppProcessInfo.pid);
                runningtask.setProcessName(ringgo.substring(0,1).toUpperCase()+ringgo.substring(1));
                adapter.addTask(runningtask);
            }
        }

    }
}


text:
Q: Menu drawer is not working in hybrid app in android by phonegap I created a android apk by using phonegap. menu drawer is working properly in html code but it is not working in android device. when i click on menu icon i dnt get any response. so am attaching screenshot of html view

this the screenshot of html page view but in android menu drawer is not working. html coding is showing below
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="format-detection" content="telephone=no" />
    <meta name="msapplication-tap-highlight" content="no" />
    <meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width" />

    <meta http-equiv="Content-Security-Policy" content="default-src * 'unsafe-inline'; style-src 'self' 'unsafe-inline'; media-src *" />

    <link rel="stylesheet" type="text/css" href="css/index.css" />
    <title>Hello World</title>

Home

Blog

Contact

About

Hybrid App

Hybrid Mobile Applications. Hybrid development combines the best (or worst) of both the native and HTML5 worlds. We define hybrid as a web app, primarily built using HTML5 and JavaScript, that is then wrapped inside a thin native container that provides access to native platform features.

Here is the code so please help me to solve the problem

A: Please register your events like that.
var app = {
    // Application Constructor
    initialize: function () {
        app.bindEvents();
    },
    bindEvents: function () {
        document.addEventListener('deviceready', app.onDeviceReady, false);
    },
    onDeviceReady: function () {

        capp.bindEvents();

    }
};
var capp = {

    bindEvents: function () {
}
};

you have to register every event because all the events will work after deviceready event.So simply use this structure and define all events in capp.
thanks


text:
Q: OpenGL error 1280 at bot beginDraw() invalid enumerant I write a program in Processing 2.1.2, to import an object as STL File and rotate it on fixed coordinates.
My program is working fine but along with that I am facing an error on bottom terminal which is :
OpenGL error 1280 at bot beginDraw(): invalid enumerant

Can you please guide me on how do I get rid from this error?
Coding of program is given below
import toxi.geom.*;
import toxi.geom.mesh.*;
import toxi.processing.*;
TriangleMesh mesh;
ToxiclibsSupport gfx;
void setup() {
  size(1000, 800,P3D);
  mesh=(TriangleMesh)new STLReader().loadBinary(sketchPath("check.stl"),STLReader.TRIANGLEMESH);
  gfx=new ToxiclibsSupport(this);

}
void draw() {

  background(51);
  translate(width/2,height/2,0);
  rotateX(radians(-4.35));   // Pitch
  rotateY(radians(180));    // Roll
  rotateZ(radians(180));   // Yaw
  directionalLight(192, 168, 128,0, -1000, -0.5);
  directionalLight(255, 64, 0, 0.5f, -0.5f, -0.1f);
  noStroke();
  scale(4);
  gfx.mesh(mesh,false);
}


text:
Q: Unable to import module 'lambda_function': No module named 'sendgrid' I am using AWS Lambda, Python 3.7 and SendGrid API and want to send an email but getting the error:
"Unable to import module 'lambda_function': No module named 'sendgrid'"

Is there a way to resolve this?  I can see that in some similar issues that the module would be imported from somewhere but can't work out from where.
My lambda code is just the sample code from the SendGrid website which values updated with the ones I want to use:
import json
import sendgrid
import os
from sendgrid.helpers.mail import *

def lambda_handler(event, context):

    sg = sendgrid.SendGridAPIClient(apikey=os.environ.get('SENDGRID_API_KEY'))
    from_email = Email("test@example.com")
    to_email = Email("****")
    subject = "Sending with SendGrid is Fun"
    content = Content("text/plain", "and easy to do anywhere, even with Python")
    mail = Mail(from_email, subject, to_email, content)
    response = sg.client.mail.send.post(request_body=mail.get())

    print(response.status_code)
    print(response.body)
    print(response.headers)

Thanks

A: The lambda environment does not have the sendgrid module available for your code to call. In order to use dependencies that aren't apart of the aws sdk or the language  (like the sendgrid library) you have to pre-build the code with the packages locally and upload a zip file. An example can be found here: aws python lambda . There is another stack overflow addressing the same question here. The second contains some tools to make uploading easier.


text:
Q: What is this string of text that looks like a URL for? To be more precise why does it have this URL like form?  It is used in my heroku appp my parsing out the host/username/passowrd/database which I use.  But why does it look like a URL address.
Is mysql a protocol?  I thought it was just a database or a command line executable in some cases.
I have found no where that I can use this URL like form that points to my database.
Even apps like sequel pro which are used to connect to mysql seem to have no use for it.
mysql://b77eeb5dd82foo:10d04foo@us-cdbr-iron-east-03.cleardb.net/heroku_37a39aa6115afoo?reconnect=true

A: That's a Data Source Name (DSN). As stated in the wiki

Software (e.g., Crystal Reports, Microsoft Excel, PHP, Perl, Python, Ruby) users can submit CRUD (Create, Read, Update, Delete) queries to a data source by establishing a connection to the DSN.

The format is
<driver>://<username>:<password>@<host>:<port>/<database>?<params>

*

*mysql: means it's a MySQL database

*b77eeb5dd82foo:10d04foo is the username and password

*us-cdbr-iron-east-03.cleardb.net is the server name

*heroku_37a39aa6115afoo is the database name

*reconnect=true is a parameter telling the driver to reconnect automatically when necessary

Most of the fields are optional; the port number is omitted from your DSN, so it uses the default (3306 for MySQL).


text:
Q: ASP.NET DataList - defining "columns/rows" when repeating horizontal and using flow layout Here is my DataList:
<asp:DataList id="DataList" Visible="false" RepeatDirection="Horizontal" Width="100%" HorizontalAlign="Justify" RepeatLayout="Flow" runat="server">
        [Contents Removed]
</asp:DataList>

This generates markup that has each item wrapped in a span. From there, I'd like to break each of these spans out into rows of three columns. Ideally I would like something like this:

 Item 1
 Item 2
 Item 3

 Item 4
 Item 5
 Item 6

[etc]

The closest I can get to this is to set RepeatColumns to "3" and then a
 is inserted after every three items in the DataList.
 Item 1
 Item 2
 Item 3

 Item 4
 Item 5
 Item 6

This gets me kind of close, but really doesn't do the trick - I still can't control the layout the way I'd like to be able to.
Can anyone suggest a way to make this better? If I could implement the above example - that would be perfect, however I'd accept a less elegant solution as well - as long as its more flexible than
 (such as inserting a  instead of
).

A: If you really needed to use a datalist for some reason instead of implementing this as a repeater, you can try doing something like this:
<asp:DataList ID="dataList" runat="server" RepeatDirection="Horizontal" Width="100%" HorizontalAlign="Justify" RepeatLayout="Flow" OnItemDataBound="dataList_ItemDataBound">
    <HeaderTemplate>

    </HeaderTemplate>
    <SeparatorTemplate>

    </SeparatorTemplate>
    <ItemTemplate>
        <%# Container.DataItem %></ItemTemplate>
    <FooterTemplate>

</FooterTemplate>
</asp:DataList>

protected void dataList_ItemDataBound(object sender, DataListItemEventArgs e) {
    if (e.Item.ItemType == ListItemType.Separator) {
        if ((e.Item.ItemIndex + 1) % 3 != 0) {
            e.Item.Controls.Clear();
        }
    }
}

A: I may be confused, but why not just use a repeater and a custom item template?

A: You can achieve your desired layout using CSS without altering the original generated markup.  Since span tags are displayed inline by default, switching to inline-block and specifying a width of 33% on those spans should do the trick.
Or more specifically, set the CssClass property of your DataList control to a value such as "threecolumns".
Define the following css style:

VS2008 might tell you that inline-block isn't a valid setting for the display property.  I wouldn't worry about that too much since almost every browser supports it.

A: add this  RepeatColumns="100000"


text:
Q: Spring (4.2.6) + Jackson (2.8.4) + Generic Type : java.util.LinkedHashMap cannot be cast to After two days, I'm stuck with the following...
If I specify the type in the controller, it works:
@RestController
public class FooController {
    @RequestMapping(method = RequestMethod.POST)
    protected ResponseModel bar(@Valid @RequestBody Foo foo) {
        // here I have foo of type Foo
    }
}

However, if I try to take advantage of generics, it doesn't work:
public class Base<U> {
    @RequestMapping(method = RequestMethod.POST)
    protected ResponseModel bar(@Valid @RequestBody U entity) {
        // here I get java.util.LinkedHashMap instead of U
        // which, in the FooController, should be Foo
    }
}

@RestController
public class FooController extends Base<Foo> {
}

Looking at the logs, when it hits the controller with defined type I get:
Read [class com...Foo] as "application/json;charset=UTF-8" with [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@cee662]

While at the generic one:
Read [U] as "application/json;charset=UTF-8" with [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@cee662]

Q: What should I do to take advantage of the Generic Type, and to be able to cut the repeated code from the controllers?
Note: this is NOT a duplicate, since all the other questions are about List<T> or from an issue on ~2.6.*
Addendum: Yuri-M-Dias suggested downgrading, which I did, so 2.5.5 works with a Generic Type, but 2.8.4 doesn't. (At least for now I have a bad and good revision to work with...)
Going further into the downgrade...
I found out that the revision 2.7.9 is a good one, I get Foo out of U, while on the 2.8.0 I get the LinkedHashMap<K,V>... maybe I missed something from the 2.8.0 release ?

A: I don't know if you happened to see Generic Controller in Spring MVC, but it may be instructive. Still, I'm not happy with what I'm about to describe, because I see what you're trying to do above. Additionally, I can't give you the reason behind the possible "necessity." Hopefully someone else will be able to fill that it.
@RestController
public class FooController extends Base<Foo> {
    @RequestMapping(method = RequestMethod.POST)
    protected ResponseModel bar(@Valid @RequestBody Foo foo) {
        super.bar(foo);
    }
}

Seems like that should make everything happy.


text:
Q: Self Joining A table I'm trying to run a query that selects all of the users from the users table and joins itself because I would like to select who it was that created the user. For some reason I'm getting the same value I do for first_name and last_name in the creator as the same user which isn't true necessarily.
user_Id, username, first_name, last_name, creator_id

1, ksmith, Kevin, Smith, 1
2, wscott, Will, Scott, 1
3, sjones, Steve, Jones, 1
4, twilliams, Tom, Williams, 4

public function get_with_creator()
{
    $this->db->select('users.user_id');
    $this->db->select('users.username');
    $this->db->select('users.first_name');
    $this->db->select('users.last_name');
    $this->db->select('users.created_at');
    $this->db->select('users.updated_at');
    $this->db->select("CONCAT(creator.first_name, ' ', creator.last_name) AS creator_name", FALSE);
    $this->db->from($this->_table);
    $this->db->join('users AS creator', 'users.user_id = creator.user_id', 'inner');
    return $this->db->get()->result();
}

A: You are joining the table(s) on users.user_id = creator.user_id.  So, it returns the same name for each field, because you are joining the same row.
You need to join on users.creator_id = creator.user_id.
DEMO: http://sqlfiddle.com/#!2/e1309/2

A: $this->db->join('users AS creator', 'users.creator_id = creator.user_id ', 'inner');


text:
Q: How to read a json from BytesIO with PySpark? I want read a json from IO variable using PySpark.
My code using pandas:
io = BytesIO()
ftp.retrbinary('RETR '+ file_name, io.write)
io.seek(0)
# With pandas
df = pd.read_json(io)

What I tried using PySpark, but don't work:
  io = BytesIO()
  ftp.retrbinary('RETR '+ file_name, io.write)
  io.seek(0)
  df = spark.read\
      .format("binaryfile")\ # I already tried with format "json"
      .option('inferSchema', 'true')\
      .option('header', 'true')\
      .json(io)

Obs: Is not possible save in a file and read that after

A: Transform io variable to json format and create a dataframe:
Bellow code:
io = BytesIO()
ftp.retrbinary('RETR '+ file_name, io.write)
io.seek(0)
data_json = io.json()
df = spark.createDataFrame(io, jsonSchema)


text:
Q: How to initialise an empty ComponentRef? Using Angular 11 and Typescript Strict mode I have:
export class ModalService {

  renderer: Renderer2;
  component?: ComponentRef<any>;
  element: HTMLElement | null;
  modal: HTMLDivElement;

  constructor(private componentFactoryResolver: ComponentFactoryResolver, private application: ApplicationRef, private rendererFactory: RendererFactory2, private popupService: PopupService) {

    this.renderer = rendererFactory.createRenderer(null, null);
    this.element = new HTMLElement();
    this.modal = new HTMLDivElement();

  }

  open(component: any, data?: any): void {

    if(this.element)
      return;

    this.renderer.addClass(document.body, 'modal');

    this.popupService.closeAll();

    const injector: Injector = Injector.create({ providers: [{ provide: 'modal', useValue: data }]});

    this.component = this.componentFactoryResolver.resolveComponentFactory(component).create(injector);

    this.component.instance.modal = this;

    this.application.attachView(this.component.hostView);

    this.element = (this.component.hostView as EmbeddedViewRef<any>).rootNodes[0] as HTMLElement;

    this.modal = document.createElement('div');

    this.modal.id = 'modal';

    this.modal.appendChild(this.element);

    document.body.appendChild(this.modal);

  }

  close(): void {

    this.application.detachView(this.component.hostView);
    this.modal.parentNode?.removeChild(this.modal);
    this.component?.destroy();
    this.element = null;
    this.renderer.removeClass(document.body, 'modal');

  }

}

I get the error:
Property 'component' has no initializer and is not definitely assigned in the constructor.

What would be the best way to solve this?
Is it possible to initialise an empty ComponentRef?

A: That could be because of strict mode.
Can you try with this?
component!: ComponentRef<any>;

Note the "!" after component.


text:
Q: How to run a visual flow with screens(Flow Type : Flow) on change of record? We have a flow with screen element which involves user input in it. This flow should be executed when user changes Opportunity stage to 'Closed Won' or 'Closed Lost'.
We don't want to use custom button here instead we have to call the flow when we change the field value.
Is there a way where we can launch flows on field change?
If not please suggest other options..

A: You can't run a flow that has interactive elements during the change to a record. You can either do so before, by using the custom button you don't want to use, or after, by using an embedded Visualforce page on the page layout, perhaps by way of changing the layout using a record type. However, at that point, the data will already be committed and the user could simply abort the flow and not complete the required process. Personally, I'd go with the custom button if it is absolutely critical that the flow run while changing the status.


text: Q: Parsin Json news-api Framework7 I am tryong to parse news from the newsapi.org into a Jquery Mobile application but it seems not to work, as follows my js into the html code. Can someone give me a glue on what happens? it only displays the page with no responde back from the news api:


text:
Q: Concatenating data descriptions and aligning to data range I have been trying to learn visual basic to write code to perform tasks when working with data in excel. I have been mostly copying snippets of code I find online and piecing them together. Currently, I have folders containing 10's of thousands of .csv files (data output from a CMM).
In each of these files column A consistently contains labels for the data and column B consistently contains the CMM data.
Currently, my program allows a user to select multiple .csv files and in a long roundabout way they all end up on one worksheet in excel with the data labels in the first column and the data in the next columns.
For example, if 10 CSV files are opened the data labels would be in the first column and the data would be in the next 10 columns.
The problem is that that the data labels are not aligned with the data and often each row of data has multiple labels.
I have been able to concatenate the data labels into one label for each row of data but cannot figure out how to align this label with the row of data.
At this point, I would be happy with a separate block of code that accomplishes this but... I suspect that my block of code that concatenates the labels could be easily modified to accomplish the task, I just haven't been able to figure it out.
So my code spits this out:
(Flatness) : Item (113)

Plane:RH_5_Mating_Surface

                                                             5.012  4.014  6.313  etc...

(Z) : Item (128) / (X) : Item (135)

Circle:Offset_Dowel_Hole

                                                             1.012  2.987  5.478  etc...

Circle:Cast_Hole_From_Offset_Dowel_Hole

                                                             2.147  7.895  4.258  etc...

Then this code concatenates the labels and spits them out in column B:
Dim rng1 As Range
Dim Lastrow As Long
Dim c As Range
Dim concat As String

Lastrow = .UsedRange.Rows(.UsedRange.Rows.Count).Row

Set rng1 = Range("A9:A" & Lastrow)
concat = ""
For Each c In rng1
If c > 0 Then
    concat = concat & " " & c.Value
    concat = Trim(concat)
Else
    c.Offset(-1, 1).Value = concat
    concat = ""
End If
Next c

The result is:
(Flatness) : Item (113) Plane:RH_5_Mating_Surface

                                                             5.012  4.014  6.313  etc...

(Z) : Item (128) / (X) : Item (135) Circle:Offset_Dowel_Hole

                                                             1.012  2.987  5.478  etc...

Circle:Cast_Hole_From_Offset_Dowel_Hole

                                                             2.147  7.895  4.258  etc...

What I need is:
I cant figure out how to show it here but...
I need the rows to match up, also note, here it shows that the data and labels are offset by the same amount but in reality they are not. So my thinking is that I need it to search for the next row containing data and put the label next to it.
I feel like I can just change this part...
Else
    c.Offset(-1, 1).Value = concat

but I don't know how to do...
I tried nesting another "For Each" here instead similar to what its already doing but with a "For Each d In rng2" where "rng2" was the data column and it would look for the next row with data and place "concat" next to the data using "d.offset(-1, -1).Value = concat"
I couldn't figure out how to get it to work...

A: This is one possible way of doing it.
Delete the empty cells and shift up in the columns. If the data order is consistent, they should line up correctly.
For i=1 to Lastrow
    If Range("A" & i).Value=""
        Range("A" & i).Delete Shift:=xlUp
    End If
    If Range("B" & i).Value=""
        Range("B" & i).Delete Shift:=xlUp
    End If
Next

You can change the range according to your sheet. Also, modify the code to use another 'IF' condition to check blanks, if that works better for your case.


text:
Q: Regular expression to join group of 5 digits I am trying to extract 10 digit phone numbers from string. In some cases the numbers are separated by space after 2 or 5 digits. How do I merge such numbers to get the final count of 10 digits?
mystr='(R) 98198 38466 (some Text) 9702977470'

import re
re.findall('\d+' , mystr)

Close, but not correct:
['98198', '38466', '9702977470']

Expected Results:
['9819838466', '9702977470']

I can write python code to concat '98198' and '38466', but I will like to know if regular expression can be used for this.

A: You could remove the non-digits first.
>>> mydigits = re.sub(r'\D', '', mystr)
>>> mydigits
'98198384669702977470'
>>> re.findall(r'.{10}', mydigits)
['9819838466', '9702977470']

A: If all the separators are one character long, this would work.
>>> re.findall(r'(?:\d.?)+\d', mystr)
['98198 38466', '9702977470']

Of course, this includes the non-digit separators in the match. A regex findall can only return some number of slices of the input string. It cannot modify them.
These are easy to remove afterwards if that's a problem.
>>> [re.sub(r'\D', '', s) for s in _]
['9819838466', '9702977470']

A:
In some cases numbers are separated by space after 2 or 5 digits.

You can use the regex:
\b(?:\d{2}\s?\d{3}|\d{5}\s)\d{5}\b
For example, this regular expression will match all of these:
01 23456789
01234 56789
0123456789

A: I doubt if you can achieve it just by a regex pattern alone. May be just use a pattern to get 10+ digits and spaces and then clean out its spaces programmatically. The below pattern should work as long as you are sure of there being some text between the phone nos.
[\d ]{10,}

A: credit goes to commenter jsonharper
\d{2} ?\d{3} ?\d{5}


text:
Q: AJAX request firing twice while success is called once I am using laravel 5.4, my Ajax functionality is called twice every time due to which I create two users however I want to create one user per click
actually it includes another page and that page don't have its on
$(document).ready(function(){

or any function like
$(document).on('click','#addproject',function(){

but they includes script tags
but if I don't include them then Ajax is called only once
Ajax call:
$(document).on('click','#addproject',function(){

        $.ajax({
            type:'get',
            url:"{!! URL::to('addProject') !!}",
            data:{},
            success:function(data){
                console.log('success');
                console.log(data);
                console.log(data.length);
                $("#newproject").fadeIn();
            },
            error:function(){

            },
        });
    });

Routes:
Route::get('/addProject','HomeController@addProject');

Controller:
  public function addProject(Request $request){
        $project = new Project;
        $data = array(
        );

        $project->create($data);
    }

A: I solved it, it turns out to be I was loading this page using load(), but I should have loaded this page using window.location.href = "updateform";
Very basic mistake though.
and solution might was my app specific.

A: maybe you could try use .one() method.
<script type="text/javascript">
var handler = function(e){

    $.ajax({
      type:'get',
      url:"{!! URL::to('addProject') !!}",
      data:{},
      success: function(data){
        console.log('success');
        console.log(data);
        console.log(data.length);
        $("#newproject").fadeIn();
        $('#addproject').one('click', handler);
      },
      error: function(){}
    });
    e.stopImmediatePropagation();
    return false;
}

$('#addproject').one('click', handler);

The one method will make sure that the handler is executed at most once per element per event type. Then after success you will need to re-bind the event handler.

A: Try this,
$("#addproject").on('click',function(){
    //your code here
});

instead of,
$(document).on('click','#addproject',function(){
    //your code
});


text:
Q: how to use cublas library I'm novice to cuda. I want to use cublas functionality in cuda programs and would like to know the procedure on how to use it. As my program is giving error i.e. *"cublas_v2.h file not present"* when I try to run it on GPU.

A: *

*The cublas documentation is contained
here.  So you
should familiarize yourself with it.

*Try and run a sample program.  There are samples in the CUDA samples that come with the CUDA 5 toolkit, or you can try the one here.  Make sure you understand how to build and run that example.

*If you're still having trouble with your own program, post a new question here with the specifics.  For example, if your program is giving error output, paste in the complete error output that you are getting, and paste in the code from your program that is generating that error output (at least).  Preferably paste in your whole program, or a simple version that will reproduce the error.

The error you're getting right now looks like it should be coming from the compiler not from when you run the program.  If so you simply need to tell the compiler where to find that header file.  If you look at a cuda sample like this one, you can see from the included makefile how to tell the compiler where to look for header files.

A: There can be multiple things because of which you must be struggling to run a code which makes use of the CuBlas library.

*

*The most important thing is to compile your source code with -lcublas flag.
It should look like nvcc -c example.cu -o example -lcublas

*Secondly, confirm whether you have Cublas Library in your system.
As it says "cublas_v2.h file not present", try doing  "whereis cublas_v2.h"
or search manually for the file, if it is not there you need to install
Cublas library from Nvidia's website.

*Confirm your Cuda Installation path and LD_LIBRARY_PATH
Your cuda path should be /usr/local/cuda.
and LD_LIBRARY_PATH should be /usr/local/cuda/lib64 OR
/usr/local/cuda/lib.


text:
Q: Implement C++ template for generating an index sequence with a given range So, C++14 provides struct make_index_sequence<N> for generating an index sequence from 0 to N-1. I am wondering how to implement one to generate an index sequence in a given range. For example:
template <size_t Min, size_t Max>
struct make_index_range;

// make_index_range<5, 9> will give index_sequence<5, 6, 7, 8>

A: The way you defined index_range (before the question was edited) the answer is simply:
template<std::size_t Min, std::size_t Max>
  using make_index_range = index_range<Min, Max>;

Which is not very useful.
So I'm going to assume you mean make_index_range<5, 9> will give index_sequence<5, 6, 7, 8>, which can be done like this:
#include <utility>

template<std::size_t N, std::size_t... Seq>
  constexpr std::index_sequence<N + Seq ...>
  add(std::index_sequence<Seq...>)
  { return {}; }

template<std::size_t Min, std::size_t Max>
  using make_index_range = decltype(add<Min>(make_index_sequence<Max-Min>()));

Or if you want make_index_range to be a class template, define add as above and then:
template<std::size_t Min, std::size_t Max>
  struct make_index_range {
    using type = decltype(add<Min>(make_index_sequence<Max-Min>()));
  };

(But with this you have to use make_index_range<5, 9>::type so the alias template is probably better, and closer to how make_index_sequence works.)


text:
Q: Create then populate colmuns in a dataframe Hello I'm trying to find a way to create new columns in a dataframe the populate them.
For example:
id = c(2, 3, 5)
v1 = c(2, 1, 7)
v2 = c(1, 9, 5)
duration=c(v1+v2)
df = data.frame(id,v1,v2,duration,stringsAsFactors=FALSE)

  id v1 v2 duration
1  2  2  1        3
2  3  1  9       10
3  5  7  5       12

Now I want to create new columns by dividing each value of  a row by the 'duration' of said row, I know how do it manually but it is prone to errors and not really elegant...
df$I_v1=v1/duration
df$I_v2=v2/duration

Or is df <- df %>% mutate(I_v1 = v1/duration) quicker/better?
  id v1 v2 duration      I_v1      I_v2
1  2  2  1        3 0.6666667 0.3333333
2  3  1  9       10 0.1000000 0.9000000

It works but I would like to know if it's possible to create -and name- the row and populate them automatically.

A: Say that you have a cols vector containing the names of the columns you want to manipulate. In your example:
cols<-c("v1","v2")

Then you can try:
df[paste0("I_",cols)]<-df[cols]/df$duration
#  id v1 v2 duration      I_v1      I_v2
#1  2  2  1        3 0.6666667 0.3333333
#2  3  1  9       10 0.1000000 0.9000000
#3  5  7  5       12 0.5833333 0.4166667

A: You can use transform():
df <- data.frame(id=c(2, 3, 5), v1=c(2, 1, 7), v2=c(1, 9, 5))
df$duration <- df$v1 + df$v2) # or ... <- with(df, v1 + v2)

df_new <- transform(df, I_v1=v1/duration, I_v2=v2/duration )

... or (if you have many columns v1, v2, ...):
as.matrix(df[, 2:3])/df$duration # or with cbind():
cbind(df, as.matrix(df[, 2:3])/df$duration)

(similar as in the answer from nicola)

A: All data frames have a row names attribute, a character vector of length the number of rows with no duplicates nor missing values. You can name the rows as:
row.names(x) <- value

Arguments:
x
object of class "data.frame", or any other class for which a method has been defined.
value
an object to be coerced to character unless an integer vector.e here


text:
Q: How To Fetch Records using MySQL With Multiple Min and Max Conditions? Table looks
StudentId, SubjcetName, Marks
1          Maths        50
1          Science      80
1          Language     70
2          Maths        80
2          Science      50
2          Language     60
3          Maths        85
3          Science      95
3          Language     60

From this table i want fetch records - Who got marks in Maths Min:50 and Max:90 and also who got marks below 75 in Science.
I Excepted results
1 Maths 50
2 Maths 80
2 Science 50
3 Maths 85

How to form a query to get the result?
Note: Subjects are dynamic and also min and max can be applicable to any subject.

A: Try this
(SELECT StudentId, SubjcetName, Marks
FROM table
WHERE SubjcetName = 'Maths'
AND Marks BETWEEN 50 AND 90)
UNION
(SELECT StudentId, SubjcetName, Marks
FROM table
WHERE SubjcetName = 'Science'
AND Marks < 75)

A: Please try below query ,
 SELECT StudentId, SubjcetName, Marks  FROM tablename
 WHERE Marks BETWEEN 50 AND 90
 AND SubjcetName="Maths"
 OR
(Marks < 75 AND SubjcetName="Science")

It is work for me.


text:
Q: Converting code from 2.7.10 to 3.4.3 I was finally able to get the recursion to print before I realized the way the professor had explained it was for 2.7 and we are supposed to be using python 3. So when I changed IDE over to 3.4.3 the code no longer works.
Any help on changing the syntax to work for 3 would be greatly appreciated I am just having no luck figuring it out.
def fibonacci(n):
    if n <= 2:
        return 1
    else:
        print("Computing fibonacci(%d) + fibonacci(%d)") % (n-1 , n-2)
        return fibonacci(n-1)+fibonacci(n-2)

A:     print("Computing fibonacci(%d) + fibonacci(%d)") % (n-1 , n-2)

This is equivalent to (whatever print returns) % (n-1 , n-2). print returns None, which doesn't support the percent operator. This explains the TypeError: unsupported operand type(s) for %: 'NoneType' and 'tuple' error.
The percent operator needs to be next to the string, rather than next to the print function. The outermost parentheses pair needs to contain your arguments.
    print("Computing fibonacci(%d) + fibonacci(%d)" % (n-1 , n-2))


text:
Q: Bash/shell code to run command on a list file of variables so for starters i have the following, main process im running
for fname in (filename); do
  ./$comma "$fname" (var1) (var2)
  mv "$fname" "${fname}.fin"
done

then i have a listfile of names looking like:
filename|var1|var2
file1|9|1
file2|8|3

etc...
would like to set it up where - when the master script goes to run the ./$comma script it reads from the listfile and populate the fname, var1, and var2 (per piped order) - right now i have a lot of repeated chunks of script like the above and would like to consolidate or clean it up for sure. Any help is appreciated - doesnt necessarily have to be a for;do loop - just as long as the script is ran on the right file with right args and gets renamed.

A: The for loop you show isn't syntactically correct. You want a while loop, though, that uses the read command.
while IFS="|" read -r fname var1 var2; do
  ./"$comma" "$fname" "$var1" "$var2"
  mv "$fname" "$fname.fin"
done < filenames.txt


text:
Q: ReferenceError: Can't find variable error I have this code:
$(document).ready(function(){
    var callPage = function(){
        $.post('/pageToCall.php');
    };

    setInterval('callPage()', 60000);
});

and it gives me the error ReferenceError: Can't find variable: callPage. Why?

A: Try setInterval(callPage, 60000);.
If you pass a string to setInterval, then this string is evaluated in global scope. The problem is that callPage is local to the ready callback, it is not global.
There is hardly ever a reason to pass a string to setInterval (setTimeout). Always pass a function (to avoid exactly this kind of errors).

A: I suspect it's because callPage is a variable scoped to the anonymous function you're creating in the document.ready event. If you move the callPage definition outside that, does it work?

A: function callPage()
{
    $.post('/pageToCall.php');
};

$(document).ready(function()
{
    setInterval('callPage()', 60000);
});

It happens because callPage's scope is the anonymous function


text:
Q: `Rmpi` unable to access all cores When trying to spawn slaves in Rmpi, I get the error
--------------------------------------------------------------------------
There are not enough slots available in the system to satisfy the 2
slots that were requested by the application:

  /opt/usern/R/4.0.4/lib/R/library/Rmpi/Rslaves.sh

Either request fewer slots for your application, or make more slots
available for use.

I know I have the hardware for several slaves:
> parallel::detectCores()
[1] 4

But how do I configure openmpi to have enough slots for several slaves?
Minimal reprex:
mpi.spawn.Rslaves(nslaves = workers)
I'm using CentOS 8, Rmpi 0.6-9.1 with openmpi 4.1.1.


text:
Q: Is there a name for dividing a set into pieces, some of which may be empty? Suppose that $X$ is a set and $V_{0}$, $J$, and $V_{1}$ are pairwise disjoint subsets of $X$ whose union is $X$. If the three subsets were nonempty it would be a partition of $X$. However, I wish to include the possibility that at least one of the sets, perhaps two of them, are empty.
For further context I work with abstract convexity. All three sets are convex and the union of $J$ with either $V_{i}$ is also convex. This is an abstraction of the following situation:
Let $f \colon V \rightarrow \mathbb{R}$ be a linear map from a real vector space to $\mathbb{R}$ and $c \in \mathbb{R}$. Define the three sets as follows:
$V_{0} = \{ v \in V \colon f(v) < c \} $
$J = \{ v \in V \colon f(v) = c \} $
$V_{1} = \{ v \in V \colon f(v) > c \} $
Is there a commonly used name for his situation?

A: As you say, "partition" doesn't really fit here since that (almost always) would require that none of the sets are empty. I would use the word "decomposition" instead. One example of this use of "decomposition" is in the Hahn decomposition theorem, where either one of the positive and negative sets may be empty.


text:
Q: How to use circle detect in a video I'm very new to python and OpenCV. What I am trying to do is find a circle on a part in a video using the hough circles and track that circle as it moves across the cameras field of view. I can use the hough circles on a still image. This is what I have so far, but I don't think it is anywhere close to being working.
import cv2
import numpy as np

img = cv2.VideoCapture(0)

circles = cv2.HoughCircles(img,cv2.cv.CV_HOUGH_GRADIENT,1,20,
                        param1=200,param2=100,minRadius=0,maxRadius=0)

circles = np.uint16(np.around(circles))
    for i in circles[0,:]:
    # draw the outer circle
    cv2.circle(cimg,(i[0],i[1]),i[2],(0,255,0),2)
    # draw the center of the circle
    cv2.circle(cimg,(i[0],i[1]),2,(0,0,255),3)

cv2.imshow('detected circles',img)

cv2.waitKey(0)
cv2.destroyAllWindows()

A: For a video analysis you have to read images from your webcam (in this case) continuously. So you need a loop as shown in the tutorials from OpenCV.
import cv2
import numpy as np

cap = cv2.VideoCapture(0)

while(1):

     #read frame from capture
     img = cap.read()

     ##############################
     # here do the whole stuff with circles and your actual image
     ##############################

     cv2.imshow('show image', img)

     #exit condition to leave the loop
     k = cv2.waitKey(30) & 0xff
     if k == 27:
          break

cv2.destroyAllWindows()
cap.release()


text:
Q: Hi am getting unexpected ')' error on line 65 Hi kindly help me check if there's any problem with my code. I am creating a command to generate a sitemap but am getting an error; 'unexpected ')' on line 65.
here is the screenshot for the code

A: I think the issue is on the IF statement. Just remove the last OR operator from the condition. Like this:
 if (
        $url->segment(1) == $priority[0] ||
        $url->segment(1) == $priority[1] ||
        $url->segment(1) == $priority[2]
    ) {...}

If this is not the issue, maybe you can tell us what is the line 65.