text:
Q: Error creating bean with name 'springSecurityFilterChain' defined in class path Hoping are well.
I'm not using web.xml for my spring configuration, and when running my repository tests after migrating to JHipster I'm getting this error:

Caused by: org.springframework.beans.factory.BeanCreationException:
Error creating bean with name 'springSecurityFilterChain' defined in
class path resource
[org/springframework/security/config/annotation/web/configuration/WebSecurityConfiguration.class]:
Bean instantiation via factory method failed; nested exception is
org.springframework.beans.BeanInstantiationException: Failed to
instantiate [javax.servlet.Filter]: Factory method
'springSecurityFilterChain' threw exception; nested exception is
java.lang.IllegalStateException: Cannot apply
org.springframework.security.config.annotation.web.configurers.ExpressionUrlAuthorizationConfigurer@7744f9fa
to already built object

Is there any recommendation?


text:
Q: Storing date value into Core Data in Objective C Can anyone tell me please how to save only date value to Core Data using objective C? I am using UIDatePicker. I searched a lot, but couldn't find any. Can you be more specific because i am newbie. Thanks

Here is my code for adding data to core data database. But instead of formatting dates into string I would like to save as a NSdate. I am creating an calendar app that stores events into CoreData. Is there any help?
- (IBAction)btnSave:(UIBarButtonItem *)sender {

    AppDelegate *delegate = [UIApplication sharedApplication].delegate;
    NSManagedObjectContext *context = [delegate managedObjectContext];
    NSManagedObject *dataRecord = [NSEntityDescription insertNewObjectForEntityForName:@"Scheduler" inManagedObjectContext:context];

    [dataRecord setValue:self.txtBxCustomerName.text forKey:@"customerName"];
    [dataRecord setValue: [self date] forKey:@"date"];
    [dataRecord setValue:[self begin] forKey:@"startTime"];
    [dataRecord setValue:[self end] forKey:@"endTime"];

    NSError *error;
    if (![context save:&error]) {
        NSLog(@"Error! %@", error);
    }

    [self dismissViewControllerAnimated:true completion:nil];
}

- (IBAction)datePicker:(id)sender {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MM-dd-yyyy"];
    NSString *string = [dateFormat stringFromDate:self.dateTime.date];
    date = string;
}

- (IBAction)startTimePicker:(id)sender {
    NSDateFormatter *timeFormat = [[NSDateFormatter alloc] init];
    [timeFormat setDateFormat:@"HH:mm"];
    NSString *str = [timeFormat stringFromDate:self.startTime.date];
    begin = str;
}

- (IBAction)endTimePicker:(id)sender {
    NSDateFormatter *endTimeFormatt = [[NSDateFormatter alloc] init];
    [endTimeFormatt setDateFormat:@"HH:mm"];
    NSString *sting = [endTimeFormatt stringFromDate:self.endTime.date];
    end = sting;
}

A: Get the date from the picker with
NSDate *chosenDate = myDatePicker.date;

and then set it to the desired attributed (in the example startDate) of your model, which should be define in Core Data as type Date
myCoreDataObject.startDate = chosenDate;

or even shorter
myCoreDataObject.startDate = myDatePicker.date;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multi-threading on UI Thread I need to update 6 graphs real-time. So I create a separate queue for every single graph and try to update it with timer.schedule but it does not really work. In particular, if I comment calls of every single timer.schedule and leave only the first one it works well. But even if I add second timer.schedule (so 1 and 2 timers only) it freezes. Here is the code I use:
timer_graph1 = new Timer();
timer_graph1.schedule(new Graph1(), 20, 20);
timer_graph2 = new Timer();
timer_graph2.schedule(new Graph2(), 20, 20);
timer_graph3 = new Timer();
timer_graph3.schedule(new Graph3(), 20, 20);
timer_graph4 = new Timer();
timer_graph4.schedule(new Graph4(), 20, 20);
timer_graph5 = new Timer();
timer_graph5.schedule(new Graph5(), 20, 20);
timer_graph6 = new Timer();
timer_graph6.schedule(new Graph6(), 20, 20);

class Graph1 extends TimerTask {

    public void run() {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //add data to the graph and update
                mChart1.invalidate();
            }
        });

    }
}

//same structure as for Graph1
class Graph2 extends TimerTask {

}

Could you please suggest what's wrong with this approach?

A: From your code I can tell either your refreshing isn't updated to GUI or your GUI is blinking fast.
The rule of thumb on updating GUI is:

*

*Update data at backend by separate thread(s). Use double buffering if needed.

*Invoke all GUI update inside SwingUtilities.invokeLater() so the update is done inside EDT thread.


text:
Q: Not able to receive file from client in python I am trying to program compilation server which compiles a C program sent by client and returns an object file which can then be linked and executed at the client. Here are my client and server programs respectively
client.py:
# Compilation client program

import sys, socket, string

File = raw_input("Enter the file name:")
ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssock.connect(('localhost', 5000))

csock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
csock.connect(('localhost', 5001))

f = open(File, "rb")
data = f.read()
f.close()
ssock.send(File)                 #send filename
ssock.send(data)                 #send file
fd=raw_input("Enter a key to start recieving object file:")

data=csock.recv(1024)            #receive status
if data=="sucess\n":
    File=File.replace(".c",".o") #objectfile name
    print "Object file, "+File+", recieved sucessfully"
else:
    print "There are compilation errors in " + File
    File="error.txt"             #errorfile name
    print "Errors are reported in the file error.txt"

fobj=open(File,"wb")
while 1:
    data=ssock.recv(1024)        # if any error in c sourcefile then  error gets
                                 # eported in errorfile "error.txt" else objectfile is
                                 # returned from server
    if not data:break
    fobj.write(data)
fobj.close()
ssock.close()
csock.close()

server.py
#Compilation Server program

import subprocess
import socket, time, string, sys, urlparse, os
ssock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
ssock.bind(('', 5000))
ssock.listen(2)
print 'Server Listening on port 5000'
csock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
csock.bind(('', 5001))
csock.listen(2)
print 'Control server listening on port 5001'
client, claddr = ssock.accept()
controlsoc, caddr = csock.accept()

filename=client.recv(1024)        #receive filename
print filename
###############  This code is not working, i'm not getting the reason   #######
###############    I want to receive a file more than 1KB from client   #######
f = open(filename,"wb")           #receive file======
while 1:
    data = client.recv(1024)
    if not data: break
    f.write(data)
f.close()
###############
###############

data="gcc -c " + filename + " 2> error.txt"  #shell command to execute c source file
                                             #report errors if any to error.txt
from subprocess import call

call(data,shell=True)                        #executes the above shell command
fil = filename.replace(".c",".o")
if (os.path.isfile(fil))== True:             #test for existence of objectfile
    data = "sucess\n"                        #no objectfile => error in compilation
    filename = filename.replace(".c",".o")
else:
    data = "unsucessful\n"
    print data+"hi"
    filename = "error.txt"

controlsoc.send(data)
f = open(filename,"rb")
data=f.read()
f.close()
print data

client.send(data)

client.close()
controlsoc.close()

I'm not able to recieve files of multiple KB. Is there any flaw in my code or how should i modify my code in order to achieve my objective of coding a compilation server.
Please help me with this regard..Thanks in advance

A: The problem here is you assume that ssock.send(File) will result in filename=client.recv(1024) reading exactly the filename and not more, but in fact the receiving side has no idea where the filename ends and you end up getting the file name and part of the data in the filename variable.
TCP connection is a bi-directional stream of bytes. It doesn't know about boundaries of your messages. One send might correspond to more then one recv on the other side (and the other way around). You need an application-level protocol on top of raw TCP.
The easiest in your case would be to send a text line in the form file-size file-name\n as a header. This way your server would be able to not only separate header from file data (via newline) but also know how many bytes of file content to expect, and reuse same TCP connection for multiple files.


text:
Q: Style TreeItem at the time of creation I would like to have some of my TreeItems with different font, italic or color and I see that perhaps TreeCell in JavaFX should be used somehow.
I want to apply this at the moment I create the TreeItem, i.e. when I do
root.getChilden().add(...)

I would imagine that there should be a way to access the style properties for this TreeItem and apply some set methods accordingly.
Regards
Update : this is more or less what I want to achieve
1.root is created
2. Add a child test i. e. root.getChildren.add("test")
3.set this child italic and red
4. Add another child test1
5 set the child test1 to font size 12 and bold


