text:
Q: remove image from model with rails 3 and carrierwave and jquery I'm using Carrierwave to add and upload an image to Amazon S3.  this works ok, and once the form is saved I display the image and an x box to remove it.
I would like to use ajax to handle the click event on the 'x' image'  on click I would like to remove the image and clear the field on the form so that the input field is once again displayed
The image field is an attribute of the model class i am editing in the form.
Person < ActiveRecord
 attr_accessible: image

the partial for this part of my form shows the image if it exists, otherwise the input file_field if it does not exists

    <%= image_tag @pass.background_image_url(:thumb) if @pass.background_image? %>
    <%= f.file_field :background_image if @pass.background_image.to_s == '' %>
    <%= content_tag :div, '', class: "delete_image_fields" if @pass.background_image? %>

I have some jquery which i can sccessful hide the image field.
jQuery ->

  $('.field .delete_image_fields').click ->
  $(this).parent().find('img').hide()
  event.preventDefault()

The image field gets hidden no problem
What i would like to happen is
a)  clear the input field from the pass object
b)  submit the change (remotely)
c) delete the remote image on S3
e) re-display the file_input field for the image so it can re-selected if required
Any help or pointers would be appreciated
UPDATE
I've got this partially working to display corect fields and adjust the input link.  but i'm not sure how to actually delete the file from the models attribute
I've updated the partial to the following which dispalsy either the image ro the create file button

  <%= f.label :background_image %>

  <% if @pass.background_image?%>
     <%= image_tag @pass.background_image_url(:thumb)  %>
     <%= f.file_field :background_image , style: "display:none"%>
     <%= content_tag :div, '', class: "delete_image_fields" %>
  <% else %>
     <%= f.file_field :background_image%>
  <% end %>

and updated my jquery to this
$('.field .delete_image_fields').click ->
  $(this).parent().find('img').hide()
  $(this).hide()
  $(this).parent().find('input').val('')
  $(this).parent().find('input').show()
  event.preventDefault()

A: To delete the file, you could take advantage of the remove_mounted_field_url carrierwave creates.
From here I see two solutions, either create a new action in your controller that will only remove the file, either use the update action. I like to use as much as possible the original actions(index/new/create ...), so I will use the second solution.
You need to do an AJAX PUT request when clicking on the X box. Here what it could look like :
$('.field .delete_image_fields').click ->
  $(this).parent().find('img').hide()
  $(this).hide()
  $(this).parent().find('input').val('')
  $(this).parent().find('input').show()
  event.preventDefault()
  $.ajax
    url: $(this).getParents('form').first().attr('action')
    method: 'PUT'
    data:
      person:
        remove_image: 1 # This will trigger the carrier wave function that remove the uploaded file
  .done (data) ->
      # You can do plenty if things here, for instance notify the user it's been correctly deleted

Note that this will only work on an edition form, as the url of the AJAX query which has to target the update action is taken from the form. I don't think this is a problem, as on the create form no photos is already uploaded, so there's nothing to delete.
Last thing, you could use the siblings method to find both inputs and the image


text:
Q: Pyodbc error after upgrading python from 3.8 to 3.11 I am using the following code:
import pandas as pd, pyodbc
from sqlalchemy import create_engine
import urllib

def connStrMDBV2(fname):
    driver = r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)}'
    connection_string = (fr"{driver};DBQ={fname};ExtendedAnsiSQL=1;")
    connection_uri = f"access+pyodbc:///?odbc_connect={urllib.parse.quote_plus(connection_string)}"
    engine = create_engine(connection_uri)
    return engine

fname = fr'C:\Users\asd\Desktop\test11\mytest.mdb'
connStrMDBV2(fname)

I get the error:
raise exc.NoSuchModuleError(
sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:access.pyodbc

I have checked all the packages are already installed and I am not using virtual environment. It used to work on Python 3.8 and I am getting error after upgrading to Python 3.11

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sql - Consulta de dois valores máximos Suponhamos que temos essa base de dados
codigo, data, valor,seq
(1, '2014-01-01', 10,2),
(1, '2014-01-02', 20,1),
(2, '2014-01-03', 30,1),
(2, '2014-01-05', 40,1),
(2, '2014-01-05', 50,2),
(3, '2014-01-06', 60,1);

Eu quero pegar a data mais recente por cada código, no entanto, haverá datas repetidas, e quando isso ocorrer terei que pegar a maior Seq.
Ou seja, o resultado esperado é
1, '2014-01-02', 20,1
2, '2014-01-05', 50,2
3, '2014-01-06', 60,1

http://sqlfiddle.com/#!18/ba9e1/1/0

A: Você só precisa verificar os registros que não possuam data ou valor maiores com o NOT EXISTS:
SELECT m.*
  FROM minha_tabela m
 WHERE NOT EXISTS(SELECT 1
                    FROM minha_tabela m2
                   WHERE m2.codigo = m.codigo
                     AND (m2.data > m.data
                      OR m2.valor > m.valor)
                   GROUP BY m2.codigo,
                            m2.data,
                            m2.valor)

A: Veja o exemplo abaixo de como você poder fazer.
SELECT m.codigo, m.data,  m.valor,  m.seq
FROM @minha_tabela m
join
(
  SELECT m2.codigo, max(m2.data) as data, max(m2.seq) as seq
  FROM @minha_tabela m2
  group by m2.codigo
) m3 on m3.codigo = m.codigo
and m3.data = m.data
and m3.seq = m.seq

A: Mais uma suposição...
Para a data inicial eu tenho vários registros (leia-se sequências 1 a 10). Porém quero selecionar a maior data e dessa maior data a maior sequência.
Código para essa solução (pode ser útil para alguem):
SELECT m.codigo, m.data,  m.valor,  m.seq
FROM minha_tabela m
where m.data = (select max(m2.data) from minha_tabela m2
                where m.codigo = m2.codigo)
and m.seq = (select max(m3.seq) from minha_tabela m3
             where m.codigo = m3.codigo
             and   m.data = m3.data);

A: Parece-me que a solução mais simples para o problema é esta:
select codigo,MAX(valor)
from minha_tabela
group by codigo


text:
Q: Plugin with constants Is it possible to have plugin with properties to access them from another plugin?
E.g. I have a plugin with plugin.properties:
some.property=test

And I want to access it in another plugin's plugin.xml by %some.property
Any suggestions how this could be implemented?

A: No, this is not possible.
You can access resources in another plug-in using the FileLocator class but you can't do it statically with references in the plugin.xml.


text:
Q: Extract html table row to google sheet I'm trying to extract a single row from a table
When using the google sheet importhtml function, I get the whole table.
=IMPORTHTML("https://www.marketwatch.com/investing/stock/jwn/options?mod=mw_quote_tab", "table",1)

How can I extract just the row right above the word  " Current price as of "
So e.g. in this case the row will have the data below. (this data will change as the date changes)
quote   1.5 0.53    76  1.36    1.47    142 39  quote   0.88    -1.73   23
I have several urls to go thorough
So e.g if I put the following url then the row position will change.
https://www.marketwatch.com/investing/stock/ge/options
Any idea how to extract that just last row right above the word " Current price as of "

A: When I saw the HTML data from the URL of https://www.marketwatch.com/investing/stock/ge/options, I thought that the value you expect might be able to be retrieved using IMPORTXML and a xpath. So in this answer, I would like to propose to use IMPORTXML.
Sample formula:
=IMPORTXML(A1,"//tr[td[1]/@class='acenter inthemoney'][last()]")

*

*In this case, the URL of https://www.marketwatch.com/investing/stock/ge/options is put in the cell "A1".

Result:

Note:

*

*This sample formula can be used for the current URL of https://www.marketwatch.com/investing/stock/ge/options. So when the URL is changed and the HTML structure is changed by updated of the site, the formula might not be able to be used. So please careful this.

Reference:

*

*IMPORTXML

A: *

*ImportHTML() simply allows you to read an (entire!) HTML table or list into your Google sheet.

*If you want to filter or manipulate the imported data, then you'll need to use other Google Sheets functions. These are documented here:
Google Sheets function list

*Alternatively, you might want to "import" input one sheet, then select certain data into another, separate sheet:
Get data from other sheets in your spreadsheet

*Here are some examples for "filtering" your data:
FILTER function


text:
Q: selectOneMenu Converter  Hi every body I'm working on Primfaces pages and I have to make a selectOneMenu wich get items from dataBase so I tried to make it this way but I still have problem's with the converter

so my source Codes are the folowing :

selectOneMenu :
<p:selectOneMenu id="devises" required="true" value="#{pret.devise}" effect="fade" converter="devise">
    <f:selectItem itemLabel="Select One" itemValue="" />
    <f:selectItems value="#{devise.listDevise()}" var="devise" itemLabel="#{devise.nomDevise}" itemValue="#{devise}"/>
</p:selectOneMenu>

converter code:
@FacesConverter(value = "devise")
public class DeviseConverter implements Converter{

    public static List<Devise> devises = Devise.listDevise();

    public Object getAsObject(FacesContext facesContext, UIComponent component, String submittedValue) {
        if (submittedValue.trim().equals("")) {
            return null;
        } else {
            try {
                int idDevise = Integer.parseInt(submittedValue);
                for (Devise p : devises) {
                    if (p.getIdDevise()== idDevise) {
                        return p;
                    }
                }
            } catch(NumberFormatException exception) {
                throw new ConverterException(new FacesMessage(FacesMessage.SEVERITY_ERROR, "Conversion Error", "Not a valid Devise"));
            }
        }
        return null;
    }

    public String getAsString(FacesContext facesContext, UIComponent component, Object value) {
        if (value == null || value.equals("")) {
            return "";
        } else {
            return String.valueOf(((Devise) value).getIdDevise());
        }
    }
}

the error Code is : "devises: Validation Error: Value is not valid"

A: Your object Devise would need to contain equals() and hashCode() methods.
Also you can use this generic converter which would workd for all the types of object and you won't need to write a converter for all the select lists.
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import java.util.WeakHashMap;

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;

@FacesConverter(value = "entityConverter")
public class EntityConverter implements Converter {

    private static Map<Object, String> entities = new WeakHashMap<Object, String>();

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object entity) {
        synchronized (entities) {
            if (!entities.containsKey(entity)) {
                String uuid = UUID.randomUUID().toString();
                entities.put(entity, uuid);
                return uuid;
            } else {
                return entities.get(entity);
            }
        }
    }

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String uuid) {
        for (Entry<Object, String> entry : entities.entrySet()) {
            if (entry.getValue().equals(uuid)) {
                return entry.getKey();
            }
        }
        return null;
    }

}


text:
Q: i can't shoot the bullet in this pygame space invaders Pygame is perfectly installed, everything else is working fine spaceship movement and enemy movement but i am not able to see the bullet which i have drawn from inside the fire_bullet function, I have tried drawing it from outside the function and that does seem to work .
import pygame
import os
import random
pygame.init()

#Screen
screen = pygame.display.set_mode((800, 600))

#Title and Icon
pygame.display.set_caption('Space Invaders ')
UFO = pygame.image.load(os.path.join('Assets2', 'ufo.png'))
pygame.display.set_icon(UFO)

#player

