text:
Q: Compare dataframe columns: TypeError: Cannot interpret 'StringDtype' as a data type I am trying to compare two dataframes columns and types to check for equality, the rows are expected to be different.
I am using pandas version 1.1.2
pd.__version__
'1.1.2'

if (df1.columns.difference(df2.columns).empty) and
                (df1.dtypes == df2.dtypes).all()

But this line errors:
(df1.dtypes == df2.dtypes).all()

Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/Users/vfrank/dev-working/venv/lib/python3.7/site-packages/pandas/core/ops/common.py", line 65, in new_method
    return method(self, other)
  File "/Users/vfrank/dev-working/venv/lib/python3.7/site-packages/pandas/core/ops/__init__.py", line 370, in wrapper
    res_values = comparison_op(lvalues, rvalues, op)
  File "/Users/vfrank/dev-working/venv/lib/python3.7/site-packages/pandas/core/ops/array_ops.py", line 239, in comparison_op
    res_values = comp_method_OBJECT_ARRAY(op, lvalues, rvalues)
  File "/Users/vfrank/dev-working/venv/lib/python3.7/site-packages/pandas/core/ops/array_ops.py", line 53, in comp_method_OBJECT_ARRAY
    result = libops.vec_compare(x.ravel(), y.ravel(), op)
  File "pandas/_libs/ops.pyx", line 169, in pandas._libs.ops.vec_compare
TypeError: Cannot interpret 'StringDtype' as a data type

What is going on and how do I workaround this problem?
Update for the datatypes for the first dataframe:
df1.dtypes
update_timestamp                 string
issue_type_desc                  string
id                                Int64
project_key                      string
teamname                         string
issue_key                        string
summary                          string
created_at                       string
updated_at                       string
updated_at_utc                   string
status_updated_at                string
resolved_at                      string
closed_at                        string
due_date                         string
age_ts                            Int64
resolution_seconds               string
reporter_name                    string
assignee                         string
issue_type_id                     Int64
priority_id                       Int64
status_id                         Int64
status_detail                    string
status_category                  string
resolution_id                    string
security_level_id                 Int64
parent_issue_key                 string
subtask_parent_key               string
subtask_parent_id                 Int64
subtask_key                      string
epickey                          string
epic_id                           Int64
epic_parent_key                  string
customfield_fversion             string
customfield_10004                string
epicdesc                         string
customfield_10005                string
sprint                           string
customfield_10003_original       string
customfield_10003_status         string
storypoint                      float64
storyhours                      float64
subtaskhours                     string
subcategory                      string
customfield_feature              string
zephyr_last_executed_at          string
zephyr_last_executed_by          string
zephyr_last_execution_status     string
fix_versions                     string
deleted                           Int64
lastupdateddatetime              string
dtype: object

And for the datatypes for the second dataframe:
df2.dtypes
update_timestamp                string
issue_type_desc                 string
id                               Int64
project_key                     string
teamname                        string
issue_key                       string
summary                         string
created_at                      string
updated_at                      string
updated_at_utc                  string
status_updated_at               string
resolved_at                     string
closed_at                       string
due_date                        string
age_ts                           Int64
resolution_seconds              string
reporter_name                   string
assignee                        string
issue_type_id                    Int64
priority_id                      Int64
status_id                        Int64
status_detail                   string
status_category                 string
resolution_id                   string
security_level_id                Int64
parent_issue_key                string
subtask_parent_key              string
subtask_parent_id                Int64
subtask_key                     string
epickey                         string
epic_id                          Int64
epic_parent_key                 string
customfield_fversion            string
customfield_10004               string
epicdesc                        string
customfield_10005               string
sprint                          string
customfield_10003_original      string
customfield_10003_status        string
storypoint                      string
storyhours                      string
subtaskhours                    string
subcategory                     string
customfield_feature             string
zephyr_last_executed_at         string
zephyr_last_executed_by         string
zephyr_last_execution_status    string
fix_versions                    string
deleted                          Int64
lastupdateddatetime             string
dtype: object

Update so far I have been able to get around this error by writing a function to the do the comparision, but that does not seem like the ideal solution. I would expect there to be a way to do dtype comparison with this new extension type:
def compare_dataframe_column_dtypes(df_compare1, df_compare2):
    """Since pandas 1.0.0 and the inception of the StringDtype
    doing `df1.dtypes == df2.dtypes` will fail on StringDtype,
    so in order to compare dataframes one must catch this error
    and convert to prior pd 1.0.0 string dtype and compare again.
    """
    df1 = df_compare1.copy()
    df2 = df_compare2.copy()
    try:
        if (df1.dtypes == df2.dtypes).all():
            return True
        return False
    except Exception as ex:
        logger.error("%s. Converting datatypes StringDType to str and then comparing again", ex.args[0])
        for column in df1:
            if pd.StringDtype.is_dtype(df1[column]):
                df1[column] = df1[column].astype(str)
        for column2 in df2:
            if pd.StringDtype.is_dtype(df2[column2]):
                df2[column2] = df2[column2].astype(str)
        if (df1.dtypes == df2.dtypes).all():
            return True
        return False

A: I stumbled upon this late, but you might be able to convert them to dictionaries and compare them
if (dict(df1.dtypes) == dict(df2.dtypes)):
        return True
    return False

https://docs.python.org/3/library/stdtypes.html#mapping-types-dict


text:
Q: R shinydashboard fit image into box element I have a Shiny dashboard App that is rendering a image based on a filter, so depending on the chosen value in a filter an image is displayed inside a box. However some images are too big and are rendered outside of the box, meaning the box is not containing the the whole image.
If I try to display the same image with img(src="imagename", height = 200) the image is automatically fitted into the box. How can I replicate the same but with the imageOutput() function?
Here a snippet of how the code looks like:
library("shiny")
library("shinydashboard")

sidebar <- dashboardSidebar()

body <- dashboardBody(
    fluidRow(
        box(imageOutput("image")) # IMAGE TOO BIG AND BOX CANNOT COMPLETELY CONTAIN IT
        img(src="imagename", height = 200) # Image adjusted to box size

    )
)

ui <- dashboardPage(dashboardHeader(title = "Example"),
                    sidebar,
                    body
)

server <- function(input, output) {

 output$image <- renderImage({

    filename <- normalizePath(file.path(paste('www/',imagename, '.png', sep='')))
        list(src = filename)},
        deleteFile = FALSE)
})
}

shinyApp(ui, server)

A: You can set the height in the list you return with renderImage:
output$image <- renderImage({
  filename <- normalizePath(file.path(paste0('www/', imagename, '.png')))
  list(
    src = filename,
    height = 200
  )
}, deleteFile = FALSE)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Maxima: generating a list of nouns with "multi-dimensional" subscripts I want to generate a list of subscripted nouns where the subscripts are "multi-dimensional".
For instance, using the two following lists as input:
[1,5,2]
[3,5,1]

I want to generate the following list:
[a[3,1],a[5,5],a[1,2]]

Here is a working example:
(%i1) indexX : [1,5,2];
(%i2) indexY : [3,5,1];
(%i3) makelist(a[i], i, indexX);
(%i4) map(endcons, indexY, %);

(%o1) [1,5,2]
(%o2) [3,5,1]
(%o3) [a[1],a[5],a[2]]
(%o4) [a[3,1],a[5,5],a[1,2]]

That works, but it requires two lines (call to makelist() then to map()). Hence it is not very elegant.
Is there a better way to achieve similar results?
Note: Arrays are not suitable for the job because 1. indices can be negative numbers and 2. I don't want to allocate memory for all indices between [1,1] and [5,5] since I am only using a few of them.

A: (%i1) display2d: false $
(%i2) indexX : [1,5,2] $
(%i3) indexY : [3,5,1] $
(%i4) map(lambda([[L]], arraymake('a, L)), indexX, indexY);
(%o4) [a[1,3],a[5,5],a[2,1]]


text:
Q: Django make query about .save() DB TABLE (null is ok)
select * from TESTDB;
id | AAA | BBB | CCC |
======================

Django code
new_dataset = TESTDB(BBB = 222)
new_dataset.save()

I want to change code like this...
target_field = 'BBB'
new_dataset = TESTDB( target_field = 222 )
new_dataset.save()

How can I complete this code?

A: You can use dict as keyword arguments feature of Python:
target_field = 'BBB'
new_dataset = TESTDB(**{target_field: 222})
new_dataset.save()


text:
Q: How to expand the file system for RPi emulation with QEMU? I've recently grabbed a pre-compiled version of QEMU running Raspbian Wheezy for use on Windows as I would like to do some testing and a dev environment like this is far more kind than using the actual device.
The only problem I have come across is that after the initial boot the device doesn't have much free space and I can't use raspi-config to expand the device at all. I am assuming this is because I'm not running it on any particular virtual disk, or I am but it is of fixed size?
Below is the batch file which runs the virtual machine in question.
qemu-system-arm.exe -M versatilepb -cpu arm1176 -hda 2012-07-15-wheezy-raspbian.img -kernel kernel-qemu -m 192 -append "root=/dev/sda2"

Is there a way to alter this to either A) provide an expandable image so that I can provide more space for my RPi install or B) expand the current device size so that I can run raspi-config and expand the device that way.

A: For linux, you can do it with gparted:
Create a loop device:
sudo losetup -f --show numar1.img

(numar1.img is your image file). It will return something like /dev/loop0.
Then run gparted with loop device:
sudo gparted /dev/loopX

(the X in loopX should be a number). Then resize the ext4 partition.


text:
Q: Python - persistent mysql connection in processes I have thousands of MySQL queries to run in a python program I am working on. I want to run these concurrently for obvious reasons, and I am trying to work out the best way to do so.
Using multiprocessing, I want to start 8 child processes. Each one should create a connection to SQL which persists for its entire lifetime. Then I want to use a ProcessPool to imap queries into those processes which utilise the persistent SQL connection. Once all queries have returned results, I want to close the connection on each of the processes.
At the moment, I can send an initializer to each of the processes that creates a MySQLdb connection and then use that in each of the queries passed in my imap. However, I can't see a nice way to "de-initialize"/deconstruct the processes and close the DB connection.
Is there a way to close the DB connection when the pool is about to destroy each process?
I've looked at using queues to transfer data to/from, and then subclass multiprocessing.Process and override run, which can create the connection, loop over the queue, and then close the connection in that single call, but there's a little more overhead in reading the queue back out and working out when the queue has nothing else to give which I'm trying to avoid.


text:
Q: Summation of $\frac{mn}{n\cdot3^m+m\cdot3^n}\left(\frac{n}{3^m}+\frac{m}{3^n}\right)$ Question: Calculate

$$\sum_{n\geq1}\sum_{m\geq1}\frac{mn}{n\cdot3^m+m\cdot3^n}\left(\frac{n}{3^m}+\frac{m}{3^n}\right)$$

My attempt:
I let $a_k=\frac{3^k}{k}$ and wrote the sum like this
$$\frac{n}{ma_m(a_m+a_n)}+\frac{m}{na_n(a_m+a_n)}$$
Now, since the second expression is the same as the first but with $m,n$ exchanged, so the sum will be two times the sum of the first but I can't compute the first sum.
Any help on how to proceed would be appreciated.

A: Maybe it will be easier.
$$\sum_{n \ge 1} \sum_{m \ge 1} a(n,m) = 2\sum_{n \ge 1} \sum_{1 \le m < n} a(n,m) + \sum_{n \ge 1} a(n,n)$$
Now we have $$\sum_{n \ge 1} a(n,n) = \sum_{n \ge 1} \dfrac{n}{3^{2n}} $$
and for first part:
$$\sum_{n \ge 1} \sum_{1 \le m < n} \dfrac{mn}{n 3^m + m3^n}\left(\dfrac{n}{3^m} +\dfrac{m}{3^n}\right)$$


text:
Q: Importing Excel Documents into Python I just want to import an excel file into python on Jupiter. I have tried everything and looked at multiple Q&A's and nothing has worked. I appreciate any help. This is the code I am using.
import numpy as np
import pandas as pd

'''
Excel_file = pd.ExcelFile('C:\Documents\Accounting\Applied_Accounting_Principles\Exercises\Data_Analytics\')
'''

df = pd.read_excel(Excel_file)

A: For starters, welcome! :)
I played with Excel on my computer and this seemed to work:
   Excel_file = pd.read_excel(r'C:\Users\Anon\Desktop\testingexcel.xlsx')

   print(Excel_file)

