Q: How to write this sql query efficiently in this case Here I have a query like below and am looping the child id and passing it to this query and getting the appropriate result. Here I have 33 child ids so the result for this query contains 33 rows
DECLARE @DATETIMENOW DATETIME
SET @DATETIMENOW = GETDATE()-7

SELECT COUNT(1) FROM  BKA.CHILDEVENTS CHE JOIN BKA.CHILDEVENTPROPERITIES CHEP ON CHEP.EVENTID = CHE.EVENTID
                      WHERE (CHE.TYPE = 'ACCIDENT' OR (CHE.TYPE = 'BREAK' AND CHEP.PROPERTY = 'SUCCESS' AND CHEP.PROPERTYVALUE = 'FALSE'))
                      AND CHE.CHILDID = @CHILDID AND CHE.ADDDATE BETWEEN DATEADD(DD, -(DATEPART(DW, @DATETIMENOW-7)-1), @DATETIMENOW-7) AND
                      DATEADD(DD, 7-(DATEPART(DW, @DATETIMENOW-7)), @DATETIMENOW-7) AS PREVIOUSWEEKACCIDENTS

here instead of looping the childid I have tried using join in this query but am getting the result in a single row. what I am doing wrong in this
DECLARE @DATETIMENOW DATETIME
SET @DATETIMENOW = GETDATE()-7
SELECT COUNT(1) FROM  BKA.CHILDEVENTS CHE JOIN BKA.CHILDEVENTPROPERITIES CHEP
                      ON CHEP.EVENTID = CHE.EVENTID
                      JOIN  BKA.CHILDINFORMATION CHINFO
                      ON CHE.CHILDID = CHINFO.CHILDID
                      WHERE (CHE.TYPE = 'ACCIDENT' OR (CHE.TYPE = 'BREAK' AND CHEP.PROPERTY = 'SUCCESS' AND CHEP.PROPERTYVALUE = 'FALSE'))
                      AND CHE.ADDDATE
                      BETWEEN DATEADD(DD, -(DATEPART(DW, @DATETIMENOW-7)-1), @DATETIMENOW-7) AND
                      DATEADD(DD, 7-(DATEPART(DW, @DATETIMENOW-7)), @DATETIMENOW-7)

Any suggestion?

A: You need to add a GROUP BY clause:
SELECT  CHINFO.CHILDID
      , COUNT(1)
FROM    BKA.CHILDEVENTS CHE
        JOIN BKA.CHILDEVENTPROPERITIES CHEP ON CHEP.EVENTID = CHE.EVENTID
        JOIN BKA.CHILDINFORMATION CHINFO ON CHE.CHILDID = CHINFO.CHILDID
WHERE   ( CHE.TYPE = 'ACCIDENT'
          OR ( CHE.TYPE = 'BREAK'
               AND CHEP.PROPERTY = 'SUCCESS'
               AND CHEP.PROPERTYVALUE = 'FALSE'
             )
        )
        AND CHE.ADDDATE BETWEEN DATEADD(DD,
                                        -( DATEPART(DW, @DATETIMENOW - 7) - 1 ),
                                        @DATETIMENOW - 7)
                        AND     DATEADD(DD,
                                        7 - ( DATEPART(DW, @DATETIMENOW - 7) ),
                                        @DATETIMENOW - 7)
GROUP BY CHINFO.CHILDID

A: A value in the where will invalidate an outer join
SELECT CHE.CHILDID
     , COUNT(1)
  FROM BKA.CHILDEVENTS CHE
  LEFT JOIN BKA.CHILDEVENTPROPERITIES CHEP
    ON CHEP.EVENTID = CHE.EVENTID
   AND ( CHE.TYPE = 'ACCIDENT'
          OR ( CHE.TYPE = 'BREAK'
               AND CHEP.PROPERTY = 'SUCCESS'
               AND CHEP.PROPERTYVALUE = 'FALSE'
             )
       )
   AND CHE.ADDDATE BETWEEN DATEADD(DD,
                                        -( DATEPART(DW, @DATETIMENOW - 7) - 1 ),
                                        @DATETIMENOW - 7)
                       AND DATEADD(DD,
                                        7 - ( DATEPART(DW, @DATETIMENOW - 7) ),
                                        @DATETIMENOW - 7)
GROUP BY CHE.CHILDID

A:           DECLARE @DATETIMENOW DATETIME
          SET @DATETIMENOW = GETDATE()

              SELECT  B.WEEK FROM BKA.CHILDINFORMATION CI LEFT OUTER JOIN

              (SELECT Distinct CHINFO.CHILDID,COUNT(*)  as week FROM  BKA.CHILDINFORMATION CHINFO
               JOIN  BKA.CHILDEVENTS CHE
                            ON CHE.CHILDID = CHINFO.CHILDID
               JOIN BKA.CHILDEVENTPROPERITIES CHEP
                            ON  CHE.EVENTID = CHEP.EVENTID
              WHERE
                          (CHE.TYPE = 'ACCIDENT' OR (CHE.TYPE = 'POTTYBREAK' AND CHEP.PROPERTY = 'SUCCESS'
                          AND CHEP.PROPERTYVALUE = 'FALSE'))
                            AND
                            CHE.ADDDATE
                            BETWEEN DATEADD(DD, -(DATEPART(DW, @DATETIMENOW-14)-1), @DATETIMENOW-14) AND
                            DATEADD(DD, 7-(DATEPART(DW, @DATETIMENOW-14)), @DATETIMENOW-14)      group by CHINFO.CHILDID) b
                            on CI.ChildID = b.ChildID


Q: Worst Case Binary Search? The question is:

In order to distinguish ordinary emails from spam,
  an algorithm with several features has been designed. Every feature provides
  information about the message, for instance number of suspicious words, the
  length of the message, degree of matching with spam templates etc. Every feature is a discrete variable with two values, for example, low/high, short/long, and similar/dissimilar. A tree with 255 nodes has been employed to make the decision whether to reject an email. How many operations/steps/time units
  are required at most to process each email?

I was thinking that this would be a perfect binary tree, so 2^n - 1 = 255, thus n = 8. However, I was starting to consider the following "worst-case" scenario:
...O
../\
.O..O
..../\
...O..O
and so forth.

So would this use a binary search recurrence relation. T(n)=T(n/2)+1?

A: I think you have the right answer Jay. From the question, I would draw the tree to look like this:
>                     o
>                    /\
> feature 1:        o  o
>                  /\  /\
> feature 2:      o  o o o
>
                   ...

So you start with a root value. Then you ask if the feature has been successfully met by the email or not, so it breaks into 2 nodes, Y or N. For Y (left-subtree), you ask if the email has met the 2nd feature, Y or N and this breaks off into 2 more node and the same is repeated on the N side (right-subtree). Repeat for all features.
We know that the big-Omega (worst case) for a perfect binary tree is log(n) [base 2]. So log(255) [base 2] is approximately 8, & that must be the max number of steps required.

A: If your tree is a balanced binary tree, then the answer would be 8.
The wording of the problem doesn't seem to call that out though. So that being said, we could make a tree that is a chain (only right children), which would make 255 the worse case.


Q: Externalize angular configuration file ( config.json ) I have an angular application (war format) that run on a jboss application server. My actual architecture is: Front app ( angular ) and back app ( java ), the front calls back services using the rest api link, that is provided in the src/conf/config.json file.
This is my app config file :
{
"restApiUrl": "https://jboss_host:8443/back/rest/",
"ldapAuthentication" : true
}

So, my needs for now ( the client need) is to externalize this config file to change the rest api link easily, without make a rebuild or redeploiment process.
I can't use any further elements in my architecture ( revers-proxy, conf server ) because it going to be a brain teaser for the client production, or api database ( the DB connection is provided by the back service ).
Please can you advise.

A: If you do not want load config file over http, try to use config.js file.
Rename config.json to config.js and change content to this:
var config = {
  "restApiUrl": "https://jboss_host:8443/back/rest/",
  "ldapAuthentication" : true
}

Then include config file into index.html in your application:
<script type="text/javascript" src="config.js"></script>

In angular application you can access to this config via (<any>window).config.
For more convenient use create ConfigService like:
@Injectable({providedIn: 'root'})
export class ConfigService {
  getConfig(): Config { // You should create some model of your config too or you can use 'any'
    return (<any>window).config;
  }
}

A: @mpstv thank you for your replay.
I was able to solve this, by using the power of java servlet. The solution was adding to the project war the WEB-INF folder ( servlet.class + web.xml ) that will charge the config file from the filesystem and serve it to the angular, while HTTP call.


Q: Calling NSXMLParser from static method does not parse I'm trying to build a nice little class with NSXMLParser for my needs.
I'm calling the class this way:
ViewController.m:
[IDAN_XML_Parser setXmlString:soapMsg];
[IDAN_XML_Parser setStringToFind:@"userID"];
[IDAN_XML_Parser setHeader:kAPP_PASSWORD andHeaderValue:kAPP_HEADER];
[IDAN_XML_Parser setSetupXml:kWEB_SERVICE_URL];
[IDAN_XML_Parser prepareParsingAndGetResponse];

NSString *answer = [IDAN_XML_Parser getResponse];
NSLog(@"Response: %@", answer);

And my class is this:
.h file:
#import <Foundation/Foundation.h>

@interface IDAN_XML_Parser : NSObject <NSXMLParserDelegate, NSURLConnectionDelegate>

+ (void)setXmlString:(NSString *)theXML;
+ (void)setStringToFind:(NSString *)stringToFind;
+ (void)setSetupXml:(NSString *)webServicesURL;
+ (void)setHeader:(NSString *)headerKey andHeaderValue:(NSString *)headerValue;
+ (BOOL)prepareParsingAndGetResponse;
- (NSInteger)startParsing;
+ (BOOL)isParsingOK;
+ (IDAN_XML_Parser *)sharedXML;
+ (NSString *)getXMLString;
+ (NSString *)getResponse;

@end

.m file
#import "IDAN_XML_Parser.h"

@implementation IDAN_XML_Parser

NSString *matchingElement;
NSString *xmlString;
NSMutableData *webData;
NSURLConnection *conn;
NSString *soapHeader_key;
NSString *soapHeader_value;
NSURL *url;
BOOL isHeader = NO;
NSInteger didGetError = 0;
BOOL elementFound;
NSMutableString *soapResults;
NSString *returnedString;
NSXMLParser *xmlParser;
NSString *exceptionReason;
NSString *resultXML;

#pragma mark - Setup Parsing

+ (IDAN_XML_Parser *)sharedXML
{
    static IDAN_XML_Parser *theParser;
    @synchronized(self) {
        if (!theParser)
            theParser = [[self alloc] init];
    }
    return theParser;
}

+ (void)setXmlString:(NSString *)theXML
{
    xmlString = theXML;
    NSLog(@"\n\nXML TO SEND: %@", xmlString);
}

+ (void)setStringToFind:(NSString *)stringToFind
{
    matchingElement = stringToFind;
}

+ (void)setHeader:(NSString *)headerKey andHeaderValue:(NSString *)headerValue
{
    isHeader = YES;
    soapHeader_key = headerKey;
    soapHeader_value = headerValue;
}

+ (void)setSetupXml:(NSString *)webServicesURL
{
    url = [NSURL URLWithString:webServicesURL];
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
    NSString *msgLength = [NSString stringWithFormat:@"%d", [xmlString length]];
    [req addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
    [req addValue:msgLength forHTTPHeaderField:@"Content-Length"];
    [req setHTTPMethod:@"POST"];
    [req setHTTPBody: [xmlString dataUsingEncoding:NSUTF8StringEncoding]];

    if (isHeader) {
        [req setValue:soapHeader_value forHTTPHeaderField:soapHeader_key];
    }

    conn = [[NSURLConnection alloc] initWithRequest:req delegate:self];

    if (conn)
    {
        webData = [NSMutableData data];
    }
}

-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *) response
{
    [webData setLength: 0];
}