text:
Q: Sort an array of object fetched from db rendered in a Flatlist React native I have this array of object that i want to sort when i display them on my screen, sort them by type.here is a look of the array:
Array [
  Object {
    "lien": "get_praticien",
    "name": "tag service  centre 2",
    "type": "Tag",
  },
  Object {
    "lien": "get_praticien",
    "name": "Ambulance",
    "type": "Acte",
  },
  Object {
    "lien": "get_praticien",
    "name": "Réadaptation Fonctionnelle",
    "type": "speciality",
  },
  Object {
    "lien": "get_praticien",
    "name": "Infirmité Motrice",
    "type": "Tag",
  },......

so i want the objects that have a type:"speciality" to be at the top of the flatlist, and the others after on whatever order.
i'm using a flatlist :
<FlatList
                data={this.state.dataSource}
                keyExtractor={item=> { return item.id.toString()}}
                renderItem= {({item})=> <MedItem Med={item}  />} />

i'll appreciate you answers

A: use a sort function to sort your data list before rendering. Also you may want to sort them on server side if you have multiple pages of data.

const test = [
  {
    "lien": "get_praticien",
    "name": "tag service  centre 2",
    "type": "Tag",
  },
  {
    "lien": "get_praticien",
    "name": "Ambulance",
    "type": "Acte",
  },
  {
    "lien": "get_praticien",
    "name": "Réadaptation Fonctionnelle",
    "type": "speciality",
  },
  {
    "lien": "get_praticien",
    "name": "Infirmité Motrice",
    "type": "Tag",
  },
  {
    "lien": "get_praticien",
    "name": "Infirmité Motrice",
    "type": "speciality",
  },
  {
    "lien": "get_praticien",
    "name": "Ambulance",
    "type": "Acte",
  },
  {
    "lien": "test",
    "name": "test Motrice",
    "type": "speciality",
  },
]

console.log(test.sort((a,b) =>  a.type === 'speciality' ? -1 : 1))


text:
Q: Passing the parameters to a callback function : Scope issue I have this someFunction in the the view of a backbone app. Now I want to send parameters defined in this function to a callback function of jConform function. I cannot figure out how scope works in such cases.
someFunction: function() {
    var thisView = this,
        paramA = 10,
        paramB = $(ev.currentTarget).data("id"),
        paramC = this.getConfig(paramB);

    jConfirm(paramC.jConfirmMessage, "Confirm Deactivation", function (ans) {
                        return thisView.anotherFunction(ans, paramC);
                    });
}

anotherFunction: function(ans, paramC){
    ...
}

How can access the paramC from sumeFunction into  anotherFunction ?
Thanks. !

A: If you are unsure about: if paramC is available in - return thisView.anotherFunction(ans, thisView.paramC).
Then answer is -  Yes, paramC is available in that statement.
Reason - the callback function defined here remembers the environment in which it was created. This idea is similar to closure. Read about closure and lexical scope here
But if your question is about how to access paramC inside the body of anotherFunction method, then you can do what as described in the first answer. Or you can create a new property of view object and assign paramC  to it.
And one last thing - javascript has functional scope. you can read about javascript scopes here.
Hope it helps.

A: Try this way
someFunction: function() {
//private
    var that = this;
    jConfirm(paramC.jConfirmMessage, "Confirm Deactivation", function (ans) {
                        return thisView.deactivateConfirm(ans, paramC);
                    });
    return {
//public
        thisView : that,
        paramA : 10,
        paramB : $(ev.currentTarget).data("id"),
        paramC : that.getConfig(paramB)
    };
}

anotherFunction: function(ans, paramC){
  //use it here
}

anotherFunction(ans, someFunction.paramC);

Useful links
first link
second link

A: to expose inner functions and variables you need to return something from the first function. Its good that you wrap them in a return statement.
someFunction: function() {
    var thisView = this;

    thisView.paramA = 10;
    thisView.paramB = $(ev.currentTarget).data("id");
    thisView.paramC = this.getConfig(paramB);

    return {
        paramA : thisView.paramA,
        paramB : thisView.paramB,
        paramC : thisView.paramC,
        jConfirm: function(thisView.paramC.jConfirmMessage, "Confirm Deactivation", function (ans)) {
                        return thisView.anotherFunction(ans, thisView.paramC)
        }
    }
}

anotherFunction: function(ans, paramC){
    console.log(someFunction.paramC);
}


text:
Q: SQL Server procedure returning no results OK, so I have the following procedure in my SQL Server 2005 Database.  I am trying to figure out why it is giving me no results.  The user attempting to access it is an administrator, but I have also tried accessing it with another user, and I still get no results.  The Bond is returned in a basic query of the Bond table.  I am just trying to figure out why this is returning no results.  Any help is appreciated.
ALTER PROCEDURE dbo.GetBondAmounts
(
    @Username varchar(20)
)
AS
DECLARE @Admin AS bit
SELECT @Admin = Admin FROM Users WHERE Username = @Username
if(@Admin = 1)
BEGIN
    RETURN
    SELECT Bond.ID, SUM(Charge.BondAmount) + SUM(ChargeWithoutPower.BondAmount) Amount,
    SUM(Charge.BondPremium) + SUM(ChargeWithoutPower.BondPremium) + SUM(Forfeiture.AmountPaid)
    + SUM(Forfeiture.CostOfApprehension) - SUM(Payment.Amount) - SUM(BalanceForgiveness.AmountForgiven) Balance
    FROM Bond LEFT OUTER JOIN Payment ON Bond.ID = Payment.Bond
    LEFT OUTER JOIN BalanceForgiveness ON Bond.ID = BalanceForgiveness.BondID
    LEFT OUTER JOIN Powers ON Bond.ID = Powers.Bond
    LEFT OUTER JOIN Charge ON Powers.Surety = Charge.PowerSurety
    AND Powers.PowerPrefix = Charge.PowerPrefix AND Powers.PowerNumber = Charge.PowerNumber
    LEFT OUTER JOIN ChargeWithoutPower ON Bond.ID = ChargeWithoutPower.ID
    LEFT OUTER JOIN Forfeiture ON Bond.ID = Forfeiture.Bond
    LEFT OUTER JOIN BondFee ON Bond.ID = BondFee.Bond
    GROUP BY Bond.ID
END
ELSE
BEGIN
    RETURN
    SELECT Bond.ID, SUM(Charge.BondAmount) + SUM(ChargeWithoutPower.BondAmount) Amount,
    SUM(Charge.BondPremium) + SUM(ChargeWithoutPower.BondPremium) + SUM(Forfeiture.AmountPaid)
    + SUM(Forfeiture.CostOfApprehension) - SUM(Payment.Amount) - SUM(BalanceForgiveness.AmountForgiven) Balance
    FROM Bond LEFT OUTER JOIN UserAgency ON Bond.Agency = UserAgency.Agency
    LEFT OUTER JOIN Payment ON Bond.ID = Payment.Bond
    LEFT OUTER JOIN BalanceForgiveness ON Bond.ID = BalanceForgiveness.BondID
    LEFT OUTER JOIN Powers ON Bond.ID = Powers.Bond
    LEFT OUTER JOIN Charge ON Powers.Surety = Charge.PowerSurety
    AND Powers.PowerPrefix = Charge.PowerPrefix AND Powers.PowerNumber = Charge.PowerNumber
    LEFT OUTER JOIN ChargeWithoutPower ON Bond.ID = ChargeWithoutPower.ID
    LEFT OUTER JOIN Forfeiture ON Bond.ID = Forfeiture.Bond
    LEFT OUTER JOIN BondFee ON Bond.ID = BondFee.Bond
    WHERE UserAgency.Username = @Username
    GROUP BY Bond.ID
END

I am accessing this procedure using C# as follows:
bondingData.Merge(getBondAmountsAdapter.GetData(currentUser.Username));

This is the line I added to test and see if any results were returned:
MessageBox.Show("Bond Count A: " + bondingData.Bond.Count.ToString() + "\r\nBond Count B: " + bondingData.GetBondAmounts.Count.ToString());

When I ran it, here is the result I received:
Bond Count A: 1
Bond Count B: 0

[edit]
OK, so here is my solution to my issue:
ALTER PROCEDURE dbo.GetBondAmounts
(
    @Username varchar(20)
)
AS
    SELECT Bond.ID, dbo.GetBondTotal(Bond.ID) Total, dbo.GetBondBalance(Bond.ID) Balance
    FROM Bond LEFT OUTER JOIN
    UserAgency ON Bond.Agency = UserAgency.Agency
    WHERE UserAgency.Username = @Username
    OR EXISTS (SELECT * FROM Users WHERE Username = @Username AND Admin = 1)
    GROUP BY Bond.ID

These are the 2 Stored Functions that are called here.  Not sure how efficient it is, but there will not be that many payments or anything related to the individual bonds.  It just might get slow when the program has a lot of records.
Function 1:
ALTER FUNCTION dbo.GetBondTotal
(
@BondID bigint
)
RETURNS money
AS
BEGIN
    DECLARE @PowersTotal AS money;
    DECLARE @ChargesTotal AS money;
    DECLARE @BondFeeTotal AS money;
    DECLARE @ForfeitureCosts AS money;
    SELECT @PowersTotal = SUM(BondPremium)
    FROM Charge INNER JOIN Powers ON Charge.PowerSurety = Powers.Surety
    AND Charge.PowerPrefix = Powers.PowerPrefix
    AND Charge.PowerNumber = Powers.PowerNumber
    WHERE Bond = @BondID
    SELECT @ChargesTotal = SUM(BondPremium)
    FROM ChargeWithoutPower
    WHERE BondID = @BondID
    SELECT @BondFeeTotal = SUM(Amount)
    FROM BondFee WHERE Bond = @BondID
    SELECT @ForfeitureCosts = SUM(CostOfApprehension) + SUM(AmountPaid)
    FROM Forfeiture WHERE Bond = @BondID
    RETURN @PowersTotal + @ChargesTotal + @BondFeeTotal + @ForfeitureCosts
END

Function 2:
ALTER FUNCTION dbo.GetBondBalance
(
@BondID bigint
)
RETURNS MONEY
AS
    BEGIN
    DECLARE @PowersTotal AS money;
    DECLARE @ChargesTotal AS money;
    DECLARE @BondFeeTotal AS money;
    DECLARE @ForfeitureCosts AS money;
    DECLARE @PaymentTotal AS money;
    DECLARE @AmountForgiven AS money;
    SELECT @PowersTotal = SUM(BondPremium)
    FROM Charge INNER JOIN Powers ON Charge.PowerSurety = Powers.Surety
    AND Charge.PowerPrefix = Powers.PowerPrefix
    AND Charge.PowerNumber = Powers.PowerNumber
    WHERE Bond = @BondID
    SELECT @ChargesTotal = SUM(BondPremium)
    FROM ChargeWithoutPower
    WHERE BondID = @BondID
    SELECT @BondFeeTotal = SUM(Amount)
    FROM BondFee WHERE Bond = @BondID
    SELECT @ForfeitureCosts = SUM(CostOfApprehension) + SUM(AmountPaid)
    FROM Forfeiture WHERE Bond = @BondID
    SELECT @PaymentTotal = SUM(Amount)
    FROM Payment WHERE Bond = @BondID
    SELECT @AmountForgiven = SUM(AmountForgiven)
    FROM BalanceForgiveness WHERE BondID = @BondID
    RETURN @PowersTotal + @ChargesTotal + @BondFeeTotal + @ForfeitureCosts - @PaymentTotal - @AmountForgiven
END

I believe I will create a third function that will cover the amounts (Charge.Amount + ChargeWithoutPower.Amount)

A: You've got a RETURN statement at the start of each section.
The query will return as soon as this statement is hit, so the SELECT will not execute and nothing will be returned.
To resolve this issue - remove the RETURN statements.

A: I suspect you are thinking that the procedure needs to RETURN a result set.  In fact, procedures can only "return" an integer.  They can set output parameters and any result sets which are selected will be put in the output stream, but they aren't really anything to do with the RETURN statement.
Also note that your second query, the WHERE clause effectively turns the first LEFT JOIN into an INNER JOIN.
You could combine these two queries into a single query which might be simpler for maintenance, and you could eliminate the need for that separate bit variable and admin query.  Note that the combined version can be easier for maintenance, BUT can have a suboptimal execution plan, since the two cases really might need very different execution plans.  It could also be vulnerable to parameter sniffing, so you might want to use the "optimize for unknown" option and/or keep them split into two - it's a tradeoff.  A lot of times when I see repetitive code which might be easier to maintain in one place, I have to weigh that.  Sometimes the repetitive joins can be turned into a view or inline table-valued function.
I think it reduces to this:
ALTER PROCEDURE dbo.GetBondAmounts
(
    @Username varchar(20)
)
AS
BEGIN
    SELECT Bond.ID
           ,SUM(Charge.BondAmount)
             + SUM(ChargeWithoutPower.BondAmount) AS Amount
           ,SUM(Charge.BondPremium)
             + SUM(ChargeWithoutPower.BondPremium)
             + SUM(Forfeiture.AmountPaid)
             + SUM(Forfeiture.CostOfApprehension)
             - SUM(Payment.Amount)
             - SUM(BalanceForgiveness.AmountForgiven) AS Balance
    FROM Bond
    LEFT OUTER JOIN UserAgency ON Bond.Agency = UserAgency.Agency
    LEFT OUTER JOIN Payment ON Bond.ID = Payment.Bond
    LEFT OUTER JOIN BalanceForgiveness ON Bond.ID = BalanceForgiveness.BondID
    LEFT OUTER JOIN Powers ON Bond.ID = Powers.Bond
    LEFT OUTER JOIN Charge ON Powers.Surety = Charge.PowerSurety
        AND Powers.PowerPrefix = Charge.PowerPrefix
        AND Powers.PowerNumber = Charge.PowerNumber
    LEFT OUTER JOIN ChargeWithoutPower ON Bond.ID = ChargeWithoutPower.ID
    LEFT OUTER JOIN Forfeiture ON Bond.ID = Forfeiture.Bond
    LEFT OUTER JOIN BondFee ON Bond.ID = BondFee.Bond
    WHERE UserAgency.Username = @Username
        OR EXISTS (SELECT * FROM Users WHERE Username = @Username AND Admin = 1)
    GROUP BY Bond.ID
END

(Note that at this point of simplification, I would strongly consider using an inline table-valued function instead of a procedure, which is like a parameterized view and more flexible than a stored proc)
It worries me a bit the way you are grouping and joining.
If you have multiple payments and forfeitures (or any of those other tables linked by Bond.ID) attached to a bond, then you will get an inadvertent cross join, multiplying the values and then summing them, getting incorrect results.
I suspect you will need to do something like this to do your groupings - note that I have done the groupings in subqueries and re-aliased them by the same names:
ALTER PROCEDURE dbo.GetBondAmounts
(
    @Username varchar(20)
)
AS
BEGIN
    SELECT Bond.ID
           ,Charge.BondAmount
             + ChargeWithoutPower.BondAmount AS Amount
           ,Charge.BondPremium
             + ChargeWithoutPower.BondPremium
             + Forfeiture.AmountPaid
             + Forfeiture.CostOfApprehension
             - Payment.Amount
             - BalanceForgiveness.AmountForgiven AS Balance
    FROM Bond
    LEFT OUTER JOIN UserAgency ON Bond.Agency = UserAgency.Agency
    LEFT OUTER JOIN (
        SELECT Bond, SUM(Amount) AS Amount
        FROM Payment
        GROUP BY Bond
    ) AS Payment ON Bond.ID = Payment.Bond
    --- etc..
    WHERE UserAgency.Username = @Username
        OR EXISTS (SELECT * FROM Users WHERE Username = @Username AND Admin = 1)
END


text:
Q: Ruby Hash check is subset? How can I tell if if a Ruby hash is a subset of (or includes) another hash?
For example:
hash = {a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7}
hash.include_hash?({})            # true
hash.include_hash?({f: 6, c: 3})  # true
hash.include_hash?({f: 6, c: 1})  # false

A: Array difference seems easiest:
class Hash
  def include_hash?(h)
    (h.to_a - to_a).empty?
  end
end

h = {a: 1, b: 2}
h.include_hash?({b: 2}) #=> true
h.include_hash?({b: 3}) #=> false

A: You could convert the hashes to sets and than perform the check using the methods subset? and superset? (or their respective aliases <= and >=):
require 'set'

hash.to_set.superset?({}.to_set)
# => true

hash.to_set >= {a: 1}.to_set
# => true

{a: 2}.to_set <= hash.to_set
# => false

Update: a benchmark of the proposed solutions:
require 'fruity'
require 'set'

hash = ('aa'..'zz').zip('aa'..'zz').to_h
# {"aa"=>"aa", "ab"=>"ab", ...
find = ('aa'..'zz').zip('aa'..'zz').select { |k, _| k[0] == k[1] }.to_h
# {"aa"=>"aa", "bb"=>"bb", ...

compare(
  toro2k:        -> { hash.to_set >= find.to_set },
  MarekLipka:    -> { hash.merge(find) == hash },
  CarySwoveland: -> { (find.to_a - hash.to_a).empty? },
  ArupRakshit:   -> { arr = hash.to_a; find.all? { |pair| arr.include?(pair) } }
)

Result:
Running each test 2 times. Test will take about 1 second.
MarekLipka is faster than toro2k by 3x ± 0.1
toro2k is faster than CarySwoveland by 39.99999999999999% ± 10.0%
CarySwoveland is faster than ArupRakshit by 1.9x ± 0.1

A: You can do :
def include_hash?(hash,subset_hash)
   arr = hash.to_a
   subset_hash.all? { |pair| arr.include?(pair) }
end

A: Since Ruby 2.3 you can also do the following to check if this is a subset
hash = {a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7}
{} <= hash           # true
{f: 6, c: 3} <= hash # true
{f: 6, c: 1} <= hash # false

A: The solution that came into my mind use Hash#merge method:
class Hash
  def include_hash?(hash)
    merge(hash) == self
  end
end

hash = {a: 1, b: 2, c: 3, d: 4, e: 5, f: 6, g: 7}
hash.include_hash?({})
# => true
hash.include_hash?(f: 6, c:3)
# => true
hash.include_hash?(f: 6, c:1)
# => false


text:
Q: Finding the index of a string in a tuple Tup = ('string1','string2','string3')

My program returned string2 how do I get it's index within Tup?

A: >>> tup.index('string2')
1

Note that the index() method has only just been added for tuples in versions 2.6 and better.


text:
Q: Utility of Annotations as compared to XML files for configuration In Java, is it a good practice to use annotations to configure an application rather than using XML files? I am more skeptical about it because, using annotations involves changing the java source files and it is as good as declaring constants in java files and then using those constants, whereas when we make the configurations using XML files, we can keep all the configuration changes away from java source files and keep the configurations in separate XML files, this approach sounds more neat. Also, when we need to make changes to configuration, we know which XML file to change rather than searching the java files for the annotations. Also, we can update an XML file in an EAR without compiling the code again, whereas if we make any change in an annotation, then we need to compile the code again.
Can anybody please throw some light on why should we use annotations and not XML files for configuration?

A: Which to use may vary depending on what's being configured, how the configuration is used, project/cultural conventions, etc. Good IDE support makes using either more convenient and reliable.
Personally, while I use both XML and annotations, I tend to prefer XML configuration for many tasks, particularly on larger projects. For example, with Spring, I prefer XML configuration: it's easier to manage the configuration itself, configuration changesets, and environment-specific changes (e.g., testing, server-based, etc.), when it's more localized.
For other configurations, annotations are often more appropriate and convenient. For quick projects with little or no domain class customization, Hibernate annotations may be more convenient.
Ultimately it's a matter of preference and convenience rather than a purely technical one. (Except when the XML and annotations support different features; sometimes one offers more-complete capabilities.)

A: I prefer annotations since my IDE can help me validate my configurations. Configurations stored in xml-files cannot be validated before runtime (I'm thinking mostly about spring and injections)
Also, I find that for anything more than a tiny project, a large xml-config is hard to maintain.

A: When working with annotations, you have to take care of only one place to configure your stuff (java code). When configuring with XML, many times a programmer can "forget" to configure a new property or class in the XML, and after the error must correct and restart, resulting in a waste of time.

A: I would say it very much depends on what you are configuring.
If configuration maybe or should be changed after deployment, then in most cases it is preferable to use XML (or other text-based format). This would include Hibernate server configuration, Tomcat/Jetty configuration, Log4j configuration, etc. The main advantage is flexibility.
For cases when configuration does not need change after deployment, configuration using annotations is preferable. Too many configuration files also complicate your software, so it's best to keep it to a minimum. Good examples would be of annotation-based configurations: Hibernate bean mapping configuration, Spring dependency injection, Guice, etc (some give you both options, but I would prefer annotations here). The advantage is better manageability, and compile-time checking for errors (this depends on the API, of course).

A: Personally, when I've tried to understand a new system, having the annotations right there with the code makes it easier to follow and comprehend. Hunting for references of the class in configuration files can be a little annoying.


text:
Q: How do I center table text both horizontally and vertically? I've seen similar or maybe even same questions but I've tried the solutions and it didn't work for me.
I'm trying to create a table that would center the text vertically and horizontally idealy using flex which for me totally destroys the entire table structure when using "d-flex align-items-center justify-content-center. Also it's important that the first blocks from the left have the extended width!
I'm trying to achieve something similar or same as the table on this website "https://media.realestate.com.au/ad-specs/ad-unit/home-page-hero/"
Here's my code

Ad unit

buy

rent

sold

news

guides

lifestyle

video hub

find agents

new homes

 justifa

Home Page Hero

ul a{
    color: #8ec302 !important;
    text-underline: none !important;
    text-decoration: none !important;
}
a{
    color: inherit !important;
    text-underline: none !important;
    text-decoration: none !important;
}
#navigation a:hover{
    color: #8ec302 !important;
    text-underline: none !important;
    text-decoration: none !important;
}
#navigation a{
     color: inherit !important;
     text-underline: none !important;
     text-decoration: none !important;
 }

