text:
Q: ssl handshake issue between GRPC Java client and NodeJS server I am using GRPC (Java client) to connect via SSL to a NodeJS server.  The SSL context I am using is copied below.  I tried running ssldump (on Mac El Capitan OS) to help debug.  I get the following exception on the server when I try to connect and send a message to the server:
chttp2_server.c:123] Handshaking failed: {"created":"@1489433622.628015000","description":"Handshake read failed","file":"../src/core/lib/security/transport/security_handshaker.c","file_line":238,"referenced_errors":[{"created":"@1489433622.628009000","description":"Socket closed","fd":24,"file":"../src/core/lib/iomgr/tcp_posix.c","file_line":249,"target_address":"ipv6:[::1]:60820"}]}

        SslContext sslContext = GrpcSslContexts.forClient()
                .startTls(true)
                .sslProvider(defaultSslProvider())
                .trustManager(publicCert)
                .keyManager(clientCert, clientKey)
               // .ciphers(null)  //testing
                .build();

I just see the following output from the ssldump:
780    1880.8428 (0.0405)  C>S  TCP FIN
780    1880.8433 (0.0005)  S>C  TCP FIN
New TCP connection #1020: localhost(61531) <-> localhost(96758)
1.3625 (1.3625)  C>S
---------------------------------------------------------------
1e 0a 16 08 b9 c6 ed bc b9 9e 84 98 e3 01 10 95    ................
b8 b5 a5 8e 8c c3 bb 91 01 10 02 22 02 08 01       ..........."...
---------------------------------------------------------------

New TCP connection #1021: localhost(61532) <-> localhost(90051)

Any thoughts on how to troubleshoot this any further will be greatly appreciated.

A: I removed the 'usePlaintext(false)' statement which seemed to have been causing the issue.
channelBuilder = NettyChannelBuilder.forAddress(host, port)
                    .overrideAuthority("localhost")
                    .negotiationType(NegotiationType.TLS)
                    **//.usePlaintext(false)**
                    .sslContext(sslContext);


text:
Q: Angular .then() is not working ( is not refreshing view after sending get request) Creating internet shop, and when i manage user cart page Angular is not refreshing view after calling deleteFromCart(), so i need to refresh page. What am I missing ? As I did promise with .then(f()) but it is not working
JS code :
    var url = $location.absUrl() + "/products";

getProducts();
function getProducts() {
    $http.get(url).then(function (response) {
        $scope.total = 0;
        $scope.products = response.data;
        $scope.products.forEach(function (product) {
            $scope.total = $scope.total + product.price;
        })
    });
}

$scope.deleteFromCart = function (productId) {
    $http.get(url + '/' + productId).then(function () {
        getProducts();
    });
}

View :

Your Cart

                Product name
                Price
                Quantity
                Action

                {{product.title}}
                {{product.price}}$
                3

                    Remove

TOTAL : {{total}}$

        <button class="btn btn-success pull-right">Confirm Order</button>

A: Why do you want to refresh the page just remove that product from the list

    Remove