Output was (for my excel file) :
   Numbers
0        1
1        2
2        3
3        4
4        5

Include the r (this is to "read" the file) before placing the file address, including the file ending with .xlsx, for example r'C:\Users\Ben\Documents\excelfile.xlsx'
If you want to just print columns you can also utilize the pd.DataFrame(Excel_file, columns=['Column Name'])
Let me know if this is what you were looking for.


text:
Q: Excluding specific loggers using a rule in nlog programmatically I am looking at a way to implement the following logging rule programmatically.
<logger name="Name.Space.*" minlevel="Debug" maxlevel="Error" final="true" />

I can use the following to set the "name" & "loglevel" but there is no way to implement the final="true"..
LoggingRule fileLoggingRule = new LoggingRule("ConnDriverLogger", LogLevel.Trace, connDriverFileTarget);
connDriverLoggingConfig.LoggingRules.Add(fileLoggingRule);

Any suggestions to implement the above?

A: What about the LoggingRule.Final property?
In your case:
LoggingRule fileLoggingRule = new LoggingRule("ConnDriverLogger", LogLevel.Trace, connDriverFileTarget);
fileLoggingRule.Final = true;
connDriverLoggingConfig.LoggingRules.Add(fileLoggingRule);

I found the LoggingRule.Final property here at NLog's repository:
https://github.com/NLog/NLog/blob/master/src/NLog/Config/LoggingRule.cs


text:
Q: Recursively Search Through a Flat Array I have a flat, associative array that is being grepped for any elements that match a particular parentID. I then, however, need to re-run the function with the returned results to see if there are any elements with a parentID that match the previous result. Esentially, I am trying to get all children and children of those children.
In the array below, each element has a parent ID that matches it up with it's parent. I have a function that will grep the array for any elements that contain the parent ID that I pass to it, this works fine.
  array("id" => "Test", "parent" => "#", "text" => "Title"),
  array("id" => "Test1", "parent" => "Test", "text" => "Title1"),
  array("id" => "Test2", "parent" => "Test", "text" => "Title2"),
  array("id" => "Test3", "parent" => "Test2", "text" => "Title3") ,
  array("id" => "Test4", "parent" => "Test1", "text" => "Title4") ,
  array("id" => "Test5", "parent" => "Test1", "text" => "Title5")

function getChildren(id){
  var children = jQuery.grep(orig, function( n, i ) {
   return ( n.parent === id );
  });
return children;

// var children = jQuery.grep(orig, function( n, i ) {
//     return ( n.parent === id );
//   });
//   $.each(children,function(a,b){
//
//       getChildren(children[0]['id']);
//   });
}

After the function is run for the first time, it will return a list of children that contain that parent id. I now need to push all of those children back through the loop and get their children. Ideally, once the loop is finished, I would have a single array containing all children. Currently, the first part of the function works, but the area I commented out (where I try to pass the results back through) does not. Any help is greatly appreciated.

A: you can do like this fiddle,
function getChildren(id){
  let result = [];
  $.each(orig, function(i, d) {
     if (d.parent === id) {
            result.push(d);
        result.push(...getChildren(d.id));
     }
  });
  return result;
}

console.log(getChildren('Test'));


text:
Q: Is there a default way to normalize a string into a valid symbol? I'm writing a macro that transform a keyword into a symbol This symbol will be used on a (def ~symbol ...) There is a "default" way to normalize :foo.bar/quoo to a valid symbol? (symbol (namespace kw) (name kw))?

A: Since Clojure 1.10 you can also use symbol directly with keywords, even namespaced ones:
user> (symbol :plain-kw)
plain-kw
user> (type (symbol :plain-kw))
clojure.lang.Symbol
user> (symbol :namespaced/kw)
namespaced/kw
user> (type (symbol :namespaced/kw))
clojure.lang.Symbol


text:
Q: Aurelia.js Framework aurelia-table pagination I am using : https://tochoromero.github.io/aurelia-table/
I have just a small issue and I would like ask your help.

  ${currentPage} - ${pageSize} of  ${totalItems}

I have 5 pages and I would show like: 1 of 5 pages os 33 items, I tried use: pagination-size: but did not work for me, can someone help me with this?  thank you.

A: If you have your total amount of items, and you know how many are gonna be on each page, it's a matter of simple math.
// Compute the amount of pages.
var amountOfPages = Math.ceil(totalItems / pageSize);

HTML:

Page: ${currentPage} of ${amountOfPages} (${totalItems} items)

If you data is dynamic and can update, you can turn the variable into a get-function:
@computedFrom('totalItems', 'pageSize')
public get amountOfPages() {
  return Math.ceil(totalItems / pageSize);
}


