text:
Q: prevent line wrap by making elements disappear with d-none bootstrap I'm building a responsive website that contains a topbar menu. This menu has lots of options, which is great for a big screen display. Unfortunately, for smaller viewports, such as cellphones, all those options don't fit, and the buttons end up wraping.
normal viewport:

cellphone:

This is the snippet code:

                    Level 1

            <button class="btn btn-primary-outline me-2"></button>

            <button class="btn btn-primary-outline me-2"></button>

                <button class="border border-field-grey btn btn-primary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
                  TC
                  0.00
                </button>

Action

Another action

Something else here

            Deposit

To try to circumvent the problem, I decided to make some of the menu elements disappear on smaller viewports, using the bootstrp5 combination d-none d-flex-sm classes (https://getbootstrap.com/docs/5.0/utilities/display/)

                    Level 1

            <button class="btn btn-primary-outline me-2"></button>

            <button class="btn btn-primary-outline me-2"></button>

                <button class="border border-field-grey btn btn-primary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
                  TC
                  0.00
                </button>

Action

Another action

Something else here

            Deposit

But they still end up wrapping, even though there is plenty of space for the elements in the small screen:

Does any one have an idea of how we can solve this issue?
Full code:
HTML:
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />

    <link href="./css/custom.css" rel="stylesheet">
    <link href="./css/navlayout.css" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/boxicons@latest/css/boxicons.min.css" rel="stylesheet">

    <link rel="icon" href="./img/icon.png" />

    <title>Vegaz.bet</title>

                    Level 1

            <button class="btn btn-primary-outline me-2"></button>

            <button class="btn btn-primary-outline me-2"></button>

                <button class="border border-field-grey btn btn-primary dropdown-toggle" type="button" id="dropdownMenuButton1" data-bs-toggle="dropdown" aria-expanded="false">
                  TC
                  0.00
                </button>

Action

Another action

Something else here

            Deposit

                      Crash
                      Roullete
                      Dice
                      Heads or Tails

                      Deposit /
 Withdrawal
                      Help

                <button id="close-chat" type="button" class="position-absolute top-8 start-10 btn-close btn-close-white" aria-label="Close"></button>
                <button type="button" class="w-50 position-absolute top-7 end-10 white-bs-color fw-bold btn btn-primary">Vegaz Chat</button>

                    11:29

                        youranus420: oi putões

                    11:29

                        youranus420: bora crash?

                    11:30

                        elon musk: Olha o nome do cara kkkkk

                        <input type="text" class="chat-font form-control" placeholder="Your message" aria-label="Message">
                        <button class="chat-font btn btn-outline-secondary" type="button" id="button-addon2">Send</button>

Main Components

CSS:
@import url("https://fonts.googleapis.com/css2?family=Montserrat&display=swap");
:root {
    --top-header-top-position: 5%;
    --header-height: 3rem;
    --nav-width: 68px;
    --chat-width: 100px;
    --primary-color: var(--bs-primary);
    --secondary-color: var(--bs-secondary);
    --field-gray: var(--bs-field-grey);
    --field-grey-transparency: var(--bs-field-grey-transparency);
    --white-color: var(--bs-white);
    --body-font: 'Montserrat', sans-serif;
    --normal-font-size: 1rem;
    --z-fixed: 100;
    --z-topbar: 101;
}

*,
::before,
::after {
    box-sizing: border-box
}

.top-header {
    width: 100%;
    height: var(--top-header-top-position);
    position: fixed;
    top: 0;
    left: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 1rem;
    background-color: var(--secondary-color);
    z-index: var(--z-topbar);
    transition: .5s;
    text-align: center !important;
}

.header {
    width: 100%;
    height: var(--header-height);
    position: fixed;
    top: var(--top-header-top-position);
    left: 0;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 1rem;
    background-color: var(--primary-color);
    z-index: var(--z-fixed);
    transition: .5s
}

.header_toggle {
    color: var(--primary-color);
    font-size: 1.5rem;
    cursor: pointer
}

.header_img {
    width: 35px;
    height: 35px;
    display: flex;
    justify-content: center;
    border-radius: 50%;
    overflow: hidden
}

.header_img img {
    width: 40px
}

.l-navbar {
    position: fixed;
    top: 0;
    left: -30%;
    width: var(--nav-width);
    height: 100vh;
    background-color: var(--primary-color);
    padding: .5rem 1rem 0 0;
    transition: .5s;
    z-index: var(--z-fixed)
}

.r-navbar {
    position: fixed;
    top: 0;
    right: 0;
    width: 0;
    height: 100vh;
    background-color: var(--primary-color);
    padding: 1rem 0 0 1rem;
    transition: .5s;
    z-index: var(--z-fixed);
    padding: 1rem 0 0 1rem;
}

.nav {
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    overflow: hidden;
    margin-top: 5rem;
}

.nav_logo,
.nav_link {
    display: grid;
    grid-template-columns: max-content max-content;
    align-items: center;
    column-gap: 1rem;
    padding: .5rem 0 .5rem 1.5rem;
    text-decoration: none;
}

.nav_logo {
    margin-bottom: 2rem
}

.nav_logo-icon {
    font-size: 1.25rem;
    color: var(--white-color)
}

.nav_logo-name {
    color: var(--white-color);
    font-weight: 700
}

.nav_link {
    position: relative;
    color: var(--white-color);
    margin-bottom: 1.5rem;
    transition: .3s
}

.nav_link:hover {
    color: var(--white-color)
}

.nav_icon {
    font-size: 1.25rem;
}

.secondary-bs-color {
    color: var(--bs-secondary)
}

.white-bs-color {
    color: var(--white-color)
}

.show-left-nav {
    left: 0;
    width: calc(var(--nav-width) + 156px);
}

.show-right-nav {
    width: 100%;
}

.body-menu-pd {
    padding-left: calc(var(--nav-width) + 188px);
}

.body-chat-pd {
    padding-right: calc(var(--chat-width) + 1rem);
}

.chat-font {
    font-size: small;
}

.time-span-chat {
    font-size: smaller;
    color: var(--white-color);
}

#chatContainer {
    -ms-overflow-style: none; /* for Internet Explorer, Edge */
    scrollbar-width: none; /* for Firefox */
    overflow-y: scroll;
}

#chatContainer::-webkit-scrollbar {
    display: none; /* for Chrome, Safari, and Opera */
}

.active {
    color: var(--white-color)
}

.active::before {
    content: '';
    position: absolute;
    left: 0;
    width: 2px;
    height: 32px;
    background-color: var(--white-color)
}

.height-100 {
    height: 100vh
}

.float-icon-chat {
    width: 60px;
    height: 60px;
    bottom: 40px;
    right: 40px;
    background-color: var(--secondary-color);
    color: var(--white-color);
    border-radius: 50px;
    text-align: center;
    vertical-align: middle;
}

.coin-dropdown-item {
    color: var(--white-color);
}

.coin-dropdown-item:hover {
    color: var(--secondary-color);
    background-color: var(--field-grey-transparency);
    font-weight: bold;
}

@media screen and (min-width: 768px) {
    .header {
        height: calc(var(--header-height) + 1rem);
        padding: 0 2rem 0 calc(var(--nav-width) + 2rem)
    }
    .header_img {
        width: 40px;
        height: 40px
    }
    .header_img img {
        width: 45px
    }
    .l-navbar {
        left: 0;
        padding: 1rem 1rem 0 0
    }
    .r-navbar {
        right: 0;
        padding: 1rem 0 0 1rem;
        width: 0;
    }
    .show-left-nav {
        width: calc(var(--nav-width) + 156px)
    }
    .show-right-nav {
        width: calc(var(--chat-width) + 156px)
    }
    .body-menu-pd {
        padding-left: calc(var(--nav-width) + 188px);
    }
    .body-chat-pd {
        padding-right: calc(var(--chat-width) + 156px)
    }
}

JS:
document.addEventListener("DOMContentLoaded", function(event) {

    const showNavbar = (toggleId, navId, bodyId, headerId) => {
        const toggle = document.getElementById(toggleId),
            nav = document.getElementById(navId),
            bodypd = document.getElementById(bodyId),
            headerpd = document.getElementById(headerId),
            toggleup = document.getElementById("toggle-up")

        // Validate that all variables exist
        if (toggle && nav && bodypd && headerpd) {
            toggleup.addEventListener('click', () => {
                // show navbar
                nav.classList.toggle('show-left-nav');
                //hide navbar buttons on sm
                document.getElementById("nav-buttons").classList.toggle('d-none');
                // change icon
                toggle.classList.toggle('fa-times');
                // add padding to body
                bodypd.classList.toggle('body-menu-pd');
                // add padding to header
                headerpd.classList.toggle('body-menu-pd');
            });
        }

    }

    showNavbar('header-toggle', 'nav-bar', 'body-pd', 'header');

    /*===== LINK ACTIVE =====*/
    const linkColor = document.querySelectorAll('.nav_link');

    function colorLink() {
        if (linkColor) {
            linkColor.forEach(l => l.classList.remove('active'));
            this.classList.add('active');
        }
    }
    linkColor.forEach(l => l.addEventListener('click', colorLink));

    // show chat
    const showChat = (toggleId, navId, bodyId, headerId) => {
        const toggle = document.getElementById(toggleId),
            nav = document.getElementById(navId),
            bodypd = document.getElementById(bodyId),
            headerpd = document.getElementById(headerId),
            closeChat = document.getElementById("close-chat")

        // Validate that all variables exist
        if (toggle && nav && bodypd && headerpd) {
            const toggleFunc = () => {
                // show navbar
                document.getElementById("invisible-toggle-div").classList.toggle('invisible');
                nav.classList.toggle('invisible');
                nav.classList.toggle('show-right-nav');

                // change icon
                toggle.classList.toggle('invisible');
                // add padding to body
                bodypd.classList.toggle('body-chat-pd');
                // add padding to header
                headerpd.classList.toggle('body-chat-pd');
            }
            toggle.addEventListener('click', toggleFunc);
            closeChat.addEventListener('click', toggleFunc);
        }

    }

    showChat('chatButton', 'nav-bar-chat', 'body-pd', 'header');

});

A: change:

to:


text:
Q: Tensorflow Slower on Python 3 vs. Python 2 My tests show that Tensorflow GPU operations are ~6% slower on Python 3 compared to Python 2. Does anyone have any insight on this?
Platform:

*

*Ubuntu 16.04.2 LTS

*Virtualenv 15.0.1

*Python 2.7.12

*Python 3.6.1

*TensorFlow 1.1

*CUDA Toolkit 8.0.44

*CUDNN 5.1

*GPU: GTX 980Ti

*CPU: i7 4 GHz

*RAM: 32 GB

A: When operating Tensorflow from python most code to feed the computational engine with data resides in python domain. There are known differences between python 2/3 when it comes to performance on various tasks. Therefore, I'd guess that the python code you use to feed the net (or TF python layer, which is quite thick) makes heavy use of python features that are (by design) a bit slower in python 3.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Setting columns in a table to match highest contextual value in another table using SQL I'm trying to fix my forum's botched database with the help of SQL queries in phpMyAdmin. The columns being used are as follows:

*

*mybb_posts is a table that stores information for a single Post in each row, while mybb_users is a table that stores information for a single User in each row.

*mybb_users.uid – The ID of a Forum User

*mybb_users.lastpost – The Timestamp of the last Post a User made

*mybb_posts.uid – Refers to which User made a Post

*mybb_posts.dateline – The Timestamp that appears on a Post

