text:
Q: How to Update properties of a OneDrive item using REST API? I am trying to update the properties of a OneDrive item using SharePoint REST API.
OneDrive item web URL:
https://vx13-my.sharepoint.com/personal/alexw_vx13_onmicrosoft_com/Documents/SrcDir/File-To-Update.txt

Mainly looking to updating following fields: Author, Created_x0020_By, Editor, Modified_x0020_By, Modified, Created
I tried using Graph API:
Request:
Method: PATCH |
URL: https://graph.microsoft.com/v1.0/sites/vx13-my.sharepoint.com,eab581b1-a945-4d23-9c8e-ec67bb74a42d,32fa1468-54b6-40d6-abbd-f775c4c3932b/drives/b!sYG16kWpI02cjuxnu3SkLWgU-jK2VNZAq733dcTDkyvIAAMdpSy_Sryiw8ARQ8Gv/root:/SrcDir/File-To-Update.txt:/listItem/fields |
Header:
Content-Type: application/json |
Accept: application/json;odata=verbose |
Body:
{
  "Created": "2019-02-01 10:25 AM",
  "Modified": "2020-01-27 11:25 AM",
  "Modified_x0020_By": "3",
  "Created_x0020_By": "3",
  "Author": "Alex Wilber",
  "Editor": "Alex Wilber"
}

It is giving failure response as:

{"code": "accessDenied", "message": "Field 'Created' is read-only"}

Through CSOM API using ValidateUpdateListItem() its working & successfully updating the property fields of OneDrive items.
But is there any way to update property fields of OneDrive item through REST API?

A: If you refer to the documentation here under the Properties section, you will notice certain fields are read only and you wont be able to update them using Graph API.
For all other properties(e.g. name), follow this documentation to update.
Being said that, you can always request for a feature by filling a User Voice so that it goes into our backlog.

A: By default, these properties are Readonly by and cannot be edited.
You need to set the ReadOnlyField to false to update these fields. I used to answer the same question here: https://learn.microsoft.com/en-us/answers/questions/221106/rest-api-to-create-item-with-custom-created-by-and.html
For Created By column:
Url: /_api/web/lists/getbytitle('Mylist')/fields/getbytitle('Created By')

 Body:
     {
     "__metadata": { "type": "SP.FieldUser"},
     "ReadOnlyField": false
     }

For Created column:
Url: /_api/web/lists/getbytitle('Mylist')/fields/getbytitle('Created')
 Body:
     {
     "__metadata": { "type": "SP.FieldDateTime"},
     "ReadOnlyField": false
     }

A: Using SharePoint REST API,
a work around to update the Properties of OneDrive item using method ValidateUpdateListItem()
Get the list-item-id of the file
GET https://vx13-my.sharepoint.com/personal/alexw_vx13_onmicrosoft_com/_api/web/GetFileByServerRelativePath(decodedurl='/personal/alexw_vx13_onmicrosoft_com/Documents/SrcDir/File-To-Update.txt')/listitemallfields/fieldvaluesastext?$select=Id

Update Author, Editor, Created & Modified fields of list item using ValidateUpdateListItem
POST https://vx13-my.sharepoint.com/personal/alexw_vx13_onmicrosoft_com/_api/web/Lists/GetByTitle('Documents')/items(<list-item-id>)/ValidateUpdateListItem()

Content-Type:application/json
Accept:application/json;odata=verbose

Body:
{
    "formValues":
    [
        {
            "FieldName": "Created",
            "FieldValue": "2019/02/01 10:25 AM"
        },
        {
            "FieldName": "Modified",
            "FieldValue": "2020/01/27 11:25 AM"
        },
        {
            "FieldName": "Author",
            "FieldValue": "[{'Key':'i:0#.f|membership|test_user_AK@vx13.onmicrosoft.com'}]"
        },
        {
            "FieldName": "Editor",
            "FieldValue": "[{'Key':'i:0#.f|membership|test_user_JV@vx13.onmicrosoft.com'}]"
        }
    ],
    "bNewDocumentUpdate": true
}


text:
Q: What does it mean to say a man is a "lightweight"? Martin Shkreli, the 32-year-old "Pharma bro", is a lightweight. What does this lightweight mean? Here is the original sentence:

Martin told me that he was a lightweight, something I'd never heard a man admit on a date (or ever).

A: According to Urban Dictionary, a lightweight is

one who can't handle their alcohol/weed.

A: This is one of those phrases that only makes sense with some background knowledge. Lightweight is used in horse-racing and boxing/wrestling to denote a weight class. Weight classes were established at some point in boxing/wrestling history to keep things fair and competitive. I'm not an expert on it so I'm not sure when or how the ranking system came to be. Lightweight is one of the smaller classes. (I'd be willing to bet that at one point it was the smallest class but without further research I can't be sure.)
At some point around 1809 according to http://www.etymonline.com/ it was used in the figurative sense meaning someone or something was small or not influential.
From dictionary.com

adjective
1.
  light in weight.
2.
  being lighter in weight, texture, etc., than another item or object of identical use, quality, or function:
  a lightweight topcoat; a lightweight alloy for ship construction.
3.
  without seriousness of purpose; trivial or trifling:
  lightweight reading.
4.
  of or relating to a lightweight:
  He's the new lightweight contender.
5.
  (of a horse, especially a hunter) able to carry up to 165 pounds (75 kg).
noun
6.
  a person of less than average weight.
7.
  Informal. a person who is of little influence, importance, or effect.
8.
  a boxer or other contestant intermediate in weight between a featherweight and a welterweight, especially a professional boxer weighing between 126 and 135 pounds (56.7–61 kg).

So, context. In this particular instance, the original quote is saying that he is a lightweight, which means he is not able to drink a lot of alcohol. Based on the rest of your sentence and that he was on a date. As another answer has also said, in American culture men like to be seen as being able to drink quite a bit without being effected. She was surprised he admitted it, or at least admitted it on a date.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is my upperRange2 column returning NULL occasionally. Am I abusing CTE's? I have a set that I am going to perform two separate random lottery pulls from. I wanted to do this lottery without a loop statement and thought CTEs were working great. As they always work for the first random selection. But when I try to chain a second repeat of the same logic I start to get random behavior out of the database. Specifically my upperRange2 field is sometimes NULL. Run the code below several times and you should see that sometimes upperRange2 has the proper value, and sometimes it just has NULL. If you only select from the candidatesSelected CTE you will see that the upperRange field always works. This issue only happens when I try to follow this pattern twice for two different random selections.
CREATE VIEW [dbo].[RandomNumberView]
AS
    SELECT RAND() AS randomNumber
GO

CREATE FUNCTION [dbo].[GetRandoms] (
    @lowerRange int,
    @upperRange int,
    @count int
)
RETURNS @randoms TABLE (
    [randomNumber] int primary key
)
AS
BEGIN
    IF (@lowerRange IS NOT NULL
        AND @upperRange IS NOT NULL
        AND @count IS NOT NULL
    )
    BEGIN
        DECLARE @candidateCount int,
                @random float,
                @selected int

        /* This is the numbers that are possible to be selected
        ** from the user specified range. */
        SELECT @candidateCount = (@upperRange - @lowerRange) + 1

        /* If the user specified a count that is greater than the
        ** candidate count, then return every possibility between
        ** the lower and upper range even though its less than
        ** the count requested. */
        IF (@count > @candidateCount)
            INSERT @randoms
                SELECT i
                FROM Seq(@lowerRange, @upperRange)

        /* So that we don't select duplicate numbers keep grabbing
        ** a unique random number until the user specified count
        ** has been reached from the range specified. */
        WHILE (@count <= @candidateCount AND (SELECT COUNT(*) FROM @randoms) < @count)
        BEGIN
            /* Note the use of the RandomNumberView.  It is forbidden
            ** to use non-deterministic functions in functions, which
            ** is why there isn't a call to RAND() here instead.  The
            ** RandomNumberView is just a boxing mechanism around the
            ** RAND() function so that it turns it into a table type
            ** source instead of a function and is therefore allowed. */
            SELECT @random = randomNumber FROM RandomNumberView

            /* To understand how the percentile random number is reduced
            ** to the range specified by the user consider this statement
            ** that produces a range of 0 to 6: ROUND(RAND() * 6, 0) */
            SELECT @selected = ROUND(@random * (@candidateCount - 1), 0) + @lowerRange
            IF (NOT EXISTS (SELECT * FROM @randoms WHERE randomNumber = @selected))
                INSERT @randoms VALUES (@selected)
        END
    END

    RETURN
END
GO

declare @candidates table (name varchar(10) primary key, [weight] int not null, secondaryWeight int not null);
insert @candidates values ('Carl', 2, 1);
insert @candidates values ('James', 1, 2);
insert @candidates values ('Randy', 3, 1);
insert @candidates values ('David', 2, 2);
insert @candidates values ('Michael', 1, 1);

declare @pickCount int = 2;

with
    candidateRows as (
        select
            name,
            [weight],
            secondaryWeight,
            row_number() over (order by [weight]) as [row]
        from @candidates
    ),
    candidateLowerRanges as (
        select
            name,
            [weight],
            secondaryWeight,
            [row],
            (
                select sum([weight])
                from candidateRows b
                where b.[row] <= a.[row]
            ) as upperRange
        from candidateRows a
    ),
    candidateFullRanges as (
        select
            name,
            [weight],
            secondaryWeight,
            [row],
            upperRange,
            lag(upperRange, 1, 0) over (order by upperRange) as previousUpperRange
        from candidateLowerRanges
    ),
    candidatesSelected as (
        select
            name,
            [weight],
            secondaryWeight,
            [row],
            upperRange,
            previousUpperRange,
            randomNumber
        from candidateFullRanges s
            inner join GetRandoms(1, (select max(upperRange) from candidateLowerRanges), @pickCount) r
                on s.upperRange >= r.randomNumber
                    and s.previousUpperRange < r.randomNumber
    ),
    secondRows as (
        select
            name,
            [weight],
            secondaryWeight,
            [row],
            upperRange,
            previousUpperRange,
            randomNumber,
            row_number() over (order by secondaryWeight desc) as [row2]
        from candidatesSelected
    ),
    secondUpperRanges as (
        select
            name,
            [weight],
            secondaryWeight,
            [row],
            upperRange,
            previousUpperRange,
            randomNumber,
            row2,
            (
                select sum(secondaryWeight)
                from secondRows b
                where b.[row] <= a.[row]
            ) as upperRange2
        from secondRows a
    )
select *
from secondUpperRanges

A: The issue is "side-effecting" not determinism or the lack thereof. (My comment this morning was not exactly correct in the details.)
"User-defined functions cannot be used to perform actions that modify the database state."
Why? I am not sure. I think the fact that calling a function during a read having the potential to change the results that would be returned is at the heart of it. You could end up with different results depending on what order SQL Server read rows. One should not need to know the order of work within a query. Stuff like that.
RAND(.5) is deterministic but still can't be used in a function.
"RAND is deterministic only when a seed parameter is specified."
CREATE FUNCTION dbo.f() RETURNS FLOAT AS BEGIN
    RETURN RAND(.5)
END

Msg 443, Level 16, State 1, Procedure f, Line 3
  Invalid use of a side-effecting operator 'rand' within a function.

So what's side-effecting about RAND()?
Pseudo random number generators typically have an internal state. When a number is gotten from the generator two things happen. The internal state is updated and a "random" number is returned. The number and new state is strictly determined by a seed, if provided, or the state as it was when the function started. That internal state is global at some level within SQL Server. So RAND() always changes state, but is deterministic when provided a seed.
Nondetermistic functions can be used in a user defined function.
GETDATE() is nodetermistic, but not "side-effecting".
CREATE FUNCTION dbo.f() RETURNS datetime AS BEGIN
    RETURN GETDATE()
END
GO
PRINT dbo.f()

Nov 20 2015  1:27PM

Boxing the call to RAND() inside the view hid RAND()'s side effecting nature, did it hide RAND()'s non determinism?
No. I can not find a system view to query to determine if SQL Server thinks a function is deterministic or not, but we can try to use the function as if it were, and observe the error.
CREATE VIEW [dbo].[RandomNumberView]
WITH SCHEMABINDING
AS
    SELECT RAND() AS randomNumber