-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *) data
{
    [webData appendData:data];
}

-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *) error
{
    didGetError = 1;
    NSLog(@"\n\nConnection Error: %@", error);
}

-(void) connectionDidFinishLoading:(NSURLConnection *) connection
{
    resultXML = [[NSString alloc] initWithBytes:[webData mutableBytes]
                                                length:[webData length]
                                              encoding:NSUTF8StringEncoding];
    didGetError = 0;
    NSLog(@"\n\nRESPONSE XML: %@", resultXML);
}

+ (BOOL)prepareParsingAndGetResponse
{
    NSInteger isParsingOK;
    isParsingOK = [[self sharedXML] startParsing];

    if (isParsingOK == 1) {
        return YES;
    } else {
        return NO;
    }
}

- (NSInteger)startParsing
{
    @try {
        xmlParser = [[NSXMLParser alloc] initWithData:webData];
        [xmlParser setDelegate:self];
        [xmlParser setShouldResolveExternalEntities:YES];
        [xmlParser parse];
    }
    @catch (NSException *exception) {
        didGetError = 1;
        exceptionReason = exception.reason;
        NSLog(@"Exception Reason: %@", exception.reason);
    }

    if (didGetError != 1) {
        didGetError = 0;
    }

    return didGetError;
}

+ (NSString *)getXMLString
{
    return resultXML;
}

+ (BOOL)isParsingOK
{
    if (didGetError == 1) { // We have error
        return 1;
    } else { // We don't have error
        return 0;
    }
}

+ (NSString *)getResponse
{
    return returnedString;
}

#pragma mark - Start Parsing

- (void)parser:(NSXMLParser *)parser didStartElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict
{
    NSLog(@"START PARSING!");
    if ([elementName isEqualToString:matchingElement]) {
        if (!soapResults) {
            soapResults = [[NSMutableString alloc] init];
        }
        elementFound = YES;
    }
}

- (void)parser:(NSXMLParser *)parser foundCharacters:(NSString *)string
{
    if (elementFound) {
        [soapResults appendString:string];
        NSLog(@"\n\nsoapResults: %@", soapResults);
    }
}

- (void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName
{
    if ([elementName isEqualToString:matchingElement]) {
        returnedString = soapResults; // Save the element we found
        elementFound = NO;
    }
}

@end

I manage to send and get back the correct xml but it's actually doesn't start the parsing.
Any idea how can I solve it?

A: You are initiating an asynchronous NSURLConnection and then immediately starting the parsing process. You need to defer the initiation of the parsing until connectionDidFinishLoading, or you should do a synchronous NSURLConnection (but obviously, not from the main queue). Thus, while you're eventually getting a response, the parsing is undoubtedly initiated before the response has been received.


Q: Best way to transfer struct from one process to another? I have one server process and some clients, the clients need to send to the server as many structures as possible, they will not wait for any answer, just send and send. In which way i can transfer next struct in that case:
typedef struct tagTDATA {
         BYTE c1;
         DWORD dw1;
         DWORD dw2;
         char ch[255];
} TDATA, *PTDATA;

Cant use Boost. The best way its Win API. And i don't need code solution just point me in right direction. Thanks.

A: In my understanding you can solve this issue by implementing a shared queue. The pattern of your problem is more towards Producer Consumer Problem
You can also take these examples

*

*http://msdn.microsoft.com/en-us/library/dd728068.aspx

*How should i write producer /consumer code in C#?

A: Are the server and clients on different hosts? If so, why don't you take UDP and to methods to serialize your structure to send via network and the second one to get it back to structure? ...

A: WM_COPYDATA is specifically meant for transferring structs between processes. Check it out.
You mentioned pointers though - and no, you cannot expect pointers to work between processes. If you have variable-length arrays or pointers, it's probably necessary to serialize the data, for example with BSON or XML.

A: It sounds like you are looking for an asynchronous IPC mechanism. Sockets are probably the easiest way to achieve this. Pipes would be another obvious alternative, and there are many higher level libraries available, but I think sockets sound like the best fit.

A: ReadProcessMemory and WriteProcessMemory ought to be able to do the trick for you.


Q: Accordion animation in ui-bootstrap is different from the original bootstrap (size of the accordion is increased, visually it "jumps") The default animation in bootstrap does not change the size of the full accordion in the process. For some reason in the ui-bootstrap that is not the case and while it animates it does a strange increase in size which looks like it "jumps" (easy to notice if you look at the bottom of control). I think that the original behaviour is way more pleasant to the eye as the ui-bootstrap may even change the scrollbar size while it's animating.
Why is it doing it differently and is there an easy way to fix it? E.g. by changing the template.

A: The accordion-group template uses the uib-collapse directive to open/close the panels, see here  Removing the uib-collapse directive will bypass some of the unexpected behavior you are seeing, but I think you will need to manage closing/opening the panels.


Q: How to prevent reordering of loads after stores using the C++11 atomics API? I know that you can use the C++11 atomics API in a producer-consumer context to make sure that a consumer sees the "done writing" flag only after some produced record has been completely written out, i.e.
producer:
data[write_index] = <something>
status[write_index].store(READABLE, std::memory_order_release)

consumer:
if (status[read_index].load(std::memory_order_acquire) == READABLE)
  //do something with data[read_index]

My question is what happens next - how does the consumer safely tell the producer that it has finished reading from data[read_index], so that the producer can write to data[read_index] for some other purpose?
On x86, I can do (I think?)
consumer:
//do something with data[read_index] //LINE A
asm volatile("" : : : "memory"); //compiler barrier
status[read_index].store(AVAILABLE, std::memory_order_relaxed) //LINE B

and
producer:
if (status[write_index].load(std::memory_order_relaxed) == AVAILABLE)
  //write_index is available for writing

My impression is that on an architecture where loads can be reordered after stores, the writer could observe LINE B before LINE A has finished, which would cause a problem.
Is there a way to do this using the C++11 atomics API? The atomic_thread_fence instructions seemed promising but after reading the documentation I don't see that it gives the guarantee I need here.
Thanks!

A: Always use sequential consistency if in doubt :)

memory_order_seq_cst
  The operation is ordered in a sequentially consistent manner: All operations using this memory order are ordered to happen once all accesses to memory that may have visible side effects on the other threads involved have already happened.
  This is the strictest memory order, guaranteeing the least unexpected side effects between thread interactions though the non-atomic memory accesses.

It applies either to the consumer's store which sends the signal back to the producer or the std::atomic_thread_fence before it.
void producer() {
  for(;;) {
    data[write_index] = <something>;
    status[write_index].store(READABLE, std::memory_order_release);
    // do something else while consumer reads it

    // producer knows for sure that reader will consume it and signal back
    while( status[write_index].load(std::memory_order_acquire) != WRITEABLE)
        _mm_pause(); // or at least std::this_thread::yield();
  }
}
void consumer() {
    while (status[read_index].load(std::memory_order_acquire) != READABLE)
        _mm_pause(); // or at least std::this_thread::yield();
    //do something with data[read_index]

    // signal back and prevent loads from reorder below
    status[read_index].store(WRITEABLE, std::memory_order_seq_cst);
}

I'm afraid that this will result in excessive synchronization on x86.. but until someone else comes up with more tricky (but still portable C++11) approach, consider this as the price of portability.


Q: Getting "TypeError: cannot pickle '_thread.RLock' object" when using Broadcast Variable in Spark Cluster The Spark Cluster has one Master and four Slaves. I have a small table in the database, so I read the table in Master node and set it as a Broadcast variable like this:
def checkTableExists(tablename, connection):
try:
    query = 'SELECT * FROM {0}'.format(str(tablename))
    print(query)
    connection.cursor.execute(query)
    return True
except odb.DatabaseError as e:
    x = e.args[0]
    if x.code == 942:  ## Only catch ORA-00942: table or view does not exist error
        return False
    else:
        raise e

def read_cheque_paper(spark, connection):
   if create_tables.checkTableExists(small_table, connection) == True:
     query_cheque = '''select * from {}'''.format(small_table)
     df = connection.read_sql(query_cheque)
     broadcastStates = spark.sparkContext.broadcast(df)
   else:
     df = spark.createDataFrame([], StructType([]))
     broadcastStates = spark.sparkContext.broadcast(df)
return broadcastStates

def trx_features(dataframe, broadcast_df):
  df_small = broadcast_df.value
  if df_small.empty:
    df = df.withColumn('field_check', lit(None).cast(StringType()))
  else:
    df = calculate_field_check(dataframe, df_small)
    df.select('field_check').where('field_check==1').show()
return df

def distribute_data(spark):
   connection = cx_Oracle.connect(
    config.username,
    config.password,
    config.dsn,
    encoding=config.encoding)
   if gf.flag_trx:
      source_table_name, table_name = gf.create_query('trx')
      broadcast_df = read_cheque_paper(spark, connection)
      predicates = list_predicates(connection, source_table_name, date_field)
      dataframe = gf.read_spark(spark, table_name, predicates, connection)
      df_trx = trx_features(dataframe, broadcast_df)
      write_spark(dist_table_name_trx, df_trx)
return

if __name__ == '__main__':
   master = "spark://IP master:7077"
   conf = SparkConf() \
    .setAppName('ETL') \
    .setMaster(master) \
    .set("spark.jars", "ojdbc8.jar")

   sc = SparkContext.getOrCreate(conf=conf)
   sqlContext = SQLContext(sc)
   spark = sqlContext.sparkSession
   spark.sparkContext.setLogLevel('ERROR')
   start_time = datetime.datetime.now().timestamp()
   distribute_data(spark)
   end_time = datetime.datetime.now().timestamp()
   duration = end_time - start_time

When this program run in local mode,I get the result without any errors. But, while I run that in the cluster,when it reach to the df_small = broadcast_df.value it was stopped with this error:
TypeError: cannot pickle '_thread.RLock' object

Would you please guide me what is wrong with defining the broadcast varible?
Any help is really appreciated .


Q: How to draw perfect straight line passing through majority of given points in MATLAB? Can someone help me figure out how to draw a perfect straight line from given set of points passing through majority (may be 5-6 point out of 20) of these points? Please note that this is not a line fit problem, but perfect line should be drawn (horizontal, vertical or somewhat slanted) between majority of the given points.
Here is MATLAB code:

e=[161    162   193   195   155    40   106   102   125   155   189   192   186   188   185   186   147   148   180   183];

f =[138    92    92   115   258   124   218   114   125   232   431   252   539   463   643   571   582   726   726   676];

figure;scatter(f, e, 5, 'red');

axis ij;

and here is image:

A: Since you want the line to go through the majority of points, it sounds quite like a line fitting problem even though you say it isn't. Have you looked at the Theil-Sen estimator (for example this one on fex), which is a linear regression ignoring up to some 30% of the outliers.
If you simply want a line through the extrema you might do something like this:
% Setup data
e = [161    162   193   195   155    40   106   102   125   155   189   192   186   188   185   186   147   148   180   183];
f = [138    92    92   115   258   124   218   114   125   232   431   252   539   463   643   571   582   726   726   676];
% Create scatterplot
figure(1);
scatter(f, e, 5, 'red');
axis ij;

% Fit extrema
[min_e, min_idx_e] = min(e);
[max_e, max_idx_e] = max(e);
[min_f, min_idx_f] = min(f);
[max_f, max_idx_f] = max(f);
% Determine largest range and draw line accordingly
if (max_e-min_e)>(max_f-min_f)
    line(f([min_idx_e, max_idx_e]), e([min_idx_e, max_idx_e]), 'color', 'blue')
    text(f(max_idx_e), e(max_idx_e), ' Extrema')
