Swift 3/SpriteKit - Draw independent shapes with finger

Question: I'm a beginner following the tutorial here for drawing shapes in Swift.
import SpriteKit

class GameScene: SKScene {

    var activeSlice: SKShapeNode!
    var activeSlicePoints = [CGPoint]()

    override func didMove(to view: SKView) {
        createSlices()
    }

    func createSlices() {
        activeSlice = SKShapeNode()
        activeSlice.strokeColor = UIColor(red: 1, green: 0.9, blue: 0, alpha: 1)
        activeSlice.lineWidth = 9
        addChild(activeSlice)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesBegan(touches, with: event)
        if let touch = touches.first {
            let location = touch.location(in: self)
            activeSlicePoints.append(location)
            redrawActiveSlice()
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else { return }
        let location = touch.location(in: self)
        activeSlicePoints.append(location)
        redrawActiveSlice()

    }

     override func touchesEnded(_ touches: Set<UITouch>?, with event: UIEvent?) {
}

    func redrawActiveSlice() {
        let path = UIBezierPath()
        path.move(to: activeSlicePoints[0])
        for i in 1 ..< activeSlicePoints.count {
            path.addLine(to: activeSlicePoints[i])
        }
        activeSlice.path = path.cgPath
    }
}

With this code, when you release the finger then touch again to draw, you have a line connecting the two shapes.
I would like to draw independent shapes.
Perhaps by modifying the code so that for each instance of touchesEnded(), the array of points that represents the shape is stored in a multidimensional array, and by creating an array of points for each new instance of touchesBegan()?
Thank you for your help.
Answer: It's something like
override func touchesEnded(_ touches: Set<UITouch>?, with event: UIEvent?) {

     createSlices()
}

Comment: Thank you! To make it work, I had to add `activeSlicePoints.removeAll(keepingCapacity: true)` to `touchesBegan()` in addition to your code.


Parsing numbers from HTML strings in Java

Question: When parsing HTML, every time i have a '>' char, I need to check if there is a number after it.  The number can be of 1, 2 or 3 digits.
The code seems OK, but I always get a StringIndexOutOfBoundException.
Code:
while (matches < 19)
    {
        more  = dataInHtml.indexOf(">",index);
        nextOne = dataInHtml.charAt(more + 1);
        nextTwo = dataInHtml.charAt(more + 2);
        nextThree = dataInHtml.charAt(more + 3);

        if (Character.isDigit(nextOne))  digitOne = true;
        if (Character.isDigit(nextTwo))  digitTwo = true;
        if (Character.isDigit(nextThree))  digitThree = true;

        if (digitThree)
        {
            data[matches] = dataInHtml.substring(more + 1, 3);
            matches++;
            digitThree = false;
            digitTwo = false;
            digitOne = false;
            index = more + 3;
            itWasADigit = true;
        }

        if (digitTwo)
        {
            data[matches] = dataInHtml.substring(more + 1, 2);
            matches++;
            digitTwo = false;
            digitOne = false;
            index = more + 2;
            itWasADigit = true;
        }

        if (digitOne)
        {
            data[matches] = dataInHtml.substring(more + 1, 1);
            matches++;
            digitOne = false;
            index = more + 1;
            itWasADigit = true;
        }

        if (!(itWasADigit))
        {
            index = more + 1;
            itWasADigit = false;
        }
    }

Comment: Convert characters to ASCII and compare values
Comment: Which line is doing a StringIndexOutOfBoundException ?
Comment: data[matches] = dataInHtml.substring(more + 1, 2);
Comment: If it is a well formed HTML (like xml) you can try using a SAX parser to extract the tokens and then parse it into integers.
Answer: If you pass the string "string >12" to this look what it will do:
more  = dataInHtml.indexOf(">",index);
  nextOne = dataInHtml.charAt(more + 1); <-- get the 1
  nextTwo = dataInHtml.charAt(more + 2); <-- Get the 2
  nextThree = dataInHtml.charAt(more + 3); <-- Try to access outside of the string as more+3 is greater than the highest index in the string, so it crashes out

Hence you see the StringIndexOutOfBoundsException.
Use something like this
if(dataInHtml.length() > more+3)

To check that the length of the string is big enough before trying to access that character.
If you are trying to read numbers from a HTML document this probably isnt the ideal approach to take. You should look into parseing it with a parser if possible.
http://jsoup.org/ looks promising.
Comment: it will break because of the last `>`. After seeing it will try to access the string index that is too large
Comment: >12<...   >1<...>  i have an HTML file like that


How to edit the correct phone number in my script?

Question: I have this sample:
link
CODE HTML:
Primary Phone Number*

<input type="text" name="primary_phone" id="primary_phone" class="_phone required-input"  value=""  maxlength="10">

CODE CSS:
.invalid{
    border:1px solid red !important;
}
.valid{
    border:1px solid green !important;
}

CODE JS:
function phoneFormat(){
    $( "._phone" ).on('blur change', function() {
        text = $(this).val().replace(/(\d{3})(\d{3})(\d{4})/, "($1) $2-$3");
        var testt=$(this).val().match(text);

        if($(this).val()=='' || $(this).val().match(text) || $(this).val().length == 0)
        {
            $(this).removeClass('valid').addClass('invalid');
        }
        else{

            $(this).removeClass('invalid').addClass('valid');
        }
        $(this).val(text);
    });
}