$scope.deleteFromCart = function (productId,index) {
    $http.get(url + '/' + productId).then(function () {
         $scope.products.splice(index,1);
    });
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: OnClick Sound breaks off after a few of clicks When i click on my display, the onClick sound comes per click 1 time. So when i click about 50 times the sound does not come anymore..
if (smaragt.getTag(R.id.artsmaragt) == BLAU) {
        final MediaPlayer coin2 = MediaPlayer.create(this, R.raw.coin1);
        coin2.start();
        punkte += 5;
    }

can someone help me ? I have no idea why

A: Don't create a new MediaPlayer each time.  That's expensive and likely your problem.  Create a media player once, and just play it every time the button is clicked.

A: You should not be creating too many instances of MediaPlayer and not release them. Just create one instance of MediaPlayer outside of this condition and use only coin2.start() to play sound.


text:
Q: How to paginate data from multiple Firestore collections in Flutter? I want to create a screen in my Flutter app to display all financing details that relate to a specific user. Each kind of financial entry has its own collection on Firestore.
To elaborate more, I have a purchases collection and a transactions collection. A user should be able to see both of these collections together in a single view sorted by date or money-spent, which means (I think) I have to "join" these two collections (like in SQL) and display the result.
The question now remains how can I paginate this data? As far as I know, I can't "join" collections in Firestore, and as far as I have searched I can't really paginate data from multiple collections simultaneously.

A: If you want to show a paginated view of the data from two collections, you will need to load the full page of data from both collections, merge them in your application code, and discard any data that is more than the page size you want to show.
In cases like this always consider whether you can instead create an additional collection where you store the data from both collections, and read from there. While data duplication is frowned upon in relational data modeling, it is very common in NoSQL databases.
To learn more about the topic, I recommend reading NoSQL data modeling and then watching Todd's excellent Getting to know Cloud Firestore.


text:
Q: Drawing a line in html I'm quite new to HTML and I need to make a website for my school. For aesthetic purposes I want to put in a line between two bits of text, but when I try to, it just shows the code where I'm trying to put the line. This is the code:
CSS:
hr {
    display: block;
    height: 1px;
    border: 0;
    border-top: 1px solid #ccc;
    margin: 1em 0;
    padding: 0;
}

With the following HTML:

            WE'VE BEEN BUSY

hr { display: block; height: 1px; border: 0; border-top: 1px solid #ccc; margin: 1em 0; padding: 0; }

            CHECK IT OUT!

And this is what happens when I look at the page

What am I doing wrong?

A: If you want to format the line, you will have to put your code up there ^ in a


text:
Q: Reduce Application size when using NDK I am using cropping library which include ABI filters so when I generate apk or bundle its size is to much unto 308Mb so is there any way to reduce apk size without using ABi Filters.
this is my Gradle default config.
    defaultConfig {
        applicationId "com.document.scanner.fast.scan.pdf.create.pdf.test" //com.document.scanner.fast.scan.pdf.create.pdf.editor //com.document.scanner.fast.scan.pdf.create.pdf.test
        minSdkVersion 23
        targetSdkVersion 30
        versionCode 1
        versionName "1.0.0"

        ndk {
            abiFilters "armeabi-v7a"
        }
//        splits { //Working But Not on Xiaomi
//            abi {
//                enable true
//                reset()
//                include 'armeabi-v7a', 'arm64_v8a'
//                universalApk false
//            }
//        }

        resConfigs "en"

    }

A: I used to face this problem, after a while looking for a solution, only using the API filter.
And I use this because it supports most new devices nowadays
ndk {
    abiFilters 'arm64-v8a', 'armeabi-v7a'
}


text:
Q: How to Sign a PDF File using Field Locators using Java including its necessary jar (i.e. java packages)? I am having a C# code for signing a PDF file using Field Locator in the given link
http://developer.arx.com/examples/sapi-local-csharp-signing-a-pdf-file-using-field-locators/
I need Java compatible code and its necessary java packages to achieve the same. Also you can have a look into my previous question How to change the coordinates of Signature in CoSign Signature SOAP API and place it over some given text (i.e. Sign Here)? querying the same.

A: A code example in Java that demonstrates how to use the Field Locators with SAPI Web Services is now available in the CoSign DevPortal.


text:
Q: How to create a simple java load balancer with sockets? Running a UDP Sever listening to multiple ports as simple as this
ExecutorService executorService = Executors.newFixedThreadPool(2);
executorService.execute(new UDPServer(9998));
executorService.execute(new UDPServer(9999));
// UDP server implementation
try (DatagramSocket socket = new DatagramSocket(port)) {
    System.out.println("Plain UDP server :" + this.port + " name :" + Thread.currentThread().getName());
    int numberOfPacketsReceived = 0;
    while (true) {
        // todo check to stop the server
        byte[] buffer = new byte[1024];
        DatagramPacket incomingDatagramPacket = new DatagramPacket(buffer, buffer.length);
        try {
            socket.receive(incomingDatagramPacket);
            System.out.println(Thread.currentThread().getName() + ":" + numberOfPacketsReceived++);
        } catch (IOException e) {
            e.printStackTrace();
            continue;
        }
    }
} catch (SocketException e) {
    e.printStackTrace();
}

Can we create a load balancer programatically listening to the port
 9997 and forwarding the packet to port 9999/9998 alternatively ?
Can we even redirect the traffic received in one UDP socket to another
 another socket ?

A: You would be better off having the workers take from a blocking queue, and having a third thread that just read in packets and put them on the queue for computing the values.
You could redirect the packets to another socket, but this would have unnecessary overhead within the same program, and you would lose the packet metadata.
If you wish to use a load balancer you could implement the load balancer like this:
class C {
  public static void main(final String... args) {
    try (DatagramSocket socket = new DatagramSocket(9997);
         DatagramSocket out = new DatagramSocket()) {

      final InetSocketAddress[] sockets = {
          new InetSocketAddress("localhost", 9998),
          new InetSocketAddress("localhost", 9999)
      };

      int i = 0;
      while (true) {
      // todo check to stop the server
        byte[] buffer = new byte[1024];
        DatagramPacket incomingDatagramPacket = new DatagramPacket(buffer, buffer.length);
        try {
          socket.receive(incomingDatagramPacket);
          incomingDatagramPacket.setSocketAddress(sockets[i++%2]);
          out.send(incomingDatagramPacket);
        } catch (IOException e) {
          e.printStackTrace();
          continue;
        }
      }
    } catch (SocketException e) {
      e.printStackTrace();
    }
  }
}


text:
Q: Issue centering a div between two floats I found a solution on this site to center a div between two floats . The solution works fine except that I have a double border now.
CSS
.trilink_container {
margin:5px;
overflow: hidden; /* contain floated elements */
}

.trilink_all {
border: 1px solid #CCCCCC;
color: #444444;
text-shadow: 0 1px 1px #F6F6F6;
background: #fdfdfd;
background: -o-linear-gradient(top,  #fdfdfd,  #eee);
background: -ms-linear-gradient(top,  #fdfdfd,  #eee);
background: -moz-linear-gradient(top,  #fdfdfd,  #eee);
background: -webkit-gradient(linear,  left top,  left bottom,  color-stop(0,  #fdfdfd),  color-stop(1,  #eee));
background: -webkit-linear-gradient(#fdfdfd,  #eee);
background: linear-gradient(top,  #fdfdfd,  #eee);
text-align:center;
 }

.trilink_item {
float: left;
width: 32%;
margin-left:5px;
}

.trilink_right {
float: right;
width: 32%;
margin-right:5px;
}

.trilink_center {
margin-left: auto;
margin-right: auto;
}

HTML

Left Test

Right Text

Centre Text

I've also added the code to jfiddle.
BTW, I realise my coding is a bit messy and intend to tidy it up once I have a solution :)
Any ideas?

A: Add overflow: hidden (or auto; anything but visible) to the .trilink_center and you will get what you want I believe (see this fiddle).
This establishes a new block formatting context which changes how the flow works. See this article for some discussion.

A: If you want to remove double border then just remove margin from left and right divs
.trilink_item {
    float: left;
    width: 32%;
    //margin-left:5px; remove it
    }

.trilink_right {
    float: right;
    width: 32%;
    //margin-right:5px; remove it
    }

JS Fiddle Example

A: try this fiddle if you want to eliminate the double border near the edges. It removes border-left and border-right for left and right divs respectively

A: `.trilink_center {
 margin-left: auto;
 margin-right: auto;
 /* float left or right
 float: left;

}`
and that's all


text:
Q: Search for square brackets in NSString I have some text loaded into NSString objects which contains annotations in square brackets - I need to strip the square brackets and everything within them so the user is only presented with the body text.
However, because of the reliance of Objective-C on square brackets for messaging etc..., I'm having a bit of a problem removing them.
Is there some special escape character for using square brackets (for example as an argument to 'rangeOfString:')? Xcode repeatedly informs me that there isn't.
Cheers

A: You can use regular expressions to remove substrings you want:
NSString *s = @"hi[bla]tototo[lalA123]a";
NSString *result = [s stringByReplacingOccurrencesOfString:@"\\[[\\w]+\\]"
                                                withString:@""
                                                   options:NSRegularExpressionSearch|NSCaseInsensitiveSearch
                                                     range:NSMakeRange(0, [s length])];
NSLog(@"%@", result);
// output "hitototoa"

P.S. You may need to adjust regexp pattern if your annotations may contain characters that not match '\w' specifier

A: You mean like @"[" and @"]" ?
Any string in Objective-C must be between @" and ".

A: I think Vladimir's regex-based answer is fine, but I wanted to address the point about using rangeOfString because OP sounds very confused.  There's no problem using square brackets inside NSStrings, and this has nothing to do with Objective C's use of square brackets for messaging.
This works fine for me:
NSString * a = @"Some [thing] here";
NSRange rangeOpen = [a rangeOfString:@"["];
NSRange rangeClose = [a rangeOfString:@"]"];
NSLog(@"%lu %lu, %lu %lu.",
      (unsigned long)rangeOpen.location,
      (unsigned long)rangeOpen.length,
      (unsigned long)rangeClose.location,
      (unsigned long)rangeClose.length);
# Logs "5 1, 11 1."


text:
Q: PostgreSQL function that returns a 'casted' complex type from query I tried to define a PostgreSQL function that returns a complex type from a query via:
CREATE TYPE last_contract AS (
    contract_id bigint,
    contract_date timestamp
);

and
CREATE OR REPLACE FUNCTION delivery_last_contract(delivery bigint) RETURNS last_contract AS $func$
DECLARE ret last_contract;
BEGIN

    SELECT DISTINCT ON (tdf.delivery_id) ROW(tcf.contract_id, tcf.date)::last_contract INTO ret
        FROM task_delivery_fetch tdf
        INNER JOIN task_contract_fetch tcf ON tcf.fetch_id = tdf.fetch_id
        WHERE tdf.delivery_id = delivery
        ORDER BY tdf.delivery_id, tcf.contract_id DESC
        LIMIT 1;

    RETURN ret;

END;
$func$ LANGUAGE plpgsql;

sadly, all I get is an error:
SELECT delivery_last_contract(12197);
ERROR:  invalid input syntax for integer: "(13605,"2016-12-06 00:00:00+01")"
CONTEXT:  PL/pgSQL function delivery_last_contract(bigint) line 5 at SQL statement

Isn't there a way to actually return a single complex type returned from a query?

A: CREATE OR REPLACE FUNCTION delivery_last_contract(delivery bigint)
                   RETURNS last_contract AS $func$
  DECLARE ret last_contract;
  BEGIN
    SELECT tcf.contract_id, tcf.date
      INTO ret
      FROM task_delivery_fetch tdf
      INNER JOIN task_contract_fetch tcf ON tcf.fetch_id = tdf.fetch_id
     WHERE tdf.delivery_id = delivery
     ORDER BY tdf.delivery_id, tcf.contract_id DESC
     LIMIT 1;
    RETURN ret;
  END;
$func$ LANGUAGE plpgsql;

works. Simpler is better.


text:
Q: How to get the quote address object when user logged in? One particular user logged in to his account from frontend and adds some items to the shopping cart. And then he logged out. And again when he logged in I want to get his quote address object.
How to achieve this? Is there any event which fires and I can get the quote address object? Any suggestions will be appreciated.

A: To get a customer's default billing adress you can do the following:
<?php
$customerId = Mage::getSingleton('customer/session')->getCustomer()->getId();
$visitorData = Mage::getModel('customer/customer')->load($customerId);
$billingaddress = Mage::getModel('customer/address')->load($visitorData->default_billing);
$addressdata = $billingaddress ->getData();
$addressdata['street'];
$addressdata['city'];
$addressdata['postcode'];
$addressdata['region'];
$addressdata['telephone'];

var_dump($addressdata);

A: What you can do is listen to customer_customer_authenticated then get the quote_address:
$quote = Mage::getResourceModel('sales/quote_collection')
    ->addAttributeToFilter('customer_id', $customer->getId())
    ->addAttributeToFilter('is_active', 1)
    ->getFirstItem();

if($quote) {
    $quote->getBillingAddress(); // quote billing address object
    $quote->getShippingAddress(); // quote shipping address object
}

if you are using the multi checkout you want to use getAllShippingAddresses() and maybe the method getAllAddresses() on $quote is interesting for you.


text:
Q: Top N in View or Crystal Reports? I am wondering if it's possible to use a view to get the top 5 lines from a table.
I am finding that Crystal reports doesn't seem to have anything built in to do this, or I'd do it there.
When I query the view Select * from qryTranHistory, it returns the first 5 items, but if I try to select a specific type Select * from qryTranHistory Where tID = 45 it returns nothing, since there are no tID=45 in the top 5 normally.
Is it possible to do this?
Can it be accomplished in a sub report in Crystal Reports?

A: It is easy to limit a report to the top 5 records.  In the menu, just choose
Report --> Selection Formulas... --> Group
In the formula, enter "RecordNumber <= 5" and you are done.
You don't need to have a group field nor summary field to do the group filter.  You don't need a sort order, but using top N records without a sort order doesn't usually make much sense.  It might not be efficient as OMG Ponies suggested, but for small number of records it is OK.

A: You can reference a sproc from Crystal Reports. In the sproc, use a conditional on the parameter.

ALTER PROCEDURE dbo.Get_TOP5
    (
    @tID INT = NULL
    )
AS
IF @tID IS NULL
    BEGIN
        SELECT TOP 5
            FIELD1,
            FIELD2

        FROM qryTranHistory
    END
ELSE
    BEGIN
        SELECT
            FIELD1,
            FIELD2

        FROM qryTranHistory

        WHERE tID =@tID
    END

A: A simple setting can limit the records to top 5!! Here it is, if you're using .Net 1.1 (similar arrangement of options in higher frameworks too!).

*

*Right click on the report layout > Reports > Top N/Sort Group Expert > Choose Top N in the Dropdown that asks for the type of filtering/ sorting you wish to do > Set the Value of top N (5 in your case) > Uncheck the option that includes other records.
Your report will be filtered for only the top 5 records from the Dataset.

There's another way how it could be done and that is through the Record selection formula where you limit the No. of records, as suggested by John Price in this thread.
Cheers!

A: Can you put the TOP in your SELECT statement instead of in the view?
SELECT TOP 5
    col1,
    col2,
    ...
FROM
    qryTranHistory
WHERE
    tid = 45

A: If your table has more then 5 rows I hope this query:
SELECT * FROM qryTranHistory

Returns more then 5 rows because you never mentioned TOP 5.
Your question doesn't make a lot of sense as I am not sure waht you are after.
You mentioned if you ran your query with WHERE tID=45, it returns nothing, what exactly do you want it to return ?
Read up on TOP in BOL:
SELECT TOP 10 Recs FROM Records WHERE...

By the way you do not want to do this in the report / a form interface, you want to do this in your db layer.

A: You can do Top N processing in Crystal Reports, but it's a little obscure - you have to use the group sort expert (and in order to use that, you need to have groups and summary fields inserted into the groups.)
Doing the Top N processing in the query should be more efficient, where possible.

A: If you have a small recordset, you can create a running total that counts the change of rows (field1), then in Section Expert in Details, tell it to supress RTotal0 (your running total variable) to > 5


text:
Q: struts 1.3 tiles with Display Tag Let me explain the problem in very simple manner,
In my app, I've a JSP which contains 2 tiles.

*

*Tile 1 is a jsp containing Search Form. Suppose it has only one search parameter that is set into ActionForm on submit action.

*Tile 2 is containing the
DisplayTag showing all results which were stored in session
attribute (After we press submit form of Tile 1).

Now 1st page of display Table is working fine. But when I click on another page links (i.e. 2,3,Last) it loads the blank page. Problem is, Search param is not accessible from here so it can not be appended behind the requestURI. (Definitely, I return the zero records when no conditions appended on sql query.)
So question is, how can I access the property of another JSP (My search form - another tile) ?
My proposed solutions (but I am not satisfied):

*

*I can put my Display Tag code into the same Tile of search form.
Works fine. But I want separation.

*I can use hidden params into Tile 2. But it may result in duplicate params same as Tile 1.

Please let me know about some efficient solution as I am new with Struts Tiles concept.

A: Display tags works with form scope session.
Put the form that you are using to display the data in table in session scope.


text:
Q: Delete particular data in mongodb using node js How can I delete particular data in mongodb using node.js ?
router.post('/deletedata', (req, res) => {
console.log("deleted values are",req.body.id)
    MongoClient.connect(url, function(err, db) {
        if (err) throw err;
         var dbo = db.db("mohan");
         var myquery = req.body.id;
         console.log("myquery value is:", myquery)
        dbo.collection("customers").remove({myquery}, function(err, obj) {
          if (err) throw err;
          db.close();
        });
      });

    res.json({
        statusCode: 200,
        result: "success",
    })
}
);

export default router;

I got particular id from React hooks crud app , So i can see  the id in node js but it does not delete the that particular id data in mongoDB

A: Your query will only delete documents with myquery: passedId
I bet query should look like {_id: myquery}
dbo.collection("customers").remove({_id: myquery}, function(err, obj) {
  if (err) throw err;
  db.close();
});

A: dbo.collection("customers").remove(myquery, function(err, obj) {
 if (err) throw err;
 db.close();
});

A: try using delete({query}) or deleteMany({query})


text:
Q: SQL Server 2005 CHECKCATALOG fails CHECKCATALOG is failing on a database that originated in SQL Server 2000. I am getting errors of the type:

Msg 3853, Level 16, State 1, Line 1
  Attribute (object_id=489156888) of row (object_id=489156888,column_id=1) in sys.columns does not have a matching row (object_id=489156888) in sys.objects.

There are 146 columns in sys.columns that do not exist in sys.objects. This represents 21 tables. If I could easily delete these rows from the sys.columns view I would (blasphemy I know). CHECKDB had not been ran before so these errors went undetected and all the backups will contain the same error.
My plan is to export the existing tables into a new database. But the db is 170GB so this is not trivial.
My question is this: can I just reuse my existing .mdf/.ldf files? Since the system tables are stored in the master database, I could create a [new_work] database and attach the .mdf/.ldf files from the [orig_work] database. Then when I drop the corrupt [orig_work] db the bad entries would be deleted from the system table.
Would this work to fix my error?


text:
Q: Copy instances of derived class based on properties with attributes Suppose I have an abstract base class in which I want a CreateCopy method:
public abstract class BaseClass
{
    ///base stuff

    public BaseClass CreateCopy() //or public object, if necessary
    {
        //?????
    }
}

Assume that all derived classes have a parameterless constructor and property fields (that can be) marked with some kind of attribute:
public class DerivedClass : BaseClass
{
    [CopiableProperty]
    public string Property1 {get; private set;}

    [CopiableProperty]
    public int Property2 {get; private set;}

    //no need to copy
    public int Property3 {get; private set;}

    //parameterless constructor
    public DerivedClass() { }
}

Is it possible with this structure to write the body of CreateCopy() in a way that I can create new instances of the derived objects with the correct CopiableProperty fields?

Naturally I could make a public abstract BaseClass CreateCopy() and force each derived class to care for its own copy, but due to the size and amount of the derived classes, this would bring too much extra effort.

A: A fairly simple approach could be using generics and reflection:
public abstract class BaseClass
{
    // restrict to children of BaseClass
    public T CreateCopy<T>() where T: BaseClass, new()
    {
        var copy = new T();

        // get properties that you actually care about
        var properties = typeof(T).GetProperties()
            .Where(x => x.GetCustomAttribute<CopiablePropertyAttribute>() != null);

        foreach (var property in properties)
        {
            // set the value to the copy from the instance that called this method
            property.SetValue(copy, property.GetValue(this));
        }

        return copy;
    }
}

public class DerivedClass : BaseClass
{
    [CopiableProperty]
    public string Property1 { get; set; }

    [CopiableProperty]
    public int Property2 { get; set; }

    public int Property3 { get; set; }

    public override string ToString()
    {
        return $"{Property1} - {Property2} - {Property3}";
    }
}

static void Main(string[] args)
{
    var original = new DerivedClass
    {
        Property1 = "Hello",
        Property2 = 123,
        Property3 = 500
    };

    var copy = original.CreateCopy<DerivedClass>();

    Console.WriteLine(original);
    Console.WriteLine(copy);

    Console.ReadLine();
}

This would print:
Hello - 123 - 500
Hello - 123 - 0

Another approach would be to take advantage of a serialization library, if you don't mind the dependency:
public abstract class BaseClass
{
    public BaseClass CreateCopy()
    {
        string serialized = JsonConvert.SerializeObject(this);

        var actualType = GetType();

        return JsonConvert.DeserializeObject(serialized, actualType) as BaseClass;
    }
}

public class DerivedClass : BaseClass
{
    public string Property1 { get; set; }

    public int Property2 { get; set; }

    [JsonIgnore]
    public int Property3 { get; set; }

    //parameterless constructor
    public DerivedClass() { }

    public override string ToString()
    {
        return $"{Property1} - {Property2} - {Property3}";
    }
}

A: My solution uses serialization/deserialization, using JSON.NET nuget package.
No need for a method in the base class, you can use an extension method instead (adapted from this answer):
using Newtonsoft.Json;

public static class ObjectExtensions
{
    public static T Clone<T>(this T source)
    {
        var serialized = JsonConvert.SerializeObject(source);
        var clone = JsonConvert.DeserializeObject<T>(serialized);

        return clone;
    }
}

And then use attributes to control which properties should be copied or not - example:
using Newtonsoft.Json;

public class DerivedClass : BaseClass
{
    public string Property1 { get; set; }

    public int Property2 { get; set; }

    [JsonIgnore]
    public int Property3 { get; set; }
}

Using the code:
var obj1 = new DerivedClass
{
    Property1 = "Abc",
    Property2 = 999,
    Property3 = 123
};

DerivedClass clone = obj1.Clone();

Result - as you can see, Property3 has the default value in the cloned object:

A: Iterate through all properties in type and check your attribute with GetCustomAttributes. See code:
public BaseClass CreateCopy()
{
    var type = GetType();
    var result = Activator.CreateInstance(type);

    foreach (var propertyInfo in type.GetProperties())
    {
        var skipThisProperty = !propertyInfo.GetCustomAttributes(
                typeof(CopiablePropertyAttribute), false)
            .Any();

        if (skipThisProperty)
            continue;

        var value = propertyInfo.GetValue(this, null);
        propertyInfo.SetValue(result, value, null);
    }

    return (BaseClass) result;
}

Please pay attention to null parameter in GetValue and SetValue. If your property is indexer, you need to pass a correct value as last argument


text:
Q: How can I arrange x values in ggplot geom_bar when non-unique labels I have a dataframe that I am trying to plot in a bar graph and arrange the labels according to values in a different column. I understand that I must create factors and order the levels (related post), but what is the best way to create a factor when the labels are not unique and you are using the fill parameter.
This is how I am plotting:
cat_all %>%
  ggplot(aes(fill=device, y=t_by_p, x=domain)) +
  geom_bar(position="stack", stat="identity", colour="black") +
  geom_text(aes(label=round(t_by_p, 2)),
            size = 3,
            position = position_stack(vjust = .5)) +
  coord_flip() +
  labs(y = "total time spent/distinct people",
       x = sprintf("Top 10 %s Domains", 'X'),
       title = sprintf("Cluster 2 %s Domain Engagement", 'X'))

The idea is to order by the total value (desktop and phone).
data:
cat_all  <- structure(list(domain = c("businessinsider.com|News/Research",
"chase.com|Banking", "paypal.com|Personal Finance", "forbes.com|News/Research",
"bloomberg.com|News/Research", "cnbc.com|News/Research", "bankofamerica.com|Banking",
"wellsfargo.com|Banking", "wsj.com|News/Research", "fidelity.com|Online Trading",
"businessinsider.com|News/Research", "paypal.com|Personal Finance",
"forbes.com|News/Research", "cnbc.com|News/Research", "reuters.com|News/Research",
"bloomberg.com|News/Research", "chase.com|Banking", "bankofamerica.com|Banking",
"wellsfargo.com|Banking", "wsj.com|News/Research"), device = c("desktop",
"desktop", "desktop", "desktop", "desktop", "desktop", "desktop",
"desktop", "desktop", "desktop", "phone", "phone", "phone", "phone",
"phone", "phone", "phone", "phone", "phone", "phone"), t_by_p = c(3.40721337398374,
8.60096034164358, 6.23387870632672, 3.78531992009132, 12.9647524904215,
6.04311842447917, 10.1131791503268, 9.58312816091954, 6.69483134556575,
20.556119009009, 4.0323962962963, 6.47267734375, 2.11255132275132,
3.36567561728395, 5.78803899371069, 3.78916862745098, 6.08099117647059,
7.82377898550725, 9.81572870370371, 3.73643333333333)), row.names = c(NA,
-20L), class = c("tbl_df", "tbl", "data.frame"), .Names = c("domain",
"device", "t_by_p"))

A: One way is to just calculate the order first. Here's a way using dplur and forcats
library(dplyr)
library(forcats)
lvls <- cat_all %>%
  group_by(domain) %>%
  summarize(total=sum(t_by_p)) %>%
  mutate(domain=fct_reorder(domain, total)) %>%
  pull(domain) %>% levels()

Then you can use the lvls vairable for plotting
cat_all %>%
  mutate(domain=factor(domain, levels=lvls)) %>%
  ggplot(aes(fill=device, y=t_by_p, x=domain)) +
  geom_bar(position="stack", stat="identity", colour="black") +
  geom_text(aes(label=round(t_by_p, 2)),
            size = 3,
            position = position_stack(vjust = .5)) +
  coord_flip() +
  labs(y = "total time spent/distinct people",
       x = sprintf("Top 10 %s Domains", 'X'),
       title = sprintf("Cluster 2 %s Domain Engagement", 'X'))

A: Staying in the tidyverse, you could do:
library(dplyr)
cat_all %>%
  group_by(domain) %>%
  summarize(total_time = sum(t_by_p)) %>%
  arrange(total_time) %>%
  select(domain) %>% unlist -> domain_breaks

cat_all %<>% mutate(domain=factor(domain, levels = domain_breaks))

library(ggplot2)
cat_all %>%
  ggplot(aes(fill=device, y=t_by_p, x=domain)) +
  geom_bar(position="stack", stat="identity", colour="black") +
  geom_text(aes(label=round(t_by_p, 2)),
            size = 3,
            position = position_stack(vjust = .5)) +
  coord_flip() +
  labs(y = "total time spent/distinct people",
       x = sprintf("Top 10 %s Domains", 'X'),
       title = sprintf("Cluster 2 %s Domain Engagement", 'X'))


text:
Q: BizTalk mapping issue I've got a mapping issue which I'm trying to solve in the mapping tool of BizTalk.
Consider the following input file:
<person>
    <ID>APersonID</ID>
    <relatives>
        <relative>
            <name>Relative name 1</name>
        </relative>
        <relative>
            <name>Relative name 2</name>
        </relative>
    </relatives>
</person>

Note:  minOccurs of the relative element is set to 0 and the maxOccurs of the relative element is set to unbounded.
This input should be mapped to the following output:
<relatives>
    <person>
        <ID>APersonID</ID>
        <relative>Relative name 1</relative>
    </person>
    <person>
        <ID>APersonID</ID>
        <relative>Relative name 2</relative>
    </person>
<relatives>

Note: The person element has a minOccurs of 1 and a maxOccurs of unbounded.
I've got the mapping to work with a Looping functoid that links the relative element of the input file to the person element in the output file.But now there is a situation in which I'm given the following input file:
<person>
    <ID>APersonID</ID>
    <relatives />
</person>

Which should be mapped to
<relatives>
    <person>
        <ID>APersonID</ID>
    </person>
<relatives>

My current mapping can't handle this situation. Can somebody give suggestions on how to make/edit the mapping so that both situations can work?

A: Things are a bit more complex than at first seems since we need to test for existence of at least one relatives/relative before progressing. I can't think of any other way than to use XSLT - see here on how to extract the XSLT from your map and change the BTM to use an XSLT instead of the visual function mapping.
The following XSLT
<?xml version="1.0" ?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt"
    xmlns:var="http://schemas.microsoft.com/BizTalk/2003/var"
    exclude-result-prefixes="msxsl var"
    version="1.0"
    xmlns:ns0="http://BizTalk_Server_Project5.Schema1">
    <xsl:output omit-xml-declaration="yes" method="xml" version="1.0" />
    <xsl:template match="/">
        <xsl:apply-templates select="/ns0:person" />
    </xsl:template>
    <xsl:template match="/ns0:person">
        <relatives>
            <xsl:variable name="personId" select="ns0:ID/text()" />
            <xsl:choose>
                <xsl:when test="not(ns0:relatives) or not(ns0:relatives/ns0:relative)">
                    <person>
                        <ID>
                            <xsl:value-of select="$personId" />
                        </ID>
                    </person>
                </xsl:when>
                <xsl:otherwise>
                    <xsl:for-each select="ns0:relatives/ns0:relative">
                        <person>
                            <ID>
                                <xsl:value-of select="$personId" />
                            </ID>
                            <relative>
                                <xsl:value-of select="ns0:name/text()" />
                            </relative>
                        </person>
                    </xsl:for-each>
                </xsl:otherwise>
            </xsl:choose>
        </relatives>
    </xsl:template>
</xsl:stylesheet>

Produces the output you've described. (Obviously change your namespaces to match, and I've assumed you've got elementFormDefault="qualified" (If not, drop the ns0 prefixes)


text:
Q: Dynamic CRM 2011 delete quote products and push new quote products I am working on the Dynamic CRM SDK to push the quote' products from an external application. Following code is working fine to push the product to the CRM. The products are pulled from SQL database from an external application and push to dynamic crm.
DataSet DS = GetAllCRM_Details(oppid);
DataTable table = DS.Tables[0];

foreach (DataRow row in table.Rows)
{

string prodid = DbCommon.ToStr(row["txtcrmprodid"]);
double Qty = DbCommon.ToDouble(row["intquantity"]);
string Note = DbCommon.ToStr(row["txtproduct_note_internal"]);
string ProdDesc = DbCommon.ToStr(row["txtproductdiscription"]);
string qid = DbCommon.ToStr(row["txtcrmquoteid"]);
string UnitCrmID = DbCommon.ToStr(row["UnitID"]);
string price = DbCommon.ToStr(row["floatlistprice"]);
string lineid = DbCommon.ToStr(row["intQlinID"]);
string price_fltTotal = DbCommon.ToStr(row["floattotal"]);
string quotedetailid = DbCommon.ToStr(row["txtcrmquotedetailid"]);
string productname_qt = DbCommon.ToStr(row["txtproductname_qt"]);

decimal nprice = 0;
decimal ManualDiscountPrice = 0;
decimal pricefltotal = 0;

if (price != "")
{
    nprice = Convert.ToDecimal(price);
}

if (price_fltTotal != "")
{
    pricefltotal = Convert.ToDecimal(price_fltTotal);
}

ManualDiscountPrice = (nprice - pricefltotal) ;

decimal extamount = nprice * Convert.ToDecimal(Qty);

// Set the quote's product quantity to a negative value.

QuoteDetail quoteDetail = new QuoteDetail()
{

    ProductId = new EntityReference(Product.EntityLogicalName, new Guid(prodid)),
    IsProductOverridden = true,
    ProductDescription = productname_qt,
    IsPriceOverridden = true,
    Quantity = Convert.ToDecimal(Qty),
    PricePerUnit = new Money(nprice),
    CTDescription = ProdDesc,
    CTInternalNote = Note,
    ManualDiscountAmount = new Money(ManualDiscountPrice),
    QuoteId = new EntityReference(Quote.EntityLogicalName, new Guid(qid)),
    UoMId = new EntityReference(UoM.EntityLogicalName, new Guid(UnitCrmID))
};

_quoteDetailId = _serviceProxy.Create(quoteDetail);

The first attempt is working fine,When user make an amendment and try to push the products to crm the existing products in the CRM need to updated/delete the exiting product and add the new products.
The product quote details id(guid) are stored in the external tool database.
Please advice.

A: You are on the right track for creating a product.
For updating please follow below steps,

*

*Using the information from your source, retrieve the information from CRM to get the GUID for the record to update. for that you can use _serviceProxy.Retrieve() or _serviceProxy.RetrieveMultiple() methods.

*Once the record is available, create an entity for the product and assign the id of this entity to the record which we retrieved in the first step and use _serviceProxy.Update(). This will update your existing product.

Now if you want to delete and create a new record follow below steps,

*

*Retrieve the record as in the case for Update.

*using _serviceProxy.Delete() method delete that particular record from the CRM

*Follow your existing code to create a new product with updated info.

Its recommended to update the record rather than always deleting and creating a new record.
Hope this helps, let me know if you have any queries.

A: We would like to delete all the product details for the quote and add the new product will speed up the process. I could not get to work with above code.
Code example will be really helpful.


text:
Q: Animating UITextField up when keyboard shows I've registered two observers, keyboardWillShow: and keyboardWillHide: in NSNotificationCenter
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillShow:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillHide:", name: UIKeyboardWillHideNotification, object: nil)

In both these methods when I try to animate the UIView containing the UITextView, it jumps to the frame I am trying to animate to and then animates back to the original location. I tried this same animation code in the touchesBegan method to test it out and it works great there (animating to the new frame I actually set it to rather than jumping and animating back to the original location).
func keyboardWillShow(notification: NSNotification) {
    if let endFrame = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() {
        UIView.animateWithDuration(1.0, animations: { () -> Void in
            self.footerView.center = CGPointMake(self.footerView.center.x, self.footerView.center.y - endFrame.size.height)
        })
    }
}

I'm stumped. Does the keyboard notification affect new animations in some way?

A: You will have to call these two methods to animate the view up and down..
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
@try
{
    if (textField == (UITextField *)[self.view viewWithTag:TEXTFIELD_MOBILE_TAG])
    {
        CGRect selfframe = CGRectMake([self.view viewWithTag:VIEW_PARENT_TAG].frame.origin.x, [self.view viewWithTag:VIEW_PARENT_TAG].frame.origin.y - 80, [self.view viewWithTag:VIEW_PARENT_TAG].frame.size.width, [self.view viewWithTag:VIEW_PARENT_TAG].frame.size.height);
        [UIView animateWithDuration:0.3 animations:^{ [self.view viewWithTag:VIEW_PARENT_TAG].frame = selfframe;}];
        [textField becomeFirstResponder];
    }

}
@catch (NSException *exception)
{
    NSLog(@"Error Occured in SignUpViewController :: textViewDidBeginEditing :: %@",[exception description]);
}

}

- (void)textFieldDidEndEditing:(UITextField *)textField
{
@try
{
    if (textField == (UITextField *)[self.view viewWithTag:TEXTFIELD_MOBILE_TAG])
    {
        CGRect selfframe = CGRectMake([self.view viewWithTag:VIEW_PARENT_TAG].frame.origin.x, [self.view viewWithTag:VIEW_PARENT_TAG].frame.origin.y + 80, [self.view viewWithTag:VIEW_PARENT_TAG].frame.size.width, [self.view viewWithTag:VIEW_PARENT_TAG].frame.size.height);
        [UIView animateWithDuration:0.3 animations:^{ [self.view viewWithTag:VIEW_PARENT_TAG].frame = selfframe;}];
        [textField resignFirstResponder];
    }
}
@catch (NSException *exception)
{
    NSLog(@"error Occured in SignUpViewController :: textViewDidEndEditing :: %@",[exception description]);
}

}


text:
Q: Let $A$ any matrix so $A^H A$ is Hermitian and $A^H A $ is positive definite. Question:
Let $A$ any matrix so $A^H A$ is Hermitian and $A^H A $ is positive definite.
Answer:
The first part is easy as: $A^H A =A A^H \Rightarrow AA^H = (A^HA)^H=(AA^H)^H$.
But how to prove (quickly) $<u|AA^H|u> \geq 0$?

A: $u^{H}A^{H}Au$ = $(Au)^{H}(Au)=||Au||^{2}$


text:
Q: Azure Function Debugging while offline when I am offline and not connected to Azure I cannot seem to debug an Azure function in Visual Studio Code.
What settings can I change in the launch.json to allow me to debug functions without connectivity?

A: Not Sure if you are using Python or PowerShell Azure Functions as nothing has been mentioned in the Question.
I have been working with both of the languages of Azure Functions in VS Code IDE.
As of now, checked with the latest Version of VS Code, Python Versions (3.9.x, 3.10.x) and PowerShell Azure Functions; they are working successfully in the debug mode.
I found the various causes and resolutions of the debugging process in Azure Functions in VS Code given by the user @HariKrishna, that will helps to fix your issue, refer to the SO #71532944
For PowerShell Azure Function, below is the code I have:
run.ps1:
using  namespace  System.Net

# Input bindings are passed in via param block.
param($Request, $TriggerMetadata)

# Write to the Azure Functions log stream.
Write-Host  "PowerShell HTTP trigger function processed a request."

# Interact with query parameters or the body of the request.
Connect-AzAccount -Tenant '<your_Azure_Tenant_id' -SubscriptionId '<Your-Azure_Subscription_Id>'
Set-AzContext -Subscription "<Your-Azure_Subscription_Id>"

$body = "Hello Pravallika, This HTTP triggered function executed successfully."

# Associate values to output bindings by calling 'Push-OutputBinding'.
Push-OutputBinding -Name Response -Value ([HttpResponseContext]@{
StatusCode = [HttpStatusCode]::OK
Body = $body
})

tasks.json:
{
    "version": "2.0.0",
    "tasks": [
{
    "label": "func start",
    "type": "shell",
    "command": "func start",
    "problemMatcher": "$func-powershell-watch",
    "isBackground": true
        }
    ]
}

host.json:
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingSettings": {
"isEnabled": true,
"excludedTypes": "Request"
}
}
},
"extensionBundle": {
"id": "Microsoft.Azure.Functions.ExtensionBundle",
"version": "[3.3.0, 4.0.0)"
},
"managedDependency": {
"enabled": true
}
}

*

*Uncomment the Az Modules in the requirements.txt file.

*Make Sure you have the Local Storage Emulator or Azure Storage account connection String value in the local.settings.json such as "AzureWebJobsStorage": "UseDevelopmentStorage=true".


text:
Q: Failed DEM via Natural Neighbor, QGIS 3.16-6 Hannover Reading How to Create DEM and Elevation Profile in QGIS, I can't generate DEM from vertices layer using Natural neighbour with height whatever the cell size and parameters.
I'm using Ubuntu 20.04, QGIS installed with flatpak. HDD 100GB avail.

Getting:
QGIS version: 3.16.6-Hannover
QGIS code revision: bfd36fdd
Qt version: 5.15.3
GDAL version: 3.2.1
GEOS version: 3.8.1-CAPI-1.13.3
PROJ version: Rel. 6.3.2, May 1st, 2020
SAGA version 7.6.3 is not officially supported - algorithms may encounter issues
Processing algorithm…
Algorithm 'Natural neighbour' starting…
Input parameters:
{ 'FIELD' : 'height', 'METHOD' : 0, 'SHAPES' : '/media/pm/Data/Downloads/vertices.geojson|layername=vertices', 'TARGET_OUT_GRID' : 'TEMPORARY_OUTPUT', 'TARGET_TEMPLATE' : None, 'TARGET_USER_FITS' : 0, 'TARGET_USER_SIZE' : 0.15, 'TARGET_USER_XMIN TARGET_USER_XMAX TARGET_USER_YMIN TARGET_USER_YMAX' : '-146.000000000,152.416666667,-80.916666667,64.000000000 [EPSG:4326]', 'WEIGHT' : 0 }

grid_gridding "Natural Neighbour" -TARGET_DEFINITION 0 -SHAPES "/tmp/processing_WmXshU/b1c91a0db1464037b1d72d688bd36dcf/SHAPES.shp" -FIELD "height" -METHOD 0 -TARGET_USER_XMIN -146.0 -TARGET_USER_XMAX 152.416666667 -TARGET_USER_YMIN -80.916666667 -TARGET_USER_YMAX 64.0 -TARGET_USER_SIZE 0.15 -TARGET_USER_FITS 0 -WEIGHT 0.0 -TARGET_OUT_GRID "/tmp/processing_WmXshU/d3966278eae04c1c90f2d7e7b7ccb382/TARGET_OUT_GRID.sdat"
____________________________

##### ## ##### ##
### ### ## ###
### # ## ## #### # ##
### ##### ## # #####
##### # ## ##### # ##
____________________________

SAGA Version: 7.6.3

Unknown option 'SHAPES'
____________________________
library path: /app/lib/saga/
library name: libgrid_gridding
library : grid_gridding
tool : Natural Neighbour
identifier : 3
author : O.Conrad (c) 2008
processors : 4 [4]
____________________________

Usage: saga_cmd grid_gridding 3 [-POINTS <str>] [-FIELD <str>] [-TARGET_DEFINITION <str>] [-TARGET_USER_SIZE <double>] [-TARGET_USER_XMIN <double>] [-TARGET_USER_XMAX <double>] [-TARGET_USER_YMIN <double>] [-TARGET_USER_YMAX <double>] [-TARGET_USER_COLS <num>] [-TARGET_USER_ROWS <num>] [-TARGET_USER_FITS <str>] [-TARGET_TEMPLATE <str>] [-TARGET_OUT_GRID <str>] [-METHOD <str>] [-WEIGHT <double>]
-POINTS:<str> Points
Shapes (input)
-FIELD:<str> Attribute
Table field
-TARGET_DEFINITION:<str> Target Grid System
Choice
Available Choices:
[0] user defined
[1] grid or grid system
Default: 0
-TARGET_USER_SIZE:<double> Cellsize
Floating point
Minimum: 0.000000
Default: 1.000000
-TARGET_USER_XMIN:<double> West
Floating point
Default: 0.000000
-TARGET_USER_XMAX:<double> East
Floating point
Default: 100.000000
-TARGET_USER_YMIN:<double> South
Floating point
Default: 0.000000
-TARGET_USER_YMAX:<double> North
Floating point
Default: 100.000000
-TARGET_USER_COLS:<num> Columns
Integer
Minimum: 1
Default: 100
-TARGET_USER_ROWS:<num> Rows
Integer
Minimum: 1
Default: 100
-TARGET_USER_FITS:<str> Fit
Choice
Available Choices:
[0] nodes
[1] cells
Default: 0
-TARGET_TEMPLATE:<str> Target System
Grid (optional input)
-TARGET_OUT_GRID:<str> Target Grid
Grid (output)
-METHOD:<str> Method
Choice
Available Choices:
[0] Linear
[1] Sibson
[2] Non-Sibsonian
Default: 1
-WEIGHT:<double> Minimum Weight
Floating point
Maximum: 0.000000
Default: 0.000000
corrupted double-linked list
/home/pm/.var/app/org.qgis.qgis/data/QGIS/QGIS3/profiles/default/processing/saga_batch_job.sh: line 1: 76 Aborted (core dumped) saga_cmd grid_gridding "Natural Neighbour" -TARGET_DEFINITION 0 -SHAPES "/tmp/processing_WmXshU/b1c91a0db1464037b1d72d688bd36dcf/SHAPES.shp" -FIELD "height" -METHOD 0 -TARGET_USER_XMIN -146.0 -TARGET_USER_XMAX 152.416666667 -TARGET_USER_YMIN -80.916666667 -TARGET_USER_YMAX 64.0 -TARGET_USER_SIZE 0.15 -TARGET_USER_FITS 0 -WEIGHT 0.0 -TARGET_OUT_GRID "/tmp/processing_WmXshU/d3966278eae04c1c90f2d7e7b7ccb382/TARGET_OUT_GRID.sdat"
Execution completed in 1.57 seconds
Results:
{'TARGET_OUT_GRID': '/tmp/processing_WmXshU/d3966278eae04c1c90f2d7e7b7ccb382/TARGET_OUT_GRID.sdat'}

Loading resulting layers
The following layers were not correctly generated.
• /tmp/processing_WmXshU/4397f9a7887a4a2f80070fce4193b0cd/TARGET_OUT_GRID.sdat
• /tmp/processing_WmXshU/d3966278eae04c1c90f2d7e7b7ccb382/TARGET_OUT_GRID.sdat
You can check the 'Log Messages Panel' in QGIS main window to find more information about the execution of the algorithm.

Also tried with other cellsizes (100, 0.0005, 0.0002, ...).
Adding the vertices.geojson (zipped) layer for you to test.


text:
Q: Skip duplicated dots based generated by randint() function I am still learning Python programming and currently struggling to achieve one goal. I got a class Dot that is used to create coordinates and compare them later on. Also, I got a class Player with two other child classes that are inherited from the Parent class.
class Dot:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __eq__(self, other):
        return self.x == other.x and self.y == other.y

    def __repr__(self):
        return {self.x, self.y}

class Player:
    def __init__(self, board, enemy):
        self.board = board
        self.enemy = enemy

    def ask(self):
        raise NotImplementedError()

    def turn(self):
        while True:
            try:
                target = self.ask()
                repeat = self.enemy.shoot(target)
                return repeat
            except BoardExceptionError as e:
                print(e)

class Viki(Player):
    def ask(self):
        answer = Dot(randint(0, 5), randint(0, 5))
        time.sleep(3)
        print(f'Turn of Viki: {answer.x} {answer.y}')
        return answer

class Human(Player):
    def ask(self):
        while True:
            h = input('Your turn: ').split()
            if len(h) != 2:
                print('Add 2 coordinates...')
                continue
            x, y = h
            if not (x.isdigit()) or not (y.isdigit()):
                print('Add numbers from 0 to 6...')
                continue
            x, y = int(x), int(y)
            return Dot(x - 1, y - 1)

What I would like to expect is that class "Viki(Player)" kind of an AI, forcing it to not use the same coordinates(Dots) that are already used(generated) previously. So, every time it should use none used cells on the board.
I understand that it might help in this case logical operators or count function. For example,
Example 1:
a = Dot(1, 2)
b = Dot(1, 3)
c = Dot(1, 4)
abc_list = [Dot(1, 2), Dot(2, 2), Dot(2, 3)]
print(a in abc_list)
Output
True

Example 2:
print(abc_list.count(a))
Output
1

I tried to play with both options but gettings different types of errors when I try to use loops and blocks. I understand that the bottleneck here is my knowledge :) Your help is much appreciated if someone can help me to sort this out. Thanks in advance!

A: Here is a generator that produces all the dots in random order (no repeats):
from itertools import product
from random import shuffle

def random_dots():
    dots = [Dot(*p) for p in product(range(6), repeat=2)]
    shuffle(dots)
    yield from dots

rd = random_dots()

Now, you can use it in you code:
dot = next(rd)

If pre-generating all dots is not an option because there are too many, you could use the following which is lighter on memory/time:
dots = set()

def random_dot():
    while (tpl := (randint(0, 5), randint(0, 5))) in dots:
        pass
    dots.add(tpl)
    return Dot(*tpl)

And use like:
dot = random_dot()


text:
Q: Bash if statement [: missing `]' error I am having trouble with bash. I am trying to put a command in an if statement and then compare it to a string.
This works perfectly.
echo $(ipcs | grep Shared | awk '{print $2}')

When I put it in an if statement I get some problems.
$ if [ "$(ipcs | grep Shared | awk '{print $2}')" -eq "Shared"]; then
  echo expression evaluated as true;
else
  echo expression evaluated as false;
fi
bash: [: missing `]'
expression evaluated as false

$ if [ "$(ipcs | grep Shared | awk '{print $2}')" = "Shared"]; then
  echo expression evaluated as true;
else
  echo expression evaluated as false;
fi
bash: [: missing `]'
expression evaluated as false

$ if [ "$(ipcs | grep Shared | awk '{print $2}')" == "Shared"]; then
  echo expression evaluated as true;
else
  echo expression evaluated as false;
fi
bash: [: missing `]'
expression evaluated as false

I tried ==, =, and -eq because I wasn't sure which one to use.

A: Your missing ]' error is because you need a space at the inbetween "Shared" and ], so the line should be if [ "$(ipcs | grep Shared | awk '{print $2}')" == "Shared" ]; then.


text:
Q: AttributeError: 'list' object has no attribute 'chat' ошибка в Python Я пытаюсь перенести функции из голосового ассистента в бота для телеграмма. В итоге я вообще не могу понять что это за ошибка, и что её вызывает - AttributeError: 'list' object has no attribute 'chat' Помогите плиз
пока отлавливал ошибку, понял что проблема в этой строке - await commands[key](args)
Полный текст ошибки:
ERROR:asyncio:Task exception was never retrieved
future: <Task finished name='Task-9' coro=<Dispatcher._process_polling_updates() done, defined at C:\Users\hybas\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\aiogram\dispatcher\dispatcher.py:409> exception=AttributeError("'list' object has no attribute 'chat'")>
Traceback (most recent call last):
  File "c:/Users/hybas/Desktop/umorist/bot_new.py", line 50, in search_for_definition_on_wikipedia
    await bot.send_message(message.chat.id, "Начинаю поиск информации о " + search_term + " на википедии")
AttributeError: 'list' object has no attribute 'chat'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "c:/Users/hybas/Desktop/umorist/bot_new.py", line 68, in execute_command_with_name
    await commands[key](args)
  File "c:/Users/hybas/Desktop/umorist/bot_new.py", line 59, in search_for_definition_on_wikipedia
    await bot.send_message(message.chat.id, "ошибка, БЗЗ")
AttributeError: 'list' object has no attribute 'chat'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\hybas\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\aiogram\dispatcher\dispatcher.py", line 417, in _process_polling_updates
    for responses in itertools.chain.from_iterable(await self.process_updates(updates, fast)):
  File "C:\Users\hybas\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\aiogram\dispatcher\dispatcher.py", line 238, in process_updates
    return await asyncio.gather(*tasks)
  File "C:\Users\hybas\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "C:\Users\hybas\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\aiogram\dispatcher\dispatcher.py", line 259, in process_update
    return await self.message_handlers.notify(update.message)
  File "C:\Users\hybas\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\aiogram\dispatcher\handler.py", line 116, in notify
    response = await handler_obj.handler(*args, **partial_data)
  File "c:/Users/hybas/Desktop/umorist/bot_new.py", line 75, in get_message
    await execute_command_with_name(command, command_options)
  File "c:/Users/hybas/Desktop/umorist/bot_new.py", line 70, in execute_command_with_name
    await bot.send_message(message.chat.id, "ошибка, БЗЗ")
AttributeError: 'list' object has no attribute 'chat'

Сам код:
import logging
import string
import bs4
import random
import logging
import wikipediaapi
import webbrowser
import traceback

from aiogram import Bot, Dispatcher, executor, types

logging.basicConfig(level=logging.INFO)

bot = Bot(token='токен')
dp = Dispatcher(bot)

#ответ на команды
@dp.message_handler(commands=['start'])
async def begin(message: types.Message):
    await bot.send_message(message.chat.id, "Привет")

@dp.message_handler(commands=['bot'])
async def begin(message: types.Message):
    await bot.send_message(message.chat.id, "На месте")

@dp.message_handler(content_types=['text'])
async def get_message(message):

    message = message.text.split(" ")
    command = message[0]
    command_options = [str(input_part) for input_part in message[1:len(message)]]

    async def search_for_definition_on_wikipedia(*args: tuple):
      if not args[0]: return

      search_term = " ".join(args[0])

      # установка языка (в данном случае используется язык, на котором говорит ассистент)
      wiki = wikipediaapi.Wikipedia("ru")

      # поиск страницы по запросу, чтение summary, открытие ссылки на страницу для получения подробной информации
      wiki_page = wiki.page(search_term)
      try:
          if wiki_page.exists():
              await bot.send_message(message.chat.id, "Начинаю поиск информации о " + search_term + " на википедии")
              # чтение ассистентом первых двух предложений summary со страницы Wikipedia
              await bot.send_message(message.chat.id, wiki_page.summary.split(".")[:2])
          else:
              # открытие ссылки на поисковик в браузере в случае, если на Wikipedia не удалось найти ничего по запросу
              await bot.send_message(message.chat.id, "Информация о " + search_term + " не была найдена")

      # поскольку все ошибки предсказать сложно, то будет произведен отлов с последующим выводом без остановки программы
      except:
          await bot.send_message(message.chat.id, "ошибка, БЗЗ")

    commands = {
    ("wikipedia", "definition", "about", "определение", "википедия", "информация", "информация о"): search_for_definition_on_wikipedia,
}
    async def execute_command_with_name(command_name: str, args: list):
      for key in commands.keys():
          if command_name in key:
              await commands[key](args)
          else:
              pass  # print("Command not found")

    await execute_command_with_name(command, command_options)

if __name__ == "__main__":
    executor.start_polling(dp, skip_updates=True)

A: message = message.text.split(" ")

Вот это превращает message в обычный list. А у него нет атрибута chat.
Лучше копируйте полный текст ошибки. И сами смотрите на этот текст. Там как правило указывается номер строки и код, который это исключение вызвал.


text:
Q: Bound of Covering Number of any Compact Set I am reading a paper that considers a D-dimensional compact parameter space $\Theta$. The paper states that:

It is known that that that the $\epsilon$-covering number of $\Theta$ with Euclidean distance is
$$
N(\Theta, || \cdot ||, \epsilon) \leq \left ( 1 + \frac{\mathrm{diam}(\Theta)}{\epsilon} \right )^D.
$$

Does anyone have a citation for this result? I have found bounds on the covering number of unit balls in "High Dimensional Probability" by Roman Vershynin and "High-Dimensional Statistics" by Marin J. Wainwright, but nothing that bounds the covering number of of general compact sets.


text:
Q: Change time in day date picker depending on location/day I'm using amsul date selector and a time selector, I want to change the min/max hours of the time selector depending on what days and check boxes are selected. Here is my code:
    var today = new Date();
    var tomorrow = new Date();
    tomorrow.setDate(today.getDate()+1);
    var nextyear=new Date();
    nextyear.setFullYear(nextyear.getFullYear()+1);
    pickupdatemin=new Date(document.getElementById('car-rental-pickup-date').value);

const timepicker = $('#car-rental-pickup-time').pickatime({
    clear: '',
    min: [9,00],
    max: [16,30],
    onSet: function(context) {
      getpricing();
    }
});
    const pickupdatepicker = $('#car-rental-pickup-date').pickadate({
        format: 'mm/dd/yyyy',
        min: tomorrow,
        max: nextyear,
        today: '',
        close: '',
        clear: '',
        disable: [1],

        onSet:function(context){
            var pickup_loc_sel = document.getElementsByName('car-rental-pickup-location');
            var pickup_loc;
            for(var i = 0; i < pickup_loc_sel.length; i++){
            if(pickup_loc_sel[i].checked){
            pickup_loc = pickup_loc_sel[i].value;
        }
    }
          var d = new Date(context.select);
          var isSat = d.getDay() == 6 && pickup_loc == "sf";
          var max = isSat ? [11,30] : [16,30];
          var time = timepicker.pickatime('picker');
          time.clear().set({max});

          var ddate = dropdatepicker.pickadate('picker');
          ddate.clear();
          ddate.set('min', d);

          getpricing();
        }
    });

So right now that code works pretty well as is, what I want to change is in addition to everything thing I have there (I was able to do the rest with the help of a previous poster on here), if pickup_loc = "oc" I want the days available to be Monday, Tuesday, Thursday, Friday and I want the times available to be 11am - 2pm. How would I go about doing this?
Edit: Here is a working jsfiddle

A: I added a function to your radio buttons, I think you are also manipulating time picker when date is set. So you have to build a function to call when date is changed and when place is changed and collate them in one function to improve consistency, right now the new function will handle your time picker all right but once you select the date those will be overridden by your date onset function.
This is not accurate code but just to help you figure out your next move.
function placeEvents() {
  var pickup_loc_sel = document.getElementsByName('car-rental-pickup-location');
  for (var i = 0; i < pickup_loc_sel.length; i++) {
    /* if (pickup_loc_sel[i].checked) {
      pickup_loc = pickup_loc_sel[i].value;
    } */
    pickup_loc_sel[i].addEventListener('change', function(e){
      var max = [16, 30];
      var min = [9, 00];
      if(e.target.value === 'oc') {
        min = [11, 0];
        max = [14, 0];
      }
      var time = timepicker.pickatime('picker');
      time.clear().set({
        max, min
      });

      disable = e.target.value === 'oc' ? [1, 4, 6] : [1];
      var date = pickupdatepicker.pickatime('picker');
      date.clear().set({
        disable
      })
    })
  }
}

JS Fiddle for your reference https://jsfiddle.net/9c6r1ns4/1/

A: Like this:
var today = new Date();
var tomorrow = new Date();
tomorrow.setDate(today.getDate()+1);
var nextyear=new Date();
nextyear.setFullYear(nextyear.getFullYear()+1);
pickupdatemin=new Date(document.getElementById('car-rental-pickup-date').value);

var timepicker = $('#car-rental-pickup-time').pickatime({
    clear: '',
    min: [9,0],
    max: [16,30]
});

var pickupdatepicker = $('#car-rental-pickup-date').pickadate({
    format: 'mm/dd/yyyy',
    min: tomorrow,
    max: nextyear,
    today: '',
    close: '',
    clear: '',
    disable: [1],
    onSet:function(context){
        updateTimePicker();
    }

});

$("input[type=radio]").change(function() {
    updateDatePicker();
});

function updateDatePicker(){

    var radioValue = $("input[type=radio]:checked").val();
    var dPicker = pickupdatepicker.pickadate('picker');

    switch (radioValue){

        case "oc":

            dPicker.set({
              'enable': [2,3,5],
              'disable': [1,4,6,7]
            });

            break;

        default:

            dPicker.set({
              'enable': [2,3,4,5,6,7],
              'disable': [1]
            });

    }

    updateTimePicker();

}

function updateTimePicker(){

    var radioValue = $("input[type=radio]:checked").val();
    var dPicker = pickupdatepicker.pickadate('picker');
    var tPicker = timepicker.pickatime('picker');

    switch (radioValue){

        case "oc":

            tPicker.set({
                'min': [11,0],
                'max': [14,0]
            });

            break;

         case "sf":

            if (dPicker.get('select') != null && dPicker.get('select').day == 6){

                tPicker.set({
                    'min': [9,0],
                    'max': [11,30]
                });

                break;

             }

             default:

             tPicker.set({
                 'min': [9,0],
                 'max': [16,30]
             });

    }

}

And here is a working fiddle


text:
Q: scroll method not working on ipad I have the following code to rotate a button when reaching the bottom of the document page, which is working everywhere but on ios devices. Anyone could help?
$(document).ready(function() {
    $(window).scroll(function() {
        if ($("body").height() == ($(window).height() + $(window).scrollTop())) {
            $(".next").addClass('rotated').bind('click touchstart', function(e) {
                e.preventDefault();
                pageScroller.goTo(1);
            });
        } else {
        $(".next").removeClass('rotated');
        }
    });
});


text:
Q: Missing Push Notification Entitlement Troubles in Ionic App using OneSignal i'm using the OneSignal API for Push Notifications in an Cordova App. My android is receiving notifications, but the iPhone isn't and i'm receiving this e-mail:

Dear developer,
We have discovered one or more issues with your recent delivery for
  "----". Your delivery was successful, but you may wish to
  correct the following issues in your next delivery:
Missing Push Notification Entitlement - Your app includes an API for
  Apple's Push Notification service, but the aps-environment entitlement
  is missing from the app's signature. To resolve this, make sure your
  App ID is enabled for push notification in the Provisioning Portal.
  Then, sign your app with a distribution provisioning profile that
  includes the aps-environment entitlement. This will create the correct
  signature, and you can resubmit your app. See "Provisioning and
  Development" in the Local and Push Notification Programming Guide for
  more information. If your app does not use the Apple Push Notification
  service, no action is required. You may remove the API from future
  submissions to stop this warning. If you use a third-party framework,
  you may need to contact the developer for information on removing the
  API.
After you've corrected the issues, you can use Xcode or Application
  Loader to upload a new binary to iTunes Connect.
Regards,
The App Store team

My App ID is enabled for push notifications and i really don't understand why it isn't working.

A: You need to enable "Push Notifications" in your project settings. Check attached the screenshot.


text:
Q: AsyncFacebookRunner implementation for login and wallpost i'm trying to create a Facebook utility class and so far it worked pretty good but when i test it on APIs greater than ICS i get this error.

09-27 07:43:50.706: E/AndroidRuntime(565): FATAL EXCEPTION: main
  09-27 07:43:50.706: E/AndroidRuntime(565): android.os.NetworkOnMainThreadException
  09-27 07:43:50.706: E/AndroidRuntime(565):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1084)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at java.net.InetAddress.getAllByName(InetAddress.java:220)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at libcore.net.http.HttpConnection.(HttpConnection.java:71)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at libcore.net.http.HttpConnection.(HttpConnection.java:50)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.makeSslConnection(HttpsURLConnectionImpl.java:460)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at libcore.net.http.HttpsURLConnectionImpl$HttpsEngine.connect(HttpsURLConnectionImpl.java:432)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at libcore.net.http.HttpsURLConnectionImpl.connect(HttpsURLConnectionImpl.java:164)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at com.facebook.android.Util.openUrl(Util.java:193)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at com.facebook.android.Facebook.request(Facebook.java:751)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at com.infobest.praiser.share.ShareFacebook.postWall(ShareFacebook.java:99)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at com.infobest.praiser.share.ShareFacebook.send(ShareFacebook.java:47)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at com.infobest.praiser.activity.PraiseActivity$7.onClick(PraiseActivity.java:472)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:924)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at android.widget.AdapterView.performItemClick(AdapterView.java:292)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at android.widget.AbsListView.performItemClick(AbsListView.java:1058)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at android.widget.AbsListView$PerformClick.run(AbsListView.java:2514)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at android.widget.AbsListView$1.run(AbsListView.java:3168)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at android.os.Handler.handleCallback(Handler.java:605)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at android.os.Handler.dispatchMessage(Handler.java:92)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at android.os.Looper.loop(Looper.java:137)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at android.app.ActivityThread.main(ActivityThread.java:4340)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at java.lang.reflect.Method.invokeNative(Native Method)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at java.lang.reflect.Method.invoke(Method.java:511)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
  09-27 07:43:50.706: E/AndroidRuntime(565):  at dalvik.system.NativeStart.main(Native Method)