else
    line(f([min_idx_f, max_idx_f]), e([min_idx_f, max_idx_f]), 'color', 'blue')
    text(f(max_idx_f), e(max_idx_f), ' Extrema')
end

% Fit using Theil-Sen estimator
[m, e0] = Theil_Sen_Regress(f', e');
line([min_f, max_f], m*[min_f, max_f]+e0, 'color', 'black')
text(max_f, m*max_f+e0, ' Theil-Sen')

However, as you'll notice neither solution automatically fits the points automatically, simply because there are too many outliers, unless you filter those beforehand. Therefore you probably are better off using the RANSAC algorithm as proposed by Shai and McMa.

A: That's a textbook example for the RANSAC algorithm. This free toolbox for Matlab actually has some very nice examples of line fitting.

A: An easy but not very efficient solution would be to compute slope between each two points and if a set of points lie on a straight line, all pairs of these set would have the same slope. So one algorithm could pick all the poirs with same slope and connect them if they have one point in common. finally you have to choose the largest set. The time complexity of this algorithm will be O(N^2 log N) which N is number of points.
As I see in your figure there is not a real perfect line going through all the points, rather there is a tolerance which in this algorithm could be defined as the criteria by which you connect two pairs. say if two slopes are different by less than 2 percent we connect the pairs.


Q: Unexpected binding behaviour I have select list i set default option to be chosen. what happen is for few second it works then it disappear and the blank option in the list is chosen as default.
 <div class="form-group">
              <select class="form-control" ng-model="item.action" ng-options="option.value as option.title for option in options">
              </select>
            </div>

i want to set defualt option to be chosen :
so my controller look like this:
$scope.item = {};
  $scope.options = [{
    title: 'On entering',
    value: 'enter'
  }, {
    title: 'On exiting',
    value: 'exit'
  }];
  $scope.item.action= $scope.options[0].value;

  $scope.profile = me.getUser();
  $scope.profile.then(
    function(user) {
      $scope.owner = user;
      $scope.item = {};
      $scope.item.data = '';
      $scope.item.published = true;
      $scope.item.action= $scope.action;
      $scope.item.owner = $scope.owner.displayName;
    },
    function(response) {
      console.log(response);
    }
  );

me is a service that fecth the user data.
the reason why am defining $scope.item = {}; again is because i can't apend the displayName to the $scope.item out of the scope.
I commented this part of the code and it works well:
  $scope.profile = me.getUser();
  $scope.profile.then(
    function(user) {
      $scope.owner = user;
      $scope.item = {};
      $scope.item.data = '';
      $scope.item.published = true;
      $scope.item.action= $scope.action;
      $scope.item.owner = $scope.owner.displayName;
    },
    function(response) {
      console.log(response);
    }
  );

But now i can't figure out how to build my item object to send it in HTTP request


Q: Simplify PHP for SQL data retrevial I'm new to PHP and SQL queries but trying to learn. Anyway, I have the following code which I'm sure there will be a simpler way of doing (hopefully as I intend to do the same for day of year not just month).
My current code is;
//Get jan power consumption
$janquery = mysql_query("SELECT SUM(kw*tdsecs) FROM data WHERE year(time) = year(CURDATE()) AND month(time) = 1");
$janresult = mysql_fetch_array($janquery);
$jankwm = $janresult[0] / 60;
$jankwh = round($jankwm / 60,2);

//Get feb power consumption
$febquery = mysql_query("SELECT SUM(kw*tdsecs) FROM data WHERE year(time) = year(CURDATE()) AND month(time) = 2");
$febresult = mysql_fetch_array($febquery);
$febkwm = $febresult[0] / 60;
$febkwh = round($febkwm / 60,2);

and so on then...
$values=array(
    "Jan" => $jankwh,
    "Feb" => $febkwh,
    "Mar" => $markwh,
    "Apr" => $aprkwh,
    "May" => $maykwh,
    "Jun" => $junkwh,
    "Jul" => $julkwh,
    "Aug" => $augkwh,
    "Sep" => $sepkwh,
    "Oct" => $octkwh,
    "Nov" => $novkwh,
    "Dec" => $deckwh
);

I want to avoid having 12 queries so any help would be appreciated.

A: SELECT
    month(time) as `month`,
    SUM(kw*tdsecs) as `sum`
FROM data
WHERE year(time) = year(CURDATE())
group by month(time)
order by month(time)

A: SELECT month(time), SUM(kw*tdsecs) FROM data
WHERE year(time) = year(CURDATE()) group by month(time);

