text:
Q: Resource not available in specific region I have a schedule that create a 5TB disk everyday but this time it throws an error like below:
The zone 'projects/abcd/zones/asia-southeast2-a' does not have enough
resources available to fulfill the request.  Try a different zone, or
try again later.

As far as I know, I still have enough quota to create this.
Any idea? Thanks

A: You can change the destination of your snapshots but this may involve some additional costs (for storing depending on the location) and network charges;

When you create a snapshot, you can specify a storage location. The
location of a snapshot affects its availability and can incur
networking costs when creating the snapshot or restoring it to a new
disk.

In some cases you may be limited to some locations if Organisation Policy requires that.
You may also move your vm to a different zone but it's not as easy as changing snapshots' zone.
Other than that you can't do much really. If you can't do any of the above then waiting for available resources is your only solution.
Here are some pointers on how to build a scalable solutions in GCP  and how to distribute your VM's across multiple zones to avoid possible outages. This documentation provides information about available CPU/GPU architectures in various zones which may also be helpful to you.


text:
Q: shell matching a pattern using a case-statement which is stored inside a variable I am trying to match a pattern with a case-statement where the pattern is stored inside a variable. Here is a minimal example:
PATTERN="foo|bar|baz|bla"

case "foo" in
    ${PATTERN})
        printf "matched\n"
        ;;
    *)
        printf "no match\n"
        ;;
esac

Unfortunately the "|" seems to be escaped (interestingly "*" or "?" are not). How do I get this to work, i.e. to match "foo"? I need to store the pattern in a variable because it is constructed dynamically. This needs to work on a POSIX compatible shell.

A: It is possible to match a sub-string in a string without spawning a sub-process (such as grep) using the only POSIX compliant methods of sh(1p), as defined in Section 2.6.2, Parameter Expansion.
Here is a convenience function:
# Note:
# Unlike a regular expression, the separator *must* enclose the pattern;
# and it could be a multi chars.

isin() {
    PATTERN=${2:?a pattern is required}
    SEP=${3:-|}
    [ -z "${PATTERN##*${SEP}${1}${SEP}*}" ]
}

Examples:
for needle in foo bar; do
    isin "$needle" "|hello|world|foo|" && echo "found: $needle"
done

# using ";" as separator
for needle in foo bar; do
    isin "$needle" ";hello;world;foo;" \; && echo "found: $needle"
done

# using the string "RS" as separator
for needle in foo bar; do
    isin "$needle" "RShelloRSworldRSfooRS" RS && echo "found: $needle"
done

You can mix this solution with the case statement if you want both of the worlds:
PATTERN="|foo bar|baz|bla|"

case "$needle" in
    xyz) echo "matched in a static part" ;;
    *)
        if [ -z "${PATTERN##*|${needle}|*}" ]; then
            echo "$needle matched $PATTERN"
        else
            echo "not found"
        fi
esac

Note
Sometimes it is good to remember you could do your whole script in awk(1p), which is also POSIX, but I believe this is for another answer.

A: This should work:
PATTERN="foo|bar|baz|bla"

shopt -s extglob

case "foo" in
    @($(echo $PATTERN)))
        printf "matched\n"
        ;;
    *)
        printf "no match\n"
        ;;
esac

A: Your pattern is in fact a list of patterns, and the separator | must be given literally. Your only option seems to be eval. However, try to avoid that if you can.

A: "You can't get there from here"
I love using case for pattern matching but in this situation you're running past the edge of what bourne shell is good for.
there are two hacks to solve this problem:
at the expense of a fork, you could use egrep
pattern="this|that|those"

if
  echo "foo" | egrep "$pattern"  > /dev/null 2>&1
then
  echo "found"
else
  echo "not found"
fi

You can also do this with only built-ins using a loop.  Depending on the situation, this may make your code run a billion times slower, so be sure you understand what's going on with the code.
pattern="this|that|those"

IFS="|" temp_pattern="$pattern"
echo=echo

for value in $temp_pattern
do
  case foo
  in
    "$list") echo "matched" ; echo=: ; break ;;
  esac
done
$echo not matched

This is clearly a horror show, an example of how shell scripts can quickly spin out of control if you try to make do anything even a little bit off the map..

A: Some versions of expr (e.g. GNU) allow pattern matching with alternation.
PATTERN="foo\|bar\|baz"
VALUE="bar"
expr "$VALUE" : "$PATTERN" && echo match || echo no match

Otherwise, I'd use a tool like awk:
awk -v value="foo" -v pattern="$PATTERN" '
    BEGIN {
        if (value ~ pattern) {
            exit 0
        } else {
            exit 1
        }
    }'

or more tersely:
awk -v v="foo" -v p="$PATTERN" 'BEGIN {exit !(v~p)}'

You can use it like this:
PATTERN="foo|bar|baz"
VALUE=oops
matches() { awk -v v="$1" -v p="$2" 'BEGIN {exit !(v~p)}'; }
if matches "$VALUE" "$PATTERN"; then
    echo match
else
    echo no match
fi

A: You can use regex matching in Bash:
PATTERN="foo|bar|baz|bla"

if [[ "foo" =~ $PATTERN ]]
then
    printf "matched\n"
elif . . .
    . . .
elif . . .
    . . .
else
    printf "no match\n"
fi

A: This obviates the need for escaping or anything else:
PATTERN="foo bar baz bla"

case "foo" in
    ${PATTERN// /|})
        printf "matched\n"
        ;;
    *)
        printf "no match\n"
        ;;
esac

redpajama_set_name: RedPajamaStackExchange


text:
Q: HTML, CSS how to make width of element always to bottom of page? I have the image fixed in the center of page and grey div around it. Margins for top, left and right are 15px but it must fill all to bottom of page. I have image to show you what I mean. My question is how to make div height all to bottom, depends on what screen resolution is? Image how it should look:

#IMAGE {
  padding-left: 20px;
  padding-right: 20px;
  /* padding-bottom: 50%; */
  border: 2px solid black;
  border-bottom: 2px solid #D1D1D1;
  border-top-left-radius: 15px;
  border-top-right-radius: 15px;
  background-color: #D1D1D1;
  bottom: 0px;
}

<?php echo "$title"; ?>

A: Easy,
Demo
body {
    overflow:hidden;
}

#wrapper {
    position:absolute;
    top:50%;
    left:50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    padding:15px;
}

#wrapper:after {
    content:'';
    display:block;
    position:absolute;
    top:0;
    left:0;
    right:0;
    bottom:-9999px;
    background:rgba(0,0,0,.2);
}

#wrapper img {
    position:relative;
    z-index:2;
}

A: I think that you are going to need to use JavaScript. You take the height of the whole page, and the height of where you want your div to start. It will come out to be something like this.
$('#yourDiv').height($(window).height() - $('#top').height());

I think this is what you are asking for.


text:
Q: Adding "xmlns" namespace with and without prefix I'm working on C# class I want to serialize, everything goes fine except i'm getting crazy obtaining namespaces of my root element as follows:
<m:DE815 xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:m="http://das.dogane.finanze.it"   xmlns="http://das.dogane.finanze.it" versione="1.0">

I need to write inside root element both xmlns="http://das.dogane.finanze.it" and xmlns:m="http://das.dogane.finanze.it" but what I obtain is this:
<m:DE815 xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:m="http://das.dogane.finanze.it" versione="1.0">

Here's the code I use to serialize my class:
            stream = new MemoryStream(); // read xml in memory

            XmlWriter xmlWriter = XmlWriter.Create(stream);

            XmlSerializer serializer = new XmlSerializer(typeof(DE815), "http://das.dogane.finanze.it");

            List<XmlQualifiedName> names = new List<XmlQualifiedName>();

            var xmlns = new XmlSerializerNamespaces(names.ToArray());
            xmlns.Add("m", "http://das.dogane.finanze.it");
            xmlns.Add("xs", "http://www.w3.org/2001/XMLSchema");
            xmlns.Add("", "http://das.dogane.finanze.it");
            serializer.Serialize(xmlWriter, de815, xmlns); // read object

            int count = (int)stream.Length; // saves object in memory stream

            byte[] arr = new byte[count];
            stream.Seek(0, SeekOrigin.Begin);

            stream.Read(arr, 0, count);
            UTF8Encoding utf = new UTF8Encoding(); // convert byte array to string

            String xmlAsString = utf.GetString(arr).Trim();

            File.WriteAllText("d:\\prova_DE815.xml", xmlAsString, Encoding.UTF8);

Here's the declaration of the class I want to serialize:
[System.CodeDom.Compiler.GeneratedCodeAttribute("xsd", "2.0.50727.3038")
System.SerializableAttribute()
System.Diagnostics.DebuggerStepThroughAttribute()
System.ComponentModel.DesignerCategoryAttribute("code")
System.Xml.Serialization.XmlTypeAttribute(Namespace="http://das.dogane.finanze.it", AnonymousType=true)
System.Xml.Serialization.XmlRootAttribute(Namespace="http://das.dogane.finanze.it", IsNullable=false)
public partial class DE815 {

What am I missing on the code?
Thanks in advance for your help, feel free to ask more questions if I missed any information.


text:
Q: Hibernate sql annotation I am using Hibernate to interface with SQL Server 2016/Azure SQL Server currently, and have been having a great time with it so far. In my database, I have implemented system versioned temporal tables. I want to map (preferably lazily) two more variables by annotation only to my Hibernate entity that represent the original ValidFrom and UpdatedBy fields from the temporal history of the appropriate table.
For example, I have a class and table for Accounts. The Account [minus nonrelated columns, constraints, etc] table is as follows:
CREATE TABLE [dbo].[Account] (
[Id]          INT                                         IDENTITY (1, 1) NOT NULL,
[UpdatedBy]   INT                                         NOT NULL,
[ValidFrom]   DATETIME2 (7) GENERATED ALWAYS AS ROW START DEFAULT (sysutcdatetime()) NOT NULL,
[ValidTo]     DATETIME2 (7) GENERATED ALWAYS AS ROW END   DEFAULT (CONVERT([datetime2],'9999-12-31 23:59:59.9999999')) NOT NULL,
CONSTRAINT [FK_Account.UpdatedById_Account.Id] FOREIGN KEY ([UpdatedBy]) REFERENCES [dbo].[Account] ([Id]),
PRIMARY KEY CLUSTERED ([Id] ASC),
PERIOD FOR SYSTEM_TIME ([ValidFrom], [ValidTo])
)
WITH (SYSTEM_VERSIONING = ON (HISTORY_TABLE=[dbo].[AccountHistory], DATA_CONSISTENCY_CHECK=ON));

The SQL statement to get the data that I want looks like this (I imagine that I would select only UpdatedBy or ValidFrom per annotation, but they are together now to be concise):
SELECT UpdatedBy, ValidFrom FROM dbo.Account
FOR SYSTEM_TIME ALL
WHERE ValidFrom IN
(
SELECT MIN(ValidFrom) OVER (Partition BY Id) AS ValidFrom
FROM dbo.Account
FOR SYSTEM_TIME ALL
WHERE ID = $(passedInIdOfThisEntity)
)

Finally, my Hibernate entity/pojo looks something like this (again, redacting irrelevant variables):
@Entity
@Table(name = "Account")
public class Account implements Serializable {

    @Id
    @Column(name = "Id", unique = true, nullable = false)
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "UpdatedBy")
    private Account updatedBy;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "ValidFrom", nullable = false, length = 27, insertable = false, updatable = false)
    private Date validFrom;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "ValidTo", nullable = false, length = 27, insertable = false, updatable = false)
    private Date validTo;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "updatedBy")
    private Set<Account> accountsUpdated;

    // This is a stub of what I'm hoping you can help me add
    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "ValidFrom", fetch = FetchType.LAZY, insertable = false, updatable = false, somesqlselect = SQL_STATEMENT_FROM_ABOVE)
    private Date createdOn;

    @Column(name = "UpdatedBy", fetch = FetchType.LAZY, insertable = false, updatable = false, somesqlselect = SQL_STATEMENT_FROM_ABOVE)
    private Account createdBy

    // ... getters and setters below
}