text:
Q: How do I get rid of the elif Syntax error Image of Code Error
while Time5 == "true":
        Act5 = input("\nWhat would you like to do this year? You can: Play Videogames | Punch your parents | Browse the internet | Youtube | Steal Food |Check Stats | Check Assests: \n")
        if Act5 == "Check Stats":
            print("Your Stats")
            print("Sanity:{}".format(Sanity))
            print("Happiness:{}".format(Happiness))
            print("Health{}".format(Health))
            print("Money{}".format((Money))
        elif Act5 == "Steal Food":
            print("You went over to your local Wendys and stole a Happy Meal.")
            Happiness = Happiness + 12
            print("The addreniline RUSH gave you 12 extra happiness\n")
            if Happiness > 100:
                print("Your HAPPINESS is maxed.")
            Wendy = input("You see another door to your left. It is the staff door. Will you enter? Yes or No \n")

I'm trying to make a life simulator.
I keep getting an invalid syntax warning on this section.
There seems to be no indenting errors.
It used to work.
Its only this section that doesn't work
If you want to see more code, go to this website:  https://docs.google.com/document/d/1HR5ahjM4B6wKOSEpeVRxXGrF9wCNTAp-OizdRl2zKuA/edit?usp=sharing and scroll down to version 4.

A: I believe the line
print("Money{}".format((Money))
is causing you problems, because like gilch said in the comment above, you have one too many parentheses. Modify that line to
print("Money{}".format(Money))
and see if that works!


text:
Q: Adding Multiple UIButton in UIView in Different Y Position I know how to add UIButton to a UIView programmatically. But I'm stuck in adding the UIButton in the new YPosition after a certain number of UIButtons are added in the previous YPosition.
Here is my case:

*

*Number of UIButtons to be added comes from NSArray - Let's take 20

*UIView is already added in the UIViewController - Let's call
'buttonView'

*I'm creating UIButton using the loop (up to 20). I have set the
buttonWidth as 70 and buttonHeight as 45

*I'm getting the screen size and dividing this by the buttonWith, so
as to calculate the number of items that can be accommodated per line
or per Y position.

*If the screen width is 414, then 414/70 = ~5.9 and I'm taking it as

*First 5 UIButton's YPosition as 0 and XPosition starts from 0 and adding buttonWidth for subsequent buttons.

*Next 5 UIButtons (6-10) should have the new YPosition as 1-5 UIButton
Yposition(0)+buttonHeight(45)+somespace(10)= 55 and XPostion should
start with 0.

*For the next set of UIButtons(11-15), the YPosition should be
Yposition(55)+buttonHeight(45)+somespace(10)= 100 and XPosition
starts with 0
How to achieve this? Below is my code
xPos = 8.0f;
yPos = 0.0f;
totalSlots =timeslots.Count - //Total Number UIButtons to be creted
buttonWidth = 70;
buttonHeight = 45;
buttonViewWidth = this.view.frame.size.width // I'm getting the screen
buttonPerLine = scrollViewWidth / (buttonWidth + 10); // This calculates no.of.buttons per line/Y Position. I'm rounding off as said before
numberOfLine = totalSlots / buttonPerLine // This gives how many lines needed

for (int i = 0; i < totalSlots; i++)
                        {
timeSlotbtn[i] = new UIButton();
                        timeSlotbtn[i] = new UIButton();
                        timeSlotbtn[i].Frame = new CGRect(xPos, yPos, buttonWidth, buttonHeight);
                        timeSlotbtn[i].SetTitle(buttonText, UIControlState.Normal);
                        timeSlotbtn[i].Layer.BorderWidth = 2.0f;
                        timeSlotbtn[i].Layer.CornerRadius = 3;
                        timeSlotbtn[i].Tag = i;
                        timeSlotbtn[i].TitleLabel.Font = UIFont.FromName("HelveticaNeue-bold", 14.0f);

                xPos = timeSlotbtn[i].Frame.Location.X + buttonWidth + buttonSpace;
                timeslotScrollView.AddSubview(timeSlotbtn[i]);
}

Pleas be noted the above code is written in Xamarin.iOS. If you know the solution, then probably you can write in Objective-c. Anyhow, the logic should be same.

A:             int buttonWidth = 65;
            int buttonSpace = 5;
            int buttonHeight = 30;
            int totalSlots = timeslots.Count;
            nfloat screenSize = firstViewController.screenSize;
            nfloat buttonPerLine = screenSize / (buttonWidth + buttonSpace );
            int roundedButtonPerLine = Convert.ToInt32(Math.Floor(buttonPerLine));
            nfloat totalLines = totalSlots / buttonPerLine;
            int roundedTotalLines = Convert.ToInt32(Math.Ceiling(totalLines));
            nfloat determineXPosition = (screenSize - (8 + (buttonWidth * roundedButtonPerLine) + (buttonSpace*(roundedButtonPerLine-1))))/2;
            nfloat xPos;
            if (roundedTotalLines > 1)
            {
                 xPos = determineXPosition;
            }
            else
            {
                 xPos = 8.0f;
            }

            nfloat yPos = 0.0f;
            int currentLine = 1;
            int loopCount = 1;

            for (int i = 0; i < room.timeslots.Count; i++)
            {
                var buttonText = room.timeslots[i].startDate.ConvertDateToStanfordLocalTime();//hour + ":" + minute + "p";
                timeSlotbtn[i] = new UIButton();
                timeSlotbtn[i].Frame = new CGRect(xPos, yPos, buttonWidth, buttonHeight);
                timeSlotbtn[i].SetTitle(buttonText, UIControlState.Normal);
                timeSlotbtn[i].Layer.BorderWidth = 2.0f;
                timeSlotbtn[i].Layer.CornerRadius = 3;
                timeSlotbtn[i].Tag = i;
                timeSlotbtn[i].TitleLabel.Font = UIFont.FromName("HelveticaNeue-bold", 14.0f);

                xPos = timeSlotbtn[i].Frame.Location.X + buttonWidth + buttonSpace;
                timeslotScrollView.AddSubview(timeSlotbtn[i]);

                if (loopCount == roundedButtonPerLine)
                {

                    if (roundedTotalLines > 1)
                    {
                         xPos = determineXPosition;
                    }
                    else
                    {
                         xPos = 8.0f;
                    }
                    currentLine++;
                    yPos = timeSlotbtn[i].Frame.Location.Y + buttonHeight + buttonSpace;
                    loopCount = 0;
                }
                loopCount++;
            }


text:
Q: 8bit sRGB and OpenGL confusion I would like to ask a clarification about the sRGB color space and its 8bit per channel representation in OpenGL. After digging in the subject, I found out that storing images in sRGB is just made to compensate the opposite gamma operation done by the monitor which "imitates" what the old CTR did by nature for compatibility reasons. The fact that the human eye has a similiar non linear response is just a coincidence and has nothing to do with gamma correction (as many confusing articles claim) as the output will be linear again anyway.
Assuming that this understanding is right, in OpenGL we have the GL_SRGB8_ALPHA8 format for textures, which has 8bit per channel. However since the range of 0~255 is the same as a linear RGB texture, does this mean that to convert a linear 8bit per channel texture to sRGB the color values remain unchanged and a simple "flag" tells OpenGL: Look this 0~255 range is not linear so interpret them as a curve?
What about sRGB 16bit per channel images (ex. 16bit PNGs) ?

A: The range is the same. The values are not.
Your linear values before storing are floating-point. So they have greater precision than an 8-bit-per-channel format.
If you store them in a linearRGB image, you're taking the input range [0, 1] and evenly mapping them to [0, 255].
But if you do sRGB conversion, then you're taking the [0, 1] range and mapping them to [0, 255] via a non-linear gamma mapping of approximately 2.2. While this non-linear mapping does not magically create more values, what it does do is effectively give you more precision in the higher parts of the range than the lower parts.
In sRGB conversion, values in the input range [0.5, 1] are mapped to [56, 255]. That's over 75% of the output range that's covered by 50% of the input range. This gives you a better representation of the larger values in your input.
A linear mapping loses precision evenly. The sRGB mapping loses more precision in the darker areas than the lighter. Or to put it another way, it preserves more precision in the lighter areas than the linear mapping.
For a memory vs. visual quality tradeoff, sRGB comes out better overall than linearRGB 8-bit-per-channel.

However since the range of 0~255 is the same as a linear RGB texture, does this mean that to convert a linear 8bit per channel texture to sRGB the color values remain unchanged and a simple "flag" tells OpenGL: Look this 0~255 range is not linear so interpret them as a curve?

It depends on what operation you're talking about.
An sRGB texture is a texture that stores its RGB information in the sRGB colorspace. However, shader operations are assumed to want data in the linearRGB colorspace, not sRGB. So using an sRGB format means that texture fetches will convert the pixels they read from sRGB to linearRGB.
Writes from a fragment shader to an FBO-attached image using an sRGB format may or may not perform conversion. Here, conversion has to be explicitly enabled with GL_FRAMEBUFFER_SRGB. The idea being that some operations will generate values in the sRGB colorspace (GUIs, for example. Most images were created in the sRGB colorspace), while others will generate values in linearRGB (normal rendering). So you have an option to turn on or off conversion.
The conversion also allows blending to read sRGB destination pixels, convert them to linear, blend with the incoming linearRGB values, and then convert them back to sRGB for writing.
Uploads to and downloads from an sRGB image will write and read the pixel values in the sRGB colorspace directly.

What about sRGB 16bit per channel images (ex. 16bit PNGs) ?

What about them? OpenGL has no 16-bit-per-channel sRGB formats.
sRGB conversion is typically done via a 256-entry table lookup. For every sRGB value, there is a pre-computed linear one.
So, just like any other case where an image format offers something that OpenGL doesn't match, you'll have to manually convert them.

A: Gamma is Good

I found out that storing images in sRGB is just made to compensate the opposite gamma operation done by the monitor...the fact that the human eye has a similiar non linear response is just a coincidence and has nothing to do with gamma correction ... Assuming that this understanding is right,

That understanding is not correct. Storing images with a gamma curve is necessary to increase the data density in dark areas for perceptual reasons. Without gamma, you would need 12 bits for linear for the same image fidelity you get with 8 bits and a gamma curve.
Old school TVs could have been designed to use a linearized signal, but in fact the design techniques of the day increased gamma from the theoretical 1.5 to the commonly used 2.4. As a function of system design the use of gamma reduced the perception of noise in the broadcast signal.
A gamma-type of transfer curve makes the most of a limited bandwidth by weighting the available bandwidth per human non-linear visual perception.
OPENGL
As for your question, If the internal format parameter is GL_SRGB, GL_SRGB8, GL_SRGB_ALPHA, or GL_SRGB8_ALPHA8, the texture is treated as if the red, green, or blue components are encoded in the sRGB color space.
This means that the values in the image are assumed to be gamma-encoded values as opposed to GL_RGB8 which are assumed to be linear.

However since the range of 0~255 is the same as a linear RGB texture, does this mean that to convert a linear 8bit per channel texture to sRGB the color values remain unchanged and a simple "flag" tells OpenGL: Look this 0~255 range is not linear so interpret them as a curve? What about sRGB 16bit per channel images (ex. 16bit PNGs) ?

The range or bit depth has nothing at all to do with a gamma curve being used or not.
An image needs gamma for perceptual reasons. A linear texture map or bump map does not. If you use the GL_SRGB8 tag on a linear bump map, then GL will use sRGB gamma on that linear data which you do NOT want to do - that is it will apply a power curve of approximately 2.2 to linear 1.0 values, and this is not want you want, unless your bump map IS an image with a gamma curve.
The sRGB tag is there so that when you have an sRGB image which has the color values encoded with a ~1/2.2 curve, those values become linearized.


text:
Q: SPUser equivalency operator Is there an operator, and if so what, to determine equivalence between two SPUser objects in PowerShell?
My instance is looping through a list of sites to replace "domain/John Smith" with "domain/Jane Doe" in a certain site property. It's pulling the SPUser currently in that property, if it's the same as the SPUser "domain/John Smith" then the property gets replaced with the SPUser "domain/Jane Doe".
In this particular instance it's easy enough to to just compare the UserLogin or DisplayName property, but I'm looking for a more sophisticated way to determine equivalency between two users.

A: Seems like a somewhat late answer, but for the sake of helping anyone stumbling across this issue I can perhaps give some ideas with what I have had to do to find a user and compare certain properties.
I have used this example for SharePoint related queries but you can obviously apply the exact principle to other areas.
I get a collection of SiteUsers for my SPWeb, then, in a foreach I iterate through all the users and perform a check: If my user's email address exists in the SPUsers Collection, then add that email address to a SharePoint List.
The following is how I would do my comparison:
$item["Line Supervisor"] = $spweb.SiteUsers | ? { $_.Email -eq ($csvrow.LineManagerMail + "@domain.com")}

Although this doesn't directly answer your question it may give you an idea how to use lambda expressions within PowerShell to help you perform quick checks on your data and not only with users. I can think of a few other similar examples if you need.
Below is a small snippet I recently used with this example:
ADD NEW USERS TO THE LIST FROM A CSV FILE
foreach ($csvrow in $icsv)
{
    $rowCellNumber = $csvrow.CellNumber;
    Write-Host($rowCellNumber);
    $item = $users | ? {$_["Cell Number"] -eq $rowCellNumber}

    If($item -eq $null)
    {
        $item = $linstance.AddItem();
        Write-Host('New User Found - Creating ' + $rowCellNumber + '...');
        $newitems = $newitems + 1;   #this is only a flag to count new items
    }
    Else
    {
        Write-Host('Existing User Found - Updating ' + $rowCellNumber + '...');
        $updateditems = $updateditems + 1;   #this is only a flag to count updated items
    }
#set spitem field values
    $item["Title"] = $csvrow.FullName
    $item["Line Manager"] = $spweb.SiteUsers | ? { $_.Email -eq ($csvrow.LineManagerMail + "@domain.com")}

    $item.Update()
}


text:
Q: How to charge/budget in agile software development projects? How do you charge your customer in a project using agile methodology?
Per hour? Then a great deal of trust has to been established before the project.
Per iteration? There's gonna be a lot of budget decisions, which can take time.
Per project? How can you do that when you don't know the scope? The very essence of agile is to not write a big upfront design/specification.

A: Short answer is, you won't.  There are a few services companies that are making headway doing it, but it is a difficult path.  Your ability to sell the methodology and convince the customer you can deliver will be high.
Customers don't want to risk paying for a solution that will never be delivered.
Typical approaches to this problem are to put "will not exceed" cost.  However, if you can't control scope, you are the one taking all of the risk.
In short, you are looking for customers that would have signed up for T&M (time and materials) contracts before Agile became the latest fad (I'm part of that fad, but it is just one in a long line of development processes.  Aspects of it will continue to grow and some permutation of it will have a different name in a few years).

A: If your customer has already bought into the use of an agile methodology, then you have a reasonable framework for negotiating price per iteration. For example, you know:

*

*How long the iteration will be.

*How many people will be committed to work on the iteration (and their rates).

*An approximate scope of work.

*A process for delivery and acceptance.

That's a lot more evidence on which to base pricing decisions than is available for most fixed price contracts.

If the agile methodology is purely an internal development process that doesn't involve the customer, then it's unlikely to have much effect on the pricing negotiation between the supplier and the customer. There is an argument that says that a process that doesn't involve the customer in setting scope and expectations at least once per iteration isn't agile at all.
Regarding Mark's comment, there is a very common pricing model based around fixed price contracts with loosely defined scope and optimistic schedules. A common outcome is that both supplier and customer find that their initial optimism was misplaced. Both end up negotiating from weak positions over the things that really matter to them, and both end up unhappy.
Some of the techniques that work well in managing this type of contract are very similar to those used in managing agile contracts (frequent delivery, horse-trading on scope, priorities & price, frank communication, ...) the main difference is that these aren't built into the original agreement, and the contract may not be flexible enough to accommodate all of them.

A: You charge your customer on the base of the terms defined by your contract that will be slightly different from a traditional fixed bid contract. Let's call that an Agile contract.
Some options are discussed by Alistair Cockburn in Agile contracts.
Another great resource is 10 Contracts for your next Agile Software Project by Peter Stevens.
Mary Poppendieck also has great material on this topic. See agilecontracts, agilecontractsworkshop, Contracts Excerpt From Lean Software Development, Lean Contracts. More here.

A: My 2c as a non-agile practitioner...in a quest to know more...
If you are doing a specific project for a customer, you will need to know the scope of the project to provide a cost and a timescale. The cost of producing this scope of work is more often than not part of the discovery of the project, you either take a hit on this to get the work or charge for this (explicitly or implicitly) In this case, a project cost can be worked out and agreed. Im this case the project is usually broken up into various stages.
Although agile may be iterative and not require a full specification; a goal, at least is certainly required. There must be some form of basic specification/requirement. It may be that you need to break the project up into smaller goals and apply costs accordingly.
The iterations I suspect are more to do with the development methodoology, ie to achieve the goals?
If there is not enough specification to produce a definitively accurate cost, I would say that a "estimate" should be given but work should be charged at an hourly rate as I would assume that there would be greater changes in the decisions made on the project over each iteration.

A: I've seen it work well when approached in 2 phases:
Phase 1) Inception (timeboxed)
A timeboxed inception period with the client to scope the project. (A one month intense inception for a project estimated to last a year is about right.)
Outputs to this phase are a full backlog of sized user stories, an estimation of flow rate per dev pair, and parameters to estimate project costs based on the number of developers and overheads of having larger teams.
The inception provides a useful budget estimation that can be tracked throughout phase 2, a clear shared vision for both client and supplier, plus the option for either side to walk away. This isn't upfront design, the stories have just enough detail for a lead dev / tester to assign relative sizes.
Phase 2) Delivery (time and materials)
A delivery contract based on time and materials, with budget estimates based on the outputs from the inception phase. The trust built up in phase 1 is vital to making this work. Because phase 1 delivered relative sizing of the entire backlog, by regularly measuring actual flow it is possible to easily and frequently report projected flow rate for the rest of the backlog with increasingly accurate estimates of budget and delivery date. The supplier should be contracted to report these stats at least every 2 weeks, with the option for the client to walk away at any point.
By paying for time and materials, the client is free to change the scope and proirity of the backlog, and is therefore in control of the budget. They are encoraged to prioritise their highest priority / highest risk stories first, and by allowing them to walk away whenever they like they should experience a positive return on investment at all times.


text:
Q: Find all primary key and foreign key who use a colunm that need type change I need to change a column data type from int4 to varchar(30) and this column is primary and foreign key in several other tables.
So I'm trying to list all the pks and fks that use this column and after alter all this tables and constrains.
So I have 2 questions:
1) there is a smarter way to do this type change?
2) How can I list all this pks and fks one line for each?
(with the select below there is one line for each column in the constraint)
using postgres 10.10
select
    tco.constraint_name,
    tco.constraint_type,
    kcu.table_schema,
    kcu.table_name,
    ccu.table_schema,
    ccu.table_name,
    ccu.column_name
