$nk^{n-1}$ is bounded?

Question: Is following true (and what is the proof)?
$$n|k|^{n-1} \le C\frac1{|k|log\frac1{|k|}}$$
$n$ is a positive integer, $|k|$ is less then $1$, $k$ can be imaginary, $C$ is a real constant.
(The origin is this book)

(Exercise 4.2.3 says just 'Verify that' )
Answer: We know that for $x=0$ and as $x$ tends to infinity, this expression goes to $0$, so the trick is to find out what is going on in the middle. Calculus is very useful in this regard, so let us consider the derivative of this function.
Expanding with product rule we get
$$\frac{d}{dx}(xk^{x-1}) = x\ln(k)k^{x-1} + k^{x-1} = (x\ln(k)+1)k^{x-2}$$
Since $k$ is always positive, we only have to worry about the $x\ln(k)+1$ term (note that $\ln(k)$ is negative).
It is easily shown that this linear term is positive for $x<-\frac{1}{\ln(k)}$, $0$ for $x=-\frac{1}{\ln(k)}$, and negative for $x>-\frac{1}{\ln(k)}$. From this we have shown that the function will achieve a maximum at $x = -\frac{1}{\ln(k)} $.
Plugging this in to the original equation, we get
$$-\frac{1}{\ln(k)}k^{-\frac{1}{\ln(k)}-1}=\frac{1}{\ln(\frac{1}{k})}\frac{1}{ek}$$
Thus we have your bound with $C=\frac{1}{e}$
$$n|k|^{n-1} \le \frac{1}{e}\frac1{|k|\ln\frac{1}{|k|}}$$
Comment: looks like $x = \color{red}{-} \frac 1 {\ln k} $. So following eq.s should be modified a little.
Comment: True, sorry about that. I will edit.

$nk^{n-1}$ is bounded?


Magnific Popup - WordPress Divi Theme - Uncaught TypeError: Cannot read property 'top' of undefined

Question: I'm trying to get the lightbox/modal windows working on this page: WordPress (4.7.2; no-plugins enabled) site with Divi theme which uses Magnific Popup (v1.1.0)
http://www.mucha-art.com/portfolio/
When I click on one of the images instead of the lightbox/pop-up working, I get a js error:
Uncaught TypeError: Cannot read property 'top' of undefined
    at t._getOffset (jquery.magnific-popup.js:4)
    at HTMLAnchorElement.<anonymous> (jquery.magnific-popup.js:4)
    at HTMLAnchorElement.dispatch (jquery.js:3)
    at HTMLAnchorElement.r.handle (jquery.js:3)
    at Object.trigger (jquery.js:3)
    at n.fn.init.triggerHandler (jquery.js:3)
    at y (jquery.magnific-popup.js:4)
    at t.open (jquery.magnific-popup.js:4)
    at t._openClick (jquery.magnific-popup.js:4)
    at HTMLAnchorElement.d (jquery.magnific-popup.js:4)

...seems to be pointing to line 722 in the console:
e.top -= a(window).scrollTop() - f;

Answer: I just encountered this myself. It's looking for .top of the image it's supposed to zoom. Without seeing your code I assume you did not preload the image.
My Client has an image assortment where the images are put in via css as background-image. If you use Magnific Popup with  hierarchies it will work out of the box. If not you will need to load the images too.
My hacky solution was to add an image tag that loads the same, full image and give it an invisible class with no height and no width so that it would be at the correct position for the zoom animation to start:
$(document).ready(function() {

    $(".galerie-content").magnificPopup({
        delegate: 'a',
        type: 'image',
        closeOnContentClick: true,
        closeBtnInside: false,
        mainClass: 'mfp-no-margins mfp-with-zoom',
        zoom: {
            enabled: true,
            duration: 200
        }
    });

});

.galerie-img-1 {
    background-image: url("../img/galery/galery_01.jpg");
    background-repeat: none;
    background-position: center;
    background-size: cover;
    opacity: 1;
    height: 300px;
}

.invisible{
    height: 0px;
    width: 0px;
}


Table resizes with text, but it should not