I have been using Hibernate to a great extent, but have had trouble finding information on this, though I have found and used examples of implementing native queries for retrieving entities instead of using criteria queries. If you can help me solve this riddle to allow me to continue using criteria queries to retrieve data and populate these fields through annotation on demand, I would greatly appreciate it.

A: The temporal table constructs that you've described isn't something that I am aware that JPA or even Hibernate support natively.  These are likely new features of the ANSI SQL standard which haven't made their way into proper support.
That said, that doesn't mean you cannot use frameworks like Hibernate to accomplish the task.  As indicated in the comments, you can specify a named query and execute that in order to get the attributes you desire.
From a JPA 2.1 perspective, you use @SqlResultSetMapping and @ConstructorResult.
@SqlResultSetMapping(
  name = "Account.getWithTemporalAttributes",
  classes = {
    @ConstructorResult(
      targetClass = com.company.domain.AccountTemporalDetails.class,
      columns = {
        @ColumnResult(name = "col1"),
        @ColumnResult(name = "col2")
      })
  })

To use this, you would do the following:
Query query = entityManager.createNativeQuery(
                 "SELECT a.col1 as col1, a.col2 as col2 FROM Account a",
                 "Account.getWithTemporalAttributes");
List<AccountTemporalDetails> results = query.getResultList();

That should allow you to use Native SQL queries, mapping them to a POJO which you can easily then use within your application without having to write boilerplate.  The @ConstructorResult annotation is meant to mimic the JPQL SELECT NEW syntax.  So you would just need to make sure that AccountTemporalDetails had a constructor that takes those arguments with the right types.


text:
Q: How to set MPMoviePlayerController playing remote videos There's a MPMoviePlayerController * movieplayer, and it will play remote mp4 files on server, code likes this:
movieplayer = [[MPMoviePlayerController alloc] init];
movieplayer.view.frame = CGRectMake(0, 0, 320, 300);
movieplayer.scalingMode = MPMovieScalingModeNone;
[self.view addSubview:movieplayer.view];

There are two buttons, abutton, bbutton, abutton calls playing a.mp4
NSString *VideoUrl = @"http://domain.com/a.mp4";
movieplayer.contentURL = [NSURL URLWithString:VideoUrl];
[movieplayer play];

bbutton calls playing b.mp4
NSString *VideoUrl = @"http://domain.com/b.mp4";
movieplayer.contentURL = [NSURL URLWithString:VideoUrl];
[movieplayer play];

I have some questions:

*

*how to determine the movieplay is playing and finish playing? use stop?

*if a.mp4 is playing, and I click bbutton, it will call playing b.mp4, but there still plays a.mp4 a second, and jump to b.mp4 and plays it.

*how to preload the videos? I think preplay doesn't work.
Thanks

A: 1) To check if your MPMoviePlayerController is playing you can check the playbackState, defined as it:
enum {
   MPMoviePlaybackStateStopped,
   MPMoviePlaybackStatePlaying,
   MPMoviePlaybackStatePaused,
   MPMoviePlaybackStateInterrupted,
   MPMoviePlaybackStateSeekingForward,
   MPMoviePlaybackStateSeekingBackward
};
typedef NSInteger MPMoviePlaybackState;

If its value is MPMoviePlaybackStatePlaying, your player is currently playing a content.
2) Correct, but before playing a new content I suggest you to stop previous one, waiting for player notification (player notifies you its state changes) and then play the new one.
3) It is already done by the player: when you play a content, the player starts to load the content: the playback starts only when the buffer has enough data (so the preload is already done by the player).
You can check the loadState var that can have one of this value:
enum {
   MPMovieLoadStateUnknown        = 0,
   MPMovieLoadStatePlayable       = 1 << 0,
   MPMovieLoadStatePlaythroughOK  = 1 << 1,
   MPMovieLoadStateStalled        = 1 << 2,
};
typedef NSInteger MPMovieLoadState;

If the player loadStateis MPMovieLoadStatePlayable, then the playback can start.
For more information please refers to the reference.

A: In order to determine the MoviePlayer playing status add a notification :
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(playbackStateChanged)
                                             name:MPMoviePlayerPlaybackStateDidChangeNotification
                                           object:nil];

You can add a notification to know when your player successfully load a video as well.
[[NSNotificationCenter defaultCenter] addObserver:self
                                         selector:@selector(MPMoviePlayerLoadStateDidChange:)
                                             name:MPMoviePlayerLoadStateDidChangeNotification
                                           object:nil];

About simply knowing if a player is currently playing or not you can just use
MoviePlayer.isPlaying

Have you considered initiating two different movie players for each movie and simply switching them? It will make the transition smoother i believe.


text:
Q: MAUI items Template are missing, how to fix it? My visual studio version was 2022 17.5 Preview 1.0 , but today now it updated to 17.5 Preview 2.0. And now i can't add any MAUI item such as Content Page or others. You can see HERE that the option "MAUI" isn't appearing...
In the last version it was working...
How can this be fixed?

A: Is this a project (solution) you created with the earlier preview?
If so, create a new project. Same problem?
If new one works, then I suspect some internal VS incompatibility between preview versions:

*

*Delete solution's hidden .vs folder.

*Delete all .bin and .obj folders.

No Maui "Project template" is more serious:

*

*Delete Visual Studio.

*Reboot PC.

*Install Visual Studio. (Windows Search should still show "Visual Studio Installer", Can install from there.)


text:
Q: C# Regular Expression excluding a char (!) the regular expression below works well:
\bG1\b

But I would like to adapt it to not find the G1 occurrences if preceded by a !. For example:
='Plan1'!G1            --> NOT match!
=G1*G2                 --> MATCH!
='Plan2'!A1+'Plan2'!G1 --> NOT match!

how would this regular expression?

A: You need a negative lookbehind:

(?<!subexpression)
  where subexpression is any regular expression pattern. For a match to be successful, subexpression must not occur at the input string to the left of the current position. However, any substring that does not match subexpression is not included in the match result.

So, use
(?<!!)\bG1\b
^^^^^^

See the regex demo


text:
Q: How to calculate count of string in array [
    {
        "assetNo":"51GQA21AP001"
    },
    {
        "assetNo":"51GQA22AP001"
    },
    {
        "assetNo":"51GQA24AP001"
    },
     {
        "assetNo":"51GQA22AP001"
    },
     {
        "assetNo":"51GQA21AP001"
    },
     {
        "assetNo":"51GQA23AP001"
    },
    {
        "assetNo":"51GQA24AP001"
    }
]

I need the output following:
[{
  "assetNo": "51GQA21AP001",
  "count": 2
}, {
  "assetNo": "51GQA22AP001",
  "count": 2
}, , {
  "assetNo": "51GQA23AP001",
  "count": 2
},{
  "assetNo": "51GQA24AP001",
  "count": 1
}]

A: Here you go :

var data = [
    {
        "assetNo":"51GQA21AP001"
    },
    {
        "assetNo":"51GQA22AP001"
    },
     {
        "assetNo":"51GQA24AP001"
    },
     {
        "assetNo":"51GQA22AP001"
    },
     {
        "assetNo":"51GQA21AP001"
    },
     {
        "assetNo":"51GQA23AP001"
    },
     {
        "assetNo":"51GQA24AP001"
    }
]

let count = {};
data.forEach(el => {
    count[el.assetNo] = count[el.assetNo] ? count[el.assetNo]+1 : 1;
})

let lastResult = [];
for (var key in count) {
  lastResult.push({ assetNo : key , count : count[key] });
}

console.log(lastResult);

A: You can use array#reduce to group your array based on assetNo.

var data = [{ "assetNo": "51GQA21AP001" }, { "assetNo": "51GQA22AP001" }, { "assetNo": "51GQA24AP001" }, { "assetNo": "51GQA22AP001" }, { "assetNo": "51GQA21AP001" }, { "assetNo": "51GQA23AP001" }, { "assetNo": "51GQA24AP001" } ],
  result = Object.values(data.reduce((r,o) => {
    r[o.assetNo] = r[o.assetNo] || {assetNo : o.assetNo, count : 0};
    r[o.assetNo].count += 1;
    return r;
  },{}));
console.log(result);


text:
Q: Backbone Relational - Deep nested models/collections Having some fun with Backbone-relational.js v0.10.0
I have a JSON object which contains nested models and collections, to keep this simple I have made the example below. A company can have many employees, employees can have one address and many tasks.
{
    name: 'Nicks Company',
    employees: [{
        name: 'Bob',
        address: {
            line1: '1 City Lane',
            city: 'London'
        },
        tasks: [{
            description: 'Make this work'
        }]
    }, {
        name: 'Bill',
        address: {
            line1: '1 The Street',
            city: 'Birmingham'
        },
        tasks: [{
            description: 'Make a cake'
        }, {
            description: 'Fix all the things'
        }]
    }]
}

In the below JSFiddle (console) you can see that the address is a plain object, also the commented out code for tasks has been disabled as tasks is returned as an array.
JSFiddle: https://jsfiddle.net/nwa29uLv/2/
Neither the address model or the collection of tasks are created as Backbone instances, is this possible or am I pushing the limits of this plugin?

A: *

*Here is how I resolved the issue. You were missing the
reverseRelation.

*BTW did you look at this post? It has a similar issue.

Follow the fiddle here

var Address = Backbone.RelationalModel.extend({});

var Task = Backbone.RelationalModel.extend({});
var TaskCollection = Backbone.Collection.extend({
  model: Task
});