from information_schema.table_constraints tco
join information_schema.key_column_usage kcu
     on kcu.constraint_name = tco.constraint_name
     and kcu.constraint_schema = tco.constraint_schema
     and kcu.constraint_name = tco.constraint_name
JOIN information_schema.constraint_column_usage ccu ON ccu.constraint_name = tco.constraint_name
where
    ( tco.constraint_type = 'PRIMARY KEY' or  tco.constraint_type = 'FOREIGN KEY' )
    and
    kcu.column_name='column_name'

A: Regardless of the misconception that can done by what you want to achieve, here is the code that is (I think) doing what you want on your '2)'.
Test structure :
drop table if exists test;
create table test (id int primary key);
create table test_2 (id int, id_1 int);
alter table test_2 add constraint pk_test_2 primary key (id, id_1);
alter table test_2 add constraint fk_test_2_test_1 foreign key (id_1) references test (id);
create table test_3 (id int primary key, id_2 int, id_1 int);
alter table test_3 add constraint fk_test_3_test_2 foreign key (id_2, id_1) references test_2 (id, id_1);

The query :
SELECT
    rel.relname as table_name
    , ccu.relname as ref_table_name
    , pg_get_constraintdef(con.oid) as con_def
    , con.conname
    , col.attname
FROM pg_catalog.pg_constraint con
    INNER JOIN pg_catalog.pg_class rel
        ON rel.oid = con.conrelid
    INNER JOIN pg_catalog.pg_namespace nsp
        ON nsp.oid = connamespace
    left outer JOIN pg_class AS ccu
        ON con.confrelid = ccu.oid
    JOIN LATERAL UNNEST(con.conkey) WITH ORDINALITY AS u(attnum, attposition) ON TRUE
    JOIN pg_attribute col ON (col.attrelid = rel.oid AND col.attnum = u.attnum)
WHERE nsp.nspname = 'public'
    and col.attname = 'id';

Or something like this :
select
    tco.constraint_name,
    tco.constraint_type,
    kcu.table_schema,
    kcu.table_name,
    ccu.table_schema,
    ccu.table_name,
    string_agg(distinct ccu.column_name, '; ')
from information_schema.table_constraints tco
join information_schema.key_column_usage kcu
     on kcu.constraint_name = tco.constraint_name
     and kcu.constraint_schema = tco.constraint_schema
     and kcu.constraint_name = tco.constraint_name
JOIN information_schema.constraint_column_usage ccu ON ccu.constraint_name = tco.constraint_name
where
    ( tco.constraint_type = 'PRIMARY KEY' or  tco.constraint_type = 'FOREIGN KEY' )
    and tco.constraint_schema = 'public'
group by tco.constraint_name,
    tco.constraint_type,
    kcu.table_schema,
    kcu.table_name,
    ccu.table_schema,
    ccu.table_name;


text:
Q: Flutter Retrieving Data from Firebase I am writing a social Media app where the user can post and read post from other users. My problem is here, I want an updated name from the user who wrote a post so that the latest name, when the user updates it's name, should appear on the post.
In this code of mine I am getting the error

The argument type 'Future<String?>' can't be assigned to the parameter type 'String'

  Widget postList (){
    return Container(
      child: StreamBuilder(
        stream: some Stream
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot>  snapshot){
          return !snapshot.hasData ?
          CircularProgressIndicator():

          ListView(
            children: snapshot.data!.docs.map((document) {
              return InkResponse(
                child: Container(
                    child: Column(
                      children: <Widget>[
                        Row(
                          children: [

                            // I'm having trouble here
                            /** What I want to happen is to retrieve the NAME of the user using UID so that even if the
                             Writer changes his name, the latest name shall appear on this */

                            Text ( getWriterInformation(uid: document['poster_uid']),
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    fontSize: 16)),
                          ],
                        ),
                      ],
                    ),
                  ),
              );
            }).toList(),
          );
        },
    );
  }

  Future <String?> getWriterInformation ({required String uid}) async {
    await Users.doc(uid).get().then((value){
      return value['display_name'].cast<String>();
    });
  }

}

If you can recommend any other way aside from my way to do this, I will gladly to appreciate it.

A: Use FutureBuilder() for Text() widget:
FutureBuilder(
  future: getWriterInformation(uid: document['poster_uid']),
  builder: (BuildContext context, AsyncSnapshot<String> text) {
    return Text(text.data);
  })