I want set the entry for each user's lastpost equal to the max value for dateline entries from posts where the uid matches the user's uid. To express that as best as I can with my limited experience with SQL:
SET mybb_users.uid = MAX(mybb_posts.dateline WHERE mybb_posts.uid = mybb_users.uid)

I've given it a few tries, including that shameful display, but all resulted in errors.

A: I think this should do it:
UPDATE
  mybb_users,
  (SELECT uid, MAX(dateline) AS date FROM mybb_posts GROUP BY uid) AS lastposts
SET mybb_users.lastpost = lastposts.date
WHERE mybb_users.uid = lastposts.uid

So what goes on here? The sub query (third line) selects the maximum datelines for every users (thanks to the GROUP BY). The WHERE makes sure the temporary table from the sub query and the mybb_users are matched on the uid.


text:
Q: Back button disappears after creating AppDelegate in Swift 3.0 I created the structure as below in xcode 8 swift 3.0.
Before I add AppDelegate code. Back button still appear fine on Apply, Apply Behalf and Profile controller.
I use segue to open page.
But after I add AppDelegate code into Homepage and Login controllers , back button disappears on Apply, Apply behalf and profile controller page.
Can someone help or explain why is this happening ? How to enable back the back button on apply, apply behalf and profile page ?
Thanks.

Home.swift
import UIKit
class ViewController: UIViewController {

    @IBOutlet var staffNumberLbl: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        staffNumberLbl.text = UserDefaults.standard.object(forKey: "login") as? String

    }
    override func viewDidAppear(_ animated: Bool) {
        let isUserLoggedIn = UserDefaults.standard.bool(forKey: "loggedIn")
        if(!isUserLoggedIn){
            self.performSegue(withIdentifier: "loginview", sender: self)
        }
    }

    @IBAction func logoutData(_ sender: Any) {
        UserDefaults.standard.set(false, forKey: "loggedIn")
        UserDefaults.standard.synchronize();
        let loginViewController = self.storyboard!.instantiateViewController(withIdentifier: "loginview") as! LoginViewController
        let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.window?.rootViewController = loginViewController
        appDelegate.window?.makeKeyAndVisible()
    }
}

Login.swift
import UIKit

class LoginViewController: UIViewController {
    @IBOutlet var loginlbl: UITextField!
    @IBOutlet var passlbl: UITextField!
    @IBOutlet var login_button: UIButton!

    var login: String!
    var pw: String!

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

    @IBAction func loginData(_ sender: Any) {

        login = loginLbl.text
        pw = passLbl.text

        if(login == "" || pw == ""){
            return
        }
        else{
            let url     = URL(string: "http://localhost/login.php")
            let session = URLSession.shared
            let request = NSMutableURLRequest(url: url! as URL)
            request.httpMethod = "POST"

            let LoginDataToPost = "login=\(login!)&pw=\(pw!)"
            request.httpBody    = LoginDataToPost.data(using: String.Encoding.utf8)

            let task = session.dataTask(with: request as URLRequest, completionHandler: {
                (data, response, error) in
                if error != nil {
                    return
                }
                else {
                    do {
                        if let json = try JSONSerialization.jsonObject(with: data!) as? [String: String]
                        {
                            DispatchQueue.main.async
                                {
                                    let message = Int(json["message"]!)
                                    let login   = json["login"]

                                    if(message == 1) {
                                        UserDefaults.standard.set(true, forKey: "isUserLoggedIn")
                                        UserDefaults.standard.set(login, forKey: "login")
                                        UserDefaults.standard.synchronize();
                                        self.dismiss(animated: true, completion: nil)
                                        let myViewController:ViewController = self.storyboard!.instantiateViewController(withIdentifier: "ViewController") as! ViewController

                                        let appDelegate = UIApplication.shared.delegate as! AppDelegate
                                        appDelegate.window?.rootViewController = myViewController
                                        appDelegate.window?.makeKeyAndVisible()

                                        print("Value for login is : \(login!)")

                                        return
                                    }
                                    else {}
                            }
                        }
                        else {}
                    }
                    catch let jsonParse {}
                }
            })
            task.resume()
        }
    }
}

AppDelegate.swift
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        let mainStoryBoard: UIStoryboard = UIStoryboard(name: "Main", bundle:nil)

        let isUserLoggedIn:Bool = UserDefaults.standard.bool(forKey: "isUserLoggedIn")
        if(!isUserLoggedIn) {

            let loginViewController = mainStoryBoard.instantiateViewController(withIdentifier: "loginview") as! LoginViewController
            window!.rootViewController = loginViewController
            window!.makeKeyAndVisible()
        }
        else {
            let homePage = mainStoryBoard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
            window!.rootViewController = homePage
            window!.makeKeyAndVisible()
        }
        return true
    }
}

A: You are setting rootviewcontroller without embedding navigation controller to it in  logoutData & loginData function.
Use this code :
let navigationController = UINavigationController.init(rootViewController: myViewController)
appDelegate.window?.rootViewController = navigationController

Use this code in AppDelegate:
if(!isUserLoggedIn) {

    let loginViewController = mainStoryBoard.instantiateViewController(withIdentifier: "loginview") as! LoginViewController
    let navigationController = UINavigationController.init(rootViewController: loginViewController)
    appDelegate.window?.rootViewController = navigationController
    window!.makeKeyAndVisible()
}
else {
     let homePage = mainStoryBoard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
     let navigationController = UINavigationController.init(rootViewController: homePage)
     appDelegate.window?.rootViewController = navigationController
     window!.makeKeyAndVisible()
}

A: After successful login,try to make NavigationController as rootViewController instead of your ViewController
Your back button will start appearing.
In AppDelegate, in else block, instead of this line
let homePage = mainStoryBoard.instantiateViewController(withIdentifier: "ViewController") as! ViewController
write this
let homePage = mainStoryBoard.instantiateViewController(withIdentifier: "NavigationController") as! UINavigationController
Inside LoginViewController, in the block if(message == 1)
replace
let myViewController:ViewController = self.storyboard!.instantiateViewController(withIdentifier: "ViewController") as! ViewController
with
let navController:UINavigationController = self.storyboard!.instantiateViewController(withIdentifier: "NavigationController") as! UINavigationController
Also set storyboard identifier for UINavigationController in storyboard to NavigationController

A: Remove this from Home.swift,
let appDelegate = UIApplication.shared.delegate as! AppDelegate
        appDelegate.window?.rootViewController = loginViewController
        appDelegate.window?.makeKeyAndVisible()

because its not inheriting the properties of Navigation controller
and add it in Appdelegate.swift file
For the other 3 viewcontrollers, you need to add the Navigation controller between eachSegway in order to inherit it or code the button by instantiating the viewcontrollers respectively

A: Depending on your configuration:
self.navigationItem.hidesBackButton = YES;

OR:
self.navigationController.navigationItem.hidesBackButton = YES;

Or, if you just want to disable the button without hiding it, you can use this.
self.navigationController.navigationItem.backBarButtonItem.enabled = NO;


text:
Q: Why is running R code inside a function faster? Consider the following examples:
> start<-Sys.time()
> for(i in 1:10000){}
> Sys.time()-start
Time difference of 0.01399994 secs
>
> fn<-function(){
+   start<-Sys.time()
+   for(i in 1:10000){}
+   Sys.time()-start
+ }
> fn()
Time difference of 0.00199604 secs

start<-Sys.time()
for(i in 1:10000){x<-100}
Sys.time()-start
Time difference of 0.012995 secs
fn<-function(){
  start<-Sys.time()
  for(i in 1:10000){x<-100}
  Sys.time()-start
}
fn()
Time difference of 0.008996964 secs

The result is the same after increasing number of iterations as shown below:
> sim<-10000000
> start<-Sys.time()
> for(i in 1:sim){x<-i}
> Sys.time()-start
Time difference of 2.832 secs
>
> fn<-function(){
+   start<-Sys.time()
+   for(i in 1:sim){x<-i}
+   Sys.time()-start
+ }
> fn()
Time difference of 2.017997 secs

I am guessing this is not a coincidence! Why does R code run faster in a function?

A: Functions in R are compiled by the JIT compiler.  After this happens, most functions will be faster.
As the docs in ?compiler::enableJIT say,

JIT is disabled if the argument is 0. If level is 1 then
larger closures are compiled before their first use. If level  is 2,
then some small closures are also compiled before their  second use.
If level is 3 then in addition all top level loops  are compiled
before they are executed. JIT level 3 requires the  compiler option
optimize to be 2 or 3. The JIT level can also  be selected by starting
R with the environment variable  R_ENABLE_JIT set to one of these
values. Calling enableJIT with  a negative argument returns the
current JIT level. The default  JIT level is 3.

So many functions will be faster than top level code.

A: To prove the JIT-impact I have used this benchmark:
library(microbenchmark)

compiler::enableJIT(0)  # use 3 for testing with full JIT compiler

fn <- function() {
   for(i in 1:10000) {}
}

microbenchmark(for_loop_without_func = for(i in 1:10000) {},
               for_loop_in_func = fn(),
               times = 100)

# Run eg. with (to avoid RStudio or other overhead):
# R --vanilla < jit_test.R

The result shows that with disabled JIT the execution time is nearly the same:
Unit: microseconds
                  expr     min       lq     mean   median      uq     max neval
 for_loop_without_func 180.619 180.7990 182.7129 180.9290 181.050 239.489   100
      for_loop_in_func 182.582 182.7075 186.2232 182.7625 182.938 309.912   100

With compiler::enableJIT(3) (which is the default) the function is faster:
Unit: microseconds
                  expr     min       lq      mean   median       uq      max neval
 for_loop_without_func 558.727 574.4875 659.21931 657.3425 702.6475 1984.351   100
      for_loop_in_func  53.019  53.4955  61.59588  53.7260  54.0320  790.632   100