A:   mysql_query("SELECT month(time),SUM(kw*tdsecs) FROM data WHERE
  year(time) = year(CURDATE()) AND month(time) in
  (1,2,3,4,5,6,7,8,9,10,11,12) group by month(time)")

A: A simple solution (not the best) would be to loop through the months and store the results in a array:
for($month=1; $month<=12; $month++) {
  $query = mysql_query(
    "SELECT SUM(kw*tdsecs) FROM data
     WHERE year(time) = year(CURDATE()) AND month(time) = $month");
  $result = mysql_fetch_array($query);
  $kwm[$month] = $result[0] / 60;
  $kwh[$month] = round($kwm[$month] / 60,2);
}


Q: How to convert Object to List in c#? I have a List<string> in Model.
When I write a html helper, I can get the data from metadata.Model, which is an object
// this is from MVC3 (namespace System.Web.Mvc -> ModelMetadata), I did not write this
// Summary:
//     Gets the value of the model.
//
// Returns:
//     The value of the model. For more information about System.Web.Mvc.ModelMetadata,
//     see the entry ASP.NET MVC 2 Templates, Part 2: ModelMetadata on Brad Wilson's
//     blog
public object Model { get; set; }

My question is: how to get List<string> from an Object?

A: If the underlying type of the object variable is List<string>, a simple cast will do:
// throws exception if Model is not of type List<string>
List<string> myModel = (List<string>)Model;

or
// return null if Model is not of type List<string>
List<string> myModel = Model as List<string>;


Q: How can I tell if a file has changed through .NET? I am looking for a way to determine when a particular file has changed, through .NET. (What I ultimately want is functionality that makes a copy of the file as soon as it has changed.) How can this be done?

A: class Program
    {
        static void Main(string[] args)
        {
            FileSystemWatcher fsw = new FileSystemWatcher(@"c:\temp");
            fsw.Changed += new FileSystemEventHandler(fsw_Changed);
            fsw.Deleted += new FileSystemEventHandler(fsw_Deleted);
            fsw.Renamed += new RenamedEventHandler(fsw_Renamed);
            fsw.Created += new FileSystemEventHandler(fsw_Created);
            fsw.EnableRaisingEvents = true;
            Console.ReadLine();
        }

        static void fsw_Created(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("{0} was created", e.FullPath);
        }

        static void fsw_Renamed(object sender, RenamedEventArgs e)
        {
            Console.WriteLine("{0} was Renamed", e.FullPath);
        }

        static void fsw_Deleted(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("{0} was Deleted", e.FullPath);
        }

        static void fsw_Changed(object sender, FileSystemEventArgs e)
        {
            Console.WriteLine("{0} was Changed", e.FullPath);
        }
}

A: Microsoft Windows, and its ultimate ancestor MS-DOS, has always had an attribute on its files that indicates whether that file was changed since the last time that attribute was cleared, sort of a "dirty flag". It was used in the past by backup programs to find those files that needed to be backed up incrementally, and then cleared when a copy of that file had been made.
You can use File.GetAttributes to get the attributes on a file, and use File.SetAttributes to clear that "Archive" attribute. The next time that file is opened for writing, that archive flag will be set again.
Be careful about copying files that have been changed, as those files may still be open. You probably want to avoid concurrency problems by opening them for read exclusively when copying, and if that fails you know that file is still open for writing.

A: To all who responded with, use FileSystemWatcher, how do you deal with the time your app isn't running? For example, the user has rebooted the box, modified the file you are interested in, and then starts up your app?
Be sure to also read the docs on FileSystemWatcher Class carefully specially the section about Events and Buffer Sizes.

A: You can use a FileSystemWatcher object.  This raises events on changes to files within the specified watched folder.

A: You're likely to run into issues with FileSystemWatcher (not getting events, too many events, etc.)  This code wraps it up and solves many of them:
http://precisionsoftware.blogspot.com/2009/05/filesystemwatcher-done-right.html

A: You will have to note the modified date of files which you want to check.
After certain period you can check if the file was modified later.
If the file is modified with different date and time, you can make the copy.


Q: Linux: how to check the largest contiguous address range available to a process I want to enter the pid at the command line and get back the largest contiguous address space that has not been reserved.  Any ideas?
Our 32 bit app, running on 64 bit RHEL 5.4, craps out after running for a while, say 24 hours.  At that time it is only up to 2.5 gb of memory use, but we get out of memory errors.  We think it failing to mmap large files because the app's memory space is fragmented.  I wanted to go out to the production servers and just test that theory.

A: Slighly nicer version of my above comment:
#!perl -T

use warnings;
use strict;

scalar(@ARGV) > 0 or die "Use: $0 <pid>";

my $pid = $ARGV[0];
$pid = oct($pid) if $pid=~/^0/;         # support hex and octal PIDs
$pid += 0; $pid = abs(int($pid));       # make sure we have a number

open(my $maps, "<", "/proc/".$pid."/maps") or
        die "can't open maps file for pid ".$pid;

my $max = 0;
my $end = 0;
while (<$maps>) {
        /([0-9a-f]+)-([0-9a-f]+)/;
        $max = hex ($1) - $end if $max < hex ($1) - $end;
        $end = hex ($2);
}

close ($maps);

END {
        print "$max\n";
}

A: Probably not exactly what you want, but from inside a process it is possible to do binary search by mmaping without allocating. I.e. mmap(4GB), if that fails mmap(2GB), if that succeeds mmap(3GB), and so on.

A:
we get out of memory errors. We think it failing to mmap large files because the app's memory space is fragmented.

However, one can also get OOM errors while still having lots of free virtual address ranges on paper, for example by sufficient lack of RAM+swap. Furthermore your system and/or program(s) may have overcomitting turned off (sysctl -a), or have swapping inhibited (mlock(2)), or you actually have a very blunt limit on mappings (ulimit -v) — the latter is easy to run in given some distributions set such ulimits one way or another.


Q: REDIS-Python -> get all keys and respective values from 1 database I am trying to get all keys and values from a REDIS db. There are about 35000+ open connections on REDIS by the other users. I am using r.scan_iter()to get all the keys and I am appending them to a list. I am currently using pipeline.execute() to get all the values for these list of keys. Is this necessary to get the values for keys from redis? Or is there some way to access values of keys from r.scan_iter() loop.
Key = a|b|c
Value = V1:X1 V2:X2 V3:X3
My code is as below:
r = redis.Redis(host,port,db)
#To get all the keys and then use pipeline to get corresponding values
for key in r.scan_iter():
    pipe.hgetall(key.decode('utf-8'))
values = pipe.execute()
#To  loop through the values and read
for value in values:
     # Get all the values for each key
     for name, value in value.items():


Q: Facebook and Whatsapp sharing buttons I have an PHP page showing an image to the user, and I want them to share via Facebook or WhatsApp,
Here the code for the head part:
<meta name="description" content="<?php echo $Rowdati['metadescrizione'];?>">
<meta name="keywords" content="<?php echo $Rowdati['keywordsapp'];?>">
<meta property="og:image" content="<?php echo $urlimmagineuser; ?>">
<meta property="og:image:type" content="image/png">
<meta property="og:image:width" content="400">
<meta property="og:image:height" content="400">
<meta property="og:title" content="<?php echo $Rowdati['titolo_fb_share'];?>">
<meta property="og:description " content="<?php echo $Rowdati['descr_fb_share'];?>">

Here the code for getting the image to share and display on the web page:
<?php echo "

    ";
?>

Here the share buttons:
<div class="col-sm-4" data-href="<?php echo $actual_link;?>" data-layout="button" data-size="large" data-mobile-iframe="true">
    <button class="btn col-xs-12 scroll_effect shadow-top-down">
        <a class="fb-xfbml-parse-ignore" target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=<?php echo $actual_link;?>;src=sdkpreparse">

share on FB
    </button>

    <button class="btn col-xs-12 scroll_effect shadow-top-down">
        <?php
            $actual_link = (isset($_SERVER['HTTPS']) ? "https" : "http") .
            "://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
        ?>
        <a href="whatsapp://send?text=<?php echo $Rowdati['testo_whatsapp'] . "http://mydomain.it";?>" data-action="share/whatsapp/share">

share on Whatsapp

    </button>

The page works fine, except that when i share it on Facebook or WhatsApp it does not return the image preview...
I cannot figure out why after checking and rechecking the code.


Q: Making a V-shaped pattern with Python I wanna make  pattern　by　algorithm.
Result is the pattern like
..........
..........
..........
..........
..........
..........
.########.
.########.
##########
##########

But my ideal pattern is
##......##
##......##
.##....##.
.##....##.
..##..##..
..##..##..
...####...
...####...
....##....
....##....

So,I cannot understand why I cannot do it in my code.
By comparing current pattern & ideal one,I think  data cannot use correctly. But I cannot know how to fix this. What should I do to do it?

A: A different approach:
final = []
for i in range(10):
    temp = ["." for j in range(10)]
    temp[int(i / 2)] = "#"
    temp[int(i / 2) + 1] = "#"
    temp[-int(i / 2) - 1] = "#"
    temp[-int(i / 2) -2] = "#"
    final.append(temp)

for a in final:
    print("".join(a))

Will print:
##......##
##......##
.##....##.
.##....##.
..##..##..
..##..##..
...####...
...####...
....##....
....##....

This can be made even cleaner, but here you can see all the different steps, so I hope it helps

A: # 10x10
#             first # start position  second # start position from last
# LN 0 1:     0                       -1
# LN 2 3:     1                       -2
# LN 2k 2k+1: k                       -k-1
# LN 8 9:     4                       -5

# dw: dot '.' width
# sw: sharp '#' width
# if k == 0 part is ugly, for list slicing
def draw(dw, sw):
    for k in range(dw//2):
        row = [ '.' for _ in range(dw) ]
        row[k:k+sw] = '#' * sw
        if k == 0:
            row[-sw:] = '#' * sw
        else:
            row[-k-sw:-k] = '#' * sw
        print("".join(row))
        print("".join(row))

draw(10, 2)

with draw(20, 2) got
##................##
##................##
.##..............##.
.##..............##.
..##............##..
..##............##..
...##..........##...
...##..........##...
....##........##....
....##........##....
.....##......##.....
.....##......##.....
......##....##......
......##....##......
.......##..##.......
.......##..##.......
........####........
........####........
.........##.........
.........##.........

A: I would use itertools' product, and filter the indices that aren't relevant
def v(row):
    return set([int(row/4), row-int(row/4), int(row/4)+1, row-int(row/4)-1])

from itertools import product
indices = product(range(len(array)),range(len(array[0])))
indices = filter(lambda i: i[1] in v(i[0]), indicies)
for r,c in indices:
    array[r][c] = "#"

A: Don't know what you're trying to accomplish here, but I can do it, too:
a = "##..."
for i in range(10):
    b = ("."*int(i/2) + a)[:5]
    print(b + b[::-1])

A: Slightly more concise:
width = 10

for i in range(width):
    line = ['.'] * width
    m = i//2
    line[m] = line[m+1] = line[-m-1] = line[-m-2] = "#"
    print(''.join(line))


Q: Do custom networks replace default network in docker-compose.yml Does specifying custom networks in docker-compose remove services from the default network? I can't find any information about this.
example
version: '3'
services:
  nginx:
    image: 'nginx:alpine'
    restart: always
    networks:
      - web
      - internal_network
    labels:
      - "traefik.docker.network=traefik"
      - "traefik.backend=blog"
      - "traefik.frontend.rule=Host:test.ondrovo.com"
      - "traefik.port=80"
      - "traefik.frontend.passHostHeader=true"
      - "traefik.protocol=http"
    volumes:
      - ./www:/srv/www
      - ./config/nginx.conf:/etc/nginx/nginx.conf
      - ./config/conf.d:/etc/nginx/conf.d

  php:
    image: php:7-fpm
    volumes:
      - ./www:/srv/www
    networks:
      - internal_network

networks:
  web:
    external:
      name: traefik

  internal_network:
    internal: true

in this case, is internal_network needed or can i just leave it out?

A: The answer is yes, the default network is removed if you specify them manually.
I went ahead and tried it.
You can specify 'default' in the networks list, however, and it apparently does not need to be declared in the top-level list.


Q: How to create filterable and sortable div elements I am using rails 3 and ruby 1.9 to develop a ecommerce app. I currently have a loop pulling product info from the database into a div for each product to populate the storefront.
Problem is I have been been trying without any luck to figure out how to make the products sortable and filterable. Basically i want potential customers to be able to filter and/or sort the products listing by some of the data associated with the products (e.g., sort by date added or filter by manufacturer).
So far i've come across some templates using jquery to accomplish this, but i haven't been able to find anything leveraging the rails framework. Ive included the code below. any assistance would be much appreciated.

Today's

Offers

<% @products.each do |product| %>

 <%= product.title %>

<%= image_tag(product.image_url, :alt =>product.title,  :class=>"product-image")%>


Q: Parse data from php to jsquery.flot.pie I've seen some questions about this already but I still couldn't clear the fog around this...
I have this sql statement to get data:
<script type="text/javascript">

<?php

$query = "SELECT rel_id, SUM(suma) FROM $tbl_rel_balansas INNER JOIN $tbl_balansas ON $tbl_rel_balansas.rel_id = $tbl_balansas.id WHERE $tbl_rel_balansas.member_id = '$_SESSION[id]'";
$result = mysql_query ($query);
while($row = mysql_fetch_array($result)){
    echo 'var some_data = ' . json_encode( $viso );
}

?>

Next is the js part:
    $(function () {

   $.plot($("#placeholder"), [some_data],
{
        series: {
            pie: {
                show: true
            }
        },
        legend: {
            show: false
        }
});
});
</script>

I was thinking I could reach the data in some_data and use it to display it in the pie chart, unfortunately this is not the way to go.
Any help and suggestions are greatly appriciated ! :)

A: The most likely problem is that your numeric data is being interpreted as a string.
From the API.txt:

Note that to simplify the internal
  logic in Flot both the x and y values
  must be numbers (even if specifying
  time series, see below for how to do
  this). This is a common problem
  because you might retrieve data from
  the database and serialize them
  directly to JSON without noticing the
  wrong type. If you're getting
  mysterious errors, double check that
  you're inputting numbers and not
  strings.

So either force your data to numeric types on the PHP side, or do it in javascript, perhaps with .Number(some_data)


Q: dotnet restore: An error occurred while retrieving package... metadata Root element is missing I have a nuget/docker build issue that I’ve spent a couple of days debugging and am running out of ideas: Do you know why I am getting the below error?
The issue is with one asp.net core solution (others that are very similar are unaffected): Although I can build the affected solution in visual studio 2019 using the docker compose file, it will not work using the dockerfile and so the docker build command can’t be run.
If I run the dockerfile by doing a build as below in command prompt:
docker build -f MStoreBosGateway/MStoreBosGatewayApi/Dockerfile --pull --no-cache -t mstorebosgateway:0.041 .

then I get the following error:
Step 11/26 : RUN dotnet restore "MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj"
>  ---> Running in 30819cb5db4f
> /usr/share/dotnet/sdk/2.2.402/NuGet.targets(123,5): error : An error
> occurred while retrieving package metadata for
> 'System.Text.Encodings.Web.4.5.0' from source
> '/usr/share/dotnet/sdk/NuGetFallbackFolder'.
> [/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj]
> /usr/share/dotnet/sdk/2.2.402/NuGet.targets(123,5): error :   Root
> element is missing.
> [/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj]
> The command '/bin/sh -c dotnet restore
> "MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj"'
> returned a non-zero code: 1

I’ve put RUN echo commands after each line in the dockerfile so it looks like it is the dotnet restore that is causing this issue. If I run the dotnet restore command by itself it runs ok.
To try to resolve this I’ve done quite a few things e.g.

*

*-Deleted the obj and bin folders from this solution and projects,

*-Uninstalled and reinstalled nuget,

*-Deleted the nuget caches to force the packages to be redownloaded,

*-uninstalled and reinstalled the dotnet core sdks,

*-Removed the package mentioned in the error message ('System.Text.Encodings.Web.4.5.0) from the project file (this did
not cause any errors so must have been redundant anyway). That did
not affect this error and it restores this package so there must be
something else saying to use this package or possibly system packages
are all included by default anyway.

My colleague can build this project and has sent me a copy of it that he can build; I get the same issue building his copy so assume it’s something external to the project.
I have added below the output if I add ‘ –verbosity detailed’ to the dotnet restore command in the docker file.
           GET https://api.nuget.org/v3-flatcontainer/microsoft.extensions.dependencyinjection.abstractions/index.json
           OK https://api.nuget.org/v3-flatcontainer/aspnet.security.oauth.validation/index.json 342ms
           GET https://api.nuget.org/v3-flatcontainer/aspnet.security.oauth.validation/2.0.0/aspnet.security.oauth.validation.2.0.0.nupkg
           OK https://api.nuget.org/v3-flatcontainer/aspnet.security.oauth.validation/2.0.0/aspnet.security.oauth.validation.2.0.0.nupkg 52ms
           GET https://api.nuget.org/v3-flatcontainer/microsoft.aspnetcore.authentication/index.json
           GET https://api.nuget.org/v3-flatcontainer/newtonsoft.json/10.0.2/newtonsoft.json.10.0.2.nupkg
     1>/usr/share/dotnet/sdk/2.2.402/NuGet.targets(123,5): error : An error occurred while retrieving package metadata for 'System.Text.Encodings.Web.4.5.0' from source '/usr/share/dotnet/sdk/NuGetFallbackFolder'. [/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj]
/usr/share/dotnet/sdk/2.2.402/NuGet.targets(123,5): error :   Root element is missing. [/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj]
           OK https://api.nuget.org/v3-flatcontainer/swashbuckle.aspnetcore.swaggergen/index.json 156ms
           GET https://api.nuget.org/v3-flatcontainer/swashbuckle.aspnetcore.swaggergen/4.0.1/swashbuckle.aspnetcore.swaggergen.4.0.1.nupkg
           OK https://api.nuget.org/v3-flatcontainer/swashbuckle.aspnetcore.swaggerui/index.json 160ms
           GET https://api.nuget.org/v3-flatcontainer/swashbuckle.aspnetcore.swaggerui/4.0.1/swashbuckle.aspnetcore.swaggerui.4.0.1.nupkg
           OK https://api.nuget.org/v3-flatcontainer/automapper/index.json 155ms
           GET https://api.nuget.org/v3-flatcontainer/automapper/8.0.0/automapper.8.0.0.nupkg
           OK https://api.nuget.org/v3-flatcontainer/swashbuckle.aspnetcore.swaggergen/4.0.1/swashbuckle.aspnetcore.swaggergen.4.0.1.nupkg 44ms
           OK https://api.nuget.org/v3-flatcontainer/swashbuckle.aspnetcore.swaggerui/4.0.1/swashbuckle.aspnetcore.swaggerui.4.0.1.nupkg 49ms
           GET https://api.nuget.org/v3-flatcontainer/microsoft.aspnetcore.mvc.apiexplorer/index.json
           GET https://api.nuget.org/v3-flatcontainer/microsoft.aspnetcore.mvc.core/index.json
           GET https://api.nuget.org/v3-flatcontainer/microsoft.aspnetcore.mvc.dataannotations/index.json
         NuGet.Protocol.Core.Types.FatalProtocolException: An error occurred while retrieving package metadata for 'System.Text.Encodings.Web.4.5.0' from source '/usr/share/dotnet/sdk/NuGetFallbackFolder'. ---> NuGet.Packaging.Core.PackagingException: An error occurred while retrieving package metadata for 'System.Text.Encodings.Web.4.5.0' from source '/usr/share/dotnet/sdk/NuGetFallbackFolder'. ---> System.Xml.XmlException: Root element is missing.
            at System.Xml.XmlTextReaderImpl.Throw(Exception e)
            at System.Xml.XmlTextReaderImpl.ParseDocumentContent()
            at System.Xml.XmlTextReaderImpl.Read()
            at System.Xml.Linq.XDocument.Load(XmlReader reader, LoadOptions options)
            at NuGet.Packaging.Core.NuspecCoreReaderBase.LoadXml(Stream stream, Boolean leaveStreamOpen)
            at NuGet.Packaging.Core.NuspecCoreReaderBase..ctor(Stream stream, Boolean leaveStreamOpen)
            at NuGet.Packaging.NuspecReader..ctor(Stream stream)
            at NuGet.Protocol.LocalPackageFileCache.GetNuspec(String manifestPath, String expandedPath)
            at NuGet.Protocol.LocalPackageFileCache.<>c__DisplayClass6_1.<GetOrAddNuspec>b__1()
            at System.Lazy`1.ViaFactory(LazyThreadSafetyMode mode)
            at System.Lazy`1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor)
            at System.Lazy`1.CreateValue()
            at NuGet.Protocol.LocalV3FindPackageByIdResource.ProcessNuspecReader[T](String id, NuGetVersion version, Func`2 process)
            --- End of inner exception stack trace ---
            --- End of inner exception stack trace ---
            at NuGet.Protocol.LocalV3FindPackageByIdResource.ProcessNuspecReader[T](String id, NuGetVersion version, Func`2 process)
            at NuGet.Protocol.LocalV3FindPackageByIdResource.GetDependencyInfoAsync(String id, NuGetVersion version, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
            at NuGet.Commands.SourceRepositoryDependencyProvider.GetDependenciesCoreAsync(LibraryIdentity match, NuGetFramework targetFramework, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
            at NuGet.Commands.SourceRepositoryDependencyProvider.<>c__DisplayClass21_0.<<GetDependenciesAsync>b__0>d.MoveNext()
         --- End of stack trace from previous location where exception was thrown ---
            at NuGet.Commands.SourceRepositoryDependencyProvider.GetDependenciesAsync(LibraryIdentity libraryIdentity, NuGetFramework targetFramework, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
            at NuGet.DependencyResolver.ResolverUtility.CreateGraphItemAsync(RemoteMatch match, NuGetFramework framework, SourceCacheContext cacheContext, ILogger logger, CancellationToken cancellationToken)
            at NuGet.DependencyResolver.ResolverUtility.FindLibraryEntryAsync(LibraryRange libraryRange, NuGetFramework framework, String runtimeIdentifier, RemoteWalkContext context, CancellationToken cancellationToken)
            at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge)
            at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge)
            at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge)
            at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge)
            at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge)
            at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge)
            at NuGet.DependencyResolver.RemoteDependencyWalker.CreateGraphNode(LibraryRange libraryRange, NuGetFramework framework, String runtimeName, RuntimeGraph runtimeGraph, Func`2 predicate, GraphEdge`1 outerEdge)
            at NuGet.Commands.ProjectRestoreCommand.WalkDependenciesAsync(LibraryRange projectRange, NuGetFramework framework, String runtimeIdentifier, RuntimeGraph runtimeGraph, RemoteDependencyWalker walker, RemoteWalkContext context, CancellationToken token)
            at NuGet.Commands.ProjectRestoreCommand.TryRestoreAsync(LibraryRange projectRange, IEnumerable`1 frameworkRuntimePairs, NuGetv3LocalRepository userPackageFolder, IReadOnlyList`1 fallbackPackageFolders, RemoteDependencyWalker remoteWalker, RemoteWalkContext context, Boolean forceRuntimeGraphCreation, CancellationToken token, TelemetryActivity telemetryActivity)
            at NuGet.Commands.RestoreCommand.ExecuteRestoreAsync(NuGetv3LocalRepository userPackageFolder, IReadOnlyList`1 fallbackPackageFolders, RemoteWalkContext context, CancellationToken token, TelemetryActivity telemetryActivity)
            at NuGet.Commands.RestoreCommand.ExecuteAsync(CancellationToken token)
            at NuGet.Commands.RestoreRunner.ExecuteAsync(RestoreSummaryRequest summaryRequest, CancellationToken token)
            at NuGet.Commands.RestoreRunner.ExecuteAndCommitAsync(RestoreSummaryRequest summaryRequest, CancellationToken token)
            at NuGet.Commands.RestoreRunner.CompleteTaskAsync(List`1 restoreTasks)
            at NuGet.Commands.RestoreRunner.RunAsync(IEnumerable`1 restoreRequests, RestoreArgs restoreContext, CancellationToken token)
            at NuGet.Commands.RestoreRunner.RunAsync(RestoreArgs restoreContext, CancellationToken token)
            at NuGet.Build.Tasks.RestoreTask.ExecuteAsync(ILogger log)
       Done executing task "RestoreTask" -- FAILED.
     1>Done building target "Restore" in project "MStoreBOSGatewayApi.csproj" -- FAILED.
     1>Done Building Project "/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj" (Restore target(s)) -- FAILED.