.footer-hyperlink-hover  a:hover{
    color: #8ec302 !important;
    text-underline: none !important;
    text-decoration: none !important;
}
.image-no-resize {
    min-height: 200px;
    min-width: 350px;
}
.card-header {
    border: 1px solid rgba(0,0,0,.125);
    border-radius: .25rem;
}

.card {
    border: none !important;
}
h6{
    padding-bottom: 2px !important;
    margin-bottom: 2px !important;
}
ul h6{
    padding-bottom: 2px !important;
    margin-bottom: 2px !important;
}
span{
    font-weight: bold;
}
/*End of styling*/

/*Pictures*/
.career-picture{
    background: linear-gradient(rgba(0, 0, 0, 0.5),rgba(0, 0, 0, 0.5)), url("../images/career.jpg") center/cover no-repeat;
}
/*End of pictures*/

/*Spacing*/
.container-fluid-short{
    max-width: 100rem;
    width: 100%;
}
.container-fluid-shorter{
    max-width: 65rem;
}
.container-fluid-shorter-inner{
    max-width: 76rem;
}

I've tried setting the custom width on the left myself which did work but stopped after my recent tweaks I've made to the code. What am I doing wrong? Thanks for any suggestions!

A: You want to use text-center align-middle. Also, set the first column of each row to

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>

Header

Header

Header

Header

Home Page Hero

                    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
                    Default
                    Center Everything