Interestingly enabling JIT seems to slow down the code running outside of the function (compared to now JIT) even though it will not be optimized. Would be interesting to understand why (perhaps JIT needs time to find out which code it will not optimize?


text:
Q: TextBlock inside an Expander(in TreeView) not setting Foreground when TreeViewItem is selected <Grid>
    <Grid.Resources>

    <HierarchicalDataTemplate x:Key="TestNode">
        <StackPanel Orientation="Vertical" >
            <TextBlock Text="Detail Feild 1" FontSize="9" FontWeight="Bold"/>
            <TextBlock Text="Detail" FontSize="9"/>
            <Expander x:Name="problemExpander" ExpandDirection="Down" IsExpanded="True">
                <StackPanel Orientation="Vertical">
                    <TextBlock Text="Details:" FontSize="9" FontWeight="Bold"/>
                    <TextBlock Text="Detail" FontSize="9"/>
                    <TextBlock Text="Status:" FontSize="9" FontWeight="Bold"/>
                    <TextBlock Text="Test Status" FontSize="9"/>
                </StackPanel>
            </Expander>
        </StackPanel>
    </HierarchicalDataTemplate>
    </Grid.Resources>

    <TreeView ItemTemplate="{StaticResource TestNode}"
              ItemsSource="{Binding DataContext.Items}" Width="525" Height="350">

    </TreeView>
</Grid>

the Following 2 textBlocks foregrounds are set properly(they turn white when the TreeViewItem is selected)
<TextBlock Text="Detail Feild 1" FontSize="9" FontWeight="Bold"/>
<TextBlock Text="Detail" FontSize="9"/>

but the foreground in the textblocks inside the expander remain their default color... If i remove the expander, the textblocks work as you(I) would think.
Why is this so?  And is there a way to have it such that the TextBlocks inside the expander will also change their foreground Color?


text:
Q: Weird semi-transparent box appears after hover I've noticed this weird bug in CSS and have no idea why it is happening.
Initial state:

Hover state:

After hover:

I tried debugging, but this box is nowhere to be found. Any ideas?
You can observe this on this page https://busko.si/settings.html (it happens on all similar buttons and switches, sometimes on hover sometimes on click in Chrome and Safari).
And if its any help, here is the CSS for the button:
.button-wrapper {
    background: var(--text-color);
    border-radius: 25px;
    box-sizing: border-box;
    cursor: pointer;
    display: inline-block;
    margin: 10px 0;
    max-width: 100%;
    overflow: scroll;
    padding: 5px 10px;
    transition: background 200ms;
    vertical-align: middle;
    white-space: nowrap;
}

.button-inner {
    border-radius: 25px;
    color: var(--text-color-alt);
    cursor: pointer;
    display: inline-block;
    font-size: 11px;
    padding: 5px 10px;
    font-weight: 500;
    text-transform: uppercase;
}

A: I had the same issue. You need to either remove overflow: scroll or use overflow: hidden; text-overflow: ellipsis; . There is something wonky with using scroll.


text:
Q: Google Maps APIv3 about handling multiple markers I have some code I put together and I see that there must be some problem with zLat and zLng. I am wondering why it is when I replace zLat and zLng with tLat and tLng inside my for loop then I get one marker which makes sense. With zLat and zLng in there I get no markers. Why would this be happening?
P.S. My alert for zLat and zLng is producing what looks like proper output but it must not be?
    // // // // // // // // Ajax returns from PHP
xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        var obj = $.parseJSON(xmlhttp.responseText);

        var tLat = getCookie("tLat");
        var tLng = getCookie("tLng");

        var options = {
          zoom: 4,
          center: new google.maps.LatLng(40.7257, -74.0047),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        // Creating the map
        var map = new google.maps.Map(document.getElementById('map'), options);

        // Adding a marker to the map
        /*var marker = new google.maps.Marker({
          position: new google.maps.LatLng(tLat, tLng),
          map: map,
          title: 'Click me',
          icon: 'http://gmaps-samples.googlecode.com/svn/trunk/markers/blue/blank.png'
        });*/

        var marker;

        alert(obj.length);

        for(var i=0;i<obj.length;i++) {

            var zLat = String(obj[i].lat);
            var zLng = String(obj[i].lng);

            marker = new google.maps.Marker({
              position: new google.maps.LatLng(zLat, zLng),
              map: map,
              title: 'Click me'
            });

            alert(zLat+','+zLng+','+i);
        }

        $('#map').show();
    }
}
// // // // // // // //

A:     // // // // // // // // Ajax returns from PHP
xmlhttp.onreadystatechange=function() {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        var obj = $.parseJSON(xmlhttp.responseText);

        var tLat = getCookie("tLat");
        var tLng = getCookie("tLng");

        var options = {
          zoom: 4,
          center: new google.maps.LatLng(tLat, tLng),
          mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        // Creating the map
        var map = new google.maps.Map(document.getElementById('map'), options);

        var myLatLng = new google.maps.LatLng(parseFloat(obj[0][2]), parseFloat(obj[0][1]));

        //var marker = new google.maps.Marker({ position: myLatLng, map: map });

        var marker;

        for(var i=0;i<obj.length;i++) {

            var myLatLng = new google.maps.LatLng(parseFloat(obj[i].lat), parseFloat(obj[i].lng));

            var marker = new google.maps.Marker({ position: myLatLng, map: map });
        }

        $('#map').show();
    }
}
// // // // // // // //


text:
Q: Sorting array in C I'm trying to sort an array size in C, i have ran some tests on it before i publish it here (I have left the testing statement in).
I get the correct answer once but than it moves the higher value into the wrong array, even though i have used an IF statement.
If you guys run the program it will make sense to you.
#include <stdio.h>
# define size 3

int sum();

main() {
    int a[size] = { 4, 2, 3 };
    int temp, i, j, x;

    for (j = 0; j < size; j++){

        for (i = 1; i < size; i++){
            for (x = 0; x < size; x++){
                printf("%d", a[x]); //testing statement;
            }
            printf("\n");
            if (a[j] > a[i]){
                temp = a[j];
                a[j] = a[i];
                a[i] = temp;

            }

        }

    }

for (x = 0; x < size; x++){
            printf("%d", a[x]);
        }
    getch();
}