Build FAILED.

       "/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj" (Restore target) (1) ->
       (Restore target) ->
         /usr/share/dotnet/sdk/2.2.402/NuGet.targets(123,5): error : An error occurred while retrieving package metadata for 'System.Text.Encodings.Web.4.5.0' from source '/usr/share/dotnet/sdk/NuGetFallbackFolder'. [/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj]
       /usr/share/dotnet/sdk/2.2.402/NuGet.targets(123,5): error :   Root element is missing. [/src/MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj]

    0 Warning(s)
    1 Error(s)

Time Elapsed 00:00:04.70
The command '/bin/sh -c dotnet restore "MStoreBOSGateway/MStoreBOSGatewayApi/MStoreBOSGatewayApi.csproj" --verbosity detailed' returned a non-zero code: 1

C:\Applications\VB2017Apps\MStoreBOSGateway>


Q: Find "complete cases" with awk Using awk, how can I output the lines of a file that have all fields non-null without manually specifying each column?
foo.dat
A||B|X
A|A|1|
|1|2|W
A|A|A|B

Should return:
A|A|A|B

In this case we can do:
awk -F"|" -v OFS="|" '$1 != "" && $2 != "" && $3 != "" && $4 != "" { print }' foo.dat

But is there a way to do this without specifying each column?

A: You can loop over all fields and skip the record if any of the fields are empty:
$ awk -F'|' '{ for (i=1; i<=NF; ++i) { if (!$i) next } }1' foo.dat
A|A|A|B

if (!$i) is "if field i is not non-empty", and 1 is short for "print the line", but it is only hit if next was not executed for any of the fields of the current line.

A: Another in awk:
$ awk -F\| 'gsub(/[^|]+(\||$)/,"&")==NF' file
A|A|A|B

print record if there are NF times | terminating (non-empty, |-excluding) strings.

A: awk '!/\|\|/&&!/\|$/&&!/^\|/' file

A|A|A|B


Q: Prevent Popup template to shows multiple feature in ArcGIS 4.16 Angular 10 I have integrated a popup on the map for a specific layer. Some time the poup shows pagination (featureNavigation) multiple data. Sometimes it fails to show the data, or mismatch in the data that actually the service returns.
    var popupTrailheads = {
            title: "ID: {ID}",
            content: this.getcustomcontent.bind(this),
          };
          // Add layer special layer
          this.layer_fifteen = new FeatureLayer({
            url: `${this.esriURL}/15`,
            visible: true,
            outFields: ['*'],
            popupTemplate: popupTrailheads,
          });

     getcustomcontent(feature) {
    // The popup content will become here from angular service
return `<div>content</div>`;
    }

I have a few options to fix the issue.
1)Popup for this layer enables only at a specific Zoom level. Else the popup won't appear.
2)The click on the map should trigger only for a point. (I believe when click on the layer it triggers multiple points that is the reason it shows multiple feature details.)
Can you please suggest an idea, how to enable a popup in specific zoom level, or select only one feature in one click on the map.
Thanks in advance.

A: So, there are a number of possible ways to enable the popup under certain conditions, like the zoom level of the view.
In the example that I made for you popup only opens if zoom is greatest than 10.

<!DOCTYPE html>

  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no" />
  <title>PopupTemplate - Auto Open False</title>

  <link rel="stylesheet" href="https://js.arcgis.com/4.15/esri/themes/light/main.css" />

Related to only display one result in the popup, you could hide the navigation like this,
view.popup.visibleElements.featureNavigation = false;
Now if what you actually want is to get only one result, then I suggest to use view method hitTest, that only gets the topmost result of the layers. You could do this after inside the click handler and only open if any result of desire layer. For this you need to set featFeatures: false, and set the features with the hit one.
Just as a comment it could result weird or confusing to the user retrieve just one of all possible features. I think probable you may have a problem with the content.


Q: Ambiguous use of a subscript when accessing a 2-dimensional array bridged from Obj-C This code which ran perfectly in Xcode 7.0 now complains with a error : Ambiguous use of a subscript in Xcode 7.3.1 on the second line.
    let ar = sender.draggingPasteboard().propertyListForType("ABLinkedPeopleUIDsPboardType") as! NSArray?

    let uniqueID = ar![0][0] as! String

I understand that the NSArray on its own is now considered bad practice, but what do I need to do to get this to compile and run?

A: NSArray is a single-dimensioned array, but you're trying to use it as a two-dimensional array. I can't see how this would ever compile.
You need to translate into Swift types immediately so you can continue programming in Swift, not go adrift in a sea of force-unwrapped Optionals.
How about:
if let ar = sender.draggingPasteboard().propertyListForType("ABLinkedPeopleUIDsPboardType") as? [[String]] {
    // I'm assuming you're expecting to get back a two-dimensional array of Strings, or in the Obj-C realm, an NSArray of NSArrays of NSStrings
    let uniqueID = ar[0][0]
}
else {
    print("Property List for ABLinkedetc. is not a 2D String Array!")
}

Hayden's link is the correct general discussion but if you're new to bridging Obj C to Swift it may be difficult to apply in your particular case.


Q: PHP ECHO VARIABLE I managed to create a new line for each only with :
$content1= hot("britney") ? "britney found" : "";
$content2= hot("gaga") ? "gaga found" : "";
$content3= hot("carol") ? "carol found" : "";

$filename = 'result.txt';
$handle = fopen($filename, 'a');
fwrite($handle, "$Content1\r\n");
fwrite($handle, "$Content2\r\n");
fwrite($handle, "$Content3\r\n");
fwrite($handle, "$Content4\r\n");
fclose($handle);