playerImg = pygame.image.load(os.path.join('Assets2', 'spaceship.png'))
playerX = 370
playerY = 480
VEL = 0

def player(x, y):
    screen.blit(playerImg, (x, y))

#enemy
enemyImg = pygame.image.load(os.path.join('Assets2', 'enemy.png'))
enemyimg1 = pygame.transform.scale(enemyImg, (45, 50))
enemyX = random.randint(0,800)
enemyY = random.randint(50,150)
enemyX_change = 0.7
enemyY_change = 40

def enemy(x,y):
    screen.blit(enemyimg1, (x, y))

#background
bg = pygame.image.load(os.path.join('Assets2', 'space.png'))

#bullet
bulletimg = pygame.image.load(os.path.join('Assets2', 'bullet.png'))
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 10
bullet_state = "ready"  #Ready - Rest, Fire - Motion

def fire_bullet(x,y):
    global bullet_state
    bullet_state = "fire"
    screen.blit(bulletimg, (x+16, y+10))

run = True

#Game loop

while run:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    # Movement
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                VEL = -1.4
            if event.key == pygame.K_RIGHT:
                VEL= 1.4
            # Bullet positioning
            if event.key == pygame.K_SPACE:
                fire_bullet(playerX, bulletY)

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                VEL = 0

    playerX += VEL

    # Restricting boundaries of spaceship
    if playerX <= 0:
        playerX = 0
    elif playerX >= 736:
        playerX = 736

    enemyX += enemyX_change

    # Restricting boundaries of Enemy
    if enemyX <= 0:
       enemyX_change = 1
       enemyY += enemyY_change
    elif enemyX >= 736:
        enemyX_change = -1
        enemyY += enemyY_change

    #Bullet Movement
    if bullet_state is "fire":
        fire_bullet(playerX, bulletY)
        bulletY -= bulletY_change

    screen.fill((255,255,0))
    screen.blit(bg, (0,0))

    player(playerX, playerY)

    enemy(enemyX, enemyY)

    pygame.display.update()

Also all the assets are fine and dowloaded correctly so idk why is it still not showing the bullet drawn from inside the function

A: Your bullet is so fast that you can barely see it. You have to limit the frames per second. Use pygame.time.Clock to control the frames per second and thus the game speed.
The method tick() of a pygame.time.Clock object, delays the game in that way, that every iteration of the loop consumes the same period of time. See pygame.time.Clock.tick():

This method should be called once per frame.

e.g.:
clock = pygame.time.Clock()

#Game loop
while run:
    clock.tick(60)

    # [...]


text:
Q: ADB and Genymotion error: "adb server is out of date. killing... cannot bind 'tcp:5037' ADB server didn't ACK" Trying to use adb shell from terminal after starting genymotion emulator and I get this error:
adb server is out of date.  killing...
cannot bind 'tcp:5037'
ADB server didn't ACK
* failed to start daemon *
error:

I read in this answer on stackoverflow to run this command killall -9 adbso I did and then it says to change genymotion settings to use custom Android SDK tools as the following:

Also did that as you can see in the above screenshot but I still keep getting the same error message.
My android Studio ADB logs give the following message whenever I try to run adb shell:
 DeviceMonitor: Adb connection Error:EOF
 DeviceMonitor: Connection attempts: 1

I even tried creating a new virtual device and using it without any success.

