Q:

According to Jehovah's Witnesses, does Jesus make the same claim as God, that he is the "first and the last,"?

Isaiah 44:6, "Thus says the Lord, the King of Israel And his Redeemer, the Lord of host; I am the first and I am the last, And there is no God besides Me."

But Jesus Christ makes the same claim in Revelation:

Revelation 1:8: I am the Alpha and the Omega, says the Lord God, who is and who was and who is to come, the Almighty.
Revelation 1:17-18: And when I saw Him, I fell at His feet as a dead man. And He laid His right hand upon me, saying, "Do not be afraid; I am the first and the last. I am He who lives, and was dead, and behold, I am alive forevermore. Amen. And I have the keys of Hades and of Death."
Revelation 21:5-6: And He who sits on the throne said, "Behold I am making all things new." And He said to me, "It is done I am the Alpha and Omega."

The point or the scope of my question has to do with the "eternality" of Jesus Christ. And since He is eternal according to John 1:1-3 He is also the one who will make all things new.
According to Jehovah's Witnesses, how and why does Jesus make these statements, when according to their teaching he is not one being with God the Father?

A:

Although you specifically ask about the designation ‘First and Last’, there is a clear biblical link to that and the oft-concurrent designation ‘Alpha and Omega’, which is abundantly clear in the book of Revelation, and in JW literature. See https://www.jw.org/en/bible-teachings/questions/alpha-omega/ Who or What Is “the Alpha and the Omega”?

“The Alpha and the Omega” refers to Jehovah God, the Almighty. This
  term occurs three times in the Bible.—Revelation 1:8; 21:6; 22:13.
  …Why does God call himself “the Alpha and the Omega”?  Alpha and omega
  are the first and last letters of the alphabet in Greek, the language
  used to write the part of the Bible commonly called the New Testament,
  which includes the book of Revelation. The respective positions of
  these letters in the Greek alphabet are used to illustrate that
  Jehovah alone is the beginning and the end. (Revelation 21:6) He was
  Almighty God in the infinite past, and he will continue to be Almighty
  God forever. He is the only one who is “from everlasting to
  everlasting.”—Psalm 90:2. Who is “the first and the last”?  The Bible
  applies this term both to Jehovah God and to his Son, Jesus, but with
  different meanings…”

More on that later.
Here is another official JW link, ‘Highlights From the Book of Revelation’, 15 January 2009 Watchtower - https://wol.jw.org/en/wol/d/r1/lp-e/2009046#h=11:0-12:0  However, I used the 1988 JW publication “Insight on the Scriptures” Vol. 1  which states (in agreement) that only Jehovah God has the title ‘Alpha and Omega’ in Rev. 1:8. This is because the verse goes on to say this one is “the Almighty” (page 81). JW teaching is that only Jehovah is the Almighty God, and Jesus is the Mighty God (Isaiah 9:6)  This explains two points in their article on ‘Alpha and Omega’:
(1) “Although the preceding verse [7] speaks of Christ Jesus, it is clear that in verse 8 the application of the title is to ‘the Almighty’ God.” Then the article cites Barnes’ Notes on the New Testament (1974) in support, as it apparently states, “It cannot be absolutely certain that the writer meant to refer to the Lord Jesus specifically here… There is no real incongruity in supposing, also, that the writer here meant to refer to God as such.” Thus, the JWs feel justified in adding the word ‘Jehovah’ before ‘God’ in their New World Translation of Rev. 1:8. citing 7 translations dating from 1599 to 1961. [See their 1969 KIT for that.]
(2) ‘Insight Vol. I’ also acknowledges an “additional occurrence of this phrase in the King James rendering of Rev. 1:11”. But the JW view is that some Greek manuscripts, including the Alexandrine, Sinaitic, and Codex Ephraemi rescriptus, do not have the trumpet sounding “I am the Alpha and Omega, the first and the last”. They therefore omit this, as do many other modern translations, which is possibly why you did not include verse 11 in your question.
The ‘Insight’ book then goes on to deal with Rev. 21:6 where it says “I am the Alpha and Omega, the beginning and the end,” dismissing that as applicable to Jesus because verse 7 adds, “and I shall be his God and he will be my son”. JW theology acknowledges Jesus as the Mighty God of Isaiah 9:6, but refuses to have him elevated from what they take to be a secondary level of deity, to a God who is to be worshipped. See Isaiah’s Prophecy Vol. I pp130-131 (published 2000). The ‘Insight’ book, however, does not say that but gives as its reason for applying verse 6 to Jehovah:

“Inasmuch as Jesus referred to those who are joint heirs with him in
  his Kingdom as ‘brothers’, not ‘sons’, the speaker must be Jesus’
  heavenly Father,  Jehovah God.” (The JW link above agrees with this.)

You particularly want to know how “the eternality” of Jesus Christ (John 1:1-3) relates to Jesus being the first and the last. It is common knowledge that the NWT renders John 1:1 as ‘the Word was a god’, meaning the Word cannot be of the same Being as God. JWs do not believe in “the eternality” of Jesus Christ and so offer an interpretation of him being ‘the first and the last’ that only refers to his unique,  one-of-a-kind resurrection. This is why JW doctrine, that the Word was created by Jehovah and so had a starting point in time, has to be explained as only referring to Jehovah raising Jesus to life in a unique way (as the ‘first fruits’ of those who sleep in death), and that as nobody else will be so resurrected, Jesus is ‘first and last’ in that sense only.
Isaiah 44:6 is dealt with in the JW book “Isaiah’s Prophecy” Vol. II pp64-65 (published 2001). It is not quoted in isolation but includes verses 7 & 8 to give context. Then the paragraph following explains how Jehovah is challenging the [false] gods to present their case, adding,

“Only ‘the first and the last,’ who existed before all the false gods
  were thought of and will still be there when they are long forgotten,
  can do such a thing. His people need not fear to bear witness to this
  truth, since they have the support of Jehovah, who is as firm and
  stable as a massive rock!”

It does not say a word about Jesus. That would fit in with the JW stance that Jesus being ‘first and last’ is only with respect to his unique resurrection – something that happened TO him, and not due to his BEING the first and the last. As JWs insist that only Jehovah is eternal (with no starting point in time) they agree he is eternal in his un-created being, but that Jesus is a created (hence, different) being: “The Bible applies this term both to Jehovah God and to his Son, Jesus, but with different meanings” as that first JW link says. I give this answer purely to answer your question, without agreeing with the JW stance.


Q:

How to merge two eloquent and load relationships

How can I merge two eloquent collections without losing any data and load relationship after that?
//I have two collections

$e1=Colour::find(1,3,7);
$e2=Colour::find(31,33,88);

//I need the following output

$merged=$e1->merge($e2)->load('relation');

When I performed the above merge, the first collection overwrites the second.
Please, give me a solution.

A:

Push elements of $e2 to $e1 collection then use $e1 as you see fit.
foreach ($e2 as $e) {
    $e1->push($e);
}
$e1->load('relation');


Q:

Ending of Ready Player One - Wade's reaction

Spoilers might be ahead -
Before getting the egg Wade explains as why he wouldn't sign the contract and how James made a mistake before. And when he gets the Egg in the end, a tear rolls down his cheek. So what made his eyes moist?
Was it just him getting overwhelmed? Or was it because he saved Oasis from IOI? Or did he sympathized with James?

A:

The same reason that Olympic champions weep when they're on the winner's podium - years and years of hard work and blood/sweat/tears have culminated into them being the best in the world at what they do - it's a release of emotions.
Against all the odds, Wade has beaten the worlds hardest contest after years and years of effort against the rest of the world.
He's also saved the oasis from IOI, he's met (sort of) his idol (Halliday), he's rich and powerful beyond his wildest dreams, and he's ensured the safety of his newly found love (as well as saving the lives of the rest of his friends).
So yes, it's a fairly emotional moment....
...or he just stepped on a LEGO brick, this generally brings a tear to anyone's eye.


Q:

How can i add indexing in mysql view table

CREATE VIEW test AS SELECT
wp_posts.ID,
wp_posts.post_title,
STR_TO_DATE(pm1.meta_value,'%c/%e/%Y') AS expiration_date,
pm2.meta_value AS ceadmin_email,
pm3.meta_value AS student_email,
pm4.meta_value AS email,
pm5.meta_value AS cefirst_name,
pm6.meta_value AS celast_name
FROM wp_posts
LEFT JOIN wp_postmeta AS pm1 ON (wp_posts.ID=pm1.post_id AND pm1.meta_key='ceexpiration_date')
LEFT JOIN wp_postmeta AS pm2 ON (wp_posts.ID=pm2.post_id AND pm2.meta_key='ceadmin_email')
LEFT JOIN wp_postmeta AS pm3 ON (wp_posts.ID=pm3.post_id AND pm3.meta_key='secondary_email')
LEFT JOIN wp_postmeta AS pm4 ON (wp_posts.ID=pm4.post_id AND pm4.meta_key='email')
LEFT JOIN wp_postmeta AS pm5 ON (wp_posts.ID=pm5.post_id AND pm5.meta_key='cefirst_name')
LEFT JOIN wp_postmeta AS pm6 ON (wp_posts.ID=pm6.post_id AND pm6.meta_key='celast_name')
WHERE wp_posts.constraint_type='PRIMARY KEY'
AND wp_posts.table_schema=DATABASE()
AND wp_posts.table_name='owalog'; wp_posts.post_type='student_certificates' AND pm2.meta_value IN (SELECT user_email FROM supervisorcount)

A:

From the MySQL documentation on views:

It is not possible to create an index on a view.

So, you really have two options available here:

You may tune the query underlying the view, by adding appropriate indices on the actual tables involved, or
You may create a temporary table using the query behind the view, and then index that directly.

MySQL does not have any formal materialized view, but a temporary table comes pretty close to this.  Note that in general a (non materialized) view will perform only as well as the underlying query.


Q:

Why don't right-wing dictators crown themselves king?

So, something that seems odd to me is that while there are a number of dictatorships around the world, very few of them have the dictator deciding to crown themselves as a monarch, despite the veneer of legitimacy that doing so might grant them (e.g. divine right to rule). The Catholic Church has been crowning monarchs for literally over a thousand years, so there doesn't seem an obvious reason why right-wing South American dictators from Catholic-dominated countries couldn't get themselves crowned as king.
Despite this, there doesn't seem to be any examples where a dictator has gotten themselves crowned as king. Why is this? Left-wing dictators have an obvious reason why, since communist ideology is anti-monarchist, but why don't right-wing dictators crown themselves as king?
Note that I'm asking about modern dictators who don't have any previous royal lineage, rather than monarchies established by individuals from existing royal lines (e.g. Saudi Arabia).

A:

tl;dr: Because the middle ages are over.
You no longer want to be King - you want to be President
Most of the world used to be ruled by kings and emperors, but today the only remaining absolute hereditary monarchies in the world are Saudi-Arabia, Brunei, Qatar, Oman and Eswatini. There are still lots of countries which are still officially hereditary monarchies (like parts of Europe or the Commonwealth realms), but the role of the monarch in these countries is mostly symbolic. The true political leader is the head of the government.
So if a dictator declares themselves monarch, then they risk the same fate as monarchies all over the world. At best having their power eroded to a level where they are just a figurehead for the elected government, at worst being ousted in favor of a non-hereditary government when they become cumbersome.
You don't want heredity legitimation, you want democratic legitimation
In the modern world, having regular elections (even if they aren't fair elections) and thus upholding the appearance of a democracy beats wearing a crown. It also makes it easier for foreign politicians from democratic countries to recognize your government as legitimate. And with most of the international superpowers in the world being democratic countries, this really matters.
The Catholic Church isn't what it used to be
The Catholic church used to crown kings and emperors during the middle ages. But it has no longer provided that service for over 200 years now. The last political leader crowned by a pope was Napoleon in 1804 (and that was more a coronation with a pope than by a pope).
With most political power being secular in nature, the authority of the Catholic church is relegated to religious and moral matters. Further, I couldn't really imagine any of the three popes I experienced during my lifetime (John-Paul II, Benedict XVI, Francis) to legitimize a dictator by crowning them king.

A:

The short answer would be: Because even dictators cannot simply do whatever they want.
Let's for example take a look at one of the oldest dictators of history: Caesar Augustus.
Now, technically Augustus was a king in all but name, but couldn't effectively call himself one, because the Romans, since having deposed of their last king centuries ago, despised the mere thought of having a king once again.
Therefore Augustus wisely chose to refrain from crowning himself king and instead carried
the title "Princeps" and proclaimed to be merely the "first among equals" amongst the citizenry of Rome.
Had he chosen to crown himself king, Rome could have potentially fallen into another civil war once again, given the fact that his father had been slain under the accusation of having the intent to crown himself king.
Ironically enough, merely a few decades later the cognomen "Caesar" had become the de facto royal title of the Roman Emperor. In fact, the german language still uses the word "Kaiser", which is directly derived from and pronounced like "Caesar", in the same way that english uses "emperor".
The point is, as said in the beginning: Even dicators with an enormous amount power cannot simply do whatever they want: Even they have to keep up the appearance as in the example above and keep their cronies satisfied, just as the roman emperors had to keep the Praetorian Guard happy, lest they be deposed of.
That being said, the short paragraph about the title "Caesar" was not merely anecdotal, but illustrates how a long lasting dictatorship might eventually drop the appearance and become an open monarchy, provided it manages to successfully establish a stable line of succession, which of course is THE core aspect of a regular monarchy.
The main issue today however seems to be exactly that: Most dictatorships simply don't last long enough and/or don't manage to establish a hereditary line of succession, but in theory it is of course possible:
Should Assad manage to stay in power and have one of his children inherited his position, as he inherited it from his father, and so forth and forth, then one day in the future Syria might be a de facto monarchy, even though the royal title might not necessarily be "king", but something else.
In fact, the better example might be North Korea, where the title of "Supreme Leader" is currently held in the third generation.

A:

(I'll assume that these dictators you're referring to actually want absolute power. It's not obvious that this is the case in general.)
The following quote is from Harry Potter and the Deathly Hallows. For context: Lord Voldemort is the "big bad guy", the Ministry of Magic is effectively the government, and the Minister of Magic is the head of that government (or the "king" in the context of your question). Voldemort had taken over the Ministry, but didn't appoint himself as Minister of Magic.

Ron: Why didn't Voldemort declare himself Minister of Magic?
Lupin (laughing): He doesn't need to,Ron. Effectively he is the minister, but why should he sit behind a desk at the ministry? His puppet, Pius Thicknesse, is taking care of everyday business, leaving Voldemort free to extend his power beyond the ministry. Naturally many people have deduced what has happened: there has been such a dramatic change in Ministry policy in the last few days, and many are whispering that Voldemort is behind it. However, that is the point: they whisper. They daren't confide in each other, not knowing whom to trust; they are scared to speak out, in case their suspicions are true and their families are targeted. Yes, Voldemort is playing a very clever game. Declaring himself might have provoked open rebellion; remaining masked has created confusion, uncertainty and fear.

In other words: They could, but there's no reason to do so when they don't actually gain anything but are risking open rebellion.


Q:

How can I tell if a Vue component is unmounted to prevent async function accessing unmounted component's data?

Please see this minimum example
import Vue from 'vue';

Vue.extend({
  data() {
    return {
      name: 'James',
    };
  },
  methods: {
    greet() {
      setTimeout(() => {
        const componentIsUnmounted = ???; // How do I tell if component is unmounted?

        if (!componentIsUnmounted) {
          console.log(this.name);
        }
      }, 300);
    },
  },
});

As you can see, I have a component with an async function, it will be triggered after 300ms when you called it, by that time, the Vue component might be unmounted.
I think I can do this by storing a flag in the global via Lodash's uniqueID() function to create a unique ID at mounted() and beforeDestroyed().
Is there another easyier way to do that?

A:

I think that it would be best if you can control the timeout (using clearTimeout(), for example, as suggested on the comments). In your case, as you're using a debounce, depending on what lib you're using, you might not have that control.
In this case, one suggestion is to mix Node.contains with vm.$el. As follows:
export default {
  methods: {
    greet() {
      const isUnmounted = !document.body.contains(this.$el)
    }
  }
}

Other alternative is to use destroyed lifecycle to control this state internally.

I've provided a guiding example that might help you: https://codesandbox.io/s/smoosh-frost-fdisj.

Hope it helps!


Q:

How to avoid specific paths in allShortestPath function?

The graph is supposed to represent a system similar to github, with commits (commit1, commit2, commit3 and commit4), documents (d1, d2) and changes on those documents (green nodes).
I am trying to use CYPHER to get all the documents values at a specific commit. In other words, I am trying to find the shortest path between the specific commit and each of the documents on my graph, but avoiding some paths.
Imagine if I am on commit4, d1 should be equal to foo2 and d2 should be equal to spain. This could be solved with the following CYPHER query:
MATCH (c:Commit {id: 'commit4'})-[:FOLLOWS|CHANGED*]->(:Value)<-[:EQUALS]-(d:Document), p = allShortestPaths((c)-[*]-(d))
RETURN p

This would give the following response:

Now, imagine that I want to be get the values on commit3. The request should not return any changes from the commit4. However, if I use the allShortestPaths function the way I do, it will go through commit4 since it is actually the shortest path to d1 and return the exact same response than if my starting node was commit4.
MATCH (c:Commit {id: 'commit3'})-[:FOLLOWS|CHANGED*]->(:Value)<-[:EQUALS]-(d:Document), p = allShortestPaths((c)-[*]-(d))
RETURN p

How could I avoid the allShortestPath function to go through a [:FOLLOWS]->(c) relationship and solve my problem?

A:

From what you explained, I understand that you don't want to traverse the FOLLOWS edge in the opposite direction of the edge. To do so you can use cypher projection in algo.shortestPath:
MATCH (start:Commit {name:'commit4'})
MATCH (end:Document)
CALL algo.shortestPath.stream(start, end, null,{
nodeQuery:'MATCH (n) RETURN id(n) AS id',
relationshipQuery:'MATCH (n)-[r:FOLLOWS|CHANGED]->(p) RETURN id(n) AS source, id(p) AS target UNION MATCH (n)-[r:EQUALS]-(p) RETURN id(n) AS source, id(p) AS target',
graph:'cypher'})
YIELD nodeId, cost
WITH end as document, algo.asNode(nodeId) AS value WHERE "Value" in labels(value)
return document, value

Replace "commit4" with any other commit name.


Q:

Python scikit svm "ValueError: X has 62 features per sample; expecting 337"

Playing around with Python's scikit SVM Linear Support Vector Classification and I'm running into an error when I attempt to make predictions:
ten_percent = len(raw_routes_data) / 10

# Training
training_label = all_labels[ten_percent:]
training_raw_data = raw_routes_data[ten_percent:]
training_data = DictVectorizer().fit_transform(training_raw_data).toarray()

learner = svm.LinearSVC()
learner.fit(training_data, training_label)

# Predicting
testing_label = all_labels[:ten_percent]
testing_raw_data = raw_routes_data[:ten_percent]
testing_data = DictVectorizer().fit_transform(testing_raw_data).toarray()

testing_predictions = learner.predict(testing_data)

m = metrics.classification_report(testing_label, testing_predictions)

The raw_data is represented as a Python dictionary with categories of arrival times for various travel options and categories for weather data:
{'72_bus': '6.0 to 11.0', 'uber_eta': '2.0 to 3.5', 'tweet_delay': '0', 'c_train': '1.0 to 4.0', 'weather': 'Overcast', '52_bus': '16.0 to 21.0', 'uber_surging': '1.0 to 1.15', 'd_train': '17.6666666667 to 21.8333333333', 'feels_like': '27.6666666667 to 32.5'}

When I train and fit the training data I use a Dictionary Vectorizer on 90% of the data and turning it into an array.
The provided testing_labels are represented as:
[1,2,3,3,1,2,3, ... ]

It's when I attempt to use the LinearSVC to predict that I'm informed:
ValueError: X has 27 features per sample; expecting 46

What am I missing here? Obviously it is the way I fit and transform the data.

A:

The problem is that you creating and fitting different DictVectorizer for train and for test.
You should create and fit only one DictVectorizer using train data and use transform method of this object on your testing data to create feature representation of your test data.


Q:

Using Symfony's serializer library to use a value in a sub-object

I am using https://jmsyst.com/libs/serializer standalone and not with Symfony. I have two entity classes as follows where SomeProperty is a sub-object to MyEntity:
class MyEntity {
    private $id, $name, $some_property;
    public function getId() {return $this->id;}
    public function getName(){return $this->name;}
    public function getSomeProperty(){return $this->some_property;}
}

class SomeProperty {
    private some_sub_property;
    public function getSomeSubProperty(){return $this->some_sub_property;}
}

I can successfully perform the default serialization of the object which results in  the following JSON:
{
    "id":123,
    "name":"foo",
    "some_property" : {
        "some_sub_property: "bar"
    }
}

But instead, I wish to include a property in the SomeProperty sub-object at the same level as the other properties in MyEntity such as:
{
    "id":123,
    "name":"foo",
    "mySubproperty": "bar"
}

I've tried about one hundred variations of XML to define the serialization and they are all somewhat similar to the follows, however, they result in including id and name but not mySubproperty.
<?xml version="1.0" encoding="UTF-8" ?>
<serializer>
    <class name="NS\App\Domain\Entity\MyEntity">
        <xml-namespace prefix="atom" uri="http://www.w3.org/2005/Atom"/>
        <property name="id"/>
        <property name="name"/>
        <virtual-property
            method="getSomeProperty"
            access-type="public_method"
            accessor-getter="getSomeSubProperty"
            serialized-name="mySubproperty"
        />
    </class>
</serializer>

How is this accomplished?  Thank you

A:

Use a @VirtualProperty annotation if it's not a field you use elsewhere. If you use it, add @Exclude on getSomeProperty() and add a virtual property with another name.
    /**
     * @Serializer\VirtualProperty()
     */
    public function getSomeProperty()
    {
        return $this->getSomeSubProperty();
    }


Q:

Is Expression Blend/Studio good for Desktop Application?

I am building a desktop application using VS2010 C#.  I plan to design and implement my own ribbon and redesign other UI controls graphically. Would Expression Studio/Blend be useful for my purpose? I have not used the software and from the web it says it's mainly for Web.

A:

Expression Web is for web design. Expression Blend is for Windows Presentation Foundation and Silverlight.
If you want to use Windows Forms then you have to either do it all by hand or use the Visual Studio 2010 designer but if you want to use WPF then Blend is the way to go.


Q:

Javascript - Using Concatenated String in Regex

I'm trying to find if a given string of digits contains a sequence of three identical digits.
using a for loop, each digit in the string gets its own representation of a three digit sequence which is then checked against the string using Regex:
var str = "6854777322"

for(var i=0; i<str.length; i++)
{
   seqToCompare = str[i] + str[i] + str[i];
   var re = new RegExp(seqToCompare, "g");
   if(str.match(re).length == 1)
   {
      match = str[i];
   }
}
console.log(match)

The result should be seven (if I put 777 in seqToCompare, it would work), but it looks like the concatenation causes it to fail. Console shows "cannot read property length for null".
You can test it here - https://jsfiddle.net/kwnL7vLs/
I tried .toString, setting seqToCompare in Regex format and even parsing it as int (out of desperation for not knowing what to do anymore...)

A:

Rather than looping over each character, you can use a simple regex to get a digit that is repeated 3 times:
/(\d)(?=\1{2})/

(\d) - Here we match a digit and group it in captured group #1
(?=\1{2}) is lookahead that asserts same captured group #1 is repeated twice ahead of current position

RegEx Demo


Q:

Correctly using else for an if condition inside foreach loop (PHP)

Recently, I was trying to use if condition inside foreach loop .. and it has been done without issues..
But, when I use else inside the loop .. the if condition becomes fully ignored and the else condition will be executed without checking the if condition ..
Here is the loop :
foreach ($ids as $id) {

    if (substr($id, 0, 8) === $first8) {
        $matched = true;
        header("Location: success.php");
        break;
    } else {
        echo "<script language=\"JavaScript\">\n";
        echo "alert('Entered ID is incorrect');\n";
        echo "window.location='index.html?loginFailed=true&reason=wrongID'";
        echo "</script>";
        exit;
    }

 }

Now when the user enter his ID.. the else condition will be executed without if condition.. weather the ID is correct or not .. Noting that when I remove the else the code is working perfectly if the ID is correct..
Any ideas?

A:

Your code check only first element of the array. Use this code:
if(in_array($first8, array_map(function($id){
    return substr($id, 0, 8);
}, $ids))) {
    header("Location: success.php");
} else {
    echo "<script language=\"JavaScript\">\n";
    echo "alert('Entered ID is incorrect');\n";
    echo "window.location='index.html?loginFailed=true&reason=wrongID'";
    echo "</script>";
    exit;
}


Q:

Order of procedures in assembly

In what order should asm procedures go in source file: from inner to outer or in reverse? Where should the main code (which is not within proc) go: near the beginning or end of file? Are there objective criteria to choose, not merely convention?

A:

There is no convention; normally put related functions near each other in the source.  Basically the same as you would in C or any other language.  As far as readability, there's nothing special about asm that overrides this, except that asm functions are usually not very short (because nothing is going to inline them for you, and you don't want actual call/ret overhead all over the place).
If you're sacrificing performance to get "small functions" for readability, asm is the wrong language; if your project is that big, let a compiler do it.  Making a block of code a callable function instead of a macro should be motivated by I-cache footprint and how often it's used.

Or for performance, group "hot" functions together to they're in the same iTLB page, and even the same L1 instruction cache line for small functions or at boundaries between end of one, start of next.  e.g. group together functions that call each other or are often called right after each other.
If you want source order to be different from binary order, you can put "cold" functions (called once at startup or shutdown) in a section like .text.startup instead of the usual .text section; GCC does this for main for example with this instead of a usual .text directive
.section        .text.startup,"ax",@progbits
.globl main
main:
  ...
.text            # shorthand for .section .text
other_function:

("ax",@progbits for an ELF target means exec permission, and that the section should be mapped into process memory instead of just sitting in the executable on disk without getting mapped by the program loader.  Or more specifically, linked into an ELF segment with those properties).
Try it on Godbolt if you're curious.

here should the main code (which is not within proc) go

Huh?  Usually you put a label on the entry point even though it's not a "function" per-se.  Often you only write a main (which is a function) and let CRT startup code call it.


Q:

Add value to nested dictionaries

If I have:
var dict = new Dictionary<Dictionary<string, string>, Dictionary<int, int>>();

How can I add values to the nested Dictionaries. What is the proper syntax to do that?
dict.Add(...)

I am aware of the syntax for >. But not for two nested dictionaries in one.

A:

Not that using a dictionary as a key for another dictionary makes much sense..
var dict1 = new Dictionary<string, string>();

var dict2 = new Dictionary<int, int>();

dict.Add(dict1, dict2);

or

dict.Add(new Dictionary<string, string>(), new Dictionary<int, int>());

or with some data using initializers
dict.Add(new Dictionary<string, string>() { { "test", "test"} }, new Dictionary<int, int>() { {1, 1}});


Q:

Adding Columns to an Existing External Content Type in SharePoint 2010 Designer

I was able to create an ECT and display the first three columns of data that I used to create the ECT.
The only issue I am running into is that I want to add more columns to the existing ECT in designer (that I created), but apparently either I have to recreate the ECT unless there is a workaround. One of the articles I found indicated it may not be possible to add columns to an existing ECT because the BCS has certain limitations and this may be one of them. However, when I went to The Portal and noticed under (Lists-> Employees-> list (in the Ribbon) -> List Settings -> ‘Columns’ heading you can see the other columns that I added to the ECT, but is not displaying on the portal for 'Employees'.  So, we know the ECT has been created and other columns added (that don't display for the end user to view), but it’s a matter of whether it needs to be re-created to pull the rest of the columns in the site to be viewable to the end user.
Many thanks in advance for your assistance. :)

A:

Ok, first of all the correct term is content, not columns. However this is what I did (with a link included for detail).
Recreated the ECT, but learned the ECT and Parameters can be changed/updated via list in SharePoint Designer. Here is the link where this information was learned:
http://www.sharepoint-videos.com/sp10-webinar-leveraging-business-connectivity-services/


Q:

Arduino HID keyboard does not work

I'm using a ItsyBitsy 32u4, Adafruit says it can act as a USB HID keyboard. The mc is based on the 32u4 which the Keyboard docs say are supported.
I have a simple sketch that prints "A" every second and should press "A". When I upload the sketch and connect to the serial port I see the print output but I don't get any key presses.
Any ideas? I'm on linux, I suspect that the controller doesn't register as a HID device, maybe I need UDEV rules or drivers?
EDIT: the keyboard works on a different computer.
#include <Keyboard.h>
void setup() {
  Serial.begin(9600);
  Keyboard.begin();
  Serial.println("Start");
}

void loop() {
  Serial.println("a");
  Keyboard.write('a');
  delay(1000);
}

A:

There was some issue with my laptop, not controller or the sketch.
I tried the my board with another computer and it worked. I tried a commercial keyboard on my first computer it also didn't work.
Both keyboards work after a reboot.


Q:

git log --since date string parsing

I was looking through some logs in a submodule today (somewhat furiously) and typed some errors into the dates in the command
git log --since="2019-12-31" --oneline | wc -l
      90

and instead of typing that I typed,
git log --since="2019-12=31" --oneline | wc -l
    2147

I was alarmed by the difference is count which is why I was able to notice the error immediately. However, I'm unclear as to what the behavior is in this case. Is this a bug or is this expected behavior for git log?
I would expect an error in parsing but it looks like the logs go back to January or February of 2019.

A:

It appears that Git's date parsing just stops when it gets to a part it can't understand.  For example "2015-13" is understood as "2015", as is "2015-4444".
In your case, it's treating "2019-12=31" as "2019".  And then a second weird "feature" kicks in: --since 2019 does not mean --since 2019-01-01, it means "since today's date in 2019".  So the meaning of your --since 2019-12-31 will actually change throughout each year when you run it!
What seems to be happening is:

Generate the current date-time (in your time zone).
Replace the parts you specified in --since, ignoring the month and day part if the parser cannot decide how to parse it.

Note that even the simple and "obviously correct" git log --since 2019-12-31 does not really do what one might expect, because it shows commits since the current time on that day, not since midnight.  So unless you specify a full date-time string, there will always be some dependency on the time when the command is executed.


Q:

Re arrange images in a stack panel using drag and drop

How i can re-arrange images inside a stackpanel / Grid, using drag and drop, In my sample app i have 4 images. I need to re arrange these images through drag and drop. I found a solution for doing the same inside listbox. But i can't use that in my application. I am new to the technology so someone please help me to implement the same.

A:

You can use the code used in my question for implementing the same. It will works fine for me. Please check the code and let me know if any issues.
Answer Link


Q:

Minecraft META-INF File

I have been watching videos about installing mods and Optifine on Minecraft. Out of all the videos I've watched, they always delete the META-INF File. I know what happens if you don't delete it but what if I want to add another mod into my Minecraft? What will I have to do if the file has been already deleted? Do I just install the mod and put together the mod files with Minecraft using WinRAR when I don't have the file anymore? Or will there always be a META-INF file to delete each time I install a mod?
If you dont understand what I just said heres what I'm basically saying. How do I install another mod when I've already deleted the META-INF file when there is nothing to delete. Will there be another META-INF file to delete again?

A:

The file won't regenerate unless you update Minecraft, and needs to be removed only once for a given version. (If Minecraft has an update and you pick "yes" when it asks if you want to update, it'll reinstall a fresh, new copy of the game, with a brand-new META-INF file and none of your mods.)
The META-INF file is a code signing file. Removing it is necessary if you mod Minecraft because the game will no longer match the code signature, and therefore won't start. Removing it prevents the game from checking if it matches, so then it runs fine.


Q:

Syntax for list construction / concatenation

I've only been at Haskell for two days now, and was wondering what the difference between the two function definitions below are:
Prelude> let swap (x1:x2:xs) = x2:x1:xs
Prelude> swap [1..5]
[2,1,3,4,5]
Prelude> let swap' (x1:x2:xs) = [x2] ++ [x1] ++ xs
Prelude> swap' [1..5]
[2,1,3,4,5]

That is, what makes x2:x1:xs different from [x2] ++ [x1] ++ xs ?
Please and thanks.

A:

The type signatures are a good place to start:
(:) :: a -> [a] -> [a]
(++) :: [a] -> [a] -> [a]

You can find these out with :type (:) and :type (++) in ghci.
As you can see from the type signatures, both are used to produce lists.
The : operator is used to construct lists (and to take them apart again for pattern matching).  To make a list [1,2,3] you just build it up with 1 : 2 : 3 : [].  The first element of : is the item to add on the front of the list, and the second element is either a list (also built up with : or the empty list signified by []).
The ++ operator is list concatenation.  It takes two lists and appends them together.  [1,2,3] ++ [4,5,6] is legal, whereas 1 ++ [1,2,3] is not.

A:

This has nothing to do with syntax. (:) and (++) are just different operators. (:) is a constructor who constructs a list from an element and another list. (++) makes a new list that is the concatenation of two lists. Because (++) is not a constructor you can't use it in patterns.
Now we come to Syntax: the notation
[x2]

that you use is a shorthand for
x2:[]

So what you really have done in the second example is:
(x2:[]) ++ (x1:[]) ++ xs

Therefore, when constructing a list, you can't avoid (:), it's ultimatively the only way to do it. Note that you must construct intermediate lists to be able to use (++).


Q:

What's the difference between MMC enterprise and trial?

I understand that Mule Management Console (mmc) only available for the enterprise edition. However, when I start mmc.zip, I get that information
"This Mule ESB Enterprise with Mule Management Console (MMC) bundle is appropriate for use only as an evaluation tool and is not considered production-ready.
To use MMC for stress testing or in a production environment, download the .war file from MuleSoft's customer portal and deploy the MMC on an application server, such as Tomcat. Please contact the MuleSoft Support Team with any questions about downloading and deploying Mule Management Console."
I wonder what is the difference between those two editions. I mean, not only what they (Mule Soft) mention above, I want to know more about mmc product version, which more functions it provides?

A:

The bundle has MMC deployed on Mule, with Derby persistence.
In production, you need to deploy MMC on a JavaEE container with external DB persistence.


Q:

Son, eres or es: which one to use with "the boys"?

We use 'eres' for 'are' with you in Spanish. We use 'es' with usted for 'are'. If we have to use 'are' with boys, what would we use: son, eres or es?
What would be the appropriate tense for "The boys."?

A:

Yo soy
Tu eres
Él es
Nosotros somos
Ustedes son
Ellos son

which of these pronouns do you think fit "the boys" best?
As to the translation- any dictionary can help you with that.

A:

When you use the usted form you use the conjugation of the third person, not the second, even if usted is used as a polite version of tú (thus, second person singular) and ustedes  as a polite version of vosotros (thus, second person plural).

Tú eres / Vosotros sois [Second person]
El (o ella) es / Ellos Son [Third person]
Usted es / ustedes son [second person that used third person conjugation]

We do this when directly addressing someone, as a way of being polite, not when we describe certain collectives. It doesn't matter if is boys or cars. What matters is if you want to be super-polite when addressing someone you are talking to.
It is unlikely that you would address a group of boys de usted but not impossible. For example if you were their teacher and wanted to be extremely formal you could address the as usted.
So with boys or kids or teenagers most likely you will use the tú form, so use the second person of whichever verb you are using. If you are not addressing them directly you have no need for the usted form.
Nevertheless, being boys a plural you are going to use third person.

Ese chico está solo. Esos chicos están jugando.


Q:

Any benefit to explicitly dropping local temporary tables at the end of a stored procedure?

Consider the following psuedo T-SQL code (performed by a stored procedure):
CREATE TABLE #localTable ...

<do something with the temporary table here>

DROP TABLE #localTable;

The DROP TABLE statement is the last statement executed by the stored proceudre – is there any benefit to that statement?
Note that I'm not asking about dropping temporary tables (local or not) in the middle of the stored procedure (i.e. after the tables are no longer needed, but before the end of the stored procedure code) – that could seemingly have important benefits due to decreasing the memory required to continue executing the stored procedure. I want to know whether there's any benefit (or any effect, really, positive or negative) to explicitly dropping the table versus 'letting' SQL Server do so when the stored procedure finishes executing.

A:

Theres a good detailed post on this here.

The temporary object is renamed to an internal form when DROP TABLE is executed, and renamed back to the same user-visible name when CREATE TABLE is encountered on the next execution.  In addition, any statistics that were auto-created on the temporary table are also cached.  This means that statistics from a previous execution remain when the procedure is next called.

A:

Won't hurt to do so, but the table gets dropped when the connection is dropped. I personally think it's a good habit to get into. It also lets developers, who might have to work on this, that you didn't simply forget to do it.


Q:

Put a quote in a HTML attribute

example,
<span class="hotspot"
    onmouseover="tooltip.show('

123

123

');"
    onmouseout="tooltip.hide();">porttitor orci

in here, i'm trying to add id attribute in table tag, but i already used "" and '', so something is messed up and not working.
Any good solution?

A:

<span class="hotspot"
    onmouseover="tooltip.show('

123

123

');"
    onmouseout="tooltip.hide();">porttitor orci

JSFiddle


Q:

OSGi Servlet with HSQLDB

I am looking for an easy way to use HSQLDB with an OSGi Servlet. I allready created an OSGi Bundle out of the HSQLDB.jar following this guide:
http://www.vogella.com/articles/EclipseJarToPlugin/article.html
But now I can't seem to figure out how to use the HSQLDB from a Servlet inside another Bundle. I can't find any good step by step guides either. I would appreciate if someone could point me into the right direction.
Thanks in advance

A:

HSQLDB has an 'official' bundle in the MvnRepository. Generally it pays off to look around for bundles before converting one yourself. Sometimes it's easy, but often it's trickier to get right.
Mind you, the article you quote is quite old and (while still correct as far as I can see), there are many more possibilities nowadays.
In any case, to work in OSGi, you need to understand how services work. From that point on, servlets are services, and no different than any other service.
When I started fooling around with OSGi, the Felix documentation was a great help to me. I also recommend taking a look at Declarative Services.


Q:

Format 1000 to 10.00 with jQuery

I've been looking for on how to format:
1000 to 10.00
8900 to 89.00
10000 to 100.00
etc.
Meaning simply get the number and add a dot (.) 2 decimals before its end. I found this PHP way of doing it Formatting numbers from 1000 to 10.00 , but cannot get a way to it with jQuery. Would really appreciate the help here.

A:

You can divide the number by 100 then use toFixed(2), like this:

function format(num) {
  return (num / 100).toFixed(2);
}

console.log(format(1000))
console.log(format(8900))
console.log(format(10000))


Q:

How to load more logo's with ajax?

I found a solution how to get a load more button that displays more content on click, but it was for posts, I want to make it work for my custom post type 'Klanten'.
I tried editing the code to match my post type, but I get an error: "Undefined index: offset"
functions.php
wp_enqueue_script( 'dfib-theme-custom', get_template_directory_uri() .'/js/custom.js', array('jquery') );
wp_localize_script( 'dfib-theme-custom', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')) );

add_action( 'wp_ajax_load_more_posts', 'load_more_posts' );
add_action( 'wp_ajax_nopriv_load_more_posts', 'load_more_posts' );

function load_more_posts(){
    global $post;
    $args = array('post_type'=>'klanten', 'posts_per_page'=> 4, 'offset'=> $_POST['offset']);
    $rst=[];
    $query = new WP_Query($args);
    if($query->have_posts()):
        while($query->have_posts()):$query->the_post();
            $rst[] = $post;
        endwhile;
        wp_reset_postdata();
        $offset = $_POST['offset']+4;
    endif;
    wp_send_json_success(array('klanten'=>$rst, 'offset'=>$offset));
}

custom.js
$('#load_more_posts').on('click', function(e){
    console.log('hi');
    e.preventDefault();
    var $offset = $(this).data('offset');
    console.log('var'+$offset);
    $.ajax({
        method: 'POST',
        url: ajax_object.ajax_url,
        type: 'JSON',
        data: {
            offset: $offset,
            action: 'load_more_posts'
        },
        success:function(response){
            console.log(response);
            $('#load_more_posts').data('offset', parseInt(response.data.offset));
        }
    });
})

php-file
$query = new WP_Query( array(
        'post_type' => 'klanten',
        'posts_per_page' => 4,
        'offset' => 0,
        'paged' => 1,
        'order' => 'ASC',
        'orderby' => 'rand',
    ) );
    if ( $query->have_posts() ) { ?>

            <?php
            while ( $query->have_posts() ) :
                $query->the_post();
                ?>

                    <img class="klant__logo" src="<?php the_post_thumbnail_url(); ?>">

            <?php endwhile; ?>

Load More...

        <?php
        wp_reset_postdata();
        return ob_get_clean();
    }

Console log

I want to show 4 logo's (elements), and load 4 more each time someone clicks the loadmore button

A:

I got help from a colleague and he figured it out. I added this in my js-file (jQuery)
// Counter for logos
    var logoCount = $('.logo__wrapper').length;
    var counter = 12;

    // Show only first 12 logos
    $('.logo__wrapper:nth-of-type(1n+13)').addClass('is-hidden');

    // Load more logos button click
    $('#load_more_posts').on('click', function (e) {

        // Loop hidden logo's
        $('.logo__wrapper.is-hidden').each(function (i) {

            // Hide button if no more logo's
            if (counter++ === logoCount) {
                $('#load_more_posts').hide();
                $('.loadmore__end').toggle();
            }

            // Show next 12 logos
            if (i < 12) {
                $(this).removeClass('is-hidden');
            }
            // Break loop after 12 logos
            else {
                return false;
            }
        });
    });


Q:

Deleted a user in rails but the session still exists--how to clear this too?

I had created several test users in my rails app to test the login.  They were automatically logged in by setting a session.
Once I was satisfied with the user login, I went into the rails console and deleted the users with
User.last.delete
However, now when I try to load localhost:3000, my browser is still looking for user number 14, whom I just deleted.
ActiveRecord::RecordNotFound in StaticPagesController#home

Couldn't find User with id=14

app/controllers/application_controller.rb:7:in `current_user'
app/views/static_pages/home.html.erb:2:in `_app_views_static_pages_home_html_erb___2558135612319095530_70269927858560'

Request

Parameters:

None

Even restarting the server and completely clearing the database with in rake db:resetdidn't help---shouldn't this destroy whatever session problem is telling my app look for id=14?

A:

Clear your cookies, that's what is causing the problem.


Q:

Is there an easy way to access the revision list of an unedited question?

There is an easy way to access the revision list of a question that was edited: to do it, I simply click on the link below the question that says "edited [date]".
I couldn't find an easy/built-in way to access this list on questions that have not had any edits. The only thing I could think of was changing "questions" in the URL to "posts" and changing the name of the question in the URL to "revisions".
Seeing the revision list on an unedited question might be desirable for example if someone wants to see the exact timeline of bounties, reasons for bounties, closing and reopening, tweets, etc.
So my question is:

Does a simple way to do this already exist and I somehow missed it?

A:

If you don't mind installing a userscript in your browser, you can use one of the existing userscripts.

SE Modifications — Username autocomplete in comments, inline revision source, and utility links adds a history link below every post if there isn't one already (as well as other features).
Add Hidden Links is more specialized.
Add Δimeline and ℜevisions Links adds these links in many question lists.

A:

In the url, there is always the post number (this is post 6196).
You can go to ...stackexchange.com/posts/(post number)/revisions
where I put "posts" in italics to indicate that it changes too. For example, this post has never been edited, but you can go to
https://math.meta.stackexchange.com/posts/6196/revisions
for this question.


Q:

React setState callback return value

I'm new in React and I was looking to achieve this kind of flow:
// set the state
// execute a function `f` (an async one, which returns a promise)
// set the state again
// return the promise value from the previous function

So, what I'm doing now is the following:
async function handleSomething() {
  this.setState((prevState) => { ... },
    () => {
      let result = await f()
      this.setState((prevState) => { ... },
        ...
      )
    })
  return result;
}

Hope you get the idea of what I want to achieve. Basically I want to get result, which is the value returned from awaiting f, and return it in handleSomething so I can use it in another place, but wrapping it up inside those setState calls:
// g()
//   setState
//     res = f()
//       setState
//   return res

My question is, how can I do this properly? Maybe should I modify the state with the result value and get it from there?.
EDIT:
Usage of handleSomething:
// inside some async function
let result = await handleSomething()

A:

You can create a Promise that resolves once both setState calls are done:
function handleSomething() {
  return new Promise(resolve => {
    this.setState(
      prevState => {
        /*...*/
      },
      async () => {
        let result = await f();
        this.setState(
          prevState => {
            /*...*/
          },
          () => resolve(result)
          //    ^^^^^^^ resolve the promise with the final result
        );
      }
    );
  });
}

Which would be used like:
this.handleSomething().then(result => /* ... */)

// or

const result = await this.handleSomething();


Q:

Объясните как перемешиваются значения в цикле

Вот программа, я начинаю путаться и не понимаю, что куда переходит. Можете объяснить с каким-нибудь примером.
void newarray(int arr1[]);
int main()
{
    int array[5]= {};
    int i;
    printf("Enter your 5 - elements array: \n");

    for(i = 0;i<5;i++)
    {
        scanf("%d", &array[i]);
    }

    newarray(array);

    return 0;
}

void newarray(int* arr1)
{
    int i, k, f;

    printf("Your array is:\n");
    for(i=0;i<5;i++){
        printf("[%d]: %d", i, arr1[i]);
    }

    printf("\n");

    srand(time(NULL));

    for(i=0;i<5;i++){
        k=rand()%5;
        f=arr1[k];   //1
        arr1[k]=arr1[i]; //2
        arr1[i]=f; //3 не совсем понимаю, что происходит в этих трёх строках

    }

    for(i= 0; i<5;i++)
    {
        printf("[%d]: %d\t", i, arr1[i]);
    }
}

A:

srand(time(NULL)); – генерирует базу, которую использует алгоритм генерации псевдослучайных чисел (функция rand), используя текущее время.
Функция rand() генерирует псевдослучайное число от 0 до константы RAND_MAX. Так как это число не должно быть больше 5, иначе мы выйдем за границы массива, оно делится на 5 и берется остаток (который всегда меньше 5) – k=rand()%5;.
Таким образом arr[k] – это случайный элемент массива, а в этих трех строчках –
    f=arr1[k];
    arr1[k]=arr1[i];
    arr1[i]=f;

меняются местами два элемента массива arr[i] – элемент который берется из массива по цикла и arr[k]. В данном случае f выступает в роли временной переменной.


Q:

Cartesian Product SQL / Inserts with multiple Values Clauses

I want to create cartesian product sql query.But,I'm getting the error.Where I wrong?
alter table #Personel
(
Ad varchar(100)
)

alter table #Masa
(
 MasaAdi varchar(100)
)

insert into #Personel values('deneme1'),('deneme2'),('deneme3')
insert into #Masa values('Masa1'),('masa2'),('masa3')
select Ad,MasaAdi from
(
   select ROW_NUMBER() over(partition by MasaAdi order by ID,Ad ) as Sira
      ,ID,Ad,MasaAdi
   from (
   select newid() as ID,Ad,MasaAdi from #Personel
   left outer join #Masa on 1=1
   ) t
) t2 where Sira = 1 order by Ad

A:

On SQL Server you can write
select Ad,MasaAdi from
(
 select ROW_NUMBER() over(partition by MasaAdi order by ID,Ad ) as Sira,ID,Ad,MasaAdi
 from (
 select newid() as ID,Ad,MasaAdi
 from #Personel
 cross join #Masa
 )t
 ) t2 where Sira = 1 order by Ad

This is the best syntax to emphasize that it is a cross join.
But on SQL Server 2008 your query gives the same result .
EDIT:
Your problem is not the select statement, but the inserts. Inserts with multiple value clauses is a new feature of SQL Server 2008. For 2005 you have to write:
insert into #Personel values('deneme1')
insert into #Personel values('deneme2')
insert into #Personel values('deneme3')

insert into #Masa values('Masa1')
insert into #Masa values('masa2')
insert into #Masa values('masa3')


Q:

Asynchronous loading of partial view in Ember

I've created an Ember helper to allow for loading a dynamically generated partial view from a URL on the server.  It looks like this:
Ember.Handlebars.helper('serverPartial', function(url, options) {
    var template;

    $.ajax(url, {
        async: false,
        success: function(templateText){
            template = Ember.Handlebars.compile(templateText);
        }
    });

    template(this, options);
});

And it's called from a parent Handlebars template like this:
{{serverPartial templateUrl}}

As you can see, the ajax call to retrieve the template from the server is a synchronous call, because I couldn't find any other way to return the template contents as expected by the Ember framework.  Unfortunately, this synchronous call holds up the rendering of the entire parent template.
Is there a way to return a promise for the template, or any other way to allow partial views to load asynchronously or independently?

A:

Thanks for the tip, @Rajat.  I did end up using Views to accomplish this.  I created a view container that initially loads a default child template, then that child loads in the actual contents from the server after it is inserted.  Here's the approach I took:
App.LoadingView = Ember.View.extend({
    didInsertElement: function(){
        var container = this._parentView;
        $.get('http://server/serverTemplate', function(data){
            container.pushObject(Ember.View.create({
                template: Ember.Handlebars.compile(data)
            }));
            container.removeObject(container.get('loadingView'));
        });
    },
    template: Ember.Handlebars.compile('client awesome')
});

// inherit from ContainerView and initialize with default content
App.SnippetView = Ember.ContainerView.extend({
    childViews: ['loadingView'],
    loadingView: App.LoadingView.create()
});

I'm sure there are better ways to express this, but does the job at a minimum.


Q:

date_diff retorna diferença incorreta

Estava fazendo uns testes com esta função, mas ela retorna uma diferença incorreta, como faço para contornar isso?
Exemplo: quando comparado a diferença entre dia 01/01 com 01/03 retornar a diferença de um mês, e só quando é dia 04/03 que retornar os dois meses.
Correto:
$datetime1 = new DateTime('2009-01-01');
$datetime2 = new DateTime('2009-03-04');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
echo $interval->format('%R%m month');

Resultado:

+62 days+2 month

Incorreto:
$datetime1 = new DateTime('2009-01-01');
$datetime2 = new DateTime('2009-03-01');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');
echo $interval->format('%R%m month');

Resultado:

+59 days+1 month

A:

O método DateInterval::format() não recalcula pontos de transporte em sequências de tempo nem em segmentos de data. Isso é esperado porque não é possível estourar valores como "32 dias", o que poderia ser interpretado como algo de "1 mês e 4 dias" a "1 mês e 1 dia".
Manual do PHP


Q:

receiving xml files via http post - security

I've a basic php script set up on a web server to accept xml files received sent via Http post. So far so good. But I'm wondering about security issues and what other things I would need to be aware of before I could put this live. Has anyone done this beofre and what things I should be aware of?
Basically all I have so far is:
<?php

header('Content-type: text/xml');

if ( $_SERVER['REQUEST_METHOD'] == 'POST' )
{
    $postText=file_get_contents('php://input');
    $datetime=date('ymdHis');
    $xmlfile="myfile" . $datetime . ".xml";
    $FileHandle=fopen($xmlfile, 'w') or die("can't open file");
    fwrite($FileHandle, $postText);
    fclose($FileHandle);
    echo
    '<?xml version="1.0" encoding="UTF-8"?>
    <cXML>
    <Response>
    <Status code="200" text="OK">OK</Status>
    </Response>
    </cXML>';
}
?>

which just writes the xml files onto the webserver. What checks would I need to be doing etc?
Thanks,

A:

You should consider:

Whether you want the files you're writing to be accessible over HTTP. If you don't, you should move them to a directory the web server cannot access.
This is susceptible to a denial of service attack; an attacker could fill your disk with garbage XML files and make you run out of disk space. You can prevent this by securing the access to your PHP script (if possible), otherwise make a check against the available disk space.

By the way, this would be more memory efficient:
$post = fopen("php://input", "r");
if ($post === false) { ... }
file_put_contents($xmlfile, $post);


Q:

What does ギョグ mean?

In my dictionaries and on the Internet, the only meaning I found for ギョグ was "fishing gear", but in the context of the text I have been translating it does not make sense. The context is: two monsters and a boy fell to the ground.

ガ　　ガア!?
Thud, Thuud!!
ふっ!
Shoom!
ギョグ!?
Fishing gear!?

A:

It, as well as ガア, shoud be just a screech of that monster. ギョグ is not common, but there is no rule on how imaginary monsters should cry.


Q:

two query results in 1 $variable

I'm trying to use codeigniter activerecords to pull some records from two tables that have the same structure.  For example I have a MARKET table with two fields (name, name_spanish) and I have an APPLICATION table with the same two fields (name, name_spanish).
Can I create a $data variable and put the results of each query into it?  Then I'd want to check the results like this psuedocode $spanish = $data['name_spanish'] where $data['name'] = "Hello"
Can this be accomplished?

A:

This sounds like a UNION query.
SELECT * FROM table1 WHERE foo = 1
  UNION SELECT * FROM table2 WHERE bar = 3 AND baz = 3

I don't think CodeIgniter's ActiveRecord supports union queries, so use the query method.


Q:

java add dns cache record

Is it possible to add a record to the dns cache from java? Or will I have to use the JNI?

A:

Is it possible to add a record to the dns cache from java? Or will I have to use the JNI?

Assuming that you are talking about the DNS cache that Java applications use, the answer is No in both cases.
The cache is implemented in the java.net.InetAddress class; refer here for the source code.  As you can see, the cache is implemented using private static attributes and all of the classes and methods involved are private or package private.  In short, the only way you could get at the cache would be by using nasty reflection tricks to subvert the Java access rules.
Since this is implemented in pure Java, JNI won't help.
EDIT
Unfortunately, the link above no longer points to the OpenJDK code :-(.
FOLLOWUP
Re: these comments.

The Java DNS cache? – WineSoaked May 9 '10 at 3:25

Sorry no, the system one. I'm trying to proxy the default browser for certain sites and i figured adding a dns record for those sites pointing to my local proxy would be easiest way. – silverbandit91 May 9 '10 at 5:32

There is no way to directly plant things in the system DNS cache from Java.  Indeed, I don't even think that Java uses the system DNS cache.
But there are better alternatives to what you are trying to do:

Get your users to configure their browsers to use an 'autoproxy.pac' file to determine which proxies to use.  IMO, this is the best option.
Put entries for the hosts that you want to selectively proxy into "/etc/hosts" and configure (using "/etc/host.conf") your local resolver to look in "/etc/hosts" before talking to the DNS server.  Unfortunately (like cache poisoning) this "pollutes" your DNS with bogus entries, can cause problems when using services other than HTTP / HTTPS.

Finally, you probably should rethink your goal of doing this totally transparently to your users:

If you are doing this to implement some company security or internet access rules, people can "route around" any measures you implement at this level.  (You'd be better off firewalling your network and forcing to use a proxy for external access ... or something like that.)
If you are just trying to implement a useful service, you should use the autoproxy.pac approach which gives the users 1) visibility of what is going on (if they care to look), and 2) the option of opting in or out.
If you are trying to do something else ...


Q:

How to refresh/update select in Javascript (vanilla) with Materialize?

I am attempting to update options in a select-widget by using Javascript (vanilla) with Materialize. I have I guess it is related to "dynamically generated select elements", but I am not sure what to do?
According to Materialize I may need to consider to implement: "In addition, you will need a separate call for any dynamically generated select elements your page generates.". Unfortunately, I am not sure (did not found) how I can "dynamically generated select elements" as to update/refresh the select-widget?
Here are my related codes:
HTML

<meta name="viewport" content="width=device-width, initial-scale=1.0"/>

<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

        <button id = "btn" class="waves-effect waves-light btn-small">person_addAdd</button>

        <button id = "btnRemove" class="waves-effect waves-light btn-small">deleteRemove</button>

          <select id="voteNoList" onchange="PersonInfo()" required>
            <option value="">Vote Number?</option>

            <option value="1">Option 1</option>
            <option value="2">Option 2</option>
            <option value="3">Option 3</option>
          </select>

Javascript (Vanilla)
  //------------
  // AUTO
  //------------
  // Select
  document.addEventListener('DOMContentLoaded', function() {
    var el = document.querySelectorAll('select');
    var instances = M.FormSelect.init(el);
  });

  // Button - Add
  document.getElementById("btn").addEventListener("click", PersonInfo);

  // Button - Remove
  document.getElementById("btnRemove").addEventListener("click", PersonDelete);

  function PersonInfo(){

    debugger;
    var selectobject = document.createElement("option");
    selectobject.text = "Text55";
    selectobject.value = "myvalue55";
    var selectList = document.getElementById("voteNoList");
    selectList.appendChild(selectobject);
    debugger;
    return;
  }

  function PersonDelete(){

    debugger;
    var selectobject=document.getElementById("voteNoList");
    for (var i=0; i<selectobject.length; i++){
      if (selectobject.options[i].value == "2"){
         selectobject.remove(i);
        break;
      }
    }
    debugger;
    return;
  }

My expectation was to have a select-widget which can increase and decrease in options depending on how the buttons have been pressed. (Observe that for simplicity, I hard-coded to only be able to add the same option and delete the option that is equal to "2".)
Although I could not find a solution in Javascript (vanilla), I was able to find a jQuery solution as seen in
link.
My codes are also available in CodePen, where one can see in debug mode that the different number options of selectList change when pressing the buttons.

A:

Apparently, the solution to my case was to add M.FormSelect.init(selectList); before return. The codes with the update/solution are available in CodePen.


Q:

How to load storyboard viewcontroller into programmatically tabbar controller in ios siwft?

I have tabbar controller which done programmatically. And tab bar is working fine. In stroyboard, i have created firstViewController and assigned class name firstViewController. When i tried to tab on first vc on tab bar controller to navigates to first viewcontroller and it crash. if i give programmatically mean it works fine.
How to navigate from programmatically tab bar controller to storyboard view controller.
here is my code of tab bar controller:
 let tabBarCnt = UITabBarController()
 func createTabBarController() {

    let firstVC = FViewController()
    firstVC.tabBarItem = UITabBarItem(tabBarSystemItem: .search, tag: 0)

    let secondVC = SViewController()
    secondVC.tabBarItem = UITabBarItem(tabBarSystemItem: .more, tag: 1)

    let thirdVC = ViewController()
    thirdVC.tabBarItem = UITabBarItem(tabBarSystemItem: .history, tag: 2)

    let fourthVC = ViewController()
    fourthVC.tabBarItem = UITabBarItem(tabBarSystemItem: .downloads, tag: 3)

    if UIDevice.current.userInterfaceIdiom == .pad {
        let controllerArray = [firstVC, secondVC, thirdVC, fourthVC]
        tabBarCnt.viewControllers = controllerArray.map{ UINavigationController.init(rootViewController: $0)}

        self.view.addSubview(tabBarCnt.view)
    } else {
        let controllerArray = [firstVC, secondVC]
        tabBarCnt.viewControllers = controllerArray.map{ UINavigationController.init(rootViewController: $0)}

        self.view.addSubview(tabBarCnt.view)
    }

}

Here is my firstVC of firstViewController code:
import UIKit

class FViewController: UIViewController, UITabBarDelegate {

@IBOutlet weak var firstBtn: UIButton!

@IBOutlet weak var fview: UIView!
override func viewDidLoad() {
    super.viewDidLoad()

    self.view.backgroundColor =  UIColor.blue
 // self.fview.backgroundColor = .brown

    // Do any additional setup after loading the view.
   }

}

A:

Please try below code. you can give view controller identifier by interface builder.
let tabBarCnt = UITabBarController()
func createTabBarController() {
let storyboard = UIStoryboard(name: "MainStoryboard", bundle: nil)
let firstVC = storyboard?.instantiateViewControllerWithIdentifier("FViewController")
firstVC.tabBarItem = UITabBarItem(tabBarSystemItem: .search, tag: 0)

let secondVC = storyboard?.instantiateViewControllerWithIdentifier("SViewController")
secondVC.tabBarItem = UITabBarItem(tabBarSystemItem: .more, tag: 1)

let thirdVC = storyboard?.instantiateViewControllerWithIdentifier("ViewController")
thirdVC.tabBarItem = UITabBarItem(tabBarSystemItem: .history, tag: 2)

let fourthVC = storyboard?.instantiateViewControllerWithIdentifier("ViewController")
fourthVC.tabBarItem = UITabBarItem(tabBarSystemItem: .downloads, tag: 3)

   var controllerArray = [firstVC, secondVC]
if UIDevice.current.userInterfaceIdiom == .pad {
      controllerArray += [thirdVC, fourthVC]
}
     tabBarCnt.viewControllers = controllerArray.map{ UINavigationController.init(rootViewController: $0)}
    self.view.addSubview(tabBarCnt.view)
}


Q:

distinct performance on large table

Suppose I have a table with a column that has repeats, e.g.
Column1
---------
    a
    a
    a
    a
    b
    a
    c
    d
    e
    ... so on

Maybe it has hundreds of thousands of rows.  Then say, I need to pull the distinct values from this column.  I can do so easily in a SELECT with DISTINCT, but I'm wondering on performance?
I could also give each item in Column1 an id, and then create a new table referenced by Column1 (to normalize this more appropriately).  Though, this adds extra complexity to making an insert, and adds in joins for other possible queries.
Is there some way to index just the distinct values in a column, or is the normalization thing the only way to go?

A:

Index on column1 will considerably speed up processing of distinct, but if you are willing to trade some space and some (short) time during insert/update/delete, you can resort to materialized view. This is indexed view you might consider as dynamic table produced and maintained following view definition.
create view view1
with schemabinding
as
   select column1,
          count_big(*) cnt
     from theTable
    group by column1
-- create unique clustered index ix_view1 on view1(column1)

(Do not forget to execute commented create index command. I usually do it this way so that view definition contains index definition, reminding me to apply it if I need to change the view.)
When you want to use it be sure to add noexpand hint to force use of materialized data (this part will remain mistery to me - something created as performance enhancement is not turned on by default, but rather activated on spot).
select *
  from view1 (noexpand)


Q:

Use docker environment path variable in bash script

I am trying to create a docker file to run a machine learning algorithm with parameters given in config.json file. Simplified version of my docker command looks like this
docker run --rm -it \
        -e "CONFIG=work/algorithms/config.json" \
        -e "SRC_TYPE=csv"
        --entrypoint /bin/bash \
        $(DOCKER_REPO)/$(DOCKER_IMAGE):$(DOCKER_VERSION)

Andy bash script running python command looks like this.
#!/bin/sh
python work/algos/neural_network.py \
--ml_conf "$CONFIG" \
--src_type "$SRC_TYPE" \
--log resources/logs/nn_iris.log

When I use the CONFIG variable in the script like this, It does not work. But the SRC_TYPE variable works. Could you please let me know the right way to use environment variables which contain path.

A:

I think you would like to use the config inside the running docker container. If so you should use docker volumes instead. Please see reference here
for example:
docker run -v /work/algorithms/config.json:/path/to/target -it <image_name:tag>


Q:

"Value cannot be null error" in PublishPipelineArtifact task

I'm trying to use the PublishPipelineArtifact task in my fist yaml pipeline, but I'm getting the following error no matter what I try:
Starting: PublishPipelineArtifact
==============================================================================
Task         : Publish pipeline artifact
Description  : Publish (upload) a file or directory as a named artifact for the current run
Version      : 1.0.0
Author       : Microsoft Corporation
Help         : Publish (upload) a file or directory as a named artifact for the current run. Published artifacts can be downloaded in other jobs, stages, or pipelines using the "Download pipeline artifact" task.
==============================================================================
##[error]Value cannot be null.
Parameter name: PublishPipelineArtifact (ecdc45f6-832d-4ad9-b52b-ee49e94659be/1.0.0)
Finishing: PublishPipelineArtifact

Currently this is the publish task in my yml file:

trigger: none

variables:

# agent/environment variables
- group: VARS_AGENT

stages:

- stage: build

  jobs:

  # ------------------------------------------------------------------------------------------------------------------------------
  #- job: 'artifacts_debug'
  # ------------------------------------------------------------------------------------------------------------------------------

  - job: 'artifacts_debug'
    displayName: 'Debug pipeline artifacts'
    workspace:
      clean: all
    pool:
      name: '$(AgentPoolName)'
      demands:
      - msbuild
      - visualstudio
    steps:

    # show artifact staging dir contents
    - script: 'echo test > "$(Build.ArtifactStagingDirectory)\test.txt" '
      displayName: 'Create dummy file'

    - script: 'dir "$(Build.ArtifactStagingDirectory)"  /s /b '
      displayName: 'Show artifact staging contents'

    - script: 'echo AgentPoolName=$(AgentPoolName)  /s /b '
      displayName: 'Echo AgentPoolName variable content'

    #publish artifacts ("new" pipeline artifacts but can't get it to work)
    - task: PublishPipelineArtifact@1
      inputs:
        path: '$(Build.ArtifactStagingDirectory)'
        artifact: Db

What am I doing wrong? The \db folder in the ArtifactStagingDirectory exists, and is not empty. The variable group VARS_AGENT resolves correctly, showing the expected value in the debug "echo" step.

A:

According to jay’s comment, the issue should caused by the agent version instead of wrong YAML. Now, the latest version is 2.155.1, but Jay’s agent version is 2.150.
After upgrade the agent version to latest, the error disappeared.


Q:

How to make same function execute different part of the code when called at different intervals

Is this even possible to do? I want to use the same function at different intervals. How can I make the function run at 5000 and execute certain part of code within the function.
here is an example to give an idea:
 var moto = function(){
   // at 5000 run this part of code
   console.log("did stuff when called at 5000 time interval")

   // at 6000 run this part of code
   console.log("did stuff when called at 6000 time interval")
 }

 window.setInterval(moto, 5000)
 window.setInterval(moto, 6000)

A:

So pass a parameter with the call.
 var moto = function( val){
   if(val===5000) {
     // at 5000 run this part of code
     console.log("did stuff when called at 5000 time interval");
   } else {
   // at 6000 run this part of code
     console.log("did stuff when called at 6000 time interval");
   }
 }

 window.setInterval(moto.bind(this, 5000), 5000);
 window.setInterval(moto.bind(this, 6000), 6000);


Q:

Resultados diferentes com a mesma instrução SQL

Fala programadores(as), tranquilos?
Eu pesquisei bastante para não repetir perguntas aqui, mas realmente não entendo o motivo da instrução SQL funcionar no MySQL Workbench e na string SQL do Java/JDBC não.
Eu tenho duas tabelas jogo e categoria, e ao listar as categorias eu gostaria de informar a quantidade de jogos cadastrados na respectiva categoria, ex:
Categoria: Ação (3) jogos
Categoria: Corrida (1) jogos
Categoria: Luta (1) jogos
Um relacionamento onde uma categoria tem muitos jogos e cada jogo tem a sua categoria.
Bom, até aí tudo bem. O problema é que antes de inserir o SQL no método preparedStatement("SQL") no java eu faço um teste no MySQL Worckbench e o teste me retornou um resultado satisfatório:
SELECT c.id, c.categoria, COUNT(j.id_categoria) as qtd
FROM categoria c INNER JOIN jogo j ON c.id = j.id_categoria GROUP BY c.id;

Resultado no workbench
id   categoria   qtd
1      Ação      3
2     Corrida    1
3      Luta      1

Porém com o mesmo SQL no java o resultado é o sequinte:
id   categoria   qtd
1      Ação       1
1      Ação       1
1      Ação       1

Parte do método getAll() da classe CategoriaDAO.
PreparedStatement ps = conexao.preparedStatement("SQL_ACIMA");
ResultSet rs = ps.executeQuery();
List<Categoria> categorias = new ArrayList<>();
while(rs.next()) {
    categoria.setId(rs.getInt("c.id"));
    categoria.setCategoria(rs.getString("c.categoria"));
    categoria.setQtd(rs.getInt("qtd"));
    categorias.add(categoria);
}
return categorias;

No JSP:
<jsp:useBean id="categorias" class="br.com.jogos.CategoriaDAO"></jsp:useBean>
<c:forEach var="cat" items="${categorias.getAll()}">

        ${cat.getCategoria()}
        ${cat.getQtd()}

</c:forEach>

Se alguém tiver alguma ideia do motivo da mesma instrução SQL ter dois resultados distintos, eu já agradeço. Obrigado!

A:

PreparedStatement ps = conexao.preparedStatement("SQL_ACIMA");
ResultSet rs = ps.executeQuery();
List<Categoria> categorias = new ArrayList<>();
while(rs.next()) {
    categoria.setId(rs.getInt("c.id"));
    categoria.setCategoria(rs.getString("c.categoria"));
    categoria.setQtd(rs.getInt("qtd"));
    categorias.add(categoria);
}
return categorias;

Observe que você está sempre usando a mesma instância de categoria e não instâncias diferentes! O que você queria era isso:
try (
    PreparedStatement ps = conexao.preparedStatement("SQL_ACIMA");
    ResultSet rs = ps.executeQuery();
) {
    List<Categoria> categorias = new ArrayList<>();
    while (rs.next()) {
        Categoria c = new Categoria();
        c.setId(rs.getInt("c.id"));
        c.setCategoria(rs.getString("c.categoria"));
        c.setQtd(rs.getInt("qtd"));
        categorias.add(c);
    }
    return categorias;
}

Ah, e lembre-se de usar o try-with-resources para gerenciar o PreparedStatement e o ResultSet adequadamente (e provavelmente o conexao também deveria).
Também sugiro utilizar objetos imutáveis com parâmetros passados no construtor. Se tivesse usado essa abordagem, o problema que você tem não teria acontecido. Tenho uma resposta sobre isso em uma outra pergunta.


Q:

MVC3 DataAnnotaions validation

is there a way to use conditional validation on MVC3 model?
for example:
public class User
{
    [Required]
    public string Password { get; set; }
    [Required, Compare("Password")]
    public string ComparePassword { get; set; }
}

Where i would like Password and confirmpassword fields to be required ONLY when adding a new user. However when editing I would like these to be empty (text boxes in the view). Only when user does type in a new Password and ConfirmPassword will the password be changed in the DB.
Thanks

A:

Typically you would have separate AddUserViewModel and EditUserViewModel classes with the appropriate fields and validators. Then in your controller action if the model is valid, you convert to your view models to your User entity and pass it on to your business logic / service to save. You can use Automapper for this.


Q:

Relocate load address of main module IDA

is it possible when performing static analysis with IDA to change the default load address of the module (ie 0x00400000 in most cases depending on PE preferences) ? I think I read a book on IDA 1 year ago which taught me how to, however with googling around and browsing in IDA i didn't find anything.

A:

Passing confirmed answer from the comment:
See Edit-->Segments-->Rebase program menu item in Ida.
Online help on this menu item is here.


Q:

Connecting esp8266 to AWS IoT

I am trying to connect a WeMos D1 mini based on ESP8266 to the Amazon Web Service AWS IoT using https://github.com/heskew/aws-sdk-arduino.
However, when I flash the device, I get a 403 back, with the following message:
"Credential should be scoped to correct service: 'execute-api'. "
Changing
this->awsService = "iotdata";

to
this->awsService = "execute-api";

in AmazonIOTClient.cpp results in a 404:
"No method found matching route things/my-thing/shadow for http method POST."
and, according to this thread the service should be 'iotdata' for the request to succeed.
Has someone had the same problem and figured out a way to get it running? If so, help would be greatly appreciated. Thanks!
Here the full code for the example:
#include <AmazonIOTClient.h>
#include <Esp8266AWSImplementations.h>
#include <AWSFoundationalTypes.h>
#include "keys.h"

const int sleepTimeS = 30;

void printWiFiData();
void printCurrentNetwork();
void publish(const char *topic, String data);
void publishToAWS();

void setup() {

  Serial.begin(9600);

  Serial.println("Started!");

  publishToAWS();
  ESP.deepSleep(sleepTimeS * 1000000);
}

void loop() {
}

void printWiFiData() {

  // IP address
  Serial.print("IP Address: ");
  Serial.println(WiFi.localIP());

  // MAC address
  byte mac[6];
  WiFi.macAddress(mac);
  Serial.print("MAC address: ");
  Serial.print(mac[5], HEX);
  Serial.print(":");
  Serial.print(mac[4], HEX);
  Serial.print(":");
  Serial.print(mac[3], HEX);
  Serial.print(":");
  Serial.print(mac[2], HEX);
  Serial.print(":");
  Serial.print(mac[1], HEX);
  Serial.print(":");
  Serial.println(mac[0], HEX);
}

void printCurrentNetwork() {

  // SSID
  Serial.print("SSID: ");
  Serial.println(WiFi.SSID());

  // signal strength:
  Serial.print("signal strength (RSSI): ");
  Serial.println(WiFi.RSSI());
}

void publish(const char *topic, String data) {

  AmazonIOTClient iotClient;
  ActionError actionError;

  Esp8266HttpClient httpClient;
  Esp8266DateTimeProvider dateTimeProvider;

  Serial.println();
  Serial.print("Connecting to ");
  Serial.print(wifiSsid);
  Serial.println("...");

  WiFi.begin(wifiSsid, wifiPwd);
  while (WiFi.status() != WL_CONNECTED) {
    Serial.print(".");
    delay(50);
  }

  Serial.println("");
  Serial.println("WiFi connected");

  printCurrentNetwork();
  printWiFiData();

  delay(50);

  Serial.println("Initializing IoT client...");

  iotClient.setAWSRegion(awsIotRegion);
  iotClient.setAWSEndpoint(awsIotEndpoint);
  iotClient.setAWSDomain(awsIotDomain);
  iotClient.setAWSPath("/things/my-thing/shadow");
  iotClient.setAWSKeyID(awsKeyID);
  iotClient.setAWSSecretKey(awsSecKey);
  iotClient.setHttpClient(&httpClient);
  iotClient.setDateTimeProvider(&dateTimeProvider);

  delay(50);

  Serial.println("Updating thing shadow...");

  MinimalString shadow = ("{\"state\":{\"reported\":{\"text\":" + data + "}}}").c_str();
  char* result = iotClient.update_shadow(shadow, actionError);

  Serial.print("result: ");
  Serial.println(result);
}

void publishToAWS() {

  Serial.println("Publishing to AWS IoT Broker");

  publish("my-thing/text", "Hello World!");
}

keys.cpp file:
#include "keys.h"

// AWS User Credentials
const char* awsKeyID = "XXXXXXXXXXXXXXXXXXXX";
const char* awsSecKey = "X1xxx23xxxxXXXX34XXxxxxX56xXxxxxxxXx789x";

// AWS IoT
const char* awsIotRegion = "eu-central-1";
const char* awsIotEndpoint = "xxxxxxxxxxxxxx";
const char* awsIotDomain = "iot.eu-central-1.amazonaws.com";

// Init and connect WiFi to local WLAN
char* wifiSsid = "mySSID";
char* wifiPwd = "password";

A:

I can finally contribute something :)
I got this very same example working a few days ago. However I used the same library just a different branch iot-get-shadow-and-cleanup. I don't recall having to make any changes as the one you mentioned:
this->awsService = "iotdata"; to this->awsService = "execute-api";
Here are the correct settings for your AWS endpoint that goes into keys.cpp
  awsIotRegion = "us-east-1";
  awsIotEndpoint = "amazonaws.com";
  awsIotDomain = "axxxxs2pxxxrlx.iot.us-east-1.amazonaws.com";`

Also add delete[] result; to the end of the publish() to save some precious heap space.
I would recommend using the iot-get-shadow-and-cleanup branch since it has fixes for memory leaks.
I made one more change to resolve all issues with running out of heap space when updating the shadow continiously. In AWSClient4.cpp I changed // delete[] server; to delete[] data; - I am not 100% sure if this was necessary but combined with the addition of delete[] result; I was able to update the shadown every minute continuously for an hour without loosing any heap.
Hope this helps.


Q:

Java has-a relationship

Would the below be correct for the following statement. "A man has a best friend who is a dog."
public class Mann {
     private BestFriend dog;
     //etc
}

A:

I'd say it would be more correct to write:
public class Man extends Entity {
     private Entity bestFriend = new Dog(); // Where Dog extends Entity
     //etc
}

Why? Let's say you have a bunch of different entities, say Man, Cat, and Dog. It would then make sense to have them each extend an Entity class, that specifies various attributes every entity should have. Each one, then, could have a bestFriend attribute, that could be any other Entity.
However, as pointed out in the comments, it would be even more correct to allow for specifying a bestFriend in the constructor:
public class Man extends Entity {
    private Entity bestFriend;

    public Main(Entity bestFriend) {
        this.bestFriend = bestFriend;
    }
    //etc
}

...

Dog bobDog = new Dog();
Man bob = new Man(bobDog);

A:

Looks like Dog should by type, because man can have other "type of best friend":
public class Mann {
     private Dog bestFriend;
     //etc
}

Update
Most close to real-live implementation will look like:
public interface Friend {}

public class Man implements Friend {}

public class Dog implements Friend {}

public class FriendRelationship {
    private Friend first;
    private Friend second;

    public FriendRelationship(Friend first, Friend second) {
        this.first = first;
        this.second = second;
    }
}

Man aPerson = new Man();
Dog aBog = new Dog();
FriendRelationship bestFriends = new FriendRelationship(aPerson, aDog);

This way one can express friend relationships between any entities. Common base class is not required. You only need implement Friend interface.


Q:

Same interface, implementation differences

Given:
- Different implementations that need to be gathered under the same interface
Unluck: these implementations have a method 'create', but with different number and types of input params
Solutions....?
What other option is there besides varargs of Object?

A:

Assuming that you want only one create method under the interface that you are intending
Create a wrapper class that implements the interface you are intending.  Now call the various implementation from wrapper class based on some condition.
For Maintainabilty Perspective
If possible avoid conditions and Send the implementation class name from calling code .just call the create method on class passed as argument from calling code.(For this you also need to create the dummy create method with some object class as parameter which contains all the parameters under each implementation class which simply delegates the call to intended method with required number of params )


Q:

pandas not works for django?

I saw the first rocket.
from django.http import HttpResponse

def index(request):
    return HttpResponse("Hello, world.")

'Hello, world.' it's ok!
also 'python manage.py migrate' ok.
But when I import pandas...
(import only and no use.)
from django.http import HttpResponse
import pandas as pd

def index(request):
    return HttpResponse("Hello, world.")

Browser thinks forever.
How can I fix this issue?
my environment
OS: CentOS Linux release 7.7.1908 (Core)
Pandas: 0.19.2
Apache: 2.4.6 (CentOS)
Django: 2.1
Browser: Google Chrome 76.0.3809.132
# python --version
  Python 3.6.0 :: Anaconda 4.3.1 (64-bit)

simply, Anaconda is older?
Please let me know if there is any missing information.

A:

Progress after that. Tried "Panda" update.
#Conda installs panda
I was able to clear the browser thinking during the import error.
I will re-install Newest Anaconda.
(_mysql_exceptions.OperationalError) (2006, "Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)") (Background on this error at: sqlalche.me/e/e3q8)

Currently, if you don't use django, you can execute SQL from py file to MySQL.


Q:

WPF TextBox Extension unable to use MahApps TextBoxHelper

I have an extended wpf textbox and I would like to use MahApps TextBoxHelper to add a watermark. Using regular textboxes worked just fine but as soon as I tried to replace them with my extended textbox TouchTextBox the watermarks disappeared along with the Metro style. My extended textbox is designed to work with a custom touch keyboard and it has a number of events geared toward handling this feature:
XAML:
<TextBox x:Class="MyNamespaceHERE.TouchTextBox"
     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
     xmlns:Controls="clr-namespace:MahApps.Metro.Controls;assembly=MahApps.Metro"
     xmlns:local="clr-namespace:MyNamespaceHERE"
     mc:Ignorable="d"
     GotFocus="TouchTextBox_GotFocus"
     LostFocus="TouchTextBox_LostFocus">
</TextBox>

Code Behind:
public partial class TouchTextBox : TextBox
{

    public TouchTextBox()
    {
        InitializeComponent();

    }

    private void TouchTextBox_GotFocus(object sender, RoutedEventArgs e)
    {
        StaticEvents.OnShowTouchKeyboard(sender, e);
        StaticEvents.TouchKeyboardKeyTouch += StaticEvents_TouchKeyboardKeyTouch;
        StaticEvents.TouchKeyboardSpaceTouch += StaticEvents_TouchKeyboardSpaceTouch;
        StaticEvents.TouchKeyboardBackspaceTouch += StaticEvents_TouchKeyboardBackspaceTouch;
    }

    private void StaticEvents_TouchKeyboardBackspaceTouch(object sender, EventArgs e)
    {
        int i = CaretIndex;
        if (CaretIndex == 0) return;
        Text = Text.Remove(CaretIndex - 1, 1);
        CaretIndex = i - 1;
    }

    private void StaticEvents_TouchKeyboardSpaceTouch(object sender, EventArgs e)
    {
        int i = CaretIndex;
        Text = Text.Insert(CaretIndex, " ");
        CaretIndex = i + 1;
    }

    private void StaticEvents_TouchKeyboardKeyTouch(object sender, EventArgs e)
    {
        int i = CaretIndex;
        string t = (sender as Button).Content.ToString();
        Text = Text.Insert(CaretIndex, t);
        CaretIndex = i + 1;
    }

    private void TouchTextBox_LostFocus(object sender, RoutedEventArgs e)
    {
        StaticEvents.OnHideTouchKeyboard(sender, e);
        StaticEvents.TouchKeyboardKeyTouch -= StaticEvents_TouchKeyboardKeyTouch;
        StaticEvents.TouchKeyboardSpaceTouch -= StaticEvents_TouchKeyboardSpaceTouch;
        StaticEvents.TouchKeyboardBackspaceTouch -= StaticEvents_TouchKeyboardBackspaceTouch;
    }
}

I followed the advice I found in this solution here but so far it has not solved the issue. According to the solution, I need to add a style that is based on TextBox, so here is what I have in my Resource Dictionary:
<Style TargetType="local:TouchTextBox" BasedOn="{StaticResource {x:Type TextBox}}" x:Key="TouchTextBoxStyle"/>

I added this style to each instance of my TouchTextBox controls so that they look like this:
<local:TouchTextBox x:Name="UsernameTextBox" Controls:TextBoxHelper.Watermark="Username" Width="200" Text="{Binding Username}" Style="{StaticResource TouchTextBoxStyle}"/>
<local:TouchTextBox x:Name="PasswordTextBox" Controls:TextBoxHelper.Watermark="Password" Width="200" Margin="0,30,0,0" Text="{Binding Password}" Style="{StaticResource TouchTextBoxStyle}"/>

So far no luck. How can I get back all the great features of MahApps' TextBoxHelper with my custom TouchTextBox user control? I really appreciate any guidance you can provide.
Edit:
I took Joel Lucsy's advice and implemented a TouchTextBoxHelper class to handle the DependencyProperty for my event handling:
public class TouchTextBoxHelper : DependencyObject
{
    public static readonly DependencyProperty IsTouchKeyboardTargetProperty = DependencyProperty.Register("IsTouchKeyboardTarget", typeof(bool), typeof(TouchTextBoxHelper), new FrameworkPropertyMetadata(false, IsTouchKeyboardTargetChanged));

    [AttachedPropertyBrowsableForType(typeof(TextBox))]
    public static bool GetIsTouchKeyboardTargetEnabled(DependencyObject obj)
    {
        return (bool)obj.GetValue(IsTouchKeyboardTargetProperty);
    }

    [AttachedPropertyBrowsableForType(typeof(TextBox))]
    public static void SetIsTouchKeyboardTargetEnabled(DependencyObject obj, bool value)
    {
        obj.SetValue(IsTouchKeyboardTargetProperty, value);
        TextBox tb = obj as TextBox;
        if (tb == null) return;
        if (value)
        {

            tb.GotFocus += TextBoxBaseGotFocus;
            tb.LostFocus += TextBoxBaseLostFocus;
        }
        else
        {
            tb.GotFocus -= TextBoxBaseGotFocus;
            tb.LostFocus -= TextBoxBaseLostFocus;
        }
    }

    private static void IsTouchKeyboardTargetChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var tb = d as TextBox;
        if (null == tb)
        {
            throw new InvalidOperationException("The property 'IsTouchKeyboardTarget' may only be set on TextBox elements.");
        }

        if (e.OldValue != e.NewValue)
        {
            //tb.SetValue(SpellCheck.IsEnabledProperty, (bool)e.NewValue);
            if ((bool)e.NewValue)
            {
                tb.GotFocus += TextBoxBaseGotFocus;
                tb.LostFocus += TextBoxBaseLostFocus;
            }
            else
            {
                tb.GotFocus -= TextBoxBaseGotFocus;
                tb.LostFocus -= TextBoxBaseLostFocus;
            }
        }
    }

    private static void TextBoxBaseGotFocus(object sender, RoutedEventArgs e)
    {
        TouchTextBoxEvents.tb = sender as TextBox;
        StaticEvents.OnShowTouchKeyboard(sender, e);
        StaticEvents.TouchKeyboardKeyTouch += TouchTextBoxEvents.StaticEvents_TouchKeyboardKeyTouch;
        StaticEvents.TouchKeyboardSpaceTouch += TouchTextBoxEvents.StaticEvents_TouchKeyboardSpaceTouch;
        StaticEvents.TouchKeyboardBackspaceTouch += TouchTextBoxEvents.StaticEvents_TouchKeyboardBackspaceTouch;
    }

    private static void TextBoxBaseLostFocus(object sender, RoutedEventArgs e)
    {
        StaticEvents.OnHideTouchKeyboard(sender, e);
        StaticEvents.TouchKeyboardKeyTouch -= TouchTextBoxEvents.StaticEvents_TouchKeyboardKeyTouch;
        StaticEvents.TouchKeyboardSpaceTouch -= TouchTextBoxEvents.StaticEvents_TouchKeyboardSpaceTouch;
        StaticEvents.TouchKeyboardBackspaceTouch -= TouchTextBoxEvents.StaticEvents_TouchKeyboardBackspaceTouch;
    }
}

public class TouchTextBoxEvents
{
    public static TextBox tb = null;
    public static void StaticEvents_TouchKeyboardKeyTouch(object sender, EventArgs e)
    {
        int i = tb.CaretIndex;
        string t = (sender as Button).Content.ToString();
        tb.Text = tb.Text.Insert(tb.CaretIndex, t);
        tb.CaretIndex = i + 1;
    }

    public static void StaticEvents_TouchKeyboardBackspaceTouch(object sender, EventArgs e)
    {
        int i = tb.CaretIndex;
        if (tb.CaretIndex == 0) return;
        tb.Text = tb.Text.Remove(tb.CaretIndex - 1, 1);
        tb.CaretIndex = i - 1;
    }

    public static void StaticEvents_TouchKeyboardSpaceTouch(object sender, EventArgs e)
    {
        int i = tb.CaretIndex;
        tb.Text = tb.Text.Insert(tb.CaretIndex, " ");
        tb.CaretIndex = i + 1;
    }
}

It's kind of horifying but it works!

A:

Rather than creating a custom control, you should create a DependencyProperty similar to the way the TextBoxHelper does to add your events into a normal TextBox. This would eliminate the need for the style as well.


Q:

interactive docker build from dockerfile?

I want to use a Dockerfile to build an image. However, commands will need user input as they run. Currently, the build is not successful because docker exits on user input. I know I can use the -i -t options on docker run command but I want to do that on a Dockerfile. How is that possible?

A:

You can try with expect or a similar tool.
The easiest way to configure it is using the autoexpect tool, which lets you run the commands interactively and creates an expect script for you.
I couldn't get the rvmsudo stuff working (I haven't used it and didn't want to spend too much time with it) so I decided to use vi instead. First run autoexpect
$ autoexpect vi test

This will open vi and you can create or edit the file and save it. After exiting the vi you'll see your file test as well as an expect script script.exp.
You can then remove the test file and execute script.exp. It will recreate the same file using the same steps.
The autoexpect tool is great, but you may have to create a script from scratch if you need to have more control over what happens. E.g. if you don't want the script to work with the exact expected input.