A: Change
for (i = 1; i < size; i++){

to something like
for (i = j + 1; i < size; i++) {

and your sort will work correctly. As it is, you're comparing the elements again with if (a[j] > a[i]){ which can move them back when you reset i to 1.


text:
Q: Visual Studio 2013 Capitalization Rules I have been working on learning angular2 project by using the great blog post, Cross-platform Single Page Applications with ASP.NET Core 1.0, Angular 2 & TypeScript.
I created my app.html file with the following HTML

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            Toggle navigation

        </button>
         Photo Gallery

When I highlight the code and choose format selection the code get formatted to the following.

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
            Toggle navigation

        </button>
         Photo Gallery

If you can see the routerLink attribute has been formatted to be all lowercase which breaks the angular2 routing.  I have also seen this happen when I save a file, the html get auto formatted.
I have tried setting the properties in Tools-> Options->Text Editor -> Html (Web Forms) -> Formatting and change all of the Capitalization settings to "As Entered" but this did not fix my issue.


text:
Q: How does the dot command work in this case? I was trying to figure out how the dot command works from an example from the book Practical Vim by Drew Neil.

Take the following bit of text:
var foo = "method("+argument1+","+"argument2"+")";

If the cursor is on the first + character, and we do the sequence:
s[space]+[space][Esc]

we add padding around the first +. i.e. the result is:
var foo = "method(" + argument1+","+"argument2"+")";

If we then move to the next + and use the dot command, we end up with:
var foo = "method(" + argument1 + ","+"argument2"+")";

I understand that Vim saves the text we type while in Insert mode until we exit to Normal mode, and then we can apply that change with the dot command.
But why does Vim save the deletion of the + that is done with the s command? Is it because the s command puts Vim in Insert mode first, and then deletes the character?

EDIT:
I checked the Vim documentation for the s command, and it says:

Delete character and start insert.

So it sounds like it deletes the character, then goes into Insert mode, which would disprove my previous theory. What's going on!?

A: Dot command repeats the last change. This is not limited to changes in INSERT mode
To learn more,
:help change.txt

In this case, as @Two-Bit Alchemist has pointed out, everything happened from pressing s to the point when you return to NORMAL mode is a change
A good thing about dot command is that it can be extended to repeat multiple changes
Tim Pope's vim-repeat is a good example of exploiting such possibilities.
Please refer to the following links to learn more
what can the dot command repeat, exactly?
can someone explain to me why the dot command is so useful in vim


text:
Q: Making CXF web service calls from within the same JVM I have a web service running (let's call it the integrator)
I would like to make calls using the client library from the same JVM. The reason for this is that there's a client which creates a serialized file (object stream) of objects which are for the client library generated from the wsdl.
Is there a way to use the client library in the same JVM as the server, and program it so that it doesn't go over HTTP?
The original problem is that the client will initially replicate a ton of data to the service making millions of calls which is too slow. so the original solution was to generate the serialized file of all the objects for the client calls and create an importer on the same machine of the server. This worked great to speed things up, but still get errors even on the local machine (read timeouts, etc which messes things up). I'm hoping to import the serialized data directly into the server, but the objects are all for the client library not the native server classes.


text:
Q: Defining global constants in C++1z? What is the best way of declaring memory efficient Global Constants in C++1z which do not make internal linkage, so a single copy is used though out all the translation units?
Although it's been mentioned in many places, we didn't have any singular "The best approach" question and answer, so here it is. Here is a partial list of places where I have found related questions.

*

*constexpr global constants in a header file and odr

*global declarations/initializations using static, const, constexpr

*Global Constants in C++11

*Defining global constant in C++

*c++ global constants issue

*Global Constants vs. Enumeration

*Proper way to make a global "constant" in C++
I am looking for a solution for atleast all basic basic types, like int, double, char, std::string.
Edit 1:
By best way, I mean "memory efficient". I know for internal linkage, multiple copies for each translation unit will be made, hence eating memory. Along with that if we can achieve fast execution time and compile time, that will be great, glamorizing (easiness of ) the code doesn't matter. Also I know external linkage will increase the fetching time because the processor may get cache misses at run time. But does latest C++ language support the best approach for all these ? Or may be suggested support for each case ?
Note: Also what will be best approach for std::string global constants ? Does there mutability will have any affect on there constness ?

A: Back in the olden days we'd declare a constant in a header file and define it in a source file:
// constants.h
extern const int size;

// constants.cpp
#include "constants.h"
const int size = 3;

// usage
std::cout << size << '\n';

But maybe that's too simple; why not lard it up with a 10-line template and funky instantiation syntax?

A: Summary
In C++17, the easiest way to define a global constant or a global variable is usually with an inline variable. You create one by simply putting a line like the following into your header file:
inline const std::string greeting = "Hello!";

If the global constant is of literal type, prefer using inline constexpr (the inline is optional if it's a static class member) instead of inline const:
inline constexpr std::string_view greeting = "Hello!"sv;

This also works for variables, but many of the advantages no longer apply, so you might want to use another method:
inline unsigned int score = 0;

Details
First, the two main disadvantages to this method are:

*

*It doesn't work before C++17, so if you need C++14 compatibility or earlier, you'll need to do something else. The template trick VTT suggests is compatible with older standards, and should have similar semantics to inline variables, but it's a hack which is no longer necessary if you only need C++17 support.

*It is somewhat slower to compile than extern variables, because the compiler needs to consolidate the multiple definitions, and because more information is available to the optimizer. The "somewhat" part turns into a "noticeably" if you might change the definition, but not the data type; since the value is now in a header file, this means recompiling everything that includes the header, instead of just re-linking. If you might need to change the data type everything will need to be recompiled no matter what.

If neither of those is important to you, I think this method beats the other ways of getting a global constant with external linkage and at most¹ one definition in the final executable².
An inline variable like this is mentioned in just one file, so it's easy to change; this is particularly useful for header-only libraries. This also means it has its value available at compile time, so the optimizer can see it and maybe eliminate some usages.
Using constexpr
In C++17, static constexpr class members are automatically inline, so if your global constant should be part of a class's scope, you can do something like
constexpr int favorite_number = -3;

Otherwise, you will need to say constexpr inline, which should still work. This will have the semantics described above, but also the usual advantages of constexpr, so the compiler will know that it can try to do more at compile time. For example:
#include <string_view>

using namespace std::literals;

inline constexpr std::string_view greeting = "Hello!"sv;

inline constexpr int scrabble_points[greeting.size()] = {4, 1, 1, 1, 1, 0};

int main() {
  int total = 0;
  for (int i : scrabble_points) {
    total += i;
  }
  return total;
}

is possible with constexpr, but not with just inline, because with constexpr it knows that greeting.size() is a compile-time constant and can be used as the size of an array.³ With optimizations, this could compile to a just a single mov instruction and ret, without including any copies of the string or array because it's unnecessary.
With the new inline semantics, everything before main could have been in a header file included in multiple places, and there would still have been at most one copy.
Variables
The same method easily supports mutable variables by leaving off the const:
inline std::string player_name = "<subject name here>";

This is then a global variable with external linkage. Since it's a variable, most of the advantages I'v mentioned over Pete's answer are gone, but some (like only declaring the variable in one place and not needing to link any thing extra) are still present. They might not be worth the slight extra compile time and the lack of C++14 compatibility, though.

¹ For a const or constexpr variable, the compiler/optimizer might completely eliminate the variable if it isn't needed. In theory, it might decide to copy it to an immediate value or something; in practice you probably shouldn't worry about that because it would only do that if it had a good reason, and this should make the final executable smaller and/or faster. You could probably tune this with -Os instead of -O3.
² Each object file which used the constant would still have a copy, but those would be combined at link time. The only way to avoid that is with extern variables.
³ This simplified example works even without inline, or with the array being only const instead of constexpr, but those are useful for more complicated real-world situations.

A: I suggest to use a template wrapper, which allows to define a global constant of any type in header file and will spawn only a single copy through out all the translation units (no C++1z required):
template<typename TDummy = void> class
t_GlobalValueHolder final
{
     public: using
     t_Value = const int; // can be anything

     public: static t_Value s_value;
};

template<typename TDummy>
typename t_GlobalValueHolder<TDummy>::t_Value
t_GlobalValueHolder<TDummy>::s_value{42};

// usage
::std::cout << t_GlobalValueHolder<>::s_value;

Notice: typically access to s_value should be restricted to only a subset of classes / methods by either making value protected and deriving user class from t_GlobalValueHolder or just with listing all the relevant items as friends of t_GlobalValueHolder. And proper access control is another benefit of this method over "extern const " besides eliminating a need to have a translation unit containing value definition.


text:
Q: Adding a method to Javascript String object, that will replace the string with a new one I'm trying to add a very simple method to the String object:
 String.prototype.double = function double() {
        let newStr = ""
        for (let char of this) {
            console.log(char)
            newStr += char;
            newStr += char;
        }
 }

As you can see, it just "doubles" each character in the string. The problem is, i don't know how to actually replace the original string, with the new one("newStr")
I've tried doing this = newStr, which resulted in an "Invalid left-hand side in assignment" error.
How can i replace the original string, on which the method was called, with the new one?

A: You need to return the new string.

String.prototype.double = function double() {
  let newStr = ""
  for (let char of this) {
    newStr += char+char;
  }
  return newStr;
}

console.log("string".double());

Other shorter approach could be

String.prototype.double = function double() {
  return this.split("").map(e=>e+e).join("");
}

console.log("string".double());

Update: (regarding OP's comment)
In JavaScript, strings are immutable objects, which means that the characters within them may not be changed and that any operations on strings actually create new strings.
So you wont be able to change the original string as any operation done on a string always returns a new string. So you will need to assign the value back to the original string.

A: Consider returning new string rather than replacing it. As mentioned, strings are immutable. So your code will be:
String.prototype.double = function double() {
    let newStr = ""
    for (let char of this) {
        console.log(char)
        newStr += char;
        newStr += char;
    }
    return newStr;
}

The additional benefit of doing this is that you can have string methods as "chained". For example:
'ab'.double().toUpperCase(); //-> "AABB"


text:
Q: How does one incrementally build a nested object structure from an array of property names? My task is straight forward. I have an array of strings:
let a=["a","b","c"];

And i want to convert that array to (can alter the original array, doesn't matter) what i would like to call as "recursive object" just so:
//in json format just to demonstrate
"object": {
    "a": {
      "b":{
        "c":{

        }

      }
    }
  }

I've tried the following logic but couldn't get it to work due to reference problem and i couldn't build recursion.
let tempObj;
let obj2;

array.slice().reverse().forEach(function(item,index){

        obj2=tempObj;
        tempObj[item]="";

    });

Just to make sure we are on the same page, another example:
let arr=["alpha","beta","gamma"];
let magicObj=someMagicFunction(arr);
//magicObj["alpha"]["beta"]["gamma"] contains the value ""

Thanks

A: Start aggregating your object from the array's right most side via reduceRight and provide e.g. an empty object / {} or an empty string / "" as this method's initial value(s) ...

console.log(
  'object :',
  ["a","b","c"]
    .reduceRight((obj, key) =>
      ({ [key]: obj }), {}
    )
);
console.log(
  'object :',
  ["alpha","beta","gamma"]
    .reduceRight((obj, key) =>
      ({ [key]: obj }), ""
    )
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

... and since code code-reuse always should be a goal the above examples change to ...

function createObjectWithParentKeyAndChildValue(value, key) {
  return { [key]: value };
}
console.log(
  'object :',
  ['a', 'b', 'c']
    .reduceRight(createObjectWithParentKeyAndChildValue, {})
);
console.log(
  'object :',
  ['alpha', 'beta', 'gamma']
    .reduceRight(createObjectWithParentKeyAndChildValue, '')
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

A: Here is a simple solution:

const arr = ["a","b","c"];
const result = arr.reverse().reduce((obj, key) => ({[key]: obj}), {})
console.log(result)

Here a little explaination:
o is the result of the last iteration and v is the current element in the array. {[v]: o} creates a new object and sets the property v to o and returns that.

A: let magicObj = arr.reverse().reduce((obj, prop) => ({ [prop]: obj }), {})

A: there is my pure recursive answer:
let a=["a","b","c"];

const b = (arr = [], obj = null) => {
  if (arr.length > 0) {
    const { length, [length - 1]: last, ...r } = arr;
    const rest = Object.values(r);
    const nextObj = obj ? { [last]: obj } : { [last]: {} };
    return b(rest, nextObj);
  }
  return obj;
};

console.log(b(a));

A: The reduce / reduceRight answers are great.  But this can also be done with a fairly trivial recursive version:

const buildDeep = ([p, ...ps], val) =>
  p == undefined ? val : {[p]: buildDeep (ps, val)}

console .log (buildDeep (['a', 'b', 'c'], {}))
console .log (buildDeep (['alpha', 'beta', 'gamma'], ''))

To my mind, this is even simpler than reduce.  It feels related to the various path-setting functions you see around, but is less complex since it doesn't have to work with an existing object.


text:
Q: Object texture issue using three.js library I achieved to apply a texture to my 3D object using THREE.texture, but I still have an issue with the lateral face (see the link below). I don't know how to select the lateral face of my object...Do you have an idea on how to solve this ?
Salmon Cut
        var manager = new THREE.LoadingManager();
        manager.onProgress = function (item, loaded, total) {
            console.log(item, loaded, total);
        };
        var texture = new THREE.Texture();
        var onProgress = function (xhr) {
            if (xhr.lengthComputable) {
                var percentComplete = xhr.loaded / xhr.total * 100;
                console.log(Math.round(percentComplete, 2) + '% downloaded');
            }
        };
        var onError = function (xhr) {};

        var loader = new THREE.ImageLoader(manager);
        loader.load('/Scan/filet_1kg500-reposition-reduit_material_0.jpg', function (image) {
            texture.image = image;
            texture.needsUpdate = true;
        });


text:
Q: Encoding on Apache with Python CGI using Zipfile.extract as new member of the community, i directly want to join with a Question....
After i found many helping and inspiering questions and answers, i am now on a level where could not even find help within Google our though related question.
But back to topic:
I struggle with an encoding problem with a running CGI python script after a zip file upload which i want to process further:
def unzip_dir(zipname):
zfile = zipfile.ZipFile(zipdir + zipname)
for name in zfile.namelist():
  (dirname, filename) = os.path.split(name)
  if filename.lower().endswith('.json'):
      if not os.path.exists(unzipdir):
        os.makedirs(unzipdir)
        #LASTCHANGE - IDENTIFIED PROBLEM WITH UTF 8 and ZIPfiles in APACHE (Not reproduceable in any terminal)
      zfile.extract(name, unzipdir)
      shutil.move(wdir+'//'+unzipdir+'//'+name, unzipdir)

Running this on unix systems through ssh works perfectly fine. But if i start this from Web through a CGI Call i run into the following error:
<type 'exceptions.UnicodeEncodeError'>: 'ascii' codec can't encode character u'\xe4' in position 95: ordinal not in range(128)
  args = ('ascii', u'analysis/Searchqueries-201650215T114640Z/Suchanf...nfragen/2007-01-01 Januar 2007 bis M\xe4rz 2007.json', 95, 96, 'ordinal not in range(128)')
  encoding = 'ascii'
  end = 96
  message = ''
  object = u'analysis/Searchqueries-201650215T114640Z/Suchanf...nfragen/2007-01-01 Januar 2007 bis M\xe4rz 2007.json'
  reason = 'ordinal not in range(128)'
  start = 95

which is located here:
zfile.extract(name, unzipdir)

As far as i understand from previous reports and Q&A the issue is related to the way Apache handles the CGI with Python some how. All attempts to change the encoding on python level (sys input and output information) or such didnt lead to anything.
I also tried to encode the name Variable in the critical line with all kind of encoding but this was mainly leading to the fact that the same line could not find the corresponding entry in the zip file anymore:
<type 'exceptions.KeyError'>: "There is no item named 'Suchanfragen/Suchanfragen/2007-01-01 Januar 2007 bis M\\x84rz 2007.json' in the archive"
  args = (r"There is no item named 'Suchanfragen/Suchanfrage...Januar 2007 bis M\x84rz 2007.json' in the archive",)
  message = r"There is no item named 'Suchanfragen/Suchanfrage...Januar 2007 bis M\x84rz 2007.json' in the archive"

I also checked the httpd.conf of the webserver but this is leading UTF-8.
Can any one give me a helping hand here ? I assume it is not such a trivial issue, but limited on my thinking.
UPDATE:
I start now some how not knowing what i am even doing and i fear i crash my whole systemd ue to stupidity. I now tried to add a value in my httpd.conf file called PassEnv in some Virtual Host area with no success after restart.
UPDATE 2:
I tried this
sys.stdout = codecs.getwriter("utf-8")(sys.stdout)

but honestly... no idea what to do with it in the context of the zip file.

A: Seems like i found a way arround the real issue.
And i am fine with it as of now:
I avoid the encoding problems with the zipfile Method by unzipping the files through Shell. I think i increase the risk through this process but i actually rather risk it at this early stage than not making any progress, which was driving me nuts.
Here is the changed method for your reference:
def unzip_dir_v2(zipname):
if not os.path.exists(unzipdir):
    os.makedirs(unzipdir)
syntaxer = 'unzip -o -j -q -d' + wdir + '/' + unzipdir + ' ' + wdir + '/' + zipdir + '' + zipname
p = subprocess.Popen(syntaxer, shell=True)
p.communicate() #now wait


text:
Q: CSS 'top' property has no effect I'm just starting with CSS and would like to understand some behaviors.
I have this defined in a CSS file:
#spa {
position : absolute;
top      : 8px;
left     : 8px;
bottom   : 8px;
right    : 8px;

min-height : 500px;
min-width  : 500px;
overflow   : hidden;

background-color : #fff;
border-radius    : 0 8px 0 8px;
}

.spa-shell-head {
  top    : 0;
  left   : 0;
  right  : 0;
  height : 40px;
}
.spa-shell-head-logo {
  **top        : 4px;
  left       : 4px;**
  height     : 32px;
  width      : 128px;
  background : orange;
}

.spa-shell-head-acct {
  **top        : 4px;
  right      : 0;**
  width      : 64px;
  height     : 32px;
  background : green;
}

and this in my HTML file:

Why is it that I can change the bold properties to any number but the elements don't change? (at least the background colour that I have set to those elements)
Full code can be found here: http://jsfiddle.net/fu6dmhdt/1/

A: Simply because neither .spa-shell-head-logo nor .spa-shell-head-acct divs are positioned.
CSS top, right, bottom and left (offset) properties are only applicable to non-static positioned elements - i.e. elements have a position other than static (fixed, absolute, relative).
For instance, give them a position of relative to see the effect - Example.

A: Top, Left, Bottom and Right property works depending upon the position. It absolutely work with when you assign position property to absolute/fixed.

A: the properties of top, left, right, and bottom, will only work if you have declared the positions of the elements you are using the tags with as position absolute, or fixed. otherwise you will want to use margining.
as a side note, it will be very beneficial for you to try and keep all of your css in the same place. Once you start adding more css, it will likely become confusing!
hope this helps.


text:
Q: tower defense javascript animation Hi :) First of all sorry for my horrible english, i'm a bad french with a bad english but i hope my resquest will be understandable.
So, i'm 17 years old and for my bac (do you know this graduate ?) Before university, i have a project for my specilisation computer science. My project is to create a Tower defense really simply in javascript/Html/Css, without graphism etc.. So my goal is to do spawn x mobs around my square, then this mobs will rush tower, if 2 mobs are on the tower, she get destroyed, if any tower left, game is lost. So, this is my code, i will ask you question after code.
    var canvas = document.getElementById("fenetreJeu");
var ctx = canvas.getContext("2d");

var mob = document.getElementById("mobile");

var fenetreDuJeuHauteur = canvas.height-5;
var fenetreDuJeuLargeur = canvas.width-5;

var largeurMobile = mob.offsetLeft;
var vx = 2; // vitesse en pixel vers la droite
var xmin = 0; // limite gauche
var xmax = fenetreDuJeuLargeur;

var hauteurMobile = mob.offsetTop; //ordonnée du mobile
var vy= 2;
var ymin = 0;
var ymax=fenetreDuJeuHauteur;

var timer1;

window.onload = function()
{

    var debut = document.getElementById("start");
    var arret   = document.getElementById("stop");
    var blocCentrale = document.getElementById("blocCentrale");
    var tour = document.getElementById("tour");

    debut.addEventListener("click",debutPartie);
    arret.addEventListener("click",pause);

    quadrillage();
    generationMob();

    ensembleMob = document.getElementsByClassName("monstre");
    ensembleMob[0].style.backgroundColor = "blue";

}
function generationMob()
{
    for(i = 0; i < 10; i++){
    creationPositionnement();
    }
}

function creationPositionnement(){

    var ensembleMob = [];
    var mobCree = document.createElement("div");

        mobCree.className = "monstre";
        mobCree.style.width = "5px";
        mobCree.style.height = "5px";
        mobCree.style.backgroundColor = "red";
        mobCree.style.position = "absolute";
        ensembleMob = document.getElementsByClassName("monstre");

    var mobCreeHauteur = mobCree.style.top = Math.floor(Math.random()*595)+"px";
    var mobCreeLargeur = mobCree.style.left = Math.floor(Math.random()*595)+"px";
    var aleatoirePosition = Math.floor((Math.random()*4)+1);

    if (aleatoirePosition == 1){
        if (mobCreeHauteur != 0){
            mobCree.style.left = "0"+"px";}
    }if (aleatoirePosition == 2){
        if (mobCreeLargeur != 0){
            mobCree.style.top = "0"+"px";}
    }if (aleatoirePosition == 3){
        if (mobCreeHauteur != 0){
            mobCree.style.left = "595"+"px";}
    }if (aleatoirePosition == 4){
        if (mobCreeLargeur != 0){
            mobCree.style.top = "595"+"px";}
    }
    blocCentrale.appendChild(mobCree);

    return ensembleMob;
}

function positionCurseur ()
{

}

function quadrillage (){
    var larg = 50;
    var haut = 50;

    for (var i = 0; i < 40;i++){
        ctx.beginPath();
        ctx.moveTo(larg,0);
        ctx.lineTo(larg,600);
        ctx.stroke();
        larg +=50;
    }

    for (var i = 0; i < 20;i++){
        ctx.beginPath();
        ctx.moveTo(0,haut);
        ctx.lineTo(canvas.width,haut);
        ctx.stroke();
        haut +=50;
    }
}

function debutPartie(){
    // lance le changement de position tout les 0,01 secondes.
    clearInterval(timer1); //arrête un éventuel timer déjà en place.
    timer1 = setInterval(animation2,10); // Lance le déplacement
}

function pause(){
    clearInterval(timer1);
}

var animation = function() {
    // déplace le mobile de Vx pixels vers la droite et change Vx si on arrive au bord.
    largeurMobile = largeurMobile + Vx;
    if ((largeurMobile<=xmin) || (largeurMobile>=xmax)) {
        Vx=-Vx; // Si on est au bord, on change le sens de déplacement.
    }
    mobile.style.left=largeurMobile+"px"; // déplacement de l'objet à l'écran.

    hauteurMobile = hauteurMobile + Vy;
    if ((hauteurMobile<=ymin) || (hauteurMobile>=ymax)) {
        Vy=-Vy; // Si on est au bord, on change le sens de déplacement.
    }
    mobile.style.top=hauteurMobile+"px"; // déplacement de l'objet à l'écran.
}

function animationBis(){

    for (i = 0; i < 10; i++){
        ensembleMob[i].style.left = ensembleMob[i].offsetLeft + vy + "px";
        if (ensembleMob[i].offsetLeft <= 0 || ensembleMob[i].offsetLeft >= 595){
        vx =- vx;
        }

        ensembleMob[i].style.top = ensembleMob[i].offsetTop + vx + "px";
        if (ensembleMob[i].offsetTop <= 0 || ensembleMob[i].offsetTop >= 595){
        vy =- vy;
        }

    }
}

function animation2(){

        ensembleMob[0].style.left = ensembleMob[0].offsetLeft + vy + "px";
            if (ensembleMob[0].offsetLeft <= 0 || ensembleMob[0].offsetLeft >= 595){
            vy =- vy;
            }
        ensembleMob[0].style.top = ensembleMob[0].offsetTop + vx + "px";
            if (ensembleMob[0].offsetTop <= 0 || ensembleMob[0].offsetTop >= 595){
            vx =- vx;
            }

}

// calculer la position d'un element sur la page
/*calcul la position d'un élément sur la page

            var item = document.getElementById(img);
            var parent = item.offsetParent;
            var posElmX = 0;
            var posElmY = 0;
            while(parent) {
                posElmX += parent.offsetLeft;
                posElmY += parent.offsetTop;
                parent = parent.offsetParent;
            }
            var positionX = item.offsetLeft + posElmX;
            var positionY = item.offsetTop + posElmY;

changer les dimension d'un élément

            item.style.width = item.offsetWidth+10+'px';
                        item.style.height = item.offsetHeight+5+'px';
                        */

Don't take care about somes function, example: function animation was a test, animationBis doesn't work, but animation2 work except if div is at the bottom or right to the block central.
So my question is about animationBis it's a "test" but i think i need ideas of this function later for the finally animation, it doesn't work. Div(mob) move yeah, but really strange move, like they are in a other div but not on my block central. I think it's because of my var vitesse, but i'm not sure.
Another question if i can :)
How can i say at mob "U rush the tower (automatic move from him position to the tower)" ?
As you see, my level of javascript is really bad and i only use function so if u can give me a answer with function i prefer :)
Still and still sorry for my awful english and thx for your answers and your patience to read me. Bye :)

A: I'll give you an example of using two very handy techniques:
// Define state variables like so:
var MOVING_LEFT = 1;
var MOVING_RIGHT = 2;
var MOVING_UP = 3;
var MOVING_DOWN = 4;

// Use these human-readable variable names to set states
var current_moving_direction = MOVING_RIGHT;

// Use these variables to check for the state again
switch (current_moving_direction){
    case MOVING_LEFT:
    // Execute code for moving left
    break;
    case MOVING_RIGHT:
    // Execute code for moving right
    break;
    case MOVING_UP:
    // Execute code for moving up
    break;
    case MOVING_DOWN:
    // Execute code for moving down
    break;
}

The variables in upper-case letters are contants. They contain the numbers 1-4 that you had to manage yourself in your way of doing it. That way, what you see from these numbers is just what they mean. Still, you can check for the numbers that are now stored in them.
The switch-case statement checks the variable 'current_moving_direction' for all states defined by each 'case' label. The 'break' is necessary to break the switch-case, once a condition was true.


text:
Q: conversion of event.srcElement using event.target in jquery I have question about cross-browser compatibility.
I want to use the event.target instead of event.srcElement in the following code to make it work for firefox.
I have used target = event.target || event.srcElement. It is not working. Any help will be appreciated.
function jumptoPopupMenuItem(theMenuID)
{
  if (event.srcElement.className == "RightClickMenuItems")
  {
    if (event.srcElement.getAttribute("url") != null)
    {
      var strParameters = "";
      if (theMenuID == "mnuAppointmentMenu")
      {
        strParameters = "AppointmentNumber=" + m_strAppointmentTypeYearNumber;
      }
      else if (theMenuID == "mnuAvailableHourMenu")
      {
        strParameters = "PreFillLanguageID=" + m_nLanguageID;
        strParameters = strParameters + "&PreFillInterpreterID=" + m_nInterpreterID;
        strParameters = strParameters + "&PreFillDateOfService=" + m_dtDateOfService;
      }
      if (event.srcElement.getAttribute("target") != null)
      {
        var PopupWindow = window.open(
            event.srcElement.url + strParameters,
            event.srcElement.getAttribute("target"));
        PopupWindow.focus();
      }
      else
      {
        window.location = event.srcElement.url;
      }
    }
    hidePopupMenu(theMenuID);
  }
}

A: if you're using jquery, just use var $target = $(e.target); -- it'll do the right thing for the browsers.


text:
Q: Why do we need the Lync SDK Controls, if they can not be used in UI Suppression mode? Why do we need the Lync SDK Controls, if they can not be used in UI Suppression mode? For example, MyStatusArea control or other.

A: The Lync controls provides value in 2 use cases as far as I can see:

*

*For use when building an app that automates Lync

*For use in a Conversation Window Extension Silverlight application

In these cases, having to code the functionality that the controls provide would be quite a lot of effort, so there's a productivity gain to be had by using the controls.
Having said that, it is a shame that the controls can't be used in UI suppression mode.
One reason is that for some controls, it doesn't make sense to run them in UI suppression mode. For example, the StartInstantMessagingButton control fires up a new conversation window - this conversation window would not be displayed in UI suppression mode (given that the UI is suppressed!)
Another possible reason (my own take on it) is that UI suppression mode is to be used when a company wants to restrict users to a limited subset of Lync functionality. e.g. they may wish to embed the ability to send an IM to a set of users in an HR department, but not allow the ability to call any other users, or add other contacts etc.
Allowing the controls to work when in Suppressed UI mode would mean that a non-developer could open Visual Studio, create a WPF/Silverlight app, drag on some controls and effectively bypass the restrictions that the company imposed. (of course, as it stands a developer could still create an app that uses the raw API to bypass those restrictions, but it would be a lot more work).
I may be way off on this, and there may be other technical reasons for the limitation.
If you're happy that this is the right answer, could you mark it as accepted using the tick, to help any other users visiting this post? Thanks


text:
Q: Symbolicate iOS Crash Stack Trace without Crash Log I'm using BugSense to track crashes from an iOS App. Recently I noticed problems symbolicating stack traces from live usage.
The problem is that Apple introduced address space randomization with iOS 4.3 so that the stack address of interest cannot solely be used to retrieve the correct methods that caused the crash.
Currently I'm trying to get the correct address by calculating
symbol address = slide + stack address - load address

I already have slide and stack address but from my understanding the load address can only be found in the crash report which I cannot get via BugSense.
The stack trace looks like
0 CoreFoundation 0x342723e7 + 162
1 libobjc.A.dylib 0x3bf63963 objc_exception_throw + 30
2 CoreFoundation 0x3427229d + 0
3 Foundation 0x34b48fa3 + 90
4 UIKit 0x360b5bd9 + 7640
5 MyApp 0x000c6e99 0xb3000 + 81561
6 UIKit 0x3623c2ff 0x3607e000 + 1827583
7 UIKit 0x361b8737 0x3607e000 + 1287991
8 UIKit 0x361a9869 0x3607e000 + 1226857
9 UIKit 0x361a97ad 0x3607e000 + 1226669
10 CoreFoundation 0x34247941 0x341b0000 + 620865
11 CoreFoundation 0x34245c39 0x341b0000 + 613433
12 CoreFoundation 0x34245f1d 0x341b0000 + 614173
13 CoreFoundation 0x341b923d CFRunLoopRunSpecific + 356
14 CoreFoundation 0x341b90c9 CFRunLoopRunInMode + 104
15 GraphicsServices 0x37d9733b GSEventRunModal + 74
16 UIKit 0x360d52b9 UIApplicationMain + 1120
17 MyApp 0x000b61bf 0xb3000 + 12735
18 MyApp 0x000b4a08 0xb3000 + 6664

Is there another way to symbolicate this address or to get the respective load address?

A: The load address is 0xb3000.
Luckily you have the symbols stripped from your app binary, otherwise this wouldn't be visible.
Also this crash happened because of an exception being thrown, so the crash report should give you a Last Exception Backtrace showing where the actual exception happened and the actual exception reason. It is likely that the call in line 5 of the posted stack trace doesn't give you a lot of information on that. The crash information you are getting looks pretty limited :(


text:
Q: Помогите с float версткой Всем привет ребята, я в html и css новичок.
Мне надо правильно сверстать с float такую страницу

Попытался что то сделать и вот что получилось:

https://jsfiddle.net/vp6xmtjf/

html, body {
    width: 100%;
    height: 100%;
}

#main{
    width: 1000px;
    height: 80%;
    margin: 0 auto;
    border: 1px solid black;
}

#content{
    width: 60%;
    height: 60%;
    float: left;
    border: 1px solid black;
    overflow: auto;
}

#content p{
    margin: 0 auto;
    width: 80%;
}

