text:
Q: In c, how do I continuously print text out until the user enters a specific character? I want to print out text (from a file previously opened) until I press the key q. All of the methods I have tried pause my text being printed out. Is there a way to print the text while looking for a key press in C?
ex:
//after turning off canonical mode and echoing

char* output = "press q to stop this";

char ch;

while(ch = getchar()!= 'q')
{
    printf("%s\n",output);
}

It only prints the prompt after you enter a char. I want it to continue to print the prompt continuously.
Solved my problem with this webpage that I found: http://cc.byexamples.com/2007/04/08/non-blocking-user-input-in-loop-without-ncurses/

A: You can create a child process.

*

*parent prints elem from file

*child waiting user input

*to stop execution you can use kill(getppid(), SIGTERM) to kill parent and exit(0) to kill child

A: Based on jave.web's response in Wait for input for a certain time
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include<unistd.h>
#include<windows.h>

char waitForCharInput( int seconds ){
    char c = '_'; //default return
    while( seconds != 0 ) {
        if( _kbhit() ) { //if there is a key in keyboard buffer
            c = _getch(); //get the char
            break; //we got char! No need to wait anymore...
        }

        Sleep(1000); //one second sleep
        --seconds; //countdown a second
    }
    return c;
}

int main()
{
    FILE *fp = fopen("_filename_","r");
    char buffer[255];
    while(fgets(buffer, 255, (FILE*) fp))
    {
        printf("%s\n", buffer);
        char response = waitForCharInput(1);
        if(response == 'q')
            break;
    }
}

A: Found my answer here: http://cc.byexamples.com/2007/04/08/non-blocking-user-input-in-loop-without-ncurses/
I understand my question was too broad but this is how I solved my issue.


text:
Q: Change perspective UIImageView with accelerometer I search a way on iOS to change the perspective of a image with the data get by the accelerometer.
I use this but the result is not correct :
 self.picture.layer.transform =  CATransform3DRotate(CATransform3DIdentity, DEGREES_TO_RADIANS(90), x, y, z);

The purpose of this is to take a picture with the camera, get info from the accelerometer and add a picture overlay with the perspective taken on the camera.
Thanks in advance

redpajama_set_name: RedPajamaStackExchange


text:
Q: Xamarin Mask Entry Currency 2 Decimal Places I'm using the following code to mask an entry field for currency. The only issue is I want to limit the input to 2 decimal places. How can I modify the code the accomplish this?
public class CurrencyConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return Decimal.Parse(value.ToString()).ToString("C");
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string valueFromString = Regex.Replace(value.ToString(), @"\D", "");

        if (valueFromString.Length <= 0)
            return 0m;

        long valueLong;
        if (!long.TryParse(valueFromString, out valueLong))
            return 0m;

        if (valueLong <= 0)
            return 0m;

        return valueLong / 100m;
    }
}

A: If you want to limit two decimals,you could add the conditions in the entry textchanged event.
like:
<Entry x:Name="entry" Keyboard="Numeric"  HorizontalOptions="StartAndExpand" WidthRequest="600" TextChanged="Entry_TextChanged"></Entry>

in the behind code:
private void Entry_TextChanged(object sender, TextChangedEventArgs e)
    {

        if (e.NewTextValue.Contains("."))
        {
            if (e.NewTextValue.Length - 1 - e.NewTextValue.IndexOf(".") > 2)
            {
              var  s = e.NewTextValue.Substring(0, e.NewTextValue.IndexOf(".") + 2 + 1);
                entry.Text =s;
                entry.SelectionLength = s.Length;
            }
        }

    }

the effect:


text:
Q: How to compute the tensor multiplier from an image transformation? Firstly, I assume people are familiar with Python numpy.tensordot. Here I use a simple instance of that as follows (pseudocode):
A.shape = (1, x, y)
B.shape = (x, y, z, t)
C = numpy.tensordot(A, B)
C.shape = (1, z, t)

Now imagine A and C above are greyscale images (1 channel), and there is an image transformation that turns A into C. To be specific, assume people are familiar with OpenCV in Python and the functions cv2.warpAffine and cv2.warpPerspective, let's (pseudocode):
C = cv2.warpSomething(A, **kwargs)

My question is that, assume the above equations hold, then how to compute B (efficiently enough) from the variables (pseudocode):
x, y, z, t, the_transformation (i.e. warpAffine or warpPerspective, M, flags, borderMode, borderValue)

I'm also satisfied if one can produce B from only (warp, x, y, z, t, M), fixing flags=INTER_LINEAR, borderMode=BORDER_CONSTANT and borderValue=0.
Thanks in advance!

A: If there are N pixels in both A and C, then the transformation tensor B has N**2 components. For N on the order of 1E+6, you really don't want to store the B tensor. If it's a very small dataset, you could try something like this:
# assuming C and A are already initialized.
B = np.zeros(A.shape + C.shape)
A1 = np.zeros_like(A)
for i in range(A1.shape[0]):
   for j in range(A1.shape[1]):
       A1[i, j] = 1
       B[i, j, :, :] = affine_something(A1)
       A1[i, j] = 0

But this is still very slow and inefficient.


text:
Q: Regex matching a multiline, mixed case string with whitespace in C# I'm trying to guarantee that a field in our CMS contains only an unordered list. For example,

        This is our first bullet point

I'm using the following to match this:
String pattern = "^
(
.*
)+
$";
Regex rgx = new Regex(@pattern,
    RegexOptions.IgnorePatternWhitespace
    | RegexOptions.Multiline
    | RegexOptions.IgnoreCase);
if(rgx.IsMatch(controlValidationValue)) { ... }

This works when the html is all on one line, but fails as soon as I get line breaks or whitespace - which may happen, as our CMS uses a rich text plugin to create the html.
I've tried using a bitwise AND (instead of OR), and played with RegexOptions.SingleLine but can't get to the bottom of the problem.
Any/all help appreciated!

A: In general i would use HtmlAgilityPack to parse HTML instead of regex.
string html = @"

        This is our first bullet point

";

var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(html.Trim());  // Trim to remove leading or trailing spaces if that's possible
bool valid = doc.DocumentNode.ChildNodes.Count == 1
          && doc.DocumentNode.ChildNodes[0].Name == "ul";


text:
Q: Using both @ErrorTemplate annotation and custom ConstraintViolationException mapper results in race condition I'm working on a Jersey project that uses a custom ConstraintViolationException mapper which builds and returns a JSON response. This JSON response is not what I want in all cases, there are some resources that I would like to respond with HTML.
@ErrorTemplate seemed to be a perfect solution to suit my needs. However, after registering MvcBeanValidationFeature.class as required and annotating the methods I wanted to respond with HTML I have a race condition somewhere.
The newly annotated with @ErrorTemplate methods work fine and return HTML using the provided template.
The resource methods that I haven't touched and would normally respond with JSON do not always do that anymore. When I place a breakpoint in the custom ConstraintViolationException mapper then I get JSON, otherwise the custom mapper is never called and I get the default response, e.g.
{
   "code" : 400,
   "message" : "Description field can't be empty.",
   "date" : "2014-11-13T15:28:23.556Z"
}

vs the default:

Description field can't be empty.(

    path=
    FormResources.createTicket.arg0.description,

    invalidValue= null
)

I'm fairly new to Jersey and can't quite figure out what the problem is. @ErrorTemplate annotation is handled by a custom ExceptionMapper so I suppose the problem/clash is somewhere there.
Have I misconfigured something? Is it at all possible to have dual error handling like this?
My thinking was that the decision of which exception handler was going to be used was based on the presence of either @Valid or @ErrorTemplate annotations...
Here is my configuration snippet:
    register(JsonConfiguration.class);
    register(RolesAllowedDynamicFeature.class);
    register(MvcBeanValidationFeature.class);
    register(ValidationFeature.class);
    property(ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);
    property(FreemarkerMvcFeature.TEMPLATES_BASE_PATH, "/templates");
    register(FreemarkerMvcFeature.class);

the custom mapper:
@Override
public Response toResponse(ConstraintViolationException exception) {
    Response build = Response
            .status(Response.Status.BAD_REQUEST)
            .type(MediaType.APPLICATION_JSON_TYPE)
            .entity(new ErrorResponse(
                    Response.Status.BAD_REQUEST.getStatusCode(),
                    exception.getConstraintViolations().iterator().next().getMessage()
            ))
            .build();
    return build;
}