how can i implement AsyncFacebookRunner if my class looks like this
{
public String msg;
public Context ctx;
public Facebook fb;
public SharedPreferences sp;

public ShareFacebook(String msg, Context ctx, Facebook fb, SharedPreferences sp)
{
    this.msg = msg;
    this.ctx = ctx;
    this.fb = fb;
    this.sp = sp;

}

public void send()
{
    if (fb.isSessionValid())
    {
        postWall();
    }
    else
    {

        fb.authorize((Activity) ctx, new String[] {"email", "publish_checkins",
            "publish_stream"}, new DialogListener()
        {

            @Override
            public void onFacebookError(FacebookError e)
            {
                e.printStackTrace();

            }

            @Override
            public void onError(DialogError e)
            {
                Toast.makeText(ctx,R.string.facebookError, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onComplete(Bundle values)
            {
                Editor editor = sp.edit();
                editor.putString("access_token", fb.getAccessToken());
                editor.putLong("access_expires", fb.getAccessExpires());
                editor.commit();
                postWall();
            }

            @Override
            public void onCancel()
            {

            }
        });
    }

}

private void postWall()
{
    Bundle params = new Bundle();
    params.putString("message",  msg );
    params.putString("link",ctx.getResources().getString(R.string.rateLink));
    params.putString("picture",
        ctx.getResources().getDrawable(R.drawable.ic_launcher).toString());
    try
    {
        fb.request("me/feed", params, "POST");
        Toast.makeText(ctx,R.string.facebookSuccess, Toast.LENGTH_SHORT).show();
    }
    catch (FileNotFoundException e)
    {
        e.printStackTrace();
    }
    catch (MalformedURLException e)
    {
        e.printStackTrace();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

}

}
Thank you :)

A: You can't call Facebook.request() from the UI thread.
It only happens on ICS and above because ICS checks to ensure that you don't try and do network comms on the UI thread.
From the method comments in the facebook api:

Note that this method blocks waiting for a network response, so do not call it in a UI thread.

Creating a thread and running fb.request from the thread should resolve the error.


text:
Q: как делать несколько конструкторов? У меня есть класс с 4 аргументами
public class Employee {
private String firstName;
private String lastName;
private String salary;
private String department;

есть ли способ  в методах, делать разные конструкторы, чтоб один принимал lastName firstname, другой Salary department.
  public Employee add(String firstName, String lastName) {
      Employee employee = new Employee(firstName, lastName);

чтобы не выдавало "Expected 4 arguments but found 2"

A: public class Employee {

  private final String firstName;
  private final String lastName;
  private final String salary;
  private final String department;

  public Employee(String firstName, String lastName, String salary, String department) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.salary = salary;
    this.department = department;
  }

}

public Employee add() {
  Employee employee = new Employee("first name", "last name", "salary", "department");
}

Ключевое слово this представляет ссылку на текущий экземпляр класса. Через это ключевое слово мы можем обращаться к переменным, методам объекта, а также вызывать его конструкторы.

A: public Employee(String firstName, String lastName, String salary, String department) {}

просто делаешь еще один конструктор
public Employee(String firstName, String lastName){}

И в зависимости от количества параметров будет вызываться соответствующий конструктор.
Если 4 параметра то первый, если 2 параметра то второй

A:
есть ли способ в методах, делать разные конструкторы, чтоб один принимал lastName firstname, другой Salary department.

"Делать" конструкторы в данном случае не получится, поскольку в данном случае все аргументы/поля в классе Employee однотипны (String).
Вместо конструкторов можно написать два разных метода-генератора, которые будут вызывать полный конструктор с четырьмя аргументами, подставляя некие значения по умолчанию или null.
Замечание: использование строк для хранения информации об отделе и особенно о зарплате не самый удачный выбор
public class Employee {
    private static final String UNKNOWN = "Unknown";

    private String firstName;
    private String lastName;
    private String salary;
    private String department;

    public Employee(String first, String last, String salary, String dept) {
        this.firstName = first;
        this.lastName = last;
        this.salary = salary;
        this.department = dept;
    }

    public static Employee byName(String first, String last) {
        return new Employee(first, last, UNKNOWN, null);
    }

    public static Employee bySalaryAndDept(String salary, String dept) {
        return new Employee("John", "Doe", salary, dept);
    }
}

Можно даже ограничить видимость общего конструктора, установив private, тогда для создания экземпляров Employee придётся использовать указанные статические методы-генераторы.

A: В таком случае (когда все поля одного типа) лучше использовать паттерн Строитель.
https://refactoring.guru/ru/design-patterns/builder
То есть Вам необходимо создать конструктор по умолчанию, который будет создавать пустой объект и возвращать ссылку на него. А после вызывать на нем методы addFirstName, addLastName, addSalary, addDepartment
Employee employee = new Employee().addFirstName("Bob").addSalary("1000");

А они будут реализованы следующим способом:
public Employee addFirstName(String firstName) {
    this.setFirstName(firstName);
    return this;
}


text:
Q: get table without Added column in sql query I have a Process table in sql server database like this:

I need to select Process if Rolename exists in to RoleTable like this:
 select ID,WorkflowXML
    from
    (
    select m.c.value('@RoleName','nvarchar(max)') as Rolename,p.*
    from Process as p
    outer apply p.WorkflowXML.nodes('/workflow/Tasks/Task[@type="start"]/TaskUsers/TaskUser') as m(c)
    ) as Pro where Pro.Rolename in
    (SELECT * from RoleTable)

In this select Rolename adds to Process. I need to only Process table. I can add Process fields (ID,WorkflowXML) to query. If I change Process table design I should edit query. This is not very good.
Is there a way to select Process table in query without adding Process fields like this?
select Pro
        from
        (
        select m.c.value('@RoleName','nvarchar(max)') as Rolename,p.*
        from Process as p
        outer apply p.WorkflowXML.nodes('/workflow/Tasks/Task[@type="start"]/TaskUsers/TaskUser') as m(c)
        ) as Pro where Pro.Rolename in
        (SELECT * from RoleTable)

Thanks.

A: You can join this table like:
select p.*
from Process as p
outer apply p.WorkflowXML.nodes('/Tasks/Task[@type="start"]/TaskUsers/TaskUser') as  m(c)
INNER JOIN RoleTable r
    ON r.Rolename = m.c.value('@RoleName','varchar(max)')


text:
Q: Dataframe nested dictionary to multi-index dataframe First to construct a simplified version of my question dataset, this is only helping to create a sample, I only have the final nest_dict on hand. Meaning I dont have dfs separately:
df1 = pd.DataFrame({'val':{'a': 1, 'b':2, 'c':3}})
df2 = pd.DataFrame({'val':{'a': 3, 'b':4, 'c':1}})
df3 = pd.DataFrame({'val':{'a': 2, 'b':1, 'c':4}})
dfs = [df1, df2, df3]
dates = ['2017-01-26','2017-02-03','2017-02-10']
nest_dict = {}
for date, d in zip(dates, dfs):
        nest_dict[date] = d

I would like to convert it to a Multi-Index Dataframe.
date1 a val1
      b val2
      c val3
date2 a val1
      b val2
      c val3
....

Its basically a dataframe with a date as key, it could easily become a panel, but since its been deprecated, how would I transform it to a multiindex dataframe?
I did try following, but it does not work:
d = {(key, item) for key, item in corr_SH50.items()}
TypeError: 'DataFrame' objects are mutable, thus they cannot be hashed

A: concat with keys:
pd.concat(dfs,keys=dates)

              val
2017-01-26 a    1
           b    2
           c    3
2017-02-03 a    3
           b    4
           c    1
2017-02-10 a    2
           b    1
           c    4


text:
Q: C++11 factory using variadic template I am working on a factory that can register and create classes with a different set a parameter types and numbers. I search over the internet and I managed to create this class:

template< typename Key, typename BaseClass >
class Factory {
    static_assert( std::has_virtual_destructor< BaseClass >::value,
        "BaseClass must have a virtual destructor" );
public:
    template< typename DerivedClass, typename ... Args >
    void register_creator( const Key& key )
    {
        static_assert( std::is_base_of< BaseClass, DerivedClass >::value,
            "DerivedClass must be a subclass of BaseClass" );
        static_assert( std::is_constructible< DerivedClass, Args... >::value,
            "DerivedClass must be constructible with Args..." );
        creators_.emplace(
            CreatorKey { key, create_function_type_index< Args... >() },
            reinterpret_cast< CreateFunc< > >( create_function_impl<
                DerivedClass, Args... > ) );
    }

    template< typename ... Args >
    std::unique_ptr< BaseClass > create(
        const Key& key,
         Args&&... args ) const
    {
        auto creator = creators_.find(
            { key, create_function_type_index< Args... >() } );
        if( creator != creators_.end() ) {
            return reinterpret_cast< CreateFunc< Args... > >( creator->second )(
                std::forward< Args>( args )... );
        } else {
            return {};
        }
    }

private:
    template< typename ... Args >
    static std::type_index create_function_type_index()
    {
        return {typeid( CreateFunc<Args...> )};
    }

    template< typename DerivedClass, typename ... Args >
    static std::unique_ptr< BaseClass > create_function_impl(
        const Args&... args )
    {
        return std::unique_ptr< BaseClass > { new DerivedClass {
            std::forward< const Args& >( args )... } };
    }

    template< typename ... Args >
    using CreateFunc = typename std::add_pointer< std::unique_ptr< BaseClass >( const Args&... ) >::type;
    using CreatorKey = std::pair< Key, std::type_index >;

    std::map< CreatorKey, CreateFunc< > > creators_;
};

My goal is to be able to run this kind of code:

class ___A___ {};
class ___B___ {};

class ___Base___ {
public:
    virtual ~___Base___() = default;
protected:
    ___Base___( ___A___ a, ___B___ b ) : a_( a ), b_( b ) {
    }
protected:
    ___A___ a_;
    ___B___ b_;
};

class ___Derived___: public ___Base___ {
public:
    ___Derived___( ___A___& a, ___B___& b ) : ___Base___( a, b ) {
    }
};

class ___Derived2___: public ___Base___ {
public:
    ___Derived2___( ___A___ a, ___B___ b ) : ___Base___( a, b ) {
    }
};

class ___Derived3___: public ___Base___ {
public:
    ___Derived3___( ___A___& a, ___B___ b ) : ___Base___( a, b ) {
    }
};

Factory< std::string, ___Base___ > factory;
factory.register_creator< ___Derived___, ___A___ &, ___B___& >( "Derived" );
factory.register_creator< ___Derived2___, ___A___, ___B___ >( "Derived2" );
factory.register_creator< ___Derived3___, ___A___ &, ___B___ >( "Derived3" );

___A___ a;
___B___ b;
auto D = factory.create( "Derived", a, b );
auto D2 = factory.create( "Derived2", a, b );
auto D3 = factory.create( "Derived3", a, b );

The registers works perfectly for both reference and value parameters but I cannot manage to instiate them using the creators. During my debugging, I saw that all the parameters where given by reference and never by value.

A: Using deduced types like this:
auto D = factory.create( "Derived", a, b );

in order to do a cast is something you should never do.  The type deduces here will be basically &decltype(a) (not decltype(&a); a reference to the type of a, not the type of a pointer to a).
return reinterpret_cast< CreateFunc< Args... > >( creator->second )(
            std::forward< Args>( args )... );

this requires exact type matching.  When this matches the type, it happens accidentally more than anything.
To do what you want, you have a whole pile of work to do, even if you want to only support "exact matching" of types.
Given a type T, there are a number of ways it can be used as an argument to a function.
It can be moved into the argument: T&&.  A "sink" argument.
It can be duplicated into the argument: T.  A "value" argument.
It can be referred to by the argument but guaranteed not to be modified, T const&.  An "in" argument.
It can be referred to by the argument, and possibly modified, T&.  An "in/out" argument.
The other options are possible, but are less interesting.
At the point where you register your function, you have to work out both the type T and which of the 4 above cases you are dealing with.
Then, at the point where you want to call your function, you have to work out the type T and which of the above 4 you support.
Then you have to inject the code to glue the incoming argument to the function to call.
We can simplify this by having fewer kinds of argument than the above 4 relatively commonly used in C++ code.  For example, "value" can usually replace "sink" at the cost of one extra std::move construction.
If you don't want the caller to have to know exactly what kind of protocol the called type needs, you have to type erase the details.
Imagine an adapter:
template<class T>
struct arg_adapter;

it can be constructed from a T&&, T const& or T&.  When it is constructed, it records a void* pointer to the incoming object, and which of the 3 categores of type it was passed.
It has a .get<U> method, where U can be any of T&&, T const& or T&.  It checks if the .get is compatible; if it is, it casts the void* stored within to remove_reference_t<U>*, dereferences it, and static_cast<U>'s it.
If it fails, it throws an exception or calls exit(-1) or somesuch.
Now you store std::function< Out(arg_adapter<std::decay_t<Args>>...) > instead of std::function< Out(Args...) >.
You know, something like this:
template
    struct tag_t {};
template<class Dest>
using p_getter = Dest(*)(void*);
template<class T>
struct arg_vtable {
    p_getter<T&> ref = 0;
    p_getter<T const&> cref = 0;
    p_getter<T> value = 0;
    p_getter<T&&> move = 0;
};
template<class Dest, class Src>
p_getter<Dest> make_getter() {
    return [](void* ptr)->Dest{
        return (Src&&)(*static_cast<std::decay_t<Src>*>(ptr));
    };
}

template<class T>
arg_vtable<T> make_arg_vtable( tag_t<T const&> ) {
    return {
        0,
        make_getter<T const&, T const&>(),
        make_getter<T, T const&>(),
        0
    };
}
template<class T>
arg_vtable<T> make_arg_vtable( tag_t<T&> ) {
    return {
        make_getter<T&, T&>(),
        make_getter<T const&, T&>(),
        make_getter<T, T&>(),
        0
    };
}
template<class T>
arg_vtable<T> make_arg_vtable( tag_t<T&&> ) {
    return {
        0,
        make_getter<T const&, T&&>(),
        make_getter<T, T&&>(),
        make_getter<T&&, T&&>(),
    };
}
template<class T>
arg_vtable<T> make_arg_vtable( tag_t<T const&&> ) {
    return make_arg_vtable( tag_t<T const&>{} );
}
template<class T, class U>
arg_vtable<T> make_arg_vtable( tag_t<T volatile&&> ) {
    return make_arg_vtable( tag_t<T&&>{} );
}
template<class T, class U>
arg_vtable<T> make_arg_vtable( tag_t<T volatile&> ) {
    return make_arg_vtable( tag_t<T&>{} );
}
template<class T, class U>
arg_vtable<T> const* get_arg_vtable( tag_t<U> tag ) {
    static const arg_vtable<T> retval = make_arg_vtable<T>(tag);
    return &retval;
}

template<class T>
struct arg_adapter {
    arg_vtable<T> const* vtable = 0;
    void* pvoid = 0;
    template<class U>
    arg_adapter( U&& u ):
        vtable( get_arg_vtable<T>( tag_t<U&&>{} ) ),
        pvoid( (void*)std::addressof(u) )
    {}
    T get(tag_t<T>) {
        if (!vtable->value) throw std::invalid_argument("value");
        return vtable->value(pvoid);
    }
    T&& get(tag_t<T&&>) {
        if (!vtable->move) throw std::invalid_argument("move");
        return vtable->move(pvoid);
    }
    T& get(tag_t<T&>) {
        if (!vtable->ref) throw std::invalid_argument("ref");
        return vtable->ref(pvoid);
    }
    T const& get(tag_t<T const&>) {
        if (!vtable->ref) throw std::invalid_argument("cref");
        return vtable->cref(pvoid);
    }
};

template<class R, class...Args>
using adapt_function = std::function< R(arg_adapter<std::decay_t<Args>>...) >;

template<class R, class...Args, class F>
adapt_function<R, Args...> adapt_args( F&& f ) {
    return [f=std::forward<F>(f)](arg_adapter<std::decay_t<Args>>... args)->R{
        return f( args.get( tag_t<Args>{} )... );
    };
}

using func_token = std::shared_ptr<void>;

template<class R, class...Args>
R invoke_token( func_token f, Args&&... args ) {
    auto const* pf = static_cast<adapt_function<R, Args...>*>(f.get());
    return (*pf)( std::forward<Args>(args)... );
}

template<class R>
struct factories {
    std::map< std::string, func_token > funcs;

    template<class...Args, class F>
    void add( std::string s, F&& f ) {
        funcs[s] = std::make_shared<adapt_function<R,Args...>>(adapt_args<R,Args...>(std::forward<F>(f)));
    }

    template<class...Args>
    R invoke( std::string s, Args&&... args ) {
        auto it = funcs.find(s);
        if (it==funcs.end()) throw std::invalid_argument("s");
        return invoke_token<R>( it->second, std::forward<Args>(args)... );
    }
};

Live example
It needs forwarding overloads to arg_adapter::get like the ones for make_arg_vtable I suspect.
Overall, I think this is a bad idea, because the invokers only handle cv conversion and nothing else.  Anything else causes a crash or other undefined behavior.


text:
Q: How to make function that swallows exceptions inline fun <T> rest(request: () -> T): T = try {
    request()
} catch (e: HttpException) {
    val requestId = e.response().raw().request().header(REQUEST_ID_HEADER)
    if (requestId != null) {
        Dialog(requestId, R.string.oops).show(fragmentManager, null)
    } else {
        throw e
    }
}

It should perform some REST request (in the request parameter) and if it fails, and it contained the specified HTTP header, display dialog with that header.
But the compiler complains at the line with Dialog, that it doesn't return T, but Unit. But that's basicaly what I want! How can I do this?
One solution that crosses my mind it to set function's return type to T? and return null, but it feel dirty doing this in Kotlin.

A: Returning null is not dirty per se. Using nulls can be abused sometimes, but this is a perfectly valid use case for using null.
Kotlin allows you to use null in safe and nice ways, so don't be afraid to use it!
Another option is to throw an exception also in the case you show the dialog (whether or not the header is present).
In order to choose, you have to ask yourself what the code calling rest() will do in case the dialog is shown. It has to deal with the absence of T in one way or another (null or exception). This is because showing a dialog is not something that ends the execution of your function.
Last but not least, there is also an option to deal with the result outside of the rest() method. Improving on Taras' answer:
sealed class Result<out T : Any> {
    class Success<out T : Any>(val value: T) : Result<T>()
    class ErrorWithId(val exception: Exception, val requestId: String) : Result<Nothing>()
    class Error(val exception: Exception) : Result<Nothing>()
}

inline fun <T : Any> rest(request: () -> T): Result<T> = try {
    Result.Success(request())
} catch (e: HttpException) {
    val requestId = e.response().raw().request().header(REQUEST_ID_HEADER)
    if (requestId != null) {
        Result.RecoverableError(e, requestId)
    } else {
        Result.Error(e)
    }
}

private fun thingCallingRest() {
    val result = rest(::testRequest)
    when (result) {
        is Result.Success -> Log.v("__DEBUG", "success: ${result.value}")
        is Result.ErrorWithId -> Dialog(result.requestId, R.string.oops).show(fragmentManager, null)
        is Result.Error -> throw result.exception
    }
}

A: You could solve it by generic Result type:
sealed class Result<out T : Any> {
    class Success<out T : Any>(val value: T) : Result<T>()
    class Error(val exception: Exception, val requestId: String?) : Result<Nothing>()
}

inline fun <T : Any> rest(request: () -> T): Result<T> = try {
    Result.Success(request())
} catch (e: HttpException) {
    val requestId = e.response().raw().request().header(REQUEST_ID_HEADER)
    Result.Error(e, requestId)
}

private fun testRest() {
    val result = rest(::testRequest)
    when (result) {
        is Result.Success -> Log.v("__DEBUG", "success: ${result.value}")
        is Result.Error -> {
            result.requestId?.let {
                Dialog(it, R.string.oops).show(fragmentManager, null)
            } ?: run {
                throw result.exception
            }
        }
    }
}

A: Returning null might feel ugly at first, but what are the options?
Option 1: Throwing an exception
If you need further information on why the code failed you should throw an exception.
Let's take a look at Kotlin's single function as an example:
listOf<Int>().single()

will throw

NoSuchElementException: List is empty.

listOf<Int>(1, 1).single { it == 1 }

will throw

IllegalArgumentException: Collection contains more than one matching element.

This is what I mean with further information. The type of exception and the given message might provide you with ways to decide how to continue.
Option 2: Returning null
In case you just want to know whether it failed or not returning null would a good way to signal that. Even Kotlin's standard library does that for example with singleOrNull().
listOf<Int>().singleOrNull() // returns null

Providing a fallback is also really concise using the elvis operator:
listOf<Int>().singleOrNull() ?: 1 // default element


text:
Q: How can I compare specific ranges of data between two excel worksheets, identify the differences, and fill in the blanks? I cannot seem to solve this VBA riddle I've been working on, please help. I'm new at this and I'm probably over complicating it
Essentially, there are two worksheets - one titled Master and the other will be created fresh daily by date. The Master tab contains 10000 rows of historical data filled from Columns A:X. The other tab generally has about 300 rows of fresh data and also contains like Columns A:X, only with blank cells in Columns A:B. I'm trying to find matches with the master tab, and if so, populate the corresponding results in cells A and B from the master to the daily. If nothing, leave blank. It is crucial that Cells H:M and R:W are identical matches.
Below is my crazy attempt, Thank you in advance for helping
Sub Previous()

Dim u As Long
u = 2
Do While ActiveSheet.Cells(u, 6) <> ""
    Dim i As Long
    i = 2
    Do While Worksheets("Master").Cells(i, 6) <> ""
        If ActiveSheet.Range(Cells(u, 8), Cells(u, 13)) _
            = Worksheets("Master").Range(Cells(i, 8), Cells(i, 13)) _
            And ActiveSheet.Range(Cells(u, 18), Cells(u, 23)) _
            = Worksheets("Master").Range(Cells(i, 18), Cells(i, 23)) _
            And ActiveSheet.Cells(u, 2) = "" Then
                ActiveSheet.Range(Cells(u, 1), Cells(u, 2)) _
                = Worksheets("Master").Range(Cells(i, 1), Cells(i, 2))
        Else: i = i + 1
        End If
    Loop
    u = u + 1
    i = 2
Loop
End Sub

A: First of all, I don't believe this snippet does what you think it does.
Worksheets("Master").Range(Cells(i, 8), Cells(i, 13))

In that snippet Cells(i,8) references the ActiveSheet, not Sheets("Master").
There is a note on this about halfway down the page on msdn's Range Object documentation.
You can simplify your code a great deal by assigning some worksheet variables.
dim actWs as Worksheet
dim mstWs as Worksheet
Set actWs = Activesheet
Set mstWs = Sheets("Master")
'then reference your ranges like this
mstWs.Cells(i,8)

But, that's not what is causing your runtime error.
Simply put, you can not compare ranges that way. You need to check the value of each cell, so you end up with another layer of nested loops.
dim u as long ' active sheet row counter
dim i as long ' master sheet row counter
dim c as long ' column counter

For u = 2 to actWs.Range("A" & .Rows.Count).End(xlUp).Row 'find last row in column "A" of active sheet
    For i = 2 to  mstWs.Range("A" & .Rows.Count).End(xlUp).Row 'find last row in column "A" of master sheet
        For c = 8 to 13
            If actWs.Cells(i,c) = mstWs.Cells(i,c) Then
                'Do stuff
            End if
        next c 'next column
    next i 'next master sheet row
next u 'next active sheet row

This is obviously a simplified version of what you'll need to do. Be careful of line continuations (" _ ") and code indentation. It's easy to trick yourself into thinking your program should flow in a way that it isn't. It would be advisable to store the value's you're checking for equality in variables to make it easier to read. You might more readily notice where you're going wrong.

A: Sub Previous()
Dim actWs As Worksheet
Set actWs = ActiveSheet
Dim mstWs As Worksheet
Set mstWs = Sheets("Master")
Dim u As Long
Dim i As Long
u = 2
Do While actWs.Cells(u, 6) <> ""
For i = 2 To mstWs.Range("C" & Rows.Count).End(xlUp).Row
If actWs.Cells(u, 8) = mstWs.Cells(i, 8) And actWs.Cells(u, 9) = mstWs.Cells(i, 9) And actWs.Cells(u, 10) = mstWs.Cells(i, 10) And actWs.Cells(u, 11) = mstWs.Cells(i, 11) And actWs.Cells(u, 12) = mstWs.Cells(i, 12) And actWs.Cells(u, 13) = mstWs.Cells(i, 13) And actWs.Cells(u, 18) = mstWs.Cells(i, 18) And actWs.Cells(u, 19) = mstWs.Cells(i, 19) And actWs.Cells(u, 20) = mstWs.Cells(i, 20) And actWs.Cells(u, 21) = mstWs.Cells(i, 21) And actWs.Cells(u, 22) = mstWs.Cells(i, 22) And actWs.Cells(u, 23) = mstWs.Cells(i, 23) Then
mstWs.Select
Range(Cells(i, 1), Cells(i, 2)).Select
Selection.Copy
actWs.Select
Range(Cells(u, 1), Cells(u, 2)).Select
actWs.Paste
End If

Next i

u = u + 1
Loop
End Sub