GO

CREATE FUNCTION dbo.MyRand() RETURNS FLOAT
WITH SCHEMABINDING AS BEGIN
    DECLARE @Result FLOAT
    SELECT @Result = randomNumber
    FROM dbo.RandomNumberView
    RETURN @Result
END
GO

CREATE TABLE dbo.T (Col int
    , ColC AS dbo.MyRand() PERSISTED)

Msg 4936, Level 16, State 1, Line 2
  Computed column 'ColC' in table 'T' cannot be persisted because the column is non-deterministic.

So dbo.MyRand() is non-deterministic, why isn't it working again?
"One caveat of almost all nondeterministic functions is that they are executed once per statement, not once per row. ... The only exception to this rule is NEWID, which will generate a new GUID for every row in the statement."
Determinism and nondeterminism are used determine whether a value can be safely persisted. You can't persist GETDATE() if it is used in a computed column or view, because the value will be different tomorrow than it is today. The value for dbo.MyRand() and rand() will be different on the next SELECT so it must be recomputed and not pulled from a persistent source.
However the writers of SQL Server have decided that within a single statement, they will only guarantee at least one call if one or more values are needed. It is nice that a single statement looks like it happened at the same time when using GETDATE(). This "feature" is a pain when trying to use randomness in a single statement.

Note: It sounds like randomness of the PRNG is important to your application. Evaluating randomness is beyond my ken. There are other methods of getting randomness at the row level within a query on SQL Server, some of which involve using NEWID which is evaluated per row. However, if randomness were important, I would not use them. See Random Sampling in T-SQL.


text:
Q: How to explain the strange power consumption difference among OSes and hardwares and how to lower it? I use a wattmeter to measure the power-consumptions of my computers. The following is the result:
my laptop     + Ubuntu 14.04:              14.5 watt
my laptop     + ArchLinux:                 30 watt
my laptop     + Bios Setting:              45 watt
my laptop + Ubuntu 14.04(init=/bin/bash):  31 watt
my laptop + ArchLinux(init=/usr/bin/bash): 33 watt
my old laptop + Ubuntu 14.04:              21 watt
my old laptop + Ubuntu 16.04:              24 watt
my old laptop + ArchLinux:                 19 watt
my old laptop + Bios Setting:              22 watt

PS:
my laptop(CPU: i5-2410; BIOS: AMI A0.18; Board: TSINGHUA TONGFANG CO.,LTD)
my old laptop(CPU: Pentium Dual-core cpu T4200; Board: LENOVO; Board: LENOVO)

all the data except when it is in Bios Setting modes are collected while the environments are idle waiting for user commands and the CPU rate is very low.
I want to tune my ArchLinux use the same or even less power than Ubuntu-14.04. I have tried cpufreq, phc-intel, and compiled my own linux kernel but nothing worked. I tried to run powertop --auto-tune, and both ArchLinux and Ubuntu-14.04 reduce power consumption by about 2-3 watt.
Here is the boot message related to ASPM of my laptop:
> dmesg | grep -i aspm
[    0.162661] acpi PNP0A08:00: _OSC: OS supports [ExtendedConfig ASPM ClockPM Segments MSI]
[    0.162746] acpi PNP0A08:00: _OSC failed (AE_ERROR); disabling ASPM
[    3.323580] r8169 0000:04:00.0: can't disable ASPM; OS doesn't have ASPM control

It's strange to note that my laptop in bios setting mode consumes 45watt. And there must be something to do with user space services, since both Ubuntu-14.04 and ArchLinux consume about 30 watt when they are init to /bin/bash. Could you explain why it's so high? Thank you.

A: I successfully reduce my laptop's power consumption to about 16.7watt.
The key is install bbswitch, according to https://wiki.archlinux.org/index.php/Bumblebee#Power_management.


text:
Q: invalid credentials - LDAP access error in git community edition I want to setup git for version control and continous integration.
I installed git community edition using docker-compose file as described in step 2 of https://docs.gitlab.com/omnibus/docker/README.html#install-gitlab-using-docker-compose. My docker-compose.yml files looks like:
web:
  image: 'gitlab/gitlab-ce:latest'
  container_name: git
  restart: always
  hostname: 'gitserver'
  environment:
    GITLAB_OMNIBUS_CONFIG: |
      external_url 'https://gitserver.local'
      # Add any other gitlab.rb configuration here, each on its own line
  ports:
    - '80:80'
    - '443:443'
    - '22:22'
  volumes:
    - '/srv/gitlab/config:/etc/gitlab'
    - '/srv/gitlab/ssl:/etc/gitlab/ssl'
    - '/srv/gitlab/logs:/var/log/gitlab'
    - '/srv/gitlab/data:/var/opt/gitlab'

I modifed my /srv/gitlab/config/gitlab.rb to include LDAP:
gitlab_rails['ldap_enabled'] = true

###! **remember to close this block with 'EOS' below**

gitlab_rails['ldap_servers'] = YAML.load <<-'EOS'
   main: # 'main' is the GitLab 'provider ID' of this LDAP server
     label: 'LDAP'
     host: 'x.x.x.x'
     port: 636
     uid: 'sAMAccountName'
     method: 'ssl' # "tls" or "ssl" or "plain"
     bind_dn: 'CN=git ldap,OU=Utility Accounts,OU=San Diego,OU=MYDOMAIN,DC=MYCOMPANY,DC=local'
     password: 'MyPwd'
     active_directory: true
     allow_username_or_email_login: false
     block_auto_created_users: false
     base: 'CN=git ldap,OU=Utility Accounts,OU=San Diego,OU=MYDOMAIN,DC=MYCOMPANY,DC=local'
EOS

I get the following error on login:
Could not athenticate you from LDAPmain because invalid credentials

/srv/gitlab/logs/gitlab-rails/production.log shows:
Started POST "/users/auth/ldapmain/callback" for x.x.x.x at 2017-07-10 21:11:06 +0000
Processing by OmniauthCallbacksController#failure as HTML
  Parameters: {"utf8"=>"â", "authenticity_token"=>"BKIQtjz0mu0JlS5bDLGssJFeKGFOJ2cLPKSKAc5JqeyLPBQUkhuI0qcjOTZ9osQEqqlCzPn/PNDlreeENnN28A==", "username"=>"xxx", "password"=>"[FILTERED]"}
Redirected to https://gitserver.local/users/sign_in
Completed 302 Found in 5ms (ActiveRecord: 0.3ms)
Started GET "/users/sign_in" for x.x.x.x at 2017-07-10 21:11:06 +0000
Processing by SessionsController#new as HTML
Completed 200 OK in 143ms (Views: 92.4ms | ActiveRecord: 3.0ms)

I have tried several permutations and combinations of LDAP settings but nothing seems to work. There are several similar settings/error and suggestions by users on the net on how they solved their problem but none seem to work for me.
Some of the things that I tried are 1) commenting out bind dn and pwd 2) setting uid to uid instead of sAMAccountName 3) tried both plain and ssl methods 4) setting allow_username_or_email_login to false.
This same LDAP settings is used by other apps in the company.. so nothing wrong with it.
I have been hitting the wall for the last one week. Any help is appreciated.
Thanks!
UPDATE: I tried the followign but no luck
1) Gitlab: LDAP "Invalid credentials", but credentials are right
2) Gitlab LDAP Authentication
UPDATE2: Note that am only able to login as git ldap and not as myself. I would like everyone to login with their own credentials

A: Note that the bind dn and base dn are exactly the same. Having CN in base dn allows only that user to login. Changing it to 'OU=MYDOMAIN,DC=MYCOMPANY,DC=local' allows all users to login


text:
Q: Incorrect value of click event layerX on svg foreignObject element On svg viewport zoomed in state (bigger svg width than viewport width). The foreignObject click event layerX property is incorrect on Safari and Chrome. In the following example click on center of yellow rect and see the console output.
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body style="margin:0">
  <svg viewBox="0 0 200 200" style="height: 400px; width: 400px;" xmlns="http://www.w3.org/2000/svg">
    <rect width="100%" height="100%" fill="red"/>
    <foreignObject x="50" y="50" width="100" height="100">
      <div style="background-color: yellow; width: 100px; height:100px;">
      </div>
    </foreignObject>
  </svg>
</body>
</html>

Try it on chrome, safari and firefox. Notice you will get different result on each browser. The chrome and safari results are meaningless and firefox calculates without considering viewport state.
Is there any workaround to this issue?

A: The trick is to not use layerX , instead use
event.clientX - rect1.getBoundingClientRect().left

I updated the example to work correctly. Now I get consistent result among chrome, firefox and safari.


text:
Q: Removing a column in a pandas dataframe if all the values are a certain string I have the following dataframe called df.
Sometimes it looks like this (where each value is unique)
   key   value1 value2 value3
0  key1  value  value  value
1  key2  value  value  value

Sometimes the entire column of value3 are is filled with dashes: '-'.
   key   value1 value2 value3
0  key1  value  value  -
1  key2  value  value  -

I want to find a command which will drop the column value3 if all the items in the column dashes.
I tried using df['value3'].any() and that that returns a '-'.
Is the right way to do what I want this?
if df['value3'].any() == '-':
    df = df.drop['value3']

Or is there a better way?

A: Use
>>> df.loc[:, ~df.eq('-').all()]
    key value1 value2
0  key1  value  value
1  key2  value  value

A: Compare for not equal by DataFrame.ne and then get all columns with match by DataFrame.any in boolean indexing:
print (df.loc[:, df.ne('-').any()])
    key value1 value2
0  key1  value  value
1  key2  value  value


text:
Q: How to move the fieldEditor to selected position? When I tried to edit the column using -(void)editColumn:(NSInteger)column row:(NSInteger)row withEvent:(NSEvent *)theEvent select:(BOOL)select of NSTableView the field editor always comes at the beginning of the NSTextField.I inserted some tab spaces for the text. I would like to move the field editor(cursor) to the start of the text. Any hints to accomplish this?

A: I am able to solve the issue using the following code.
[[self.tableView currentEditor] setString:@"YourStringValue"];


text:
Q: Verify that an increase in 8º C will saturate a common emitter In the Art of Electronics there is an assertion that if a bias is established with 0.5 the supply voltage, the transistor will saturate if the temperate goes up 8ºC. The schematic is the basic one for common emitter.
I tried to verify that the collector-emitter voltage became zero or less. However I can't manage to get it right. If we start by taking the V_BE voltage as 0.6, it would go down to .5832, but how can we use that to verify it saturates?
Thanks!

A: You know that \$\text I_c\$ = \$\text I_s e^{V_{BE}/Vt}\$
To get the transistor to saturate you have to double the collector current, so if you consider \$\frac{\text I_{c1}}{\text I_{c2}} = 2\$, then
\$\Delta V_{BE}\$ = ln(2)Vt = 18mV, assuming Vt = 26mV (room temperature)
So a base voltage delta of 18mV will cause the collector current to double. If we assume the base voltage divider is 'stiff', then a \$\Delta V_{BE}\$ from 0.600 to 0.582 will cause the transistor to saturate.


text:
Q: Java call to web service not updating boolean properties Scenario:
I am developing a Swing app which connects to a webservice created by .NET (WCF). Had a few issues, but mostly resolved now. However, I can't seem to update boolean properties. In my entity, I have a boolean property Gender:
True = Male,
False = Female,
Null = Unknown/Unspecified.
CODE:
updatedEntry.setGender(factory.createBoolean(true));

Here, factory is just an instance of the ObjectFactory class generated for me by Netbeans. updatedEntry is of type JAXBElement<Boolean> and I can see that the value is indeed set to True. The update method runs fine without any errors but then I see the database has NULL for that column. This is very weird because the other columns are updated just fine.
Just to make sure there wasn't something wrong with my web service, I used SoapUI and manually input the parameters.. it worked fine. One thing I noticed was that I could not use the string True, but had to input a 1 for it to work. Which makes me wonder; is the JAXBElement or some other generated code from my Netbeans project sending the value as true instead of 1? Though, if that were the case then why did SoapUI throw me an error when I tried that but Netbeans did not? Like I said.. from Netbeans, all the properties were updated EXCEPT the Gender.
Is there some way I can view the generated Soap XML that is generated by Netbeans? Or does anyone have any ideas..., seen this issue before?

