text:
Q: Converting unknown JSON string to correct object I'm receiving an unknown string from a socket connection. It always follows the format
{
    "eventType": "playerListUpdate"
    "data": "...changes..."
}

I'm deserialising it using:
var message = JsonConvert.DeserializeObject<NetworkMessage>(data);

With the NetworkMessage looking like this:
public class NetworkMessage
{
    public string data;
    public string eventType;
}

My problem is that sometimes the data property stays as a string, and other times it contains an array with more complex data (think DB results). So when I try to deserialise a string with an array in data, it fails.
An example of more complex data is
{"eventType":"latestPlayersList","data":[{"id":1,"firstName":"Harry"},{"id":2,"firstName":"Ted"},{"id":3,"firstName":"Michael"},{"id":4,"firstName":"Mike"}],"from":"server"}

How can I deserialise a JSON string into different VO depending on the value of eventType?

A: One way to deserialise is to go directly to a JObject
var jObject = JsonConvert.DeserializeObject<JObject>(json);

Now you can access property values like this:
var eventType = jObject.Value<string>("eventType")

Now you could also extend this to check the value of eventType and then deserialise to the right object type. So we could have a generic class like this:
public class NetworkMessage<T>
{
    public string EventType;
    public T Data;
}

public class Player
{
    public int Id { get; set; }
    public string FirstName { get; set; }
}

And decide what the generic type we use based on the value of eventType. Note, this isn't the most efficient code in the world as it deserialises twice, but it will work:
private void ProcessJson(string json)
{
    var jObject = JsonConvert.DeserializeObject<JObject>(json);

    switch (jObject.Value<string>("eventType"))
    {
        case "playerListUpdate":
            HandlePlayerListUpdate(jObject.ToObject<NetworkMessage<string>>());
            break;
        case "latestPlayersList":
            HandleLatestPlayersList(jObject.ToObject<NetworkMessage<List<Player>>>());
            break;
    }
}

private void HandlePlayerListUpdate(NetworkMessage<string> playerListUpdateMessage)
{
    Console.WriteLine($"Player list update: {playerListUpdateMessage.Data}");
}

private void HandleLatestPlayersList(NetworkMessage<List<Player>> latestPlayersListMessage)
{
    Console.WriteLine($"Latest Players list: {latestPlayersListMessage.Data.Count} players");
}

A: You can use Newtonsoft.json. Try below.
var files = JObject.Parse(YourJSONHere);
var recList = files.SelectTokens("$..eventType").ToList();
for (int i = 0; i < recList.Count(); i++)
        {
            if (recList[i].ToString().Contains("latestPlayersList"))
            {
                var data = files.SelectTokens("$..data").ToList();
                Console.Write(data.FirstOrDefault());
            }

            if (recList[i].ToString().Contains("playerListUpdate"))
            {
                var data = files.SelectTokens("$..data").ToList();
            }

        }