A: The root cause for this issue is that you try to run adbs of different versions.
PC(Host) side adb is made of two parts: adb and adb server.
adb <----> adb server <--------USB-------> adbd(device)
adb and adb server actually is the same binary, but adb server is running at background when you first issue a adb command. After that, adb command will contact which adb server each time you run adb, and first of all it check the versions of running adb server. If version is not match, then you will see 'adb server is out of date.  killing...'. This is the only reason.
int adb_connect(const std::string& service, std::string* error) {
    // first query the adb server's version
    int fd = _adb_connect("host:version", error);
...
        if (version != ADB_SERVER_VERSION) {
            printf("adb server is out of date.  killing...\n");
            fd = _adb_connect("host:kill", error);
            adb_close(fd);

            /* XXX can we better detect its death? */
            adb_sleep_ms(2000);
            goto start_server;
        }

To resolve this problem, you just need to make sure you are not tring to run different version adb.

*

*Find the binary path of running adb server by using a task manager tool, search "adb". check its version using command

[path to adb server]/adb version

The output like this:
Android Debug Bridge version 1.0.35
Revision 68de85bda98d-android

"1.0.35" is the version number.

*check the version of the adb which cause your problem. just type

adb version

*compare the version numbers, they must match.

if they are not matched, you can:

*

*just keep only one adb, delete others.

*or you can ignore the error. if it always shows, find out who is running different adb tool for you and stop it. For example, some phone assistant program.

A: update the adb to 1.0.32 if you have 1.0.31 or lower
adb version
Android Debug Bridge version 1.0.31
wget -O - https://skia.googlesource.com/skia/+archive/cd048d18e0b81338c1a04b9749a00444597df394/platform_tools/android/bin/linux.tar.gz | tar -zxvf - adb
sudo mv adb /usr/bin/adb
sudo chmod +x /usr/bin/adb
adb version
Android Debug Bridge version 1.0.32

A: Neither of those solutions worked for me at all.
The solution which solved my error was to add both the missing /Android/Sdk/tools & /Android/Sdk/platform-tools directories to my Environment PATH variable,this can be achieved with the following command:
export PATH=/home/{username}/Android/Sdk/tools:/home/{username}/Android/Sdk/platform-tools:$PATH

Be sure to interpolate your own username into the command, replacing {username} with your operating system username.
Doing so will direct your command line to search your Environmant's PATH  variable for the proper location of the adb executable, without this environment variable set, your system does not know where to look for the correct executable.


text:
Q: How to make sure a table is indexed by a certain column when using RedBean PHP ORM? I have an entity named 'account' which will have a username column and I want to index by this because I will be using it to lookup the username when logging in.
How do I tell redbean orm that I would like this table to have column 'username' to be indexed for faster lookup? Would I have to update the database manually instead of going through redbean orm?

A: I think this is what you're after:
R::$writer->addIndex('account','userindex','username');


text:
Q: debugger gem installation issue on windows 7 Not able to install debugger or ruby-debug19 on a windows 64 bit machine. Have installed Devkit, rubygems and able to install all the other gems except this.
ruby -v
ruby 1.9.3p551 (2014-11-13) [i386-mingw32]

gem --version
2.4.1

ERROR :
gem install debugger
Temporarily enhancing PATH to include DevKit...
Building native extensions.  This could take a while...
ERROR:  Error installing debugger:
        ERROR: Failed to build gem native extension.

    C:/Ruby193/bin/ruby.exe -r ./siteconf20141205-5484-1qgupo8.rb extconf.rb

 checking for rb_method_entry_t.called_id in method.h... no
    checking for rb_control_frame_t.method_id in method.h... no
    checking for rb_method_entry_t.called_id in method.h... yes
    checking for vm_core.h... yes
    checking for iseq.h... yes
    checking for insns.inc... yes
    checking for insns_info.inc... yes
    checking for eval_intern.h... yes
    checking for struct iseq_line_info_entry in vm_core.h,iseq.h... no
    checking for struct iseq_insn_info_entry in vm_core.h,iseq.h... yes
    checking for if rb_iseq_compile_with_option was added an argument filepath... yes
    creating Makefile

    make  clean
    Makefile:165: *** target pattern contains no `%'.  Stop.

    make
    Makefile:165: *** target pattern contains no `%'.  Stop.

    make failed, exit code 2

    Gem files will remain installed in C:/Ruby193/lib/ruby/gems/1.9.1/gems/debugger-1.6.8 for inspection.
    Results logged to C:/Ruby193/lib/ruby/gems/1.9.1/extensions/x86-mingw32/1.9.1/debugger-1.6.8/gem_make.out

gem list

*** LOCAL GEMS ***

archive-tar-minitar (0.5.2)
atk (2.2.3 x86-mingw32)
bigdecimal (1.1.0)
cairo (1.14.0 x86-mingw32)
columnize (0.8.9)
debugger-linecache (1.2.0)
debugger-ruby_core_source (1.3.7, 1.1.6
gdk_pixbuf2 (2.2.3 x86-mingw32)
glib2 (2.2.3 x86-mingw32)
green_shoes (1.1.374)
gtk2 (2.2.3 x86-mingw32)
io-console (0.3)
json (1.5.5)
minitest (2.5.1)
pango (2.2.3 x86-mingw32)
pkg-config (1.1.6)
rake (0.9.2.2)
rbx-require-relative (0.0.9)
rdoc (3.9.5)
ruby_core_source (0.1.5)
rubygems-update (2.4.5)

Thanks in advance

A: Looks like there is some issue with the latest version of RubyGems.
This version has a failure with Ruby 1.9.3 that is causing the error.
Downgrading to version 1.8.x running the following command:
gem update --system 1.8.29

And then I could install the debugger gem.
gem install debugger
Temporarily enhancing PATH to include DevKit...
Building native extensions.  This could take a while...
Successfully installed debugger-1.6.8
1 gem installed
Installing ri documentation for debugger-1.6.8...
Installing RDoc documentation for debugger-1.6.8...


text:
Q: How to interpret increase to AIC and adjusted r-squared? I understand adjusted r-squared and AIC can be used to select an ideal model from a group. Higher AIC is worse but higher ar2 is better.
After adding a categorical variable to an OLS model, my adjusted r-squared went up and so did my AIC. Some of the categorical values are associated with a high p-value.
Three questions:

*

*How can I interpret the discrepancy?

*I tend to favor including the variable because of the ar2 effect. Is this a fair justification?

*Is either metric generally preferred among AR2 and AIC?


text:
Q: Installing from rpm gives weird dependency error I'm trying to install mysql from rpm file and this is what is get.
libaio.so.1 is needed by MySQL-server-5.6.14-1.el6.i686
libaio.so.1(LIBAIO_0.1) is needed by MySQL-server-5.6.14-1.el6.i686
libaio.so.1(LIBAIO_0.4) is needed by MySQL-server-5.6.14-1.el6.i686
libc.so.6 is needed by MySQL-server-5.6.14-1.el6.i686
libc.so.6(GLIBC_2.0) is needed by MySQL-server-5.6.14-1.el6.i686
libc.so.6(GLIBC_2.1) is needed by MySQL-server-5.6.14-1.el6.i686
libc.so.6(GLIBC_2.1.2) is needed by MySQL-server-5.6.14-1.el6.i686
libc.so.6(GLIBC_2.1.3) is needed by MySQL-server-5.6.14-1.el6.i686
libc.so.6(GLIBC_2.10) is needed by MySQL-server-5.6.14-1.el6.i686
libc.so.6(GLIBC_2.2) is needed by MySQL-server-5.6.14-1.el6.i686
libc.so.6(GLIBC_2.2.3) is needed by MySQL-server-5.6.14-1.el6.i686
libc.so.6(GLIBC_2.3) is needed by MySQL-server-5.6.14-1.el6.i686
libc.so.6(GLIBC_2.3.3) is needed by MySQL-server-5.6.14-1.el6.i686
libc.so.6(GLIBC_2.3.4) is needed by MySQL-server-5.6.14-1.el6.i686
libc.so.6(GLIBC_2.4) is needed by MySQL-server-5.6.14-1.el6.i686
libc.so.6(GLIBC_2.7) is needed by MySQL-server-5.6.14-1.el6.i686
libc.so.6(GLIBC_2.8) is needed by MySQL-server-5.6.14-1.el6.i686
libcrypt.so.1 is needed by MySQL-server-5.6.14-1.el6.i686
libcrypt.so.1(GLIBC_2.0) is needed by MySQL-server-5.6.14-1.el6.i686
libdl.so.2 is needed by MySQL-server-5.6.14-1.el6.i686
libdl.so.2(GLIBC_2.0) is needed by MySQL-server-5.6.14-1.el6.i686
libdl.so.2(GLIBC_2.1) is needed by MySQL-server-5.6.14-1.el6.i686
libgcc_s.so.1 is needed by MySQL-server-5.6.14-1.el6.i686
libgcc_s.so.1(GCC_3.0) is needed by MySQL-server-5.6.14-1.el6.i686
libgcc_s.so.1(GLIBC_2.0) is needed by MySQL-server-5.6.14-1.el6.i686
libm.so.6 is needed by MySQL-server-5.6.14-1.el6.i686
libm.so.6(GLIBC_2.0) is needed by MySQL-server-5.6.14-1.el6.i686
libm.so.6(GLIBC_2.1) is needed by MySQL-server-5.6.14-1.el6.i686
libpthread.so.0 is needed by MySQL-server-5.6.14-1.el6.i686
libpthread.so.0(GLIBC_2.0) is needed by MySQL-server-5.6.14-1.el6.i686
libpthread.so.0(GLIBC_2.1) is needed by MySQL-server-5.6.14-1.el6.i686
libpthread.so.0(GLIBC_2.2) is needed by MySQL-server-5.6.14-1.el6.i686
libpthread.so.0(GLIBC_2.3.2) is needed by MySQL-server-5.6.14-1.el6.i686
librt.so.1 is needed by MySQL-server-5.6.14-1.el6.i686
librt.so.1(GLIBC_2.2) is needed by MySQL-server-5.6.14-1.el6.i686
libstdc++.so.6 is needed by MySQL-server-5.6.14-1.el6.i686
libstdc++.so.6(CXXABI_1.3) is needed by MySQL-server-5.6.14-1.el6.i686
libstdc++.so.6(GLIBCXX_3.4) is needed by MySQL-server-5.6.14-1.el6.i686
libstdc++.so.6(GLIBCXX_3.4.11) is needed by MySQL-server-5.6.14-1.el6.i686

A: From LinuxQuestions.org forum:

The easy way is to make a backup of your /usr/lib/libstdc++.so.6.0.8, and delete the link libstdc++.so.6 , and use a replacement that works  with your glibc : will usually be libstdc++.so.6.0.13 from the package libstdc++6_4.4.5-8_i386.deb ( 32bits ) http://ftp.de.debian.org/debian/pool...4.5-8_i386.deb 64bits http://ftp.de.debian.org/debian/pool....5-8_amd64.deb
Unpack with : ar -x .deb && tar xvf data.tar.gz, ... and copy libstdc++.so.6.0.13 to /usr/lib/, and : # ln -s libstdc++.so.6.0.13 libstdc++.so.6

Reference: http://packages.debian.org/squeeze/libstdc++6

A: How are you installing this? rpm -ivh? you can install using "yum install filename.rpm". So yum will try to resolve dependencies on its own.
on the other hand, this link for 5.6.15 could prove useful
http://tecadmin.net/step-to-install-mysql-5-6-12-on-centos-6-and-rhel-6/#


text:
Q: how to solve this error when upgrade from core 2.1 to core 3.1 OptionsValidationException: Cookie.Expiration is ignored, use ExpireTimeSpan instead I have upgraded my asp.net core 2.1 application to asp.net core 3.1, but when I run the project I got this error OptionsValidationException: Cookie. Expiration is ignored, use ExpireTimeSpan instead. the first display of my application show this error
here is my startup code asp.net core 3.1, that I have upgraded from .net core 2.1,
  public class Startup
{
    public IConfiguration Configuration { get; }
    public IWebHostEnvironment Environment { get; }
    public Startup(IConfiguration configuration, IWebHostEnvironment environment)
    {
        Configuration = configuration;
        Environment = environment;
    }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        var connection = Configuration.GetConnectionString("DentalDBconnection");
        services.AddDbContext<HoshmandDBContext>(option => option.UseSqlServer(connection));
        services.AddAuthentication(option =>
        {
            option.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            option.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme;
            option.DefaultChallengeScheme = CookieAuthenticationDefaults.AuthenticationScheme;
        })
        .AddCookie(options =>
        {
            options.LoginPath = "/Logins/UserLogin/";
            options.AccessDeniedPath = "/AccessDenied";
            options.Cookie.Expiration = new TimeSpan(10, 00, 00);
        });

        services.AddDistributedMemoryCache();
        services.AddSession(options =>
        {
            options.IdleTimeout = TimeSpan.FromHours(2);
            options.Cookie.HttpOnly = true;
            options.Cookie.IsEssential = true;

        });

        services.ConfigureApplicationCookie(option =>
        {
            option.ExpireTimeSpan = TimeSpan.FromMinutes(540);
        });

        services.AddAuthorization(options =>
        {
            options.AddPolicy("HasAccess", policy => policy.AddRequirements(new HasAccessRequirment()));
        });
        // services.AddTransient<IFingerPrint, FingerPrint>();
        services.AddTransient<IAuthorizationHandler, HasAccessHandler>();
        services.AddTransient<IMvcControllerDiscovery, MvcControllerDiscovery>();
        services.AddMvc();
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app)
    {
        if (Environment.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseExceptionHandler("/Home/Error");
        }

        var cachePeriod = Environment.IsDevelopment() ? "600" : "604800";
        app.UseStaticFiles(new StaticFileOptions
        {
            OnPrepareResponse = ctx =>
            {
                ctx.Context.Response.Headers.Append("Cache-Control", $"public, max-age={cachePeriod}");
            }
        });
        app.UseHttpsRedirection();
        app.UseStaticFiles();
        app.UseRouting();
        app.UseCors();
        app.UseAuthentication();
        app.UseCookiePolicy();
        app.UseSession();
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllerRoute(name: "default", pattern: "{controller=UserProfiles}/{action=Index}/{id?}");
        });

please help me, what else I need to change when upgrating from asp.net core 2.1 to asp.net core 3.1 to not got this error Thank you
New Section Code Added
I think the issue is somewhere else by default in my startup code user redirects to this controller, from EndPoint
endpoints.MapControllerRoute(name: "default", pattern: "{controller=UserProfiles}/{action=Index}/{id?}");

in UserProfile Controller there is, a check if a user is not login, this function redirects to the user's login page
public async Task<IActionResult> Index(bool? passIsChanged = null) // userId
    {
        if (passIsChanged != null)
        {
            ViewBag.isSuccessed = passIsChanged;
        }
        int id = Convert.ToInt32(User.Identity.Name);
        var user = _context.UserAccountTbs.FirstOrDefault(a => a.UserId == id);
        if (user == null)
        {
            return RedirectToAction("UserLogin", "Logins");
        }

From UserProfile when GO to the login page this Error Happens

A: Use options.ExpireTimeSpan instead of options.Cookie.Expiration (which, yes, is ignored).
services.AddAuthentication(...)
   .AddCookie(options =>
   {
       options.LoginPath = "/Logins/UserLogin/";
       options.AccessDeniedPath = "/AccessDenied";
       options.ExpireTimeSpan = new TimeSpan(10, 00, 00);
   });


text:
Q: Parse Server Cloud Code background job query and update objects I have a Parse Server app hosted on back4app and I am running a Background Job that runs every minute and queries the Letters class, where the column deliveryDate is less or equal to the current date, here's my main.js file:
// DELIVER A LETTER
Parse.Cloud.job("deliverLetter", function (request, status) {
    var now = new Date();
    // var nowTime = date.getTime();

    var Letters = Parse.Object.extend("Letters");
    var query = new Parse.Query(Letters);
    query.lessThanOrEqualTo("deliveryDate", now);
    query.find().then (function (objects) {
        objects.forEach(function (obj) {
            obj.set("isDelivered", true);

            Parse.Cloud.useMasterKey();
            obj.save(null, { useMasterKey: true } ).then(function(obj) {
                response.success(obj);
            }, function(error) {
                response.error(error)
            });
    });
});

So, for instance, I save a row in the Letters class where deliveryDate is set to yesterday, in order for me to test this Cloud Code function. There's another column called isDelivered and it's set to False. So, my function above should set isDelivered into True and update my Letters's object.
But it doesn't work, so I don't know what I'm doing wrong.
Edit
Thanks to danh, I've fixed my code as it follows:
var Letters = Parse.Object.extend("Letters");
    var query = new Parse.Query(Letters);
    query.lessThanOrEqualTo("deliveryDate", now);
    query.equalTo("isDelivered", false);

    query.find().then (function (objects) {
        let savePromises = objects.map(function (obj) {
            obj.set("isDelivered", true);
            return obj.save(null, { useMasterKey: true } );
        });
        Promise.all(savePromises).then(function(obj) {
            response.success(obj);
        }, function(error) {
            response.error(error)
        });
    });

I would need to call another function from my main.js file which sends a push notifications and needs some parameters. I usually call it from my app, how would I call it from within that above function?
Parse.Cloud.define("pushiOS", function(request, response) {

  var user = request.user;
  var params = request.params;
  var userObjectID = params.userObjectID
  var data = params.data

  var recipientUser = new Parse.User();
  recipientUser.id = userObjectID;

  var pushQuery = new Parse.Query(Parse.Installation);
  pushQuery.equalTo("userID", userObjectID);

  Parse.Push.send({
    where: pushQuery,
    data: data
  }, { success: function() {
      console.log("#### PUSH SENT!");
  }, error: function(error) {
      console.log("#### PUSH ERROR: " + error.message);
  }, useMasterKey: true});
  response.success('success');
});

Maybe into Promise.all()?
Promise.all(savePromises).then(function(obj) {
     response.success(obj);

Parse.Cloud.define("pushiOS"...

}, function(error) {
    response.error(error)
});

A: Any save() that's in progress or not yet started when response.success() is called will be terminated (or won't get a chance to start). To fix, collect promises for all of the saves, and run them together with Promise.all(), which resolves only after all of the promises passed to it have resolved.
query.find().then (function (objects) {
    // Parse.Cloud.useMasterKey(); don't need this
    let savePromises = objects.map(function (obj) {
        obj.set("isDelivered", true);
        return obj.save(null, { useMasterKey: true } );
    });
    Promise.all(savePromises).then(function(obj) {
        response.success(obj);
    }, function(error) {
        response.error(error)
    });
});

Also, note, incidentally, that query.lessThanOrEqualTo("deliveryDate", now); will get all of the objects with deliveryDates before now, including the ones you processed previously.  That result will get monotonically longer over time, eventually exceeding the 1 minute between runs, or blowing some other system resource.
Maybe you really want...
query.lessThanOrEqualTo("deliveryDate", now);
query.equalTo("isDelivered", false);

EDIT
The second question can be handled by factoring a promise-returning push function like this...
function pushDataToUser(userID, data)
    var recipientUser = new Parse.User();
    recipientUser.id = userID;
    let pushQuery = new Parse.Query(Parse.Installation);
    pushQuery.equalTo("userID", userID);
    return Parse.Push.send({ where:pushQuery, data:data });
}

That can be called from cloud code like this...
Parse.Cloud.define("pushiOS", function(request, response) {
    let params = request.params;
    pushDataToUser(params.userObjectID, params.data).then(function() {
        console.log("#### PUSH SENT!");
        response.success('success');
    }, function(error) {
        console.log("#### PUSH ERROR! " + JSON.stringify(error));
        response.error(error);
    });
}

...and the new promise-returning function can be added to any other promise chain like this...
// function doSomething() returns a promise (like from a find() or a save()
return doSomething().then(function() {
    // initialize someId and someData
    return pushDataToUser(someId, someData)
});


text:
Q: HQL: Handling special characters I am trying to fetch value from database using HQL but am getting exceptions because value contains special characters. I am not able to figure out why.
Below is the code i am trying:
    HotelMapping hotelMapping = null;
    SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
    Session session = sessionFactory.openSession();

    Transaction tx = session.getTransaction();
    tx.begin();
    String hotelName = "A Fisher's Inn Motel";
    Query query = session.createQuery("from HotelMapping hm where hm.hotelID.hotelName='"+hotelName+"'");
    HotelMapping mapping = query.uniqueResult();
    }
    tx.rollback();

    sessionFactory.close();

The pojos look like below:
Hotel.java
public class Hotel{
    String hotelName;
    double price;
    //getters and setters
}

HotelMapping.java
public class HotelMapping{

     @OneToOne(cascade = CascadeType.ALL)
     Hotel hoteID

     String location;
}

The query string
Query query = session.createQuery("from HotelMapping hm where hm.hotelID.hotelName='"+hotelName+"'");  gives me below exception :
Exception in thread "main" org.hibernate.QueryException: expecting ''', found '<EOF>' [from com.pb.model.HotelMapping hm where hm.hotelID.hotelName='A Fisher's Inn Motel']

I tried escaping the apostrophe but with no luck. I ven tried setting the query parameter but again i got exception
query.setParameter("hotelName", "A Fisher's Inn Motel");

It says Exception in thread "main" org.hibernate.QueryParameterException: could not locate named parameter [hotelName]
Please if someone could help me achieving a generalized solution for the special character handling?

A: You should never use concatenation to pass dynamic parameters like this. This is not only not efficient, but also not robust (since a single quote in the parameter value makes the query invalid) and insecure, since a malicious user could pass a value that changes the semantics of the query (google for "SQL injection attack").
Instead, use parameters:
Query query = session.createQuery(
    "from HotelMapping hm where hm.hotelID.hotelName = :hotelName");
query.setString("hotelName", hotelName);


text:
Q: Unity, fresnel shader on raw image Hello I'm trying to archive the effect in the image below (that is like shine light but only on top of the raw image)
Unfortunately I can not figure out how to do it, tried some shaders and assets from the asset store, but so far no one has worked, also I dont know much about shaders.
The raw image is an ui element, and renders a render texture that is being captured by a camera.
I'm totally lost here, any kind of help will be appreciated, how to make that effect?

A: Fresnel shaders use the difference between the surface normal and the view vector to detect which pixels are facing the viewer and which aren't. A UI plane will always face the user, so no luck there.
Solving this with shaders can be done in two ways - either you bake a normal map of the imagined "curvature" of the outer edge (example), or you create a signed distance field (example), or some similar method which maps the distance to the edge. A normal map would probably allow for the most complex effects, and i am sure that some fresnel shaders could work with that too. It does however require you to make a model of the shape and bake the normals from that.
A signed distance field on the other hand can be generated with script from an image, so if you have a lot of images, it might be the fastest approach. Getting the edge distance in real time inside the shader would not really work since you'd have to sample a very large amount of neighboring pixels, which might make the shader 10-20 times slower depending on how thick you need the edge to be.
If you don't need the image to be that dynamic, then maybe just creating an inner glow black/white texture in Photoshop and overlaying it using an additive shader would work better for you. If you don't know how to write shaders, then maybe the two above approaches are a bit of a tall order.


text:
Q: In vue.js when building for production, I get a 404 error on files inside the static folder, even when the URL is correct I'm trying to get my application ready for production and everything is working perfect in dev. However, when I run the build and upload it to the server, it only loads the HTML, Javascript, some CSS and some files. It gives me a 404 error on a few files inside the 'static' folder (not all), even when those paths are correct and it should find the files inside there.
I should mention I've tried adding a base to the vue-router, as well as changing the webpack assetsPublicPath to (/folder/) since the app is being served inside a folder in the server. I've also tried assetsSubDirectory with 'static', './static' to no avail.
I used the default WPA template from the vue-cli when setting up the project.
Can anyone help me find what I'm doing wrong?

A: Static copys the files to /dist. Yes It works with webpack dev server

Example: You have a png file in the static folder.
The url is hostname/image.png insted of hostname/static.png

A: After doing some research I realized only .obj files were giving me the error (3D model files). So I found this answer which finally solved the issue:
Three.js Loading .OBJ error in Azure but not Locally


text:
Q: mpirun error of oneAPI with Slurm (and PBS) in old cluster Recently I installed Intel OneAPI including c compiler, FORTRAN compiler and mpi library and complied VASP with it.
Before presenting the question, there are some tricks I need to clarify during the installation of VASP:

*

*GLIBC2.14: the cluster is an old machine with a glibc version of 2.12, where OneAPI needs a version of 2.14. So I compile the GLIBC2.14 and export the ld_path: export LD_LIBRARY_PATH="~/mysoft/glibc214/lib:$LD_LIBRARY_PATH"

*ld 2.24: The ld version is 2.20 in the cluster, while a higher version is needed. So I installed binutils 2.24.

There is one master computer connected with 30 calculating nodes in the cluster. The calculation is executed with 3 ways:

*

*When I do the calculation in the master, it's totally OK.

*When I login the nodes manually with rsh command, the calculation in the logged node is also no problem.

*But usually I submit the calculation script from the master (with slurm or pbs), and then do the calculation in the node. In that case, I met following error message:
[mpiexec@node3.alineos.net] poll_for_event (../../../../../src/pm/i_hydra/libhydra/demux/hydra_demux_poll.c:159): check exit codes error
[mpiexec@node3.alineos.net] HYD_dmx_poll_wait_for_proxy_event (../../../../../src/pm/i_hydra/libhydra/demux/hydra_demux_poll.c:212): poll for event error
[mpiexec@node3.alineos.net] HYD_bstrap_setup (../../../../../src/pm/i_hydra/libhydra/bstrap/src/intel/i_hydra_bstrap.c:1062): error waiting for event
[mpiexec@node3.alineos.net] HYD_print_bstrap_setup_error_message (../../../../../src/pm/i_hydra/mpiexec/intel/i_mpiexec.c:1015): error setting up the bootstrap proxies
[mpiexec@node3.alineos.net] Possible reasons:
[mpiexec@node3.alineos.net] 1. Host is unavailable. Please check that all hosts are available.
[mpiexec@node3.alineos.net] 2. Cannot launch hydra_bstrap_proxy or it crashed on one of the hosts. Make sure hydra_bstrap_proxy is available on all hosts and it has right permissions.
[mpiexec@node3.alineos.net] 3. Firewall refused connection. Check that enough ports are allowed in the firewall and specify them with the I_MPI_PORT_RANGE variable.
[mpiexec@node3.alineos.net] 4. pbs bootstrap cannot launch processes on remote host. You may try using -bootstrap option to select alternative launcher.

I only met this error with oneAPI compiled codes but Intel® Parallel Studio XE compiled. Do you have any idea of this error? Your response will be highly appreciated.
Best,
Léon

A: Could it be a permissions error with the Slurm agent not having the correct permissions or library path?


text:
Q: Composition of template class I have a template class:
template<typename A, typename B>
class A {

};

In another .h file
template<typename A, typename B>
class A; //forward declaration

How could I declare m_A over here? I keep getting C++ forbids declaration of A with no type error:
class B {
  A* m_A;
};

A: If you don't know the types that you want to instantiate A with when inside of B, then you will have to also make a template out of B
template<typename A1, typename B1>
class B
{
   A<A1, B1>* m_A;
};

Either that, or you would have to instantiate A as a specific type, i.e.,
class B
{
    A<Type_1, Type_2>* m_A;
};

A: Declare m_A with some specific types for A:
class B
{
    A<int, char>* m_A;
}

If you B is such that you don't know a priori what types should be used in the m_A declaration, perhaps B needs to be template class and you'd use those type parameters in the declarion of m_A.

A: Templates are nice little peculiar beasts. The template definition must be available for the compiler at the place of instantiation, so the most common pattern is defining the template in the header so that each translation unit that uses the templated methods (and thus instantiates them) will have access to the definition.
Alternatively, you can provide the template definitions in a single translation unit, but you will have to ensure that you are instantiating the template for all the types for which you use it in the whole program.
// header
template <typename T> struct A
{
   void foo( T );
}

// single translation unit
#include "header"
template <typename T>      // template member definitino
void A<T>::foo( T x ) {
   std::cout << "A(" << x << ")" << std::endl;
}
template struct A<int>;    // explicit instantiation for int
template struct A<double>; // explicit instantiation for double

// main
#include "header"
int main() {
   A<int> ai;
   ai.foo( 5.5 ); // will print 5 (int rounded down)
   A<double> ad;
   ad.foo( 5.5 ); // will print 5.5
   A<char> ac;
   ac.foo( 'a' ); // linker error, A<char>::foo undefined
}

Because in general templates are meant to be used with any type through the program, defining the template methods in a single translation unit and using explicit instantiation is not a good idea. On the other hand, in the few cases where you need to control the set of types for which the template is instantiated, or under a few other circumstances (reducing large compile times [*]) you might want to follow this second approach. But again, in the general case, it is simpler to define the member functions in the header, and again it is simpler to defined them inside the class definition.
[*] Templates are compiled in all translation units in which they are used, which means that if you instantiate A<int>::foo in 5 different translation units, the compiler will compile it 5 times, and then the linker will discard 4 of the instantiations. In some cases where the template is complex, it might be an advantage to compile it once in one translation unit and just call it from the others. Note that with explicit instantiation, all member functions are compiled, while with implicit instantiation (at the place of use) only those members that are actually used will get compiled, so depending on the situation, explicit instantiation may be more costly than implicit instantiation (in classes with many members)

A: template<typename A>
void B<A>::function()
{
}
Btw, do not separate definitions and declarations while writing a template class.
EDIT:
changed < to < and > to >
Before that code looked like:
template
void B::function()
{
}


text:
Q: Cutting a pandas DataFrame into small blocks and do simple calculations on each block I want to divide pandas DataFrame columns into blocks of 3 and find the mean of each block for each row.
Towards that end, by using a for-loop, I created a list of DataFrames by cutting them into blocks of 3, found their mean and reshaped it back into the shape I want.
The following code does the job:
df = pd.DataFrame(np.random.rand(2000,100))
blocks = [df.iloc[:,i:i+3] for i in range(0,df.shape[1],3)]

list_df = []
for quarter in range(0,len(blocks)):
    list_df.append(blocks[quarter].T.mean())
df = np.reshape(list_df,(len(blocks),len(blocks[0]))).T
df = pd.DataFrame(df)

The problem is, this is incredibly slow (given the size of my data, the for-loop is really taking its time). My question is, is there a more efficient way to do it? Specifically, are there any built-in pandas functions that do the same job?

A: I think you can do it directly by specifying axis=1 in mean on the selection of the 3 columns in the list comprehension. then use it in pd.concat
df_ = pd.concat([df.iloc[:,i:i+3].mean(axis=1) for i in range(0,df.shape[1],3)],
                axis=1, ignore_index=True)

In the specific case where the number of columns is a multiple of 3 (not like in your example but just in case for your real data), you could use to_numpy, reshape and mean along the last axis, it should even be faster.
pd.DataFrame(df.to_numpy()
               .reshape(df.shape[0], df.shape[1]//3, 3)
               .mean(axis=-1)
            )

A: First, I assume your index is the usual 0, 1, ... Then, simply
df.groupby(df.index//3).mean()

should do the trick.


text:
Q: Retrieve date, month, year from a date in php I have this piece of code which gets me a field from the database:
$end_date=$row1['end_date'];

If i print it it gives me something like: 25-09-2012
What i need is to get the month value, the year and date.
something like:
$month=09;
$day=25;
$year=2012;

How can i do that?
thanks!

A: Using DateTime:
$date = new DateTime($row1['end_date']);
$year = $date -> format('Y');
$month = $date -> format('m');
$day = $date -> format('d');

If your timestamps are all like the one provided, keep it simple:
list($day, $month, $year) = explode('-', $row1['end_date']);

A: In your case, you can use the explode function like this :
// store a string containing "25-09-2012"
$end_date = $row1['end_date'];

// split "25-09-2012" into an array of three elements
$thedate = explode("-", $end_date);

// retrieve the values
$month = $thedate[0]; // 25
$day = $thedate[1]; // 09
$year = $thedate[2]; // 2012

A: try
[month('end_date')]
[day('end_date')]
[year('end_date')]
Or use explode and use - as the delimiter

A: Take a peak at this helpful tutorial describing various formatting methods and useful date functions in PHP:
Date/Time Functions
Date Formats

A: $values = getdate(strtotime($row1['end_date']));
echo $values['mon']; //month
echo $values['mday']; //day
echo $values['year']; //year

A: A. You can use DateTime
$date = DateTime::createFromFormat('d-m-Y',$row1['end_date']);
$month = $date->format("m");
$day = $date->format("d");
$year = $date->format("Y");

B. Using strtotime
$date = strtotime($row1['end_date']);
$month = date("m", $date);
$day = date("d", $date);
$year = date("Y", $date);

C. You can just sscanf scan through the string
$date = sscanf($row1['end_date'], "%d-%d-%d");
$month = $date[0] ;
$day =  $date[1] ;
$year =  $date[2] ;

D. Another method is using list & explode
list($day, $month, $year) = explode('-', $row1['end_date']);

A: Do it on a single line and format it however you would like.  (Dec, December, 12) and so on with date().
list($month, $day, $year) = explode('-', date('m-d-Y', strtotime($row1['end_date'])));


text:
Q: How to JOIN data from query with list of data? Two tables with some data in the second one.
CREATE TABLE IF NOT EXISTS dst (
  id integer NOT NULL,
  content varchar(200) NOT NULL);

CREATE TABLE IF NOT EXISTS src (
  id integer NOT NULL,
  name varchar(200) NOT NULL);

INSERT INTO src VALUES('100', 'ET'), ('200', 'Luke'), ('300', 'Jojo');

Now, I insert one selected id from src and some other list of values. So the result should look like this:
200, one
200, two
200, three

And this is my try of
INSERT INTO dst (id, content)
SELECT * FROM ((SELECT id FROM src WHERE name = 'Luke') AS bar
CROSS JOIN ('one', 'two', 'three')) AS foo;

The issue is how can I put the second argument for JOIN - ('one', 'two', 'three'), because this way doesn't work. ERROR: syntax error at or near "'one'"

A: Use UNION ALL (in your case you didn't alias the column of the second subquery. e.g. as content, and comma seperated strings ('one','two','three') will not work, should be converted to a query )
INSERT INTO dst (id, content)
 SELECT bar.id, foo.content
   FROM
   (
    ( SELECT id FROM src WHERE name = 'Luke' ) as bar
    CROSS JOIN
    (
     SELECT 'one' as content UNION ALL
     SELECT 'two' UNION ALL
     SELECT 'three'
    ) as foo
   )

A: An alternative solution is to use unnest() - this will convert an array into rows:
select
    unnest(array['one', 'two', 'three']::varchar[]) as content

Would yield
content (varchar)
---------------
one
two
three

This is implicitly cross joined when used in a select statement:
insert into dst (
    id,
    content
) (
    select
        src.id,
        unnest(array['one', 'two', 'three']::varchar[])
    from
        src
    where
        src.name = 'Luke'
);


text:
Q: python beautifulSoup findAll I am having an issue getting all of the data from this site...
The section of the code I cannot get to produce all of the data is "pn"
I am hoping this code would product these numbers from the site.
58312-GA4
58312-RG4
58312-RR$
I have tried a number of things from switching the tags and classes and going back and fourth with find, findAll, and find_all and no matter what I try I am getting only one result.
Any help would be great - thanks
Here is the code:
theurl="http://www.colehersee.com/home/grid/cat/14/?"
thepage = urllib.request.urlopen(theurl)
soup = BeautifulSoup(thepage,"html.parser")

for pn in soup.find('table',{"class":"mod_products_grid_listing"}).find_all('span',{"class":"product_code"}):
    pn2 = pn.text
for main in soup.find_all('nav',{"id":"breadcrumb"}):
    main1 = main.text

    print(pn2)
    print (main1)

A: You're running the for loop for getting the 'pn' value quite separately from the for loop for the 'main' value. To be specific, by the time your code reaches the second for loop, the previous for loop has already executed in its entirety.
This results in the variable pn2 getting assigned the last value that was returned by the for loop.
You might want to do something like
pn2 = []
for pn in soup.find('table',{"class":"mod_products_grid_listing"}).find_all('span',{"class":"product_code"}):
    pn2.append(pn.text)


text:
Q: Listview filter without using searchview or edittext I have created a list view in android and I already implement search filter by using searchview and charsequence as parameter like this
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String query) {
                adapter.getFilter().filter(query);
                return false;
            }
        });

so we must type something in searchview.
can anyone tell me please if there is a way to filter the list adapter in android instead of charsequence we use string?so we dont have to type something as parameter but for example adapter.getFilter().filter("example");


text:
Q: Как задать таску с небольшим отличием для каждого сервера У меня есть есть список хостов:
192.168.77.101 ansible_user=vagrant ansible_ssh_pass=vagrant
192.168.77.102 ansible_user=vagrant ansible_ssh_pass=vagrant
192.168.77.103 ansible_user=vagrant ansible_ssh_pass=vagrant

Для каждого из них мне необходимо выполнить команду:
echo "1" > /data/zookeeper/myid

Но число после echo у каждого сервера будет свое (от 1 до 3). Есть ли простой способ сделать это?

A: Например, можно так:
192.168.77.101 ansible_user=vagrant ansible_ssh_pass=vagrant echo=1
192.168.77.102 ansible_user=vagrant ansible_ssh_pass=vagrant echo=2
192.168.77.103 ansible_user=vagrant ansible_ssh_pass=vagrant echo=3
...
tasks:
- name: set
  copy:
    content: "{{ echo }}"
    dest: /data/zookeeper/myid


text:
Q: django returning 'AnonymousUser' object has no attribute '_meta' error I am developing a feature, when a user registers it automatically logs the user in
but i get 'AnonymousUser' object has no attribute '_meta' error.
but when i use the same code to login the user it works fine.
my forms.py:
from django.contrib.auth.forms import UserCreationForm
from django import forms
from django.core.exceptions import ObjectDoesNotExist
from django.contrib.auth.models import User
from .models import *

class RegisterForm(forms.Form):
    fname = forms.CharField(error_messages=(), widget=forms.TextInput(attrs={"class":"fname entry", "placeholder":"First Name"}), required=True)
    lname = forms.CharField(error_messages=(), widget=forms.TextInput(attrs={"class":"lname entry", "placeholder":"Last Name"}), required=True)
    phone = forms.CharField(error_messages=(), widget=forms.TextInput(attrs={"class":"phone entry", "placeholder":"Phone Number"}), required=True)
    password = forms.CharField(widget=forms.PasswordInput(attrs={"class":"password entry", "placeholder":"Password", "autocomplete":"off"}), required=True)
    password2 = forms.CharField(widget=forms.PasswordInput(attrs={"class":"password entry", "placeholder":"Confirm Password", "autocomplete":"off"}), required=True)

    def clean(self, *args, **kwargs):
        fname = self.cleaned_data.get("fname")
        lname = self.cleaned_data.get("lname")
        phone = self.cleaned_data.get("phone")
        password = self.cleaned_data.get("password")
        password2 = self.cleaned_data.get("password2")

        if phone and password and fname and lname and password2:

        try:
            user = User.objects.get(phone=PhoneNumber.objects.get(number=phone))
            if user:
                raise forms.ValidationError("user exists login instead")

        except ObjectDoesNotExist:
            pass

        if password!=password2:
            raise forms.ValidationError("passwords didn't match")

        else:
            if len(password)<8:
                raise forms.ValidationError("short password! password should be longer than 8")

in my forms i have a registration form which does not inherit from django's user creation form.
my views.py:
def registerView(request):
    if request.method == "POST":
        form = RegisterForm(request.POST)
        if form.is_valid():

           fname = form.cleaned_data.get("fname")
           lname = form.cleaned_data.get("lname")
           username = generate_username(fname, lname)
           phone = form.cleaned_data.get("phone")

           u = User.objects.create_user(email="", first_name=fname, last_name=lname, username=username, is_active=False)
           u.set_password(form.cleaned_data.get("password"))
           u.save()
           p = PhoneNumber(user=u, number=phone)
           p.save()

           phone = PhoneNumber.objects.get(number=phone)
           u = User.objects.get(phone=phone)
           userLogin = authenticate(username=username, password=u.password)

        login(request, userLogin)
        return redirect('home')

  else:
    form = RegisterForm()

  return render(request, 'main/register.html', {'form':form})

my loginView:
def loginView(request):
    if request.method == "POST":
       form = LoginForm(request.POST)
       if form.is_valid():
          phone = PhoneNumber.objects.get(number=form.cleaned_data.get('phone'))
          u = User.objects.get(phone=phone)
          user = authenticate(username=u.username, password=form.cleaned_data.get('password'))
          login(request, user, backend='django.contrib.auth.backends.ModelBackend')
          print('success')
          return redirect('home')

    else:
        form = LoginForm()

    return render(request, 'main/login.html', {'form':form})

i have imported everything i need. the same code works with the loginView function but it doesn't work on registerView
What should i do to fix this?

A: You have this line in your view:
userLogin = authenticate(username=username, password=u.password)

The point to be noted here is that u is an instance of the user model and u.password will give the hashed password while authenticate expects it to be a raw password and hence returns None. In fact you don't even need to use authenticate while registering as you already have the user instance:

def registerView(request):
    if request.method == "POST":
        form = RegisterForm(request.POST)
        if form.is_valid():
            fname = form.cleaned_data.get("fname")
            lname = form.cleaned_data.get("lname")
            username = generate_username(fname, lname)
            phone = form.cleaned_data.get("phone")

            # removed `is_active=False` as per comment by @Nahu Gere
            user = User.objects.create_user(email="", first_name=fname, last_name=lname, username=username) # better variable name
            user.set_password(form.cleaned_data.get("password"))
            user.save()
            phone = PhoneNumber(user=user, number=phone)
            phone.save()
            login(request, user) # Directly use saved user instance
            return redirect('home')
    else:
        form = RegisterForm()
    return render(request, 'main/register.html', {'form':form})

A: I got this error because In my register view, I had this code:
user.is_active = False
user.save()

then I had so the user got logged in automatically after registering an account.
user = authenticate(username=user.username, password=raw_password)
login(request, user)

I solved it by commenting out the auto login
# user = authenticate(username=user.username, password=raw_password)
# login(request, user)


text:
Q: libtdms: How to access the metadata of the .tdms file in order to process it? For reading .tdms file with c++ I downloaded libtdms from sourceforge.net. I use Visual Studio 22 on Windows so I also installed MinGW for executing the Makefile.

*

*The library does what it should, reading the .tdms file, but I dont know how to access the data in order to process and visualize it. Do I have to look inside the variables of libtdms?
Is there an easier way of outputting some kind of table with all the informations without getting deep into the code. (not that easy as mechanical engineer)

*How do I include the full library dictionary with its makefiles into a possible programm?
So far i only included single .h files when programming
My goal is to get measurements from the .tdms file (values, coordinates,...) an then use them for plotting datapoints 2D and 3D.
this kind of output would be helpful for processing the data further


text:
Q: How to do greater than X and less than Y in VB? Here is what I have tried... which is completely wrong I assume, as it did not work.
If ProgressBar1.Value > 5 < 20 Then
    Label8.Text = "Hello"
End If

All help is greatly appreciated! Thank you.

A: If ProgressBar1.Value > 5 AndAlso ProgressBar1.Value < 20 Then
    Label8.Text = "Hello"
End If

Is one way.
AndAlso means that the condition will 'short circuit' if the first value evaluates to false.  So if ProgressBar1.Value is not > 5 - it won't bother checking the rest of the condition.
You could also write it using And
If ProgressBar1.Value > 5 And ProgressBar1.Value < 20 Then
    Label8.Text = "Hello"
End If

and it would evaluate both conditions.  In this particular case, it won't make much difference, but I generally prefer AndAlso/OrElse over And/Or

A: You have to do an and statement using the "And" line. It should look something like this
If ProgressBar1.Value > 5 And ProgressBar1.Value < 20 Then
    Label8.Text = "Hello"
End If

Additionally you can use the "or" statement if you just want one of them to be true.


text:
Q: How to declare Map from constructor (key) and class instance (value) in Typescript? Following code has error with component.constructor (Entity constructor and addComponent and removeComponent methods).
Error: Argument of type 'Function' is not assignable to parameter of type 'typeof Component'.
How I can declare Map where is key = Class constructor, value = Class instance?
declare class Component {
  constructor(...argArray: any[]);
}

// declare type MapOfComponents = Map<{new(): Component}, Component>
declare type MapOfComponents = Map<typeof Component, Component>

export default class Entity {
  static id = 1;

  id: number;
  components: MapOfComponents = new Map();

  constructor(components?: Array<Object>) {
    this.id = Entity.id++;

    components.forEach((component) => {
      this.components.set(component.constructor, component);
    });
  }

  addComponent(component: Component): this {
    this.components.set(component.constructor, component);
    return this;
  }

  removeComponent(component: Component): this {
    this.components.delete(component.constructor);
    return this;
  }

  hasComponent(ctr: typeof Component): boolean {
    return !!this.components.get(ctr);
  }

  getComponent(ctr: typeof Component): Object {
    return this.components.get(ctr);
  }
}

A: A constructor is a function, so you can write:
declare type MapOfComponents = Map<Function, Component>


text:
Q: Send Email From Specific Outlook Account Via Python? I had some code that was written to email lab users whenever certain processes had finished running. This was sent from a gmail account, using SMTP.
However, my supervisor wants the mail to be sent from an official department address, which means that I have use Outlook and MAPI. I've had an account created which I want the email to originate from regardless of the lab machine the job is being run on. The problem is that I can only get email to send from the local Outlook account, and not all of the lab machines have a local account.
import win32com.client as win32
outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = 'user@domain.com'
mail.Subject = 'Message Subject'
mail.body = 'Message text. Message text'
mail.send

Surely there's a way to specify the username/password/server that I want the email to be sent from?

A: The Outlook object model doesn't provide anything for configuring profiles. However, if you have an account configured in Outlook you may find the SendUsingAccount property of the MailItem class helpful. It allows to set an Account object that represents the account under which the MailItem is to be sent.
You may find the following links helpful:

*

*Configure Outlook Mail Settings Programmatically?

*White paper: Configuring Outlook profiles by using a PRF file

A: As Eugene suggested, you can either manually create a POP3/SMTP account and assign it to the MailItem.SendUsingAccount property prior to calling Send, or you can create a new POP3/SMTP account dynamically using Redemption (I am its author) and its RDOSession.Accounts.AddPOP3Account method.

A: I know this comes very late but this is how I've managed to select a specific e-mail address to send the e-mail from. The address needs to be among your outlook addresses.
import win32com.client as win32

outlook = win32.Dispatch('outlook.application')

mail = outlook.CreateItem(0)
mail.Subject = "Test subject"
mail.To = "yourrecipient@gmail.com"

# If you want to set which address the e-mail is sent from.
# The e-mail needs to be part of your outlook account.
From = None
for myEmailAddress in outlook.Session.Accounts:
    if "iongroup.com" in str(myEmailAddress):
        From = myEmailAddress
        break

if From != None:
    # This line basically calls the "mail.SendUsingAccount = xyz@email.com" outlook VBA command
    mail._oleobj_.Invoke(*(64209, 0, 8, 0, From))

mail.Send()


text:
Q: How to send the Access Token in order to access AWS services - BEGINNER I followed the following tutorial and got the facebook login working. At the end it prints out the accessToken which is great.
FB.login(function (response) {

  // Check if the user logged in successfully.
  if (response.authResponse) {

    console.log('You are now logged in.');

    // Add the Facebook access token to the Cognito credentials login map.
    AWS.config.credentials = new AWS.CognitoIdentityCredentials({
      IdentityPoolId: 'IDENTITY_POOL_ID',
      Logins: {
        'graph.facebook.com': response.authResponse.accessToken
      }
    });

    // Obtain AWS credentials
    AWS.config.credentials.get(function(){
        // Access AWS resources here.
             console.log('Access Token is '+ AWS.config.credentials.identityId);
         var s3= new AWS.s3();

    });

  } else {
    console.log('There was a problem logging you in.');
  }

});

I believe that the following line of code Logins: {
            'graph.facebook.com': response.authResponse.accessToken
          } will register the accessToken in Cognito. Correct me if i am wrong.
My problem is, Should I save this accessToken and pass it when ever I am communicating with an AWS service (for example : DynamoDB write Item or else while adding a file to S3) ?
If so How can I do it ? (I have almost googled the entire web and found none on this)
** Note: I think the purpose of a accessToken is to add some security when the user request to access an AWS service. So in that case How can I use the accessToken to validate ?

A: Once you give it to Cognito in a call to get some credentials, Cognito will registered it to, and will give back credentials scoped to, that authenticated identity.
Those credentials alone will map back to that token, so all you need to give to other AWS clients when accessing them is the credentials. That being said, once those credentials have expired, you will need to have the token still handy to get more for that authenticated identity. Cognito requires at least one token linked to an authenticated identity to get credentials for it.


text: Q: QGIS: an offset line symbol works fine in layout but not in exported image In QGIS (multiple versions), I have 2 overlapping lines. For clarity i use offset on one of them in the symbol properties. This looks fine in layout manager, the lines are next to each other. When i export as image, the two lines are on top of each other again, as if it doesn't use the offset value anymore.


text:
Q: How should I understand the generalized velocity? I have a doubt, I don't know how to understand generalized velocities,  I have seen in the books that they are used like variables. But if they are the derivatives of generalized coordinates, why are they not functions?
I don't know if the generalized velocities are functions, parameters, variables or coordinate axes?

A: First, we can call 'variable' anything that is not a constant, so generalized velocities will generally be variables, though, depending on the problem, they could also be constants.
On the other hand, generalized velocities are always functions of time, so they are indeed functions. When the function of time is constant, then obviously the corresponding generalized velocity is a constant. However, in general the function of time will not be constant, so the corresponding generalized velocity will be a variable.
In general, we don't call generalized velocities parameters, however, 'parameter' is such a general term in physics that in the right context anything can be called a parameter. For any purpose in Lagrangian Mechanics, it is best to think of time as the only parameter.
Finally, you can view generalized velocities as coordinate axes. It is similar to how you view generalized coordinates as coordinate axes. However, they are axes corresponding to different spaces, i.e. the velocity space and the coordinate space.


text:
Q: how to load a page with popover in ionic4 How to load (lazy load) a page and not a component from popover in ionic 4?
I try like this:
  async CreateContent(ev: any) {
    const popover = await this.popoverCtrl.create({
      component: 'ContentPopoverPage',
      event: ev,
      translucent: true
    });
    popover.onDidDismiss().then((res: any) => {
      if (res.data !== undefined && res.data != null) {
        const gallery: IGallery = res.data.contentData;
        this.galleryList.unshift(gallery);
      }
    });

    return await popover.present();
  });

and the error result is:

ERROR Error: Uncaught (in promise): Error: No component factory found
  for ContentPopoverPage. Did you add it to @NgModule.entryComponents?

A: i had routing in content-popover.module.ts like this:
const routes: Routes = [
  {
    path: '',
    component: ContentPopoverPage
  }
];

so i change path from '' to something in my app.routing.module
const routes: Routes = [
  {
    path: 'content-popover',
    component: ContentPopoverPage
  }
];

after that i imported ContentPopoverPageModule in my gallery.module
@NgModule({
  imports: [
    ContentPopoverPageModule,
    CommonModule,
    ...

finlay in my gallery.ts file:
  import { ContentPopoverPage } from '../content-popover/content-popover.page';

  async CreateContent() {
    const popover = await this.popoverCtrl.create({
      component: ContentPopoverPage
  });

    popover.onDidDismiss().then((data: any) => {
    });

    await popover.present();
 }


text:
Q: jQuery selectors for list elements I am using jQuery and jQuery UI.
Using the getJSON function, we are creating list elements and appending them to an OL element. Here's the code:
$.getJSON("http://localhost/b/t.php", function(data){

        $.each(data, function(i, thet){
            //alert(thet.fname)
            var t = '
' + thet.pid + ' ' + thet.fname + ' ' + thet.lname + '
';

            $(t).appendTo("#" + thet.tour + 'list');

        });
    });

I am trying to select list elements using jQuery. If I manually put a list in the HTML page, it will work. However, programatically appending the list items to an OL, doesn't allow it to select - at least from what I've tried.
$('li:last-child').css({color: 'red', backgroundColor: 'black'});

I've tried using ID's and many other multiple selectors, to no avail.
Any ideas?

A: When are you trying to execute that command that colors the list items?  I believe you'll have to put at the end of the callback function of getJSON as follows:
$.getJSON("http://localhost/b/t.php", function(data){
    $.each(data, function(i, thet){
        //alert(thet.fname)
        var t = '
' + thet.pid + ' ' + thet.fname + ' ' + thet.lname + '
';

        $(t).appendTo("#" + thet.tour + 'list');
    });
    $('li:last-child').css({color:'red',backgroundColor:'black'});
});


text:
Q: How to send mails from plsql I am in need of sending emails to recipients from my oracle procedure, however i am restricted to use UTL_MAIL and UTL_SMTP. Other than these i am not aware of any other way of sending mails.
Also is tehre a way to connect to unix from oracle plsql code so that i can use mailx -s and trigger the mail.
Can you please help me here.

A: UTL_MAIL and UTL_SMTP are the supported way to generate e-mail from PL/SQL and should offer a less complicated design than executing a shell script. It would also be much more secure. That said, the following links describe several different ways to execute OS scripts from within PL/SQL:

*

*http://www.dba-oracle.com/t_execute_shell_script_plsql_procedure.htm

*https://www.oracle.com/technetwork/database/enterprise-edition/calling-shell-commands-from-plsql-1-1-129519.pdf

*https://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:9533837800346646784

*https://oracle-base.com/articles/8i/shell-commands-from-plsql


text:
Q: Is there a trend toward not capitalizing the word Bible? Just in the past few months, I've been coming across the word bible as a lowercase word. I'm not talking about the word as used in, say, "the fisherman's bible," or such similar uses; rather, the appearance of the word when it clearly refers to the Holy Bible, as in the Judeo-Christian Scriptures.
As a lifelong Christian, I am somewhat concerned (assuming tentatively there is a trend) that the use of the word bible, when referring to the Holy Bible, may be related to a general devaluing of this traditionally sacred book.
My questions, then: a) "Is there a trend toward replacing the capital B in Bible with a lowercase b?"; and b) Are there data that substantiate this trend, if in fact it is a trend?

A: Generally speaking, capital letters are used with proper nouns while lowercase letters are used with common nouns.
For example:

1. I met President Trump.
  2. I met the president.

In the first sentence, President is part of a specific title, but in the second sentence, it's simply a generic class.

This specific distinction is also made clear by, for example, the definition of bible at Merriam-Webster:

1 capitalized, religion
a : the sacred scriptures of Christians comprising the Old Testament and the New Testament
b : the sacred scriptures of some other religion (such as Judaism)
3 capitalized, religion : a copy or an edition of the Bible
  // gave each of her grandchildren a Bible
4 : a publication that is preeminent especially in authoritativeness or wide readership
  // the fisherman's bible
  // the bible of the entertainment industry

Bible is (normally) only capitalized if it's talking about a specific religious text. (Or if it's the actual title of something.)

The question is somewhat confusing, however, because it starts off by implying that this distinction is already clear. It also seems to at least imply that it's not asking about the difference between a common noun and a proper noun, but the incorrect use of the lowercase when it comes to the proper noun in the case of the Bible itself.
In other words, it could be paraphrased like this:

Has anybody noticed a recent trend of writing Holy bible rather than Holy Bible?

If that's really what's being asked, then I'd agree that this would be unusual. It wouldn't follow common conventions of style or punctuation.
But the claim would also need to be backed up by some kind of metric or other objective evidence to show that there actually is such a trend—and one which could then be explained in some way. As a simple statement, it could just be a subjectively increasing annoyance over seeing a mistake—like any other mistake in grammar—that only appears to be increasingly common.

A: I am not able to supply a direct answer to "Is there a trend...?" and "Are there data...? And I sense that it may be difficult to find anyone who is.
If it helps I can, though, express my own view about the matter, which may to some extent reflect the attitudes of others.
For me it would depend on context.
If I were saying Holy Bible I would always use a capital HB - not necessarily for religious reasons. I would do the same for Austen's Pride and Prejudice as it is the name of a work of literature.
However "bible" and words deriving from it e.g. "biblical", written alone, I would normally not capitalise - for the reason that it would only be a shorthand informal everyday reference to the HB.
If I were saying something like "Following the sale at the bookshop there were a number of bibles left on the shelf" - I don't think I would use a capital B. I'm not sure why, but it just seems inappropriate to me.
But if I wanted to draw attention to the sacredness or the majesty of a quotation I would either write "Holy Bible", or possibly Bible with a capital, if it felt appropriate to do so.
In a footnote it would be important to refer to the particular translation - such as Authorised Version
 and subsequently "AV". But far more likely, most authors would quote the name of the book of the bible - such as Deuteronomy, followed by "AV" - which would always be capitalised.
As a clergyman once told me, in my youth, "the bible isn't a book - it is a library".


text:
Q: Print Windows mapping of root path in MSYS Bash In MSYS Bash I get:
$ cd ~
$ pwd
/c/Users/antonio

but:
$ cd /
$ pwd
/

Can I get the full Windows absolute path from Bash?

A: In recent versions, e.g. MSYS2, you can use:
~$  cygpath -w /
C:\path\to\root

or with a mixed path style:
~$  cygpath -m /
C:/path/to/root

Similarly, you might use:
~$  cygpath -w ~
C:\path\to\home
~$  cygpath -m ~
C:/path/to/home


text:
Q: Children processes created in ASP.NET Core Process gets killed on exit I'm spawning a child process in ASP.NET Core (.NET Framework) with Process class:
var process = new Process
            {
                StartInfo = new ProcessStartInfo(executableDir)
                {
                    Arguments = commandDefinition.CommandDef.ArgumentsAsString,
                    RedirectStandardOutput = true,
                    RedirectStandardError = true,
                    UseShellExecute = false,
                    CreateNoWindow = true,
                    WorkingDirectory = _contentPath,
                },
            };

process.Start()

As far as I understand when parent (ASP.Net Core) process gets killed, the children process should stay alive. I have tested this behaviour using two console applications and children process never gets killed after killing parent process.
However when I spawn a new process in ASP.NET Core then children process gets killed when:

*

*IIS recycles app.

*MSDeploy publishes a new version of ASP.NET Core app.

*When using dotnet watch and the application is restarted during to
code change.

It doesn't get killed ONLY if parent is killed through task manager.(after some tests it's not always the case)
From the above I suspect that there is a mechanism in ASP.NET Core that kills all children processes on successful exit. Is it documented somewhere? Is there a way to avoid it? I couldn't find any info about such behaviour.
Edit:
The repro is actually pretty easy.

*

*Create ASP.NET Core project (.NET Framework or .NET Core, doesn't matter)

*Add below code somewhere to your Startup class

*Start web app. It will be hosted under IIS Express. The calc process will start. Now either kill your app through task manager or close it through IIS express tray icon.

*Calc process will get killed. (Sometimes you need to try to refresh the your offline webpage)

 var process = new Process
 {
      StartInfo = new ProcessStartInfo("calc.exe")
      {
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            UseShellExecute = false,
            CreateNoWindow = true,
      },
 };
 process.Start();

Edit2: The issue seems to be in IIS. I have two profiles in launchSettings.json. If I run it with IISExpress then it gets closed, however when using a second one it lives.
"IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "WebApplication3Core": {
      "commandName": "Project",
      "launchBrowser": true,
      "launchUrl": "api/values",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      },
      "applicationUrl": "http://localhost:52135/"
    }

Edit4:
I did some research with process monitor and here is the output:

As you can see in ss1 that there is a "Process Exit" operation with iisexpress, then there are many irrevelant logs and after some time there is a Process Exit for calc.exe. It's not any different than normal exit. The only difference is the latter log which says "CloseFile" and path to my web app, I don't know what it actually means.
It's definitely iis who kills calc.exe. I have IIS Express 10.0.14358 version (Server version where I found this is also 10)

A: As I said in my comment, there is a Job Object which is created by ASP.NET core in the out-of-process scenario. The relevant source code portion is here:
https://github.com/aspnet/AspNetCore/blob/master/src/Servers/IIS/AspNetCoreModuleV2/OutOfProcessRequestHandler/serverprocess.cpp#L89
HRESULT
SERVER_PROCESS::SetupJobObject(VOID)
{
    HRESULT                                 hr = S_OK;
    JOBOBJECT_EXTENDED_LIMIT_INFORMATION    jobInfo = { 0 };

    if (m_hJobObject == NULL)
    {
      ....
            jobInfo.BasicLimitInformation.LimitFlags =
                JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;

            if (!SetInformationJobObject(m_hJobObject,
                JobObjectExtendedLimitInformation,
                &jobInfo,
                sizeof jobInfo))
            {
                hr = HRESULT_FROM_WIN32(GetLastError());
            }
        }
    }

    return hr;
}

As per documentation, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE:

Causes all processes associated with the job to terminate when the
  last handle to the job is closed.

If you dig the source further, it does not seem to be optional.
Now, you can actually see this by yourself, if you reproduce your steps. Use Process Explorer, and navigate to your dotnet.exe process, this is what it will display:

*

*note 1: in fact calc.exe stays alive (at least in my Windows 10 installation because it's now a WinRT app, so it will not end up as child of dotnet.exe), that's why I used notepad.exe

*note 2: iisexpress.exe also creates a job object, but it's configured as breakaway ok, which means it won't kill child processes.

*note 3: if you run from Visual Studio (not my screenshot), you may see an intermediary VSIISExeLauncher.exe process between iisexpress.exe and dotnet.exe. This one also creates a Job Object with 'kill on close' to add to the confusion...

A: Edit

Solution not working for notepad.exe - I will try to see if there is
  any optionn based on Simon's answer as yo why this behaviour happens

Old answer (to be removed)
I have to wash my hands now for writing this code, but I think you can work around this limitation if that is what you need in your context. I advise against running external processes, especially
from the "web server". It's asking for trouble. Replacing the process by some malicious person, credential escalation, unexpected behaviour because of syntax changes just to name a few.
Anyway this  might work for you (interposing cmd.exe in between, to try to break the child-parent relationship):
var process = new Process
{
  StartInfo = new ProcessStartInfo
      {
         FileName ="cmd.exe",
         Arguments = "/c calc.exe",
         WindowStyle =  ProcessWindowStyle.Hidden
      }
};

process.Start();


text:
Q: How can i get JavaFX working on raspberry pi 3 please can someone provide me with simple step by step instructions for getting javafx working on raspberry pi 3. I have tried all day to add javafx to raspberry pi 3 and i am still getting the error:
"JavaFX deployment library not found in the active JDK"
in netbeans when i try to build, even though there are no errors showing in my code.
I downloaded the gluon community build for javaFX embedded sdk here: http://gluonhq.com/labs/javafxports/downloads/
and followed the instructions here: http://docs.gluonhq.com/javafxports/
please can anyone offer any easy to follow advice on getting javaFX working on raspberry pi 3! i am quite new to linux

A: If you have read the documentation here, under 2.1.4 Prerequisites for Embedded:

*

*Download the latest version of JDK 8 for ARM to your embedded device, available from here. You will have to download this file: http://download.oracle.com/otn-pub/java/jdk/8u91-b14/jdk-8u91-linux-arm32-vfp-hflt.tar.gz
You can download it to your computer first, and then move it to the Pi, or directly download it from the Raspberry Pi, unzip and install.

*Download the latest version of the JavaFX Embedded SDK port, available here, and copy to your Pi. Unzip the downloaded JavaFX Embedded SDK and copy the following files into the JDK 8 installation directory:

*

*armv6hf-sdk/rt/lib/ext/jfxrt.jar  -->  jre/lib/ext/

*armv6hf-sdk/rt/lib/arm/*  --> jre/lib/arm/

*armv6hf-sdk/rt/lib/javafx.platform.properties --> jre/lib/

*armv6hf-sdk/rt/lib/javafx.properties --> jre/lib/

*armv6hf-sdk/rt/lib/jfxswt.jar  --> jre/lib/

You can deploy JavaFX projects on your Pi directly copying them from your computer, or using the remote deployment available with NetBeans (Remote Platform) or with the Gluon Plugin for your IDE.
For a short guide on creating a remote platform on NetBeans, check this link. For the Gluon Plugin, check these settings.


text:
Q: Is It A Good Idea or A Huge Mistake to Combine More Than 1 Type of Data Into A Single Column in An SQL Database Table? So, let's say I have 5 items, A, B, C, D and E. Item A comes in sizes 1 and 2, item B comes in sizes 2 and 3, C comes in 1 and 3, D comes in 1 and E comes in 3. Now, I am considering 2 table options, as follow:
Table 1

Name
Size

A
1

A
2

B
2

B
3

C
1

C
3

D
1

E
3

Another option is Table 2, as follows:

Name

A1

A2

B2

B3

C1

C3

D1

E3

Now, which of these 2 tables is actually a better option? What are the advantages and disadvantages (if any) of each of the 2 tables above? One thing that I can think of is that, if I use table 1, I can easily extract all items by size, no matter what item I want. So, for instance, if I want to analyze this month's sales of items of size 1, it's easy to do it with Table 1. I can't seem to see the same advantage if I use table 2. What do you guys think? Please kindly enlighten me on this matter. Thank you in advance for your kind assistance, everyone. Cheers! :)

A: I don't even understand why you have the second table option - what purpose does it have or how does it help you?  Plain and simple you have a one to many relationship.  That is an item comes in 1 or more different sizes.  You just saying that sentence should scream ONLY option 1.  Option 2 will make your life a living hell because you are going against normalization guidelines by taking 2 datatypes into 1, and it has no real benefit.
Option 1 says I have an item and it can have one or more sizes associated with it.
Item  Size
A      1
A      2
A      3
B      1
C      1
C      2

Then you can do simple queries like give me all items that have more then 1 size.  Give me any item that only has 1 size.  Give me all the sizes of item with item id A, etc.


text:
Q: How to share monitors and mouse/keyboard between a MBP (only USB C ports) and Windows desktop (only USB A ports)? I have a MBP that only has USB C ports and a Windows PC that only has USB A ports (and a GPU with HDMI and DisplayPort outputs).
I have a docking station that has all the necessary ports to get my monitors and mouse/keyboard working on my MBP (goes out to USB C) but that means I would have to disconnect/reconnect everything between my PC and MBP when I want to use one or the other.
Is there any kind of device/docking station I could use that would allow me to easily switch my peripherals from one computer to the other?


text:
Q: Can I make mods for Skyrim? Can regular owners of the Skyrim game make mods for skyrim? Will it include mod tools, level editors, etc?
If not, are there any customizations that end users can do?

A: The creation kit has now been released and can be found on Steam.

When we created Skyrim, we set out to make the largest, most engrossing role-playing game we had ever attempted. Now it's about to get a whole lot bigger, thanks to our amazing modding community.
Mod-makers have a long history with Bethesda Game Studios, bringing to life new quests, locations and characters, as well as making changes to game from subtle tweaks to full-blown overhauls. With the Creation Kit, the same tool we used to create Skyrim, there's almost no limit to what can be accomplished – and we're putting that power in your hands.
  Best of all, access to the Skyrim Workshop and Creation Kit is free for anybody with a Steam account and a copy of Skyrim.
With the Skyrim Workshop, finding and installing your favorite mods is easier than ever before. Mod-makers will also enjoy a streamlined process for uploading mods directly to Steam.

Here is a link to the steam workship for Skyrim.
Source: Creation Kit Wiki


text:
Q: Having issues with D3 rendering in bar chart I get a blank screen when the browser tries to render the following code and its json file.  happens both Safari and Chrome. Seems like it renders the SVG in the canvas but not the rest. Am I missing something in the structure? Or should it be run on a server ?
<!DOCTYPE html>
<html>
<head>
<script src="http://d3js.org/d3.v3.min.js"></script>
</head>
<body>
<script>
// load the external data from built-in method in D3
   d3.json("datastuff.json", function(data) {

   // after data load then...
    var canvas = d3.select("body").append("svg")
   .attr("width", 500)
   .attr("height", 500)

   canvas.selectAll("rect")
   .data(data)
   .enter()
       .append("rect")
       .attr("width", function (d) { return d.age * 10; })
       .attr("height", 50)
       .attr("y", function (d,i) {return  i * 50; })
       .attr("fill", "blue")

    })

</script>

</body>
</html>

Here is its associated external datastuff.json file.
[
{"name":"Maria","age":30},
{"name":"Fred","age":50},
{"name":"Francis","age":12}
]


text:
Q: Is there a way to change about:config DOM value for only one website in firefox I would like to allow one website to use the window.resizeTo(); function but disallow all the other websites from doing that... I wonder if there is any way to do that even if its difficult.
even if its not in the firefox original settings maybe there is an addon that will allow for it??

A: It doesn't appear that the about:config preferences are that granular. You can either set a preference value to true for the entire browser, or false for the entire browser. But you cannot define case-by-case values.
Source: http://kb.mozillazine.org/Firefox...config_Entries#DOM.
This limitation is illustrated through the options of the browser as well (all or none):

A: You can create a file called user.js in your profile directory. Most Firefox preferences are kept in a file called prefs.js - but the browser can write to this file, and often overwrite any changes.
If user.js can accept if-else logic and access the current URL, you could very easily establish logic to turn preferences on and off depending upon the URL.
I found this information here.
Update
As far as I can see, user.js is only read when the browser loads - so the method described above won't work :( The best way to achieve required functionality would be to use/write/invent a Firefox addon.


text:
Q: Best way to Read and process large file with 50 million rows (8GB). After POJO creation Store in Mongo DB ListIterator it= FileUtils.lineIterator(bigFile);
List<String> rows = new ArrayList<String>();
//Iterate and add lines to list
while(it.hasNext){
    rows.add(it.next())// Exception1
}
//ExecutorService to Iterate a chunk of 20K rows
// In Executor create do validations and create pojo List
// exeutor service to iterate Pojo list and save 20k chunk pojo in mongo db

Issues/ Exception:.
  1.   Unable to create list named rows,  Getting outOfMemory heap exception.
  2.    If i do not create list and process each row and store in mongo. It will take a lot of time and may also lead to other exceptions.
What is the best approach to read and process such large file?

A: 2 GB of bytes will double as String normally will contain a char[] and char is a two bytes UTF-16 value.
Best would be to have some compression, maybe on 20 KB chunks of the file as mentioned. The application can also be given more memory -DXmax=2g.
Your code assumes the huge file is plain text (or HTML or an SQL dump or a log file).
I have done a line based compression (which is not that good, even negative for empty lines).
Path path = Paths.get(bigFile); // String bigFile
Path path = bigFile.toPath(); // File bigFile
Charset charset = Charset.defaultCharset(); // Or whatever the charset is.
List<byte[]> compressedLines = Files.lines(path, charset)
    .map(line -> compress(line)) // Or compress(line + "\n")
    .collect(Collectors.toList());

byte[] compress(String s) {
    byte[] content = s.getBytes(StandardCharsets.UTF_8);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (GZipOutputStream out = new GZipOutputStream(baos)) {
        out.write(content);
    }
    return baos.toByteArray();
}

String decompress(byte[] compressed) {
    ByteArrayInputStream bais = new ByteArrayInputStream(compressed);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try (GZipInputStream in = new GZipInputStream(bais)) {
        byte[] buf = new byte[128];
        for (;;) {
            int nread = in.read(buf, 0, buf.length);
            if (nread <= 0) {
                break;
            }
            baos.write(buf, 0, nread);
        }
    }
    return new String(baos.toByteArray(), StandardCharsets.UTF_8);
}

This might not be the best solution as-is.


text:
Q: Calling Google's Custom Search API via Python I am writing in Python a module that will query Google's Custom Search API and return all listings of domain 'example.com'
I Have been reading instructions at https://code.google.com/apis/customsearch/v1/getting_started.html and am a little stumped at the moment.
Are my assumptions listed below correct?
For example, to search for results that has 'example.com' in the URL, the query is:
*'https://www.googleapis.com/customsearch/v1?key=my_key&cx=017576662512468239146:omuauf_lfve&q=site:example.com'*
*key=my_key:* value of key given by google
cx=017576662512468239146: name of the search engine (google)? Is this correct?
*omuauf_lfve:* I have no idea what this is
q=site:example.com: This should return all results with 'example.com'; e.g. www.a.example.com, b.example.com, example .com

A: Though this question is quite old and the author doesn't seem to be too responsive, Google still highly ranks this page and many people may come here, so I post my answer.
Searching with Google Custom Search is described in this answer to similar question.
Parameters are as follows:
key - yes, it is API key for your Google account. To obtain it go to APIs console, switch on Custom Search API on Services tab and find actual API key on API Access tab.
cx - yes again, it is search engine unique code. Note, that this code is of form "123456:abcdef", so "omuauf_lfve" is part of this code, not the other param.
q - actual search query. "site:example.com" is part of Google's query language. See search tips for details.


text:
Q: Run Cucumber test with Mockito I'm trying to run a JUnit Cucumber test that uses Mockito. Here's the issue I'm running into. In my Cucumber Runner class, I have
@RunWith(Cucumber.class)

And in my regular JUnit tests I have
@RunWith(Mockito.class)

Given that I can only have one @RunWith at a time, how can I use Mockito in conjunction with Cucumber?

A: Yes, you can use Cucumber and Mockito at the same time.
You can't use two JUnit runners at the same time.  But if you add Mockito as a dependency to your project and create your mocks like this: List mockedList = mock(List.class); then you should be able to combine the tools.
More information is availabe at http://mockito.org/

A: You can run Mockito using JUnit rule instead of using @RunWith so that you can use @RunWith with another JUnit runner.
//@RunWith(MockitoJUnitRunner.class)
@RunWith(AnotherRunner.class)
public class TestSomething {
    @Rule public MockitoRule mockitoRule = MockitoJUnit.rule();

    @Mock
    MyMock myMock;
    ...
}