an example resource method that is supposed to return JSON on errors but doesn't always do that any more:
@POST
@Consumes({MediaType.APPLICATION_JSON})
public TicketEntity createTicket(@Valid TicketEntity te) throws Exception {

an example resource method that returns HTML on errors:
@POST
@Consumes({MediaType.APPLICATION_FORM_URLENCODED})
@Produces({MediaType.TEXT_HTML})
@ErrorTemplate(name = TEMPLATE_FORM_VALIDATION_ERROR)
public Viewable createTicketFromForm(
    @NotNull(message = "The ticket must contain a description.")
    @Size(min = 1, message = "The ticket must contain a description.")
    @FormParam("description") String paramDescription,
    ...

and finally the extra addition to the POM, namely jersey-mvc-bean-validation:
    <dependency>
        <groupId>org.glassfish.jersey.ext</groupId>
        <artifactId>jersey-bean-validation</artifactId>
    </dependency>
    <dependency>
        <groupId>org.glassfish.jersey.ext</groupId>
        <artifactId>jersey-mvc-bean-validation</artifactId>
    </dependency>


text:
Q: Not echoing correct values I'm having an issue with my array in the view file. What I"m trying to do is have it show the list of titles and and contenders for each title. As of right now its showing Vacant as the champion for each title AND TBD for each contender for each title when I have values that should be working but isn't.
If the value for the championID is 0 in the table it should display Vacant if its not then it should get the champions name and display it. For each of the contenders if its a 0 in the database then it should display TBD if its not then it should display their name.
Here's the query:
/**
 * Get title champions
 *
 * @return  object/NULL
 */
function getTitlesChampions()
{
    $this->db->select('titlesList.titleName');
    $this->db->select('rosterList.rosterName AS champion');
    $this->db->select('con1.rosterName AS contender1');
    $this->db->select('con2.rosterName AS contender2');
    $this->db->select('con3.rosterName AS contender3');
    $this->db->from('titlesChampions');
    $this->db->join('titlesList', 'titlesList.id = titlesChampions.titlesListID');
    $this->db->join('rosterList', 'rosterList.id = titlesChampions.championID', 'left');
    $this->db->join('rosterList AS con1', 'con1.id = titlesChampions.contender1ID', 'left');
    $this->db->join('rosterList AS con2', 'con2.id = titlesChampions.contender2ID', 'left');
    $this->db->join('rosterList AS con3', 'con3.id = titlesChampions.contender3ID', 'left');
    $query = $this->db->get();
    if ($query->num_rows() > 0)
    {
        return $query->result();
    }
    return null;
}

Values inside of the titlesChampions table is this:
id - 1  titlesListID - 1  championID - 1  contender1ID - 1   contender2ID - 1  contender3ID - 1
id - 2  titlesListID - 2  championID - 1  contender1ID - 0   contender2ID - 0  contender3ID - 0
id - 3  titlesListID - 3  championID - 1  contender1ID - 0   contender2ID - 0  contender3ID - 0

I run a print_r of the array in the view file and this is what prints out:
Array
(
[0] => stdClass Object
    (
        [titleName] => Undisputed Heavyweight Title
        [champion] => Kid Wonder
        [contender1] => Kid Wonder
        [contender2] => Kid Wonder
        [contender3] => Kid Wonder
    )

[1] => stdClass Object
    (
        [titleName] => Outlaw Title
        [champion] => Kid Wonder
        [contender1] =>
        [contender2] =>
        [contender3] =>
    )

[2] => stdClass Object
    (
        [titleName] => Tag Team Titles
        [champion] => Kid Wonder
        [contender1] =>
        [contender2] =>
        [contender3] =>
    )

)

    <?php if (!is_null($titlesChampionsList)) { foreach ($titlesChampionsList AS $champion) {
                    echo '
';
                    echo ''.$champion->id.'	';
                    echo ''.$champion->titleName.'	';
                    echo '';
                    if ($champion->champion == 0)
                    {
                        echo 'Vacant';
                    }
                    else {
                        $champion->champion;
                    }
                    echo '	';
                    echo '';
                    if ($champion->contender1 == 0)
                    {
                        echo 'TBD';
                    }
                    else {
                        $champion->contender1;
                    }
                    echo '	';
                    echo '';
                    if ($champion->contender2 == 0)
                    {
                        echo 'TBD';
                    }
                    else {
                        $champion->contender2;
                    }
                    echo '	';
                    echo '';
                    if ($champion->contender3 == 0)
                    {
                        echo 'TBD';
                    }
                    else {
                        $champion->contender3;
                    }
                    echo '	';
                    echo '';
                    $data = array('name' => 'user', 'value' => $champion->id);
                    echo '';
                    echo '';
                    echo '	';
                    echo '

                    '; } } ?>

Any ideas?

A: Assuming that array is in fact what is returned from the function:
foreach ($array as $key => $titleObject) {
    $champion = ($titleObject->champion ? $titleObject->champion : 'Vacant');
    echo $titleObject->titleName.' champion is '.$champion.'
';
    $contender1 = ($titleObject->contender1 ? $titleObject->contender1 : 'tbd');
    $contender2 = ($titleObject->contender2 ? $titleObject->contender2 : 'tbd');
    $contender3 = ($titleObject->contender3 ? $titleObject->contender3 : 'tbd');
    echo $titleObject->titleName.' contenders are '.$contender1.', '.$contender2.' and '.$contender3.'
';
}


text:
Q: Elegant code when there are many subclasses? I have an interesting programming problem that has had me stumped for days. Some context to aid my questions:
Currently I am writing a game that uses a Material Emum to hold all the materials needed in the game ie Material.DIRT, Material.WATER, Material.CLOTH ...
However I wish to make the code as modifiable as possible and have the ability that should someone want to extend the game to add new materials they can do so. Thus my current Enum system breaks down and so I have attempted to switch to a Class/Subclass system. I have found two ways to do this, they are explained below with their pros and cons.
Case 1 - Having an abstract Material class and subclassing.
Thus every material would extend Material. This is advantageous as we can now "group" like materials together ie Fabric could extend Material and then Wool and Cotton etc extend this. The problem with this is that for every material there has to exist a class and with so little parameters for each material it feels like a waste. If there is 1000 materials there would be 1000 classes all with virtually nothing in them. I could cut this down by having anonymous classes but now the code has no way to differentiate one material from the other. I could use an id system which is the major problem with case 2.
The question for case 1 is:
Is there a more elegant way of doing this?
Case 2 - Having a single Material class and instantiating each new material as an instance of this class defining each material with a different id/name. This saves a lot of writing and also allows us to differentiate between materials. The problem with this is now we have an id system, what do we base this system on? Strings, ints? I ask this because I am always keen to have a complex free system that avoids using hardcoded strings and ints in the code. This is why I like the enums as there is no worry of typesetting. Another problem is users wanting to add new materials could have conflicting ids with other users.
My question for case 2 is:
Is there a full proof method of being able to differentiate instances uniquely and consistently (is the same every runtime)?
Thank you for reading. Any help or methods on how best to do this would be most appreciated.
Edit: I should note that some materials may have methods and behaviours associated with them. Some behaviours may be unique to certain materials and some that are similar for a "group".

A: Use a configuration file with all the materials in it, written in some DSL (simple table, basically).


text:
Q: Should every single action need a component in Angular 6 I am very new to Angular,
I have successfully coded a login system using JWT ( Backend is PHP / Lumen ).
When I login, I store the user info in the local storage.
localStorage.setItem('currentUser', JSON.stringify({email, token: res.token}));

So, basically, logout is just removing this file, one line of code.
Is it necessary to create a whole component for logout action ?
It seems a lot for me.
Can you a propose me a easier way to do it ? I don't really know how should I organise it.

A: My personal opinion is that you must use some kind of service for this case, so that you can inject it in whatever component you need it.
The service can be something like that

import { Injectable } from "@angular/core";

@Injectable()
export class AuthService {

  constructor() {}

  logout() {
      this.cookies.delete() // this line is pseudo code
  }
}

UPDATE:
You might call it like that

import { Component, Input, OnDestroy, OnInit } from "@angular/core";
import { AuthService } from "./some-service path";

@Component({
  selector: "app-recursive",
  templateUrl: "./recursive.component.html",
  styleUrls: ["./recursive.component.css"]
})
export class RecursiveComponent implements OnDestroy, OnInit {
  nextLayer = [];

  constructor(private auth: AuthService) {}

  ngOnInit() {

  }

  logoutFunc() {
    this.auth.logout(); // If we asume that you have logout method in the service
  }

}

Here you can dive deeper in the logic behind the services TourOfHeroesServicesChapter , also i advice you to go trough each part of the tour of heroes, there is a lot of useful stuff

A: You don't need to necessarily have component for every action. Since your logout is in the navbar, you can write and perform all necesary actions in the navbar component to keep it organised


text:
Q: Won't insert data to "users" collection to mongoDB with nodeJS I'm having troubls inserting data to mongoDB with nodeJS.
This is part of my server.js file:
app.post('/users', function(req, res, next){

db.collection('users', function(err, usersCollection){

    usersCollection.insert(req.body, {w : 1} , function(err){
        return res.send();
    });

    });
});

this is my controller in my index.html file:
app.controller('SLController', function ($scope, $http){
    $scope.submitSignup = function(){
        var newUser = {
            username: $scope.username,
            email: $scope.email,
            password: $scope.password

        };

    $http.post('/users', newUser).then(function(){
            alert('Success');
        });

    }

    /*$scope.signin = function (){
        $http.put('/users/signin', {username: $scope.username, password: $scope.password})
            .then(function(){
                alert("Successfully signed in.");
            }, function(err){
                alert("Bad login credentials.");
            })
        }*/

});

and this is the section of the form that i'm trying to insert from my sl.html file:

Sign Up

<input type="text" class="form-control form-subtitles" placeholder="Usuario" ng-model="username">

<input type="text" class="form-control form-subtitles" placeholder="E-mail" ng-model="email">

<input type="password" class="form-control form-subtitles" placeholder="Password" ng-model="password">

<input ng-click="submitSignup()" type="submit" class="form-control form-subtitles btn btn-info" value="Signup">

I've looked at the other questions but they are quiet different.
PS. the command i'm using in mongo's console is db.users.find()
Thank you!
----------------------------------------------------------- EDIT ----------------------------------------------------------
A parcial solution i used to fix it:
app.post('/users', function(req, res, next){

 db.collection('users', function(err, usersCollection){

    usersCollection***.save***(req.body, {w : 1} , function(err){
        return res.send();
    });
  });
});

INSTEAD OF .insert use .save

A: This is the simple as simple , by which you can easily create a record into your database.only two parameters are required email and name.
router.all('/create', function (req, res) {
        var database = req.Collection;
        var name = req.body.name;// or you can do directly as 'shekhar'
        var email = req.body.email;// or you can do directly as 'a@gmail.com'
        var record = new database({
            name: name,
            email: email
        });
        if (record.length > 0) {
            record.save(function (err, result) {
                if (err) {
                    res.json({status: 0, message: err})
                } else {
                    res.json({status: 1, name: name, email: email, message: " success"});
                }
            })
        } else {
            res.json({status: 0, msg: "Invalid Fields"});
        }
    });

A: A parcial solution i used to fix it:
 app.post('/users', function(req, res, next){

  db.collection('users', function(err, usersCollection){

     usersCollection***.save***(req.body, {w : 1} , function(err){
         return res.send();
     });
  });
 });

INSTEAD OF *.insert*  use  *.save*


text:
Q: Somar valor a uma data com PHP Estou com um problema ao somar uma data que vem do banco de dados que vem da seguinte forma:
Ex.: 10/05/2018 17:48:27
Estou utilizando o seguinte método para para somar dias a essa data:
date('d/m/Y H:i:s', strtotime('+10 days', strtotime('10/05/2018 17:48:27')));

Porém o resulta do que obtenho é esse:
10-01-1970 16:00:00
Verifiquei que quando o formato da data é com "-" (ou seja... 10-05-2018 17:48:27) ao invés de "/" a soma dá certo.
Minha pergunta é, como seria fazer essa soma dar certo com o padrão que recebo do banco de dados, como no exemplo "10/05/2018 17:48:27".

A: É sempre mais seguro nesses casos usar DateTime::createFromFormat, já que  é você quem diz para o PHP qual é o formato que deve ser usado para fazer o parser da data.
Veja:
 $datetime = DateTime::createFromFormat('d/m/Y H:i:s', '10/05/2018 17:48:27');

Para acrescentar os dias, basta usar modify
 $datetime->modify('+10 days');

Para exibir use  format
 echo $datetime->format('d/m/Y H:i:s');

Alguns comentários sobre o que você colocou na pergunta

Porém o resulta do que obtenho é esse: 10-01-1970 16:00:00

Geralmente, quando o PHP não consegue processar uma data corretamente, a data definida é essa. Em alguns casos, a classe DateTime até acusa erros na sintaxe da data (no caso, acredito ser o parser usado internamente do strtotime que faça essa verificação);
Se você ver esse exemplo onde eu uso a função date_parse, poderá perceber como é que o PHP entendeu a sua string de data.
Código do Exemplo:
 print_r(date_parse ('10/05/2018 17:48:27'));

A saída é:
array(12) {
  ["year"]=>
  int(2018)
  ["month"]=>
  int(10)
  ["day"]=>
  int(5)
  ["hour"]=>
  int(17)
  ["minute"]=>
  int(48)
  ["second"]=>
  int(27)
  ["fraction"]=>
  float(0)
  ["warning_count"]=>
  int(0)
  ["warnings"]=>
  array(0) {
  }
  ["error_count"]=>
  int(0)
  ["errors"]=>
  array(0) {
  }
  ["is_localtime"]=>
  bool(false)
}

Repare que o PHP interpreta o 05 como dia e o 10 como mês.

Verifiquei que quando o formato da data é com "-" (ou seja... 10-05-2018 17:48:27) ao invés de "/" a soma dá certo.

Sim, funções como strtotime e date_parse ou a classe DateTime do PHP têm uma lista de formatos pré-definidos para fazer a interpretação data, no qual o formato que geralmente é usado no Brasil não faz parte desta lista.
Como eu disse anteriormente, basta usar createFromFormat que seu problema é resolvido.


text:
Q: How to block a user agent using mod_rewrite in htaccess I'm trying to block the access to this user agent who's visiting me: Mozilla/5.0 (compatible; Seekport Crawler; http://seekport.com/ (with no ) at the end, its not a fault).
I have tried this one (with two more agents)
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} OnalyticaBot [NC, OR]
RewriteCond %{HTTP_USER_AGENT} Re-re Studio (+http://vip0.ru/) [NC, OR]
RewriteCond %{HTTP_USER_AGENT} Mozilla/5.0 (compatible; Seekport Crawler; http://seekport.com/ [NC]
RewriteRule .* - [F,L]

I have tried a couple more with this sintax (using entire string and using only "Seekport") but still seeing the agent user asking for in the log
RewriteCond %{HTTP_USER_AGENT} ^.(user_agent1|user_agent2).$ [NC]

Could you help me?

A:
RewriteCond %{HTTP_USER_AGENT} Re-re Studio (+http://vip0.ru/) [NC, OR]

By default, the 2nd argument to the RewriteCond directive is a regular expression (regex), so any meta characters (eg. + and .) need to be properly escaped. But importantly, spaces are delimiters in Apache config files so these also need to be escaped, otherwise, the directive will be wholly invalid. On Apache, the above will result in a fatal error (500 Internal Server Error) due to "bad flag delimiters". On LiteSpeed, it will simply fail silently.
Spaces can be "escaped" by either:

*

*Precede the space with a backslash. eg. \  in hello\ world

*Or, use a \s shorthand character class to represent any white-space character. eg. hello\sworld.

*Or, enclose the entire argument in double-quotes. eg. "hello world".

[NC, OR] - However, there should be no spaces in the flag delimiters argument. This should be [NC,OR] (no space).
So, the above could be written like this:
RewriteEngine On
RewriteCond %{HTTP_USER_AGENT} OnalyticaBot [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "Re-re Studio (\+http://vip0\.ru/)" [NC,OR]
RewriteCond %{HTTP_USER_AGENT} "^Mozilla/5\.0 (compatible; Seekport Crawler; http://seekport\.com/$" [NC]
RewriteRule ^ - [F]

The regex .* in the RewriteRule pattern can be simplified to just ^ (which is more efficient) and the L flag is not required when using F - it is implied.
If you want to match an entire user-agent string then you can use the = (lexicographical string comparison for equality) prefix operator (together with double-quotes) on the CondPattern to test for an exact match.
For example:
RewriteCond %{HTTP_USER_AGENT} "=This is the exact user-agent I want to block"
RewriteRule ^ - [F]

In the above example, the string This is the ... block is an ordinary string, not a regex.


text:
Q: Cannot install AMD graphics driver I had AMD graphics installed on my windows 7 laptop. Last week, I performed a clean install of windows 8.1 and since I could not change brightness and other display settings (well, I could change the settings, but the display would not adjust to it), I figured I had to update the display drivers.
The AMD graphics 13.9 could not be installed:

Nothing enlightening in the log.
I went to the device manager and uninstalled the driver. Upon restarting the computer, I noticed that there is a generic MS driver there:

Tried to install the AMD driver and it failed again. Does anyone know how to solve this?

A: uninstall driver USB 3.0,
restart PC,
install AMD driver and restart PC, after update Windows for sound
(Advanced Micro Device)
now install driver USB 3.0


text:
Q: Passing arguments to child process in nodejs which has some dependency in execFile method I trying to pass some of the arguments to the child process in node js. I'am actually running a phantom script inside the child process.I'am using execFile method to run my child script. This is how my index.js looks:
var childProcess = require('child_process');
var path = require('path');
var phantomjs = require('phantomjs');
var binPath = phantomjs.path

console.log('inside index method ');

    // Set the path as described here: https://aws.amazon.com/blogs/compute/running-executables-in-aws-lambda/

    // Set the path to the phantomjs binary
    //var phantomPath = path.join(__dirname, 'phantomjs_linux-x86_64');

    // Arguments for the phantom script
    var processArgs = [
        path.join(__dirname, 'ThumbnailCreator.js'),
        'myargs'
    ];

    // Launch the child process
    childProcess.execFile(binPath, processArgs, function(error, stdout, stderr) {
        console.log('stdout: ', stdout);
        console.log('stderr: ', stderr);
        if (error !== null) {
          console.log('exec error: ', error);
        }
    });

And m trying to print the argument which i have passed.But it is not printing anything. This is how m trying to print it in the child process:
console.log(process.argv[1]);

A: You can parse it like this  in  ThumbnailCreator.js
var system = require('system');
var args = system.args;
args[0]  is file name
args[1] will give you value passed in first argument.


text:
Q: Tableau Web Data Connector and handling required and non-required fields on form I'm trying to find a example of a tablaeu Web Data Connector that would basically provide an html form for a user in which certain fields are required but other fields can be inputted or not based on if the user is trying to get specific data. I know the handling would be done somewhere in the javascript code but I'm a newbie in javascript so I'm not sure how this is doable.
Does anybody have any example? I can't seem to find anything concrete on google, github, etc...
When a user inputs all fields, I include inputs inside the URL and that works only when all fields are inputted by the user. It breaks when I miss some of the fields on the form. I tried to change URL based on the input but I'm not sure how to accomplish this.


text:
Q: Accidentally installed SharePointServices 3.0 on a live MOSS2007 box Was working with two RDP windows and meant to install SharePointServices 3.0 on a new dev box but accidentally installed it on the live farm web server running MOSS2007.
All sharepoint sites now simply read
Server error: http://go.microsoft.com/fwlink?LinkID=96177
Central Administration still shows all the old shared services but they errors with the same as above when you click on them.
What happens if I run SharePointServices again and go to repair -> remove? How do I fix this?

A: If it's worth more than $250, call Microsoft Support.

A: Since it was a live box, you should have a backup. Restore it.

A: You have probably detached your Sharepoint server from the config database, and effectively from your farm.
So what I would do is this:

*

*Backup all your Sharepoint databases (you already have a backup of this right?)

*Uninstall Office Sharepoint Server

*Uninstall Sharepoint Services

*Reinstall Office Sharepoint Server

*Reinstall any Service Packs and hotfixes you already applied

*Run the Sharepoint Products and Technologies Configuration Wizard and point it at your config database.

That should get you back up and running.
Probably a good idea to change the background colour of your production servers so you have a very obvious visual cue where you are running a particular command!


text:
Q: Error on starting cassandra I have downloaded apcahe cassandra 3.11.1 on an amazon instance.
I run this in cassandra/bin:
sh cassandra

I get an error:
CassandraDaemon.java:706 - Local host name unknown: java.net.UnknownHostException: ip-172-30-0-229: ip-172-30-0-229: Name or service not known

I tried to follow this answer
This is the content of my /etc/hosts file:
127.0.0.1 localhost

# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts

I have tried editing it and adding ip-172-30-0-229: in front of 127.0.0.1 localhost, but I still get the same error.
What can I do?

A: Adding 127.0.1.1 ip-172-30-0-229 in /etc/hosts file fixed it.


text:
Q: How to create a grid-based website with an 100% width image? I want to create website based on the 1140 grid system with a "landing" image that fills the whole browser, so you'll have to scroll for the content.
So, basically, when you open it, you see this image (with height and width that fill 100% percent of the browser, without any constraints) and when you scroll you see the rest of the page, which is in centered and in columns.
Please not that I want the "landing" image to be scalable as well - it will fit an smartphone or tablet widts as well.

A: It sounds like you are looking for something like this.  It is a very basic layout, but you should be able to get the idea from that fiddle.
Basically, you just create a
 with 100% height and width.  It will take up whatever size the browser is, then you can add another block element below that to house your other content.

    here is some other stuff

    here is some other stuff


text:
Q: How to include a .pas in the Delphi Project? How can I include a .pas in my project?
This .pas is in the same folder than the other but it does not appear together to the other.

Somebody can help me?

A: Go to Project->Add to project (shift + F11) and select the file you want to add on your project, the file you added will be inserted to dpr and then you can see this file on project.

A: It isn't enough to just put the units in the same folder. You have to explicitly add the units to your project in order for them to show up in the Project Manager. This will add an entry in your project's .dpr and .dproj files.
Use Shift+F11 to add units.

A: Tested with XE7:
You can add a .pas file, which is currently open in the editor, by "drag & drop":

*

*click on the tab (which shows the file name) of the editor, and hold the mouse key pressed

*move the mouse cursor, to the project inspector window, until it is over the project name (the cursor will now change its style, to indicate that dropping is possible)

*release the mouse button

The IDE will now ask if you would like to add the file to the project.


text:
Q: An electronic company is planning to introduce a new camera phone. $60\%$ of the products introduced by the company have been successful An electronic company is planning to introduce a new camera phone. The company commissions a marketing report for each new product that predicts either success or the failure of the product. $60\%$ of the products introduced by the company have been successful. Furthermore, $70\%$ of the successful products were predicted to be success, while $40\%$ of the failed products were predicted to be success.
a) What is the probability that a new camera phone will be successful if it is predicted to be successful.
b) What is the probability that a new camera phone will be failure if it is predicted to be successful.
I know the formula as $$P(F\mid E)=\frac { P(E\mid F)\cdot P(F) }{ P(E\mid F)\cdot P(F)+P(E\mid \bar { F } )\cdot P(\bar { F } ) } $$
But, I don't know what should be taken as $ P(E\mid F)$, $P(F) $, $P(E\mid \bar { F })$, $P(\bar { F } )$
Please explain me this...

A: Problems like these are best modeled using a Probability Tree. It makes things much clearer.
Let's define:
$S =$ Successful
$\bar{S} =$not successful
$K =$ Predicted to be Successful
$\bar{K} =$ not predicted to be successful
Here's the probability tree for this problem:
You can construct the tree easily using the Complement Rule.
In question a) they want us to compute $P(S|K)$ meaning the probability of a success $(S)$ given that we predicted the product to be a success $(K)$.
If you notice on the probability tree we don't have $P(S|K)$ already computed. Because note that $P(K|S)$ is NOT the same as $P(S|K)$ (Probability of predicting a success given that it's successful is not the same as the probability of a product being successful given that it is predicted to be successful).
So seeing that it doesn't figure on our tree, we have to compute it ourselves using Bayes' Theorem:
$P(S\mid K)=\frac { P(S∩K) }{P(K) }$
The numerator expands into a simple joint probability (the basic intersection formula) and the denominator expands into the Law of Total Probability:
$P(S\mid K)=\frac { P(K\mid S)\cdot P(S) }{ P(K\mid S)\cdot P(S)+P(K\mid \bar { S } )\cdot P(\bar { S } ) }$
You can look up the tree and you'll see that all of these probabilites can be derived from it, and so we have:
$P(S\mid K)=\frac { 0.7 \times 0.6 }{(0.7 \times 0.6) + (0.4 \times 0.4) }=0.72$
N.B: You might want to re-check the computations as I did this on the run so there might be some mistakes due to rushing, but this is the procedure for finding the probabilities. The same procedure applies to question $b)$.


text:
Q: Dropdown menu automatically closes when you open it on iPhone (Bootstrap v3.3.1) I've just been working on the backend on a new site when I've noticed a big error on the front-end and I'm stuck trying to work this one out.
I have an old version of the site that I've been working on and have moved and tidied up the rest of it on a new version. However when I go to the Safari Browser on the iPhone it doesn't load the dropdown menu correctly on the new one, despite copying the website header and footer (which contains the same menu) across from the old site.
When you push the menu, it will open then immediately close on an iPhone. However chrome and firefox web browsers works fine. I've tried to look at forums and change the bootstrap code but nothing seems to work. It only does it on the responsive menu dropdown.
Oddly thou, the old site has the full width dropdown menu, and the new site sticks on the right hand side (not full width) as if it hasn't loaded correctly.
Old Site (Working)
old.hidden-network.co.uk
<!DOCTYPE html>

    <meta charset="utf-8">
    <title><?php echo $title; ?> | Social Research Unit</title>

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="keywords" content="<?php echo $keywords; ?>">
    <meta name="description" content="<?php echo $description; ?>">
    <link rel="icon" href="/inc/img/favicon.ico" type="image/x-icon">
    <link rel="shortcut icon" href="/inc/img/favicon.ico" type="image/x-icon">
    <link href="/inc/css/bootstrap.min.css" rel="stylesheet">
    <link href="/inc/css/prettyPhoto.css" rel="stylesheet">
    <link href="/inc/css/screen.min.css" rel="stylesheet" media="screen">
    <link href="/inc/css/print.min.css" rel="stylesheet" media="print">

            <?php $lang->getLinks(); ?>

                    Toggle navigation
                    Menu

                    <li<?php $if->active('about'); ?>>
                        About

                    <li<?php $if->active('process'); ?>>
                        Methods

                    <li<?php $if->active('projects'); ?>>
                        Projects

                    <li<?php $if->active('resources'); ?>>
                        Resource

                    <li<?php $if->active('contact'); ?>>
                        Contact

New Site (Not Working)
new.hidden-network.co.uk
<!DOCTYPE html>

    <meta charset="utf-8">
    <title><?php echo $title; ?> | Social Research Unit</title>

    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="keywords" content="<?php echo $keywords; ?>">
    <meta name="description" content="<?php echo $description; ?>">
    <link rel="icon" href="/inc/img/favicon.ico" type="image/x-icon">
    <link rel="shortcut icon" href="/inc/img/favicon.ico" type="image/x-icon">
    <link href="/inc/css/bootstrap.min.css" rel="stylesheet">
    <link href="/inc/css/prettyPhoto.css" rel="stylesheet">
    <link href="/inc/css/screen.min.css" rel="stylesheet" media="screen">
    <link href="/inc/css/print.min.css" rel="stylesheet" media="print">

            <?php $lang->getLinks(); ?>

                    Toggle navigation

                    <li<?php $if->active('about'); ?>>
                        About

                    <li<?php $if->active('methods'); ?>>
                        Methods

                    <li<?php $if->active('projects'); ?>>
                        Projects

                    <li<?php $if->active('resources'); ?>>
                        Resource

                    <li<?php $if->active('contact'); ?>>
                        Contact

                                <input type="text" id="search" data-search="Search" />

A:
.navbar-right {position: absolute;} remove this style. –  vel

This worked great, thankyou vel !


text:
Q: Javascript | Odd Array Behavior - Parsing a Combined Array vs a Pre Definied Array I'm experiencing some odd behavior with arrays. I don't understand what's happening. If I create two arrays...
var a = [0,0,1,0];
var b = [0,2, 1,2];

And combine them...
combineChars();
function combineChars(){
   combo.push(a);
   combo.push(b);
}

I end up with an array...
combo = [0,0,1,0,0,2,1,2];

However, if I attempt to split the array into two separate arrays It doesn't split as expected.
function splitArray(a){
    console.log("splitArray("+a+")"); //splitArray(0,0,1,0,0,2,1,2)
    for (i=0;i<a.length;i++){
        if ((i+2)%2==0) {
            rSplit.push(a[i]);
        } else {
            cSplit.push(a[i]);
        }
    }
    console.log("rSplit = " + rSplit); //rSplit = 0,0,1,0
    console.log("cSplit = " + cSplit); //cSplit = 0,2,1,2
}

expected...
console.log("rSplit = " + rSplit); //rSplit = 0,0,1,0,0,1,0,1
console.log("cSplit = " + cSplit); //cSplit = 0,2,1,2,0,0,2,2

Fiddle: https://jsfiddle.net/taylorRichie/yrzrqm38/4/
As you can see from the fiddle, if I create the array "co" instead of combining two arrays, it behaves as expected.
???
Any help would be greatly appreciated.
Richie

A: Given an empty combo array, and your a and b arrays,
combo.push(a);
combo.push(b);

does not push the elements of a and b to combo, as you claim, but instead, pushes the arrays themselves, making combo an array with 2 elements, both elements being the original a and b arrays themselves.
If you use concat instead of push, your combo array will be constructed as you originally expected.
i.e. change your combineChars function to the following:
function combineChars(){
   combo = combo.concat(a);
   combo = combo.concat(b);
}

Note that you need to reassign combo, because concat does not mutate the original array, but returns a new one.

A: Look to built in Array.prototype methods first
var rSplit = [].concat(a).concat(b);
var lSplit = [].concat(b).concat(a);

A: You are not ending up with an array combo which is those 8 elements. You're ending up with an array combo which is 2 elements, each being their respective original 4 element arrays. Arrays can hold other arrays as elements. Push adds something as an element...it does not concatenate arrays together.
You need to use .concat to actually combine two arrays.
combo = a.concat(b);


text:
Q: Interactive ssh session started from bash command I'm trying to launch an interactive ssh session created from a bash command (as shown below).
If I do not add the 'ttt', I just get a 'non interactive' session message and the ssh session is closed.
After adding the 'ttt' flag, the session remains open but I can not enter commands or interact with the remote session.
This is a simplified version of the command I'm trying to execute
 echo "username@host" | xargs -I{} bash -x -c 'ssh -ttt" $0' {}

Not sure if there is an additional flag that should be added or alternative way of doing this.

A: Input to xargs (and therefore bash and therefore ssh) is coming from the pipe, not your terminal. Depending on the larger context, one of these options should work to let ssh read from the terminal:

*

*Capture the list of hosts to an array first, then use a for loop instead of xargs. Something like this:
 readarray -t hostarray < <(echo "username@host")
 for host in "${hostarray[@]}"; do
     ssh "$host"
 done

*Add the -o option to xargs, which tells it to redirect stdin of the command from /dev/tty (i.e. the terminal).

*Redirect the regular stdin around the xargs command via a different file descriptor, e.g. #3 (note: I haven't tested this):
 { echo "username@host" | xargs -I{} bash -x -c 'ssh -ttt "$0" <&3' {}; } 3<&0

BTW, in addition to problems with ssh not getting input it's supposed to get (i.e. from the terminal), you can also have trouble with it stealing input that was intended for something else, like parts of the list of hosts you wanted xargs to read. See BashFAQ #89: I'm reading a file line by line and running ssh or ffmpeg, only the first line gets processed!


text:
Q: onclick listener listens to child element click so I have the following event listener:
$("#searchArea dl dd a").on('click',function(e){
    //code
});

and I want it to only execute the function when the "a" nodes inside the "dd" nodes (located in the #searchArea div) are clicked, but I also have some "i" nodes inside the "a" nodes. Apparently the event listener also executes the function, when they are clicked.
Here is an example of the structure:

Is there any way to prevent the "i" nodes to execute the function if they are clicked?
Help is much appreciated.

A: Just compare the target of the event:
$("#searchArea dl dd a").on('click',function(e){
    if (e.target !== this) return;
    //code
});

(Note that this takes advantage of the fact that jQuery normalizes event objects so there'll be a "target" property in all browsers.)


text:
Q: Function pointer with a reference argument cannot derive Debug I have a enum where I want to generalize an function pointer. As soon as I add a reference inside the function pointer definition. it fails to compile because it cannot print it with Debug:
fn div1(t: i64, b: i64) -> i64 {
    t / b
}

fn div2(t: i64, b: &i64) -> i64 {
    t / b
}

#[derive(Debug)]
enum Enum {
    FnTest1(fn(i64, i64) -> i64),
    FnTest2(fn(i64, &i64) -> i64),
}

fn main() {
    println!("{:?}", Enum::FnTest1(div1));
    println!("{:?}", Enum::FnTest2(div2));
}

The error I get is this
error[E0277]: `for<'r> fn(i64, &'r i64) -> i64` doesn't implement `std::fmt::Debug`
  --> src/main.rs:12:13
   |
12 |     FnTest2(fn(i64, &i64) -> i64),
   |             ^^^^^^^^^^^^^^^^^^^^ `for<'r> fn(i64, &'r i64) -> i64` cannot be formatted using `{:?}` because it doesn't implement `std::fmt::Debug`
   |
   = help: the trait `std::fmt::Debug` is not implemented for `for<'r> fn(i64, &'r i64) -> i64`
   = note: required because of the requirements on the impl of `std::fmt::Debug` for `&for<'r> fn(i64, &'r i64) -> i64`
   = note: required for the cast to the object type `dyn std::fmt::Debug`

It only shows an error for FnTest2 which has a reference argument while FnTest1 works fine.
Is this a bug in Rust or is there a solution or an alternative method to this issue?
I am running Rust nightly (rustup says: rustc 1.30.0-nightly (ae7fe84e8 2018-09-26)).

A:
Is this a bug in Rust

No, but it is a limitation:

*

*Cannot derive(Debug) for a struct with a function with a reference parameter (#45048)

*#[derive] Debug, PartialEq, Hash, etc. for any function pointers, regardless of type signature (#54508)

is there a solution or an alternative method

Yes, you must implement Debug for the type Enum yourself.


text:
Q: Supremum proof real analysis hope somebody can help me. I have a feeling it is a simple question, but I just cannot figure it out.

Suppose A and B are two non-empty bounded subsets of $\mathbb{R}$ such
  that $\sup A =\sup B$ and $\sup A$ is NOT in A. Show that $\forall_{a
> \in A} \exists_{b \in B} : a<b$

Thanks in advance

A: Let $a \in A$ be arbitrary. Show that there is $b \in B$ such that $a < b$.
Proof by contradiction: Assume that $b \leq a$ for all $b \in B$. Then $\sup B \leq a < \sup A$, which contradicts the assumption $\sup A = \sup B$. Note that the last inequality is strict by the assumption $\sup A \not\in A$.
The intuition is that both sets have the same "upper endpoint". If $b \leq a$ would hold for all $b \in B$, then, clearly, the "upper endpoint" of $B$ would be less than that of $A$.

A: Let $K=\sup A$. Let $a$ be some element of $A$ and consider $\epsilon=K-a>0$ (since $K\not\in A$). Assume $\not\exists b\in B$ such that $a<b$. Then $B$ is bounded above by $K-\frac{1}{2}\epsilon$ and so $\sup B\neq K$. Contradiction.


text:
Q: Accessing a view model element through Javascript I am passing a Model to my view that is called HomeViewModel. The HomeViewModel has a bool property called isNext. In my view, I simply want to display the isNext value. So basically I have this:
@model Impoware.Models.HomeViewModel

@{
    ViewBag.Title = "View Contest";
}

View Current Contest

@using (Html.BeginForm())
{

            @Html.LabelFor(m => m.isNext)

            Submenu goes here

}

In the same view, I have a simple div that onclick calls setIsNext(true). Essentially I want to set the value of isNext to true/false based on what
 is clicked but seemingly javascript cannot find the elemntbyId('isNext') (alert('2') never gets called). Any ideas?

A: You will need to specify ID in the View file
// in cshtml
@Html.LabelFor(m => m.isNext, new { id = "MyNextId" })

var output = document.getElementById('MyNextId');

A: LabelFor is going to render a label for your property name, not the value of that property. If you want to set the value of that so that when the form is submitted ,the updated value is available, you should use an input field. If you do not prefer to show a visible input field, you may consider using a hidden field.
@using (Html.BeginForm())
{

             @Html.HiddenFor(f=>f.isNext)
            Submenu goes here

Yes

No

}

And you can read the data-val attribute value of the clicked button and set that to the hidden input.
$(function () {

    $(".myDiv").click(function(e) {
            $("#isNext").val($(this).data("val"));
    });

});

Also, If you prefer to have a checkbox in the UI for the boolean property and want to update the value of that based on the div click, you can do this.
@using (Html.BeginForm())
{
   @Html.CheckBoxFor(f=>f.isNext)

Yes

No

}

and when the div is clicked you need to update the checked status as well
$(function () {

    $(".myDiv") .click(function (e) {
            var v = $(this).data("val");
            $("input[name='isNext']").val(v);
            $("#isNext").attr("checked", v);;
        });

});


text:
Q: Как прописать ссылку в wordpress с плагином PODS Как прописать ссылку на php? Как вставить изображение разобрался, но найти как вставить ссылку так и не понял. Внизу картинки есть ссылка, которая в плагине PODS создавалась через "Сайты", но как ее сейчас вставить в код html с помощью php?
Картинку вставлял вот так: <?php echo get_the_post_thumbnail_url(); ?>
Предпологаю что и ссылку можно вставить почти так же, но как не знаю

A: Можно предположить что таким образом:
<?php echo esc_url( get_post_meta( get_the_ID(), 'link', true ) ); ?>

конечно же если ярлык Вашего поля link.
Либо воспользоваться PODS display.
<?php
$your_post_type_name = pods('your_post_type_name', get_the_ID()); // Либо $post->ID если Вы внутри WordPress цикла и у Вас объявлена глобальная переменная $post
echo esc_url( $your_post_type_name->display('link') );


text:
Q: Apple incorrectly regards an in-app purchase as already subscribed I am working on an in-app purchase for an app which is already live. App name is suppose TestApp, I implemented in app purchase in it and suppose user subscribes to a auto renewing subscription from his iTunes id (let's say itunes@example.com) to buy auto renewing subscription having id "com.subscription.example" for his app which is logged in via his personal account (personal@gmail.com).
His iTunes email id and personal email id is different here. Everything works fine and payment is done and then I update accordingly and hit respective APIs.
Now the issue: if he logs into his app from his friend's email id suppose "friend@gmail.com" and buys the subscription ("com.subscription.example") for him using his same apple id (i.e itunes@example.com) on purchase Apple will say that this product is already subscribed and will go into the success block of purchase payment function, and then all the API etc will be hit accordingly so a new subscription will be active on his friend's account without any payment. What can be done?
This is the function I'm using for purchase payment (I'm using swiftystorekit), it only needs purchase ID as parameters.
  func purchaseProduct(id: String) {
if self.canMakePurchases() {
  UIApplication.shared.isNetworkActivityIndicatorVisible = true
  purchaseButton.isUserInteractionEnabled = false
  purchaseButton.alpha = 0.6
  NVActivityIndicatorPresenter.sharedInstance.startAnimating(activityData)
  purchaseButton.setTitle("Please wait..", for: .normal)
  SwiftyStoreKit.purchaseProduct(id, quantity: 1, atomically: true) { result in
    NVActivityIndicatorPresenter.sharedInstance.stopAnimating()
    UIApplication.shared.isNetworkActivityIndicatorVisible = false
    self.purchaseButton.isUserInteractionEnabled = true
    self.purchaseButton.setTitle("Purchase", for: .normal)
    self.purchaseButton.alpha = 1
    switch result {
    case .success(let purchase):
      print("Purchase Success: \(purchase.productId)")
      let transactionId = purchase.transaction.transactionIdentifier
      self.createSubscription(status:"active",transID : transactionId!)
    case .error(let error):
      self.createSubscription(status: "not_subscribed",transID:"")
      switch error.code {
      case .unknown: print("Unknown error. Please contact support")
      case .clientInvalid: print("Not allowed to make the payment")
      case .paymentCancelled: break
      case .paymentInvalid: print("The purchase identifier was invalid")
      case .paymentNotAllowed: print("The device is not allowed to make the payment")
      case .storeProductNotAvailable: print("The product is not available in the current storefront")
      case .cloudServicePermissionDenied: print("Access to cloud service information is not allowed")
      case .cloudServiceNetworkConnectionFailed: print("Could not connect to the network")
      case .cloudServiceRevoked: print("User has revoked permission to use this cloud service")
      }
    }
  }
} else {
  UIAlertView(title: "Sorry",
              message: "Purchases are disabled in your device!",
              delegate: nil, cancelButtonTitle: "OK").show()
}
}


text:
Q: no me inserta los datos en mysql php .xls estoy tratando de importar datos de excel a mysql con php
pero este no me ejecuta bien el archvivo supuestamente lo esta guardando pero en mysql no me aparece nada
aqui esta el codigo
<?php
include "database.php";
include "class.upload.php";

if(isset($_FILES["name"])){
$up = new Upload($_FILES["name"]);
if($up->uploaded){
$up->Process("./uploads/");
if($up->processed){
/// leer el archivo excel
require_once 'PHPExcel/Classes/PHPExcel.php';
$archivo = "uploads/".$up->file_dst_name;
$inputFileType = PHPExcel_IOFactory::identify($archivo);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($archivo);
$sheet = $objPHPExcel->getSheet(0);
$highestRow = $sheet->getHighestRow();
$highestColumn = $sheet->getHighestColumn();
for ($row = 2; $row <= $highestRow; $row++){
$autonumero = $sheet->getCell("A".$row)->getValue();
$piloto_copiloto = $sheet->getCell("B".$row)->getValue();
$clase = $sheet->getCell("C".$row)->getValue();
$vuelta = $sheet->getCell("D".$row)->getValue();
$largada = $sheet->getCell("E".$row)->getValue();
$llegada = $sheet->getCell("F".$row)->getValue();
$final = $sheet->getCell("G".$row)->getValue();
$penalizacion = $sheet->getCell("H".$row)->getValue();
$tiempofinal = $sheet->getCell("I".$row)->getValue();
$diferencia = $sheet->getCell("J".$row)->getValue();
//$cnv =(1-(floatval($mont_pagar) /$sdo_total)) *100;
date_default_timezone_set('America/Mexico_City');
$now = date('Y-m-d H:i:s');

$sql="INSERT INTO rallyracer ( autonumero, piloto_copiloto, clase, vuelta, largada, llegada, final, penalizacion, tiempofinal,penalizacion,actualizado_a)
VALUES  ('$autonumero', '$piloto_copiloto', '$clase', '$vuelta','$largada' ,'$llegada','$final', '$tiempofinal', '$penalizacion','$now')";  $con->query($sql);

$cons=mysqli_query($con,$sql);

var_dump($sql);

}

unlink($archivo);

}

}
}

?>

y aqui esta la parte de mysql

quiero poder importar desde php a mysql pero no me lo permite
PD: el var_dump no me arroja nada esta en blanco

A: tienes un tema con la obtención de los datos de la planilla. Te paso el código que a mi me funcionó.
Nota importante 1: estoy asumiendo que la clase Upload, Process y la carga de la clase phpExcel, son correctas. Menciono esto porque en mi caso, utilizo otros métodos. Solo estoy cambiando el código de carga de la planilla.
Nota importante 2: no revisé si la carga posterior en la base de datos es correcta. Asumo que si porque le problema era que no había ningún dato para cargar por el error de carga de XLS.
Donde dice:
$inputFileType = PHPExcel_IOFactory::identify($archivo);
$objReader = PHPExcel_IOFactory::createReader($inputFileType);
$objPHPExcel = $objReader->load($archivo);
$sheet = $objPHPExcel->getSheet(0);

Debiera decir
$inputFileType = PhpOffice\PhpSpreadsheet\IOFactory::identify($archivo);
$objReader = PhpOffice\PhpSpreadsheet\IOFactory::createReader($inputFileType);
$objReader->setLoadAllSheets();
$spreadsheet = $objReader->load($archivo);
$loadedSheetNames = $spreadsheet->getSheetNames();
foreach ($loadedSheetNames as $sheetIndex => $loadedSheetName) {
    $xls[$loadedSheetName] = $spreadsheet->getSheetByName($loadedSheetName)->toArray(null,true,true,true);
}
var_dump($xls);

Agregue un var_dump al array que tiene los datos recuperados del XLS.
Agregue un foreach para obtener las demás solapas de la planilla (si hubiera mas de una).
Ojalá esta info sea de utilidad.

A: Hay varias cosas en tu código:

*

*La consulta no es correcta, estás repitiendo dos veces la columna penalizacion, y omitiendo la columna diferencia. Luego, hay 11 nombres de columna y 10 valores. Para evitar este tipo de errores te recomiendo que escribas tus consultas identadas (como veremos más abajo), así podrás hacer una verificación rápida si fuera preciso.

*Estás ejecutando dos veces la consulta, aquí: $con->query($sql); y aquí: $con->query($sql); Es el mismo método, con dos estilos distintos.

*Es extraño que el var_dump no arroje nada. Pues lo que estarías imprimiendo sería la consulta SQL que no es otra cosa que una cadena.

*No estás controlando posibles errores con respecto a la consulta. En la respuesta lo implementaremos. En cuanto al Excel y los datos que vienen de él lo dejo a tu cuidado, pues es algo que escapa al alcance de la respuesta por no tener contexto suficiente.

*Es recomendable para este código usar consultas preparadas, cosa que haremos.
Te propongo esta solución la cual, repito, sólo atañe a la parte de la consulta. Si no funciona o no muestra nada, debes revisar la parte del archivo y controlar que realmente los datos que intentas leer en él existen.
if ($con) {
    $sql="INSERT INTO rallyracer
              (autonumero,
               piloto_copiloto,
               clase,
               vuelta,
               largada,
               llegada,
               final,
               penalizacion,
               tiempofinal,
               diferencia,
               actualizado_a)
            VALUES
              (?,?,?,?,?,?,?,?,?,?)";

    if( $stmt=$con->prepare($sql) ) {
        $stmt->bind_param("sssssssssss", $autonumero, $piloto_copiloto, $clase, $vuelta,
                                         $largada, $llegada, $final, $penalizacion,
                                         $tiempofinal, $diferencia, $now);
        if ($stmt->execute()) {
            $outPut="Consulta exitosa. Filas insertadas: ".$stmt->affected_rows;
        } else {
            $outPut="Error en la consulta: ".$stmt->error;
        }
    } else {
        $outPut="Error preparando la consulta: ".$con->error;
    }

} else {
    $outPut="Error de conexión";
}
echo $outPut;

El código hace una verificación de todos los posibles errores, así como de los resultados exitosos. En todos los casos guardará información en la variable $outPut que será mostrada al final.
NÓTESE: que he hecho dos llamadas a la propiedad error de mysqli. Esa llamada te ayudará a conocer el motivo por el que código estaría fallando. No obstante, estás llamadas no son recomendables para la fase de producción de tu aplicación, deberías cambiarlas por mensajes de error genéricos o personalizados o incorporar tu propia política de manejo de errores.


text:
Q: Xamarin Forms ScrollView issue with Editor when using the software Keyboard I'm using Xamarin Forms with iOS. I have an Editor within a scrollview. The editor is set to the fill most of the page. This is working.
<ContentPage.Content>
    <ScrollView>
    <StackLayout>
        <Editor x:Name="NotesEditor" Text="{Binding Contact.AttendanceDetails.Notes, Mode=TwoWay}"  VerticalOptions="FillAndExpand"
            HorizontalOptions="FillAndExpand" BackgroundColor="AliceBlue" TextChanged="NotesEditor_TextChanged"  ></Editor>

    </StackLayout>
    </ScrollView>
</ContentPage.Content>

The issue is when the software keyboard is used, the page scrolls and when the user starts typing, they do not initially see the text they are typing on the keyboard without manual scrolling.
Is there a way the software keyboard doesn't push the scrollview? So the user can do it manually maybe?
Any thoughts would be appreciated.

A: Managed a fix by adding an event to the Editor Focused event:
XAML:
<ScrollView x:Name="scrollview">
    <StackLayout>
        <Editor x:Name="NotesEditor" Text="{Binding Contact.Notes, Mode=TwoWay}"  VerticalOptions="FillAndExpand"
            HorizontalOptions="FillAndExpand" BackgroundColor="AliceBlue" TextChanged="NotesEditor_TextChanged" Focused="NotesEditor_Focused"   ></Editor>

    </StackLayout>
    </ScrollView>

Code behind:
private void NotesEditor_Focused(object sender, FocusEventArgs e)
    {
        scrollview.ScrollToAsync(0, 0,true);
    }

A: I'm not sure of your use case but why not completely remove the ScrollView ? There's no reason to scroll if the editor is full screen, You can apply margin to the label if you still want to see it.
<ContentPage.Content>
    <StackLayout>
        <Editor x:Name="NotesEditor" Text="{Binding Contact.AttendanceDetails.Notes, Mode=TwoWay}"  VerticalOptions="FillAndExpand"
            HorizontalOptions="FillAndExpand" BackgroundColor="AliceBlue" TextChanged="NotesEditor_TextChanged"  ></Editor>

    </StackLayout>
</ContentPage.Content>

A: Try this component it might work  with no need for the scrollView . However it will fail if you enabled the expanding of the editor .
https://devlinduldulao.pro/how-to-fix-keyboard-overlapping-or-covering-entry/

A: If you want an editor in a scrollview, you can try this solution.
<ContentPage>
 <ScrollView >
                  <Grid VerticalOptions="FillAndExpand">
                              <Grid.RowDefinitions>
                             <RowDefinition Height="Auto" />
                               </Grid.RowDefinitions>

                   <Editor VerticalOptions="FillAndExpand"
                                                       AutoSize="TextChanges"
                              -----
                              Grid.Row="0" />
                     </Grid>
  </ScrollView>
</ContentPage>

for eg: your code should be like this
<ContentPage.Content>
    <ScrollView>
   <Grid VerticalOptions="FillAndExpand">
                              <Grid.RowDefinitions>
                                <RowDefinition Height="Auto" />
                                 <RowDefinition Height="Auto" />
                               </Grid.RowDefinitions>
        <Editor x:Name="NotesEditor" Text="{Binding Contact.AttendanceDetails.Notes, Mode=TwoWay}"  VerticalOptions="FillAndExpand"
            HorizontalOptions="FillAndExpand" BackgroundColor="AliceBlue" TextChanged="NotesEditor_TextChanged" Grid.Row="0" ></Editor>

    </Grid>
    </ScrollView>
</ContentPage.Content>

Note: You can Set hightRequest for the Scroll view if required.


text:
Q: ReactJs: onClick is preemtively called I have 2 onClick functions
function VisitGallery(name) {
  const history = useHistory();
  console.log("visitgallery", name)
  history.push("/gallery")
}

function App() {
  const accesstoken = "******************"
  const [viewport, setviewport] = React.useState({
    latitude: ******
    longitude: *******
    width: "100vw",
    height: "100vh",
    zoom: 11
  })

  const [details, setdetails] = React.useState([
  ])

  React.useEffect(() => {
    const fetchData = async () => {
      const db = firebase.firestore()
      const data = await db.collection("data").get()
      setdetails(data.docs.map(doc => doc.data()))
    }
    fetchData();
  }, [])

  const [selectedpark, useselectedpark] = React.useState(null);

  React.useEffect(() => {
    const listener = e => {
      if (e.key === "Escape") {
        useselectedpark(null);
      }
    };
    window.addEventListener("keydown", listener)

    return () => {
      window.removeEventListener("keydown", listener)
    }
  }, [])

  return (

      <ReactMapGl {...viewport}
        mapboxApiAccessToken={accesstoken}
        mapStyle="mapbox://**************"
        onViewportChange={viewport => {
          setviewport(viewport)
        }}>

        {details.map((details) =>
          <Marker key={details.name} latitude={details.lat} longitude={details.long}>

            <button class="marker-btn" onClick={(e) => {
              e.preventDefault();
              useselectedpark(details);
            }}>

            </button>

          </Marker>

        )}

        {selectedpark ?
          (<Popup
            latitude={selectedpark.lat}
            longitude={selectedpark.long}
            onClose={() => {
              useselectedpark(null);
            }}
          >

              <Card style={{ width: '18rem' }}>
                <Card.Body>
                  <Card.Title>{selectedpark.name}</Card.Title>
                  <Card.Text>
                    {selectedpark.postalcode}
                  </Card.Text>
                  <Button variant="primary" onClick = VisitGallery() >Visit Gallery</Button>
                </Card.Body>
              </Card>

          </Popup>)
          : null}
        {
          console.log("in render", details)
        }

      </ReactMapGl>

  );
}

export default App;

The outer onClick is assigned when the marker is first created, and when it is clicked the useselectedpark function is called, details is then assigned to selectedpark.
The inner onClick is assigned to the function VisitGallery(). When the inner onClick is triggered, i want to navigate to another page, hence the history.push().
Ideally, what i want for it to happen is, when the outer onClick is triggered, the cardview shows, and i have an option to visit the next page, which can be triggered by an onClick within the card. However, what is happening right now is both the onClicks are triggered when i click on the thumbnail. How do i fix it such that it is how i want it to be ideally?
ps: do let me know if my explanation is confusing and i will edit it accordingly

A: Try adding your second onClick into a callback function?
<Button variant="primary" onClick='()=>{ VisitGallery() }' >Visit Gallery</Button>

So that it doesn't automatically invoke the function until the click is triggered.


text:
Q: Export sqoop eval results into a comma delimited output I am running a sqoop eval code which produces output in a pipe separated format. I would like to have it in a comma format and remove the extra formatting so that I can store it in variable and can use somewhere else.
Below is the code:
sqoop eval -Dmapreduce.job.queuename=comres $PASS_STRING --connect 'jdbc:sqlserver://XXXX:1433;DatabaseName=XXXX' --query "select column_name from information_schema.columns where table_name='MOT_BAJA' AND TABLE_CATALOG='EEEE'"
This is what is showing right now:
------------------------
| column_name          |
------------------------
| TB_CODIGO            |
| TB_ELEMENT           |
| TB_INGLES            |
| TB_IMSS              |
| TB_NUMERO            |
| TB_TEXTO             |
| LLAVE                |
------------------------

I want it like this:
TB_CODIGO,TB_ELEMENT,TB_INGLES,TB_IMSS,TB_NUMERO,TB_TEXTO,LLAVE

A: You can maybe use awk:
your_command | awk 'NR > 3 && NF==3 {printf "%s%s", (printed ? "," : ""), $2; printed++}'

Explanation:
NR > 3 && NF == 3: if the Number of Row (NR) we are currently processing is greater than 3, and the Number of Fields (NF) for this row is 3, then go ahead and process the row using the code in { ... }.
printed: we keep in this variable the number of fields we have printed by far.
(printed ? "," : ""): if have printed at least one field by far, this evaluates to ",". Else it evaluates to an empty string "".
printf "%s%s", (printed ? "," : ""), $2: , print a "," if we have already printed a field before. Then print the second word of the current row.


text:
Q: org.openqa.selenium.json.JsonOutput.write(Ljava/lang/Object;)Lorg/openqa/selenium/json/JsonOutput; due to java.io.IOException: Incomplete document I'm creating a new test framework from scratch using Spring Boot 2 and Appium. To write the tests I'm using JUnit which is already included in Spring Boot's spring-boot-starter-test POM along with many others. I added Appium to my POM and it now looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.automationexperiment</groupId>
    <artifactId>one</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>jar</packaging>

    <name>demo</name>
    <description>Demo project for Spring Boot</description>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.6.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/io.appium/java-client -->
        <dependency>
            <groupId>io.appium</groupId>
            <artifactId>java-client</artifactId>
            <version>6.1.0</version>
            <scope>test</scope>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>
</project>

As for my tests, I have a DriverSetup class that looks like this:
@RunWith(SpringRunner.class)
@SpringBootTest
public class DriverSetup {

  protected AndroidDriver<AndroidElement> driver;

  @Before
  public void setUp() throws MalformedURLException {
    DesiredCapabilities capabilities = new DesiredCapabilities();
    capabilities.setCapability(MobileCapabilityType.PLATFORM_NAME, "Android");
    capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "6.0.1");
    capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "DeviceName");
    capabilities.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, "com.google.android.gm");
    capabilities.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, ".ConversationListActivityGmail");
    URL myUrl = new URL("http://127.0.0.1:4723/wd/hub");
    this.driver = new AndroidDriver<AndroidElement>(myUrl, capabilities);
    this.driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
  }
}

Finally, I have another class that extends from DriverSetup to make sure driver initialization is done before every test. It looks like this:
@RunWith(SpringRunner.class)
@SpringBootTest
public class FirstTryTest extends DriverSetup {

  public FirstTryTest() { }

  @Test
  public void test() {
    System.out.println("test");
  }
}

I just want to make sure I can reach the test in my FirstTryTest, but every time the code initializes the AndroidDriver with the URL and the DesiredCapabilities, I get the following error:
java.lang.NoSuchMethodError: org.openqa.selenium.json.JsonOutput.write(Ljava/lang/Object;)Lorg/openqa/selenium/json/JsonOutput;
    at io.appium.java_client.remote.NewAppiumSessionPayload.writeTo(NewAppiumSessionPayload.java:265)
    at io.appium.java_client.remote.AppiumCommandExecutor$1.createSession(AppiumCommandExecutor.java:175)
    at io.appium.java_client.remote.AppiumCommandExecutor.createSession(AppiumCommandExecutor.java:209)
    at io.appium.java_client.remote.AppiumCommandExecutor.execute(AppiumCommandExecutor.java:231)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:601)
    at io.appium.java_client.DefaultGenericMobileDriver.execute(DefaultGenericMobileDriver.java:42)
    at io.appium.java_client.AppiumDriver.execute(AppiumDriver.java:1)
    at io.appium.java_client.android.AndroidDriver.execute(AndroidDriver.java:1)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:219)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:142)
    at io.appium.java_client.DefaultGenericMobileDriver.<init>(DefaultGenericMobileDriver.java:38)
    at io.appium.java_client.AppiumDriver.<init>(AppiumDriver.java:84)
    at io.appium.java_client.AppiumDriver.<init>(AppiumDriver.java:94)
    at io.appium.java_client.android.AndroidDriver.<init>(AndroidDriver.java:93)
    at com.automationexperiment.one.driversetup.DriverSetup.setUp(DriverSetup.java:31)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at com.microsoft.java.test.runner.JUnit4TestReference.run(JUnit4TestReference.java:51)
    at com.microsoft.java.test.runner.CustomizedJUnitCoreRunner.run(CustomizedJUnitCoreRunner.java:45)
    at com.microsoft.java.test.runner.JUnitLauncher.execute(JUnitLauncher.java:26)
    at com.microsoft.java.test.runner.JUnitLauncher.main(JUnitLauncher.java:15)
    Suppressed: java.io.IOException: Incomplete document
        at com.google.gson.stream.JsonWriter.close(JsonWriter.java:559)
        at org.openqa.selenium.json.JsonOutput.close(JsonOutput.java:39)
        at io.appium.java_client.remote.NewAppiumSessionPayload.writeTo(NewAppiumSessionPayload.java:288)
        ... 41 more