text:
Q: A confusion about ${array[*]} versus ${array[@]} in the context of a bash completion I'm taking a stab at writing a bash completion for the first time, and I'm a bit confused about about the two ways of dereferencing bash arrays (${array[@]} and ${array[*]}).
Here's the relevant chunk of code (it works, but I would like to understand it better):
_switch()
{
    local cur perls
    local ROOT=${PERLBREW_ROOT:-$HOME/perl5/perlbrew}
    COMPREPLY=()
    cur=${COMP_WORDS[COMP_CWORD]}
    perls=($ROOT/perls/perl-*)
    # remove all but the final part of the name
    perls=(${perls[*]##*/})

    COMPREPLY=( $( compgen -W "${perls[*]} /usr/bin/perl" -- ${cur} ) )
}

bash's documentation says:

Any element of an array may be referenced using ${name[subscript]}. The braces are required to avoid conflicts with the shell's filename expansion operators. If the subscript is '@' or '*', the word expands to all members of the array name. These subscripts differ only when the word appears within double quotes. If the word is double-quoted, ${name[*]} expands to a single word with the value of each array member separated by the first character of the IFS variable, and ${name[@]} expands each element of name to a separate word.

Now I think I understand that compgen -W expects a string containing a wordlist of possible alternatives, but in this context I don't understand what "${name[@]} expands each element of name to a separate word" means.
Long story short: ${array[*]} works; ${array[@]} doesn't. I would like to know why, and I would like to understand better what exactly ${array[@]} expands into.

A: Your title asks about ${array[@]} versus ${array[*]} (both within {}) but then you ask about $array[*] versus $array[@] (both without {}) which is a bit confusing. I'll answer both (within {}):
When you quote an array variable and use @ as a subscript, each element of the array is expanded to its full content regardless of whitespace (actually, one of $IFS) that may be present within that content. When you use the asterisk (*) as the subscript (regardless of whether it's quoted or not) it may expand to new content created by breaking up each array element's content at $IFS.
Here's the example script:
#!/bin/sh

myarray[0]="one"
myarray[1]="two"
myarray[3]="three four"

echo "with quotes around myarray[*]"
for x in "${myarray[*]}"; do
        echo "ARG[*]: '$x'"
done

echo "with quotes around myarray[@]"
for x in "${myarray[@]}"; do
        echo "ARG[@]: '$x'"
done

echo "without quotes around myarray[*]"
for x in ${myarray[*]}; do
        echo "ARG[*]: '$x'"
done

echo "without quotes around myarray[@]"
for x in ${myarray[@]}; do
        echo "ARG[@]: '$x'"
done

And here's it's output:
with quotes around myarray[*]
ARG[*]: 'one two three four'
with quotes around myarray[@]
ARG[@]: 'one'
ARG[@]: 'two'
ARG[@]: 'three four'
without quotes around myarray[*]
ARG[*]: 'one'
ARG[*]: 'two'
ARG[*]: 'three'
ARG[*]: 'four'
without quotes around myarray[@]
ARG[@]: 'one'
ARG[@]: 'two'
ARG[@]: 'three'
ARG[@]: 'four'

I personally usually want "${myarray[@]}". Now, to answer the second part of your question, ${array[@]} versus $array[@].
Quoting the bash docs, which you quoted:

The braces are required to avoid conflicts with the shell's filename expansion operators.

$ myarray=
$ myarray[0]="one"
$ myarray[1]="two"
$ echo ${myarray[@]}
one two

But, when you do $myarray[@], the dollar sign is tightly bound to myarray so it is evaluated before the [@]. For example:
$ ls $myarray[@]
ls: cannot access one[@]: No such file or directory

But, as noted in the documentation, the brackets are for filename expansion, so let's try this:
$ touch one@
$ ls $myarray[@]
one@

Now we can see that the filename expansion happened after the $myarray exapansion.
And one more note, $myarray without a subscript expands to the first value of the array:
$ myarray[0]="one four"
$ echo $myarray[5]
one four[5]

A: (This is an expansion of my comment on Kaleb Pederson's answer -- see that answer for a more general treatment of [@] vs [*].)
When bash (or any similar shell) parses a command line, it splits it into a series of "words" (which I will call "shell-words" to avoid confusion later).  Generally, shell-words are separated by spaces (or other whitespace), but spaces can be included in a shell-word by escaping or quoting them.  The difference between [@] and [*]-expanded arrays in double-quotes is that "${myarray[@]}" leads to each element of the array being treated as a separate shell-word, while "${myarray[*]}" results in a single shell-word with all of the elements of the array separated by spaces (or whatever the first character of IFS is).
Usually, the [@] behavior is what you want.  Suppose we have perls=(perl-one perl-two) and use ls "${perls[*]}" -- that's equivalent to ls "perl-one perl-two", which will look for single file named perl-one perl-two, which is probably not what you wanted.  ls "${perls[@]}" is equivalent to ls "perl-one" "perl-two", which is much more likely to do something useful.
Providing a list of completion words (which I will call comp-words to avoid confusion with shell-words) to compgen is different; the -W option takes a list of comp-words, but it must be in the form of a single shell-word with the comp-words separated by spaces.  Note that command options that take arguments always (at least as far as I know) take a single shell-word -- otherwise there'd be no way to tell when the arguments to the option end, and the regular command arguments (/other option flags) begin.
In more detail:
perls=(perl-one perl-two)
compgen -W "${perls[*]} /usr/bin/perl" -- ${cur}

is equivalent to:
compgen -W "perl-one perl-two /usr/bin/perl" -- ${cur}

...which does what you want.  On the other hand,
perls=(perl-one perl-two)
compgen -W "${perls[@]} /usr/bin/perl" -- ${cur}

is equivalent to:
compgen -W "perl-one" "perl-two /usr/bin/perl" -- ${cur}

...which is complete nonsense: "perl-one" is the only comp-word attached to the -W flag, and the first real argument -- which compgen will take as the string to be completed -- is "perl-two /usr/bin/perl".  I'd expect compgen to complain that it's been given extra arguments ("--" and whatever's in $cur), but apparently it just ignores them.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Async transactions with PHP and mySQL When a certain action happens on the site (built in PHP and MySQL) I would like few asynchronous things to happen on the site.
For example, when a user answers a question, uploads document, I want few asynchronous things to happen in the background such as:
1.update user's score
2. Post a message on Facebook wall
3.track users actions.
What PHP, JavaScript and MySQL technologies are best for achieving this? Please help.
I want something that MySQL triggers but wanted to happen asynchronously.

A: The only two options I can think of are a messaging queue, and async ajax.
The first option works by putting jobs into a database, then a scheduled php program will loop through every job in the database and run them.
The second is just calling a php program using ajax.
For the first option look at something like: http://alanstorm.com/simple_php_job_queue
For the second look at jquery, and its ajax options: http://api.jquery.com/jQuery.ajax/

A: The best option is to call three separate PHP scripts using exec and passing the output to null, like below.
exec("/usr/bin/php somescript.php >> some_log_file.log 2>&1 &");
Doing the same exec on three scripts for your three functions will execute, all three things concurrently/asynchronously. This is what your after.
If you add jobs to a job queue and then have a cron clear that queue, your not really doing it asynchronously. Your still doing things one by one, in a synchronous blocking fashion - although the user is not waiting for these things to happen. There might be a delay in the queue being cleared as well if your site has high traffic, you won't get the same delay with exec. Since the script will be executed immediately and concurrently to the initial request.
Side Note: This is why Node.js is becoming so popular it's built on JavaScript which is designed for this kind of development approach. Asynchronous and event driven.

A: Use the swoole extension.
https://github.com/matyhtf/swoole
asyc mysql example:
$db = new mysqli;
$db->connect('127.0.0.1', 'root', 'root', 'test');
$db->query("show tables", MYSQLI_ASYNC);
swoole_event_add(swoole_get_mysqli_sock($db), function($__db_sock) {
    global $db;
    $res = $db->reap_async_query();
    var_dump($res->fetch_all(MYSQLI_ASSOC));
    exit;
});

A: You could use a message queue server.

A: also you can use php system call to run another program in background: http://php.net/manual/en/function.system.php


text:
Q: pthread library inclusion at (linking?) step I'm trying to compile a program provided to me.  I noticed in the Makefile it runs the command
g++ -o test [...] -lpthread

I noticed the pthread library file is in /lib/libpthread.so.0 , but when I try to make the target, it gives me this error:
/usr/bin/ld: cannot find -lpthread
collect2: ld returned 1 exit status

how do I fix this?

A: In order to use -lpthread, you need a libpthread.a library archive and this is for static linking. libpthread.so.0 is a shared object which means it is used for dynamic linking. See GCC Link Options


text:
Q: How to iterate through a nested array in a Mongo collection I've been trying to figure this out for hours now. Basically this is my issue:
I am trying to iterate through a nested array. I have a collection called "Categories" in which these is a field called Agents[]. I need to display the list of these Agents. This is my current code:
 return (

        {Categories2.find({name: Session.get("catName")}, {Agents: 1}).fetch().map((category)=> {

          if (category.Agents.length == 0){
            return (
No Agents Exist Yet
);
          }

          tempVarEmail= category.Agents[count].email;
          console.log (tempVarEmail + " " + count);
          count++;

          tempVarId = category.name;

        return(

{tempVarEmail}  x

        )

        })}

)

I am assuming I need to nested map() function or something but I cannot get the syntax correct. This only displays the first Agent in the category because that's exactly what it tells it to.
Any help?


text:
Q: The GET method is not supported for this route. Supported methods: HEAD Hello i am new to laravel but i can't discover why i can't acess to my default path
My route:
      Route::get('/', 'HomeController@home');

My controller:
<?php

 namespace App\Http\Controllers;

 use Illuminate\Http\Request;

 class HomeController extends Controller
 {

 public function home()
 {
    return view('home.home');
 }
}

My route list

I have try with diferent middlewares and also i have change this api.route
i have delete this:
 //Route::middleware('auth:api')->get('/user', function (Request $request) {
  //  return $request->user();
  //});

Please help i am start going crazy.

A: in my case:
php artisan optimize
php artisan optimize:clear

solve the problem

A: It works for me
 php artisan optimize:clear
 php artisan route:clear

A: If you're facing this problem, simply run this command
php artisan optimize

The above command will clear all routes, files and configurations and also go ahead to create new cache for them.

A: Solved my same problem just with command:
php artisan route:clear

A: Try using the following commands:
php artisan cache:clear
php artisan route:cache
php artisan config:cache
php artisan view:clear

A: in my case i solve this issue with run : php artisan cache:clear command 4 times.

*

*more usefull command :

*php artisan cache:clear # for clear your application cache.

*php artisan route:cache # for clear your application route cache.

*php artisan config:cache # you should cache all of your configuration files into a single file

*php artisan view:clear # if you want to
clear view cache

A: the best way for solving this problem is to clear route cache through
php artisan route:clear

I have tried many methods but did not get to the right solution however did not lose the heart and try php artisan route:clear

A: php artisan optimize
php artisan optimize:clear

It works for me


text:
Q: preg_match to remove stray HTML I'm having trouble eliminating some stray portions of HTML that are ending up in an automatically generated excerpt for a WordPress site. For example, at the beginning of an excerpt I'll see:

href="https://stackoverflow.com">Excerpt text starts here...

or at the end of an excerpt:

...excerpt text ends here <a

So it seems what I'm looking for is a method to match and remove any string of non-space characters at the start of the excerpt that end with ">" or any string of non-space characters at the end of the excerpt that start with "<".

A: If the excerpt doesn't contain < and > characters, there are a couple of approaches you can take. One to remove the segments as you describe in your question using preg_replace, the other to use preg_match to find a set of characters between a > and a <. For example:
$excerpts = array('href="https://stackoverflow.com">Excerpt text starts here... ...excerpt text ends here <a',
    'href="https://stackoverflow.com">Excerpt text starts here... ...excerpt text ends here',
    'Excerpt text starts here... ...excerpt text ends here <a',
    'Excerpt text starts here... ...excerpt text ends here'
);

foreach ($excerpts as $excerpt) {
    preg_match('/(?<=^|>)[^<>]+(?=<|$)/', $excerpt, $matches);
    echo $matches[0] . PHP_EOL;
}

foreach ($excerpts as $excerpt) {
    echo preg_replace(array('/.*>/', '/<.*$/'), '', $excerpt) . PHP_EOL;
}

Output:
Excerpt text starts here... ...excerpt text ends here

Demo on 3v4l.org

A: You could use T-Regx, which could make @Nick pattern more readable
echo pattern('(?<=^|>)[^<>]+(?=<|$)')->match($input)->first();


text:
Q: Magento Performance: How to use several subdomains (static1-3) for static assets? is there an easy way to add subdomains to the URLs of my static assets (JS, CSS, images) in Magento? What I am looking for is a way to change an url like this
http://store.com/js/script.js

to this
http://static1.store.com/js/script.js

The number behind 'static' should be rand(1,3).
The reason I want that is of course performance. By spreading assets over several domains browsers load them faster since they are restricted to load not more than 2 files from one domain at a time.
I know there exists a plugin for Wordpress and I would like to do it for Magento.
This whole thing has to happen server side, so before any html is generated.
Thank you for your input!

A: To speed up static content the best way is using a good CDN.
I'm using AWS CloudFront (http://aws.amazon.com/cloudfront/).
Using CloudFront you don't need to worry about http requests in several subdomains, the CDN deals with it for you.


text:
Q: Ajax method is getting a 405 error when I try to consume a WCF Service I have an enabled CORS WCF Service and the other hand, I have a Rails app where I'm trying to make a request via Ajax (I manually ran this at Browser Debug Console):
function GetBookId(){

$.ajax({
   type: "GET",
   url:  "http://localhost:8369/BookService.svc/Book/3",
   contentType: "json",
   dataType: "json",
   xhrFields: {
      withCredentials: false
    },
   headers: "GET",
   //processData: true,
   success: function (data) {
    var jsonData = JSON.stringify(data);
    var objData = $.parseJSON(jsonData);
    var bookId = objData.BookId;
    var isbn = objData.ISBN;
    },
    error: function (xhr) {
        alert(xhr.responseText);
    }
  });
}

The WCF Service is running at port 8369, and my Rails app is at port 3000, so browsers complain about Cross-Domain or Cross-Origin preflight requests with a Error 405. As I said, the WCF Service is enabled to receive GET, POST, PUT and DELETE methods:
...
    <httpProtocol>
      <customHeaders>
        <add name="Access-Control-Allow-Origin" value="*" />
        <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
      </customHeaders>
    </httpProtocol>
...

After debugging or watching the Request Headers, I found when I use the GetBookId() method, Is sending OPTIONS as Request Method instead a GET or POST, so get that

XMLHttpRequest cannot load
  http://localhost:8369/BookService.svc/Book/3. Response for preflight
  has invalid HTTP status code 405

In Firefox Developer Tools I edited the Request Header as a GET Method and send it again. The Response was a 200. So I guess that problem is that. The jQuery ajax method is sending a wrong Method, How can I send it properly with this method?


text:
Q: Azure Devops API - Can't find a way to get permission groups/membership using API I am looking for a way to use the Azure DevOps API to get membership of permission groups.  The data I am looking for is in the following location on the front end:

I had the same requirement to get team membership within Azure DevOps and was able to do so using the following URI:
https://dev.azure.com/{organization}/_apis/projects/hrs/teams/{teamname}/members?api-version=6.0
I could not find a similar URI to get permission groups and need a way to pull this information using the API.
I've tried many of the API endpoints on the official api documentation (below) focusing on any that seem like they may pull security group related information.   In all cases I came up short either because the endpoint did not provide me with what I was looking for, or the documentation for an endpoint wasn't clear on how parameters need to be structured for more advanced use cases.
https://learn.microsoft.com/en-us/rest/api/azure/devops/graph/groups/get?view=azure-devops-rest-7.0&tabs=HTTP
I also tried asking this question to ChatGPT however the endpoints the chatbot provided me with did not work either.

A: I found a way to get what I am looking for, but I am not a big fan of the approach.
You can use the graph API to list all permission groups
once you have the permission groups, you can write a script to filter for the group object within the API response you want to get the members of.
The group object has the appropriate API endpoint to hit to get the member objects within the _links.memberships property.
Call the API with the memberships link from above.  It will return an array of descriptors which can be used in further API calls.
For each descriptor, hit the appropriate API endpoint to resolve the object for that descriptor.  If the descriptor starts with aad then it is a user and you can use the user get api.  If the descriptor starts with aadgp then it is a group and you use the group get api.
This strategy is rather complicated and requires an API call for each member of the group.  I'd hope there is a better solution.


text:
Q: How to filter queryset with custom function I have the following models and I am trying to apply some filtering.
Basically I have this player model that can have multiple Experiences, and I want to send on my query params xp that will receive a value in years, and my queryset should only retrieve the players with at least that amount of years of experience in total.
The calc_player_experience method reads throw the players experience and calculates de amount of experience the player has and returns true or false if it meets the xp received on the query params.
How do I apply a function to model.filter()? is that a thing?
models.py

class Player(BaseModel):
    name = models.CharField(_("name"), max_length=255, blank=True)

class Experience(BaseModel):
    player = models.ForeignKey(
        "players.Player", on_delete=models.CASCADE
    )
    team = models.CharField(_("team"), max_length=255)
    start_date = models.DateField(_("start_date"), null=True, blank=True)
    end_date = models.DateField(_("end_date"), null=True, blank=True)

views.py

class PlayersViewSet(viewsets.ModelViewSet):
    serializer_class = PlayerSerializer
    queryset = Player.objects.all()

    def get_queryset(self):
        """Filters the players to retrieve only those not archived and approved"""
        queryset = Player.objects.filter(is_approved=True, is_active=True)
        return apply_filters(self, queryset)

def apply_filters(obj, queryset):
    """Apply filters to given queryset"""

    xp = dict(obj.request.GET).get("xp", [])
    if xp:
        queryset = queryset.filter(lambda player: obj.calc_player_experience(player,xp[0]))

A: In your views.py you need to return the queryset from the apply_filters function. Make sure you have a queryset returned even if it is empty.

def apply_filters(obj, queryset):
    """Apply filters to given queryset"""

    xp = dict(obj.request.GET).get("xp", [])
    if xp:
        queryset = queryset.filter(lambda player: obj.calc_player_experience(player,xp[0]))
    return queryset


text:
Q: how to perform hyphenation on a UILabel sensitive to a language different from the one set in iOS preferences? I couldn't find any hint to this quite specific question: How can I set the grammar rule by which hyphenation on a UILabel is performed?
You see, my app is localised for english and german language and contains german street names (which obviously will not be translated to english). When the language of the device is set to german, the hyphenation works fine.
But on a device with language set to english, the hyphenation seems to struggle with the german street names (meaning: hyphenation is happening, but in a grammatically wrong way). I assume that's because it is derived from the language set in iOS preferences.
here's how I perform the hyphenation on that label:
func updateStreetNameLabel(streetName: String) {

    let paragraphStyle: NSMutableParagraphStyle = NSMutableParagraphStyle()
    paragraphStyle.hyphenationFactor = 1.0
    paragraphStyle.alignment = .Center

    let streetNameWithHyphens: NSMutableAttributedString = NSMutableAttributedString(string: streetName, attributes: [NSParagraphStyleAttributeName : paragraphStyle])

    streetNameLabel.attributedText = streetNameWithHyphens

}

I would have thought there was a specific attribute to do this, but I was not able to find out how to go about it.
Thanks for any help with this tiny but tricky problem!
S.

A: You can set the user's language preference from within your app, although it's not recommended. A better, but a lot more painful, solution is to add the German place names, with English hyphenation rules, to the user's dictionary, if that's even possible. But the best solution is probably to turn hyphenation off when the app is running in English.


text:
Q: ¿Cómo puedo usar un ViewBag dentro de una vista parcial? Estoy tratando es utilizar el ViewBag que carga la vista index en una vista parcial, pero siempre llega null, ¿alguna sugerencia de cómo podría utilizarlo?
@{
    List<TRAZA.Models.NombreProductosMasterViewModel> producto = ViewBag.EspeciePresentacion;
}


text:
Q: typescript, how to reference the unexported OAuth2Client? google-api-nodejs-client I am trying to follow https://developers.google.com/sheets/api/quickstart/nodejs tutorial
I am using typescript and I like the type annotation and auto-complition features it provides and I would like to re-write the example in typescript and async rather than callbacks.
Sadly I am stuck, OAuth2Client.
in my code I creating an oauth client inside a function like this:
async function setupClient() {
  const content: string = await fs.readFile("credentials.json", "utf8");
  const credentials = JSON.parse(content);
  // eslint-disable-next-line camelcase
  const { client_secret, client_id, redirect_uris } = credentials.installed;
  const oAuth2Client: o2 = new google.auth.OAuth2(
    client_id,
    client_secret,
    redirect_uris[0]
  );
  type OAuth2Client = typeof oAuth2Client;
  return oAuth2Client;
}

And I would like to delegate that client to two other setup functions:
function setupAuthUrl(oAuth2Client, scopes) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: "offline",
    scope: scopes,
  });
  return authUrl;
}
function setupToken(oAuth2Client, code) {
  //code
}

But I am struggling to annotate oauth2client type as it is not directly exposed by anything?
One would guess that it is exposed under the 'oauth2_v2' namespace? but doesn't seem to be it.
I have been looking for a way to reference this type prior to instantiation, preferably via importing, sadly, when installing this libary via npm install googleapis it doesn't provide a dependency to niether of these google-auth-library, googleapis-common where it is exported and exposed for importing. eslint errors unless it adds the dependency and I struggle to see why It is required as the type should be accessable for code completion with ease.
As for type aliasing:
type OAuth2Client = typeof GoogleApis.prototype.auth.OAuth2.prototype;

This is the only option I could figure out that doesn't throw an error/warning(object as namespace) for aliasing. this is both a long line and very weird one at that too coming from other OO languages

*

*TLDR: What's the prefered way to access OAuth2Client and maybe other types for code completion in typescript?

A: As of Jun 19 a merge request adding this feature has been approved.
https://github.com/googleapis/google-api-nodejs-client/issues/2208
import { google, Auth } from 'googleapis';
const oauthClient: Auth.OAuth2Client = new google.auth.OAuth2();

Thanks for angelxmoreno for the example


text:
Q: How do i generate a 4-digit pin with no duplicating number I'm new to android programming and i want to make a 4 Digit PIN generator without any repeats. How do I do it?? I don't know how to loop that very well yet. Thank you!!
I already tried Random but it gives me numbers that repeat.
int randomPIN = (int)(Math.random()*9000)+1000;

String pin = String.valueOf(randomPIN);
dummy.setText(pin);

I'm looking for an outcome of 1354, 4682, 3645 but the results are mostly 3344, 6577, 1988

A: Create a list of the digits, shuffle it, and return the first four digits. Here's one way of doing it as a static method:
/* No need for a new list each time */
private static final List<Integer> digits =
    new ArrayList<>(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 9));

/**
 * Returns a PIN string that contains four distinct digits.
 */
public static String nextPin() {
    Collections.shuffle(digits);
    final StringBuilder sb = new StringBuilder(4);
    for (Integer digit : digits.subList(0, 4)) {
        sb.append(digit);
    }
    return sb.toString();
}

Obviously, if you wanted the digits as an array of numbers instead of a string, you'd process the sublist differently than I've shown here.
If you just return the sublist itself, be aware that it will change each time you

A: //create list ArrayList numbers = new ArrayList();
Random randomGenerator=new Random();while (numbers.size() < 4) {int random = randomGenerator .nextInt(4); if (!numbers.contains(random)) { numbers.add(random);}}

A: Somewhat of an academic exercise - here's one requiring Java 8:
    // flag to control if you want number sequence to be the same each run
    boolean repeatable = true;

    // seed for randomness - for permutation of list (not the integers)
    Random rnd = new Random((repeatable ? 3 : System.currentTimeMillis()));

    // generate randomized sequence as a List
    List<Integer> myNums;
    Collections.shuffle((myNums = IntStream.rangeClosed(1000, 9999).boxed().collect(Collectors.toList())), rnd);

    // Work with list...
    for (Integer somePin : myNums) {
        Log.i("", "Next PIN: "+somePin);
    }

A: You're gonna have to add the random ints step after step and check for duplicates.
Random random = new Random();
int rdmInt = random.nextInt(9);
String pin = "";
while (pin.length() < 4) {
    rdmInt = random.nextInt(9);
    String addition = String.valueOf(rdmInt);
    if (pin.contains(addition)) continue;
    pin += addition;
}


text:
Q: Is it thermal paste conducting heat from integrated GPU? Why is it different from CPU's thermal paste? I have an Asus eee pc 1015ped. Upon disassembly I've found out the heat sink cools 2 chips. The one on the left is obviously the CPU and the one on the right is the integrated GPU I assume.

And the detached heat sink looks like this:

The left square is thermal paste for the CPU. The right (bigger) one bothers me. Is it thermal paste too? If so, why is it different? Also, why doesn't the GPU have this shiny mirror thing?
I want to change the paste for the CPU. Will the same paste do for the GPU (if my assumptions are correct at all)?

A: There is no grease. As pjc50 has pointed out, an integrated GPU is part of the die along with the CPU.
The two packages are different approaches to BGA packaging. This document gives examples of your packages on page 14-4. The left package is an HL-PBGA die-up package, and the "shiny mirror thing" is actually the bottom of the die. The other package is an H-PBGA die-down package - if you were to dismount the package you'd see a well in the underside with the chip inside.
In both cases, thermal contact with the heat sink is made by thermal conductive pads
rather than thermal grease. Thermal pads are not quite as good (thermally) as a good grease, but they can be much thicker, and they have much more tolerance for differences in separation between the IC and heat sink. This allows adequate performance at much lower cost than would be needed to handle multiple chips, each with a different surface height. And you can see that two different pads (with different nominal thicknesses) have been used for the two chips. Note also that the left-hand pad has compressed around the die, evidence of good mechanical contact and pressure.

A: "Integrated" GPUs are on the same die as the processor itself. So the left heatsink works for both. The "shiny mirror" is a heat spreader, made of ceramic or possibly just regular epoxy that has been polished flat.
The thing on the right looks more like an eMMC Flash device to me. It has the normal slightly rough epoxy surface normally used for chip packaging. The pad on top of it looks like a thermally-transmissive sticky pad.


text:
Q: What does index mean in python? Perhaps, it sounds like a stupid question. However, I have to learn what index is because I want to learn python.
For example, in a website, I saw this:

The method find() determines if string str occurs in string, or in a
  substring of string if starting index beg and ending index end are
  given.

http://www.tutorialspoint.com/python/string_find.htm
What does "index" mean here? I would like you to explain it to me like you are explaining something to a child. Because my comprehension is somewhat bad. Anyway. You can even provide examples to explain what index is.
Many thanks.

A: "index" is meant as "position".
Let's use find() as an example: find() will look for a string in another string. It will start its search at the beginning index called beg and will end its search at the end index called end. So it will only search between beg and end. Usually (by default) beg is 0 (which means it is the first character in the string) and end is the length of the string minus one (which means it is the very last character in the string). So an index is just a position (not only in a string, e.g. also in an array).

A: Consider this string "Hello". If you wanted to point out to some of it's characters like e you would need an index, which is a position number. Indices in python start counting from zero. So the index of letter e in "Hello" is 1.
Try to run this line of code:
print "Hello".find("e");

It should return you 1.
You can further play with it an run it again what it does. Try to replace "e" with "H", next try something that isn't in "Hello".

A: If a street with houses is an analogy for an array with elements, then house number is analogy for index. However, Python uses numbers from zero.
The built in sequence types in Python (ver. 3) are strings (sequences of unicode characters), bytes (sequences of small integers from zero to 255, i.e. of byte values), tuples (sequences of whatever elements), and lists (sequences of whatever elements). All of them are implemented via arrays; this way they can be indexed as is usual for arrays in any (other) programming language.
If a is such an array (i.e. one of the above sequence types), then a[0] refers to the content of the first house in the street, a[1] to the second house, etc. Some of the sequences can be modified (here only the lists), therefore they are called mutable. Some of the sequences cannot be modified (strings, bytes, tuples), therefore they are called immutable.
For mutable sequence type objects, the elements can be changed via assignment like lst[0] = 3, the elements of the immutable sequences can only be read and the value used, like print(s[3]).
For lists and tuples the elements are not stored directly inside the array. Only the references to the target objects are stored inside. The target object is accessed indirectly (one hop along the reference). Think in terms that you go to the indexed house, and the person inside tells you where is the real content (in another house, not in this street). In such case, even the element from the (immutable) tuple like t[5]--i.e. the reference--can be used to change the target object content... if the target object is mutable.

A: An index, in your example, refers to a position within an ordered list. Python strings can be thought of as lists of characters; each character is given an index from zero (at the beginning) to the length minus one (at the end).
For the string "Python", the indexes break down like this:
P y t h o n
0 1 2 3 4 5

In addition, Python supports negative indexes, in which case it counts from the end. So the last character can be indexed with -1, the second to last with -2, etc.:
 P  y  t  h  o  n
-6 -5 -4 -3 -2 -1

Most of the time, you can freely mix positive and negative indexes. So for example, if you want to use find only from the second to second-to-last characters, you can do:
"Python".find("y", beg=1, end=-2)

A: In python, the indexing start from 0. So basically lst[0] means first element in list (lst), lst[1] means second element and so on.... Also we can access last element as lst[-1], lst[-2] is second from the last and so on...In other programming language like R, indexing starts from 1 instead of 0, so we need to be careful with that.


text:
Q: Storing BigInt values in AngularJs In SQlServer I have these values stored in the ID -6410551811284209102
2248193693505952772
1897495303850505563
But while fetching it truncate the value in AngularJS, Like
for 1897495303850505563 it convert as 1897495303850505500
for 2248193693505952772 it convert as 2248193693505952800.
This is because I am storing these values in either number or object. But these are BigInt in SqlServer.
Anybody has any clue for how to store these values in bigInt.

A: Maybe you can use this javascript library for AngularJS https://www.npmjs.com/package/big-integer

A: Can you convert/cast the big int to a string?


text:
Q: Max no of users in SSRS I was working to set up SSRS as a Self Service tool for all the users in an organisation.
Is it possible to have 5000 unique users for SSRS ?
If so, can we set up row level security for each employee ?

A: Yes you can provide row level security. By providing the individual user permissions to the database and restrict the data returned for your report.
There is no rule as to how many users you can have (I believe it is set to 32767). However depending on what they are doing, the simultaneous user connection number can get limited by your hardware specifications so to not overload your server.


text:
Q: Run Sparc v9 64-bit executable on bare metal QEMU I tried this recipe : How to run a bare metal ELF file on QEMU? to run bare metal AArch64 executables on QEMU (and it worked). I'd like to do the same for 64-bit SPARCv9 executables (preferably starting from C/C++, not assembly) - I tried the examples in this link : Run SPARC assembly in QEMU, but that one runs in user-mode Linux, does syscall translation to the host system, etc.
Example :
int main(int argc, char **argv) {
  volatile int a = 11, b = 13, c = 7, d = 5;
  return a + b - c - d;
}

How do I run this example as a bare metal Sparcv9 executable AND connect gdb to it ?
Any of the available 64-bit boards in qemu/hw/sparc64/ would be fine. Thank you.

A: I believe what you are after is the qemu-system-sparc64 command. Just something to note is that the general form for bare-metal emulation is qemu-system-{ARCH} and the general command for user mode emulation is qemu-{ARCH}.
An example from the qemu docs.
qemu-system-sparc64 \
  -drive file=hd.qcow2,if=none,id=hd \
  -device virtio-blk-pci,bus=pciB,drive=hd,bootindex=0

As for building your own c/c++ bare-metal executables, that's a relatively broad topic, but I'd recommend starting with GCC and newlib-nano (for libc).

A: Basically it's similar to running an AArch64 bare-metal ELF:
qemu-system-sparc64 -nographic -kernel test64.elf -serial mon:stdio -s

or
qemu-system-sparc64 -nographic -bios test64.elf -serial mon:stdio -s

Both -kernel and -bios options in sun4u emulation may load ELF files, the difference is that in the first example the hardware is initialized by OpenBIOS, and in the second example you are running in a PROM right after the cold start.
The -s option will make QEMU listen for an incoming connection from gdb on TCP port 1234.
In the second example you probably also would like to add the -S option in oder to make QEMU not to start the execution of your ELF file until you tell it to from gdb.
In gdb you do the following:
(gdb) set architecture sparc:v9
The target architecture is assumed to be sparc:v9
(gdb)  target remote localhost:1234


text:
Q: Mysql query issue(how to eliminate records having null value for old_device_id column) I have two tables
device(id, name)
device_map(email, old_device_id)

device_map is list of users and old devices. Some users may not have old devices.
old_device_id is unique and refers to id from device table. But it can also be null.
Now I want to have select query on table join.
select device.email, device.old_device_id, device.name
from join of device.id and device_map.old_device_id sort by device.name

Some rows in device_map which has old_device_id null are not selected.
SELECT dmap.email, dmap.old_device_id, d.name
FROM device_map dmap
JOIN device d ON d.id = dmap.old_device_id ORDER BY d.name

A: Here is the query:
SELECT dm.email, dm.old_device_id, d.name
FROM device_map dm
LEFT JOIN device d ON d.id = dm.old_device_id ORDER BY d.name

INNER JOIN between device_map and device tables will automatically eliminate records with null value for old_device_id.
LEFT JOIN will include null records as well.


text:
Q: android com.android.dialer package is missing on a 4.2 device I was trying to trigger an ACTION_DIAL intent but then the "queryIntentActivities" didn't find any dialer app installed, however it is supposed to be installed by default or am I wrong ? The device in question is not an official one but a custom one, for professional usage.
Is it possible to get the APK related to this package ? I only found the com.google.android.dialer but it's not the default package


text:
Q: Interpolation of geocoordinates I'd like to do the equivalent of linear interpolation in geo space.
e.g.
in Cartesian 2D space I do
[x,y] = [x0,y0]+([x1,y1]-[x0,y0])*d

with d={0..1.0}

to calculate any point between [x0,y0] and [x1,y1]. How do I proceed in geo coordinates with  latitude,longitude ?
Thanx

A: It seems that Slerp is what you need.


text:
Q: How can I handle "-10005, 'IPC timeout'" error during python connection to MetaTrader5? I have tried to write this code to initialize MetaTrader5 from python:
import MetaTrader5 as mt5

# establish connection to the MetaTrader 5 terminal
if not mt5.initialize(login=999999, server="myserver-Demo",password="abcdefg"):
    print("failed to connect at account #{}, error code: {}".format(account, mt5.last_error()))
    mt5.shutdown()

But this code returns:
failed to connect at account #999999, error code: (-10005, 'IPC timeout')

What should I do?


text:
Q: how can we categorize m-complete languages of RE (recursive enumerable, re-complete)? is there any hierarchy for many-one complete languages of re (re-complete languages)? how can we propose a categorization for these languages? depending on what measures?

A: Under many-one reductions by arbitrary total computable functions, HALT is the prototypical re-complete problem. A common technique for showing that some problem is undecidable (though not usually expressed in these terms) is to show that it is re-hard by reduction from HALT.
Using a weaker class of allowed reductions may lead to fewer problems being complete, but HALT is still re-complete even under linear-time many-one reductions.
For some reason, this terminology is much less used (to the point of not being used at all) in computability than in complexity.


text:
Q: Почему нельзя объявить массив указателей? Почему так можно:
int a = 1, b = 2, c = 3;
int A[] = {a, b, c},
    B[] = {c, b, a};

а так нельзя:
int a = 1, b = 2, c = 3;
int* A[] = {&a, &b, &c},
     B[] = {&c, &b, &a};

И ещё: почему нельзя объявить массив ссылок?

A: Перепишите чуть иначе:
int *A[] = {&a, &b, &c},
    B[]  = {&c, &b, &a};

И стало ясно, почему. Знак * относится только к первому объявлению.

A: У вас ошибка возникает когда вы объявляете массив B типа int , а не указатель на тип int. Первая звездочка относится к первому объявлению массива A, а ко второму массиву она не имеет никакого отношения, поэтому ее надо указать второй раз перед объявлением массива B вот так:
int main(){
    int a = 1, b = 2, c = 3;
    int * A[] = {&a, &b, &c}, * B[] = {&a, &b, &c};

    return 0;
}

A:
И почему нельзя объявить массив ссылок?

С разрешением "массивов ссылок" в рамках языка С++ появилась бы масса концептуальных проблем. В языке С++ ссылочные типы не являются объектными типами и формально не занимают памяти (т.е. языком не специфицируется, занимают ли ссылки память). По этой причине, в частности, в языке не существует указателей на ссылки и невозможно узнать "размер" ссылки через sizeof.
А отсутствие указателей на ссылки тут же само по себе "блокирует" возможность создания массивов ссылок, ибо в С++ (как и в С) вся основная функциональность встроенных массивов фундаментально завязана на возможность array-to-pointer conversion, т.е. на возможность формирования указателей на элементы массива и выполнения над ними адресной арифметики.


text:
Q: Possible to skip inlined, named modules with r.js build? In my application, I have a named module defined inline in index.html:
<script>
    define('config', {
        mode: '...',
        environment: '...',
        apiUrl: '...',
        rootPath: '...',
        baseImageUrl: '...'
    });
</script>

I need to define this in my web page because I pull some stuff in using environment variables. So, in my modules, I can then include 'config':
define(['config', 'jquery'], function(config, $) { ... });

When I run a RequireJS build using Grunt (with grunt-require, which uses r.js), it's complaining that it's not finding config.js. My build configuration looks like this:
{
    baseUrl: 'js',
    main: 'app/Main',
    dir: 'js/build',
    out: null,
    modules: { ... },
    paths: { ... },
    shim: { ... }
}

When I build, I get:
Error: Error: ENOENT, no such file or directory '/projects/projectname/js/build/config.js

How can I allow for use of named, inline-defined modules in conjunction with an r.js build?

A: Setting
paths: {
   config : 'empty:'
}

in your build configuration file should exclude this module out of optimization process and, as a result, stop raising this error.
But this is a bit tricky way, because this option is commonly used to exclude third-party dependencies (for example, when developing some js library based on Backbone, it would be better to separate your lib from Backbone)


text:
Q: Send JSON and FormData (Angular to Spring) Angular
register(usuario:any, id: File): Observable<any>{

 let formData = new FormData();

 formData.append("user", JSON.stringify({username:'Userr'}));
 formData.append("file", id);

 return this.http.post(AUTH_API + 'signup', formData);

CODE
enter image description here
SPRING
@PostMapping(value = "/signup")
    public ResponseEntity<?> registerUser( @RequestParam SignupRequest user,
            @RequestParam("file") MultipartFile archivo) {

        System.out.println(archivo.getSize());
        System.out.println(user.getUsername());
}

ERROR
2021-01-02 16:50:55.397  WARN 15076 --- [nio-8080-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.method.annotation.MethodArgumentConversionNotSupportedException:
Failed to convert value of type 'java.lang.String' to required type 'SignupRequest';
nested exception is java.lang.IllegalStateException: Cannot convert value of type 'java.lang.String' to required type 'com.AreMyNews.Request.SignupRequest': no matching editors or conversion strategy found]

A: Use @ModelAttribute instead of @RequestParam for SignupRequest user.
PostMapping(value = "/signup")
    public ResponseEntity<?> registerUser( @ModelAttribute SignupRequest user,
            @RequestParam("file") MultipartFile archivo) {

        System.out.println(archivo.getSize());
        System.out.println(user.getUsername());
}


text:
Q: xtable for not supported functions (with R) what am I supposed to do, if xtable doesn't know a special command. For example assume the estimation of a tobit model, like this:
require(AER)
require(xtable)
attach(cars)
tob<-tobit(dist~speed)
summary(tob)
xtable(summary(tob))
detach(cars)
the output of summary is pretty similar compared to an output of a linear model... What can I do, to make xtable understand, that I want to have the coefficients in a Latex table? Samme with other functions like summary(zeroinfl(<model>)) from the pakage pscl?
What would you guys recommend to do?

A: The short answer is "convert it to a class xtable understands". For example,
tmp <- summary(tob)
str(tmp) ## a list
names(tmp) ## the contents of tmp
str(tmp$coefficients) ## the class of the coeffients table ("coeftest")
is.matrix(tmp$coefficients) # TRUE
class(tmp$coefficients) <- "matrix"
xtable(tmp$coefficients)

A: Here is another function that you can use. It is a modified version of the xtable defined for lm.
i.e I have just modified the function xtable.summary.lm for the tobit case.
It will also be aligned to other xtable functionalities
xtable.summary.tobit <-
function (x, caption = NULL, label = NULL, align = NULL, digits = NULL,
display = NULL, ...)
{
 x <- data.frame(unclass(x$coef), check.names = FALSE)
 class(x) <- c("xtable", "data.frame")
 caption(x) <- caption
 label(x) <- label
 align(x) <- switch(1 + is.null(align), align, c("r", "r",
     "r", "r", "r"))
 digits(x) <- switch(1 + is.null(digits), digits, c(0, 4,
     4, 2, 4))
 display(x) <- switch(1 + is.null(display), display, c("s",
     "f", "f", "f", "f"))
 return(x)
}
## Now this should give you the desired result
xtable(summary(tob))

Hope it helps in getting the desired result


text:
Q: Copy URL after "/" and paste on button This script is already working but I want to know if it's possible to copy only the "parameter" after the "/" (slash).
My marketing campaigns adds diferents parameters after the "/" do know where the user came from, example: XV-MEL-OM-REVHL-X-X-POP-X-X.
This FORM is one POPUP, and i need to copy on a "hidden" input the parameter after the "/" to know where the user came from.
Script:
    <script type="text/javascript">
    function Copy()
    {
        var Url = document.getElementById("paste-box");
        Url.value = window.location.href;
        Url.focus();
        Url.select();
        document.execCommand("Copy");
    }

HTML:
    <form action="https://ws.inversapub.com/subscribe" method="POST" target="hiddenFrame">

  <input name="emailAddress" type="email" required="" oninput="this.setCustomValidity('')" oninvalid="this.setCustomValidity('Preencha um endereço de e-mail válido.')" placeholder="Coloque seu e-mail aqui" class="input-email-popup">

   <input type="submit" value="QUERO DOBRAR MEU DINHEIRO AINDA ESTE ANO" onclick="Copy();" class="btn-submit-popup om-trigger-conversion">
  <input type="hidden" name="sourceId" id="paste-box" value="XV-MEL-OM-REVHL-X-X-POP-X-X">

  <input name="listCode" type="hidden" value="inv_hotlist_revhl"/>

  <input name="redirect" type="hidden"  value="#" />

  <input name="email_page" type="hidden" value="inv_welcome_revhl"/>

</form>

My URL is:  http://lp.inversapub.com/teste-lp-optin/
It's copying only the /teste-lp-option/
BTW, I'ts possible to add the parameter "XV-MEL-OM-REVHL-X-X-POP-X-X" if thats nothing after the "/"?

Hasta Dhana solution is working! But i need to add the parameters "XV-MEL-OM-REVHL-X-X-POP-X-X" if thats nothing after the "/"

A: I think that you are looking for the location.pathname property of the Location API.
Code for your example:
function Copy()
{
  var Url = document.getElementById("paste-box");
  Url.value = window.location.pathname;
  Url.focus();
  Url.select();
  document.execCommand("Copy");
}

EDIT:
To add the default parameter you can test the location with a regular expression like this:
function Copy()
{
  var Url = document.getElementById("paste-box");
  Url.value = window.location.pathname + (/\/$/.test(location.pathname) ? "XV-MEL-OM-REVHL-X-X-POP-X-X" : "");
  Url.focus();
  Url.select();
  document.execCommand("Copy");
}

A: You may use window.location.pathname instead of window.location.href to take only the path part of the URL. If you need everything after the / (like GET parameters and hash) you can take the URL and remove the origin part:
window.location.href // http://example.com/path?get=value#bang
window.location.origin // http://example.com
window.location.href.slice(window.location.origin.length) // /path?get=value#bang

If you want to insert the whole URL but copy only the part of it you can look at selectionStart and selectionEnd properties. Here is a nice comment on it: https://stackoverflow.com/a/3085656/3641734.

A: You could use the lastIndexOf() function to locate the last portion of the / character in your URL :
function Copy()
{
    var Url = document.getElementById("paste-box");
    Url.value = window.location.href.substr(window.location.href.lastIndexOf('/') + 1);
    Url.focus();
    Url.select();
    document.execCommand("Copy");
}


text:
Q: Inno Setup "Source file C:\Windows\System32\vcruntime140_1.dll does not exist" error I'm trying to install some Visual Studio dlls on the guest machine with Inno Setup. Here is the [Files] section of my script:
[Files]
Source: ...
...
Source: "C:\Windows\System32\msvcp140.dll"; DestDir: "{app}"
Source: "C:\Windows\System32\vcruntime140.dll"; DestDir: "{app}"
Source: "C:\Windows\System32\vcruntime140_1.dll"; DestDir: "{app}"

It gives me an error in the last line, saying that it can't find the source file, although it is there. Does it have something to do with the _ having a special effect with Inno Setup?

A: On my 64-bit system, the vcruntime140_1.dll is in the real 64-bit C:\Windows\System32. Inno Setup compiler is a 32-bit application. Due to WOW64 file system redirection, when a 32-bit application tries to access the C:\Windows\System32, it gets redirected to C:\Windows\SysWOW64, where 32-bit system files are. There's no vcruntime140_1.dll.
This also shows you the weakness of your approach, as others have commented. You likely didn't even realize that there are multiple versions of the DLL. If you use the official Visual C++ Redistributable installer, it will take care of installing the right versions to the right locations. While you would not. You should not mess with System32 folder.
Some examples:

*

*How to install Microsoft VC++ redistributables silently in Inno Setup?

*How to make vcredist_x86 reinstall only if not yet installed?


text:
Q: Получить массив с ID дочерних категорий Есть список категорий и их подкатегорий:
Компьютеры
- Ноутбуки
-- БУ ноуты
- Неттопы
-- БУ Неттопы
Комплектующие для компьютеров
- Процессоры
- Материнские платы

Мне необходимо получить id всех подкатегорий в виде массива из категории "Компьютеры".
Входные данные:
$rsCategories = Array
(
    [0] => Array
        (
            [id] => 1
            [parent_id] => 0
            [name] => Компьютеры
        )

    [1] => Array
        (
            [id] => 2
            [parent_id] => 1
            [name] => Ноутбуки
        )

    [2] => Array
        (
            [id] => 7
            [parent_id] => 2
            [name] => БУ ноутбуки
        )

    [3] => Array
        (
            [id] => 3
            [parent_id] => 1
            [name] => Неттопы
        )

    [4] => Array
        (
            [id] => 8
            [parent_id] => 3
            [name] => БУ Неттопы
        )

    [5] => Array
        (
            [id] => 4
            [parent_id] => 0
            [position] => 0
            [name] => Комплектующие для компьютеров
        )

    [6] => Array
        (
            [id] => 5
            [parent_id] => 4
            [name] => Процессоры
        )

    [7] => Array
        (
            [id] => 6
            [parent_id] => 4
            [name] => Материнские платы
        )

)

Сама функция:
function getIdAllChildrenByParent($catId, $rsCategories) {

    // создаём массив для хранения айдишников дочерних категорий
    $arrIdChildCats = array();

    // сохраняем айдишники дочерних категорий в массив
    foreach($rsCategories as $value) {
        if($value['parent_id'] == $catId) {
            $arrIdChildCats[] = $value['id'];
        }
    }

    // найденные айдишники записываем в строку и проходимся
    // по каждому из них нашей функцией, чтобы найти ещё дочерние категории
    foreach($arrIdChildCats as $value) {
        $result .= "{$value}, ";
        $result .= getIdAllChildrenByParent($value, $rsCategories);
    }

    return $result;

}

Вызов функции:
// передаём айди запрошенной категории и массив содержаший все категории
getIdAllChildrenByParent($catId, $rsCategories);

Получаю результат в виде строки "2, 7, 3, 8, ".
Мозгов хватило решить задачу только так, а как получить результат в виде такого массива?
$result = Array
(
    [0] => 2
    [1] => 3
    [2] => 7
    [3] => 8
)

A: Вместо того, чтобы собирать все в одну строку собирайте в массив и возвращайте его
// найденные айдишники записываем в строку и проходимся
// по каждому из них нашей функцией, чтобы найти ещё дочерние категории
$result = array();
foreach($arrIdChildCats as $value) {
    $result[] = $value;
    $result = array_merge(
        $result,
        getIdAllChildrenByParent($value, $rsCategories)
    );
}

return $result;


text:
Q: Reflection, contravariance and polymorphism I have a base class (abstract) with multiple implementations, and some of them contain collection properties of other implementations - like so:
class BigThing : BaseThing
{
    /* other properties omitted for brevity */
    List<SquareThing> Squares { get; set; }
    List<LittleThing> SmallThings { get; set;}
    /* etc. */
}

Now sometimes I get a BigThing and I need to map it to another BigThing, along with all of its collections of BaseThings. However, when this happens, I need to be able to tell if a BaseThing in a collection from the source BigThing is a new BaseThing, and thus should be Add()-ed to the destination BigThing's collection, or if it's an existing BaseThing that should be mapped to one of the BaseThings that already exist in the destination collection. Each implementation of BaseThing has a different set of matching criteria on which it should be evaluated for new-ness. I have the following generic extension method to evaluate this:
static void UpdateOrCreateThing<T>(this T candidate, ICollection<T> destinationEntities) where T : BaseThing
{
    var thingToUpdate = destinationEntites.FirstOrDefault(candidate.ThingMatchingCriteria);
    if (thingToUpdate == null) /* Create new thing and add to destinationEntities */
    else /* Map thing */
}

Which works fine. However I think I am getting lost with the method that deals in BigThings. I want to make this method generic because there are a few different kinds of BigThings, and I don't want to have to write methods for each, and if I add collection properties I don't want to have to change my methods. I have written the following generic method that makes use of reflection, but it is not
void MapThing(T sourceThing, T destinationThing) where T : BaseThing
{
    //Take care of first-level properties
    Mapper.Map(sourceThing, destinationThing);

    //Now find all properties which are collections
    var collectionPropertyInfo = typeof(T).GetProperties().Where(p => typeof(ICollection).IsAssignableFrom(p.PropertyType));

    //Get property values for source and destination
    var sourceProperties = collectionPropertyInfo.Select(p => p.GetValue(sourceThing));
    var destinationProperties = collectionPropertyInfo.Select(p => p.GetValue(destinationThing));

    //Now loop through collection properties and call extension method on each item
    for (int i = 0; i < collectionPropertyInfo.Count; i++)
    {
        //These casts make me suspicious, although they do work and the values are retained
        var thisSourcePropertyCollection = sourceProperties[i] as ICollection;
        var sourcePropertyCollectionAsThings = thisSourcePropertyCollection.Cast<BaseThing>();
        //Repeat for destination properties

        var thisDestinationPropertyCollection = destinationProperties[i] as ICollection;
        var destinationPropertyCollectionAsThings = thisDestinationPropertyCollection.Cast<BaseThing>();

        foreach (BaseThing thing in sourcePropertyCollectionAsThings)
        {
            thing.UpdateOrCreateThing(destinationPropertyCollectionAsThings);
        }
    }
}

This compiles and runs, and the extension method runs successfully (matching and mapping as expected), but the collection property values in destinationThing remain unchanged. I suspect I have lost the reference to the original destinationThing properties with all the casting and assigning to other variables and so on. Is my approach here fundamentally flawed? Am I missing a more obvious solution? Or is there some simple bug in my code that's leading to the incorrect behavior?

A: Without thinking too much, I'd say you have fallen to a inheritance abuse trap, and now trying to save yourself, you might want to consider how can you solve your problem while ditching the existing design which leads you to do such things at the first place. I know, this is painful, but it's an investment in future :-)
That said,
   var destinationPropertyCollectionAsThings =
       thisDestinationPropertyCollection.Cast<BaseThing>();

    foreach (BaseThing thing in sourcePropertyCollectionAsThings)
    {
        thing.UpdateOrCreateThing(destinationPropertyCollectionAsThings);
    }

You are losing your ICollection when you use Linq Cast operator that creates the new IEnumerable<BaseThing>. You can't use contravariance either, because ICollectiondoes not support it. If it would, you'd get away with as ICollection<BaseThing> which would be nice.
Instead, you have to build the generic method call dynamically, and invoke it. The simplest way is probably using dynamic keyword, and let the runtime figure out, as such:
thing.UpdateOrCreateThing((dynamic)thisDestinationPropertyCollection);


text: Q: Bandwidth in R gstat spatio-temporal variogram kriging I am using gstat to perform two-dimensional interpolations. Now, I want to perform a three-dimensional interpolation (X,Y, elevation) using the spatio-temporal package of gstat. In order to do that, I was searching for a bandwidth option, which restricts the pairing of the sampling locations within a maximum distance perpendicular to the plane of interest (e.g., allow choosing pairs with depth difference less than a threshold value to perform horizontal variogram), without any success. Is there any available option to do that, or a trick, or something?


text:
Q: Safari/iOS basic authentication dialog on every page load I have a https website running on NGINX and protected with basic authentication.
It works well except on iOS/Safari on iPhone (iOS version 9.3.1) -- Safari shows authorization dialog on every page load even after entering credentials, but still loads the page in background.
Is there any way to avoid showing auth dialog on every page load?
Part of NGINX config:
server {
    auth_basic "Restricted";
    auth_basic_user_file /etc/nginx/.htpasswd;
# ... more config
}

Thanks.


text:
Q: AngularJs directive: call method from parent scope within template I'm pretty new to Angular directives, and I'm having a lot of trouble getting this to do what I want. Here's the basics of what I have:
Controller:
controller('profileCtrl', function($scope) {
  $scope.editing = {
    'section1': false,
    'section2': false
  }
  $scope.updateProfile = function() {};
  $scope.cancelProfile = function() {};
});

Directive:
directive('editButton', function() {
  return {
    restrict: 'E',
    templateUrl: 'editbutton.tpl.html',
    scope: {
      editModel: '=ngEdit'
    }
  };
});

Template (editbutton.tpl.html):
<button
  ng-show="!editModel"
  ng-click="editModel=true"></button>
<button
  ng-show="editModel"
  ng-click="updateProfile(); editModel=false"></button>
<button
  ng-show="editModel"
  ng-click="cancelProfile(); editModel=false"></button>

HTML:
<edit-button ng-edit="editing.section1"></edit-button>

If it's not clear, I want the <edit-button> tag to contain with three different buttons, each interacting with whatever scope property is passed into ng-edit. When clicked, they should change that property then call the appropriate scope method.
The way it is now, clicking the buttons correctly changes the values of $scope.editing, but the updateProfile and cancelProfile methods don't work. I may be way off base on how to use directives properly, but I'm having trouble finding an example online to help me accomplish what I'm trying to do. Any help would be appreciated.

A: One way would be to call the functions using $parent.
<button ng-show="editModel" ng-click="$parent.cancelProfile(); editModel=false">b3</button>

Demo
Another way (and probably the better way), is to configure your directive's isolated scope to contain references to those controller functions:
app.directive('editButton', function() {
  return {
    restrict: 'E',
    templateUrl: 'editbutton.tpl.html',
    scope: {
      editModel: '=ngEdit',
      updateProfile: '&',
      cancelProfile: '&'
    }
  };
});

Then you pass the functions in via HTML:
<edit-button ng-edit="editing.section1" update-profile='updateProfile()' cancel-profile='cancelProfile()'></edit-button>

Demo


text:
Q: Как переопределить скрипт? Привет есть скрипт отправки формы
$("#openform").submit(function() { //Change
    var th = $(this);
    $.ajax({
        type: "POST",
        url: path/js/mail.php", //Change
        data: th.serialize()
    }).done(function() {
        $('#openform')[0].reset();
        alert('Ваша заявка отправлена.')
    });
    return false;

});

Как задать условие что если не все гладко вывести alert( на данный момент в коносоль показывает ошибку, к примеру если не все поля заполнены)

A: $("#openform").submit(function() { //Change
    var th = $(this);

    if (th.email) {
        $.ajax({
            type: "POST",
            url: path/js/mail.php", //Change
            data: th.serialize()
        }).done(function() {
            $('#openform')[0].reset();
            alert('Ваша заявка отправлена.')
        });
    } else {
         alert('Вы не заполнили поле E-MAIL');
         return false;
    }
});


text:
Q: How do I clean up sensitive Node.js Buffers from Electron renderer process memory dumps? I have a simple Electron test application that runs an Angular app in the renderer process. This angular app has two pages: Login and Account. After you log in using a username and password, you are redirected to the account page, where you can then log out.
Login
Component
@Component({
    selector: 'app-login',
    templateUrl: 'login.component.html',
})
export class LoginComponent {
    password: string;
    username: string;

    constructor(private router: Router) {
    }

    submit() {
        let usernameBuffer = Buffer.from(this.username, 'utf8');
        let passwordBuffer = Buffer.from(this.password, 'utf8');

        // Do some Node stuff with the buffers...

        // Now done with the buffers. Clearing the properties like this
        // doesn't seem to help.
        usernameBuffer = null;
        passwordBuffer = null;

        this.router.navigate(['/account']);
    }
}

HTML
<form id="login-page" (ngSubmit)="submit()">
    Username

    <input id="username" type="text" name="Username" [(ngModel)]="username" required>

    Password

    <input id="password" type="password" name="Password" [(ngModel)]="password" required>

    <button type="submit">Log In</button>
</form>

Account
Component
@Component({
    selector: 'app-account',
    templateUrl: 'account.component.html',
})
export class AccountComponent {
}

HTML

You are logged in!

Log Out

Test App
If interested, full source code for this test app can be found here: https://github.com/kspearrin/electron-memtest . Just clone it, then run npm i and npm run electron.

Using Windows 10, after the user logs into the application and is on the account page, I can go to the task manager and perform a memory dump to create a .DMP file. Opening this .DMP file in Notepad, I can perform a search and see the username and password in plaintext.
In this test, I logged in with username "testusername" and password "testpassword-123".

This only happens if I create Node Buffers with the username and password data, as shown above in the LoginComponent. It seems like the Buffers are never released from memory. I thought that maybe the Node garbage collection just needed to eventually run, however, I let this application keep running all day long and the values are still there when creating new .DMP files. Maybe I need to force run garbage collection?

*

*Why are these Buffers staying in memory?

*How can I properly clean this sensitive data up?

A: Zero fill them:
usernameBuffer.fill(0)
passwordBuffer.fill(0)


text:
Q: Function parameters: Copy or pointer? I'm kind of new to C++ and have some questions, this is one of them.
Is there ANY reason when you are using a function that takes in one or several parameters, parameters of which you know will always be stored in a variable before the function call, to pass a copy of the variable, rather than a pointer to the variable?
I'm talking in terms of performance. Seems to me that it would take a lot more resources to pass a copy of a whole struct than just a pointer(4 bytes).

A: A pointer opens up for bugs, since it allows the callee to alter the object. Pointers can be 0, which tends to create crashes, and this creates a need to test for 0 pointers all over the place, this can be annoying. Using C++ references, const-declared where possible, circumvents both these problems.

A: Avoid using pointer.Use constant Reference if is IN parameter else just reference for IN OUT parameter

A: The main question isn't about performance, but semantics, and whether your function modifies the data in the structure.
If your function modifies the structure, then passing a pointer will let the caller see the changed data in the structure.  In this case, passing a copy will likely be wrong, since your function will modify a copy which is then (presumably) discarded. Of course, it is possible that your function modifies the data, but you don't want the modifications, in which case a copy is the right thing to do, to protect the original values from changes.
If your function doesn't modify the structure, then there's no reason to copy the values, since they will only be read.
If you are not comfortable with the concept of passing pointers to structures, you should get some practice, because it is the typical way of dealing with structures in C and C++.
As far as performance goes, it's more work to copy the structure, but it's fairly minor in the scheme of things.  Keep your mind on the semantics of the code first.

A: There are several ways in which passing a copy can be cheaper than passing a pointer.

*

*The object is equal to or smaller than a pointer. Directly accessing a value will always be faster than dereferencing a pointer.

*The structure is small enough to be put on the stack by the compiler. In this case, access to the values in the structure is done by indexed addressing modes rather than indirect, indexed addressing modes. The former are generally faster.

There are other reasons for wanting to pass a copy rather than a reference, namely your function will be making changes in the structure which are not to be reflected back to the caller. While this is generally a poor practice, making the parameter pass-by-value will ensure that the caller's view isn't changed incorrectly.
Now for the part of the answer you probably don't want to hear: It generally doesn't make that much difference! Use the parameter passing method that makes the most sense for the semantics of your program. If you find later that there is a performance bottleneck in a particular area then focus in on improving the performance there. Don't over optimize!

A: Passing an object by pointer (or reference) and passing a copy of the same object have different semantics. If you want changes you make on an object to be reflected outside the function call you want reference semantics, otherwise you want value semantics.
Commonly value semantics can be expressed either by passing the value by value or by const reference
void value_semantics(my_obj obj);
void value_semantics(const my_obj& obj);

However the const reference way has some drawbacks as well, it prevents several optimizations that the compiler may make because of aliasing issues also for objects with trivial constructors the extra level of indirection (a reference is implemented as a pointer) may outweigh the benefits of avoiding the copy.
In order to get reference semantics you can choose either passing by reference or by pointer, as others already said references are more natural than pointers in C++ (you don't have to use the address of operator &) and the only real advantage of pointers is if you want to enable NULL values.
The rule of thumb is that for non-trivial classes you should pass by const reference, otherwise by value.

A: a reference is more common, or a const reference if they aren't going to change.


text:
Q: Can I change Earth Engine's pyramid scheme for a dataset? I'd like to change Earth Engines pyramid scheme for a particular dataset from the mean() of pixels to the max() of pixels.
Is there any way to do this?
I suspect not.
My use case is that I'm making a multiband image from a number of different sources, and want to get the max of pixels in one of the images (which is the one with the finest resolution) when I stratifiedSample the multiband image at a particular scale.
I suppose another option would be to somehow downscale all the other images when adding them to the multiband image.

A: You use reduceResolution for that sort of thing.
https://developers.google.com/earth-engine/guides/resample#reduce-resolution


text:
Q: How to test a clustered Express app with Mocha? Here is a simplified version of my cluster Express app:
/index.js
module.exports = process.env.CODE_COV
    ? require('./lib-cov/app')
    : require('./lib/app');

/lib/app.js
var cluster = require('cluster'),
    express = require('express'),
    app = module.exports = express.createServer();

if (cluster.isMaster) {
    // Considering I have 4 cores.
    for (var i = 0; i < 4; ++i) {
        cluster.fork();
    }
} else {
    // do app configurations, then...

    // Don't listen to this port if the app is required from a test script.
    if (!module.parent.parent) {
        app.listen(8080);
    }
}

/test/test1.js
var app = require('../');

app.listen(7777);

// send requests to app, then assert the response.

Questions:

*

*var app = require('../'); will not work in this cluster environment. Which of the worker apps should it return? Should it return the cluster object instead of an Express app?

*Now, obviously setting the port in the test script will not work. How would you set a port within a test script to a cluster of apps?

*How would you send requests to this cluster of apps?

The only solution I can think of is to conditionally turn off the clustering feature and run only one app if the app is requested from a test script (if (module.parent.parent) ...).
Any other way to test a clustered Express app with Mocha?

A: I have a much simpler way of doing this
    if (process.env.NODE_ENV !== 'test') {
    if (cluster.isMaster) {
        var numCPUs = require('os').cpus().length;
        console.log('total cpu cores on this host: ', numCPUs);
        for (var i = 0; i < numCPUs; i++) {
            console.log('forking worker...');
            cluster.fork();
        }

        cluster.on('online', function(worker) {
            console.log('Worker ' + worker.process.pid + ' is online.');
        });
        cluster.on('exit', function(worker, code, signal) {
            console.log('worker ' + worker.process.pid + ' died.');
        });
    } else {
        console.log('Im a worker');
        // application code
        setupServer()
    }
} else {
    // when running tests
    setupServer();
    }

Just make sure to set the env to test when running the tests
ex: NODE_ENV=test grunt test

A: It's been quite a long time since I have posted this question. Since no one has answered, I will answer to this question myself.
I kept the /index.js as it is:
module.exports = process.env.CODE_COV
    ? require('./lib-cov/app')
    : require('./lib/app');

In /lib/app.js which starts the cluster, I have the following code. In brief, I start the cluster only in non-test environment. In test environment the cluster is not started but only one app/worker itself is started as defined in the cluster.isMaster && !module.parent.parent condition.
var cluster = require('cluster'),
    express = require('express'),
    app = module.exports = express.createServer();

if (cluster.isMaster && !module.parent.parent) {
    // Considering I have 4 cores.
    for (var i = 0; i < 4; ++i) {
        cluster.fork();
    }
} else {
    // do app configurations, then...

    // Don't listen to this port if the app is required from a test script.
    if (!module.parent.parent) {
        app.listen(8080);
    }
}

In the above case !module.parent.parent will be evaluated as a truthful object only if the application was not started by a test script.

*

*module is the current /lib/app.js script.

*module.parent is its parent /index.js script.

*module.parent.parent is undefined if the application was started directly via node index.js.

*module.parent.parent is the test script if the application was started via one of the scripts.

Thus, I can safely start the script where I can set a custom port.
/test/test1.js
var app = require('../');

app.listen(7777);

// send requests to app, then assert the response.

At the same time if I need to run the application in real, i.e. not for testing, then I run node index.js and it will start up the cluster of applications.

A: I kind of liked your solution because of it's simplicity, however, in an environment like an MVC framework for node, you may end up chaining module.parent up to 11 times (seriously).
I think a better approach would be to simply check which script node started processing with. The node's command-line arguments are available at process.argv.
The first item in this array would be 'node', the executable and the second argument would be the path to the file that node start executing. This would be index.js in your case.
So instead of checking
                   module.parent.parent
                            ^       ^
                         (app.js)   |
                                (index.js)

You could do something like this
var starter = process.argv[1].split(path.sep).pop();

Where starter would be index or index.js depending on what you started your server with.
node index.js vs node index
The check would then look like:
if (cluster.isMaster && starter === 'index.js') {
    cluster.fork();
}

Worked in my environments—I hope this helps!


text:
Q: Order by dynamic parameter I'm trying to make and order by with dynamic parameter, this is the code:
var res = from c in db.CUSTOMERS select c;

if (!string.IsNullOrEmpty(sortBy) && !string.IsNullOrEmpty(direction))
      {
       var property = typeof(CUSTOMERS).GetProperty(sortBy);

       if(direction == "asc")
         {
            res = res.OrderBy(x => property.GetValue(x));
         }
      else
         {
           res = res.OrderBy(x => property.GetValue(x));
         }
}

return res.ToList();

but I get this error :

LINQ to Entities does not recognize the method 'System.Object GetValue(System.Object)' method, and this method cannot be translated into a store expression.

A: If you want to do sorting on the Server Side, you have to correct expression.
 var query = from c in db.CUSTOMERS select c;

 if (!string.IsNullOrEmpty(sortBy) && !string.IsNullOrEmpty(direction))
 {
    query = query.ApplyOrderBy(new [] {Tuple.Create(sortBy, direction != "asc")});
 }

 return query.ToList();

And implementation:
public static class QueryableExtensions
{
    public static IQueryable<T> ApplyOrderBy<T>(this IQueryable<T> query, IEnumerable<Tuple<string, bool>> order)
    {
        var expr = ApplyOrderBy(typeof(T), query.Expression, order);
        return query.Provider.CreateQuery<T>(expr);
    }

    static Expression MakePropPath(Expression objExpression, string path)
    {
        return path.Split('.').Aggregate(objExpression, Expression.PropertyOrField);
    }

    static Expression ApplyOrderBy(Type entityType, Expression queryExpr, IEnumerable<Tuple<string, bool>> order)
    {
        var param = Expression.Parameter(entityType, "e");
        var isFirst = true;
        foreach (var tuple in order)
        {
            var lambda = Expression.Lambda(MakePropPath(param, tuple.Item1), param);
            var methodName =
                isFirst ? tuple.Item2 ? nameof(Queryable.OrderByDescending) : nameof(Queryable.OrderBy)
                : tuple.Item2 ? nameof(Queryable.ThenByDescending) : nameof(Queryable.ThenBy);

            queryExpr = Expression.Call(typeof(Queryable), methodName, new[] { entityType, lambda.Body.Type }, queryExpr, lambda);
            isFirst = false;
        }

        return queryExpr;
    }
}


text:
Q: why i can not load Read only view object in the adf tester I am work with jdeveloper 12.2.1 and when i try to run the Application Module to test the view object instances the adf tester model windows loeded but when i add a Read only view object to the adf tester and try to reload agin the adf tester model windows not load and that error appear :
enter image description here
i searched a lot to resolve this error but no avail
any help?

A: in view object xml source change this line
trustMode="untrusted"
to
trustMode="trusted"
and the view object will be loaded in adf model tester


text:
Q: Url query parameter with no value on ASP.NET Web API 2 This is my controller's action for POST api/foo?bar=true requests:
[HttpPost]
[Route("api/foo")]
public async Task<HttpResponseMessage> Update(bool bar)
{}

It works fine, but when I try to do the same with a query parameter with no value like POST api/foo?bar, the action above doesn't work and this message is returned:

The parameters dictionary contains a null entry for parameter
  'bar' of non-nullable type 'System.Boolean' for method 'System.Threading.Tasks.Task`[System.Net.Http.HttpResponseMessage]
  Update(Boolean)' in
  'Foo.Controllers.FooController'. An optional parameter
  must be a reference type, a nullable type, or be declared as an
  optional parameter.

How can I make requests like POST api/foo?bar get into the Update() action? Optional parameter/Other type for the parameter?
Any help is welcome! Thanks.

A: Solved!
Made the parameter nullable leaving the action like this:
[HttpPost]
[Route("api/foo")]
public async Task<HttpResponseMessage> Update(bool? bar)
{}


text:
Q: How efficient is Chokidar (Node.js)? I have a caching engine on the server which caches all files accessed under a root directory. I'm thinking of using Chokidar to watch the entire directory tree (recursively) for file changes and update the cache accordingly. But I'm concerned about what would happen if a sub directory contained hundreds of thousands of files - How efficient would Chokidar be?

A: Chokidar's efficiency depends on which operating system it's running on.
On OS X, it uses a module that provides access to the native fsevents API, which is extremely efficient.
On other systems, it uses node.js's fs.watch or fs.watchFile APIs. Under the hood, fs.watch uses various system APIs to be notified of changes, which may be reasonably efficient. fs.watchFile uses stat polling, which would definitely be inappropriate for directories as large as you're describing.
My suggestion is that you set the chokidar option usePolling: false and give it a try, monitoring your cpu load.
Update (July 2015): Chokidar has been substantially improved since this was originally written, and polling is no longer the default on any platform.


text:
Q: Does the phrasal verb "I need off this place" mean the same as "I want out of this place"? In informal US English, "I want out of this room" means the desire to get out of that room.
But I've also heard this being said: I need off this room.
Does it mean the same?

A: You can use "I need off this place" if the affirmative is normally expressed with the preposition "on," for example, on the farm, on the ranch.
But watch out.  If the thing you're on isn't a place, but a thing, then your phrase won't work.  For example: John is on a train.  He wants off.  In other words, he wants off the train.  (You can't say, "He wants off this place" because the train isn't exactly a place.)
Now let's look more closely at what happens with the room.  Since no one would ever say, "I am on the room," you can't say "I need off this place" in that case.
However, you can say

I need out.

Or

I need to get out of this place.


text:
Q: How would you (incrementally) backup KVM VMs based on LVM storage? I'm running a set of KVM hypervisors on LVM storage (unfortunately I can't use QCOW2, because the virtualization platform I'm using is strictly LVM-based).
The virtualization platform has a very poor backup support, so I wrote a series of scripts which perform LVM snapshots, grab the image with qemu-image, compress and store it on a separate storage.
My scripts work well enough, but with increasing number of VMs and data to manage are beginning to show their limits.
Can someone suggest me a free or commercial solution to have the work done well?
This is what I'm doing now and what I need to do:

*

*scheduled backups

*daily and weekly rotation and retention

*backup saved on external storage

*restore system

*(extra points for incremental backup)

The VMs are both Linux and Windows, so I can't rely on the internal filesystem.
I don't need a web UI or other frills, CLI management is enough.

A: Use Veeam agent-based VM backup. Before Veeam would re-publish  their Nutanix AHV backup as a "generic" KVM VM backup.

A: You can try Vinchin Backup & Recovery for KVM incremental and scheduled backup and find other options like adding backup storage, systematically backup and restore VM, etc.


text:
Q: nested IF(AND(ISBLANK)) Statement not working? I have a formula that is supposed to place an "X" if a value populated in one or more of three columns (J,R,AL).
=IF(AND(ISBLANK(J:J),ISBLANK(R:R)),ISBLANK(AL:AL))),"","x")

