text:
Q: Nginx custom configuration I need my NGINX configuration to do some unique things based on the URL.
If the URL is:
mydomain.com/blog OR mydomain.com/blog/
I need NGINX to serve up a ghost blog on port 2368 I have done this by:
location /blog/ {
    proxy_pass http://localhost:2368;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_set_header X-Forwarded-Proto $scheme;
    proxy_buffering off;
}

If the URL is:
mydomain.com/some-article-title
I need NGINX to direct to some-article-title.html. I have done this by:
location / {
    try_files $uri $uri/ $uri.html =404;
}

FIRST QUESTION: I would also like this to work if the url is mydomain.com/some-article-title/ OR if the case is different such as mydomain.com/Some-article-Title.  How can I do this in NGINX?
SECOND QUESTION: I also need NGINX to redirect to a specific subdomain if there is no matching HTML file i.e. If the URL is mydomain.com/jimsmith and there is no HTML file jimsmith.html I need NGINX to take the user to jimsmith.mydomain.com  How can I do that?

A: location /blog/ won't match requests for /blog, but location /blog will.
try_files... try files. Thus, if your request contains a trailing slash, nginx will search for a directory (files ending with / are directories only on any filesystem).
If you wish nginx to search for a file when a requests contains a trailing slash, you will need to rewrite the request to its pre-trailing-slash form. Note that directories won't be accessible anymore... so the most generic form showed below is far from being recommended. The trailing slash kind of rewrite is discouraged at all in any form anyway...
location ~* ^(?<article>/[^/]+)/$ {
    return 302 $scheme://$host$article;
}

You cannot have several files having the same name with letters capitalized or not in the filesystem, such as some-article-title and Some-article-Title, so a search for either name will always succeed with the existing file.
If you want to redirect files not matched by try_files first parameters, the last on can be used as a fallback to a named location, where you can issue a redirect (see try_files documentation).
location / {
    try_files $uri $uri/ $uri.html @notexisting;
}

location @notexisting {
    rewrite ^/(?<subdomain>.*)$ $scheme://$subdomain.mydomain.com;
}


text:
Q: Terraform for aws failing I am using terraform first time in order to create resources on my AWS account . I ran the below template for test but it always fails with the issue:

Error parsing <path>/main.tf: At 1:10: illegal char

provider "aws" {
    access_key = "${var.access_key}"
    secret_key = "${var.access_secret_key}"
    region = "${var.region}"enter code here }
    resource "aws_vpc" "${var.vpc_name}" { cidr_block = "10.0.0.0/16" enable_dns_hostnames = true }

Error: terraform init There are some problems with the configuration, described below.

A: Use this instead and let us know
provider "aws" {
   access_key = "${var.access_key}"
   secret_key = "${var.access_secret_key}"
   region     = "${var.region}"
}
resource "aws_vpc" "${var.vpc_name}" {
   cidr_block           = "10.0.0.0/16"
   enable_dns_hostnames = true
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I save the selected photos from iPhone Photo Library into the document directory?
Error Domain=NSCocoaErrorDomain Code=257 "The file "IMG_0125.PNG"
  couldn't be opened because you don't have permission to view it."
  UserInfo={NSFilePath=/var/mobile/Media/DCIM/100APPLE/IMG_0125.PNG,
  NSUnderlyingError=0x1c045d130 Error Domain=NSPOSIXErrorDomain Code=1
  "Operation not permitted"}}

I am getting above error while using below code
do{
    try filemanager.copyItem(at: sourceURL, to: dirConPath1)
}catch let error as NSError{
    print(error.debugDescription)
}

Also I have added:
    <key>NSPhotoLibraryUsageDescription</key>
    <string>want access of photos</string>
    <key>NSPhotoLibraryAddUsageDescription</key>
    <string>photos save description.</string>

into the info.plist
I am using Swift 4.1 and Xcode 9.3.1.

A: if you want to save image in local directory put this method in your file and just call with your image and image name ...
func saveImageToDocumentLocal(name:String,image:UIImage)  {
                let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
                let random = arc4random()
                let fileURL = documentsDirectory.appendingPathComponent("\(name)\(random)")
                if let data = UIImageJPEGRepresentation(image, 0.5),
                        !FileManager.default.fileExists(atPath: fileURL.path) {
                        do {
                            try data.write(to: fileURL)
                            print("file saved")
                            print(fileURL.path)

                        } catch {
                            print("error saving file:", error)
                        }
                }else{
            }
        }


text:
Q: In Haskell, how do I get an average float from a list of integers? I have written a simple function that displays: Name of place, Degrees North, Degrees East, and a list of rainfall numbers.
How do I get an average rainfall specific to a place? For example in my code, how do I get an average rainfall for London?
Sorry if my code is not the best, I'm just learning Haskell.
import Data.Char
import Data.List
type Place = (String, Float, Float, [Int])

testData :: [Place]
testData = [("London", 51.5, -0.1, [0, 0, 5, 8, 8, 0, 0]),
            ("Cardiff", 51.5, -3.2, [12, 8, 15, 0, 0, 0, 2]),
            ("Norwich", 52.6, 1.3, [0, 6, 5, 0, 0, 0, 3])]

rainLevels :: [Place] -> Float
rainLevels level (_, _, _, numbers) = sum numbers / 7

A: To find the average rainfall for "London", you need to first find the record for "London" in your list, then average its rainfall numbers.
getAvgRainLevel consumes a name of a specific city: name, and a list of records: xs; it finds the record of that city by its name, then calculates the average rainfall level for that city.
getAvgRainLevel name xs = fmap avg $ lookup name (sanitize xs)
  where
    sanitize = fmap (\(city, _, _, rainLevels) -> (city, rainLevels))
    avg = (/) <$> sum <*>  fromIntegral . length

A: If you want to divide Ints in Haskell, you first have to convert them to Floats. This avoids the problems you get with division in other statically typed languages like C, where 5/2 is 2.
So, how do you convert an Int to a Float? There are a number of functions for doing this, but the most paradigmatic choice is fromIntegral:
fromIntegral :: (Num b, Integral a) => a -> b

This will convert any Integral type to any Numeric type. Thus if you need to convert a [Int] to a [Float]:
fmap fromIntegral :: (Functor f, Num b, Integral a) => f a -> f b

There are another couple problems. Your code will not compile as-is. You have declared your function rainLevels to only take one argument, but you pattern match on two arguments when you define it. As currently defined, the actual type of rainLevels is:
rainLevels :: (Frac e) => a -> (b, c, d, [e]) -> e

Place matches (b, c, d, [e]), but not with the constraint (Frac e), which is what fromIntegral will solve, but you'll still be left with the issue that [Place] will not pattern match on (_, _, _, numbers). Since my mind-reading skills have sadly lapsed, I leave it to you to work out whether rainLevels is meant to take one Place or a list of them, but either way, you need to make the signature match the definition.

A: In addition to the explanation of Andrew Ray, I thought it might be helpful to provide an working example in code:
module Lib
    ( avgRainLevel
    , rainLevels
    , testData
    ) where

import Data.Char
import Data.List
type Place = (String, Float, Float, [Int])

testData :: [Place]
testData = [("London", 51.5, -0.1, [0, 0, 5, 8, 8, 0, 0]),
            ("Cardiff", 51.5, -3.2, [12, 8, 15, 0, 0, 0, 2]),
            ("Norwich", 52.6, 1.3, [0, 6, 5, 0, 0, 0, 3])]

findPlace :: [Place] -> String -> Place
findPlace placeList place = head . filter isPlace $ placeList
  where isPlace (name, _, _, _) = name == place

getLevel :: Place -> [Int]
getLevel (_, _, _, levels) = levels

rainLevels :: [Place] -> String -> [Int]
rainLevels placeList place = getLevel $ findPlace placeList place

average :: [Int] -> Float
average ints = fromIntegral levelSum / fromIntegral count
  where levelSum = sum ints
        count = length ints

avgRainLevel :: [Place] -> String -> Float
avgRainLevel placeList place = average $ rainLevels placeList place

I was a bit unsure what the actual value you want to get. From the name rainLevels I concluded that you want the list of rain levels, so I adapted the type to [Int]. Because you don't just provide the list of places, but also the actual place you want to query, I had to add another parameter which added a -> String to the type declaration of the function.
Based on the function, I did another function avgRainLevel that calculates the average of the values in the list of type [Int].
The code will work like documented with these tests:
import Lib (rainLevels, avgRainLevel, testData)
import Test.Hspec (Spec, it, shouldBe)
import Test.Hspec.Runner (configFastFail, defaultConfig, hspecWith)

main :: IO ()
main = hspecWith defaultConfig {configFastFail = True} specs

specs :: Spec
specs = do

  it "can read the list of levels" $ do
    let levels = rainLevels testData "London"
    levels `shouldBe` [0, 0, 5, 8, 8, 0, 0]

  it "can calculate the average rain level" $ do
    let avg = avgRainLevel testData "Norwich"
    avg `shouldBe` 2

Please note, that actually you shouldn't return [Int] or Float from any of these two functions. The code as it is will panic when you query for a place, that is not present in the list of places. You should better return Maybe [Int] and Maybe Float. In that case you can return Nothing when you have no information about a given place available.


text:
Q: Load D3 Url With API key I am trying to load a dataset from the URL "https://data.raleighnc.gov/resource/5ccj-g2ps.json" but it requires an API key. I have had no luck with D3 or Jquery.
How would I go about doing this so that I can load the dataset in Json format?
I have the following:
$.ajax({
url: "https://data.raleighnc.gov/resource/xce4-kemu.json",
type: "GET",
data: {
  "$limit" : 5000,
  "$$app_token" : "YOURAPPTOKENHERE"
}
}).done(data) {
alert("Retrieved " + data.length + " records from the dataset!");
console.log(data);
});

It says I have a misplaced "{" but I don't see where.

A: There are a lot of mistakes in your code...
$.ajax({
    url: "https://data.raleighnc.gov/resource/xce4-kemu.json", // didn't you want to get another URL??!?
    type: "GET",
    dataType: "json",
    data: {
      "$limit" : 5000, // Does the API require the dollar signs? Looks weird.
      "$$app_token" : "YOURAPPTOKENHERE" // Did you actually replace with your API key?
    },
    success: (data) => {
        alert("Retrieved " + data.length + " records from the dataset!");
        console.log(data);
    },
    error: (xhr, textStatus, errorThrown) => {
        // error
    }
});

Should be working.


text:
Q: AWS - StepFunctions: How to access artifacts with StepFunctions from previous stage in CodePipeline? I have the following pipeline:
AWS - Codepipeline flow
I am having trouble linking the output artifacts from the source (GitHub) stage to the input artifacts of the StepFunctions stage.
My goal is for my StepFunctions stage to have access to the last zip file name (on S3 Bucket) that the source stage output to.
I already tried:

*

*Define Namespace in the Source stage to use it in the StepFunctions stage.
link to docs: https://docs.aws.amazon.com/codepipeline/latest/userguide/reference-variables.html

*Read this docs: https://docs.aws.amazon.com/codepipeline/latest/userguide/tutorials-step-functions.html

*new case: Stage with Lambda instead StepFunctions, it receives the link to S3 folder and other meta-data from the Source stage while StepFunctions do not.