A: Below is an example that will help.
XML Schema - schema.xsd
You will get a property of type JAXBElement<Boolean> when you have an element that is both nillable="true" and minOccurs="0".
<?xml version="1.0" encoding="UTF-8"?>
<schema xmlns="http://www.w3.org/2001/XMLSchema"
    targetNamespace="http://www.example.org/schema"
    xmlns:tns="http://www.example.org/schema"
    elementFormDefault="qualified">

    <element name="root">
        <complexType>
            <sequence>
                <element name="trueValue" type="boolean" minOccurs="0" nillable="true"/>
                <element name="falseValue" type="boolean" minOccurs="0" nillable="true"/>
                <element name="nullValue" type="boolean" minOccurs="0" nillable="true"/>
                <element name="notSetValue" type="boolean" minOccurs="0" nillable="true"/>
            </sequence>
        </complexType>
    </element>

</schema>

Generated Model - Root
Below is what the class generated from the root elemnent might look like:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {"trueValue", "falseValue", "nullValue", "notSetValue"})
@XmlRootElement(name = "root")
public class Root {

    @XmlElementRef(name = "trueValue", namespace = "http://www.example.org/schema", type = JAXBElement.class, required = false)
    protected JAXBElement<Boolean> trueValue;
    @XmlElementRef(name = "falseValue", namespace = "http://www.example.org/schema", type = JAXBElement.class, required = false)
    protected JAXBElement<Boolean> falseValue;
    @XmlElementRef(name = "nullValue", namespace = "http://www.example.org/schema", type = JAXBElement.class, required = false)
    protected JAXBElement<Boolean> nullValue;
    @XmlElementRef(name = "notSetValue", namespace = "http://www.example.org/schema", type = JAXBElement.class, required = false)
    protected JAXBElement<Boolean> notSetValue;

}

Generated Model - ObjectFactory
@XmlRegistry
public class ObjectFactory {

    private final static QName _RootNullValue_QNAME = new QName("http://www.example.org/schema", "nullValue");
    private final static QName _RootTrueValue_QNAME = new QName("http://www.example.org/schema", "trueValue");
    private final static QName _RootFalseValue_QNAME = new QName("http://www.example.org/schema", "falseValue");
    private final static QName _RootNotSetValue_QNAME = new QName("http://www.example.org/schema", "notSetValue");

    public ObjectFactory() {
    }

    public Root createRoot() {
        return new Root();
    }

    @XmlElementDecl(namespace = "http://www.example.org/schema", name = "nullValue", scope = Root.class)
    public JAXBElement<Boolean> createRootNullValue(Boolean value) {
        return new JAXBElement<Boolean>(_RootNullValue_QNAME, Boolean.class, Root.class, value);
    }

    @XmlElementDecl(namespace = "http://www.example.org/schema", name = "trueValue", scope = Root.class)
    public JAXBElement<Boolean> createRootTrueValue(Boolean value) {
        return new JAXBElement<Boolean>(_RootTrueValue_QNAME, Boolean.class, Root.class, value);
    }

    @XmlElementDecl(namespace = "http://www.example.org/schema", name = "falseValue", scope = Root.class)
    public JAXBElement<Boolean> createRootFalseValue(Boolean value) {
        return new JAXBElement<Boolean>(_RootFalseValue_QNAME, Boolean.class, Root.class, value);
    }

    @XmlElementDecl(namespace = "http://www.example.org/schema", name = "notSetValue", scope = Root.class)
    public JAXBElement<Boolean> createRootNotSetValue(Boolean value) {
        return new JAXBElement<Boolean>(_RootNotSetValue_QNAME, Boolean.class, Root.class, value);
    }

}

Demo
Below is some demo code that will populate each of the JAXBElement<Boolean> properties differently to demonstrate each of 4 possible options.
public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance("forum15170433");

        Root root = new Root();
        ObjectFactory objectFactory = new ObjectFactory();

        // set the value to true
        root.setTrueValue(objectFactory.createRootTrueValue(true));

        // set the value to false
        root.setFalseValue(objectFactory.createRootFalseValue(false));

        // set the value to null
        root.setNullValue(objectFactory.createRootNullValue(null));

        // specify the value is unset
        root.setNotSetValue(null);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(root, System.out);
    }

}

Output
Below is the output from running the demo code.  We see that the xsi:nil attribute is used to represent the null value and the unset value is not marshalled.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<root xmlns="http://www.example.org/schema">
    <trueValue>true</trueValue>
    <falseValue>false</falseValue>
    <nullValue xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:nil="true"/>
</root>


text:
Q: iOS how to change default onPress button color I have been trying to figure out this problem for a while now and no avail. I have a program I inherited and it uses a a white background image for the buttons. You can change what image you want easily from UI editor. When the user presses down on that button the white background image is switched out for a different image, showing a blue highlight instead. For the life of me I can't find where that is being referenced at. I even tried adding a new button and it is the stock highlight color.
Where is that onPress reference probably at? Or where can I re-reference this new button to have a new onPress image background?
Thank you!

A: Select the button in Interface Builder. Open the attributes inspector for that button. Under Button you can choose the "State Config". Change that to "Highlighted". Now you can change the Image config for the highlighted state.


text:
Q: Xamarin Forms - Preserve Basic Authentication after redirect? How to preserve Basic Auth after redirecting in HttpClient?

*

*Original URL: https://myapp.herokuapp.com/api/login

*Redirect URL with custom domain: http://io.myapp.co/api/login
Below is my code I use in Xamarin Forms.
When I use the original URL, authentication works. But when I use the redirect URL, I get an "Unauthorized" response. The redirect URL works fine in Postman.
using (var client = new HttpClient())
{
    client.DefaultRequestHeaders.Add("email", TxtEmail.Text);
    client.DefaultRequestHeaders.Add("password", TxtPassword.Text);
    client.DefaultRequestHeaders.Authorization = HttpClientHelper.NdAuth;
    var result = await client.GetAsync(Constants.UrlLoginUser);
}

How to preserve Basic Auth while redirecting? How Postman is able to do it?


text:
Q: TypeScript: Put array into array Note: This question is about TypeScript (not JavaScript).
I want to put an array into an array at a specified position:
var a = [];
a[0] = [1,2];

a is now [1,2] but should be [[1,2]].
How can I achieve that my array [1,2] that I want to put into the array is not flattened but put directly as it is into the array?
so finally i need the procedure for putting array into array .

A: Try following code snippet
a = new Array(5)

a[0] = new Array(2)

a[0][0] = Array(1,2);

a[0][1] = Array(3,4);

A: Where are you seeing a as [1,2]? I just tried this and it shows [[1,2]]
Also, a different method you could try is to use push:
a.push([1,2]);
both the push() and your code give me the same results, both are what you are looking for. Are you seeing this in a browser? or node?

A: In Javascript:
I tried what you said in console and I get the expected result:
a = []

a[0] = [1,2]

a; output=>
[Array[2]]

a.length: output=>
1

a[0].length: output=>
2

A: Okay, so you are right. The code in my question works as expected.
I was just confused by visual studio debugger visualizer:

...showing [[1,2]] as [1,2] (which is really not nice, is it?).
And also confused by internet explorer 11 console:

...showing [[1,2]] as 1,2.

A: Your code is fine

var a = [];
a[0] = [1, 2];
console.log(a.join(',')); //prints, `1,2`
console.log(JSON.stringify(a)); //prints, `[[1,2]]`
Open console...


text:
Q: Irreducible unitary representations of $ \Bbb{R}^{2} \rtimes_{\alpha} \Bbb{R} $.
Let $ \alpha $ be the action of $ \Bbb{R} $ on the group $ \Bbb{R}^{2} $ defined by $ \alpha_{t} \! \left( \begin{bmatrix} a \\ b \end{bmatrix} \right) = \exp \! \left( \begin{bmatrix} t & 0 \\ 0 & - t \end{bmatrix} \right) \begin{bmatrix} a \\ b \end{bmatrix} $. Let $ G = \Bbb{R}^{2} \rtimes_{\alpha} \Bbb{R} $. Determine the equivalence classes of irreducible unitary representations of $ G $.

I came up with two approaches.
The first one is to actually work with the matrices.
The other one is to use Schur's Lemma and use the fact that an irreducible representation $ \pi $ on the center of $ G $ is just a character.
But with those approaches, I don't know how to go further and I guess it's because I'm not really sure whether my approach is reasonable.
Thanks.


text:
Q: Why is my Headset playing through my Mic I dont know why. But my headset sounds are playing through my mic.
Aka, if someone talks to me, they can hear them selves.
And game audio is playing through too.
Now, the first thing, is maybe the sound is too high .. and so its being Picked up by the mic.. But this is not the case.
Its like some audio setup bug..
Any ideas?

A: You haven't posted your operating system, but that sounds as if you have the "mix" setting enabled in your windows audio. Check your advanced settings in your audio.


text:
Q: i5 6th generation drivers are available in ubuntu 16.4 I want to upgrade my system with Intel i5 6th generation,8gb ram.
but my question is that if I install Ubuntu 16.04 64bit so all systems drivers are available default in it. (Ubuntu 16.04).


text:
Q: Plan Cache Pages by Database in SQL Server 2008R2 Is it possible to get a break down of how many plan cache pages are being used per database? Perfmon seems to only have the total for the server, but maybe there is a DMV with more detail?
Also, does the buffer pool (sys.dm_os_buffer_descriptors) include the plan cache or is that separate?

A: Here are queries that will give you buffer breakdown and plan cache breakdown per database. Note that plan cache is broken down by MB, not by pages - I don't know of a handy way, off the top of my head, to calculate the pages used by the plan cache (you'd think it's simple division, but not necessarily).
-- buffer pool breakdown

SELECT
  db = DB_NAME(database_id),
  c = COUNT(DISTINCT page_id),
  size_MB = CONVERT(DECIMAL(12,2), COUNT(DISTINCT page_id)*8.0/1024)
FROM sys.dm_os_buffer_descriptors
WHERE database_id < 32767
GROUP BY database_id
ORDER BY c DESC;

-- plan cache breakdown

SELECT
  db = DB_NAME(t.[dbid]),
  size_MB = CONVERT(DECIMAL(12,2), SUM(p.size_in_bytes)/1024.0/1024)
FROM sys.dm_exec_cached_plans AS p
CROSS APPLY sys.dm_exec_sql_text(plan_handle) AS t
WHERE t.[dbid] < 32767
GROUP BY t.[dbid]
ORDER BY size_MB DESC;

On my test instance there are cases where plan cache is larger than the buffer pool for a given database.
The buffer pool contains both the data cache and the plan cache. But AFAIK sys.dm_os_buffer_descriptors only contains information about the data cache (index and data pages), so it does not necessarily reflect the entire buffer pool. The cases I saw above seem to support that theory.

A: use db1;
select ...
from db2..table
join db3..table;

Should the memory allocated for this plan be counted against db1, db2 or db3? Usually the three dbs in my example are the same and the issue is not perceived, but the problem is there none the less and this is why a view like sys.dm_exec_cached_plans does not project database_id, and sys.dm_exec_query_plan has the note:

For ad hoc and prepared SQL statements, the ID of the database where
the statements were compiled.

The thinking around this issues should be 'memory allocated for plans', 'memory allocated for execution' and don't consider such memory as 'pages'. This is even more so in the SQL Server 2012 memory model which makes the buffer pool and ordinary client of the memory broker.
For 'data' is all clear: a data page has an obvious database is coming from and sys.dm_os_buffer_descriptors will describe it exactly.
And for the second question: sys.dm_os_buffer_descriptors will only show data, not stolen pages.