It gives an argument error message, and I know it has something to do with the syntax structure of the parentheses. Can anyone help me figure out how to edit this?

A: It is not clear to me exactly what you have intended here, but you have an inappropriate number of parentheses. Google Sheets detects this error correctly right away, and I would be surprised if Excel didn't also give you a clearer error message.
=IF(
  AND(
    ISBLANK(J:J),ISBLANK(R:R)
     ),
  ISBLANK(AL:AL)
   )
),"","x")   /// <--- all of this is trailing junk

Perhaps your intention was to check if all of them were blank? You would still have one too many parentheses and you would need an extra AND, but at least your number of arguments would also make more sense.
=IF(AND(AND(ISBLANK(J:J),ISBLANK(R:R)),ISBLANK(AL:AL)),"","x")

A: An easier variation of your formula would be
=IF(COUNTA(J:J, R:R, AL:AL) > 0, "X", "")

Formula COUNTA counts non-empty cells. So the moment there is one non-empty it means there is data somewhere in at least one of these columns.
In my opinion, a much more elegant solution

EDIT: As found out in the comments, formula isn't supposed to check for entire column, but only for values in the colums per row. So, it should be:
(presuming your data starts at J1, R1, AL1)
=IF(COUNTA(J1, R1, A1) > 0, "X", "")