text:
Q: Convert array^ data to const byte* data - C++/CLR I am trying to call a function in C from C# though c ++
so basically C# -> C++ - >C
In C#, I have byte[] bytes - which reads the information from the file. I am passing the byte array and the size to C++ .
In C++ I get the byte array and the size but I am not able to convert to the specific data types.
void Image::OpenMemFile(array<Byte>^ data, unsigned int size)
{

    Free();
    m_dataStream = data;
    Byte const* streamData = &data[0];   // this is where it throws error
         // Should I use marshaling here ? What call should that ;be ?
         hImage = ::OpenMemImage(streamData , size);
    modified = false;
}

// this is the function I need to call
EXIVSIMPLE_API HIMAGE OpenMemImage(const BYTE *data, unsigned int size)
{
   // code
        imgWrap->image = Exiv2::ImageFactory::open(data, size);

}

the C function it needs to call is
Image::AutoPtr ImageFactory::open(const byte* data, long size)
    {
      /// code
    }

I need to help in converting the byte array to const byte* . I realize I need to use Marshaling. Is there a specific function to marshal arrays in C++ ?
Any help is appreciated.
Thanks

A: pin_ptr<unsigned char> pin_buffer = &data[0];
unsigned char* pData = pin_buffer;


text:
Q: How to use flume to read data from mysql? How to use flume to read continously from mysql to load to hbase?
I am familiar with sqoop but I need to continuously do it from a mysql source.
Is it required to have custom source to do this?

A: Sqoop is good for bulk import from RDBMS to HDFS/Hive/HBase. If it's just one time import, it's very good, it does what it promises on paper. But the problem comes when you wanna have real-time incremental updates. Between two types of incremental updates Sqoop supports:
Append, this one allows you to re-run the sqoop job, and every new job starts where the last old job ends. eg. first sqoop job only imported row 0-100, then next job will start from 101 based on --last-value=100. But even if 0-100 got updated, Append mode won't cover them anymore.
last-modified, this one is even worse IMHO, it requires the source table has a timestamp field which indicates when the row gets last updated. Then based on the timestamp, it does the incremental updates import. If the source table doesn't have anything like that, this one is not useful.
I'd say, if you do have hands on your source db, you can go for the last-modified mode using Sqoop.

A: There are a number of ways to do this, but I would write a script that takes your data from MySQL and generates an Avro event for each.
You can then use the built-in Avro source to receive this data, sending it to the HDFS sink.


text:
Q: sub report not getting any value in crystal report I have a sub report in crystal report ..i am using vb.net

delParkingtype.rpt

i created as sub report.then i calling this report to my crystal report viewr like this:
        Dim rpt As New DelivaryPerformance
        Dim rpt1 As New DelParkingtype
        Dim locid As Integer = RecordID("Locid", "Location_tbl", "LocName", CmbLocations.Text)
        Dim cmdstatus As New SqlCommand("IBS_DelivaryStaus", con.connect)
        cmdstatus.CommandType = CommandType.StoredProcedure
        cmdstatus.Parameters.Add("@locid", SqlDbType.Int).Value = locid
        da.SelectCommand = cmdstatus
        da.Fill(ds)
        If (ds.Tables(0).Rows.Count > 0) Then

            rpt.SetDataSource(ds.Tables(0))
            ' CrystalReportViewer1.ReportSource = rpt
        End If
        Dim cmdparkingtype As New SqlCommand("IBS_Delivaryparkingtype", con.connect)
        cmdparkingtype.CommandType = CommandType.StoredProcedure
        cmdparkingtype.Parameters.Add("@locid", SqlDbType.Int).Value = locid
        da1.SelectCommand = cmdparkingtype
        da1.Fill(ds1)
        If (ds1.Tables(0).Rows.Count > 0) Then

            rpt1.SetDataSource(ds1.Tables(0))
            CrystalReportViewer1.ReportSource = rpt1
            CrystalReportViewer1.ReportSource = rpt
        End If

but

DelParkingtype not filling any data..what is wrong with my code

A: You should do something like this, you have to add the datasource to the subreport of your main report. After that you just add the main report to reportSource.
rpt.Subreports(0).SetDataSource(ds1.Tables(0))
CrystalReportViewer1.ReportSource = rpt;

You won't need this
Dim rpt1 As New DelParkingtype

Hope this helps you


text:
Q: Sort Dictionaries in Array? I need to sort an nsmutablearray of nsdictionaries, using a keyed object from the dictionary. The object is an NSNumber. How would I sort the dictionaries in the nsmutablearray with the first object being the highest nsnumber?
Thanks!

A: With a custom comparator defined with a block (you can go other ways but this is quite compact):
NSComparator mysort = ^(id dict1, id dict2) {
    NSNumber n1 = [dict1 objectForKey:@"key"];
    NSNumber n2 = [dict2 objectForKey:@"key"];
    return (NSComparisonResult)[n1 compare:n2];
};

[yourArray sortUsingComparator:mysort];

A: That code seems a bit off. Here is one that works.
[theMutableArrayThatWillBeSorted sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSNumber* n1 = [obj1 objectForKey:@"key"];
    NSNumber* n2 = [obj2 objectForKey:@"key"];

    return [n1 compare:n2];
}];


text:
Q: Why can't I POP from one Gmail account to another? Alright, so I'm in email2@gmail.com, which I just created. I want to POP from email1@gmail.com to email2@gmail.com. I go to Gear / Settings / Accounts and Import / Add a POP3 mail account you own. I type in email1@gmail.com as the address, and:
Username: email1@gmail.com
Password: <Password>
POP Server: pop.gmail.com
Port: 995
Unchecked Leave a copy of retrieved message on the server.
Checked Always use a secure connection (SSL) when retrieving mail.
Checked Label incoming messages: email1@gmail.com
Unchecked Archive incoming messages (Skip the inbox)

I receive the following error message:
Server denied POP3 access for the given username and password.
Server returned error: "[AUTH] Web login required: https://support.google.com/mail/bin/answer.py?answer=78754"

Which leads me to probably one of the most unhelpful support page I've ever read in my entire life.
Beforehand, I logged into both of the accounts and went to Gear / Settings / Forwarding and POP/IMAP and clicked Enable POP for all mail (even mail that's already been downloaded) and When messages are accessed via POP delete Gmail's copy. This made no difference. Are there password restrictions in POP? I just can't think of what else it might be.

A: I guess Google considers their own client 'insecure'. Try allowing access for 'less secure apps': https://www.google.com/settings/security/lesssecureapps

edit (2019-12-17):
As this is a popular answer, I want to use this to warn people running into this problem that the solution presented here will likely soon stop working.
Yesterday Google communicated the following to G Suite administrators:

We're constantly working to improve the security of your organization's
  Google accounts. As part of this effort, and in consideration of the
  current threat landscape, we'll be turning off access to less secure apps
  (LSA) — non-Google apps that can access your Google account with only a
  username and password, without requiring any additional verification
  steps. Access through only a username and password makes your account more
  vulnerable to hijacking attempts. Moving forward, only apps that support a
  more modern and secure access method called OAuth will be able to access
  your G Suite account.
Access to LSAs will be turned off in two stages:

*

*June 15, 2020 - Users who try to connect to an LSA for the first time
  will no longer be able to do so. This includes third-party apps that
  allow password-only access to Google calendars, contacts, and email
  via protocols such as CalDAV, CardDAV and IMAP. Users who have
  connected to LSAs prior to this date will be able to continue using
  them until usage of all LSAs is turned off.

*February 15, 2021 - Access to LSAs will be turned off for all G Suite
     accounts.

A: I got this fixed. The answer for me was in that link that we all received. I thought I followed it and probably did but not with the secondary account that I wanted to add.

So this is what I did:

*

*Logout of your primary gmail account.

*Login to the secondary gmail account (the one you wanted to add).

*Go to https://accounts.google.com/b/0/DisplayUnlockCaptcha and follow the instructions on the page to allow access.

*Logout of this account.

*Log back into your primary gmail account and now try adding that second account. It should work now.

*You should get an email to confirm that you own that account. Make sure you login to that second account again to confirm (by clicking on
the link or entering the confirmation code).

It worked perfectly for me. I have two gmail accounts synced into one
now :)

Source: Can't add pop3 account in gmail account at gmail forum


text:
Q: Simple sql query to get value for a given date I have this simple problem in SQL. I have a table with 4 columns. Columns being ID, DateTime, Decimal, AnotherID.
DECLARE @data DATETIME
SET @data = '20120101'

SELECT [ID]
      ,[Data]
      ,[Value]
      ,[InID]
 FROM [dbo].[Static]
 WHERE InID = 1 AND [Data] <= @data

Now I have to choose proper Value based on InID and Data. InID can have multiple rows with different dates. This is example output for InID = 1.
ID          Data            Value              InID
389         2012-01-02      10.00000000     1
390         2011-12-16      20.00000000     1
391         2011-12-13      15.00000000     1

Now based on InID and Data I need to get Value for given date. For example for InID = 1 I need to get Value for day 2011-12-14. Of course the value should be taken from 13th of December and if I ask it about value for date 2012-01-13 it should take last value. However in case the question is about date before the first date it should return NULL. I tried multiple combinations but my brain seems to be out of order atm so any help would be appreciated.

A: Try this to get only the most recent Value constrained by the @data parameter:
SELECT TOP 1 [Value]
FROM [dbo].[Static]
WHERE InID = 1 AND [Data] <= @data
ORDER BY [Data] DESC;

To the last part of your question if you need a NULL result you'll have to wrap the query above as it will return an empty result set if nothing qualifies:
DECLARE @theValue float;
SELECT @theValue = (
  SELECT TOP 1 [Value]
  FROM [dbo].[Static]
  WHERE InID = 1 AND [Data] <= @data
  ORDER BY [Data] DESC
);

The nearest would be this (just be aware that it can grab either future or past dates):
 SELECT TOP 1 [Value]
 FROM [dbo].[Static]
 WHERE InID = 1
 ORDER BY ABS(DATEDIFF(Day, [Data], @data));

A: I have no idea how efficient this is, but it should work...
-- Some other commands here, that MUST be terminated with a ;
-- It's anal, but that's how MS implemented the WITH syntax

WITH
  sequenced_data AS
(
  SELECT
    ROW_NUMBER() OVER (PARTITION BY InID ORDER BY ABS(DATEDIFF(day, @yourDate, Data)) ASC) AS sequence_id,
    *
  FROM
    static
)
SELECT
  *
FROM
  sequenced_data
WHERE
  sequence_id = 1

EDIT
This is what I had originally...
It gives The nearest date down.
;WITH
  sequenced_data AS
(
  SELECT
    ROW_NUMBER() OVER (PARTITION BY InID ORDER BY Data DESC) AS sequence_id,
    *
  FROM
    static
  WHERE
    Data <= @yourDate
)
SELECT
  *
FROM
  sequenced_data
WHERE
  sequence_id = 1

A: SELECT TOP 1
       [ID]
      ,[Data]
      ,[Value]
      ,[InID]
 FROM [dbo].[Static]
 WHERE InID = 1 AND [Data] <= @data
ORDER BY DATA desc

If the rows does not exists you wand NULLs in all the fields?

A: This should give you all the values for the one row based on the highest qualified date record.  Only issue is if you have multiple entries on the same date with an "InID" = 1.  If the field for data is actually a date/time precision (just simplified for your posting sample), then you'll get even better precision.  I would ensure an index on InID and Data to optimize better.
select
      Static.*
   from
      ( select max( Data ) as HighestQualifiedDate
           from Static
          where InID = 1
            and Data <= @data ) PreQuery
      JOIN Static
         on InID = 1
         AND PreQuery.HighestQualifiedDate = Static.Data