text:
Q: Apache Beam euphoria Issue I have built the apache beam un-official version from github.com/apache/beam their was a new class to use DataSet Facility euphoria but after Putting all the jar in .m2 repository on my PC i am Facing below Issue.
Failed to read artifact descriptor for com.esotericsoftware:kryo:jar:4.0.2
org.eclipse.aether.resolution.ArtifactDescriptorException: Failed to read artifact descriptor for com.esotericsoftware:kryo:jar:4.0.2
    at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.loadPom(DefaultArtifactDescriptorReader.java:282)
    at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.readArtifactDescriptor(DefaultArtifactDescriptorReader.java:198)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.resolveCachedArtifactDescriptor(DefaultDependencyCollector.java:535)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.getArtifactDescriptorResult(DefaultDependencyCollector.java:519)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.processDependency(DefaultDependencyCollector.java:409)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.processDependency(DefaultDependencyCollector.java:363)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.process(DefaultDependencyCollector.java:351)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.doRecurse(DefaultDependencyCollector.java:504)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.processDependency(DefaultDependencyCollector.java:458)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.processDependency(DefaultDependencyCollector.java:363)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.process(DefaultDependencyCollector.java:351)
    at org.eclipse.aether.internal.impl.DefaultDependencyCollector.collectDependencies(DefaultDependencyCollector.java:254)
    at org.eclipse.aether.internal.impl.DefaultRepositorySystem.collectDependencies(DefaultRepositorySystem.java:316)
    at org.apache.maven.project.DefaultProjectDependenciesResolver.resolve(DefaultProjectDependenciesResolver.java:172)
    at org.apache.maven.project.DefaultProjectBuilder.resolveDependencies(DefaultProjectBuilder.java:215)
    at org.apache.maven.project.DefaultProjectBuilder.build(DefaultProjectBuilder.java:188)
    at org.apache.maven.project.DefaultProjectBuilder.build(DefaultProjectBuilder.java:119)
    at org.eclipse.m2e.core.internal.embedder.MavenImpl.readMavenProject(MavenImpl.java:636)
    at org.eclipse.m2e.core.internal.project.registry.DefaultMavenDependencyResolver.resolveProjectDependencies(DefaultMavenDependencyResolver.java:63)
    at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.refreshPhase2(ProjectRegistryManager.java:530)
    at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager$3.call(ProjectRegistryManager.java:492)
    at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager$3.call(ProjectRegistryManager.java:1)
    at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.executeBare(MavenExecutionContext.java:177)
    at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.execute(MavenExecutionContext.java:151)
    at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.refresh(ProjectRegistryManager.java:496)
    at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.refresh(ProjectRegistryManager.java:351)
    at org.eclipse.m2e.core.internal.project.registry.ProjectRegistryManager.refresh(ProjectRegistryManager.java:298)
    at org.eclipse.m2e.core.internal.builder.MavenBuilder$BuildMethod.getProjectFacade(MavenBuilder.java:154)
    at org.eclipse.m2e.core.internal.builder.MavenBuilder$BuildMethod$1.call(MavenBuilder.java:89)
    at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.executeBare(MavenExecutionContext.java:177)
    at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.execute(MavenExecutionContext.java:151)
    at org.eclipse.m2e.core.internal.embedder.MavenExecutionContext.execute(MavenExecutionContext.java:99)
    at org.eclipse.m2e.core.internal.builder.MavenBuilder$BuildMethod.execute(MavenBuilder.java:86)
    at org.eclipse.m2e.core.internal.builder.MavenBuilder.build(MavenBuilder.java:200)
    at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:735)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:206)
    at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:246)
    at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:301)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:304)
    at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:360)
    at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:383)
    at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:142)
    at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:232)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:56)
Caused by: org.eclipse.aether.resolution.ArtifactResolutionException: Failure to transfer com.esotericsoftware:kryo:pom:4.0.2 from https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact com.esotericsoftware:kryo:pom:4.0.2 from/to central (https://repo.maven.apache.org/maven2): repo.maven.apache.org
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:444)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifacts(DefaultArtifactResolver.java:246)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolveArtifact(DefaultArtifactResolver.java:223)
    at org.apache.maven.repository.internal.DefaultArtifactDescriptorReader.loadPom(DefaultArtifactDescriptorReader.java:267)
    ... 45 more
Caused by: org.eclipse.aether.transfer.ArtifactTransferException: Failure to transfer com.esotericsoftware:kryo:pom:4.0.2 from https://repo.maven.apache.org/maven2 was cached in the local repository, resolution will not be reattempted until the update interval of central has elapsed or updates are forced. Original error: Could not transfer artifact com.esotericsoftware:kryo:pom:4.0.2 from/to central (https://repo.maven.apache.org/maven2): repo.maven.apache.org
    at org.eclipse.aether.internal.impl.DefaultUpdateCheckManager.newException(DefaultUpdateCheckManager.java:238)
    at org.eclipse.aether.internal.impl.DefaultUpdateCheckManager.checkArtifact(DefaultUpdateCheckManager.java:206)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.gatherDownloads(DefaultArtifactResolver.java:585)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.performDownloads(DefaultArtifactResolver.java:503)
    at org.eclipse.aether.internal.impl.DefaultArtifactResolver.resolve(DefaultArtifactResolver.java:421)
    ... 48 more

Any Solution to test it for now/I need to wait for Official Release.

A: Thanks for the interest in Euphoria! You can use Apache snapshots repository, in order to use euphoria right now.
https://repository.apache.org/content/repositories/snapshots/org/apache/beam/
You can add the repository to your maven project as follows:
<repository>
    <id>apache.snapshots</id>
    <name>Apache Development Snapshot Repository</name>
    <url>https://repository.apache.org/content/repositories/snapshots/</url>
    <releases>
        <enabled>false</enabled>
    </releases>
    <snapshots>
        <enabled>true</enabled>
    </snapshots>
</repository>

Please note that there will likely be some API changes before the first official release - eg. replacing Dataset abstraction with PCollection.
David