This:
  return Container(
  child: StreamBuilder(
    stream: some Stream
    builder: (BuildContext context, AsyncSnapshot<QuerySnapshot>  snapshot){
      return !snapshot.hasData ?
      CircularProgressIndicator():

      ListView(
        children: snapshot.data!.docs.map((document) {
          return InkResponse(
            child: Container(
                child: Column(
                  children: <Widget>[
                    Row(
                      children: [

                        // I'm having trouble here
                        /** What I want to happen is to retrieve the NAME of the user using UID so that even if the
                         Writer changes his name, the latest name shall appear on this */

                        FutureBuilder(
                          future: getWriterInformation(uid: document['poster_uid']),
                          builder: (BuildContext context, AsyncSnapshot<String> text) {
                          return Text(text.data);
                        })
                      ],
                    ),
                  ],
                ),
              ),
          );
        }).toList(),
      );
    },
);

A: this is happening because getWriterInformation return type of future string. You can't assign future string val into String. Text widget only accepts string. You need futureBuilder for this. some data from the firebase take time so on page launch and show a loader until data comes.
Saitoh Akira answer is correct.

A: you could use .snapshots() to get realtime updates from firebase if you're using that
 Widget postList (){
    return Container(
      child: StreamBuilder(
        stream: some Stream
        builder: (BuildContext context, AsyncSnapshot<QuerySnapshot>  snapshot){
          if(!snapshot.hasData ?){
          return CircularProgressIndicator();}
          else {

          return ListView.builder(
              count: snapshot.docs.length,
              builder: (context, snapshot) {
                Map<String, dynamic> data = snapshot.docs!.data as Map<String, dynamic>;
                return InkResponse(
                  child: Container(
                    child: Column(
                      children: <Widget>[
                        Row(
                          children: [
                            Text(data['name'])
                          ],
                        ),
                      ],
                    ),
                  ),
              );
}
  )}

/// this is not required ?
  Future <String?> getWriterInformation ({required String uid}) async {
    await Users.doc(uid).get().then((value){
      return value['display_name'].cast<String>();
    });
  }

}


text:
Q: Process /etc/passwd file to list all users whose home folder is in /home I have an example /etc/passwd file like this:
tom:x:1000:1000:Work:/home/tom:/bin/bash
george:x:1000:1000:Work:/home/george:/bin/bash
bla:x:1000:1000:Work:/home/bla:/bin/bash
boo:x:1000:1000:Work:/home/boo:/bin/bash
bee:x:1000:1000:Work:/root/list:/bin/bash

I'm trying to list all users with a home folder in /home/.
I wrote
cat ~/Desktop/e.txt |awk -F ":" '{if ($6 ~/^/home/) print $1;}'

where e.txt is the text I copied here.
I understand there is a problem with the backslash which is an escape character, but how do I fix it so I can list them in one line of a command?

A: Assuming e.txt is actually /etc/passwd, you should actually use getent passwd instead of parsing the file since user account information may be stored in multiple locations specified in /etc/nsswitch.conf such as LDAP.
getent passwd | awk -F ':' '$6 ~ "^/home"'

Note that the print statement is implied when the condition is true. That will print the whole line, though. This will print only the user name:
getent passwd | awk -F ':' '$6 ~ "^/home" {print $1}'

A: Alternative for those of us who just don't like awk:
grep -E '^([^:]*:){5}/home/' ~/Desktop/e.txt | cut -d: -f1

Explanation:

*

*grep -E enables the use of a few extended regular expression features

*The expression ([^:]*:) matches one column, including the following ':' separator

*^([^:]*:){5} matches the first five columns of each line

*^([^:]*:){5}/home/ matches every line where the 6th column starts with '/home/'

*cut -d: -f1 selects only the first column of its input, using : as column separator

A: You can also use index for fixed string matching like grep -F and use the return value to ensure it matches start of string
$ awk -F: 'index($6,"/home/")==1{print $1}' ip.txt
tom
george
bla
boo

or if regex is needed, pass it as environment variable
$ r='^/home/' awk -F: '$6 ~ ENVIRON["r"]{print $1}' ip.txt
tom
george
bla
boo

A: Just for variety
$ perl -F: -lane 'print $F[0] if m(/home/)' e.txt
tom
george
bla
boo

Explanation
-F:     use ":" as field separator
-lane
    l   add newline line-ending to every print statement
    a   auto-split input lines into @F array
    n   apply expression line by line to named file (or STDIN)
    e   evaluate perl commands given on command line

print $F[0]   print (only) the first field of each line
if m(/home/)  but only if the line contains the text /home/

Variation if you want to be picky about where /home/ is found
perl -F: -lane 'print $F[0] if $F[5] =~ m(^/home/)' e.txt

A: You can use quotes instead of / for the regex, to avoid escaping the /:
awk -F: '$6 ~ "^/home/" {print $1}' ~/Desktop/e.txt

With awk, {if (foo) ... } can often be simplified to just foo {...}.

A: You may escape forward slashes as shown below:
awk -F':' '$6~/^\/home\//{ print $1 }' ~/Desktop/e.txt

Another trick would be using complex field separator:
awk -F'[:/]' '$7=="home"{ print $1 }' ~/Desktop/e.txt

*

*-F'[:/]' - treat both : and / to be a field separator


text:
Q: Dyld Symbol not Found Error Here's my error.
dyld: Symbol not found: __ZTIN8eqOsirix3ROIE
  Referenced from: /Users/slate/Documents/osirixplugins/CoreDataTrial_EQOsirix/build/Development/rcOsirix.app/Contents/MacOS/rcOsirix
  Expected in: flat namespace
 in /Users/slate/Documents/osirixplugins/CoreDataTrial_EQOsirix/build/Development/rcOsirix.app/Contents/MacOS/rcOsirix
Data Formatters temporarily unavailable, will re-try after a 'continue'. (Not safe to call dlopen at this time.)
(gdb) bt
#0  0x8fe01065 in __dyld_dyld_fatal_error ()
#1  0x8fe04fa5 in __dyld__ZN4dyld4haltEPKc ()
#2  0x8fe0796b in __dyld__ZN4dyld5_mainEPK12macho_headermiPPKcS5_S5_ ()
#3  0x8fe018b1 in __dyld__ZN13dyldbootstrap5startEPK12macho_headeriPPKcl ()
#4  0x8fe01057 in __dyld__dyld_start ()
(gdb) continue
Program received signal:  "EXC_BAD_ACCESS".
Data Formatters temporarily unavailable, will re-try after a 'continue'. (Not safe to call dlopen at this time.)
(gdb) bt
#0  0x8fe010e3 in __dyld__ZN13dyldbootstrapL30randomizeExecutableLoadAddressEPK12macho_headerPPKcPm ()
#1  0x8fe04fa5 in __dyld__ZN4dyld4haltEPKc ()
#2  0x8fe0796b in __dyld__ZN4dyld5_mainEPK12macho_headermiPPKcS5_S5_ ()
#3  0x8fe018b1 in __dyld__ZN13dyldbootstrap5startEPK12macho_headeriPPKcl ()
#4  0x8fe01057 in __dyld__dyld_start ()
(gdb)

where eqOsirix is my main namespace.  I had two similar problems a while ago (one and two) but neither solution is helping me now.
I noticed the problem after I updated my mac, but I think it's unrelated.
No compile errors are generated (or warnings).
What could cause this?  Why isn't the compiler catching anything during linking?  I've done clean builds, reset both XCode and the Mac.... I'm just at wit's end and Google just gives me stuff for 3rd party Frameworks not being included but this is my main namespace!!  Augh!

[EDIT]
Since @Troubador pointed out that ROI wasn't part of the scramble, I'm including ROI below:
#ifndef EQOSIRIX_ROI_H
#define EQOSIRIX_ROI_H

namespace eqOsirix{

    class ROI : public eq::Object
    {

    public:
        ROI() {};
        virtual ~ROI() {};

        virtual uint32_t getType() {return NONE;};

        virtual void draw() {};

    protected:

        enum ROIType {
            NONE = 0,
            LINE,
            POLY,
            AREA,
            VOLUME
        };

    private:

    };

}

#endif//EQOSIRIX_ROI_H

not much to screw up, and I think I have all the virtuals defined ok for C++ (as opposed to Java or ObjC) ???

A: Based on our discussion on your question I'm sure it has something to do with the fact that all your methods are defined within the class definition. This means that gcc has no "key" function alongside which it can emit the symbol for the typeinfo object i.e. there is no single object file that the typeinfo object can be placed in. What gcc therefore does is to emit the typeinfo symbol into each object file that requires it and inform the linker to ignore duplicates when it creates the dylib.
The reason I asked about the visibility attributes is that if even one of the duplicated symbols is marked as "hidden" then the linker will hide the typeinfo symbol within the dylib and any other part of your application will fail to look it up at run-time. You will not get a compile time error which seems to fit the behaviour you are reporting.
If you are not sure if you are using visibility attributes then you probably are not since the default visiblity is "default" which basically means not hidden. Look for options to gcc that start -fvisibility in your build files. Visiblity can also be marked up in code using things like __attribute__ ((visibility ("hidden"))).
The reason I suggested moving at least one member definition inside a cpp file was to force a single emission of the typeinfo object and test whether this made a difference. You didn't say whether you tried this or not so it would be good to know.


text:
Q: How do I know what manufacturer's parts are on a gun? I've seen loading tips like "assault rifles with a Vladof barrel fire faster as you keep the trigger held"; this clearly refer to the "Spinigun" triple gatling barrel assault rifles. Aside from that and the Elemental accessory (which I believe is exclusively made by Maliwan) I don't really know how to recognize which parts come from other manufacturers. Note that these parts show up on other manufacturer's guns, I've seen Bandit and Jakob's Spiniguns and elemental guns from everyone but Jakob's.
Are there other parts that are made by specific manufacturers that show up on guns? Most parts appear to be exclusive to a manufacturer's guns (e.g. Tediore's clean, mass-produced aesthetic), but it's implied certain parts can be on other manufacturer's guns, like the Vladof rifle barrel. How can I recognize them?

A: Infographics of various weapon parts:

*

*SMGs

*Rocket Launchers

*Sniper Rifles

*Shotguns

*Pistols

*Assault Rifles

Source and higher-resolution version of images from Reddit user Zikel's "Weapon parts infographic" series of posts at /r/Borderlands:

*

*Weapon parts infographic [#1] SMGs

*Weapon parts infographic [#2] Rocket launchers

*Weapon parts infographic [#3] Sniper rifles

*Weapon parts infographic [#4] Shotguns

*Weapon parts infographic [#5] Pistols

*Weapon parts infographic [#6] Assault rifles

A: It seems the only way to check in-game is to visually recognize the parts; some are more obvious than others, for example Vladof Sniper and Pistol barrels are always double, rotating barrels.
You can check the manufacturers' parts directly using Gibbed's Borderlands 2 Save Editor (link is to the most recent version as of now, it's actively updated and I don't think there's a single page to always get the latest version).
Basically you just load up your character's save file, go to "bank" or "backpack" and you can check out your stored/current gear and what stats they have. You can also of course edit them, but that's not required (and make sure to save your game before doing any editing yada yada yada).
For example here's a Maliwan legendary Norfleet clearly showing parts from multiple manufacturers:

Different parts have different manufacturer options so there's really no easy way to tell what's what without looking through this tool (or recognizing the parts after becoming familiar with them via this tool).
Note that the tool rapidly becomes out of date (after each patch) and may not work properly until a new version is released after a patch. DLCs tend to break it since they introduce new guns.
If you're not sure how to use the editor, guides for the current version can usually be found in the Se7enSins forums for Borderlands 2 Modding.  A stickied thread on there right now has a compilation of various related threads.

A: The guns are always made by just one company.
Vladof guns (and therefore also Vladof barrels) have the highest firerates. Tediore always have the explosive reload. Bandit guns (the ones with the horrible spelling) have the largest magazines. Maliwan guns are always elemental (and in general very good). Jakobs guns are old-style high damage (the revolvers that fire as fast as you can pull the trigger). Hyperion guns are more accurate the longer the trigger is held. Dahl guns aways fire in bursts when aiming down sights. Torgue guns always deal explosive damage.
This does not mean that Vladof guns can't have elemental effects for example. A manufacturers gun will always have the classic manufacturer effect though.
Additional info: Guns name prefixes (such as "Perma-Sharp SMG") are dependent on certain gun accessorys. These are effects/modifiers like 50% more melee damage. Here is a complete list: Strength Gamer Guide: 'Borderlands 2' Accessory Prefixes List
Hope I managed to help, all based on personal experience as a level 50 (as of 6 days ago^^).

A: The body/action of a gun determines it's manufacture. So it may have parts/accessories from 3/4 weapons manufacturers but the gun's actual body/action will be it's manufacturer's


text:
Q: How can I pass a scope variable which may change as directive parameter Hi I have following directive:
    app.directive('multiselectTableFilter', ['dependency1',
        function (dependency1) {
        return {
            restrict: 'E',
            scope: {
                model: '=',
                options: '=',
            },
            template:
                    "
" +
                        "<button class='btn btn-link btn-xs dropdown-toggle' data-ng-click='openDropdown()' ng-class=\"model.length !== options.length ? 'filterEdited' : ''\"></button>" +
                        "
" +
                            "
 {{option}}
" +
                        "
" +
                    "
",

            controller: function ($scope) {
                $scope.filteredElement = {};
                $scope.openDropdown = function () {
                    $scope.open = !$scope.open;
                };
                console.log($scope.model); console.log($scope.options);
  }]);
 })(app);

This is how I call this directive:
<multiselect-table-filter model="selectedUserIds.bugSeverity" options="options2"></multiselect-table-filter>

In Controller I assign the value of selectedUserIds and options2.
$scope.getFilteredData = function(list, filters){
        $scope.filteredData = $filter('inArray')($scope.p0Bugs, $scope.selectedUserIds.bugStatus, "bugStatus");
        $scope.filteredData = $filter('inArray')($scope.filteredData, $scope.selectedUserIds.bugSeverity, "bugSeverity");
        $scope.severity = _.uniq(_.map($scope.filteredData, "bugSeverity"));
        $scope.options2 = $scope.severity; // **when I assign options2 to this value, it throws error. (digest cycle error)**
        console.log($scope.filteredData);
        console.log($scope.severity)
        return $scope.filteredData;
};

Can any one help me to solve this. How I can pass the updated $scope.options2 value to the directive. Please let me know if you need any more information.


text:
Q: Kernel module probe function is never called I try to load a sample device tree driver, but the probe function is never called.
The entry in dts file looks like this
dummy1 {
    compatible = "ti,dummy";
    reg = <0x9f200000 0x1000>,
        <0x9f201000 0x8>;
};

And the relevant driver code is:
#define DRV_NAME  "dummy"
static const struct of_device_id dummy_of_match[] = {
{
.compatible = "ti,dummy",
}, {
},
};

static struct platform_driver dummy_driver = {
.driver = {
.name = DRV_NAME,
.of_match_table = dummy_of_match,
},
.probe   = dummy_probe,
.remove   = dummy_remove,
};
MODULE_DEVICE_TABLE(of, dummy_of_match);
module_platform_driver(dummy_driver);

I have recompiled the dtb file (dtdiff shows it contains my device) and have copied it to target, but nothing happens when I insmod the driver.
I also can't find it in /sys/firmware/devicetree/

A: Trying to solve the issue, I even removed the dtb file...and magically the kernel continued to boot as if nothing happened. I thought dtb could be baked into zImage which is possible with some additional tweaking, but that wasn't the case.
Solution:
Finally, I found out that the uboot was also checking the ./boot directory on the emmc card first! Removing the dtb from there immediately made the file on the NFS 'visible'.
P.S.: If you run into similar issues try to read the outputs carefully. I began to to understand the issue when I saw the .dtb load error when I removed it on NFS, but after that a message appeared that it was successfully loaded to the memory.


text:
Q: IBM Mainframe copy/paste Disclaimer: I'm new to using Rumba to access IBM Mainframe.
I have currently set up a library for personal use and I have some code that I want to store in a member of this library, how can I copy/paste from a .txt file on my desktop into this program??? As of right now  I can successfully copy/paste one line at a time from documents outside of Rumba.

A: There are various ways. The best one will depend upon the size of the file/amount of data to be transferred.
If it's only a few lines, block copy and paste should work, but you might have to play with Rumba's 'paste' edit settings such as how to handle new lines, etc.
Bigger files can be transferred with the TSO file transfer program ind£file (maybe ind$file on your system) which essentially copies a file to the screen and then Rumba 'scrapes' the screen for data to put into a file (this is for a mainframe-to-PC transfer; for going the other way the operation is reversed). This can be surprisingly quick.
Lastly there's FTP - either from the command line or via a program such as WinSCP.
Edit:
Based on your comment that the files are about 300 lines long, I'd look into using Rumba's file-transfer option using the ind$file utility. Once you have the files on one system, speak to your mainframe tech support team about the best way to get them to the other systems.
If you need help uploading the files, then the tech support team should be your first point of call.

A: What mainframe editor are you running?  TSO/ISPF?
I copy and and paste from ".txt" files into ISPS all the time with no problem.
Select the text you want to copy (in the ".txt" file)
Press CTRL-C
Open the mainframe file using ISPF Edit (option 2).
Enter line command "Inn" at the line where where you want the copy to start.
(This inserts "nn" empty lines to receive the copied data.  Personally, I usually use "nn"=20)
Position your cursor at the first character of the first empty line.
Press CTRL-V


text:
Q: Value cannot be null, Parameter name: viewInfo After installing SP2 to an existing SQL Server 2008 R2 I lost access to all my databases and started facing the error in the screenshot.

Any ideas?

A: Check the environment value for Temp and TMP.
C:\Users\buck>set t
TEMP=C:\Users\buck\AppData\Local\Temp\2
TMP=C:\Users\buck\AppData\Local\Temp\2
Make sure the directory listed exist and your id has appropriate permission to write to that directory. Alternatively, through the control panel (Control Panel-> System and Security-> System -> Advanced system settings), you can change the default directories that are assigned to TEMP and TMP.

A: Right click on the SSMS icon and click 'run as administrator'. At the SSMS console verify that the error is gone by clicking on the 'Databases' tree node. The error should now be permanently fixed and you do not need to run SSMS as admin anymore. Next time just start SSMS normally and it should work fine.

A: When running into this I found it was related to the environment temp folder (TMP Temp).
I had tried adding the "2" folder to this location with no success.
C:\Users\USER\AppData\Local\Temp\2
Try typing %temp% in file explorer and see if it takes you to a valid location. I found that I received an error because it was trying to go to a "4" location.
C:\Users\USER\AppData\Local\Temp\4
I created a folder named "4" in the Temp folder, reran SSMS, and it started working again.

A: Changing the temp variables did not resolve. Drive with SMMS installed has 34% free space.
However, using Run > %temp% > it would error out as "C:\%username%\appdata\local\temp\4 was missing" (this is not listed in my TEMP/TMP variables).
Quick solution was to add sub folder for "4" in c:\%username%\appdata\local\temp\ and now able to open SMMS without issue.

A: When I've seen this issue, it is usually because the Drive that SSMS is installed on has run out of free space. Deleting some old Log files clears the issue up.
Doing that quick check might be worthwhile before going forward with a re-install.

A: A quick google suggest that apparently it is a bit common issue. It looks like that it is not an issue of SQL Server itself but actually .NET issue And most common (and quick) solution I found is to reinstall SSMS.

A: I got this error on our remote shared server. Turned out that our C drive did not have any space left.
I got it working by asking my colleague to close his SQL Server Management Studio session and it cleared up 7 GB right away! I could login then! Woot woot!

A: I've found that if you are upgrading an iseries odbc driver on a sql cluster. Lots of times you will run into this issue exactly. Renaming the machine.config in both the 32 bit and 64 bit folders does the trick. we currently upgraded from version 12 or 6.1 to 7.1 or 13 as the version 12 was causing a bug check on one of our SQL instances. Upgraded, and the issues all went away.
Cheers,

A: According to the following link:
https://connect.microsoft.com/SQLServer/feedback/details/573771/value-cannot-be-null
I just checked that my user is local admin, then i logged off and logged back in.
After that step i haven't received this error again.

A: I was receiving this exact error and thought I'd have a go at running the repair.
Well the repair didn't resolve the issue however it did tell me that it was unable to access machine.config in C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG - found it didn't exist! There was another file machine.config.default
So had a stab at copying, renaming to .config and viola resolved it and everything working like a champion.

A: I got the same error in SSMS and I found this link and followed the steps as it mentioned.

The problem appeared to be when accessing the contents of a settings file. The file had invalid entries. This file is CurrentSettings-. The fix for this is as shown below:

*

*On the server Go to start menu–>Your profile–>Documents–>SQL Server Management Studio–>Settings (this is the location of the file specified above)

*Delete all files from this folder

*Restart sqlserver services

*Launch the SSMS and this error is gone. You will be able to expand all the folders and perform regular SSMS activities without this error.

Once I performed these steps and restarted my PC this error was gone and SSMS worked fine.

A: I just faced this issue and resolved it immediately in 5 mins. Just go to Control Panel and Run Troubleshooting tool on Programs.
**PATH** Control Panel\All Control Panel Items\Troubleshooting\Programs

It will give you the list of installed programs which may have any issue. Scroll down that list and find 'SQL Server Management Studio' and run troubleshooting process on that. It will hopefully fix you issue.

A: I gets this messages many times and every time it is resolved by different solutions below few of it.

*

*Solution: Clear cache from temp folder, Press windows + R => type "%temp%" => Delete all the files from temp folder... And try weather it works and opens ssms successfully

*Solution: create folder named "2" in this above mentioned temp folder location... And try weather it works and opens ssms successfully.

*Solution:create folder named "4" in this above mentioned temp folder location... And try weather it works and opens ssms successfully.

*Solution: It may cause because of low disk space in drive ssms is installed... so free some space...And try weather it works and opens ssms successfully.

*Solution: Format is the last solution...


text:
Q: Include multiple incoming SMS messages/responses with Twilio functions I'm working on a project now within Twilio, using Twilio Functions, where I'm trying to set up SMS messaging so that if we receive an incoming keyword, we respond with a specific message, including a URL. The plan is to have multiple incoming keywords, with different responses so if someone sends an SMS to one of our numbers, depending on that key word, we respond with a basic message and a URL.  I'm trying to figure out the best way to handle this within Twilio Functions.
I have this working for a single incoming keyword/response, as seen below.
if (incomingMessage.includes('testpark')) {
  twiml.message('StartMyParking:\n\nTo start your parking, please click this link: https://blahblah.com');
} else if (incomingMessage.includes('bye')) {
  twiml.message('Goodbye!');
} else {
  twiml.message('Please check your zone/code and try again.');
}

While that works, I want to add in more incoming words, along with responses, such as an incoming message of 'testpark2' and a response of 'StartMyParking:\n\nTo start your parking, please click this link: https://blahblah2.com'.
Then I would want to include another one with 'testpark3' and a response of 'StartMyParking:\n\nTo start your parking, please click this link: https://blahblah3.com' and so on, all within the same script.
Can someone help me understand how to achieve this?

A: There are a lot of ways to achieve your desired outcome, but here's the most straightforward to begin with.
Instead of creating an else if statement for every possible keyword, you could define the keyword/response pairs up front using a JavaScript Map.
The keys of the Map will be your keywords, the values of the Map will be your responses:
const keywordResponseMap = new Map([
    ['testpark2', 'StartMyParking:\n\nTo start your parking, please click this link: https://blahblah2.com'],
    ['testpark3', 'StartMyParking:\n\nTo start your parking, please click this link: https://blahblah3.com'],
    ['testpark', 'StartMyParking:\n\nTo start your parking, please click this link: https://blahblah.com'],
]);

const keywords = Array.from(keywordResponseMap.keys());
let keyword;

if (incomingMessage.includes('bye')) {
    twiml.message('Goodbye!');
}
else if (keyword = keywords.find(k => incomingMessage.includes(k))) {
    const response = keywordResponseMap.get(keyword);
    twiml.message(response);
} else {
    twiml.message('Please check your zone/code and try again.');
}

Also note that I'm putting the bye case up front because it is more performant than looking for the keywords in the incomingMessage, thus you avoid unnecessarily doing that processing when a user says bye.
You can use find to search for any keyword that is in the incomingMessage, then you can use the keyword that you found to retrieve the response from the map.
If your response will always be the same except for the URL, you could further optimize this by only storing the URL in the map and using string interpolation like this:
const keywordUrlMap = new Map([
    ['testpark2', 'https://blahblah2.com'],
    ['testpark3', 'https://blahblah3.com'],
    ['testpark', 'https://blahblah.com'],
]);

const keywords = Array.from(keywordUrlMap.keys());
let keyword;

if (incomingMessage.includes('bye')) {
    twiml.message('Goodbye!');
}
else if (keyword = keywords.find(k => incomingMessage.includes(k))) {
    const url = keywordUrlMap.get(keyword);
    twiml.message(`StartMyParking:\n\nTo start your parking, please click this link: ${url}`);
} else {
    twiml.message('Please check your zone/code and try again.');
}

It is also important to note that I'm putting testpark last in the map because testpark matches to testpark2 and testpark3. If you'd put it first, it would always resolve to testpark even with a user submits testpark2 or similar values.
Also, I'm using the Map type because it guarantees the order in which the keys are returned, which is again important for the previous point.
When you have a lot more keywords and responses, you may have to start looking at a solution to store them externally like a database, and query the database by keyword to resolve the response.
Good luck, we can't wait to see what you build!


text:
Q: while loop will not stop after each input Ok guys, Im having a problem getting this while loop to stop. As long as I enter something it loops again.  Point of this program is to guess a random number, and if the guess is lower display " too low" and if higher than the random number display "too high" and give them 7 tries and kill the game if the make 7 tries or get it right. please help
My output
I'm thinking of a number between 1-100.  You have 7 guesses.
First guess:
20
Sorry too low
Guess 1:
20
Guess 2:
20
Sorry, you didn't guess it in 7 tries.  You lose.
Sorry too low
Guess 3:
22
Guess 4:
2
Sorry, you didn't guess it in 7 tries.  You lose.
Sorry too low
Guess 5:
22
Guess 6:
2
Sorry too low
Guess 7:
2
Guess 8:

Output should be:
I'm thinking of a number between 1-100.  You have 7 guesses.
First guess: 1
Sorry, you are too low.
Guess # 2: 2
Sorry, you are too low.
Guess # 3: -8
Sorry, you are too low.
Guess # 4: 0
Sorry, you are too low.
Guess # 5: 7
Sorry, you are too low.
Guess # 6: 612
Sorry, that guess is too high.
Guess # 7: -523
Sorry, you didn't guess it in 7 tries.  You lose.

Code:
import java.util.Scanner;
import java.util.Random;

public class App1
{
public static void main( String[] args )
{
    Scanner keyboard = new Scanner(System.in);
    Random r = new Random();

    int secretNumber = 1 + r.nextInt(100);
    int guesses;
    int tries = 0;

    System.out.println("I'm thinking of a number between 1-100.  You have 7        guesses.");
    System.out.println("First guess: ");
    guesses = keyboard.nextInt();
    tries++;

    while(guesses != secretNumber && guesses < secretNumber ){
        System.out.println("Sorry too low");
        System.out.println("Guess " + tries + ":");
        guesses = keyboard.nextInt();
        tries++;

    while(guesses != secretNumber && guesses > secretNumber )
        System.out.println("Sorry too high");
        System.out.println("Guess " + tries + ":");
        guesses = keyboard.nextInt();

        tries++;

    if (tries <7){
        System.out.println("Sorry, you didn't guess it in 7 tries.  You     lose.");
    }

    }
}
}

A: Use a single while loop, and check the input using if statements, something like this:
while(guesses != secretNumber){
  if(guesses != secretNumber && guesses < secretNumber ){
    System.out.println("Sorry too low");
    System.out.println("Guess " + tries + ":");
    guesses = keyboard.nextInt();
    tries++;}

  else if(guesses != secretNumber && guesses > secretNumber ){
    System.out.println("Sorry too high");
    System.out.println("Guess " + tries + ":");
    guesses = keyboard.nextInt();
    tries++;}

  if (tries <7){
    System.out.println("Sorry, you didn't guess it in 7 tries.  You     lose.");
    break;
  }
}

A: Think of it like this, you need to ask the user for value, you need to compare that against a known/random value and display some message if it's not equal.  You increment the number of tries and check to see if they have exceeded the available number of tries...
Something like...
Scanner keyboard = new Scanner(System.in);
Random r = new Random();

int secretNumber = 1 + r.nextInt(100);
int guess = 0;
int tries = 0;
System.out.println("I'm thinking of a number between 1-100.");
do {
    System.out.println("You have " + (7 - tries) + " remaining");
    guess = keyboard.nextInt();
    if (guess < secretNumber) {
        System.out.println("To low");
    } else if (guess > secretNumber) {
        System.out.println("To high");
    }
    tries++;
} while (guess != secretNumber && tries < 7);

if (guess == secretNumber) {
    System.out.println("You guessed right, well done");
} else {
    System.out.println("Sorry, you loose");
}

for example

A: You have to learn more on the scoping and program flow. However, good attempt. The following code will fix your code.
public static void main( String[] args )
{
    Scanner keyboard = new Scanner(System.in);
    Random r = new Random();

    int secretNumber = 1 + r.nextInt(100);
    int guesses = 0;
    int tries = 0;

    System.out.println("I'm thinking of a number between 1-100.  You have 7        guesses.");
    while(guesses != secretNumber && tries < 7) {
        System.out.println("Guess #"+tries+": ");
        guesses = keyboard.nextInt();
        if(guesses == secretNumber) {
            System.out.println("You win");
            break;
        } else if(guesses < secretNumber) {
            System.out.println("Sorry too low");
        } else {
            System.out.println("Sorry too high");
        }
        tries++;
        if(tries >= 7) {
            System.out.println("Sorry, you didn't guess it in 7 tries.  You lose.");
        }
    }
}

A: You can use a for loop to only execute code a certain number of times.
for (int guessNum = 1; guessNum < 8; guessNum++)
    // do stuff

The above code will be run 7 times, and the variable guessNum will hold your "guess number". If you would like to end the loop before 7 guesses have passed, you can use the break statement in the body of the for loop. So if the user doesn't guess right, the loop continues. If they do, you "break" out of the loop and the guessing ends.
Here's my rendition, just for completeness:
Scanner cin = new Scanner(System.in);
Random rng = new Random();

int secretNumber = 1 + rng.nextInt(100);
System.out.println("I'm thinking of a number between 1-100.");

boolean success = false;
for (int guessNum = 1; guessNum < 8; guessNum++) {
    System.out.println("Guess #" + guessNum + ". You have " + (7 - guessNum + 1) + " attempts remaining.");
    int guess = cin.nextInt();
    if (guess < secretNumber) {
        System.out.println("Too low!");
    } else if (guess > secretNumber) {
        System.out.println("Too high!");
    } else {
        System.out.println("You guessed right! Have a cookie!");
        success = true;
        break;
    }
}

if (!success)
    System.out.println("Better luck next time.");

cin.close();


text:
Q: I want to Split an String in if_then_else format in javascript I want to parse an string given in following format:
STRING : if( (a==10) && (b==20) && (c==30) && ((d==40) && (e==50)))
OUTPUT : [ "a==10","b==20","c==30","(d==40) &&(e==50)" ]
What is the best way to achieve the same in Javascript .
I'm not that familiar with regular expressions .

A: var match = str.match(/[a-z]==[0-9]{2,}/g);

This assumes that the sequence will always be a single letter followed by two equals signs followed by a number greater than 10.
Demo


text:
Q: Count consecutive strings of zeroes and ones over multiple groups There have been several discussions about counting consecutive strings of zeroes and ones (or other values) using functions like rle or cumsum. I have played around with these functions, but I can't easily figure out how to get them to apply to my specific problem.
I am working with ecological presence/absence data ("pres.abs" = 1 or 0) organized by time ("year") and location ("id"). For each location id, I would like to separately calculate the length of consecutive ones and zeroes through time. Where these cannot be calculated, I want to return "NA".
Below is a sample of what the data looks like (first 3 columns) and the output I am hoping to achieve (last 2 columns). Ideally, this would be a pretty fast function avoiding for-loops since the real data frame contains ~15,000 rows.
year = rep(1:10, times=3)
id = c(rep(1, times=10), rep(2, times=10), rep(3, times=10))
pres.abs.id.1 = c(0, 0, 0, 1, 1, 1, 0, 0, 1, 1) #Pres/abs data at site 1 across time
pres.abs.id.2 = c(1, 1, 0, 1, 0, 0, 1, 0, 0, 0) #Pres/abs data at site 2 across time
pres.abs.id.3 = c(0, 0, 0, 0, 0, 1, 1, 1, 1, 1) #Pres/abs data at site 3 across time
pres.abs = c(pres.abs.id.1, pres.abs.id.2, pres.abs.id.3)
dat = data.frame(id, year, pres.abs)

dat$cumul.zeroes = c(1,2,3,NA,NA,NA,1,2,NA,NA,NA,NA,1,NA,1,2,NA,1,2,3,1,2,3,4,5,NA,NA,NA,NA,NA)
dat$cumul.ones = c(NA,NA,NA,1,2,3,NA,NA,1,2,1,2,NA,1,NA,NA,1,NA,NA,NA,NA,NA,NA,NA,NA,1,2,3,4,5)

> dat
   id year pres.abs cumul.zeroes cumul.ones
1   1    1        0            1         NA
2   1    2        0            2         NA
3   1    3        0            3         NA
4   1    4        1           NA          1
5   1    5        1           NA          2
6   1    6        1           NA          3
7   1    7        0            1         NA
8   1    8        0            2         NA
9   1    9        1           NA          1
10  1   10        1           NA          2
11  2    1        1           NA          1
12  2    2        1           NA          2
13  2    3        0            1         NA
14  2    4        1           NA          1
15  2    5        0            1         NA
16  2    6        0            2         NA
17  2    7        1           NA          1
18  2    8        0            1         NA
19  2    9        0            2         NA
20  2   10        0            3         NA
21  3    1        0            1         NA
22  3    2        0            2         NA
23  3    3        0            3         NA
24  3    4        0            4         NA
25  3    5        0            5         NA
26  3    6        1           NA          1
27  3    7        1           NA          2
28  3    8        1           NA          3
29  3    9        1           NA          4
30  3   10        1           NA          5

Thanks very much for your help.

A: Here's a base R way using rle and sequence:
dat <- within(dat, {
    cumul.counts <- unlist(lapply(split(pres.abs, id), function(x) sequence(rle(x)$lengths)))
    cumul.zeroes <- replace(cumul.counts, pres.abs == 1, NA)
    cumul.ones <- replace(cumul.counts, pres.abs == 0, NA)
    rm(cumul.counts)
})

#    id year pres.abs cumul.ones cumul.zeroes
# 1   1    1        0         NA            1
# 2   1    2        0         NA            2
# 3   1    3        0         NA            3
# 4   1    4        1          1           NA
# 5   1    5        1          2           NA
# 6   1    6        1          3           NA
# 7   1    7        0         NA            1
# 8   1    8        0         NA            2
# 9   1    9        1          1           NA
# 10  1   10        1          2           NA
# 11  2    1        1          1           NA
# 12  2    2        1          2           NA
# 13  2    3        0         NA            1
# 14  2    4        1          1           NA
# 15  2    5        0         NA            1
# 16  2    6        0         NA            2
# 17  2    7        1          1           NA
# 18  2    8        0         NA            1
# 19  2    9        0         NA            2
# 20  2   10        0         NA            3
# 21  3    1        0         NA            1
# 22  3    2        0         NA            2
# 23  3    3        0         NA            3
# 24  3    4        0         NA            4
# 25  3    5        0         NA            5
# 26  3    6        1          1           NA
# 27  3    7        1          2           NA
# 28  3    8        1          3           NA
# 29  3    9        1          4           NA
# 30  3   10        1          5           NA

A: Here's one option with dplyr:
require(dplyr)
dat %>%
  group_by(id, x = cumsum(c(0,diff(pres.abs)) != 0)) %>%
  mutate(cumul.zeros = ifelse(pres.abs, NA_integer_, row_number()),
         cumul.ones = ifelse(!pres.abs, NA_integer_, row_number())) %>%
  ungroup() %>% select(-x)

#Source: local data frame [30 x 5]
#
#   id year pres.abs cumul.zeros cumul.ones
#1   1    1        0           1         NA
#2   1    2        0           2         NA
#3   1    3        0           3         NA
#4   1    4        1          NA          1
#5   1    5        1          NA          2
#6   1    6        1          NA          3
#7   1    7        0           1         NA
#8   1    8        0           2         NA
#9   1    9        1          NA          1
#10  1   10        1          NA          2
#11  2    1        1          NA          1
#12  2    2        1          NA          2
#13  2    3        0           1         NA
#14  2    4        1          NA          1
#15  2    5        0           1         NA
#16  2    6        0           2         NA
#17  2    7        1          NA          1
#18  2    8        0           1         NA
#19  2    9        0           2         NA
#20  2   10        0           3         NA
#21  3    1        0           1         NA
#22  3    2        0           2         NA
#23  3    3        0           3         NA
#24  3    4        0           4         NA
#25  3    5        0           5         NA
#26  3    6        1          NA          1
#27  3    7        1          NA          2
#28  3    8        1          NA          3
#29  3    9        1          NA          4
#30  3   10        1          NA          5


text:
Q: How do I separate this data using Awk? {"name":"john","rollno":"1040.48","marks":"0.00"

I want to separate rollno:1040.48 from above line using awk.

A: Assuming the complete JSON file
{
  "name": "john",
  "rollno": "1040.48",
  "marks": "0.00"
}

(newlines are not significant), then the following will extract the data associated with the key rollno using jq:
$ jq -r '.rollno' file.json
1040.48

Or, with some string formatting included:
$ jq -r '"rollno: \(.rollno)"' file.json
rollno: 1040.48

The -r flag is to get "raw" output from jq, not JSON.

A: Try this:
echo '{"name":"john","rollno":"1040.48","marks":"0.00"' | awk -F, '{print $2}'

Output
"rollno":"1040.48"


text:
Q: Wikipedia says that the center of S4 is trivial. Is it? Wikipedia says that the center of the symmetric group n>=3 is trivial.
https://en.wikipedia.org/wiki/Center_(group_theory)#Examples
But IIRC, S4 is the same group as the rotations of a cube, and the group of rotations of a cube has an abelian subgroup Z2×Z2 consisting of the rotations by 180 degrees, which is nontrivial.
So ... what's going on?

A: The statement $S_4$ has an abelian subgroup $H=\mathbb{Z}_2\times \mathbb{Z}_2$ means that every element in $H$ commutes with other element in $H$. This does not mean that every element in $H$ commutes with all the elements in $S_4$. So this does not imply $H\leq Z(S_4)$.

A: Not every abelian subgroup of a group is central.   Examples abound.
Let's see, to take a few, any finite group divisible by a prime $p$ has a (cyclic) subgroup of order $p$, by Cauchy's theorem (which is abelian).  But that subgroup needn't be central.   The $S_n'$s ($n\ge3$) indeed provide infinitely many examples.
So you're confusing the definitions. Central elements commute with every element of the parent group.
And, this may be a little like beating a dead horse now but, by Cayley's theorem, any finite abelian group embeds in an $S_n$.


text:
Q: Is there a novel way to integrate this without using complex numbers? I've been reading a post on Quora about lesser known techniques of integration and I'm just curious if there's also a novel way to integrate this type of integral without resorting to complex analysis.
$$ \int^\infty_0 \frac {\cos (ax)\,dx}{x^2}, a \geq 0  $$

A: The given integral is not converging, so I assume you wanted to study:
$$f(a)=\int_{0}^{+\infty}\frac{1-\cos(ax)}{x^2}\,dx$$
that is an even function, hence we can assume $a\geq 0$ WLOG. Integration by parts then gives:
$$ f(a) = a\int_{0}^{+\infty}\frac{\sin(ax)}{x}\,dx $$
and by replacing $x$ with $\frac{z}{a}$ we get:
$$ f(a)=a\int_{0}^{+\infty}\frac{\sin x}{x}\,dx = \frac{\pi}{2}\,a $$
leading to:

$$\forall r\in\mathbb{R},\qquad \int_{0}^{+\infty}\frac{1-\cos(rx)}{x}\,dx = \frac{\pi}{2}|r|.$$


text:
Q: PyOpenGL, pygame, and errors when drawing a shape I've been writing a custom snake game using python, pygame, and pyopengl. I'm trying to draw a shape on the screen. However, I've stumbled upon this error:
Traceback (most recent call last):
  File "F:\Projects\python\Python_Game\venv\lib\site-packages\OpenGL\latebind.py", line 43, in __call__
    return self._finalCall( *args, **named )
TypeError: 'NoneType' object is not callable

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "F:\Projects\python\Python_Game\src\game.py", line 35, in <module>
    main()
  File "F:\Projects\python\Python_Game\src\game.py", line 31, in main
    game.draw_shapes()
  File "F:\Projects\python\Python_Game\src\game_classes.py", line 203, in draw_shapes
    f.draw()
  File "F:\Projects\python\Python_Game\src\game_classes.py", line 128, in draw
    shape.draw()
  File "F:\Projects\python\Python_Game\src\opengl_classes.py", line 128, in draw
    glVertex2fv(cosine, sine)
  File "F:\Projects\python\Python_Game\venv\lib\site-packages\OpenGL\latebind.py", line 47, in __call__
    return self._finalCall( *args, **named )
  File "F:\Projects\python\Python_Game\venv\lib\site-packages\OpenGL\wrapper.py", line 689, in wrapperCall
    pyArgs = tuple( calculate_pyArgs( args ))
  File "F:\Projects\python\Python_Game\venv\lib\site-packages\OpenGL\wrapper.py", line 450, in calculate_pyArgs
    yield converter(args[index], self, args)
  File "F:\Projects\python\Python_Game\venv\lib\site-packages\OpenGL\arrays\arrayhelpers.py", line 115, in asArraySize
    byteSize = handler.arrayByteCount( result )
AttributeError: ("'NumberHandler' object has no attribute 'arrayByteCount'", <function asArrayTypeSize.<locals>.asArraySize at 0x000002642A35DCA0>)

The console is throwing me a TypeError and an Attribute error. I'm not sure if this is due to my code or an issue with one of the libraries. I'm using Python 3.9.1, pygame 2.0.1, and PyOpenGL 3.1.5.
Here's the snippet of my script where the issue arises:
class Circle:
    def __init__(self, pivot: Point, radius: int, sides: int, fill: bool, color: Color):
        self.pivot = pivot
        self.radius = radius
        self.sides = sides
        self.fill = fill
        self.color = color

    # Draw the shape of the circle
    def draw(self):
        glColor3f(self.color.r, self.color.g, self.color.b)
        if self.fill:
            glBegin(GL_POLYGON)
        else:
            glBegin(GL_LINE_LOOP)
        for i in range(100):
            cosine = self.radius * cos(i*2*pi/self.sides) + self.pivot.x
            sine = self.radius * sin(i*2*pi/self.sides) + self.pivot.y
            glVertex2fv(cosine, sine)
        glEnd()

A: The argument of glVertex2fv must be an array with 2 elements. If you have two separate coordinates which are not aggregated in an array you must use glVertex2f. See glVertex:
glVertex2fv(cosine, sine)
glVertex2f(cosine, sine)


text:
Q: deactivate less temporarily - having a less-free expression less is really helpful for clean css. but now I have problem with it
I want to center a div box and gave it the following style:
div {
  width: 400px;
  height: 200px;
  position: absolute;
  top: calc(50% - 100px);
  left: calc(50% - 200px);
}

but now less thinks it should calculate 50% minus 100px, can't do that and write instead: left: calc(-50%) (50-100 = -50)
Is there a way to tell less that it should let this particular code snippet as it is?

A: Copied from Disable LESS-CSS Overwriting calc()
You can use an escaped value:
width: ~"calc(100% - 200px)";

Also, in case you need to mix Less math with escaped values:
width: calc(~"100% - 15rem +" (10px+5px) ~"+ 2em");

Compiles to:
width: calc(100% - 15rem + 15px + 2em);

This works as Less concatenates values (the escaped values and math result) with a space by default.


text:
Q: Как отобразить блок с помощью option? Есть вот такой код:
<select>
  <option id="umor">Юмор</option>
  <option id="music">Музыка</option>
  <option id="images">Картинки</option>
  <option id="video">Видео</option>
</select>

Как сделать, допустим, так, чтобы при выборе <option id="music">Музыка</option> появлялся только

Пробовал:
$("#music").click(function(){
    $(".music").show();
});

Не помогло.

A: Для определения изменения выбора в селекте используется функция change(), вот пример того, как можно сделать вашу логику.
HTML:
<select id="selectItem">
    <option id="umor">Юмор</option>
    <option id="music">Музыка</option>
    <option id="images">Картинки</option>
    <option id="video">Видео</option>
</select>

Показываем юмор

Показываем музыку

Показываем картинки

Показываем видео

JS:
$('.umor').show();

$("#selectItem").change(function(){
    $('.container').find('div').hide();
    var selected = $('#selectItem option:selected').attr('id');
    $('.' + selected).show();
});