#localNavigation{
    background: #F7F7D0;
    height: 550px;
    width: 20%;
    float: left;
}

#relatedLinks{
    background: #F8E9F8;
    width: 20%;
    height: 550px;
    float: right;
}

#identity{
    background: #B4C7E7;
    height: 130px;
    float:left;
}

#pageHeader{
    background: #F4F7FC;
    height: 130px;
    float:left;
}

#pageFooter{
    background: #D0F7DD;
    height: 60px;
}

body {
    background-color:#FFFFFF;
    color:#000000;
}

.clearfix {
    clear:both;
}

    Identity

    Page Header

Local navigation

Lorem ipsum ea sea quot nonumy, te per detracto sadipscing. Te nec
    assum percipit intellegam, dicam bonorum fabellas qui te. Prodesset
    signiferumque mea eu, eu homero denique perfecto eam, te vix cetero
    commune. Atqui omittam no nam. Te vis harum fuisset recusabo, ne has
    possim adolescens. Et eam noster quodsi apeirian.
    Ut has sint quaestio, ei usu alterum expetenda salutatus. Quem
    fabellas no sed, quo in probo debet minimum. Ea vel urbanitas
    mnesarchum. Nam nulla vulputate vituperata ut, qui at graecis
    invidunt abhorreant. Ad cum eruditi accusam, ex iusto oportere
    deseruisse usu. Summo movet vulputate mea at. Id vel libris
    honestatis.
    Te eius natum tantas eam, melius offendit singulis eum ad. Inermis
    imperdiet ne his, an alia doctus mea. Audire alienum delectus mea
    te, odio libris putent ne eam, at has cibo habemus democritum. At
    mei errem phaedrum. Ut eligendi tincidunt sea, te nam verear
    quaerendum. Mel quot ullum cetero ne, debet dissentiunt ut mei.
    Ei mei altera mandamus, vix facilis contentiones ea. Ea ceteros
    torquatos pro, usu et fabulas salutatus. An sea wisi prima
    dissentiunt. Vel eu sumo detraxit mediocrem.
    Duo sumo recusabo adversarium ei, an prima facete mel. Ius ei postea
    deserunt. Feugait deseruisse interpretaris id est. Et tollit mollis
    vix. Duis erat pri in, appareat scripserit an nam.
    Ea has debet nusquam, no sea melius alterum platonem. Ne sit aeque
    consul, choro appareat maiestatis vel at. Ad sale nihil omittantur
    quo, iriure liberavisse delicatissimi ad sit, kasd labores
    instructior ad mea. Ei choro appetere has. Est exerci delenit
    appellantur ut, rebum tation cu mei.
    Sed modo duis ne, vis id clita inciderint. His ex alii libris
    contentiones. An eius detraxit aliquando sea, idque graecis scaevola
    an vim, verear meliore vivendo sed an. Aliquid dissentiet ius ei,
    postea admodum vis an. Vix at lorem nemore, natum dicit per ex, ad
    vim vero concludaturque. Quo ei habemus reprehendunt, option
    evertitur te vim.
    Usu no adolescens interesset referrentur. Usu id scripta veritus, in
    ponderum adipisci sea, ius ea errem choro democritum. Ei duo
    perfecto accusamus torquatos, mel id dico mediocrem. Sonet
    mediocritatem cum ad, at eam molestie repudiandae, ius eu veniam
    philosophia consectetuer. Timeam deterruisset no vel. Per fugit
    explicari definiebas ea, cum homero legimus luptatum te.
    Ea partem animal eam, eum eu sint feugiat. Essent eirmod deleniti
    mel ut, in eam legere consulatu. Sea congue civibus te, inani
    invenire maiestatis vim cu, inani facete nam ut. An urbanitas
    persecuti eum. Mutat mucius consulatu cu nec, facer dolores
    cotidieque at est. Has quas semper ne, usu homero nonummy
    concludaturque ad.
    Eum consul soluta id. Adipisci honestatis mediocritatem ut vel, cum
    ex omnium persecuti efficiendi. Veri nominavi his ex. Ex aliquando
    philosophia est, velit soluta vix at. In tale nullam sit. Ex mel
    labores inermis, mei option commodo hendrerit et.

    Related Links