text:
Q: Elasticsearch bad request on mapping put method I m trying to create an index in Elastic Search and to add analyzer and maaping to handle special characters like @ to search on Email field. Here is my code
Analyzer.txt
{
"analysis": {
    "analyzer": {
        "email_search": {
            "type": "custom",
            "tokenizer": "uax_url_email",
            "filter": [ "lowercase", "stop" ]
        }
    }
}

Mapping.txt
{"users":
 {
  "properties": {
  "email": {
    "type": "string",
    "analyzer": "email_search"
  }
 }
}

CreatedIndex
string _docuementType ="users";
string _indexName="usermanager";
public bool Index(T entity)
    {
        SetupAnalyzers();
        SetupMappings();
        var indexResponse = _elasticClient.Index(entity, i => i.Index(_indexName)
                                                                  .Type(_docuementType)
                                                                  .Id(entity.Id));

        return indexResponse.IsValid;
    }

SetupAnalyzer
protected void SetupAnalyzers()
    {
        if (!_elasticClient.IndexExists(_indexName).Exists)
        {
            _elasticClient.CreateIndex(_indexName);
        }

        using (var client = new System.Net.WebClient())
        {
           string analyzers = File.ReadAllText("analyzers.txt");
           client.UploadData("http://localhost:9200/usermanager/_settings", "PUT", Encoding.ASCII.GetBytes(analyzers));
        }
    }

SetupMappings
protected void SetupMappings()
    {
        using (var client = new System.Net.WebClient())
        {
            var mappings = File.ReadAllText("mappings.txt");
            client.UploadData("http://localhost:9200/usermanager/users/_mapping", "PUT", Encoding.ASCII.GetBytes(mappings));
        }
    }

But getting error on SetupMappings method

The remote server returned an error: (400) Bad Request.

Elastic version is 1.7.5
Nest version is 5.5

A: The problem is
var indexResponse = _elasticClient.Index(entity, i => i.Index(_indexName)
                                                       .Type(_docuementType)
                                                       .Id(entity.Id));

You're indexing documents before setting up the mapping and analyzers; in this case, Elasticsearch will automatically create the index, infer a mapping from the first document it sees and string properties will be mapped as analyzed string fields using the standard analyzer.
To fix this, you should create the index, analyzers and mappings before indexing any documents. You can also disable auto index creation if you need to, in elasticsearch.yml config. It depends on your use case as to whether this is might be a good idea; a search use case with known indices and explicit mappings is a case where you might consider disabling it.
So, the procedural flow would be something like
void Main()
{
    var indexName = "usermanager";
    var typeName = "users";

    var settings = new ConnectionSettings(new Uri("http://localhost:9200"))
        .MapDefaultTypeNames(d => d
            // map the default index to use for the User type
            .Add(typeof(User), typeName)
        )
        .MapDefaultTypeIndices(d => d
            // map the default type to use for the User type
            .Add(typeof(User), indexName)
        );

    var client = new ElasticClient(settings);

    if (!client.IndexExists(indexName).Exists)
    {
        client.CreateIndex(indexName, c => c
            .Analysis(a => a
                .Analyzers(aa => aa
                    .Add("email_search", new CustomAnalyzer
                    {
                        Tokenizer = "uax_url_email",
                        Filter = new [] { "lowercase", "stop" }
                    })
                )
            )
            .AddMapping<User>(m => m
                .Properties(p => p
                    .String(s => s
                        .Name(n => n.Email)
                        .Analyzer("email_search")
                    )
                )
            )
        );
    }

    client.Index(new User { Email = "me@example.com" });
}

public class User
{
    public string Email { get; set; }
}

which will send the following requests (assuming index doesn't exist)
HEAD http://localhost:9200/usermanager

POST http://localhost:9200/usermanager
{
  "settings": {
    "index": {
      "analysis": {
        "analyzer": {
          "email_search": {
            "tokenizer": "uax_url_email",
            "filter": [
              "lowercase",
              "stop"
            ],
            "type": "custom"
          }
        }
      }
    }
  },
  "mappings": {
    "users": {
      "properties": {
        "email": {
          "analyzer": "email_search",
          "type": "string"
        }
      }
    }
  }
}

POST http://localhost:9200/usermanager/users
{
  "email": "me@example.com"
}

NOTE: You will need to delete the index and recreate, in order to change the mapping. It's a good idea to use aliases to interact with indices, so that you can iterate on mappings whilst developing.


text:
Q: What does /.*=/ mean in jquery/javascript? What does /.*=/ mean in the following jquery?
var id=this.href.replace(/.*=/,'');
this.id='delete_link_'+id;

A: That's a regular expression that will select all characters before and including an equal sign.
The '.' means any character other than a newline.
The '*' means the character before it can appear any number of times.
The '=' is the regular equals sign.
So any character ('.') any number of times ('*') followed by an equals sign ('=').

A: That's a regular expression.
The code will replace everything before the '='-sign (and the equal sign) with an empty string. So it will delete the = and everything before it.
My guess is that your url looks something like this http://mysite.com?id=3 then your variable id will contain 3.

A: The /.*=/ is a regular expression. It replaces any number of characters followed by an equals sign with an empty string.

A: It's a regular expression (or regex).
A regex is a search and replace method which uses pattern matching to locate parts of a string that fit a pattern. (Similar to how a wildcard dir *.* lists all the files in the current directory).


text:
Q: MS Access VBA, not getting results when running DoCmd to find a record I am not a programmer by any means but I am trying to get a small data collection database going.  I need to find a record based on input.  Ive got two criteria that I want it to find, and if both arent found together, it is supposed to create a new record (with both fields filled out to prevent duplication of the pair).  First criteria is that it needs to look for a date.  I figured that one out already, here is the code.
Dim Date1 As String
Date1 = Text6.Value

DoCmd.OpenForm "Data", , , "Data![ShiftDate] = #" & Date1 & "#"

Works like a charm.  Now, I tried to add the second criteria in.  The second criteria pulls from a listbox, either Day or Night.  Then, it is supposed to search my data fields for that same criteria in a list box on my Data! form.
Dim Date1 As String
Dim Shift1 As String

Date1 = Text6.Value
Shift1 = List12.Column(1)
MsgBox Shift1

DoCmd.OpenForm "Data", , , _
   "Data![ShiftDate] = #" & Date1 & "# AND Data![Shift] ='" & Shift1 & "'"

the msgbox was just to verify that it is pulling the right words, day or night.  Everything works great, but instead of pulling a record on the right date, and with the right shift, I get blank records.  I tried taking out the first half of the where statement to isolate the shift part and still just cannot get it to find a record.  I have no idea what I am doing wrong.

A: It seems that you already have a form.
I recommend you trying this:
Add a button with a click event to the form and add following code to the click event:
dim rs as dao.recordset
set rs = currentdb.openrecordset ("SELECT * FROM [yourtable] WHERE ('ShiftDate' = '" & [yourParameter] & "' AND 'Shift' = '" & [your2ndParameter] & "')")
if rs.eof then
' here NO record is found
currentdb.execute ("INSERT INTO [yourtable] ('ShiftDate', 'Shift') VALUES ('" & [yourParameter] & "', '" & [your2ndParameter] & "')")
else
' here a record is found
endif
Since your ShiftDate is a date you need to convert your date to a SQL date Format, like this:
Function SQLDatum(Datumx) As String
If IsDate(Datumx) Then
    SQLDatum = Format(CDate(Datumx), "\#yyyy-mm-dd\#", vbMonday, _
                      vbFirstFourDays)
  Else
    SQLDatum = ""
End If
End Function

A: In your command
DoCmd.OpenForm "Data", , , "Data![ShiftDate] = #" & Date1 & "# AND ...

You open a form Data but at the same time you specify a filter by referring  to the form which is being opened with Data![ShiftDate]. This is very strange, since the filter must be applied to the data source. I would simply write
DoCmd.OpenForm "Data", , , "ShiftDate= #" & Date1 & "# AND Shift= '" & Shift1 & "'"

by referring to the table columns of the data source (on the left side of =).
Note that the column Shift must be a text column. If it was some number, you would have to drop the single quotes and pass it a corresponding id.


text:
Q: How to embed an audio and a subtitle file into a MKV file I have a MKV file in which I want to embed an AC3 audio file. I also want to embed a SRT subtitle file into it. How can I achieve that?
Note: AC3 file is the same length of the original video.

A: If you have MKVToolnix installed, you can use the mkvmerge command to merge together the streams.
mkvmerge -o output.mkv -A input.mkv sound.ac3 subtitles.srt

The -A switch makes sure no sound is taken from input.mkv. See the examples section for more.

For Windows, there exists the MKVToolnix GUI, which would make this a little easier:

In Ubuntu and similar distros, there should be the mkvtoolnix-gui package.


text:
Q: Speech recognition with python, detect Specific words like human name Using Speech Recognition to recognize human speech with sentences.
I use Sqlite to storage human names. Now I can split the human name and search in database.
But the problem is some of unusual names cannot be recognized for example:Shox, Finxy.
I wanna regulate the machine or give it a dataset to help him recognize specific words.
I know it seems need deep learning to implement this problem.
Could you help me with this? Or give me some idea about it.
I expect that 'Hello I wanna look for Finxy', the machine can recognize 'Finxy' rather than fixxie or something. Even those words unexist.

import speech_recognition as sr
import sqlite3

def recog(recognizer, microphone):
    if not isinstance(recognizer, sr.Recognizer):
        raise TypeError("`recognizer` must be `Recognizer` instance")
    if not isinstance(microphone, sr.Microphone):
        raise TypeError("`microphone` must be `Microphone` instance")

    with microphone as source:
        print('Talk')
        recognizer.adjust_for_ambient_noise(source)
        audio = recognizer.listen(source)
    return recognizer.recognize_google(audio, language='en_US')

if __name__ == '__main__':
    recognizer = sr.Recognizer()
    microphone = sr.Microphone()
    sentence = recog(recognizer, microphone)

    # using google speech recognition
    try:
        print("You said " + sentence)
    except sr.UnknownValueError:
        print("Error")
    except sr.RequestError as e:
        print("Could not request results from Google Speech Recognition service; {0}".format(e))

    # Connect to database (creates if not exists)
    conn = sqlite3.connect("sogeti.db")

    # Create a cursor object
    cursor = conn.cursor()

    # Execute the CREATE TABLE statement
    staff = []
    cursor.execute('SELECT * FROM employees')
    records = cursor.fetchall()
    for i in records:
        staff.append(i[1])
    for name in staff:
        if name in sentence.split(' '):
            print('Yes, ' + name + ' is here')
        else:
            cursor.execute('SELECT name FROM employees where name LIKE')

    conn.commit()
    conn.close()


text:
Q: Revert a failed Ubuntu dist upgrade I would like to upgrade my Ubuntu 18.04 installation to 20.04 in the near future. However, I have had bad experiences with system upgrades in the past, especially with Ubuntu, and are therefore reluctant towards an upgrade because I fear it might fail.
Is it possible to revert a failed upgrade to the state before the upgrade, e.g., using Timeshift? Or is Timeshift unable to recover if there is a failed installation of Ubuntu on the disk? How to make sure a rollback is possible?


text:
Q: C++ Cannot instantiate abstaract class's child I have abstract class Transaction which contains couple of normal properties and methods and one method - Behavior - which I made pure virtual, so the classes which inherits from Transaction can implement it on their own.
My Transaction.h
class Transaction abstract{

protected:

...

public:

...

virtual void behavior() = 0;

};
I think this should be correct. Than I have class Cow, which I would like to inherit from the Transaction.
This is how I tried to do it
class Cow : public Transaction {

    public:
        Cow(int p, Calendar* cal){
        this->priority = p;
        this->cal = cal;
    }

    void Behavior() {

        ...

        do some stuff

        ...

    }
};

The problem is, whenever I try to make an object of class Cow. Either it is in Main.cpp or in Cow::Behavior (which are basicly only two places in code I need to be able to create objects of Cow) I end up with an error below.
error C2259: 'Cow' : cannot instantiate abstract class

This really confuses me, as I'm not trying to instantiate an abstract class, but the class that inherits from it. I'm sure this is basic stuff, but I don't seem to be able to solve this problem on my own.
Btw. this is how I try to create new instance of Cow.
    Calendar *calendar = new Calendar();
calendar->push(0, new Cow(1, calendar));

where the method Calendar::Push accepts
void Calendar::push(int t, Transaction *tr)

Any ideas?
Thank You!

A: You've declared a pure virtual function behavior in the base class, and an unrelated function Behavior in the derived class. This doesn't override the pure function since it has a different name. C++ is case-sensitive.

A: C++ is case sensitive. You spelled behavior with lowercase 'b' in your base class and Behavior in the derived one.

A: Since you are not overriding the pure virtual function behavior in your class Cow [Behavior is taken as different function] so Cow becomes an abstract class too. And rest are C++ semantics.

A: First of all C++ has no keyword abstract. It seems you are using C++/CLI. Try the following definitions
ref class Transaction abstract{

protected:

...

public:

...

virtual void behavior() = 0;

};

ref class Cow : public Transaction {

    public:
        Cow(int p, Calendar* cal){
        this->priority = p;
        this->cal = cal;
    }

    void behavior() override {

        ...

        do some stuff

        ...

    }
};


text:
Q: A Generic Error occurred in GDI+ when calling Bitmap.GetHicon Why I'm getting "A Generic Error occurred in GDI+" Exception ?
IntPtr hicon = tempBitmap.GetHicon();
Icon bitmapIcon = Icon.FromHandle(hicon);
return bitmapIcon;

The error occurred when my application has been running for more than 30 minutes. (I am converting System.Drawing.Bitmap to System.Drawing.Icon every second)

A: You probably need to clean up your icon.
The example for Icon.FromHandle on MSDN shows you how. Unfortunately it requires PInvoke:
[System.Runtime.InteropServices.DllImport("user32.dll", CharSet=CharSet.Auto)]
extern static bool DestroyIcon(IntPtr handle);

And then inside your method:
IntPtr hicon = tempBitmap.GetHicon();
Icon bitmapIcon = Icon.FromHandle(hicon);

// And then somewhere later...
DestroyIcon(bitMapIcon.Handle);

If you call DestoryIcon before you use it, it may not work. For my own particular instance of this problem, I ended up keeping a reference to the last icon I created and then called DestroyIcon on it the next time I generated an icon.

A: That's caused by a handle leak.  You can diagnose the leak with TaskMgr.exe, Processes tab.  View + Select Columns and tick Handles, GDI Objects and USER Objects.  Observe these columns while your program is running.  If my guess is right, you'll see the GDI Objects value for your process steadily climbing.  When it reaches 10,000 then the show is over, Windows refuses to allow you to leak more objects.
The Remarks section for Icon.FromHandle says:

When using this method you must dispose of the resulting icon using the DestroyIcon method in the Win32 API to ensure the resources are released.

That's good advice but usually pretty painful to do.  You can find a hack to force the Icon object to own the handle, and automatically release it, in this answer.  Relevant code is after the "Invoke private Icon constructor" section.


text:
Q: Kafka user - project design advise I am new to Kafka and data streaming and need some advice for the following requirement,
Our system is expecting close to 1 million incoming messages per day. The message carries a project identifier. The message should be pushed to users of only that project. For our case, lets say we have projects A, B and C. Users who opens project A's dashboard only sees / receives messages of project A.
This is my idea so far on implementing solution for the requirement,
The messages should be pushed to a Kafka Topic as they arrive, lets call this topic as Root Topic. The messages once pushed to the Root Topic, can be read by a Kafka Consumer/Listener and based on the project identifier in the message can push that message to a project specific Topic. So any message can end up at Topic A or B or C. Thinking of using websockets to update the message as they arrive on the project users' dashboards. There will be N Consumers/Listeners for the N project Topics. These consumers will push the project specific message to the project specifc websocket endpoints.
Please advise if I can make any improvements to the above design.
Chose Kafka as the messaging system here as it is highly scalable and fault tolerant.
There is no complex transformation or data enrichment before it gets sent to the client. Will it makes sense to use Apache Flink or Hazelcast Jet for the streaming or Kafka streaming is good enough for this simple requirement.
Also, when should I consider using Hazelcast Jet or Apache Flink in my project.
Should i use Flink say when I have to update few properties in the message based on a web service call or database lookup before sending it to the users?
Should I use Hazelcast Jet only when I need the entire dataset in memory to arrive at a property value? or will using Jet bring some benefits even for my simple use case specified above. Please advise.

A: Kafka Streams are a great tool to convert one Kafka topic to another Kafka topic.
What you need is a tool to move data from a Kafka topic to another system via web sockets.
Stream processor gives you a convenient tooling to build this data pipeline (among others connectors to Kafka and web sockets and scalable, fault-tolerant execution environment). So you might want use stream processor even if you don't transform the data.
The benefit of Hazelcast Jet is it's embedded scalable caching layer. You might want to cache your database/web service calls so that the enrichment is performed locally, reducing remote service calls.
See how to use Jet to read from Kafka and how to write data to a TCP socket (not websocket).

A: I would like to give you another option. I'm not Spark/Jet expert at all, but I've studying them for a few weeks.
I would use Pentaho Data Integration(kettle) to consume from the Kafka and I would write a kettle step (or User Defined Java Class step) to write the messages to a Hazelcast IMAP.
Then, would use this approach http://www.c2b2.co.uk/middleware-blog/hazelcast-websockets.php to provided the Websockets for the end-users.


text:
Q: Formik handleSubmit does nothing I have two components that both contain a form and I am implementing Formik in each component in exactly the same way, yet in one component handleSubmit is working and in the other component it is not.
The component code can be viewed here: https://gist.github.com/chris-haupt/c6c0e22851b03a74e504a5ee94a774bd
I am simply trying to run any code in the callback that is being passed to the onSubmit prop. Previously I was able to do this without a problem by passing handleSubmit to the form element.
When I click the submit button, or press enter, nothing happens. Nothing at all. If I pass a console.log to onSubmit on the form element then the log fires just fine. So for some reason there is a disconnect where handleSubmit is not being passed correctly.
The final bit of evidence I have is a console.log of onSubmit.toString():
function () {
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }

    return ref.current.apply(void 0, args);
  }

But this code means very little to me :/

A: It turns out that the handleSubmit function doesn't fire if there are any errors in the errors object. In this case I was passing formikValidation to the validate prop and this was checking for fields that don't exist on this component so it would always return an error stating that the field was empty.


text:
Q: Get filename of file which ran PHP include When using the PHP include, how can I find out which file is calling the include? In short, what is the parent's file filename?

A: Got this from here: https://stackoverflow.com/a/35622743/9270227
echo "Parent full URL: ";
echo $_SERVER["SCRIPT_FILENAME"] . '<br>';

A: I was searching same information on web for complement my online course about php and found two ways. The first was
$file = baseline($_SERVER['PHP_SELF']);
echo $file;  //that outputs file name

BUT, in include or require cases it gets the final file that it's included or required.
Also found this, the second
$file = __FILE__;
echo $file; //that outputs the absolute way from file

BUT i just was looking for the file name.
So... I mix it up and it worths well!
$file = basename(__FILE__);
echo $file; //that outputs the file name itself (no include/require problems)

A: An easy way is to assign a variable in the parent file (before the inclue), then reference that variable in the included file.
Parent File:
$myvar_not_replicated = __FILE__; // Make sure nothing else is going to overwrite
include 'other_file.php';

Included File:
if (isset($myvar_not_replicated)) echo "{$myvar_not_replicated} included me";
else echo "Unknown file included me";

You could also mess around with get_included_files() or debug_backtrace() and find the event when and where the file got included, but that can get a little messy and complicated.

A: $fileList = get_included_files();
$topMost = $fileList[0];
if ($topMost == __FILE__) echo 'no parents';
else echo "parent is $topMost";

I think this should give the right result when there's a single parent.
By that I mean the situation where the parent is not a required or an included file itself.

A: Late answer, but ...
I check the running parent filename by using:
$_SERVER["SCRIPT_NAME"] // or
$_SERVER["REQUEST_URI"] // (with query string)

A: You could use debug_backtrace() directly with no additional changes from within the included file:
$including_filename = pathinfo(debug_backtrace()[0]['file'])['basename'];

This will give you the name of the file that's including you.
To see everything you have access to from within the included file, run this from within it:
print_r(debug_backtrace());

You will get something like:
Array
(
    [0] => Array
        (
            [file] => /var/folder/folder/folder/file.php
            [line] => 554
            [function] => include
        )

)

A: In the parent file, add this line before including the child file:
$_SESSION['parent_file'] = $_SERVER['PHP_SELF'];

And then in the child file, read the session variable:
$parent_file = $_SESSION['parent_file']


text:
Q: Cannot access Objective-C singleton's array from Swift code I made an array in a singleton to write objects into it from multiple parts of my code. Here's how:
// in singleton.h
#import <UIKit/UIKit.h>

// make globally accessible array
@interface MyManager : NSObject {
    NSMutableArray *imgArray;
}
@property (nonatomic, retain) NSMutableArray *imgArray;
+ (id)sharedManager;
@end

// in singleton.m
#import "singleton.h"

For my .m file :
@implementation MyManager

@synthesize imgArray;

#pragma mark Singleton Methods

+ (id)sharedManager {
    static MyManager *sharedMyManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedMyManager = [[self alloc] init];
    });
    return sharedMyManager;
}