But i have many lines and it makes a lot of modifications...
How could i automatize the process ?
maybe something like foreach setRequestHeader("Cookie","Cookie: host");
 $ajax->open("GET",$url,true);
 $ajax->send(null);
 if($ajax->status==200){
  $rHeader=$ajax->getResponseHeader("Set-Cookie");
  if(substr_count($rHeader, "Present!")>0) { return true; }
 }else{ return false; }
}

echo ( hot("britney") )?"britney found":"
";
echo ( hot("gaga") )?"gaga found":"
";
echo ( hot("carol") )?"carol found":"
";

AND
<?php
$filename = 'test.txt';
$Content = "Add this to the file\r\n";

echo "open";
$handle = fopen($filename, 'x+');
echo " write";
fwrite($handle, $Content);
echo " close";
fclose($handle);
?>

and i have many echo ( hot("britney") )?"britney found":"
"; in my script and because of that i want to send them to a file
how can i set a string for echo ( hot("britney") )?"britney found":"
";to be able to use it in my code that sends the info to file
i also don't want the page to print anything to the screen

A: $Content = hot("britney") ? "britney found" : "
";

A: Just store stuff in a variable then write variable.
// put stuff in $content instead of printing
$content = '';
$content .= hot("britney") ? "britney found" : "
";
$content .= hot("gaga") ? "gaga found" : "
";
$content .= hot("carol") ? "carol found" : "
";

// write to file
$handle = fopen($filename, 'x+');
fwrite($handle, $content);
fclose($handle);

A: As others have already stated, put the contents of your echos into a variable then write that into a file. There are two ways to do this. You can use file handlers:
<?php
// "w" will create the file if it does not exist and overwrite if it does
// "a" will create the file if it does not exist and append to the end if it does
$file = fopen('/path/to/file', 'w');
fwrite($file, $content);
fclose($file);

A slightly simpler way is to use file_put_contents():
<?php
file_put_contents('/path/to/file', $contents);

And if you want to append to the file:
<?php
file_put_contents('/path/to/file', $contents, FILE_APPEND);