This will return the desired result


text:
Q: What's the point of seduce in crusader kings 2? What can you do with it? I can seduce women and sometimes have children with them. Can you do anything with the children? Like adopt them? Is there anything you can do after seduction gameplay wise or is it just a way to get opinion?

A: There are several very useful things you can do with seduce:

*

*If you are female, you can increase the number of children you have and select your mating partners

*Same goes if you are male, you can increase the number of children, but you will gain a negative opinion modifier with all your other children

*Finally, you can target female rulers. If you acknowledge the child as yours once they are born, they will inherit the ruler's claims, which you can then press and increase your realm size

A: When a bastard is born, an event MAY occur for a father to acknowledge the baby. It gives you an opinion penalty (cheated your wife) and a child is considered your own. Later you can legitimize your bastards.
Why is it useful? Right now my ruler is about 30 and has no children. Something goes wrong between him and his wife. So going seducing some women (with good genetic traits) is a way to continue my bloodline)

A: It can increase your plot power also if the women/men you're seducing have high intrigue stats. An example would be in my Venice play through. As the Doge I seduce every woman I can find in my rival patricians' courts which makes assassinating them a breeze. This keeps my dynasty in charge of the republic with minimal campaign funds.


text:
Q: ruby thread not wait In ruby I want to execute some local command which will generate a file,then I want to read the contents of the file,and modify it.
However I always get null.
This is the code:
exec "java -jar xx.jar --output main.txt";
content=IO.read('main.txt');
content="somethinkg:"+content;
File.open('main.txt','w') do |f|
  f.puts content