 $( "#primary_phone" ).blur(function() {
        phoneFormat();
    });

I put a script that arranges text format
for example, we can add this number :
1234567890

After calling script appears next form (what is right)
(123) 456-7890

The problem is when you want to edit my phone number ... if you want to delete the last two numbers because I put the following code  maxlength="10"
I want the user can not write more than 10 characters.
How do I fulfill both requirements.
If something is not explained well I'll do an edit to this post
Thanks in advance!
Comment: your link doesnt work, no code
Comment: sorry, the link works now
Answer: Just remove all special characters when you focus in on the input box:
  $("#primary_phone").on("click", function() {
   var thisVal = $(this).val();

    var value = thisVal.replace(/[^\/\d]/g,'');
    $(this).val(value);

});

Now when you click out of the input box, your original function to format the number comes in to play :)
Working fiddle : https://jsfiddle.net/reko91/gto0qeyx/2/
Answer: I would set a higher maxlength (say 15) and bind the input to keypress.
Inside the event you can check the keyCode against a set of allowed ones and suppress the event (entry of the character) otherwise.
I would also suppress the entry of numbers if we already have 10 (with one exception: if the user selected (marked) a portion of the input and that selection contains numbers.
var alwaysAllowed = [32, 40, 41, 45]; // [" ","(",")","-"]

function keyCode(keyCode) {
    if (alwaysAllowed.indexOf(keyCode) !== -1) {
        return "allowed";
    } else if (keyCode >= 48 && keyCode <= 57) {
        // 0 - 9
        return "number";
    } else {
        // any other character
        return false;
    }
}

function countNumbers(text) {
    // return the number of characters [0-9] in the string "text"
    var counter = 0;
    for (var i = 0; i < text.length; i++) {
        if (parseInt(text[i]) >= 0 && parseInt(text[i]) < 10) {
            counter++;
        }
    }
    return counter;
}

$primaryPhone.on("keypress", function () {
    var keyCodeEvaluation = keyCode(event.keyCode);
    if (keyCodeEvaluation === false) {
        event.preventDefault();
    } else if (keyCodeEvaluation === "number") {
        var value = this.value,
            counter = countNumbers(value.substring(this.selectionStart, this.selectionEnd));
        //
        if (counter === 0 && countNumbers(value) > 9) {
            event.preventDefault();
        }
    }

});

This would allow the user to edit (or write) the phonenumber with your format applied.
MORE IMPORTANTLY
You should rewrite your phoneFormat() function.
Each execution adds another event listener. The first time you change the input value it executes one time. Then two times, three times and so forth.
You should also store objects you use repeatedly in a variable, e.g. $( this ) (creating the same jQuery object each time is a performance killer).
Here is a working example that should cover most of your use cases.


Use one jquery code for all tabs

Question: I need help. I have 6 tabs on website. But when i`m clicking to one of the tab, all other tabs changes too. How i can to have unigue id for every tab ? Please help. This my codes:
   jQuery(document).ready(function () {
       //  When user clicks on tab, this code will be executed
       jQuery("#tabs li").click(function () {
           //  First remove class "active" from currently active tab
           jQuery("#tabs li").removeClass('active');
           //  Now add class "active" to the selected/clicked tab
           jQuery(this).addClass("active");
           //  Hide all tab content
           jQuery(".tab_content").hide();
           //  Here we get the href value of the selected tab
           var selected_tab = jQuery(this).find("a").attr("href");
           //  Show the selected tab content
           jQuery(selected_tab).fadeIn();
           //  At the end, we add return false so that the click on the link is not executed
           return false;
       });
   });

This is my html - css:

Tab 1

Tab 2

Tab 3

 tab content 1

This tab has icon in it.

Suspendisse blandit velit eget erat suscipit in malesuada odio venenatis.

Comment: Please reformat your code to make it more readable, or even better.. use http://jsfiddle.net/ so everyone can take a quick view of the problem and help you.
Answer: I use that way in my projects. Try this:
// Javascript Part:
$(document).ready(function() {
  function switch_tabs($obj){
    // hide tab contents
    $('.tab_content').hide();

    // deactivate currenct tab
    $('.tab_links a').removeClass('active');

    // activate tab and show content
    var id = $obj.attr('href');
    $(id).show();
    $obj.addClass('active');

}

  $('.Tabs a').click(function(){
    switch_tabs($(this));

    return false;
  });
  switch_tabs($('.Tabs a.active'));
});

// HTML Part:

Logs

Sessions

    LOGS CONTENT HERE

    SESSIONS CONTENT HERE

// CSS Part:
.Tabs { }
.Tabs ul.tab_links { margin:0 0 0 10px; padding:0; list-style:none; }
.Tabs ul.tab_links li { float:left; font-size:.75em; margin:0 0 -1px 5px; line-height:1.2em; border:1px solid #BBB;
                        background-color:#DDD; }
.Tabs ul.tab_links a { display:block; color:#666; width:100%; height:100%; padding:2px 10px; text-decoration:none;   }
.Tabs ul.tab_links a.active {color:#BF3723; font-weight:bold; border-color:#AAA; border-bottom-color:#FFF; }
.Tabs div.tab_content { clear:left; padding:15px; border:1px solid #BBB; }

I hope this helps..

Use one jquery code for all tabs


Essentials hub not working?

Question: On my Bukkit server I installed Hub-Essentials
The problem is when  ever I join it doesn't teleport me from my logout place/world to the place I /hub set.
It also won't give my the items and the book to ex: toggle players.
Can someone tell me:
How to make it teleport me to the place I set the hub.
Why it won't give me the items/book?
I looked in the configs for all them, they are all enabled.
Answer: Type /reload or just restart the server. If that doesn't work try re-installing it.

Essentials hub not working?


Compatability issues with IE 11 ,how to make the page to look same when it is in preivous versions of IE with disabling the back compatability

Question: I am working on compatability Issues for IE11 and previous versions.
My Project is looking nice with IE compatability mode.But when I remove the compatability and set to EDGE it looks ugly.
After googled I came to know that it may required the code changes for IE11.
My pages are very bad and the css are not properly applied and alignments are at there worst.
tables are overlapped.
will it requires the code changes or will there be any generic solution.
it is written in JSP
Please help me with some suggestions.
Thanks in advance
Comment: How the heck should we know?  We can't psychically see your site.
Comment: Hi Erik,Thanks for the response.I cannot give the site screen shots as  it will violates my company policies as that is not a www domain one..I am looking for a generalized solutions or suggestions or how to attack the problem.
Comment: There isn't one, since there are billions of reasons for compatibility issues, we need to see actual code that illustrates the problem (it doesn't have to be your actual company code, just code that illustrates the problem).
Comment: it's an old application .which is probably developed 10 years back standards.
Comment: That doesn't change the fact that the problems could be *anything* and we need actual code to solve the problem.  No matter how you argue this, it won't change this fact.  We need code that illustrates the problem in order to suggest fixes to it.
Answer: There are basically three things you can do:

Use a legacy document mode, e.g. add an x-ua-compatible header to the page with content="IE=5".
Since you're using IE11, you can give Enterprise mode (EMIE) a shot.
Rewrite the app to use modern standards (like the most cost effective in the long run).

The ideal answer to your question is probably somewhere along the lines of all the above.  The x-ua-compatible header will likely fix things in the short term, possibly buying you time to rewrite the app to use modern features and standards.  Unfortunately, document modes are documented as deprecated and the IE team in on record as wanting to eliminate them entirely.  EMIE can handle situations where you're running on an intranet, but there's no guarantee that it will be available beyond the next version of Windows. In a way, it's only prolonging the inevitable.
Hope this helps...
-- Lance


Commands not working on Minecraft Realms?

Question: I am an operator (OP) on my friends Realm. Today I tried to play and noticed that no commands would work for me, or anyone else granted OP. They only worked for the owner of said realm.
He has de-oped us and re-oped us with no cure to the problem. What's causing this?
Also another problem that when he tries to reload the realm it fails every single time, any options that would fix this problem?
Comment: Did the owner grant you operator status via clicking the crown icon in Realm settings?
Answer: This is a bug, currently operator permissions don't work at all on any MCPE Realm: https://bugs.mojang.com/browse/REALMS-1511
Comment: Hi Fabian, this is now the duplicate target - if any more of these same issues crop up, please VTC as duplicate instead of creating duplicate answers :)
Comment: Just want to add, within the last 18 hours, this has actually been fixed by the Mojang Team. Close the realm, wait 5 minutes then start it back up. This fixes it.
Comment: @Jayden You can edit my answer, best with a link as source.


Using .reloc from assembly

Question: This is a cut-down version of the problem I'm facing on AArch64:
I've this macro that keeps dumping some data into a section.

#define GEN_DATA(_type) \
    .pushsection .mydata_##_type, "aw"; \
    .ifndef start; \
    start:; \
    .endif; \
    .word 1; \
    .reloc end_loc, R_AARCH64_ABS64, .; \
    .popsection

I eventually wanted to capture the start and end of similar types in a structure like this:

    .pushsection .head, "aw"
    .quad start
    end_loc:
    .quad 0
    .popsection

I can track where the section starts with the start symbol. I don't know in advance how many invocations of GEN_DATA() will be there in the build, so I can't define an end. I don't know how many _types of section will be used either, so can't place guard symbol script. Therefore I decided to leave a relocation entry for end_loc so that linker will eventually fixup where the whole section ends. Yes, there will be multiple relocation entries for the same end_loc, but because they're absolute relocations, I reckon they don't conflict.
I had hunch, but in the final binary, end_loc is getting fixed up with a wrong address. I'll blame it on multiple relocation entries, but the weird thing is that, everything is OK if I also add a dummy, extra relocation entry too -- I.e. I modify the structures above to:

#define GEN_DATA(_type) \
    .pushsection .mydata_##_type, "aw"; \
    .ifndef start; \
    start:; \
    .endif; \
    .word 1; \
    .reloc end_loc, R_AARCH64_ABS64, .; \
    .reloc dummy_loc, R_AARCH64_ABS64, .; \
    .popsection

and:

    .pushsection .head, "aw"
    .quad start
    end_loc:
    .quad 0
    dummy_loc:
    .quad 0
    .popsection

So I'm wondering:

Why is end_loc getting fixed up wrongly? What's wrong with multiple absolute relocation entries, if at all? Isn't the linker expected to go through them in order, and the last one falls into effect?
Why would simply adding a dummy relocation make everything right?

Basically, what's going on?!
And finally, are there any alternatives approaches that I could try?
EDIT: I've now pushed the sample code to a Git repository. Use make and make broken=1 to view the disassembly. Needs Linaro AArch64 tool chain in $PATH.
Answer: I don't know what's going on with the relocations, but the easiest way to do what you're trying accomplish is to use a linker script. This will let you group all the .mydata_XXX_type sections together and provide symbols for the start and end of the grouped sections. Something like this:
SECTIONS
{
    .mydata :
    {
        start   = .;
        *(.mydata*);
        end_loc = .;
    }
}

Which you would use with an assembly file like this:
    .macro gen_data, type
    .pushsection .mydata_\()\type\()_type, "aw"
    .word   1
    .popsection
    .endm

    .text
    gen_data foo
    gen_data bar
    gen_data baz

    .section .head, "aw"
    .quad   start
    .quad   end_loc

(I've used assembler macros instead of C macros because they're much easier to work with.)  You'd use the two above files like this:
    as -o test.o test.s
    ld -o test test.o test.ld

If you know all the possible section "types" then you do it without using a linker script by relying on the fact the linker places unknown sections in the order it first encounters them. For example:
    .section .mydata_start, "aw"
start:
    .section .mydata_foo_type, "aw"
    .section .mydata_bar_type, "aw"
    .section .mydata_baz_type, "aw"
    .section .mydata_end, "aw"
end_loc:

    .macro gen_data, type
    .ifndef .mydata_\()\type\()_type
    .error  "gen_data invoked with unknown type '\type\()'"
    .endif
    .pushsection .mydata_\()\type\()_type, "aw"
    .word   1
    .popsection
    .endm

    .text
    gen_data foo
    gen_data bar
    gen_data baz
    # gen_data unk

    .section .head, "aw"
    .quad   start
    .quad   end_loc

If you have multiple assembler files using the macro make sure that all the assembler files include the .section directives shown above at the start so it doesn't matter which order they appear on the linker command line.
Note that both solutions resolve a problem with your macro, it's possible other unknown sections can be placed in between your .mydata_XXX_type sections if they happen to appear to the linker for the first time in that order.

Using .reloc from assembly


Expo, React Native takePictureAsync does not return

Question: I'm using expo-camera pretty much straight from the code snippet in the docs and the takePictureAsync function never returns.
  async takePicture () {
    try {
      let photo = await this.camera.takePictureAsync()
      console.log('this will never return', photo)
    } catch (err) {
      console.error('this does not error', err)
    }
  }

I have granted permission and I've tested out various ways it might be a promise issue, but no luck.
I'm running on-device with a Pixel 3a. Any advice would be appreciated.
Comment: It accepts an options object as an argument, have you tried that?  And make sure the apps cache is large enough for the photo.
Comment: Heh, looks like the options object is required and does not error if you omit it. Looks like all I had to do is pass an empty object.
Comment: Mind if I put it in an answer
Comment: I had the same issue except only on the android emulator. Everything works fine on a physical device. If anyone is encountering the same issue see my answer here: https://github.com/react-native-camera/react-native-camera/issues/3141#issuecomment-1525911195
Answer: It accepts an options object as a a required argument.

quality (number) -- Specify the quality of compression, from 0 to 1. 0
  means compress for small size, 1 means compress for maximum quality.
exif (boolean) -- Whether to also include the EXIF data for the image.
onPictureSaved (function) -- A callback invoked when picture is saved.
  If set, the promise of this method will resolve immediately with no
  data after picture is captured. The data that it should contain will
  be passed to this callback. If displaying or processing a captured
  photo right after taking it is not your case, this callback lets you
  skip waiting for it to be saved.
skipProcessing (boolean) - Android only. If set to true, camera skips
  orientation adjustment and returns an image straight from the device's
  camera. If enabled, quality option is discarded (processing pipeline
  is skipped as a whole). Although enabling this option reduces image
  delivery time significantly, it may cause the image to appear in a
  wrong orientation in the Image component (at the time of writing, it
  does not respect EXIF orientation of the images).

source
Comment: I should note that this sometimes doesn't work with just an empty object. The only way I've gotten it to consistently work is with the `skipProcessing: true` option.
Comment: Would be nice if it threw an error if you don't include it!
Comment: It would once this is all in typescript. They're not done yet though and I'm not sure if this is part of it. https://docs.expo.io/versions/latest/guides/typescript/


What is best practice regarding passing errors to the caller?

Question: Should you generally pass errors that occur in functions and class methods back to the caller to handle?  What are cases when you might not?  I'm asking because I am creating a module to perform the oauth dance, and if you get a negative response from the websites you are trying to access I'm not sure if I should pass it up to the caller, or handle it there.
Answer: It generally depends on the answer to two questions:

What layer has the information to explain the error, and present it to users or developers?
What layer can correct the error, in a way that the upper layer cannot tell it ever happened?

Examine the problem layer by layer. Find where the error can be caught, corrected and transparently handled. Failing that, find where the error can be explained in useful terms, and enriched with relevant information.
It's often the case that the function that actually encounters the error can neither explain it adequately nor correct it. It should raise an exception, delegating the decision to the upper layer, possibly attaching additional data to the error.
When the exception has climbed high enough, you'll find yourself in one of the 2 cases I described above, in a position where you can either correct the error transparently or report it in clear language, with the information needed to track down the cause.
In the case of your OAuth module, you should:

Decide whether retrying the action makes sense (eg network error)
Determine the cause of the problem (eg wrong credentials), and raise an exception that clearly conveys that.
Answer: We usually raiseError when we expect a certain value or input from the user. For eg: If a program requires the user to enter a positive integer and they enter a negative integer, we raise an error and ask them to enter the A POSITIVE INTEGER.
We handle errors when it's not up to the user for it. For eg: If the website to access requires email verification and the email entered by the user is not recognized, you raiseError and ask them to put in a valid email address, but if, the website has a search bar and the string put in does not split properly for the search and we get a keyValueError, it's up to the programmer to handle it.


ARKit – Cannot decode ARAnchor in MCSession

Question: I'm testing out Apple's Multiuser AR demo app with ARKit 2.0 that was introduced in WWDC 2018: Creating a multiuser AR experience.
The documentation says that after each device relocalizes to the same World Map, only the information needed to recreate each user action is shared among devices (e.g. if the user taps on the screen and a 3D object appears, only that new object's ARAnchor should be sent to other devices). For me, while it shows all the 3D characters that were placed by the sending device before it captured and sent a World Map, it doesn't show any objects that are added after the World Map has been sent. The error I'm getting says:
// can't decode data recieved from peer.

Has anyone had this issue and knows what it's about?
I haven't changed anything in the demo code.
Answer: I had the same trouble but I kind of solved it in this way.
(1)first create a variable to check if the world map has send.
var worldMapHasInited: Bool = false
(2)Then in func shareSession(_ button: UIButton) add this line to the end below
self.multipeerSession.sendToAllPeers(data)
self.worldMapHasInited = true
(3)And finally in func receivedData(_ data: Data, from peer: MCPeerID)
check if the world map has sent, if is sent, skip checking if the data contains   world map or not.
    if !worldMapHasInited {
        if let worldMap = try NSKeyedUnarchiver.unarchivedObject(ofClass: ARWorldMap.self, from: data)
        {
            //....
            // when received world map, set the receiver's
            // worldMapHasInited to true
            self.worldMapHasInited = true
        }
    }
    else
        if let anchor = try NSKeyedUnarchiver.unarchivedObject(ofClass: ARAnchor.self, from: data) {
            // ...
    }

This will directly check if the data contains anchor or not.
Answer: In MultipeerConnectivity ARSession several peers share data among each other. But sent and received data must be, at first, archived and then unarchived using two instance methods of NSKeyedArchiver and NSKeyedUnarchiver classes:
func archive(worldMap: ARWorldMap) throws {

    let data = try NSKeyedArchiver.archivedData(withRootObject: worldMap,
                                         requiringSecureCoding: true)

    try data.write(to: worldMapURL, options: [.atomic])
}

and:
func unarchive(worldMapData: Data) -> ARWorldMap? {

    guard let unarchievedData = try? NSKeyedUnarchiver.unarchivedObject(ofClass: ARWorldMap.self,
                                                                           from: worldMapData)
    else { return nil }

    return unarchievedData
}

Hence, if you get the following message in Xcode Console:
"can't decode data received from peer"

it means the error occurred while transferring or unarchiving a ARWorldMap data.


How can I secure a door latch blocker without drilling?

Question: I have a door latch cover that looks like this:

Its installed in a common area so I cannot drill any holes. Right now its attached to the door with an elastic band as shown in the photo but they keep stretching out so I constantly have to replace them. What could I use instead of an elastic band to make this more or less permanent? First thing that comes to mind is to use a metal wire but how do I connect the two free ends after cutting out a big enough piece?
Many years ago I've seen a small metal connector used on a clothesline where you put two ends of the cable inside and then used the screw to make the rope tight, but I can't remember what it was called and can't find it in Google. Something like this would be perfect for my purposes.
Comment: Zip ties.  Small ones
Comment: look under the cover ... do you see any screws?
Comment: @jsotola yes but the latch cover isn't big enough for me to use the existing holes in the metal part of the latch. If this was my own door I'd just make a hole on the wooden sides and call it a day but sadly that's not an option
Comment: @Kris thank you! I *knew* I'm missing a very simple solution here, just couldn't figure out what. This should work perfectly.
Answer: Use cable ties instead of the elastic bands.
Comment: If the cable ties are too short, you can tie them together.  If you want to trim off excess, be sure to sand down any sharp corners, or tape them over; they will be quite sharp.
Answer: if you want to use wire bend both ends of the wire round the anchor tab of the blocker.
I worry that wire might mar the door handle, something soft like string or parachute cord might be a better choice. You may need an assistant to help you tie the knot.
Answer: I had a similar problem and I found that simply putting a flat metal plate over the strike plate offered free access. This is a more permanent solution as if you want the door to lock our stay closed occasionally you would have to remove the metal plate to accomplish normal use.
Comment: How did you secure the metal plate to the door?


Flex push one item below the others that are next to each other?

Question: Flex is sometimes killing me, here's a simple code:

1

2

3

I want to end up with something of this sort:
[   .one  ][.two]

[    .three.    ]

It's super easy using block/inline-block:
.one { display: inline-block; width: 80%; }
.two { display: inline-block; width: 20%; }
.three { display: block; width: 100%; } /* Don't even need the with here, added for clarity */

But of course nothing is easy with flexbox ;) I don't want (and can't) change flex-direction, it has to stay as the default value (I think that's not an issue, because .one and .two are actually next to each other). Unfortunately because of that I have no clue how to push .three below them, the sane way would be something like this:
.wrapper { display: flex; }
.one { width: 80%; }
.two { width: 20%; }
.three { width: 100%; } /* move to the next line as you cant fit in the current! */

But all I'm getting is:
[.one][.two][   .three  ]

I've tried align-self and everything I could find but nothing seem to help.
To sum up:

I can't affect the DOM structure or the parents css.
I don't want to add any .break or .clear empty elements or pseudoelements because its not 1997 anymore and makes everything even more complex (somehow the first example does not need all that sorcery).
I'd rather not add next layer of abstraction (I think I could wrap one/two in a div and then three in another, but boy, why all that hustle for something that simple?).

How can I achieve simple two column / two row layout with flexbox? Am I missing something? I feel like something is wrong here. Thank you.
Demo: https://jsfiddle.net/rh9vpb2e/
Comment: just add `flex-flow: wrap;` to `.wrapper`
Answer: So close!
You just need;
flex-wrap: wrap;

on the .wrapper class to ensure flex wraps the rows!
Updated fiddle
flex-wrap docs
Comment: I cant add any classes of the parent element, but it makes total sense now, i'm a moron I guess. I will just add it using JS and to hell with it, thank you. I think `flex-wrap: wrap;` should be the default value!


access to array into controller codeigniter

Question: i have a problem, this is my model, return many columns, for example (cert_num) :
<code>$this->db->select('*');
$this->db->from('certificado_asegurado');
$this->db->where('certificado_asegurado.cert_id', $search_string);
$query = $this->db->get();
return $query->result_array();
</code>
Now, in my controller i need do other query to other model, but with "cert_num" valor return:
<code>$data['certificado'] = $this->certificado_model->get_certificado($search_string);
$cert_num=$data['certificado']['cert_num']->cert_num; //not work
$cert_num= $certificado['cert_num']; //not work
$cert_num=$data['certificado']['cert_num']; //not work
</code>
I need $cert_num valor for send to model
<code>$data['user'] = $this->certificado_model->get_user($cert_num);
</code>
Any solution please, to retry with foreach but not work. Thanks.
Answer: iDont know exactly how your array is being returned but you could try access it from its index just like this
<code>$cert_num=$data['certificado'][0]->cert_num;
</code>
or
<code>$cert_num=$data['certificado'][0]['cert_num'];
</code>


Can not insert data ino table

Question: <code>`protected void Page_Load(object sender, EventArgs e)
    {
        TextBox6.Text = DateTime.Now.ToShortDateString();
        TextBox7.Text = DateTime.Now.AddMonths(6).ToShortDateString();
    }` protected void Button1_Click(object sender, EventArgs e)
    {
        SqlConnection con = new SqlConnection("Data Source=ASHISH;Initial Catalog=esaote;Integrated Security=True");
        string q = "insert into info(c_name,c_address, machine, s_version, email,i_ date,due_date) values(@c_name, @c_address, @machine, @s_version, @email, @i_date,@due_date)";
        SqlCommand cmd = new SqlCommand(q, con);

        cmd.Parameters.AddWithValue("@c_name", TextBox1.Text);
        cmd.Parameters.AddWithValue("@c_address", TextBox2.Text);
        cmd.Parameters.AddWithValue("@machine", TextBox3.Text);
        cmd.Parameters.AddWithValue("@s_version", TextBox4.Text);
        cmd.Parameters.AddWithValue("@email", TextBox5.Text);
        cmd.Parameters.AddWithValue("@i_date",TextBox6.Text );
        cmd.Parameters.AddWithValue("@due_date", TextBox7.Text);
        //string due_date = DateTime.Now.ToShortDateString() + DateTime.Now.AddMonths(6).ToShortDateString();
        try
        {
            con.Open();
            cmd.ExecuteNonQuery();
            Response.Redirect("<script language='javascript'>alert('due date is'" + TextBox7.Text + ")</script>");
        }
        catch (Exception exp)
        {
            Console.Write(exp.Message);
        }
        finally
        {
            con.Close();
        }
    }
</code>
the catch block is giving incorrect syntax near date exception. i have changed i_date in the last cmd.parameter... to due_date. all the attributes in table have same name as given.i am not able to find a sol. also have converted the syntax
Answer: Error is here:
insert into info(c_name,c_address, machine, s_version, email,i_ date,due_date)
should be:
<code>insert into info(c_name,c_address, machine, s_version, email,i_date,due_date)
</code>

Can not insert data ino table


How to create a centralized callback for multiple ajax requests?

Question: I would like to be able to send multiple ajax requests and merge all the responses in a single callback, how can i do that without mess with callbacks inside each request?
Instead of a system like this
-> send ajax1
    on ajax1 success
         -> send ajax2
               on ajax2 success process both answer and render a view
I would like to be able to request ajax1 and ajax2
call ajax1
call ajax2

> when both are finished
process answer from both requests in a single function

callback (response_ajax1, response_ajax2 ) {
    // process information
}

Comment: This has been answered many, many times before, so why you're posting a duplicate and answering it yourself is beyond me. +1 for effort at least.
Answer: According to jquery, since it's version 1.5 we can use Deferred objects for this.
What's a deferred object?:

[...] deferreds can be thought of as a way to represent asynchronous (not realtime)
  operations which can take a long time to complete (ajax requests are
  one of thoose examples).

-

Deferred objects are the asynchronous alternative to blocking functions and the
  general idea is that rather than your application blocking while it
  awaits some request to complete before returning a result.

-

[...] a deferred object can instead be returned immediately.

As summary:

Deferred objects provides a way to register multiple callbacks into self-managed
  callback queues, invoke callback queues as appropriate, and relay the
  success or failure state of any synchronous or asynchronous function..

To answer the question:
http://jsfiddle.net/mreis1/DCmrN/
function _ajax(id){
    return $.ajax({
        url: '/echo/json/',
        type: 'GET',
        dataType: 'json',
        data: {param1: id},
        complete: function(xhr, textStatus) {
          //called when complete
        },
        success: function(data, textStatus, xhr) {
            //console.log(data)
          //called when successful

        },
        error: function(xhr, textStatus, errorThrown) {
          //called when there is an error
        }

});

}

// merge response data from both ajax calls when they are done
$.when( _ajax(1), _ajax(2) ).done(function(a1, a2){
      console.log(a1, a2);
});

DOCUMENTATION
http://api.jquery.com/category/deferred-object/
SIMILAR PROBLEMS
http://forum.jquery.com/topic/using-when-to-deal-with-response-of-multiple-ajax-calls-deferred-objects
ARTICLES TO EXPLORE
http://www.tentonaxe.com/index.cfm/2011/9/22/Using-jQuerywhen-with-a-dynamic-number-of-objects
http://learn.jquery.com/code-organization/deferreds/
http://learn.jquery.com/code-organization/deferreds/examples/
Comment: Your wrapper function is completely unnecessary.
Comment: The wrapper function pretends to simplify the amount of code necessary to perform ajax calls. This wrapper can be greatly improved but the this examples pretends to show how it can be made. Examples at the end of the post pretend to complement the post it self. Thanks ;)


Moving from Windows to Ubuntu. What programs to use?

Question: Maby my question is not related to this forum, but I want to ask. I want to change my OS from Windows XP to Ubuntu 10.6. But I like some programs in Windows, so is there a GOOD programs in Linux(Ubuntu) to change this list of programs? And I'll be apprishiated for some links where I can download GOOD software for Linux. I need such programs, that I could open their files in Windows OS environment. For example: .doc, .jpeg, .png, .gif, .txt and others. Thanx!
Musical players: Aimp Winamp Sound forge
Kodecks for video, audio etc.
Microsoft Office 2003, Vizio, WinRAR, Adobe reader, Dejavju reader, Fine Reader, Adobe Photoshop, Paint, Nero, Alcohol 120%, DiamonTools, Far, Total Commander, Dreamveawer, Visual Studio 2005, Denwer
Messangers: QiP, ICQ, Skype
Browsers: Opera, Mozila
Antiviruses!! NOD32, Avast, Kaspersky?
Translators: Lingvo 12, Pragma
BitTorrent, Download Master.
Comment: A community wiki might be handier here?
Comment: You may wish to check this post [What are the most useful programs installed after setup of a Vanilla Ubuntu?](http://askubuntu.com/questions/1237/what-are-the-most-useful-programs-installed-after-setup-of-a-vanilla-ubuntu)
Comment: Post closed Marco :(
Answer: First of all, welcome to Ubuntu! :-)
So, all the software you mentioned in your list have an equivalent in Linux. I really suggest you spend time reading one of these links I offer you below:

Linux software equivalent to Windows software
List of free and open source software packages
List Of Open-source Programs (LOOP): 1, 2

I'm sure you will have great suggestions apart from those lists. It was there that I chose to use the following equivalents:

gimp for images (.jpeg, .png, .gif)
OpenOffice.org for create and manipulate Microsoft Office docs
Telepathy for Messangers (QiP, ICQ, Msn, etc) with Skype available
Mozila Firefox replacing Iternet Explorer

For all other software you have an equivalent in Ubuntu, and you can easily search and install using the tool Ubuntu Software Center, see a screenshot below (from wikipedia):
Answer: You would be able to open the .doc, .jpeg, .png, .gif, .txt  formats out of the box without any extra effort.
After you finish installing ubuntu on your computer you just have to run one command to get all the audio,video codecs and java, and flash.
Microsoft Office 2003, WinRAR, Adobe reader, Adobe Photoshop, Paint, Nero, Dreamveawer,
Nero there are alternatives for these softwares but you can install them under a software called Wine.
Nero has a native linux version.
Messangers: QiP, ICQ, Skype
Skype works nativaly and ICQ and Qip chat would be available under empathy messanger whick is default messanger of ubuntu.
Browsers: Opera, Mozila
Both of these browsers and Google chrome also work natively
for bittorrent you can use transmission which comes out of the box in ubuntu or Deluge which has utorrent like User interface.
Some links to download softwares
There is an ubuntu software centre in ubuntu just like Iphone appstore, but almost all the software there are free and as you are a new user you would find most of the sofware that you need in the software centre, so you dont need any links download software.
PS. I think I have given you enough reasons to switch into ubuntu :)
Answer: First off, you shouldn't need to download apps from the web (at least most of the time) as the Ubuntu Software Centre, found under the Applications tab in the upper left of the screen, contains most of the applications you will need on Ubuntu, all for free. The Software Centre is divided into categories (Office, Web, Programming, etc) and all you have to do to install software from it is to hit the 'install' button and enter you user password, and you're all set.
Now, onto specific applications.
Visual Studio: If you're planning on doing development on Linux, you may want to check out the accepted answer to this question on Stack Overflow. The default text editor on Ubuntu has built in support for syntax highlighting of a great many languages and can have it's functionality expanded with plugins (many of which some preinstalled). If you're looking for an IDE for a particular language, then just search for that language in the Software Centre (you probably don't need to include 'IDE').
Nero: Fluendo is available from the Software Centre for $25 under the recently introduced 'for purchase' category.
Adobe Reader: Ubuntu has a built in pdf viewer called Evince.
Alcohol 120%: Ubuntu has a DVD burner called Brasero, though I'm not sure how it compares to Alcohol in terms of features.
WinRAR: Ubuntu has a built in archive manage that can handle .zip and .tar.gz. Though if you want to use WinRAR, I think there's a Linux version available.
Total Commander: Nautilus is Ubuntu's window manager. Play around with it and see if it has the features you use in Total Commander.
Far: Nautilus and Archive Manager, mentioned as possible alternatives elsewhere in this list, may be able to replace this, though I've never encountered Far before so I can't say for sure.
Vizio: I think Dia, found in the Software Centre, is what you're after there, though I've not used Vizio so I couldn't say how it compares.
Adobe Photoshop: The Gimp, available from the Software Centre, is the bext bitmap editor available on Linux, and Inkscape is available if you want to do some vector editing.
Microsoft Office: Open Office is the primary alternative to MS Office and is preinstalled in Ubuntu.
BitTorrent: Transmission is the torrent client preinstalled in Ubuntu
Security: ClamAV is a good anti-virus program, not preinstalled but found in the Software Centre. The Ubuntu firewall is good and so you won't need a third party program.
Browsers: Firefox comes preinstalled on Ubuntu
Messengers: Empathy is the preinstalled IM/IRC client on Ubuntu. It supports a wide range of services including MSN, Gtalk and Facebook Chat.
Music players: Rhythmbox is preinstalled on Ubuntu, although I personally use Banshee (available from the Software Centre) because of the increased functionality. If you're used to WinAmp, then you might like to check that one out.
Codecs: There are few preinstalled codecs on Ubuntu, but support for pretty much all AV filetypes is available from the Software Centre. Just search for 'Gstreamer' and you'll get a list of codecs that provide the support for a multitude of formats. Check them out and install the ones you want.
.txt files can be opened in Ubuntu's default text editor, Gedit, and the various images formats can be opened in the default image viewer.
I've done what I can here, though you're going to have to fire up Ubuntu and play around with it and see what it does for you. Remember, just search the Software Centre and see what you come across.
Answer: When moving from WindowsXP to Ubuntu/GNOME you will find that from the usability of your desktop not very much may have changed. Still, you are now on a very different OS. This needs some change of thinking especially when it comes to applications and how to install them.
Unlike Windows you have not only installed a modern operating system with Ubuntu but much more: it's what we call a "distribution". This means that almost all useful applications that are tested to run are already included but perhaps not yet installed on your PC from the installation CD.
Running Applications that are not provided on CD is done with a few mouse clicks only. There are several programs installed that do this, but you will find the Software Center where you can choose from an overwhelming variety of tested, useful and mostly free software a good point to start.
Downloading files from other internet recources is rarely needed. In fact it is discouraged because those applications may not be tested, can cause instabilities to your system and cannot be updated automatically (which is otherwise the case).
Try out Ubuntu and you will soon find that thinking "the Ubuntu way" is what you have always missed in the past.
Answer: Musical players: Aimp Winamp Sound forge
VLC, Banshee, Rhythmbox, even Winamp itself (using playonlinux); all available in the software center.
Codecs for video, audio etc. - if you choose install extras during your install *(maverick, 10.10, and later) you don't have to install these. To be sure, install ubuntu-restricted-addons and -extras (using software center, or synaptic).
Microsoft Office 2003,
Open Office works fine with files from Office 2003, but if you are really really looking for the exact thing, use PlayOnLinux to give you an easy install. (It's in the ubuntu-software center)
Vizio,
Try Dia.
WinRAR,
So long as you install rar and unrar, you will get support for rar files in Archive Manager that comes with ubuntu.
Adobe reader,
Ubuntu can open PDF's by default, and you can also install Adobe Reader if you enable the partner repo in software center.
Dejavju reader,
Is in software center.
Fine Reader,
Not sure what that is.
Adobe Photoshop,
Try GIMP (in software center), or GIMPShop.
Paint,
Try Pinta.
Nero
Ubuntu comes with Brasero, but you can also try K3B (software center).
Alcohol 120%
There are various applications in the software center that do the same job, but brasero can create iso files, so basically you can use it to backup CD/DVD media.
DiamonTools,
GMountIso, AcetoneISO, etc.\
Far,
Not sure what that is
Total Commander,
Nautilus should be powerful enough.
Dreamveawer, Visual Studio 2005, Denwer
Bluefish, Monodevelop, not sure what the 3rd is, but there are many alternatives in software center.
Messangers: QiP, ICQ, Skype
Empathy, Pidgin, Skype. See the software center :D.
Browsers: Opera, Mozila
Firefox is included, Opera is available for ubuntu.
Antiviruses!! NOD32, Avast, Kaspersky?
Ubuntu doesn't really need an antivirus program, but you coudld use a firewall user-interface such as Guard Dog or Gufw, to add some rules to the built in firewall.
Translators: Lingvo 12, Pragma
There are some translation applications in the software center, but this is not a field I can expand on much.
Answer: Musical players: Personally I use Banshee, but it is more iTunes like than winamp. There is a lot of different players out there, like Guayadeque, Clementine, Amarok and Rhythmbox (which is bundled with Ubuntu). Maybe you would like to check out DeaDBeeF.
Kodecks: If you install the ubuntu-restricted-extras package, you should have all the stuff you need, including flash and java.
The apps i know of:
Microsoft Office 2003: OpenOffice.org is bundled with Ubuntu.
WinRAR: Already present. Rar files can be opened by installing the package rar.
Adobe reader: Replacement is already there, though you can install Adobe Reader too. I like the default better though.
Dejavju reader: Install libdjvulibre21 to make the document opener support djvu files.
Adobe Photoshop: GIMP.
Paint: I use GIMP for the most, it's not as slow as PS. You could try out Pinta though.
Nero: Brasero is bundled.
Alcohol 120%: Mounting is supported by default. For more advanced stuff you could try out acetoneiso or gisomount.
Total Commander: I use FileZilla for FTP.
Dreamveawer: Bluefish is a good bet.
Visual Studio 2005: See this thread.
Messangers: Empathy is installed by default. Another good multi-protocol messenger is Pidgin. Skype can be installed from the software center.
Browsers: All of them are available native.
Antiviruses: You could install ClamAv, but it is only detecting windows viruses. You really don't need antivirus on linux (one of the great advantages).
Translators: I don't really know anything here.
BitTorrent: Transmission gets the job done for me. Otherwise there's Deluge and a lot of other clients.


Is a multi wire shared neutral circuit a 220 volt circuit

Question: I am wondering if a multi wire shared neutral circuit is considered a 240v circuit.
I ask because in the code it says that AFCI breakers are not required on 240v circuits.  A 240 20amp breaker costs 16 dollars, a 240v 20amp afci costs 216 dollars. Is a 220 breaker safe on a multi wire circuit, will it trip as quickly as two single breakers?
I would just add a new wire and split the circuits (my first choice) but my attic is full of insulation and I can't see how I can remove enough to put a raceway on the rafter tops.  The problem is I have a 4 in 12 roof and have added insulation 4 times over the years to keep up with new standards so I have insulation batts going two directions and one layer of blown in insulation. Does anyone have any tricks on how to work around the insulation?
Would I have to de rate the wires in conduit in the attic?
Comment: You have a lot of questions. Usually you'll get better answers if you ask one cohesive question at a time.
Comment: What are you feeding?
Answer: You could use a subpanel.
I'm assuming you have a series of 120V receptacles on this circuit, at 20A or 15A.
You would keep the 20A 2-pole breaker on the main panel, and the 12/3+G cable.
At the other end, put a very small load center. You can use a "main lug" type, 2-circuit, 4-space. They're under $20. For example: http://www.amazon.com/dp/B000BPOROY/
Then you can put AFCI breakers in this subpanel to branch out as needed.
I haven't gotten a reliable answer as to whether 20A subpanels are allowed in code (30A may be a minimum), but the electrical theory is sound.
Comment: Do you secretly own a business that makes subpanels? :P
Comment: Looks like I can use a 220 breaker but it has to be an afci breaker. I cannot see spending $600 for three breakers so I will fight the insulation to split the circuits. On the existing wiring can I just cut the red wire flush at each end of the run and at the panel and use the cable as one circuit, or do I have to pull the old wire out.
Comment: @Dave: Maybe you misunderstand me: the feeder breaker in the main panel doesn't need to be AFCI. The branch circuit breakers in the subpanel only need to be 120V, so they won't be so expensive.
Comment: You might like to know that professionals hate the term subpanel.
Comment: @PhilipNgai: No one will mistake me for a professional! ha ha
Answer: First of all, what you are describing is not a true 240VAC circuit. You are actually creating two 120 volt branches, not a single use 240vac circuit.  You cannot protect opposing legs of two 120vac branches with a double pole breaker. You must use two single pole breakers, one per leg.  In your case, if the areas being serviced are 120vac legs that require AFCI, then you must install single pole AFCI  breakers as required by code.
The 240vac rule is referring to single use circuits such as air conditioners, heaters etc that require 240vac source voltage.
Comment: Well, but if the shared-neutral circuit is to code, it would use a double-pole breaker (to make sure both of the "hots" that could energize any part of the circuit are cold). You couldn't use two single-poles in this instance because that's a shock hazard. I still think you're right in that using this as a dual-120V circuit instead of a single-purpose 220V does not entitle OP to the 220V exception, making AFCI a requirement if two single-poles controlling separate runs to the same area would have to be AFCI.


Are MMORPGs, specifically WoW, limited by their latency in terms of FPS?

Question: It sounds crazy, but I've been doing a lot of reading on exactly why WoW performs very poorly, even on a 1080Ti / 8700k OC'd and overall, a high-end machine.
Overclocking the CPU yielded great results, but after ~4.7 GHz, my returns were, at best, minimal, as such, running at 5.0 GHz makes no difference.
So I was thinking:
The server issues data to the CPU. The CPU issues draw calls to my GPU. My GPU can be downclocked by ~40-50%, and it still won't affect FPS. My CPU is clearly hitting its ceiling.
So, then, could it very well be that, say, on a ~80-90 ms connection, my FPS would be limited due to how much it could output, since the GPU is basically waiting?
Answer: Online games do not work the way you describe. The server doesn't give the client one frame's worth of data every frame. That would be awful. Instead, every client has its own copy of the game state, and the rendering happens as if it were an offline game: every frame, the game state is updated locally. That means your inputs such as moving the mouse to control the view take effect immediately. Things that aren't under players' control (such as the movement of projectiles in flight) are also updated locally. Many games also have some kind of motion prediction for other players' characters - in the simplest case, just updating the state as if they kept going in the same direction.
These state updates are performed by the CPU on its scene-graph, and they result in some update to GPU state too. The frame is then rendered by the GPU, usually in parallel with the CPU starting work on the next frame's updates.
When an update arrives from the server, this also updates the state on the CPU. This update will include new projectiles, replacements for the predicted motions of other player characters, and replacements for the motions of the local player's character (e.g. if they bumped into another player or were hit by some unpredicted projectiles).
Resolving conflicts between the predicted state on the client and the new state from the server, and applying the lag to the server state before applying it, are important parts of the game's architecture that really determine how the game feels to play and what lag looks like. Applying the updates from the server is done within one frame update on the client, so if an update takes too long to apply, it'll cause some frames to be much slower, but the age of the update doesn't really affect that.
Summary
Client-server latency doesn't usually increase the frame time, because the client doesn't wait for a server round-trip each frame.


Memory Leak using Property List / NSMutableDictionary

Question: I'm using a Property List in my main bundle to store information about the levels and player. The pList gets copied over to the phone the first time the app is launched, then I access the information as needed from that local copy. I'm running Leaks in Instruments, and I keep coming across memory leaks that I believe are related to creating the dictionary and other data types stored in the pList.
Here's where the dictionary is created - after finding the path to the pList:
<code>if fileManager.fileExists(atPath: path.path) {

    if let dictionaryForPlist = NSMutableDictionary(contentsOf: path) {

        return(dictionaryForPlist)
    }
    else {
        print("pList not found")
    }

let levelInstanceData = LevelData() //this class searches the main bundle for the plist and stores the pList as an NSMutableDictionary
let currentLevel = levelInstanceData.localDataFile["Level1"] as! Int //localDataFile is the NSMutableDictionary storing the information
let levelName = levelInstanceData.localDataFile["Level1Name"] as! String
</code>
I forcefully cast each piece of data to the correct data type and use it throughout the level.

Here is a screenshot of the leaked objects in Instruments. Has anyone else had this issue or have any ideas how to stop the leaks?
Comment: There are several questions about memory leaks on the Apple SpriteKit forums. This is the first I've seen with dictionaries. You might be lucky. The first to find this one. SK and bugs....
Answer: Providing all the leaked objects isn't overly helpful. What you will need to do is look at the call tree related to each leaked object. This will show you where in code the leak has originated from. And from there you can start to deduce what needs to be done to remedy it.
You should read this. It is dated, but it discusses the call tree.
https://www.raywenderlich.com/2696/instruments-tutorial-for-ios-how-to-debug-memory-leaks
Comment: Thanks, this is helpful, but I'm not sure there's anything I can do about some of these leaks - a lot of them originate from `if let dictionaryForPlist = NSMutableDictionary(contentsOf: path) {` and several are from appending to arrays and setting up playSoundFileNamed actions.
Comment: Someone is still holding onto the dictionary created by `if let dictionaryForPlist = NSMutableDictionary(contentsOf: path)`. You could, as a test, have the callers of the method that get the plist copy the dictionary. Anyways, without a call tree, it is all speculation. You are going to need to better understand how retained objects work as well as how to deduce this. It is your code base so an external can't see what you see.
Comment: thanks for your comment. I'm beginning to get the hang identifying the retention cycles and have removed lots of them, but apparently not all of them. I didn't see the retention path for this, but I'll look into it again. I'll also try to grab a screenshot of one of the call trees and post it in the question.
Comment: An update to this issue - The memory leak happens on a device running iOS10, but not one running iOS9. That should mean that it's not my code that's causing the memory leak, right?


Opening a file on unix using c++

Question: I am trying to open a file in c++ and the server the progam in running on is based on tux.
string filename = "../dir/input.txt"; works but
string filename = "~jal/dir1/dir/input.txt"; fails

Is there any way to open a file in c++ when the filename provided is in the second format?
Answer: The ~jal expansion is performed by the shell (bash/csh/whatever), not by the system itself, so your program is trying to look into the folder named ~jal/, not /home/jal/.
I'm not a C coder, but getpwent() may be what you need.
Comment: I meant duh by me not the poster of the question.
Comment: Magnus, $HOME contains *your* homedir - and ~jal expands to the homedir of user 'jal'.
Comment: 2Magnus: I'm not sure about $HOME, if program will run via 'su', for example
Comment: you were almost right, you omitted only  one sign /, instead of "~jal/dir1/dir/input.txt"  it should look like "~/jal/dir1/dir/input.txt"
Answer: You could scan the string, replacing ~user by the appropriate directory.
The POSIX function wordexp does that, and a few other things

variable substitution, like you can use $HOME
optional command substitution, like $(echo foo) (can be disabled)
arithmetic expansion, like $((3+4))
word splitting, like splitting ~/a ~/b into two words
wildcard expansion, like *.cpp
and quoting, like "~/a ~/b" remains that
Answer: Here is a ready piece of code, that performs this task:

How do I expand `~' in a filename like the shell does?

Opening a file on unix using c++


Form window resize on tab change: good or bad?

Question: On one tab I have (let's say) 3 form fields — with label and text input. On another tab there are a bit more forms. Is it OK if the window resizes based on the forms it has?
Example:

Or, is it better if the first window would be the height and width of the largest window of all tabs (if I were to add more)?
What is the best practice, or what is the most common solution to this?
NOTE: this is for desktops.
Comment: Is this for a desktop app which might have a custom size window? Or a website?
Comment: For a desktop, window resizes are not very intuitive. That woud throw off the user a bit, and he might need a few seconds to recalibrate. I would prefer the constant window size option. Fit/Resize the elements in the smaller screen to fit the bigger screen size
Answer: I can only speak from my own personal experience: on desktop I often arrange my windows' sizes and positions using nView or [insert generic window manager] depending on the combination of applications I am working with.
An application that would resize itself based its content, would likely interfere with window management workflows. As an end-user, I would rather the application start with its 'biggest' reasonable size (Form 2), and instead display the content from Form 1 in a way that it looks nice even with the screen size presented in Form 2.
This leaves the freedom of controlling the window size to the user, and contributes to a consistent and predictable experience in terms of window management - a central aspect of the desktop experience.
Comment: This is what i am trying to figure out. If form is little and input is not more than 100 chars, i wouldn´t put form one below another and resize the form to full width. But i do agree on starting with window line on Form 2 for content Form 1 has and not resizing based on content. Makes sence


Which programs use the new "Online Accounts"?

Question: In Ubuntu Oneiric 11.10 it's possible to configure a Google Online Account. I'm able to configure this program to get access to Mail, Contacts, Calendar and Chat.
But which programs use this data? There is no information about that.
After I configured my Google Account, I supposed that I will be able to use Google Chat with Empathy, or that I will be able to access my Contacts and Calendar in Thunderbird.
But none of this is true. So, how does Ubuntu use the configured Google Accounts?
Comment: this is how ubuntu **should** be using the account setup. If its not working then it is a bug which you should add to launchpad
Comment: Related (identical?): http://askubuntu.com/questions/63891/how-to-integrate-gnome-online-accounts
Comment: @Bernd - If possible, please consider closing some of your other open questions by [selecting the best answer](http://meta.askubuntu.com/questions/1137/how-do-i-accept-an-answer) (if they have one). Consider which answers have been useful and need an upvote. We need users to maintain their questions so that the site can be an effective tool for the next person with your problems. For more details on best practices consider reading [the FAQ on asking questions](http://askubuntu.com/faq#howtoask).
Answer: The idea is that those types of accounts should be configured in one place and then all other programs can get your identities. Your email clients, IM clients, VoIP, photo albums, etc.
Obviously, any tool must exist before applications can start to use it, so it's no surprise that many applications doesn't use this yet. I thought at least Empathy would use this now, though?
Answer: gnome-contacts uses Google Contacts if you set up an online account.
<code>sudo apt-get install gnome-contacts
</code>
or click this
Answer: According to the Gnome 3.2 release notes.
Online Accounts
Documents, contacts, calendars — They can be stored locally on the computer, but storing this type of information online is becoming increasingly popular. In GNOME 3.2, Online Accounts provides one place to manage these online sources. These online accounts are automatically used by Documents, Contacts, Empathy, Evolution as well as the calendar drop-down.
Probably this features didn't make it to unity yet.


Convert miliseconds to date and time and format by locale

Question: How can I convert milliseconds to a time and date string and format it correctly like the user expects it to be?
I did the following:
((SimpleDateFormat)DateFormat.getDateInstance(DateFormat.DEFAULT,Locale.getDefault())).format(new Date(Long.parseLong(timeInMilliseconds)));

Which seems to work, but I only get the date with this method.
Edit:
To clearify, I need to get the time/date pattern from system somehow to give each user his common format
Now I combined your solutions with mine and it seems to work like I expect.
private String getFormattedDateTimeString(Context context, String timeInMilliseconds) {
    SimpleDateFormat dateInstance = (SimpleDateFormat) DateFormat.getDateInstance(DateFormat.DEFAULT, Locale.getDefault());
    SimpleDateFormat timeInstance = (SimpleDateFormat) DateFormat.getTimeInstance(DateFormat.DEFAULT, Locale.getDefault());
    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(Long.parseLong(timeInMilliseconds));
    String date = dateInstance.format(calendar.getTime());
    String time = timeInstance.format(calendar.getTime());
    return date + " " + time;
}

Why the hell do I get downvotes for this question???
Answer: All the other answers are missing the point that the string representation of the date-time needs to be localized.
Joda-Time
The Joda-Time 2.3 library makes this work much easier.
Joda-Time leverages a java.util.Locale to determine proper formatting of a date-time's string representation. The DateTimeFormat class offers an option for "style" pattern as a way of generating a DateTimeFormatter. You specify a two character style pattern. The first character is the date style, and the second character is the time style. Specify a character of 'S' for short style, 'M' for medium, 'L' for long, and 'F' for full. A date or time may be omitted by specifying a style character '-'.
If you do not specify a Locale or time zone, the JVM's default will be used.
Locale
To create a java.util.Locale, you need:

Language code (either, see combined list)

ISO 639 alpha-2
ISO 639 alpha-3

Country Code (either)

ISO 3166 alpha-2 country code
UN M.49 numeric-3 area code

Example Code
// Simulate input.
long millisecondsSinceEpoch = DateTime.now().getMillis();

// Proceed with a 'long' value in hand.
DateTime dateTimeUtc = new DateTime( millisecondsSinceEpoch, DateTimeZone.UTC );

DateTimeZone timeZone = DateTimeZone.forID( "Asia/Riyadh" );
DateTime dateTimeRiyadh = dateTimeUtc.withZone( timeZone );

// 'ar' = Arabic, 'SA' = Saudi Arabia.
java.util.Locale locale = new Locale( "ar", "SA" ); // ( language code, country code );
DateTimeFormatter formatter = DateTimeFormat.forStyle( "FF" ).withLocale( locale ).withZone( timeZone );
String output = formatter.print( dateTimeUtc );

Dump to console…
System.out.println( "millisecondsSinceEpoch: " + millisecondsSinceEpoch );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeRiyadh: " + dateTimeRiyadh );
System.out.println( "output: " + output );

When run…
millisecondsSinceEpoch: 1392583624765
dateTimeUtc: 2014-02-16T20:47:04.765Z
dateTimeRiyadh: 2014-02-16T23:47:04.765+03:00
output: 16 فبراير, 2014 AST 11:47:04 م

Comment: Thank you, looks promising. I´ll try that when I´m at home
Answer: Leaving your code as is, just change:
Instead of
getDateInstance

try
getDateTimeInstance

Or, you'd better use:
SimpleDateFormat fmt = new SimpleDateFormat("MM-dd-yyyy HH:mm:ss");
String datetime = fmt.format(cal.getTimeInMillis());

Answer: Use this...
String dateFormat = "dd/MM/yyyy hh:mm:ss.SSS";

// Create a DateFormatter object for displaying date in specified format.
DateFormat formatter = new SimpleDateFormat(dateFormat);

// Create a calendar object that will convert the date and time value in milliseconds to date.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(milliSeconds);

String formatedDate =  formatter.format(calendar.getTime());

Answer: Try this
SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");// you can rearange it as you like

 cal.setTimeInMillis(timeInMilliseconds); //convert the time in milli to a date

 String date = format.format(cal.getTime());// here you get your time formated

Answer: Why on earth do you want to use a calendar object???? It's just a waste of resources.
// Create a DateFormatter object for displaying date in specified format.
DateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

String formatedDate =  myDateFormat.format(new Date(timeInMilliseconds));


How can I add a window to my front door?

Question: I have a traditional six panel wood door that I would like to add a window to. How can I remove the wood sections to install a glass panel? Thank you!
Comment: I believe a new door would be a lot easier..  Meanwhile, welcome to Home Improvement.  You can take the tour at http://diy.stackexchange.com/Tour to get the most out of this site.
Answer: In a traditional panel door construction, the panels are held in grooves cut into the rails (horizontal pieces) and stiles (vertical side pieces). The rails and stiles are doweled and firmly glued together, and it is impossible to take them apart without ruining them. The panels are not glued in place, so they can expand and contract with the heat or humidity, without changing the overall dimensions of the door.
If you want to try to replace one of the panels with a glass or perspex pane, you must carefully cut away the molding from one side of the panel. (You should cut on the outside of the door because windows are traditionally caulked on the outside.) Remove the wooden panel and use a chisel and sandpaper to clean up the opening.
The steps, in cross-section:

Then you can install your pane using standard glazing technique.
You might also want to replace a damaged wooden panel with another wooden panel. In that case, instead of caulking you would install milled wooden strips, such as quarter-round or very small crown molding, to hold the new panel while allowing for expansion etc.
One problem you will have is figuring out how much molding to cut away. You should carefully carve material away, about halfway along one edge, until you can see the edge of the panel, then extend the measurement to the corners.
Alternately you may be able to break the panel and remove it without damaging the door. Cut out most of the panel with a jigsaw, notch the remaining frame almost to the molding in several places, and break out the remaining pieces. Once you have wrenched out the first piece, the others will come out quite easily. Then you can measure the depth of the groove directly and decide how much to cut away.
I would call this an advanced-level project, because the results of your carpentry -- joinery, really -- and your glazing will be highly visible and in your face every time you enter or leave your house.
If you have some artistic design or special effect in mind the results can be worth the effort. But if you only want to get some more light into the place, just buy a new door.
Comment: great answer, especially with the images. Note that you show a single pane of glass, and it could be that is all that can be retrofit in such a project. If the home is in a region that gets cold in winter, this could have non-trivial heat loss and significant condensation issues. Note also that code could require tempered glass.


SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified on LocalDB

Question: I have written a c# wpf application that talks to a SQL Server 2012 LocalDB on my machine.
To make the app accessible on other peoples machine's I have:

Included the database file in a zip for the user to extract to the programs directory.
Written SQL scripts to attach the database to the local machine's LocalDB instance.

The application works perfectly fine on my machine, however after installing on someone else's computer (after the .NET and SQL Server 2012 LocalDB prerequisites have been installed), it keeps filling up the error logs with the following message:

Exception: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified).

Now there are a lot of other references to the same error message, but I cannot find any that relate to LocalDB or what to try with LocalDB.
Keeping in mind the application is designed for the common 'end-user', so I can't have them following numerous instructions to use SQL Server Management Studio or configuration manager.
The attach SQL script is as follows in case you need to know:
<code>CREATE DATABASE BaseDB
    ON (FILENAME = 'C:\MyApp\Base\MyDB.mdf'),
(FILENAME = 'C:\MyApp\Base\MyDB.ldf')
FOR ATTACH;
</code>
Can anyone suggest why this wouldn't be working?
Comment: Have you installed SQL Server on Client machine?
Comment: Yes, as per my description -> after the .NET and SQL Server 2012 LocalDB prerequisites have been installed
Answer: To solve this problem:

Install this update to Microsoft Net Framework 4.0: KB2544514

Start: <code>`SqlLocalDB [create|c] instance-name [-s]`</code>
For example:<code>`SqlLocalDB.exe create MSSQLLocalDB -s`</code>


Check if string contains word in array

Question: This is for a chat page.  I have a $string = "This dude is a mothertrucker".  I have an array of badwords: $bads = array('truck', 'shot', etc).  How could I check to see if $string contains any of the words in $bad?
So far I have:
        foreach ($bads as $bad) {
        if (strpos($string,$bad) !== false) {
            //say NO!
        }
        else {
            // YES!            }
        }

Except when I do this, when a user types in a word in the $bads list, the output is NO! followed by YES! so for some reason the code is running it twice through.
Comment: You can use `in_array`  http://php.net/manual/en/function.in-array.php
Comment: @LearneR The problem with that is that even though 'truck' is a bad word, it doesn't detect 'mothertrucker' since it detects by exactness.  I prefer strpos since there is more flexibility.
Comment: Although, with strpos, you could mistake "classic" for a bad word no? You need to add a break when you find a bad word to prevent going through the rest of the list unnecessarily.
Answer: function contains($str, array $arr)
{
    foreach($arr as $a) {
        if (stripos($str,$a) !== false) return true;
    }
    return false;
}

Comment: This only works for me if I swap to `stripos($str,$a)` as the string is the haystack
Comment: This doesn't work if your stopword is part of another word, for example: if one of the words was "shed" and the string contained the word "washed".
I was thinking of a more specific case, like the string containing the word "Essex" and trying to block explicit spam.
Comment: Same as @Robert Went, you shoud change to `stripos($str,$a)`
Comment: strpos first parameter is string and second one is the  word which you need to find .So strpos($a,$str); is right  one.
Comment: @TonyPayne do you have a solution for this?
Answer: 1) The simplest way:
if ( in_array( 'three',  ['one', 'three', 'seven'] ))
...

2) Another way (while checking arrays towards another arrays):
$keywords=array('one','two','three');
$targets=array('eleven','six','two');
foreach ( $targets as $string )
{
  foreach ( $keywords as $keyword )
  {
    if ( strpos( $string, $keyword ) !== FALSE )
     { echo "The word appeared !!" }
  }
}

Comment: Both of these examples perform worse than other [answers](http://stackoverflow.com/a/13795849/630996) to this question.  The first as it's written has a Big-O algorithmic complexity of O(1), but to make it work given the OP's original question, one would have to loop through all of the words in the chat message, which would give it an O(N) (where N is the number of words in the string).  Since the length of the chat message can vary, performance will degrade as the length of the message increases.  And the second is O(M*N) due to the double loop.
Answer: can you please try this instead of your code
$string = "This dude is a mothertrucker";
$bads = array('truck', 'shot');
foreach($bads as $bad) {
    $place = strpos($string, $bad);
    if (!empty($place)) {
        echo 'Bad word';
        exit;
    } else {
        echo "Good";
    }
}

Comment: This is ill-advised code that should not be used in any project.  `false` and `0` are both satisfied by `empty()`.  In other words, if the sentence starts with `shot`, then `Good` will be echoed.  Proof of failure: https://3v4l.org/tG67U
Answer: There is a very short php script that you can use to identify bad words in a string which uses str_ireplace as follows:
$string = "This dude is a mean mothertrucker";
$badwords = array('truck', 'shot', 'ass');
$banstring = ($string != str_ireplace($badwords,"XX",$string))? true: false;
if ($banstring) {
   echo 'Bad words found';
} else {
    echo 'No bad words in the string';
}

The single line:
$banstring = ($string != str_ireplace($badwords,"XX",$string))? true: false;

does all the work.
Comment: I am not sure that you looked carefully at the answer from @Clinton. The approach only uses str_ireplace() to identify if bad words exist (as part of the conditional), it does not actually replace strings. Quite a neat approach actually and a lot faster than iterating through each of the the words to check.
Comment: The OP makes no mention of replacing strings.  This is the correct answer to a differeent question.
Answer: You can flip your bad word array and do the same checking much faster. Define each bad word as a key of the array. For example,
//define global variable that is available to too part of php script
//you don't want to redefine the array each time you call the function
//as a work around you may write a class if you don't want global variable
$GLOBALS['bad_words']= array('truck' => true, 'shot' => true);

function containsBadWord($str){
    //get rid of extra white spaces at the end and beginning of the string
    $str= trim($str);
    //replace multiple white spaces next to each other with single space.
    //So we don't have problem when we use explode on the string(we dont want empty elements in the array)
    $str= preg_replace('/\s+/', ' ', $str);

    $word_list= explode(" ", $str);
    foreach($word_list as $word){
        if( isset($GLOBALS['bad_words'][$word]) ){
            return true;
        }
    }
    return false;
}

$string = "This dude is a mothertrucker";

if ( !containsBadWord($string) ){
    //doesn't contain bad word
}
else{
    //contains bad word
}

In this code we are just checking if an index exist rather than comparing bad word with all the words in the bad word list.
isset is much faster than in_array and marginally faster than array_key_exists.
Make sure none of the values in bad word array are set to null.
isset will return false if the array index is set to null.
Comment: Thank you but how to put bad words in file `.txt`
`$GLOBALS['bad_words']= array('truck' => true, 'shot' => true);`
 i try
`$bad_words = file_get_contents('bad_words.txt');`
`$GLOBALS['bad_words']= $bad_words ;`
does not work
Answer: You can do the filter this way also
$string = "This dude is a mothertrucker";
if (preg_match_all('#\b(truck|shot|etc)\b#', $string )) //add all bad words here.
    {
  echo "There is a bad word in the string";
    }
else {
    echo "There is no bad word in the string";
   }

Comment: Why would anyone bother matching all, when the OP only needs to match one?
Answer: Put and exit or die once it find any bad words, like this
foreach ($bads as $bad) {
 if (strpos($string,$bad) !== false) {
        //say NO!
 }
 else {
        echo YES;
        die(); or exit;
  }
}

Comment: Thank you @Sanjay!  This worked!  All I had to change was to put another exit also in the if since if I did not NO would be echoed twice.
Comment: Hi It is because this works in a for each loop and all time it check each words with your bad words array.I don't think it is a correct method to put exit there at No loop , because if the 3rd or 4th word is a bad word it may not give you correct result, so could you please check that.
Comment: Yes, you are correct, the problem persists with the exit in the if part, sorry.  Also, I realized that if I chose a bad word further down the indexo of the array, it wouldn't say NO.
Comment: Hi so that i said only put exit in the YES loop only, so once in the string it find any bad words it will stop further execution.Means if it find any bad words in the string it stop execution. I think that you need right?
Comment: If I only put it in the YES loop then if I type in a badword, NO pops up but then YES also pops up.
Comment: Do not use `die()` or `exit()`, use `break` to break a loop instead of halting all execution.
Answer: Wanted this?
$string = "This dude is a mothertrucker";
$bads = array('truck', 'shot', 'mothertrucker');

    foreach ($bads as $bad) {
        if (strstr($string,$bad) !== false) {
            echo 'NO
';
        }
        else {
            echo 'YES
';
        }
    }

Comment: The php manual clearly states not use `strstr()` to check the existence of a substring. https://www.php.net/manual/en/function.strstr.php#:~:text=If%20you%20only,instead.
Comment: @mickmackusa Thanks for mentioning. I knew but overlooked. Micromanaging are not always that worthy in the long-run.
Answer: I would go that way if chat string is not that long.
$badwords = array('mothertrucker', 'ash', 'whole');
$chatstr = 'This dude is a mothertrucker';
$chatstrArr = explode(' ',$chatstr);
$badwordfound = false;
foreach ($chatstrArr as $k => $v) {
    if (in_array($v,$badwords)) {$badwordfound = true; break;}
    foreach($badwords as $kb => $vb) {
        if (strstr($v, $kb)) $badwordfound = true;
        break;
    }
}
if ($badwordfound) { echo 'You\'re nasty!';}
else echo 'GoodGuy!';

Comment: change the foreach line for this :

foreach ($chatstrArr as $k => $v) {

foreach ($badwords as $kb => $vb) {
     || strstr($v,$vb) {$badwordfound = true; break;}
Comment: Damn comment box wont let me enter code modifs...
I Changed my response to search for all badwords into all chat string words
Comment: The php manual clearly states not use `strstr()` to check the existence of a substring. https://www.php.net/manual/en/function.strstr.php#:~:text=If%20you%20only,instead.
Answer: If you want to do with array_intersect(), then use below code :
function checkString(array $arr, $str) {

  $str = preg_replace( array('/[^ \w]+/', '/\s+/'), ' ', strtolower($str) ); // Remove Special Characters and extra spaces -or- convert to LowerCase

  $matchedString = array_intersect( explode(' ', $str), $arr);

  if ( count($matchedString) > 0 ) {
    return true;
  }
  return false;
}

Answer:  $string = "This dude is a good man";
 $bad = array('truck','shot','etc');
 $flag='0';
 foreach($bad as $word){
    if(in_array($word,$string))
    {
        $flag=1;
    }
}
if($flag==1)
  echo "Exist";
else
  echo "Not Exist";

Comment: This answer was not tested and is provably incorrect/broken: https://3v4l.org/SlU81
Comment: Good eyes to check all replies. Kudos @mickmackusa

Check if string contains word in array


Will the Olympic skins (+ other future event skins) be buyable after the event is over?

Question: There's brand new skins in overwatch, and they are event themed.
Will they be just gone after the event (those who have it keep it, those who don't are screwed...)
It should be one of 3 scenarios

Skin can still be got in boxes
Skin cannot be got in boxes but can be bought with gold
Skin is unavailable to any who dont have it, like with the founders skins
Comment: I voted to reopen. Don't think this is about unreleased content. It's about the loot boxes which are currently available. That's released content. They've said officially they're only available for the event.
Comment: I won't answer this question because I believe it's off topic, but Blizzard have stated that these cosmetics won't be available outside of the event loot boxes, and that this is going to be a yearly event. Next year it might or might not be possible to obtain the same skins again, in addition to new ones.
Comment: @DCShannon The question is explicitly asking about what will happen in the future.  We have nothing in-game to base any sort of answers on, leading this to the exact same issue as unreleased games.  Voting to leave closed.
Comment: Now we do. Should be reopened.
Answer: Game director Jeff Kaplan talks about seasonal items:
Seasonal/Event items will only be available through loot boxes earned during the event period and you won't be able to get them after the event ends. You won't be able to buy them with gold or money either. You just have to wait for next season if it returns.
Note about the new Anniversary event:
This event may be more unique than the others, but the temporariness of the event and its items remains the same.
Source:

You'll earn Anniversary Loot Boxes as you play, plus pick up a free box when you log in between May 23 and June 12, 2017. Anniversary Loot Boxes are also available for purchase—but they'll be locked away after the event ends.

Blizzard announced that the Summer Games event will be returning with some new and some old skins further indicating that these will be reoccurring events with annual opportunities to acquire skins etc.
Comment: Also, from the [Overwatch blog](https://playoverwatch.com/en-us/blog/20216482): While any Summer Games item you unlock will be yours forever, the collection will be heading back into the vault on August 22 when the event concludes. So, if you've got your eye on something specific, there's no time to lose!


How to use MKTileOverLay in iOS7?

Question: I tried to use tiled map in ios7 using the method that provided in wwdc, but it doesn't appear anything. Anyone has sample code for that? My code is provided below
<code>#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.

    NSString *template = @"http://c.tile.openstreetmap.org/{z}/{x}/{y}.png";
    MKTileOverlay *overLay = [[MKTileOverlay alloc] initWithURLTemplate:template];
    overLay.canReplaceMapContent = YES;
    [self.mapView addOverlay:overLay level:MKOverlayLevelAboveLabels];
    [self.mapView setRegion:MKCoordinateRegionMake(CLLocationCoordinate2DMake(37.776884, -122.387255), MKCoordinateSpanMake(0.25, 0.25))];

}

-(MKTileOverlayRenderer *)mapView:(MKMapView*)mapView rendererForOverlay:(id<MKOverlay>)overlay {

    MKTileOverlayRenderer *renderer = [[MKTileOverlayRenderer alloc] initWithOverlay:overlay];
    renderer.alpha = 0.6;
    return renderer;
</code>
Answer: Did you set your mapView's delegate to self? Because if not, the -rendererForOverlay won't get called.

How to use MKTileOverLay in iOS7?


Accuracy issues with NSNumberFormatter

Question: My problem is that I'm currently using a NSNumberFormatter with NSNumberFormatterDecimalStyle. I'm using this because I want to have the commas separate the numbers every three numbers just like one would write it when I turn it into a string. This works great however the precision of the decimal place is quite small. It's only precise to the thousandths place. For my application I need it to be accurate to the 12th decimal place. I can do it very easily with the %g format specifier by just putting %.12g in the string format but I don't know how I can achieve this with the NSNumberFormatter. I tried removing the format: NSNumberFormatterDecimalStyle but that just makes my number an integer. Any help would be appreciated.
Here is the code I'm using currently to format the double: number.
NSNumber *theNumber = [NSNumber numberWithDouble:number];
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
[num setNumberStyle:NSNumberFormatterDecimalStyle];
[num setGroupingSeparator:@","];

Answer: Make sure the starting value you're working with is a double, not a float.
Then, have you tried setting maximumFractionDigits on your formatter before using it to do your conversion?
Answer: Just set the minimum or digits to the right of the decimal point:
- (void)setMinimumFractionDigits:(NSUInteger)number
Example:
NSNumber *number = @123456.654321;
NSNumberFormatter *formatter = [NSNumberFormatter new];
[formatter setNumberStyle:NSNumberFormatterDecimalStyle];
[formatter setGroupingSeparator:@","];
[formatter setMinimumFractionDigits:12];
NSString *stringNumber = [formatter stringFromNumber:number];
NSLog(@"Number: '%@'", stringNumber);

NSLog output

Number: '123,456.654321000000'
Comment: Thanks, I was unaware of the minimum fraction digits.

Accuracy issues with NSNumberFormatter


HTML-like layout in iPhone application

Question: How do I make a resolution-independent iPhone view controller that can stack it's subviews like the browser stacks HTML elements?
Here's an example. One UILabel at the top that could contain 1-6 lines of text; two UIButtons in a row right below the label; the left button could have a short or long title. I want the buttons to appear at the right vertical position where the text ends; I want the left button to scale accordingly to the length of it's title and the right button to reposition automatically.
In other words, I want the most natural behavior for this kind of UI when it's content changes.
Is there a way to tell Interface Builder or UIKit to implement this kind of behavior automatically?
Answer: Cocoa's layout managers are not available on the iPhone. The only automatic layout tool isUIView's autoresizingMask property, which is not enough to solve your problem. So have to code it yourself.
The right place to start is to overwrite the view's layoutSubviews method. It gets called automatically whenever the bounds of the view change. Some controls also have a decent autoresizing-to-content behavior calling their sizeToFit method.
Answer: I would have a look at how Silverlight handles layout, and create an analogous set of containers for iOS.  It doesn't look like anyone's done this yet, so I'm planning to do this for my next project.
Basically, there are different container controls that lay out sub-controls in different ways.  There's a StackPanel, for instance, which stacks up sub-controls according to various properties that you can set.  There's also a Grid, for when you want to structure things like an HTML table.  They're well designed for composition, so you can use the containers in various combinations to achieve a pretty wide range of layouts with a small amount of code.

HTML-like layout in iPhone application


FormControl change to FormControlName in formGroup

Question: my code was:
  <mat-form-field>
    <mat-label>Toppings</mat-label>
    <mat-select [formControl]="toppings" multiple>
      <mat-option *ngFor="let topping of toppingList" [value]="topping">
        {{topping}}
      </mat-option>
    </mat-select>
  </mat-form-field>

  <mat-chip-list>
    <mat-chip *ngFor="let item of toppings.value" removable (removed)="onToppingRemoved(item)">
      {{item}}
      <mat-icon matChipRemove>cancel</mat-icon>
    </mat-chip>
  </mat-chip-list>

I would like to merge FormControl into FormGroup. It will to be:
  <mat-form-field>
    <mat-label>Toppings</mat-label>
    <mat-select formControlName ="toppings" multiple>
      <mat-option *ngFor="let topping of toppingList" [value]="topping">
       {{topping}}
      </mat-option>
    </mat-select>
  </mat-form-field>

  <mat-chip-list>
    <mat-chip *ngFor="let item of toppings.value" removable (removed)="onToppingRemoved(item)">
      {{item}}
     <mat-icon matChipRemove>cancel</mat-icon>
   </mat-chip>
  </mat-chip-list>

but always report error

TS2339: Property 'toppings' does not exist on type 'testComponent'.
<mat-chip *ngFor="let item of toppings.value" removable
(removed)="onToppingRemoved(item)">

how to fix this or some points? thanks a lot.
Comment: Is this typo in your real code as well? ``
Comment: Yes. it's sample what i foud from google. It's work for me.
Answer: formControlName directive just need the name of your formControl as it retrieves it thanks to the parent formGroup diretive placed on your <form>.
But outside of this context, using toppings means you have a toppings property declared into your component.
To fix it you need to retrieve the formcontrol from your form to get its value.
For example if the structure of your form is :
form = new FormGroup({
 toppings: new FormControl()
});

you can retrieve the formcontrol value this way into your component :
<mat-chip *ngFor="let item of form.get('toppings').value"></mat-chip>

Comment: i had define :  form: FormGroup = this.fb.group({
    toppings: [{ value: '' }],
  }); in my testComponent.ts. Is it wrong way?
Comment: move your form to : `form: FormGroup = this.fb.group({ toppings: [], });` as you don't need nested **value**.


How to configure arduino ide for Python?

Question: I recently bought arduino uno. I am not much familiar with C# which is used in arduino software. I know that boards like  nodemcu can run on python and it is much easier to code with python. My main language is python. So, I want to know If I can configure the python in arduino IDE.
Comment: A NodeMCU board has 100 times the Flash, 32 times the RAM, and 5 times the clock speed of an Arduino Uno.  Python is simply not an option available to you, no matter what IDE you use.
Comment: Arduino is C++, not C#
Answer: Yes, You can use python to code your arduino board.
you can refer this link. https://realpython.com/arduino-python/
Comment: The only Python programming mentioned at that link is running on a PC, *not* the Arduino.


How to install git bash on ubuntu?

Question: I am new to Ubuntu. Previously I was on Windows and was using git bash for git commands.
But I have decided to use Ubuntu and I installed git but I am not sure whether it is necessary to install git bash on Ubuntu? And, if it is necessary, how should I install it?
Comment: You only need `git bash` on Windows because Windows doesn't have its own `bash` shell available. All *NIX have `bash` available so `git bash` isn't needed
Answer: If it's not installed yet:
sudo apt-get install git-core

Check installation:
git --version

When it's installed, you can use it inside your existing bash in ubuntu.
Comment: Git bash only exist for Windows because there was traditionally no bash (or other unix-ish shell) on that OS. In Ubuntu, you may just want to use the standard bash for Git. If you want to customize the prompt similar to Git bash (showing branch etc.), you can google for something like "git bash ps1" for guidance.
Comment: `git` comes with his own terminal **Git bash** I see no such terminal in ubuntu but I have one in windows once installed
Comment: What about separate terminal of `git`
Comment: @AzharUddinSheikh What exactly is your question?

How to install git bash on ubuntu?


When do stations move to a new location?

Question: In the Civilization Wikia, on the Stations Page it indicates that:

Stations may land on the planet at any time. They are looking to trade with the players, and if nobody comes forward within a given period of time, they pack their belongings and move to a new location on the planet. Only one city per each civilization can trade with a given Station simultaneously.

But I haven't found anything on how much that period of time is before they leave.
Is there a confirmation of how long it takes? Also, is there a way to find out if nobody else has traded with them?
Comment: I think depends on the speed setting of the game. I have observed this behaviour myself, and although I cant give an accurate answer I would say its around the 50 turns mark.
Answer: Stations will disappear after 45 turns without people sending trade routes (scaling with game speed). The game will try to maintain 2 Stations per Player, so relatively shortly after a station has withdrawn the game will try to spawn a new one (Stations CAN spawn again after they have withdrawn/been destroyed) as long as there is enough space between cities available.
Some people claim that it is 30 turns - but they may have been on different game speeds. Generally assume it is minimum of 30 and max around 45.
There is not really a way to see who is trading with them unless you are watching for trade vessels to and from the station.
Overall there is not a ton of documented information about stations mostly because of the mixed response the game got - and now with Civ VI out it has been largely abandoned.