As for the parenthesis you have around the conditional for your echos, I prefer something more like the following:
<?php
$contents = '';
$contents .= (hot('britney') ? 'britney found' : '
');

If you want to be able to easily read the file outside of a web browser, you should use a new line instead of a
 to separate your output. For example:
<?php
$contents = '';
$contents .= (hot('britney') ? 'britney found'."\n" : "\n");

A: Replace all of the echo statements with a variable, then write that variable to a file.
$Content.= ( hot("britney") )?"britney found":"
";

etc...

A: First off, your parentheses are in the wrong place. Should be like this:
echo ( hot("britney") ? "britney found" : "" );
If you want to capture your echo and other output, use the ob_start and ob_flush methods.
But if you're making HTTP requests to that file it won't echo on the screen.
If that's what you meant, then that's your answer.


Q: perl6 Is using junctions in matching possible? Is it possible to use junction to match any of the values in a junction? I want to match any of the values in an array. What is the proper way to do it?
lisprog$ perl6
To exit type 'exit' or '^D'
> my @a=<a b c>
[a b c]
> any(@a)
any(a, b, c)
> my $x=any(@a)
any(a, b, c)
> my $y = "a 1"
a 1
> say $y ~~ m/ $x /
False
> say $y ~~ m/ "$x" /
False
> my $x = any(@a).Str
any("a", "b", "c")
> say $y ~~ m/ $x /
False
> say $y ~~ m/ || $x /
False
> say $y ~~ m/ || @a /
｢a｣
>

Thanks !!

A: Junctions are not meant to be interpolated into regexes. They're meant to be used in normal Perl 6 expressions, particularly with comparison operators (such as eq):
my @a = <x y z>;
say    "y" eq any(@a);  # any(False, True, False)
say so "y" eq any(@a);  # True

To match any of the values of an array in a regex, simply write the name of the array variable (starting with @) in the regex. By default, this is interpreted as an | alternation ("longest match"), but you can also specify it to be a || alternation ("first match"):
my @a = <foo bar barkeep>;
say "barkeeper" ~~ / @a /;     # ｢barkeep｣
say "barkeeper" ~~ / || @a /;  # ｢bar｣


Q: Rename the newly created sheet based on active cell in Sheet1 I am newbie at VBA and have a problem to solve, which for you will be more than simple, I am sure. Here is the problem:
I have table with company names in column A. What I want is to select cell with company name, click the button which will run a macro creating new sheet based on template, and rename the newly created sheet with name of the selected cell in Sheet1 (company name).
The macro generally works, I have only problem with renaming it. Your help will be greatly appriciated. Also any comments on my code in general will be very useful. Here is the code:
Sub NewSheet()

Dim wb As Workbook
Dim ws As Worksheet
Dim activeWB As Workbook
Dim FilePath As String

Application.ScreenUpdating = False
Application.DisplayAlerts = False

On Error Resume Next
Set wb = Application.Workbooks.Open(FilePath)
wb.Worksheets(1).Copy After:=activeWB.Sheets(activeWB.Sheets.Count)
activeWB.Activate

ActiveSheet.Name = Worksheets("Arkusz1").ActiveCell.Value

wb.Close False

Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

A: If you need to use the ActiveCell, you can use something like the code below:
Dim ShtName As String
ShtName = ActiveCell.Value2 ' <-- save the value of the ActiveCell

Set wb = Application.Workbooks.Open(FilePath)
wb.Worksheets(1).Copy After:=activeWB.Sheets(activeWB.Sheets.Count)

' rename the sheet
activeWB.Sheets(activeWB.Sheets.Count).Name = ShtName

A: You've copied the new worksheet to the end, so you can get hold of the last worksheet like so:
Set activeWB = ActiveWorkbook
' You copied sheet 1
wb.Worksheets(1).Copy After:=activeWB.Sheets(activeWB.Sheets.Count)
' New sheet is last sheet
Dim sh As WorkSheet
Set sh = activeWB.Sheets(activeWB.Sheets.Count)
' Rename sheet
sh.Name = activeWB.Sheets("Arkusz1").ActiveCell.Value

Please note, relying on selections and active cells/sheets/workbooks is risky, and can create hard-to-diagnose errors. Try and use cell addresses instead of active cells.


Q: Change value in private member in JFrame with reflection Hello,
I have the following code, what I want is to modify the value of the instance called number to any value
I have both classes in the same package
ReflectionOnClass.class
import javax.swing.*;
import java.awt.*;

public class ReflectionOnClass extends JFrame {

private int number = 2;
private JLabel jLabel = new JLabel("X: " + number);

public ReflectionOnClass() {
    setLayout(new FlowLayout());
    setPreferredSize(new Dimension(200,200));
    add(jLabel);
    setDefaultCloseOperation(3);
    setLocationRelativeTo(null);
    pack();
    setVisible(true);
    }
}

ExecReflection.class
import java.lang.reflect.Field;
import java.util.stream.Stream;

public class ExecReflection {

private static final String C = "ReflectionOnClass";

public ExecReflection() {

    try {
        final Field field = Class.forName(C).getDeclaredField("number");
        field.setAccessible(true);
        final ReflectionOnClass rF = new ReflectionOnClass();
        field.set(rF , 100);
        mostrar("Value number: " + field.get(rF));
    }catch (Exception ex){
        ex.printStackTrace();
    }
 }

 public <T> void mostrar(final T t){System.out.println(t);}
 public static void main(String ...gaga) {
    final Runnable r = ExecReflection::new;
    r.run();
 }
}

the output is the correct as in the image but in the JFrame there is no

there is no possibility to change the value of said variable before the JFrame starts?
Update this was what I wanted, to modify the value before the JFrame started, but with reflection
final Field field = Class.forName(C).getDeclaredField("jLabel");
field.setAccessible(true);
if(field.getType() == JLabel.class) {
  final JLabel j = (JLabel)field.get(ReflectionOnClass.class.newInstance());
  j.setText("X: " + 5000);
}

A: Its possible.
You can add this functions to ReflectionOnClass:
public void setNumber(int num){
    this.number = num;
    label.setText("X: " + this.number);
}

public int getNumber(){
    return this.number;
}

and just call them from ExecReflection:
final ReflectionOnClass rF = new ReflectionOnClass();
rF.setNumber(4);
System.out.println("Value number: " + rF.getNumber());

A: Nothing is changing because you are not actually changing value that is displayed
private int number = 2;
private JLabel jLabel = new JLabel("X: " + number);

You need to access jLabel field, as this is your displayed value, and change text to something else, if number is used in other places, then you probably need to change both of them, so number to this example 100 value, and jLabel text to X: 100


Q: How to make a Twitter-like following system How can i make a Twitter-like following system where, if you follow someone, you will receive their tweets. I have a database table called "users", "followings", and "posts". The users table holds the users that are on my site. The followings shows the persons followers, this table is setup like this :'id, user_one, user_two'. And the posts table holds all the tweets or posts that the unique user has.
I have a profile page set up for each user, with a follow button. And also I have a news feed for the user, but in that news feed I need it to show posts from users that the logged-in user is following. So is there anyway for me to have a user follow someone and receive the posts from that user on their news feed.
Now I did some research: their system wouldn't seem to work. I kept getting this error:

Warning: implode() [function.implode]: Invalid arguments passed in function.php on line 12

SELECT
  user_id,
  body,
  stamp
FROM posts
WHERE user_id in ()
ORDER BY stamp DESC

Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in function.php.

This line right here was suppose to help make it where when you follow that person you will receive there tweets and stuff
function show_posts($userid,$limit=0){
$posts = array();

$user_string = implode(',', $userid);
$extra =  " and id in ($user_string)";

if ($limit > 0){
    $extra = "limit $limit";
}else{
    $extra = '';
}

$sql = "select user_id,body, stamp from posts
    where user_id in ($user_string)
    order by stamp desc $extra";
echo $sql;
$result = mysql_query($sql);

while($data = mysql_fetch_object($result)){
    $posts[] = array(   'stamp' => $data->stamp,
                        'userid' => $data->user_id,
                        'body' => $data->body
                );
}
return $posts;

}
I believe this piece of code, which is supposed to show posts from other users, is causing this problem but I don't know why.

A: Use a join. For example:
select user_id, text from posts
    inner join followings on posts.user_id = followings.followed_id
    where followings.follower_id = :user_id;

If I may recommend, stop using the mysql_ functions; they are deprecated and should not be used in newer applications. Instead, I'd recommend using PDO.


Q: Changing JSON return object names I have this function for returning users and user count
List<User> entitiesList = DB.Users.OrderBy(x => x.UserName).ToList();
var count = DB.Users.Count
return (entitiesList, count)

The result from HTTP request is this
{
    "item1":
[
    {
        "fullName":"Joe Smith"
    },
    {"fullName":"Bob Rogan"
    }
]
    "item2":["2"]
}

Question is why does JSON result has objects named item1 and item2, where does these names come from, I haven't specified such names anywhere, shouldn't there just be no name in such case? And how do I rename 'item1' to 'users' and 'item2' to 'count'?

A: It's because you return a tuple, in your case (Class User, integer). You should return a custom class:
public class Response {
    public List<User> Users;
    public int Count;
}

....
return (new Response { Users = entitiesList, Count = count});


Q: Does javascript loaded via .load run even after it's "deleted"? I don't know any better way of asking this, or search for it, so here it goes:
I have a webpage that's basically a menu and a big white DIV in the center. All the subpages are loaded inside that div via .load. This is all fine, but:

I want to know if scripts loaded with the page are still going to run after the div's content is changed to another sub-page. To get what I mean, please visit http://carnbox.zapto.org (testing VPS) and log in using the credentials tomi : tomi .
Once logged in, go ahead and click on "My Services". All these scripts are inlined in the PHP pages that display the content. I found their lenght to be too small to make them external, and I wished to only load the scripts when viewing the page so the initial loading time of the website is smaller.

After clicking on another page, which will replace the contents of the white space with another page, will the setintervals from the previous page still be running? Will the scripts still be loaded in the user's browser or will they also be wiped?
Or more importantly, will swithing between the pages multiple times cause any trouble for the users?
Is this error related to the way I'm loading scripts, and should I switch to external files and jquery.getscript() ?
Synchronous XMLHttpRequest on the main thread is deprecated because of
its detrimental effects to the end user's experience. For more help,
check http://xhr.spec.whatwg.org/

A: Yes, JavaScript code loaded by .load continues running even if the elements it was loaded with are removed from the DOM. Removing a script tag has no effect whatsoever on the code that the script loaded.
Here's a live example doing the same thing with html (load ends up calling html under the covers):

var content = [
  // foo
  "This loads a script saying 'foo' once a second " +
  "for 100 seconds." +
  "


Q: Graphql-Client ruby OpenSSL::SSL::SSLError I am trying to test if I can connect to a graphql API from a rails backend by using graphql-client with the following code:
require "graphql/client"
require "graphql/client/http"

HTTP = GraphQL::Client::HTTP.new("https://x.x.x.x:3100/graphql")

Schema = GraphQL::Client.load_schema(HTTP)

Client = GraphQL::Client.new(schema: Schema, execute: HTTP)

but I get the following error:
    9: from db/seeds.rb:14:in `<main>'
    8: from /Library/Ruby/Gems/2.6.0/gems/graphql-client-0.16.0/lib/graphql/client.rb:61:in `load_schema'
    7: from /Library/Ruby/Gems/2.6.0/gems/graphql-client-0.16.0/lib/graphql/client.rb:77:in `dump_schema'
    6: from /Library/Ruby/Gems/2.6.0/gems/graphql-client-0.16.0/lib/graphql/client/http.rb:73:in `execute'
    5: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/net/http.rb:1470:in `request'
    4: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/net/http.rb:919:in `start'
    3: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/net/http.rb:930:in `do_start'
    2: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/net/http.rb:996:in `connect'
    1: from /System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/net/protocol.rb:44:in `ssl_socket_connect'
/System/Library/Frameworks/Ruby.framework/Versions/2.6/usr/lib/ruby/2.6.0/net/protocol.rb:44:in `connect_nonblock': SSL_connect returned=1 errno=0 state=SSLv3 read server hello A: wrong version number (OpenSSL::SSL::SSLError)

SSL_connect returned=1 errno=0 state=SSLv3 read server hello A: wrong version number (OpenSSL::SSL::SSLError)
I have no idea how to get that solved as when I look that error up it is always in different situation than mine.


Q: android AVD (Emulator) exit I cannot open the emulator, each time I Press launch avd. the emulato exit immidately before launching.
and it seems like there is no integration ? or something wrong as I have the below error: emulator unknow.
even though I have an emulator.
I don't even know what sort of issues is this!
as it exits without any error message.
Edit:
I solved the issue by simply reinstalling Intel HAXM

A: When this type of problem happens, best way is to make sure you have followed below points correctly.

*

*You have proper SDK installed

*You have Intel HAXM & virtualization option enabled in your BIOS

*Configure emulator correctly, download the Intel X86 Atom system image for better performance.

*Disable and then Enable ADB Integration

*User arm instead of x86 if you have AMD processor when creating emulator.(In most of case)


Q: Creating index by concatinating multiple columns MySQL I am new to mySQL and trying to migrate to MySQL from oracle and I have an index that I need to convert to mySQL. In oracle I have created this index by using 2 columns as :
CREATE INDEX TEST ON TABLE(COL1||'/'||COL2, COL3)

Now I am trying to find alternate for this in mySQL. I know that I can create index on multiple columns in my sql like :
CREATE INDEX TEST on TABLE(COL1, COL2)

But I want to create index on multiple columns such that I can combine COL1 and COL2 using '/' delimiter and create index on it. I Found that I can create a generated column and create index on it. So basically I will have something like this :
 CREATE INDEX TEST on TABLE(GENERATED_COL, COL2)

when I try to create this generated column I keep getting syntax error for generated column. Here is my syntax to create table :
CREATE TABLE PATH (
ID INT(38) NOT NULL,
PATH_PREFIX VARCHAR(2000) NOT NULL,
PATH_SUFFIX VARCHAR(255) NOT NULL,
FULLPATH VARCHAR(3000) AS (CONCAT(PATH_PREFIX,'/',PATH_SUFFIX)),
PRIMARY KEY (ID)
)

Here is my error :
SQL Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AS (CONCAT(PATH_PREFIX,'/',PATH_SUFFIX)),
PRIMARY KEY (ID)

Not sure if I am doing something wrong here? If this is not right way can someone please advise me on what is the right way of creating index like CONCAT(PATH_PREFIX,'/',PATH_SUFFIX)

A: From mysql v5.7.6 you can create generated columns. If you set its type to stored, then you can create secondary indexes on it. From v5.7.8 you can even create indexes on virtual generated columns, see mysql's documentation on create table:

As of MySQL 5.7.8, InnoDB supports secondary indexes on virtual
  generated columns. Other index types are not supported.
A secondary index may be created on one or more virtual columns or on
  a combination of virtual columns and non-virtual generated columns.
  Secondary indexes on virtual columns may be defined as UNIQUE.


Q: How to auto-backup Access Database I want to autoback up my access database with the below code and it didn't work for me. I got an error "cannot find the input table or query "WinAutoBackup" Please view the picture. Also, did I use CurrentProject correctly?
[Function fMakeBackup() As Boolean

Dim Source As String
Dim Target As String
Dim retval As Integer

On Error GoTo sysBackup_Err

Source = CurrentDb.name

Target = "CurrentProject.path\backups\"
Target = Target & Format(Now, "yyyymmdd-hhnn") & ".accdb"

If DateDiff("d", DLookup("\[BackupDate\]", "WinAutoBackup", "\[BckID\]
=1"), Date) = 3 Then

retval = 0
Dim objFSO As Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
retval = objFSO.CopyFile(Source, Target, True)
Set objFSO = Nothing

DoCmd.SetWarnings False
   DoCmd.RunSQL "UPDATE WinAutoBackup SET WinAutoBackup.BackupDate =
Date();"
DoCmd.SetWarnings True

MsgBox "Backup successfull. Next auto backup in 3 days"

Else
Exit Function
End If

sysBackup_Exit:
Exit Function

sysBackup_Err:
MsgBox Err.Description, , "sysBackup()"
Resume sysBackup_Exit
End Function][1]

A: Start with including:
Option Explicit

at the top of the module.
Then try with:
Function fMakeBackup() As Boolean

    Dim objFSO As Object

    Dim Source As String
    Dim Target As String
    Dim retval As Integer

    ' Disable error handling during development.
    ' On Error GoTo sysBackup_Err

    Source = CurrentDb.Name

    ' Adjust if if backup folder is not \backups\.
    Target = CurrentProject.Path & "\backups\"
    Target = Target & Format(Now, "yyyymmdd-hhnn") & ".accdb"

    ' To run every time, use this line in plade of If DateDiff ...:
    ' If True Then
    If DateDiff("d", DLookup("[BackupDate]", "[WinAutoBackup]", "[BckID] = 1"), Date) >= 3 Then

        Set objFSO = CreateObject("Scripting.FileSystemObject")
        retval = objFSO.CopyFile(Source, Target, True)
        Set objFSO = Nothing

        DoCmd.SetWarnings False
            DoCmd.RunSQL "UPDATE WinAutoBackup SET WinAutoBackup.BackupDate = Date() WHERE [BckID] = 1;"
        DoCmd.SetWarnings True

        MsgBox "Backup successful. Next auto backup in 3 days."
    End If

sysBackup_Exit:
    Exit Function

sysBackup_Err:
    MsgBox Err.Description, , "sysBackup()"
    Resume sysBackup_Exit

End Function


Q: GridView button with condition I have a gridview with 3 columns Name,Surname,Change(ButtonField column) which is populated from an SqlDataReader with the following code
               SqlCommand sqlCommand = new SqlCommand("select * from Empl where userId ='" + userid + "'", sqlConnection);
            sqlConnection.Open();

            SqlDataReader reader = sqlCommand.ExecuteReader();

            GridView1.DataSource = reader;
            GridView1.DataBind();

In my database there are 4 columns UserId,Name,Surname,Change(bit). How can i show the button change only when Change(bit) column is true inside the database?

A: You can do like..
<asp:TemplateField>
      <ItemTemplate>
         <asp:Button ID="btnChange" runat="server" Text="Change"
              Visible='<%# (Boolean) Eval("Change") %>' />
      </ItemTemplate>
 </asp:TemplateField>

As you mentioned in the comment you are getting error on the above code, you try like...
Visible='<%# Convert.ToBoolean(Eval("Change")) == true ? true : false %>'


Q: how to make inserted items sortable

$('.parent').sortable({
 containment: "parent",
 tolerance: "pointer",
 axis: "x"
 });

 $('button').on('click', function(){
 var str = $('#store').html();
 $(str).insertBefore($('.parent').eq(0));
 });
.parent{
background:silver;
margin:9px 0;
}
.title{
background:gold;
display:inline-block;
width:25%;
cursor:cell;
}

lorem

ipsum

<button>CLICK</button>

How to make inserted items sortable?
I tried all solutions here and here and ...
Nothing works.

A: When adding items, you need to run refresh:

Refresh the sortable items. Triggers the reloading of all sortable items, causing new items to be recognized.

In regards to placement, you appear to selecting more than you need. I suspect you just need to insert more items to the same list. Consider the following:

$(function() {
  $('.parent').sortable({
    containment: "parent",
    tolerance: "pointer",
    axis: "x"
  });

  $('button').on('click', function() {
    var str = $('#store .parent').html();
    $(str).insertBefore($('.parent div:eq(0)'));
    $('.parent').sortable("refresh");
  });
});
.parent {
  background: silver;
  margin: 9px 0;
}

.title {
  background: gold;
  display: inline-block;
  width: auto;
  cursor: cell;
}

lorem

ipsum

<button>CLICK</button>

If you need a new list, then you need to add it and re-assign sortable to the new item.

$(function() {
  $('.parent').sortable({
    containment: "parent",
    tolerance: "pointer",
    axis: "x"
  });

  $('button').on('click', function() {
    var str = $('#store .parent:last').prop("outerHTML");
    $(str).insertBefore($('.parent:eq(0)'));
    $("#store .parent").sortable({
      containment: "parent",
      tolerance: "pointer",
      axis: "x"
    });
  });
});
.parent {
  background: silver;
  margin: 9px 0;
}

.title {
  background: gold;
  display: inline-block;
  width: 25%;
  cursor: cell;
}

lorem

ipsum

<button>CLICK</button>

Hope that helps.


Q: How do I align elements vertically in Vuetify? I have these social media buttons in the top left corner:

And here is the code:
<v-row v-for="(button, index) in socialMediaButtons" :key="index">
  <v-col>
    <v-btn fixed fab class="mt-5 ml-1"><v-icon>{{ button.logo }}</v-icon></v-btn>
  </v-col>
</v-row>

As you can see, the buttons are overlapping each other. How can I achieve that they have space between them vertically?

A: This is because you have fixed props, which makes v-col thinks there is nothing inside the column. So the height of the button is not calculated, which makes the buttons overlap.
Try something like this (example)
<v-row>
  <v-col sm="12">
    <v-btn fab dark small color="primary">
      <v-icon dark>mdi-minus</v-icon>
    </v-btn>
  </v-col>
  <v-col sm="12">
    <v-btn fab dark small color="pink">
      <v-icon dark>mdi-heart</v-icon>
    </v-btn>
  </v-col>
</v-row>;

Your code
<v-row v-for="(button, index) in socialMediaButtons" :key="index">
  <v-col sm="12>
    <v-btn fab class="mt-5 ml-1"><v-icon>{{ button.logo }}</v-icon></v-btn>
  </v-col>
</v-row>


Q: Javascript won't work when passed in jquery AJAX / jquery call in loaded DIV I know this question has sort of been asked, but it's been asked for other issues not related to how my code is set up, and I believe it's unrelated to how this works. I can't for the life of me figure how to fix this.
I have two PHP pages set up. index.php and getresult.php. index is paginated using AJAX. The AJAX calls to getresult.php for the data. I have a script to load youtube videos(lazy load JS, not your typical embed). My problem is that the page will load via AJAX, but the javascript for my youtube embeds isn't working. They appear as black boxes. The html, video titles, etc all come through, but the JS just won't work on the div now. Here's the div used on getresult.php (

 ) where class="youtube-player" is supposed to activate the JS, but the JS isn't triggered by it. Here is the JS for the youtube player if it matters. The Youtube lazy load JS was working without pagination/ajax(if I were to keep everything on the same page), but with pagination and ajax, it won't.
On index.php I have the following:
function getresult(url) {
    $.ajax({
        url: url,
        type: "GET",
        data: {
            rowcount: $("#rowcount").val(),
            "pagination_setting": $("#pagination-setting").val()
        },
        beforeSend: function () {
            $("#overlay").show();
        },
        success: function (data) {
            $("#pagination-result").html(data);
            setInterval(function () {
                $("#overlay").hide();
            }, 500);

        },
        error: function () {}
    });
}

function changePagination(option) {
    if (option != "") {
        getresult("pagination/getresult.php");
    }
}

I'll keep a close eye on this. I've spent literally hours trying to figure it out and I can't figure it out. Thanks!
Edit: Some magical wizard stopped by and helped me. Solution in the comments.

A: In your JS file, you ara attaching DomContentLoaded event to your code that activates youtube player. So, when your first get result is fired, it shall work fine as DOM is loaded and JS activates. But, in subsequent get calls your dom is not getting loaded, it’s changing.
I believe, you need to call the code which is activating youtube player everytime AJAX call succeeds.
What tou can do is attach your JS code to a custom event and then trigger this even everytime AJAX call succeeds.
In JS:
You can follow this link to see how an event can be created and triggered in JS
How to trigger event in JavaScript?

A: Try re-initializing the function for the youtube embeds as shown below:

function getresult(url) {
    $.ajax({
        url: url,
        type: "GET",
        data: {
            rowcount: $("#rowcount").val(),
            "pagination_setting": $("#pagination-setting").val()
        },
        beforeSend: function () {
            $("#overlay").show();
        },
        success: function (data) {
            $("#pagination-result").html(data);

            var div, n,
                v = document.getElementsByClassName("youtube-player");
            for (n = 0; n < v.length; n++) {
                div = document.createElement("div");
                div.setAttribute("data-id", v[n].dataset.id);
                div.innerHTML = labnolThumb(v[n].dataset.id);
                div.onclick = labnolIframe;
                v[n].appendChild(div);
            }

            setInterval(function () {
                $("#overlay").hide();
            }, 500);

        },
        error: function () {}
    });
}

function changePagination(option) {
    if (option != "") {
        getresult("pagination/getresult.php");
    }
}

function labnolThumb(id) {
  var thumb = '',
  play = '

';
  return thumb.replace("ID", id) + play;
}

function labnolIframe() {
  var iframe = document.createElement("iframe");
  var embed = "https://www.youtube.com/embed/ID?autoplay=1";
  iframe.setAttribute("src", embed.replace("ID", this.dataset.id));
  iframe.setAttribute("frameborder", "0");
  iframe.setAttribute("allowfullscreen", "1");
  this.parentNode.replaceChild(iframe, this);
}


Q: Multiple select statements in single query while using 'group by' and 'join' I have three tables -
podcasts, videos and others.
Each of the entities under these are associated with a category and subcategories.
Example for podcasts -

This category_id and subcategory_id have their name values in their respective tables -

Now, I want to get the count of podcasts, videos and text under each category & subcategory combination. My individual SQL query are these -
For podcasts -
SELECT c.category_name, sc.sub_category_name, count(p.*) AS podcast_count
FROM podcasts p
JOIN categories c ON c.category_id = p.podcast_category_id
JOIN sub_categories sc ON sc.sub_category_id = p.podcast_subcategory_id
WHERE p.podcast_owner = 14 AND p.podcast_upload_time_stamp >= timestamp '2020-10-22 00:00:00'
GROUP BY 1, 2

For others -
SELECT c.category_name, sc.sub_category_name, count(o.*) AS other_count
FROM otherlinks o
JOIN categories c ON c.category_id = o.other_link_category_id
JOIN sub_categories sc ON sc.sub_category_id = o.other_link_subcategory_id
WHERE o.other_link_owner = 14 AND o.other_link_add_time_stamp >= timestamp '2020-10-22 00:00:00'
GROUP BY 1, 2

And similar one for videos
Now, I want to combine them into a single query so that I get three columns for counts in a single result - podcast_count, other_count and videos_count. How do I do that?

A: Join the CROSS join of categories to sub_categories, so you get all the combinations of categories and subcategories,  to the other 3 tables with LEFT joins and group by each combination and aggregate:
select c.category_name, sc.sub_category_name,
       count(distinct p.podcast_id) podcast_count,
       count(distinct v.video_id) videos_count,
       count(distinct o.other_link_id) other_count
from categories c cross join sub_categories sc
left join podcasts p on (p.podcast_category_id, p.podcast_subcategory_id) = (c.category_id, sc.sub_category_id)
  and p.podcast_owner = 14 AND p.podcast_upload_time_stamp >= timestamp '2020-10-22 00:00:00'
left join videos v on (v.video_category_id, v.video_subcategory_id) = (c.category_id, sc.sub_category_id)
  and v.video_owner = 14 AND v.video_upload_time_stamp >= timestamp '2020-10-22 00:00:00'
left join otherlinks o on (o.other_link_category_id, o.other_link_subcategory_id) = (c.category_id, sc.sub_category_id)
  and o.other_link_owner = 14 AND o.other_link_add_time_stamp >= timestamp '2020-10-22 00:00:00'
where coalesce(p.podcast_id, v.video_id, o.other_link_id) is not null
group by c.category_id, c.category_name, sc.sub_category_id, sc.sub_category_name

The WHERE clause filters out any combination of category and subcategory that does not contain any podcast, video or other link.

A: You can use UNION ALL and add a constant to distinguish them.
SELECT 'podcasts' as "rowtype", c.category_name, sc.sub_category_name, count(p.*) AS type_count
FROM podcasts p
JOIN categories c ON c.category_id = p.podcast_category_id
JOIN sub_categories sc ON sc.sub_category_id = p.podcast_subcategory_id
WHERE p.podcast_owner = 14 AND p.podcast_upload_time_stamp >= timestamp '2020-10-22 00:00:00'
GROUP BY 1, 2, 3

UNION ALL
SELECT 'videos' as "rowtype", c.category_name, sc.sub_category_name, count(o.*) AS type_count
FROM videolinks o
JOIN categories c ON c.category_id = o.other_link_category_id
JOIN sub_categories sc ON sc.sub_category_id = o.other_link_subcategory_id
WHERE o.other_link_owner = 14 AND o.other_link_add_time_stamp >= timestamp '2020-10-22 00:00:00'
GROUP BY 1, 2, 3

UNION ALL
SELECT 'other' as "rowtype", c.category_name, sc.sub_category_name, count(o.*) AS type_count
FROM otherlinks o
JOIN categories c ON c.category_id = o.other_link_category_id
JOIN sub_categories sc ON sc.sub_category_id = o.other_link_subcategory_id
WHERE o.other_link_owner = 14 AND o.other_link_add_time_stamp >= timestamp '2020-10-22 00:00:00'
GROUP BY 1, 2, 3

I want to note that even just union might work, but union all is more often than not the one that gives the desired result.


Q: Gant table in excel Experts, can you help me with one task I have?  I have to make a Gant table in excel for real production. Do you have any teplate of working gant in excel? I would be grateful if someone could share an example. Thank you in advance.
Isue for excel Gant table


Q: Is there any way to compile a C# assembly statically into a project? I'd like to compile the same build number into a number of separate assemblies written in C#.
When I update the build number in a single place, I need it to update in all of the individual assemblies.
Whats the easiest method to do this?

A: Use a shared AssemblyInfo file as described here: http://blogs.msdn.com/b/jjameson/archive/2009/04/03/shared-assembly-info-in-visual-studio-projects.aspx


Q: Creating a websocket ping in vanilla browser JS I've searched a lot but cannot find a specific example of how to send - using javascript - a ping over a websocket (https://www.rfc-editor.org/rfc/rfc6455#section-5.5.2) from the browser. I'm told that the server I'm using will reply to a ping, but I've been trying variations on the following theme without success.
var sockets= {};
// ... code that attaches sockets to this object

for (let key in sockets) {
    console.log("about to send pings to", key)
    sockets[key].send(0x9)
}

A: const ws = new WebSocket('URL goes here');
ws.onopen = () => { ws.send('ping') };
ws.onmessage = (data) => { console.log(data); } // this should be pong

EDIT the script that you'll need,
<script src="https://cdnjs.cloudflare.com/ajax/libs/web-socket-js/1.0.0/web_socket.min.js"></script>


Q: why is the value being changed even in a const function? #include<iostream>
using namespace std;

class temp
    {
      int value1;
      public :
        void fun() const
        {
        ((temp*)this)->value1 = 10;
        }
        void print()
        {
            cout<<value1<<endl;
        }
     };
int main()
{
  temp t;
  t.fun();
  t.print();
}

A: $5.4/5 is about explicit type conversion (which is what is being used here)

The conversions performed by
— a const_cast (5.2.11),
— a static_cast (5.2.9),
— a static_cast followed by a const_cast,
— a reinterpret_cast (5.2.10), or
— a reinterpret_cast followed by a const_cast,
can be performed using the cast notation of
  explicit type conversion. The same
  semantic restrictions and behaviors
  apply. If a conversion can be
  interpreted in more than one of the
  ways listed above, the interpretation
  that appears first in the list is
  used, even if a cast resulting from
  that interpretation is ill-formed.
  If a conversion can be interpreted in
  more than one way as a static_cast
  followed by a const_cast, the
  conversion is ill-formed.

In this case, ((temp*)this) got treated as (const_cast<temp *>(this)) and was well-formed. This removed away the constness, thereby allowing to change the class member value.

A: C++ tries to prevent accidental errors, but it doesn't go out of its way to fight a programmer who's determined to have things their own way.  If you use cast operators you're telling it "trust me, I know what's there", demanding it ignore it's own knowledge of the program.  It's precisely because the C-style casting operator you've used is dangerous and can be easily misused that C++ introduces static_cast, const_cast and reinterpret_cast, which communicate the programmer's intent in such a way that the compiler can still say "hey, hold on there, that'd require more than just the type of leniency you're asking for".  reinterpret_cast is the big daddy though... no arguing with that... just as brutal as the C-cast and rarely needed in a high-level application.  Precisely because it's rarely needed, verbose and easily seen, it draws scrutiny.  Code littered with C-style casts can easily hide bugs.

A: Because you're casting away const...
When you cast something, the responsibility is yours for making sure that it doesn't do something dumb.

Note that if temp t; is changed to const temp t;, you get undefined behavior, for modifying a const value.
Coincidentally I literally just touched on this in my blog. (Almost the same function, too.)