end

the main.txt is generated,however I can not modify the content.
Then I think it maybe caused by the thread,when the main.txt is being read,the java command is not complete,so the content is empty.
Then I tried this:
t=Thread.new do
  exec "java -jar xx.jar --output main.txt";
end
t.join
content=IO.read('main.txt');
puts content
content="somethinkg:"+content;
File.open('main.txt','w') do |f|
  f.puts content
end

However nothing changed,I can not still get the content.
What is the problem?

A: I think the problem over here is the exec command If you check the ruby documentation on exec
over here
the code after exec never execute
so
t=Thread.new do
  exec "java -jar xx.jar --output main.txt";
end

So your code never run anything after this
Try with system or backtick command
something like this
t=Thread.new do
  system "java -jar xx.jar --output main.txt";
end
t.join
content=IO.read('main.txt');
puts content
content="somethinkg:"+content;
File.open('main.txt','w') do |f|
  f.puts content
end

Hope it help


text:
Q: complex integrals springing from IMO question? I was looking at problem $A2$ here: https://www.imo-official.org/problems/IMO2006SL.pdf
The comment following $A2$ suggests that complex contours lead to a nice expression, but I don't see the connection. It may have to do with the residue theorem.

A: By the comment following A2 we know
$$\sum_{k=0}^\infty a_k z^k=\frac{z}{\log (1-z)},\quad (|z|<1)$$
where the branch of $\log(1-z)$ is chosen so that $\log 1 =0$ of course.
We can rewrite this as
$$\sum_{k=0}^\infty a_k z^k=\frac{z}{\log (z-1)-i\pi},$$
where the branch of $\log(z-1)$ is chosen so that $0\le \operatorname{Im}\,\log (z-1)<2\pi$.
Dividing both sides by $z^{n+1}$ we have $$
\sum_{k=0}^\infty a_k z^{k-n-1}=\frac{1}{z^n(\log (z-1)-i\pi)}$$
and hence the residue therem yields
$$
a_n=\frac{1}{2\pi i}\int_{|z|=r}  \frac{dz}{z^n(\log (z-1)-i\pi)} \quad (r<1).$$
Now we consider the keyhole-shaped contour consisting of
1. the horizontal line segment $I_1$ from $1+i\varepsilon $ to $\sqrt{R^2-\varepsilon ^2}+i\varepsilon $;
2. the circular arc $C_R$ of radius $R$ traced counterclockwise from $\sqrt{R^2-\varepsilon ^2 } +i\varepsilon $ to $\sqrt{R^2-\varepsilon ^2 } -i\varepsilon$;
3. the horizontal line segment $I_2$ from $\sqrt{R^2-\varepsilon ^2}-i\varepsilon $ to $1-i\varepsilon $;
4. the semi-circle $C_\varepsilon $ of radius $\varepsilon $ traced clockwise from $1-i\varepsilon $ to $1+i\varepsilon $.
Then we have \begin{align}
a_n=\frac{1}{2\pi i}\left(\int_{I_1}+\int_{C_R}+\int_{I_2}+\int_{C_\varepsilon }\right)  \frac{dz}{z^n(\log (z-1)-i\pi)} ,\tag{1}\end{align}
since the integrand is analytic in $\mathbb{C}\setminus (\{0\}\cup [1,\infty))$.
Note that \begin{align}
\lim_{\varepsilon \to 0} \int_{I_2} \frac{dz}{z^n(\log (z-1)-i\pi)}&=\int_R^1 \frac{dx}{x^n(\log (x-1)+2i\pi-i\pi)}\\
&=\int_R^1 \frac{dx}{x^n(\log (x-1)+i\pi)}.\end{align}
Therefore letting $R \to \infty$, $\varepsilon \to 0$ in $(1)$, we have
\begin{align}
a_n&=\frac{1}{2\pi i}\left(\int_1^\infty \frac{dx}{x^n\left(\log (x-1)-i\pi\right)}+\int_\infty^1 \frac{dx}{x^n\left(\log (x-1)+i\pi\right)}\right)\\
&=\int_1^\infty \frac{dx}{x^n\left(\log^2(x-1)+\pi^2\right)},
\end{align}
since integrals along $C_\varepsilon $ and $C_R$ tend to $0$.