text:
Q: Changing of basis from conjugate diagonal to rotation matrix Given matrices,
$$D = \begin{pmatrix}
z & 0 \\
0 & \bar{z}
\end{pmatrix}, \hspace{12pt}
B = \begin{pmatrix}
1 & -i \\
1 & i
\end{pmatrix}, \hspace{12pt}
U = \begin{pmatrix}
Re(z)& Im(z) \\
-Im(z) & Re(z)
\end{pmatrix}$$
the change of basis given by $B$ results in
$U = B^{-1} D B$.
Of course, I can do the computations and verify this. But what's really going on here? Is there something geometric in this change of basis that allows me to decompose $z$ into its real and imaginary parts? Is the fact that $U$ is a rotation matrix relevant?


text:
Q: Undefined local variable or method `fritkot' for #Please bear with me as I'm still trying to learn JS, Ajax, and RoR.
If you don't want to read through all the this nonsense, TL;DR: I have problems trying to incorporate geojson data from a regular ruby model into a map (mapbox.js), adding marker popups a long the way and using Js and AJAX.
I'm trying to include the mapbox.js (version 2.2.2) library into a Rails (4.2.4), but I keep getting this error msg:

Undefined local variable or method `fritkot' for FritkotController

Here is the code in my controller:
# GET /fritkots
# GET /fritkots.json

 def index
   @fritkots = Fritkot.all
   @geojson = Array.new
   build_geojson(fritkot, @geojson) ## Where the error appears

   respond_to do |format|
     format.html
     format.json { render json: @geojson }
   end
 end

 # FIX: To be extracted into a class method (.self_geojson)?

 def build_geojson(fritkots, geojson)
   fritkots.each do |fritkot|
     geojson << GeojsonBuilder.build_fritkot(fritkot)
   end
 end

At the moment, I created a GeojsonBuilder class, but I'm thinking this should be perhaps a module or a helper extending or including my Fritkot model? Or is it the other way around? (I'm sorry if I'm mixing things up, it's just that I have worked on this problem the last couple of days and everything is getting tangled up).
Here is the code:
 class GeojsonBuilder

  def build_fritkot(fritkot, geojson)
    geojson << {
      type: "Feature",
      geometry: {
        type: "Point",
        coordinates: [fritkot.longitude, fritkot.latitude]
      },
      properties: {
        title: fritkot.title,
        address: fritkot.address,
        :"marker-color" => "#f86767",
        :"marker-size" => "medium",
        :"marker-symbol" => "circle", #fast_food
      }
    }
  end
end