Подскажите как правильно сделать.
Заранее спасибо!

A: Вам нужно вложить элементы каждого ряда в блок:
[[][]]
[[][][]]
[[]]

но есть один нюанс float: left заставляет блочные элементы "прилепляться" друг за другом, и, чтобы сбросить это поведение для следующего ряда элементов - одного контейнера недостаточно, нужно использовать clearfix для этого контейнера.
Кроссбраузерный clearfix вот:
.clearfix:after {
   content: " ";
   visibility: hidden;
   display: block;
   height: 0;
   clear: both;
}

его нужно назначить каждому контейнеру ряда.
Но также, для современных браузеров, хорошим вариантом  будет использование dispay: inline-block - это также позволяет прилеплять блоки друг за другом, но лишено проблемы float-блоков, т.е. для сброса ряда достаточно обычного внешнего контейнера.

A: Держи, там только с рамкой проблема в 1 пиксель

 html,
 body {
   width: 100%;
   height: 100%;
 }
 body {
   background-color: #FFFFFF;
   color: #000000;
 }
 #identity {
   background: #B4C7E7;
   width: 20%;
   height: 130px;
   float: left;
 }
 #pageHeader {
   background: #F4F7FC;
   height: 130px;
   width: 80%;
 }
 .conc {
   clear: both;
 }
 #localNavigation {
   background: #F7F7D0;
   height: 550px;
   width: 20%;
   float: left;
 }
 #content {
   width: 60%;
   height: 550px;
   float: left;
   border: 1px solid black;
   overflow-y: scroll;
 }
 #content p {
   margin: 0 auto;
   width: 80%;
 }
 #relatedLinks {
   background: #F8E9F8;
   width: 19%;
   height: 550px;
   float: right;
 }
 footer {
   clear: both;
   background: #D0F7DD;
   height: 60px;
 }
<!DOCTYPE html>

  <meta charset="UTF-8" />
  <title>Labb3 c</title>

      Identity

      Page Header

Local navigation

Lorem ipsum ea sea quot nonumy, te per detracto sadipscing. Te nec assum percipit intellegam, dicam bonorum fabellas qui te. Prodesset signiferumque mea eu, eu homero denique perfecto eam, te vix cetero commune. Atqui omittam no nam. Te vis harum
        fuisset recusabo, ne has possim adolescens. Et eam noster quodsi apeirian. Ut has sint quaestio, ei usu alterum expetenda salutatus. Quem fabellas no sed, quo in probo debet minimum. Ea vel urbanitas mnesarchum. Nam nulla vulputate vituperata
        ut, qui at graecis invidunt abhorreant. Ad cum eruditi accusam, ex iusto oportere deseruisse usu. Summo movet vulputate mea at. Id vel libris honestatis. Te eius natum tantas eam, melius offendit singulis eum ad. Inermis imperdiet ne his, an alia
        doctus mea. Audire alienum delectus mea te, odio libris putent ne eam, at has cibo habemus democritum. At mei errem phaedrum. Ut eligendi tincidunt sea, te nam verear quaerendum. Mel quot ullum cetero ne, debet dissentiunt ut mei. Ei mei altera
        mandamus, vix facilis contentiones ea. Ea ceteros torquatos pro, usu et fabulas salutatus. An sea wisi prima dissentiunt. Vel eu sumo detraxit mediocrem. Duo sumo recusabo adversarium ei, an prima facete mel. Ius ei postea deserunt. Feugait deseruisse
        interpretaris id est. Et tollit mollis vix. Duis erat pri in, appareat scripserit an nam. Ea has debet nusquam, no sea melius alterum platonem. Ne sit aeque consul, choro appareat maiestatis vel at. Ad sale nihil omittantur quo, iriure liberavisse
        delicatissimi ad sit, kasd labores instructior ad mea. Ei choro appetere has. Est exerci delenit appellantur ut, rebum tation cu mei. Sed modo duis ne, vis id clita inciderint. His ex alii libris contentiones. An eius detraxit aliquando sea, idque
        graecis scaevola an vim, verear meliore vivendo sed an. Aliquid dissentiet ius ei, postea admodum vis an. Vix at lorem nemore, natum dicit per ex, ad vim vero concludaturque. Quo ei habemus reprehendunt, option evertitur te vim. Usu no adolescens
        interesset referrentur. Usu id scripta veritus, in ponderum adipisci sea, ius ea errem choro democritum. Ei duo perfecto accusamus torquatos, mel id dico mediocrem. Sonet mediocritatem cum ad, at eam molestie repudiandae, ius eu veniam philosophia
        consectetuer. Timeam deterruisset no vel. Per fugit explicari definiebas ea, cum homero legimus luptatum te. Ea partem animal eam, eum eu sint feugiat. Essent eirmod deleniti mel ut, in eam legere consulatu. Sea congue civibus te, inani invenire
        maiestatis vim cu, inani facete nam ut. An urbanitas persecuti eum. Mutat mucius consulatu cu nec, facer dolores cotidieque at est. Has quas semper ne, usu homero nonummy concludaturque ad. Eum consul soluta id. Adipisci honestatis mediocritatem
        ut vel, cum ex omnium persecuti efficiendi. Veri nominavi his ex. Ex aliquando philosophia est, velit soluta vix at. In tale nullam sit. Ex mel labores inermis, mei option commodo hendrerit et.

      Related Links