Question: I have this problem (I think it's quite simple, however, I cannot solve it):
I normally never work with tables (except this one time). I usually code with divs, but I have to use tables this time for an email design ( O normally also don't use the  tags etc :P)
Please take a look at the two links below:
http://www.flo-net.org/test1.html page 1
http://www.flo-net.org/test2.html page 2
The difference between the two pages is, that when you add text to the upper row, the bottom left  resizes with the text. But I don't want that! That  should stay put at 20px like page 2.
Can anyone help me? Sorry if I did not explain it too well.
Comment: ^^ Why is this editted after more than 7 years? I mean, I cringe about this post I wrote  in my young innocence as well, but I don't think anyone would care anymore.
Answer: If the top row is all one piece of the design, set , assuming you have 4 columns.
Comment: Jup, thats it. Thank you! I was adding colspan to the  tag (dumb me)


Conversion of UTF-8 char * to CString

Question: How do I convert a string in UTF-8 char* to CString?
Answer: bool Utf8ToCString( CString& cstr, const char* utf8Str )
{
    size_t utf8StrLen = strlen(utf8Str);

    if( utf8StrLen == 0 )
    {
        cstr.Empty();
        return true;
    }

    LPTSTR* ptr = cstr.GetBuffer(utf8StrLen+1);

#ifdef UNICODE
    // CString is UNICODE string so we decode
    int newLen = MultiByteToWideChar(
                     CP_UTF8,  0,
                     utf8Str, utf8StrLen,  ptr, utf8StrLen+1
                     );
    if( !newLen )
    {
        cstr.ReleaseBuffer(0);
        return false;
    }
#else
    WCHAR* buf = (WCHAR*)malloc(utf8StrLen);

    if( buf == NULL )
    {
        cstr.ReleaseBuffer(0);
        return false;
    }

    int newLen = MultiByteToWideChar(
                     CP_UTF8,  0,
                     utf8Str, utf8StrLen,  buf, utf8StrLen
                     );
    if( !newLen )
    {
        free(buf);
        cstr.ReleaseBuffer(0);
        return false;
    }

    assert( newLen < utf8StrLen );
    newLen = WideCharToMultiByte(
                     CP_ACP,  0,
                     buf, newLen,  ptr, utf8StrLen
                     );
    if( !newLen )
    {
        free(buf);
        cstr.ReleaseBuffer(0);
        return false;
    }

    free(buf);
#endif

    cstr.ReleaseBuffer(newLen);
    return true;
}

Though this function is valid for both UNICODE and non-UNICODE configurations IMHO using UNICODE configuration in Win32 programs is much more productive (in general and in this function).
Comment: this is not a solution. The solution is to figure out the target single-byte code page and to convert UTF-8 string to single-byte string of that CP.
Comment: @Jurlie: read the comment before memcpy. Though may be I'll post implementation now.
Comment: Edited the post to include UTF8 to current 8-bit code page conversion.
Answer: Call MultiByteToWideChar with a code page of CP_UTF8, then use CString as normal.
Comment: @Athreya : Isn't `char*` what you already have? In any case, I'm not aware of any "MultiByteToMultiByte" sort of function, so I think you'll have to round-trip it -- call `MultiByteToWideChar` with `CP_UTF8` then `WideCharToMultiByte` with whatever code page you want the resulting `char*` in.
Comment: @Athreya : Why on earth would you want that? That conversion is bound to be lossy -- if the string was Unicode to begin with, what makes you think it contains exclusively ANSI characters?
Comment: I want it to be converted to char* not wchar_t *.. Is there any method?
Comment: I need to parse and execute the statement using OCI library which only accepts char* as input
Answer: If your string contains only ASCII-characters with codes 0 to 127 you may threat your UTF-8 string as ASCII string and initialise CString with it:
CString my_cstr((char*)my_string);

Otherwise (if your UTF-8 string contains some other characters) you have no easy way to get char* string from it.
Comment: I've got other characters in the UTF-8 string
Comment: @Athreya what is codepage you want to convert your string to? Or what is the language at least? Are you sure your UTF-8 string could be represented as single-byte string at all?
Comment: @Athreya : Jurlie means *losslessly* represented as a single-byte string. And your first comment on this answer indicates that this isn't the case.
Comment: I meant the language of string to convert, not a programming language :-D
Comment: @Julie the string is Japanese

Conversion of UTF-8 char * to CString


Why shouldn't I I ever compile header files (C++)?

Question: My question is about header files. Why shouldn't I ever compile header files (C++)?
Comment: The only time they are not is when they are passed as source which are ment to be used as header only libraries to include in your own code.  Which then get compiled.
Comment: If you have a large, complicated header, or a large number of headers, [sometimes you DO want to compile them](https://en.wikipedia.org/wiki/Precompiled_header) to speed build times.
Answer: Header files are compiled all the time, since they are included in translation units that you should compile.
Answer: The difference between something called a 'header file' and something called 'code file' is exclusively that header files are to be included into code files.
In other words, a header file that needs to be compiled is not a header file by definition, but a code file.


understand positioning system in three.js

Question: I'm new to javascript and three.js, i'm trying to figure out how to get the 3d positions on a webpage.
for ex. i want to set a point light at (50,20,10) x,y,z values. how can I know that where this x,y,z values will come on a webpage?.I have seen code like below.

var light2 = new THREE.PointLight(0xffffff, 10)
    light2.position.set(500, 100, 0)
    scene.add(light2)

I have googled but I didn't get enough information to sort out the things properly, can somebody help me with a good explanation or some article/tutorial link?
Comment: What do you mean the webpage has range -1 to 1?  You aren't putting a light in a webpage, you are putting it into a 3D world that will be rendered through WebGL and canvas.
Comment: @zero298 i googled 3d space in web and it showed that a webpage is always in that -1 to 1 range. i really don't know much about it, can you please help me to understand the 3d space in web?
Answer: Just a little background first...

3D space is infinite.
The canvas is a viewport into that space.
The size of the canvas on the page has no direct relation to anything in 3D space. You can double the size of the canvas, and all it does is make the rendered image bigger.

To your question...
That's not to say you can't figure out where on the canvas a 3D thing might appear. You can project any point in 3D space into Normalized Device Coordinates with Vector3.project.
var light2 = new THREE.PointLight(0xffffff, 10)
    light2.position.set(500, 100, 0)
    scene.add(light2)

// Where is it in NDC?
var ndc = new THREE.Vector3().copy( light2.position ).project( camera );

Normalized Device Coordinates range from -1 to 1, and represent the normalized width and height of the viewport with (0,0) at the center of the rendered image. So, you will need to convert them from NDC into pixel values on your canvas. (Also, you can ignore the z component, because the screen has no depth.)
var canvasX = ( ndc.x + 1 ) * canvasWidth / 2;
var canvasY = ( ndc.y + 1 ) * canvasHeight / -2;


How to use checklist-model in edit mode?

Question: I'm using this directive to loop through some data when I create a pop so I can add the list checked to this object.
but the problem is how I can check the checkboxes that already in that object in the edit page (I use one HTML page for both create and edit):
<md-input-container ng-repeat="tab in allTabs">
    <md-checkbox aria-label="tab.name" checklist-model="pop.tabs" checklist-value="tab">
        {{tab.name}}
    </md-checkbox>
</md-input-container>

Answer: If the existing objects are not mapping correctly - try using a 'track by' with the ng-repeat:
    <md-input-container ng-repeat="tab in allTabs track by tab.Id">
      <md-checkbox aria-label="tab.name" checklist-model="pop.tabs" checklist-value="tab">
        {{tab.name}}
      </md-checkbox>
    </md-input-container>

That should work 97% of the time. If you happen to fall in the 3% and you've been pulling your hair out for the last 3 days - try adding a comparator in your controller:
    $scope.compareFn = function(obj1, obj2){
        return obj1.id === obj2.id;
    };

And the 'checklist-comparator'
    <md-input-container ng-repeat="tab in allTabs track by tab.Id">
      <md-checkbox aria-label="tab.name" checklist-model="pop.tabs" checklist-value="tab" checklist-comparator="compareFn">
        {{tab.name}}
      </md-checkbox>
    </md-input-container>


Inserting javascript variable into json string

Question: This should be super simple but I keep getting errors.
I have a JSON string that I need to add a js variable to, the code sample is below. Essentially I need to add frameVideo variable after the hash tag in the URL string.
var frameVideo = window.location.hash.substring(1);

jwplayer("sVid").setup({
'share-video': {
       'code': '<embed src="http://www.website.com/test.php#"\'.frameVideo.\'" width="480" height="270" allowfullscreen="true" />'
   },
});

What do I need to do differently?
Comment: Your posted code is neither valid Javascript code, nor valid JSON string.
Answer: You're using PHP concatenation instead of javascript style.
var frameVideo = window.location.hash.substring(1);

var JSON =
{
       'code': '<embed src="http://www.website.com/test.php#"' + frameVideo + ' width="480" height="270" allowfullscreen="true" />'
   };

Comment: Wow that embarrassing, I completely missed that. Thanks.
Answer: Use + instead of the . to concatenate your string.
Answer: I'm guessing you are just coming over to javascript from PHP, given the coding style. In javascript, we use + to concatinate, as opposed to the . in PHP.
JSON strings are essentially javascript objects:
var obj = {
    'share-video': {
        'code': '<embed src="http://www.website.com/test.php#' + frameVideo + '" width="480" height="270" allowfullscreen="true" />'
    }
}

You are also defining an index of an object outside of the context of an Object. 'variable':'something' is a syntax error when outside of an object. Objects are encapsulated within { and }. The above code is semantically correct.
When debugging javascript, always check your console logs. They can help pinpoint exactly what is causing a problem. If you didn't know how to activate the console, it is accessed with F12 in most browsers, or by right-click->inspect element. I recommend Google Chrome for javascript debugging.
Answer: Use + for concatenation.
No need to escape anything here either.
You have an extra double quote after the #.
You want to use double quotes for key names in JSON (it probably wouldn't make a difference here, but a good habit regardless)
You have a trailing comma after your "share-video" object.
var frameVideo = window.location.hash.substring(1);

jwplayer("sVid").setup({
    "share-video": {
        "code": '<embed src="http://www.website.com/test.php#' + frameVideo + '" width="480" height="270" allowfullscreen="true" />'
    }
});


In JavaScript, how do I detect whether or not the input contains letters?

Question: My code is below, it outputs what the user is typing in the text box. It should output an error message if the user puts anything other than a number. I'm confused as to how to do this, though. Quite frankly, I'd settle with it being able to detect whether or not the first letter of input is a B, but I can't quite figure that out either and the former option is preferred.
HTML
Banner ID: B<input type="text" name="bannerID" id="bannerID" onkeyup="showBannerID()" value="" />

JavaScript
function showBannerID() {

var textInput = document.getElementById('bannerID').value;

if (textInput.length == 0) {
    document.getElementById('bannerOutput').innerHTML = "Field can't be empty!";
}
else if (textInput.charAt(0) == "B") {
    document.getElementById('bannerOutput').innerHTML = "Please omit the B! It's not necessary.
}
else {
    document.getElementById('bannerOutput').innerHTML = "Your Banner ID is: B" + textInput + ".";
}
}

Comment: Your code contains a syntax error. Did you know that? (the quote at the else-if-B block is not closed).
Answer: You can use regular expressions to search for anything other than numbers:
if (/[^\d]/.test(textInput)) {
    /* error stuff */
}

Comment: I'll have to look this up, we haven't learned regular expressions yet.

Further question: is there a way to detect whether or not the first number they put in is a B, and output an error message if they do?
Comment: @Doug Your `charAt` test should work for that. Are not getting the results you expect?
Answer: You can use isNaN() (Not a Number) as a condition.
isNaN(123) would give false, isNaN("hello") would give true.
Comment: Perfect! Now is there a way I could implement that, as well as implementing an else if for if they put in a B as the first letter?


What is recommended method for mounting chandelier canopy that has 2 screws?

Question: I want to mount a chandelier canopy like this one to the ceiling.

You'll notice the hole on the left and the hole on the right.
The way this assumingly is supposed to work is that you have the bracket which is screwed to the electrical box as shown:

And once that bracket is screwed to the electrical box, you take the screws that came with the canopy and hang them down through the slots as follows:

Then I assumed that you push the canopy up to the bracket, with the screws that are pointing down going through the two holes on the canopy:

and as seen from the other side:

And then finally you screw these nice little trim pieces - little caps - onto the screw ends to finish it off.

The problem is that in any bracket the screws that hang down into the holes in the canopy are free floating in the slots.  So when I press the canopy onto the screws and try to screw on the caps there is nothing to hold the screws in place and I can never get the caps on.
I must be doing this wrong?
Comment: That hickey isn't for the cord.  Don't route it through there unless you have no choice.
Comment: Unfortunately I have no choice since the strain relief pieces forces the cord in a direction that would conflict with the bracket if I didn't put the cord through the center hole.
Answer: After you figure out the spacing of the bolts hanging down, you thread a nut on the bolts on the side of the bracket opposite the heads.
Cinch down the nuts, check the alignment. If okay, install the bracket and the bolts should stay put as you try to tighten the nut.
Comment: No, no. Simply lesson learned. The best of mechanics/electricians have the "of course!" moments.
Comment: Why I didn't think of this first will haunt me forever lol.
Answer: I believe  you have it upside down.
The floating screws in the slots attach the bracket to the box and the other screws are in threaded holes so you can adjust them up or down to give you the exact amount you need that sticks through the canopy.
Comment: I agree if the threaded holes align with the holes in the canopy. If not, you can use the slots if you use nuts to lock the bolts in place.
Comment: Initially I thought I might have it upside down but the screw I show pointing upwards are the proper size and pitch for the lighting box whereas the downward screws aren't; and the holes don't line up, and also the trim end caps only fit the screws I show that are going down.
Answer: I don't know about the quality or provenance of the unit, but it looks like they tossed in a random, generic mounting bracket.  It's possible the mounting bracket does not fit your ceiling (or even the lamp, if it's an imported cheapie from you-know-where, with attendant quality problems).
The right way to use that mounting bracket is to a) mount it to the ceiling box using the slots, unthreaded holes or hickey; then b) mount the lamp to the bracket, screw heads down, shank going into the threaded holes provided as part of the bracket. I'm not sure why they provided those nut caps, but it sounds like a "just in case".
Also, keep in mind that not every junction box is chandelier rated. A standard box is only rated for a light that weighs 4 pounds. As such, it may not have screws in the right place for a chandelier bracket.


Passing a variable into PHPMailer body

Question: I am using PHPMailer to send emails after registration, but I can't seem to put a variable into
$htmlBody = 'Confirm';

Where $com_code is a unique passkey attached to a link received by the user in their email. The problem is that $com_code is showing up as $com_code instead of the actual string. Any ideas would be helpful.
Answer: Use double quotes instead of single quotes for the string, and escape the double quotes inside, as such:
$htmlBody = "Confirm";

Alternatively, use the concatenation operator instead, as such:
$htmlBody = 'Confirm';

PHP only searches for variables inside strings wrapped with double quotes.
Comment: That is good to know. It will save me a lot of headaches in the future.
Answer: The problem has nothing to do with the PHPMailer. The problem is you are attempting to interpolate a variable in the string wrongly.
Remember that unlike the double-quoted and heredoc syntaxes, variables and escape sequences for special characters will not be expanded when they occur in single quoted strings.
You can use two ways out of many in your situation:
1)
$htmlBody = "Confirm";

2)
$htmlBody = 'Confirm';

Please note how quotes are used!

Passing a variable into PHPMailer body


Need help displaying file/folder permissions in clear text

Question: I need help displaying permissions in clear and understandable text.
I.e. rwx-wx--- as:
User permission: read, write, execute
Group permission: write, execute
Other permission: No permission

I need this script to make it easier to understand for non-technical users.
Answer: This script will do the trick (I called the script filestat - put it in your path):
#!/bin/bash

# Iterate over each argument
for file in "$@"; do
  perm_type=('User' 'Group' 'Other')
  (( j = 0 ))

  # Check if file exists
  if [[ -e "$file" ]]; then

    # Print filename
    echo -e "\nFilename: $file"

    # Isolate permission octet
    perm_octet=$( stat -c "%a %n" "$file" | cut -d ' ' -f 1 )

    # Add each value of octet to array
    perm_array=()
    for (( i = 0; i < "${#perm_octet}"; i++ )); do
      perm_array+=("${perm_octet:$i:1}")
    done

    # Iterate over array
    for x in "${perm_array[@]}"; do

      # Print permission type and increase counter
      echo -n "${perm_type[$j]} permission: "
      (( j++ ))

      # Check if permission is zero (none), print and start next iteration
      if (( "$x" == 0 )); then
        echo "NONE "
        continue
      fi

      # Check if permission has "read", print and subtract 4
      if (( "$x" > 3 )); then
        echo -n "read "
        (( x = x - 4 ))
      fi

      # Check if permission has "write", print and subtract 2
      if (( "$x" > 1 )); then
        echo -n "write "
        (( x = x - 2 ))
      fi

      # Check if permission has "execute", print and subtract 1
      if (( "$x" > 0 )); then
        echo -n "execute "
        (( x = x - 1 ))
      fi

      echo ""
    done

  fi

done

EDIT: Takes any number of files as input, and checks if the file exists. Example output:
$ filestat ~/.bashrc ~/.config

Filename: /home/am/.bashrc
User permission: read write
Group permission: read write
Other permission: read

Filename: /home/am/.config
User permission: read write execute
Group permission: NONE
Other permission: NONE


Why can't I `print __doc__` in Python 3?

Question: I have this code:
#!/usr/local/bin/python
"""

USAGE:

    apache_logs.py

"""

import sys
import os

if __name__ == "__main__":
    if not len(sys.argv) > 1:
        print __doc__
        sys.exit(1)
    infile_name = sys.argv[1]

I get an error that says
Tue Jul 21{stevenhirsch@steven-hirschs-macbook-pro-2}/projects/python:-->./apache_logs.py
  File "./apache_logs.py", line 17
    print __doc__
                ^
SyntaxError: invalid syntax

Why? The documentation I've read all seems to suggest it should work.
Answer: What version of Python do you have? In Python 3, print was changed to work like a function rather than a statement, i.e. print('Hello World') instead of print 'Hello World'
I can recommend you to keep using Python 2.6 unless you're doing some brand new production development. Python 3 is still pretty new.
Comment: It's fine to use Python 3.x for small hobby projects, as long as you're aware that most of the 3rd-party Python libraries haven't been ported yet.
Comment: Right, no one should be using Python 3.x yet unless they have a really good reason.
Comment: Wahnfrieden, why should 'no one' use Python 3.0.  If it's library support, you've got a serious chicken and the egg problem.  If 'no one' should use it then no libraries will be ported.  I'd recommend using Python 3 if you accept the library limits, if you don't, then you should use 2.6.
Comment: Developing a Python library is a "really good reason" to be using Python 3.x, so my point stands. Basically, if you have to ask, then Python 3.x isn't for you, yet, but maybe in a year or two. For learners, 2.6 already has some important 3.0 features backported to it, so it's a much better starting place.


Being attacked with one unit

Question: I'm playing Clash of Clans, Silver League 1, and I've been seeing some attacks on me by players who commit one unit and then surrender, giving me a whole stack of trophies for nothing. At first I thought it was just someone who waited a bit too long before deciding not to attack but it seems to be a bit too frequent for that.
Is there some bizarre strategy going on here, or what is it?
Comment: When I used to play this game I would do exactly what you described simply to be in the lower ranks. I would drop one troop and end battle to cheaply do it. The benefits of this were not being attacked as often because the lower ranks did not have players well off enough to attack me, and resource boosting. The resources in the lower leagues can be easy to come by from inactive players whom just about always have full resource containers.
Comment: Did my answer address everything you wanted to know, or is there anything I can do to improve it? If it addressed everything, could you click the check mark on it?
Answer: There are 3 reasons this may be happening, lionwaffles and lord Jorge touched on 2 of them.

They may have accidently dropped a troop when trying to click next or end battle.

The reason they would then end the battle is possibly because they don't want to waste their troops trying to get the amount of loot you have, or they don't think their troops are strong enough to successfully attack you. In both cases they decided losing trophies was better than wasting troops.

They may be actively trying to drop trophies.

To expand on why someone would want to drop trophies, they may have pushed trophies to get to a certain league or trophy count for a gem reward and wish to return to their lower league, they may be approaching the trophy count to get promoted to the next league and want to drop trophies to remain in their current league, they may want to drop to a lower league to find easier bases (generally speaking the higher the trophy level, the stronger the bases are), or they may want to drop trophies to protect loot (at higher trophies people will generally attack with stronger armies).

They may have actually been trying to raid your base and accidently clicked end battle when trying to switch or deploy troops.
Comment: Really, the most important part of this answer is the second reason. Reasons 1 and 3 almost never happen.
Comment: @PythonMaster ive seen people accidentally end battles that way before. if you are tapping quickly, there is a chance that you may accidentally click surrender and ok before you notice what you did
Comment: 3 is like invalid since there is a pop-up that ensures that you click yes or no to actually surrender
Answer: this is actually an strategy, in the latest patch the old and non-active villages had their TH outside the base, and destroying the TH no longer grants a shield, so the biggest pool of non-active villages were deep in bronze lueague, at least it was like that for two o three weeks after the big update.
Comment: So it's a strategy to get down to the league where the pool of unprotected villages are?
Comment: It's not clear what the strategy is, and I seriously question there is one other than simply dropping trophies to make it less likely your base gets streamrolled by more advanced players.
Comment: The idea is to farm with barbarian and archres, so a ot of people is going down for that, just like we used to farm before the update, that is the main reason...
Answer: No it is not a strategy. It has happened to me as well. Sometimes people touch the screen by accident which deploys the troop.
Comment: There is certainly a reason for a player to intentionally drop a single unit and surrender immediately.

Being attacked with one unit


Difficulty using "count" for mysql queries

Question: I started with mysql and I had this problem
The problem is that I want to make a query between related trablas of a specific table where I have the gender of the people, be it woman or man.
This would be my code to make the query
SELECT c.Nom_carre as Preparatory, count(a.Gen_alum) as Gender
FROM alumno a, carrera c WHERE a.idCarrera=c.idCarrera

This code count(a.Gen_alum) shows me the total of people whether men or women.
I would like to know separately, how many men and how many women are?
Comment: You should either use conditianal aggregations (`COUNT(CASE WHEN a.Gen_alum = 'm' END) as total_m`) or `GROUP BY a.Gen_alum WITH ROLLUP`. But it's difficult/impossible to give you the correct answer as long as you don't clearly define the relations between the tables. Also note that it doesn't make sense to select any columns (like `c.Nom_carre`) that are not in the group by clause.
Answer: Try below code.
SELECT c.Nom_carre AS Preparatory,
       count(a.Gen_alum) AS Gender
FROM alumno a,
     carrera c
WHERE a.idCarrera=c.idCarrera
GROUP BY a.Gen_alum

It helps you.
Comment: this will give an error: unknown column Gender in Group by clause
Answer: Here you need to use count with group by
SELECT c.Nom_carre as Preparatory, count(a.Gen_alum) as Gender
FROM alumno a
JOIN carrera c ON a.idCarrera = c.idCarrera
GROUP BY a.Gen_alum

Comment: Is good but I put the gender vertically and do not put it horizontally
Comment: Share DB structure... do not understand what you mean by vertical or horizontal
Answer: you should be use with join
SELECT c.Nom_carre as Preparatory, count(a.Gen_alum) as Gender
FROM alumno a
join carrera c on a.idCarrera=c.idCarrera
group by a.Gen_alum;

updated
use Field() to that display vertically data as your requirement
SELECT c.Nom_carre as Preparatory, sum(field(a.Gen_alum,'male')) as Male,sum(field(a.Gen_alum,'Female')) as Female
FROM alumno a
join carrera c on a.idCarrera=c.idCarrera
group by a.idCarrera;

here 'male' and 'female',change this with which you want to count from column
Comment: Is good but I put the gender vertically and do not put it horizontally
Comment: please show me your Gen_alum data
Comment: You're a genius, thank you, I worked perfectly! I apologize a little for my lack of congruence when I ask, I speak very little English: /
Comment: welcome dude.thanks for accept the answer.


Solution verification: Prove $f$ doesn't take the value $14$ for any integer input.

Question:
Let $f\in\mathbb Z[x]$ be a polynomial with integer coefficients, s.t.
  it takes the value $7$ for $4\;\text{distinct integers}$. Prove $f$
  doesn't take the value $14$ for any integer input.

My attempt:
$$f(\alpha)=f(\beta)=f(\gamma)=f(\delta)=7,\;\;\alpha\ne\beta\ne\gamma\ne\delta\in\mathbb Z$$
From the fact: $$\forall x,y\in\mathbb Z\;\;x\pm y\in \mathbb Z$$
$$g(x):=f(x)-f(\alpha)=f(x)-f(\beta)=f(x)-f(\gamma)=f(x)-f(\delta)$$
$$\implies g(x)=(x-\alpha)(x-\beta)(x-\gamma)(x-\delta)q(x)$$
Let $\varepsilon\in\mathbb Z$.
$$f(\varepsilon)=14$$
By the above definition of $g(x)$, for $g(\varepsilon)$:
$$g(\varepsilon)=(\varepsilon-\alpha)(\varepsilon-\beta)(\varepsilon-\gamma)(\varepsilon-\delta)q(\varepsilon)$$
$$\alpha\ne\beta\ne\gamma\ne\delta\ne\varepsilon\in\mathbb Z\implies\;(\varepsilon-\alpha)\ne(\varepsilon-\beta)\ne(\varepsilon-\gamma)\ne(\varepsilon-\delta)\in\mathbb Z$$
$14$ can be factorised by at most $4\;\text{distinct integers}$,e.g.:
$$14=1\cdot(-1)\cdot(-2)\cdot7\leftarrow\;\text{one permutation}$$
Therefore,$f$ doesn't take the value $14$ for any integer input.
Is this legitimate?
Comment: $g(\varepsilon)=7$, not $14$.
Comment: But is $q(\varepsilon)$ required to be distinct from all the other factors?
Comment: Already answered here: [Polynomials and Arithmetic: If $p(x_i) = 7$ for four integers, then $p(z)\ne14$](https://math.stackexchange.com/questions/1617628/polynomials-and-arithmetic-if-px-i-7-for-four-integers-then-pz-ne14)
Comment: @Arthur, but they aren't distinct then.
Comment: @TonyK, I haven't found that thanks for contributing, but I'm still wondering if my answer is precise and correct.
Comment: You could have $q(\varepsilon)=\pm 1$ without any issues, though, couldn't you?
Comment: @mathlove, thank you for noticing!
Comment: @metamorphy, I hadn't found that until I saw the link in comments because I translated it into English how it was written in my mother tongue. Users also responded here on the question if what I wrote is correct or not, so my question is answered just like yours.
Answer: The idea of your argument is excellent, and it can be written correctly as follows.
Let $g(x)=f(x)-7$; then $$g(x)=(x-\alpha)(x-\beta)(x-\gamma)(x-\delta)q(x).$$
Now, for contradiction, suppose that $f(n)=14$ for some $n$; then $g(n)=7$. But if $g(n)=7$ for some integer $n$, then
$$7=(n-\alpha)(n-\beta)(n-\gamma)(n-\delta)q(n).$$
$7$ can be expressed as the product of at most 3 distinct integers and so cannot have the four distinct factors $$(n-\alpha),(n-\beta),(n-\gamma),(n-\delta)$$
Comment: Let me fill in a step that I'd have found helpful here: Right after "let $g(x) = ...q(x)$", perhaps one should say, "Now, for contradiction, suppose that $f(n) = 14$ for some $n$; then $g(n) = 7$. But if $g(n) = 7$, then ..."
Comment: Yes, good idea - I've added it in the hope that it helps the OP
Comment: @S. Dolan Thank you very much for the explanation and correction!


How to fit 4" rigid aluminum duct vent in between walls when there is an angle brace?

Question: I want to do what these people have done here:

The problem is I have bracing going diagonally and it is not leaving enough space for the 4" aluminum duct vent.

Can I saw the bracing off for the 1 section where I need to pass the pipe?
I assume not..
What else can I do ?
Comment: Looking really closely at the sample picture that you showed it appears that the area where the duct is routed is using a 2x6 stud.
Comment: Be careful of your length of run, it is not recommended to go over a certain amount of feet, usually 35 ft, and that is straight run only. THEN deduct an additional 5 ft for every elbow in the run. If it is possible, run the duct down and through a floor joist section out through a side wall.
Answer: I wouldn't build it that way in the first place. Hiding a dryer duct within a wall and venting it through the roof (I'm guessing here, but that's what it looks like to me) is just begging for nobody to clean it until it eventually catches fire and burns the house down.
I recently re-did my utility room and discovered an in-wall rigid steel duct just like the one in your picture which vented through the roof. Clearly nobody ever cleaned it due to the annoyance of having to get up on the roof, and as a result it was entirely blocked by lint and dust, with a bunch of creepy-crawlies living in it due to disuse and abundant organic material during an unoccupied period. Not only that, but a section of the ducting had gotten open and was depositing moist air right into the wall cavity, which eventually invited termites into that wall:

Do the world a favor and don't hide your dryer ductwork inside a framed wall and vent it through the roof!
Comment: I agree but I have no choice due to how the house is constructed.
Comment: Even if you have to vent it through the roof because the laundry room doesn't touch an exterior wall, you can still leave the exhaust duct out in the open. That way, it'll never become "out of sight, out of mind." It'll be uglier, but it may prevent a fire.
Answer: One thing you could look into would be flat oval ducting:

You can get it as small as 3" in the smaller dimension, but it will likely be a lot harder to find and a lot more expensive. Also, it will compound the issue @iLikeDirt pointed out in keeping it clean, especially if you have transitions to round pipe anywhere. I would also limit yourself to one transition for that reason - a round-oval-round would collect a ton of lint.
Answer: Another alternative is to build out one side of the wall that is away from the brace side. For example you could attach 2x2s to the edge of each stud to open up the wall cavity to another 1.5". This actually removes only a small amount of finished space in the room. If done all the way across one wall surface you would probably hardly realize that that one wall was "thicker" once all finished off.
Answer: I definitely agree with iLikeDirt, but if you have no choice you can use oval duct such as this: http://www.deflecto.com/products/pc/Skinny-Duct-Aluminum-Dryer-Vent-br-4-Oval-Duct-Adjustable-27-48-4p445.htm
If anything, as a safety precaution you should foil tape ALL joints and even elbows. I do this as standard even for exposed duct work. DO NOT use typical duct tape as "duct tape" is terrible for duct work since the glue does dry out over time and will eventually fail.
An example of foil tape: http://www.homedepot.com/p/Nashua-Tape-322-1-57-64-in-x-50-yds-Aluminum-Foil-Tape-3220020500/100030120
Interesting read: http://www.lbl.gov/Science-Articles/Archive/duct-tape-HVAC.html
Answer: The brace you refer to was probably put there to keep the house framing square until all exterior sheathing was installed. The sheathing now serves as bracing long as it was nailed to code. Cutting a notch in the bracing seems a fine alternative long as you inspect lint buildup in venting at regular intervals. After the install you can put hurricane straps connecting that brace which is thin and sheetrock can go over it without noticing.
Comment: Temporary construction braces are generally not left in place - if the brace is there in a finished house, it's a part of the load design of the house, and not something that should be removed/cut.


Using :inner_lateral in Ecto Elixir

Question: I was trying to use ecto's :inner_lateral And I wrote this query
SnapshotExtractor
|> order_by(desc: :created_at)
|> limit(1)
|> join(:inner_lateral, [se], cam in fragment("SELECT * FROM cameras as cam WHERE cam.id = ?", se.camera_id))
|> select([se, cam], { se.from_date, se.to_date, se.interval, se.schedule, cam.exid, cam.timezone})
|> Repo.one

Its working fine and giving me good resuls but its giving me an un-named object, no name with the resulting values.. Question is can we add names to the values as well? my resulting values are
{#Ecto.DateTime<2016-02-25 00:00:00>, #Ecto.DateTime<2016-02-25 00:00:00>, 0,
 %{"Friday" => [], "Monday" => ["0:0-0:0"], "Saturday" => [], "Sunday" => [],
   "Thursday" => [], "Tuesday" => [], "Wednesday" => []}, "oscar2", nil}

Answer: The thing you're referring to as "unnamed object" is a tuple. You're getting that back because your select expression is a tuple. You probably want a Map if you want to give them names. To get back a Map, just return a Map in the select expression:
|> select([se, cam], %{ from_date: se.from_date, to_date: se.to_date, interval: se.interval, schedule: se.schedule, exid: cam.exid, timezone: cam.timezone})

If you assign the return value to foo, you can access the fields using foo.from_date, foo.to_date, etc.
Comment: Thanks.. I wasnt aware of this! after 7 minutes.. I will accept the answer.

Using :inner_lateral in Ecto Elixir


top command in shell script

Question: I am trying to get first 5 lines of top command through expect script. Im calling this expect script from a shell script along with some other stuff.
top | head -5 gives me below output ie without cpu stats-

top - 09:10:58 up 46 days, 17:03, 12 users,  load average: 0.01, 0.02,
  0.00 Tasks: 138 total,   1 running, 137 sleeping,   0 stopped,   0 zombie
Mem:  16432400k total,  8408096k used,  8024304k free,   609200k
  buffers Swap:  6290736k total,        0k used,  6290736k free,
  6754356k cached

If I run just top command on that remote server I can see there is a 2-3 second delay before the CPU states line is updated, can some one please help me to get all 5 lines with updated cpu states? Below is my expect script -
#!/usr/bin/expect -f
set user1 abc
set pass1 pass
set timeout 8
match_max 1000
spawn ssh -C -o stricthostkeychecking=no $user1@<ip>
expect "*?assword:*"
send  "$pass3\r"
expect "?xterm*"
send "\r"
send "top | head -5\r"
expect eof

Answer: You need to run top in batch mode instead of the default interactive mode. In addition you need to define the number of iterations that top performs for getting its measurements.
num_iterations=3
top -b -n $num_iterations | head -5

If you want the output to only list the top 5 processes and skip the statistic header displayed, you can try this:
num_iterations=3
top -b -n $num_iterations | sed -n '8,12p'

Also tune the value of num_iterations as per your need.
Comment: Yes that is correct. You can tune the value of num_iterations as per your application need.
Comment: You mean in expect script I need to add set num_iterations 3, and send "top -b -n $num_iterations | head -5" ? If so, Im getting the same output without CPU stats, On just a taught can we some how specify wait x seconds before output is piped to head command?
Comment: Do you need output for only the top 5 processes ? I find that replacing `head -5` with `head -12` lists the top 5 processes. If you want to skip the header and grab the info only for the top 5 processes, you could do `top -b -n 3 | sed -n '8,12p'`. The sed command selects lines 8-12 in the output.
Comment: Thank You for your help Tuxdude, it dint work for me..the cpu stats dont populate no matter what I try..
Comment: try top -b -n 2. This returns cpu% in second iteration.
Answer: top -b -n 2 -u $(whoami) | grep -A6 -B5 PID |tail -12

Adjust below values as per requirement.
grep
  -A$after_lines_count
  -B$before_lines_count
tail -$($after+$before + 1)
tail value should be [ before lines count + after lines count + 1 (PID match line) ]
If you don't want user specific details.
  top -b -n 2 | grep -A6 -B5 PID |tail -12

Note: Number of top iterations are 2 (top -n 2) i.e, it takes 6 sec to display output ( depends on delay set per iteration)
Comment: if you need only five lines use this
"  top -b -n 2 | grep  -B6 PID |tail -7 |head -5  "

top command in shell script


Ubuntu 17.04: Starting up laptop with lid closed

Question: I'm using my Fujitsu Lifebook E746 laptop on a dock with 2 external monitors, so I'm usually not using the integrated laptop monitor. The problem I'm having is the following:
Starting up the device lid closed from the power button on the dock seems to still have the integrated display active. I can enter login credentials etc. on the external monitors and startup is fine, BUT the display is still on, so i can move windows to that screen, which is pretty annoying.
This can be fixed by opening the lid and closing it again to disable the display, but that's way annoying.
Is there a way to have the integrated display disabled when starting up with the lid closed?
Answer: I had the same problem, but i use arch linux with xfce4, all i did was disable the monitor completely. the problem is the in built monitor will always be disabled and you cannot use the laptop without the external monitor(s).
how i did it


Server.Transfer, session state null

Question: Why is the session state null when you use Server.Transfer? Is there anyway to enable the session? (session state is already enabled and working fine, it's just that HttpContext.Current.Session is null when you Server.Transfer into a new page within the same site)
Answer: Add this to your page.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="NewPage" **EnableSessionState="True"** %>

May be try this as well: Context.RewritePath instead of sever.transfer
Answer: I am not sure if this is a duplicate or just very similar. However, it does look a lot like a duplicate of this question
Either way, it looks like somebody already had a bear of a time with it or else it would not have had a 200 point bounty :). So, hopefully you can benefit.
Answer: Could you check if the enableSessionState="true" is set in the page tag in the web.config?
Comment: It's already enabled, tried Inproc, Stateserver etc. SessionState is always null when you use Server.Transfer.

Server.Transfer, session state null


Controlling LED's with PCA9685

Question: I have bought an Adafruit PCA9685 and completed the library installation, however, I have no clue of how to Program it. I want to base it on the following code I wrote:
import RPi.GPIO as GPIO
import time
import sys
from pubnub import Pubnub

GPIO.setmode(GPIO.BCM)

PIN_LIVING = 22
PIN_PORCH = 17
PIN_FIREPLACE = 27

GPIO.setup(PIN_LIVING,GPIO.OUT)
GPIO.setup(PIN_PORCH,GPIO.OUT)
GPIO.setup(PIN_FIREPLACE,GPIO.OUT)

FREQ = 100 # frequency in Hz
FIRE_FREQ = 30 #  flickering effect

# Duty Cycle (0 <= dc <=100)

living = GPIO.PWM(PIN_LIVING, FREQ)
living.start(0)

porch = GPIO.PWM(PIN_PORCH, FREQ)
porch.start(0)

fire = GPIO.PWM(PIN_FIREPLACE, FIRE_FREQ)
fire.start(0)

# PubNub

pubnub = Pubnub(publish_key='demo', subscribe_key='demo')

channel = 'pi-house'

def _callback(m, channel):
    print(m)

    dc = m['brightness'] *10

    if m['item'] == 'light-living':
        living.ChangeDutyCycle(dc)

    elif m['item'] == 'light-porch':
        porch.ChangeDutyCycle(dc)

    elif m['item'] == 'fireplace':
        fire.ChangeDutyCycle(dc)

def _error(m):
  print(m)

pubnub.subscribe(channels='pi-house', callback=_callback, error=_error)

try:
    while 1:
        pass
except KeyboardInterrupt:
    GPIO.cleanup()
    sys.exit(1)

I dont know if on this its similar. I bought it because I wanted to be able to control more LED's with PWM from the Raspberry pi. I looked into it and found all kinds of weird commands and terms specific to this Chip.
Thanks!
Comment: I looked at this tutorial (https://learn.adafruit.com/downloads/pdf/adafruit-16-channel-servo-driver-with-raspberry-pi.pdf) and a) it only works with servos, b) it didn't work. Is it really that complicated to control LED's with this device?
Comment: Can someone give me some info on this or provide me with links because I haven't found anything to control LED's.
Comment: *" it only works with servos"* How do you know? Does it actually say that in the guide? (I don't see why it wouldn't work with other stuff)
Comment: Is it completely necessary to have a 5V power from the power outlet, or can it be from a battery?
Comment: *"The PCA9685 operates with a supply voltage range of 2.3 V to 5.5 V (...)"* Check [the data-sheet](http://cache.nxp.com/documents/data_sheet/PCA9685.pdf)
Comment: Because when I tried it, the power indicator (led) that was on, turned off when I ran the test programm
Comment: Can someone mark this question as answered?
Answer: First, If you look at page 29 of the data sheet (fig. 15) it shows that for Direct LED connection, you need to connect your LEDs inverted. i.e. connect the ground of the LED to the PWM line on the PCA9685 and the positive of the LED to the V+
Code is pretty simple (below is for an Arduino) And you use the function pwm.setPWM(uint8_t num, uint16_t on, uint16_t off) to turn the LEDs on and off and to different levels of brightness.
#include <Wire.h>
#include <Adafruit_PWMServoDriver.h>

Adafruit_PWMServoDriver pwm = Adafruit_PWMServoDriver();

void setup()
{
Serial.begin(9600);

pwm.begin();
pwm.setPWMFreq(1600);  //This is the maximum PWM frequency

pwm.setPWM(1,0,4095); //this turns on the LED connected to channel one (I suspect the only line you're really looking for)
}

Hope that answers your question!
Answer: See below how to do this in python
import Adafruit_PCA9685
pwm = Adafruit_PCA9685.PCA9685()

pwm.set_pwm_freq(60)

# Demo using LED on Channel 12 of the PCA9685
# Wire up the LED  on  Channel 12 such that
#    Shortleg of LED goes to GND and
#    Long leg goes to PWM pin on channel 12

pwm.set_pwm(12,0,4095)   # Full bright
time.sleep(5)

pwm.set_pwm(12,1024,3072) # half bright
time.sleep(5)

pwm.set_pwm(12,0,0)  #off
time.sleep(5)

Controlling LED's with PCA9685


What should the default value be for a credit card expiration date?

Question: What is the optimal default value for a credit card expiration date?  The only value I've ever noticed in practice is either the current month or the earliest possible month (January 1900 or similar).
Comment: Why have a value at all? It will almost never be correct.
Comment: The earliest possible month _is_ the current month. If a card expires in January 1900, it's not useable anymore.
Comment: I hate it when forms prefill in the expiration date.  It's useless and can introduce more work for a user.
Comment: @jcuenod It's work that the user has to undo.  The user might have to clear the field.  If it's a drop-down list, instead of being able to have a habit of pressing the down arrow a fixed number of times to get to a particular month, now it's variable.  It's pointless additional work.
Comment: If the user has to select a month and year, by not pre-populating all you do is guarantee that s/he has to fill stuff in. In a dropdown changing the value is the same whether the default is a placeholder or not. No user memorises "5 down clicks for the month field" there's not enough consistency in all the interfaces that we come across to train ourselves like that. The only thing that may cause more work is if the user doesn't realise the values are wrong and submits the form but then you can quickly point the user to the fact that the expiration date is unchanged and was probably overlooked.
Comment: Consider using text inputs instead of dropdown menus. That allows me to type the month I have memorised or transcribe it from my card without having to locate anything in a list.
Comment: @jamesdlin How on earth can it "introduce more work for a user"?
Comment: @jcuenod The user's going to have fill stuff in anyway, because filling in the current month/year is almost never going to be correct.  You might not think that users memorize "5 clicks down for the month field", but *I* do that for shopping sites that I frequent.  It doesn't necessarily have to be consistent across different sites, but for sites I use a lot, it should at least be consistent *every time I visit them*.
Comment: @FedericoPoloni yes, but the behaviour is far from ideal, especially for years (firstly my card shows the expiry year as two digits, so I have to recognise the different pattern, secondly typing "2017" into a field currently set to 2015 does nothing at all in response to my first three key presses). I don't really understand the value in putting this sort of thing into a drop-down.
Comment: @jcuenod: Maybe my card really does expire this month.  The only way to know i didn't mean it, would be to make the default a nonsensical value.  Not just invalid, but so invalid that i never would have entered it.  (Making it blank would serve this purpose as well, if the field is required.)
Comment: @RemcoGerlich: The earliest possible month can be a month in the future, if the credit card must be valid for at least x more months.
Comment: @KitGrose I understand your point about it not being user-friendly, but in fact you *can* enter data in a drop-down menu by typing them. After typing your name on the card,  02  2015 works on most systems. The first matching entry gets selected as you type.
Comment: @FedericoPoloni: I remember seeing it not work that way in Chrome without JS to fudge it.  Has that changed recently?
Comment: @cHao Works for me (Linux/Chromium, I don't have a Windows box to test it there): http://jsfiddle.net/yhgq13rx/.
Answer: Entering a default month and date can be confusing to a user because you are presuming an answer.
As a result, the user may skip over the field, if she is in a hurry,  or assume it has been auto-filled after she entered her credit card number.
A placeholder value is better, you can use:
MM  / YYYY
This indicates to the user (a)  what the format of the date is; and (b)  that the field is still empty and needs to be filled out.
Alternatively you can also use blanks, which visually indicate the empty field (and are visually compatible with the empty text box to the left), but they are not as informative.
Comment: A placeholder text with one valid format is a good idea. But actually requiring all users to enter the exact same format is not such a great idea, because regardless of which format you chose, half the users will think your chosen format is stupid and wrong. I'd rather allow the users to enter the month in any format of their choosing, as long as it is unambiguous.
Comment: @kasperd while this may be true of other use cases (e.g. entering a date for a calendar entry), I disagree in this case.  Open formatting is not necessarily better for users, because a blank textbox that says "enter a date" (a) forces the user to think more than a format cue (cognitive load);  (b) creates unnecessary semantic issues  (e.g. if a user enters 1 Oct 2017 when the payment process just needs month and date, there is a semantic mismatch which leaves the user feeling disoriented); (c) creates  language side effects that you now have to deal with (e.g.In russian:  1 октября 17)
Comment: I specifically said that a placeholder text with one valid format is a good idea. There doesn't have to be any suggestion to the user, that the form supports any other format. However if the user does enter an unambiguous date in a different format, I would consider it more user friendly to accept that input.
Answer: I would have no usable default, so if the user skips it, the page doesn't post, and it indicates the expiration date in a red outline, bold type, or some other fairly obvious means, mainly so the user knows they missed a field, as opposed to typoing a CAPTCHA or something like that.
As stated above, I'd have MM-YY as defaults, and when the year elapses, remove any values that are not of this year.  I'd even consider entering a value earlier than the month of the current year cause an immediate error (or at least prevent the page from being submitted.)  This is mainly a sanity check.
Instead of typing in, I'd probably consider a pop-up menu.  This way, someone typing in 01-2015 can be notified that the date they inputted in is a no-go, and to change it.
Comment: If you mean that somebody entering "January 2015" should receive a warning now that it's March, I agree. If you mean that the interface should start making quizzical looks at you and mouthing "Are you sure?" as soon as the user enters "January" and it's later in the year than that, everybody with a January-expiring card will hate you for eleven months of the year.
Answer: In most cases there are 2 main criteria that default value have to satisfy

It must be valid. When user submits the form, fields with default values should not cause a validation errors.
Value must be more common than the other values. For instance, if application is showing a monthly financial report and you are asking a user to pick the month, it is more likely that user will pick the current month.

In case of expire date, you can't have a valid value, it strictly depends on user, and all option are equally likely os there is not usual value.
Comment: It would be interesting to have statistical datas to confirm equal repartition of date. I presume the next 2 years will be definitely more represented. As for the months, I am curious if there is any significant seasonality (for instance, low frequency of summer months due to lower activity, or alternatively higher frequency due to people getting international credit card for holydays). From a UX perspective, I assume that having an arbitrary date as default would be more confusing than anything else and might require explanation (and/or critical mass) before reaching efficiency gain.


StackOverflowException when adding a row to a datatable

Question: Using recursion to build up the hierarchy.
This recursion works fine in windows server 2003 + IIS6 but throwing exception in windows server 2008 R2 and IIS 7.0
Here is the code snippet:
Public Sub Expand(ByVal SE_Index As Int64)

    Dim row As DataRow

    If aryHierarchyData(SE_Index).Visable = True Then
        aryHierarchyData(SE_Index).Target_Row = gvCurrent_Row_Number
        gvCurrent_Row_Number = gvCurrent_Row_Number + 1

        Try
            row = dtExpand.NewRow
            row("SE_NO") = aryHierarchyData(SE_Index).SE_No
            row("Selection_Index") = aryHierarchyData(SE_Index).Selection_Index
            **dtExpand.Rows.Add(row)**--->>>throwing error "stackoverflow"

        Catch ex As StackOverflowException
            If (ex.Message.Contains("Column 'SE_NO, Selection_Index' is constrained to  be unique.")) Then
                Exit Sub
            End If

        Catch ex As Exception

        Finally
            row = Nothing
        End Try

        ' expand this SE's children  -  first
        If aryHierarchyData(SE_Index).Child > 0 Then
            Expand(aryHierarchyData(SE_Index).Child)
        End If
    End If

    ' expand this SE's Siblings  -  second

    If aryHierarchyData(SE_Index).Sibling > 0 Then
        Expand(aryHierarchyData(SE_Index).Sibling)
    End If

End Sub

Comment: I dont think it is because of IIS and windows server. I think it is because of data. In [msdn](http://msdn.microsoft.com/en-us/library/system.stackoverflowexception(v=vs.80).aspx) it is clearly stated that "**The exception that is thrown when the execution stack overflows because it contains too many nested method calls. This class cannot be inherited.**
"
Answer: This exception is depending on computer memory and Framework. It has nothing to do with IIS and windows server.
The exception that is thrown when the execution stack overflows because it contains too many nested method calls. This class cannot be inherited.MSDN
I tried your code with some changes. I alter above statement according to my experience
Framework 4.0
The exception that is thrown when the execution stack overflows because it contains 7573 nested method calls. This class cannot be inherited.
Framework 2.0
The exception that is thrown when the execution stack overflows because it contains 7038 nested method calls. This class cannot be inherited.
Comment: Thanks for your reply.Am using windows server 2008 R2 ,IIS 7.0 and .NET 4.0.Without changing code,what changed need to be brought in computer memory or framework.We have upgraded application from .net 2.0 to .net 4.0
Comment: Well i did not tried with windows server 2008 R2, IIS 7.0 and .NET 4.0. Well i think what you have to do is to increase the stack size May be this article could help you [http://www.atalasoft.com/cs/blogs/rickm/archive/2008/04/22/increasing-the-size-of-your-stack-net-memory-management-part-3.aspx](http://www.atalasoft.com/cs/blogs/rickm/archive/2008/04/22/increasing-the-size-of-your-stack-net-memory-management-part-3.aspx)
Answer: Stackoverflow problem could be solved using thread.
Call expand() under recursivethread function.

Private Sub RecurseThread(totalSeCount As Long)
 For iIdx = 1 To totalSeCount
    If aryHierarchyData(iIdx).Target_Row = 0 Then
    dtExpand.Clear()
    dtExpand.AcceptChanges()
    Expand(iIdx)
  End If
Next iIdx
End Sub

Dim t As Thread = New Thread(AddressOf RecurseThread, 1024 * 1024)
t.Start(totalSeCount)
t.Join()


Very low hot water pressure entire house

Question: Setup: Electric 53 Gallon Heater, installed in 2014 by previous owners.
Location: Tampa bay, Florida, Home built in 1961, typical cinder block house.
WE purchase the home in December and all has been working great.
Issue: Very low hot water pressure in the entire house. Water begins when first turned on with an acceptable amount of pressure but quickly over a few minutes drops to very low pressure. Enough time for a 5 minute shower, if that!
We called a plumber out and they recommended to replace the water heater. They suggested there is probably a clogged line in the water heater itself?
What I have done: I have drained the hot water heater from the bottom of the tank for about 5 gallons, there was no sediment what so ever at the bottom.
Any ideas?
Comment: Do you have the same issue if the cold water is left for the same amount of time?
Comment: @apeek2901 we assume you have found your answer - can you post it?
Answer: Your house was built at a time when galvanised pipe was common, the problem is most possibly your pipe has slowly corroded closed in 1 or more places, thus when you turn the hot off the pipe charges open and you loose pressure the longer it is on with a new water heater and old house that is what I would look at a switch over to Plastic with some of the new shark bites is not really that hard and you may get all the pressure you have on your cold by just replacing the main line worth a look and cheaper than another water heator that may end up with the same problem
Comment: it seals all but a small fraction so you have pressure to start with but then it falls off, take a hose, turn the water so only a small trickle of water is flowing, now stop the flow out the end of the hose it may even take a minute or so but you will see pressure build, then let the water flow there will big a big burst of flow and it will diminish untill it is at the trickle level again, this is quite common with old galvy lines if they dont start leaking, trying to post a pic of pipe
Comment: I don't follow this logic. If the galvanized pipe were corroding shut, the pressure would always be low. apeek2901 described a problem that develops over the course of about 5 minutes.
Comment: Interesting. So in his case the flow restriction would probably need to be behind the water. I couldn't imagine the small amount of pipe between water heater and fixture storing enough pressure to last 5 minutes but if it's between the water heater and the street, you get the pressure of all the plumbing in the house plus the tank.
Comment: Also, I second the recommendation of plastic (PEX) plumbing as replacement. The best fitting as of 2009 when I replace all my plumbing was the expansion fitting, which requires a special tool but isn't that much more difficult. There are numerous advantages to PEX.
Comment: I typed "picture of galvanised pipe corrosion" it came up with many examples , I hope you look and try the hose thing it will make it clear that What I have explained can be the cause VS an almost new water heator as they said the cold was fine so the main line to the water heater


How can I make an outdoor water feature/fountain out of concrete?

Question: I am looking to create a trough-like basin for two water features I want to place in my yard. I don't consider this to be in the landscaping/gardening department since I am working with concrete. My overall dimensions will be approximately 3ft wide and long by about 14" in height. Inside in the center of the trough I'm going to place a water pump so that a spring will shoot up about ten to twelve inches into the air to create that relaxing sound of splashing water. This will be a modern austere look/style.
It'll sort of look like this:

Taken from this website:
https://www.amazonasmagazine.com/2020/01/09/build-a-lightweight-waterproof-concrete-basin-for-ponds-and-plants/
In the link above the author of that DIY article states this could be used for a pond or aquarium. But then in the Q&A at the bottom he sort of contradicts himself by responding to someone who is asking to make a pond. Well, the contributor is asking to make a very large version on this. Devin Biggs, the author of the online article, responds back by expressing doubt that an 8ft long by 3ft wide version of a foam core concrete basin would hold up to the constant pressure of the weight of the water inside.
This makes me sort of doubtful that even my small dimensions would hold up over time. But then again, I have no idea and have limited experience in working with concrete. Does anyone know if using pink insulation foam board to create concrete troughs will hold up over time? I live in the desert so it'll never freeze. So there is no issue in freezing with water expansion; causing stress on the structure. I like this idea because it will be lightweight and I'd be able to move this, if I so choose.
Otherwise, if making one in solid concrete with rebar and wire enforcements for strength and longevity is the way to go I'll stick with that.
Any feedback?
Comment: Yes, concrete with rebars placed on the stable ground will be very durable.  I would provide a layer of liner on the interior face to prevent leaks from potential cracks, If landscaping block/brick is available, it works for a small to medium-sized pond too.
Comment: If you want light weight ditch the foam and use a product like vermiculite. It will need a wire & rebar mesh for strength but is much lighter than straight concrete, we never went any thinner than 3" for pools, I think planning to move a "pond" is not something I would want to do with a cement product. not getting bedded correctly will damage it after a move, go bigger and just plan on it staying there. If a hot area plan on going deeper I think my aunt had to go 4' deep to keep from cooking her fish it had a small surface area for how many gallons it was and aerator only at night.
Comment: @Adrien  You are missing the third dimension of your proposed basin. Can edit that in? Because whatever you decide remember how much water you will want in the basin for the fountain to run. because the weight of one cubic foot of water is 7.48052 gallons times 8.3453 pounds, which equals 62. 42718356 pounds of water per cubic foot.  I have a lily pond that used to have a 2" concrete base below ground with mesh and rebar and it still cracked under 2 feet of water on top of it.
Comment: Thanks for the comments. I plan to run some pvc through the back in order to have a small ball valve inside the basin to automatically fill the basin with water as it evaporates over time. And I don't plan on keeping fish in this water feature. It gets up to 121 degrees here. The fish would not survive!
Comment: Making it out of cement, it will not be light weight.  Might move it with a good size ATV.
Comment: @ G Warner - I wonder if your pond cracked because you didn't compact the ground area that it sat on. I use a tamper and pound the heck out of the ground area when I do sidewalks. Also, did you place a layer of uniform gravel and compact that first? That's what I'm going to do if I go with solid concrete. Mine will only be 14" tall.
Answer: For consideration

Once you buy the water trough you are done.  They come in a range of sizes.  They will hold water a long time.   They are not expensive.  In the desert where you live there will be a store for people who keep animals and you can look at troughs there.
If the trough you like stands too high, set it down into the ground a few inches.  If you are digging the chic look of concrete you can stack cinderblocks around the trough to occlude it from view.  Or you can use rocks you find on your land, or salvaged bricks or timbers or stucco it or whatever you like.  All the trim will be purely decorative which frees you up as regards choices.
Comment: Yup. Troughs like that come in many sizes and materials. Getting one big enough to line with some sort of brick/block material and still have the interior dimension desired would be the way to go. Any sort of farm supply store will have them in every size imaginable.
Comment: Yes; go with plastic or rubber sheet liner . At least to find out if you really want a fountain.   I have a standard pond liner  ( HPDM ?) which is fine after 20 years.


Problem with Latin character using JavaDocx

Question: I just got JavaDocx free library two days ago. I'm trying to generate a file which has to contain Latin characters as ó, ú, etc. When I try to open the generated file, Word shows me a message that the file cannot be open because a the file has a not valid xml character.
Thanks for your help
Comment: I wonder if the answer at http://stackoverflow.com/questions/1571626/simplyxml-and-accented-characters-in-php/1572421#1572421 would help you.
Comment: Hi! We've seen this same question at JavaDocx forums and apparently the user came to the solution by himself, because a few hours later he posted: "The problem is solved!!! The problem was that the encoding used by eclipse is cp1252, thus the solution was to change the encoding to utf8."

It's not a library issue, but we thought this info could be useful for those in the same case as user783057 so we posted it here :)

Cheers,
JavaDocX Team
Answer: If it's latin-1, you might try tell your xml-file that
<?xml version="1.0" encoding="ISO-8859-1"?>

If it's utf-8 the same goes
<?xml version="1.0" encoding="UTF-8"?>

If you open up your xml-file in a decent text editor (eclipse to name one), you can check out its properties.  There you can see what encoding the file is interpreted in.
I personally think Latin-1 is seldom the right choice due to its narrow character-set.
(no € for example)


no wifi adaptor found for hp15da0327tu

Question: I have installed ubuntu 18.04 onto hp laptop within modal hp15da0327tu and the kernel version of my system is 5.3.0-28-generic.
but I'm not able to use wifi internet.
please help me with this.
Comment: FYI: You are using a EOL kernel, a fully upgraded Ubuntu 18.04 system should be using the 5.4 kernel (as 5.3 is EOL).  Have you not upgraded via ethernet? or are you using something other than Ubuntu 18.04 LTS (as 5.3 is unsupported)
Comment: I'm using ubuntu only and i also upgraded via ethernet but when i update kernel version it was not taking boot so i have to remove version 5.4
Comment: What is your output of 'lspci -k | grep Network'?
Comment: 02:00.0 Network controller: Realtek Semiconductor Co., Ltd. Device d723
Answer: I have had problems getting WiFi to work with countless laptops and versions of Ubuntu down the years.
After much time wasted trying to fix this I eventually bought one of these:
https://www.amazon.co.uk/TP-Link-TL-WN823N-Wireless-Supports-10-9-10-13/dp/B0088TKTY2
I have never looked back.
Answer: First, check your kernel version with uname -r, then

sudo apt install linux-headers git build-essential wget unzip dkms (linux-headers of installed kernel version, you may use synaptic package manager)
wget -d -c -O 'rtl8723de.zip' https://github.com/smlinux/rtl8723de/archive/4.11-up.zip to download the driver zip file for kernel version 4.11 and up
unzip rtl8723de.zip shall unzip the driver folder
cd rtl8723de will take you to the respective directory
make && sudo make install shall install the driver
sudo reboot

P.S. If you're using kernel version 4.10 or down then wget -d -c -O 'rtl8723de.zip' https://github.com/smlinux/rtl8723de/archive/4.10-down.zip shall give you the driver file
Hope it helps

no wifi adaptor found for hp15da0327tu


Dockerfile dependency installed properly but resulting image doesn't have it

Question: I have the following Dockerfile:
FROM ubuntu:trusty
RUN apt-get update
RUN apt-get -y install python-software-properties

Running it with:
sudo docker build -t my_step1 .

I see the bottom line is:
Successfully built b7f1e789d8e8

Which looks promising. However, trying it I get:
avidane$ docker run -it my_step1 bash
root@e6756cdd93bd:/# add-apt-repository
bash: add-apt-repository: command not found

What am I missing?
Comment: What if you add `RUN apt-get -y install software-properties-common` to the Dockerfile?
Comment: That works, many thanks.
Comment: @jdo You might create an answer that can be accepted by author.
Answer: This question is quite specific to Ubuntu and Debian so it probably belongs on askubuntu.com where it's been asked already.
In all versions of Ubuntu based on Debian jessie, you'll find add-apt-repository in the package python-software-common:
sudo apt-get install python-software-common

In all versions of Ubuntu based on Debian wheezy, you'll find add-apt-repository in the package python-software-properties:
sudo apt-get install python-software-properties

Tip: type cat /etc/debian_version in a terminal to find out which Debian version your current Ubuntu distro is based on.
All the jessie/wheezy Ubuntu versions:
15.10  wily       jessie  / sid
15.04  vivid      jessie  / sid
14.10  utopic     jessie  / sid
14.04  trusty     jessie  / sid  <-- the OP is using trusty/jessie
13.10  saucy      wheezy  / sid
13.04  raring     wheezy  / sid
12.10  quantal    wheezy  / sid
12.04  precise    wheezy  / sid
11.10  oneiric    wheezy  / sid

You can look up packages and specific files within packages here:
http://packages.ubuntu.com/
Searching for the file add-apt-repository in Ubuntu trusty:
http://packages.ubuntu.com/search?searchon=contents&keywords=add-apt-repository&mode=exactfilename&suite=trusty&arch=any
File                            Packages
/usr/bin/add-apt-repository     software-properties-common


Horizontal overflow mobile

Question: I've been looking for hours now but can't seem to find the problem to why I have an horizontal scrollbar on mobile screen.
If you need any code, I'd be happy to paste it here but I don't even know what code is necessary.
http://sap.clouddesign.be/public/
Comment: If you are not providing any code, then at least leave the link in place … or just delete the whole question.
Answer: Your .row element in #subfooter has a margin-right:-15px coming from bootstrap.
Normally this is countered by the 15px horizontal padding of the .container element around .rows – but that is missing in this case.
Either put a .container element around the .row, or eliminate that margin-right for that specific element, and the scrollbar will be gone.
Comment: There is already a `.container` around `.row`, plus eliminating `margin-right` doesn't fix it.
Comment: _"There is already a `.container` around `.row`"_ – yes, but for that one you explicitly eliminated the `padding-right` via a rule with selector `#footer #subfooter` in your own stylesheet … _"plus eliminating `margin-right` doesn't fix it"_ – it does for me, at least in Responsive Design View in Firefox.
Answer: You have some div error i think. You can fix this really easy. Just you need to do add   overflow-x: hidden; for body element.

Horizontal overflow mobile


Hit group - export already defined

Question: I am getting this error when creating RTPSO with multiple hit groups:
D3D12 ERROR: ID3D12Device::CreateStateObject: Export "MissIndirect" (mangled name: "\01?MissIndirect@@YAXURayPayload@@@Z") already defined. [ STATE_CREATION ERROR #1194: CREATE_STATE_OBJECT_ERROR]

With single hit group I am not getting any errors and code below works correctly:
void RaytracingResources::CreateRTPSO(ID3D12Device5* device, size_t maxPayloadSize)
{
    // Need 11 subobjects:
    // 1 for RGS program
    // 1 for Miss program
    // 1 for CHS program
    // 1 for AHS program
    // 1 for Hit Group
    // 2 for RayGen Root Signature (root-signature and association)
    // 2 for Shader Config (config and association)
    // 1 for Global Root Signature
    // 1 for Pipeline Config
    UINT index = 0;
    std::vector<D3D12_STATE_SUBOBJECT> subobjects;
    size_t size = 0;
    size += 1; // rgs
    for (auto& hitGroup : m_hitGroups)
    {
        size += 2; // chs, miss
        size += (hitGroup.hitShader.ahs.name != nullptr) ? 1 : 0; // ahs
        size += 1; // hit group
        size += 2; // payload + association
        size += 2; // local root + association
    }
    size += 2; // global root + pipeline config
    subobjects.resize(size);

    std::vector<LPCWSTR> usedNames;
    std::vector<IDxcBlob> usedBlobs;

    // Add state subobject for the RGS
    {
        D3D12_EXPORT_DESC rgsExportDesc = { m_hitGroups[0].rayGenShader.name, nullptr, D3D12_EXPORT_FLAG_NONE };

        D3D12_DXIL_LIBRARY_DESC rgsLibDesc = {};
        rgsLibDesc.DXILLibrary.BytecodeLength = m_hitGroups[0].rayGenShader.blob->GetBufferSize();
        rgsLibDesc.DXILLibrary.pShaderBytecode = m_hitGroups[0].rayGenShader.blob->GetBufferPointer();
        rgsLibDesc.NumExports = 1;
        rgsLibDesc.pExports = &rgsExportDesc;

        D3D12_STATE_SUBOBJECT rgs = { D3D12_STATE_SUBOBJECT_TYPE_DXIL_LIBRARY, &rgsLibDesc };
        subobjects[index++] = rgs;
        usedNames.push_back(m_hitGroups[0].rayGenShader.name);
    }

    for (auto& hitGroup : m_hitGroups)
    {
        //Add state subobject for the Miss shader
        {
            D3D12_EXPORT_DESC msExportDesc = { hitGroup.missShader.name, hitGroup.missShader.exportToRename, D3D12_EXPORT_FLAG_NONE };

            D3D12_DXIL_LIBRARY_DESC msLibDesc = {};
            msLibDesc.DXILLibrary.BytecodeLength = hitGroup.missShader.blob->GetBufferSize();
            msLibDesc.DXILLibrary.pShaderBytecode = hitGroup.missShader.blob->GetBufferPointer();
            msLibDesc.NumExports = 1;
            msLibDesc.pExports = &msExportDesc;

            D3D12_STATE_SUBOBJECT ms = { D3D12_STATE_SUBOBJECT_TYPE_DXIL_LIBRARY, &msLibDesc };
            subobjects[index++] = ms;
        }

        // Add state subobject for the Closest Hit shader
        {
            D3D12_EXPORT_DESC chsExportDesc = { hitGroup.hitShader.chs.name, hitGroup.hitShader.chs.exportToRename, D3D12_EXPORT_FLAG_NONE };

            D3D12_DXIL_LIBRARY_DESC chsLibDesc = {};
            chsLibDesc.DXILLibrary.BytecodeLength = hitGroup.hitShader.chs.blob->GetBufferSize();
            chsLibDesc.DXILLibrary.pShaderBytecode = hitGroup.hitShader.chs.blob->GetBufferPointer();
            chsLibDesc.NumExports = 1;
            chsLibDesc.pExports = &chsExportDesc;

            D3D12_STATE_SUBOBJECT chs = { D3D12_STATE_SUBOBJECT_TYPE_DXIL_LIBRARY, &chsLibDesc };
            subobjects[index++] = chs;
        }

        // Add state subobject for the Any Hit shader
        if (hitGroup.hitShader.ahs.name != nullptr)
        {
            D3D12_EXPORT_DESC ahsExportDesc = { hitGroup.hitShader.ahs.name, hitGroup.hitShader.ahs.exportToRename, D3D12_EXPORT_FLAG_NONE };

            D3D12_DXIL_LIBRARY_DESC ahsLibDesc = {};
            ahsLibDesc.DXILLibrary.BytecodeLength = hitGroup.hitShader.ahs.blob->GetBufferSize();
            ahsLibDesc.DXILLibrary.pShaderBytecode = hitGroup.hitShader.ahs.blob->GetBufferPointer();
            ahsLibDesc.NumExports = 1;
            ahsLibDesc.pExports = &ahsExportDesc;

            D3D12_STATE_SUBOBJECT ahs = { D3D12_STATE_SUBOBJECT_TYPE_DXIL_LIBRARY, &ahsLibDesc };
            subobjects[index++] = ahs;
        }

        // Add a state subobject for the hit group
        {
            D3D12_HIT_GROUP_DESC hitGroupDesc = {};
            hitGroupDesc.ClosestHitShaderImport = hitGroup.hitShader.chs.name;
            if (hitGroup.hitShader.ahs.name != nullptr) hitGroupDesc.AnyHitShaderImport = hitGroup.hitShader.ahs.name;
            hitGroupDesc.HitGroupExport = hitGroup.hitGroupName;

            D3D12_STATE_SUBOBJECT hitGroup = { D3D12_STATE_SUBOBJECT_TYPE_HIT_GROUP, &hitGroupDesc };
            subobjects[index++] = hitGroup;
        }

        // Add a state subobject for the shader payload configuration
        {
            D3D12_RAYTRACING_SHADER_CONFIG shaderDesc = { static_cast<UINT>(maxPayloadSize), D3D12_RAYTRACING_MAX_ATTRIBUTE_SIZE_IN_BYTES };
            D3D12_STATE_SUBOBJECT shaderConfigObject = { D3D12_STATE_SUBOBJECT_TYPE_RAYTRACING_SHADER_CONFIG, &shaderDesc };
            subobjects[index++] = shaderConfigObject;
        }

        // Create a list of the shader export names that use the payload
        {
            D3D12_SUBOBJECT_TO_EXPORTS_ASSOCIATION shaderPayloadAssociation = {};
            if (hitGroup.hitShader.ahs.name != nullptr) {
                const WCHAR* shaderExports[] = { m_hitGroups[0].rayGenShader.name, hitGroup.missShader.name, hitGroup.hitShader.chs.name, hitGroup.hitShader.ahs.name };
                shaderPayloadAssociation = { &subobjects[(index - 1)], _countof(shaderExports), shaderExports };
            }
            else {
                const WCHAR* shaderExports[] = { m_hitGroups[0].rayGenShader.name, hitGroup.missShader.name, hitGroup.hitShader.chs.name };
                shaderPayloadAssociation = { &subobjects[(index - 1)], _countof(shaderExports), shaderExports };
            }

            D3D12_STATE_SUBOBJECT shaderPayloadAssociationObject = { D3D12_STATE_SUBOBJECT_TYPE_SUBOBJECT_TO_EXPORTS_ASSOCIATION, &shaderPayloadAssociation };
            subobjects[index++] = shaderPayloadAssociationObject;
        }

        // Add a state subobject for the shared root signature
        {
            D3D12_STATE_SUBOBJECT rayGenRootSigObject = { D3D12_STATE_SUBOBJECT_TYPE_LOCAL_ROOT_SIGNATURE, &hitGroup.rayGenShader.pRootSignature };
            subobjects[index++] = rayGenRootSigObject;
        }

        // Create a list of the shader export names that use the root signature
        {
            D3D12_SUBOBJECT_TO_EXPORTS_ASSOCIATION rayGenShaderRootSigAssociation = {};
            if (hitGroup.hitShader.ahs.name != nullptr)
            {
                const WCHAR* rootSigExports[] = { m_hitGroups[0].rayGenShader.name, hitGroup.missShader.name, hitGroup.hitShader.chs.name, hitGroup.hitShader.ahs.name };
                rayGenShaderRootSigAssociation = { &subobjects[(index - 1)], _countof(rootSigExports), rootSigExports };
            }
            else
            {
                const WCHAR* rootSigExports[] = { m_hitGroups[0].rayGenShader.name, hitGroup.missShader.name, hitGroup.hitShader.chs.name };
                rayGenShaderRootSigAssociation = { &subobjects[(index - 1)], _countof(rootSigExports), rootSigExports };
            }

            D3D12_STATE_SUBOBJECT rayGenShaderRootSigAssociationObject = { D3D12_STATE_SUBOBJECT_TYPE_SUBOBJECT_TO_EXPORTS_ASSOCIATION, &rayGenShaderRootSigAssociation };
            subobjects[index++] = rayGenShaderRootSigAssociationObject;
        }
    }

    // Setup global root signature
    {
        D3D12_STATE_SUBOBJECT globalRootSig = { D3D12_STATE_SUBOBJECT_TYPE_GLOBAL_ROOT_SIGNATURE, &m_hitGroups[0].missShader.pRootSignature };
        subobjects[index++] = globalRootSig;
    }

    // Add a state subobject for the ray tracing pipeline config
    {
        D3D12_RAYTRACING_PIPELINE_CONFIG pipelineConfig = { 1 }; // Max Trace Recursion Depth
        D3D12_STATE_SUBOBJECT pipelineConfigObject = { D3D12_STATE_SUBOBJECT_TYPE_RAYTRACING_PIPELINE_CONFIG, &pipelineConfig };
        subobjects[index++] = pipelineConfigObject;
    }

    // Finish rtpso creation and store in variable
    {
        // Describe RTPSO
        D3D12_STATE_OBJECT_DESC pipelineDesc = { D3D12_STATE_OBJECT_TYPE_RAYTRACING_PIPELINE, static_cast<UINT>(subobjects.size()), subobjects.data() };

        // Create the RT Pipeline State Object (RTPSO) / Get the RTPSO properties
        ThrowIfFailed(device->CreateStateObject(&pipelineDesc, IID_PPV_ARGS(&m_rtpso)));
        ThrowIfFailed(m_rtpso->QueryInterface(IID_PPV_ARGS(&m_rtpsoInfo)));
    }
}

I am calling it with code below:
CreateRayGenShader(rayGenShader, m_shaderCompiler, L"Shaders/RT_Lambertian.hlsl", 2, 1, 5, {}, L"RayGen");
CreateMissShader(missShader, m_shaderCompiler, L"Shaders/RT_Lambertian.hlsl", L"Miss");
CreateClosestHitShader(hitShader, m_shaderCompiler, L"Shaders/RT_Lambertian.hlsl", L"ClosestHit");

CreateMissShader(missShader_new, m_shaderCompiler, L"Shaders/RT_Lambertian_Indirect.hlsl", L"MissIndirect");
CreateClosestHitShader(hitShader_new, m_shaderCompiler, L"Shaders/RT_Lambertian_Indirect.hlsl", L"ClosestHitIndirect");

HitGroup group = { rayGenShader, missShader, hitShader, L"GroupLambert" };
HitGroup group_new = { rayGenShader, missShader_new, hitShader_new, L"GroupLambert_new" };

m_raytracingLambert = std::shared_ptr<RaytracingResources>(new RaytracingResources(m_device.Get(), m_commandList, model, { group, group_new }));

However, even when I'm trying to create single group, but I am using std::vector to iterate over rgs, ms, chs - it causes same error: (i.e. export "name" already defined [ STATE_CREATION ERROR #1194: CREATE_STATE_OBJECT_ERROR]). Therefore, I am using lengthy code which is called seperately for ms, rgs, chs (and ahs if present).
std::vector<RtProgram> rtPrograms;
HitGroup hitGroup = m_hitGroups[0];
rtPrograms.push_back(hitGroup.rayGenShader);
rtPrograms.push_back(hitGroup.missShader);
rtPrograms.push_back(hitGroup.hitShader.chs);

for (auto& shader : rtPrograms)
{
    D3D12_EXPORT_DESC exportDesc = { shader.name, shader.exportToRename, D3D12_EXPORT_FLAG_NONE };

    D3D12_DXIL_LIBRARY_DESC libDesc = {};
    libDesc.DXILLibrary.BytecodeLength = shader.blob->GetBufferSize();
    libDesc.DXILLibrary.pShaderBytecode = shader.blob->GetBufferPointer();
    libDesc.NumExports = 1;
    libDesc.pExports = &exportDesc;

    D3D12_STATE_SUBOBJECT stateSubobject = { D3D12_STATE_SUBOBJECT_TYPE_DXIL_LIBRARY, &libDesc };
    subobjects[index++] = stateSubobject;
}

Repo with this code can be found here - https://github.com/komilll/RTCP/blob/0b81a41f95ae3fa536324b27201a5fce94f92f24/RTCP/Renderer.cpp#L1039
Answer: I don't know why, but using any loop while using D3D12_DXIL_LIBRARY_DESC is causing problems. It doesn't seem that it goes out of scope, because current code is seperate by blocks with seperate scops already. Therefore I don't think that's what causes problem.
I've dealt with it by simply copy-pasting code and changing index of used data, guarded with (if array.size() > 1). For now, I need only two arrays, but in future, I might add multiple copy-pastes like that. Ideal solution would be either using macros or reaching dxc developers to know what causes problem. However, for my usage purposes it is enough solution.
Also, please take a look at this link - https://www.willusher.io/graphics/2019/11/20/the-sbt-three-ways - it turns to be very useful to understand indexing of miss shader/hit groups data.

Hit group - export already defined


What is the effect from 'change of delivery type' upgrade?

Question: I don't know if that's the right name of the upgrade, please correct it if i'm wrong.
How does the change of cargo (like car parts to hazardous chemicals), the one on upgrades, affects your game/delivery?
I really don't get the direct effect of that upgrade though since it's not explained thoroughly.
Answer: It adds possibility to take this kind of cargo.
On the right side of the transport details mission there is an arrow that specify what kind of cargo you will be given.


Application crashes on device - works perfectly on Simulator

Question: Recently, I have been working on an application. The goal of the application is to show you your last 10 photos taken in the Today view of the Notification Center, among other things. The application works perfectly in the iOS Simulator, but as soon as I put it on a real device for testing, it fails. It returns the error:
fatal error: Unexpected nil while unwrapping an Optional value

Typically this is very easy to fix since XCode highlights the code that returned nil and gives you the opportunity to fix it. In this case, none of my code gets highlighted. Instead, it highlights a line from Thread 1 (Is this the correct term? Thread 1?), as seen below:

Also note that above the highlited line is the line
; function signature specialization <Arg[0] = Exploded, Arg[1] = Exploded of Swift.(_fatalErrorMessage (Swift.StaticString, Swift.StaticString, Swift.StaticString, Swift.UInt) -> ()).(closure #2)

I included this line in the picture because of the "fatalErrorMessage" part of it. I suspect this could clue me in on the error, but I have no idea what this means. I'm not yet to the point of understanding that.
Also, after some thought, I placed a breakpoint at the viewDidLoad() function in the hopes of tracking any nil values, but the code appears to never even get to this point. It seems as if none of my code is being run.
Has anyone had problems like this/understands what that error code (If that's what it is) means? I'm pretty desperate now, hence me being here.
Thanks,
CodeIt
EDIT:
I placed a println line inside the viewDidLoad function to double check if it was being run. The println function runs and outputs correctly, so I think I may just have messed up my breakpoint somehow. Anyway - the code runs, but it still doesn't highlight any of my code causing the nil value.
EDIT 2:
As requested, I have inserted parts of my code. Please keep in mind that this code is a "first draft", if you will, and I have not yet gotten around to cleaning it up. I'm just trying to get it to work:
@IBOutlet weak var currentPosLabel: UILabel!
var currentImgPos = 0
@IBOutlet weak var imageView: UIImageView!
var images: NSMutableArray!
var totalImageCountNeeded: Int!

func fetchPhotos() {
    images = NSMutableArray()
    totalImageCountNeeded = 10
    self.fetchPhotoAtIndexFromEnd(0)
}

func fetchPhotoAtIndexFromEnd(index: Int) {
    let imgManager = PHImageManager.defaultManager()

    var requestOptions = PHImageRequestOptions()
    requestOptions.synchronous = true

    var fetchOptions = PHFetchOptions()
    fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]

    if let fetchResult = PHAsset.fetchAssetsWithMediaType(PHAssetMediaType.Image, options: fetchOptions) {
        if fetchResult.count > 0 {
            imgManager.requestImageForAsset(fetchResult.objectAtIndex(fetchResult.count - 1 - index) as? PHAsset, targetSize: view.frame.size, contentMode: PHImageContentMode.AspectFill, options: requestOptions, resultHandler: { (image, _) in
                self.images.addObject(image)
                if index + 1 < fetchResult.count && self.images.count < self.totalImageCountNeeded {
                    self.fetchPhotoAtIndexFromEnd(index + 1)
                } else {
                    println("Completed array: \(self.images)")
                }

            })
        }
    }

}

override func viewDidLoad() {
    super.viewDidLoad()
}

override func viewDidAppear(animated: Bool) {
    // NOTE: I am calling the fetchPhotos() function here since earlier in my debugging I thought the problem may be that I was calling it too early in the viewDidLoad function. It an incorrect theory, but it was worth a try.
    fetchPhotos()
    if images.count > 0 {
        imageView.image = images[1] as? UIImage
    }
}

I removed some parts of the code that I know have no reasons to cause my error, such as @IBActions, didReceiveMemoryWarning(), etc..
Comment: Just to be clear, you have set an Exception breakpoint?
Comment: @Allan Chau, Originally I just click on the side bar by a line of code to add a breakpoint. Is this an exception breakpoint? I don't think so, but I'm not sure. I'm not all that familiar with the different types of breakpoints. I have just tried adding an exception breakpoint set to All Exceptions, but it stops at the same area.
Comment: Did you find any solution for it  ?? Even I am facing the same problem..!!
Comment: @IrshadQureshi (This is a rather late reply to your question. Apologies!) The accepted answer is the answer that *might* have fixed my problem. However, I did the steps seen in the accepted answer after the Swift 1.2 to Swift 2.1 update. Anything could have changed with XCode in this update, so I'm not sure if the accepted answer really fixed the problem. It is, however, the most likely answer. I suggest trying it out and then letting us know how it worked for you.
Answer: Even it's old question. I found my issue by deleting derived data from xcode.
Xcode -> window->Projects then select and delete your project derived data.
Comment: was that the only thing that solved the error ? I'm having the same issue as well
Comment: I dug up the project and updated it from Swift 1 to Swift 2.1. When I ran it on my device, it no longer had the error. Any number of things could have changed when I updated it from Swift 1 to Swift 2.1, but before running it on my device, I had tried what you suggested. I'm going to accept your answer because it may have been what fixed it (Although I'll never know if it was the answer or if it was something else).
Answer: I don't think it is possible to determine exactly where the problem is without seeing your code.
Somewhere in your code you may have forced downcast a variable as!. If you change this to:
if let variable = optionalVariable as? SomeClass {
    //Insert your code
}

Then this should fix your problem. Read this to learn more about casting in swift:
https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TypeCasting.html
Comment: I have gone through and replaced my "as!" with "as?", but it still is not fixing the problem. Thank you for the link - I will take a look and learn about proper casting! Also, I have updated the question to include code that I think is relevant to answer this question. It's currently pretty messy.
Comment: have you put code in your app delegate? I think the problem is happening before this view controller calls viewDidLoad. Perhaps check the currentPosLabel or imageView link in your storyboard.
Comment: I have no excess code in my AppDelegate, and I have double checked all the links in my storyboard items. All IBOutlets/IBActions are correctly connected. If these was a problem with the connections I would expect it to show up when ran on the Simulator. The only other thing I could think of causing a problem is that I use App Groups and NSUserDefaults to pass data between the extension and main app, however these are only ever called when a "share" button is pressed.
Comment: So, remember in my main post I said: "I placed a breakpoint at the viewDidLoad() function in the hopes of tracking any nil values, but the code appears to never even get to this point. It seems as if none of my code is being run." I just ran the code in the simulator (where it works) with breakpoints, and none of my breakpoints were tripped there either. My breakpoints are obviously not working correctly, so I'll do some investigation on the issue. Then perhaps I can track down my stray nil value.. Now, to find out why they aren't working...
Answer: You should run the same device on simulator and real device.As an example if you run on 5s on real device then try the same device on simulator.By running simulator, it will definitely show the error.My error was the not connecting the @IBActions. Hope that this tip will help you.
Answer: I received the same error when trying to set a non-optional value to the value of an implicitly-unwrapped optional that was nil.
Ex. someGlobalFunction() returns an ImplicitlyUnwrappedOptional with a nil value then you try to set that to a regular value.
func someGlobalFunction() -> String! { return nil }

class MyClass {
    let aVariable: String

    init() {
        aVariable = someGlobalFunction()
    }
}