text:
Q: AWS beanstalk display html code I developed my java web app on intelli j (java 8) and i store it on aws beanstalk and i use the tomcat preset for it. Everything is fine but it is displaying the html code on the site. It thinks it is related to the out.println("") in the servlet but I have no idea how to solve the problem.
what it is diplaying :
`<!DOCTYPE html>

<title>Raid HEI - Le Raid</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-
awesome/4.7.0/css/font-awesome.min.css">
<link rel="icon" href="images/logo.png">

`

servlet code :
@WebServlet("/index")
public class IndexServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {

}

protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");

    PrintWriter out = response.getWriter();

    out.println("<!DOCTYPE html>\n" +
            "\n" +
            "<title>Raid HEI - Le Raid</title>\n" +
            "<meta charset=\"UTF-8\">\n" +
            "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n" +
            "<link rel=\"stylesheet\" href=\"https://www.w3schools.com/w3css/4/w3.css\">\n" +
            "<link rel=\"stylesheet\" href=\"https://fonts.googleapis.com/css?family=Lato\">\n" +
            "<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\">\n" +
            "<link rel=\"icon\" href=\"images/logo.png\">\n" +
            ""+
            "\n" +
            "\n" +
            "\n" +
            "\n" +
            "
\n" +
            "    \n" +
            "
\n" +

1-what it is diplaying          2-servlet code


text:
Q: How to test if user is filtering post list in dashboard I am using the following code to enable a hierarchical exclusion filtering system in the dashboard when users access post lists and media library.
Admin posts & media are hidden to all users, while "teachers" and "students" have restrictions. Teachers may view they're own stuff and students data. students are restricted to their role-group.
The problem is that if a restricted user attempts to filter in the dashboard the post list, the action will be ignored because my filtering system will override.
There should be a way to apply my filtering system only when the users are not selecting an allowed filter. I see that the url changes on user filtering, adding some parameters but this is an unreliable system IMO.
Any idea?
//********** post & media lists filtered by user role & category ****************
function posts_for_current_role($query) {
global $students_allowed_cat;
global $teachers_allowed_cat;
global $pagenow;
    if($query->is_admin && !current_user_can('administrator')) {
        //$filtered_cat = '3,22';
        $user = wp_get_current_user();

        if( 'edit.php' == $pagenow   ){
            if ( in_array( 'teacher', (array) $user->roles ) ) {
                //The user has the "teacher" role
                $filtered_cat = $teachers_allowed_cat;
            }
            if ( in_array( 'student', (array) $user->roles ) ) {
                //The user has the "student" role
                $filtered_cat = $students_allowed_cat;
            }
            $query->set('cat',  $filtered_cat);
        }
        if( in_array( $pagenow, array( 'upload.php', 'admin-ajax.php' )  ) ){
            // hide media from admin
            $query->set('author',  '-1');
        }

    }
    return $query;
}

if( !current_user_can('administrator') ){
add_filter('pre_get_posts', 'posts_for_current_role');

A: I have found a solution, using  $query->get('cat'): when restricted users select "all categories" $query->get('cat') will return '0', so in this case I will apply filtering, otherwise my code won't run, allowing user-selected filter (in a restricted range) to be applied
/********** post & media lists filtered by user role & category ****************
function posts_for_current_role($query) {
global $students_allowed_cat;
global $teachers_allowed_cat;
global $pagenow;
    if($query->is_admin && !current_user_can('administrator')) {
        $user = wp_get_current_user();

        if( 'edit.php' == $pagenow   ){
            if ($query->get('cat') == '0'){
                if ( in_array( 'teacher', (array) $user->roles ) ) {
                    //The user has the "teacher" role
                    $filtered_cat = $teachers_allowed_cat;
                }
                if ( in_array( 'student', (array) $user->roles ) ) {
                    //The user has the "student" role
                    $filtered_cat = $students_allowed_cat;
                }
                $query->set('cat',  $filtered_cat);
            }
        }
        if( in_array( $pagenow, array( 'upload.php', 'admin-ajax.php' )  ) ){
            // hide media from admin
            $query->set('author',  '-1');
        }

    }
    return $query;
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Typescript - Kotlin-like copy function In Kotlin a data class can be copied using its auto-generated copy function.
val jack = User(name = "Jack", age = 1)
val olderJack = jack.copy(age = 2)

The copy function signature, as per documentation (Docs):
fun copy(name: String = this.name, age: Int = this.age) = User(name, age)

Can something like this be done in TypeScript?
Is this an acceptable solution, or can it be improved somehow?
export class User {
    constructor(
            public name: string,
            public age: number) {}

    copy(parameters: {
        name?: string,
        age?: number
    }): User {
        const { name, age } = parameters
        return new User(name || this.name, age || this.age)
    }
}

This could be solved even with a Partial<User>:
copy(partialUser: Partial<User>): User {
   return new User(
            partialUser.name || this.name,
            partialUser.age || this.age)
}

A: You can deconstruct the item as shown below:
class User {
    constructor(
            public name: string,
            public age: number) {}
}

const jack = new User("Jack", 1);

const newJack = { ...jack, age: 2 };

This results in the copy, except the age, which is now 2.
The ordering is important (i.e. age must follow the object deconstruction).
Extended example below:
class User {
    constructor(
        public name: string,
        public age: number) { }

    copy(user: Pick<User, 'name' | 'age'>) {
        return new User(user.name, user.age);
    }
}

const jack = new User("Jack", 1);

const newJack = jack.copy({ ...jack, age: 2 });

console.log(newJack);


text:
Q: Add extra commands to the syntax highlighting e.g. DATEPART, month, CASE I was playing with the Data Explorer, and was doing a simple query to see how many posts appeared by month.  This was my query:
select datepart(year, p.creationdate) as year,
datepart(month, p.creationdate) as month,
count(*) as postcount
from posts p
group by datepart(year, p.creationdate),
datepart(month, p.creationdate)
order by datepart(year, p.creationdate),
datepart(month, p.creationdate)

However, "datepart" and "month" aren't being recognised as keywords for syntax highlighting.  This is understandable for the main site, since it's a bit obscure, but it might be helpful to increase the number of recognised reserved words for the SEDE editor, since it only needs to handle the one language.
Having noticed this, I did a bit of extra playing.  The editor appears to not know the TSQL CASE statement, either: case when [body] like '%sql%' then 1 else 0 end highlights only the  "like '%sql%'" and the 1 and 0.
Is it possible to add these in?

A: Okay, I added a whole bunch of keywords and functions to the syntax highlighting.
If I missed any other important ones, let me know.
Oh, for day, month, and year, those are both keywords and functions in SQL -- in SSMS they show up highlighted as functions in both cases, so that's what I put them in as in SEDE.
Edit: This is now live.


text:
Q: I get the "SC OpenService Failed Access is denied" error when using an sc config command.
I am already running cmd.exe with the highest privilege. Why am I still denied access?
Other commands like sc queryex works just fine.

I have not tried using the sc config on other services yet. Didn't want to mess too much with things when I don't yet know what's going on.
I am running Windows Version 6.3.9600 (Windows 8.1)

A: The Task Scheduler is an essential system component and as such is protected
from some manipulations.
I do not understand why it is necessary to configure it for auto-start.
It should already be set this way. The fact that you are having troubles
configuring it means that it is already running.
If you are just practicing on using the sc config command, I suggest trying
it on a less important service. Verify by
opening the Services applet, right-click the service and check that not all actions
are grayed-out.
Although not recommended,
this thread
has an answer on how to disable such a service so it may be configured.
I do not recommend it, as Windows boot might malfunction.

A: "SC OpenService Failed Access is denied" error when using an sc config command.
Looking at your second screenshot, it looks like you are trying to change the configuration of a running service.
Try stopping the service first and then restarting it after you have changed the configuration.

Some options only take effect at the point when the service is started e.g. the SC config command allows the executable of a service to be changed. When the service next starts up it will run the new executable. Config changes requires the current user to have "permission to configure the service".

Source SC - Service Control - Windows CMD - SS64.com

A: Looks like Windows protects some services configuration from changes. It doesn't matter whether the service is running or not. I tried disabling Windows Store service and failed the same way:
sc config WSService start=disabled
Access is denied.

But at the same time I could do it by editing registry:
HKEY_LOCAL_MACHINE\SYSTEM\ControlSet001\Services\WSService\Start=4


text:
Q: Jupyter Notbooks not launching I'm running Python 3.8 (Anaconda) on Windows 10 and have previously not had any issues launching Jupyter Notebooks. Today that changed: When I tried to launch it from the Anaconda Navigator, it suggested that it launched it but didn't open anything in my default browser (Chrome), so nothing really happened. Also, not terminal prompt was launched. When I tried launching it from the command line, typing both jupyter notebook and jupyter-notebook it launches the notbook but only in the background (ie. it provides a link that I need to copy into my browser). I find this quite strange and am trying to understand what's going on. My hunch is that it's some kind of Windows related issue but I'd like to know what issue.
So my question is what can explain this behaviour? And assuming that this is related to some strange Windows issue, I'd be keen to find out what it is.
I replicated the exact steps I used to always launch it (which worked), so this shouldn't be anything to do with the setup.
Cheers!


text:
Q: Why local.xml always use <![CDATA[localhost]]>? I want to see what database a Magento installation was using. If i observe the file /public_html/app/etc/local.xml
Surprisingly, it shows a database that doesn't exist, even my hosting server is justhost.com it is showing  ?
How is this possible?

A: Look for the host server of the database. This will be visible between the  tags. In my example, it's localhost.
<connection>
      <host><![CDATA[localhost]]></host>
      <username><![CDATA[magento_db_user]]></username>
      <password><![CDATA[password12]></password>
      <dbname><![CDATA[magento_db]]></dbname>

A: You can find more info on this page
https://my.justhost.com/cgi/help/mojomarketplace
Please find this part:
"
Hostname: The name of the host where the database is located. If the database is on your Just Host account then it would be "localhost "
Username: The database username.
Password: The password for the database username.
Database Name: The name of the database
"
So yes " localhost " sounds about right and
I think database name is generated automatically :) there you are not aware of it :)

A: By saying it is generated automatically i mean you probably used the option to do so:
In your hosting manual it says :
"

Automatically create a new database
If using this option, the MOJO Marketplace installer will
  automatically create the database and database username for you. If
  you choose to use your own database you will need to create it first

"
I do think you should see it on phpmyadmin page.
If I was you I would contact your hosting provider and ask about this.
They should clear things out for you.
If your magento webshop is up and running
It is driven by real and not a ghost database ;) for sure.

A: You should contact your hosting provider to ask them why you do not have access to the database of your Magento store as they will be the only one who can tell you why the database doesn't exist.

A: The actual database Magento is running on can be different from the settings in local.xml for several reasons:

*

*local.xml was updated but the Config Cache was not cleared

*There is an other .xml file in app/etc/ which contains the settings. All *.xml files in that dir are loaded as config.


text:
Q: Identifying Physics Equipment We are clearing out some old cupboards at school in our science department and have come across three different sets of physics equipment with no labels or instructions. Please could people kindly identify these if possible and what they would be used for in terms of a practical and if it is therefore worth keeping them?
Just want to mention that the picture of the wooden piece of equipment laid down on the table has 3 metal cups in it as this isn't clear from the picture.
Thanks in advance.


text:
Q: Need help timing the iterations for a for loop any help you can give me would be great. I am working on a simple game in python. I would like to have a countdown timer running on the screen. Based on other questions answered on this site, I think I have the code mostly correct, the problem I am having is that I am running the timer code using a "for" loop. I am not really sure why it is not working for me at the moment, when I run the game, I do not get any errors, the countdown displays but it has only counted down one second and it sticks on this time (01:29). Any suggestions would be really appreciated. The code that I am struggling with is towards the end of the program in a section called """Timer Countdown""" in the main loop for the game (line 354). Many thanks.
# Ice Hockey Game
from livewires import games, color
from tkinter import*
import pygame
import math, random
import os
import sys
import time
pygame.init()

games.init(screen_width = 1016, screen_height = 511, fps = 50)

################################################################################
"""timer variables"""
################################################################################
clock = pygame.time.Clock()
font = pygame.font.Font(None, 25)
red      = ( 255,   0,   0)
frame_count = 0
frame_rate = 50
start_time = 90
done= False
output_string = ""

################################################################################
"""Score display variables"""
################################################################################
right_score = games.Text(value = 0, size = 25, color = color.black,
                                top = 30, right = games.screen.width - 250,
                                is_collideable = False)
games.screen.add(right_score)

left_score = games.Text(value = 0, size = 25, color = color.black,
                                top = 30, right = 250,
                                is_collideable = False)
games.screen.add(left_score)

player1_message = games.Message(value = "Player 1 Score",
                            size = 35,
                            color = color.black,
                            x = 250,
                            y = 15,
                            lifetime = 100000000,
                            is_collideable = False)

games.screen.add(player1_message)

player2_message = games.Message(value = "Player 2 Score",
                            size = 35,
                            color = color.black,
                            x = 750,
                            y = 15,
                            lifetime = 100000000,
                            is_collideable = False)

games.screen.add(player2_message)

###############################################################################
"""Player 1 and Player 2 WIN messages"""
###############################################################################

p1_won_message = games.Message(value = "Player 1 Wins!!!",
                            size = 100,
                            color = color.blue,
                            x = games.screen.width/2,
                            y = games.screen.height/2,
                            lifetime = 500,
                            after_death = games.screen.quit,
                            is_collideable = False)

p2_won_message = games.Message(value = "Player 2 Wins!!!",
                            size = 100,
                            color = color.blue,
                            x = games.screen.width/2,
                            y = games.screen.height/2,
                            lifetime = 500,
                            after_death = games.screen.quit,
                            is_collideable = False)

##############################################################################
"""Goal animation images and functions"""
################################################################################

"""Animation images"""
goal_anim_files = ["Goal_Anim_001.bmp", "Goal_Anim_002.bmp", "Goal_Anim_003.bmp",
            "Goal_Anim_004.bmp","Goal_Anim_005.bmp","Goal_Anim_006.bmp",
            "Goal_Anim_007.bmp","Goal_Anim_008.bmp","Goal_Anim_009.bmp","Goal_Anim_010.bmp", "Goal_Anim_011.bmp", "Goal_Anim_012.bmp", "Goal_Anim_013.bmp",
            "Goal_Anim_014.bmp","Goal_Anim_015.bmp","Goal_Anim_016.bmp",
            "Goal_Anim_017.bmp","Goal_Anim_018.bmp","Goal_Anim_019.bmp","Goal_Anim_020.bmp", "Goal_Anim_021.bmp","Goal_Anim_022.bmp", "Goal_Anim_023.bmp",
            "Goal_Anim_024.bmp","Goal_Anim_025.bmp"]

def goal_msg_left(self):
    global goal_anim_left
    goal_anim_left = games.Animation(images = goal_anim_files, x = 250,
                    y= games.screen.height/2, n_repeats = 1,
                    repeat_interval = 1, is_collideable = False)

    #print("inside goal_msg_left")

def goal_msg_right(self):
    global goal_anim_right
    goal_anim_right = games.Animation(images = goal_anim_files, x = 750,
                    y= games.screen.height/2, n_repeats = 1,
                    repeat_interval = 1, is_collideable = False)

    #print("inside goal_msg_right")

class Leftgoalanim(games.Animation):
    """goal animation"""

    def update(self):
        self.check_collide()

    def check_collide(self):
        for player1 in self.overlapping_sprites:
            player1.handle_player_collide()
        for player2 in self.overlapping_sprites:
            player2.handle_player_collide()

class Leftgoal(games.Sprite):

    def update(self):
        self.check_collide()
        self.check_goal()
    def check_collide(self):
        """ Check for collision with puck. """
        for puck in self.overlapping_sprites:
            puck.handle_collide()

    def handle_collide(self):
        """ Move to a random screen location. """
        self.dx = -self.dx
        self.dy = 0
        self.x = games.screen.width/2
        self.y = games.screen.height/2

    def check_goal(self):
        """ Check if left goal. """

        global goal_anim_left
        for puck in self.overlapping_sprites:

            #puck.handle_collide()
            goal_msg_left(self)
            games.screen.add(goal_anim_left)
            right_score.value += 1
            if right_score.value >= 10:
                games.screen.add(p2_won_message)

class Rightgoal(games.Sprite):
    def update(self):
        self.check_collide()
        self.check_goal()
    def check_collide(self):
        """ Check for collision with puck. """
        for puck in self.overlapping_sprites:
            puck.handle_collide()

    def handle_collide(self):
        """ Move to a random screen location. """
        self.dx = -self.dx
        self.dy = 0
        self.x = games.screen.width/2
        self.y = games.screen.height/2

    def check_goal(self):
        """ Check if left goal. """
        for puck in self.overlapping_sprites:

            #puck.handle_collide()
            goal_msg_right(self)
            games.screen.add(goal_anim_right)
            left_score.value += 1
            if left_score.value >= 10:
                games.screen.add(p1_won_message)

################################################################################
"""Classes for Players sprites"""
################################################################################

class Player1(games.Sprite):
    """move the player 1"""
    VELOCITY_STEP = .03
    VELOCITY_MAX = 3

    def update(self):
        if games.keyboard.is_pressed(games.K_w):
            self.y -= 3
        if games.keyboard.is_pressed(games.K_s):
            self.y += 3
        if games.keyboard.is_pressed(games.K_a):
            self.x -= 3
        if games.keyboard.is_pressed(games.K_d):
            self.x += 3

        if self.right > 940:
            self.x = 913
        if self.left < 85:
            self.x = 108

        if self.bottom > games.screen.height:
            self.y = 475
        if self.top < 0:
            self.y = 50

        self.check_collide()

    def check_collide(self):
        """ Check for collision with puck. """
        for puck in self.overlapping_sprites:
            puck.handle_collide()

    def handle_player_collide(self):
        self.dx = -self.dx
        self.dy = 0

    def handle_collide(self):
        """ Move to a random screen location. """
        self.dx = -self.dx
        self.dy = 0

class Player2(games.Sprite):
    """move the player 2"""
    VELOCITY_STEP = .03
    VELOCITY_MAX = 3
    def update(self):

        if games.keyboard.is_pressed(games.K_UP):
            self.y -= 3
        if games.keyboard.is_pressed(games.K_DOWN):
            self.y += 3
        if games.keyboard.is_pressed(games.K_LEFT):
            self.x -= 3
        if games.keyboard.is_pressed(games.K_RIGHT):
            self.x += 3

        if self.right > 940:
            self.x = 913
        if self.left < 85:
            self.x = 108

        if self.bottom > games.screen.height:
            self.y = 475
        if self.top < 0:
            self.y = 50

        self.check_collide()

    def check_collide(self):
        """ Check for collision with puck. """
        for puck in self.overlapping_sprites:
            puck.handle_collide()

    def handle_collide(self):
        """ Move to a random screen location. """
        self.dx = -self.dx
        self.dy = 0

    def handle_player_collide(self):
        self.dx = -self.dx
        self.dy = 0

################################################################################
"""Class for Puck"""
################################################################################

class Puck(games.Sprite):
    """ A bouncing puck. """

    def update(self):
        """ Reverse a velocity component if edge of screen reached. """
        if self.right > games.screen.width or self.left < 0:
            self.dx = -self.dx

        if self.bottom > games.screen.height or self.top < 0:
            self.dy = -self.dy

    def handle_collide(self):
        """ reverses x direction when collides. """
        self.dx = -self.dx
        self.dy = self.dy

    def handle_goal(self):
        """what happens to the puck when goal"""
        self.dx = -self.dx
        self.dy = self.dy

################################################################################

"""Main Loop For Game"""

################################################################################

def main():
    wall_image = games.load_image("Table_002_1016H_511W.jpg", transparent = False)
    games.screen.background = wall_image

    #########image left and right goal images and add them to game##########
    left_goal_image = games.load_image("Goal_left_cropped.bmp")
    the_left_goal = Leftgoal(image = left_goal_image,
                             x = 40,
                             y = games.screen.height/2,
                             )

    right_goal_image = games.load_image("Goal_right_cropped.bmp")
    the_right_goal = Rightgoal(image = right_goal_image,
                             x = 976,
                             y = games.screen.height/2,
                             )

    #########player 1 import image and add to game##########################
    player1_image = games.load_image("Player_red_half_50_75_Fixed.bmp")
    the_player1 = Player1(image = player1_image,
                      x = games.screen.width/4,
                      y = games.screen.height/2)
    games.screen.add(the_player1)

    #########player 2 import image and add to game##########################
    player2_image = games.load_image("Player_green_half_50_75_flipped_fixed.bmp")
    the_player2 = Player2(image = player2_image,
                      x = 750,
                      y = games.screen.height/2)

    games.screen.add(the_player2)

    ################Import image for the Puck and Add to the game###########
    puck_image = games.load_image("puck_small.png", transparent = True)
    the_puck = Puck(image = puck_image,
                      x = games.screen.width/2,
                      y = games.screen.height/2,
                      dx = -3,
                      dy = 3)
    counter = 0

###########################################################################
    """TIMER COUNTDOWN"""
###########################################################################
    clock = pygame.time.Clock()
    font = pygame.font.Font(None, 25)
    red      = ( 255,   0,   0)
    frame_count = 0
    frame_rate = 50
    start_time = 90
    done= False
    output_string = ""
    for n in reversed(range(0, start_time)):
        total_seconds = frame_count // frame_rate

        minutes = total_seconds // 60

        seconds = total_seconds % 60

        output_string = "Time: {0:02}:{1:02}".format(minutes, seconds)
        # Blit to the screen
        text = font.render(output_string, True, red)
        #screen.blit(text, [250, 250])

        # --- Timer going down ---
        # --- Timer going up ---
        # Calculate total seconds
        total_seconds = start_time - (frame_count // frame_rate)
        if total_seconds < 0:
            total_seconds = 0

        # Divide by 60 to get total minutes
        minutes = total_seconds // 60

        # Use modulus (remainder) to get seconds
        seconds = total_seconds % 60

        # Use python string formatting to format in leading zeros
        output_string = "Time left: {0:02}:{1:02}".format(minutes, seconds)

        # Blit to the screen
        text = font.render(output_string, True, red)

        #screen.blit(text, [250, 280])

        # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT
        frame_count += 1
        # Limit to 20 frames per second
        clock.tick_busy_loop(50)

        # Go ahead and update the screen with what we've drawn.
        pygame.display.flip()

    ###Timer Display###

    timer_text = games.Message(value = "TIME",
                                size = 45,
                                color = color.red,
                                top = 30, right = games.screen.width/2,
                                lifetime = 100000000,
                                is_collideable = False)
    timer_countdown = games.Text(value = output_string, size = 25, color = color.red,
                                    top = 60, right = 600,
                                    is_collideable = False)

    games.screen.add(timer_countdown)
    games.screen.add(timer_text)
    games.screen.add(the_left_goal)
    games.screen.add(the_right_goal)
    games.screen.add(the_puck)
    games.screen.event_grab = True
    games.mouse.is_visible = False
    games.screen.mainloop()

# start the game
main()

A: Using pygame.time.get_ticks() to store a start time,
calling this again every frame will give a time greater than your stored start time, simply subtract your start time from this to get the interval in milliseconds since the timer started
As @jonrsharpe said however, it should be a code "sample", not the whole sodding thing, As such I might not have actually answered your question, I can't tell because I'm not going to read and understand the whole code.


text:
Q: How to refresh page in the SE Android app? I can not figure out how to refresh a page in my SE Android app, v1.0.89. I have Android version 7.0 on a OnePlus 3 smartphone.
Researching this, I found many SE questions and answers talking about "pull to refresh". As I understand it, that means putting your finger on the app title bar, sliding down slightly, and releasing. When I do that, nothing happens.  The title bar does not even move. Do I misunderstand how to use "pull to refresh"? If so, how do I do it properly?  If not, what is the proper refresh method?
A related issue, which led to this one, was the vague permanency of a page update after editing a post. I made a slight edit to an answer of mine, using my smartphone. After submitting it, the change was there. I happened to flip my phone sidewise, which forced a reformat. In the reformatted text, the change was absent. I flipped the phone back upright, and the change was still gone. Since I could not figure out how to do an actual page refresh, I quit the app and restarted it. Going back to the page, I saw that my edit had indeed been made permanent. I wouldn't classify this as a "bug" -- the confused buffers are more of an inconvenience, really. So long as I was posting anyway, it seems worth mentioning.

A: Actually, anywhere but the app title bar would work.
The steps are:

*

*Put your finger anywhere on the screen, below the app title bar. (personally prefer on the post body, you can also do it with the question title.)

*Pull the finger down. Speed doesn't matter, it can be slow and it can be fast.

*A blue-ish circle will appear, with an arrow forming as you pull down.

*Pull until the arrow is fully blue and release. (if you release before that, it won't do anything.)

*Question will refresh.

Also found a demo on YouTube, though with different design.


text:
Q: mongodb $in operator in $expr doesn't use the index I need documents by several identifiers
It doesn't work(freeze):
db.collection.aggregate([{
    $match: {
        $expr: {
            $in: ['$_id', [4, 6]]
        }
    }
}]);

but it works:
db.collection.find({
    _id: {
        $in: [4, 6]
    }
});

A: $expr has limitation on index use
see this

only $eq, $lt, $lte, $gt, and $gte aggregate operators can use index

In the past even less operators were supported, MongoDB 5.0 added more and probably next versions will add even more.
$in aggregate operator cannot use the index.
But if you replace it with
aggregate(
[{"$match":
  {"$expr":{"$or":[{"$eq":[4, "$_id"]}, {"$eq":[6, "$_id"]}]}}}])

It will be fast, and index will be used.
Here you can avoid the need for $expr you can use the $in query operator not the $in aggregate operator, as noted in the comments also.
{ $match: { _id: {$in: [4, 6]} }


text:
Q: Replace image with different image/button - javascript within a function, I'm trying to replace a image/button with another image/button.

But I have the problem that there is two of the same button, (button 2) when it is replaced! (one at the top of the page, and one where it is meant to be). I was wondering if there is a way of getting rid of the extra button at the top, or creating the button element within the javascript function?
Thanks for any help.

A: You can remove an element in javascript using
var el = document.getElementById('id');
var remElement = (el.parentNode).removeChild(el);

A: I'd suggest something akin to the following:
function swapImageSrc(elem, nextElemId) {
    if (!elem) {
        return false;
    }
    if (!nextElemId || !document.getElementById(nextElemId)) {
        var id = elem.id.replace(/\d+/, ''),
            nextNum = parseInt(elem.id.match(/\d+/), 10) + 1,
            next = document.getElementById(id + nextNum).src;
    }
    else {
        var next = document.getElementById(nextElemId).src;
    }

    elem.src = next;
}

var images = document.getElementsByTagName('img');

for (var i = 0, len = images.length; i < len; i++) {
    images[i].onclick = function() {
        swapImageSrc(this,imgButton2);
    };
}

JS Fiddle demo.

Edited to add that, while it is possible to switch the src attribute of an image it seems needless, since both images are present in the DOM. The alternative approach is to simply hide the clicked image and show the next:
function swapImageSrc(elem, nextElemId) {
    if (!elem) {
        return false;
    }
    if (!nextElemId || !document.getElementById(nextElemId)) {
        var id = elem.id.replace(/\d+/, ''),
            nextNum = parseInt(elem.id.match(/\d+/), 10) + 1,
            next = document.getElementById(id + nextNum);
    }
    else {
        var next = document.getElementById(nextElemId);
    }
    if (!next){
        return false;
    }
    elem.style.display = 'none';
    next.style.display = 'inline-block';
}

var images = document.getElementsByTagName('img');

for (var i = 0, len = images.length; i < len; i++) {
    images[i].onclick = function() {
        swapImageSrc(this,imgButton2);
    };
}

JS Fiddle demo.

Edited to offer an alternate approach, which moves the next element to the same location as the clicked image element:
function swapImageSrc(elem, nextElemId) {
    if (!elem) {
        return false;
    }
    if (!nextElemId || !document.getElementById(nextElemId)) {
        var id = elem.id.replace(/\d+/, ''),
            nextNum = parseInt(elem.id.match(/\d+/), 10) + 1,
            next = document.getElementById(id + nextNum);
    }
    else {
        var next = document.getElementById(nextElemId);
    }
    if (!next){
        return false;
    }
    elem.parentNode.insertBefore(next,elem.nextSibling);
    elem.style.display = 'none';
    next.style.display = 'inline-block';
}

var images = document.getElementsByTagName('img');

for (var i = 0, len = images.length; i < len; i++) {
    images[i].onclick = function() {
        swapImageSrc(this,imgButton2);
    };
}

JS Fiddle demo.

A: You can hide the first button, not only change the image source. The code below shows one way of doing that.


text:
Q: What are TypeErrors? One of them appeared in my code Why is this error coming? It is a TypeError. And also, what are TypeErrors anyways?
All the code needed:
from collections import namedtuple
account = namedtuple('person', 'password')

acc1 = account('example', 'passwordex1')

And here is the error:
Traceback (most recent call last):
  File "C:\Users\user\Desktop\Python\Secret.py", line 4, in <module>
    acc1 = account('example', 'passwordex1')
TypeError: __new__() takes 2 positional arguments but 3 were given

A: namedtuple('person', 'password') creates a type person with one field (password). You want this instead:
account = namedtuple('account', ('person', 'password'))


text:
Q: How to access an element of a model after a join in Django? My post is similar to this one except I can't access an item : Stackoverflow : How to make an Inner Join in django?
I want to display in an Html the locomotive number and the name of the customer who owns this locomotive. But they are in different tables.
Here is my models.py
class Client(models.Model):
    client_name = models.CharField(max_length=100, null=False, unique=True)

    def __str__(self):
        return self.client_name

class Locomotive(models.Model):
    locomotive_number_id = models.CharField(max_length=50, null=False, unique=True)
    locomotive_asset_id = models.CharField(max_length=50, null=False, unique=True)
    locomotive_client = models.ForeignKey(Client, null=False, on_delete=models.CASCADE)

    def __str__(self):
        return self.locomotive_number_id

Here is my views.py
def settings(request):

    my_clients = Client.objects.values_list('client_name', flat=True)
    my_locomotives = Locomotive.objects.select_related('locomotive_client')
    return render(request, 'home/settings.html', context={"my_clients": my_clients,"my_locomotives": my_locomotives})

if I print my_locomotives.query I get this :
print(str(my_locomotives.query))

SELECT
 "foo_bar_locomotive"."id",
 "foo_bar_locomotive"."locomotive_number_id",
 "foo_bar_locomotive"."locomotive_asset_id",
 "foo_bar_locomotive"."locomotive_client_id",
 "something1_something2_client"."id",
 "something1_something2_client"."client_name"
FROM "foo_bar_locomotive"
 INNER JOIN "something1_something2_client" ON ("foo_bar_locomotive"."locomotive_client_id" = "something1_something2_client"."id")

Here is the html code that allows me to display the list of locomotives. Except that I can't display the name of the customer who owns the locomotive.
{% for elements in my_locomotives %}
    <option value="{{elements}}">{{elements}} - {{elements.client_name}}</option>
{% endfor %}

How can I do to display this:
Locomotive N° 550XXXYYY - CUSTXXXYYY

A: If I understood correctly what you wanted to achieve, then you just have to do elements.locomotive_client.client_name in your template to get your client name. You'd then have something like that :
{% for elements in my_locomotives %}
    <option value="{{elements}}">Locomotive N°{{elements.locomotive_number_id}} - {{elements.locomotive_client.client_name}}</option>
{% endfor %}


text:
Q: HMACSHA1 SSL issue I have the following code which creates a hash from a password and then compares it with a stored hashed password in the db. All works fine over http. This for an asp.net webforms application running under c# 4.0
HMACSHA1 hash = new HMACSHA1();
hash.Key = Encoding.Unicode.GetBytes(password);
encodedPassword = Convert.ToBase64String(hash.ComputeHash(Encoding.Unicode.GetBytes(password)));

However when running over https/ssl the encoded password is different and therefore the user cannot login.
Does the .net framework do something different when computing hash when going over SSL?
If I step through the code and copy the encoded password and update my db then over SSL I can login.
Any ideas?
Many thanks

A: Please try setting Globalization settings as defined in MSDN article at http://msdn.microsoft.com/en-CA/library/39d1w2xf%28v=vs.100%29.aspx
This will ensure that the hash.key is uniform across your application which in turn, will ensure that the computed hash is identical every time it is computed with a key.


text:
Q: Radio Button inside radion group doesn't remains selected in Android I have three radio buttons inside one radio group. I had basically made all radio buttons unselected by removing set selected line from xml file. Now when user selects any button it only works for one time, when again it goes to radio button selection window it had lost all before selection state. I had tried so many statements but hadn't got succeed. Means I want when user checks any button it will be always remain selected until user doesn't check any other button. Please help me. Below is my code.
SelectedLanguage.java:
public class SelectLanguage extends ActionBarActivity {
    public static String lang;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.select_language);

        RadioGroup group = (RadioGroup) findViewById(R.id.radioGroup1);
        RadioButton gujarati = (RadioButton) findViewById(R.id.radio0);
        RadioButton hindi = (RadioButton) findViewById(R.id.radio1);
        RadioButton english = (RadioButton) findViewById(R.id.radio2);

        //int radio_selected = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE).getInt("my_selected_radio",0);
        //int radio_selected = getSharedPreferences("your_prefs", Activity.MODE_PRIVATE).edit().putInt("my_selected_radio",selectedValue).commit();

        group.setOnCheckedChangeListener(new OnCheckedChangeListener(){

            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // TODO Auto-generated method stub
                if(checkedId == R.id.radio0) {
                    lang = "Gujarati";

                } else if(checkedId == R.id.radio1) {
                    lang = "Hindi";

                } else {
                    lang = "English";

                }

            }

        });

    }

select_language.xml:
<RadioGroup
        android:id="@+id/radioGroup1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="25dp" >

        <RadioButton
            android:id="@+id/radio0"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="RadioButton" />

        <RadioButton
            android:id="@+id/radio1"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="RadioButton" />

        <RadioButton
            android:id="@+id/radio2"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="RadioButton" />
    </RadioGroup>

A: This is complete answer for your need, I had tried this and this is working perfect. This code stores the value of selected checkbox in sharedpreferances and when required it returns the stored value.
group.setOnCheckedChangeListener(new OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        // TODO Auto-generated method stub
        pref = getApplicationContext().getSharedPreferences("MyPref", 0);
        Editor editor1 = pref.edit();
        editor1.remove("key_name");
        if (checkedId == R.id.radio0) {
            lang = "Gujarati";
            pref = getApplicationContext().getSharedPreferences("MyPref", 0);
            Editor editor = pref.edit();
            editor.putString("key_name", lang);
            editor.commit();
            // chk = pref.getString("key_name", null);
            txtV.setText(lang);

        } else if (checkedId == R.id.radio1) {
            lang = "Hindi";
            pref = getApplicationContext().getSharedPreferences("MyPref", 0);
            Editor editor = pref.edit();
            editor.putString("key_name", lang);
            editor.commit();
            // chk = pref.getString("key_name", null);
            txtV.setText(lang);
        } else if (checkedId == R.id.radio2) {
            lang = "English";
            pref = getApplicationContext().getSharedPreferences("MyPref", 0);
            Editor editor = pref.edit();
            editor.putString("key_name", lang);
            editor.commit();
            // chk = pref.getString("key_name", null);
            txtV.setText(lang);

        }
    }

});

pref = getApplicationContext().getSharedPreferences("MyPref", 0);
chk = pref.getString("key_name", null);
System.err.println("Get value is=====" + chk);
if (chk != null) {
    if (chk.equals("Gujarati")) {
        gujarati.setChecked(true);
    }
    if (chk.equals("Hindi")) {
        hindi.setChecked(true);
    }
    if (chk.equals("English")) {
        english.setChecked(true);
    }
}

A: Can you please describe the actual flow? Does it involve the user selecting the radio button, the screen is closed, and then the user goes back to the same screen and you want to display the previsouly-selected radio button as selected?
If that's the case, I believe you need to specifically set the checked/selected radio button with something like:
    ((RadioButton)radioGroup.getChildAt(INDEX)).setChecked(true);


text:
Q: Odeint function by scipy.integrate does not follow the given time vector when solving the system I am trying to solve a ODE matrix system in which one of the terms change with time. To change it to the accurate value, the code should search within the predefined time vector to find at what instant it is, and use the same index (named control on the code) to set the values in the matrix, as shown below:
from scipy.integrate import odeint as ode

#(Here, I cut some of the non-relevant to the issue objects, that I can guarantee that are correct)

def susp(x,TT):
    dxdt=[]
    control=0
    dxdtlong=np.zeros((1,4),float)

    for i in range(time_size):
        ttt=t[i]
        if TT!=ttt:
            control+=1
        else:
            break

    W[0,0]=zr[control]
    W[1,0]=zrp[control]

    matriz1=np.matrix(np.dot(A,x))
    matriz2=np.matrix(np.dot(H,W))

    for j in range(len(matriz1)):
        for k in range(len(matriz1[0])):
            dxdtlong=matriz1[k][j]+matriz2[k][j]

    dxdt.append(dxdtlong[0,0])
    dxdt.append(dxdtlong[0,1])
    dxdt.append(dxdtlong[0,2])
    dxdt.append(dxdtlong[0,3])

    data=np.reshape(dxdt,np.size(dxdt))
    return data

x=ode(susp, x0_reshaped, t, full_output=1)

t is a equally spaced time vector, created with linspace.
Oddly, when running this code, the second time point called by ODE isn't t[1], but a value that isn't even in my time vector.
Can someone please explain to me what I am doing wrong?


text:
Q: CSS
* issue with jquery and quicksand I have a page with jquery and quicksand plugin that works fine if I have the same size images.
If I have add an different size image it does not show up correctly.
Page: -removed-
I presume it has something to do with the CSS and I cannot see what the issue might be.
Size test-1 looks fine but Size test-2/3 have the issue that the smaller images do not start to populate the page at the left side. It should use the empty space left of the big image as well.
Anyone knows the solution?

A: Have you tried removing adjustHeight: 'dynamic'?
This is probably what is causing it.
When I click on Test2 I get a big image showing up, the file name is 010.png.
But when I inspect the page before clicking on Test2, 010.png isn't there at all.
** EDIT
I see, it uses ajax to pull other pages.
I don't see anything wrong actually. It is working how it should...

A: Everything is working correctly; that's how floats work. You could give jquery.masonry a try though. Add the script to your site, and call masonry on .wmshowcase
$('.wmshowcase').masonry({
  itemSelector: 'li'
});

I have to say I haven't tested it :P


text:
Q: I am trying to test login scenario of android application and verify toast messages Application Screen ShotI am testing login scenario of an android app.
I have 7 different  Test cases
I have written code for that but it is giving error
Please check my code and error and let me know, where i am going wrong.
I have tried this code only
    package TestCases.Project_Entry;

    import java.io.IOException;
    import java.net.MalformedURLException;

    import org.openqa.selenium.By;
    import org.openqa.selenium.remote.RemoteWebDriver;
    import org.testng.Assert;
    import org.testng.annotations.*;

    import PageObject.loginObjects;
    import io.appium.java_client.MobileElement;
    import io.appium.java_client.android.AndroidDriver;
    import io.appium.java_client.android.AndroidElement;

    public class loginTestCases extends launch {

         @BeforeTest
    public void openapp() throws MalformedURLException {
        capabilities();
    }

    @Test
    public void CodeAndPasswordBlank() {

        loginObjects log = new loginObjects(driver);
        log.Login.click();
        String ToastMessage1 = driver.findElement(By.xpath("//android.widget.Toast")).getAttribute("name");
        System.out.println(ToastMessage1);
        Assert.assertEquals(ToastMessage1, "can't be blank!");
    }

    @Test
    public void CodeBlankPasswordCorrect() {
        loginObjects log = new loginObjects(driver);
        log.Password.sendKeys("111111");
        log.Login.click();
        String ToastMessage2 = driver.findElement(By.xpath("//android.widget.Toast")).getAttribute("name");
        System.out.println(ToastMessage2);
        Assert.assertEquals(ToastMessage2, "can't be blank!");

    }

    @Test
    public void CodeCorrectPasswordBlank() {
        loginObjects log = new loginObjects(driver);
        log.Code.sendKeys("111111");
        log.Login.click();
        String ToastMessage3 = driver.findElement(By.xpath("//android.widget.Toast")).getAttribute("name");
        System.out.println(ToastMessage3);
        Assert.assertEquals(ToastMessage3, "can't be blank!");
    }

    @Test
    public void CodeIncorrectPasswordCorrect() {
        loginObjects log = new loginObjects(driver);
        log.Code.sendKeys("111112");
        log.Password.sendKeys("111111");
        log.Login.click();
        String ToastMessage4 = driver.findElement(By.xpath("//android.widget.Toast")).getAttribute("name");
        System.out.println(ToastMessage4);
        Assert.assertEquals(ToastMessage4, "Invalid login!");
    }

    @Test
    public void CodeCorrectPasswordInorrect() {
        loginObjects log = new loginObjects(driver);
        log.Code.sendKeys("111111");
        log.Password.sendKeys("123456");
        log.Login.click();
        String ToastMessage5 = driver.findElement(By.xpath("//android.widget.Toast")).getAttribute("name");
        System.out.println(ToastMessage5);
        Assert.assertEquals(ToastMessage5, "Invalid login!");
    }

    @Test
    public void CodeInCorrectPasswordInorrect() {
        loginObjects log = new loginObjects(driver);
        log.Code.sendKeys("111211");
        log.Password.sendKeys("123456");
        log.Login.click();
        String ToastMessage6 = driver.findElement(By.xpath("//android.widget.Toast")).getAttribute("name");
        System.out.println(ToastMessage6);
        Assert.assertEquals(ToastMessage6, "Invalid login!");
    }

    @Test
    public void CodeCorrectPasswordCorrect() {
        loginObjects log = new loginObjects(driver);
        log.Code.sendKeys("111111");
        log.Password.sendKeys("111111");
        log.Login.click();
        AndroidElement SelectGroup = driver.findElement(By.id("android:id/alertTitle"));
        SelectGroup.isDisplayed();
    }

}

Only these two getting passed.
PASSED: CodeAndPasswordBlank
PASSED: CodeBlankPasswordCorrect

A: I think touching the Input field to pop-up the keyboard is missed here.
Before entering numbers you should call the keyboard by click() on Input field.
So please check this and upload a screenshot from there to better helping

A: Actually i got the issue.
before every test i need to check if code and password field already has something, than i need to check this and clear it and then move further.
Please let me know how can we check this before every test.


text:
Q: services in android can anybody give example with service in android?
Thanks

A: In Android you basically have 2 kinds of services.

*

*Local Service

*Remote Service

If you run local service then your application as well as your service will run on same ProcessID
If you run a remote service it runs as a different process you can communicate with your service using Android Interface Definition Language(AIDL)
You can find sample codes in API Demo which comes along with Android SDK as well as here
http://marakana.com/forums/android/examples/60.html
http://developer.android.com/intl/de/guide/developing/tools/aidl.html#implementing


text:
Q: How do i make a string of only one backslash? For example s = "\" I am working on a project and to make a new path I needed backslash as a string.
So far I've tried S = "\", but it didn't work.
This code snippet might help you to understand the situation.
dir_num = "1566510932"
reduced_base_directory = phosphogly_ws_len_path + r"\" + dir_num + r".result" + r"\" + dir_num + r".fas."

A: You can give it an extra slash:
S="\\"


text:
Q: Is it difference between 0 and -0 in c++ I want to create a cycled linked list and I need to find max and min values in it, so I need some checkpoint to stop, and I want to do that with -0 in first element(it will be just a checkpoint not anything else).
I don't want to use any else value because user can input new data into the list, if user inputs -0 I will simply replace it on 0 because from math side it is no difference between them (I don't use eternally-small digits :) ).
I use integer values.
question is not profitable now.
I try it and the result is they are same:
#include <iostream>

using namespace std;

int main() {
    if(0 != -0){
        cout << "they are different!";
    }else{
        cout << "they are same";
    }

    return 0;
}

Thanks to all.

A: As in maths 0 and -0 are the same value. You can not differentiate them in any way and so you can use this condition as you describe it.

A: Integer values in the nearly universal twos-complement system can't be negative zero - there's no representation for them. Negative zero simply doesn't exist.
Negative zero is possible with IEEE floating point numbers, but don't come about very often. Multiplying a negative number by 0.0 will do it.
I'd suggest finding another sentinel value.

A: This would require you store ints as doubles, mind. But you could do something like this.
signbit probably does the trick. If not, try taking the reciprocal. 1/+0.0 = +inf, 1/-0.0 = -inf. As a last ditch effort, do something like:
double d=-0.0;
bool is_neg = (*(uint64_t*)&d)&0x8000000000000000;

A: Use NaN as a checkpoint:
#include <iostream>
#include <limits>
struct cll {
  double value;
  cll * next;
};
int main() {
  int N = 5;
  double input[] = {1,2,3,4,5};
  cll * first = new cll;
  first->value = std::numeric_limits<double>::quiet_NaN();
  cll * next = first;
  for (int i = 0; i < N; ++i) {
    cll * last = new cll;
    next->next = last;
    last->value = input[i];
    last->next = first;
    next = last;
  }
  next = next->next;
  next = next->next;
  while (next->value == next->value)  {
    next = next->next;
  }
  next = next->next;
  while (next->value == next->value) {
    std::cout << next->value << '\n';
    next = next->next;
  }
  return 0;
}


text:
Q: How to convert a string to a series of integers? Making an RPG and want the currency to be represented in platinum, gold, silver and copper.  Unfortunately, my professor wants the currency stored as a string (i.e. string class, not cStrings).  For example -- 0.1.23.15 would be 0 platinum, 1 gold, 23 silver and 15 copper.
I would just like to know the big idea of how to implement this.  For example -- could I use strtok (i.e. I believe this only works on cStrings) or some other C++ function to accomplish this?

A: Here's one solution:
#include <iostream>
#include <sstream>
#include <vector>

using namespace std;

int main()
{
    string str="0.1.23.15",temp;
    stringstream s(str);
    vector<int> v;

    while(getline(s,temp,'.'))
    {
        v.push_back(stoi(temp));
    }

    for(int i: v) cout << i << endl;//C++11 style
    //for(int i=0; i<v.size(); i++) cout << v[i] << endl; //Old school :D
    system("pause");
    return 0;
}


text:
Q: How can I mount an ISO Image in Windows 7 WinPE? I have a 16GB USB flash drive that I want to set up like this:

*

*It boots WinPE

*It has useful diagnostic and system maintenance tools

*There are several .ISO files of operating system install DVDs on the flash drive

*I can mount one of the .ISO files and start an OS install.
Perhaps there's a way I can use Virtual CloneDrive within WinPE?

A: Maybe you can try ImDisk. I've used this to install Windows 7 from a USB disk where Windows wouldn't install if it did not see its files on a DVD. I used the steps here to install the driver from the command line.

A: If all you need to do is install the OS you could use Diskpart to partition the drive, ImageX to copy a custom .wim file to the partition and BCDboot to copy boot information to the system partition.
Check this out for more info.

A: Personally, I use GRUB4DOS to do things like this.  It's a boot loader capable of booting from ISO images, floppy images or partitions located on any media (USB, CDROM/DVDROM etc.).  I personally have a USB stick with WinPE/ImageX, a huge collection of diagnostics and install media for Win7 and a few linux distros.


text:
Q: Как скопировать из vim в буфер X сервера? B терминале Tilda запущен сеанс tmux с vim. Нужно копипастить фрагменты через буфер обмена x сервера.
Средствами редактора (чтобы не захватывалась нумерация строк и соседние тайлы tmux) я делаю это так:
:'<,'>!xclip -sel clip

— скопировать выделение в буфер обмера X сервера. (требуется xclip)
Правда после этого надо жать u, потому, что идёт не копирование а вырезание, почему-то.
Как сделать именно копирование?

A: такая конструкция:
:<диапазон>!<команда оболочки>

использует команду оболочки как фильтр — передаёт ей (на stdin) указанный диапазон строк, и всё, что команда запишет в свой stdout, используется как замена для указанного дипазона строк.
чтобы замены не происходило, можно воспользоваться командой :write (пробел после команды обязателен, иначе ошибку получите):
:<диапазон>write !<команда оболочки>

имя данной команды для удобства можно сократить до одной буквы (w).
в вашем примере:
:'<,'>w !xclip -sel clip

доп. чтение: :h :w_c

A: Посмотрел свои файлы и нашел только следующее:
tmux.conf
set -g set-clipboard on
bind -T copy-mode-vi Enter send-keys -X copy-pipe-and-cancel "xclip -i -f -selection primary | xclip -i -selection clipboard"

init.vim
set clipboard+=unnamedplus

Работаю в neovim.
Если выделяю фрагмент мышкой то для копирования просто нажимаю Enter.
Если в редакторе выделяю с помощью v (режим VISUAL), то прост нажимаю y.
В обоих случаях нужный фрагмент копируется в буфер обмена.
OS Fedora.


text: Q: Can a SATA 2.5" disk with a smart error work as removable disk? I have a hard disk that reports a smart error when I try to use it as the installation disk for w10, but when i plug it as an external device it seems to work fine. Can I use it as removable disk ?


text:
Q: propel-gen insert-sql without losing data? Is it possible to make
propel-gen insert-sql
without losing previous data? Is there any hack for this?
I usually just add or remove some rows in a table editing schema.xml, executing:
propel-gen
propel-gen sql
propel-gen insert-sql

and this wipes out all the data, which is annoying!

A: For this to work, Propel should know what has changed and only execute those changes. For example, if you change the name of a column, Propel only sees the new schema and has no way of knowing whether you just changed the name or deleted the old column and added a new one.
You want to migrate, or "update" your database from one version to another. Propel 1.6 (not yet released) will have this built-in, but there is an older Symfony plugin that adds simple migration support. You write the SQL queries to change the database yourself. This is not as automated as you might want, but it probably means that it will still work with the current version of Symfony and Propel.

A: As Jan said above, Propel is implementing a "migrate" feature, but more importantly, this is combined with an "sql-diff" feature that allows you to generate SQL for altering tables (versus dropping and re-adding). These two features won't be "officially" released until 1.6, but you can get them with the development version of 1.5.3.
Brief documentation of the new features
Download 1.5.3-devel from SVN (will be 1.6 when done)


text:
Q: Number input falsely accepting floats with decimal places

<form>
  <input type="number" step="1" required>
  <input type="submit">
</form>

In the above code snippet, if you insert
0.0000001

into the number input, you cannot submit the form: The "step" attribute prevents this.
But if you insert
0.00000001

it works in Chrome/Chromium! Why does it seem to only read the first seven decimal places when validating the input? Is this documented anywhere and what can I do to prevent this?
I tested Firefox, it does not accept any such values.
For clarification, the common pitfall 0.30000000000000004 === 0.1+0.2 cannot be the issue here, as this occurs only with 16 decimal places. The input value above fails with 8 decimal places.

A: To prevent that, I can propose you to limite the action for the user :
I added onkeypress="return event.charCode >= 48 && event.charCode <= 57" to don't allow the user to type . and ,
The last problem is that user can paste value inside the input so there is a little script to prevent that :

  const pasteBox = document.getElementById("no-paste");
  pasteBox.onpaste = e => {
    e.preventDefault();
    return false;
  };
<form>
  <input
     type="number"
     step="1"
     onkeypress="return event.charCode >= 48 && event.charCode <= 57"
     required
     id="no-paste">
  <input type="submit">
</form>

Hope it help you ;)
EDIT : You can use this javascript to limit the decimals :

const myInput = document.getElementById("my-input");
  myInput.addEventListener("input", function() {
    const dec = myInput.getAttribute('decimals');
    const regex = new RegExp("(\\.\\d{" + dec + "})\\d+", "g");
    myInput.value = myInput.value.replace(regex, '$1');
  });
 <input id="my-input" type="text" decimals="2" placeholder="2 dec" />

A: While it is certainly a bug with the numbers you have, it actually allows to prevent issues with other sets of steps/values. There are core issues with fraction rounding, making a perfect step validation not that easy, at least not with that level of precision. In fact if you look at Firefox source code, you can find this comment https://dxr.mozilla.org/mozilla-central/source/dom/html/HTMLInputElement.cpp#4654:

There could be rounding issues below when dealing with fractional numbers, but let's ignore that until ECMAScript supplies us with a decimal number type.

So the issues are not only with Chrome. But let's start with the bug you describe. If you look at Chromium source code, you can see that in the step_range handling, there is a method called AcceptableError, which adjust the difference between the value and the value adjusted in regard to the step. See https://cs.chromium.org/chromium/src/third_party/blink/renderer/core/html/forms/step_range.cc?l=60. This acceptable error is defined as:
the step value / 2^24 (in the source code UINT64_C(1) << FLT_MANT_DIG)

This gives for a step of 1:
1 / 16777216 = 0.000000059604645

So in your original example, any number that has a remainder under this value, will validate, even if it shouldn't. The formula to calculate the remainder is:
value - step * Math.abs(Math.round(value / step));

So for example if you enter 2.000000059604644, the remainder will be:
  2.000000059604644 - 1 * Math.abs(Math.round(2.000000059604644))
= 2.000000059604644 - 2
= 0.000000059604644

0.000000059604644 is under 0.000000059604645 so it'll validate. 2.000000059604646 won't.

<form>
  <input type="number" step="1" required>
  <input type="submit">
</form>

You can try with bigger numbers, for example take a step of 167772167. This gives an acceptable error of:
16777217 / 16777216 = 1.000000059604645

and for a value of 16777218 a remainder of:
  16777218 - 16777217 * Math.abs(Math.round(1.000000059604645 ))
= 16777218 - 16777217
= 1

<form>
  <input type="number" step="16777217" required>
  <input type="submit">
</form>

which is under your acceptable error of 1, so it'll validate.
So this is the bug. What it allows in revenge, is to tolerate certain steps and values that because of a loss of precision in the decimal operations wouldn't validate when they should. And in browsers such as Firefox, this is exactly what happens. Some values/steps pair don't validate when they should.
Take for example a step of 853.2394 and a value of 495714162280.48785. This should certainly validate, since :
495714162280.48785 / 853.2394 = 580978987

If you try it in Firefox, it doesn't validate. But in Chrome, it validates, because of the tolerance that causes the bug with the first case.

<form>
  <input type="number" step="853.2394" required>
  <input type="submit">
</form>

So in the end, this bug is linked to known issues with fractional operations, which aren't precise. The classic example is 0.1 + 0.2 = 0.30000000000000004. What happens in the background is a bit more complex and more precise, but the problem of dealing with decimal calculations causes these issues, and makes them hard to prevent for every case.

A: Just a simple answer computer works on binary, not in decimal so floating-point calculation on the computer is different from the real-world that's why it is showing an unexpected result.
You can use multiply and divide method to correct the error. This is gonna fix the error:
(0.1*100+0.2*100)/100

And it is not a chrome bug


text:
Q: Data insertion not happening in a database I'm trying to insert data into a database. the connection is working fine. However I can't insert data and I have no idea why. The table is just not getting updated.
string ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Kaushalya\\Documents\\NewAgain.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True";

SqlCommand cmd = new SqlCommand("Insert into Tabel1(name) VALUES (@UserName);",conn);
cmd.Parameters.Add(new SqlParameter("@UserName", Convert.ToInt32(0)));

Connection when tested is working fine. However, I can't do anything with the database.

A: You need to execute the Command object.
cmd.ExecuteNonQuery();

More info here.

A: You need to call ExecuteNonQuery() to run the query.


text:
Q: Add id dynamically to each table cells I am trying to create a dynamic js table and I want to give id to each cell dynamically. I want to use those ids to use in different js event handlers. How it can be done? I have tried in different ways but none of them works!
<html>

<head>
    <style>
        #colors {
            float: right;
            width: 400px;
            height: 400px;
        }
    </style>
</head>

<body>
    <script>
        var d;
        var k = 0;
        function makeit() {
            var tbl = document.createElement("table");
            var atts = document.createAttribute("style");
            atts.value = "border:1px solid black;text-align:center;padding:2px;margin:3px 3px 3px 3px;";
            tbl.setAttributeNode(atts);
            for (i = 0; i < 5; i++) {
                var rows = tbl.insertRow(i);

                for (j = 0; j < 7; j++) {
                    d = rows.insertCell(j);
                    d.height = "50px";
                    d.width = "50px";
                    d.style.backgroundColor = "yellow";
                    d.addEventListener("click", function myfunc() { d.style.backgroundColor = "red"; });

                }
            }

            document.body.appendChild(tbl);
        }

        window.onload = makeit;
    </script>
</body>

</html>

A: Just add
d.id = "r" + i + "c" + j;

under
d=rows.insertCell(j);

to set unique ids on each td.
Obviously, you can change the syntax r2c4 (which would be 3. row and the 5. cell) to your own liking.
If you want to call a function when clicking on a specific td you could even pass the row index (i) and column index (j) to that function.
Side note
You should consider using a JavaScript library or framework like jQuery for manipulations like this. It would facilitate your work a lot in the long term.

A: The problem is a scope issue. When adding the event listener, d's reference gets updated to be the last table cell you have created.
You can simply change the event listener's function to:
function myfunc() {
     this.style.backgroundColor="red";
}

So that this references the object it is attached to. Depending on your intention, you may not need unique ids if you have access to the cell itself.

A: Using an approach that includes wongcode's solution, you may wish to consider the following code:
<html>
<head>
<style>
#myTbl{ border:1px solid black;text-align:center;padding:2px;margin:3px 3px 3px 3px; }
#myTbl td{ width: 50px; height: 50px; background-color: yellow;}
</style>
</head>
<body>
<script>

function onCellClicked(e)
{
    this.style.backgroundColor = 'red';
}

function makeit()
{
    var tbl=document.createElement("table");
    tbl.id = 'myTbl';
    var curCellIndex = 0;
    for(i=0;i<5;i++)
    {
        var rows=tbl.insertRow(i);
        for(j=0;j<7;j++)
        {
            d=rows.insertCell(j);
            d.id = 'cell_' + curCellIndex;
            curCellIndex++;
            d.addEventListener("click",onCellClicked, false);
        }
     }
    document.body.appendChild(tbl);
}

window.onload=makeit;
</script>
</body>
</html>

Some of the advantages include:

*

*Smaller html file created in your editor

*Smaller html code created in the browser

*Use of context and the this keyword

*Smaller memory consumption, since each TD doesn't contain the full
body of the event handler (it only include a 'pointer' to the
function to be executed)

EDIT: forgot to add code to give the cells an id. Now fixed.


text:
Q: Running a Batch with Admin Rights, but with pre saved User&Pass in the Batch to avoid windows asking for the Cridentials I am already using the following Batch to open my Jar file with Admin Right:
@echo off
:: BatchGotAdmin (Run as Admin code starts)
REM --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"
REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
echo Requesting administrative privileges...
goto UACPrompt
) else ( goto gotAdmin )
:UACPrompt
echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
echo UAC.ShellExecute "%~s0", "", "", "runas", 1 >> "%temp%\getadmin.vbs"
"%temp%\getadmin.vbs"
exit /B
:gotAdmin
if exist "%temp%\getadmin.vbs" ( del "%temp%\getadmin.vbs" )
pushd "%CD%"
CD /D "%~dp0"
:: BatchGotAdmin (Run as Admin code ends)
:: Your codes should start from the following line
-cp Jarfile.jar com.testApp

however after clicking on the Batch file, the windows will ask me to insert the Username and password.
The Question is , is there any way to give the user and pass inside the Batch file to open the Jar file but without windows asking for user and pass?


text:
Q: No Make or GCC on my OSX I'm new with OSX. When I open a terminal I don't have make or gcc; however I have installed xcode so from what I have read they should by somewhere on the OS.
What should I do?

A: Go to the Apple Developer website, log in and then look for "Command Line Development Tools".  They should be found at https://developer.apple.com/downloads.
Logging in is important as you need to do this to get access to these specific tools.


text:
Q: Rolling average matching cases across multiple columns I'm sorry if this has been asked but I can't find another question like this.
I have a data frame in Pandas like this:
Home   Away   Home_Score   Away_Score
MIL    NYC    1            2
ATL    NYC    1            3
NYC    PHX    2            1
HOU    NYC    1            6

I want to calculate the moving average for each team, but the catch is that I want to do it for all of their games, both home and away combined.
So for a moving average window of size 3 for 'NYC' the answer should be (2+3+2)/3 for row 1 and then (3+2+6)/3 for row 2, etc.

A: You can exploid stack to convert the two columns into one and groupby:
(df[['Home_Score','Away_Score']]
   .stack()
   .groupby(df[['Home','Away']].stack().values)
   .rolling(3).mean()
   .reset_index(level=0, drop=True)
   .unstack()
   .add_prefix('Avg_')
)

Output:
   Avg_Away_Score  Avg_Home_Score
0             NaN             NaN
1             NaN             NaN
2             NaN        2.333333
3        3.666667             NaN


text:
Q: If $\sum_{n=1}^{\infty} \sum_{k=1}^{\infty} f_{n}(k) = \infty$ then $\sum_{k=1}^{\infty} \sum_{n=1}^{\infty} f_{n}(k) = \infty$. Suppose $\{f_{n}\}_{n=1}^{\infty}$ be functions such that $f_{n} : \Bbb{N} \rightarrow \Bbb{R}^{+}$ for each $n$.
I was trying to prove -
If $\sum_{n=1}^{\infty} \sum_{k=1}^{\infty} f_{n}(k) = \infty$ then $\sum_{k=1}^{\infty} \sum_{n=1}^{\infty} f_{n}(k) = \infty$.
I can see that both the double summation series are  equal by expanding the double summation.But I am trying to prove it ? any other thoughts?
Hm, as the order of summation are changed, is Uniform convergence likely to play any role here?

A: With nonnegative summands we have regardless of convergence of the inner sum to a finite value or $\infty$,
$$\sum_{n=1}^N \sum_{k=1}^\infty f_{nk} = \sum_{k=1}^\infty \sum_{n=1}^N f_{nk}$$ and by the MCT
$$\sum_{n=1}^\infty \sum_{k=1}^\infty f_{nk} = \sum_{k=1}^\infty \sum_{n=1}^\infty f_{nk}$$


text:
Q: Syntax highlight for APIDoc/JSDoc in VS Code I'm using APIDoc to document my server side APIs.
I do so in separate .js files that are hundreds of lines long so syntax highlighting could be helpful.
It should probably look something like this.
Before writing a custom syntax highlighter I want to make sure I'm not missing anything though - is there a way to highlight APIDoc/JSDoc syntax already (something like this for Atom)?
Thanks!


text:
Q: Nonclosing close button in Windows Mobile ( developed with Qt) Whenever I set maximized the Windows Mobile applications by code that I developed with Qt , their titlebar disappear and there remains only Windows Mobile's default Title Bar. However, whenever I click on that X button, Application won't get closed; instead it keeps running behind.
alt text http://img27.imageshack.us/img27/2296/winmobileexit.jpg
After a few Google searches, I realized that this is the default behaviour for X button on Windows Mobile, which is also the cause of my problem; when I want to show the minimized/hided program by clicking Activate from Settings->System->Memory->Running Programs,
alt text http://img17.imageshack.us/img17/7387/winmobileexit2.jpg
Application isn't repainted and remains invisible and child widgets respond the respective events:
alt text http://img505.imageshack.us/img505/5276/winmobileexit3.jpg
I don't think this behaviour is any way related to my code, as this problem occurs even with the following simple code: ( I would be appreciated if you can test this on your device)
#include <QApplication>
#include <QtGui>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QLabel w("aduket");
    w.setWindowState(w.windowState()|Qt::WindowMaximized);
    w.show();
    return a.exec();
}

Although, I have tried to get the close event of that button, I couldn't. Yet again, only solution that cconceived to me is to remove that X button and add an Exit item to the bottom right menu. Is this reasonable? What might be the cause of this behaviour? Do you have any idea how to resolve this behavior?
Thanks in advance.

A: The "Smart Minimize" button is handled by a style bit typically set when the Windows is created - specifically WS_NONAVDONEBUTTON.  For a CF application, this is controlled by setting the MinimizeButton property to false.  In C/C++, it is done by adding the bit when calling CreateWindow or setting the bit afterward (directly or, as Shane suggests, via SHDoneButton).
Qt is obviously creating a Window, so it's in that process that you need to change the style bit.  I'm not a Qt developer, so exactly how it's done in that framework I don't know.

A: When using .NET/CF, there is a MinimizeBox property on each Form, setting it to false changes the button to [Ok] and it will close the app. I'm guessing Qt might have a similar setting.

A: If you don't want the default windows mobile behavior you will need to call the function SHDoneButton.
It takes three possible arguments:

*

*SHDB_HIDE - which is the default and WM most likely displays the 'X' button and will minimize your app when it's pressed.  Also note on some devices the 'X' button will send a WM_QUIT to your application.

*SHDB_SHOW - will show a 'ok' button and will send a IDOK WM_COMMAND to your window when pressed.

*SHDB_SHOWCANCEL - will show a 'x' button and will send a IDCANCEL WM_COMMAND to your window when pressed.

A: Thanks for your indispensable answers. They all contributed to my solution. When I tried to change X button to OK button, I found out that there is a Windows CE specific flag to make OK button visible.
 #ifdef Q_OS_WINCE
       setWindowFlags(windowFlags()|Qt::WindowOkButtonHint);
 #endif

after setting that Button, I have overrided event(QEvent*) function to catch the event fired from OK in order to close the application.
bool MainWindow::event(QEvent *mEvent)
{

    if (mEvent->type()==QEvent::OkRequest)
    {
         qApp->closeAllWindows();
         return true;
    }

    return QMainWindow::event(mEvent);

}

and now it works like a charm =)


text:
Q: Oracle Apex delete entry from collection I have two interactive reports with check boxes. If the user select entries from interactive report1 and press a button, the selected entries will be added into a collection and displayed in interactive report2.
In interactive report2 I have again a checkbox and if the user select an entry, it should be deleted from the collection and interactive report2 by pressing a button.
I have defined a process which is fired when the button is pressed:
declare v_id number;
begin
FOR i in 1..APEX_APPLICATION.G_F03.count

LOOP
select id into v_id from apex_collections where collection_name = 'SELECTED2' and c001 = APEX_APPLICATION.G_F03(i);
   apex_collection.delete_member(
   p_collection_name => 'SELECTED2',
   p_seq => v_id);
END LOOP;
end;

SELECTED2 is the name of the collection.
APEX_APPLICATION.G_F03 is the checkox value of the check box in interactive report2.
Problem, the entire collection is deleted and not only the selected rows in  interactive report2. How could I delete only the selected rows?

A: This is an example on the emp/dept schema with 2 interactive reports:

*

*IR_1 on emp with all records that are in table but not in collection

*IR_2 on emp with all records that are in collection

When a user selects checkbox in IR_1 and submits, those records are put in a collection. When a user selects checkbox in IR_2 and submits, record is removed from collection.
IR_1 has query:
select EMPNO,
       ENAME,
       APEX_ITEM.CHECKBOX(1,empno,'UNCHECKED') AS CHECKBOX
  from EMP
where NOT EXISTS (SELECT n001 FROM apex_collections WHERE collection_name = 'EMP' AND n001 = empno)

and a button "ADD" with action "Submit Page" in IR_1 region
IR_2 has query:
select EMPNO,
       ENAME,
       APEX_ITEM.CHECKBOX(2,empno,'UNCHECKED') AS CHECKBOX
  from EMP WHERE empno IN (SELECT n001 FROM apex_collections WHERE collection_name = 'EMP')

and a button "REMOVE" with action "Submit Page" in IR_2 region.
Create 2 page processes of type Execute Code:

*

*"Add to Collection"

IF NOT APEX_COLLECTION.COLLECTION_EXISTS ( p_collection_name => 'EMP') THEN
  APEX_COLLECTION.CREATE_COLLECTION( p_collection_name => 'EMP');
END IF;
FOR I in 1..APEX_APPLICATION.G_F01.COUNT LOOP
  APEX_COLLECTION.ADD_MEMBER (
    p_collection_name => 'EMP',
    p_n001 => to_number(APEX_APPLICATION.G_F01(i)));
END LOOP;

Condition: When button pressed = ADD

*"Remove fromCollection"

FOR I in 1..APEX_APPLICATION.G_F02.COUNT LOOP
  FOR j IN (SELECT seq_id FROM apex_collections WHERE collection_name = 'EMP' and n001 = to_number(APEX_APPLICATION.G_F02(i)))
  LOOP
    APEX_COLLECTION.DELETE_MEMBER (
      p_collection_name => 'EMP',
      p_seq => j.seq_id);
  END LOOP;
END LOOP;

Condition: When button pressed = REMOVE
Note: Since those 2 interactive reports are on a single page 2 different ids need to be taken for the checkbox. IR_1 uses 1 (and  APEX_APPLICATION.G_F01) in the page process and IR_2 uses 2 - (and  APEX_APPLICATION.G_F02) in the page process.


text:
Q: What regulatory hurdles do I need to conform to to sell my products? I have products that involve some simple resistors and diodes etc that plug into the microphone jack of a mobile phone (they are sensors).
What regulatory hurdles must I cross in order to sell on eBay to 'test the market'?
The Low Voltage Directive isn't applicable because its below 50V (the voltages are phone voltages).
Someone suggested I can 'self-certify' BS-EN 60950 - The Information Technology Standard.  But my 'devices' are much simpler than that would normally be applied to.
Any ideas?

A: In the US, if your device has any chip in it than runs at above 1.705MHz, you need to have it tested to verify that any unintended radio wave output is below acceptable levels.  If you only really have passive components, you may be able to sell without having your device pass a verification test.
Here is a good article on the topic.


text:
Q: In which controls, other than Button, can WPF Geometry icons be shown without defining Stroke or Fill? I need to show icons like this:
<Geometry x:Key="Geometry.LeftArrow">M 6.5 0.5 L 7.5 1 L 7.5 0 L 6.5 0.5 z</Geometry>

If I put them in Button they're Ok. However I need to show them in many other places but they're not shown. Sometimes it helps to define Stroke/Fill but this is wrong. I don't want to make up some colors that are hardcoded and look stupid when Theme/Style is changed.
This works:
<Button>
    <Path Data="{StaticResource Geometry.LeftArrow}" Stretch="Uniform" MaxHeight="12"/>
</Button>

This does not:
<Label>
    <Path Data="{StaticResource Geometry.LeftArrow}" Stretch="Uniform" MaxHeight="12"/>
</Label>

So what is the logic here and how can I have just show them let's say next to some TextBox?

A: I tried this and the Path didn't get a default fill or stroke in a Button.
My solution would be to define a default Path Style which sets Fill (or Stroke, whichever) to {DynamicResource {x:Static SystemColors.ControlTextBrushKey}}.
<Style TargetType="Path">
    <Setter
        Property="Fill"
        Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"
        />
</Style>

A well-designed theme should use those SystemColors brush keys. If a theme isn't well designed, you can add some "shim" resource definitions which define SystemColors brush keys to appropriate theme resources.
If I wanted to give Path a default fill in Button but not elsewhere, I could do that by defining that default Path style in the resources for the Button style:
<Style TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
    <Style.Resources>
        <Style TargetType="Path">
            <Setter
                Property="Fill"
                Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"
                />
        </Style>
    </Style.Resources>

    <!-- other stuff -->
</Style>

And now that you've talked to your style and icon people (so jelly; we have to do that stuff for ourselves), it looks like that's the essence of what's happening here.


text:
Q: Lock certain pages and leave others open I have a website that show info to all users but if you are logged in you get access to more info and pages then unlogged user does.
Can i use some sessions variables and include them in each of the pages ?
What is the best way to do this.
Also, what is the best way to make user stay logged in, sort of "Remember me" checkbox. Save a cookie on hdd ?

A: To answer your first question. The easiest route to go is to have something in your code behind that sets the visible flag on or off of certain controls based on something you've saved in session.
This can get complex fast, so I would play with it a bit and figure out what works best with your business rules.
To answer your second question. You should save something in a static cookie that you can reference later. I personally like saving a GUID in their cookie, which I save a copy of in a local database. When someone re-visits the site, I look for this cookie. If the GUID is present and matches one stored for someone in my Database, I auto-log them in.

A: I would recommend using ASP.NET Membership. It has a Login control with a "remember me" function. You can also restrict access to pages via the web.config with it.
This is a good series of articles on the subject: https://web.archive.org/web/20211020153319/https://www.4guysfromrolla.com/articles/062508-1.aspx

A: you probably need to implement Authorization mechanism for your application
Here is a Built-in Infrastructure provided by Asp.Net

*

*User-Based Authorization
For second Question, the best way is to use cookies. have a look at this tutorial

*

*Read, Write, and Delete Cookies in
ASP.NET

A: Membership and authentication is one of the basic needs of every Web-Application and among all feature that .net Framework has provided , ASP.NET Membership is one of greatest one that most of developers founded it useful . If you want you can implement your own Authorization and authentication But recommended  to use Authentication and Authorization in ASP.NET


text:
Q: What FLOSS skype alternatives are available? Given Skype's slow development speed for the GNU/Linux version and its recent acquisition by Microsoft, I am looking for alternative softwares.
What FLOSS (free/libre/open-source software) Skype alternatives are available?

A: TOX is an open source project to build a code library establishing a messaging and video calling protocol, started with user privacy in mind. It provides and API, or core, around which user front-ends, or clients, can be built.
There are three Tox clients in development for Linux:
. Venom - a cross-platform graphical user interface for Tox written in Vala using GTK+. Install instructions.
. Blight - a cross-platform graphical user interface for Tox written in Racket that utilizes libtoxcore-racket. In very early pre-alpha stage.
. Qt GUI for Tox - a cross-platform front end for Tox Core written in Qt5 and C++. Development is in very early stages and usage beyond testing is not advised.

A: SIP Clients
These all are SIP clients which means they all can be used to call each other and they just need a SIP address (like your mobile number). You can get a SIP address for free from many providers (Ekiga, jit.si, iptel), some of which (sip2sip.info, ippi.com, localphone.com, nonoh.net) also have PSTN gateways into the normal phone network which allows you to make and receive regular calls from/to your SIP client (for a fee). For various reasons some clients may not work with some providers (for example, for Nonoh and Iptel, Blink works but Jitsi, Ekiga, and Linphone don't).
Ekiga (available in the software center)
Here is First use documentation for ekiga .
Here is documentation on how to use the PC to Phone feature in ekiga .

Ekiga (formely known as GnomeMeeting) is an open source SoftPhone, Video Conferencing and Instant Messenger application over the Internet.

Ring (available in the software center)

Ring is free software for universal communication which respects freedoms and privacy of its users. It supports SIP accounts. Ring is available under the GNU GPL license, version 3.

Twinkle  (available in the software center)

Twinkle is a softphone for your voice over IP and instant messaging communcations using the SIP protocol. You can use it for direct IP phone to IP phone communication or in a network using a SIP proxy to route your calls and messages.

Yate VoIP (available in the software center)

YATE is a telephony engine aimed at creating a telephony server that performs well enough to deal with PBX requirements and also flexible enough for complex Gateway and IVR solutions.
YateClient uses the same telephony code to produce a software desktop VoIP (SIP, H.323, IAX2) phone. yate-qt4 uses this to provide such a telephony

QuteCom  (available in the software center)

QuteCom is a community of enthusiasts and developers, creating free software products related to communication over IP. The flagship product of the QuteCom project is a softphone which allows you to make free PC to PC video and voice calls, and to integrate all your IM contacts in one place.

Linphone (available in the software center)

Linphone is an internet phone or Voice Over IP phone (VoIP).
With linphone you can communicate freely with people over the internet,
with voice, video, and text instant
messaging.
Linphone makes use of the SIP protocol , an open standard for
internet telephony. You can use
Linphone with any SIP VoIP operator,
including our free SIP audio/video
service

Jitsi

Jitsi - Open Source Video Calls and Chat
Secure video calls, conferencing, chat, desktop sharing, file transfer, support for your favorite OS, and IM network. All this, and more, in Jitsi - the most complete and advanced open source communicator. Implemented in Java.

Blink

A state of the art, easy to use SIP client
Available for Mac, Windows and Linux. Comprehensive controls over the details of the protocol. Blink is the end-result of cumulated knowledge built over many years by its developers who worked on the development of popular open-source SIP infrastructure software and attended relevant IETF and SIPIT events where SIP protocol has been developed and tested 18.  Implemented using Qt.

A: You can use Empathy (pre-installed in Ubuntu) instead of Skype.
For users of Windows, OS/X, you can ask them to install Google Voice and Video chat, http://www.google.com/chat/video
Empathy and Google Voice and Video chat are compatible with each other, so you can have voice and video chats!
There is an option for VoIP (SIP) support in Empathy. You install the telepathy-sofiasip package to add SIP support. It might not be excellent yet, however you can get the work done.
In addition, with Empathy you have many additional options (not found in basic Skype), including

*

*you have the option for remote desktop to your IM contacts (pre-installed)

*you can SSH to the computer of your contacts (requires package to install)

*you can collaborate with your contacts in writing a document with gedit (see gedit-collaborate).

A: Not FLOSS but you can use Googles Voice and Video chat from within the browser.

A: The most popular tool is Jitsi. It is an Encrypted text, voice, and video messaging for multiple platforms.

More from the home page:

Jitsi (formerly SIP Communicator) is an audio/video and chat
  communicator that supports protocols such as SIP, XMPP/Jabber,
  AIM/ICQ, Windows Live, Yahoo! and many other useful features.

You can find more Free Software alternatives to Close Systems on PRISM BREAK.


text:
Q: Ubuntu Linux: find files between specific times? I found an SO called using Find/Grep to search files between specific time of day
Based on that and a Unix SE called Grep command to find files containing text string and move them I ended up with:
find . -type f -mtime -20 | grep -v -e " \(0[012345]\|18\|19\|2[0123]\)" | xargs mv -t daytime/

But it's moving ALL the files. Does it make a difference that I'm using Ubuntu?
All I want to do is move all files between 6am and 6pm to another directory. Any suggestions would be appreciated.

A: Actually, find already has this functionality:
find . -newermt "2013-01-01 00:00:00" ! -newermt "2013-01-02 00:00:00"

From the manpage:
-newerXY reference
       Compares  the timestamp of the current file with reference.  The
       reference argument is normally the name of a file  (and  one  of
       its  timestamps is used for the comparison) but it may also be a
       string describing an absolute time.  X and  Y  are  placeholders
       for other letters, and these letters select which time belonging
       to how reference is used for the comparison.

       a   The access time of the file reference
       B   The birth time of the file reference
       c   The inode status change time of reference
       m   The modification time of the file reference
       t   reference is interpreted directly as a time

       Some combinations are invalid; for example, it is invalid for  X
       to  be t.  Some combinations are not implemented on all systems;
       for example B is not supported on all systems.  If an invalid or
       unsupported  combination  of  XY  is  specified,  a  fatal error
       results.  Time specifications are interpreted as for  the  argu‐
       ment  to the -d option of GNU date.  If you try to use the birth
       time of a reference file, and the birth time  cannot  be  deter‐
       mined,  a  fatal  error  message results.  If you specify a test
       which refers to the birth time of  files  being  examined,  this
       test will fail for any files where the birth time is unknown.


text:
Q: Embedding Wave Dashboards into a Visualforce Page I'm trying to embed a Wave dashboard onto a Visualforce page, but I'm getting the error "
This dashboard doesn't exist, has been deleted, or you may not have access to it".
I checked the sharing settings on the dashboard, and the entire organization has manager access. The entire app (where this dashboard is hosted), is also shared with the Entire Organization with manager access.
The code I'm using is:
<apex:page sidebar="true" standardController="Opportunity">

  wave:dashboard dashboardId="0FKB000000006Y7OAI"
        showTitle="true"
        height="800px"
        openLinksInNewWindow="true"
        filter="{'datasets' : {'opportunity': [ {'fields':['Id'], 'selection': ['{!Opportunity.Id}']}]}}"/>

</apex:page>

A: This is a Wave(Einstein) analytics access issue, not with the VF page.
As a System Administrator, view this VF page and navigate to the associated Dashboard this page is using (Click open in wave icon).

*

*Click Share (round arrow icon pointing to right side)

*You will see the pop-up options - Give Access,Post to feed, Download

*At the bottom of this pop up, you will see a message.
-To invite others to view, edit, or manage this Dashboard, click
"XXX" and share the app. XXX is the App in which this dashboard belongs.

*Click on XXX (App), and all you need to do is give access to the affected user. (Viewer/Editor/Manager) - generally we might want to give Viewer.

This should resolve. Actually the dashboard is inside an App, and the App is not shared with the affected user, hence wasn't able to view it in the VF page.


text:
Q: Virtual env: Connection in use error I was working on github cloned folder, and created my first ever branch. After switching branches/closing the terminal I went back into my project dir root and ran the usual:
  $ source venv/bin/activate
    (venv)$ foreman start
    14:13:42 web.1  | started with pid 5591
    14:13:42 web.1  | 2014-04-29 14:13:42 [5591] [INFO] Starting gunicorn 18.0
    14:13:42 web.1  | 2014-04-29 14:13:42 [5591] [ERROR] Connection in use: ('0.0.0.0', 5000)
    14:13:42 web.1  | 2014-04-29 14:13:42 [5591] [ERROR] Retrying in 1 second.
    14:13:43 web.1  | 2014-04-29 14:13:43 [5591] [ERROR] Connection in use: ('0.0.0.0', 5000)
    14:13:43 web.1  | 2014-04-29 14:13:43 [5591] [ERROR] Retrying in 1 second.
    14:13:44 web.1  | 2014-04-29 14:13:44 [5591] [ERROR] Connection in use: ('0.0.0.0', 5000)
    14:13:44 web.1  | 2014-04-29 14:13:44 [5591] [ERROR] Retrying in 1 second.
    14:13:45 web.1  | 2014-04-29 14:13:45 [5591] [ERROR] Connection in use: ('0.0.0.0', 5000)
    14:13:45 web.1  | 2014-04-29 14:13:45 [5591] [ERROR] Retrying in 1 second.
    14:13:46 web.1  | 2014-04-29 14:13:46 [5591] [ERROR] Connection in use: ('0.0.0.0', 5000)
    14:13:46 web.1  | 2014-04-29 14:13:46 [5591] [ERROR] Retrying in 1 second.
    14:13:47 web.1  | 2014-04-29 14:13:47 [5591] [ERROR] Can't connect to ('0.0.0.0', 5000)
    14:13:47 web.1  | exited with code 1
    14:13:47 system | sending SIGTERM to all processes
    SIGTERM received

And I am receiving this error, and I can't quite figure out what the issue is. Does it have to do with branching?

A: You still have an instance of gunicorn running. foreman runs a daemon instance of gunicorn so if you close terminal down it will still run in the background. For this reason you should always Ctrl + C foreman before closing down terminal. There is however a way to kill the server.
Firstly you can find the id for unicorn to kill it via $ ps ax|grep unicorn and then using the id of the gunicorn instance $ kill <id>
Alternatively you can use $ pkill gunicorn


text:
Q: Is it safe to subscribe to an observable with an async function I have an event emitter that sends events at 50Hz.
I'd like to subscribe to this emitter with an async method. The code looks like the following:
this.emitter = fromEventPattern(this.addHandler, this.removeHandler, (err, char) => [err, char]);
this.rxSubscription = this.emitter.subscribe(this.handleUpdatedValuesComingFromSensor);

and
       handleUpdatedValuesComingFromSensor = async (arr: any[]): Promise<void> => {
   ...
   await someMethodAsync();
   ...
}

I maybe wrong but I'm under the impression that awaiting in there makes the emitter calls onNext() immediately because I've exited the method.
This is very difficult to debug with console calls because of the event rate.
Am I right or wrong?
Thanks for your help.
EDIT 1:
I'm using typescript targetting ES2015 so a state machine is generated for async/await.
If I'm right, how can I ensure that calls do not overlap? I need to compute averages on values I receive.

A:
awaiting in there makes the emitter calls onNext() immediately because I've exited the method

You are correct. Rx ignores the return types of its subscription functions, so it ignores the promise returned from your async function when it hits its first await. This means:

*

*As soon as another item arrives on the observable, Rx will invoke your subscription function again. It ignored the promise that was returned, so it doesn't know the old invocation is still in progress.

*Exceptions from your async function will be ignored, since the promise was ignored. Some promise libraries have a global "unobserved promise error" event that can handle this.

A: I'm not entirely clear what your concerns are.  It is valid, your method will be called once for each and every element.  It isn't going to skip anything or cut your method off halfway through but:

*

*It will not wait for one iteration of handleUpdatedValuesComingFromSensor to finish before starting another (assuming handleUpdatedValuesComingFromSensor truly does something asynchronous) so you could have multiple instances of handleUpdatedValuesComingFromSensor in flight at the same time.

*Similarly, if you have multiple subscribers then it will not wait for handleUpdatedValuesComingFromSensor to finish before sending the event to the next subscriber.