`


text:
Q: Creating a Neural Network layer has sum of N tf.exp function in Tensorflow I want to create a function f which will take input x and gives output y as: y = f(x)
f(x) = c1 exp( (x-m1) /l1 ) + c2 exp( (x-m2) /l2 ) + ......

here, x is input tensor. cn, mn and ln (n=1 to N) are Tensorflow scalar variables (N*3 variables).

A: Solution 1) Explicit broadcasting then reduction:
tiling = [1] * len(x.get_shape().as_list()) + [n]
res = tf.reduce_sum(
    c * tf.exp((tf.tile(tf.expand_dims(x, axis=-1), tiling) - m) / l),
    axis=-1)

Solution 2) Looping over n:
condition = lambda i, y: i < n
operation = lambda i, y: [i+1, y + c[i] * tf.exp((x - m[i]) / l[i])]
_, res = tf.while_loop(condition, operation,
                       loop_vars=[0, tf.zeros_like(x)],
                       shape_invariants=[tf.TensorShape([]), x.get_shape()])

Example:
import tensorflow as tf
import numpy as np

# Inputs for example:
x_val = np.random.rand(3, 2)
n = 3
c_val, m_val, l_val = np.random.rand(3, n)

x = tf.constant(x_val)
c, m, l = tf.constant(c_val), tf.constant(m_val), tf.constant(l_val)

# Getting numpy result for comparison:
res = np.sum([c_val[i] * np.exp((x_val - m_val[i]) / l_val[i]) for i in range(n)], axis=0)
print(res)
# [[ 2.55195594  0.42834575]
#  [ 0.29125215  0.29025419]
#  [ 0.74048059  1.63411303]]

# Solution 1:
tiling = [1] * len(x.get_shape().as_list()) + [n]
res_broad = tf.reduce_sum(c * tf.exp((tf.tile(tf.expand_dims(x, axis=-1), tiling) - m) / l),
                          axis=-1)

# Solution 2:
condition = lambda i, y: i < n
operation = lambda i, y: [i+1, y + c[i] * tf.exp((x - m[i]) / l[i])]
_, res_loop = tf.while_loop(condition, operation,
                            loop_vars=[0, tf.zeros_like(x)],
                            shape_invariants=[tf.TensorShape([]), x.get_shape()])

with tf.Session() as sess:
    print(sess.run(res_broad))
# [[2.55195594  0.42834575]
#  [0.29125215  0.29025419]
#  [0.74048059 1.63411303]]
    print(sess.run(res_loop))
# [[2.55195594  0.42834575]
#  [0.29125215  0.29025419]
#  [0.74048059 1.63411303]]


text:
Q: Does a bootstrap row have to always equal 12? The reason I ask is because I am using a php function via a plugin (within WordPress) that creates rows of data...
It appears that boostrap happily loads a column of say 'col-sm-6' but my question is really one for 'standards'.
Thank you.

A: No, it doesn't have to be equal 12. As stated in the Grid System docs:

Bootstrap includes a responsive, mobile first fluid grid system that appropriately scales up to 12 columns as the device or viewport size increases

...which means in short that it can scale up to 12, but it's not required to be 12 always.
Therefore, it's ok to use only 6 columns, depending on your requirements.


text:
Q: how to not print newline at end of statement in for loop r, c = input().split()
r=int(r)
c=int(c)
list1=[]
v=1
for i in range(r):
    list2=[]
    for j in range(c):
        list2.append(v)
        v=v+1
    list1.append(list2)

for i in range(r):
    for j in range(c):
        print(list1[i][j],end=" ")
    print()

Here is an image showing the actual output and the output I
am getting:

A: The issue is that you need to skip the newline at the end of the outermost loop and the spaces at the end of each line. For a general iterator, this requires a bit of extra work, but for your simple case, just checking iand j will suffice:
for i in range(r):
    for j in range(c):
        print(list1[i][j], end=" " if j < c - 1 else "")
    if i < r - 1:
        print()

A: I had the same issue, this is what I did:
>>> help(print)
Help on built-in function print in module builtins:
print(...)

    print(value, ..., sep=' ', end='\n', file=sys.stdout, flush=False)

    Prints the values to a stream, or to sys.stdout by default.
    Optional keyword arguments:
    file:  a file-like object (stream); defaults to the current sys.stdout.
    sep:   string inserted between values, default a space.
    end:   string appended after the last value, default a newline.
    flush: whether to forcibly flush the stream.

I am very new to python, but this is my code to eliminate a new line at the end of a print statement:
for ch in message:
    print (ord(ch), end=' ')

If I wanted to eliminate the ' ' at the end of each line of my statements, since this comes from the default (sep=" "), then I would use the following:
for ch in message:
        print (ord(ch), ch, sep = '' if ch==message[-1] else ' ', end=' ', )

#Please note that message is a string.

A: You can create sublist that partition the data you need to print.
Before printing the eacht part, test if you need to print a '\n' for the previous line and print partitiones without '\n':
r, c = map(int, input().split())

# create the parts that go into each line as sublist inside partitioned
partitioned = [ list(range(i+1,i+c+1)) for i in range(0,r*c,c)]
#                       ^^^^ 1 ^^^^              ^^^^ 2 ^^^^

for i,data in enumerate(partitioned):
    if i>0: # we need to print a newline after what we printed last
        print("")

    print(*data, sep = " ", end = "") # print sublist with spaces between numbers and no \n

*

*^^^^ 1 ^^^^ creates a range of all the numbers you need to print for each partition

*^^^^ 2 ^^^^ creates the starting numbers of each "row" thats used in ^^^^ 1 ^^^^ (reduced by 1 but thats fixed in 1's range)

*enumerate(partitioned) returns position inside sequence and the data at that position - you only want to print '\n' after the first output was done.

After the last partitioned - output the for ... is finished and wont enter again - hence no \n after it.

Output for '6 3'  (\n added for claritiy reasons):
1 2 3\n
4 5 6\n
7 8 9\n
10 11 12\n
13 14 15\n
16 17 18

with partitioned being:
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15], [16, 17, 18]]


text:
Q: How to use Regex in java to find a value in a string between characters I am trying to find some rates in a table using Regular Expressions that I am reading into a string from HTML.  Here is an example:
Euro
0.772199
1.295003

I am trying to find the numbers contained in the above string.  They constantly change so it can't be a hard-coded number search.
I've tried using something similar to this:  to=EUR'>(...)
but it only returns the 0.7, not the rest.  Any help is appreciated!
EDIT:  some code was requested, so here it is
      String re2="to=EUR'>(...)";   // Float 1

    Pattern p = Pattern.compile(re2,Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
    Matcher m = p.matcher(webData);

    if (m.find())
    {
        String float1=m.group(1);
        System.out.print("("+float1.toString()+")"+"\n");
    }

A: You can use this expression for quick and dirty searches:
EUR'>([^<]*)<

This is not ideal, though: using an HTML or an XHTML parser is a much better solution, because it is much more powerful and robust than any regex-based solution.

A: To match just numbers, use positive lookarounds:
(?<=EUR'>)\\d+(?:\\.\\d*)?(?=<)
(?<=USD'>)\\d+(?:\\.\\d*)?(?=<)

A: OK, not what you asked for, but I wanted to point out that when both sides of the string you are looking for are fixed like that, you can use the substring() and indexOf() methods which can often be simpler to debug:
public class substring_not_regex {

   public static void main(String args[])
   {
      String test= "1.295003	";
      String result = getConversion(test,"to=USD'>");
      System.out.println("The result is: " + result);
      test= "0.772199	";
;     result = getConversion(test,"to=EUR'>");
      System.out.println("The result is: " + result);
   }

   static String getConversion(String tableLine,String toSearchFor)
   {
      String value = "";
      String aref_terminator = "";
      int position = tableLine.indexOf(toSearchFor);
      if ( position == -1 ) return value;
      int start_position = position + toSearchFor.length();
      int end_position = tableLine.indexOf(aref_terminator,start_position);
      if ( end_position == -1 ) return value;
      value = tableLine.substring(start_position,end_position);
      return value;
   }
}

outputs:
The result is: 1.295003
The result is: 0.772199


text:
Q: Transformar JsonObject em JsonArray Como pego o dados desse Json? Quero transformar em um JsonArray para poder percorrer, mas ele é um JsonObject...
{
  "1":{"a":"1","c":"0","d":"0","m":"0","ns":"0","proc":"0"},
  "2":{"a":"1","c":"0","d":"0","m":"0","ns":"0","proc":"0"},
  "3":{"a":"1","c":"0","d":"0","m":"0","ns":"0","proc":"0"},
  "4":{"a":"1","c":"0","d":"0","m":"0","ns":"0","proc":"0"},
  "5":{"a":"1","c":"0","d":"0","m":"0","ns":"0","proc":"0"}
}

A: Pelo que entendi, você já tem esse JSON e quer 'transformar' ele de JSONObject pra JSONArray.
Seguindo, pode ser feito da seguinte forma.
JSONObject json; // <- O seu JSONObject
JSONArray array = new JSONArray(); // JSONArray com os objetos
for(int i = 1; i <= json.lenght(); i++) {
    array.put(json.getJSONObject(""+i));
}

O seu JSONArray resultante será algo parecido com esse:
[
    {"a":1,"c":0,"d":0,"m":0,"ns":0,"proc":0},
    {"a":1,"c":0,"d":0,"m":0,"ns":0,"proc":0},
    {"a":1,"c":0,"d":0,"m":0,"ns":0,"proc":0}
]

A: Tente desta forma:
JSONObject jsonObject = new JSONObject("my json");
JSONArray jsonArray = jsonObject.getJSONArray("1");
jsonArray.getString(0);// 1

Teste com o seu json e veja se a saida vai ser 1.
Espero que ajude

A: Para transformar um JSONObject em JSONArray você terá que percorrer todas as chaves e ir adicionando os filhos no JSONArray.
Dessa forma:

{"1":{"a":1,"c":0},"2":{"a":1,"c":0},"3":{"a":1,"c":0}} // JSONObject que será tranformado

JSONObject json = new JSONObject();

json.put("1", new JSONObject() {{
    put("a", 1);
    put("c", 0);
}});
json.put("2", new JSONObject() {{
    put("a", 1);
    put("c", 0);
}});
json.put("3", new JSONObject() {{
    put("a", 1);
    put("c", 0);
}});

JSONArray jsonArray = new JSONArray();

// Percorre as chaves do JSONObject e vai adicionando os filhos no JSONArray.
for (String key : JSONObject.getNames(json)) {
    jsonArray.put(json.getJSONObject(key));
}

// Exibe o conteúdo do jsonArray
System.out.println(jsonArray);

A primeira etapa é montar o JSONObject. Como você já tem ele, não precisará fazer isso. Em seguida, declaro o JSONArray. Por fim, percorro as chaves do JSONObject adicionando os seus filhos no JSONArray.
Ao final você terá o seu JSONArray da seguinte forma:

[{"a":1,"c":0},{"a":1,"c":0},{"a":1,"c":0}]


text:
Q: How is weapon accuracy interpolated between ranges? The wiki lists the accuracy of each weapon at ranges of 4, 15, 30, and 50 tiles. It also says:

Between those ranges, accuracy stats are interpolated.

How exactly are they interpolated? Also, how accurate are weapons at below 4 tiles distance?

A: The in-game stated accuracy of the starter pistol and bolt-rifle.
Range          3  12  25  40
PistolAcc     80  75  45  35
BoltRifleAcc  65  80  90  80

When at distances less than short (3), the short range applies.  So a pistol has 80 accuracy from 0-3 range.  You can see this via the accuracy tooltip, by moving next to a squirrel and aiming.
When at distances between two numbers, the accuracy is a weighted average.  A pistol has 79 accuracy at range 4 and 78 accuracy at ranges 5 and 6.  It is likely that the number is rounded for display purposes only, and the unrounded weighted average is used in the calculation.
The wiki has been updated with these ranges and accuracies, as well as with an explanation of how accuracies are interpolated.  I believe it to be reliable at this point.


text:
Q: Using JSON with VB.NET ASP.NET 2.0 Total newby question here, I've been struggling with it for hours!
I'm trying to understand how to actually use, and create JSON data. I've been Googling all afternoon and trying to understand what I fine here http://james.newtonking.com/projects/json/help/ having downloaded the Newtonsoft DLLs.
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);

using (JsonWriter jsonWriter = new JsonTextWriter(sw))
{
jsonWriter.Formatting = Formatting.Indented;

jsonWriter.WriteStartObject();
jsonWriter.WritePropertyName("CPU");
jsonWriter.WriteValue("Intel");
jsonWriter.WritePropertyName("PSU");
jsonWriter.WriteValue("500W");
jsonWriter.WritePropertyName("Drives");
jsonWriter.WriteStartArray();
jsonWriter.WriteValue("DVD read/writer");
jsonWriter.WriteComment("(broken)");
jsonWriter.WriteValue("500 gigabyte hard drive");
jsonWriter.WriteValue("200 gigabype hard drive");
jsonWriter.WriteEnd();
jsonWriter.WriteEndObject();
}

Should create something that looks like:
{
   "CPU": "Intel",
   "PSU": "500W",
   "Drives": [
   "DVD read/writer"
    /*(broken)*/,
     "500 gigabyte hard drive",
     "200 gigabype hard drive"      ]
}

and I am sure it does... but how do I view it? How do I turn that into an object that the browser can output.
It seems to me that the first stage I need to resolve is "how to create" JSON files/strings, next stage will be how to actually use them. If it helps answer the question, what I'm aiming for initially is to be able to use AJAX Autocomplete from a search page generated from my MySQL database, I was hoping I could write a simple SQL query and have that returned using something similar to the above, but I'm clearly going about it all wrong!
BTW, the example above is in C#, I have successfully converted the process to VB, as that's what I am using, but any responses would be much appreciated as VB examples!

A: I came across this post about two years after it was posted, but I had the exact same question and noticed that the question wasn't really answered. To answer OP's question, this will get you the JSON string in his example.
sb.toString()

A: The upshot is that you need to get the JSON string back to the browser. You can either place it in a javascript variable (be sure to clean up line enders and single quotes if you do this) or pass it back as the result of an ajax query.
We actually use the built-in Javascript serializer since it has support both on the server and the client side and is quite easy to use. Assuming that you have an existing object, this code goes on the server side:
''' <summary>
''' This method safely serializes an object for JSON by removing all of the special characters (i.e. CRLFs, quotes, etc)
''' </summary>
''' <param name="oObject"></param>
''' <param name="fForScript">Set this to true when the JSON will be embedded directly in web page (as opposed to being passed through an ajax call)</param>
''' <returns></returns>
''' <remarks></remarks>
Public Function SerializeObjectForJSON(ByVal oObject As Object, Optional ByVal fForScript As Boolean = False) As String

If oObject IsNot Nothing Then
    Dim sValue As String

    sValue = (New System.Web.Script.Serialization.JavaScriptSerializer).Serialize(oObject)

    If fForScript Then
        ' If this serialized object is being placed directly on the page, then we need to ensure that its CRLFs are not interpreted literlally (i.e. as the actual JS values)
        ' If we don't do this, the script will not deserialize correctly if there are any embedded crlfs.
        sValue = sValue.Replace("\r\n", "\\r\\n")

        ' Fix quote marks
        Return CleanString(sValue)
    Else
        Return sValue
    End If
Else
    Return String.Empty
End If
End Function

On the client side, deserialization is trivial:
    // The result should be a json-serialized record
    oRecord = Sys.Serialization.JavaScriptSerializer.deserialize(result.value);

Once you have deserialized the object, you can use its properties directly in javascript:
alert('CPU = ' + oRecord.CPU);

A: In terms of generating the JSON try
    public class HardwareInfo
    {
        [JsonProperty(PropertyName = "CPU")]
        public string Cpu { get; set; }
        [JsonProperty(PropertyName = "PSU")]
        public string Psu { get; set; }
        [JsonProperty]
        public ICollection<string> Drives { get; set; }
    }

    public string SerializeHardwareInfo()
    {
        var info = new HardwareInfo
        {
            Cpu = "Intel",
            Psu = "500W",
            Drives = new List<string> { "DVD read/writer", "500 gigabyte hard drive", "200 gigabype hard drive" }
        };

        var json = JsonConvert.SerializeObject(info, Formatting.Indented);
        //  {
        //    "CPU": "Intel",
        //    "PSU": "500W",
        //    "Drives": [
        //      "DVD read/writer",
        //      "500 gigabyte hard drive",
        //      "200 gigabype hard drive"
        //    ]
        //  }
        return json;
    }

The formatting argument is optional.  Best of luck.


text:
Q: How to read in 2 timeframe data of 1 indicator in PineScript? I cannot find any document in TradingView, can any one help me out this problem:
I have Trend1 indicator from 3rd-party script, it has Buy and Sell data series:

And I wanna read Trend1 data on H1 and M15 timeframe like:
//@version=4
study("SupertrendSignal", overlay = true)

trend1_H1 = input(trend_1_result_on_H1, title="Trend1 on H1")
trend1_M15 = input(trend_1_result_on_M15, title="Trend1 on M15")

if (trend1_H1 is buy) and (trend1_M15 is buy)
then plot(1)
else plot(0)

But I cannot find any guide to do this.
My big problem is I'm new to Pinescript and:

*

*I don't know how to get data from SuperTrend custom indicator above

*I don't know how to get H1 and M15 data at the same time from indicator

*Is there anyway to debug the data better than plot it on the chart?, cause I'm familiar with the breakpoint in other languages, I don't know how to see its data structure.

A: You must use the security() function. Here is an example
//@version=4
study("Example security 1", overlay=true)
ibm_15 = security("NYSE:IBM", "15", close)
plot(ibm_15)


text:
Q: If $U$ is uniformly distributed with mean $5$ and variance $3$, what is $P(U<4)$ I'm stuck on this question, can someone help me, many thanks.
If $U$ is uniformly distributed with mean $5$ and variance $3$, what is $P(U<4)$?
update(this problem has been solved):
I made a mistake when calculating, the result should be under the condition : x ranges from a to b. The final result is 1/3.

A: Hint:- Let us suppose $U$ follows Uniform distribution with parameter $a$ and $b$.
Mean=$E(U)=\frac{b+a}{2}=5$ and Variance $=V(U)=\frac{(b-a)^2}{12}=3$.

A: As the mean is directly in the middle between $a$ and $b$ you can set

*

*$a = 5-x$ and $b=5+x$ for $x>0$
Now solve
$$\sigma^2 = \frac{(b-a)^2}{12}= \frac{(2x)^2}{12}=\frac{x^2}{3} = 3\stackrel{x>0}{\Rightarrow} x= 3$$
So, $U$ "lives" on $[a,b]=[2,8]$. It follows
$$P(U<4) = \frac{4-2}{8-2}=\frac{2}{6}=\frac{1}{3}$$


text:
Q: symbols displayed at run time but not present in code I am creating a site with html and php.
When I Run my php page on borwser using localhost(XAMPP server), then some symbols () are displayed but when I check my html-php code, then no symbol or script like: ¿ or » is found.
If i am wrong somewhere then Please let me know.

A: That's a UTF-8 byte-order marker. You should configure your editor to save UTF-8 without BOM. It isn't mandatory for the UTF-8 encoding; in fact, its use is discouraged and it only causes problems.
Additionally, make sure your web server is sending an appropriate Content-Type HTTP header:
Content-Type: text/plain; charset=utf-8

A: ¿ or » are html entities, they are looks different at php code and at browser. You can find them, for example, here. Also, you possibly have an issue with BOM

A: My best guess: You have an issue with encoding (UTF vs. ISO). Look up encoding used by your editor on saving, and send it to the browser like i.e. header("Content-type:text/html;charset=UTF-8")

A: sounds like you're dealing with a character encoding problem.
try to declare the encoding in your headers.
header("Content-Type: text/html; charset=UTF-8")

this needs to be output before any text is sent to the client.


text:
Q: Create Tabs or Hide/Unhide Content in Jekyll? Essentially what the question says - is there some way to achieve the equivalent of Angular's ng-if or just the html's visibility: hidden; and toggle it in Jekyll?

A: Please understand what Jekyll is: It is a static site generator that outputs static HTML on change (not on request, like PHP does). There is no such thing as hiding or unhiding things in Jekyll. All tabs should exists in the the HTML/DOM that Jekyll generates. Some of them can initially be hidden, but that is as far as Jekyll goes.
The actual switching between the visible elements should be done by javascript, as javascript can change the HTML/DOM after the request.
So, to answer your question: You can create/generate different tabs in Jekyll, but you should toggle them using javascript.
Does that answer your question?


text:
Q: DataGridView deleting row save my problem is that i have datagridview, and i select row i click delete button but when i refresh it is back
Private Sub btnDlt_Click(sender As Object, e As EventArgs) Handles btnDlt.Click
    For Each row As DataGridViewRow In dgwData.SelectedRows
        dgwData.Rows.Remove(row)
        SQL.DBDA.Update(SQL.DBDT)
    Next
End Sub

and my upadte is working good, it is saving everything, here is code
    Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
    If MsgBox("Nazaj si prajete uložiť tieto zmeny?", MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then
        SQL.DBDA.Update(SQL.DBDT)
        loadGrid()
        btnUpdate.Enabled = False
        If SQL.hasException() Then
            Exit Sub
        End If
    Else
        btnUpdate.Enabled = False
        loadGrid()
    End If

End Sub

A: The problem should be with your datasource, check your delete query if it work fine.


text:
Q: Ramsey Theorem Exercise Let $r_1<r_2<..<r_s$ and $k$ be positive integers. Prove that there is $n(k; r_1,r_2,...,r_s)$ with the following property. For every colorings of ${[n]}\choose{i}$ with $r_i$ colors, $i=1,...,s$, there is a subset $K\in$${[n]}\choose{k}$ such that all $i$-sets of $K$ are monochromatic.
Hello, I have been reading about Ramsey's Theorem by my self and trying to do some exercises. Although I did some of them, I am not being able to get this. That's why it would be nice if someone can help me or give to me some hints!
Thanks for your help!


text:
Q: Trim a string to get only domain name in PHP I am having a list of array of domains from which I want to get only the name of the domain so the list is something like this :
$domain_name = [
            "domain",
            "somedomain",
            "mydomain",
            "yourdomain"
        ];

And i will be using $_SERVER['HTTP_REFERER'] to catch a domain name. From which I just want to get the domain base name with any www. or .com/ .in/ .io/ .net / .org e.t.c or any tralling slash in the URL. Just want to know the basic domain name. Is there any way to do that in php?