- (id) init {
    if (self = [super init]) {
        self.imgArray = [NSMutableArray new];
        }
    NSLog(@"initialized");
    return self;
}

@end

I can access my array called imgArray it from my objective C code. However, In swift I get an error when I do this:
let array  = MyManager.sharedManager()

array.imgArray.add("hello world") .    (!!!) Value of type 'Any?' has no member 'imgArray'

I can access MyManager.sharedManager(), but Why can't I access imgArray the same way as in objective C?

A: You should declare it as instancetype or MyManager *. E.g.
+ (MyManager *)sharedManager;

or
+ (instancetype)sharedManager;

A couple of suggestions:

*

*The Swift convention for singleton's is to use a class property name of shared, not a class method of sharedManager(). When you declare it in Objective-C, you might want to explicitly say that it's a class property:
@property (class, readonly, strong) MyManager *sharedManager NS_SWIFT_NAME(shared);

This won't change any of the Objective-C behavior, but in Swift, you can just do:
let manager = MyManager.shared
manager.images.add(image)

This results in more concise and idiomatic Swift code.

*I'd suggest that you audit your Objective-C for nullability. I.e., confirm what can be nil and what can't. Since both imgArray (which I might just call images) and sharedManager can never be nil, I would just use the NS_ASSUME_NONNULL_BEGIN/END macros which tells the compiler "unless I tell you otherwise, assuming this property cannot be nil":
//  MyManager.h

@import UIKit;

NS_ASSUME_NONNULL_BEGIN

@interface MyManager : NSObject

@property (nonatomic, strong) NSMutableArray <UIImage *> *images;
@property (class, readonly, strong) MyManager *sharedManager NS_SWIFT_NAME(shared);

@end

NS_ASSUME_NONNULL_END

By telling the compiler that these two cannot be nil, that means that you'll have to do less unnecessary unwrapping of optionals in your Swift code.

*As an aside, notice that I didn't declare an instance variable. (And if you did need one, I wouldn't advise declaring it in the public interface.) Objective-C will now synthesize the ivars backing our properties automatically for us. (So my property images will have an ivar called _images that will be synthesized for me.) And you don't need/want the @synthesize line, either:
//  MyManager.m

#import "MyManager.h"

@implementation MyManager

+ (instancetype)sharedManager {
    static MyManager *sharedMyManager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedMyManager = [[self alloc] init];
    });
    return sharedMyManager;
}

- (instancetype)init {
    if (self = [super init]) {
        self.images = [NSMutableArray new];
    }
    NSLog(@"initialized");
    return self;
}

@end

A: Change + (id)sharedManager; to + (MyManager *)sharedManager;. Otherwise Swift doesn't know what kind of object sharedManager is and it will assume it's Any.


text:
Q: how to handle response get html format
Error Log cat:retrofit.RetrofitError:
  com.google.gson.JsonSyntaxException: java.lang.IllegalStateException:
  Expected BEGIN_ARRAY but was STRING at line 1 column 1 path $

respons server:

    <form id="SatisForm"  action="http://www.Home.com/SS/ecure/demo2.aspx" method="post">
    <input type="hidden" value="816764744736727737776722746733744827751737736738744795820820817827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827816784739736724747776722752733744733817712816792784739736724747776722752733744733817827827827827827827827827827827827827827827827827827827827827827827827827827827827827816755733736727746776727743733770739817712816792755733736727746776727743733770739817827827827827827827827827827827827827827827827827827827827827827827827827827827827827816771726727737727776727735736733817721816792771726727737727776727735736733817827827827827827827827827827827827827827827827827827827827827827827827827827827827827816760733743737722754724733735736722737722817816792760733743737722754724733735736722737722817827827827827827827827827827827827827827827827827827827827827827827827827827827827827816763722746733743736722746733724733770739746817816792763722746733743736722746733724733770739746817827827827827827827827827827827827827827827827827827827827827827827827827827827827827816776727752722731722746778733741733817721816792776727752722731722746778733741733817827827827827827827827827827827827827827827827827827827827827827827827827827827827827816782727723784739736724747817827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827816782727723779752727770739817721816792782727723779752727770739817827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827827816764741817712719713814713714718814712714814713718816792764741817

2772472774373673373673373577872274373373173381782782782782782782782782782782782782782782782782782782782782782782782782782782782782782782782782782782782782781676774372772673376772274374675675678171381771371571281679276827827827816792782727723784739736724747817827827827827827827827827827827827827827827827827827827827827816792764744736727737776722746733744817712" name="satisXML"/>

        $(document).ready(function(){
        $('#submit3dform').click();
        });

code :
void addSeatPaymnet(@Query("api.key")String key,
                        @Query("userid")String userid,
                        @Query("gender")String gender,
                        @Query("FirmaNo")String FirmaNo,
                        @Query("hatNo")String hatNo,
                        @Query("departure_city")String departure,
                        @Query("seatNo[]")String seatNo,
                        @Query("seferTakipNo")String seferTakipNo,
                        @Query("tarih")String tarih,
                        @Query("price")String price,
                        @Query("destination_city")String destination_city,
                        @Query("No_of_passenger")String No_of_passenger,
                        @Query("credit_card_holder_name")String credit_card_holder_name,
                        @Query("credit_card_number")String credit_card_number,
                        @Query("credit_card_security_code")String credit_card_security_code,
                        @Query("credit_card_expiry_month")String credit_card_expiry_month,
                        @Query("credit_card_expiry_year")String credit_card_expiry_year,
                        @Query("email")String email,
                        @Query("customer_name")String customer_name,
                        @Query("customer_surname")String customer_surname,
                        @Query("customer_mobile")String customer_mobile,
                        @Query("saat")String saat,
                        @Query("tc_number")String tc_number,
                        @Query("travelDate")String travelDate,
                        Callback<List<PaymentDetailBean> >callback);

RestClient.post().addSeatPaymnet(appConstants.api_key, "119", "2", "284", "284", "abc", "2", "687036", "2016-02-26", "75", "bcd",
                "1", "abdusl", "4222 3160 8933 0000", "242", "11", "2018", "patel@gmail.com",
                "abc", "raul", "312155555", "MTkwMC0wMS0wMV==", "1900-01-01T05:00:00-02:00", "07 March 2016 - 10:00", new Callback<List<PaymentDetailBean>>() {
                    @Override
                    public void success(List<PaymentDetailBean> paymentDetailBeans, Response response) {
                        Log.d("success", "1"+response);
                    }

                    @Override
                    public void failure(RetrofitError error) {
                        Log.d("success", "2" + error);
                    }
                });


text:
Q: Java program that prints a string backwards I'm trying to write a program that takes a string, breaks it up into characters, and prints each character backwards. I sort of see what the problem is, I just am not sure how to fix it. Here is my code:
public static void main(String[] args) {
    //takes a string and prints all the letters backwards all on one line

    String fruit = "apple";
    backwards(fruit);
    }

