text:
Q: close web app tab works from script editor but not from google sheet :( I am trying to close the web app tab after the web app does its job.
I am using

in index.html to achieve my aim.
It does what it is expected to do (close the web app tab) when triggered with a click on the link in the google script editor/deploy as web app/execute the app as Me, accsess to anyone, even anonymous/test web app for your latest code,
but if I copy that same link and insert that same link to a cell in google sheet and click on it, it does open the web app in new tab, but it doesn't close it as expected :(
So,

works only from google script editor but not if I click on the web app link inserted in google sheet cell or paste it directly into a browser.
My code.gs is:

function doGet() {
  var html = HtmlService.createTemplateFromFile("index").evaluate();
  html.setTitle("Some Testing");
  return html;
}

function include(filename) {
  return HtmlService.createHtmlOutputFromFile(filename)
      .setSandboxMode(HtmlService.SandboxMode.IFRAME)
      .getContent();
}

My index.html is:

<!DOCTYPE html>

    <base target="_top">

    HELLO WORLD :)

my google sheet for calling my web app is:
https://docs.google.com/spreadsheets/d/18Ot_4LePEJPiEiCe955meR7wZkaFXAp2egmLCLT7CCg/edit?usp=sharing
(anyone who has the link can edit :)
Please help me to see what I don't see. Thanx.


text:
Q: How are pixels arranged in SDL2? I have 2x2 image
Shouldn't the pixels be arranged like this?
1 2 // each number is a pixel
3 4

I'm having trouble accessing a pixel with x and y because
when x = 1 and y = 0  i get index 2 but prints the rgb values of pixel 4
so it's something like?
1 2 // each number is a pixel
4 3

Here's the code that I use
index = y + x * s->w;
c = s->format->palette->colors[index]; // c is an SDL_Color and s is an SDL_Surface*

I also use this for loop and still prints the same
for (Uint8 i = *(Uint8 *)s->pixels; i < s->w*s->h; i++) {
    c = s->format->palette->colors[i];
    printf("%u %u %u %u \n", i, c.r , c.g , c.b);
}

SDL_Surface struct definition from the SDL documentation
typedef struct SDL_Surface {
    Uint32 flags;                           /* Read-only */
    SDL_PixelFormat *format;                /* Read-only */
    int w, h;                               /* Read-only */
    Uint16 pitch;                           /* Read-only */
    void *pixels;                           /* Read-write */

    /* clipping information */
    SDL_Rect clip_rect;                     /* Read-only */

    /* Reference count -- used when freeing surface */
    int refcount;                           /* Read-mostly */

/* This structure also contains private fields not shown here */
} SDL_Surface;

A: Uint8 *pixel = (Uint8 *)s->pixels,*index;
index = &pixel[y + x * s->pitch];
c = s->format->palette->colors[*index];

Got it doing using @holyblackcat's suggestion.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to use replacingOccurrences for NSAttributedString in swift? In a NSAttributed type statement, I want to keep the existing attributed value and give it a new attributed value.
The problem is that replacingOccurrences is only possible for string types, as I want to give a new value every time the word appears in the entire sentence.
If I change NSAttributedString to string type, the attributed value is deleted. I must keep the existing values.
How can I do that?

A: You can use replaceCharacters.  You can find the range of the substring you want to remove and use it as your range.

A: To get this working,
1. First you need to find the indices of all the duplicate substrings existing in a string. To get that you can use this: https://stackoverflow.com/a/40413665/5716829
extension String {
    func indicesOf(string: String) -> [Int] {
        var indices = [Int]()
        var searchStartIndex = self.startIndex

        while searchStartIndex < self.endIndex,
            let range = self.range(of: string, range: searchStartIndex..<self.endIndex),
            !range.isEmpty
        {
            let index = distance(from: self.startIndex, to: range.lowerBound)
            indices.append(index)
            searchStartIndex = range.upperBound
        }

        return indices
    }
}

2. Next you need to apply your desired attribute to substring at each index, i.e.
    let str = "The problem is that replacingOccurrences Hello is only possible for string types, as I want to give Hello a new value every time Hello the word appears in the entire sentence Hello."
    let indices = str.indicesOf(string: "Hello")
    let attrStr = NSMutableAttributedString(string: str, attributes: [.foregroundColor : UIColor.blue])
    for index in indices
    {
        //You can write your own logic to specify the color for each duplicate. I have used some hardcode indices
        var color: UIColor
        switch index
        {
        case 41:
            color = .orange
        case 100:
            color = .magenta
        case 129:
            color = .green
        default:
            color = .red
        }
        attrStr.addAttribute(.foregroundColor, value: color, range: NSRange(location: index, length: "Hello".count))
    }

Screenshot:

Let me know if you still face any issues. Happy Coding..


text:
Q: unixODBC and DB2 ODBC connection issue on Ubuntu I went through the tutorial on unixODBC.org website for DB2 connections and I can't successfully get the connection to succeed with isql. Think I'm getting stuck on the configuration of odbc.ini  vs  odbcinst.ini and  vs  db2cli.ini
I installed the iAccess drivers version 10.5 fix pack 6
ODBC.ini
[mustship]
Description=Connection to AS400
Driver=DB2
Host=10.220.1.10
Port=446
Username=common
Password=common

ODBCINST.ini
[DB2]
Description=DB2 Driver
Driver=/usr/local/lib/clidriver/lib/libdb2.so
FileUsage=1
DontDLClose=1

DB2CLI.ini
[mustship]
Database=matt

Error
[08001][unixODBC][IBM][CLI Driver] SQL1013N The database alias name or database name "MUSTSHIP" could not be found. SQLSTATE=42705
[ISQL]ERROR: Could not SQLConnect
I am trying to connect to the library "matt" on my DB2

A: For anyone else with this issue, I found this great post explaining the process in more detail. This resolved it for me:
http://fractio.nl/2007/10/26/setting-up-unixodbc-with-a-remote-db2/


text:
Q: Connecting to proxmox web GUI via hamachi I have a server with multiple network adaptors. I have installed proxmox, and hamachi on that. I want to be able to access the web GUI through hamachi as I am not able to port forward or have both the server and laptop on the same network. My server IP on hamachi is 25.54.34.60. I want to be able to access the web-GUI, which is accessible on 1.2.3.4:8006 (example ip) from the hamachi IP. I have no idea how to do this. Any help appreciated.

A: A) Preliminary steps to follow if you're not using the Enterprise version of Proxmox:

*

*Fix your repository so that the enterprise repository is disabled (commented out) and such that the sources.list contains the correct URL (see information here)

*While you're in there, you might as well do this if you're not on enterprise: https://johnscs.com/remove-proxmox51-subscription-notice/

*Sing up for a Hamachi account: https://secure.logmein.com/welcome/hamachi/vpn/default.aspx
B) Hamachi installation and setup:

*

*Go to this page and follow the "Task One" steps. For steps 1 & 2, see this:

*Continue on to "Task Two" and when you get into the snapd installation process, see Debian instructions here and be sure to reload your terminal to get $PATH reloaded (if you're on the web interface Shell, reload browser).

C) Accept the pending join request if you've set it to require admin acceptation from Hamachi:

*

*Notice pending join request:

*Accept it:

You're done!


text:
Q: Google Drive API/SDK TransferOwnership Im trying to transfer the ownership of a specific file to another user.

Total Code
foreach (Permission permission in RetrievePermissions(service(), file.Id))
        {
            if (permission.Role == EnumClass.PERMISSIONROLE.OWNER.ToText())
            {
                //Downgrade Owner Writer
                UpdatePermission(service(), file.Id, permission.Id, EnumClass.PERMISSIONROLE.WRITER);
                //Create New Writer
                InsertPermission(service(), file.Id, ownerMail, EnumClass.PERMISSIONROLE.WRITER);

                foreach (Permission thisPermission in RetrievePermissions(service(), file.Id))
                {   //Update Writer to Owner
                    if (thisPermission.Name == "Person X")
                    {
                        //Set Person X as new Owner
                        UpdatePermission(service(), file.Id, thisPermission.Id, EnumClass.PERMISSIONROLE.OWNER);
                    }
                }
            }
        }