Code on map.js
 $(document).on("ready", function() {
  L.mapbox.accessToken = "pk.eyJ1IjoiZHNvbGlzIiwiYSI6ImViNzgwOGZmZmVlMmVjYzg5ZjZhNzYxNDE3MWE0ZTFhIn0.0E-Z_FCmS8VHPRY07tVSEQ";
 var map = L.mapbox.map("map", "dsolis.ni76oel2", { zoomControl: false }.setView([50.854975, 4.3753899], 7);

  map.featureLayer.on("ready", function(e) {
  getEvents(map);
  });
});

function getevents(map) {
  var $loading_wheel = $("#spinning-wheel")
  $loading_wheel.show();
  $.ajax({
    dataType: 'text',
    url: '/events.json',
    success:function(events) {
    $loading_wheel.hide();
      var geojson = $.parseJSON(events);
      map.featureLayer.setGeoJSON({
        type: "FeatureCollection",
        features: geojson
      });
      addEventPopups(map);
     },
    error:function() {
      $loading_wheel.hide();
      alert("Opps something went wrong.");
    }
  });
}

function addEventPopups(map) {
  map.featureLayer.on("layeradd", function(e) {
    var marker = e.layer;
    var properties = marker.feature.properties;
    var popupContent = '
' + '
' + properties.title + '
' +
                     '
' + properties.address + '
' + '
';
    marker.bindPopup(popupContent, {closeButton: false, minWidth: 300});
   });
 }

Any help would be greatly appreciated. Thank you.
EDIT 1: Add Screenshot of error
ScreenShot of where I get the error
EDIT 2: Add Comment where the error msg appear
EDIT 3: Fix some code as per @snkashis suggestions.
EDIT 4: Here is public gist with the code.
However, I'm still unable to load/view my objects on the map. I get this type of error when opening the console:
Uncaught Error: Invalid LatLng object: (NaN, NaN)o.LatLng @ leaflet-src.js:1122o.extend.coordsToLatLng @ leaflet-src.js:6206o.extend.geometryToLayer @ leaflet-src.js:6160L.FeatureGroup.extend._initialize @ feature_layer.js:94L.FeatureGroup.extend._initialize @ feature_layer.js:85L.FeatureGroup.extend.setGeoJSON @ feature_layer.js:37$.ajax.success @ map.self-9667db8b4bdc056a4ee3b0d7d005cf31e80d182ed0fc56a57b58ef94a30dd618.js?body=1:25jQuery.Callbacks.fire @ jquery.self-a714331225dda820228db323939889f149aec0127aeb06255646b616ba1ca419.js?body=1:3149jQuery.Callbacks.self.fireWith @ jquery.self-a714331225dda820228db323939889f149aec0127aeb06255646b616ba1ca419.js?body=1:3261done @ jquery.self-a714331225dda820228db323939889f149aec0127aeb06255646b616ba1ca419.js?body=1:9315jQuery.ajaxTransport.options.send.callback @ jquery.self-a714331225dda820228db323939889f149aec0127aeb06255646b616ba1ca419.js?body=1:9719

Here is updated code
Controller:
  # GET /fritkots
  # GET /fritkots.json
  def index
    @fritkots = Fritkot.all
    # @geojson = Array.new
    # build_geojson(fritkot, @geojson)

    @geojson = @fritkots.map do |fritkot|
      GeojsonBuilder.build_fritkot(fritkot)
    end

    respond_to do |format|
      format.html
      format.json { render json: @geojson }
    end
  end

  # FIX: To be extracted into a .self_geojson?
  def build_geojson(fritkots, geojson)
    fritkots.each do |fritkot|
      geojson << GeojsonBuilder.build_fritkot(fritkot)
    end
  end

  # GET /fritkots/1
  # GET /fritkots/1.json
  def show
    @fritkot = Fritkot.find(params[:id])
  end

map.js:
$(document).on("ready", function() {
  L.mapbox.accessToken = "pk.eyJ1IjoiZHNvbGlzIiwiYSI6ImViNzgwOGZmZmVlMmVjYzg5ZjZhNzYxNDE3MWE0ZTFhIn0.0E-Z_FCmS8VHPRY07tVSEQ";
  var map = L.mapbox.map("map", "dsolis.ni76oel2", { zoomControl: false }).setView([50.846026, 4.3491641], 13);

    map.featureLayer.on("ready", function(e) {
      getEvents(map);
    });
  });

  function getEvents(map) {
    var $loading_wheel = $("#spinning-wheel")
    $loading_wheel.show();
    $.ajax({
      dataType: 'text',
      url: '/fritkots.json',
      success:function(fritkots) {
        $loading_wheel.hide();
        var geojson = $.parseJSON(fritkots);
        map.featureLayer.setGeoJSON({
          type: "FeatureCollection",
          features: geojson
        });
        addEventPopups(map);
      },
      error:function() {
        $loading_wheel.hide();
        alert("Oops something went wrong.");
      }
    });
  }

  function addEventPopups(map) {
    map.featureLayer.on("layeradd", function(e){
      var marker = e.layer;
      var properties = marker.feature.properties;
      var popupContent = '
' + '
' + properties.title + '
' +
                         '
' + properties.address + '
' + '
';
      marker.bindPopup(popupContent, {closeButton: false, minWidth: 300});
    });
  }

GeojsonBuilder:
class GeojsonBuilder

  def self.build_fritkot(fritkot)
    geojson = {
        type: "Feature",
        geometry: {
          type: "Point",
          coordinates: [fritkot.longitude, fritkot.latitude]
        },
        properties: {
          title: fritkot.title,
          address: fritkot.address,
          :"marker-color" => "#FFFFFF",
          :"marker-size" => "medium",
          :"marker-symbol" => "circle", #fast_food
        }
      }
    geojson
  end
end

I'm getting closer and closer to fix this up.

A: I don't know the geojson at all, so I apologize if I'm way off but here's what I see programmatically.
You declare 2 variables: fritkots and geojson.  You then send fritkot and @geojson to build_gejson().  build_geojson() receives fritkots and geojson and operates on a 'sequence' (array?, list?) of fritkot.
My 'guess' is that you should be sending fritkots to build_geojson() - if that's wrong, let me know and I'll delete the answer.
[edit]
one other possibility, should you be sending Fritkot instead of fritkot to build_gejson()?
[/edit]

A: You are still sending an undefined fritkot to the build_geojson controller method, when it is expecting an array.
Secondly, I don't see the point of making an empty array in the previous line.
I'd suggest doing this in your index method for the time being, and then modifying GeojsonBuilder to only take one parameter and return one thing.
@geojson = @fritkots.map do |fritkot|
    GeojsonBuilder.build_fritkot(fritkot)
end

Change def build_fritkot(fritkot, geojson) to def build_fritkot(fritkot) and just make it return the Hash(meaning no <<) it makes instead of appending to a given array.
And to take a step further, why run this expensive loop to generate the GeoJSON every single time someone hits your index...I'd recommend caching this somehow instead.


text:
Q: Split multi paragraphed shell output to multiple variables I am looking to split multi paragraphed shell results into different variables,
Here's a sample output from sensors to illustrate
acpitz-virtual-0
Adapter: Virtual device
temp1:        +41.0°C  (crit = +95.0°C)

coretemp-isa-0000
Adapter: ISA adapter
Core 0:       +36.0°C  (high = +90.0°C, crit = +90.0°C)
Core 1:       +36.0°C  (high = +90.0°C, crit = +90.0°C)

In this case I am looking to have a variable sensors (the command name) with the whole output,  sensors_acpitz_virtual_0 with the whole first paragraph of output and a variable sensors_coretemp_isa_0000 with the content of the second paragraph.
sensors_acpitz_virtual_0
acpitz-virtual-0
Adapter: Virtual device
temp1:        +41.0°C  (crit = +95.0°C)

sensors_coretemp_isa_0000
coretemp-isa-0000
Adapter: ISA adapter
Core 0:       +36.0°C  (high = +90.0°C, crit = +90.0°C)
Core 1:       +36.0°C  (high = +90.0°C, crit = +90.0°C)

Then a variable sensors_acpitz_virtual_0__Adapter__Virtual_device that will only contain the content of this part of the first paragraph
Adapter: Virtual device
temp1:        +41.0°C  (crit = +95.0°C)

A variable sensors_acpitz_virtual_0__Adapter__Virtual_device__temp1 that will contain only the temperature of temp1 from the Virtual device adapter of acpitz-virtual-0 and so on.
+41.0°C  (crit = +95.0°C)

What tools (preferably commonly available pre installed in distros) should I use and how, to get this kind of results ?

A: well, i'm not really sure i get from whence the name acpitz_virtual_0__Adapter__Virtual_device__temp1 is supposed to come, and so this doesn't do anything for it, but:
sed     -e '/./{H;$!d;}' -e'x;s///' \
        -e 's/\(\n.*\)*-/_\1/g' \
        -e "s/\n\(.*\)/='\1'/" <your_input

...writes output as follows:
acpitz_virtual_0='Adapter: Virtual device
temp1:        +41.0°C  (crit = +95.0°C)'
coretemp_isa_0000='Adapter: ISA adapter
Core 0:       +36.0°C  (high = +90.0°C, crit = +90.0°C)
Core 1:       +36.0°C  (high = +90.0°C, crit = +90.0°C)'

I didn't allow for any possibility of a ' single-quote in your input, and i assume the only incompatibility with portable shell names are the dashes in each. To handle the quotes (just in case) do:
sed     -e '/./{H;$!d;}' -ex\;s/// \
        -e "s/\(\n.*\)*['-]/_\1/g" \
        -e "s/'/'"'\\&&/g'         \
        -e "s/\n\(.*\)/='\1'/" <your_input

...which will always escape any hardquote in input.
To use this output in the way you specify there are several options. You can wrap it in eval:
eval "$(sed ... <your_input)"

...or read it out to a file...
sed ... <your_input >out; . ./out

...or stream it to a subshell...
sed ... <your_input | sh

...and many other things besides.

Here's another sed that can do the fancy stuff you asked about:
sed -netDel -e'/./{H;g;s///'              \
-e'# grow'  -e's/[0-9]*:  .*\n[^:0-9]*//' \
-e'# loop'  -e's/:  .*//'                 \
-e'# ends'  -e's/[^_[:alnum:]]/_/g;}'     \
-e'# here'  -e's/\(.\)\(.*\)/& \\/p'      \
-e$\!t -ex  -e's//\2\1. \\/'              \
-e'# swap'  -e"s/'/'"'\\&&/g;tDel'        \
-ed\;:Del   -e"s/\(.*\). /'\1' /"         \
-e'# loop'  -e'/^[^:]*:  /!{p;D;}'        \
-e'# ends'  -e"s/\n/' \\\&/;P;D"  <infile >outfile

Here's how this works: sed kind of burns its candle at both ends here, in a manner of speaking. sed alternates states between iterative growth from left-to-right, and, at the end of each paragraph, iterative reduction in the same direction.
Kind of like:
1
1:2    # grow
1:2:3  # swap
  2:3  # del
    3
#if that makes any sense at all...

The grow state is handled between /./{H;g;...p;};$!t.

*

*For each input line matching at least a . single character, sed appends a copy to Hold space, and immediately afterwards gets all of the hold space by overwriting the pattern space.

*

*In this way sed can perform edits on the growing stack and print the results for each iteration while saving the original input in hold space all the while.

*In the grow state, sed will print a valid shell name for each input line.

*

*sed removes everything between the first and last occurrences of "[0-9]*:  " and everything from the last occurrence of ":  " on, but otherwise replaces any characters which are ^not in the class [_[:alnum:]] with the character _ - and so the names grow recursively (until they don't).

*sed tests for any line which has undergone a successful edit during a grow state and branches those away from the script before attempting to handle logic for the swap state.

*

*As a special case, this test is !not performed for the $last input line, and so it falls-through to the swap state anyway.

The swap state is handled between x;...;d

*

*sed exchanges either the last or a blank pattern space buffer for the hold space buffer, thereby clearing the save space for the next input paragraph (if any).

*

*Sequences of more than a single blank-line in input do not negatively affect this pattern - exchanging a blank hold space for a blank pattern space can happen as often as is needed to arrive at identical results.

*sed swaps the paragraph's leading blank line to its tail, appends a space followed by a backslash, and escapes at once all single-quotes (if any) in the paragraph before falling through for a non-blank hold buffer to the del state, or else deleting a blank one.

The del state is effective while tDel -> :Del and is handled between :Del;...;D.

*

*sed wraps all of its recursively reducing pattern buffer in a pair of single-quotes.

*

*The first of these is removed with the first line for every del iteration, but the last is always replaced with itself.

*For a paragraph buffer matching "^[^:]*:  " sed will prepend another single quote followed by a space and a backslash to the first occurring embedded \newline in the buffer (if any) and Print to output only the first line of the buffer.

*

*Otherwise, sed prints a not-blank buffer entirely.

*Either way, sed then Deletes up to the first occurring \newline in the buffer before cycling back to the top of the script should any remain.

*

*If a buffer is not emptied here, then at the top of the script - after the first line is removed - the initial test will prove true for the quote substitution just performed, and so sed will skip the majority of its edit script directly to the :Del label for each iteration of the del state until the buffer is emptied entirely.

And so sed mostly can do the fancy stuff you asked about. sed's streaming nature is not excepted here, and so it writes output like:
acpitz_virtual_0 \
acpitz_virtual_0_Adapter__Virtual_device \
acpitz_virtual_0_Adapter__Virtual_device_temp1 \
'acpitz-virtual-0
Adapter: Virtual device
temp1:        +41.0°C  (crit = +95.0°C)
' \
'Adapter: Virtual device
temp1:        +41.0°C  (crit = +95.0°C)
' \
'temp1:        +41.0°C  (crit = +95.0°C)' \
'' \
coretemp_isa_0000 \
coretemp_isa_0000_Adapter__ISA_adapter \
coretemp_isa_0000_Adapter__ISA_adapter_Core_0 \
coretemp_isa_0000_Adapter__ISA_adapter_Core_1 \
'coretemp-isa-0000
Adapter: ISA adapter
Core 0:       +36.0°C  (high = +90.0°C, crit = +90.0°C)
Core 1:       +36.0°C  (high = +90.0°C, crit = +90.0°C)
' \
'Adapter: ISA adapter
Core 0:       +36.0°C  (high = +90.0°C, crit = +90.0°C)
Core 1:       +36.0°C  (high = +90.0°C, crit = +90.0°C)
' \
'Core 0:       +36.0°C  (high = +90.0°C, crit = +90.0°C)' \
'Core 1:       +36.0°C  (high = +90.0°C, crit = +90.0°C)' \
'' \
###backslashes for set or for assignment

... in a stack per paragraph: names first, then values. You can loop over it, and each paragraph will end in a null argument.
There's also a lot more validation going on here, and so there should be no danger of invalid shell names or unquoted output values of any kind whatever its input.
This function works with your input:
ineval(){
        . /dev/fd/0
        for     v
        do      case    ${#v}:${s:-$v}  in
                (0*)    until   [ 0 -eq "${#1}" ] &&
                        s= &&   ${1+"shift"}
                        do      shift;  done;;
                (*:*[-:]*) eval "s=- $1=\$v;shift"
        esac;   done
}       <<SET
        set ''  $(    sed -netDel -e'/./{H;g;s///'              \
                      -e'# grow'  -e's/[0-9]*:  .*\n[^:0-9]*//' \
                      -e'# loop'  -e's/:  .*//'                 \
                      -e'# ends'  -e's/[^_[:alnum:]]/_/g;}'     \
                      -e'# here'  -e's/\(.\)\(.*\)/& \\/p'      \
                      -e$\!t -ex  -e's//\2\1. \\/'              \
                      -e'# swap'  -e"s/'/'"'\\&&/g;tDel'        \
                      -ed\;:Del   -e"s/\(.*\). /'\1' /"         \
                      -e'# loop'  -e'/^[^:]*:  /!{p;D;}'        \
                      -e'# ends'  -e"s/\n/' \\\&/;P;D"     "$@" )
SET

Here is a set -x of your input:
(set -x; ineval /tmp/sens)

+ sed -netDel -e/./{H;g;s/// -e# grow -es/[0-9]*:  .*\n[^:0-9]*// -e# loop -es/:  .*// -e# ends -es/[^_[:alnum:]]/_/g;} -e# here -es/\(.\)\(.*\)/& \\/p -e$!t -ex -es//\2\1. \\/ -e# swap -es/'/'\\&&/g;tDel -ed;:Del -es/\(.*\). /'\1' / -e# loop -e/^[^:]*:  /!{p;D;} -e# ends -es/\n/' \\&/;P;D /tmp/sens
+ . /dev/fd/0
+ set  acpitz_virtual_0 acpitz_virtual_0_Adapter__Virtual_device acpitz_virtual_0_Adapter__Virtual_device_temp1 acpitz-virtual-0
Adapter: Virtual device
temp1:        +41.0°C  (crit = +95.0°C)
 Adapter: Virtual device
temp1:        +41.0°C  (crit = +95.0°C)
 temp1:        +41.0°C  (crit = +95.0°C)  coretemp_isa_0000 coretemp_isa_0000_Adapter__ISA_adapter coretemp_isa_0000_Adapter__ISA_adapter_Core_0 coretemp_isa_0000_Adapter__ISA_adapter_Core_1 coretemp-isa-0000
Adapter: ISA adapter
Core 0:       +36.0°C  (high = +90.0°C, crit = +90.0°C)
Core 1:       +36.0°C  (high = +90.0°C, crit = +90.0°C)
 Adapter: ISA adapter
Core 0:       +36.0°C  (high = +90.0°C, crit = +90.0°C)
Core 1:       +36.0°C  (high = +90.0°C, crit = +90.0°C)
 Core 0:       +36.0°C  (high = +90.0°C, crit = +90.0°C) Core 1:       +36.0°C  (high = +90.0°C, crit = +90.0°C)
+ [ 0 -eq 0 ]
+ s=
+ shift
+ eval s=- acpitz_virtual_0=$v;shift
+ s=- acpitz_virtual_0=acpitz-virtual-0
Adapter: Virtual device
temp1:        +41.0°C  (crit = +95.0°C)

+ shift
+ eval s=- acpitz_virtual_0_Adapter__Virtual_device=$v;shift
+ s=- acpitz_virtual_0_Adapter__Virtual_device=Adapter: Virtual device
temp1:        +41.0°C  (crit = +95.0°C)

+ shift
+ eval s=- acpitz_virtual_0_Adapter__Virtual_device_temp1=$v;shift
+ s=- acpitz_virtual_0_Adapter__Virtual_device_temp1=temp1:        +41.0°C  (crit = +95.0°C)
+ shift
+ [ 0 -eq 83 ]
+ shift
+ [ 0 -eq 66 ]
+ shift
+ [ 0 -eq 41 ]
+ shift
+ [ 0 -eq 0 ]
+ s=
+ shift
+ eval s=- coretemp_isa_0000=$v;shift
+ s=- coretemp_isa_0000=coretemp-isa-0000
Adapter: ISA adapter
Core 0:       +36.0°C  (high = +90.0°C, crit = +90.0°C)
Core 1:       +36.0°C  (high = +90.0°C, crit = +90.0°C)

+ shift
+ eval s=- coretemp_isa_0000_Adapter__ISA_adapter=$v;shift
+ s=- coretemp_isa_0000_Adapter__ISA_adapter=Adapter: ISA adapter
Core 0:       +36.0°C  (high = +90.0°C, crit = +90.0°C)
Core 1:       +36.0°C  (high = +90.0°C, crit = +90.0°C)

+ shift
+ eval s=- coretemp_isa_0000_Adapter__ISA_adapter_Core_0=$v;shift
+ s=- coretemp_isa_0000_Adapter__ISA_adapter_Core_0=Core 0:       +36.0°C  (high = +90.0°C, crit = +90.0°C)
+ shift
+ eval s=- coretemp_isa_0000_Adapter__ISA_adapter_Core_1=$v;shift
+ s=- coretemp_isa_0000_Adapter__ISA_adapter_Core_1=Core 1:       +36.0°C  (high = +90.0°C, crit = +90.0°C)
+ shift
+ [ 0 -eq 157 ]
+ shift
+ [ 0 -eq 139 ]
+ shift
+ [ 0 -eq 58 ]
+ shift
+ [ 0 -eq 58 ]
+ shift
+ [ 0 -eq 0 ]
+ s=
+ shift

A: I'd do something like:
eval "$(#"
  perl -MString::ShellQuote -00 -lne '
    if (/^(.+)\n(.+)/) {
      ($v1, $v2, $rest) = ("sensors_$1", "$2", $'\'');
      # $v1, $v2 contain the first 2 lines, $rest the rest

      s/\W/_/g for $v1, $v2;
      # replace non-word characters with _ in the variables

      print "$v1=" . shell_quote("$1\n$2$rest");
      print "${v1}__$v2=" . shell_quote("$2$rest");
      # output the variable definition taking care to quote the value

      while ($rest =~ /^(.*?):\s*(.*)/gm) {
        # process the "foo: bar" lines in the rest
        ($v3,$val) = ("$1", $2);
        $v3 =~ s/\W/_/g;
        print "${v1}__${v2}__$v3=" . shell_quote($val)
      }
    }' < that-file)"

-00 for paragraph mode. -l to remove the paragraph separator off the end of the records and for print to add one on output.
-n process the input one record at a time.
On your sample, that perl command will output the following shell code:
sensors_acpitz_virtual_0='acpitz-virtual-0
Adapter: Virtual device
temp1:        +41.0°C  (crit = +95.0°C)'

sensors_acpitz_virtual_0__Adapter__Virtual_device='Adapter: Virtual device
temp1:        +41.0°C  (crit = +95.0°C)'

sensors_acpitz_virtual_0__Adapter__Virtual_device__temp1='+41.0°C  (crit = +95.0°C)'

sensors_coretemp_isa_0000='coretemp-isa-0000
Adapter: ISA adapter
Core 0:       +36.0°C  (high = +90.0°C, crit = +90.0°C)
Core 1:       +36.0°C  (high = +90.0°C, crit = +90.0°C)'

sensors_coretemp_isa_0000__Adapter__ISA_adapter='Adapter: ISA adapter
Core 0:       +36.0°C  (high = +90.0°C, crit = +90.0°C)
Core 1:       +36.0°C  (high = +90.0°C, crit = +90.0°C)'

sensors_coretemp_isa_0000__Adapter__ISA_adapter__Core_0='+36.0°C  (high = +90.0°C, crit = +90.0°C)'

sensors_coretemp_isa_0000__Adapter__ISA_adapter__Core_1='+36.0°C  (high = +90.0°C, crit = +90.0°C)'

And we use eval "$(that-perl-command)" to tell the shell to evaluate that code output by that command.

A: Perl has a special paragrph mode in which it defines "lines" as paragraphs. This means that a line is defined by two consecutive \n, not one. From man perlrun:
   -0[octal/hexadecimal]
        specifies the input record separator ($/) as an octal or
        hexadecimal number. [. . .]

    The special value 00 will cause Perl to slurp files in paragraph
    mode.

You can therefore write a perl script that prints your variables:
$ perl -00lne '/.*/; $v=$&; $v=~s/-/_/g; print "$v=\"$_\""' file
acpitz_virtual_0="acpitz-virtual-0
Adapter: Virtual device
temp1:        +41.0°C  (crit = +95.0°C)"

coretemp_isa_0000="coretemp-isa-0000
Adapter: ISA adapter
Core 0:       +36.0°C  (high = +90.0°C, crit = +90.0°C)
Core 1:       +36.0°C  (high = +90.0°C, crit = +90.0°C)"

And then use eval to tell your shell to read them:
$ eval "$(perl -00lne '/.*/; $v=$&; $v=~s/-/_/g; print "$v=\"$_\""' file )"
$ echo "$coretemp_isa_0000"
coretemp-isa-0000
Adapter: ISA adapter
Core 0:       +36.0°C  (high = +90.0°C, crit = +90.0°C)
Core 1:       +36.0°C  (high = +90.0°C, crit = +90.0°C)

The Perl script might need some explaining. Here's the same thing as a commented script:
## The . doesn't match newlines by default, so this is just a
## quick way of getting the text before the first \n, this will be
## you variable's name.
/.*/;
## $& is whatever was matched my the last match (//) operator. We set
## $v to that.
$v=$&;
## Bash doesn't like dashes in variable names, this will replace
## them with underscores.
$v=~s/-/_/g;
## Print the variable name and its value ($foo="bar")
print "$v=\"$_\""


text:
Q: Don't understand a libGDX error I started a new libGDX project, copied all the relevant code from the previous project, but am now getting a strange error I dont understand:
Exception in thread "main" java.lang.NoClassDefFoundError: com/badlogic/gdx/jnigen/NativeCodeGenerator
    at com.badlogic.gdx.utils.GdxBuild.main(GdxBuild.java:34)
Caused by: java.lang.ClassNotFoundException: com.badlogic.gdx.jnigen.NativeCodeGenerator
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 1 more

I can't even render a simple window.
Hopefully someone can explain to me, what this error means.
Cheers, Joshflux


text:
Q: Create a dictionary from CSV file I need to create a dictionary from a csv file. CSV would look something like this:
hostnames,device_platform,device_role
co-agg-r1,cisco_ios,co-agg-r
co-edg-fw,cisco_asa,co-edg-fw
co-acc-sw,cisco_ios,co-acc-sw
co-acc-rsw,broadcom_icos,co-acc-rsw

I need the dictionary to be created so that the hostnames are the keys. Something like this:
devices_dict = {
 'co-agg-r1': { 'device_platform': 'cisco_ios', 'device_role': 'co-agg-r'},
 'co-edg-fw': { 'device_platform': 'cisco_asa', 'device_role': 'co-edg-fw'},
 'co-acc-sw1': { 'device_platform': 'cisco_ios', 'device_role': 'co-acc-sw'},
 'co-acc-rsw1': { 'device_platform': 'broadcom_icos', 'device_role': 'co-acc-rsw'}
}

What's the easiest way to do this?

A: import pandas as pd
df = pd.read_csv("/tmp/data.csv")  # data you provided
df.set_index("hostnames").T.to_dict()  # or df.set_index("hostnames").to_dict("index")

yields
{'co-agg-r1': {'device_platform': 'cisco_ios', 'device_role': 'co-agg-r'},
 'co-edg-fw': {'device_platform': 'cisco_asa', 'device_role': 'co-edg-fw'},
 'co-acc-sw': {'device_platform': 'cisco_ios', 'device_role': 'co-acc-sw'},
 'co-acc-rsw': {'device_platform': 'broadcom_icos',
  'device_role': 'co-acc-rsw'}}

A: Alternative without Pandas (nothing wrong with Pandas):
import csv

with open("file.csv", "r") as file:
    reader = csv.reader(file)
    keys = next(reader)[1:]
    devices_dict = {key: dict(zip(keys, values)) for key, *values in reader}

Result:
{'co-agg-r1': {'device_platform': 'cisco_ios', 'device_role': 'co-agg-r'},
 'co-edg-fw': {'device_platform': 'cisco_asa', 'device_role': 'co-edg-fw'},
 'co-acc-sw': {'device_platform': 'cisco_ios', 'device_role': 'co-acc-sw'},
 'co-acc-rsw': {'device_platform': 'broadcom_icos', 'device_role': 'co-acc-rsw'}}


text:
Q: Apply function to pandas Series with argument (which varies for every element) I have a pandas Series and a function that I want to apply to each element of the Series. The function have an additional argument too. So far so good: for example
python pandas: apply a function with arguments to a series. Update
What about if the argument varies by itself running over a given list?
I had to face this problem in my code and I have found a straightforward solution but it is quite specific and (even worse) do not use the apply method.
Here is a toy model code:
a=pd.DataFrame({'x'=[1,2]})
t=[10,20]

I want to multiply elements in a['x'] by elements in t. Here the function is quite simple and len(t) matches with len(a['x'].index) so I could just do:
a['t']=t
a['x*t']=a['x']*a['t']

But what about if the function is more elaborate or the two lengths do not match?
What I would like is a command line like:
a['x'].apply(lambda x,y: x*y, arg=t)

The point is that this specific line exits with an error because the arg variable in that case will accept only a tuple of len=1. I do not see any 'place' to put the various element of t.

A: What you're looking for is similar to what R calls "recycling", where operations on arrays of unequal length loops through the smaller array over and over as many times as needed to match the length of the longer array.
I'm not aware of any simple, built-in way to do this with numpy or pandas.  What you can do is use np.tile to repeat your smaller array.  Something like:
a.x*np.tile(t, len(a)/len(t))

This will only work if the longer array's length is a simple multiple of the shorter one's.
The behavior you want is somewhat unusual.  Depending on what you're doing, there may be a better way to handle it.  Relying on the values to match up in the desired way just by repetition is a little fragile.  If you have some way to match up the values in each array that you want to multiply, you could use the .map method of Series to select the right "other value" to multiply each element of your Series with.


text:
Q: AsyncTask Delays Program Flow / Screen Freezes I've got a simple login screen. If you click "Login", a progress bar should appear while we wait for the AsyncTask in the background to check the login credentials.
If I run the code without the AsyncTask in the background, my progress bar appears immediately. However, if I use the AsyncTask, which I set up after I make my progress bar appear, the app freezes at the exact moment I click on "Login". Then it waits until the AsyncTask has got its result (get() command) and only then it unfreezes, making my progress bar useless.
Is this a commonly known issue? How do you solve it?
This is how where I set up the AsyncTask, after I show the progress bar.
    showProgress(true, "Logging in ...");
    mAuthTask = new InternetConnection();
    String arguments = "email="+mEmail+"&pwd="+mPassword;
    boolean k = mAuthTask.makeConnection("ADDRESS", arguments, getBaseContext());
    String f = mAuthTask.getResult();

And this is my AsyncTask. downloadUrl() sets up an HttpURLConnection. This works, I tested it.
    private DownloadData data = new DownloadData();
    public boolean makeConnection(String url, String arguments, Context context) {
        if(isWifi(context) || isMobile(context)) {
            argsString = arguments;
            data.execute(url);
            return true;
        } else {
            return false; //No network available.
        }
    }

    public String getResult() {
        try {
            return data.get();
        } catch (InterruptedException e) {
            return "Error while retrieving data.";
        } catch (ExecutionException e) {
            return "Error while retrieving data.";
        }
    }

    private class DownloadData extends AsyncTask<String, Void, String> {

        @Override
            protected String doInBackground(String... url) {
                try {
                    return downloadUrl(url[0]);
                } catch (IOException e) {
                    return "Unable to retrieve data.";
            }
    }

A: You should not call get() it blocks the ui waiting for the result to be returned making asynctask no more asynchronous.
You have
 private DownloadData data = new DownloadData();

and you have
 data.get(); // this why it freezes

and
  private class DownloadData extends AsyncTask<String, Void, String>

http://developer.android.com/reference/android/os/AsyncTask.html#get()
You only need
  data.execute(url);

And if your asynctask is an inner class of activity class you can return result in doInbackground and update ui in onPostExecute. If not you can use interface as a callback to the activity to return the result.

A: your issue is related to the fact that you are calling getResult from the UI Thread. getResult calls data.get() that is a blocking operation. That's why you are getting a freeze. Your UI Thread is waiting for get() to complete and it is unable to draw everything else

A: Do it like:
  @Override
    protected void onPreExecute() {
    Asycdialog.setMessage("Working");
    Asycdialog.getWindow().setGravity(Gravity.CENTER_VERTICAL);
    Asycdialog.getWindow().setGravity(Gravity.CENTER_HORIZONTAL);
    Asycdialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
    Asycdialog.setCancelable(false);
    //Dialog Show
    Asycdialog.show();
    super.onPreExecute();

And then in onPostExecute:
protected void onPostExecute(String result) {
            // hide the dialog

            Asycdialog.dismiss();
            super.onPostExecute(result);
        }

To use the same Async task from Different classes:
    class MainActivity{
    new MyTask().execute();
    }

    class DifferentActivity {
      new MyTask().execute();//a new instance
    }

    class MyTask extends AsyncTask{
       public MyTask(Context context){
       }//Pass in context.
    }

Pass the context to the constructor, if you want a consistent Progress dialog.
TO publish the progress from doInBackground you can use the following:
publishProgress(progress);
Asycdialog.setMax(lines);
Asycdialog.incrementProgressBy(1);

Where progress is a string, lines are the max number of items.


text:
Q: Smoothing out lines created by raster layers I have a line layer that has been formed from a raster layer (It was a skeletonised raster layer). It now has a lot of unwanted vertices and needs smoothing out before further analysis. I have tried various methods including:

*

*Simplify (Geometry Tools)

*Line Simplification and line smoothing (SAGA vector line tools)

*v.clean and v.generalizer (GRASS)

*Smooth (Vector Geometry)

*Generalizer (Generalizer3 Plugin)

Where I can I have tried the Chaiken's Algorithm. I have also tried various tolerances for the functions that didn't just freeze/fail outright. When I run all of these methods they all return the same line with no change. I'm not sure if I am using these wrong. So any advice on them would also be useful.
Here is an example of the line. Between vertices in the line is about 1m. Ideally this would be just one curved line.

However the whole layer is much larger. It has a 15km radius as you can see below. So these small lines could really do with smoothing out.

Coordinate Reference System: EPSG:27700 - OSGB 1936 / British National Grid

A: Geometry Generator
If you are just looking for a dynamic, visual smoothing (without altering the underlying geometries), the easiest way is Geometry Generator, one of QGIS' powerful features.

*

*Double click on the layer's name

*Select Symbology

*Under Symbol Layer Type choose Geometry Generator

*In the function area, input smooth($geometry,xxx) (use a real value instead of xxx) and click Apply
This trick is also useful because you can save the symbology as style and re-use it for any number of layers.

A: Line smoothing from the SAGA toolbox does a pretty good job on default settings.

A: I have also a few times needed to straighten lines and found no tool which did the trick.
So I wrote a python script which removes every nth vertice. This will create a new memory line layer:
lyr = iface.activeLayer() #Click/highlight the layer in layer tree

#Create an empty line layer
vl = QgsVectorLayer("LineString?crs={}&index=yes".format(lyr.crs().authid()), "simplified_line", "memory")
provider = vl.dataProvider()

for feature in lyr.getFeatures(): #For each line in the jagged line layer
    geom = feature.geometry() #Fetch the geometry
    newline = QgsMultiLineString() #Create a new empty multilinestring
    for subline in geom.parts(): #For each subline in the current line
        vertices = [p for p in subline.vertices()] #List all vertices
        vertices_thinned = [p for e, p in enumerate(vertices) if e%2==0] #Remove every other vertice. You can change 2 to 3 or higher to remove more vertices
        newsubline = QgsLineString(vertices_thinned) #Create a new linestring from the thinned lines
        newline.addGeometry(newsubline) #Add this linestring to the empty multilinestring
    f = QgsFeature() #Create a new feature
    f.setGeometry(newline) #Set the geometry to the new multilinestring
    provider.addFeature(f) #Add the feature

QgsProject.instance().addMapLayer(vl) #Add the new layer to the map

A: As stated in one of the comments posted on my question, the problem was each straight line was an individual line and therefore couldn't be smoothed by any of the functions I had tried.

*

*I used Geometric Attributes 'Merge Linestrings' tool. This took over 12 hours.

*Then, the Geometry tool 'Simplify', which worked very quickly.

(Note: I found the Geoprocessing tool 'Dissolve' didn't work as I lost too much information for further analysis this way.)


text:
Q: Multiple consecutive \par's equivalent to just one? I think the answer to this question should be positive but I just couldn't find it answered elsewhere: Are multiple consecutive \par's the same as a single \par? For example, is \par\par the same as just \par?
More generally, since an empty line is equivalent to a \par: Is any finite sequence of consecutive \par's and empty lines (or any mixture of them) equivalent to a single \par (or a single empty line)?
I know this question might seem trivial, but I do want to know it for defining macros. Any help appreciated!

A: The quoted text (in egreg's answer) is about the tex primitive, but a blank line really is a \par token which can be redefined at any time (and is quite often redefined in latex). So whether consecutive \par are equivalent to one depends on the definition. At the start of any list (or list defined environment such as center) for example you can have 1 or 2 or 1000 \par but don't push your luck further than that:
\documentclass{article}

\begin{document}

\def\cpar{\par\par\par\par\par\par\par\par\par\par
\par\par\par\par\par\par\par\par\par\par
\par\par\par\par\par\par\par\par\par\par
\par\par\par\par\par\par\par\par\par\par
\par\par\par\par\par\par\par\par\par\par
\par\par\par\par\par\par\par\par\par\par
\par\par\par\par\par\par\par\par\par\par
\par\par\par\par\par\par\par\par\par\par
\par\par\par\par\par\par\par\par\par\par
\par\par\par\par\par\par\par\par\par\par}

\begin{center}
\par
\end{center}

\begin{center}
\cpar\cpar\cpar\cpar\cpar\cpar\cpar\cpar\cpar\cpar
\end{center}

\begin{center}
\cpar\cpar\cpar\cpar\cpar\cpar\cpar\cpar\cpar\cpar
\par% straw camel back....
\end{center}

\end{document}

A: After \par, TeX is in vertical mode. Then page 283 of the TeXbook, second bullet, explains that

The primitive \par command has no effect when TeX is in vertical mode,
  except that the page builder is exercised in case something is present
  on the contribution list, and the paragraph shape parameters are cleared.

"Exercising the page builder" is explained on page 281:

TeX periodically takes material that has been put on the main vertical list and moves it from the "contribution list" to the "current page." At such times the output routine might be invoked. We shall say that TeX exercises the page builder whenever it tries to empty the current contribution list. The concept of contribution list exists only in the outermost vertical mode, so nothing happens when TeX exercises the page builder in internal vertical mode.

The paragraph shape parameters are any value given to \parshape, \hangindent or \hangafter.
So no, you don't have to worry much about having consecutive \par tokens unless you have redefined \par. Two consecutive blank lines count for two \par tokens, as the following Plain TeX example shows:
\def\par{X\endgraf}
a

b
\bye

that produces


text:
Q: how do I add files already stored on s3 to carrierwave backed by same datastore? I already have files in my s3, which were uploaded via FTP, and I'd just like to attach them to my models, which allow upload via CarrierWave, if I'm using the same bucket to store the files I upload via CarrierWave and the ones I upload via FTP, is there a way to just assign the s3 key for the file to the (new) associated record (via a model) where the file itself is handled via CarrierWave's attachment strategy?

A: Assuming you have the thumbnails already created, and can store the files in the correct directory on S3, you could simply:
@user.update_column(:image, "your-image-name.png")

This will not execute any callbacks, and carrierwave will assume all processing has already been completed.
That's a lot of assumptions though, so this would likely not work for you in reality.


text:
Q: Assignment with OR operator So I came across this code when I was reading source code in Github.
addr2int = ( (uint32_t)paddr[2] ) | ( (uint32_t)paddr[3] << 8 ) | ( (uint32_t)paddr[4] << 16 ) | ( (uint32_t)paddr[5] << 24 )

Can someone explain to me what happens here?
As far as I can tell this is an assignment but I don't understand why there are | operators, or whether this is an multiple assignment.

A:
(uint32_t)paddr[2] ) | ( (uint32_t)paddr[3] << 8 ) | (
  (uint32_t)paddr[4] << 16 ) | ( (uint32_t)paddr[5] << 24 )

*

*It's basically bitwise OR (operator |) of four integers.

*Secondly, consider this: (uint32_t)paddr[2]. Here we tell the compiler to cast whatever is inside paddr[2] into an unsigned long int, where uint32_t is c++11 std. Nevertheless (uint32_t)variable is a C-style casting. In modern C++11, you can write it as static_cast<uint32_t>paddr[2].

*Thirdly, variable_x << variable_y is a bitwise left shift. Read more about it here with an example.


text:
Q: Uploading images with ckeditor + carrierwave I am trying to add some pictures to the text field of my articles with this gem ckeditor.
I first added ckeditor to pretty things up and it works well. After that I added carrierwave as explained on the ckeditor page.
Now everything is working fine except the file upload. As soon as I try to send an image to the server it gives me following error message:
Data Failed to manipulate with MiniMagick, maybe it is not an image? Original Error: MiniMagick::Invalid

The files that I tried to upload are getting saved in my public/upload/tmp folder though what I find really odd. But still I cant manage to see it in my text field. After uploading the image the text field wont change at all. So I tried to use a url in the first tab of the upload screen that point to the right picture but I cannot figure out how to set up the right url so that I only get a blank image frame with an X.
When I try to use an image via a valid link in the second tab I get a message that the url in the first tab is missing again.
So in the end I am really confused on how to load up some images there. Maybe I am just way to stupid but I would really appreciate some help of you guys.

A: You may give ckeditor-imgur a try, if you don't plan to manage images by yourself.
The gem help you upload your images to imgur in easy way and painless.
https://github.com/yfxie/ckeditor-imgur

A: I did not have the exact same error, but something similar happened because I did not have imagemagick installed on the server machine - installing it with brew install imagemagick fixed it for me (this is for a mac - other environments may require a different command). minimagick requires imagemagick, but imagemagick is not a gem, so it needs to be installed on the machine.


text:
Q: Where to put Scudo allocator __scudo_default_options callback? From Scudo page:
Some parameters of the allocator can be defined on a per-process basis through several ways:

Statically: Define a __scudo_default_options function in the program that returns the options string to be parsed. This function must have the following prototype: extern "C" const char *__scudo_default_options().
Dynamically: Use the environment variable SCUDO_OPTIONS containing the options string to be parsed. Options defined this way override any definition made through __scudo_default_options.

Im fairly new to Android, could someone help me understand where to put functions like __scudo_default_options in cpp code, I have MainActivity.cpp and MidiManager.cpp

A: The function can be located anywhere within the application, as long as it's discoverable by the linker. Putting it in the vicinity of your main compilation unit is probably better.
You want to make sure that the symbol has a public visibility.
You can refer to the example in the tests here:
https://github.com/llvm/llvm-project/blob/main/compiler-rt/lib/scudo/standalone/tests/scudo_unit_test_main.cpp#L23
eg. in MainActivity.cpp, something to the extent of:
extern "C" __attribute__((visibility("default"))) const char *
__scudo_default_options() {
  return "quarantine_size_kb=256:thread_local_quarantine_size_kb=128:"
         "quarantine_max_chunk_size=512";
}


text:
Q: App rejected because of screenshot, what should I do now? I've always used my app's onboarding pages for screenshots for the previous versions and nothing was wrong. But this time apple rejected it and said the issue was:

Guideline 2.3.3 - Performance - Accurate Metadata
We noticed that your screenshots do not sufficiently reflect your app in use.
Specifically, your screenshots do not display the actual app in use.
Next Steps
To resolve this issue, please revise your screenshots to ensure that they accurately reflect the app in use on the supported devices. For iPhone, you need a set of 5.5-inch display screenshots and for iPad, you need a set for 12.9-inch display. This set will be scaled appropriately down to other device sizes when viewed on the App Store in each territory.
Note that 6.5-inch display assets for iPhone XS Max are optional, and can scale down to iPhone XR, iPhone XS, and iPhone X. Screenshots that include features like rounded corners or sensor housing should only be used for the 6.5-inch or 5.8-inch display.
Resources
For resources on creating great screenshots for the App Store, you may want to review the App Store Product Page information available on the Apple developer portal.
Please ensure you have made any screenshot modifications using Media Manager. You should confirm your app looks and behaves identically in all languages and on all supported devices. Learn how to use Media Manager to add custom screenshots for each display size and localization.
Please see attached screenshots for details.
Since your App Store Connect status is Metadata Rejected, we do NOT require a new binary. To revise the metadata, visit App Store Connect to select your app and revise the desired metadata values. Once you've completed all changes, reply to this message in Resolution Center and we will continue the review.

What is my best option to get my app approved? My app doesn't support iPad but they seem to be demanding for iPad screenshots too.

A: I have faced same rejection from apple.
In my case I was added so many pages/screen in application but not added screenshot in apple store.
So I added all other screenshot then my application got approved.
If you don't want your application available for ipad then don't add screenshot in ipad or you can do as follow :
In XCode Target -> General -> Deployment Info -> Devices should be set to iPhone.


text:
Q: Sum all the numbers in a list of dotted pairs I'm new in Scheme and I have a lot of problems to understand it.
If I have this list '((a . 1) (c . 3) (b . 2)), I will need to get the number 6.
I know how to do it with numbers instead of dotted pairs (get it from this SO answer):
(define (sum elemList)
  (if
    (null? elemList)
    0
    (+ (car elemList) (sum (cdr elemList)))
  )
)

But, how can I get the sum of all numbers in a dotted pairs list?

A: This is how you can do it:
(define (sum elemList)
  (if (null? elemList)
      0
      (+ (cdr (car elemList)) (sum (cdr elemList)))))

Simply take the cdr of the car of each element. With the car part you extract the first pair of the list, and with the cdr you retrieve the second element of that pair. We can even simplify it a bit:
(cdr (car elemList))

Is equivalent to this:
(cdar elemList)

But in Scheme we prefer to use built-in functions to compose solutions, so an even more idiomatic way to write it would be:
(define (sum elemList)
  (apply + (map cdr elemList)))

We take the cdr of each pair in the list, and then we add them all together. Short, nice and simple. Any of the above solutions will work as expected:
(sum '((a . 1) (c . 3) (b . 2)))
=> 6


text:
Q: TCP + UDP Socket in C using Daytime Protocol My lecturer gave us his implemented Daytime Protocol in C using TCP and we have to extend it to UDP. It should only accept UDP or TCP using cmd flags -u / -t. I have done everything so far, but the sendto() function returns
"Server started, listening on 0.0.0.0:13 ...
Received message from 127.0.0.1:35585:
Successful incoming connection from 127.0.0.1:35585.
Error in function sending_datetime() line 319: ERROR IN SENDTO(): Socket operation on non-socket
"
I have tried everything but still cant fix it, please help me and thank you :) (iam a beginner)
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <getopt.h>
#include <assert.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netdb.h>
#include <netinet/in.h>
#include <time.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <arpa/inet.h>

#define TCP         1
#define UDP         2

#define PROTO       TCP
#define PORT        13
#define BACKLOG     256

#define MSGLENGTH   27

#define XSTR(s)     STR(s)
#define STR(s)      #s

#define ERROR(str)  (fprintf(stderr, "Error in function %s() line %d: ", __FUNCTION__, __LINE__),\
                    perror(str), kill(0, SIGTERM), exit(EXIT_FAILURE))

#define LOG(...)    (printf(__VA_ARGS__), fflush(stdout))

volatile sig_atomic_t   active = 1;

/*
 * struct srvcfg is used to manage all necessary settings for a daytime service
 */
struct srvcfg {
    int                 proto;
    unsigned short      port;
    struct in_addr      server_ip;
    struct sockaddr_in  server_addr;
    int                 sockfd;
};
/*
 * Declaration of functions
 */
void exiting(int sig);
void set_signal_handler(void);
void print_usage(void);
void parse_arguments(int argc, char *argv[], struct srvcfg *cfg);
void start_server(struct srvcfg *cfg);
int create_socket(int type, struct sockaddr_in *addr);
int sending_datetime(int fd, int port);
void destroy_server(struct srvcfg *cfg);

int main(int argc, char *argv[]) {

    struct srvcfg *cfg;
    struct sockaddr_in client;
    int client_len = sizeof(struct sockaddr_in);
    int fd;

    if ((cfg = malloc(sizeof(struct srvcfg))) == NULL)
        ERROR("Error allocating memory");

    set_signal_handler();
    parse_arguments(argc, argv, cfg);
    start_server(cfg);

    while (active) {

        // Sockets are set to non-blocking, therefor errno needs to be checked
        // for EWOULDBLOCK and/or EAGAIN
        if (cfg->proto == TCP)
        {
            if (((fd = accept(cfg->sockfd, (struct sockaddr *)&client, &client_len)) == -1)
                && (errno != EWOULDBLOCK) && (errno != EAGAIN))
                ERROR("Error incoming connection");
        }
        else if (cfg->proto == UDP)
        {
            char buffer[MSGLENGTH];

            if ((fd = recvfrom(cfg->sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&client, &client_len)) == -1)
            {
                if (errno != EWOULDBLOCK && errno != EAGAIN)
                    ERROR("Error receiving message");
            }
            else
            {
                buffer[fd] = '\0';
                printf("Received message from %s:%d: %s\n",
                inet_ntoa(client.sin_addr), ntohs(client.sin_port), buffer);
            }
        }

        // Only if we get a socket descriptor from the accept() call,
        // we continue sending the daytime message
        if (fd != -1) {

            LOG("Successful incoming connection from %s:%d.\n", \
                inet_ntoa(client.sin_addr),ntohs(client.sin_port));

            if (cfg->proto == TCP)
            {
                if (sending_datetime(fd, TCP) == -1)
                    ERROR("Error sending datetime");
            }

            else if (cfg->proto == UDP)
            {
                if (sending_datetime(fd, UDP) == -1)
                    ERROR("Error sending datetime via UDP");
            }

            LOG("Successfully sent datetime to %s:%d.\n", \
                inet_ntoa(client.sin_addr),ntohs(client.sin_port));

            if (close(fd) == -1)
                ERROR("Error on closing socket");

            LOG("Successfully closing connection from %s:%d.\n", \
                inet_ntoa(client.sin_addr),ntohs(client.sin_port));
        }

    }

    destroy_server(cfg);

    free(cfg);

    exit(EXIT_SUCCESS);
}

 * Starting the daytime services by using create_socket() until the socket is in
 * listen state.
 */
void start_server(struct srvcfg *cfg)
{
    assert(cfg != NULL);

    bzero(&cfg->server_addr, sizeof(cfg->server_addr));
    cfg->server_addr.sin_family = AF_INET;
    cfg->server_addr.sin_port = htons(cfg->port);
    cfg->server_addr.sin_addr.s_addr = cfg->server_ip.s_addr;

    if (cfg->proto == TCP) {
        cfg->sockfd = create_socket(SOCK_STREAM, &cfg->server_addr);
        // We set the socket to non-blocking, which means an accept() call won't block
        // until a client connection request is received
        fcntl(cfg->sockfd, F_SETFL, fcntl(cfg->sockfd, F_GETFL, 0) | O_NONBLOCK);
    }

    else if (cfg->proto == UDP)
    {
        cfg->sockfd = create_socket(SOCK_DGRAM, &cfg->server_addr);           // UDP Erweiterung
    }

    LOG("Server started, listening on %s:%d ...\n", inet_ntoa(cfg->server_ip), cfg->port);
}

/*
 * Creating a socket in listen state for the daytime service.
 */
int create_socket(int type, struct sockaddr_in *addr)
{
    assert(type == SOCK_STREAM || type == SOCK_DGRAM);
    assert(addr != NULL);

    int sockfd;
    int reuseaddr = 1;

    if ((sockfd = socket(PF_INET, type, 0)) == -1)
        ERROR("Error creating socket");

    if ((setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR,
                    &reuseaddr, sizeof(reuseaddr))) == -1)
        ERROR("Error setting socket options");

    if ((bind(sockfd, (struct sockaddr *)addr, sizeof(*addr))) == -1)
        ERROR("Error binding socket");

    if (type == SOCK_STREAM) {
        if ((listen(sockfd, BACKLOG)) == -1)
            ERROR("Error setting stream socket into listening mode");
    }

    return sockfd;
}

/*
 * Sending a daytime message to the client.
 */
int sending_datetime(int fd, int port)
{
    time_t curr_time;
    char buffer[MSGLENGTH];
    struct sockaddr_in client;
    int client_len = sizeof(client);

    /*
     * A daytime message from this server is 26 bytes long, including a closing \r\n.
     * Example: Thu Nov 26 11:29:54 2020\r\n
     */
    curr_time = time(NULL);
    snprintf(buffer, sizeof(buffer), "%.24s\r\n", ctime(&curr_time));

    if (port == TCP)
    {
        return write(fd, buffer, strlen(buffer));
    }

    else if (port == UDP)
    {
        int n;
        n = sendto(fd, buffer, strlen(buffer), 0, (struct sockaddr *)&client, client_len);
        if (n < 0)
        {
            ERROR("ERROR IN SENDTO()");   // <----  HERE !!!!***
        }
        else
            return n;

    }

        //sendto(fd, buffer, strlen(buffer), 0, (struct sockaddr *)&client, sizeof(client));

}

void destroy_server(struct srvcfg *cfg)
{
    assert(cfg != NULL);

    if ((close(cfg->sockfd)) == -1)
        ERROR("Error closing socket");
}

A: else if (cfg->proto == UDP)
        {
            char buffer[MSGLENGTH];

            if ((fd = recvfrom(cfg->sockfd, buffer, sizeof(buffer), 0, (struct sockaddr *)&client, &client_len)) == -1)
            {
                if (errno != EWOULDBLOCK && errno != EAGAIN)

From the man page:

Upon successful completion, recvfrom() shall return the length of the
message in bytes. If no messages are available to be received and the
peer has performed an orderly shutdown, recvfrom() shall return 0.
Otherwise, the function shall return -1 and set errno to indicate the
error.

recvfrom() doesn't return a file descriptor. It returns the length of the message in bytes.
A subsequent sendto() operation then tries to write to the return value of recvfrom(), which causes it to fail with EBADF:
The socket argument is not a valid file descriptor.

Fix:
You need to specify the socket descriptor the server is bound to instead of the return value of recvfrom().

The sendto() function shall send a message through a connection-mode
or connectionless-mode socket. If the socket is connectionless-mode,
the message shall be sent to the address specified by dest_addr.

Pass in the struct srvcfg to sending_daytime(), and replace fd with cfg->sock.
int sending_datetime(struct srvcfg *cfg, int fd, int port)
{
    time_t curr_time;
    char buffer[MSGLENGTH];
    struct sockaddr_in client;
    int client_len = sizeof(client);

    /*
     * A daytime message from this server is 26 bytes long, including a closing \r\n.
     * Example: Thu Nov 26 11:29:54 2020\r\n
     */
    curr_time = time(NULL);
    snprintf(buffer, sizeof(buffer), "%.24s\r\n", ctime(&curr_time));

    if (port == TCP)
    {
        return write(fd, buffer, strlen(buffer));
    }

    else if (port == UDP)
    {
        int n;
        n = sendto(cfg->sockfd, buffer, strlen(buffer), 0, (struct sockaddr *)&client, client_len);
        if (n < 0)
        {
            ERROR("ERROR IN SENDTO()");
        }
        else
            return n;

    }
}

NB that time() and ctime() can fail. Pedantic code must check their return values.


text:
Q: SQLite database not refreshing in iPhone simulator So I got SQLite database working for my app. It loads text values from database, copies it to the array and displays it in Table View.
The first time I got it going i had the values Tuesday, Thursday, Saturday displaying. Then I modified the database using SQLite Manager add-on for firefox (I also used it to create it) by adding new values. However, the new values are not displaying, and even if I delete values like Saturday, the same old "Tuesday, Thursday, Saturday" keeps reappearing. I'm baffled.
Notes:

*

*I tried restarting Xcode and even the computer lol.

*When I modify database in SQLite Manager, the update time on database file is refreshed in Xcode.

*My database management, just like in the tutorial, happens in AppDelegate.

*In appdelegate: (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions I have this code at beginning
routines = nil; // Reset array
database = nil; // not opened yet
selStmt = nil; // no compiled statement yet
updStmt = nil; // no compiled statement yet

I'm following this tutorial and modifying it on my needs:
http://technologyservants.com/index.php?option=com_content&view=article&id=46:shopping-list-an-iphone-sqlite-tutorial

A: You're probably copying the database from the app bundle into the documents directory if it doesn't already exist in the documents directory.
The next time you run your app (with a new db) you check that the db exists in the user's documents directory and then you're probably not copying it again. You're not comparing the versions of the db, you're just checking that a db with that name exists.
If you're in development still, an easy solution is to just clear reset the content and settings of the simulator, which will cause your app to copy the db again.

A: As Firoze stated (I only skimmed the tutorial so forgive me if I'm wrong) on the first load the database is copied from the bundle and into the documents directory. For each launch after that there is no need to copy the database out as it already exists.
If you are working on the simulator and want to change the data so it is reflected live while you work you need to open the database located at
/Users/<username>/Library/Application Support/iPhone Simulator/4.3.2/Applications/<app bundle identifier>/Documents/<database file>

The file may not be in that exact location but it gives you an idea of where to start looking around


text:
Q: Magento CMS Variables not rendering I have been searching and experimenting for days now on a solution for getting custom product attribute data into a static block. I decided to go ahead and use a call to a template file that defines the call to the products attribute.
The problem however, is that my Magento Community 1.7 installation doesnt render any variables, either within CMS pages, product attributes, or static blocks. I have seen everwhere that this is the way to do it. I put in something such as the following:
{{block type="core/template" template="/catalog/product/compatibility.phtml"}}

After saving, and making sure that HTML on the frontend is set to yes, I check to see if it worked. What I see is the exact code of the variable and not that it even tried to access the template file. I have even tried inserting stock variables (such as a widget or even just the store name) into a page/static block to see if they render but they dont NONE do.
Am I missing something? Is there something that needs to be enabled for variables to work at all on my site? Spent 4 solid days ripping my hair out already

A: Please forgive me if this is too simple, but are you making sure you click to hide/disable the WYSIWYG editor before pasting the code into the blocks?
If you paste the code directly into the WYSIWYG editpr it will encode the tag and stop it being parsed properly.
also, you don't need to leading slash in the template path:
{{block type="core/template" template="catalog/product/compatibility.phtml"}}