text:
Q: PHP fill array every nth row I'm trying to create an array that holds a marker on every 10th row, every 50th row and every 100th row. But my current code I've shown below is just marking every row after "count" = 10 as 10. Can anyone see what I'm doing wrong?
<?php

function randomString($length = 15) {
$rs = "";
$char = array_merge(range('A','Z'), range('a','z'), range('0','9'));
$max = count($char) - 1;
for ($i = 0; $i < $length; $i++) {
    $rand = mt_rand(0, $max);
    $rs .= $char[$rand];
}
return $rs;

}

$i = 0;
$times_to_run = 100;
$prize='';
$counter = 0;
// $array = array();
while ($i++ < $times_to_run)
{
    $counter++;

    if ($counter % 10 == 0) {
        $prize='10';
    }
    elseif ($counter % 50 == 0) {
        $prize='50';
    }
    elseif ($counter % 100 == 0) {
        $prize='100';
    } else {$prize=='';}

    $array[] = array(
        'count' => $i,
        'code1' => randomString(),
        'prize' => $prize
    );
}

// var_dump($array);

echo"
";
$codes = $array;
foreach ($codes as $code){
    echo'
';
    echo''. $code['count']."	";
    echo''. $code['code1']."	";
    echo''. $code['prize']."	";
    echo'
';
}
echo"
";