Update Permission Method
public static Permission UpdatePermission(DriveService service, String fileId, String permissionId, EnumClass.PERMISSIONROLE ROLE)
    {
        try
        {
            // First retrieve the permission from the API.
            Permission permission = service.Permissions.Get(fileId, permissionId).Execute();
            permission.Role = ROLE.ToText();

            //if new Role is Owner, Downgrad current Owner
            if (ROLE == EnumClass.PERMISSIONROLE.OWNER)
            {
                var myPermission = service.Permissions.Update(permission, fileId, permissionId);
                myPermission.TransferOwnership = true;

                foreach (Permission per in RetrievePermissions(service, fileId))
                {
                    if (per.Role == EnumClass.PERMISSIONROLE.OWNER.ToText())
                    {
                        per.Role = EnumClass.PERMISSIONROLE.WRITER.ToText();
                    }
                }
            }
            return service.Permissions.Update(permission, fileId, permissionId).Execute();
        }

        catch (Exception e)
        {
            Console.WriteLine("An error occurred: " + e.Message);
        }
        return null;

Insert Permission Method
 public static Permission InsertPermission(DriveService service, String fileId, String userMail, EnumClass.PERMISSIONROLE Role)
    {
        Permission newPermission = new Permission();
        newPermission.Name = userMail;
        newPermission.Value = userMail;
        newPermission.Type = EnumClass.PERMISSIONTYPE.USER.ToText();
        newPermission.Role = Role.ToText();

        try
        {
            return service.Permissions.Insert(newPermission, fileId).Execute();
        }
        catch (Exception InsertError)
        {
            Console.WriteLine("Error inserting permission for " + userMail + Environment.NewLine + "Error on Insert: " + InsertError.Message);
        }
        return null;
    }

Error

Google.Apis.Requests.RequestError Insufficient permissions for this
  file [403] Errors [   Message[Insufficient permissions for this file]
  Location[ - ] Reason[forbidden] Domain[global] ]

Im currently using the ServiceAccount.
All help appreciated!

A: Did you try to use impersonation?
var initializer = new ServiceAccountCredential.Initializer(ServiceAccountEmail)
{
    Scopes = new[] { DriveService.Scope.Drive },
    User = "user@yourdomain.com"
};

A: The best way to transfer the ownership is to

*

*Enable domain wide delegation to the service account

*Impersonate the user while initialling the drive service as below:
*
 using (var credentialJSON =new FileStream(_settings.CertificatePath,FileMode.Open, FileAccess.Read))
            {
                var credentialParameters =
                    NewtonsoftJsonSerializer.Instance.Deserialize<JsonCredentialParameters>(credentialJSON);

                credential = new ServiceAccountCredential(
                    new ServiceAccountCredential.Initializer(credentialParameters.ClientEmail)
                    {
                        Scopes = scopes,
                        User = ownerEmailAddress, //put in the actual user email address
                    }.FromPrivateKey(credentialParameters.PrivateKey));
            }


text:
Q: Problems setting up FastAi working on Colab I'm trying to work through a tutorial on CycleGANs using the Colab platform but I'm struggling to find a way through the 'simple' part of just importing libraries.
I'm just trying to import the following:
from fastai.conv_learner import *
from fastai.dataset import *
from cgan.options.train_options import *
from sklearn.model_selection import train_test_split
from cgan.options.train_options import TrainOptions
from cgan.data.data_loader import CreateDataLoader
from cgan.models.models import create_model
from cgan.util.visualizer import Visualizer
from google_images_download import google_images_download

I'm currently stuck with an error on the first line:
----> 7 class IntermediateLayerGetter(nn.ModuleDict):
      8     """
      9     Module wrapper that returns intermediate layers from a model

AttributeError: module 'torch.nn' has no attribute 'ModuleDict'

The code can be found online: https://colab.research.google.com/drive/1dMQWStzLfAHDTGuKaUNQn1aOBWeJw4FN

A: Did you check this issue it sorts partially the problem.
Afterthat I received and this error (Detected that PyTorch and torchvision were compiled with different CUDA versions. PyTorch has CUDA Version=9.0 and torchvision has CUDA Version=10.0. Please reinstall the torchvision that matches your PyTorch install.) and solve it with
pip install torch==1.0.1 -f https://download.pytorch.org/whl/cu100/stable

I hope it helps :)


text: Q: Is parallelism in computer science always directly tied to the number of processor cores? Specific to the Java programming language, would it be accurate to say that two threads can be concurrent, but can only truly be run in parallel if there are two or more cores?


text:
Q: Calling delete on address of variable Why can I do:
int i = *(new int (5));

and successfuly use i after it,
but when I'm trying:
delete &i;

I get a run time error:

Unhandled exception at 0x5ddccaf7 (msvcr100d.dll) in Test.exe:
  0xC00000FD: Stack overflow.

If i was a reference:
int & i = *(new int (5));

, all this (including delete) works fine.
I know, that it's no good to keep allocated memory handler in something other than pointer and *(new ...) is awful, but I'm just wondering, why new works good, but delete fails.
//Below are just my guesses about the reason of such behavior:
Is it because module which executes program (it's probably not "compiler", because of there is run time already) when it encounters with delete, it searches for some information like length of data pointing by &i (in some internal array of such information about all pointers) and don't find it or interpretes some trash data as this information? (I suppose, pointers and references have it, but variables don't)

A: Your original version does not assign i to an address. It allocates a new int on the heap and initializes its value to 5, then copies that value into i which is on the stack. The memory that you allocated (new'ed) is inaccessible and gets leaked.
The reference version works because i refers to the otherwise-anonymous new'ed memory. Hence &i gives the heap address. In your first version, &i gives the address of the stack variable, not the heap memory, and deleting stack memory is bad news.

A: You get a run-time error because the address of i is not the same as the address returned by the operator new. Once you dereference the result of new, you make a copy of the value. That copy is then placed into variable i, which has an address in automatic storage, which cannot be passed to delete legally without triggering undefined behavior.
When you make a reference, however, you do not make a copy: the result of new becomes referenced through a variable i of type "reference to int". Hence, the reference has the same address as has been returned by operator new,  so the code that uses the reference works fine.

A: The line:
int i = *(new int (5));

Is equivalent to:
int* p = new int(5);
int i = *p;

The address of i (which you are trying to delete) is not the address of the allocated memory.
In mathematical notation, &x == &y implies x == y, but x == ydoes not imply &x == &y.


text:
Q: custom variable in rewrite nginx It is an way to make this work?
set $test "some|else";
rewrite ^/page/$test/ /index.php?blabla=yes last;

Then to work like http://www.demo.com/page/some/ or http://www.demo.com/page/else/

A: I think it should be something like this, but I haven't tested:
if ($request_uri ~* ^/page\/(some|else)$)
{
  rewrite ^(.*)$ /index.php?blabla=yes;
}

Let me know if it did the trick for you.


text:
Q: Do nested conditionals have a significant performance impact? This is a question that lives in my mind from a long time.
Does the use of multiple nested conditional statements impact the performance of a taken code? So far I know that programmers have created a precise term to describe this situation, the in-famous "Pyramid of doom" [Wikipedia page], but a side from that how much can this degrade performances?
Let's take this situation as an example: I have a JSON coming from a server response containing a few objects that represent the user purchases in an application, before taking the needed data from it I need to check various conditions:

*

*Is the response we are looking for?

*Does response has resultCode: OK?

*Are the any contents to process?

At this point if everything is true a "processing process" will begin, parsing and editing the server response, in this case for changing the date format from US to the standard european format. The process consist in two nested for-loops and an if statement.
This is the example code in Objective-C, since I'm an iOS Developer:
if ([remoteManager.operationId isEqualToString:NEEDED_OPERATION_ID]) {
    if ([response[RESULT_CODE_KEY] isEqualToString:@"OK"]) {
        if ([response[RESULT_OBJ_KEY][@"CONTENT_LIST"] count] > 0) {
            NSMutableDictionary *tempDict = [[NSMutableDictionary alloc] init];

            for (NSMutableDictionary *productsAvailable in response[RESULT_OBJ_KEY][@"CONTENT_LIST"]) {
                for (NSString *key in productsAvailable) {
                    if ([key isEqualToString:@"NEEDED_KEY"]) {
                        /* We change the date format here */
                    }
                }
            }
        }
    }
}

In my opining this code can't really have an impact on the performance of an application because those checks are not so complicated for the system to do. But does this can be a problem if we need to have the maximum speed and performances? In other words: should nested conditionals be avoided or not? And also does putting multiple conditions at the same time reduces the performance problems (if any)?

A: The problem with nested conditions is not speed, its human comprehension.
Human beings have trouble coping with many possibilities at once.
They reach their limit (which is fairly small) then start to make mistakes without realising it.
Conditional statements increase complexity fairly quickly: 2, 4, 8, 16, 32, 64, 128... and for almost all programmers, the limit is in single digits.
Computers have no problems optimising code with very many nested conditions, but humans will find it almost impossible to maintain the source code - which means it won't work.
Most programming techniques are about coping with human weakness, rather than speed. Source code is for humans.

A: The sequence of steps that you described appears to be a sequence of steps that you must perform, in order for your application to achieve what it is supposed to achieve.  So, there is nothing that you could add or remove.
With the existing code, you have the following options:

*

*Rearrange the order in which the conditionals are evaluated. You could, perhaps, achieve better performance by re-arranging the conditionals so that the most frequently failing ones are evaluated first, or so that the more computationally expensive ones are evaluated last, but it is hardly worth the effort, and in any case you need to spend some time measuring stuff before you attempt that, otherwise you are shotgunning the problem and running the danger of worsening things instead of improving things.

*Replace nesting with multiple expressions ANDed together. I know nothing of Objective-C, but I would be willing to bet that it stays true to the tradition of C, and it uses short-circuit boolean expression evaluation, so the construct if(a) { if(b) { ... } } is equivalent to if((a) && (b)) { ... }, so nesting or no nesting makes absolutely no difference.

*Replace nesting with early-exiting.  Early exiting is when you say if(!a) return; if(!b) return; bulk-of-code-goes-here. There are people who insist on early exiting, so as to reduce the nesting, and others who see no problem with nesting, and believe that early exiting is evil. But again, this makes no difference on how fast the code will run, so this issue is all about style, not performance: "to nest or not to nest" is an entirely subjective question which can only receive a subjective answer. (Which is of course "die, you nesting fool !")
So, there is pretty much nothing you can do to improve things, and nesting or no nesting has absolutely no impact on performance.  On top of that, no matter how you structure your conditionals, the compiler is generally free to emit the machine code in whatever way it sees fit, as long as it has the same result, so your nested conditionals will probably be implemented as early exits by the compiler, just as short-circuit evaluation would. This means that at the end of the day, the only criterion for how to arrange your conditionals ought to be how it is most natural for you to read them and understand them.
I would recommend that you heed the advice contained in gnat's excellent (and ironic) suggestion that your question is a duplicate of another question which is in fact about micro-optimizations: stop worrying about performance of code.  You should only start being worried about performance if your final product is found to actually suffer performance-wise, and even then, the solutions that you will find will most likely be algorithmic, big-picture optimizations, and it is highly unlikely that they will have anything to do with how you order individual instructions.


text:
Q: Django app hang-up in cv.CaptureFromCAM(0) I am trying to take an image from my webcam with a simple Django app. This is my view:
def show_home_page(request, template_name="content/homepage.html"):
""" show page """

    capture = cv.CaptureFromCAM(0)
    img = cv.QueryFrame(capture)
    cv.SaveImage("test.jpg",img)

    return render_to_response(template_name, locals(), context_instance=RequestContext(request))

The code hangs in the line: capture = cv.CaptureFromCAM(0)
I tried using the same code in a simple python app and that works:
import cv
from Tkinter import *

def main():
    root = Tk()
    capture = cv.CaptureFromCAM(0)
    img = cv.QueryFrame(capture)
    cv.SaveImage("test.jpg",img)
    cv.ShowImage('Raw', img)
    root.mainloop()

if __name__ == '__main__':
    main()

In both cases I run the program in Eclipse 4.2.0, Python 2.7 on Mac OSx mountain Lion. I use opencv-2.4.2
Any clues?
Thanks in advance,
Frans


text:
Q: Mysql trigger with cursor to fetch all column from one table and insert into other I have two table product and product_log. When i insert,update or delete a record in product table i want to call a trigger which perform following operations
1:- fetch all column name from product table.
2:- arrange product table column name and value in json format
e.g. log = {"col_first":"value_first", "col_second":"value_second"}
3:- After that insert into product log.

product table
    create table product(
    id int auto_increment primary key,
    name varchar(100),
    description text,
    created_at datetime
    );

product_log table
   create table product_log(
    id int auto_increment primary key,
    table_name varchar(100),
    logdata longtext,
    created_at datetime
    );

Here is my trigger code which is not correct please help me friends. Any suggestion will be appreciated. thank You
DELIMITER $$
    create trigger after_product_insert
    AFTER INSERT on product for each ROW
    BEGIN
        DECLARE finished INTEGER DEFAULT 0;
        declare stProduct text;
        DECLARE stRes text;
        declare prodct cursor for SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='mydb' AND TABLE_NAME='product';

        DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;

        OPEN prodct;
            stLoop: LOOP
                FETCH prodct INTO stProduct;
                IF finished = 1 THEN
                    LEAVE stLoop;
                END IF;

                SET stRes = CONCAT(stProduct,",",stRes);
            END LOOP stLoop;
            insert into product_log(table_name, logdata) values ('product', stRes);
        CLOSE prodct;

    END$$
DELIMITER ;

After Query Run table look like:
Product table
|----------|----------|------------------|---------------------|
|   id     |   name   | description      |   created_at        |
|----------|----------|------------------|---------------------|
|    1     | laptop   | all about laptop | 2020-01-29 00:00:00 |
|----------|----------|------------------|---------------------|

product_log table
|----------|----------------|---------------------------------------------|---------------------|
|   id     |   table_name   |     logdata                                 |   created_at        |
|----------|----------------|---------------------------------------------|---------------------|
|    1     |   product      | {"name":"laptop","description":"all ..",..} | 2020-01-29 00:00:00 |
|----------|----------------|---------------------------------------------|---------------------|

A: If you just concat, it can not be used as json.
json_set(columnname, key, value[, key, value]);

Secondly, if you just want pairs of values inside a longtext, you can use
select group_concat( concat(name, ":", description) SEPARATOR ",")...


text:
Q: Cannot receive the http status code 413 for CORS I have this web application where the web services are hosted on Amazon API gateway & the client application is hosted on cloudefront site. The services are CORS enabled. For any error such as http 500, 401, 403 I am able to receive the http status from the jqxhr object using status property. But it seem that for http status 413 i am getting status 0 in the code.
I have also noticed that http status 413 can be received if the request is made with in the server. But only for cross domain ajax, the status 413 is received as status 0.
Is there any way to handle http status 413 for cross domain ajax request.
Just brevity, consider the following code block, for http status 500, 401 the error callback log's out 500 or 401. But for 413 it displays 0.
        $.ajax({
            url: 'URL to AWS API Gateway',
            success: function(d){
                 console.log(d);
            },
            error: function(a){
                console.log( a.status );
            }
        });

A: See the following http://jsfiddle.net/tqgv7z9c/1/ (note http not https)
$.ajax({
    url: 'http://www.mocky.io/v2/57bb03fc100000460a585000',
    error: function(a){
        $('#code').text( a.status );
    }
});

I set it up using http://www.mocky.io/ with the following setup:

*

*413 Request Entity Too Large

*CORS Headers

*

*Access-Control-Allow-Origin: http://fiddle.jshell.net

*Access-Control-Allow-Methods: GET

You can see the 413 code is correctly returned.
Without seeing more detail on the response you receive, I'd imagine the browser is taking a follow up action, I know this is a problem if a 304 Found response comes back with a Location header, this will cause a new request to occur and you won't be able to intercept before the browser continues. if this is what is happening for you, there is likely little you can do about it if you don't have the ability to modify the API itself.


text:
Q: Find a subgroup of $\Bbb Z_4\oplus\Bbb Z_2$ not of the form $H\oplus K$ for some $H\le \Bbb Z_4, K\le \Bbb Z_2$. This is Exercise 8.28 of Gallian's "Contemporary Abstract Algebra".
Answers that use only methods from the textbook prior to the exercise are preferred.
Here $G_1\oplus G_2$ is the external direct product of  $G_1$ by $G_2$.
Here $G_1\le G_2$ means $G_1$ is a subgroup or equal to the group $G_2$.
The Question:

Find a subgroup of $\Bbb Z_4\oplus\Bbb Z_2$ not of the form $H\oplus K$ for some $H\le \Bbb Z_4, K\le \Bbb Z_2$.

Thoughts:
I must confess: I cheated here a little bit by looking up the subgroups of $\Bbb Z_4\times \Bbb Z_2$. But notice the difference in notation! I think in terms of just plain old direct products (because aren't internal and external direct products equivalent? Yes! But this is not established in the textbook yet; indeed, the former is not even mentioned at this point).
It appears to me to be a trick question. Here are the subgroups of $\Bbb Z_4\times \Bbb Z_2$. Where is the subgroup of the desired form?
My guess is that there's some technical aspect of external direct products that is being emphasised here.
Please help :)

A: The cyclic group generated by $(1,1)$ fits. It maps surjectively under both projections, but it is not the whole group, so you cannot write it as the direct product of two subgroups.


text:
Q: Reordering a Javascript Array I've got an array that I want to re order based on the index of an item in the array
I've tried two different methods so far but it seems that the array comes out just as when it was sent in.
function orderPlayers(players, fpIndex){
    for(var i = 0; i < players.length; i ++ ){
        players.move(i, fpIndex);
        fpIndex = fpIndex + 1;
        if(fpIndex > players.length - 1){fpIndex = 0;}
    }
    return players;
 }

 Array.prototype.move = function (from, to) {
     this.splice(to, 0, this.splice(from, 1)[0]);
 };

Example of data:
fpIndex: 1 //The player that is first is at array index 1

Players: {
     player: {
         age: 19,
         name: Bob,
         piece: "red",
         isFirst: false
     }

     player: {
         age: 21,
         name: Steve,
         piece: "blue",
         isFirst: true
     }
}

Should come out as:
Players: {
     player: {
         age: 21,
         name: Steve,
         piece: "blue",
         isFirst: true
     }

     player: {
         age: 19,
         name: Bob,
         piece: "red",
         isFirst: false
     }
}

A: so you want to reverse an array? have you tried Array.prototype.reverse()?

A: Is this what you are looking for? See working example:

var players =
    {
      "Players":
      [
        {
          "player": {
            "age": 21,
            "name": "Steve",
            "piece": "blue",
            "isFirst": true
          }
        },

        {
          "player": {
            "age": 19,
            "name": "Bob",
            "piece": "red",
            "isFirst": false
          }
        }
      ]
    }

var fpIndex = 1;

function orderPlayers(plys, index){
  index = index % plys.length;
  if(plys.length === 0 || plys.length === 1 || index === 0){
    return plys;
  }
  let part = plys.splice(plys.length - index);
  return part.concat(plys);
}

console.log(orderPlayers(players.Players, fpIndex));


text:
Q: I'm using spring boot, can I enter values in database without using entity classes? It's not working like this? How to add data?
@Override
public void addArticle(Article article) {
    //Add article
    String sql = "INSERT INTO articles (articleId, title, category) values (?, ?, ?)";
    jdbcTemplate.update(sql, article.getArticleId(), article.getTitle(), article.getCategory());

    //Fetch article id
    sql = "SELECT articleId FROM articles WHERE title = ? and category=?";
    int articleId = jdbcTemplate.queryForObject(sql, Integer.class, article.getTitle(), article.getCategory());

    //Set article id
    article.setArticleId(articleId);
}

A: One way to do it is described below:
Create a file data.sql and keep all your queries inside that file for example
INSERT INTO country (name) VALUES ('India');
and put this file on the classpath.
SpringBoot will pick it up and populate the Entries in the DB.


text:
Q: Data update when navigating to a screen I have a question about React-Navigation.
I have two screens being: ScreenA and ScreenB.
Inside ScreenA I have data obtained from the database.
TelaB adds data to this same database.
After ScreenB adds data to the database, it navigates back to ScreenA but the data is not updated. I would like to update the data only when this browsing occurs to avoid unnecessary requests.
Is it possible to invoke a method like forceupdate from ScreenA when ScreenB navigates to Screen A? When screenA is first mounted, data is obtained within the componentDidMount method. If there is a way of "reassembling" every time I navigate to ScreenA, that would resolve too.
Screens are in a DrawerNavigation
Sorry for any mistake, I'm using a translator.

A: The best thing you could do would be to use redux and having your most used data that you need for multiple screens in one spot.
You can read about it at redux's official site : https://redux.js.org/
The other solution if you just need to communicate between these two screen can be done by using react-navigation.
react-navigation offers a HOC named withNavigationFocus. Adding the HOC to your screenA component you can check if it's passing from a blurred state to a focused one
For example:
import {withNavigationFocus} from react-navigation;

...

...

...

componentDidUpdate = prevProps => {
    if( prevProps.isFocused !== this.props.isFocused && this.props.isFocused === true){
        //Update your data in screenA triggering a setState()
    }

}

...

...

...

export default withNavigationFocus(ScreenA);


text:
Q: How to compare dates in a sql script to progress database? We have a field in our progress database which is DATETIME-TZ so an example of the data is "23/05/2019 12:11:16.099" -  I'm need some help to compare dates in this field with an SQL select statement
In progress procedure editor, I can compare dates easily, for example
select date(bond-no) from accadd where date(bond-no) <= Today
This works perfectly, but i need to get this info via sql for a web page and just get an error, even breaking the field down as a substring and making the date back up doesn't seem to work
SELECT date(""bond-no"") FROM accadd WHERE date(""bond-no"") <= Date()
Have tried variations on the above and this too...
DATE(SUBSTRING(""bond-no"",4,2),SUBSTRING(""bond-no"",1,2),SUBSTRING(""bond-no"",7,4))
This should return just dates earlier than today, but just get the old syntax incorrect message, so i'm missing something somewhere
[DataDirect][ODBC Progress OpenEdge Wire Protocol driver][OPENEDGE]Syntax error in SQL statement at or about ") FROM accadd WHERE" (10713)

A: Using the SQL Editor in PDSOE which uses JDBC on a datetime (no -tz) field:
SELECT "bond-no" FROM pub.accadd WHERE "bond-no" <= CURDATE()

To use a static date:
SELECT "bond-no" FROM pub.accadd WHERE "bond-no" <= TO_DATE('5/31/2019')

Or:
SELECT "bond-no" FROM pub.accadd WHERE "bond-no" <= { d'5/31/2019' }

A: You do need to quote the field name because it contains a dash but your sample code has doubled quotes.  Have you tried:
SELECT date("bond-no") FROM accadd WHERE date("bond-no") <= Date()

I'm not sure why you are doing it but I don't think that you need the DATE() function around the "bond-no".  DATE() is a 4gl function so it works when you are at the "procedure editor" and using the embedded SQL but the OpenEdge SQL92 engine does not have a DATE() function.  There is, however, a TO_DATE() function:
  https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/dmsrf%2Fto-date.html%23wwID0EXIOS
The following works with the sports2000 database and using sqlexp (rather than embedded sql at the procedure editor):
select * from pub.order where orderdate < '1/1/1999'

I also added a datetime-tz field called "tstamp", initialized it and tried it like so:
select tstamp from pub.order where tstamp < '1/1/1999'

which worked fine too.


text:
Q: How to set custom property on ics calendar invite BEGIN:VCALENDAR
PRODID:-//Microsoft Corporation//Outlook 14.0 MIMEDIR//EN
VERSION:2.0
METHOD:REQUEST
X-MS-OLK-FORCEINSPECTOROPEN:TRUE
BEGIN:VTIMEZONE
TZID:GMT
BEGIN:STANDARD
END:STANDARD
END:VTIMEZONE
BEGIN:VEVENT
ATTENDEE;CN=test@abc.com;RSVP=TRUE:mailto:test@abc.com
ATTENDEE;CN=test@abc.com;RSVP=TRUE:mailto:test@abc.com
CLASS:PUBLIC
CREATED:20220916T003527
DESCRIPTION:test custom property in email.
DTEND;TZID=GMT:20110420T093502
DTSTAMP:20220916T003527
DTSTART;TZID=GMT:20220916T003527
LAST-MODIFIED:20220916T003527
ORGANIZER;CN=test@abc.com:mailto:test@abc.com
SUMMARY;ENCODING=QUOTED-PRINTABLE:Test Sample custom
TRANSP:OPAQUE
UID:22952194683567780405841975923477846064353531523395013511058263369055782053751411479304767882751767652242148467737398
X-EXTRAPARAMS:Test Extra Param

X-MICROSOFT-CDO-BUSYSTATUS:BUSY
X-MICROSOFT-CDO-IMPORTANCE:1
X-MICROSOFT-DISALLOW-COUNTER:FALSE
X-MS-OLK-AUTOFILLLOCATION:FALSE
X-MS-OLK-CONFTYPE:0
BEGIN:VALARM
TRIGGER:-PT15M
ACTION:DISPLAY
DESCRIPTION:Reminder
END:VALARM
END:VEVENT
END:VCALENDAR

In this we have set X-EXTRAPARAMS value which needs to be shown to user in his calendar but the value is not displayed to the user in his invite.
How can we set the same so that it is displayed to the end user in his calendar?

A: No calendar app will process a header it knows nothing about. If you want to reliably show something to an end user, it has to be either DESCRIPTION or SUMMARY.


text:
Q: Why should the map $-\Delta^{-1}$ be continuous? I'm reading an article by Wei-Ming Ni about the existence of solutions for the elliptic problem $$\Delta u +|x|^\lambda |u|^\tau =0,$$
in the unit ball $\Omega$ in dimension $>2$. I'm looking for solutions in $E=\tilde{H}^1_0$, which means this functions are also radially symmetric and in $H^1_0$. The scalar product is $$\langle u,v \rangle_E = \int_\Omega \nabla u \cdot \nabla v $$
The last step of the proof is based on the definition of a functional $T:E\to E$ such that
$$\langle Tu,v \rangle_E = \int_\Omega |x|^\lambda |u|^\tau v.$$
How do I know such an operator is well-defined?
Moreover, it says it can be written in the form $Tu = -\Delta^{-1} (|x|^\lambda |u|^\tau),$ and it goes on saying that the map $T_1 : H^{-1} \to E$ such that $|x|^\lambda|u|^\tau \mapsto  -\Delta^{-1} (|x|^\lambda |u|^\tau)$ is continuous. I can't get why this should be well-defined (and continuous).

A: First of all, there should be a constraint on the exponent $\tau$ to guarantee certain integrability  conditions. Define
$$n^*:=\frac{2(n+\lambda)}{n-2}, $$
where $n$ denotes the dimension of the ball. Then $E$ embeds continuously in the Banach space $ X:=L^{n^*}(0,1; r^{\lambda+n-1} dr)$. (For a proof of this I refer to this old paper of mine.)
Define $\tau^*:=n^*-1$. (This is the critical Sobolev exponent.) Assume
$$\tau \leq \tau^*. $$
Set $r:=|x|$, $x\in \mathbb{R}^n$. Use  Holder's inequality  for the conjugate exponents $n^*$ and $\frac{n^*}{\tau^*}$  and the Sobolev embedding $E\to X$ to verify that
$$\left\vert\int_\Omega r^\lambda |u|^\tau v dx\right\vert \leq C\Vert u\Vert_E\cdot \Vert v\Vert_E. $$
This proves that $Tu$ defines a linear functional on $E$. The dual of $E$ is $H^{-1}$.
The Laplacian  defines an isomorphism $\Delta E\to H^{-1}$ with inverse  $\Delta^{-1}$. The continuity statement   is proved by observing that the map
$$ E\ni u\mapsto |u|^\tau \in L^{\frac{n^*}{\tau^*}}(0,1, r^{\lambda+n-1} dr). $$
is continuous.


text:
Q: Why does powershell ignore a `r when followed with 15 `t I'm writing a program that outputs a display to the screen containing information on the status of a process running on multiple computers. I've deliberately avoided arrays, objects, and format-table so that I can output each member of the information in a different color based on the status. Example:
Server    Service Status    Latest config backup
------------------------------------------------
Srv01     Running           2021-01-13_1500.bak

The Running will be green, the backup file will be green or red based on the age, etc.
This means a nasty set of:
write-host "`r`t`t`t`t`t`t`t`t`t`t`t`t`t`t`t`t`t`t$servicestatus" -nonewline -foregroundcolor $color

What I've discovered however is that once I hit 15 consecutive `t entries, my powershell window will start to mess up and ignore the initial `r and I end up with text wrapping onto a new line due to reaching maximum screen width.
Server    Service Status    Latest config backup
------------------------------------------------
Srv01     Running
2021-01-13_1500.bak

examples above exaggerated, length not to scale.
If you can suggest a way to put colors in a format-table, I'll happily switch to an object or array or whatever.
Edit:
Please see the below screenshot for illustration.

A: `r (\r in most languages) is the Carriage Return character in PowerShell. To understand what that is you need to know a little bit of history around line endings on different platforms. Once upon a time there were typewriters (yes, the story starts there). The original use of typewriters involved typists both entering a new line AND moving the carriage back to the beginning so that they could start typing at the start of the line. Eventually this became more automated so that typewriters would do both at the click of a button. But enough about typewriters. Some platforms (Windows) kept the history and end their lines with BOTH a new line character (also known as the line feed character) and a carriage return character (the latter representing the physical act of moving the carriage), abbreviated to CRLF; while other platforms (Linux/Mac) dropped the history and kept the only really needed new line character, abbreviate to LF.
So, lines end in either a `r`n or a `n, depending on the platform. However, in PowerShell you can get away with just a `n no matter the platform. The thing is, a `r on its own is ignored, so your code is the same with or without it regardless of the number of tab characters (`t) you use.
For your real issue: PowerShell does automatic line wrapping so either determine the width of things dynamically and pad with spaces to get your alignment or check out PowerShell's builtin custom formatting to see if it would work.


text:
Q: Adding trailing zeros to Timestamp string in HH:MM:SS.ssssss format Consider a string representation timestamp as "2017-06-05T19:27:10.917360". But
if there are continous trailing zeros to above timestamp,  Upstream system truncates zeros for second and milliseconds in above example
 like "2017-06 05T19:27:00.000000"
Is there any formatter available in java to add trailing zero in specific format including separator as : between hours, minutes and seconds.
For example: "2017-06-05" should convert to "2017-06-05T00:00:00.000000"
Edit:- Zeros can be get truncated from any of the field HH, MM, SS. If there are series of zeros at tail for time-stamp it will be truncated

A:     DateTimeFormatter desiredFormatter
            = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS");
    String truncatedDateTimeString = "2017-06-05T19:27";
    LocalDateTime dateTime = LocalDateTime.parse(truncatedDateTimeString);
    String fixedDateTimeString = dateTime.format(desiredFormatter);
    System.out.println(fixedDateTimeString);

This prints

2017-06-05T19:27:00.000000

If also the minutes and hours are missing, we need some more trickery, though. Look into DateTimeFormatterBuilder and its parseDefaulting method. Use square brackets [] in the format pattern string to surround the parts that may be missing. I am not sure what your string will look like if the hours have been truncated — will the T be missing too?
On the other hand the above also works if the string was 2017-06-05T19:27:10.917360, and in this case just prints the same string back.
Also I am not sure which problem you are really trying to solve. Trailing zeroes are redundant, so what is the problem in them being truncated?
Edit: The following method fleshes out what I said about DateTimeFormatterBuilder, its parseDefaulting method and square brackets in the format pattern string:
public static String addTrailingZerosToTimestamp(String timeStamp) {
    DateTimeFormatter truncatedFormatter = new DateTimeFormatterBuilder()
            .appendPattern("uuuu-MM-dd['T'HH[:mm[:ss[.SSSSSS]]]]")
            .parseDefaulting(ChronoField.HOUR_OF_DAY, 0)
            .parseDefaulting(ChronoField.MINUTE_OF_HOUR, 0)
            .parseDefaulting(ChronoField.SECOND_OF_MINUTE, 0)
            .parseDefaulting(ChronoField.NANO_OF_SECOND, 0)
            .toFormatter();
    DateTimeFormatter desiredFormatter
            = DateTimeFormatter.ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSSSSS");
    LocalDateTime dateTime = LocalDateTime.parse(timeStamp, truncatedFormatter);
    return dateTime.format(desiredFormatter);
}

It works with 2017-06-05, 2017-06-05T19, 2017-06-05T19:27, 2017-06-05T19:27:10 and 2017-06-05T19:27:10.917360, but not with 2017-06-05T19:27:10.917.

A: Used below code for the purpose
public static String addTrailingZerosToTimestamp(String timeStamp) {
    String param = timeStamp;
    String newCmitTime = "";
    if (param.length() < 26) {

        String currentCmitDate = param.substring(0, 10);
        if (param.length() <= 11) {
            param = currentCmitDate + "T" + "00:00:00.000000";

        } else {
            String currentCmitTime = param.substring(11, param.length());

            String[] timeSplit = currentCmitTime.split("\\:|\\.");

            switch (timeSplit.length) {
                case 4:
                    newCmitTime = currentCmitTime;
                    break;
                case 3:
                    newCmitTime = currentCmitTime + ".000000";
                    break;
                case 2:
                    newCmitTime = currentCmitTime + ":00.000000";
                    break;
                case 1:
                    newCmitTime = currentCmitTime + ":00:00.000000";
                    break;
                case 0:
                    newCmitTime = currentCmitTime + "00:00:00.000000";
                    break;
            }
            param = currentCmitDate + "T" + newCmitTime;
       }
    } else {
        return param;
    }
    return param;
}


text:
Q: How to stay on page after submission of form I've looked for days to try and find an answer to my specific problem, but I am unable to do so.  Please help.
I have a form on my website that once clicked, should send an email.  I want to do this while staying on the same page and changing the div from a form to an image.
This is the code I've managed to scavenge from the internet.
Please give advice if you can in the most Barney style possible.
Thank you in advance to anyone that may be able to assist.

jQuery(document).ready(function(){

    jQuery('.contact').submit( function() {

$.ajax({
      type: "POST",
      url: "contact-form-handler.php",
      data: dataString,
      success: function() {
        $('#contact_form').html("

");
        $('#message').html("")
        .append("
We will be in touch soon.
")
        .hide();
        });
      }
    });
        return false;

});
<form method="post" action="" name="contact" id="contact" class="w3-container w3-light-grey w3-margin">

      <input class="w3-input w3-border" required name="name" id="name" type="text" placeholder="Name">

      <input class="w3-input w3-border" required name="email" id="email" type="text" placeholder="Email">

      <input id="message" class="w3-input w3-border" required name="message" type="text" placeholder="Message">

    <input type="submit" name="submit" class="button w3-section w3-black w3-ripple" id="submit_btn" value="Send" />

</form>

`

<?php
$errors = '';
$myemail = 'jerry@sitesbyjc.com';//<-----Put Your email address here.
if(empty($_POST['name'])  ||
   empty($_POST['email']) ||
   empty($_POST['message']))
{
    $errors .= "\n Error: all fields are required";
}

$name = $_POST['name'];
$email_address = $_POST['email'];
$message = $_POST['message'];

if (!preg_match(
"/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i",
$email_address))
{
    $errors .= "\n Error: Invalid email address";
}

if( empty($errors))
{
 $to = $myemail;
 $email_subject = "Contact form submission: $name";
 $email_body = "You have received a new message. ".
 " Here are the details:\n Name: $name \n Email: $email_address \n Message: \n $message";

 $headers = "From: $myemail\n";
 $headers .= "Reply-To: $email_address";

 mail($to,$email_subject,$email_body,$headers);

}
?>

A: The <form> has it as a default behaviour, to redirect the user to the URL on submit. The URL taken from action attribute.
In order to prevent this redirection, you have to tell the browser to: "DO NOT redirect".
Short: e.preventDefault()
Long: In the submit callback, your function take a parameter. Simply name it like: e. This is an object, and it has a function preventDefault. This function prevents the default behaviour: redirect. Do this call in the first row of the callback function.

A: If I understand your question, You need to use preventDefault() when you call the AJAX In order to prevent the submission (by default), so you can do something like this:
jQuery(document).ready(function(){
    jQuery('.contact').submit( function($e) {

        $e.preventDefault();
        $.ajax({
            type: "POST",
            url: "contact-form-handler.php",
            data: dataString,
            success: function() {
                $('#contact_form').html("

");
                $('#message').html("")
                .append("
We will be in touch soon.
")
                .hide();
            });
        }
    });
    return false;

});

Learn more about preventDefault(), and also about defaultPrevented on MDN.

A: Well you can attach the event handler to your submit button and change the submit button to a simple button, so it will not submit the form when it is clicked. The button code can be changed to:
<input type="button" name="submit" class="button w3-section w3-black w3-ripple" id="submit_btn" value="Send" />

The event handling code can be changed to:
jQuery('#submit_btn').submit( function() {

};


text:
Q: Acceso a un array que está dentro de una clase C++ No he encontrado modo de tener acceso al array que está dentro de mi clase heredada. ¿Me podrían ayudar a obtener acceso al array?¿Cómo podría hacerse?
class FacultadMecanica:public Universidad
{

    private:

    public:

        void CarrerasFacultadMecanica(){
            string *Carreras;
            Carreras=new string[2];
            Carreras[0]="Ing.Quimica";
            Carreras[1]="Ing.Mecanica";
            Carreras[2]="Ing.Electrica";
        }

};

Edit:
Gracias por hacerme caer en cuenta los errores que cometi :)
Aqui dejo el codigo mas completo,desde main intento obtener los valores del array pero da error en las lineas indicadas.
    // Example program
#include <iostream>
#include <string>
using namespace std;

class Persona
{

private:

public:

void CarrerasArry(){string *Carreras;Carreras=new string[2];Carreras[0]="Ing.Quimica";Carreras[1]="Ing.Mecanica";}

};

int main()
{

Persona Datos;

//En las dos lienas siguientes da erro :

cout<<Datos.Carreras[0]<<endl;

cout<<Carreras[0]<<endl;

}

A: Como norma general, en C++ hay dos formas posibles de que una función devuelva un resultado:

*

*Con un tipo de retorno.

*En un argumento por referencia o puntero.

Lo primero a comentar, antes de entrar en detalles sobre cómo devolver un dato, es que tienes un error garrafal en tu función:
void CarrerasFacultadMecanica(){
  string *Carreras;
  Carreras=new string[2];
  Carreras[0]="Ing.Quimica";
  Carreras[1]="Ing.Mecanica";
  Carreras[2]="Ing.Electrica"; // <<<--- AQUI!!!
}

Si Carreras lo preparas para admitir 2 objetos de tipo string no puedes pretender que en dicho arreglo entren tres elementos. Si tu creas un arreglo tal que int* arreglo = new int[10] has de ser consciente que arreglo únicamente va a admitir 10 enteros, accesibles éstos con los índices 0 a 9 y no 0-10). Este error provoca que pises memoria de tu propio programa, haciendo que éste se pueda comportar de forma errática.
Para evitar este tipo de problemas suele ser recomendable usar los contenedores de C++. En tu caso lo más lógico sería usar std::vector. Con esta solución ya no tendrías que preocuparte del tamaño del arreglo:
void CarrerasFacultadMecanica(){
  std::vector<string> Carreras;
  Carreras.push_back("Ing.Quimica");
  Carreras.push_back("Ing.Mecanica");
  Carreras.push_back("Ing.Electrica");
}

Volviendo a tu duda, para devolver un resultado generado dentro de una función hay, como norma general, dos posibles soluciones:

*

*Devolver el resultado usando el retorno de la función.

*Almacenar el resultado en un argumento, siendo éste un puntero o una referencia.

El caso más común es el primero y, aplicado a tu programa la solución podría quedar tal que:
string* CarrerasFacultadMecanica(){
  string *Carreras;
  Carreras=new string[3];
  Carreras[0]="Ing.Quimica";
  Carreras[1]="Ing.Mecanica";
  Carreras[2]="Ing.Electrica";

  return Carreras;
}

Como te he comentado, también podría almacenarse en un argumento, en este caso has de ser consciente que el argumento ha de ser una referencia o un puntero, es decir, ha de añadir un nivel de indirección a la variable. Dado que la variable a devolver es un arreglo, arreglo que inicializas con new todo sea dicho, necesitarías un puntero doble:
void CarrerasFacultadMecanica(string** Carreras){
  *Carreras=new string[3];
  *Carreras[0]="Ing.Quimica";
  *Carreras[1]="Ing.Mecanica";
  *Carreras[2]="Ing.Electrica";
}

Esta solución (aplicada así tal cual) plantea ciertas complicaciones. Habría que decidir, por ejemplo, qué hacer si a la función le llega un puntero que ya está inicializado. ¿Hay que borrarlo o basta con ignorar su estado anterior? Cada opción tiene implicaciones que habría que analizar en detalle.
Sin embargo, si hacemos caso a la recomendación que te he propuesto anteriormente y usamos contenedores de la stl la solución se torna más sencilla:
void CarrerasFacultadMecanica(std::vector<string>& Carreras){
  Carreras.clear(); // Borramos lo que haya en el vector
  Carreras.push_back("Ing.Quimica");
  Carreras.push_back("Ing.Mecanica");
  Carreras.push_back("Ing.Electrica");
}

Devolver un resultado a través de un argumento puede tener sentido en aquellas situaciones en las que una función ha de devolver varios tipos de resultados diferentes. Dado que mediante el return únicamente podemos devolver un tipo de resultado una posible solución es usar los argumentos para devolver el resto. Aunque insisto que es una posible solución.
Habría otras soluciones, como almacenar el resultado en la clase y ofrecerlo a través de un getter, pero a falta de más detalles no veo necesario desarrollar esa parte.


text:
Q: PuTTY Remote Port Forwarding not connecting - Server refused? So I'm at work and we have port 80/443 blocked. I'm trying to get access to the internet via SSH Tunnel. I'm currently connected to a VPN that gives me access to the external network but of course I can't browse. So I'm trying to connect to my SSH Server at home using putty following this tutorial http://anotheritblog.net/2012/11/26/ssh-tunneling-on-windows-with-putty/. My server is listening on port 222 and does have the GatewayPorts yes option configured but PuTTY is telling me it's disabled on my server when it isn't?
2016-03-16 11:09:08 Requesting remote port 80 forward to myserver.com:222
2016-03-16 11:09:08 Remote debug message: Server has disabled port forwarding.
2016-03-16 11:09:08 Remote port forwarding from 80 refused

Since I'm forwarding port 80 I thought maybe it was a firewall issue on my server so I added this rule to IPTABLES
# iptables -A INPUT -p tcp --dport 80 -j ACCEPT

but this did not resolve the problem. I even changed the GatewayPorts yes to GatewayPorts clientspecified but that also did not resolve the problem. Any ideas?

A: If you are getting a message indicating the server has disabled port forwarding do you have AllowTCPForwarding no in the SSHD configuration file? The configuration file will likely be /etc/ssh/sshd_config on a Linux SSH server. If you do, change it to AllowTCPForwarding yes and restart the SSH server service.
Did you configure PuTTY to use a SOCKS proxy connection and then configure your browser to use the SOCKS proxy connection? For web access on ports 80 (HTTP) and 443 (HTTPS) that is the way I normally access websites via a tunneled SSH connection.

A: From the log, you're trying to create a reverse tunnel from the destination of the putty session back through putty and to myserver.com on port 222.  I'm a bit confused as to how you would use this to browse the Internet from the PC running putty.  So perhaps I'm confused as to what you're trying to do, or how you've set things up.  There are several types of VPN, so it would be helpful to name the product or describe the nature of the VPN.
I've seen this specific message when the remote server already had a session listening on the remote port in question - in this case, port 80.  However, it is likely to also be a problem if the remote user account you used to login does not have permission to create a socket listening on port 80.  Under UNIX and Linux, listening sockets that accept connections on ports below 1024 can only be created by the root user.
Try changing the remote port number from 80 to something like 8080 and see if you continue to get the same error.

A: Indirectly related to the question -- just in case someone comes across the same problem:
At some point I started to receive the following errors when trying to run port forwarding
Event Log: Local port 2001 SOCKS dynamic forwarding failed: Network error: Permission denied

After struggling with that for a while, installed Bitwise SSH where the error would appear as:
Failed to enable SOCKS/HTTP proxy forwarding on 127.0.0.1:2001: Address is already in use; bind() in ListeningSocket::StartListening() failed: Windows error 10013: An attempt was made to access a socket in a way forbidden by its access permissions.

After that it was clear that the port is in use - although it didn't show up in CurrPorts. So I resolved that by changing the port number


text:
Q: Potential energy in Schrödinger equation In the Schrödinger equation what does potential
energy $V$ mean?
In harmonic oscillation, it is the potential energy of the particle itself.
However, in a potential well, it
looks like the potential is an external energy environment.
What does $V(x)$ represent?

A: The potential (to be more precise, the gradient of the potential) represents the force acting on a particle as a consequence of its position. In solid state physics, for example, it might be used to represent the electromagnetic forces acting on an electron. For most real life applications, the Schrödinger equation can't be solved analytically- you have to use numerical techniques to find solutions. Even then, it is very difficult to solve the equations by explicitly accounting for all the individual particle in the system being considered, so instead physicists use simpler models. A common technique is to adopt a 'one-electron' model of a solid, in which you solve the Schrodinger equation for a single electron, taking into account its interactions with all the other electrons and ions in the solid by replacing them with a background potential that simulates their effects.


text:
Q: How to set first and second child of ordered list to have the same indentation? What I'm trying to achieve is:
1 text
1.1 text
2 text
2.1 text
    2.1.1 text
    2.1.2 text
3. text
3.1 text
    3.1.1 text
    3.1.2 text
    3.1.3 text

The parent i.e 1, 2, 3 will not have any indentation. Same goes to its first child i.e 1.1, 2.1, 3.1 as you can see on code above.
My current code:


text:
Q: Entity Framework not caching objects I've got a list of "cases" using a stored procedure.
List<Case> tmp = context.Case_Search(Query).ToList();

When i display this list on the page it references a linked table called "CaseContacts" this makes EF run an SQL statement for each case.
As i can't use include on a stored procedure i've tried to pre-load the linked objects using:
int[] ids = tmp.Select(x => x.ID).ToArray();
CaseContact[] CCs = context.CaseContacts.Where(x => ids.Contains(x.CaseID)).ToArray();

However EF is still going to the DB for each linked CaseContact.
Do i need to tell EF to use the cached version? I assumed if the object had previously been loaded EF would use the object rather than another trip to the DB.
Update:
I've changed my code to switch off lazy loading before i run my code and to switch it back on afterwards and it seems to do what i expect 1-2 sql trips instead of 200+.
context.Configuration.LazyLoadingEnabled = false;
List<Case> tmp = context.Case_Search(Query).ToList();
context.Configuration.LazyLoadingEnabled = true;

It doesn't even need the extra query to load the linked property.  Any downsides to this?


text:
Q: How to format properly when converting from string to bytes Is there a way to keep the formatting when converting from a string to bytes.
For example:
string = "Hello \n my \n name \n is \n foo"

bites = bytes(string, 'utf-8')

And I would like the bites variable to format in the same way the string does where there is a new line after every \n

A: This is because the default method __str__ method of bytes is implemented in the way so that 0x0A (the newline character is encoded by 0x0A in ASCII) are printed as \n.
If you want it to print as a newline character, you can implement your own bytes class this way:
class MyBytes(bytes):
    def __str__(self):
        return self.decode()
string = "Hello \n my \n name \n is \n foo"
bites = MyBytes(string, 'utf-8')

Then if you print(bites); it gives you the new line.

A: You're probably looking for a "raw string" prefixed by r
>>> print(r"my raw\nstring")
my raw\nstring
>>> print("my raw\nstring")
my raw
string

A: A bytes object is different from a str object.
The print method will behave different depending in the object passed to it, since it calls the __str__ method from the object. So, for a bytes object it prints the string without transforming special characters, like newlines to actual newlines.
>>> print(bites)
b'Hello \n my \n name \n is \n foo'
>>> a = bites.__str__()
>>> a  # this is a string with newlines scaped
"b'Hello \\n my \\n name \\n is \\n foo'"
>>> isinstance(a, str)
True
>>> isinstance(bites, bytes)
True

If you want to print bytes with newlines the best alternative would be to transform it to a string
>>> a = bites.decode('utf-8')
>>> isinstance(a, str)
True
>>> a
'Hello \n my \n name \n is \n foo'
>>> print(a)
Hello
 my
 name
 is
 foo


text:
Q: Построение графика с отображением времени через заданный интервал Есть датасет, содержащий массив временных меток в формате (YYYY-MM-DD HH:MM:SS) и массив чисел с плавающей запятой, каждый из которых соответствует значению в массиве timestamp.
Нужно построить график изменения чисел с плавающей запятой от времени так, чтобы по оси х отметки времени стояли через суточный интервал. График с недельным интервалом строится кодом
import pandas as pd
import matplotlib.pyplot as plt
from dateparser import parse

data = pd.read_csv('dataset.csv', parse_dates=[0], encoding='utf-8', decimal=',', header=None)
data["Date_parsed"] = data[0].map(parse)
x = data["Date_parsed"]
y = data[2]
plt.figure(figsize=(18,8))
plt.title("Изменение величины по времени")
plt.ylabel("Величина")
plt.plot(x, y)

Попытка построить график, разбив его между минимальным и максимальным значением дат от x.min() до x.max() завершается ошибкой и непонятно, как при таком формате даты объявлять шаг в сутки.
x_range = list(range(x.min, x.max))

Как отобразить все значения, какие есть, но нарисовать метки по оси x с частотой в сутки?


text:
Q: Как изменить маршрут к bootstrap.css в Yii2? Даже если в AssetBondle все выключить, то все равно грузятся фалы bootstrap.css и bootstrap.js. Я в принципе не против, чтоб они грузились, но я собираю свой bootstrap из less файлов, и мне всего-то хотелось бы изменить путь к этому файлу. Как это сделать правильно?
Подключаю только свои файлы css в AssetBundle:
namespace app\assets;

use yii\web\AssetBundle;

/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class RazzAsset extends AssetBundle
{
    public $basePath = '@webroot';
    public $baseUrl = '@web';
    public $css = [
        'css/my_bootstrap.css',
        'css/main.css',
    ];
    public $js = [

    ];

}

На странице грузится два bootstrap файла:
<link href="/yii2/css/my_bootstrap.css" rel="stylesheet">
<link href="/yii2/css/main.css" rel="stylesheet">
<link href="/yii2/assets/b6651f1/css/bootstrap.css" rel="stylesheet">
<link href="/yii2/assets/4327c007/toolbar.css" rel="stylesheet"></head>

Бесит это навязывание своего способа добавления стилей в Yii2. Хотя, если решить эту проблему, может, и будет удобно.

A: В конфиг web.php
Добавьте
'components' => [
    'assetManager' => [
        'bundles' => [
            'yii\bootstrap\BootstrapAsset' => [
                'css' => []
            ]
        ]
    ],
    ...
],

Выключит bootstrap.css для всех виджетов.


text:
Q: Найти в строке текст и заменить его на return функции Есть строка вида
$str = 'Привет, это мой project(1, 10) проект';

Мне нужно чтобы там произошло выполнение функции:
function project($ot, $do) {
     .....
     return $res;
}

И соответственно чтобы в тексте было уже то что вернула функция.
P.S. эта строка выводиться из базы.
Хотелось бы что-то вроде:
str_replace('project(*), function project(*, *), $str)

A: посмотрите в сторону preg_replace_callback. Я думаю, это то, что вам нужно.
<?php

$str = preg_replace_callback('/(\s?)project\s?\(\s?(\d+)\s?,\s?(\d+)\s?\)(\s?)/ui', function($arr){return $arr[1] . project($arr[2], $arr[3]) . $arr[4];}, $str);


text:
Q: problema al obtener el numero del dia de la semana en sql server Tengo la siguiente consulta
SELECT DATEPART(WEEKDAY,'2018-01-18')

lo que quiero es ejemplo que si ese dia es jueves ejemplo me devuelva un 3 porque en la tabla que tengo los dias empiezan desde el 0 hasta el 6 el campo es de tipo int y se llama DAYID, por cuando utilizo la consulta antes mencionada me devulve el numero 5

A: Sql server enumera los días de la semana del 1 al 7 empezando por el domingo como día 1, sábado día 7, para lograr lo que necesitas usa:
--Indicamos al motor que el lunes lo considere como el primer dia de la semana
SET DATEFIRST 1
--Al enumerar los dias de la semana del 1 al 7 necesitamos
--restar 1 a la enumeración para que concuerde con la tabla que tienes
SELECT (DATEPART(WEEKDAY,'2018-01-18') - 1)  -- resultado 3
SELECT (DATEPART(WEEKDAY,'2018-01-15') - 1)  -- resultado 0

SQL Fiddle

A: Si lo que quieres es una función (no sé si recomendarte) que retorne el día de la semana, sin considerar la respuesta anterior (la cuál es válida). Tendrías que hacer, por ejemplo:
CREATE FUNCTION UDF_DIASEMANA(
    @FECHA DATETIME
)
RETURNS INT
AS
BEGIN
    DECLARE @DIA INT = DATEPART(WEEKDAY, @FECHA)

    RETURN @DIA + CASE WHEN @DIA >= 2 THEN -2 ELSE 5 END
END
GO

SELECT
    DBO.UDF_DIASEMANA('20180115'),
    DBO.UDF_DIASEMANA('20180116'),
    DBO.UDF_DIASEMANA('20180117'),
    DBO.UDF_DIASEMANA('20180118'),
    DBO.UDF_DIASEMANA('20180119'),
    DBO.UDF_DIASEMANA('20180120'),
    DBO.UDF_DIASEMANA('20180121'),
    DBO.UDF_DIASEMANA('20180122')

Obtendrás:

+---+---+---+---+---+---+---+---+
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 0 |
+---+---+---+---+---+---+---+---+

DEMO


text:
Q: IP tables gateway I am trying to make an iptables gateway. I ordered 3 dedicated server from my hosting company all with dual nics. One server has been given all the ip addresses and is connected directly to the internet and has its other nic connected to a switch where the other servers are all connected also. I want to setup iptables so for example the ip address 50.0.2.4 comes into my gateway server it fowards all the traffic to a private ip address using the second nic. This way the second nic can do what ever it needs and can respond back also. I also want it setup that if any of the other servers needs to download anything over the inernet it is able to do so and by using the same ip address that is used for its incomming traffic.
Lastly I would like to be able to setup dns and other needed networking stuff that i maybe not thinking about.

A: I use firewall builder to put together a template iptables with NAT for you.
Gateway machine

*

*External Interface: eth0 (IP:50.0.2.4)

*Internal Interface: eth1 (IP:192.168.1.1

*Services forward to 192.168.1.10: imap, imaps, pop, pops, smtp, smtps

*Services forward to 192.168.1.20: http, https

Internal machine 1

*

*Interface: eth0 (IP:192.168.1.10)

Internal machine 2

*

*Interface: eth0 (IP:192.168.1.20)

    IPTABLES="/sbin/iptables"

    # ================ Table 'filter', automatic rules
    # accept established sessions
    $IPTABLES -A INPUT   -m state --state ESTABLISHED,RELATED -j ACCEPT
    $IPTABLES -A OUTPUT  -m state --state ESTABLISHED,RELATED -j ACCEPT
    $IPTABLES -A FORWARD -m state --state ESTABLISHED,RELATED -j ACCEPT

    # ================ Table 'nat',  rule set NAT
    #
    # Rule 0 (NAT)
    #
    echo "Rule 0 (NAT)"
    #
    $IPTABLES -t nat -A PREROUTING -p tcp -m tcp -m multiport   -d 50.0.2.4  --dports 143,993,110,995,25,465 -j DNAT --to-destination 192.168.1.10
    #
    # Rule 1 (NAT)
    #
    echo "Rule 1 (NAT)"
    #
    $IPTABLES -t nat -A PREROUTING -p tcp -m tcp -m multiport   -d 50.0.2.4  --dports 80,443 -j DNAT --to-destination 192.168.1.20
    #
    # Rule 2 (NAT)
    #
    echo "Rule 2 (NAT)"
    #
    $IPTABLES -t nat -A POSTROUTING -o eth0   -s 192.168.1.0/24  -j SNAT --to-source 50.0.2.4

    # ================ Table 'filter', rule set Policy
    #
    # Rule 0 (eth0)
    #
    echo "Rule 0 (eth0)"
    #
    # anti spoofing rule
    $IPTABLES -N In_RULE_0
    $IPTABLES -A INPUT -i eth0   -s 50.0.2.4   -j In_RULE_0
    $IPTABLES -A INPUT -i eth0   -s 192.168.1.1   -j In_RULE_0
    $IPTABLES -A INPUT -i eth0   -s 192.168.1.0/24   -j In_RULE_0
    $IPTABLES -A FORWARD -i eth0   -s 50.0.2.4   -j In_RULE_0
    $IPTABLES -A FORWARD -i eth0   -s 192.168.1.1   -j In_RULE_0
    $IPTABLES -A FORWARD -i eth0   -s 192.168.1.0/24   -j In_RULE_0
    $IPTABLES -A In_RULE_0  -j LOG  --log-level info --log-prefix "RULE 0 -- DENY "
    $IPTABLES -A In_RULE_0  -j DROP
    #
    # Rule 1 (lo)
    #
    echo "Rule 1 (lo)"
    #
    $IPTABLES -A INPUT -i lo   -m state --state NEW  -j ACCEPT
    $IPTABLES -A OUTPUT -o lo   -m state --state NEW  -j ACCEPT
    #
    # Rule 2 (global)
    #
    echo "Rule 2 (global)"
    #
    # SSH Access to firewall is permitted
    $IPTABLES -N Cid4216X2697.0
    $IPTABLES -A OUTPUT -p tcp -m tcp  -m multiport  --dports 80,443,143,993,110,995,25,465,22  -m state --state NEW  -j Cid4216X2697.0
    $IPTABLES -A Cid4216X2697.0  -d 50.0.2.4   -j ACCEPT
    $IPTABLES -A Cid4216X2697.0  -d 192.168.1.1   -j ACCEPT
    $IPTABLES -A INPUT -p tcp -m tcp  -m multiport  --dports 80,443,143,993,110,995,25,465,22  -m state --state NEW  -j ACCEPT
    #
    # Rule 3 (global)
    #
    echo "Rule 3 (global)"
    #
    # Firewall can connect to anything
    $IPTABLES -A INPUT  -s 50.0.2.4   -m state --state NEW  -j ACCEPT
    $IPTABLES -A INPUT  -s 192.168.1.1   -m state --state NEW  -j ACCEPT
    $IPTABLES -A OUTPUT  -m state --state NEW  -j ACCEPT
    #
    # Rule 4 (global)
    #
    echo "Rule 4 (global)"
    #
    # All other attempts to connect to
    # the firewall are denied and logged
    $IPTABLES -N RULE_4
    $IPTABLES -A OUTPUT  -d 50.0.2.4   -j RULE_4
    $IPTABLES -A OUTPUT  -d 192.168.1.1   -j RULE_4
    $IPTABLES -A INPUT  -j RULE_4
    $IPTABLES -A RULE_4  -j LOG  --log-level info --log-prefix "RULE 4 -- DENY "
    $IPTABLES -A RULE_4  -j DROP
    #
    # Rule 5 (global)
    #
    echo "Rule 5 (global)"
    #
    $IPTABLES -A INPUT  -s 192.168.1.0/24   -m state --state NEW  -j ACCEPT
    $IPTABLES -A OUTPUT  -s 192.168.1.0/24   -m state --state NEW  -j ACCEPT
    $IPTABLES -A FORWARD  -s 192.168.1.0/24   -m state --state NEW  -j ACCEPT
    #
    # Rule 6 (global)
    #
    echo "Rule 6 (global)"
    #
    $IPTABLES -N RULE_6
    $IPTABLES -A OUTPUT  -j RULE_6
    $IPTABLES -A INPUT  -j RULE_6
    $IPTABLES -A FORWARD  -j RULE_6
    $IPTABLES -A RULE_6  -j LOG  --log-level info --log-prefix "RULE 6 -- DENY "
    $IPTABLES -A RULE_6  -j DROP

    echo 1 > /proc/sys/net/ipv4/ip_forward


text:
Q: How to add inertia to widget rotated by swipe offset? (add momentum) For example, I have a widget which is rotated on user swipe using variable dragoffset += details.offset.dx;
How is it possible to add inertia to rotation when swipe ended? E.g. when you release your finger, and object continues to rotate with descending velocity -- just like ListView normally behaves.
Here's some boilerplate code as example:
Widget rotatedWidget() {
    double fingerOffset = 0.0;
    return GestureDetector(
        onHorizontalDragUpdate: (details) {
          setState((){
             fingerOffset += details.delta.dx;
          });
        },
        onHorizontalDragEnd: (details) {
           /// some code to add inertia
        },
        child: Transform.rotate(
          angle: offset,
          child: Container(width: 100, height: 100, color: Colors.blue),
        ));
  }

A: Thanks to @pskink for this solution.
(Edit: Adding physics package import and SingleTickerProviderStateMixin to the class's inheritance as it's needed for an AnimationController to be vsynced to the current class)
import 'package:flutter/physics.dart';

class RotateState extends State<Rotate> with SingleTickerProviderStateMixin {

 AnimationController ctrl;

  @override
  void initState() {
    super.initState();
    ctrl = AnimationController.unbounded(vsync: this);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onPanUpdate: (d) => ctrl.value += d.delta.dx / 100,
      onPanEnd: (d) {
        ctrl.animateWith(
          FrictionSimulation(
              0.05, // <- the bigger this value, the less friction is applied
              ctrl.value,
              d.velocity.pixelsPerSecond.dx / 100 // <- Velocity of inertia
          ));
        },
      child: Scaffold(
        appBar: AppBar(
          title: Text('RotatedBox'),
        ),
        body: AnimatedBuilder(
          animation: ctrl,
          builder: (ctx, w) {
            return Center(
              child: Transform.rotate(
                angle: ctrl.value,
                child: Container(width: 100, height: 100, color: Colors.blue),
              ),
            );
          },
        ),
      ),
    );
  }
}


text:
Q: Pandas giving KeyError when merging on df2.columns I've got two dataframes. First one is empty but with columns defined:
Empty DataFrame
Columns: [ID, 3120, 3121, 3122, 3123, 3124, 3125, 3126, 3127, 3128, 3129, 3130, 3131, 3146, 3147, 3148, 3149, 3150, 3151, 3152, 3153, 3154, 3155, 3156, 3157]
Index: []

Second dataframe is:
    3123    3124    3125    3126    3127
0   A       B       C       D

Later, I will have another dataframe that will be:
    3146    3147    3148    3149    3150
0   X       Y       Z

And so on. What I want is to put all this little dataframes in the first one to get something like:
ID  3120    3121    3122    3123    3124    3125    3126    3127    3128    3129    3130    3131    3146    3147    3148    3149    3150    3151    3152    3153    3154    3155    3156    3157
1                           A       B       C       D                                               X       Y       Z

So what I am doing in my loop is:
df_main.merge(df_i, how='inner', on=df_i.columns)

Where, when i=1:
df_main.columns:

Index(['ID', '3120', '3121', '3122', '3123', '3124', '3125', '3126',
       '3127', '3128', '3129', '3130', '3131', '3146', '3147', '3148', '3149',
       '3150', '3151', '3152', '3153', '3154', '3155', '3156', '3157'],
      dtype='object')

df_i.columns:

Index(['3123', '3124', '3125', '3126', '3127'], dtype='object')

And code is raising this KeyError:
    raise KeyError(key)
KeyError: Index(['3123', '3124', '3125', '3126', '3127'], dtype='object')

How is this possible? df_i.columns is contained and exist in df_main.columns
Thank you in advance!

A: okay one way to do this
df1
  3123 3124 3125 3126  3127
0    A    B    C    D   NaN

df2
  3146 3147 3148  3149  3150
0    X    Y    Z   NaN   NaN

using pd.concat
df = pd.concat([df.drop(df1.columns.append(df2.columns),axis=1),df2,df3], sort=True, axis=1)
df = df[['ID', 3120, 3121, 3122, 3123, 3124, 3125, 3126, 3127, 3128, 3129, 3130, 3131, 3146, 3147, 3148, 3149, 3150, 3151, 3152, 3153, 3154, 3155, 3156, 3157]] # for reordering
df.fillna('', inplace=True)

Output
    ID 3120 3121 3122 3123 3124 3125 3126 3127 3128 ...  3148 3149 3150 3151  \
0                      A    B    C    D           ...     Z

  3152 3153 3154 3155 3156 3157
0

[1 rows x 25 columns]


text:
Q: How many 1080p Monitors i can connect to MacBook pro 13 inch 2019 model with 4 thunderbolt port? Can anyone please help me to connect my MacBook pro 13 inches with 4 thunderbolts to 3 external monitors ( one U2414H and two P2419H) ?
I tried connecting them using three type-c to HDMI convertors but I can only power any two of them with or without my built-in MacBook pro display.
any help would be appreciated, guys
my mac info:

A: The 13" MacBook Pro 2019 supports 2 external monitors (in addition to the built-in monitor).
If you want to connect more monitors, you'll external equipment such as a DisplayLink adapter or an eGPU for hooking up extra monitors.


text:
Q: Title update directly from the WP7app My problem is:
I would like to allow my user to pin single element information from the WP7app (like information from listbox item) to the Live tile. How to do that? TileScheduler only updates image and push notification needs exclusive webservice to handle them. I would like allow my app to set the tile value.
Please, help.
xawer.

A: You have control of the image used. You can add text to an image using WriteableBitmap.Render().
If you're ok with waiting one hour for the first TileScheduler update to take place you can do this locally, however if you want a more responsive result you will, as you noted, need to implement a web service and the PNS.


text:
Q: Error: Can't set headers after they are sent. at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:356:11) I am developing a basic app with NodeJs and ZeroMQ, however I am currently facing an error, which i cannot seem to rid of. I have read solutions that suggest the program "sends" more than once, however i only have one "send" method. Please see code below...
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
var server_port = "3000";

/** app settings **/
var zeromq = require("zeromq");
var socket = zeromq.socket("req");/* sends request */
var protocol = "tcp://";
var ip = "192.000.0.000"; //server
var socket_port = "9998";
var url = protocol + ip + ":" + socket_port;

/*header settings*/
app.use(function (request, response, next) {
    response.setHeader('Content-Type', 'text/plain');
    response.setHeader( 'Access-Control-Allow-Origin', 'http://localhost:8888');
    response.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
    response.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
    response.setHeader('Access-Control-Allow-Credentials', true);
    next();
});

app.use(bodyParser());

/** paths **/
app.post('/request', function (request, response) {
    var command = request.body;

    //connect to port
    socket.connect(url, function (error) {
        if (error) {
            console.log("connection error : ", error);
            process.exit(0);
        }
    });

    //response to front end
    socket.send(JSON.stringify(command));

    //recieve request
    socket.on('message', function (message) {

        //output message to console
        console.log("Recieved message @ : " + (new Date().toDateString()) + " : " + message.toString());

        //send response
        response.status(200).send(JSON.stringify(message.toString()));
    });
});

// test purposes
app.get('/recieve', function (request, response) {
    response.send("{ 'led': 'on' }").end();
});

/** start app **/
app.listen(server_port);

console.log("Server started on port: " + server_port);

A: The problem is here :
response.status(200).send(JSON.stringify(message.toString()));
response.end();

.send() and .end() both reply to the browser and are redundant. Just use one or the other, but not both in a row.
As an aside, you stringify a string, so you really make sure that the front-end doesn't get a nice JSON to work with (that you surely re-parse to JSON afterwards). I don't know why everyone always stringify everything and refuse to work with JSON? Captain?


text:
Q: Select rows from a data frame where two elements match on a single row from another data frame Im trying to make a new data frame that has all rows from data frame A where both the values for column x and column y match on one row from data frame B.
I tried finding the index of the rows from data frame B where only the value for column x matched to try and see if i could then match the values for y on those indices but i was not able to retrieve the indices. Also tried iterrows to match the two conditions but that was also unsuccessful.
A={'x':[1,2,3,4],'y':[5,6,7,8]}
B={'x':[1,2,3,10],'y':[5,6,90,8]}

i want code to return
{'x':[1,2],'y':[5,6]}

A: Suppose you have 2 dataframes:
A=pd.DataFrame({'x':[1,2,3,4],'y':[5,6,7,8]})
B=pd.DataFrame({'x':[1,2,3,10],'y':[5,6,90,8]})

Then you can do:
idx = A.x == B.x
idy = A.y == B.y
ID = idx&idy
A[ID]
    x   y
0   1   5
1   2   6

Or, you may convert it to the desired output:
A[ID].to_dict("list")
{'x': [1, 2], 'y': [5, 6]}


text:
Q: How do I create a LinQ query with an "IN" statement like SQL? I need a LinQ query that does the same thing as below...but I can't seem to figure it out. (I'm using C#)
SELECT * FROM Groups WHERE Id IN(
SELECT DISTINCT [GroupId] FROM [MyTable].[dbo].[Detail])

NOT This (as marked a duplicate question)
SELECT * FROM Users WHERE User_Rights IN ("Admin", "User", "Limited")
If they are the same then so be it...I'll of course take that as the answer.

A: If Groups collection was in groups and detail was in detail then
 groups.Where(z => detail.Any(x => x.groupid == z.id));

This checks each element of groups to see if the id property is the same as any groupid property of the detail collection.

It is important to note this might not be the best solution for your use case -- if your groups are very large then I would consider making it into a list and using contains -- that will give you hash performance.  For smaller size groups the cost of making the list will be bigger than the performance gain.
 var idlist = details.Select(x => x.groupid).ToList();

 groups.Where(z => idlist.Contains(z.id));


text:
Q: Typescript does not allow to access a property dynamically I have some issues when I try to access  my object property in typescript:

const total = (type: string) => {
  return {
    status: 'Total',
    test: data?[type].total,
  };
};

total('first')

This is how my data looks:

data: {
  first: {
    total: 15
  },
  second: {
    total: 515
  }
}

Trying to access the property i get TS2339: Property 'total' does not exist on type 'string[]'. Why i get this and how to solve the issue?

A: You are looking for for optional chaining operator here and
data?.[type] is correct syntax.
Also TS will throw an error if just try to read object field with object[property]. It assumes correctly that it's not possible to read object property with just any string, it requires more specifics types. Have a look at code below.
interface Data {
  first: {
    total: number
  },
  second: {
    total: number
  }
}

const data: Data = {
  first: {
    total: 15
  },
  second: {
    total: 515
  }
}

const total = (type: keyof Data) => {
  return {
    status: 'Total',
    test: data?.[type].total
  }
}

total('first')

Working snippet


text:
Q: .NET Core bin path changes randomly on Amazon Linux 2 We deploy our ASP.NET Core applications in Amazon Linux 2 using AWS Auto Scaling
When the linux services were created, the path for the dotnet binary was configured as: ExecStart=/usr/bin/dotnet ...
That path worked fine until some months ago, on new auto scaled instances the dotnet binary path randomly changed to /usr/bin/local/dotnet forcing to update the systemd service files with the new path.
Today one of our instances was refreshed with a new one by AWS and the services didn't start because the bin path changed again to /usr/bin/dotnet
I am unable to find in documentation or changelogs on why this binary path is being changed.
For reference, ASP.NET Core is being installed automatically on the instances by an install script containing:
sudo rpm -Uvh https://packages.microsoft.com/config/centos/7/packages-microsoft-prod.rpm
sudo yum install -y aspnetcore-runtime-5.0

We're in the process of updating our application to .NET 6 as .NET 5 will no longer be receiving support, but I don't think that would be the cause for this issue.
Any insights on why this path is being changed randomly?
If this can't be prevented, any way to specify in the .service file to use dotnet on whichever path it's found? I think that setting ExecStart=dotnet ... will not find the binary.

A: Could you just figure it out in the installation script?
Something like filling the path with --DOTNET_PATH--.
Installing dotnet the normal way and then using which dotnet and replacing it.
The Service file
ExecStart=--DOTNET_PATH--

The installation script
sudo rpm -Uvh https://packages.microsoft.com/config/centos/7/packages-microsoft-prod.rpm
sudo yum install -y aspnetcore-runtime-5.0
sed -i "s/--DOTNET_PATH--/$(which dotnet)/" /path/to/servicefile

Alternatively, figuring it out which file exists and then symlinking one to the other would also work.


text:
Q: Invoke g++/clang from python to compile a python string I am currently writing an application that generates C++ code into a python string. I want to compile this code and create a .so from it.
The easiest way is to write the python string containing the code into a file, and use subprocess.Popen(...) to invoke g++/clang to compile it into a .so, but I would rather not write the string to disk first and have that as an intermediate step.
I have looked online for g++/clang bindings in python, and they were all simply parsers(for example, libclang), and do not actually compile anything.
Is there an alternative method that I'm missing here? Or do I need to bite the bullet and use subprocess?

A: Mat's comment in python3 using the input argument of subprocess.run
This uses the fact that g++ accepts code from standard input when passed the file name -. Because there is no file name suffix, the compiler cannot guess the language, so it should be specified with -x.
The encoding argument was added to make the input argument accept a string, otherwise it expects a bytes-like object.
#!/usr/bin/python3

import subprocess
import locale

def compile_cpp(cpp_code_as_string, exe_name):
    command = ('g++', '-xc++', '-', '-o', exe_name)
    subprocess.run(command, input=cpp_code_as_string, encoding=locale.getpreferredencoding())

hello = '''
#include <iostream>

int main() {
  std::cout << "Hello World!\\n";
  return 0;
}
'''

compile_cpp(hello, 'hello')
subprocess.run(['./hello'])


text:
Q: SonarQube issue resolve using @NotNull and @JsonProperty together I'm working on sonarQube issues in my company, on previously developed module I've to modify variable names as a part of fix. So I've applied @JsonProperty but I can't remove @NotNull as well. So my problem is @JsonProperty doing it's job but not null validation failing (THROWING EXCEPTION). Please help me with solution should I apply both annotation's. We are using spring mvc, and restful call to this dto. For now I don't want to make any validation in controller.
public class CustomerImpl extends Customer {

    @NotNull(message = "should not be null")
    @JsonProperty("customer_Id")
    private int customerId;

    @NotNull(message = "should not be null")
    @JsonProperty("first_name")
    private String firstName;

    @NotNull(message = "should not be null")
    @JsonProperty("last_name")
    private String lastName;

    public int getCustomerId() {
        return customerId;
    }

    public void setCustomerId(int customerId) {
        this.customerId = customerId;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

}


text:
Q: Creating Page Border for Single Page only I am digitizing a book and there is  only a single page which has page border as shown in the attached image.
How can I create border to a single page? Is there a library where I can choose a border from?

A: One option would be to use the fancybox package. Analogous to \thispagestyle{...}, it provides \thisfancyput(<x>,<y>){<LR stuff>}. Here is a very short example.
\documentclass{article}
\usepackage{fancybox}% http://ctan.org/pkg/fancybox
\usepackage{lipsum}% http://ctan.org/pkg/fancybox
\begin{document}

\thisfancyput(3.25in,-4.5in){%
  \setlength{\unitlength}{1in}\fancyoval(7,9.5)}%
\lipsum[1-20]

\end{document}

You can add various components sequentially by using the starred version * of \thisfancyput.
It is extremely limited in its capability with respect to tikz/pgf.

Here is another alternative, using pst-node (from the pstricks bundle). Using eso-pic to tap into the "background" of a specific page via \AddtoShipoutPictureBG*, you can be creative with any pstricks-related code:

\documentclass{article}
\usepackage{pst-node}% http://ctan.org/pkg/pstricks
\usepackage{xcolor}% http://ctan.org/pkg/xcolor
\usepackage{eso-pic}% http://ctan.org/pkg/eso-pic
\usepackage{lipsum}% http://ctan.org/pkg/lipsum
\begin{document}

\begin{titlepage}
  \AddToShipoutPictureBG*{%
    \begin{pspicture}(\paperwidth,\paperheight)
      \psset{xunit=\the\paperwidth,yunit=\the\paperheight,nodesep=2cm}
      \pnode(1,1){page.northeast}%
      \pnode(0,0){page.southwest}%

      \psframe[linestyle=dashed,linewidth=10pt,linecolor=orange!50]([angle=45]page.southwest)([angle=-135]page.northeast)
    \end{pspicture}
  }
  \centering
  \huge
  Your title text

  Author

  more text
\end{titlepage}

\lipsum[1-10]
\end{document}

This does require a latex -> dvips -> ps2pdf compilation sequence though. xcolor provided an advanced colour selection interface, while lipsum provides dummy text Lorem Ipsum style.

A: the "glisterings" column by peter wilson in tugboat 32:2 (2011) includes instructions for a border using fleurons from the (free) Web-O-Mints font, with latex support provided by Maurizio Loreti.  the general approach is to define an "evenfoot" and an "oddfoot" by stringing together appropriately matching fleurons in a picture environment and using the \put command to move the frame into the desired location. it is placed on the desired page using the standard \pagestyle technique.
since this column is in the most recent issue of tugboat, at the moment it is accessible only to tug members, but i will see if i can negotiate an exception.

A: You can make a title page like this using TikZ decorations e.g. inside a titlepage environment. TikZ allows for a lot of different decorations and you can even define your own. It also allows for easy use of colors etc.
Example to show the principle:
\documentclass{book}

\usepackage{tikz}
\usetikzlibrary{calc}
\usetikzlibrary{decorations.pathmorphing}

\usepackage{lipsum}% dummy text
\begin{document}

\begin{titlepage}
    \centering
\begin{tikzpicture}[overlay,remember picture]
    \draw [line width=1mm,decorate,decoration={snake
        %,segment length=<length>,amplitude=<length>
        }]
        ($ (current page.north west) + (1cm,-1cm) $)
        rectangle
        ($ (current page.south east) + (-1cm,1cm) $);
    \draw [line width=1mm,decorate,decoration={zigzag
        %,segment length=<length>,amplitude=<length>
        }]
        ($ (current page.north west) + (2cm,-2cm) $)
        rectangle
        ($ (current page.south east) + (-2cm,2cm) $);
\end{tikzpicture}
    \huge
    Your title text

    Author

    more text

\end{titlepage}

\lipsum

\end{document}

A: This kind of thing would probably be easiest to perform with Tikz. Simply draw a path around the border of the page and decorate it as described in chapter 21 of the manual.
edit: I could have sworn I added a link... Well added it now, as for the example, I think Martin's answer already adresses that, so it would be superfluous to add one here now.


text:
Q: Converting the power series from sigma notation to a function? The sigma notation for the power series is equivalent to the following function:
$$\sum_{n=0}^\infty x^n = \frac{1}{1-x}$$
However, given the sigma notation above,
how would one arrive at it's equivalent function?

A: Assume that $|x|<1$, else the series does not converge. Let $S_n = \sum_{k=0}^n x^k$. Then
$$
(1-x)S_n = \sum_{k=0}^n x^k - \sum_{k=0}^n x^{k+1} = 1 -x^{n+1}.
$$
Dividing by $1-x$ yields
$$
S_n = \frac{1 -x^{n+1}}{1-x}\stackrel{n\to\infty}\longrightarrow \frac1{1-x}.
$$


text:
Q: Javascript array of json prints empty but it has an object inside I'm trying to understand why Javascript prints an empty array when it should have at least one value inside it. Please, check this code:
detail = [];
detail.cat1=[];
detail.cat2=[];
detail.cat3=[];
detail.cat4=[];

var newEntry = {"cod":"01","dt":"2021-10-02 09:07:21.205-07:00"};

detail.cat2.push(newEntry);
console.log(detail);
console.log(detail.length);
console.log(detail.cat2);

The results are:
> Array []
> 0
> Array [Object { cod: "01", dt: "2021-10-02 09:07:21.205-07:00" }]

How could it print [] since I have one object inside? And how can the length be zero? I was using any Javascript online editor, and the result is the same.

A: Since an array is really an object, we can add methods/properties directly to an individual array.
Then if you want to see the keys in an object for instance, Object.keys won't see it, but Reflect.ownKeys() will.
The Reflect version of defineProperty will return success or fail, while Object's returns the object passed.
Remember Reflect.preventExtensions() will (like it says) stop you or others from extending them.
As far as question about length is there, ".length" gives length of values not properties so it still gives 0

A: Array is an indexed collection of values, means you can put element at particular index and get element from particular index.
In the below example, you can see that if there are already elements in an array then you can get its length using length property.
Remember: The length of an array is (highest integer index at which the element is present in array + 1)

const arr = [1, 2, 3, 4];

console.log(arr);   // prints whole array
console.log(arr.length);  // prints length of an array
console.log(arr[2]);  // Element at index 2

If you set element at particular index let say arr[8] = "something" then its length will be 9

const arr = [];
arr[8] = "something";

console.log(arr.length)   // 9

It is true that array's are objects, so you can set/get values to/from array. But if you set property that is not a numbered index then it will not increase its length but It will set the property to that array object as:

const arr = [];

arr["introduction"] = "I'm an array";
arr.property = "This is a property"

console.log(arr.length);
console.log(arr.introduction);
console.log(arr.property);

A: When displaying an array, the default Array.prototype.toString method is usually called. This actually calls Array.prototype.join with no arguments, so produces a comma separated string of the elements of the array.
The join method only returns properties that have a positive integer name (an array index, indicating an array element), other properties are ignored by join.
Similarly, only elements of the array affect the length property, ordinarly properties (i.e. those that don't have an array index for their name) don't affect length.


text:
Q: Windows server- disk management and diskpart show different disk sizes I have an HB proliant server with windows server 2012 R2 as OS. it has already 4Tb disk that drive c and D are on it. recently we added a bay with 8 disk all together are 8 TB. i wanted to format and assign this newly added disk then i realize that in disk management it shows:
   disk 0 : 4471 GB
   disk 1 : 14531 GB

then i ran powershell and in diskpart after list disk i have this:
   disk 0 : 4471 GB
   disk 1 : 7734 GB

why this happens and how i can fix it?
edit: rebooting the server does not work.

A: diskmgmt.msc

Hit Win+R and run the above command it will show details about the available disk and partitions.