A: SELECT TOP 1
    [Value]
FROM
  ( SELECT TOP 1
        [Data], [Value]
    FROM [dbo].[Static]
    WHERE InID = 1 AND [Data] <= @data
    ORDER BY [Data] DESC
  UNION ALL
    SELECT TOP 1
        [Data], [Value]
    FROM [dbo].[Static]
    WHERE InID = 1 AND [Data] >= @data
    ORDER BY [Data] ASC
  UNION ALL
    SELECT
        DATEADD(day, -1, MIN([Data])), NULL
    FROM [dbo].[Static]
    WHERE InID = 1
  ) AS tmp
ORDER BY ABS(DATEDIFF(Day, [Data], @data))


text:
Q: Hybrid graphics in linux I came across Nvidia optimus implementation for linux called bumblebee project https://github.com/Bumblebee-Project
I installed bumblebee on my laptop with Nvidia graphics card. The issue is that for the applications which need to use discrete gpu, have to be run through a special command "Optirun". Hence only when this is done, the discrete gpu is powered on else it is powered off whenever necessary to conserve power.
Is there a way to identity whether an application needs discrete gpu to run or could run on normal on chip graphics processor. Can this be done in linux ?

A: I don't think so, I also have a laptop with an optimus card, even on windows it has a list of applications you want to run with the nvidia chip or the intel one.
I believe that when you install the driver it comes with a list.
In theory you could profile each application that uses the video card for how much GPU/Memory it uses, if it is more than said limit you tag that this app should run on the nvidia if it is running on nvidia but using a small ammount you tag it to use the intel chip


text:
Q: Comparing strings with Python: X in ['item1', 'item2', ...] vs. X == 'item1', X == 'item2', ...? I am fairly new to Python and I have a question regarding performance when comparing strings. Both codes below seem to achieve what I want but is there any reason to use one of them instead of the other?
Option1:
if first_column_header == 'author name' or first_column_header == 'author' or first_column_header == 'name':

Option2:
if first_column_header in ['author name', 'author', 'name']:

A: Option 2 is definitely shorter and more pythonic. It's also possible that it adds a little more of overhead to your code because it creates a list and then iterates through it.
This is a trade off you'll have to accept by making programs more readable but, IMHO, this is too little overhead to worry so I'll go with Option 2.
Hope this helps!

A: If you have a lot of choices, say more than a dozen, and speed is really critical, then use a set. It's the fastest to check membership, although there's some overhead since the item being checked needs to be hashed. Define the set ahead of time so it's not redefined each time the if statement is executed.
first_column_names  = {"author name", "author", "name"}

# In Python before 2.7, you must use `set()` instead:
first_column_names = set(("author name", "author", "name"))

if first_column_header in first_column_names:

But if speed is critical, what are you writing it in Python for to begin with?  :-)  Generally you'll want to go with what's more readable. In this situation, that'll be a list or a tuple. Defining a tuple literal is marginally faster so, with readability being equal, I'd go that way:
if first_column_header in ("author name", "author", "name"):

A: I have to disagree with Paulo on the fact that Option 1 is faster. Here is what dis shows for these 2 functions:
def t():
    if a == 'author name' or a == 'author' or a == 'name':
        return True
    return False

def t2():
    if a in ['author name','author','name']:
        return True
    return False

It seems that a is loaded many times in the first case, and that the list in option 2 is created before the call.
3           0 LOAD_GLOBAL              0 (a)
              3 LOAD_CONST               1 ('author name')
              6 COMPARE_OP               2 (==)
              9 POP_JUMP_IF_TRUE        36
             12 LOAD_GLOBAL              0 (a)
             15 LOAD_CONST               2 ('author')
             18 COMPARE_OP               2 (==)
             21 POP_JUMP_IF_TRUE        36
             24 LOAD_GLOBAL              0 (a)
             27 LOAD_CONST               3 ('name')
             30 COMPARE_OP               2 (==)
             33 POP_JUMP_IF_FALSE       40

  4     >>   36 LOAD_CONST               4 (True)
             39 RETURN_VALUE

  5     >>   40 LOAD_CONST               5 (False)
             43 RETURN_VALUE
  8           0 LOAD_GLOBAL              0 (a)
              3 LOAD_CONST               4 (('author name', 'author', 'name'))
              6 COMPARE_OP               6 (in)
              9 POP_JUMP_IF_FALSE       16

  9          12 LOAD_CONST               5 (True)
             15 RETURN_VALUE

 10     >>   16 LOAD_CONST               6 (False)
             19 RETURN_VALUE


text:
Q: query search on an index with two different documents type i've an index in which there are heterogeneous documents. These documents have only 1 common field (a personal id) for example:
DOC
id: 7
content: this example content doc has a long text
type: content
DOC
id: 7
title: example doc
public: yes
type: metadata
i've chosen this solution because i want to manage the long text documents separately from the metadata documents.
If i perform a query like this
+(content: example title: example) +public: yes

lucene return correctly the document type "metadata" with id 7 but if i perform this other one:
+(content: long) +public: yes

lucene doesn't return me the document because the clause +public: yes (necessary for my application) corresponds to a field not in "content" type document.
My question: how can i ask  lucene to give back the "content" document that has the "public" field "yes" contained into the other document with the same id (with only a single query)?
Sorry for my english, thanks to all.

A: Would it work if you didn't make the 'public' field required. So:
+(content: long) public: yes

Or can you strip the 'public' field out of the query string before submitting it to Lucene?


text:
Q: javascript find symmetric difference My function needs to accept any number of lists, then output their symmetric difference. sym([1, 2, 3], [5, 2, 1, 4]) should return [3, 5, 4] and sym([1, 2, 5], [2, 3, 5], [3, 4, 5]) should return [1, 4, 5]. I am confused by the result of my code - this returns an empty array.
function isin(num,arra)
{
  for (var i=0; i<arra.length; i++)
  {
    if (num == arra[i])
    {
      return true;
    }
  }
  return false;
}

function sym()
{
   console.log("logging args");
   console.log(arguments); // logs [Array[3], Array[4]]
   var syms = [];
   for (var i=0; i<arguments.length-1; i++)
   {
     var ins = false;
     for (var j=0; j<arguments[i].length; j++)
     {
        for (var k=i+1; k < arguments.length; k++)
        {
          if(isin(arguments[i][j], arguments[k]))
          {
            ins = true;
          }
        }
     }
     if (ins === false)
     {
       syms.push(arguments[i][j]);
     }
   }
  return syms;
}
sym([1, 2, 3], [5, 2, 1, 4]);

A: EDITED: to add some code
Your loop variables are all global, including i. Put a var in front of them (at least before i) and you're done.
The following gets the symmetric difference of two sets. I hope you can get on from there.
function isin(num,arra)
{
  for (var i=0; i<arra.length; i++)
  {
    if (num == arra[i]){return true;}
  }
  return false;
}

function sym()
{
   var j,k,i,l;
   var syms = [];
   for ( i=0; i<arguments.length; i++)
   {
     var ins = false;

     for (k=i+1; k < arguments.length; k++){
       for ( j=0; j<arguments[i].length; j++){
         if(!isin(arguments[i][j], arguments[k]))
         {
           syms.push(arguments[i][j]);
         }
       }
       for ( l=0; l<arguments[k].length; l++){
         if(!isin(arguments[k][l], arguments[i]))
         {
           syms.push(arguments[k][l]);
         }
       }
     }
   }
  return syms;
}
sym([1, 2, 3], [5, 2, 1, 4]);

A:
my code returns an array of undefined values

This is because when you are pushing onto syms, your for-loop with the j variable has completed. So it is actually at j = <arguments[i].length (now it really is an out-of-bounds index read).
 if (ins === false)
 {
   syms.push(arguments[i][j]);  # push "undefined" onto syms.
 }

Make sure you put this block of code inside the for (var j=0; j<arguments[i].length; j++) block.

A: To solve the symmetric difference of multiple arrays, we can start by designing a function which returns the symmetric difference of two arrays
As shown in function sym2(), the main idea of getting the result from sym2(a1,a2) can be divided into two steps: (1). for every elements in array a1[], if a1[j] is not in array a2[] and a1[j] is not in the result array syms[], then a1[j] is pushed to the result array.  (!isin(a1[j],syms)can prevent repeating numbers in a1[], such as sym2 ([1,1],[3]) can return [1,3] instead of [1,1,3].  after a1-a2 is done, the second step a2-a1 is performed the same way (2).for every elements in array a2[], if a2[l] is not in array a1[] and a2[l] is not in the result array syms[], then a2[l] is pushed to the result array.
function sym() take a list of arrays, first, we can save all arrays from the arguments to a variable, like arg[array1,array2,array3], and use Array.reduce() function. for example,if arg contains [a1,a2,a3] arg.reduce(function(a,b){return sym2(a,b)}); is executed like following:

*

*syms2(a1,a2)

*syms2(syms2(a1,a2),a3)
all code :
function isin(num,arra)
{
    for (var i=0; i<arra.length; i++)
        if (num == arra[i]){return true;}
    return false;
}

function sym2(a1,a2)
{
    var j,l;
    var syms = [];
    for ( j=0; j<a1.length; j++){
        if(!isin(a1[j], a2)&&!isin(a1[j],syms))
            syms.push(a1[j]);
        }
    for ( l=0; l<a2.length; l++){
        if(!isin(a2[l], a1)&&!isin(a2[l],syms))
            syms.push(a2[l]);
        }
    return syms;
}
function sym(){
    var arg=[];
    for(var o = 0; o<arguments.length;o++)
        arg.push(arguments[o]);
    return arg.reduce(function(a,b){
        return sym2(a,b);
    });
}


text:
Q: Chart.ux.Highcharts how to get work with simple store i'm trying to use Highcharts plugin and I've started with the simple example in his documentation
I've correctly set the enviroment (I'm sure).
This is the windows i've declared:
//other part of app.js (working)
launch:function():{
var sto = Ext.create('AM.store.mysto');
var win = new Ext.create('Ext.window.Window', {
    layout: 'fit',
    items: [{
       xtype: 'highchart',
       series:[{
          dashStyle: 'DashDot',
          dataIndex: 'value'
       }],
       xField: 'month',
       store: sto,
       chartConfig: {
          chart: {
             type: 'spline'
          },
          title: {
             text: 'A simple graph'
          }
       }
    }]
}).show();
//other part of app.js (working)
}
//........more other part of app.js (working)

and I've declared the store as follow:
Ext.define('AM.store.mysto', {
  extend : 'Ext.data.Store',
  model : 'AM.model.mysto',
  data : [{
    month : 'x',
    value:1
  }, {
    month : 'y',
    value:12,

    value:2
  }, {
    month : 'z',
    value:3
  }]
});

And finally this is my model:
Ext.define('AM.model.mysto', {
  extend : 'Ext.data.Model',
  fields : [{
    name : 'month'
  }, {
    name : 'value'
  }]
});

If I execute my application, this will be my window: an empty window with no chart inside.

The only difference I've with the doc example is the store. Can someone tell me what is wrong?
thank you!