public static void backwards(String theFruit) {
    int length = theFruit.length() - 1;
    int counter = 0;
    while(length > counter) {
        char theCharacter = theFruit.charAt(length);
        System.out.println(theCharacter);
        counter++;
    }
}

For some reason it just prints all one letter and I am not sure why.

A: The problem is that length doesn't change, and you are using the length for your println statement.
Instead of adding to counter at the end of your loop, subtract from length. You should then change your while to check that is >= counter:
while (length >= counter)
{
    System.out.println(theFruit.charAt(length));
    length--;
}

You could also change your loop and use a for loop instead:
for (int i = length; i >= 0; i--)
{
    System.out.println(theFruit.charAt(i));
}

A: I think that the easiest approach for your task is to use StringBuilder class.
public static void backwards(String theFruit) {
    return new StringBuilder(theFruit).reverse().toString();
}

A: decrements the length in while loop. and don't increase counter variable.
as :
while(length >= counter) {
    char theCharacter = theFruit.charAt(length);
    System.out.println(theCharacter);
    length--;
}

A: Decrease the value of length
while(length >= counter) {
        char theCharacter = theFruit.charAt(length);
        System.out.println(theCharacter);
        length--;
}

with your approach you are printing the last character everytime because length value never changed
Demo

A: You can use StringBuffer Class.
public static void main(String[] args) {
    StringBuffer fruit = new StringBuffer("apple");
    System.ouyt.println(fruit.reverse());
    }


text:
Q: asp.net dropdown iniside datagrid I'm inserting a dropdwon list in datagrid on row editing. When i run the project the datasource is not rekognized. The asp.net part is there:
<asp:TemplateField HeaderText="Lookup 1">
                            <EditItemTemplate>
                                   <asp:DropDownList
                                   ID="Loocup1DropDownList"
                                   Width="100%"
                                   runat="server"
                                   DataSource ="<%GetValueForDropDownCombinationContent()%>"
                                   DataValueField="LOOKUP_ID"
                                   DataTextField="lookup_name" >
                                </asp:DropDownList>

                            </EditItemTemplate>
                            <ItemTemplate>
                                <asp:Label ID="LOOKUP1_NAME" runat="server" Text='<%# Bind("LOOKUP1_NAME") %>'></asp:Label>
                            </ItemTemplate>

This is the vb.net function:
Protected Function GetValueForDropDownCombinationContent() As DataSet
    Dim dsProductLookups As New DataSet
    dsProductLookups = DocumentManager.Data.DataRepository.Provider.ExecuteDataSet("sp_GetCombinationsLookups", productCombo.SelectedValue)
    Return dsProductLookups
End Function

any ideas???

A: First thing you should be looking at is the way you apply your data source. It should be
DataSource='<%# GetValueForDropDownCombinationContent() %>'

Use the single quotes instead of double quotes. At least this works 100% in C#, and I'm hoping that it's the same in VB.NET..
Secondly - you didn't set the selected value there:
SelectedValue='<%# Bind("LOOKUP1_NAME") %>'

With these two applied - you should have no problems getting your dropdown to work )


text:
Q: Proxy issues using WFS from Cadcorp GeognoSIS I have web and WMS/WFS servers hosted on the same machine, although on different ports.
I'm currently using OpenLayers to consume the WMS feeds which works well, but now I need to allow the user to extract info about objects so am trying to incorporate WFS into the OpenLayers setup.
Being on different ports, I've set up proxy.asp to do the WFS requests:
<%
set objHttp = Server.CreateObject("Msxml2.ServerXMLHTTP")
strURL = Request("url")
objHttp.open "GET", strURL, False
objHttp.Send

If objHttp.status = 200 Then
    Response.Expires = 90
    Response.ContentType = "application/xml;charset=UTF-8"
    Response.BinaryWrite objHttp.responseBody
    set objHttp = Nothing
End If
%>

I've tested the proxy using this URL:
http:///maps/proxy.asp?url=http%3A//:4326/OgcService/WFS.impl?service=wfs?request=getCapabilities
This returns the GetCapabilities which is identical to that returned if I access it directly, but without the proxy.
However, when using this WFS, via proxy, I can't get OpenLayers to display any content. At this stage it could well be my OpenLayers code, which I can post if necessary, but the same WFS URL via proxy doesn't work in MapInfo or Cadcorp MapModeller (it does with just the base URL). I suspect the proxy is the issue.
Any ideas what the issue is likely to be?

A: Try using the Cadcorp.OGC.CGI.exe (which you can just rename to, for example, wfs.exe) instead of your proxy.asp. It is configured via a companion INI file, and passes on everything that GeognoSIS needs.
Or, you could use WMS GetFeatureInfo instead of WFS, for a simplified response


text:
Q: Facebook login within an iframe (but outside FB) At some point in my application, I use an iframe. In this iframe, some Facebook stuff could be useful and for that, I use the graph API a lot.
Problem is : when someone isn't logged in to facebook or hasn't allowed my application yet, they are prompted to click the "connect with facebook" button. But as soon as they click it, the iframe gets destroyed and the top page is replaced with the Facebook login page. Eventually the top page is redireccted to the previous iframe URL, but the former parent page is lost forever.
Is this the intended behaviour of FB connect ?
Is there a way to avoid it or to hack around it ? (maybe using a popup instead of an iframe, but that sounds ugly (uglier than an iframe)).
I am currently using the PHP SDK
Thanks a lot

A: Here is a solution for opening a pop-up :
https://developers.facebook.com/docs/reference/javascript/FB.login/
By having an element that trigger the following code on click event :
FB.login( callback );

it should open a pop-up with the form to login  / authorize your app.
So it involves to not use the ( deprecated ) FBML alternative.
Concerning the iframe element, I doubt you'll find a way to achieve that. The reason is that facebook' script checks the window.top.location to be on facebook domain.


text:
Q: How to estimate the error in Leave One Out Cross Validation Is there a proper way to perform LOOCV and estimate the error as the mean of all the train data.
I already perform a K-FOLD CROSS-VALIDATION as gives:
scores = cross_val_score(clf, X, y, cv = 10, scoring = "accuracy")
print('mean score and the 95% confidence interval of the score estimate')
print("Accuracy: %0.2f (+/- %0.2f)" % (scores.mean(), scores.std() * 2))

I was wondering how would be the proper way for LOOC since this one suppose a cv=N(number of instances). I was reading about it in the documentation but what I am looking for is the estimated error for LOOCV.
What I came across with was this code but it doesn't seem to generate an accuracy or an error for each validation:
 from sklearn.model_selection import LeaveOneOut
 loo = LeaveOneOut()
 for train, test in loo.split(X):
     print("%s %s" % (train, test))

Thanks in advance


text:
Q: Filtering mongodb geospatial return data? I have a geospatial collection that's working well -- given a simple query and data return like this:
    > distance = db.runCommand({ geoNear : "geodata_geo", near : [-121.8993988, 36.9771729], spherical : true, maxDistance : range / earthRadius, num : 3 }).results;