var Employee = Backbone.RelationalModel.extend({
  relations: [{
    type: Backbone.HasOne,
    key: 'address',
    relatedModel: Address,
    reverseRelation: {
      type: Backbone.HasOne,
      key: 'employee'
    }
  }, {
    type: Backbone.HasMany,
    key: 'tasks',
    collectionType: TaskCollection,
    relatedModel: Task,
    reverseRelation: {
      type: Backbone.HasOne,
      key: 'operatesOn'
    }
  }]
});

var EmployeeCollection = Backbone.Collection.extend({
  model: Employee
});

var Company = Backbone.RelationalModel.extend({
  relations: [{
    type: Backbone.HasMany,
    key: 'employees',
    relatedModel: Employee,
    reverseRelation: {
      key: 'worksFor'
    }
  }]
});

var company = new Company({
  name: 'Nicks Company',
  employees: [{
    name: 'Bob',
    address: {
      line1: '1 City Lane',
      city: 'London'
    },
    tasks: [{
      description: 'Make this work'
    }]
  }, {
    name: 'Bill',
    address: {
      line1: '1 The Street',
      city: 'Birmingham'
    },
    tasks: [{
      description: 'Make a cake'
    }, {
      description: 'Fix all the things'
    }]
  }]
});

console.log('Company:', company.get('name'));
company.get('employees').each(function(employee) {
  console.log('Employee:', employee.get('name'));
  console.log('Employee:', employee.get('name'), 'Address Model:', employee.get('address').get('city'));
  employee.get('tasks').each(function(task) {
    console.log('Employee:', employee.get('name'), 'Task: ', task.get('description'));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.3.3/backbone-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone-relational/0.10.0/backbone-relational.js"></script>


text:
Q: Drop observations once condition is met by multiple variables I have the following data and used one of the existing answered questions to solve my data problem but could not get what I want. Here is what I have in my data

*

*Amt1 is populated when the Evt_type is Fee

*Amt2 is populated when the Evt_type is REF1/REF2

*I don't want to display any observations after the last Flag='Y'

*If there is no Flag='Y' then I want all the observations for that id (e.g. id=102)

*I want to display if the next row for that id is a Fee followed by REF1/REF2 after flag='Y' (e.g. id=101) However I don't want if there is no REF1/REF2 (e.g.id=103)
Have:
       id   Date        Evt_Type   Flag   Amt1   Amt2
      101  2/2/2019      Fee              5
      101  2/3/2019      REF1      Y             5
      101  2/4/2019      Fee              10
      101  2/6/2019      REF2      Y             10
      101  2/7/2019      Fee               4
      101  2/8/2019      REF1
      102  2/2/2019      Fee              25
      102  2/2/2019      REF1      N      25
      103  2/3/2019      Fee              10
      103  2/4/2019      REF1      Y             10
      103  2/5/2019      Fee              10

Want:
      id   Date        Evt_Type   Flag   Amt1   Amt2
     101  2/2/2019      Fee              5
     101  2/3/2019      REF1      Y             5
     101  2/4/2019      Fee              10
     101  2/6/2019      REF2      Y             10
     101  2/7/2019      Fee               4
     101  2/8/2019      REF1
     102  2/2/2019      Fee              25
     102  2/2/2019      REF1      N      25
     103  2/4/2019      REF1      Y             10
     103  2/5/2019      Fee              10

I tried the following
data want;
    set have;
    by id Date;
    drop count;

    if (first.id or first.date) and FLAG='Y' then
        do;
            retain count;
            count=1;
            output;
            return;
        end;

    if count=1 and ((first.id or first.date) and Flag ne 'Y') then
        do;
            retain count;
            delete;
            return;
        end;
    output;
run;

Any help is appreciated.
Thanks

A: A technique known as DOW loop can perform a computation that measures a group in some way and then, in a second loop, apply that computation to members of the group.
The DOW relies on a SET statement inside the loop.  In this case the computation is 'what row in the group is the last one having flag="Y".
data want;
  * DOW loop, contains computation;

  _max_n_with_Y = 1e12;

  do _n_ = 1 by 1 until (last.id);
    set have;
    by id;
    if flag='Y' then _max_n_with_Y = _n_;
  end;

  * Follow up loop, applies computation;
  do _n_ = 1 to _n_;
    set have;
    if _n_ <= _max_n_with_Y then OUTPUT;
  end;
  drop _:;
run;

A: Here is one way
data have;
input id $ Date : mmddyy10. Evt_Type $ Flag $ Amt1 Amt2;
format Date mmddyy10.;
infile datalines dsd missover;
datalines;
101,2/2/2019,Fee,,5,
101,2/3/2019,REF1,Y,,5
101,2/4/2019,Fee,,10,
101,2/6/2019,REF2,Y,,10
101,2/7/2019,Fee,,4,
102,2/2/2019,Fee,,25,
102,2/2/2019,REF1,N,25,
;

data want;
   do _N_ = 1 by 1 until (last.id);
      set have;
      by id;
      if flag = "Y" then _iorc_ = _N_;
   end;

   do _N_ = 1 to _N_;
      set have;
      if _N_ le _iorc_ then output;
   end;
   _iorc_=1e7;
run;


text:
Q: Using non-FUJITSU 10Gb Ethernet Cards in FUJITSU servers We are currently trying to upgrade old servers to 10Gb connections. The servers in question are:

*

*PRIMERGY RX200 S6

*PRIMERGY RX300 S5

Our FUJITSU partner told us that there were no cards available by FUJITSU. There seem to be cards available by 3rd-party-manufacturers though. The PCIe slots in the servers seem to be PCIe 2.0 x8.
Should we expect any problems running non-FUJITSU cards in the servers?


text:
Q: Install Ubuntu10.04 on LVM :: error: no such disk I installed Ubuntu10.04 on one LVM Disk.
But when I boot my computer.
It prompts:
error:no such disk

But after a few seconds,it can display the Grub menu and I can go in my Ubuntu10.04.
What is wrong?  Does anyone have the same problems?

A: I have solved this problem. I went to my BIOS and disabled the floppy. It now works!


text:
Q: Storyboard: setting the initial view controller at runtime I'm developing an iOS 7+ app, and I've been told to set a different initial view for the app depending on a parameter I won't know until runtime. One of the possible initial UIViewController is an UITabBarViewController, and the other one is an UINavigationController.
Is it possible to manage this using a storyboard? Or is it the only way to use separated nib files?
Thanks

A: No need to use separate nib files, I do the same by following code in AppDelegate
- (BOOL)application:(UIApplication *)application willFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    UIStoryboard *storyboard = self.window.rootViewController.storyboard;
    if(condition1) {
        UITabBarController *rootViewController= [storyboard instantiateViewControllerWithIdentifier:@"TabbarController"];
        [self setRootViewController:rootViewController];
    } else if(condition2) {
        UIViewController *rootViewController= [storyboard instantiateViewControllerWithIdentifier:@"ViewController"];
        [self setRootViewController:rootViewController];
    } else {
        UIViewController *rootViewController= [storyboard instantiateViewControllerWithIdentifier:@"ViewController1"];
        [self setRootViewController:rootViewController];
    }
}

-(void)setRootViewController:(UIViewController *)rootViewController {
    self.window.rootViewController = rootViewController;
    [self.window makeKeyAndVisible];
}

A: You can specify the ID for your UITabBarViewController and UINavigationController in the storyboard.Then manually set the rootViewController of your app as the code below.
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
UIStoryboard *board = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
self.window.rootViewController = [board instantiateViewControllerWithIdentifier:@"TabBarController"];
[self.window makeKeyAndVisible];

}

A: I'm not sure if I understood you right, but try to use JLRoutes. Set your TabBarController as initial view controller in one storyboard and navigation controller will be initial in other storyboard. Then navigate between them using JLRoutes


text:
Q: Geometry problem on the incentre and circumcenter of a triangle I have the following problem:

In a triangle $ABC$ the line joining incentre and circumcentre is parallel to side $BC$. Prove that $\cos B + \cos C=1$.

Could someone help me solve it?

A: This question provides simple proofs of the identity: $$\frac{r}{R}+1=\cos A+\cos B+\cos C$$
Referring to Derek's diagram, $\angle CKB = 2\angle A = 2\angle CKR$. Since, the angle made by the chord $BC$ at the point $A$ on the circumcircle of $\Delta ABC$ is half the angle made at the circumcentre $K$.
Also, $\cos A = \cos \angle CKR = \dfrac{KR}{CK}=\dfrac{r}{R}$ (since, IK is parallel to $BC$, we have $KR = r$).
So, $\cos B + \cos C = 1$

A: This one has been untouched for a few days now, so here's a solution. It does the job but it feels like I beat it into submission with a stick.
I would be interested to know if anyone has a more elegant approach, as it was tougher than I was expecting.

In the above diagram $I$ is the incentre and $K$ is the circumcentre of $\Delta$ ABC.
$PS \parallel BC $ therefore
$$ \frac{CP}{BS}=\frac{AC}{AB}= \frac{ \sin B}{\sin C}, \quad (1)$$
by the sine rule.
Furthermore, $\Delta$ CIP and $\Delta$ BIS are isosceles and so
$$ \frac{PS}{BC}=\frac{CP+BS}{BC}= 1 - \frac{BS}{AB},$$
the last equality is implied by $PS \parallel BC .$ And so
$$ CP = \left( 1 - \frac{BS}{AB} \right) BC - BS = \frac{\sin B}{\sin C} \cdot BS,$$
using $(1).$
Hence
$$ BC = BS \left( 1+ \frac{\sin B}{\sin C} + \frac{BC}{AB} \right)
= BS \left( 1+ \frac{\sin B}{\sin C} + \frac{\sin (B+C)}{\sin C} \right), \quad (2)$$
by the sine rule.
Let $ \angle CBK=\theta$ then, again by the sine rule and noting that $BK=CK,$
we have
$$\frac{\sin B}{\sin (B+C)} = \frac{AC}{BC} = \frac{\cos (C-\theta)}{\cos \theta} =
\cos C + \sin C \tan \theta.$$
Hence
$$ \tan \theta = \frac{ \frac{\sin B}{\sin (B+C)} - \cos C}{\sin C}. $$
Also
$$BC = 2 RK \cot \theta = 2 BS \sin B \cot \theta
= \frac{2BS \sin B \sin C}{ \frac{\sin B}{\sin(B+C)} - \cos C}, \quad (3)$$
using $RK = BS \sin B$ and the expression for $\tan \theta.$
Combining $(2)$ and $(3)$ we obtain
$$ 1+ \frac{\sin B}{\sin C} + \frac{\sin (B+C)}{\sin C}
=\frac{2\sin B \sin C}{ \frac{\sin B}{\sin(B+C)} - \cos C}. \quad (4)$$
Now we need to show that $(4) \Rightarrow \cos B + \cos C = 1.$
ABC is a non-degenerate triangle and so $C \ne 0$ and $\cos B + \cos C \ne -1$ and so
$\cos B + \cos C = 1 \Longleftrightarrow$
$$2\sin B \sin^2 C = 2 \sin B (1- \cos^2 C) + \sin C
\lbrace 1 - (\cos B + \cos C)^2 \rbrace $$
$$= 2\sin B - 2\sin B \cos^2 C + \sin C (-2\cos B \cos C + \sin^2 B - \cos^2 C)$$
$$=\lbrace 2 + \cos(B-C) \rbrace \lbrace \sin B - \cos C \sin(B+C) \rbrace, \quad (5)$$
noting that $\sin(B+C)\cos(B-C) = \sin B \cos B + \sin C \cos C.$ When we expand the RHS of $(5)$ the two terms $\sin B \cos B \cos C$ and $-\sin B \cos B \cos C$ cancel, leaving precisely the RHS of the second to last line of $(5).$
Hence we have $\cos B + \cos C = 1 \Longleftrightarrow$
$$ \frac{2+ \cos(B-C)}{\sin C} = \frac{2 \sin B \sin C}{\sin B - \cos C \sin (B+C)}. \quad (6)$$
Now
$$\sin (B+C) \lbrace 1+ \cos(B-C) \rbrace = \sin(B+C) + \sin(B+C) \cos(B-C)$$
$$=\sin B \cos C + \cos B\sin C + \sin B \cos B + \sin C \cos C $$
$$=(\sin B + \sin C)(\cos B + \cos C) = \sin B + \sin C \quad (7)$$
$\Longleftrightarrow \cos B + \cos C = 1,$ since $\sin B + \sin C \ne 0.$
And so the LHS of $(4)$
$$ 1+ \frac{\sin B}{\sin C} + \frac{\sin (B+C)}{\sin C} =
\frac{\sin B + \sin C + \sin(B+C)}{\sin C}$$
and using $(7)$ to substitute for $\sin B + \sin C$
$$=\frac{2\sin(B+C)+ \sin(B+C)\cos(B-C)}{\sin C}
=\sin(B+C)\frac{2+\cos(B-C)}{\sin C}$$
and using $(6)$ to substitute for the fraction
$$=\frac{2\sin B \sin C \sin(B+C)}{\sin B - \cos C \sin(B+C)}
=\frac{2\sin B \sin C}{ \frac{\sin B}{\sin(B+C)} - \cos C}.$$
And so we have shown that when $B$ and $C$ are angles of a triangle then
$(4) \Rightarrow \cos B + \cos C = 1$ and the result is proved.

A: Given Line joining Circumcentre and Incentre are parallel
$$r=4R\sin A/2\sin B/2\sin C/2=R\cos A$$
$$4\sin A/2\sin B/2\sin C/2=\cos A$$
$$\cos A+\cos B+\cos C-1=\cos A$$
$$\cos B+\cos C=1$$


text:
Q: ERROR: Error caught on signal handler: Every time I am trying to execute the code, I am facing this error. I am using scrapy-playwright. It is also not able to launch the browser. What is the reason behind this and how to solve this issue?
2022-04-08 17:50:53 [scrapy.core.engine] INFO: Spider opened
2022-04-08 17:50:53 [scrapy.extensions.logstats] INFO: Crawled 0 pages (at 0 pages/min), scraped 0 items (at 0 items/min)
2022-04-08 17:50:53 [scrapy.extensions.telnet] INFO: Telnet console listening on 127.0.0.1:6023
2022-04-08 17:50:53 [scrapy-playwright] INFO: Launching browser
2022-04-08 17:50:53 [scrapy-playwright] INFO: Launching browser
2022-04-08 17:51:23 [scrapy.utils.signal] ERROR: Error caught on signal handler: <bound method ScrapyPlaywrightDownloadHandler._engine_started of <scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler object at 0x7fc184e49180>>
Traceback (most recent call last):
  File "/home/raisulrana/anaconda3/envs/scrapy/lib/python3.10/site-packages/twisted/internet/defer.py", line 1030, in adapt
    extracted = result.result()
  File "/home/raisulrana/anaconda3/envs/scrapy/lib/python3.10/site-packages/scrapy_playwright/handler.py", line 130, in _launch_browser
    self.browser = await browser_launcher(**self.launch_options)
  File "/home/raisulrana/anaconda3/envs/scrapy/lib/python3.10/site-packages/playwright/async_api/_generated.py", line 11633, in launch
    await self._async(
  File "/home/raisulrana/anaconda3/envs/scrapy/lib/python3.10/site-packages/playwright/_impl/_browser_type.py", line 90, in launch
    Browser, from_channel(await self._channel.send("launch", params))
  File "/home/raisulrana/anaconda3/envs/scrapy/lib/python3.10/site-packages/playwright/_impl/_connection.py", line 39, in send
    return await self.inner_send(method, params, False)
  File "/home/raisulrana/anaconda3/envs/scrapy/lib/python3.10/site-packages/playwright/_impl/_connection.py", line 63, in inner_send
    result = next(iter(done)).result()
playwright._impl._api_types.TimeoutError: Timeout 30000ms exceeded.
=========================== logs ===========================
<launching> /home/raisulrana/.cache/ms-playwright/chromium-956323/chrome-linux/chrome --disable-background-networking --enable-features=NetworkService,NetworkServiceInProcess --disable-background-timer-throttling --disable-backgrounding-occluded-windows --disable-breakpad --disable-client-side-phishing-detection --disable-component-extensions-with-background-pages --disable-default-apps --disable-dev-shm-usage --disable-extensions --disable-features=ImprovedCookieControls,LazyFrameLoading,GlobalMediaControls,DestroyProfileOnBrowserClose,MediaRouter,AcceptCHFrame,AutoExpandDetailsElement --allow-pre-commit-input --disable-hang-monitor --disable-ipc-flooding-protection --disable-popup-blocking --disable-prompt-on-repost
--disable-renderer-backgrounding --disable-sync --force-color-profile=srgb --metrics-recording-only --no-first-run --enable-automation --password-store=basic --use-mock-keychain --no-service-autorun --export-tagged-pdf --no-sandbox --user-data-dir=/tmp/playwright_chromiumdev_profile-MxuOHN --remote-debugging-pipe --no-startup-window
<launched> pid=15139
[pid=15139][err] [0408/175057.243838:ERROR:exception_handler_server.cc(361)] getsockopt: Invalid argument (22)
============================================================
2022-04-08 17:51:23 [scrapy.utils.signal] ERROR: Error caught on signal handler: <bound method ScrapyPlaywrightDownloadHandler._engine_started of <scrapy_playwright.handler.ScrapyPlaywrightDownloadHandler object at 0x7fc1851456f0>>
Traceback (most recent call last):
  File "/home/raisulrana/anaconda3/envs/scrapy/lib/python3.10/site-packages/twisted/internet/defer.py", line 1030, in adapt
    extracted = result.result()
  File "/home/raisulrana/anaconda3/envs/scrapy/lib/python3.10/site-packages/scrapy_playwright/handler.py", line 130, in _launch_browser
    self.browser = await browser_launcher(**self.launch_options)
  File "/home/raisulrana/anaconda3/envs/scrapy/lib/python3.10/site-packages/playwright/async_api/_generated.py", line 11633, in launch
    await self._async(
  File "/home/raisulrana/anaconda3/envs/scrapy/lib/python3.10/site-packages/playwright/_impl/_browser_type.py", line 90, in launch
    Browser, from_channel(await self._channel.send("launch", params))
  File "/home/raisulrana/anaconda3/envs/scrapy/lib/python3.10/site-packages/playwright/_impl/_connection.py", line 39, in send
    return await self.inner_send(method, params, False)
  File "/home/raisulrana/anaconda3/envs/scrapy/lib/python3.10/site-packages/playwright/_impl/_connection.py", line 63, in inner_send
    result = next(iter(done)).result()
playwright._impl._api_types.TimeoutError: Timeout 30000ms exceeded.
=========================== logs ===========================

A: Install these first
playwright
scrapy-playwright
Scrapy
And then run in the terminal
playwright install  (This will install the driver required for playwright)


text:
Q: Getting error while training a DANN model -> CUDA error: CUBLAS_STATUS_EXECUTION_FAILED At first I want to tell, that I am a newbie to Machine Learning. So I apologize if there is any mistake in my code.
I am training a DANN(Domain Adversarial Neural Network) on the CIFAR10 and CIFAR100 datasets and I am getting a error code
---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-25-f44419d6a132> in <module>
     27         D.zero_grad()
     28
---> 29         Ltot.backward()
     30
     31         C_opt.step()

1 frames
/usr/local/lib/python3.8/dist-packages/torch/_tensor.py in backward(self, gradient, retain_graph, create_graph, inputs)
    486                 inputs=inputs,
    487             )
--> 488         torch.autograd.backward(
    489             self, gradient, retain_graph, create_graph, inputs=inputs
    490         )

/usr/local/lib/python3.8/dist-packages/torch/autograd/__init__.py in backward(tensors, grad_tensors, retain_graph, create_graph, grad_variables, inputs)
    195     # some Python versions print out the first line of a multi-line function
    196     # calls in the traceback and some print out the last line
--> 197     Variable._execution_engine.run_backward(  # Calls into the C++ engine to run the backward pass
    198         tensors, grad_tensors_, retain_graph, create_graph, inputs,
    199         allow_unreachable=True, accumulate_grad=True)  # Calls into the C++ engine to run the backward pass

RuntimeError: CUDA error: CUBLAS_STATUS_EXECUTION_FAILED when calling `cublasSgemm( handle, opa, opb, m, n, k, &alpha, a, lda, b, ldb, &beta, c, ldc)

Couldn't figure out the problem in the code. Kindly attaching the whole code for your reference.
class FeatureExtractor(nn.Module):
    """
        Feature Extractor
    """
    def __init__(self, in_channel=3, hidden_dims=512):
        super(FeatureExtractor, self).__init__()
        self.conv = nn.Sequential(
            nn.Conv2d(in_channel, 64, 3, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(2,2), # Add max pooling layer
            nn.Conv2d(64, 128, 3, padding=1),
            nn.BatchNorm2d(128),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(2,2), # Add max pooling layer
            nn.Conv2d(128, 256, 3, padding=1),
            nn.BatchNorm2d(256),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(2,2), # Add max pooling layer
            nn.Conv2d(256, 256, 3, padding=1),
            nn.BatchNorm2d(256),
            nn.ReLU(inplace=True),
            nn.MaxPool2d(2,2), # Add max pooling layer
            nn.Conv2d(256, hidden_dims, 3, padding=1),
            nn.BatchNorm2d(hidden_dims),
            nn.ReLU(inplace=True),
            nn.AdaptiveAvgPool2d((1,1)),
        )

    def forward(self, x):
        h = self.conv(x).squeeze() # (N, hidden_dims)
        return h

class Classifier(nn.Module):
    """
        Classifier
    """
    def __init__(self, input_size=512, num_classes=10):
        super(Classifier, self).__init__()
        self.layer = nn.Sequential(
            nn.Linear(input_size, 256),
            nn.ReLU(inplace=True),
            nn.Dropout(0.5),
            nn.Linear(256, num_classes),
        )

    def forward(self, h):
        c = self.layer(h)
        return c

class Discriminator(nn.Module):
    """
        Simple Discriminator w/ MLP
    """
    def __init__(self, input_size=512, num_classes=1):
        super(Discriminator, self).__init__()
        self.layer = nn.Sequential(
            nn.Linear(input_size, 256),
            nn.LeakyReLU(0.2),
            nn.Dropout(0.5),
            nn.Linear(256, 128),
            nn.LeakyReLU(0.2),
            nn.Linear(128, num_classes),
            nn.Sigmoid(),
        )

    def forward(self, h):
        y = self.layer(h)
        return y

F = FeatureExtractor().to(DEVICE)
C = Classifier().to(DEVICE)
D = Discriminator().to(DEVICE)

transform = transforms.Compose([
    transforms.Resize(28),
    transforms.CenterCrop(28),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.5],
                         std=[0.5])
])

mnist_train = datasets.CIFAR10(root='../data/', train=True, transform=transform, download=True)
mnist_test = datasets.CIFAR10(root='../data/', train=False, transform=transform, download=True)

svhn_train = datasets.CIFAR100(root='../data/', train=True,transform=transform, download=True)
svhn_test = datasets.CIFAR100(root='../data/', train=False,transform=transform, download=True)

batch_size = 64

svhn_train.data.shape

svhn_loader = DataLoader(dataset=svhn_train, batch_size=batch_size, shuffle=True, drop_last=True,num_workers=3, pin_memory=True)
mnist_loader = DataLoader(dataset=mnist_train, batch_size=batch_size, shuffle=True, drop_last=True, num_workers=3, pin_memory=True  )
eval_loader = DataLoader(dataset=svhn_test, batch_size=batch_size, shuffle=False, drop_last=False,num_workers=3, pin_memory=True)
test_loader = DataLoader(dataset=mnist_test, batch_size=batch_size, shuffle=False, drop_last=False,num_workers=3, pin_memory=True)

bce = nn.BCELoss()
xe = nn.CrossEntropyLoss()

F_opt = torch.optim.Adam(F.parameters())
C_opt = torch.optim.Adam(C.parameters())
D_opt = torch.optim.Adam(D.parameters())

max_epoch = 50
step = 0
n_critic = 1 # for training more k steps about Discriminator
n_batches = len(mnist_train)//batch_size
# lamda = 0.01

D_src = torch.ones(batch_size, 1).to(DEVICE) # Discriminator Label to real
D_tgt = torch.zeros(batch_size, 1).to(DEVICE) # Discriminator Label to fake
D_labels = torch.cat([D_src, D_tgt], dim=0)

"""### Training Code

"""

def get_lambda(epoch, max_epoch):
    p = epoch / max_epoch
    return 2. / (1+np.exp(-10.*p)) - 1.

mnist_set = iter(mnist_loader)

def sample_mnist(step, n_batches):
    global mnist_set
    if step % n_batches == 0:
        mnist_set = iter(mnist_loader)
    return next(mnist_set)

ll_c, ll_d = [], []
acc_lst = []

torch.cuda.empty_cache()

for epoch in range(1, max_epoch+1):
    for idx, (src_images, labels) in enumerate(svhn_loader):
        tgt_images, _ = sample_mnist(step, n_batches)
        # Training Discriminator
        src, labels, tgt = src_images.to(DEVICE), labels.to(DEVICE), tgt_images.to(DEVICE)

        x = torch.cat([src, tgt], dim=0)
        h = F(x)
        y = D(h.detach())

        Ld = bce(y, D_labels)
        D.zero_grad()
        Ld.backward()
        D_opt.step()

        c = C(h[:batch_size])
        y = D(h)
        Lc = xe(c, labels)
        Ld = bce(y, D_labels)
        lamda = 0.1*get_lambda(epoch, max_epoch)
        Ltot = Lc -lamda*Ld

        F.zero_grad()
        C.zero_grad()
        D.zero_grad()

        Ltot.backward()

        C_opt.step()
        F_opt.step()

        if step % 100 == 0:
            dt = datetime.datetime.now().strftime('%H:%M:%S')
            print('Epoch: {}/{}, Step: {}, D Loss: {:.4f}, C Loss: {:.4f}, lambda: {:.4f} ---- {}'.format(epoch, max_epoch, step, Ld.item(), Lc.item(), lamda, dt))
            ll_c.append(Lc.detach().cpu().numpy())
            ll_d.append(Ld.detach().cpu().numpy())

        if step % 500 == 0:
            F.eval()
            C.eval()
            with torch.no_grad():
                corrects = torch.zeros(1).to(DEVICE)
                for idx, (src, labels) in enumerate(eval_loader):
                    src, labels = src.to(DEVICE), labels.to(DEVICE)
                    c = C(F(src))
                    _, preds = torch.max(c, 1)
                    corrects += (preds == labels).sum()
                acc = corrects.item() / len(eval_loader.dataset)
                print('***** Eval Result: {:.4f}, Step: {}'.format(acc, step))

                corrects = torch.zeros(1).to(DEVICE)
                for idx, (tgt, labels) in enumerate(test_loader):
                    tgt, labels = tgt.to(DEVICE), labels.to(DEVICE)
                    c = C(F(tgt))
                    _, preds = torch.max(c, 1)
                    corrects += (preds == labels).sum()
                acc = corrects.item() / len(test_loader.dataset)
                print('***** Test Result: {:.4f}, Step: {}'.format(acc, step))
                acc_lst.append(acc)

            F.train()
            C.train()
        step += 1


text:
Q: Trying to get PyCharm to work, keep getting "No Python interpreter selected" I'm trying to learn Python and decided to use PyCharm.  When I try to start a new project I get a dialog that says "No Python interpreter selected".  It has a drop down to select a interpreter, but the drop down is empty.

A: Your problem probably is that you haven't installed python. Meaning that, if you are using Windows, you have not downloaded the installer for Windows, that you can find on the official Python website.
In case you have, chances are that PyCharm cannot find your Python installation because its not in the default location, which is usually C:\Python27 or C:\Python33 (for me at least).
So, if you have installed Python and it still gives this error, then there can be two things that have happened:

*

*You use a virtualenv and that virtualenv has been deleted or the filepath changed. In this case, you will have to find proceed to the next part of this answer.

*Your python installation is not in its default place, in which case you will need to find its location, and locate the python.exe file.

Once you have located the necessary binaries, you will need to tell PyCharm were to look:

*

*Open your settings dialogue CTRL + ALT + S

*Then you will need to type in interpreter in the search box:

*As you can see above, you will need to go to Project Interpreter and then go to Python Interpreter. The location has been selected for you in the above image.

*To the side you will see a couple of options as icons, click the big + icon, then click on local, because your interpreter is on this computer.

*This will open up a dialogue box. Make sure to select the python.exe file of that directory, do not give pycharm the whole directory. It just wants the interpreter.

A: This situation occurred to me when I uninstalled a method and tried to reinstall it. My very same interpreter, which worked before, suddenly stopped working. And this error occurred.
I tried restarting my PC, reinstalling Pycharm, invalidating caches, nothing worked.
Then I went here to reinstall the interpreter:
https://www.python.org/downloads/
When you install it, there's an option to fix the python.exe interpreter. Click that. My IDE went back to normal working conditions.

A: During the install of python make sure you have "Install for all users" selected.
Uninstall python and do a custom install and check "Install for all users".

A: Go to File->Settings->Project Settings->Project Interpreter->Python Interpreters
There will be a "+" sign on the right side. Navigate to your python binary, PyCharm will figure out the rest.

A: Even I got the same issue and my mistake was that I didn't download python MSI file. You will get it here: https://www.python.org/downloads/
Once you download the msi, run the setup and that will solve the problem. After that you can go to File->Settings->Project Settings->Project Interpreter->Python Interpreters
and select the python.exe file. (This file will be available at c:\Python34)
Select the python.exe file. That's it.

A: for mac I can tell you that first you have to check your path
by executing this command
which python or which python3

then you have to configure it in your pycharm.
pycharm-->preferences-->gear button-->add..

click on system interpreter--> then on ...
then you search where your python version is installed

once it is done then you have to configure for your project
click on edit configuration

then choose the python interpreter

A: If you are using Ubuntu, Python has already been downloaded on your PC.
so, go to -> ctrl + alt + s -> search interpreter -> go to project interpreter than select Python 3.6 in the dropdown menu.
Edit: If there is no Python interpreter in drop-down menu, you should click the gear icon that on the right of the drop-down menu --> add --> select an interpreter.
(on PyCharm 2018.2.4 Community Edition)

A: I got the same issue when i newly installed pycharm in my windows 10 machine.

*

*download python setup

*install this solved my problem.
for more help visit
goodluck

During the install of python make sure you have "Install for all users" selected. Uninstall python and do a custom install and check "Install for all users"

A: In my case, there are several interpreters, but I have to manually add them.
To the right of where you see "No Interpreters", there is a gear icon. Click the gear icon -> Click "Add...", then you can add the ones you need.

A: In Linux, it was solved by opening PyCharm from the terminal and leaving it open. After that, I was able to choose the correct interpreter in preferences. In my case, linked to a virtual environment (venv).

A: You don't have Python Interpreter installed on your machine whereas Pycharm is looking for a Python interpreter, just go to https://www.python.org/downloads/
and download python and then create a new project, you'll be all set!

A: I had the same problem and stumbled onto this solution.
I ran PyCharm (as administrator, though not sure if necessary).
After PyCharm has completely loaded (green tick mark top right), see  bottom right. Click on it.
An interface will open. In my case the path was already there. I just clicked OK and all was fine.
closed PyCharm and ran it again normally. Still all fine.

A: I has to close PyCharm, delete the .idea folder then open PyCharm again.


text:
Q: Using more data sets in Report Server from one stored procedure I am deploying a lot of report lately.
And so to I kept code and version clear and understanding,
Ill like to  have one stored procedure per report.
Mostly time I need more data sets for one reports.
Is there possibility to I have more then one data set in report SSRS for calling only one stored procedure for that report.
(I am using remote reports hosted on Sql Report Server 2008 ).
I uses familiar Issue whit sample console application for creating multiple CSV files from  SQL using one stored procedure.
snipes of code looks something like this:
        SqlConnection conn = new SqlConnection(strConn);
        SqlCommand command = new SqlCommand("sp_ado_pos_data", conn);
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add("@skl_id", SqlDbType.Int).Value = 158;
        SqlDataAdapter adapter = new SqlDataAdapter(command);
        DataSet ds = new DataSet();
        adapter.Fill(ds);
        for (int i = 0; i < ds.Tables.Count; i++)
        {
            string datoteka  = (string.Format(@"{0}tablea{1}.csv", direktorij, i));
            DataTable tabela = ds.Tables[i];
            //Here I fill datasets with multiple results from one stored proc.
            CreateCSVFile(tabela,datoteka );
            Console.WriteLine("Generišem tabelu {0}", datoteka);
        }

A: It appears that this isn't possible with standard reports presented through the default report viewer - SSRS ignores all but the first result set from a multi result-set source.
However, based on this article, it appears that it is be possible in stand-alone  reports (.rdlc extension). I'm not sure whether this means that, with a custom report viewer, standard .rdl reports could be configured in a similar way.


text:
Q: Update TableView through posted data from Spring Server I am trying to make a game for my class project. The requirements are that I need to use a Spring architecture for both the server and client. I have done all that, I have even managed to post or get stuff from the server through RestTemplate.
My Server is completely on Spring Boot.
My Client is running on JavaFX and Spring Boot.
My problem now here is that sometimes I want the Server to post data to the client. The post is working, I am getting the data but I cannot seem to update the TableView in my screen.
I know that since the server is triggering this on the client side, it must not be on the main JavaFX UI Thread. So I tried loading the FXML
gameDetails = playerView;
    FXMLLoader loader = new FXMLLoader(getClass().getClassLoader().getResource("pre_game.fxml"));
    try {
        Parent root = loader.load();
    } catch (IOException e) {
        e.printStackTrace();
    }
    PreGame controller = loader.getController();
    TableView<PlayerView> tblPlayerList = controller.tblPlayerList;
    TableColumn<PlayerView, String> colPlayerName = controller.colPlayerName;
    ObservableList<PlayerView> gamesObservableList = controller.gamesObservableList;
    gamesObservableList.clear();
    gamesObservableList = FXCollections.observableArrayList(gameDetails);
    tblPlayerList.setItems(gamesObservableList);

But nothing happens on the screen.
On the server side, I am posting a list of "Players" to any clients. It works, I am receiving the data correctly. All that is a problem is that I cannot understand how to update the TableView since I don't have access to the main UI Thread.

A: In the initialize function of my JavaFX controller, I need to add the following line:
controller_name = this;

And outside the initialize function a declaration of the controller object like:
public static ControllerName controller_name;

So then when the Spring server tries to contact my UI, I can access my UI element through:
controller_name.ui_element_name

Provided that I may have to also use Platform.RunLater to update the UI as it's not on the JavaFX thread.


text:
Q: Global Object name in Javascript I am using an ERP that has the functionality of allowing me to write Javascript in order to control/adjust the flow of events. In my case there is no "window" global object.
I need to use eval() on global scope and I am missing the name of the global object. Is there a way of finding this out?

A:
I need to use eval() on global scope...

If you literally mean you need to eval something at global scope, you can do that with indirect eval:
(0, eval)("your code here");

It looks weird, but it makes eval work in global scope rather than local scope.

var n;    // A global `n`
function direct() {
  var n;

  eval("n = 'a';");
  console.log("Direct:");
  console.log("  local n =  " + n);
  console.log("  global n = " + window.n);
}
function indirect() {
  var n;

  (0, eval)("n = 'b';");
  console.log("Indirect:");
  console.log("  local n =  " + n);
  console.log("  global n = " + window.n);
}
direct();
indirect();

...and I am missing the name of the global object. Is there a way of finding this out?

If you're running your code in loose mode, you can get access to the global object by calling a function, which will run with this referencing the global object. So:
var global = (function() { return this; })();

...gives you a variable called global that references the global object. It doesn't work in strict mode, because in strict mode, this in that function will be undefined.
It's also entirely possible that your code is being called with this already referencing the global object, so you might check that first.


text:
Q: Unfuddle svn access behind a proxy I am using unfuddle to host some private projects, unfuddle is an excellent solution to being able to update and modify my sources through SVN anytime and when I feel like to even when I'm not home.
The problem is at work we are behind a mandatory proxy which I cannot disable, keeping me from accessing my unfuddle repository through SVN.
Is there any solution to this, or is there some free alternative to unfuddle which has not the proxy limitation ? I don't care much about project management and bug  tracking like unfuddle provides, I just want to be able to have access to my source code through SVN anywhere I want to.

A: Many subversion hosters allow connecting to them via HTTPS. In that case the proxy server doesn't see the special subversion commands and usually passes them through transparently as when you would use https for a webserver only.
(I have no experience with unfuddle, but it worked in a few other cases)


text:
Q: What is the Lagrangian for a relativistic charge that includes the self-force? The usual Lagrangian for a relativistically moving charge, as found in most text books, doesn't take into account the self force from it radiating EM energy. So what is the Lagrangian for a relativistic charge that includes the self-force?

A: classical electrodynamics mainly deals with two kinds of proplems: a) The action of a field on a charged particle and b) the fields arising from the motion of such a field. Of course, this can only be approximative but it turns out that a lot of phenomena can be described in this way.
However, you are right, an entire treatment would include a) and b) simultaniously - including the whole dynamics of such a system with radiative reaction (or, the Abraham-Lorentz-Force and its relativistic counterpart).
But as Qmechanic pointed out in a comment, there may be no fully consistent way to do so within the framework of classical electrodynamics. Jackson (Chapter 16) states:

The difficulties presented by this problem touch one of the most fundamental aspects of physics, the nature of an elementary particle. Although partial solutions, workable within limiting areas, can be given, the basic problem remains unsolved.

Thus, you will have to search for a really satisfactory answer within the description of Quantum Electrodynamics. Otherwise, you may include the effect phenomenologically. This was done e.g. by Barone and Mendes in Lagrangian description of the radiation damping (PRA, 2007) and they give a Lagrangian of the form
$$\mathcal{L}=\frac{m}{2}\dot{\mathbf{r}}_1\cdot\dot{\mathbf{r}}_2 - \frac{\gamma}{2}\epsilon\left(\dot{\mathbf{r}}_1,\ddot{\mathbf{r}}_2\right)
-V\left(\mathbf{r}_1,\mathbf{r}_2\right),$$
with $\gamma :=  2e^2/3c^3$, with $\epsilon = \epsilon_{ij}dx^idx^j$ beeing the Levi-Cevita tensor, and the $\mathbf{r}_i$ arise from the special treatment of the problem used in the paper employing some kind of image phase-space representation of the system. Furthermore, $V\,$ is the potential related to the Abraham–Lorentz–Dirac-Force which is given explicitely in the paper.

A: It is the usual CED Lagrangian for a charge and electromagnetic field; it includes the free field Lagrangian, a free particle Lagrangian and the interaction Lagrangian $jA$. Self-action is encoded in it when you consider the system as a whole, as coupled unknown variables. Of course, it yields rubbish: an infinite "electromagnetic mass" that you need to discard.
I say "rubbish" because, on one hand, we define the charge as a stable, fixed entity; on the other hand we introduce a self-force to get some dynamics due to it. Our definition contradicts our intentions.
EDIT: The infinite "electromagnetic mass" in the charge equation takes simply into account the self-induction effect that prevents the charge from accelerating ;-)

A: Solving both, Lorentz force and Maxwell's equation, does include radiation reaction. Radiation reaction emerges from the interaction of the charge with the field it has emitted itself, the self-field. If you do not want to solve Maxwell's equations and treat the fields as external, you can use Lorentz-Abraham-Dirac equation with some known inconsistencies for unphysical initial conditions, or the Landau-Lifshitz equation as approximation. Some authors claim that Landau-Lifshitz equation is not an approximation but agrees with solutions Lorentz-Abraham-Dirac equation for physical initial conditions. Lorentz-Abraham-Dirac and Landau-Lifshitz equations cannot be derived from Hamilton's principle because radiation emission is a dissipative process. For a pedagogical review see http://arxiv.org/abs/gr-qc/9912045.

A: I would say that it is already in the Lagrangian, problem being: in the classical ED lagrangian you describe point-like particles, and the self interaction is classically described as the classical lorentz force a charge creates on itself if it is a sphere-like particle, considering retarded potentials. A classical solution would be to include the shape in the lagrangian, but the lagrangian is local, so it deals with points. If someone talks to you about QED, it is because classically you reach the conclusion that the reaction creates a mass like term opposing acceleration, and this mass can become infinite, in QED you also have some infinites, but you can remove them. Nonetheless I would say you remove it because what actually interests QED is the measure you make, and you never really reach the size of a point while measuring, but it might be an over interpretation.
BUT I have a good news for you there exists a classical formulation that includes the retroaction, to the expense of retrocausality, or waves flowing backward in time, or a kind of action at a distance: it is the lagrangian you can find in the Feynman-Wheeler absorber theory. very interesting but Feynman abandoned it.

A: If the charge is point-like then its classical self-energy is infinite. As the self-force comes from the gradient of potentials, the result is undetermined.
Consider a theory with a local interaction. Then we must take into account some field, e.g. the electromagnetic field. Now for a massive relativistic particle moving at constant velocity there is always an inertial frame of reference where the particle is not moving. Therefore the magnetic field vanishes and the electric field is that given by Coulomb's law, i.e.
$$\mathbf E(\mathbf r)=\frac q{4\pi\epsilon}\frac{\mathbf r}{\Vert \mathbf r\Vert^3}.$$
Since the particle stays at $\mathbf r=0$, the force is undefined.
So far the only massless particle known is the photon, which is neutral.


text:
Q: Possible to implement is_pod type trait in C++03 using SFINAE? According to "Which <type_traits> cannot be implemented without compiler hooks?", it's not possible to implement is_pod in C++03 without compiler intrinsics.  I thought of a possible way, though: C++03 does not allow unions that have members with a nontrivial constructor.  Is it possible to use SFINAE to detect this without throwing a compiler error?
I tried the following and many variants, and couldn't get it to work.  It always either throws an error or returns invalid answers.
#include <cstdio>

template <typename T>
class is_pod
{
  template <typename U, void (U::*)()> struct Check;
  template <typename U> union Union { U u; void member(); };
  template <typename U> static char func(Check<Union<U>, &Union<U>::member> *);
  template <typename U> static char (&func(...))[2];
public:
  enum { value = sizeof(func<T>(0)) == sizeof(char) };
};

struct Meow { };

struct Purr { Purr() { } };

int main()
{
  std::printf("%d\n", is_pod<Meow>::value);
  std::printf("%d\n", is_pod<Purr>::value);
  return 0;
}


text:
Q: PreparedStatement not putting arguments I am having problems running this code using PreparedStatement on my MySQL server. It has been doing np before, when I had a standart Statement included. Mind: this is a test program, I am only learning this stuff. The code is:
PreparedStatement st = null;
try {
    int id = registry.newID("ID");
    if (id == 0) {
        out.println("Failed to generate a new ID. Terminating dialogue.");
        return;
    }
    String insert = "INSERT INTO registry (ID, NAME, SURNAME, DATE_OF_BIRTH, CITY, STREET) "
        + "VALUES (?, ?, ?, ?, ?, ?);";
    st = registry.getConn().prepareStatement(insert);
    st.setInt(1, id);
    st.setString(2, name);
    st.setString(3, surname);
    st.setDate(4, date);
    st.setString(5, city);
    st.setString(6, street);
    st.executeUpdate(insert);
    registry.getConn().commit();
    out.println("Added. Add a number? [y/n] ");
    char choice = in.next().charAt(0);
    if (choice == 'y') {
        addNumber(id, registry);
    }
    st.close();
} catch (SQLException ex) {
    out.println("SQL Exception: " + ex);
}

with params being the following:
int id;
String name, surname, city, street;
java.sql.Date date;

This gives me the following exception:

SQL Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?, ?, ?, ?, ?, ?)' at line 1

Why aren't the values set in the st.setXXXX statements?
Thanks

A: Here's the problem:
st.executeUpdate(insert);

So, instead of PreparedStatement.executeUpdate you call Statement.executeUpdate(String sql) and pass insert statement with question marks.
Try to change this line to:
st.executeUpdate();

A: The problem is with SQL syntax. I suspect the semicolon at the end of the SQL statement. It does not belong there - you probably copied it form some other tool where you tested your query.


text:
Q: Trigonometric position function and intersection I have the following position function for a point:
$x(t) := C_x - (S_x-C_x) \cdot \cos(t\cdot\theta) + (S_y-C_y) \cdot \sin(t\cdot\theta) + t \cdot v_x$
$y(t) := C_y - (S_x-C_x) \cdot \sin(t\cdot\theta) - (S_y-C_y) \cdot \cos(t\cdot\theta) + t \cdot v_y$
These functions calculate the x and y coordinates for a point $S$ at time $0.0 \leq t \leq 1.0$, which is rotating around a center $C$ and moving by a vector $\overrightarrow{v}$.
I would now like to calculate the intersection of this movement with a static line described by $y := m \cdot x + c$
This means, which values for t satisfy the equation $y(t) = m \cdot x(t) + c$
Is there an algebraic solution for this (at least I couldn't find one because of the trigonometric functions)? Or does it only have a numerical solution?
In the latter case, the equation could be changed to:
$f(t) := y(t) - m \cdot x(t) - c$
The solutions are then all values t for which $f(t) = 0$
and be numerically solved with newtons method. The problem here is to find good start values and how to make sure, that all values have been found. Depending on the vector $v$ there may be an arbitrary number of solutions (but it should be possible to calculate the upper limit: $\left \lfloor{\frac{t \cdot \theta}{2\cdot\pi}}\right \rfloor + 2$).
Is there an error in my thoughts? Any suggestions on this?

A: Your setup is highly overloaded. What we see is a cycloid $\gamma$ and an extra line $\ell$. Kinematically $\gamma$ is the superposition of a circular motion having radius $R:=|S-C|$ and a forward motion in direction $\vec v$.
If $\ell$ is parallel to $\vec v$ the set $\gamma\cap\ell$ is either empty, or consists of infinitely many points which repeat periodically along the direction $\vec v$. This case should not be too difficult.
If $\ell$ is not parallel to $\vec v$ the line $\ell$ will intersect the trace  $t\mapsto c(t)$  of the center of the circular motion in a point $O$. Choose this point as origin of your coordinate system, assume that the origin of time is chosen such that $c(0)=O$, and choose the $x$-axis in the direction of $\vec v$. If the rotation is counterclockwise the cycloid $\gamma$ then appears as
$$\eqalign{x(t)&=R\cos(t+\alpha)+ v t\cr
y(t)&=R\sin(t+\alpha)\cr}$$
with a certain $\alpha\in[0,2\pi[\ $, and $\ell$ assumes the form $y=mx$, see the figure below. The number of  points $p\in\ell\cap\gamma$ is finite, and gets smaller when $|m|$ gets larger. Since all these points have a $y$-coordinate of absolute value $\leq R$ their $x$-coordinate is $\leq R/|m|$, and this bounds the $t$-range in which such points should be sought.


text:
Q: How small would an electron have to be in order to become a black hole? According to quantum mechanics electrons don't behave like everyday objects. Would this prevent the formation of a black hole? If so why?
Also, assuming they behave like everyday objects, at what size would they become a black hole?
I ask because according to various sources an electron could be a point, have a 'classical electron radius' of $10^{-15}$ m, or a diameter of planck's length ($10^{-35}$), and it seems to me that even though an electron has very little mass having no size would make it immeasurably dense.
Edit: Here's a wikipedia page I found that directly answers this question (Black hole electron - http://en.wikipedia.org/wiki/Black_hole_electron).

A: The rest mass of an electron is estimated to be about 9.1 * 10^-31 Kg.  The Schwarzschild radius defines the maximum size sphere which any mass may occupy in order to be a black hole. The Schwarzschild radius for an object with the rest mass of an electron would be about 1.4 * 10^-58 meters.
But the Planck length is about 1.6 * 10^-35 meters.  Quantum gravity becomes important in understanding what happens at this scale.  As there currently is not a generally accepted theory of quantum gravity, and as the Schwarzschild radius for an electron is significantly smaller than the Planck length, it's uncertain that General Relativity, which predicts and describes black holes, would apply.  So I don't think that one can predict an object with the mass of an electron would ever become a black hole.


text:
Q: Infinite staircase where each step is a 1 ohm resistor There is an infinite staircase where each step is a 1 ohm resistor. How do you  calculate the equivalent resistance between any of the two points on the staircase?

A: it depends on how you connect the resistors
if you arrange them in a grid, where they connect both going sideways along the stairs and up/down the stairs, then I think it would tend towards zero
but if you have separate lines of resistors going up/down the stairs then it should be infinite?

A: If you're considering the following:

then the resistance between the ends is $1 + \frac{1}{2} + \frac{1}{3} + \cdots $ which doesn't converge.

A: I'm imagining this infinte staircase:
         +--+ -->
         |  |
      +--+--+
      |  |  |
   +--+--+--+
   |  |  |  |
+--+--+--+--+ -->
|           |
V           V

If the staircase has infinite underfill, by symmetry, the resistance of two points on the edge will be twice that between the same two points on the infinite resistor grid plane.


text:
Q: I wrote a ramp function but it's work wrong in some cases I'm new to Matlab and I faced this problem:
I wrote a ramp function , it is work correctly if I plot ramp(t-1),ramp(t-2),ramp(t-3)....
but it doesn't work when I'm trying to plot ramp(t),ramp(t+1),ramp(t+2)....
here is my code:
    function [ y ] = ramp(x)
    y(x<0)=0;
    s = (abs(x(length(x)))+abs(x(1)))/length(x);% x(2)-x(1) or x(i)-x(i-1), EX:{1,1.2,1.4}s=0.2
    y(x>=0)= 0:s:x(length(x));

    end

A: I can't see reproduce any errors using your code, but here is a different way of doing the same thing.
function [ y ] = ramp(x)
    y=zeros(size(x));
    y(x>=0)=linspace(0,x(end),length(x(x>=0)))
end


text:
Q: Saving nested model laravel in one go I have create two tables
AREAS
-id
-areaName

SOCIETIES
-id
-area_id
-societyName

My relationship is defined like this
class Area extends Model
{
    //
    public function society()
    {
        return $this->hasMany('App\Society');
    }
}

class Society extends Model
{
    public function area()
    {
        return $this->belongsTo('App\Area');
    }
}

Now I have created objects for both area and society
$area = new \App\Area();
$area->areaName = $input['areaName'];

$society = new \App\Society();
$society->societyName = $input['societyName'];

$society->area()->associate($area);

After this when I call "$society->save()" its not saving any record and giving error area_id cannot be null. I want to save society and its relation area in one go.
When I use "$area->save()" before associate its saving the record when calling "$society->save()". All I want to do is skip "$area->save()" and save both society and area in one go.

A: It is giving you the error because you don't have a record in the database with an id for it. You need to save the area record first and then associate it with the relation. I don't think it will work other wise, take a look at eloquent docs on laravel's website:
https://laravel.com/docs/5.1/eloquent-relationships


text:
Q: tx_news category menu doesnt filter news- TYPO3 I need to configure a news category menu in my site. I list all news in one column and the other column in the same page shows the category menu. News list and category menu is configured using plugin not by TypoScript. The same page contain another news listing for another purpose.
The problem is the news doesn't get filterd by category.

A: First you set set the page properties to "No Cache" to make sure, caching is not the problem. If caching can be exluded as the problem, please check your list plugin settings -> second tab -> last option "Disable override demand" should NOT be checked.

A: another prerequisite is that you have to set the Category mode of the list plugin to "Show items with selected categories (OR)". But don't select any categories then. from – mtness


text:
Q: Apache Beam Java ElasticsearchIO error for AWS OpenSearch I'm trying to deploy an Apache Beam batch processing pipeline in a GCP project. My pipeline will read from an Elasticsearch cluster in AWS OpenSearch.
Here's my code that I've written for doing the same:
        ElasticSearchOptions options = PipelineOptionsFactory.fromArgs(args).withValidation()
                .as(ElasticSearchOptions.class);

        Pipeline pipeline = Pipeline.create(options);

        options.setAwsCredentialsProvider(
                new AWSStaticCredentialsProvider(new BasicAWSCredentials(
                        options.getAwsAccessKey(),
                        options.getAwsSecretKey()
                )
            )
        );
        options.setAwsRegion("us-east-1");

        PCollection<String> output =
            pipeline.apply(
                    ElasticsearchIO.read().withConnectionConfiguration(
                            ElasticsearchIO.ConnectionConfiguration.create(
                                    <hostName>,
                                    options.getElasticSearchIndex(),
                                    options.getElasticSearchType()
                                    )
                    )
                .withQuery("field_name:some-value")
            );

I'm getting an error
403: User anonymous is not authorized to perform: es:ESHTTPGet

To understand this error better, I printed the AWS secret and access key from my worker node to ensure that the values passed were getting processed properly. And it is!
I'm stuck at this point. How do I authorize myself with my AWS credentials (access and secret key) and sign my requests for the Elasticsearch Read operator?

A: I may guess that ElasticsearchIO knows nothing about AWS credentials and AwsCredentialsProvider that you set before and it uses only an instance of ConnectionConfiguration, which you pass to .withConnectionConfiguration(), to connect to cluster.
So, you may try to set your username/password by ConnectionConfiguration withUsername(String) and ConnectionConfiguration withPassword(String) if they are the same as AWS credentials (tbh, I don't know how Elasticsearch authentication works with AWS OpenSearch).


text:
Q: Documentation on https://www.dropbox.com/1/connect?k=XXXXX i have encountered several apps using https://www.dropbox.com/1/connect?k=XXXXX url to request authorisation to their apps but I can't find official documentation on the dropbox site... on dropbox... they have documentation on oauth authentication where you must request authorisation code and then fetch your token but it requires that you have an ssl website
Any idea how to use https://www.dropbox.com/1/connect?k=XXXXX instead?

A: All of Dropbox's mobile SDKs use this endpoint, but if you're not using one of those SDKs, I definitely recommend just using the documented OAuth endpoints.
If you're building a mobile app, I recommend using a scheme like db-<APP_KEY>:// for a redirect URI, just as the mobile SDKs do. There's no need to redirect to a website; you can just redirect back to your app.
It may be worth reading the code for the Android or iOS SDKs to see how they do authorization before building your own implementation.
EDIT: It occurs to me that you might not be building a mobile app at all. If that's the case, a little more context about what you're building might help.


text:
Q: Applying display properties similar to using ApplySymbologyFromLayer tool in ModelBuilder? I have created a layer file using ArcGIS 10.3 ModelBuilder.
I have applied symbology to this layer using the ApplySymbologyFromLayer tool in ModelBuilder.
The tool applied the symbology to my created file, but it did not transfer over the display properties (the options found under the 'Display' tab within Layer properties).
In particular, I wanted the selected resampling method (bilinear) from the source layer (the one whose symbology was copied) to be applied to the ModelBuilder layer file the way the symbology was applied. The model actually creates a different layer for each iterated value, so I'd rather not do it manually for each output.
Is there a way to apply source layer display properties to a newly created layer using ArcGIS 10.3 ModelBuilder?

A: I'm not sure you can do that within ModelBuilder.  A bit of arcpy may be able to do it, but probably easier would be to change your ArcGIS defaults using AdvancedArcMapSettings.
On my PC it's found at C:\Program Files (x86)\ArcGIS\Desktop10.4\Utilities - I believe it's in matching folder path in other versions (Desktop10.3, Desktop10.2 etc.)
Select Bilinear Interpolation as your Default resampling mode and hit Apply.


text:
Q: What is the difference between URI and Uri class I am confused , how to use Uri because i am using it in android development at Intent's Action dial
Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:555-2368"));

What I want to do :
I want to create a file inside which I want to put 2 phone numbers. Then, I want to use toUri() method  with this file, and want to put that Uri in the intent, then I want to see what happens with the intent.

A: According to the Android API docs you can create a file Uri with:
public static Uri fromFile (File file)

A: java.net.URI is mutable
android.net.Uri is immutable
java.net.URI
A Uniform Resource Identifier that identifies an abstract or physical resource, as specified by RFC 2396.
android.net.Uri
      . A URI reference includes a URI and a fragment, the component of the URI following a '#'. Builds and parses URI references which conform to RFC 2396.
In the interest of performance, this class performs little to no validation. Behavior is undefined for invalid input. This class is very forgiving--in the face of invalid input, it will return garbage rather than throw an exception unless otherwise specified.

A: URIs identify and URLs locate; however, locations are also identifications,
so every URL is also a URI, but there are URIs which are not URLs.
URL - http://example.com/some/page.html
URI - /some/page.html


text:
Q: Failed to execute db.system.keys.find() via root, how can this collection be find()? MongoDB version is 4.0.3
Root user has been created via
db.createUser({user:"root",pwd:"arthur",roles:[{role:"root",db:"admin"}]})

Via listCollections or db.getCollectionInfos(), three collections as list,
system.users
system.version
system.keys

'Not authorized' info would be shown when find() on system.keys. And another two collections are without any error.
I'm not sure anything missing/wrong for user creation or others. How can I handle this error. Look forward to your help.
How can I get details about this collection
which is not mentioned in document
https://docs.mongodb.com/manual/reference/system-collections/
Console print as below
MongoDB Enterprise mongos> use admin
switched to db admin
MongoDB Enterprise mongos> db.auth("root","arthur")
1
MongoDB Enterprise mongos> db.runCommand( { listCollections: 1.0, authorizedCollections: true, nameOnly: true } )
{
    "cursor" : {
        "id" : NumberLong(0),
        "ns" : "admin.$cmd.listCollections",
        "firstBatch" : [ ]
    },
    "ok" : 1,
    "operationTime" : Timestamp(1541747273, 1),
    "$clusterTime" : {
        "clusterTime" : Timestamp(1541747273, 1),
        "signature" : {
            "hash" : BinData(0,"FnDH1ejRM/2TfV+0WiPFqH0KIMk="),
            "keyId" : NumberLong("6621746286506803230")
        }
    }
}
MongoDB Enterprise mongos> db.runCommand( { listCollections: 1.0, nameOnly: true } )
{
    "cursor" : {
        "id" : NumberLong(0),
        "ns" : "admin.$cmd.listCollections",
        "firstBatch" : [
            {
                "name" : "system.users",
                "type" : "collection"
            },
            {
                "name" : "system.version",
                "type" : "collection"
            },
            {
                "name" : "system.keys",
                "type" : "collection"
            }
        ]
    },
    "ok" : 1,
    "operationTime" : Timestamp(1541747273, 1),
    "$clusterTime" : {
        "clusterTime" : Timestamp(1541747273, 1),
        "signature" : {
            "hash" : BinData(0,"FnDH1ejRM/2TfV+0WiPFqH0KIMk="),
            "keyId" : NumberLong("6621746286506803230")
        }
    }
}
MongoDB Enterprise mongos> db.system.keys.find()
Error: error: {
    "ok" : 0,
    "errmsg" : "not authorized on admin to execute command { find: \"system.keys\", filter: {}, lsid: { id: UUID(\"a7884ca5-0f46-4906-8a15-955bbd74d2ae\") }, $clusterTime: { clusterTime: Timestamp(1541747273, 1), signature: { hash: BinData(0, 1670C7D5E8D133FD937D5FB45A23C5A87D0A20C9), keyId: 6621746286506803230 } }, $db: \"admin\" }",
    "code" : 13,
    "codeName" : "Unauthorized",
    "operationTime" : Timestamp(1541747273, 1),
    "$clusterTime" : {
        "clusterTime" : Timestamp(1541747273, 1),
        "signature" : {
            "hash" : BinData(0,"FnDH1ejRM/2TfV+0WiPFqH0KIMk="),
            "keyId" : NumberLong("6621746286506803230")
        }
    }
}
MongoDB Enterprise mongos>

A: only "backup" and "__system" can operate this table
db.system.keys.find()/count()       <====   "__system" role only
other operations (not verify all)   <====   "backup" and "__system" role

does any one share the detail about this collection.
thanks


text:
Q: Extract msi to Visual Basic.net I was developing a small software and my laptop stolen when I was traveling but I had no backup. At this moment I have only installation file that I make by setup and deployment from visual studio 2015.
I develop this software program using vb.net
Can I extract the installation file to source code ?
I have two files

*

*Microsoft installer I mean msi

*exe

Can anybody help me to extract it?
Thankx in advance


text:
Q: How to ask a http server present a http header field `Content-Length`? I am testing the Last.fm api using row socket interface.
Now i noticed that some of api's http response have not contain a field Content-Length .
But I want to know is there a way to ask the server presenting it?
Because i can't take good care of this in my program elegantly.
Quoth the RFC:
 7.2.2 Length
 When an Entity-Body is included with a message, the length of that body may be determined in one of two ways. If a Content-Length header field is present, its value in bytes represents the length of the Entity-Body. Otherwise, the body length is determined by the closing of the connection by the server.

A: The right RFC to look at is RFC 7230 (Section 3.3.2).
And no, in HTTP/1.1 a client has to be able to process chunked encoding (which would be the only legitimate reason not to provide a Content-Length header field).


text:
Q: How do I either pause, or pass answers to Jenkins execute shell script This is also a bash question. I have a script that when run ./recompile it asks 3 questions, separately, 1 at a time.
The answers are as follows: 1, 1, y.
So I need jenkins to run my script, but to also answer the questions.
Jenkins has this execute shell box, which I take is basically a bash script entry point.
So I have set it to execute my script, but I don't know how to simulate the answers.
I did something like this
./recompile
1
1
y

and
./recompile && 1 && 1 && y

But it says 1 is not a command....
What bash command am I looking for to pass the parameters that will be asked after the script is ran?
EDIT
When the script is run, it should start off like this.
    $ ./recompile

Choose the environment to recompile:  1) Dev  2) Stage  3) Prod ? 1
Use Watch mode?y
Will WATCH after dump completed. Use ctrl+c to exit

You are about to recompile Symfony DEV Environment, please verify the following settings:
------------------------------------------
- DEV
- clear cache
- install assets as symlinks
- watch assets, includes force dumping (use ctrl+c to exit)
Ready to run? y

---------------------------
running

A: You need to redirect STDIN into your script
$ echo "a
> b
> c" | sh a.sh
a
b
c
a  b  c

with this sort of bash script for a.sh
#!/bin/bash

echo "a"
read $a

echo "b"
read $b

echo "c"
read  $c

echo "a ${a} b ${b} c ${c}"


text:
Q: IIS 10 site needing URL Rewrite for changed WordPress subfolder name I have a client with an ASP.NET MVC project running on IIS 10.
In IIS 10 I have an Application setup under the site that points to a WordPress installation folder. The alias was previously oldblog and has now changed to blog.
The WordPress URI was requested to be changed so I need to permanently redirect requests to the old URI to the new one.
Root ASP site: https://www.example.com/
Old WP URI: https://www.example.com/oldblog/
New WP URI: https://www.example.com/blog/
The following rule only partially works. oldblog does get rewritten to blog, but the rest of the URI is unpredictable/inconsistent.
  <rule name="Rewrite /oldblog to /blog" stopProcessing="true">
    <match url="^oldblog(.*)$" ignoreCase="true" />
    <action type="Redirect" url="https://www.example.com/blog/{R:1}" redirectType="Permanent" />
  </rule>

I need to rewrite all requests to /oldblog/* to /blog/* - regardless of the full URI/querystring, I only want to rewrite oldblog to blog
/oldblog/  =>  /blog/
/oldblog/category/somecategory/  =>  /blog/category/somecategory/

A: I would suggest you try to make tests with the URL Rewrite rule below could help you redirect from URLs below.
/oldblog/  =>  /blog/
/oldblog/category/somecategory/  =>  /blog/category/somecategory/

Sample Rule
<rewrite>
            <rules>
                <clear />
            <rule name="Rule-3" enabled="true" stopProcessing="true">
                        <match url="(.*)" />
                            <conditions logicalGrouping="MatchAll" trackAllCaptures="true">
                                <add input="{HTTP_HOST}" pattern="example.com" />
                                <add input="{REQUEST_URI}" pattern="/oldblog(.*)|/oldblog" />
                            </conditions>
                            <action type="Redirect" url="/blog{C:1}" />
                    </rule>
            </rules>
</rewrite>

Test Result

Further, you could modify the rule above as per your own requirements.