A: the guru of Sencha "mitchellsimoens" said:
"You have layout : 'fit' on the window which will size the child item to the window's size so you would need to give the window a size."
it's true. I've added the size and it works fine:
  var win = new Ext.create('Ext.window.Window', {
    layout: 'fit',

//HERE!!!!
      width: 200,
      height: 200,

    items: [{

A: the problem is not a window size actually,
the problem is - window empty and no chart inside
have the same issue by the way
in the original example the store not loaded, and even autoload in store is not a case for you
, autoLoad: true

cause you should create window only after store loaded with data or reload a store after window creation
that way I would do it something like this
var chartStore = Ext.create('chartStore');
chartStore.load({

    callback: function (data, operation, success) {

        // here the store is loaded with data already
        var winChart = new Ext.create('Ext.window.Window', {
            width: 400
            , height: 400
            , layout: 'fit'
            items: [{
                xtype: 'highchart'
                , series: [{
    }

moreover this can be an idea as well
Chart.ux.Highcharts >>> initAnimAfterLoad

Since Highcharts initial and update animations are not the same, if you want to make sure there is initial animation, then you should create store and extension in specific sequence. First, set the Ext.data.Store.autoLoad option to false, create the Highcharts component with the store, then call the Ext.data.Store.load method. The initAnimAfterLoad defers creating the chart internally until the store is loaded. Disabling it, the extension will create the chart instantly and you will only see the update animation after the load.

also this store param give more info in console
, debug: true

Solved with colleague's advice
this should be added in store and that works like a charm
, autoLoad: true

thank you


text:
Q: How can i align in D435 by using opencv? Intel gives example to align RGB camera and Depth(IR) camera, but i need adapt to opencv.
the example show only "align in render", so i can't use them because i will use below function.
Mat color(Size(640, 480), CV_8UC3, (void*)color_frame.get_data(), Mat::AUTO_STEP);
i need align frame like below sentences form.
rs2::frameset frames = pipe.wait_for_frames();
rs2::frame color_frame = frames.get_color_frame();
rs2::frame depth_frame = color_map(frames.get_depth_frame());

So, is it possible that i can use align function like below ex) sentence?
ex) rs2:: frameset align_frame = ...... allocate_composite_frame......
OR, is there any function like "depth_aligned_to_color" in D435 like SR300?

A: The frameset will be returned after align function is called, you can retrieve back the aligned color/depth image to set into CV function without problem. Please download the latest version LibRS and check the rs-align.cpp, attach code snippet below.
//Get processed aligned frame
auto processed = align.process(frameset);

// Trying to get both other and aligned depth frames
rs2::video_frame other_frame = processed.first(align_to);
rs2::depth_frame aligned_depth_frame = processed.get_depth_frame();


text:
Q: Security of Samsung Remote Test Lab I am developing an Android application and I am testing it with Samsung's "REMOTE TEST LAB" service. The tool is nice to test the application on different Samsung devices.
My application is not released yet and I am worried whether it will be safe to test the application using "REMOTE TEST LAB". I am concerned about whether application will be accessible to other user of this service if I forgot to uninstall the application from the device of "REMOTE TEST LAB" service.
It would be helpful if anyone can provide additional thoughts/suggestions.
Thank you.


text:
Q: C# Unity - Parent position shifts after I add childs So I am adding 10 childs to a empty GameObject in 2D. The empty GameObject has a position of 0,0,0.
When I add the 10 childs his position shifts only in the game view/scene to 4.5 on the X axys, but in the inspector still says that he is in the 0,0,0.
If I open the scene he is in the middle of the childs if I shift he backwards to the center now the inspector reads -4.5,0,0.
Anyone knows how to fix the issue?
Here is the code:
int sizeX = 10;
int sizeY = 1;
for (int i = 0; i < sizeX ; i++)  {
    for (int j = 0; j < sizeY; j++)  {
        Instantiate(blocks[Random.Range(0, blocks.Length)],
                    new Vector2( i,(transform.position.y - j)/2),
                    Quaternion.identity,transform);
    }
 }

A: Your Empty gameObject will stay in 0,0,0 unless you change it manually or with script.
your scene display the centered pivot, not the real pivot, it centered because you have child, so the pivot for transform manipulator tool has changed to bound to the child.

hit Z on the Keyboard to toggle Pivot Mode, or X to toggle pivot
  rotation.

Please read the documentation https://docs.unity3d.com/Manual/PositioningGameObjects.html


text:
Q: How to prevent a logon script applied to the entire domain by Group Policy from affecting one particular computer OU? We have a logon script applied to the entire domain, mapping drives when users logon.
For one particular computer OU, I would like to prevent this GPO from being applied.
I thought that using Group Policy loopback processing might be able to do this, but I am not sure how to do this for drive mapping (and my tests with both "merge" and "replace" loopback processing have been unsuccessful).
Can anyone point me in the right direction?

A: To prevent a GPO linked to the domain from applying to an OU, you use Block Inheritance on that OU by right-clicking the OU and choosing Block Inheritance.
This also blocks inheritance of all other GPOs that would normally be inherited by that OU unless they're Enforced. If you need to avoid that, then what I would do is use the settings in the Delegation tab of that Group Policy object and specifically deny a user or group the ability to read/apply that GPO.
Use Group Policy Management Console
1.  Click Start, point to Administrative Tools, and then click Group Policy Management.
2.  In the console tree on the left, expand Forest.
3.  Expand Domains.
4.  Expand Domain Name.
5.  Expand Group Policy Objects.
6.  Click the Group Policy object that you do not want to apply to [some group].
7.  In the display pane on the right, click the Delegation tab.
8.  Click the Advanced button in the lower-right corner of the display pane.
9.  Click Add, and then type the account name that you do not want the Group Policy object to apply to.
10.  Click OK.

Note Group Policy objects contain settings that apply to computer objects and to user objects. If you want only to restrict user settings from applying, add only the user account that you do not want the policy settings to apply to. If you want only to restrict computer settings from applying, add only the computer account that you do not want the policy settings to apply to. To add computer accounts, you have to click the Object Types button, and then click to select the Computers check box.
11. Make sure that the newly-added account is selected in the Group or user names window. Then, scroll down in the Permissions window, and click to select the Deny check box for the Apply group policy permission.
12.Click OK.
13. Click Yes at the Windows Security prompt.

This method implies that you manage a separate security group for people you do not want that drive mapping policy applied to.


text:
Q: Matching FORTRAN rounding in C# FORTRAN provides several functions to convert a double precision number to an integral value.  The method used for truncation/rounding differs.  I am converting complex scientific algorithms which use these.
According to FORTRAN documentation:
aint(x) returns the integral value between x and 0, nearest x.
anint(x) returns the nearest integral value to x, except halfway cases are
         rounded to the integral value larger in magnitude.
nint(x) converts x into int format rounding to the nearest int value, except
         halfway cases are rounded to the int value larger in magnitude.
Does anyone have an implementation of these in C#?
It might be tricky getting it right.
(int)x appears to match aint()
Convert.ToInt32(x) does not match any of the above.
Trunc(x) does not match any of the above.
Round(x) might match anint or nint.
The difference between anint and nint seems to be the return type, where anint returns a double precision value but nint returns an integer.  Both are used (acutal sample):
DOUBLE PRECISION A, B, C, D, E, F, G
... values set here ...
F = ANINT(A-B) + ANINT(C-D) + ANINT(B+D-E)
G = NINT(F) + 1D0;
Perhaps a FORTRAN expert could help clarify why the author chose to use both (I am assuming it was intentional).

A: From your definitions of the calls, nint and anint are provided by Math.Round using MidpointRounding.AwayFromZero.
For aint, an explicit cast from double to int will achieve that result.

A: From what I can see, aint() is just Math.Floor().
For the other two, I think you are right that the only difference is the return type: nint() returns an actual integer, while anint() returns a double (fortran: real) that happens to have an integral value.

A: I have an implementation of the function  anint, follow the code:
double anint(double x)
{
    int a;
    double y;

    a = (int)x; //a=9

    if (10 * x - 10 * (double)a >= 5)
    {
        a = a + 1;
    }

    y = (double)a;

    return y;
}


text:
Q: How to get MSP subproject statusdate in a masterplan from Excel VBA I am building an Excel dashboard which I want it to get data from my department MSP Masterplan.
So far I managed to get all data I want except the statusdate of subprojects.
Sub ImportMSPData()

Dim r As Range
Dim MSP As MSProject.Application
Dim proj As Project
Dim subproj As Subproject
Dim ligne As Long

Set MSP = CreateObject("MSProject.Application")
MSP.Visible = False

Application.ScreenUpdating = False
Application.EnableEvents = False

AppActivate MSP
If MSP.FileOpenEx(MasterplanPath, , , , , , , , , , , pjDoNotOpenPool) Then
    Set proj = MSP.ActiveProject
Else
    MsgBox "Fichier non trouvé : " & vbCrLf & Files.MspRoutine
    Exit Sub
End If

ligne = 1

For Each subproj In proj.Subprojects
        ThisWorkbook.Sheets("test").Cells(ligne, 1).Value = subproj.Path
        ThisWorkbook.Sheets("test").Cells(ligne, 2).Value = Left(subproj.InsertedProjectSummary.Name, 15)
        ThisWorkbook.Sheets("test").Cells(ligne, 3).Value = Mid(subproj.InsertedProjectSummary.Name, 19)
        ThisWorkbook.Sheets("test").Cells(ligne, 5).Value = subproj.InsertedProjectSummary.Start
        ThisWorkbook.Sheets("test").Cells(ligne, 6).Value = subproj.InsertedProjectSummary.Finish
        ligne = ligne + 1
Next
End Sub

I can get Statusdate by looping through all supbrojects, opening them, reading data and closing after that, but it takes forever depending on the number of subprojects. Is there a way I can get this information in the loop here above without opening the subprojects?

A: To get the Status Date for the SubProjects, use the SourceProject property to reference the underlying subproject properties:
ThisWorkbook.Sheets("test").Cells(ligne, 7).Value = subproj.SourceProject.StatusDate


text:
Q: Separate every digit of number by comma in php My String is like this
$str="12345"

I want to get
$str1 = "1,2,3,4,5"

A: explose to an array with str_split and then implode
implode(str_split('testing'), ',')

will give you
t,e,s,t,i,n,g

samefor 1234

A: try this, check the live demo
implode(',', str_split($str));

A: $strLen = strlen($s);
$o = '';
for($i =0; $i < $strLen; $i++) {
      $comma = ($i < $strLen) ? ' , ' : '';
      $o .= $strLen[$i] . $comma;
 }
 echo $o;

A: Without explode or implode:
$str="123456789";
echo substr(chunk_split($str,1,","),0,-1);


text:
Q: Getting Value Through C# Getter Setter Property Returns Null I have a Login.cs class and I have set properties in it as below.
private string Username_;
private string Password_;

public string UserName
{
    get => Username_;
    set => Username_ = value;
}
public string Password
{
    get => Password_;
    set => Password_ = value;
}

and setting the values in the same class for both properties as below.
UserName = "admin";
Password = "admin";

Where Username_ & Password_ are both strings. Now I have another Usercontrol which I am accessing in MainWindow on button click which is shown below.
<vm:ViewUsers x:Name="ViewAllUsers" Visibility="Hidden"/>

What I am doing in Code behind of UserControl is as below to access the values of Username and Password through Property Getter Setter as below.
string username = Login.GetInstance().UserName;
string password = Login.GetInstance().Password;

On debugging obj.UserName; property Returns Null. Why does it return null and how should I fix that?

A: The problem is that you're creating a new instance of Login() before you fetch the properties:
// Code originally in the question
Login obj = new Login();

This has now been changed to Login.GetInstance(), but we don't know what that method does. If that method returns a reference to a new instance of Login each time, we're left with the same problem.
Both properties in that object will be null, because you haven't set them to anything. (The default value for all reference types is null.) It's not clear to me where you're setting the properties to any other value, but whichever object you're setting them on isn't the same one that you're then using in the final piece of code you showed us.
You need to make sure you can use the "getters" on the same object that you called the "setters" on.
As an aside, because your properties are trivial (they're just getting and setting variables, with no other behavior such as validation) you can replace all of the first piece of code you've got with automatically implemented properties:
public string UserName { get; set; }
public string Password { get; set; }

A: You are misunderstanding how getters and setters work I think.
At the moment of initialization of an object, all it's uninitialized fields are set to default values (null for reference types, 0 for numbers, etc.).
Getters and setters are, as their name suggest, for setting value and getting.
What you are doing, after initialization you use private fields to supply value for respective setter. But what it does is assign value supplied to it to underlaying field.
Since you are using the same private field, you never initialize it, since it is null (as I mentioned), then you try to set its value through setter, but what you pass there is null, hence you end up with nulls as well.
And C# provide something known as properties, so you don't need private fields. Unless you want to develop some additional logic for getters and setters.

A: As other users have stated, you are creating a new instance of Login which automatically initializes the fields to default values (null for reference types, 0 for numbers).
Also, you can look at removing the default constructor for Login class and have the following as constructor:
public Login(string username, string password)
{
    Username = username;
    Password = password;
}

By doing this, you can then do Login login = new Login("admin", "admin").
You can also look at Singleton pattern if you only wish to have one instance of Login class.


text:
Q: React.createElement() onClick does not work I'm iterating over a few SVG react components generated via SVGR that are saved in an array of objects, which works fine, the components render as they are supposed to, so far so good. Now I want to pass every Element an onclick function, which does not work for some reason. If I just say
{objectIconArray.map((object, i) => {
        return (
          <ScrollContainer
            key={i}
            className={`scroll-container iconToolbarRow ${object}`}
            id="xDragToolbar"
          >
            {Object.keys(object).map(function (icon, j) {
              return React.createElement(
                object[icon],
                {
                  key: j,
                  onClick: () => {
                    svgConvaEvent(icon);
                  },
                },
                null
              );
            })}
          </ScrollContainer>
        );
      })}
      })}

Nothing happens when I click a component, whereas if I remove the arrow function within the create element statement, like so:
{objectIconArray.map((object, i) => {
        return (
          <ScrollContainer
            key={i}
            className={`scroll-container iconToolbarRow ${object}`}
            id="xDragToolbar"
          >
            {Object.keys(object).map(function (icon, j) {
              return React.createElement(
                object[icon],
                {
                  key: j,
                  onClick:
                    svgConvaEvent(icon)

                },
                null
              );
            })}
          </ScrollContainer>
        );
      })}
      })}

the function svgConvaEvent gets invoked on render of every component, which would be normal behavior. Does anyone have a fix for this? Thanks in advance


text:
Q: Is there a convention for communicating the domain name of a server back to itself? I'm starting out learning Linux and NodeJS development and part of my current project has an API for which I'm serving documentation with Swagger UI. To support the "try it out" functionality of Swagger I need to specify a host name of the server in the API specs. Everything works fine when I'm running things locally and have the server hard coded to localhost:3000, but in production I obviously want this to show up as myactualdomain.example and not localhost.
Is there a convention for communicating to domain name of a server back to itself? I tried using a HOSTNAME environment variable as follows:
const HOSTNAME = process.env.HOSTNAME || "localhost";
var PORT = process.env.PORT || 80;
const apiSpecs = YAML.load("./api-spec.yml");
apiSpecs.servers = [{ url: `http://${HOSTNAME}:${PORT}` }];
app.use("/api-docs", swaggerUI.serve, swaggerUI.setup(apiSpecs));

This works, but sets the URL to the random host name the Docker container my app is running in is assigned. I could of course override HOSTNAME to myactualdomain.example but I'm not sure if this is "correct" way to do this or if the convention is to use a different environment variable or use another method entirely?


text:
Q: How to graph $\eta(t)=(t,|t|)$? We are studying lines (I am not quite sure about the correct term in English and could not find any other term for this from googling so please correct me if I am wrong) in our calculus class right now and this might be a dumb question but I am having a hard time understanding how to draw graphs.
As an example, we were given $\gamma:[0,2\pi]\to\mathbb{R}^2$, $\gamma(t)=(\cos{t},\sin{t})$ and said that it graphs a unit circle. However, it is not quite clear to me how does this happen. Does $\gamma$ take values from $[0,2\pi]$ and I plug them in such as $\gamma(0)=(\cos{0},\sin{0})=(1,0)$, which is the starting point, and $\gamma(2\pi)=(\cos{2\pi},\sin{2\pi})=(1,0)$, which is the ending point? I mean $t\in [0,2\pi]$ right? And when I connect the starting and ending points I get an unit circle.
Another example which actually confused me was we were given $\eta: I\to\mathbb{R}^2$, $\eta(t)=(t,|t|)$ where $I=[-1,1]$. This was graphed as

but I don't know how we got that. If I plug in the values as I did on the first example, $\eta(-1)=(-1,|-1|)=(-1,1)$ and $\eta(1)=(1,|1|)=(1,1)$ but if it is now true that $(-1,1)$ is the starting point and $(1,1)$ the ending point, why the graph is not just a straight line between these points? How did we suddenly connected the points to the origin $(0,0)$?

A: For the unit circle, if you know that $\cos^2 t + \sin^2 t = 1$, then it follows by deparameterizing the curve. Since $x = \cos t$, we have that $y^2 = \sin^2 t = 1-\cos^2 t = 1-x^2$, so the curve is given by $x^2+y^2 = 1$, or $y = \pm\sqrt{1-x^2}$. Since $\cos t$ and $\sin t$ are periodic with period $2\pi$, the graph for $t\in [0,2\pi]$ should be the entire circle, with the point $(1,0)$ being the starting and ending point.
For the absolute value, we do the same thing. We have $x = t$, so $y = |x|$ with $x\in [-1,1]$ Thus, we just graph the absolute value function only over the values $[-1,1]$ on the $x$-axis.
If you want to graph some parameterized curve like this without solving it algebraically (and sometimes you can't), you can simply plug in a bunch of values for $t$ in order and play connect-the-dots. The more $t$ values you use, the closer your approximation will be to the actual curve.


text:
Q: What happens if you don't resolve or reject a promise? I have a scenario where I am returning a promise.
The promise is basically triggered by an ajax request.
On rejecting the promise it shows an error dialog that there is a server error.
What I want to do is when the response code is 401, I neither want to resolve the promise nor reject it (because it already shows the error dialog). I want to simply redirect to the login page.
My code looks something like this:
function makeRequest(ur, params) {
  return new Promise(function (resolve, reject) {
    fetch(url, params).then((response) => {
      let status = response.status;
      if (status >= 200 && status < 300) {
        response.json().then((data) => {
          resolve(data);
        });
      } else {
        if (status === 401) {
          redirectToLoginPage();
        } else {
          response.json().then((error) => {
            if (!error.message) {
              error.message = constants.SERVER_ERROR;
            }
            reject({ status, error });
          });
        }
      }
    });
  });
}

As you can see, if the status is 401, I am redirecting to the login page. The promise is neither resolved nor rejected.
Is this code OK, or is there any better way to accomplish this?

A: I think the "what happens if we don't resolve reject" has been answered fine - it's your choice whether to add a .then or a .catch.
However, Is this code OK? Or is there any better way to accomplish this. I would say there are two things:
You are wrapping a Promise in new Promise when it is not necessary and the fetch call can fail, you should act on that so that your calling method doesn't sit and wait for a Promise which will never be resolved.
Here's an example (I think this should work for your business logic, not 100% sure):
const constants = {
  SERVER_ERROR: "500 Server Error"
};
function makeRequest(url,params) {
  // fetch already returns a Promise itself
  return fetch(url,params)
        .then((response) => {

            let status = response.status;

            // If status is forbidden, redirect to Login & return nothing,
            // indicating the end of the Promise chain
            if(status === 401) {
              redirectToLoginPage();
              return;
            }
            // If status is success, return a JSON Promise
            if(status >= 200 && status < 300) {
              return response.json();
            }
            // If status is a failure, get the JSON Promise,
            // map the message & status, then Reject the promise
            return response.json()
              .then(json => {
                if (!json.message) {
                    json.message = constants.SERVER_ERROR;
                }
                return Promise.reject({status, error: json.message});
              })
        });
}
// This can now be used as:
makeRequest("http://example", {})
  .then(json => {
    if(typeof json === "undefined") {
      // Redirect request occurred
    }
    console.log("Success:", json);
  })
  .catch(error => {
    console.log("Error:", error.status, error.message);
  })

By contrast, calling your code using:
makeRequest("http://example", {})
  .then(info => console.log("info", info))
  .catch(err => console.log("error", err));

Will not log anything because the call to http://example will fail, but the catch handler will never execute.

A: As others stated it's true that it's not really an issue if you don't resolve/reject a promise. Anyway I would solve your problem a bit different:
function makeRequest(ur,params) {

    return new Promise(function(resolve,reject) {

        fetch(url,params)
        .then((response) => {

            let status = response.status;

            if (status >= 200 && status < 300) {
                response.json().then((data) => {
                    resolve(data);
                })
            }
            else {
                reject(response);
            }
        })
    });
}

makeRequest().then(function success(data) {
   //...
}, function error(response) {
    if (response.status === 401) {
        redirectToLoginPage();
    }
    else {
        response.json().then((error) => {
            if (!error.message) {
                error.message = constants.SERVER_ERROR;
            }

            //do sth. with error
        });
    }
});

That means I would reject every bad response state and then handle this in your error handler of your makeRequest.

A: A promise is just an object with properties in Javascript.  There's no magic to it.  So failing to resolve or reject a promise just fails to ever change the state from "pending" to anything else.  This doesn't cause any fundamental problem in Javascript because a promise is just a regular Javascript object.  The promise will still get garbage collected (even if still pending) if no code keeps a reference to the promise.
The real consequence here is what does that mean to the consumer of the promise if its state is never changed?  Any .then() or .catch() listeners for resolve or reject transitions will never get called.   Most code that uses promises expects them to resolve or reject at some point in the future (that's why promises are used in the first place).  If they don't, then that code generally never gets to finish its work.
Or if code is using await on the promise instead of .then(), then that function will just remain suspended forever on that await.  The rest of the function will be dead code and will never execute.
It's possible that you could have some other code that finishes the work for that task and the promise is just abandoned without ever doing its thing.  There's no internal problem in Javascript if you do it that way, but it is not how promises were designed to work and is generally not how the consumer of promises expect them to work.

As you can see if the status is 401, I am redirecting to login page.
Promise is neither resolved nor rejected.
Is this code OK? Or is there any better way to accomplish this.

In this particular case, it's all OK and a redirect is a somewhat special and unique case.  A redirect to a new browser page will completely clear the current page state (including all Javascript state) so it's perfectly fine to take a shortcut with the redirect and just leave other things unresolved.  The system will completely reinitialize your Javascript state when the new page starts to load so any promises that were still pending will get cleaned up.

A: It works and isn't really a problem, except when a caller of makeRequest expects of promise to fulfil. So, you're breaking the contract there.
Instead, you could defer the promise, or (in this case) reject with status code/error.

A: The ECMAScript spec explains the purpose of promises and new Promise():

A Promise is an object that is used as a placeholder for the eventual results of a deferred (and possibly asynchronous) computation.
25.6.3.1 Promise ( executor )
NOTE The executor argument must be a function object. It is called for initiating and reporting completion of the possibly deferred action represented by this Promise object.

You should use promises to obtain future values.  Furthermore, to keep your code concise and direct, you should only use promises to obtain future values, and not to do other things.
Since you've also mixed program control flow (redirection logic) into your promise's "executor" logic, your promise is no longer "a placeholder for the results of a computation;" rather, it's now a little JavaScript program masquerading as a promise.
So, instead of wrapping this JavaScript program inside a new Promise(), I recommend just writing it like a normal JavaScript program:
async function makeRequest(url, params) {
  let response = await fetch(url, params);
  let { status } = response;
  if (status >= 200 && status < 300) {
    let data = await response.json();
    successLogic(data);
  } else if (status === 401) {
    redirectToLoginPage();
  } else {
    let error = await response.json()
    if (!error.message) {
      error.message = constants.SERVER_ERROR;
    }
    errorLogic({ status, error });
  }
}


text:
Q: Migrating on-premise server with RAID1 to EC2 I have an on-premise physical server running Debian 10 that I would like to migrate to AWS EC2. The server storage consists of two 1TB HDD drives on /dev/sda and /dev/sdb that have been set up as a RAID1 array with mdadm. Most of the capacity of the array is unused as I only have about 60GB of data on the server.
The server is running a lot of legacy software that I would prefer not to have to set up from scratch on a fresh instance, so I tried to use the AWS Application Migration Service for a quick and easy lift-and-shift which has worked great for me in the past. However, the EC2 instance refuses to start with the error message Client.InternalError: Client error on launch. I followed the troubleshooting guide but the drives were both attached and seem to be in a healthy state.
One thing I did notice is that EC2 wants to mount the other volume to /dev/sda1. The RAID array has two volumes:

*

*/dev/md0 is the boot volume and uses /dev/hda2 and /dev/hdb2

*/dev/md2 holds the root file system and uses /dev/hda4 and /dev/hdb4.

I tried to detach the volume mounted as /dev/hda1 and reattach it as /dev/hda but EC2 doesn't allow that:

Value (/dev/sda) for parameter device is invalid. /dev/sda is not a
valid EBS device name.

Is there a way to get this working or do I just have to bite the bullet and try to manually migrate all the services I set up in the Debian Etch era to a fresh instance?
Edit: Here's the output of fdisk -l, df and mdadm:
me@mybox ~ $ df
Filesystem     1K-blocks     Used Available Use% Mounted on
udev             3904748        0   3904748   0% /dev
tmpfs             791100    82712    708388  11% /run
/dev/md2       952731676 58111432 846197444   7% /
tmpfs            3955496        0   3955496   0% /dev/shm
tmpfs               5120        0      5120   0% /run/lock
tmpfs            3955496        0   3955496   0% /sys/fs/cgroup
/dev/md0          468009    80478    362562  19% /boot
tmpfs             791096        0    791096   0% /run/user/1000

me@mybox ~ $ sudo fdisk -l
Disk /dev/sdb: 931.5 GiB, 1000204886016 bytes, 1953525168 sectors
Disk model: WDC WD1002FBYS-5
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: EFCE7E13-5FF6-4EEE-9E5F-BCE87C01BE67

Device        Start        End    Sectors   Size Type
/dev/sdb1      2048       4095       2048     1M BIOS boot
/dev/sdb2      4096    1003519     999424   488M Linux RAID
/dev/sdb3   1003520   17004543   16001024   7.6G Linux RAID
/dev/sdb4  17004544 1953523711 1936519168 923.4G Linux RAID

Disk /dev/sda: 931.5 GiB, 1000204886016 bytes, 1953525168 sectors
Disk model: WDC WD1002FBYS-5
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: gpt
Disk identifier: 128EBD01-6A5E-4928-8B3A-010A11B3DFEA

Device        Start        End    Sectors   Size Type
/dev/sda1      2048       4095       2048     1M BIOS boot
/dev/sda2      4096    1003519     999424   488M Linux RAID
/dev/sda3   1003520   17004543   16001024   7.6G Linux RAID
/dev/sda4  17004544 1953523711 1936519168 923.4G Linux RAID

Disk /dev/md0: 487.7 MiB, 511377408 bytes, 998784 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/md1: 7.6 GiB, 8188264448 bytes, 15992704 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

Disk /dev/md2: 923.3 GiB, 991363399680 bytes, 1936256640 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes

me@mybox ~ $ sudo mdadm --misc --detail /dev/md0
/dev/md0:
           Version : 1.2
     Creation Time : Sat Jul 27 23:21:40 2013
        Raid Level : raid1
        Array Size : 499392 (487.69 MiB 511.38 MB)
     Used Dev Size : 499392 (487.69 MiB 511.38 MB)
      Raid Devices : 2
     Total Devices : 2
       Persistence : Superblock is persistent

       Update Time : Sat Aug 27 06:27:46 2022
             State : clean
    Active Devices : 2
   Working Devices : 2
    Failed Devices : 0
     Spare Devices : 0

Consistency Policy : resync

              Name : mybox:0  (local to host mybox)
              UUID : (redacted)
            Events : 376

    Number   Major   Minor   RaidDevice State
       0       8       18        0      active sync   /dev/sdb2
       1       8        2        1      active sync   /dev/sda2

A: Googled:
https://community.spiceworks.com/topic/2297594-can-we-migrate-a-physical-server-to-aws-if-yes-then-how-please-help
There is a small and excellent free tool that is capable of doing this called V2V Converter https://www.starwindsoftware.com/starwind-v2v-converter. Run it on the target system, specify the entire disk as a source, and provide your AWS credentials as the target. The tool will do the rest.
Basically, that will be a P2V conversion, and the server is migrated "as is". Make sure you are aware of the specifics and know what you are doing


text:
Q: What's the difference between 1 :| [2, 3, 4] and [1, 2, 3, 4] in Haskell I'm learning Haskell, one of the best functional-programming language. I've got roadblocks during my studies with the list. As I figured out there are two possibilities to write a list - just wrap using []. or use a NonEmpty list. What's the difference between these variants and what's better to use and why?

A: [1,2,3,4] is actually syntactic sugar for
Prelude> 1:2:3:4:[]
[1,2,3,4]

The [] type has two data constructors: : and []. You use : to 'cons' a value to an existing list. The empty list [] is the base case, so in order to be able to create a finite list, you'll have to terminate the 'cons chain' with an empty list, as in the above example.
In other words, while [1,2,3,4] is one valid example of a list, so is []. Lists can be empty.
As the name implies, NonEmpty can't be empty. It has only one data constructor: :|. Thus, the shortest list you can express using NonEmpty is a singleton list:
Prelude Data.List.NonEmpty> 1 :| []
1 :| []

While the right-hand side of :| does accept an empty list ([]), you must supply a value for the left-hand side (in the above example 1). Thus, a NonEmpty list will always contain at least one element.
These properties are guaranteed at compile time, so if you need a non-empty list, use NonEmpty, and if you need a list that may be empty, use [].


text:
Q: MySQL query works through workbench but not mysqli I am attempting to call my PHP class and run the function get_group_count which counts the number of groups for a certain user ID. The mysqli query uses a stored procedure that works in MySQL Workbench but not with PHP's mysqli.
Public function:
public function get_group_count($userID) {
    if($this->status()) {
        $db = Database::getInstance();
        $con = $db->getConnection();

        $pull = $con->prepare("CALL get_group_count(?)");
        $pull->bind_param('i', $userID); // line 19

        if(!$pull->execute()) {
            $pull->close();
            return false;
        };

        $pull->store_result();
        $pull->bind_result($count);
        $pull->fetch();
        $pull->close();

        return $count;
    };
    return false;
}

Error:
Call to a member function bind_param() on a non-object in ... on line 19

Stored procedure:
DELIMITER //
CREATE PROCEDURE get_group_count(IN userID int)
BEGIN
    SELECT (SELECT count(*) FROM groups WHERE adminID = userID) + (SELECT count(*) FROM members WHERE userID = userID) AS count;
END //
DELIMITER ;

When calling the procedure through MySQL Workbench it returns a total number of rows from the groups table and members table.
Note: I also get the same error when attempting to run the query through mysqli rather than the stored procedure.
How can I fix this?
EDIT:
$con var_dump:
object(mysqli)#4 (19) {
  ["affected_rows"]=>
  int(1)
  ["client_info"]=>
  string(6) "5.5.45"
  ["client_version"]=>
  int(50545)
  ["connect_errno"]=>
  int(0)
  ["connect_error"]=>
  NULL
  ["errno"]=>
  int(2014)
  ["error"]=>
  string(52) "Commands out of sync; you can't run this command now"
  ["error_list"]=>
  array(1) {
    [0]=>
    array(3) {
      ["errno"]=>
      int(2014)
      ["sqlstate"]=>
      string(5) "HY000"
      ["error"]=>
      string(52) "Commands out of sync; you can't run this command now"
    }
  }
  ["field_count"]=>
  int(1)
  ["host_info"]=>
  string(25) "Localhost via UNIX socket"
  ["info"]=>
  NULL
  ["insert_id"]=>
  int(0)
  ["server_info"]=>
  string(14) "5.5.45-cll-lve"
  ["server_version"]=>
  int(50545)
  ["stat"]=>
  string(52) "Commands out of sync; you can't run this command now"
  ["sqlstate"]=>
  string(5) "HY000"
  ["protocol_version"]=>
  int(10)
  ["thread_id"]=>
  int(36623197)
  ["warning_count"]=>
  int(0)
}

$pull var_dump:
bool(false)
NULL

EDIT2: Ended up switching to PDO, everything works now.

A: After looking at the $con dump, it appears that the last query you're executing on this connection is not using its result. mysqli uses unbuffered queries by default, so you need to either fetch the result of the previous query executed into a buffer manually, or free the memory that it's using to make room for your new query, with either store_result() or free_result(), respectively.


text:
Q: How to keep removing values at odd places from a vector until we're just left with one? Let J be a vector having values (0, 1, 1, 2, 3, 5, 8, 3, 1)
I want to keep removing all values from odd places from the vector until J has only one element left in it.
(0, 1, 1, 2, 3, 5, 8, 3, 1) => (1, 2, 5, 3)  => (2,3) => (3)
How do I achieve this?
My approach:
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

int main()
{
  int J[] = {0, 1, 1, 2, 3, 5, 8, 3, 1};
  int len=sizeof(J)/sizeof(J[0]);
  vector<int> Jvec;
  for (int i=0; i<len; i++) {  //Putting the values of array into Jvec
    Jvec.push_back(J[i]);
  }

  while (Jvec.size()!=1) {
    vector<int> oddJ;
    for (int k=0; k<Jvec.size(); k=k+2) {  //Storing values of odd places
      oddJ.push_back(Jvec[k]);
    }

    for (int i=0; i<oddJ.size(); i++) {
      Jvec.erase(remove(Jvec.begin(), Jvec.end(), oddJ[i]), Jvec.end()); //removing values from vector by value, not index
    }
  }
  cout << Jvec[0];
  return 0;
}

I'm getting 5 instead of 3. Is my logic faulty? Where am I going wrong?

A: Actually, there is a quite neat and fast solution to your problem.
Since you'd like to remove the 1st, 3rd, 5th, etc. indices on each step, the arrays are 0-based, you should actually remove the 0th, 2nd, 4th indices on each step.
Here are some observations, that are helpful when searching the answer:

*

*On each step, the array gets halved, meaning that in O(logN) steps you will get an array of size 1.

*On the last step, the searched value has index 0.

*On each step (but the last one), the searched value has an odd index, so that it's preserved, until the array size gets 1.
So, on the last step the index of the searched value is 0, on the previous step it had index 1, on the step before that it had index 3 and so on.
We can clearly see that that starting from 0, the index gets doubled and then 1 is added, so that it gets odd and not deleted. This happens exactly log n times.
So, in order to track the index of the number that we should print in the end, we can do:
int[] values = {0, 1, 1, 2, 3, 5, 8, 3, 1};
int n = values.length, index = 0;
while (n > 1) {
  index = 2 * index + 1;
  n /= 2;
}
System.out.println(values[index]);

I wrote the code in Java, but you can easily adapt it do your language of choice.
This gives an overall complexity of O(logN), where N is the size of the values array.

A: Although correct solutions have been already provided, the same result can be achieved with somewhat simpler code:
#include <iostream>
#include <vector>

using std::cout;
using std::vector;

int main()
{
   vector<int> v = { 0, 1, 1, 2, 3, 5, 8, 3, 1 };

   while (v.size() > 1)
   {
        for(size_t i = 0; i < v.size(); i++)
        {
            v.erase(v.begin() + i);
        }
        for (const auto &i : v) cout << i << ' ';
        cout << '\n';
   }
   return 0;
}

A: To answer your question, where you are going wrong: std::remove removes all elements of the given value, so if you apply it the second time on the "1" it actually removes both ones, same with the "3" later on. See Erase-remove idiom. To see how to solve your problem in general see comment from Renat: How to remove odd positions from a list?

A: In C++ indices of arrays and standard containers start from 0. So it woul be more correctly to say

How to keep removing values at even places from a vector until
  we're just left with one?

Here is a demonstrative program that shows how it can be done.
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

int main()
{
    std::vector<int> v = { 0, 1, 1, 2, 3, 5, 8, 3, 1 };

    while ( v.size() > 1 )
    {
        // comment these two statements in the release version
        for ( const auto &item : v ) std::cout << item << ' ';
        std::cout << '\n';

        std::vector<int>::size_type i = 0;

        auto even_pos = [&i] ( const auto & ) { return i++ % 2 == 0; };

        v.erase( std::remove_if( std::begin( v ), std::end( v ), even_pos ),
                 std::end( v ) );
    }

    for ( const auto &item : v ) std::cout << item << ' ';
    std::cout << '\n';

    return 0;
}

The program output is
0 1 1 2 3 5 8 3 1
1 2 5 3
2 3
3

As for your code then this call
Jvec.erase(remove(Jvec.begin(), Jvec.end(), oddJ[i]), Jvec.end());

erases not only one but all elements equal to oddJ[i] from the vector Jvec.
So for example if oddJ[i] is equal to 3 then two elements at positions 4 and 7 will be deleted from the vector Jvec.


text:
Q: R loop over a list Hi I'm new here and also quite new to R.
Would be great if anyone could please help me here.
I'm trying to make a for loop to get the desired output but a little struggling at the moment.
Let's suppose I have a table below:
> d
  names    variables            value
1 colour   c(red, blue)         10
2 colour   c(yellow, blue)      32
3 colour   c(green, red, pink)  81
4 colour   c(pink, purple)      14
5 shape    c(circle, triangle)  5
6 shape    c(rectangle)         31
7 .....

What I'm trying to do is to create a for loop going over the variables for each name.
If a target variable for each name exist, then set the original value to be 0 and make a duplicated row with value taking the negative value of the original value.
As an example, let's say our target variable for colour is 'red'.
What I want the output to look like is:
> d1
  names    variables            value
1 colour   c(red, blue)         0
2 colour   c(yellow, blue)      32
3 colour   c(green, red, pink)  0
4 colour   c(pink, purple)      14
5 colour1  c(red, blue)         -10
6 colour2  c(green, red, pink)  -81
7 shape    c(circle, triangle)  5
8 shape    c(rectangle)         31
7 .....

I hope I'm making sense.
Any help or comments would be appreciated.
Thanks!!

A: You can do this with tidyverse:

*

*First we use str_detect from stringr package (it is in tidyverse) to identify those rows with red ind variables.

*Then we add 1 and 2 (=row_number) to names and multiple value by -1 to get the negative values.

*we use bind_rows from dplyr package (it is in tidyverse) to bind to original dataframe.

*Then we use an ifelse statement to set variables red to 0 in value (assuming the original values are > 0.

*we use as_tibble() to remove the rownames and finally arrange
library(tidyverse)

df %>%
  filter(str_detect(variables, "red")) %>%
  mutate(names = paste0(names, row_number()),
         value = value*-1) %>%
  bind_rows(df) %>%
  mutate(value = ifelse(str_detect(variables, "red") &
                          value > 0, 0, value)) %>%
  as_tibble() %>%
  arrange(names)

  names   variables           value
  <chr>   <chr>               <dbl>
1 colour  c(red, blue)            0
2 colour  c(yellow, blue)        32
3 colour  c(green, red, pink)     0
4 colour  c(pink, purple)        14
5 colour1 c(red, blue)          -10
6 colour2 c(green, red, pink)   -81
7 shape   c(circle, triangle)     5
8 shape   c(rectangle)           31

structure(list(names = c("colour", "colour", "colour", "colour",
"shape", "shape"), variables = c("c(red, blue)", "c(yellow, blue)",
"c(green, red, pink)", "c(pink, purple)", "c(circle, triangle)",
"c(rectangle)"), value = c(10L, 32L, 81L, 14L, 5L, 31L)), class = "data.frame", row.names = c("1",
"2", "3", "4", "5", "6"))

A: Here a solution with Base R only, using TarJae's construction of the data, for a dataframe x:
# Create a vector with the row indeces that contain the target string:
target <- grep( 'red', x[ , 2 ] )
# Put these rows away in a separate data.frame:
stash <- x[ target, ]
# Set the value of the original rows to `0`
x[ target, 3 ] <- 0
# Set the values in the separated rows to their negative value
stash[ , 3 ] <- stash[ , 3 ] * -1
# Modify `names` as desired:
for( i in 1 : length( stash[ , 1 ] ) )
    stash[ i, 1 ] <-  paste( stash[ i, 1 ], i, sep = "" )

# Insert the modified data (supposes that the dataframe is expected
# to be sorted on the first column):
x <- rbind( x, stash )
x <- x[ order(x[ 1 ] ),  ]

That gives you
> x
     names           variables value
1   colour        c(red, blue)     0
2   colour     c(yellow, blue)    32
3   colour c(green, red, pink)     0
4   colour     c(pink, purple)    14
11 colour1        c(red, blue)   -10
31 colour2 c(green, red, pink)   -81
5    shape c(circle, triangle)     5
6    shape        c(rectangle)    31

This works as well if you replace 'red' with 'blue' or with 'rectangle'. For the extended question in your comment: One could create a vector with the targets (such as c( "red", "triangle" ), then loop over the code above, writing each output into a list. More sample data and information about your desired output would be needed, though. As a first step, you could try:
crit <- c( "rectangle", "red", "blue" )     # vector with target values
y <- list()                                 # initialize receiving list
for( j in 1 : length( crit ) )
{
    target <- grep( crit[ j ], x[ , 2 ] )
    stash <- x[ target, ]
    stash[ , 3 ] <- stash[ , 3 ] * -1
    # Modify `names` as desired:
    for( i in 1 : length( stash[ , 1 ] ) )
        stash[ i, 1 ] <-  paste( stash[ i, 1 ], ( 10 * i + j ), sep = "" )

    # write to list element instead of overwriting original dataframe
    y[[ j ]] <- rbind( x, stash )
    y[[ j ]][ target, 3 ] <- 0      # Set the value of the original rows to `0`
    y[[ j ]] <- y[[ j ]][ order( y[[ j ]][ 1 ] ),  ]
    # here, you have a list with individual dataframes for each target value

    # you could merge into one joint dataframe with
    z <- Reduce( function( x, y, ... ) merge( x, y, all = TRUE, ... ), y )
}

That produces
> z
      names           variables value
1    colour c(green, red, pink)     0
2    colour c(green, red, pink)    81
3    colour     c(pink, purple)    14
4    colour        c(red, blue)     0
5    colour        c(red, blue)    10
6    colour     c(yellow, blue)     0
7    colour     c(yellow, blue)    32
8  colour12        c(red, blue)   -10
9  colour13        c(red, blue)   -10
10 colour22 c(green, red, pink)   -81
11 colour23     c(yellow, blue)   -32
12    shape c(circle, triangle)     5
13    shape        c(rectangle)     0
14    shape        c(rectangle)    31
15  shape11        c(rectangle)   -31

and may be a good start for further work


text:
Q: magento2 invoice paid status I'm creating an invoice module for Magento2 and I've got my custom payment method setup and working. (Customers can select it, it does its things and works, etc)
I'm stuck on the next step though, and what I want to happen is that when the administrator in the back-end generates an invoice the status for the invoice should be "Unpaid" and not the default "Paid". The administrator then prints out the invoice, sends to the customer, and when they receive the payment they should be able to change it to Paid manually and complete the order.
I assume I should start somewhere by extending adminhtml in one of the default magento modules but I'm not sure where. Any help is appreciated, thank you.

A: I think you should add Unpaid status in magento Admin Panel(or by the migration script), and you should set it as default to processing state.
take a look on those tables:
sales_order_status
sales_order_status_history
sales_order_status_label
sales_order_status_state


text:
Q: beautiful soup find_all returning the None type im new to bs4 and thought trying to scrape the descrpitions of the main 9 strawhat pirates(from luffy to brook) would be an ok way to practice what i know so far. but whenever i use find to get the  tag related to each pirate it returns none instead of the aside tag.
input
import requests
from bs4 import BeautifulSoup

url = 'https://onepiece.fandom.com/wiki/Straw_Hat_Pirates'
response = requests.get(url)
soup = BeautifulSoup(response.text, 'html.parser')
straw_section = soup.find('table', 'cs StrawHatPiratesColors')
pirates = straw_section.find_all('div', class_ = 'Gallery-pic')
pirate_links=[pirate.a['href'] for count, pirate in enumerate(pirates) if count < 9]

def prt_crawler():
    for pirate_link in pirate_links:
        prt_response = requests.get( "https://onepiece.fandom.com/wiki" + pirate_link)
        prt_soup = BeautifulSoup(prt_response.text, 'html.parser')
        prt_section = prt_soup.find('aside', class_ = 'portable-infobox pi-background pi-theme-CharBox pi-theme-StrawHatPiratesColors pi-layout-default')
        print(prt_section)
        print()

prt_crawler()

output
None

None

None

None

None

None

None

None

None

ive tried both lmxl and html.parser, neither seem to make a difference
i was expecting to get nine variations of this html code:

Monkey D. Luffy

                Anime post-timeskip

                Anime pre-timeskip

                Manga post-timeskip

                Manga pre-timeskip

                    <img src="https://static.wikia.nocookie.net/onepiece/images/6/6d/Monkey_D._Luffy_Anime_Post_Timeskip_Infobox.png/revision/latest/scale-to-width-down/239?cb=20200429191518" srcset="https://static.wikia.nocookie.net/onepiece/images/6/6d/Monkey_D._Luffy_Anime_Post_Timeskip_Infobox.png/revision/latest/scale-to-width-down/239?cb=20200429191518 1x, https://static.wikia.nocookie.net/onepiece/images/6/6d/Monkey_D._Luffy_Anime_Post_Timeskip_Infobox.png/revision/latest/scale-to-width-down/478?cb=20200429191518 2x" class="pi-image-thumbnail" alt="Anime post-timeskip" width="239" height="500" data-image-key="Monkey D. Luffy Anime Post Timeskip Infobox.png" data-image-name="Monkey D. Luffy Anime Post Timeskip Infobox.png">

                    <img src="https://static.wikia.nocookie.net/onepiece/images/e/e5/Monkey_D._Luffy_Anime_Pre_Timeskip_Infobox.png/revision/latest/scale-to-width-down/255?cb=20200124060150" srcset="https://static.wikia.nocookie.net/onepiece/images/e/e5/Monkey_D._Luffy_Anime_Pre_Timeskip_Infobox.png/revision/latest/scale-to-width-down/255?cb=20200124060150 1x, https://static.wikia.nocookie.net/onepiece/images/e/e5/Monkey_D._Luffy_Anime_Pre_Timeskip_Infobox.png/revision/latest/scale-to-width-down/511?cb=20200124060150 2x" class="pi-image-thumbnail" alt="Anime pre-timeskip" width="256" height="500" data-image-key="Monkey D. Luffy Anime Pre Timeskip Infobox.png" data-image-name="Monkey D. Luffy Anime Pre Timeskip Infobox.png">

                    <img src="https://static.wikia.nocookie.net/onepiece/images/d/d8/Monkey_D._Luffy_Manga_Post_Timeskip_Infobox.png/revision/latest/scale-to-width-down/293?cb=20141011154302" srcset="https://static.wikia.nocookie.net/onepiece/images/d/d8/Monkey_D._Luffy_Manga_Post_Timeskip_Infobox.png/revision/latest/scale-to-width-down/293?cb=20141011154302 1x, https://static.wikia.nocookie.net/onepiece/images/d/d8/Monkey_D._Luffy_Manga_Post_Timeskip_Infobox.png/revision/latest/scale-to-width-down/586?cb=20141011154302 2x" class="pi-image-thumbnail" alt="Manga post-timeskip" width="270" height="461" data-image-key="Monkey D. Luffy Manga Post Timeskip Infobox.png" data-image-name="Monkey D. Luffy Manga Post Timeskip Infobox.png">

                    <img src="https://static.wikia.nocookie.net/onepiece/images/7/72/Monkey_D._Luffy_Manga_Pre_Timeskip_Infobox.png/revision/latest/scale-to-width-down/312?cb=20210427074037" srcset="https://static.wikia.nocookie.net/onepiece/images/7/72/Monkey_D._Luffy_Manga_Pre_Timeskip_Infobox.png/revision/latest/scale-to-width-down/312?cb=20210427074037 1x, https://static.wikia.nocookie.net/onepiece/images/7/72/Monkey_D._Luffy_Manga_Pre_Timeskip_Infobox.png/revision/latest/scale-to-width-down/624?cb=20210427074037 2x" class="pi-image-thumbnail" alt="Manga pre-timeskip" width="270" height="370" data-image-key="Monkey D. Luffy Manga Pre Timeskip Infobox.png" data-image-name="Monkey D. Luffy Manga Pre Timeskip Infobox.png">

Introduction • Gallery • Personality • Relationships • Abilities and Powers • History • Misc.

Statistics

Japanese Name:

モンキー・<ruby lang="ja"><rb>D</rb><rp>(</rp><rt>ディー</rt><rp>)</rp></ruby>・ルフィ

Romanized Name:

Monkī Dī Rufi

Official English Name:

Monkey D. Luffy

Debut:

Chapter 1;[1] Episode 1[2]

Affiliations:

Straw Hat Pirates;

Ninja-Pirate-Mink-Samurai Alliance;

Dadan Family (former);

Impel Down (former)

Occupations:

Pirate; Captain[2]; Prisoner (former); Bandit (former)

Residence:

Foosha Village (former); Mt. Colubo (former); Rusukaina (former)

Alias:

Lucy (ルーシー, Rūshī?)[3]

Luffy-tarou[4] (ルフィ太郎, Rufitarō?, English version: "Luffytaro")[5]

Luffy-no-Umi (ルフィの海, Rufinoumi?)[6]

Epithet:

Straw Hat Luffy (麦わらのルフィ, Mugiwara no Rufi?)[7]

Status:

Alive

Age:

7 (debut);

17 (pre-timeskip)[9];

19 (post-timeskip)[10][11]

Birthday:

May 5th (Children's Day)[12]

Height:

91 cm  (2'11¾) (debut)[4]

172 cm (5'7¾") (pre-timeskip)[13][14]

174 cm (5'8½") (post-timeskip)[12][15]

Blood Type:

F[8]

Bounty:

1,500,000,000[16]

<s>500,000,000</s>[17][18]

<s>400,000,000</s>[19]

<s>300,000,000</s>[20]

<s>100,000,000</s>[21]

<s>30,000,000</s>[22]

Japanese VA:

Mayumi Tanaka,
 Urara Takano (OVA)

Odex English VA:

Chuck Powers

4Kids English VA:

Bella Hudson

Funi English VA:

Colleen Clinkenbeard

Devil Fruit

Japanese Name:

Gomu Gomu no Mi

English Name:

Gum-Gum Fruit

Meaning:

Rubber

Type:

Paramecia[23]

A: The trick here is to find the element you want and go up in tags until you find a sequence you can use to get to the said element. In this case, there are only 69 elements that go from body to tr to the and from 9 to 17 are the ones you are looking for. Keep in mind that this is a quick and "dirty" way to do it, there could be a better way to solve the problem.
for i in range(9, 18):
    soup.select("tbody > tr > th")[i].text.strip()


text:
Q: Why does it work to print the 4th element when I've only malloc-ated 3? Here's an example:
%load_ext cython

%%cython -a

from libc.stdlib cimport malloc

def main():
    cdef int *qux = <int*>malloc(3*sizeof(int))
    qux[0] = 4
    qux[1] = 5
    qux[2] = 6
    qux[3] = 7
    print(qux[0])
    print(qux[3])

I was expecting the first print statement to work, but for either qux[3] = 7 to fail, or print(qux[3]) to print garbage. However, it correctly prints 7.
Why is this? Does it not matter how much I malloc to qux?


text:
Q: Scrollable TextView between views I have TextView (green A) between 2 views.

Normally I want the B view to appear below A view. But when the TextView's content will be big enough that the B view will meet the bottom of the screen, I want to be able to scroll that 'excessive' A's content. How can I achieve this?

A: You can achieve this by many methods, i will list 3:
Put A and B views inside a ScrollView.
Put A inside a ScrollView.
To scroll the 'excessive' A's content, search on google and use an ScrollableTextView.

A: I found a solution but forgot to post it here. So, to achieve this, we need to somehow force a ScrollView's measurement to take place after other views' measurements in a layout. And we can do it by setting layout_weight attribute in ScrollView. So basically, our layout should look like this:
<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    >

    <View
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

     <ScrollView
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1"
        android:fillViewport="true"
        >

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />
    </ScrollView>

    <View
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

</LinearLayout>


text:
Q: How do I make a formula to find the dimensions of a shape that is offset from the original by 1/4 inch? I am trying to make a formula that given 3 lengths (left height, right height and base) it can give me new lengths of a shape that is 1/4" offset out from every side.
For example given this shape:
example shape
I need to find what the new dimensions would be for a similar shape that is off set 1/4" on every side like so:
Offset shape by 1/4" in green
I know for the base it will always be current base + 0.5". However left and right height change based off the slope.
Here is what I was trying to no avail, not sure if it is right:
Attempt Pic 1
Left height = 30"
Right height = 10.5"
Base = 60"
Attempt Pic 2
The easiest offset is for the Base as it is just adding 1/2"
Base = 60"+0.5"
Base = 60.5"
Attempt Pic 4
separate the triangle
a=Base
b=Left Height-Right Height
c= √(a²+b²)
a=60"
b=19.5"
c=63.08922253"
∠bc=tan^-1(a/b)
∠bc=tan^-1(60"/19.5")
∠bc=72°
Attempt Pic 4
Next is finding the radius of the inscribed circle:
r= (ab/a+b+c)
r= ((60")(19.5")/60"+19.5"+63.08922253")
r= 8.205388733"
Next is the radius of the offset circle:
r=8.205388733"+.25
r=8.455388733"
The ratio between the two radius is:
1.030467783
After I got that far I used the ratio x the triangle lengths to get the offset triangle however when I tried to add it back to the original shape it kept coming out with the wrong dimensions.
I don't know if what I am doing makes sense but this is where I am stuck.
After I figure out an equation for this shape I will then need to make one for this type to, however it has one extra dimensions which is left inset.
Other shape

A:
From the above figure you can see that the length that has to be deducted from
the original (black) sides at the intersection is
$ a = t \cot(\dfrac{\theta}{2}) $
where $\theta $ is the angle between the two black sides.
So, with the given example, the sides are: $30, 60, 10.5, \sqrt{19.5^2 + 60^2} $.  The bottom angles are $90^\circ$ each, while the top left is $\theta^* = \tan^{-1}\left( \dfrac{60}{19.5} \right) \approx 72^\circ$
Hence, using the above calculation, the bottom side will be reduced by $2 \times 0.25'' $ , the left side will be reduced by $0.25'' + 0.25'' \times \cot(36^\circ) = 0.594'' $, and the right side will be reduced by $0.25'' + 0.25'' \cot(0.5(180 - 72)^\circ ) = 0.431''$, and finally the top side will be reduced by $0.25'' (\cot(36^\circ) + \cot(54^\circ) ) = 0.526'' $
Hence the sides of the new shape are
Bottom:  $60'' - 0.5'' = 59.5''$
Left Height: $30'' - 0.594'' = 29.406''$
Right Height: $10.5'' - 0.431'' = 10.069''$
Top Side:  $\sqrt{60^2 + 19.5^2} - 0.526'' = 62.563''$


text:
Q: Read Hyperlinks, changing data to bold and font size through apache POI I am working on an automation project in which I am using Java with Apache POI to read the data from excel. However, my requirement is to read the hyperlink and it should remain as a hyperlink only as I am importing hyperlinks into a desktop application.
Plus I want other formatting should also get copied into that application.
FYI: Desktop application can do everything that an excel can do.

A: Assuming that you already have a sheet object created out of a workbook object, the next step is to just read the hyperlinks using apache poi, the following snippet should do the job:
Cell cell = sheet.getRow(0).getCell(0);
Hyperlink link = cell.getHyperlink();

But again, does your cell contain multiple URLs or a single URL...?
Also, regarding the formatting can you elaborate your question a bit more with some example?
P.S: Everything you need is already well documented here: http://poi.apache.org/components/spreadsheet/quick-guide.html