text:
Q: i have a problem: my enemies are stacked vertically, on top of my player which is weird, and they don't move to their predefined positions i have earlier tried to format my question properly but i hope this one is better. am creating a shooter game from https://github.com/russs123/Shooter. however my problem is that my enemies are stacked vertically upwards in a straight line when i run my game and the enemies don't start off at their predefined location. below is the full code i wrote. perhaps if you can run it, it will be better understood.
import pygame, sys
from player import Player
import os
import random
import csv

pygame.init()
screen_width = 600
scroll_thresh = 200
screen_scroll = 0
bg_scroll = 0
screen_height = int(screen_width * 0.8)
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Shooter Game")
clock = pygame.time.Clock()
fps = 60
# define game variables
GRAVITY = 0.75

level = 1
ROWS = 16
COLS = 150
TILE_SIZE = screen_height // ROWS
TILE_TYPES = 21
img_list = []
for x in range(TILE_TYPES):
    img = pygame.image.load(f"img/tile/{x}.png")
    img = pygame.transform.scale(img, (TILE_SIZE, TILE_SIZE))
    img_list.append(img)
# color variables
bg = (144, 201, 120)
RED = (255, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
BLACK = (0, 0, 0)
# define player action variables
moving_left = False
moving_right = False
shoot = False
grenade = False
grenade_thrown = False
# load up images
pine1_img = pygame.image.load("img/Background/pine1.png").convert_alpha()
pine2_img = pygame.image.load("img/Background/pine2.png").convert_alpha()
mountain_img = pygame.image.load("img/Background/mountain.png").convert_alpha()
sky_cloud_img = pygame.image.load("img/Background/sky_cloud.png").convert_alpha()
bullet_img = pygame.image.load("img/icons/bullet.png").convert_alpha()

grenade_img = pygame.image.load("img/icons/grenade.png").convert_alpha()
# pick up boxes
health_box_img = pygame.image.load("img/icons/health_box.png").convert_alpha()
ammo_box_img = pygame.image.load("img/icons/ammo_box.png").convert_alpha()
grenade_box_img = pygame.image.load("img/icons/grenade_box.png").convert_alpha()
# name_dt = type(name)
item_boxes = {
    "Health": health_box_img,
    "Ammo": ammo_box_img,
    "Grenade": grenade_img,
}

# define fonts
font = pygame.font.SysFont("Futura", 30)

def draw_text(text, font, text_col, x, y):
    img = font.render(text, True, text_col)
    screen.blit(img, (x, y))

def draw_bg():
    screen.fill(bg)
    screen.blit(sky_cloud_img, (0, 0))
    screen.blit(mountain_img, (0, screen_height - mountain_img.get_height() - 300))
    screen.blit(pine1_img, (0, screen_height - pine1_img.get_height() - 150))
    screen.blit(pine2_img, (0, screen_height - pine2_img.get_height()))

class Soldier(pygame.sprite.Sprite):
    def __init__(self, char_type, x, y, scale, speed, ammo, grenades):
        pygame.sprite.Sprite.__init__(self)
        self.alive = True
        self.char_type = char_type
        self.speed = speed
        self.ammo = ammo
        self.start_ammo = ammo
        self.shoot_cooldown = 0
        self.grenades = grenades
        self.health = 100
        self.max_health = self.health
        self.direction = 1
        self.vel_y = 0
        self.jump = False
        self.in_air = True
        self.flip = False
        self.animation_list = []
        self.frame_index = 0
        self.action = 0
        # ai specific variables
        self.move_counter = 0
        self.vision = pygame.Rect(0, 0, 150, 20)
        self.idling = 0
        self.idling_counter = 0

        self.update_time = pygame.time.get_ticks()

        # load all images for the players
        animation_types = ["idle", "run", "jump", "death"]
        for animation in animation_types:
            temp_list = []
            # reset temporary list of images
            # count number of files in the folder
            num_of_frames = len(os.listdir(f"img/{self.char_type}/{animation}"))
            for i in range(num_of_frames):
                img = pygame.image.load(f"img/{self.char_type}/{animation}/{i}.png").convert_alpha()
                img = pygame.transform.scale(img, (int(img.get_width() * scale), int(img.get_height() * scale)))
                temp_list.append(img)
            self.animation_list.append(temp_list)

        self.image = self.animation_list[self.action][self.frame_index]
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.width = self.image.get_width()
        self.height = self.image.get_height()

    def update(self):
        self.update_animation()
        self.check_alive()
        # update cooldown
        if self.shoot_cooldown > 0:
            self.shoot_cooldown -= 1

    def move(self, moving_left, moving_right):
        screen_scroll = 0
        dx = 0
        dy = 0
        if moving_left:
            dx = -self.speed
            self.flip = True
            self.direction = -1
        if moving_right:
            dx = self.speed
            self.flip = False
            self.direction = 1
        if self.jump == True and self.in_air == False:
            self.vel_y = -11
            self.jump = False
            self.in_air = True
        # apply gravity
        self.vel_y += GRAVITY
        if self.vel_y > 10:
            self.vel_y
        dy += self.vel_y
        # check for collision
        for tile in world.obstacle_list:
            # check collision in the x direction
            if tile[1].colliderect(self.rect.x + dx, self.rect.y, self.width, self.height):
                dx = 0
            # check for collision in the y direction
            if tile[1].colliderect(self.rect.x, self.rect.y + dy, self.width, self.height):
                # check if below the ground, i.e jumping
                if self.vel_y < 0:
                    self.vel_y = 0
                    dy = tile[1].bottom - self.rect.top
                # check if above the ground, ie falling
                elif self.vel_y >= 0:
                    self.vel_y = 0
                    self.in_air = False
                    dy = tile[1].top - self.rect.bottom

        self.rect.x += dx
        self.rect.y += dy
        # update scroll based on player position
        if self.char_type == "player":
            if self.rect.right > screen_width - scroll_thresh or self.rect.left < scroll_thresh:
                self.rect.x = -dx
                screen_scroll = -dx
        return screen_scroll

    def shoot(self):
        if self.shoot_cooldown == 0 and self.ammo > 0:
            self.shoot_cooldown = 20
            bullet = Bullet(self.rect.centerx + (0.75 * self.rect.size[0] * self.direction), self.rect.centery,
                            self.direction)
            bullet_group.add(bullet)
            # reduce ammo after each shot
            self.ammo -= 1

    def ai(self):
        if self.alive and player.alive:
            if self.idling == False and random.randint(1, 200) == 1:
                self.update_action(0)
                self.idling = True
                self.idling_counter = 50
            # check if ai is near the player
            if self.vision.colliderect(player.rect):
                # stop running and face the player
                self.update_action(0)
                self.shoot()
            else:
                if self.idling == False:
                    if self.direction == 1:
                        ai_moving_right = True
                    else:
                        ai_moving_right = False
                    ai_moving_left = not ai_moving_right
                    self.move(ai_moving_left, ai_moving_right)
                    self.update_action(1)
                    self.move_counter += 1
                    # update ai vision as the enemy moves
                    self.vision.center = (self.rect.centerx + 75 * self.direction, self.rect.centery)

                    if self.move_counter > TILE_SIZE:
                        self.direction *= -1
                        self.move_counter *= -1
                else:
                    self.idling_counter -= 1
                    if self.idling_counter <= 0:
                        self.idling = False

        # scroll
        self.rect.x = screen_scroll

    def update_animation(self):
        ANIMATION_COOLDOWN = 100
        # update image depending on current index
        self.image = self.animation_list[self.action][self.frame_index]
        # check if enough time has passed since the last update
        if pygame.time.get_ticks() - self.update_time > ANIMATION_COOLDOWN:
            self.update_time = pygame.time.get_ticks()
            self.frame_index += 1
        # if animation has run out then restart to the first
        if self.frame_index >= len(self.animation_list[self.action]):
            if self.action == 3:
                self.frame_index = len(self.animation_list[self.action]) - 1
            else:
                self.frame_index = 0

    def check_alive(self):
        if self.health <= 0:
            self.health = 0
            self.speed = 0
            self.alive = False
            self.update_action(3)

    def update_action(self, new_action):
        # check if new action is different from the previous one
        if new_action != self.action:
            self.action = new_action
            # update animation settings
            self.frame_index = 0
            self.update_time = pygame.time.get_ticks()

    def draw(self):
        screen.blit(pygame.transform.flip(self.image, self.flip, False), self.rect)

class HealthBar():
    def __init__(self, health, x, y, max_health):
        self.x = x
        self.y = y
        self.health = health
        self.max_health = max_health

    def draw(self, health):
        self.health = health
        pygame.draw.rect(screen, BLACK, (self.x - 2, self.y - 2, 154, 24))
        pygame.draw.rect(screen, RED, (self.x, self.y, 150, 20))
        ratio = self.health / self.max_health
        pygame.draw.rect(screen, GREEN, (self.x, self.y, 150 * ratio, 20))

class World():
    def __init__(self):
        self.obstacle_list = []

    def process_data(self, data):
        for y, row in enumerate(data):
            for x, tile in enumerate(row):
                if tile >= 0:
                    img = img_list[tile]
                    img_rect = img.get_rect()
                    img_rect.x = x * TILE_SIZE
                    img_rect.y = y * TILE_SIZE
                    tile_data = (img, img_rect)
                    if 0 <= tile <= 8:
                        self.obstacle_list.append(tile_data)
                    elif 9 <= tile <= 10:
                        # water
                        water = Water(img, x * TILE_SIZE, y * TILE_SIZE, )
                        water_group.add(water)
                        pass
                    elif 11 <= tile <= 14:
                        # decoration
                        decoration = Decoration(img, x * TILE_SIZE, y * TILE_SIZE)
                        decoration_group.add(decoration)
                    elif tile == 15:
                        # create a player
                        player = Soldier("player", x * TILE_SIZE, y * TILE_SIZE, 1.65, 5, 20, 5)
                        health_bar = HealthBar(10, 10, player.health, player.health)
                    elif tile == 16:
                        # create enemy
                        enemy = Soldier("enemy", x * TILE_SIZE, y * TILE_SIZE, 1.65, 2, 20, 0)
                        enemy_group.add(enemy)
                    elif tile == 17:
                        # create ammo box
                        item_box = ItemBox("Ammo", x * TILE_SIZE, y * TILE_SIZE)
                        item_box_group.add(item_box)
                    elif tile == 18:
                        # create grenade box
                        item_box = ItemBox("Grenade", x * TILE_SIZE, y * TILE_SIZE)
                        item_box_group.add(item_box)
                    elif tile == 19:
                        # create health box
                        item_box = ItemBox("Health", x * TILE_SIZE, y * TILE_SIZE)
                        item_box_group.add(item_box)

                    elif tile == 20:
                        # create exit point
                        exit = Exit(img, x * TILE_SIZE, y * TILE_SIZE, )
                        exit_group.add(exit)
        return player, health_bar

    def draw(self):
        for tile in self.obstacle_list:
            tile[1][0] += screen_scroll
            screen.blit(tile[0], tile[1])

class Decoration(pygame.sprite.Sprite):
    def __init__(self, img, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.image = img
        self.rect = self.image.get_rect()
        self.rect.midtop = (x + TILE_SIZE // 2, y + (TILE_SIZE - self.image.get_height()))

    def update(self):
        self.rect.x += screen_scroll

class Water(pygame.sprite.Sprite):
    def __init__(self, img, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.image = img
        self.rect = self.image.get_rect()
        self.rect.midtop = (x + TILE_SIZE // 2, y + (TILE_SIZE - self.image.get_height()))

    def update(self):
        self.rect.x += screen_scroll

class Exit(pygame.sprite.Sprite):
    def __init__(self, img, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.image = img
        self.rect = self.image.get_rect()
        self.rect.midtop = (x + TILE_SIZE // 2, y + (TILE_SIZE - self.image.get_height()))

class ItemBox(pygame.sprite.Sprite):
    def __init__(self, item_type, x, y):
        pygame.sprite.Sprite.__init__(self)
        self.item_type = item_type
        self.image = item_boxes[self.item_type]
        self.rect = self.image.get_rect()
        self.rect.midtop = (x + TILE_SIZE // 2, y + (TILE_SIZE - self.image.get_height()))

    def update(self):
        # scroll
        self.rect.x += screen_scroll
        # check if player has picked up the box
        if pygame.sprite.collide_rect(self, player):
            # check what kind of box it was
            if self.item_type == "Health":
                player.health += 25
                if player.health > player.max_health:
                    player.health = player.max_health
            elif self.item_type == "Ammo":
                player.ammo += 15
            elif self.item_type == "Grenade":
                player.grenades += 3
            # delete the item box
            self.kill()

class Bullet(pygame.sprite.Sprite):
    def __init__(self, x, y, direction):
        pygame.sprite.Sprite.__init__(self)
        self.speed = 10
        self.image = bullet_img
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.direction = direction

    def update(self):
        self.rect.x += self.direction * self.speed
        # check if bullet has left the screen
        if self.rect.right < 0 and self.rect.left > screen_width:
            self.kill()
        # check for collision with level
        for tile in world.obstacle_list:
            if tile[1].colliderect(self.rect):
                self.kill()
        # check collision with characters
        if pygame.sprite.spritecollide(player, bullet_group, False):
            if player.alive:
                player.health -= 5
                self.kill()
        for enemy in enemy_group:
            if pygame.sprite.spritecollide(enemy, bullet_group, False):
                if enemy.alive:
                    enemy.health -= 25
                    self.kill()

class Grenade(pygame.sprite.Sprite):
    def __init__(self, x, y, direction):
        pygame.sprite.Sprite.__init__(self)
        self.timer = 100
        self.vel_y = -11
        self.speed = 7
        self.image = grenade_img
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.direction = direction
        self.width = self.image.get_width()
        self.height = self.image.get_height()

    def update(self):
        self.vel_y += GRAVITY
        dx = self.direction * self.speed
        dy = self.vel_y
        # check for collision with level
        for tile in world.obstacle_list:
            # check if grenade has hit a wall
            if tile[1].colliderect(self.rect.x + dx, self.rect.y, self.width, self.height):
                self.direction *= -1
                dx = self.direction * self.speed
            if tile[1].colliderect(self.rect.x, self.rect.y + dy, self.width, self.height):
                self.speed = 0
                # check if below the ground, i.e thrown
                if self.vel_y < 0:
                    self.y = 0
                    dy = tile[1].bottom - self.rect.top
                # check if above the ground, ie falling
                elif self.vel_y >= 0:
                    self.vel_y = 0
                    dy = tile[1].top - self.rect.bottom

        # update grenade position
        self.rect.x += dx
        self.rect.y += dy
        # explosion countdown
        self.timer -= 1
        if self.timer <= 0:
            self.kill()
            explosion = Explosion(self.rect.x, self.rect.y, 0.5)
            explosion_group.add(explosion)
            # do damage to anyone nearby
            if abs(self.rect.centerx - player.rect.centerx) < TILE_SIZE * 2 and \
                    abs(self.rect.centery - player.rect.centery) < TILE_SIZE * 2:
                player.health -= 50
            for enemy in enemy_group:
                if abs(self.rect.centerx - enemy.rect.centerx) < TILE_SIZE * 2 and \
                        abs(self.rect.centery - enemy.rect.centery) < TILE_SIZE * 2:
                    enemy.health -= 50

class Explosion(pygame.sprite.Sprite):
    def __init__(self, x, y, scale):
        pygame.sprite.Sprite.__init__(self)
        self.images = []
        for num in range(1, 6):
            img = pygame.image.load(f"img/explosion/exp{num}.png").convert_alpha()
            img = pygame.transform.scale(img, (int(img.get_width() * scale), (int(img.get_height() * scale))))
            self.images.append(img)
        self.frame_index = 0

        self.image = self.images[self.frame_index]
        self.rect = self.image.get_rect()
        self.rect.center = (x, y)
        self.counter = 0

    def update(self):
        EXPLOSION_SPEED = 4
        # update explosion animation
        self.counter += 1

        if self.counter >= EXPLOSION_SPEED:

            self.counter = 0
            self.frame_index += 1
            # if animation is complete, then delete the explosion
            if self.frame_index >= len(self.images):
                self.kill()
            else:
                self.image = self.images[self.frame_index]

# create sprite groups
enemy_group = pygame.sprite.Group()
bullet_group = pygame.sprite.Group()
grenade_group = pygame.sprite.Group()
explosion_group = pygame.sprite.Group()
item_box_group = pygame.sprite.Group()
decoration_group = pygame.sprite.Group()
water_group = pygame.sprite.Group()
exit_group = pygame.sprite.Group()

# create empty tile list

world_data = []
for row in range(ROWS):
    r = [-1] * COLS
    world_data.append(r)
# load in level data and create world
with open(f"level{level}_data.csv", newline="") as csvfile:
    reader = csv.reader(csvfile, delimiter=",")
    for x, row in enumerate(reader):
        for y, tile in enumerate(row):
            world_data[x][y] = int(tile)
print(world_data)

world = World()
player, health_bar = world.process_data(world_data)

run = True
while run:
    clock.tick(fps)
    draw_bg()
    world.draw()
    health_bar.draw(player.health)
    # show ammo
    draw_text("AMMO:", font, WHITE, 10, 35)
    for x in range(player.ammo):
        screen.blit(bullet_img, (90 + (x * 10), 40))
    # show grenade
    draw_text("GRENADES: ", font, WHITE, 10, 65)
    for x in range(player.grenades):
        screen.blit(grenade_img, (130 + (x * 15), 66))
    player.update()
    player.draw()
    for enemy in enemy_group:
        enemy.ai()
        enemy.update()
        enemy.draw()

    # update and draw groups
    bullet_group.update()
    grenade_group.update()
    explosion_group.update()
    item_box_group.update()
    decoration_group.update()
    water_group.update()
    exit_group.update()
    bullet_group.draw(screen)
    grenade_group.draw(screen)
    explosion_group.draw(screen)
    item_box_group.draw(screen)
    decoration_group.draw(screen)
    water_group.draw(screen)
    exit_group.draw(screen)

    # update player actions, 1 is run, 0 = idle, 2 = in air
    if player.alive:
        # shoot bullet
        if shoot:
            player.shoot()
        elif grenade and grenade_thrown == False and player.grenades > 0:
            grenade = Grenade(player.rect.centerx + (0.5 * player.rect.size[0] * player.direction),
                              player.rect.top, player.direction)

            grenade_group.add(grenade)
            # reduce grenades
            player.grenades -= 1
            grenade_thrown = True

        if player.in_air:
            player.update_action(2)
        elif moving_left or moving_right:
            player.update_action(1)
        else:
            player.update_action(0)
        screen_scroll = player.move(moving_left, moving_right)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False
        # keyboard presses
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_a:
                moving_left = True
            if event.key == pygame.K_d:
                moving_right = True
            if event.key == pygame.K_SPACE:
                shoot = True
            if event.key == pygame.K_q:
                grenade = True
            if event.key == pygame.K_w and player.alive:
                player.jump = True
            if event.key == pygame.K_ESCAPE:
                run = False
        # keyboard button released
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_a:
                moving_left = False
            if event.key == pygame.K_d:
                moving_right = False
            if event.key == pygame.K_SPACE:
                shoot = False
            if event.key == pygame.K_q:
                grenade = False
                grenade_thrown = False

    pygame.display.update()
pygame.quit()

i have looked at this code for days but cant seem to find out the problem exactly. so, the question once again is how to properly arrange the enemies on the screen at their various predefined positions and not directly on top of my player.


text:
Q: Rss Feeds Not Working I am using the following google api to get feeds.
http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&output=json&q=<URLHERE>

In my case query is
http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&output=json&q=https://www.youtube.com/channel/UCP2UBhhA2k32TM8YiJkUTBg/feed

No data coming for this only message coming:
{"responseData": null, "responseDetails": "Feed could not be loaded.", "responseStatus": 400}

What is wrong with the link?

A: You'd hit the wrong URL. The Google feed service needs some kind of RSS input, you just provided a ordinary HTML page. I've looked upon the right feed url
So the full url is:
http://ajax.googleapis.com/ajax/services/feed/load?v=1.0&num=10&output=json&q=https://gdata.youtube.com/feeds/api/users/UCP2UBhhA2k32TM8YiJkUTBg/uploads?alt=rss

redpajama_set_name: RedPajamaStackExchange


text:
Q: NHibernate Linq .Contains code generation has bug? I'm trying to achieve:
select StoreId, StoreName from Store where StoreId in (
     select StoreId from Employee where EmployeeName = 'Steve Jobs')

I have this code:
public class Store
{
  public virtual int StoreId { get; private set; }
  public virtual string StoreName { get; set; }

  public virtual IList<Employee> Staff { get; set; }
}

public class Employee
{
  public virtual Store Store { get; set; }

  public virtual int EmployeeId { get; private set; }
  public virtual string EmployeeName { get; set; }
}

var q = from s in session.Query<Store>()
        where
            (from e in session.Query<Employee>()
            where s.EmployeeName == "Steve Jobs"
            select e.Store.StoreId).Contains(s.StoreId)
        select s;

NHibernate generates this (aliases stripped):
    select s.StoreId, s.StoreName
    from Store s
    where exists
        (
            select t.StoreId
            from Employee e
            left join Store t on t.StoreId = e.StoreId
            where e.EmployeeName = 'Steve Jobs'

                -- wrongly generated code
                and t.EmployeeId = s.StoreId

        )

Linq-toSql generates the code correctly:
    select s.StoreId, s.StoreName
    from Store s
    where exists
        (
            select null
            from Employee e
            where e.EmployeeName = 'Steve Jobs'
                and e.StoreId = s.StoreId

        )

Is there a problem with subquery code generation on Linq to NHibernate?
However, HQL works:
var q = session.CreateQuery("from Store as s where s.StoreId in (select e.WorkingInStore.StoreId from Employee as e where e.EmployeeName = 'lennon')").List<Store>();

A: Certainly looks like a bug, but I think you're overcomplicating the whole query. As I understand, you want all stores where an employee named Steve Jobs is on the payroll. Try:
var q = from s in session.Query<Store>()
        where s.Staff.Any(e=>e.EmployeeName == "Steve Jobs")

This should generate the query you want, and it's much cleaner and more readable than the subquery.

A: I answered a similar question in this post.  Instead of using Contains() operator, we can tweak the subquery a little bit and use Any() operator instead.
LINQ to NHibernate WHERE EXISTS IN


text:
Q: Check if the lastest entry in my table is between two dates in sequelize I have a User model and an Order model which has a createdAt column.
Order belongs to User.
I want to get all the users where the most recent order (based on createdAt) is between two dates.
Is it possible with Sequelize?


text:
Q: Can the word 'pre-order' be used for an item already in production? As I understand it the term pre-order refers to ordering an item that hasn't been released yet, probably as a concatenation of pre-release order.  However I just received an email from Farnell Element14 inviting me to pre-order my Raspberry Pi.  Now as I understand it, these machines are already in production and limited release; a lot of people have already received theirs.
Shouldn't the company in this instance have invited me to simply order my copy at this point, even if the estimated dispatch time is a couple of months away, or does the term pre-order have a different meaning in this context?

A: A pre-order is made before the item is available to send out to the customer.
It doesn't matter if they're still on the drawing board, being prototyped, or being manufactured, or being sent to the shops.
As soon as the item is ready to be sent out to the customer, you order instead of pre-order.
The OED's first quotation is from 1957 and defines pre-order as:

The placing of an order before an item is available or required; an order of this type, an advance order.

A: Strictly speaking, you are being asked to pre-order from this company, and the term actually refers to ordering product before the supplier has received any*. So the fact that they are already out and available is not relevant, because this particular supplier has not so far received any.
Slightly more generally, they are out and on, as you say, limited release. So this is an opportunity to order one from the publicly available stock before that has been formally released. It is marketing (as @mhoran_psprep says), but it also means that they cannot give you a delivery date yet for it. However, they would like your money.
*or, alternatively, before they have a definite delivery date or quantity. Basically, they do not yet have the supply stream set up, so it is at your own risk.

A: Because there is a delay between your order, and the shipment, they are asking you to start the process early. One reason they want you to order now, is to lock in sales before the first shipment to them arrives. This eliminates risk, that they will go unsold, or the risk that they won't order enough.
They are using marketing practices to say, we like you so pre-order with us now. We promise to deliver the product from the first batch we get. The use of the term pre-order makes it seem more special, or more of a perk. It is nothing more than marketing.


text:
Q: Meaning of the phrase "dipole moment of the combination" Here is a question I came across in a book:

Three point charges $-q$,$-q$ and $2q$ are placed on the vertices of an equilateral triangle of side length $d$ units.What is the dipole moment of the combination?

I had learnt that the dipole moment is defined for 2 point charges only with equal magnitudes but opposite character.I am in a bit of a fix regarding what the author means by that phrase in bold.Thank you in advance!
Edit:I just noticed theoretical physics has been merged here;I sincerely apologise if the question is unbearably stupid.

A: Dipole moment is a vector and can be calculated using formula
$$\vec{p} = \sum_i q_i \vec{r}_i.$$
It can be shown easily using the formula above that in case of two charges separated by distance $d$
$$\vec{p} = q \vec{d},$$
where vector $\vec{d}$ goes starts at negative ends at positive charge.
http://en.wikipedia.org/wiki/Electric_dipole_moment#Dipole_moment_density_and_polarization_density

A:
I had learnt that the dipole moment is defined for 2 point charges only with equal magnitudes but opposite character.

Actually, that is not the case. You can calculate a dipole moment for any charge distribution.
In fact, the dipole moment is just one of a whole series of multipole moments which can be used to describe a charge distribution.

*

*The monopole moment $$q = \sum_i q_i$$

*The dipole moment $$\vec{p} = \sum_i q_i \vec{r}_i$$

*The quadrupole moment $$\overset{\leftrightarrow}{Q} = \sum_i q_i(3 \vec{r}_i \otimes \vec{r}_i - r_i^2)$$

and so on. These moments are kind of analogous to the coefficients of a Taylor series expansion.
It turns out that if you take a positive point charge and a negative point charge of equal magnitude and bring them infinitesimally close together, then the resulting charge distribution (called a dipole) has only a dipole moment. All the other multipole moments are zero. That's where the dipole moment gets its name. You've been taught that you can calculate a dipole moment for a system of two charges because that is the simplest way to create a charge distribution with a dipole moment. But it is not the only way.


text:
Q: Porting windows batch file to shell script. If possible execute the task in parallel I have this windows based version which opens my current tasks in multiple thread. Though, it opens multiple threads yet acceptable.
I want to port this to Linux? I have limited knowledge of Linux and hence hoping for someone to help here.
clean.bat
ant -DCorrelator.port="15800" clean

*start_parallel.bat*
call clean.bat
start "Engine 1500" ant -Dengine.port="15800" -Dfamily.one="true" -Dfamily.two="false" start
start "Engine 1505" ant -Dengine.port="15805" -Dfamily.one="false" -Dfamily.two="true" start

A: I have to admit, I am not sure I fully understand your scenario, but to run tasks in parallel in linux, you can put them in the backgrund using &.
Example:
start "Engine 1500" ant start &
start "Engine 1505" ant start &

To call your other script, simply execute it from your first shell script.
So in total you would have:
clean.sh:
#!/bin/sh
ant -DCorrelator clean

start_parallel.sh
#!/bin/sh
clean.sh
start "Engine 1500" ant -Dengine.port="15800" -Dfamily.one="true" -Dfamily.two="false" start &
start "Engine 1505" ant -Dengine.port="15800" -Dfamily.one="false" -Dfamily.two="true" start &

Make sure you make both scripts executable using chmod:
chmod +x clean.sh
chmod +x start_parallel.sh

And Linux only looks in your path (echo $PATH) for executable scripts. If you want to execute scripts in a different directory, you have to give at least its relative path. If the script is in your current directory do:
./start_parallel.sh

And you would also have to call clean.sh as ./clean.sh in your script. To avoid this, I suggest you put the scripts into a directory in your path, usually /usr/local/bin/ or create a bin directory in your home directory and add that to your path using for example.profile`.
Cheers.

A: clean.sh
#!/bin/bash
# Note: The header above is only necessary if you intend to call the script as standalone as well.
ant -DCorrelator.port="15800" clean

start_parallel.sh
#!/bin/bash
source ./clean.sh
konsole -p tabtitle="Engine 1500" -e ant -Dengine.port="15800" -Dfamily.one="true" -Dfamily.two="false" start
konsole -p tabtitle="Engine 1505" -e ant -Dengine.port="15805" -Dfamily.one="false" -Dfamily.two="true" start

It works with konsole but I'll try to update with other terminals.
Run with bash start_parallel.sh.
Update for XTerm
...
xterm -T "Engine 1500" -e ant -Dengine.port="15800" -Dfamily.one="true" -Dfamily.two="false" start &
xterm -T "Engine 1505" -e ant -Dengine.port="15805" -Dfamily.one="false" -Dfamily.two="true" start &


text:
Q: LogNormal Distribution I was replaying the next plot in Mathematica

For that I used the next code line
Plot[PDF[LogNormalDistribution[18.3, 8.8], x] // Evaluate, {x, 0, 40},
  Frame -> True, PlotRange -> All, PlotStyle -> Blue,
 PlotLabel -> "Times distribution ",
 FrameLabel -> {"days", "probability"}]

But the plot is very different:

What is it happening?

A: dist = LogNormalDistribution[m, s];

Given the mean and standard deviation, the underlying parameters {m, s} are
param = NSolve[{Mean[dist] == 183/10,
    StandardDeviation[dist] == 88/10, s > 0},
   {m, s}, Reals][[1]]

(* {m -> 2.80289, s -> 0.456094} *)

Plot[PDF[dist /. param, x] // Evaluate, {x, 0, 40},
 Frame -> True,
 PlotRange -> All,
 PlotStyle -> Blue,
 PlotLabel -> "Times distribution ",
 FrameLabel -> {"days", "probability"}]


text:
Q: Cordial saludo, soy nueva en C# ,no se porque no me aparece nada en la consola Cuando intento ejecutar mi codigo ,aparece 0 errores,pero aun asi no me imprime nada en la consola:
este es mi código:
static String recibirCa(String texto){
  String contenido = "textos";
  recibirCa(contenido);
  Console.WriteLine("contenido");
  return contenido;
}

A: El problema es que estás llamando el método recibirCa(String texto) recursivamente, posiblemente tengas un error del tipo StackOverflowException que impide la impresión del texto, debes eliminar su llamado dentro del mismo método.
static String recibirCa(String texto){
  String contenido = texto;
  //recibirCa(contenido);
  Console.WriteLine(contenido);
  return contenido;
}

Recuerda que para escribir en la ventana de salida (Output), también puedes usar Debug.WriteLine():
System.Diagnostics.Debug.WriteLine("Hola Dahiana!");

A: Veo que estas en net6.0 donde La plantilla de aplicación de consola de C# de .NET 6 genera instrucciones de nivel superior. Ten en cuenta eso.
Creo que lo que intentas hacer es algo como esto:
recibirCa("algun texto");

static void recibirCa(String texto)
{

    Console.WriteLine(texto);

}

Aunque si lo que quieres es que tu función devuelva una cadena sería así:
Console.WriteLine(recibirCa("algún texto"));

static string recibirCa(String texto)
{
    return texto;
}

Pero eso no tendría mucho sentido ya que nos estaría devolviendo el mismo dato que le pasamos como argumento. Normalmente dentro de la función realizamos algún procedimiento con los argumentos que nos pasan. Un simple ejemplo sería añadir un poco mas de texto así:
Console.WriteLine(recibirCa("algún texto"));

static string recibirCa(String texto)
{

    return texto + "texto adicional";
}


text:
Q: How to put a file text into a two dimensional array in bash or python I am working on a bash script and so far this is what I want to do;
Let's say that i have a file.txt
This Is
The File
Text That
I Am
Referring To
I want to make my script to print out using a variable the first column
This
The
Text
I
Referring
Also another variable to print the second column
Is
File
That
Am
To
I want to put the two different output into an array so I can call it whenever I want
Can you please help me?

A: For a file sample.txt
This Is
The File
Text That
I Am
Referring To

the command
$ cut -d' ' -f1 sample.txt
outputs the following to the standard output.
This
The
Text
I
Referring

and the command (with -f2)
$ cut -d' ' -f2 sample.txt
outputs the following
Is
File
That
Am
To

Maybe you can modify them to store the result to an array.

With python, you can get a 'list of list' which may be used somewhat like a 2D array as following
nice_list=[line.split() for line in open('sample.txt','r')]

For example, the following script
#!/usr/bin/env python

fname='sample.txt'
nice_list=[line.split() for line in open(fname,'r')]

numrow=len(nice_list)

print '----------------'
print 'first column:'
for jrow in range(numrow):
    print nice_list[jrow][0]

print '----------------'
print 'second column:'
for jrow in range(numrow):
    print nice_list[jrow][1]

outputs
----------------
first column:
This
The
Text
I
Referring
----------------
second column:
Is
File
That
Am
To


text:
Q: Nginx letsencrypt certbot ssl page will not load over https but will load over http I am trying to set up a digital ocean server using this tutorial https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-16-04
The site is served just fine over HTTP but will not load from https.
(will not load references this chrome error)
This site can't be reached kronoswebsolutions.com took too long to respond.
Try:

Checking the connection
Checking the proxy and the firewall
ERR_CONNECTION_TIMED_OUT

As advised I did check the firewall previous to posting but here is the output of my ufw. I do not have a firewall enabled on my digital ocean droplet web gui.
Nginx Full                 ALLOW       Anywhere
22                         ALLOW       *************
22                         ALLOW       *************
OpenSSH                    ALLOW       Anywhere
Nginx Full (v6)            ALLOW       Anywhere (v6)
OpenSSH (v6)               ALLOW       Anywhere (v6)

Here is the results of nmap from my local machine using the ip of my server...

nmap -Pn -p 443 IPADDRESS
Starting Nmap 7.70 ( https://nmap.org ) at 2019-05-07 23:46 MDT
Nmap scan report for IPADDRESS
Host is up.

PORT    STATE    SERVICE
443/tcp filtered https

I am using Debian stretch rather than Ubuntu.

A: Looks like it was definitely a firewall issue.
I used this to reset my firewalls settings in iptables then set ufw up again and it is working.
First, set the default policies for each of the built-in chains to ACCEPT. The main reason to do this is to ensure that you won't be locked out from your server via SSH:
$ sudo iptables -P INPUT ACCEPT
$ sudo iptables -P FORWARD ACCEPT
$ sudo iptables -P OUTPUT ACCEPT

Then flush the nat and mangle tables, flush all chains (-F), and delete all non-default chains (-X):
$ sudo iptables -t nat -F
$ sudo iptables -t mangle -F
$ sudo iptables -F
$ sudo iptables -X

Then re enable ufw
$ sudo ufw enable

A: I was having the same issue after following this tutorial and it turns out that it misses this piece of code that you have to add to your site's nginx.conf:
listen [::]:443 ssl ipv6only=on; # managed by Certbot
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/{{ domain }}/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/{{ domain }}/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot


text:
Q: UITableView non-using Navigation control Can I not use Navigation control to switch my UIViewController?
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
 [tableView deselectRowAtIndexPath:indexPath animated:NO];
 BATTrailsViewController *trailsController = [[BATTrailsViewController alloc] initWithStyle:UITableViewStylePlain];
 trailsController.selectedRegion = [regions objectAtIndex:indexPath.row];

 [[self navigationController] pushViewController:trailsController animated:YES];
}

Can I do this without using [[self navigationController] pushViewController:trailsController animated:YES];??
I want my UITableView selectrow to a new UIViewController without navigation.

A: try using
[self presentViewController:animated:completion];

Hope this helps.


text:
Q: Any way to speed up CreateIfNotExists in Entity Framework? I'm using EF 4.3 Code First on SQL Server 2008. I run several test suites that delete and recreate the database with CreateIfNotExists. This works fine but is dog slow. It can take up to 15 seconds to create the database on the first call, and typically 3-6 seconds after that. I have several places where this is called. I've already optimized to call this as few times as I can. Is there something I can do to speed up database creation programmatically? I'm willing to go around EF to do this if that helps, but I would like to keep my database build in code and not go back to a SQL script. Thanks!

A:
This works fine but is dog slow.

Yes. The point is to use the real database only for integration tests which don't have to be executed so often and the whole set of integration tests is usually executed only on build server.

It can take up to 15 seconds to create the database on the first call

This is because of slow initialization of EF when unit testing (you can try to switch to x86). The time is also consumed by view generation. Views can be pre-generated which is usually done to reduce startup and initialization of the real system but in case of speeding up unit tests using view pre-generation will not help too much because you will just move the time from test to build.

I'm willing to go around EF to do this if that helps, but I would like to keep my database build in code and not go back to a SQL

Going around would just mean using plain old SQL script. The additional time needed for this operation is may be spent in generating that SQL. I think the SQL is not cached because normal application execution normally doesn't need it more than once but you can ask EF to give you at lest the most important part of that SQL, cache it somewhere and execute it yourselves every time you need it. EF is able to give you SQL for tables and constraints:
var dbSql = ((IObjectContextAdapter) context).ObjectContext.CreateDatabaseScript();

You just need to have your own small SQL to create database and use them together. Even something like following script should be enough:
CREATE DATABASE YourDatabaseName

USE YourDatabaseName

You must also turn off database generation in code first to make this work and to take control over the process:
Database.SetInitializer<YourContextType>(null);

When executing database creation SQL you will need separate connection string pointing to Master database.


text:
Q: Can't import installed scala/sbt library dependency from github I need to install some dependencies in my simplest scala project (I am passing some tutorial) and one of them is from github. My build.sbt looks like this:
import sbt._

lazy val root = Project("root", file("."))
    .dependsOn(smile)
    .settings(
        name := "Xyclade ML practical examples",
        version := "1.0",
        scalaVersion := "2.10.6",
        sbtVersion := "0.13.9",
        libraryDependencies += "org.scala-lang" % "scala-swing" % "2.10.2"
    )

lazy val smile = ProjectRef(uri("https://github.com/haifengl/smile.git#master"), "root")

Maybe, I am missing some basic scala/sbt knowledge (I am a complete noob), but:
1) import com.github.haifengl._ fails with object github is not a member of package com
2) import smile._ leads to error not found: object smile
And as far as I found out, the library package should be called something like com.github.haifengl: https://github.com/haifengl/smile/search?utf8=%E2%9C%93&q=com.github.haifengl&type=Code

A: Are you sure package com.github.haifengl is in github project you've mentioned? Could it be in some of it's dependencies?
You should not add ProjectRef to github project, instead you'd better add it to dependencies:
"com.github.haifengl" % "smile-core" % "1.0.4"

Like following:
import sbt._

lazy val root = Project("root", file("."))
    .settings(
        name := "Xyclade ML practical examples",
        version := "1.0",
        scalaVersion := "2.10.6",
        sbtVersion := "0.13.9",
        libraryDependencies += Seq(
                "org.scala-lang" % "scala-swing" % "2.10.2",
                 "com.github.haifengl" % "smile-core" % "1.0.4"
    )


text:
Q: Urigo: Angular-Meteor: what sort of array is returned when subscribing Mongo Collection through $meteor.collection service I have subscribed to a MongoDB collection through $meteor service, What I get is an array of docs plus some methods embeded on the array.
But whenever I do JSON.stringify(subscribed_collection) only json docs are displayed?

A: The returned object of $meteor.collection is AngularMeteorCollection. here is a usage example from there:
$scope.notAutoTodos = $scope.$meteorCollection(Todos, false).subscribe("publicTodos");


text:
Q: Using libCurl to POST adds unknown header and footer I'm using libCurl in c++ to make a POST request of an xml file to my server. The post works, I receive the xml on my server. However the xml also has a strange header & footer around the xml:
------------------------------b6966127f870Content-Disposition: form-data; name="myName"; filename="myFile.xml"Content-Type: application/xml<CORRECT XML FILE HERE>------------------------------b6966127f870--

What is this header/footer?
Can I get rid of it? Or should I just parse around it?
Is curl adding these?
Here are the relevant curl calls I make to post the xml file.
void CurlUtils::postFileToURL(const char* const inFile,
                              const char* const urlString)
{
  // Setup
  CURL* const curl = curl_easy_init();
  curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
  curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);

  // Post
  struct curl_httppost* post = NULL;
  struct curl_httppost* last = NULL;
  curl_formadd(&post, &last,
               CURLFORM_COPYNAME, "myName",
               CURLFORM_FILE, inFile,
               CURLFORM_END);
  curl_easy_setopt(curl, CURLOPT_URL, urlString);
  curl_easy_setopt(curl, CURLOPT_HTTPPOST, post);
  curl_easy_perform(curl);

  // Cleanup ...
}

A: You're using CURLOPT_HTTPPOST which makes a multipart formpost to the server. A multipart formpost is a series of parts with MIME style separators and a set of headers for each part, exactly what you see there.
If you want a plain POST without the multipart stuff, use CURLOPT_POSTFIELDS or set a read callback and use CURLOPT_POST.


text:
Q: cannot parse hibernate.cfg.xml I am new to hibernate .. and I am facing some basic problems :
My xml is
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<?xml version='1.0' encoding='utf-8'?>
<hibernate-configuration
    xmlns="http://www.hibernate.org/xsd/hibernate-configuration"
    xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-configuration hibernate-configuration-4.0.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/database</property>
<property name="connection.username">user</property>
<property name="connection.password">user123</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache  -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping class="hibernateDTO.StudentDetails"/>
</session-factory>
</hibernate-configuration>

I have written 2 classes one which is entity class and other with a main method to store / read operations.
I am using hibernate 4 and once I run my class I get exception
Nov 13, 2014 10:58:58 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {4.3.7.Final}
Nov 13, 2014 10:58:58 PM org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
Nov 13, 2014 10:58:58 PM org.hibernate.cfg.Environment buildBytecodeProvider
INFO: HHH000021: Bytecode provider name : javassist
Nov 13, 2014 10:58:58 PM org.hibernate.cfg.Configuration configure
INFO: HHH000043: Configuring from resource: /hibernate.cfg.xml
Nov 13, 2014 10:58:58 PM org.hibernate.cfg.Configuration getConfigurationInputStream
INFO: HHH000040: Configuration resource: /hibernate.cfg.xml
Exception in thread "main" org.hibernate.HibernateException: Could not parse configuration: /hibernate.cfg.xml
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2165)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2077)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2056)
at hibernateTest.Hirbernate.main(Hirbernate.java:20)
Caused by: org.dom4j.DocumentException: Error on line 5 of document  : The processing instruction target matching "[xX][mM][lL]" is not allowed. Nested exception: The processing instruction target matching "[xX][mM][lL]" is not allowed.
    at org.dom4j.io.SAXReader.read(SAXReader.java:482)
    at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2157)
    ... 3 more

My jars are
hibernate-entitymanager-4.3.7.Final
antlr-2.7.7
dom4j-1.6.1
hibernate-commons-annotations-4.0.5.Final
hibernate-core-4.3.7.Final
hibernate-jpa-2.1-api-1.0.0.Final
jandex-1.1.0.Final
javassist-3.18.1-GA
jboss-logging-3.1.3.GA
jboss-logging-annotations-1.2.0.Beta1
jboss-transaction-api_1.2_spec-1.0.0.Final
and mysql-connector-java-5.1.33-bin
am I missing out in jars or have wrong jars?

A: You need to put your XML processing instruction above your DOCTYPE declaration, so to get rid of the XML parsing error, the start of your file should look like this:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

Second problem: you're referencing both a DTD file (for Hibernate version 3) and an XML schema (for version 4). You should probably get rid of the DOCTYPE declaration altogether.

A: First, the first line in all XML file, must be something similar to:
<?xml version='1.0' encoding='utf-8'?>

So, you can try the next:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
  <session-factory>
    <!-- Database connection settings -->
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/database</property>
    <property name="connection.username">user</property>
    <property name="connection.password">user123</property>
    <!-- JDBC connection pool (use the built-in) -->
    <property name="connection.pool_size">1</property>
    <!-- SQL dialect -->
    <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
    <!-- Enable Hibernate's automatic session context management -->
    <property name="current_session_context_class">thread</property>
    <!-- Disable the second-level cache  -->
    <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
    <!-- Echo all executed SQL to stdout -->
    <property name="show_sql">true</property>
    <!-- Drop and re-create the database schema on startup -->
    <property name="hbm2ddl.auto">create</property>
    <mapping class="hibernateDTO.StudentDetails"/>
  </session-factory>
</hibernate-configuration>

See also XML Validator online and Hibernate Configuration in www.tutorialspoint.com

A: do it like
 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

        <hibernate-configuration>
        <session-factory>

the problem you have done is you  have again defined namespaced in hibernate-configuration tag.
    <!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<?xml version='1.0' encoding='utf-8'?>
<hibernate-configuration
    xmlns="http://www.hibernate.org/xsd/hibernate-configuration"
    xsi:schemaLocation="http://www.hibernate.org/xsd/hibernate-configuration hibernate-configuration-4.0.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<session-factory>


text:
Q: How to view NFC tag object in raw format I read about the Tag object in the NFC basics of Android API guide. I then added this enter link description here project to my Eclipse environment, and can run it on Samsung Note. I now want to view the Tag object that is created in the code. I have marked the code I have added to the existing code. I am not sure if did it correctly. Is there anyway I can see what is inside of the Tag object I have in the code? I did try adding a breakpoint, and looked at what I have in variables, but I don't see a variable called tag. Here is the code from the source:
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Log.d(TAG, "onCreate");

    setContentView(R.layout.main);

    // initialize NFC
    nfcAdapter = NfcAdapter.getDefaultAdapter(this);
    nfcPendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, this.getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);

    // Register Android Beam callback
    nfcAdapter.setNdefPushMessageCallback(this, this);
    // Register callback to listen for message-sent success
    nfcAdapter.setOnNdefPushCompleteCallback(this, this);
    /***********************************
     * I added this portion of the code myself to view the tag object
     ***************************/
    Intent intent = new Intent(NfcAdapter.ACTION_TAG_DISCOVERED);
    intent.putExtra(NfcAdapter.EXTRA_TAG, "");
    Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
    //************************************************************
    if(getIntent().hasExtra(NfcAdapter.EXTRA_TAG)) {
        TextView textView = (TextView) findViewById(R.id.title);
        //textView.setText("Hello NFC tag from home screen!");
        textView.setTag(tag);
    };

    printTagId(getIntent());
}

A: The Tag object is a handle that points the Android NFC service to communicating with the right tag. It does not contain much information about the tag, other than what communication technologies thwe tag was detected to support and the tags ID (as used during the enumeration or anti-collision phase of the communication protocol). You can get that information using the getTechList() method (for the supported communication technologies) and getId() method (for the tag's identifier).
Other that that, the Tag object itself does not contain any information about the structure or contents of a tag. So there is nothing to "view" in the Tag object. In fact it is even a bit more complicated than that:
A contactless token can be either a pure memory card (which provides certain commands to read and write data) or can be a processor smartcard (which contains applications that can be interfaced by smartcard commands). With current standardized (by the NFC Forum) NFC tags, there are four different tag types. They differ in communication protocol and memory layout. One of them can even be based on top of a processor smartcard. Besides those standardized tag types, there also exist several NFC-compatible tag types that also differ in memory layout and communication protocol.
So, if you wan to retrieve the structure and data of a tag, you would need to implement that tag's specific communication protocol (and sometimes you even need to know the exact memory layout).
There is however an exception to that: There exists an abstraction layer for NFC tags: NDEF (NFC Data Exchange Format). Current NFC devices typically implement this abstraction layer for at least the four standardized tag types. If your tag is supported (you can find this by browsing the tag technology list or by simply trying to get an instance with Ndef.get(tag)), you can get the tag's NDEF contents by using the methods of an Ndef instance for your Tag object.
Btw. the getTag()/setTag() methods of various Android UI elements are completely unrelated to NFC tags. So it does not make much sense to store a tag handle with them.


text:
Q: How do I disable field name in logrus while logging to file I am using logrus in golang to log to file. Right now, logrus is logging to file with field name.
ie
time="26-03-2017 03:37:58" level=error msg="Not fatal. An error. Won't stop execution"
How do I remove the field names so that the log entry becomes
ERRO 26-03-2017 03:37:58 Not fatal. An error. Won't stop execution
like how it behaves in case of stderr?

A: Here's how to get what you requested:
package main

import (
    log "github.com/sirupsen/logrus"
    "fmt"
)

type PlainFormatter struct {
    TimestampFormat string
    LevelDesc []string
}

func (f *PlainFormatter) Format(entry *log.Entry) ([]byte, error) {
    timestamp := fmt.Sprintf(entry.Time.Format(f.TimestampFormat))
    return []byte(fmt.Sprintf("%s %s %s\n", f.LevelDesc[entry.Level], timestamp, entry.Message)), nil
}

func main() {
    plainFormatter := new(PlainFormatter)
    plainFormatter.TimestampFormat = "2006-01-02 15:04:05"
    plainFormatter.LevelDesc = []string{"PANC", "FATL", "ERRO", "WARN", "INFO", "DEBG"}
    log.SetFormatter(plainFormatter)
    log.Errorln("Not fatal. An error. Won't stop execution")
    log.Infoln("Just some info")
}

*

*Create the PlainFormatter struct (with timestamp format and level fields)

*Create a Format function/method (where your struct is the receiver)

*Set logrus to use your custom formatter

Output:
ERRO 2017-07-01 18:22:21 Not fatal. An error. Won't stop execution
INFO 2017-07-01 18:22:21 Just some info

In my book Learn Functional Programming in Go book you can see a more practical example of how you can manipulate your application logger in Adding Functionality with Decoration chapter.

A: You need to write a custom formatter that emits only the fields you want to see.
There is an example in the logrus readme:
type MyJSONFormatter struct {
}

log.SetFormatter(new(MyJSONFormatter))

func (f *MyJSONFormatter) Format(entry *Entry) ([]byte, error) {
  // Note this doesn't include Time, Level and Message which are available on
  // the Entry. Consult `godoc` on information about those fields or read the
  // source of the official loggers.
  serialized, err := json.Marshal(entry.Data)
    if err != nil {
      return nil, fmt.Errorf("Failed to marshal fields to JSON, %v", err)
    }
  return append(serialized, '\n'), nil
}


text:
Q: Many simple ternary operator and one if-else, which one should I use? For example, suppose I have a toggle button listener, and it has some tasks to do according to the state of toggle:
style 1 : use many ternary operator:
tutorialModeToggle(isTutorialOn){
    SoundUtility.play(isTutorialOn?"s1.mp3":"s2.mp3");
    this.titleLabel.setString(isTutorialOn?"(Tutorial Mode)":"");
    this.tutorialLayout.opacity=isTutorialOn?255:128;
    isTutorialOn?this.playAnimation1():this.playAnimation2();
    .
    .
    .
}

style 2: use a single if-else:
tutorialModeToggle(isTutorialOn){
    if(isTutorialOn){
        SoundUtility.play("s1.mp3");
        this.titleLabel.setString("(Tutorial Mode)");
        this.tutorialLayout.opacity=255;
        this.playAnimation1();
        .
        .
        .
    }else{
        SoundUtility.play("s2.mp3");
        this.titleLabel.setString("");
        this.tutorialLayout.opacity=128;
        this.playAnimation2()
        .
        .
        .
    }
}

Which one should I use?
Note: I'm not asking about
Ternary operator considered harmful?
Should the ternary operator be used outside of assignment statements?
because they are about ONE ternary operator VS ONE if-else, but I'm asking about MANY ternary operator vs ONE if-else.
Also I'm not asking about
Style for control flow with validation checks
because those question is about MULTIPLE condition check but I'm asking about ONE condition check

A: I your language supports it, I'd suggest a third way: use a tuple, or your language's equivalent. This avoids the need for the code repetition with if/else and avoids testing isTutorialOn multiple times:
tutorialModeToggle(isTutorialOn) {
    (sound, title, opacity, playAnimation) = isTutorialOn
        ? ("s1.mp3", "(Tutorial Mode)", 255, this.playAnimation1)
        : ("s2.mp3", "", 128, this.playAnimation2);

    SoundUtility.play(sound);
    this.titleLabel.setString(title);
    this.tutorialLayout.opacity = opacity;
    playAnimation();
    .
    .
    .
}

A: This is completely arbitrary. When you have a grid of n×m items, it is not important if you order these by the first axis or the second axis in the grid. Here, your two axes are:

*

*Whether the condition is true or false.

*The different settings affected by the condition.

Since the choice is arbitrary, it might be better to keep related things close together. But whether the settings within a condition or the two values of one setting are more closely related, is primarily your opinion.
Note that if you consider the distinction by the condition more important, you may be able to avoid the condition by using object oriented techniques. E.g. you could use the State Pattern to switch between normal mode and tutorial mode, compare also the "replace conditionals with polymorphism" refactoring technique.

A: You should use the if/else. It only evaluates the bool once, which isn't only a teeny performance win but also makes your code more robust in the face of race conditions.
And despite recent backlashes against imperative code, a basic un-nested if/else is easy to read and easy to maintain and easier to debug, even for beginner programmers.


text:
Q: How to fadeout header in list view like whatsapp i want to fadeout a first visible header in a stickyheaderlistview (lib) . how do i fadeout the first visible header in a list view. please give me some example. thank you. if you observe the date header it will hide if there is no user interaction after some time

A: Compile this:
compile 'se.emilsjolander:stickylistheaders:2.1.3'

In your adapter
public class ChatAdapter extends BaseAdapter implements StickyListHeadersAdapter {

    private Activity mActivity;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    private SimpleDateFormat dateformat = new SimpleDateFormat("hh:mm a");
    private SimpleDateFormat format1 = new SimpleDateFormat("ddMMyyyy");
    private SimpleDateFormat headerdateformat = new SimpleDateFormat("dd MMMM yyyy");
    private Date date = null;
    private String msgDate = "";
    private Date headerDate = null;
    private String msgHeader = "";
    private String msg = "";
    private String mName = "";
    private int day = 0;
List<GroupChatHistoryData> mChatArrayList = new ArrayList<>();

    public ChatAdapter(Activity mActivity,List<GroupChatHistoryData> mChatArrayList) {
        this.mActivity = mActivity;
this.mChatArrayList = mChatArrayList;
    }

    @Override
    public int getCount() {
        return mChatArrayList.size();
    }

    @Override
    public Object getItem(int position) {
        return mChatArrayList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final ViewHolder holder;

        if (convertView == null) {

            LayoutInflater inflater = (LayoutInflater) mActivity.
                    getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            /****** Inflate tabitem.xml file for each row ( Defined below ) *******/
            convertView = inflater.inflate(R.layout.chat_details_row_item, null);

            holder = new ViewHolder();

            holder.receive_message_text = (TextView) convertView.findViewById(R.id.receive_message_text);
            holder.receive_message_date = (TextView) convertView.findViewById(R.id.receive_message_date);
            holder.receive_member_name = (TextView) convertView.findViewById(R.id.receive_member_name);
            holder.sent_message_date = (TextView) convertView.findViewById(R.id.sent_message_date);
            holder.sent_message_text = (TextView) convertView.findViewById(R.id.sent_message_text);

            holder.chat_receive_layout = (LinearLayout) convertView.findViewById(R.id.chat_receive_layout);
            holder.sent_msg_ll = (LinearLayout) convertView.findViewById(R.id.sent_msg_ll);

            convertView.setTag(holder);
        } else {
            holder = (ViewHolder) convertView.getTag();
        }

        final GroupChatHistoryData bean = mChatArrayList.get(position);

        try {
            if (bean.getTime() != null && !bean.getTime().equalsIgnoreCase("")) {
                date = format.parse(bean.getTime());
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (date != null) {
            msgDate = dateformat.format(date);
        }

        msg = bean.getMessage();

// your rest views

        return convertView;
    }

    @Override
    public View getHeaderView(int position, View convertView, ViewGroup parent) {
        final HeaderViewHolder holder;
        LayoutInflater inflater = LayoutInflater.from(mActivity);
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.chat_header, parent, false);
            holder = new HeaderViewHolder();

            holder.headerDate = (TextView) convertView.findViewById(R.id.header_date);

            convertView.setTag(holder);

        } else {
            holder = (HeaderViewHolder) convertView.getTag();
        }

        GroupChatHistoryData bean = mChatArrayList.get(position);

        try {
            if (bean.getDatetime() != null && !bean.getDatetime().equalsIgnoreCase("")) {
                headerDate = format1.parse(bean.getDatetime());
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        if (headerDate != null) {
            msgHeader = headerdateformat.format(headerDate);
        }

        if (show(msgHeader) == 0) {
            holder.headerDate.setText("TODAY");
        } else if (show(msgHeader) == -1) {
            holder.headerDate.setText("YESTERDAY");
        } else {
            holder.headerDate.setText(msgHeader);
        }

        return convertView;
    }

    private class HeaderViewHolder {
        private TextView headerDate;
    }

    @Override
    public long getHeaderId(int position) {
        String mDate = mChatArrayList.get(position).getDatetime();
        int mDatePos = Integer.parseInt(mDate);
        return mDatePos;
    }

    private class ViewHolder {
        TextView receive_message_text;
        TextView receive_message_date;
        TextView receive_member_name;
        TextView sent_message_date;
        TextView sent_message_text;

        LinearLayout chat_receive_layout;
        LinearLayout sent_msg_ll;
    }

    private int show(String time) {
        try {
            String outputPattern = "dd MMMM yyyy";
            SimpleDateFormat format = new SimpleDateFormat(outputPattern);

            Date Date1 = format.parse(getdate());
            Date Date2 = format.parse(time);
            long mills = Date2.getTime() - Date1.getTime();
            long Day1 = mills / (1000 * 60 * 60);

            day = (int) Day1 / 24;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return day;
    }

    private String getdate() {
        String time = "";
        try {
            String outputPattern = "dd MMMM yyyy";

            Calendar c = Calendar.getInstance();
            SimpleDateFormat df = new SimpleDateFormat(outputPattern);
            time = df.format(c.getTime());

        } catch (Exception e) {
            e.printStackTrace();
        }
        return time;
    }

}

chat_header.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp">

        <TextView
            android:id="@+id/header_date"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:background="#BDD9E4"
            android:gravity="center"
            android:padding="10dp"
            android:textAllCaps="true"
            android:textSize="12sp"
            android:textColor="@color/gray"
            android:textStyle="bold" />

    </RelativeLayout>

</RelativeLayout>

GroupChatHistoryData Bean something like this:
public class GroupChatHistoryData {

    private SimpleDateFormat headerdateformat = new SimpleDateFormat("ddMMyyyy");
    private Date headerDate = null;
    private Date mTime = null;
    private SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    private SimpleDateFormat timeformat = new SimpleDateFormat("hh:mm a");

    @SerializedName("user_id")
    @Expose
    private String userId;
    @SerializedName("group_id")
    @Expose
    private String groupId;
    @SerializedName("message")
    @Expose
    private String message;
    @SerializedName("datetime")
    @Expose
    private String datetime;
    @SerializedName("fname")
    @Expose
    private String fname;
    @SerializedName("time")
    @Expose
    private String time;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public String getGroupId() {
        return groupId;
    }

    public void setGroupId(String groupId) {
        this.groupId = groupId;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getDatetime() {

        String date = "";
        try {
            if (datetime != null && !datetime.equalsIgnoreCase("")) {
                headerDate = format.parse(datetime);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (headerDate != null) {
            date = headerdateformat.format(headerDate);
        }

        return date;
    }

    public void setDatetime(String datetime) {
        this.datetime = datetime;
    }

    public String getFname() {
        return fname;
    }

    public void setFname(String fname) {
        this.fname = fname;
    }

    public boolean isMine() {
        return isMine;
    }

    public void setMine(boolean mine) {
        isMine = mine;
    }

    public boolean isMine = false;

    public String getTime() {

        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

}

A: I think you should try ObservableScrollView.
https://github.com/ksoichiro/Android-ObservableScrollView


text:
Q: Conversion of VARCHAR to DATETIME I have a VARCHAR that holds datetime data in the following format:
15/04/2014 16:05

I need to convert this to datetime (with the exact format as before) but get an out of range error on the conversion:
CONVERT(DATETIME, @endDate, 108)

The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.
Could any advise the best way to successfully convert? Bear in mind i cannot change the source format and eventually need to compare the date to see if it is past the present day.

A: I think you want to use 103 instead of 108 for the final parameter.

A: Please use date constant values that are language/country independent
-- Independent constant (natural date)
DECLARE @END_DTE VARCHAR(20) = '20140415 16:05'

-- Show the result
SELECT CONVERT(DATETIME, @END_DTE, 108) AS FORMAT_DTE


text:
Q: Auto formatting a 100mb+ C++ file I have a 100mb auto generated C++ file with broken formatting that I want to autoformat (indentation primarily).
All editors I have tried either crash or do not allow autoformatting more than a few megabytes of text.
By auto formatting I mean indentation.
Beyond writing some custom code to do this how can I auto format 100mb C/c++ files?
I have tried:
VSCode
Visual Studio
Notepad++
Why do I need this?
We need to search the code for meta data (it is decompiled from assembly) and it makes it a lot easier to read if its indented properly.
We don't know ahead of time which parts of the code we need.. until we need it. It needs to be a single file to make it simpler to search for names/functions without constantly searching 1000s of individual files (if we did it per function).
The original C code would be millions of lines long which is why its so large

A: My first three recommendations are text editors, but I don't know if they'll work for you: 1) JEdit has a CLangBeauty plugin for reformatting source. 2) I assume Netbeans has a similar plugin, and can handle large files.  3) Then, there is QtCreator, which is available in a Windows version.  If you let it install Qt, it will be a large install, but I think you can do a custom install and just get the IDE; but it is very good at large files and can reformat them.  Just choose the Open Source Edition at the download.
Here's a page with a list of text editors than can open files gigabytes in size: "How to open Gigabyte-sized text files on Windows".  I've used glogg to view huge text files successfully; although it's features are minimalistic.
In order to reformat "C" and "C++" code, there is a handy utility "UniversalIndentGUI" that can call a number of code beautifiers/formatters.  It was lasted updated in 2012, though.  One of the command-line tools it can call is "Uncrustify".
Uncrustify is a command-line utility for reformatting code, and should be more memory efficient than the editor-based methods, as will be command-line code formatters in general. It is probably the most powerful at customizing the format it puts things in than the others.  It has recently been updated as of this writing. clang-format will probably also do it too.  These are command line utilities, so it's best to run them from a command prompt, call them in a pipe, or from an external GUI like UniversalIndentGUI; at least on Windows.  Uncrustify has a LOT of configuration options you can make.  I was also able to contact the author, and get him to add a feature for code formatting that I felt to be important.  Uncrustify should do it if none of the others will do.


text:
Q: Call a python script with flask: what is the best way? I am fairly new to flask and therefore I have a question regarding the logic behind my code and if my thought process makes sense.
I have an old python script, that takes a lot of data, processes it and then produces a plot with matplotlib. This works fine.
Now I want to build a web application, where a user selects specific input parameters, clicks the submit button, my server checks (with the help of sqlite) if there already exists a plot/the data to make the plot with those parameters, if yes then make it downloadable by the user.
If this plot/the data does not exist, my flask application calls my python script and the new plot/data for it will get created, uploaded to sqlite and then the user can download it from the web application.
As you can see in my code so far the python script is an external one and my plan is to not include it in my views from my flask app, does this make sense? Should I call an external script here or just copy the code directly to my views? (I wanted to avoid it so far since it's a pretty big script)
My logic so far looks like this:
# this part works well so far, I get the user input here and redirect it to the specific page
@app.route('/plot', methods = ['GET','POST'])
def get_plot():
    if request.method == 'POST':
        input1 = request.form['input1']
        input2 = request.form['input2']
        input3 = request.form['input3']
        return redirect('plot/{}/{}/{}/'.format(input1, input2, input3))
    else:
        return render_template('plot.html')

# here it get's a bit tricky for me
@app.route('/plot/<input1>/<input2>/<input3>/')
def create_plot(input1='1', input2='2', input3='3'):
    try:
        db = get_db(DB_PLOT)
        cur = db.execute('SELECT * FROM {} WHERE param1 = {} AND param2={}'.format(input1, input2, input3)) # get all the data from the table
    except:
        return "Plot not found !"
        # CALL THE EXTERNAL PYTHON SCRIPT HERE?
        cur = db.execute('SELECT * FROM {} WHERE param1 = {} AND param2={}'.format(input1, input2, input3)) # python script should have updated the database, so i can call the data here

    data = cur.fetchall()
    return render_template('show_plot.html', data=data)

Furthermore, I have another question:
As said my python script, which I've only ever used so far on its own, takes raw data, manipulates it and then creates a plot with matplotlib.
When I want to implement it in my web application, should I still create the plot with the python script, upload the plot to sqlite and then get the image from sqlite with the web application OR should I just upload the manipulated data, then download this data from sqlite and create the plot with flask?
In the end, I want to make it possible for the user to download the plot as .jpg and .pdf file.
Thank you so much!

A: You can use the subprocess module to achieve this. Depending on how long your script takes to generate the plot you should consider returning a page to the user asking him to refresh the page after some time until the plot is available (you could also auto refresh using javascript frequently). A view function which takes too long can be a problem because the amount of threads Flask uses to handle requests is limited, this could make your application unavailable if too many users are generating plots at the same time.
Returning before calling your script won't work obviously.
return "Plot not found !"
# CALL THE EXTERNAL PYTHON SCRIPT HERE?

You also need to insert a entry in the database before starting to work on the plot generation so no other user can run your script again with the same parameters.
Your except case (when the plot is not is the database already) would look something like this (probably vulerable to SQL injection):
# write entry to the database with parameters but without plot
db.execute('INSERT INTO {} (param1, param2, param3) VALUES ({}, {}, {})'.format(table_name, input1, input2, input3))
# start process which does it's calculations in another process and
# updates the table we just inserted with the plot when finished
p = Popen(['/path/to/script.py', input1, input2, input3], stdin=None, stdout=None, stderr=None, close_fds=True)

return "Plot is beeing generated ..., please refresh page until the plot is available"

The script generating the plot would then update the entry as follows (probably vulerable to SQL injection):
db.execute('UPDATE {} SET plot_blob = {} WHERE param1 = {} AND param2 = {} AND param3 = {}'.format(table_name, binary_image_data, input1, input2, input3))

NOTES:

*

*You can build the URL with url_for which might be neater:
return redirect(url_for('create_plot', input1=input1, input2=input2, input3=input3))

*Your SQL query is probably vulnerable to SQL injection, although the library your using might handle this. I don't know which it is.


text:
Q: Naudio ImaAdpcmWaveFormat, BufferedWaveprovider not happy I am working on an application where I use Naudio to play sound streamed to/from a modem (no luck with tapi on this particular modem, so AT-commands).
This works acceptably well when I used a linear waveformat (WaveFormat waveFormat = new WaveFormat(8000, 16, 1);) but now I want to try getting full duplex, which means that using a slightly more efficient sound format is probably a good idea.
Saw that Naudio has an ImaAdpcmWaveFormat, so tried to replace the WaveFormat object with that one (ImaAdpcmWaveFormat imaadpcm_waveformat = new ImaAdpcmWaveFormat(8000, 1, 4);).
However, now the waveout.init throws a System.DivideByZeroException :(.
I had a similar problem when I had managed to misread the specification for WaveFormat and put 2 instead of 16 for "bits", but 4 bits/sample should be an acceptable rate for IMA ADPCM? Anyhow, same exception for 8 or 16 bits/sample...
Exception data:

System.DivideByZeroException
  HResult=0x80020012
  Message=Attempted to divide by zer0.
  Source=NAudio
  StackTrace:
    at NAudio.Wave.WaveFormat.ConvertLatencyToByteSize(Int32 milliseconds)
    at NAudio.Wave.WaveOut.Init(IWaveProvider waveProvider)
    at USRModemTest.Form1..ctor() in C:\Users\c\Source\Repos\USRModemTest\USRModemTest\Form1.cs:line 56
    at USRModemTest.Program.Main() in C:\Users\c\Source\Repos\USRModemTest\USRModemTest\Program.cs:line 19

From the constructor:
Note that this works acceptably well if I replace imaadpcm_waveformat with waveFormat
//waveFormat = new WaveFormat(8000, 16, 1);
imaadpcm_waveformat = new ImaAdpcmWaveFormat(8000, 1, 4);

//bwp_ModemToSpeakers = new BufferedWaveProvider(waveFormat);
bwp_ModemToSpeakers = new BufferedWaveProvider(imaadpcm_waveformat);
bwp_ModemToSpeakers.DiscardOnBufferOverflow = true;
//bwp_ModemToSpeakers.BufferDuration = System.TimeSpan.FromMilliseconds(200);
bwp_ModemToSpeakers.ReadFully = true;
bwp_ModemToSpeakers.BufferLength = 1000 ; // as small as possible it seems

waveout = new WaveOut();
waveout.DeviceNumber = -1; // default communications device
waveout.DesiredLatency = 200;
waveout.Init(bwp_ModemToSpeakers);

A: You cannot play audio encoded with IMA ADPCM directly. I recommend you decode the audio into PCM before placing it into BufferedWaveProvider. Examples of this can be found in the NAudio demo project and you can make use of the AcmStream class for the conversion.


text:
Q: Forgot Password test. I get this error: in `slice!': can't convert String into Integer (Ruby) I am testing Forgot Password feature via Gmail API and having trouble slicing my result (string).
I am trying to slice a string and always get: in `slice!': can't convert String into Integer (TypeError)
The example below works just fine, but when I run this is a test case it fails on line 5.
 1 gmail = Gmail.new('email@noemail.com', 'Password')
 2 try(5) { @email = gmail.inbox.emails(:unread, :from => 'example@example.com').last }
 3 message_body = @email.message.body.raw_source
 4 pwd = message_body.scan(/Password: (?! )(?=.*[0-9])(?=.*[A-Z]).*[^ ]$/)
    => "Password: _iDE-T!y7G\r"
 5 pwd.slice! "Password: " #slicing "Password: "
    => "_iDE-T!y7G\r"
 6 new_pwd = pwd[0..-2] # slicing "\r"
    => "_iDE-T!y7G"

Thanks in advance!

A: scan returns an array, so you're not using String#slice! but instead Array#slice! which works differently.
Since you're already using a regular expression, just capture the content properly:
matches = message_body.scan(/Password: (?! )(.*[0-9])(?=.*[A-Z]).*[^ ]$/)

pwd = matches.flatten.first


text:
Q: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.settings.USAGE_ACCESS_SETTINGS } This issue is happening on Android 5.0 Lollipop only. I dont have access to a phone with Lollipop, I have developed the code in Genymotion Android Emulator but this issue does not happen in the emulator. I am only getting failing stacktraces from users' phones.
My Code:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    Intent intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
    startActivity(intent);
}

The App crashes and the stacktrace I am getting from users:
android.content.ActivityNotFoundException: No Activity found to handle Intent {     act=android.settings.USAGE_ACCESS_SETTINGS }
at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1765)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1485)
at android.app.Activity.startActivityForResult(Activity.java:3780)
at android.app.Activity.startActivityForResult(Activity.java:3741)
at android.support.v4.app.FragmentActivity.startActivityFromFragment(FragmentActivity.java:849)
at android.support.v4.app.Fragment.startActivity(Fragment.java:880)
at     com.myapp.myfirstapp.fragments.addablock.apps.Fragment_appsselect_addblock$2.onClick(Fragment_ appsselect_addblock.java:147)
at android.view.View.performClick(View.java:4763)
at android.view.View$PerformClick.run(View.java:19821)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5274)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

A: I am seeing this crash too. It seems that LG has removed the newly introduced Usage Permission Setttings screen from their version of Lollipop.


text:
Q: An interest calculation task I'm working on doesn't output the proper results So I'm currently taking a C# fundamentals course as the entrance stage of a 6 month C# learning program. One of the tasks we have under the "Data Types and Variables" is an interest calculator.
The premise is such: You have a "deposit" that you write in the first line. The deposit has a 5% interest to it. The program needs to output the deposit's value for 3 years, for each year, all at once.
So 100.00, 105.00, 110.25, 115.76. The numbers after the decimal point need to be rounded to 2 digits, as well as "The rules of math for rounding apply here".
double deposit = double.Parse(Console.ReadLine());
            double interest = (deposit*5)/100;

            double yearOne = deposit + interest;
            double yearTwo = yearOne + interest;
            double yearThree = yearTwo + interest;

            string totalSums = ($"{yearOne:N2}\n{yearTwo:N2}\n{yearThree:N2}\n");

            Console.WriteLine( totalSums );

This is the code I've written so far. It SEEMS to work, but it's not as accepted.
If I put the deposit value as 100 (one of the examples), I get this output:
100
105.00
110.00
115.00
I've put the calculation for the interest percentage as double interest = (deposit*5)/100, which checks out if I use an external calculator to test it. But the program doesn't give the right output.
Say if I put 100.23 as the deposit input, I'll get: 105.24, 110.25, 115.26 when I should get 105.24, 110.50, 116.02. However, a round 100.00 doesn't even display the digits after the decimal point, just rounds them down to the whole number.
I thought the problem comes from using double and not decimal due to floating-point precision issues, so I changed everything to decimal. I still get this exact problem. Nothing changes.
I've had other issues that I at least have ideas on where I'm going wrong, but this one has been screwing with me since 3 days. So I resorted to some help here.
Why am I not getting the correct outputs ? Where is my problem coming from ? Is it the math ? Or logic ? Maybe I'm not using the correct method ? I'm at a loss... And the learning resources I've been given don't seem to help me with this issue, too. Like it's the ONLY task that the resources don't help with.
I've also seen other posts about compound interest, but they use arrays and other things that I'm not yet at the point of learning within the program. So code like that isn't gonna pass the automatic tester. I'm not asking for a complete code solving or "cheat" if you will; I just need some guidance on what my issue here is, because I'm clueless at this point.

A: Your question is about compound interest, not simple interest. Therefore, you need to calculate the new interest every year.
double deposit = double.Parse(Console.ReadLine());

double yearOne = deposit + (deposit * 5)/100;
double yearTwo = yearOne + (yearOne * 5)/100;
double yearThree = yearTwo + (yearTwo * 5)/100;

string totalSums = ($"{yearOne:N2}\n{yearTwo:N2}\n{yearThree:N2}\n");

Console.WriteLine( totalSums );

A: If you know about loops, you can create a loop over 3 years and update the amount in the account:
static class Program
{
    static void Main(string[] args)
    {
        // set interest rate (fixed)
        decimal rate = 5m/100;
        // get deposit amount from user
        Console.WriteLine("Enter Initial Amount:");
        string input = Console.ReadLine();
        decimal amount = decimal.Parse(input);
        // loop over three years
        Console.WriteLine($"{"year"}\t{"amount"}");
        for (int year = 1; year <= 3; year++)
        {
            // calculate interest for the year based on
            // current amount in the account
            decimal interest = rate * amount;
            // deposit interest in account
            amount += interest;
            Console.WriteLine($"{year}\t{amount:c2}");
        }
    }
}

with output
Enter Initial Amount:
1000
year    amount
1       $1,050.00
2       $1,102.50
3       $1,157.63

A: you need to recalculate the interest amount each year.
        double deposit = double.Parse(Console.ReadLine());

        //Use deposit to calculate interest
        double yearOneinterest = (deposit*5)/100;
        double yearOne = deposit + yearOneinterest;

        //Use yearOne amount to calculate interest
        double yearTwointerest = (yearOne*5)/100;
        double yearTwo = yearOne + yearTwointerest;

        //Use yearTwo amount to calculate interest
        double yearThreeinterest = (yearTwointerest*5)/100;
        double yearThree = yearTwo + yearThreeinterest;

        string totalSums = ($"{yearOne:N2}\n{yearTwo:N2}\n{yearThree:N2}\n");

        Console.WriteLine( totalSums );


text:
Q: About the integral $\int \log (x)/(x-k) dx$ and the polylogarithm During some calculations I ran into the integral
$\int  \log(x)/(x-k) dx $ which Wolfram alpha happily tells me satisfies
$$ \int  \log(x)/(x-k) dx = {\rm{Li}}_2(x/k)+\log(x) \log(1-x/k)+C, $$
but not much else.
Given I saw the polylogarithm for the first time now and have only read the wikipedia page, can then be made an argument that the above is true? If so, which?

A: The polylogarithm function is initially defined by the series
$$
{\rm{Li}}_2(z):=\sum_{n\geq 1}\frac{z^n}{n^2},\quad |z|<1.\tag1
$$
Thus if you consider
$$
\int_0^x\frac{\log t}{t-k}dt, \quad k>1,\, |x|<1,\tag2
$$
then you may write
$$
\frac{1}{t-k}=-\frac{1}{k}\:\frac{1}{1-t/k}=-\sum_{n\geq 0}\frac{t^n}{k^{n+1}}, \quad |t|<1, \, k>1,\tag3
$$ giving, by a termwise integration, which is allowed here, using the following result, obtained by an integration by parts,
$$
\int_0^xt^n\log t\:dt= -\frac{x^{n+1}}{(n+1)^2}+\frac{x^{n+1}}{n+1}\log x\tag4
$$
$$
\int_0^x\frac{\log t}{t-k}dt=-\sum_{n\geq 0}\frac{1}{k^{n+1}}\int_0^xt^n\log t\:dt=\sum_{n\geq 0}\frac{1}{k^{n+1}}\frac{x^{n+1}}{(n+1)^2}-\log x\sum_{n\geq 0}\frac{1}{k^{n+1}}\frac{x^{n+1}}{n+1}.
$$ Equivalently, using $(1)$ and the standard power series for $ \displaystyle \log (1-x)$ we get
$$
\int_0^x\frac{\log t}{t-k}dt={\rm{Li}}_2\left(\frac{x}{k} \right)+\log x\log \left(1- \frac{x}{k}\right) \tag5
$$ as announced.


text:
Q: Is there any way to use jquery code inside razor? Here is my jQuery code with Razor:
    $("#GroupC_grup_name").attr('value', '@foreach (SelectListItem sel in (SelectList)ViewData["Gruplar"]){ @sel.Text }')
    $("#GroupC_id").attr('value', '@foreach(SelectListItem sel in (SelectList)ViewData["Gruplar"]){ @sel.Value }')

I want to merge these together, as in I dont want to call for ViewData["Gruplar"] twice.
Can I do something like this?
 @foreach(SelectListItem sel in (SelectList)ViewData["Gruplar"]){
     @:$("#GroupC_grup_name").attr('value', '@sel.Text');
     @:$("#GroupC_id").attr('value', '@sel.Value');
 }

I've tried everything I can think of but still can't achieve what I want.

A: The code you suggest should work, the code below uses a string array instead of a SelectList but the principle should be be the same, the code below has been tested and works -
@{String[] testarr = {"hello","bye"};}
@foreach(String sel in testarr){
 @:$("#GroupC_grup_name").attr('value', '@sel');
 @:$("#GroupC_id").attr('value', '@sel');
}

A: I read it carefully and understand what you want to do. However your example is what is confusing. (it seems to everyone that answered)
What you've done in the second example should work just fine you could wrap your jQuery in a <text></text> element if that helps as well. If there's only ever one value you could just
<script type='text/javascript'>
    @{ var x = ((SelectList)ViewData["Gruplar"]).First(); }
    $("#GroupC_grup_name").attr('value', '@x.Text');
    $("#GroupC_id").attr('value', '@x.Value');
</script>

There are any number of ways you could accomplish razor within jquery. It's basically the same as razor with html.
It you want to execute razor on the client side then that's not going to happen. Razor is executed before it gets sent to the client.

A: As I understand it, you want to update the elements when a SELECT item is selected?
Create a regular select list and add the following jquery code:
<script type="text/javascript">
$(function () {
    $('#selectListId').change(function() {
        $selectedItem = $("option:selected", this);
        $("#GroupC_grup_name").val(selectedItem.html());
        $("#GroupC_id").val(selectedItem.val());
    });

});
</script>


text:
Q: Negating a complex regex containing three parts I need a regex which is matched when the string doesn't have both lowercase and uppercase letters.

*

*If the string has only lowercase letters -> should be matched

*If the string has only uppercase letters -> should be matched

*If the string has only digits or special characters -> should be matched

For example
abc, ABC, 123, abc123, ABC123&^ - should match
AbC, A12b, AB^%12c - should not match
Basically I need an inverse/negation of the following regex:

^(?=.*[a-z])(?=.*[A-Z]).+$

A: Does not sound like any lookarounds would be needed.
Either match only characters that are not a-z or only characters, that are not A-Z.
^(?:[^a-z]+|[^A-Z]+)$

See this demo at regex101 (used + for one or more)

A: You may use
^(?!.*[A-Z].*[a-z])(?!.*[a-z].*[A-Z])\S+$

Or
^(?=(?:[^a-z]+|[^A-Z]+)$).*$

See the regex demo #1 and regex demo #2
A lookaround solution like this can be used in more complex scenarios, when you need to apply more restrictions on the pattern. Else, consider a non-lookaround solution.
Details

*

*^ - start of string

*(?!.*[A-Z].*[a-z]) - no uppercase followed with a lowercase letter

*(?!.*[a-z].*[A-Z]) - no lowercase letter followed with an uppercase one

*(?=(?:[^a-z]+|[^A-Z]+)$) - a positive lookahead that requires 1 or more characters other than lowercase ASCII letters ([^a-z]+) to the end of the string, or  1 or more characters other than uppercase ASCII letters ([^A-Z]+) to the end of the string

*.+ - 1+ chars other than line break chars

*$ - end of string.

A: You can use this regex
^(([A-Z0-9?&%^](?![a-z]))+|([a-z0-9?&%^](?![A-Z]))+)$

You can test more cases here.
I've only added the characcter ?&%^ as possible character, but you could add which ever you like.

A: I would go with:
^(?:[^a-z]+?|[^A-Z]+?)$

It translates to "If the entire string is composed of non-lowercase letters or non-uppercase letters then match the string."
Lazy quantifiers +? are used so that the end-string $ anchor is obeyed when the multiline flag is enabled. If you're only validating a single-line string the you can simply use + without the question mark.
If you have a whitelist of specific allowed special chars then change [^A-Z] into [A-Z0-9()_+=-] and list the allowed special chars.
https://regex101.com/r/Wg6tLn/1