Q:

How to get a separate context in different SoapUI testcase instances running in parallel?

I have a SoapUI test case (name "create entity") with groovy script test step which uses some variables received in context, e.g. counter value, processes it and returns some other value, e.g. returnId
// these variables are effectively shared across different threads, I want to avoid it
def threadId = context.getProperty("threadId")
def counter = context.getProperty("counter").toInteger()
...
testRunner.testCase.setPropertyValue("returnId", returnId)

And this test case is called from another test case groovy script step, which creates several threads with numerous test case executions
...
def counter = new AtomicInteger()
...

// multiple threads
1.upto(2) {
  threads << new Thread({
    def tc = testRunner.testCase.testSuite.getTestCaseByName("create entity")
    def txInstanceContext = new com.eviware.soapui.support.types.StringToObjectMap()
    // thread specific parameter
    def threadId = ...
    txInstanceContext.put("threadId", threadId)

    // multiple executions loop
    1.upto(2) {
      def number = counter.getAndIncrement().toString()
      // execution specific variable
      txInstanceContext.put("counter", number)
      log.info "Started uploading " + number + " at " + new Date().getTime()
      def runner = tc.run( txInstanceContext, false )
      while(runner.status == Status.RUNNING) {
        this.sleep(50)
      }
      log.info "Status: " + runner.status + ", time taken for upload was: " + runner.timeTaken + " ms"
      ...
      assert runner.status != Status.FAILED : runner.reason
      def returnId = tc.getPropertyValue("returnId")
      log.info "Finished uploading " + number + " at " + new Date().getTime()
      log.info "Returned id: " + returnId
      ...
    }
  })
}

threads.each {
  it.start()
}
threads.each {
  it.join()
}

How to get an isolated scope for each execution, to avoid overriding/setting test case variables by other thread executions?

A:

I think you need to create a TC runner and then WsdlTestRunContext.
I ran into similar situation where I needed to create a TC runner. Here . I believe you can go one step further and create a context by using createContext(StringToObjectMap properties) method of this WsdlTestCaseRunner.


Q:

Converting character matrix with vectors of numerics and plain numerics into numeric

this in theory simple task turned out to drive me crazy today. I'm rather new to R, but got along quite well until now. Maybe someone of you is having an easier time to solve it.
In short: How do I get the maximum values per observation out of a somehow 'mixed' character matrix similar to this one?
dummy = as.matrix(c("c(1.5,2.6,3)", "2", "1.5", "c(1.8, 2.9)"))

so that my result says (in numeric): c(3, 2, 1.5, 2.9)
The longer story:
I'm coming from a
stri_match_all_regex(somestring, regexp)

to get some numbers from a plain text. This returns me a character matrix (by definition of the stri_match_all_regex function)
let it look something similar like this after stripping out some stray characters:
dummy = as.matrix(c("c(1.5,2.6,3)","2","1.5","c(1.8,2.9)"))

You already see the complication of the strings instead of vectors in my matrix here. My desired state is to identify the maximum value of each row.
Usually nothing simpler as that, I'd e.g. run
lapply(dummy, max)

But applying numerical functions obviously won't work with these characters disguised as numericals.(until this point I did not even realize that these are all characters and not numbers as they show up without quotation marks in rStudio View(dummy) ). Turning it into numerics with
as.numeric(dummy)

makes me lose the vectors within the matrix with NAs. Not what I want. I want each "c(1.2,5)" interpreted as if it would be a 'real'/'quotation-mark-less c(1.2,5), and the numbers as numbers of course too.
I even tried to strsplit / gsub the columns but that doesn't seem fruitful either or I'm just doing it wrong.
gsub( ",|c\\(|\\)", ",", dummy)

leaves me with NAs as the , isn't properly interpreted and
as.numeric(strsplit(dummy, ",|.\\(|\\)"))

won't allow me to coerce th elist object returned to numeric
Hence the straightforward question:
How do I turn a character Matrix similar to dummy into a "usable" form to apply numeric functions on both, the plain numbers and the vectors consisting of numbers?
Thanks for your help! I feel like this should be easy.. but I'm stuck with it for quite a while now.

A:

You can use eval/parse to get the numeric values.
result <- apply(dummy, 1, function(s) {
  eval(parse(text = s))
})

result
#[[1]]
#[1] 1.5 2.6 3.0
#
#[[2]]
#[1] 2
#
#[[3]]
#[1] 1.5
#
#[[4]]
#[1] 1.8 2.9


Q:

$SU(2)$ generators and creation annihilation operators

The algebraic method to find the irreducible representation of the $SU(2)$ group makes use of the operators:
$$J_z\\J_+=\frac{1}{\sqrt{2}}(J_x+iJ_y)\\J_-=\frac{1}{\sqrt{2}}(J_x-iJ_y)$$
In the book Georgi (Lie Algebra in particle physics, 1999) this set of operators is said to be a set of generators of a $SU(2)$ subalgebra (chapter 6.5, pag 93).
So, if this were a set of generators, I would say that those operators satisfy a this algebra:
$$[J_z,J_\pm]=\pm J_{\pm}\\ [J_+,J_-]= J_z$$
which is clearly different from the $SU(2)$ algebra:
$$[J_a,J_b]=i \varepsilon_{abc}J_c $$
So is it correct to say that operators $J_z,J_+,J_-$ are NOT a set of generators of the $SU(2)$ group?

A:

I think I have found a rigorous answer (http://en.wikipedia.org/wiki/Representation_theory_of_SU%282%29).
This is the complexified algebra of SU(2)
$$[J_z,J_\pm]=\pm J_{\pm}\\ [J_+,J_-]= J_z$$
The complex Lie algebra (i.e. the complexification of the Lie algebra) doesn't affect the representation theory.
So both the real $[J_a,J_b]=i\varepsilon_{abc}J_c$ and the complexified algebra (above) originates the same representation of the SU(2) group.


Q:

Can a mother taste her own breastmilk?

Can a mother drink/taste her own breastmilk?
I know theres an issur for a non-baby to drink directly from the breast; but, what about from a cup?
Further, if it is indeed assur (even from a cup), what about "tasting" it (i.e. to see if it's gone bad) as one might "taste" chicken soup to see if it needs salt (without actually eating it so you're not fleishik and it doesn't require a bracha)?

A:

Human breastmilk is 100% kosher once it has left the woman's body (Shulchan Aruch YD 81:7). Furthermore, it is pareve, but shouldn't be cooked with meat to avoid issues of Marat Ayin (ibid. 87:4).


Q:

How do I use jQuery to create a bookmark-able hash?

I have a single URL I am using as an image gallery. At this URL is a thumbs div (I'm only showing four thumbs for the sake of brevity):

And an empty div called #content:

and a hidden div called #preload:

My jQuery uses the ID of the clicked thumbnail to clone() the images from the corresponding span and drop them into #content using the html() method. It works great. Now, I'd like to return to mysite.com/#project01 and have #content already filled with Project 01.
How can I give each image a hashed URL that will call up the same jQuery state?

A:

You can just perform a click on that thumb as soon as the page loads and your current code should execute, like this:
$(function() {
  if(window.location.hash.indexOf('project') > -1)
    $(window.location.hash).click();
});

This uses the window.location.hash property which would be "#project01" in your example URL...so it's already an #ID selector, we're just checking that it's a hash we care about, then using that selector to fire a .click().  Just make sure this runs after your current click handler for the thumbs is bound.


Q:

How to create a cache system for a live search while typing

Im trying to make a search engine on key up to return results from DB but also if phrase has been typed to pull results from object not from DB
For example : when you type "BMW 300" will pull data from DB and will save phrase and results in object , and object will look like this
object {
b: (4) […]
  0: Object { name: "BMW"}
  1: Object { name: "BMW 300"}
  2: Object { name: "BMW XS"}
  3: Object { name: "BMW Z 500"}

bm: (4) […]
  0: Object { name: "BMW"}
  1: Object { name: "BMW 300"}
  2: Object { name: "BMW XS"}
  3: Object { name: "BMW Z 500"}

bmw: (4) […]
  0: Object { name: "BMW"}
  1: Object { name: "BMW 300"}
  2: Object { name: "BMW XS"}
  3: Object { name: "BMW Z 500"}

"bmw 3": (1) […]
  0: Object { name: "BMW 300"}

"bmw 30": (1) […]
  0: Object { name: "BMW 300"}

"bmw 300": (1) […]
  0: Object { name: "BMW 300"}
}

if you delete 300 phrase is become "BMW" now should pull results from object because phrase "BMW" has been typed .
I code both logic and they work perfect , but the problem is how to swap when to read from object and when to read from DB ?
// create object
var hold_results = {};

$('input[name="search"]').on('keyup', function(){

var phrase = jQuery.trim($(this).val());

if (phrase.length > 0) {
  $.ajax({
    type: "POST",
    url: 'index.php?route=product/newsearch',
    data: 'phrase='+phrase,
    success: function(data) {
      if (data.length != 0) {

      // push phrase and currect results in object
        hold_results[phrase] = data;

          $.each(data , function(key, value){
            if (value != '') {
              html = '
'+value.name+'
';
              $('#search-results').append(html);
            }
        });
      }
    }
  });
}

// should pull results from object here if phrase exist
$.each(hold_results , function(key , value){

  if (key == phrase) {
    $.each(value, function(k , v){
      html = '
'+v.name+'
';
      $('#search-results').append(html);
    })
  }
});
});

A:

There is a simple approach to achieve that - But first you need to be aware that your implementation will fire too many times and may not work as expected.
I would consider adding several things:

Aborting previously fired async ajax requests before firing the new search - In your code it will just keep firing and receive many results that may not be relevant any more.
Add a Caching mechanism - you want to control how much records it will store and you want a good way to match required search terms (Exact match OR subsets OR both).

Here is Demo in JSfiddle - I will walk you through
First we create a variable that will hold an active ajax request otherwise will be null:
//this is the variable that will store the ajax call
var request = null;

Now we can create an Object that will be our Cache system with all the required methods:
var cache = {
  storageFIFO: [], // The array that will hold our results
  maxResults: 20, // max enteries in the storedResultFifo array - will shift once when exceeded
  pushResults: function(phrase, data) {
    cache.storageFIFO.push({
      term: phrase,
      data: data
    });
    if (cache.storageFIFO.length > cache.maxResults) {
      cache.storageFIFO.shift();
    }
  },
  getCachedResults: function(phrase) {
    //First try exact match against cached search terms:
    for (var i = 0; i < cache.storageFIFO.length; i++)
      if (cache.storageFIFO[i].term === phrase)
        return cache.storageFIFO[i].data;
    //try phrase as a substring of the terms stored in the cache
    for (var i = 0; i < cache.storageFIFO.length; i++)
      if (cache.storageFIFO[i].term.includes(phrase))
        return cache.storageFIFO[i].data;
    return false;
  }
};

A few notes about the Cache:

FIFO (first in first out) : When storage limit is reached the oldest record is removed.
.shift(); Will pop the first element (index 0 which is the oldest) to achieve the FIFO like data structure.
getCachedResults : this method will try to match the phrase twice - Once for an exact match (for better results) otherwise will try to match the phrase as a subset of the cached terms.
string1.includes(string2) this is the way that I match subsets.

Now that the cache mechanism is set - I put the logic inside the keyup event:
//Bind the event to search:
$('input[name="search"]').on('keyup', function() {
  var phrase = jQuery.trim($(this).val());
  if (phrase.length <= 1) return; // From length of two
  //This is just for testing and generating random data:
  var randomData = [];
  for (var i = 0; i < Math.floor(Math.random() * (20 - 5 + 1)) + 5; i++)
    randomData.push({
      phrase: phrase,
      href: "#",
      name: Math.random().toString(36).substring(7)
    });
  //This will trigger an abort of previous unfinished ajax request
  //When aborted the ajax `complete` will set it back to null
  if (request != null) request.abort();

  //try to load from Cache first:
  var fromCache = cache.getCachedResults(phrase);
  if (fromCache !== false) {
    drawResults(fromCache, "Cached Results");
    return;
  }

  //If we got here that means that the cache does not has matching phrases:
  //Send a request to db:
  request = $.ajax({
    url: '/echo/json/', // A jsfiddle async request endpoint
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    data: { //the correct data structure for jsfiddle async requests
      json: JSON.stringify(randomData),
      delay: 0.15
    },
    success: function(data) {
      if (data.length != 0) {
        //Cache it:
        cache.pushResults(phrase, data);
        //Draw it:
        drawResults(data, "DataBase");
      }
    },
    complete: function() {
      request = null;
    }
  });

});

Here you can see some additional stuff that is for the jsfiddle created (to get results from a dummy async request server).
A few notes about the Logic and Ajax request:

if (phrase.length <= 1) return; : will prevent queries that are not 2 chars and longer.
if (request != null) request.abort(); : will abort previously running requests. As you can see in the Ajax complete callback it will set it back to null when finished (success, abort, error etc...)
cache.getCachedResults(phrase); : First try from cache - Will return false if no match.
After no hits againts the cache - then an ajax is fired (note that the url, and data is modified to the required values to work with jsfiddle).

Final Notes
Drawing the results is up to you - I just included a small quick  function to visualize the results and to see where they came from.


Q:

Changing version from MAJOR.MINOR to MAJOR.MINOR.PATCH

I have an android app on playstore and currently, we are using MAJOR.MINOR (eg. 2.1) version format.
I would like to change this to MAJOR.MINOR.PATCH format. How do I do that? Any specific procedure for that or simply add PATCH version to version code in next release (eg. 2.1.1). Please suggest.

A:

Within your app-level build.gradle, the versionName property is a String and can be defined in any format you like, for example:

Major minor e.g. 2.1
Major minor patch e.g. 2.1.1
Major minor patch + commitHash e.g. 2.1.1+a2b3c4d5
Or any other format as defined in Semantic Versioning

The versionCode, however, must remain an integer which must be greater than the previous version. Personally I determine my version codes by multiplying each part by a factor:

Major x 10,000
Minor x 100
Patch x 1

So a versionName of 2.1.1 would have a versionCode of 20101. This allows for 100 patches and 100 minor increments, starting from 0.


Q:

Is it possible to go deeper than nearest superclass (i.e. super.super)?

Assume that I want to skip one level in call super.viewDidLoad(), for example. So I wish to be able to do something like this:
override func viewDidLoad() {
    super.super.viewDidLoad()
}

or
-(void)viewDidLoad {
    [[super super] viewDidLoad];
}

This code will not compile. Is this possible by some other solution?

A:

For expository purposes only, the following code does as requested.  It only fails to crash when compiled without ARC, which means it has a bug in it.  It does no error checking.
Never use this code unless you are playing around and trying to learn.
@import Foundation;
#import <objc/runtime.h>
#import <objc/message.h>

@interface M : NSObject

- (void)print;

@end

@implementation M

- (void)print { NSLog(@"M"); }

@end

@interface N : M
@end

@implementation N

- (void)print { NSLog(@"N"); }

@end

@interface O : N
@end

@implementation O

- (void)print {
    Class mysupersuper = [[self superclass] superclass];
    Method supersuperMethod = class_getInstanceMethod(mysupersuper, _cmd);

    method_invoke(self, supersuperMethod);
}

@end

int main(int argc, char **argv)
{
    O *o = O.new;

    [o print];

    return 0;
}

I compiled it using the command: clang -framework Foundation -fno-objc-arc  -fmodules test.m.


Q:

Saving data within an .exe

I want to create a simple WinForms or WPF application in C#, that manages some data (strings and integers).
What I do not know is where should I store this data so that when I close the program and reopen it, the data will still be there. Same goes for deleting.
I know I could make an adjacent file(xml, txt or similar) but I wish to keep it to one file only. Does Visual Studio have any feature I could use?

A:

You can save your data in the application settings files it is very simple to use.
double-click on your application properties and open the settings menu. Here the definition of variables and use it as follows code
To write
YourProjectNamespace.Properties.Settings.Default.YourVariable = value;
YourProjectNamespace.Properties.Settings.Default.Save();
To read
TempVariable = YourProjectNamespace.Properties.Settings.Default.YourVariable;
Good Luck


Q:

Testing ideas for video recording feature

We recently implemented a video recording feature to our application.
Its specs are:

Video should be available to all iOS users
Video should be available on both iPad and iPhone
A user can record and playback on iOS devices
Should support all iOS versions
Have to be able to support iOS 12

I have come up with a list of test cases, but want to get more ideas from you guys.

A:

Test cases that are based on its specs:
Video should be available to all iOS users; this spec is not very clear.

Does your application have some kind of account sharing feature?
Or it simply means as long as a user has got an iOS device, this video feature is available to them?
Test case, since it is not really practical to test on every iOS device, I would personally choose a few representative devices; I stole this chart from www.statista.com and www.iossupportmatrix.com  You may need to choose one or more iPhones to make sure your video feature is working for all iOS users. I doubt you need to test them all, but the more devices you test, the more confident you are.

Video should be available on both iPad and iPhone, this spec is not very clear.

What do you mean by available? Is this video recording feature available or the recorded video that is available?
Test case, you can also refer to the two charts above. Again, I doubt you will need to test all versions of iPhone and iPad.

A user can record and playback on iOS devices,

Test case, you may need to test against the boundary values of how long a video is allowed to be.
Test case, you may need to test against how record and playback can handle interrupt and resume
Test case, you may need to playback a video recorded from one iOS device on a different iOS device, testing on different iOS versions too?

Should support all iOS versions,

You cannot test all of it, choose a few representative ones.

Have to be able to support iOS 12

As of 16th of August 2018, iOS 12 has not been officially released, you will need to sign up for a beta testing account in order to download it. Check it out here, https://beta.apple.com/sp/betaprogram/


Q:

Cometd/Bayeux client in Android App

Has anybody implemented a Cometd/Bayeux client in a native Android App?
I tried to use
org.cometd.java:cometd-java-client:3.0.3

but it uses jetty HttpClient which has dependencies to java.lang.management.ManagementFactory which is not available on Android.

A:

You can use CometD 2.9.1 on Android. The protocol has not changed between CometD 2 and CometD 3, and you will have Android compatibility.


Q:

Facebook orkut style date in android application

In my application I am showing a list of posts with its creator name, text of post and post date.
I want to show date in the format which is used in facebook or orkut like if a post is added before 3 sec then I want to show date as "added 3 sec ago"
Can any one please guide me how to achieve this in android.

A:

Take a look at the PrettyTime library.


Q:

When i call the controller method in which i write this code to send email. My webpage does not load . and it does not show any error

When i call the controller method in which i write this code
 $config = array(
        'protocol' => 'smtp',
        'smtp_host' => 'ssl://smtp.googlemail.com',
        'smtp_port' => 465,
        'smtp_user' => 'me.atiq32@gmail.com',
        'smtp_pass' => '********'
    );
    $this->load->library('email', $config);
    $this->email->from('me.atiq32@gmail.com', 'Atiq');
    $this->email->to('***@yahoo.com');
    $this->email->subject('Email Test');
    $this->email->message('Testing the email class.');

    if ($this->email->send()) {
        echo 'Email will be Sent';
    } else {
        echo $this->email->print_debugger();
    }
} '

to send email.
 My webpage does not load (in loading ....).
and even does not show any error.

A:

are those stray characters at the very end? if yes they might be messing it up.
otherwise -- its hard to tell because we can't see all the code. what i do in situations like this is echo out a check before the method is called like
 echo " before email " ;
 $this->sendemail() ;
 echo " after email " ;

that gives you a sanity check to see where in the chain its breaking down. otherwise if you can't figure it out post more of your code.


Q:

How to write a "Not In" SQL query in LINQ?

How would I translate the following SQL query in to a comparable LINQ query?
select * from Dept
where Id not in (
    Select Id
    from Employee
    where Salary > 100);

A:

Try something like this:
var result = from d in Dept
             let expensiveEmployeeIds = (from e in Employee.Employees
                                       where e.Salary > 100
                                       select e.Id)
             where !expensiveEmployeeIds.Contains(d.Id)
             select d;


Q:

Error trying to get window of iFrame

I am attempting to get the window of an iFrame using the following code:
  var frameWindow = document.getElementById("loginframe");
  var iWindow = frameWindow.contentWindow;

Unfortunately, I keep getting the following error:
Property 'contentWindow' does not exist on type 'HTMLElement'.)

As you can see in the screenshot below, "contentWindow" is highlighted in red which is an error...

I have tried casting:
  let map = document.getElementById("loginframe") as HTMLObjectElement;
  let insideDoc = map.contentDocument;

But this does not work either...
Is this something to do with angular libraries that perhaps I need to include?

A:

First of all you shouldn't select a DOM element like that you should use a viewChild to do that.
<iframe src="urlHere" #loginframe ></iframe>

Then you can use it in your TypeScript code like this:
@ViewChild('loginframe') loginframe: ElementRef;

After that you can select the element like this: (Note: you should cast it to a HTMLIFrameElement)
const win = (<HTMLIFrameElement> this.loginframe).nativeElement.contentWindow;

Here is a fully working plnkr! (open your console to see the output)
https://embed.plnkr.co/kicS6o8QlOEcXyMKNjFi/


Q:

Keeping returned records from mysql unique

Is there a quick way to make sure the records you return from a MySQL JOIN query are unique?
The code below could potentially bring back the same category twice.  Its the category ID which should be distinct!
SELECT
   exp_categories.cat_name, exp_categories.cat_id, exp_categories.cat_url_title
  ,exp_category_posts.entry_id, exp_channel_titles.status
FROM (exp_categories
LEFT JOIN exp_category_posts
       ON exp_categories.cat_id = exp_category_posts.cat_id)
LEFT JOIN exp_channel_titles
       ON exp_category_posts.entry_id = exp_channel_titles.entry_id
WHERE exp_categories.group_id = 2
  AND exp_category_posts.entry_id IS NOT NULL
  AND exp_channel_titles.status = 'open'
ORDER BY RAND()
LIMIT 2

A:

    SELECT
   exp_categories.cat_name, exp_categories.cat_id, exp_categories.cat_url_title
  ,exp_category_posts.entry_id, exp_channel_titles.status
FROM (exp_categories
LEFT JOIN exp_category_posts
       ON exp_categories.cat_id = exp_category_posts.cat_id)
LEFT JOIN exp_channel_titles
       ON exp_category_posts.entry_id = exp_channel_titles.entry_id
WHERE exp_categories.group_id = 2
  AND exp_category_posts.entry_id IS NOT NULL
  AND exp_channel_titles.status = 'open'
  GROUP BY exp_categories.cat_id
ORDER BY RAND()
LIMIT 2

edit: Adding the column you want to be distinct in the GROUP BY clause will ensure there's only 1 returned.  Also, the ORDER BY RAND() is heavily discouraged, see: http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/


Q:

Random Number Generator not working with 2D arrays that output - C++

Okay, so I have a problem. I am trying to get the code to output to the console in a format like this:
123456
789012
345678
901234
567890
123456

But it is displaying like this:
123456

I don't know what the problem is, but here is the code:
void mazeLayout() {
    srand(time(NULL));
    const int mazeLayoutArraySize = 6;
    int mazeLayoutOne = rand()%6+1;
    int mazeLayoutTwo = rand()%6+1;
    int mazeLayoutThree = rand()%6+1;
    int mazeLayoutFour = rand()%6+1;
    int mazeLayoutFive = rand()%6+1;
    int mazeLayoutSix = rand()%6+1;
    int mazeLayoutSeven = rand()%6+1;
    int mazeLayoutEight = rand()%6+1;
    int mazeLayoutNine = rand()%6+1;
    int mazeLayoutTen = rand()%6+1;
    int mazeLayoutEleven = rand()%6+1;
    int mazeLayoutTwelve = rand()%6+1;
    int mazeLayoutThirteen = rand()%6+1;
    int mazeLayoutFourteen = rand()%6+1;
    int mazeLayoutFifteen = rand()%6+1;
    int mazeLayoutSixteen = rand()%6+1;
    int mazeLayoutSeventeen = rand()%6+1;
    int mazeLayoutEightteen = rand()%6+1;
    int mazeLayoutNineteen = rand()%6+1;
    int mazeLayoutTwenty = rand()%6+1;
    int mazeLayoutTwentyOne = rand()%6+1;
    int mazeLayoutTwentyTwo = rand()%6+1;
    int mazeLayoutTwentyThree = rand()%6+1;
    int mazeLayoutTwentyFour = rand()%6+1;
    int mazeLayoutTwentyFive = rand()%6+1;
    int mazeLayoutTwentySix = rand()%6+1;
    int mazeLayoutTwentySeven = rand()%6+1;
    int mazeLayoutTwentyEight = rand()%6+1;
    int mazeLayoutTwentyNine = rand()%6+1;
    int mazeLayoutThirty = rand()%6+1;
    int mazeLayoutThirtyOne = rand()%6+1;
    int mazeLayoutThirtyTwo = rand()%6+1;
    int mazeLayoutThirtyThree = rand()%6+1;
    int mazeLayoutThirtyFour = rand()%6+1;
    int mazeLayoutThirtyFive = rand()%6+1;
    int mazeLayoutThirtySix = rand()%6+1;
    int mazeLayoutArray[mazeLayoutArraySize][mazeLayoutArraySize]={{mazeLayoutOne, mazeLayoutTwo, mazeLayoutThree, mazeLayoutFour, mazeLayoutFive, mazeLayoutSix},
                               {mazeLayoutSeven, mazeLayoutEight, mazeLayoutNine, mazeLayoutTen, mazeLayoutEleven, mazeLayoutTwelve},
                               {mazeLayoutThirteen, mazeLayoutFourteen, mazeLayoutFifteen, mazeLayoutSixteen, mazeLayoutSeventeen, mazeLayoutEightteen},
                               {mazeLayoutNineteen, mazeLayoutTwenty, mazeLayoutTwentyOne, mazeLayoutTwentyTwo, mazeLayoutTwentyThree, mazeLayoutTwentyFour},
                               {mazeLayoutTwentyFive, mazeLayoutTwentySix, mazeLayoutTwentySeven, mazeLayoutTwentyEight, mazeLayoutTwentyNine, mazeLayoutThirty},
                               {mazeLayoutThirtyOne, mazeLayoutThirtyTwo, mazeLayoutThirtyThree, mazeLayoutThirtyFour, mazeLayoutThirtyFive, mazeLayoutThirtySix}};

//for loop to read rows
for(int index1=0; index1<6; index1++){
        for(int index2=0; index2<6; index2++) {
            cout << mazeLayoutArray[index1][index2];
        }
        cout << endl;
        exit(0);
    }

}

If you have any questions, just ask me!

A:

for(int index1=0; index1<6; index1++){
    for(int index2=0; index2<6; index2++) {
        cout << mazeLayoutArray[index1][index2];
    }
    cout << endl;
    exit(0);
}

After the inner loop prints out the first line, you just exit()'d the program.


Q:

Order by clause confusion

Below are the contents of sid column in a table ( where "S05201215" is
a fixed string and remaining part of the Sring is a sequence of
numbers)
S052012151
S052012152
S052012153
S052012154
S052012155
S052012156

I want to sort the the remaining part of the string (i.e.
the numbers that i've appended to the string S05201215  in
descending order ..  what modifications should i do to the below query
to get desired output?
SELECT `sid` FROM `mytable` order by SUBSTRING(`sid`,10,length(`sid`))

A:

To sort in descending order, just add "DESC" to the end of your ORDER BY:
SELECT `sid`
FROM `mytable`
ORDER BY SUBSTRING(`sid`, 10, length(`sid`)) DESC

However, if the values of sid are of different lengths, you are probably going to want to cast the values to a numeric type before sorting:
SELECT `sid`
FROM `mytable`
ORDER BY CAST(SUBSTRING(`sid`, 10, length(`sid`)) AS SIGNED) DESC


Q:

Makefile vpath %.o not finding obj files

I'm using the following vpath to attempt locating my $(OBJ) files:
vpath %.o ./lib/obj

And my target is setup as such:
# Link target
link:
    @echo "\nLinking files"
    $(CC) $(LINK_FLAGS) -o main.elf $(OBJS)

When looking at the output, I get (for all the *.o files):
...error: misc.o: No such file or directory

My project structure looks as follows:
.
├── Makefile
├── inc
│   └── main.h
├── lib
│   ├── inc
│   │   ├── cmsis
│   │   │   ├── arm_common_tables.h
│   │   │   ├── ...
│   │   ├── peripherals
│   │   │   ├── misc.h
│   │   │   ├── ...
│   │   └── stm32f4xx
│   │       ├── stm32f4xx.h
│   │       ├── ...
│   ├── obj
│   │   ├── misc.o
│   ├── src
│   │   ├── peripherals
│   │   │   ├── misc.c
│   │   │   ├── ...
│   │   └── system_stm32f4xx.c
│   └── startup_stm32f4xx.s
├── src
│   └── main.c
└── stm32f4.ld

Why are my .o files not being found?
Full output for reference:

arm-none-eabi-gcc -T"stm32f3.ld" -nostartfiles -Wl,-Map,"main.map"
  -mcpu=cortex-m4 -mthumb -g3 -gdwarf-2 -L"./" -o main.elf misc.o stm32f4xx_adc.o stm32f4xx_can.o stm32f4xx_crc.o stm32f4xx_cryp.o
  stm32f4xx_cryp_aes.o stm32f4xx_cryp_des.o stm32f4xx_cryp_tdes.o
  stm32f4xx_dac.o stm32f4xx_dbgmcu.o stm32f4xx_dcmi.o stm32f4xx_dma.o
  stm32f4xx_exti.o stm32f4xx_flash.o stm32f4xx_fsmc.o stm32f4xx_gpio.o
  stm32f4xx_hash.o stm32f4xx_hash_md5.o stm32f4xx_hash_sha1.o
  stm32f4xx_i2c.o stm32f4xx_iwdg.o stm32f4xx_pwr.o stm32f4xx_rcc.o
  stm32f4xx_rng.o stm32f4xx_rtc.o stm32f4xx_sdio.o stm32f4xx_spi.o
  stm32f4xx_syscfg.o stm32f4xx_tim.o stm32f4xx_usart.o stm32f4xx_wwdg.o
  system_stm32f4xx.o

A:

$(OBJS) is just a variable, and gets expanded as text.  When it appears in the text of the command in your link rule, it is simply expanded as text.
vpath searches are applied to prerequisites, so you will have to arrange for your $(OBJS) to appear as prerequisites to your link rule and for the rule's commands to use those prerequisites (via automatic variables, rather than just using $(OBJS) directly).
So your rule needs to look more like
# Link target
link: main.elf

main.elf: $(OBJS)
    @echo "\nLinking files"
    $(CC) $(LINK_FLAGS) -o $@ $+

(I have also taken the liberty of writing out the file generated (main.elf) as the non-phony target of an intermediate rule.  Making these things explicit to Make is generally a good idea.)

A:

Although the other answers are correct in the details of what they say, there is a larger point here: it is not possible to use VPATH/vpath reliably to find derived files, like .o files that you build from your makefile.  VPATH/vpath is only useful for finding source files, such as .c files.
You should read http://make.mad-scientist.net/vpath.html

A:

vpath just tells make where to find the files, not the compiler/linker.  You have to get make to tell the compiler/linker where it found them.  The easiest way is to make them proper dependencies (so they get rebuilt before linking) and then use $^:
# Link target
link: $(OBJS)
        @echo "\nLinking files"
        $(CC) $(LINK_FLAGS) -o main.elf $^


Q:

Why are the icon classes not getting changed when using event listeners to detect changes?

I was trying to do my own take of this: https://codepen.io/codifiedconcepts/pen/bwgxRq
I've made a few tweaks, but when I change the time in the drop-downs, the icons don't change as intended. I've tested it by manually changing the time and the icons changed, and I've tested the event listeners by adding an alert box - everything is fine.
But when I go to change on the drop-down themselves, the icons don't change. I just can't seem to get it to work.

  let wakeTime = 7;
    let noon = 12;
    let lunch = 12;
    let evening = 17;
    let dinner = 18;
    let bed = 21;

    //Setting time up
    let showCurrentTime = () => {
        const clock = document.getElementById('clock');
        let currentTime = new Date();
        let hours = currentTime.getHours();
        let minutes = currentTime.getMinutes();
        let seconds = currentTime.getSeconds();
        let meridian = "AM";

             if (hours >= noon)
          {
              meridian = "PM";
          }

          if (hours > noon)
          {
              hours = hours - 12;
          }

        // Set Minutes
        if (minutes < 10)
        {
            minutes = "0" + minutes;
        }

        // Set Seconds
        if (seconds < 10)
        {
            seconds = "0" + seconds;
        }
            //Putting it all together
            let clockTime = `${hours}:${minutes}:${seconds}  ${meridian}!`;
            clock.innerText = clockTime;
    };

    //Getting the clock to update on its own so it changes pictures and messages
    let updateClock = () => {
        let time = new Date().getHours();
        let message = document.getElementById('message');
        let icon = document.getElementById('food-icon');

        if(time === wakeTime){
            icon.classList.remove('fa-smile');
            icon.classList.add('fa-clock');
            message.textContent = 'Wakey wakey!';
        } else if (time === lunch){
            icon.classList.remove('fa-smile');
            icon.classList.add('fa-hotdog');
            message.textContent = "I'm hungry."
        } else if (time === dinner ) {
            icon.classList.remove('fa-smile');
            icon.classList.add('fa-utensils');
            message.textContent = "Can I have more food?";
        } else if (time === bed){
            icon.classList.remove('fa-smile');
            icon.classList.add('fa-bed');
            message.textContent = "YAWN";
        } else if (time >= noon ) {
            icon.classList.add('fa-smile');
            message.textContent = "Good afternoon!"
        } else if (time < noon) {
            icon.classList.add('fa-smile');
            message.innerHtml = "Good morning!";
        } else if (time >= evening) {
            icon.classList.add('fa-smile');
            message.textContent = "Good evening!";
        }
        showCurrentTime();
    };
    updateClock();

    //Getting the clock to increment once a second
    const oneSecond = 1000;
    setInterval(updateClock, oneSecond);

    const wakeSelect = document.querySelector('#wakeSelect')
    wakeSelect.addEventListener('change', function() {
        wakeTime = wakeSelect.value;
    });

    const lunchSelect = document.querySelector('#lunchSelect')
    lunchSelect.addEventListener('change', () => {
        lunch = lunchSelect.value;
    });

    const dinnerSelect = document.querySelector('#dinnerSelect')
    dinnerSelect.addEventListener('change', () => {
        dinner = dinnerSelect.value;
    });
<!DOCTYPE html>

        <meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <title>Vanilla JS Clock</title>
        <meta name="description" content="">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="">

What time is it!?

        Clock goes here

Hello!

        Choose wake up time:
        <select id="wakeSelect">
            <option value="1">1 AM</option>
            <option value="2">2 AM</option>
            <option value="3">3 AM - 4AM</option>
            <option value="4">4 AM - 5AM</option>
            <option value="5">5 AM - 6AM</option>
            <option value="6">6 AM - 7AM</option>
            <option value="7">7 AM - 8AM</option>
            <option value="8" selected>8 AM - 9AM</option>
            <option value="9">9 AM - 10AM</option>
            <option value="10">10 AM - 11AM</option>
            <option value="11">11 AM - 12PM</option>
            <option value="12">12 PM - 1PM</option>
            <option value="13">1 PM - 2PM</option>
            <option value="14">2 PM - 3PM</option>
            <option value="15">3 PM - 4PM</option>
            <option value="16">4 PM - 5PM</option>
            <option value="17">5 PM - 6PM</option>
            <option value="18">6 PM - 7PM</option>
            <option value="19">7 PM - 8PM</option>
            <option value="20">8 PM - 9PM</option>
            <option value="21">9 PM - 10PM</option>
            <option value="22">10 PM - 11PM</option>
            <option value="23">11 PM - 12AM</option>
            <option value="24">12 AM - 1AM</option>
          </select>

         Choose lunch time
            <select id="lunchSelect">
              <option value="1">1 AM - 2AM</option>
              <option value="2">2 AM - 3AM</option>
              <option value="3">3 AM - 4AM</option>
              <option value="4">4 AM - 5AM</option>
              <option value="5">5 AM - 6AM</option>
              <option value="6">6 AM - 7AM</option>
              <option value="7">7 AM - 8AM</option>
              <option value="8">8 AM - 9AM</option>
              <option value="9">9 AM - 10AM</option>
              <option value="10">10 AM - 11AM</option>
              <option value="11">11 AM - 12PM</option>
              <option value="12" selected>12 PM - 1PM</option>
              <option value="13">1 PM - 2PM</option>
              <option value="14">2 PM - 3PM</option>
              <option value="15">3 PM - 4PM</option>
              <option value="16">4 PM - 5PM</option>
              <option value="17">5 PM - 6PM</option>
              <option value="18">6 PM - 7PM</option>
              <option value="19">7 PM - 8PM</option>
              <option value="20">8 PM - 9PM</option>
              <option value="21">9 PM - 10PM</option>
              <option value="22">10 PM - 11PM</option>
              <option value="23">11 PM - 12AM</option>
              <option value="24">12 AM - 1AM</option>
            </select>

            Choose dinner time
            <select id="dinnerSelect">
              <option value="1">1 AM - 2AM</option>
              <option value="2">2 AM - 3AM</option>
              <option value="3">3 AM - 4AM</option>
              <option value="4">4 AM - 5AM</option>
              <option value="5">5 AM - 6AM</option>
              <option value="6">6 AM - 7AM</option>
              <option value="7">7 AM - 8AM</option>
              <option value="8">8 AM - 9AM</option>
              <option value="9">9 AM - 10AM</option>
              <option value="10">10 AM - 11AM</option>
              <option value="11">11 AM - 12PM</option>
              <option value="12">12 PM - 1PM</option>
              <option value="13">1 PM - 2PM</option>
              <option value="14">2 PM - 3PM</option>
              <option value="15">3 PM - 4PM</option>
              <option value="16">4 PM - 5PM</option>
              <option value="17">5 PM - 6PM</option>
              <option value="18" selected>6 PM – 7PM</option>
              <option value="19">7 PM - 8PM</option>
              <option value="20">8 PM - 9PM</option>
              <option value="21">9 PM - 10PM</option>
              <option value="22">10 PM - 11PM</option>
              <option value="23">11 PM - 12AM</option>
              <option value="24">12 AM - 1AM</option>
            </select>

A:

The problem is that you are trying to compare variables of different types using === which compares the values and the data type. So when you were doing this in updateClock:
if(time === wakeTime)

it was failing even if the values were the same because time is a number and wakeTime is a string. There are 2 ways you can change the code to fix this:

Compare the values only and not the types using == : if(time == wakeTime)

Or change the string to a number using the Number or parseInt functions, e.g. if(time === Number(wakeTime))

I've changed this below in your updateClock function, you can see it working here! I've also fixed the incorrect icon classes not being removed (see the update below):

let wakeTime = 7;
    let noon = 12;
    let lunch = 12;
    let evening = 17;
    let dinner = 18;
    let bed = 21;

    //Setting time up
    let showCurrentTime = () => {
        const clock = document.getElementById('clock');
        let currentTime = new Date();
        let hours = currentTime.getHours();
        let minutes = currentTime.getMinutes();
        let seconds = currentTime.getSeconds();
        let meridian = "AM";

             if (hours >= noon)
          {
              meridian = "PM";
          }

          if (hours > noon)
          {
              hours = hours - 12;
          }

        // Set Minutes
        if (minutes < 10)
        {
            minutes = "0" + minutes;
        }

        // Set Seconds
        if (seconds < 10)
        {
            seconds = "0" + seconds;
        }
            //Putting it all together
            let clockTime = `${hours}:${minutes}:${seconds}  ${meridian}!`;
            clock.innerText = clockTime;
    };

    //Getting the clock to update on its own so it changes pictures and messages
    let updateClock = () => {
        let time = new Date().getHours();
        let message = document.getElementById('message');
        let icon = document.getElementById('food-icon');

        if(time == wakeTime){
            changeIcon(icon, 'fa-clock');
            message.textContent = 'Wakey wakey!';
        } else if (time == lunch){
            changeIcon(icon, 'fa-hotdog');
            message.textContent = "I'm hungry."
        } else if (time == dinner ) {
            changeIcon(icon, 'fa-utensils');
            message.textContent = "Can I have more food?";
        } else if (time == bed){
            changeIcon(icon, 'fa-bed');
            message.textContent = "YAWN";
        } else if (time >= noon ) {
            changeIcon(icon, 'fa-smile');
            message.textContent = "Good afternoon!"
        } else if (time < noon) {
            changeIcon(icon, 'fa-smile');
            message.innerHtml = "Good morning!";
        } else if (time >= evening) {
            changeIcon(icon, 'fa-smile');
            message.textContent = "Good evening!";
        }
        showCurrentTime();
    };
    updateClock();

    //Getting the clock to increment once a second
    const oneSecond = 1000;
    setInterval(updateClock, oneSecond);

    const wakeSelect = document.querySelector('#wakeSelect')
    wakeSelect.addEventListener('change', function() {
        wakeTime = wakeSelect.value;
    });

    const lunchSelect = document.querySelector('#lunchSelect')
    lunchSelect.addEventListener('change', () => {
        lunch = lunchSelect.value;
    });

    const dinnerSelect = document.querySelector('#dinnerSelect')
    dinnerSelect.addEventListener('change', () => {
        dinner = dinnerSelect.value;
    });

function changeIcon(iconElement, newIconClass){
    // remove all existing icon classes
    iconElement.classList.forEach(className => {
        // check for classes starting with "fa-" but are not "fa-5x"
        if (className.startsWith('fa-') && className!=('fa-5x'))
            iconElement.classList.remove(className);
    });
    // now add the new class
    iconElement.classList.add(newIconClass);
}

What time is it!?

        Clock goes here

Hello!

        Choose wake up time:
        <select id="wakeSelect">
            <option value="1">1 AM</option>
            <option value="2">2 AM</option>
            <option value="3">3 AM - 4AM</option>
            <option value="4">4 AM - 5AM</option>
            <option value="5">5 AM - 6AM</option>
            <option value="6">6 AM - 7AM</option>
            <option value="7">7 AM - 8AM</option>
            <option value="8" selected>8 AM - 9AM</option>
            <option value="9">9 AM - 10AM</option>
            <option value="10">10 AM - 11AM</option>
            <option value="11">11 AM - 12PM</option>
            <option value="12">12 PM - 1PM</option>
            <option value="13">1 PM - 2PM</option>
            <option value="14">2 PM - 3PM</option>
            <option value="15">3 PM - 4PM</option>
            <option value="16">4 PM - 5PM</option>
            <option value="17">5 PM - 6PM</option>
            <option value="18">6 PM - 7PM</option>
            <option value="19">7 PM - 8PM</option>
            <option value="20">8 PM - 9PM</option>
            <option value="21">9 PM - 10PM</option>
            <option value="22">10 PM - 11PM</option>
            <option value="23">11 PM - 12AM</option>
            <option value="24">12 AM - 1AM</option>
          </select>

         Choose lunch time
            <select id="lunchSelect">
              <option value="1">1 AM - 2AM</option>
              <option value="2">2 AM - 3AM</option>
              <option value="3">3 AM - 4AM</option>
              <option value="4">4 AM - 5AM</option>
              <option value="5">5 AM - 6AM</option>
              <option value="6">6 AM - 7AM</option>
              <option value="7">7 AM - 8AM</option>
              <option value="8">8 AM - 9AM</option>
              <option value="9">9 AM - 10AM</option>
              <option value="10">10 AM - 11AM</option>
              <option value="11">11 AM - 12PM</option>
              <option value="12" selected>12 PM - 1PM</option>
              <option value="13">1 PM - 2PM</option>
              <option value="14">2 PM - 3PM</option>
              <option value="15">3 PM - 4PM</option>
              <option value="16">4 PM - 5PM</option>
              <option value="17">5 PM - 6PM</option>
              <option value="18">6 PM - 7PM</option>
              <option value="19">7 PM - 8PM</option>
              <option value="20">8 PM - 9PM</option>
              <option value="21">9 PM - 10PM</option>
              <option value="22">10 PM - 11PM</option>
              <option value="23">11 PM - 12AM</option>
              <option value="24">12 AM - 1AM</option>
            </select>

            Choose dinner time
            <select id="dinnerSelect">
              <option value="1">1 AM - 2AM</option>
              <option value="2">2 AM - 3AM</option>
              <option value="3">3 AM - 4AM</option>
              <option value="4">4 AM - 5AM</option>
              <option value="5">5 AM - 6AM</option>
              <option value="6">6 AM - 7AM</option>
              <option value="7">7 AM - 8AM</option>
              <option value="8">8 AM - 9AM</option>
              <option value="9">9 AM - 10AM</option>
              <option value="10">10 AM - 11AM</option>
              <option value="11">11 AM - 12PM</option>
              <option value="12">12 PM - 1PM</option>
              <option value="13">1 PM - 2PM</option>
              <option value="14">2 PM - 3PM</option>
              <option value="15">3 PM - 4PM</option>
              <option value="16">4 PM - 5PM</option>
              <option value="17">5 PM - 6PM</option>
              <option value="18" selected>6 PM – 7PM</option>
              <option value="19">7 PM - 8PM</option>
              <option value="20">8 PM - 9PM</option>
              <option value="21">9 PM - 10PM</option>
              <option value="22">10 PM - 11PM</option>
              <option value="23">11 PM - 12AM</option>
              <option value="24">12 AM - 1AM</option>
            </select>

Note: you have other problems with your logic removing your icons. For example you are only removing the fa-smile class from if (time==wakeTime) so if you changed lunch time for example, then the icon would be something else and you are not removing it. You can change it so that it removes all existing classes instead of specific ones.
UPDATE - remove all existing fa- icon classes:
The most flexible way to do this is probably to remove any icon classes starting with fa-, so you don't have to keep a list.
The following function looks for all classes starting with fa- except fa-5x (because you need that for the size), and removes them. You can also pass in the new icon class:
function changeIcon(iconElement, newIconClass){
    // remove all existing icon classes
    iconElement.classList.forEach(className => {
        // check for classes starting with "fa-" but are not "fa-5x"
        if (className.startsWith('fa-') && className!=('fa-5x'))
            iconElement.classList.remove(className);
    });
    // now add the new class
    iconElement.classList.add(newIconClass);
}

To use it, you just need to do the following!
if(time == wakeTime){
    changeIcon(icon, 'fa-clock');
    message.textContent = 'Wakey wakey!';
}
// etc


Q:

Bug script para deletar todo o banco SQL SERVER

Eu tenho o script abaixo para dropar TUDO do banco de dados, mas em um dos banco que eu tenho o processamento que precisa deste script acontece um bug, por algum motivo ele não consegue rodar na primeira vez que eu executo, mas na segunda roda sem nenhum impedimento. Segue script
DECLARE @ALT_TAB varchar(250)
DECLARE @COMANDO varchar(8000)

/***********  DROP CONSTRAINTS  ********************/
SET  @COMANDO = ''
DECLARE vendor_cursor CURSOR FOR
  SELECT ('ALTER TABLE ' + TABLE_SCHEMA + '.[' + TABLE_NAME+ '] DROP CONSTRAINT [' + CONSTRAINT_NAME + '];') as ALT
  FROM information_schema.table_constraints
  WHERE CONSTRAINT_TYPE = 'FOREIGN KEY'

OPEN vendor_cursor
FETCH NEXT FROM vendor_cursor INTO @ALT_TAB

WHILE @@FETCH_STATUS = 0
 BEGIN
  IF ISNULL(@ALT_TAB, '') <> ''
  SET @COMANDO = @COMANDO + ISNULL(@ALT_TAB, '') + CHAR(13)

  FETCH NEXT FROM vendor_cursor INTO @ALT_TAB
 END

CLOSE vendor_cursor;
DEALLOCATE vendor_cursor;

EXEC(@COMANDO)
/**********************************************************/

/***********  DROP TABLES  **********************/
SET  @COMANDO = ''
DECLARE tables_cursor CURSOR FOR
 SELECT 'DROP TABLE ' + TABLE_NAME + ';'
 FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_TYPE = 'BASE TABLE' AND TABLE_NAME <> 'sysdiagrams'
 ORDER BY TABLE_NAME

OPEN tables_cursor
FETCH NEXT FROM tables_cursor INTO @ALT_TAB

WHILE @@FETCH_STATUS = 0
 BEGIN
  IF ISNULL(@ALT_TAB, '') <> ''
  SET @COMANDO = @COMANDO + ISNULL(@ALT_TAB, '') + CHAR(13)

  FETCH NEXT FROM tables_cursor INTO @ALT_TAB
 END

CLOSE tables_cursor;
DEALLOCATE tables_cursor;

EXEC(@COMANDO)

Os erros apresentados são:
 (Obs.: O NOME_TABELA é sempre o nome de uma tabela diferente)
Mensagem 105, Nível 15, Estado 1, Linha 1
Unclosed quotation mark after the character string 'CT_ENTIDADE_PRINCIPAL'.
Mensagem 102, Nível 15, Estado 1, Linha 1
Incorrect syntax near 'CT_ENTIDADE_PRINCIPAL'.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.
Mensagem 3726, Nível 16, Estado 1, Linha 1
Could not drop object 'NOME_TABELA' because it is referenced by a FOREIGN KEY constraint.

O que poderia estar acarretando nesse erro?
Por que somente neste banco de dados ocorre esse erro?
Por que se eu executar duas vezes o script ele funciona?
Obrigado pela atenção!

A:

A variável @COMANDO era varchar(8000), mas a quantidade de CONSTRAINT fazia o comando estourar esse tamanho, por causa disso a ultima linha ficava cortada. Aí se eu executasse a segunda vez ele terminava de deletar o resto das CT que faltavam e funcionava. Consegui ver isso fazendo um SELECT no @COMANDO.
Se alterar o @COMANDO para varchar(MAX) passa a funcionar independente do tamanho do banco.
@Murilo que deu a ideia de como descobrir o problema.


Q:

Call function from calling object

This is for a personal project. Not assignment or work.
Say I have an object, objA that has a function callB().
When I run callB() it calls a function in object B. The function in objB can have calls to functions in objA.
Eg. objA calls callB().
Inside callB() there is a function like setObjAName() which sets a variable on objA.
How would I do this in Java? How do I reference objA from objB?

A:

The simplest method is to simply pass a reference to A in with the method call, which will allow for B to access any of A's public methods.
public class ClassA {

    public String someAVar;

    public void callB(ClassA a){
        //do stuff
        ClassB b = new ClassB();
        b.setObjA(this,"newValue");
    }
}
public class ClassB{
    public void setObjA(ClassA A, String newValue){
        A.someAVar = newValue;
    }
}

Alternatively you might want the variable to be settable without passing in a particular instance, in which case static methods and variables are your friend.
public class ClassA {

    public static String someAVar;

    public void callB(){
        //do stuff
        ClassB b = new ClassB();
        b.setObjA("newValue");
    }
}

public class ClassB{
    public void setObjA(String newValue){
        ClassA.someAVar = newValue;
    }
}


Q:

Different circular sectors as new logo of the International System

This question does not ask the user to provide me a full MWE, but simply to obtain any information step by step as to create different circular sectors.

This image is taken from the site: https://www.inrim.it/sites/default/files/mediaroot/eventi/logo_nuovosi.png
I have read the only the manual pgf-pie to build pie charts and with lot of sincerity I have seen the responses of users and I have been so scared (see here: Multi-layer Donut Pie).
In fact, I was wondering if you need very much code to make a frontal one that is not in 3D.
I would like to make it because I absolutely don't like some symbols like $\Delta v$ and $K_{\text{cd}}$.
So I only ask users for the simplest steps and no complete MWE.
Thank you (excuse me very much for not having added the link of the image and I have not specified that it serves only me and will not be published, or used improperly).

A:

The following code seems sufficiently simple and solves the rotation issue with the letters in the bottom blocks.
\documentclass[border=3mm]{standalone}

\usepackage[dvipsnames]{xcolor}
\usepackage{tikz}

\usepackage{arev}

\begin{document}
\Large

\begin{tikzpicture}[scale=1.3]
% -----------------------------------
% the \foreach-part
\foreach\n/\k/\l/\o
    [evaluate={\n as \p         using int((\n-3)*(\n-4))},
     evaluate={\n as \angle     using (90+360/14-360/7*\n)},
     evaluate={\n as \Angle     using (90+360/14-360/7*(\n+1))},
     evaluate={\n as \nsegment  using (360/7*\n)}
    ]
    in
    {0  /red/kg/$h$,
     1  /orange/m/$c$,
     2  /yellow/s/$\Delta v$,
     3  /Green/A/$e$,
     4  /RoyalBlue/K/$k$,
     5  /violet/mol/$N_A$,
     6  /Blue/cd/$K_{\textnormal{\scriptsize cd}}$%
    }
    {\fill[draw=white,line width=2.5pt,fill=\k!90!black,domain=\angle:\Angle,variable=\t]
        plot ({2*cos(\t)},{2*sin(\t)})
        -- (0,0)
        -- cycle;
     \fill[white,opacity=.4,domain=\angle:\Angle,variable=\t]
        plot ({1.2*cos(\t)},{1.2*sin(\t)})
        -- (0,0)
        -- cycle;
     \ifnum\p=0
        \path
            node[white,rotate=180-\nsegment] at (90-\nsegment:1.6) {\l}
            node[rotate=180-\nsegment,font=\small] at (90-\nsegment:.95) {\o};
     \else
        \path
            node[white,rotate=-\nsegment] at (90-\nsegment:1.6) {\l}
            node[font=\small,rotate=-\nsegment] at (90-\nsegment:.95) {\o};
     \fi
    }
% -----------------------------------
\node[circle,font=\huge,fill=white,inner sep=7pt] (0,0) {SI};
\end{tikzpicture}
\end{document}

A:

Perhaps something like this:

You can get the colours of your logo by looking through the xcolor manual. If you really want the K, A and s rotated as in the OP this can be done but the rotations below are more natural.
Here is the code:
\documentclass[tikz, border=2mm]{standalone}

\begin{document}

  \begin{tikzpicture}
    \foreach \top/\mid/\col [count=\c,
                  evaluate=\c as \st using {360/7*(\c-1)+1},
                  evaluate=\c as \en using {360/7*\c-1},
                  evaluate=\st as \se using {(\st+\en)/2}
    ] in {m/c/orange,
          kg/h/red,
          cd/K_cd/purple,
          mol/N_A/purple,
          K/k/blue,
          A/e/green,
          S/\Delta v/yellow} {
       \draw[\col,fill=\col!80] (\st:1)--(\st:2)
           arc [start angle=\st, end angle=\en, radius=2]
           --(\en:1)
           arc [start angle=\en, end angle=\st, radius=1];
       \draw[\col,fill=\col!50] (\st:0.5)--(\st:1)
           arc [start angle=\st, end angle=\en, radius=1]
           --(\en:0.5)
           arc [start angle=\en, end angle=\st, radius=0.5];
       \node[white,rotate=\se-90,font=\bfseries] at (\se:1.5){\top};
       \node[rotate=\se-90,font=\scriptsize] at (\se:0.75){$\mid$};
    }
  \end{tikzpicture}

\end{document}


Q:

Tabla Personalizada de Auditoria SQL Server

Necesito hacer un trigger, que me inserte en una tabla auditoria, el nombre de la tabla la fecha y el tipo de accion que se realiza, este trigger debe ejecutarse a nivel base de datos luego de un UPDATE, INSERT O DELETE de cualquiera de las tablas de la BD. Hasta el momento realice esto:
SELECT top 1 s.name, s.type_desc, s.modify_date
  FROM sys.objects s
 where s.type like 'U'
 ORDER BY S.modify_date DESC

Pero no me dice que tipo de modificación se hizo. ¿Me podrían dar una mano?

A:

En SQL Server, no hay un trigger que ejecute de manera global para toda operación DML, por lo que debes escribir el o los triggers para cada una de las tablas. Voy a hacer un ejemplo escribiendo un trigger por cada operación, y solo a mencionar que podrías hacer un único trigger para las 3, pero en ese caso, debes determinar tu si se trata de un insert, update, o delete
Suponiendo que tienes una tabla de bitácora como esta:
create table BitacoraOperaciones (
   TableName sysname
 , Operacion varchar(50)
 , Fecha datetime
);

Y una tabla llamada Factura de la que quieres registra la bitácora, los triggers quedarían de esta manera:
create trigger trFacturaIns
    on Factura
 after insert
as
  insert into BitacoraOperaciones (TableName, Operacion, Fecha) values ('Factura', 'insert', getdate());
go

create trigger trFacturaUpd
    on Factura
 after update
as
  insert into BitacoraOperaciones (TableName, Operacion, Fecha) values ('Factura', 'update', getdate());
go

create trigger trFacturaIns
    on Factura
 after delete
as
  insert into BitacoraOperaciones (TableName, Operacion, Fecha) values ('Factura', 'delete', getdate());
go

A partir de este momento, cada operación insert, update o delete que se realice sobre la tabla factura, dejará un registro en la tabla de bitácora.
Dado que debes repetir este proceso para todas las tablas de la base de datos (excepto la bitácora misma).
Bonus

Como ya mencioné arriba, puedes escribir un único trigger por tabla, para las 3 operaciones, y valerte de las pseudo-tablas inserted y deleted para determinar la operación de la que se trata.
Dado que la estructura del trigger es la misma para todas las tablas, podrías valerte del diccionario de datos para generar un script SQL a partir de una consulta a la tabla sys.Tables, que te devuelva todas las tablas creadas por ti, algo como:
select s.name schema_name, t.name table_name
  from sys.tables t
       inner join sys.schemas s on s.schema_id = t.schema_id
 where t.type = 'U'
   and t.name != 'BitacoraOperaciones'


Q:

Как поставить последнюю версию git?

У меня веб-сервер на debian поставил git через apt-get install git поставилась версия 2.1.4 но на хабре была статья про версию 2.7 и в ней есть несколько интересных фишек, которые меня заинтересовали.
Как правильно обновить git на сервере до последней версии? Нужно свежие репозитории вручную добавлять? И как перед установкой узнать какая версия установится?

A:

судя по информации о пакете git в разных релизах дистрибутива debian gnu/linux, у вас стоит релиз jessie (доступная версия пакета: 1:2.1.4-2.1+deb8u4. символы 1: означают «эпоху», это «внутренняя кухня» пакетирования, upstream-версия программы здесь — 2.1.4). уточнить версию релиза можно командой:
$ lsb_release -rc
Release:        8.9
Codename:       jessie

если программа lsb_release отсутствует, то можно просто посмотреть файлы в /etc такой, например, командой (пример вывода как раз на системе с релизом jessie):
$ cat /etc/*release*
PRETTY_NAME="Debian GNU/Linux 8 (jessie)"
NAME="Debian GNU/Linux"
VERSION_ID="8"
VERSION="8 (jessie)"
ID=debian
HOME_URL="http://www.debian.org/"
SUPPORT_URL="http://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"

путей поставить более новую версию программы много. наименее «болезненный» — подключить репозиторий jessie-backports и установить имеющуюся там версию 1:2.11.0-3~bpo8+1.
согласно инструкциям с сайта backports.debian.org:

надо добавить описание репозитория:
$ echo "deb http://mirror.yandex.ru/debian jessie-backports main" | sudo tee /etc/apt/sources.list.d/jbp.list

и обновить список пакетов:
$ sudo apt-get update

теперь будет доступна для установки более новая версия пакета git (в данном случае — 1:2.11.0-3~bpo8+1 0):
$ apt-cache policy git
git:
  Installed: (none)
  Candidate: 1:2.1.4-2.1+deb8u4
  Version table:
     1:2.11.0-3~bpo8+1 0
        100 http://mirror.yandex.ru/debian/ jessie-backports/main amd64 Packages
     1:2.1.4-2.1+deb8u4 0
        500 http://security.debian.org/ jessie/updates/main amd64 Packages
     1:2.1.4-2.1+deb8u3 0
        500 http://deb.debian.org/debian/ jessie/main amd64 Packages

вот её и устанавливайте:
$ sudo apt-get install --no-install-recommends -t=jessie-backports git=1:2.11.0-3~bpo8+1

--no-install-recommends — не ствить пакеты, рекомендумые в устанавливаемом пакете (на сервере имеет смысл всегда пользоваться такой опцией или даже настроить apt на такое умолчальное поведение)
-t=jessie-backports — брать при необходимости пакеты из репозитория jessie-backports
git=1:2.11.0-3~bpo8+1 — установить пакет git именно указанной версии

в конце концов проверяем, что же установилось:
$ git --version
git version 2.11.0

A:

Можно установить Git последней версии из репозитория нестабильного дистрибутива.
echo 'deb http://mirror.yandex.ru/debian unstable main' | sudo tee /etc/apt/sources.list.d/unstable.list
sudo apt-get update
sudo apt-get install git/unstable

А чтобы нечайно вся система не обновилась до нестабильного состояния, создайте файл /etc/apt/preferences.d/unstable со следующим содержимым
Package: *
Pin: release a=unstable
Pin-Priority: 90
Package: git
Pin: release a=unstable
Pin-Priority: 200

Кстати, обратите внимание, в последней версии Git 2.14.1 была исправлена серьёзная уязвимость, настоятельно рекомендуется обновиться. Кроме того, у вас на сервере, судя по всему, стоит Debian Jessie, срок поддержки которого уже меньше года. Так же стоит обновить.


Q:

Determine whether this statement is true or false $\forall x \in {Z}, \exists y , z \in {Z} [x = 5y + 7z] $

Just beginning in Discrete math stumbled into the symbolic logic section and need some selp on this question, any input is appreciated.
$$ \forall x \in {Z}, \exists y , z \in {Z}  [x = 5y + 7z] $$
Determine whether this statement is true or false.

A:

Since $\gcd(5,7) = 1$, there exist $m,n$ such that $5m+7n = 1$. And every integer can be written as a sum of $1$ or $-1$.


Q:

Generate a random duration

I want to know how to generate a random Duration in ada.
There is my code :
time : Duration;
time := 0.8;

How can I add a random value to time between 0.5 and 1.3 ?

A:

The answer is not quite as simple as one might hope. The Ada language provides random number generators for floating point types and for discrete types. The type Duration is a fixed point type.
The following code will generate a random duration in the range of 0.500 seconds to 1.300 seconds (with a random variability to the nearest millisecond).
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Numerics.Discrete_Random;

procedure Main is

   Random_Duration : Duration;
   type Custom is range 500..1300;
   package Rand_Cust is new Ada.Numerics.Discrete_Random(Custom);
   use Rand_Cust;
   Seed : Generator;
   Num  : Custom;
begin
   -- Create the seed for the random number generator
   Reset(Seed);

   -- Generate a random integer from 500 to 1300
   Num := Random(Seed);

   -- Convert Num to a Duration value from 0.5 to 1.3
   Random_Duration := Duration(Num) / 1000.0;

   -- Output the random duration value
   Put_Line(Random_Duration'Image);
end Main;


Q:

What is the best Layout to be used While designing for multiple screens and for both landscape and portrait

Hello! I have just started playing with android layouts and i wonder if there is a general way of applying basic layout so that it will adjust itself to multiple screens and automatically to landscape view. For example:
 In the picture above, I have added some buttons. Now what i want to learn is which layout or options(like weight,gravity,alignment) to b used so that they remain the same in Every view & on every screen. Some says to use linear layout within linear and then add weight and alignment. They said that by doing this, you have flexibility to remove any button and yet no other button looses its place(unlike in relative layout). Can there be better way that will have same layout on all screens and yet flexible??

A:

RelativeLayout is very easy to use and if you learn to align the widgets in it, the layout will look the same on every screen BUT it's good for a layout that is very simple (few widgets on layout) or a layout that you know that will never change because changing on RelativeLayout is so hard and the best way is editing the XML not working on DesignView.
LinearLayout is not flexible like RelativeLayout but making change in it is so simple and other widgets will not lose their positions.
After all if you want to design layout for multiple screen size I recommend to use Fragments.


Q:

Change ActionBarSherlock background color AFTER it has been shown

I'm trying to change the action bar's background (ABS 4.2) when I navigate from page 1 to 2 of a ViewPager.
I've tried setTheme(R.style...) but as it says on the docs it should be called before the view is drawn. In fact I'm getting no changes at all.
I've created the theme using this and I want to switch between the solid and the transparent action bar style.
On the setTheme(int) I'm not using the int of the style, I've created a new theme that overrides only the android:actionBarStyle and actionBarStyle with the transparent drawable.
Is there a way to change the color on the fly?

A:

Just create your background as a drawable xml (or it can be a color if you want a simple color). And then use setBackgroundDrawable(drawable) method.
Look here: How do I make an ActionBar with a background like the YouTube app
and here: ActionBar setBackgroundDrawable() nulling background from Thread/Handler


Q:

Outlook Event API : At least one property failed validation error

I'm creating an Outlook event via Outlook API by providing following JSON input :
{
   "subject":"bla bla bla",
   "start":{
      "dateTime":"2018-01-14T17:00:00",
      "timeZone":"India Standard Time"
   },
    "Attendees": [
    {
      "EmailAddress": {
        "Address": "janets@a830edad9050849NDA1.onmicrosoft.com",
        "Name": "Janet Schorr"
      },
      "Type": "Required"
    }
  ]
}

However I'm getting the following error response :
{
    "error": {
        "code": "ErrorPropertyValidationFailure",
        "message": "At least one property failed validation.",
        "innerError": {
            "request-id": "6f3d1676-77cc-49b0-87a2-b96b6ed1f15d",
            "date": "2018-01-12T05:25:10"
        }
    }
}

If I pass the end attribute in the above JSON, the event is created successfully. The below JSON works fine :
{
   "subject":"bla bla bla",
   "start":{
      "dateTime":"2018-01-14T17:00:00",
      "timeZone":"India Standard Time"
   },
   "end":{
          "dateTime":"2018-01-14T17:00:00",
          "timeZone":"India Standard Time"
       },
    "Attendees": [
    {
      "EmailAddress": {
        "Address": "janets@a830edad9050849NDA1.onmicrosoft.com",
        "Name": "Janet Schorr"
      },
      "Type": "Required"
    }
  ]
}

Is it required to pass an end attribute for event creation? Or is there something wrong with the above JSON input?

A:

Yes, end is required. Outlook/Exchange don't support events with no end date :)


Q:

getgroups() on macOS is not returning all the supplementary groups, but instead just the primary group

'id' command does give me all the supplementary groups, but the following code is just returning the primary groups for which the use belongs:
gid_size = getgroups(0, NULL); //1 is getting returned here
grouplist = malloc(gid_size * sizeof(gid_t));
getgroups(gid_size, grouplist); //Even with gid_size>1, only primary groups is returned.

My question is, whether there's any other alternative way to get all the supplementary groups on macOS.

A:

You should be able to get up to 16 more groups by invoking initgroups() first, but even this is not ideal.
From the initgroups(3) man page:

Processes should not use the group ID numbers from getgroups(2) to determine a user's group membership.  The list obtained from getgroups() may only be a partial list of a user's group membership.  Membership checks should use the mbr_gid_to_uuid(3), mbr_uid_to_uuid(3), and mbr_check_membership(3) functions.

So if you're trying to check if the user is a member of a specific group, the mbr_*() functions are the way to go.
Note that the source code of the id command is available and based on a very quick inspection it looks like it uses the undocumented getgrouplist_2().
It looks like this is a variant of the getgrouplist() function, but without the 16-group limitation.
I don't think this function is declared in any public headers, id.c uses the prototype
int32_t getgrouplist_2(const char *, gid_t, gid_t **);


Q:

Disable DoubleClicks

I'm trying to disable double clicks on buttons and currently the only way I know is to handle the PreviewMouseDoubleClick and set the e.Handled = true.
Is there a way to do this in a button style?   Or even better, disable double clicks application wide?

A:

I would use an attached behavior (see this article).  For example, say I create an attached behavior called DisableDoubleClickAttachedBehavior which handles the double click mouse event and sets e.Handled = true.
Then, you can nicely set the property via a style in XAML:
    <Style x:Key="DisableDoubleClickStyle">
        <Setter Property="p:DisableDoubleClickAttachedBehavior.Enabled" Value="True" />
    </Style>

    <Button Style="{StaticResource DoubleClickDisabledStyle}">Hi!</Button>

Or, you can override the style for all buttons (like you wanted):
    <Style TargetType="Button">
        <Setter Property="p:DisableDoubleClickAttachedBehavior.Enabled" Value="True" />
    </Style>

I tested this and it seems to work nicely.


Q:

An Exercise in Spatial Geometry

You're on a treasure hunt for a mysterious object, and the clue you need is hidden somewhere in a giant library. You have the following clue:

uxq
pt

as well as the following piece of paper:

Someone else has tried and failed to find the object of interest, but died in the process. He did, however, manage to solve this riddle. You have his answer, but unfortunately, it's too faded to read, though you can still see some characters.

________of the_______________.

Where should you look?
EDIT: As you are trying to solve this riddle, you have one of your best gophers  workers (a.k.a. me) attempting to decipher the journal of the deceased man, Sir Tim le Death, in hopes of getting more clues. He however seems to be preoccupied with some confounded site called Puzzling.SE, so you don't expect any hints for a few more hours.
Edit 2: Your worker finally pulled through. Here is an excerpt from the diary of Sir Tim le Death.

 This puzzle was by far the hardest of the ones I have faced so far. I was tipped off to the solution by the shape of the grid of words, and the words 'spatial geometry', which for some reason appeared in my head. That, coupled with the ubiquitous presence of the number five: five letters, five rows, five columns, another twenty five letters, led me to reason that. .

That's how far he got.

A:

The clue for the mysterious object is hidden in

 Romance of the Three Kingdoms, a famous Chinese novel.

The 1st clue is

 a series of pentomino shapes, labeled with the Conway method (the other has no Q).
 The references to fives in the extra hint are a clue for this.

Combined with the square,

 You get a board filled with the corresponding pentomino (U,X,Q,P,T) from left to right. .
 Rearranging the letters from each piece in order, you get: ROMAN|CEOFT|HETHR|EEKIN|GDOMS

A:

Just a guess, I don't know how the clue fits in:

North of the shore

Why I think this:

Well first I was looking for directions (north,south,east,west) in the parchment and for North there are the letters there, and for the other directions not, although not connected. And I also tried to find other words in the parchment that might be connected and so I noticed the letters for Shore are also in the parchment in the bottom right in a connected way.


Q:

Applying Lehmann-Scheffe Theorem to an example

Let me state the theorem first:

Let $T$ be a sufficient and complete statistic for the statistical model $\mathcal{P}$  and let $\tilde{\gamma}_1$ be an unbiased estimator for the parameter $\gamma = g(\theta) \in  \mathbb{R}^k$ then the estimator
  \begin{equation}\hat{\gamma} = \hat{\gamma}(T)=E.(\tilde{\gamma}_1 \mid T)  \end{equation}
has the smallest covariance matrix among all unbiased estimators for the parameter $\gamma = g(\theta)$

Here is the example: let $\boldsymbol{X}$  be a sample of independent $N(\mu,\sigma^2)$ distributed  r.v's with parameter if interest $\theta = (\mu,\sigma^2)$
The arithmetic mean $\bar{X} = \dfrac{1}{n}\sum X_i $  and sample variance $S^2 = \dfrac{1}{n-1} \sum (X_i - \bar{X})^2$ are unbiased estimators.
We also know that  ($\sum X_i, \sum X^2_i$) is sufficient and complete for the class of all normal distributions.
....................
Iam trying to apply the theorem above therefore i first set $\tilde{\gamma}_1 = (\bar{X},S^2)^T$ and $T = (\sum X_i, \sum X^2_i)^T$
but does  $\hat{\gamma}(T)=E.(\tilde{\gamma}_1 \mid T)$ mean: $E\begin{pmatrix} \bar{X} \mid \sum X_i \\S^2 \mid \sum X^2_i  \end{pmatrix}$ ? this cannot be the right , can someone tell me what Iam doing wrong?

Let me take another example: Let $(X_1,...,X_n)$ be iid acording to  the uniform distribution over the interval $[0,\theta]$ then $\hat{\theta}_{MLE}= X_{max}$ is an unbiased estimator and $E_{\theta}X_{max} = \dfrac{n}{n+1}\theta$.
We know that $X_{max}$ is complete and sufficient , hence according to the theorem
$E[\frac{n+1}{n}X_{max} \mid X_{max} ] = \theta $ but that is just the parameter  i should get an estimator, i think I am missing something fundamental

A:

It's actually easier than you're making it. Another way you can think about Lehmann Scheffe (or really Rao-Blackwellizing as that's what you're doing here) is that you're looking for a function of the sufficient statistics that is an unbiased estimator of whatever parameter you're estimating. The important bit there is recognizing that conditioning your estimator on the sufficient statistic accomplishes the same goal as finding a function of the sufficient statistics. That means that if the thing you start with as your unbiased estimator is already a function of the sufficient statistics, you're done. You've found the UMVUE.
In the context of the normal distribution both $\bar{X}$ and $S^{2}$ are already function of the UMVUE parameter (this is where your logic was wrong. You don't condition each separately but rather on the joint statistic $\vec{T(X)}=(\sum_{i}X_{i},\sum_{i}X_{i}^{2}$ ) and so they are already the UMVUE.
As far as the uniform family goes, you're computing the expectation wrong. $E[Y|Y]=Y$


Q:

Vue & Typescript: How to avoid TS error when accessing child component's methods

I've created a custom class-based vue component and I'm trying to access its methods and/or computed properties from a parent component. There is an example in the Vue Docs that explains what I'm trying to do (https://vuejs.org/v2/guide/components-edge-cases.html#Accessing-Child-Component-Instances-amp-Child-Elements). So basically it's this
class ParentComponent extends Vue {
    someMethod() {
        (this.$refs.myChildRef as ChildComponent).focus()
    }
}

class ChildComponent extends Vue {
    focus() {
        // do something
    }
}

Now, this leads to a TS error:
"TS2339: Property 'focus' does not exist on type 'Vue'"
So apparently, typescript doesn't see that my ChildComponent has additional methods.
The code still works during runtime though, so it just appears to be a typescript issue.
Does anyone have an idea how to solve this?

A:

Option 1: Ignore it
//@ts-ignore

Option 2: Type any
const child: any = this.$refs.myChildRef;
child.focus();

Option 3: Interface, as mentioned by @LLai
interface ComponentInterface {
    focus: () => void
}

Option 4: Merge types
As a one liner as @LaLai says
(this.$refs.myChildRef as ChildComponent & { focus: () => void }).focus()

or if you need it more often
Class ParentComponent extends Vue {
    $refs: Vue["$refs"] & {
      myChildRef: { focus: () => void }
    };
}


Q:

Are Stack Overflow profiles indexed by search engines?

Is it possible to find a given user's about page by searching for information contained in it on google?
-EDIT-
I managed to find my profile by searching for text on my "about me" box, but couldn't manage to find it by searching for my full name, even if I add the words "stack overflow" to the query.

A:

Yes, if I search for the first paragraph of text in my "about me" box, my Stack Overflow user profile is the first result returned by Google, so that information does appear to be indexed.


Q:

Group by dynamic number of columns in java list of map

I have the following aList object:
    List<Map<String,String>> aList = new ArrayList<>();
    Map<String,String> mapOne= new HashMap<>();
    Map<String,String> mapTwo= new HashMap<>();
    mapOne.put("Name","John");
    mapOne.put("Age","30");
    mapOne.put("City","Kolkata");
    mapTwo.put("Name","Jack");
    mapTwo.put("Age","31");
    mapTwo.put("City","Kolkata");
    aList.add(mapOne);
    aList.add(mapTwo);

My requirement is to now return a list of results based on dynamic number of order by clause. So I wrote the following code to order by City
        Map<String, List<Collection<String>>> city = aList.stream()
            .collect(Collectors.groupingBy(map -> map.get("City")
                    , Collectors.mapping(Map::values, Collectors.toList())));
    System.out.println(city);

But as you notice, here I am able to group by only city but the user should have the choice to group by with other attributes like Name, Age and so on. So how can I return the result when I do not know which and how many attributes the user is going to choose to group by?

A:

It seems you want to return a Map<List<String>, List<Collection<String>>> when there are more then one criteria.
You can make the groupingBy classifier to return a map with the desired field's values and then group by that list.
Map<List<String>, List<Collection<String>>> city = aList.stream()
        .collect(Collectors.groupingBy(map -> List.of(map.get("City"), map.get("Age")),
                Collectors.mapping(Map::values, Collectors.toList())));
System.out.println(city);

This prints
{[Kolkata, 30]=[[Kolkata, 30, John]], [Kolkata, 31]=[[Kolkata, 31, Jack]]}

Replace List.of(..) with Arrays.asList(..) if you are using Java < 9.
To make this dynamic, you can move the logic to build the classifier function to a method and call it for each map.
private static List<String> buildClassificationFunction(Map<String,String> map, List<String> fields) {
    return fields.stream()
            .map(map::get)
            .collect(Collectors.toList());
}

List<String> fields = List.of("City", "Age"); //This will be constructed as per user's wish

Map<List<String>, List<Collection<String>>> city = aList.stream()
        .collect(Collectors.groupingBy(map ->
                    buildClassificationFunction(map, fields), //Call the function to build the list
                Collectors.mapping(Map::values, Collectors.toList())));


Q:

Show correct page name when linking in Skype, Facebook, etc

I can't figure this one out,so I just made a small web page and when i link it in skype/facebook I don't get the name of the page in skype/facebook but instead I get.
"Open classfields installation", I assume this is from a previous "web platform" that I tested in the same domain.
How do I change that? My <head> looks like this
<meta charset="utf-8">
<title>My website title</title>
<meta name="viewport" content="initial-scale=1">
<link href="images/small_icon.png" rel="icon">
<meta name="description" content="My description">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="style/stylesheet.css">

A:

First, be absolutely sure that you're sharing the right URL. I know it sounds dumb, but you should make sure that the page you expect is definitely there (and not being 302 redirected to, or in an iframe, or anything like that).
Once you've made sure of that, you can look at the page itself. From what you've written, it looks like you will probably need to add OpenGraph meta tags to help sites see the page details clearly, for example:
<meta property="og:title" content="Introducing our New Site">
<meta property="og:image" content="images/myimage.jpg">
<meta property="og:description" content="My amazing new site is amazing">

When that's done, you can ask Facebook to get the latest version (otherwise it will be a cached version) using their URL Linter:
https://developers.facebook.com/tools/debug/
You can also debug your OpenGraph tags to ensure it's picking them up, too.
I don't believe there's a way to force Skype to get a new version of the URL, but the OpenGraph meta tags may help it see what you want it to see.


Q:

Folders with custom columns in Pages library

I'd like to create a custom navigation for my site's Pages library. To do this, I'm going to organize the pages in folders, and have a few extra columns on the folders, such as a CSS class, display order, subheading, etc. I've created a new site content type, inheriting from the Folder content type. I've added the extra columns to the new folder content type, and I've added the content type to the Pages library. But when I try to create a new folder using this content type, I get a "Sorry, something went wrong" error.
Is it not possible to use custom folder content types in the Pages library? It works in a standard document library.

A:

Finally found a solution to this. The error occurred only when logged in as a site collection administrator. When logged in as a normal user, it worked.


Q:

Rails "AssociationTypeMismatch" Error

In attempts to test my models, im trying to run the following in rails console:
user.occasions << Occasion.first

getting this error:
irb(main):013:0>  user.occasions << Occasion.first
Occasion Load (0.2ms)  SELECT "occasions".* FROM "occasions" LIMIT 1
(0.0ms)  begin transaction
(0.0ms)  rollback transaction
ActiveRecord::AssociationTypeMismatch: Occasion(#70119208170580) expected, got NilClass(#70119200119960)`

Here are my model classes:
class User < ActiveRecord::Base
  has_many :occasions
  rolify
  devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable
  attr_accessible :name, :email, :password, :password_confirmation, :remember_me, :id
end

class Occasion < ActiveRecord::Base
  attr_accessible :date, :name
  belongs_to :user
end

How can I get my code fragment to work?

A:

It looks as if either:

You're attempting to add your first Occasion record to this User -- and there are no Occasion record yet created, or
You're attempting to add the first Occasion record to this User, and that record already belongs to another User.

Can you try this in the console and post the results?
foo = Occasion.first
Occasion.first.inspect


Q:

When I run the test “ rspec item_container_spec.rb ”In the console, I'll get a warning

  it 'add items into the container' do
    item1 = Item.new('kettle', price: 200)
    item2 = Item.new('kettle', price: 300)
    @box.add_item(item1)
    @box.add_item(item2)
    @box.items.should have(2).items
  end

This team might mistake? " @box.items.should have(2).items  " .
In the console, I'll get a warning
**E:\work\storeapp\spec>rspec item_container_spec.rb
F

Failures:

  1) ItemContainer add items into the container
     Failure/Error: @box.items.should have(2).items
     NoMethodError:
       undefined method `have' for #<RSpec::ExampleGroups::ItemContainer:0x2419908>
     # ./item_container_spec.rb:27:in `block (2 levels) in <top (required)>'

Finished in 0 seconds (files took 0.23234 seconds to load)
1 example, 1 failure

Failed examples:

rspec ./item_container_spec.rb:22 # ItemContainer add items into the container**

where is my mistake?

A:

I bet that you have installed rspec 3.0.
The have family of matchers was deprecated in RSpec 2.99 and has been moved to a separate rspec-collection_matchers gem as of RSpec 3.0.
Take a look here.


Q:

Handling SOAP Web services in an iPhone application-the object oriented way

I am developing an app which requires interaction with a SOAP web service, to retreive and display data. Now in the application, multiple view controllers have the possibility of calling different methods, of the web service to retreive some data.
I tried to write a common class to handle all the web service related stuff, but was unsuccessfull. The problem I am facing is as mentioned below:
I call the common class method, which has web service handling methods, from a view controller with required parameters. The common class hits the web service, parses the data and returns me the result. I receive the result and use it in my view controller. The problem here is that view controller's execution doesn't wait for the completion of execution of common class's all the delegate methods. That is my view would for exapmle navigate, without waiting for the result from the common class.
Anyone solved this problem??Hoping to get a reply soon. Thanks.

A:

Create a protocol for your view controllers to conform to, for callbacks when the data is retrieved.  The view controller implementation will refresh display as appropriate.  You can present a spinner while waiting; it is best to use the status bar activity indicator to show that this is network activity.


Q:

Measuring an electrical signal without tapping wires

I came across a product which taps into a twisted pair differential signal without making physical contact with the conductors. Instead, the wires are untwisted for a few centimeters and clamped into cylindrical sensor in a parallel orientation with a small gap between them.

What physical principles is a device like this based on and how does it work?

A:

Consider this

simulate this circuit – Schematic created using CircuitLab


Q:

How do I create a randomly distributed boolean variable for a  that will change in the model?

I am writing a model with two breeds:
sexworkers and officers
where sexworkers possess a boolean variable that is randomly distributed at the setup, but then changes at the go according to the behavior of and interaction with officers.
I use sexworkers-own [ trust? ]
in the preamble, but then I am not sure how to distribute y/n of the variable randomly across the sexworkers population. Really appreciate any input!
Thank you so much!

A:

If I understand your question correctly, you're just wanting sexworkers to randomly choose between true and false for the trust? variable on setup. If that's right, then maybe one-of will do the trick for you- for an example, run this simple setup:
breed [ sexworkers sexworker ]
sexworkers-own [ trust? ]

to setup
  ca
  create-sexworkers 1000 [
    set trust? one-of [ true false ]
  ]
  print word "% Trusting: "  ( ( count sexworkers with [ trust? ] ) /
    count sexworkers * 100 )
  reset-ticks
end

If you're looking for some kind of uneven distribution you can do simple ones using the random or random-float primitives. For example, if I want 25% of the sexworkers to start with trust? = true, I can do something like:
to setup-2
  ca
  create-sexworkers 1000 [
    ifelse random-float 1 < 0.25 [
      set trust? true
    ] [
      set trust? false
    ]
  ]
  print word "% Trusting: "  ( ( count sexworkers with [ trust? ] ) /
    count sexworkers * 100 )
  reset-ticks
end

For specific distributions, have a look at the various random reporters
For weighted randomness, have a look at the rnd extension


Q:

XSL: add a link to a substring within a string made of several TEI-XML elements

Since few days, I try to add a link to substring w[@type='verb'] within a string.
I am working on a TEI-XML transliteration of clay tablets, thus elements and @type of <w> contained in <l> are not always in the same order.
XSLT version 3.0:
<?xml version="1.0" encoding="UTF-8"?>

<xsl:template match="/">
 <xsl:apply-templates select="//div1"/>
</xsl:template>

<xsl:template match="//div1">

    <xsl:for-each select="descendant-or-self::lg/l[@n]">
       <xsl:variable name="verb1" select="w[@type='verb']"/>
       <xsl:variable name="href1" select="w[@type='verb']/@lemmaRef"/>
       <xsl:variable name="single-l" select="w[@type='coo'] | w[@type='noun'] | w[@type='verb'] | w[@type='num'] | w[@type='adv'] | w[@type='adj'] | g | name"/>

       <xsl:value-of select="$single-l"/>
       <xsl:value-of select="./@n"/>
     </xsl:for-each>

</xsl:template>

I need to add a link lemmaRef for each w[@type='verb'].
A sample of TEI — I removed @xml:id from element other than l for this example:
<lg>
    <l n="4b-5a" xml:id="ktu1-3_ii_l4b-5a">
       <w type="coo">w</w><space/>
       <w type="verb" lemmaRef="uga/verb.xsl#qry"><damage degree="medium" facs="definir"><supplied resp="KTU">t</supplied></damage>qry</w>
       <g>.</g>
       <w type="noun" lemmaRef="uga/noun.xsl#ġlm">ġlmm</w>
       <lb/><w>b</w><space/>
       <w type="noun" lemmaRef="uga/noun.xsl#št">št</w>
       <g>.</g>
       <w type="noun" lemmaRef="uga/noun.xsl#ġr">ġr</w>
       <g>.</g>
    </l>
 </lg>

I need to display:

w tqry . ġlmm št . ġr .4b-5a

"tqry" is a verb contained in <l>.
How can I do in XSLT to be able to display <xsl:value-of select="$verb1"/>. I tried replace of $single-l or to define a new variable of the previous XSLT code, but it doesn't work. I have tried also with key but I think I still have a problem of undertanding...
In advance, thank you for your kind advice.

A:

I don't think you should try to build a string and then to insert markup there, it seems it should be possible to simply process the child elements and then match on the lg/l[@n]/w[@type = 'verb'] to transform it to a HTML hyperlink:
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:xs="http://www.w3.org/2001/XMLSchema"
    exclude-result-prefixes="xs"
    version="3.0">

  <xsl:output method="html" indent="yes" html-version="5"/>
  <xsl:strip-space elements="*"/>

  <xsl:template match="/">

        <title>Example</title>

      <xsl:apply-templates/>

  </xsl:template>

  <xsl:template match="div">

              <xsl:apply-templates select=".//lg/l[@n]"/>

  </xsl:template>

  <xsl:template match="lg/l[@n]">

          <xsl:apply-templates/>

              <xsl:value-of select="@n"/>

  </xsl:template>

  <xsl:template match="lg/l[@n]/w[@type = 'verb']">

          <xsl:apply-templates/>

  </xsl:template>

  <xsl:template match="space">
      <xsl:text> </xsl:text>
  </xsl:template>

</xsl:stylesheet>

This currently does not quite produce the wanted result but

w tqry.ġlmmb št.ġr.4b-5a

instead but if there is content from an element you don't need or want you can add an empty template for that so that it doesn't produce any output (e.g. <xsl:template match="lg/l[@n]/w[not(@type)]"/>).
I am not sure whether there is also important white space missing and what are the rules to insert it, you might need to explain that.
Online sample is at http://xsltfiddle.liberty-development.net/b4GWV5/1.


Q:

C Pointer Write Error

 void fileNameProcess(char * inputName){
             int size =strlen(inputName);
             bool change=false;
             char * name=inputName;

             for(int i =0; i<size; i++){
                 char temp=* (name+i);
                 if(temp<0x10||temp>0x5b){
                     change=true;
                 }else if(0x19<temp<0x21){
                     change=true;
                 }else if(0x3a<temp<0x41){
                     change=true;
                 }
                 if(change){
                     //*(name+i)='_';
                     memset(name+i, '_', 1);
                     change=false;
                 }
             }

         }

it breaks when i try to set a character in a string (memeset), but i dont understand why it doesnt allow me to do that? why i can allow access to read it but couldnt modify it?
can anyone explain it in memory aspect. i guess it is because the string is passed into the function. but as long as i know the memeory location, i could set it right?
thanks
char * filename= strdup("try1.mat");
    writter.locate(filename);

in locate it assign filename to class memeber char* filepath

A:

This:
if(1 < variable < 2)

Probably doesn't do what you want. Use:
if(1 < variable && variable < 2)

edit
if(1 < variable < 2) evaluates like this:
if( (1 < variable) < 2)
if( (true) < 2)
//given true is often* assigned a value of 1 this will always be true and
if( (false) < 2)
//false is always zero this will also be true

*I don't think this is required by the standard so don't rely on it.

A:

Most probably you are giving a constant literal string as the input:
char * str = "test";
fileNameProcess(str);

If that is the case, try:
char * str = strdup("test");
fileNameProcess(str);

A:

I'm guessing that you're passing in a string literal to the function:
fileNameProcess( "myfile.dat");

String literals cannot be modified.
However, you could pass in an array that's initialized by a literal:
char fname[] = "myfile.dat";

fileNameProcess( fname);

As with any string handling routines, take care that when you modify the passed in string that you keep it properly terminated and don't write past the end of the buffer.


Q:

How to allow non-root user to listen on privileged port?

I want syslog to run as a non-root user on my linux box. That makes it impossible for it to bind to port 514 - because that's a privileged port. Is there any way I can grant non-admin user "foo" the ability to listen on port 514?

A:

setcap 'cap_net_bind_service=+ep' /path/to/syslogd

Requires a not-ancient linux kernel (2.6.24 or later)

A:

You could configure rinetd (available in most, if not all, distribution's standard repositories) to listen on port 514 and forward connections to some other port (above 1024, say 1514). That way the non-privileged user process can listen on 1514 and rinetd will forward connections so it appears to be listening on 514.
This will only work for TCP connections though. If you need to support UDP (or anything else) this way as well as or instead of TCP, then you can use iptables translation rules to achieve the same effect.