I've tried using an older version of Appium (5.0.4) but it didn't work. I'd like to emphasize the end of the StackTrace. An IOException is mentioned while in other questions with similar errors script fails due to a
 org.openqa.selenium.json.JsonException`.

A: This error message:
java.lang.NoSuchMethodError: org.openqa.selenium.json.JsonOutput.write(Ljava/lang/Object;)Lorg/openqa/selenium/json/JsonOutput;
.
Suppressed: java.io.IOException: Incomplete document

...implies that java.lang.NoSuchMethodError was raised by the JVM.
You have mentioned about using an older version of Appium v5.0.4
It's pretty tough to analyze the error in absence of the following information pertaining to your Test Environment:

*

*Appium server version

*Desktop OS/version

*Mobile platform/version under test

*Real device or emulator/simulator

As per the discussions Error while running Appium script with AndroidDriver and iOS :Could not initialize the ios capabilities with 6.0.0  this error seems to be coming from the NumberCoercer Class which have been modified in Selenium RemoteDriver v3.12.0 to accept Port as Integer while earlier it was accepting String.
Solution

*

*Update to the latest Appium Java Client v6.1.0

*Update to the latest (atleast) Selenium v3.12.0

*@SrinivasanTarget mentions one important aspect that:

*

*
Appium's Java client comes along with Selenium Dependency so we don't recommend to exclude selenium and add as separate dependency as it may raise conflicts at times.

Here you will find a relevant discussion on java.lang.NoSuchMethodError: org.openqa.selenium.json.JsonOutput.write(Ljava/lang/Object;Ljava/lang/reflect/Type;)


text:
Q: SQL return the output of SELECT and not the output of another stored procedure How do I return the result of the SELECT as the output of the stored procedure? Sorry I'm new to stored procedures!
In this query below I'm calling stored procedure spCuExt_ExtractLog and assigning the result to variable @StartDate. I then use this variable within the main stored procedure, in a SELECT statement. I need to return only the result of the SELECT statement from the main stored procedure:
-- Main stored procedure
BEGIN
    DECLARE @StartDate DATETIME

    EXEC @StartDate = spCuExt_ExtractLog 'Customers'

    SELECT Id, [Name], LogoPath, IsDeleted
    FROM dbo.Customers
    WHERE RecordCreatedDateUTC>= @StartDate
END

This returns the result of the call to spCuExt_ExtractLog as well as the result of the SELECT statement but I want to output the result of the SELECT only.
How do I do this?

A: Here's a link to a pretty good document explaining all the different ways to solve your problem (although a lot of them can't be used since you can't modify the existing stored procedure.)
http://www.sommarskog.se/share_data.html

A: Put the results into a table variable instead:
create procedure dbo.usp_Child
as
begin
    select N'Hello world!' as [message];
end;
go

create procedure dbo.usp_Main
as
begin;
    declare @results table ([message] nvarchar(max));

    insert into @results
    execute dbo.usp_Child;

    select N'success';
end;
go

execute dbo.usp_Main;


text:
Q: PHP file_put_contents doesn't work as expected within in register_shutdown_function() I am playing with output buffering in my script and stumbled upon unexpected behaviour.
Writing to a file works everywhere else in my script, but it doesn't quite do so after entering the register_shutdown_function()-function.
I get a warning telling me I don't have permission to write to the file.  So I checked which path I was in.  Apparently the current working directory vanishes from the moment you enter the shutdown function.
My question is not particularly on how to solve this; As you can see, I just included the correct path.  My question is, is this expected behavior and if so, what's the logic behind it?
I'm on OSX/MAMP-PRO if that matters.  Haven't tried it yet on another box.
<?
register_shutdown_function('_lib_bootstrap_end');
ob_start();
_lib_bootstrap_start();
file_put_contents('test1.log','this_one_writes_fine');

function _lib_bootstrap_start()
{
    echo getcwd()."\n"; // prints '/Users/macbook/Documents/WWW';
    file_put_contents('test2.log','this_one_writes_fine');
}

function _lib_bootstrap_end()
{
    global $html;

    file_put_contents('test3.log', 'this_one_triggers_warning');
    $html[] = ob_get_contents();
    $return = implode("\n",$html);
    ob_end_clean();

    echo $return;
    echo getcwd()."\n"; // prints '/';

    file_put_contents('test4.log', 'this_one_triggers_warning');
    // prints 'Warning: file_put_contents(test4.log): failed to open stream: Permission denied in ob_problem.php on line 24'

    file_put_contents($_SERVER['DOCUMENT_ROOT'].'/'.'test5.log','this_one_writes_fine');
}
?>

A: The behaviour is expected according to the manual page for register_shutdown_function():

Working directory of the script can change inside the shutdown function under some web servers, e.g. Apache.

I don't know the reasoning behind this.


text:
Q: Least angle regression for a set of vectors? As far as I know, LARS solves the following problem (using the same notation as Efron et al. Least angle regression):

Given a vector y, and a matrix X. Pick some column vectors from X, and express y as a linear combination of these column vectors.

In my problem, I have a set of vectors, which can form a matrix Y. I would like to express each column vector of Y as a linear combination of some column vectors from X. I hope that the fitting quality could be good (L2), and the number of column vectors I use from X is small (L1). Therefore, I am wondering if there is any systematic study (any papers?) on applying LARS to fit a set of vectors, rather than just one vector.
Below is my solution. Comments are highly appreciated.
Suppose Y = (y1 y2 ...) and X = (x1 x2 ...), where yi, xi are vectors. Treat Y as a high-dimensional 1D vector (flatten it) like
$Y' = \left(\begin{array}{c}
y1\\
y2\\
...\end{array}\right)$
Then we define the new basis matrix X' as (the blank part are all zeros)
$X' = \left(\begin{array}{ccc}
X & & \\
& X &\\
& & ...\end{array}\right)$
Then we just apply LARS directly to fit Y' using X'. Once we have picked columns from X', we merge them into a set of columns from X, which will be the final "basis vector" set to fit Y.
One thing I feel uncomfortable about the above solution is that, it does not consider the fact that the same set of basis vectors from X will be used to express all column vectors of Y. Only the final step merges the result from LARS. Your help is appreciated. Thanks.

A: You should read about multi-task learning. A good place to start is this page: http://www.public.asu.edu/~jye02/Software/MALSAR/index.html (both the manual and tutorial).
There are many, many formulations and regularizers that people have devised for the class of problems you are interested in.


text:
Q: Programmatically creating an image in Electron I'd like to create an image (say a nativeImage) from a JS array containing raw pixel RGB values.
I tried creating a nativeImage like this:

const buf = Buffer.from([[0, 0, 255], [0, 0, 0], [0, 255, 0], [255, 0, 0]])
const img = nativeImage.createFromBuffer(buf, {width: 2, height: 2})
...
<img width={16} height={16} src={img.toDataURL()} />

But it seems like the image always turns out black.
Some online resources seem to indicate that the createFromBuffer call expects the buffer to contain PNG encoded data (I couldn't really tell from the API ref).
Is there a way to go directly from pixel values to an image?

A: The buffer should contain values alpha values too, not just RGB (e.g,. [A0,R0,G0,B0, A1,R1,G1,B1, ... ]).
For example:
const buf = Buffer.from([255,0,0,255, 0,255,0,255, 0,0,255,255, 0,0,0,255])
const img = nativeImage.createFromBuffer(buf, {width: 2, height: 2})

This will generate an image like so:


text:
Q: Run modules that contain parts in native android on snack.expo I'm having trouble running a module that contains parts in native android.
I am given the following error.
Invariant Violation: View config not found for name RNMaterialLetter.
The module is as follows:
https://www.npmjs.com/package/react-native-material-letter-icon
Is there any way to run these modules that have a part in native on snack.expo?

A: All the modules whom require a react-native link are incompatible with snack and expo.
In order to use it, you have to detach to expokit.
There's some rare exceptions to this rule, like react-native-element, because dependecies need by this module are already in the expo sdk.


text:
Q: Get XML schema used by sql column I want to select xml schema assigned to a xml column in my SQL Server database, from a SQL statement.
I am stuck, I've looked in information_schema.columns with no luck, I can just alter it.
In Management Studio, in column properties under Xml Type Specification I can set (scheme collection) I want to simply select this from SQL statement.
Thanks for your help.

A: Something like this should do it.
select C2.name
from sys.columns as C1
  inner join sys.xml_schema_collections as C2
    on C1.xml_collection_id = C2.xml_collection_id
where C1.object_id = object_id('TableName') and
      C1.name = 'ColumnName'


text:
Q: How do I recover deleted books from inventory in minecraft? I died in my hardcore mode world that I really care about. and I changed myself to creative mode, grabbed my stuff, put it in a chest and made a new book explaining to my future self how I died and how long I survived for in case my future self curiously came into the world to see what it was.
After I finished writing the book I grabbed my book of coordinates from my chest that I created and wrote before I died. I decided to play around with the save toolbar hotkey (dumb idea) and went to try save my toolbar, but instead of pressing C+6 like I meant to, I accidentally pressed X+6, which cleared my inventory completely because toolbar number 6 in the inventory was already previously empty, so it essentially replaced all my items with air.
My question here is, is there any way I can find and recover those 2 books in the world files or game files? I don't care what it takes to get those books back even if I have to mod the game, I just want a way to recover the books.
I don't really care much for the death book, just as long as I can get my coordinates back because they are extremely important to have.

A: Your only chance would be to Alt + F4 out of the game (or crash it by other means) before it saves anything to your drive, so you have to do this as soon as possible. But you should use this approach with caution. In rare cases it could as well corrupt your game files and eventually destroy your saved world.
If it's already too late for that there is no known way of getting your books back.
There is currently nothing in the game that can restore a cleared inventory by normal means.
For the future:
Make backups. Save a copy of your world somewhere else and doing so on a regular basis can save you a lot of headache.


text:
Q: Using Bernoulli distribution approximate the $q$-th moment Let $x$ be vector in $R^n$. Let $\pi(⋅)$  be a permutation on the set $\{1,\ldots,n\}$  with a uniform distribution.  Let $|m|\leq n, m \in Z$.
Using Bernoulli (or maybe some other) distribution approimate the $q$-th moment
$$
E\left|\sum_{i=1}^mx_{\pi(i)}\right|^q, \quad q\geq 2.
$$
Thank you.


text:
Q: Security Error in Silverlight Application i have deployed my silverlight app, service and database all in different server. but when trying to run app, got security error. after doing researches, there are mostly the same solution which is about clientaccesspolicy.xml and crossdomain.xml. so, i have created these 2 files and put this in inetpub/wwwroot/ for all servers. but i still got the error. pls help me...what should i do now? should my app be put in inetpub/wwwroot/ too?, since now it is located in different drive.
clientaccesspolicy.xml:
<?xml version="1.0" encoding="utf-8"?>
<access-policy>
    <cross-domain-access>
        <policy>
            <allow-from http-request-headers="SOAPAction">
                <!-- IMPORTANT! Include these lines -->
                <domain uri="http://*"/>
                <domain uri="https://*"/>
            </allow-from>
            <grant-to>
                <resource path="/" include-subpaths="true"/>
            </grant-to>
        </policy>
    </cross-domain-access>
</access-policy>

crossdomain.xml:
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
  <allow-http-request-headers-from domain="*" headers="SOAPAction,Content-Type"/>
</cross-domain-policy>


text:
Q: preserving JSON in jq with massive filter and sub() So i have this massive jq filter, and i can pretty much get it to do what i want.
cat test.json |jq '.spec.install.spec.deployments[].spec.template.spec.containers[].env[] | select(.name | contains("_IMAGE")) | .value |= sub("registry.redhat.io"; "repo.home.nicknach.net:5000"; "g")'

which yields:
{
  "name": "ELASTICSEARCH_IMAGE",
  "value": "repo.home.nicknach.net:5000/openshift4/ose-logging-elasticsearch5@sha256:ea785fcfd3896d22a96eaea2dc5aab6496c2b8f79005d3e8a49b8b69320ed877"
}
{
  "name": "FLUENTD_IMAGE",
  "value": "repo.home.nicknach.net:5000/openshift4/ose-logging-fluentd@sha256:41718848dff54ef399b05cb9ba93f1b498dc656ae625638fbfb277aab46de2c9"
}
{
  "name": "KIBANA_IMAGE",
  "value": "repo.home.nicknach.net:5000/openshift4/ose-logging-kibana5@sha256:ddf4a9ea97213775576a8c4d340ca6e7f1117dc5e97378adbc01cda4f1eabb26"
}
...

The problem is, i dont understand how to get the entire JSON (it's huge) with my modified values.  Is this possible in jq?  I seem to only be able to get the parts that i modified.  I want the entire thing, with the parts that i modified in there.

A: |= (Update-assignment) operates on paths. .spec.install.spec.deployments[].spec.template.spec.containers[].env[] | … is a filter which already modifies your document.
TLDR: you are missing parentheses to turn the left-hand side of the assignment into a single path expression:
(
  .spec.install.spec.deployments[].spec.template.spec.containers[].env[]
  | select(.name | contains("_IMAGE"))
  | .value
) |= sub("registry.redhat.io"; "repo.home.nicknach.net:5000"; "g")

NB: always provide an MWE to make it easier for answerers to actually answer your question. I had to come up with a valid (?) input myself:
{
    "spec": {
        "install": {
            "spec": {
                "deployments": [
                    {
                        "spec": {
                            "template": {
                                "spec": {
                                    "containers": [
                                        {
                                            "env": [
                                                {
                                                    "name": "ES_IMAGE",
                                                    "value": "registry.redhat.io/yada"
                                                },
                                                {
                                                    "name": "KIBANA_IMAGE",
                                                    "value": "registry.redhat.io/yada"
                                                },
                                                {
                                                    "name": "other_var",
                                                    "value": "not a registry.redhat.io"
                                                }
                                            ]
                                        },
                                        {
                                            "env": [
                                                {
                                                    "name": "ES_IMAGE",
                                                    "value": "registry.redhat.io/yada"
                                                },
                                                {
                                                    "name": "KIBANA_IMAGE",
                                                    "value": "registry.redhat.io/yada"
                                                }
                                            ]
                                        }
                                    ]
                                }
                            }
                        }
                    }
                ]
            }
        }
    }
}

which yields the following output when being applied the above filter:
{
  "spec": {
    "install": {
      "spec": {
        "deployments": [
          {
            "spec": {
              "template": {
                "spec": {
                  "containers": [
                    {
                      "env": [
                        {
                          "name": "ES_IMAGE",
                          "value": "repo.home.nicknach.net:5000/yada"
                        },
                        {
                          "name": "KIBANA_IMAGE",
                          "value": "repo.home.nicknach.net:5000/yada"
                        },
                        {
                          "name": "other_var",
                          "value": "not a registry.redhat.io"
                        }
                      ]
                    },
                    {
                      "env": [
                        {
                          "name": "ES_IMAGE",
                          "value": "repo.home.nicknach.net:5000/yada"
                        },
                        {
                          "name": "KIBANA_IMAGE",
                          "value": "repo.home.nicknach.net:5000/yada"
                        }
                      ]
                    }
                  ]
                }
              }
            }
          }
        ]
      }
    }
  }
}