[
    {
        "dis" : 0,
        "obj" : {
            "CountryID" : 231,
            "_id" : ObjectId("4ecea8348044dc9bdd21eda3"),
            "cityCode" : "3183347",
            "cityID" : 952717,
            "cityName" : "Aptos",
            "countryCode" : "US",
            "countryName" : "United States",
            "countyCode" : "US005044",
            "countyID" : 5932,
            "countyName" : "Santa Cruz",
            "**id_geo**" : 952717,
            "lat" : 36.9771728515625,
            "loc" : {
                "lon" : -121.8993988,
                "lat" : 36.9771729
            },
            "lon" : -121.89939880371094,
            "regionCode" : "NAm",
            "regionID" : 1078,
            "regionName" : "North America",
            "stateCode" : "US005",
            "stateID" : 3725,
            "stateName" : "California"
        }
    },

Is there a way to form this query so that I  only return the (list of) id_geo values from within the collection?  I've tried several variations but none seem to give me what I need...I know I can handle this programmatically, but was wondering if this was mongopossible...
thanks!

A: Do you really need geoNear? The docs indicate that "the find() syntax above is typically preferred".
If you're OK with find(), then it's easy. Returning all fields:
db.customers.find({ "addresses.billing_address.location" :
  { $within : { $center : [[-117.15,32.72],0.15] } } }
)

Returning the same documents but only the account_type field:
db.customers.find({ "addresses.billing_address.location" :
  { $within : { $center : [[-117.15,32.72],0.15] } } }, {"account_type" : 1}
)

A: Try specifying the fields parameter:
db.runCommand({ geoNear : "geodata_geo",
                near : [-121.8993988, 36.9771729],
                spherical : true,
                maxDistance : 45,
                num : 3 },
              {fields : { "obj.id_geo" : 1 } }).results;

This is documented for the findAndModify command.


text:
Q: React native Reanimated: timing() duration is not working I'm trying to make element return to its initial position once PanGestureHandler is released.
onGestureEvent = event(
    [
      {
        nativeEvent: ({ translationY, state, velocityY }) =>
          cond(
            eq(state, State.ACTIVE),
            // ignore this part, it's working fine
            [
              cond(
                lessOrEq(this.scrollOffset, 0),
                set(
                  this.gestureY,
                  divide(sub(translationY, this.ignoredGestureY), 2)
                ),
                set(this.ignoredGestureY, translations)
              )
            ],
            [
              // here I invoke bounce back animation
              set(
                this.gestureY,
                runTiming(this.backClock, this.gestureY, new Value(0))
              )
            ]
          )
      }
    ],
    { useNativeDriver: true }
  )

Here is runTiming function:
function runTiming (clock, value, dest, startStopClock = true) {
  const state = {
    finished: new Value(0),
    position: new Value(0),
    frameTime: new Value(3000),
    time: new Value(3000)
  }

  const config = {
    toValue: new Value(0),
    duration: 3000,
    easing: Easing.ease
  }

  return [
    cond(clockRunning(clock), 0, [
      set(state.finished, 0),
      set(state.frameTime, 3000),
      set(state.time, 3000),
      set(state.position, value),
      set(config.toValue, dest),
      startClock(clock)
    ]),
    timing(clock, state, config),
    cond(state.finished, stopClock(clock)),
    state.position
  ]
}

The problem is that the element returns back instantly. Why is 3000 ms duration is not working?


text:
Q: How to compile multiple plots into a single plot in Python? I'm currently trying to combine multiple plots into a single plot (with sub-plots). Please check out the following code:
import matplotlib.pyplot as plt

a = list(range(1,10))
b = list(map(lambda x: x**2, a))
c = list(map(lambda x: x**3, a))
d = list(map(lambda x: x+200, a))

plots = []

plt.plot(a, b)
plots.append(plt.gcf())
plt.close()

plt.plot(a, c)
plots.append(plt.gcf())
plt.close()

plt.plot(b, c)
plots.append(plt.gcf())
plt.close()

plt.plot(a, d)
plots.append(plt.gcf())
plt.close()

fig, ax = plt.subplots(len(plots))
for i,plot_obj in enumerate(plots, start=1):
    print(f"{i=}, {plot_obj=}")
    ax[i].set_figure(plot_obj)
    plot_obj.show()

plt.tight_layout()
plt.show()

# plt.savefig('temp.png')

The constraints I have are -

*

*The plots will be created earlier - I'm storing the figure objects in a list.

*These plots need to be accessed later on in the code and a single figure needs to be created with each of the plot as a sub-plot.

On running the above code, I'm encountering the error - RuntimeError: Can not put single artist in more than one figure while trying to set the figure of each sub-plot. The thought process is to set each sub-plots's figure with the saved figure object. Is there any way to accomplish this ?
Thanks!

A: If you save the individual plots to files, you can later use imshow() and imread() from the matplotlib.image library to piece them together into one plot:
import matplotlib.pyplot as plt
import matplotlib.image as mpimg

a = list(range(1,10))
b = list(map(lambda x: x**2, a))
c = list(map(lambda x: x**3, a))
d = list(map(lambda x: x+200, a))

def save_plot(x, y, name):
    fig, ax = plt.subplots()
    ax.plot(x, y)
    ax.figure.savefig(name)
    plt.close()

save_plot(a, b, 'plot1')
save_plot(a, c, 'plot2')
save_plot(b, c, 'plot3')
save_plot(a, d, 'plot4')

fig, axs = plt.subplots(2, 2)
for i, ax in enumerate(axs.flat):
    ax.set_axis_off()
    filename = 'plot' + str(i+1) + '.png'
    ax.imshow(mpimg.imread(filename))
plt.show()

You may want to look into the imshow() documentation to reduce the whitespace around each subplot.

A: This may not be the cleanest way to write it, but I guess it does what you want:
a = list(range(1,10))
b = list(map(lambda x: x**2, a))
c = list(map(lambda x: x**3, a))
d = list(map(lambda x: x+200, a))

plots = []

fig=plt.figure()
plt.plot(a, b)
plots.append(fig)
plt.close()

fig=plt.figure()
plt.plot(a, c)
plots.append(fig)
plt.close()

fig=plt.figure()
ax3= plt.plot(b, c)
plots.append(fig)
plt.close()

fig=plt.figure()
plt.plot(a, d)
plots.append(fig)
plt.close()

fig,axs =plt.subplots(2,2)
axs[0,0].plot(a,b)
axs[0,1].plot(a,c)
axs[1,0].plot(b,c)
axs[1,1].plot(a,d)
plt.tight_layout()

plt.savefig('temp.png')


text:
Q: Why doesn't an HTML form post work properly on a WP7 device? I'm currently developing a mobile site and I am having trouble getting it to work on WP7. It's as basic as it doesn't pass data when doing a form submit. When I perform the submit, it will take me to the URL in the action but when I try and access data posted from that page it's null.
I created a basic test page to see if something else on the site was interfering - but that wasn't the case, the following code is that of the test page.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>

</head>
<body>
<form method="post" name="frmConfig" target="_blank" action="http://localhost/SessionTestApp/Default.aspx" >
    <input type="submit" value="Send" /><br />
    <textarea name="testpost" id="testpost" cols="80" rows="30" onclick="this.select()">
    </textarea>
</form>

</body>
</html>

and in the code behind of the aspx page I have the following C#
string strTest = "none";
strTest = Request["testpost"].ToString();
Response.Write(strTest);

I have tried it with a text area as above and an input box of type text. I have tried changing the submit to a button and using javascript to do the post.
Bare in mind this code works on the emulators of
Android 2.1/2.2/2.3
Blackberry v6
and on the real devices of
Android 2.1/2.2
Blackberry v5
Windows Mobile 6.5 - both IE and Opera
It also works in all desktop browsers - I can't find any reason for it but it doesn't work in the WP7 emulator or on a WP7 device. If I have missed something or anyone could tell me why it would be greatly appreciated!
Tom

A: If I connect to the page on the server (host PC of emulator image) then this works for me.
If I have the HTML on the phone (loaded via NavigateToString) then this doesn't work. :(
How are you loading the content on the phone?

A: It's fixed itself.
I installed WAMP and posts worked. I thought great... time to inspect IIS settings - at this point it still wasn't working using IIS.
I did a bit more testing, I deleted all my testing html files from IIS's wwwroot and copied them back from apache's www. Tried it again and it worked. Nothing more than deleting a file and recreating it. If anyone has any insight as to why deleting and remaking a file stopped a POST changing to a GET in a request header please enlighten me... I've gone spare over the past couple of days.
Also why did it only affect WP7? I suppose a situation like this it's similar to asking "What is the meaning of life?"


text:
Q: Rails/ActiveRecord: not retrieving the correct column through a join with a has_one/ belongs_to relationship Models
class Feature < ActiveRecord::Base
  belongs_to :agency_feature
  ...
end

class Agency < ActiveRecord::Base
  has_many  :agency_features, dependent: :destroy
  ...
end

class AgencyFeature < ActiveRecord::Base
  belongs_to :agency
  has_one :feature
end

Schema
create_table "agency_features", force: true do |t|
  t.integer "agency_id"
  t.integer "feature_id"
  t.boolean "enabled"
end

add_index "agency_features", ["agency_id"], name: "index_agency_features_on_agency_id", using: :btree
add_index "agency_features", ["feature_id"], name: "index_agency_features_on_feature_id", using: :btree

The problem
Agency.first.agency_feature gives me:
<AgencyFeature id: 508, agency_id: 1, feature_id: 1, enabled: false>

and Agency.first.agency_features.first.agencyreturns the correct agency.
The problem is Agency.first.agency_features.first.feature gives a column doesn't exist error and is trying to look for "agency_feature_id" inside of features.
How do I make it look for the feature with an id that corresponds to the "feature_id" attribute inside of AgencyFeature?

A: Replace has_one :feature, with belongs_to :feature
class AgencyFeature < ActiveRecord::Base
  belongs_to :agency
  belongs_to :feature
end

A: Maybe try running the migration again. I agree with Marnuss here. I think you don't have the field agency_feature_id in your Feature table. It should look something like -
create_table "features", force: true do |t|
  t.integer "agency_feature_id"
  ...
end

A: I actually figured this one out by changing key attributes in the feature model.
class AgencyFeature < ActiveRecord::Base
  belongs_to :agency
  has_one :feature, foreign_key: "id", primary_key: "feature_id"
end

Now I can use the has_one relationship like I intended. Where feature_id corresponds to the id of the feature in the feature table.


text:
Q: Android not starting Activity when started from a JobScheduler This is my issue.

*

*I have a main activity that triggers an app install if a specific apk is available. Which runs fine and shows the install dialog etc. so all good.

*Within the main activity I setup a job scheduler with a job info and schedule it to run every 30 mins. within the job I check for the apk, if present runs the installer and renames the installed apk.

The issue I have is that the install process (both use the same) works 100% from the main activity but when it runs from the jobscheduler the install intent is never shown.
Everything else in the jobscheduler process runs fine though. ie. file rename etc.
I've setup permissions in the manifest file.
<service android:name=".MyInstallService" android:permission="android.permission.BIND_JOB_SERVICE" />

Permissions:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.DELETE_PACKAGES" />
<uses-permission android:name="android.permission.GET_PACKAGE_SIZE" />
<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES" />
<uses-permission android:name="android.permission.REQUEST_DELETE_PACKAGES" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.INSTANT_APP_FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.QUERY_ALL_PACKAGES" />
<uses-permission android:name="android.permission.BROADCAST_PACKAGE_REMOVED" />
<uses-permission android:name="android.permission.WAKE_LOCK" />

Code:
    var fileProviderAuthorities = "my.files.provider";
    Java.IO.File file = new Java.IO.File(path);
    Android.Net.Uri apkUri = AndroidX.Core.Content.FileProvider.GetUriForFile(Android.App.Application.Context, fileProviderAuthorities, file);

    var intent = new Android.Content.Intent("android.intent.action.INSTALL_PACKAGE");
    intent.SetData(apkUri);
    intent.AddFlags(ActivityFlags.GrantReadUriPermission);
    intent.AddFlags(ActivityFlags.NewTask);

    Android.App.Application.Context.StartActivity(intent);


text:
Q: How to get cpu, memory and disk information about service fabric instances (maybe using REST apis)? I would like to have some hints to undestand the best and most convinient way to build a custom web page to monitor my service fabric cluster status showing some information about cluster nodes, for example cpu usage, free disk space, memory usage and state of single services.

A: You could use EventFlow to setup collection of Performance Counters and have that running on a stateless service on each node. From there you could collect which ever Perf Counters, and other health data you generate yourself, in addition to Service Fabric generated health data (such as Diagnostics and performance monitoring for Reliable Actors and Diagnostic functionality for Stateful Reliable Services.
Once you have setup your inputs to collect events and metrics you want to display you could create you own Custom Output that send the data to some storage or service from which you can generate your custom web view of it.
Another way would be to setup an Application Insights output and customize your dashboard to show the information you want. You could even setup export to Power BI if you want to work with that as a visualization tool and them embed your reports/Dashboards in a web page.
Or, you could, as suggested in the comments setup OMS/Log Analytics for Service Fabric.
If you're able to monitor and measure this information within your services within the cluster, you could also use Metrics and Node Capacity to gather an report this information directly within Service Fabric. You may want to do that anyway to ensure that Service Fabric is taking capacity into consideration and balancing the consumption of these resources.


text:
Q: How to make Xdebug only show backtrace when opening page, and not log the backtrace? Xdebug currently logs the entire backtrace in the defined error_log file:
CustomLog /var/log/www/access.log combined
ErrorLog /var/log/www/error.log
php_value error_log /var/log/www/error.log

This is fine. However, it logs too much. Ever since I installed Xdebug, it logs like this:
[02-May-2016 16:14:20 Europe/Berlin] PHP Notice:  Undefined variable: k in /var/www/index.php on line 30
[02-May-2016 16:14:20 Europe/Berlin] PHP Stack trace:
[02-May-2016 16:14:20 Europe/Berlin] PHP   1. {main}() /var/www/index.php:0

This repeats about 10 times. I'm absolutely fine with just the error message like this:
[02-May-2016 16:14:20 Europe/Berlin] PHP Notice:  Undefined variable: k in /var/www/index.php on line 30

and having the full stack trace on the page when opening. Is it possible? I can't find any options related to logging just the message, and showing the trace on the page.

*

*PHP Version 5.6.4

*xdebug version 2.4.0

A: After XDebug docs:
xdebug.default_enable = 0

Default value: 1
If this setting is 1, then stacktraces will be shown by default on an error event. You can disable showing stacktraces from your code with xdebug_disable(). As this is one of the basic functions of Xdebug, it is advisable to leave this setting set to 1.

Where I would rather use somewhere at the beginning of script tree function of xdebug_disable() with a proper switch, to make it possible to turn it on and off, depening on the development state:
define('VERBOSE', /* from config/db/etc value of true/false */ false);
if(!VERBOSE) {
    xdebug_disable();
}

Will leave you a bit more flexibility if you have an admin holding your servers who won't be happy to change production environment configurations.