?>

so.. when "count" is 10, "prize" should be 10. Prize should then be empty until "count" = 20 and so on until "count" reaches 50 - "prize" should show 50. At the moment it is just doing what is shown in the image:

A: The very first check:
if ($counter % 10 == 0) {
    $prize='10';
}

sets the $prize to 10 and nobody then resets it. Once you want the explicit set of rows be marked, mark them:
if ($counter == 10 || $counter == 50 || $counter == 100 ) {
  // set it
} else {
  // RESET IT — IMPORTANT
}

Another glitch with your code is that your first check:
if ($counter % 10 == 0) { ...

is evaluated to true for 50 and 100 as well, forcing second and third branches of if-else switch to become unreachable.

A: replace your while loop
for($i=1;$i<=$times_to_run;$i++){
            if($i == '10' || $i == '50' || $i == '100'){
                $prize=$i;
            }else{
                $prize='';
            }
            $array[] = array(
                'count' => $i,
                'code1' => randomString(),
                'prize' => $prize
            );
        }

        echo "
";print_r($array);

A: If I understand correctly then you want to this
$prize= "";
if ($counter % 10 == 0)
{
  $prize= floor($counter/10) * 10;
}

  $array[] = array(
    'count' => $i,
    'code1' => randomString(),
    'prize' => $prize
   );

OR
If you want to 10, 50, 100 then
for ($i=0;$i< $times_to_run;$i++)
{
   $prize="";
    if($i == 10 || $i == 50 || $i == 100) {
      $prize = $i;
    }
}