text:
Q: Как передать скрипту аргументы из тхт пишу скрипт на питоне в котором необходимо по очереди подключаться к разным коммутаторам из списка в тхт файле.В этом файле содержаться только ip адреса подключений ,а я хочу добавить в него логины и пароли от цисок,чтобы скрипт сразу конектился без участия пользователя.Пример строки в тхт файле-

192.168.1.2 : логинциски : парольциски : энейблпароль :портподключения

Вопрос в том как это реализовать.
import sys
import time
from netmiko import ConnectHandler
import os
import cmd
import datetime
import re
import shutil

now = datetime.datetime.now()
device_params={}
with open('ip2.txt', 'r') as f:
    nums = f.read().splitlines()
    for el in nums:
        if el:
            ip, user, password, enable_password, port, = el.replace(' ', '').split(":")
            device_params = {
                'device_type': 'cisco_ios_telnet',
                'ip': ip,
                'username': user,
                'password': password,
                'secret': enable_password,
                'port': port
            }
            print(device_params)
        try:
            connection = ConnectHandler(**device_params)
            connection.enable()
            output = connection.send_command('show run')
            prompt = connection.find_prompt()
            hostname = prompt[:-1]
            path = 'C:/adb/'
            folder_names = str(now.year) + '-' + str(now.month) + '-' + str(now.day)

            def createFolderForTiff(folder_names, path):
                _fold_name = folder_names
                _path = path

                if (os.path.exists(_path + '/' + _fold_name)):
                    print('Папка с именем ' + folder_names + ' уже существует')
                else:
                    os.chdir(_path)
                    os.mkdir(_fold_name)

            createFolderForTiff(folder_names, path)

            today = str(now.year) + '-' + str(now.month) + '-' + str(now.day)
            file = today + '-' + hostname + '.txt'
            with open(path + folder_names + '/' + file, 'w') as backup:
                backup.write(output)
                print('Backup of ' + hostname + ' completed successfuly')
                print('#' * 30)
            connection.disconnect()
        except ():
            device_type=device_params.setdefault('device_type','cisco_ios')
            connection = ConnectHandler(**device_params)
            connection.enable()
            output = connection.send_command('show run')
            prompt = connection.find_prompt()
            hostname = prompt[:-1]
            path = 'C:/adb/'
            folder_names = str(now.year) + '-' + str(now.month) + '-' + str(now.day)
            def createFolderForTiff(folder_names, path):
                _fold_name = folder_names
                _path = path

                if (os.path.exists(_path + '/' + _fold_name)):
                    print('Папка с именем ' + folder_names + ' уже существует')
                else:
                    os.chdir(_path)
                    os.mkdir(_fold_name)

            createFolderForTiff(folder_names, path)

            today = str(now.year) + '-' + str(now.month) + '-' + str(now.day)
            file = today + '-' + hostname + '.txt'
            with open (path+folder_names+'/'+file, 'w') as backup:
                backup.write(output)
                print('Backup of ' + hostname + ' completed successfuly')
                print('#' *30)
            connection.disconnect()

A: Если трудности именно с тем что не знаете как получить параметры из текстового файла
device_params={}
with open('text.txt', 'r') as f:
    nums = f.read().splitlines()
    for el in nums:
        if el:
            ip, user, password, enable_password, port, = el.replace(' ', '').split(":")
            device_params = {
                'device_type': 'cisco_ios',
                'ip': ip,
                'username': user,
                'password': password,
                'secret': enable_password,
                'port': port
            }
            print(device_params)

в итоге получаем вывод
подключение к ip
192.168.1.2
вводим логин
admin
подключение к ip
192.168.1.3
вводим логин
admin
подключение к ip
192.168.1.4
вводим логин
admin
подключение к ip
192.168.1.5
вводим логин
admin


text:
Q: How to remotely debug Go code with VSCode I run a process inside a docker container that needs to be debugged. The process is started in the docker's entry point via
dlv debug /go/src/path/to/package --headless --listen=:2345 --log for the purpose of enabling debugging later in VSCode.
The docker container is started via
docker run --rm -it -p 2345:2345 my_image:tag. Note delve's port is exposed.
In VSCode I define launch.json as follows:
{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Attach remote",
            "type": "go",
            "request": "attach",
            "mode": "remote",
            "port": 2345,
            "host": "127.0.0.1",
            "apiVersion": 1
        }
    ]
}

Upon starting the "attach remote" VSCode debugging configuration I get

It isn't crystal clear, but that UI leads me to believe I'm now connected to the remote headless debugger and ready to debug. I have one breakpoint defined which I know would be hit by a request I can send the remote process. I send that request, I get a result, and that breakpoint never hit, indicating that I haven't yet achieved remote debugging.
Is something wrong with my VSCode "attach remote" configuration? I can do command-line debugging with dlv connect :2345 and actually debug the remote process just fine, which indicates the headless server is functional. I would rather debug with source code, in VSCode though.

A: Try again with the latest beta of vscode-go (April 2020) (for any time after April 2020, the latest official vscode-go release will be enough)
Microsoft/vscode-go issue 2010 includes this confirmation from Ramya Rao:

The fix from #3108 is available in the latest beta version of this extension. Please do try and share feedback
The latest version of the extension now has the fix to this issue

And:

I can confirm that I am able to hit breakpoints now using AWS SAM to launch a linux container with delve and go binaries compiled from Windows.
For anyone still having this problem (like I was before I edited this comment), take care that the "remotePath" element of your launch.json is the absolute path to the source files as compiled on your local system (not the container).
As implied above - it's the absolute local path that is added to the DWARF compilation unit file table when you compile the binary.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python sibling directory import errors My imports dont show any linting errors (flake8), but generate a ModuleNotFoundError when run.
The application can be started from either __main__.py or bar.py. Both modules call bar.py. The application seems to work when __main__ is called, but I get the following error when running bar:
Traceback (most recent call last):
  File "a:/Git/repo/lib/data/bar.py", line 1, in <module>
    from src.foo import classA
ModuleNotFoundError: No module named 'src'

Directory structure
repo
└── lib
    ├── src
    │   ├── __init__.py
    │   ├── __main__.py
    │   └── foo.py
    ├── data
    │   ├── __init__.py
    │   └── bar.py
    └── __init__.py

main
from foo import classA

foo
class classA:
    def dostuff(x):
        ...

bar
from src.foo import classA

A: If you are attempting an import from a module, you need to make sure you're giving it context in relation to where the file you're importing is in the structure.
In bar.py you need to note that data is on the same level as src so you must go one level higher before you reference src: from ..src.foo import ClassA. from src.foo as in your question is equivalent to from .src.foo which would be searching for foo inside the data directory.


text:
Q: How to concatenate different latex files Suppose I wrote several latex files, resulting with several pdf files that I want to concatenate together.
Now suppose that different latex files are written with different templates and packages and I do not want to mess up with latex files too much. What would be the cleanest way to concatenate these files?
Would the case of the same template to write pdf files - such as tufte-latex - make concatenation easier?

A: If you would like to simply put all the pdfs together, you can use this basic code:
\documentclass[a4paper]{article}
\usepackage{pdfpages}

\begin{document}

% first page of the pdf
\includepdf{document-title}

% all pages
\includepdf[pages=-]{document-title}

% all pages starting from page 2
\includepdf[pages=2-]{document-title}

\end{document}

For more information, look here: pdfpages documentation.
This will not change your LaTeX files at all. However, in the resulting pdf hyperlinks will not work. (Also, page numbering etc. will not change.)
(As mentioned by @leandriis)


text:
Q: Does a new run of for loop ends the scope of last run of for loop? I do not understand why following program prints 0 1 2. I thought it will print 2 2 2.
package main

import (
    "fmt"
)

func main() {
    var funcs []func()
    for i := 0; i < 3; i++ {
        idx := i
        funcs = append(funcs, func() { fmt.Println(idx) })
    }

    for _, f := range funcs {
        f()
    }
}

My reasoning of it should print 2 2 2 is that each run of the for loop shared the same scope(e.g., 2nd run of for loop does not terminate the scope of 1st run, the scope are shared). Thus idx's reference is shared by the anonymous function created with in each run of for loop. Thus when the loop ends, all 3 functions created shared the same reference of idx, whose value is 2.
So I think the question boils down to: Does a new run (e.g., i == 2) of for loop ends the scope of last run (e.g., i == 1) of for loop? Would appreciate if answer would point me to golang spec. (I could not find the spec mentioning this).

A: From spec https://golang.org/ref/spec#For_statements

A "for" statement specifies repeated execution of a block.

each of those blocks has its own scope and they are not nested or shared. But

Each "if", "for", and "switch" statement is considered to be in its
  own implicit block.

so variable i in your snippet is shared and
for i := 0; i < 3; i++ {
        funcs = append(funcs, func() { fmt.Println(i) })
}

for _, f := range funcs {
        f()
}

will print 3 3 3 as expected.


text:
Q: Max resolution problem My monitor resolution 1600x1200 but when I go to settings and displays the maximal resolution is 1360x768 I tried detect displays but nothing happened

A: Try setting a custom resolution in xorg.conf. You should have one already, and if not, use this. Make sure your SubSection: Display has the right resolution. I had a problem with monitor resolution when I used a DVI to VGA adapter, these adapters can strip out EDID data. The monitor sends the EDID data to the computer to tell it what resolutions it can support.
Section "Screen"
    Identifier    "Default Screen"
    Device        "NVIDIA Corporation NV34 [GeForce FX 5200]"
    Monitor        "CM752ET"
    DefaultDepth    16
    SubSection "Display":
        Depth        16
        Modes      "1280x1024" "1024x768"
    EndSubSection
EndSection

A: This solution work for me. I use it on Ubuntu 14.04 and 16.04 and working good!
If you want for example resolution 1290x1080 (Full HD) type in terminal console
cvt 1920 1080

You will see something like this for output:
# 1920x1080 59.96 Hz (CVT 2.07M9) hsync: 67.16 kHz; pclk: 173.00 MHz
Modeline "1920x1080_60.00"  173.00  1920 2048 2248 2576  1080 1083 1088 1120 -hsync +vsync

Go to your home folder for example
cd /home/mikia

Edit or create file .xprofile
vi .xprofile

Insert folowing text na following previous output from command cvt:
xrandr --newmode "1920x1080_60.00"  173.00  1920 2048 2248 2576  1080 1083 1088 1120 -hsync +vsync
xrandr --addmode VGA1 "1920x1080_60.00"

Save file, reboot and enjoy in your new resolution :)


text:
Q: How to solve the alignment problem of the columns in a text file after copy and paste? I copied column 7,8 and 9 from file 1 into columns 7,8 and 9 in file 2 producing a new file 3. the produced file (file 3) is not aligned as the original files, How can I edit it to preserve the alignment ?
I used the command:
awk '(getline line < "file 1") > -1 {split(line,a); $7 = a[7]; $8 = a[8]; $9= a[9]} 1' file 2 > file 3

file 1:
GRM in vacuum

192700

1GRM     C1    1  17.188   0.311  13.994 -0.5971  0.0204 -0.0724
1GRM     C2    2   0.094   0.383   0.005  0.4831 -0.8709 -0.2204
1GRM     C3    3   0.091   0.524   0.008 -0.7098  0.3449 -0.3952

file 2:
GRM in vacuum

192760

1GRM     C1    1   0.061   0.071  14.000
1GRM     C2    2   0.184   0.142  14.000
1GRM     C3    3   0.184   0.284   0.000

file 3 (The output):
GRM in vacuum

192760

1GRM C1 1 0.061 0.071 14.000 -0.5971 0.0204 -0.0724
1GRM C2 2 0.184 0.142 14.000 0.4831 -0.8709 -0.2204
1GRM C3 3 0.184 0.284 0.000 -0.7098 0.3449 -0.3952

To solve the alignment problem I used:
    awk 'BEGIN{fmt="%10s%9s%7d%8.3f%8.3f%8.3f%8.4f%8.4f%8.4f"} (getline line < "file 1") > -1 {n = split(line,a)} n > 6 {$0 = sprintf(fmt,$1,$2,$3,$4,$5,$6,a[7],a[8],a[9])} 1' "file 2" > file 3

but still I have 2 problems.
The first problem is the alignment of the columns in the output file is not like the original files (file 1 and file 2).
The second problem happens at line 10002, column 2 and 3 combine together which lead to disappearing a complete column in the output file starting from line 10002 to the end, below are the 3 files at line 10002:
file 1:
2500GRM     C3 9999  15.716   8.242   0.002  0.2372 -0.2989 -0.0758   # line 10001
2500GRM     C410000  15.592   8.311   0.003  0.2603 -0.2492 -0.2394   # line 10002
2501GRM     C110001  15.591   8.453   0.006  0.0887 -0.2458 -0.7014   # line 10003
2501GRM     C210002  15.714   8.524   0.007 -0.0788  0.0598 -0.9619   # line 10004

file 2:
2500GRM     C3 9999  15.433   8.378   0.000   # line 10001
2500GRM     C410000  15.310   8.449   0.000   # line 10002
2501GRM     C110001  15.310   8.591   0.000   # line 10003
2501GRM     C210002  15.433   8.662   0.000   # line 10004

file 3:
2500GRM C3 9999 15.433 8.378 0.000 0.2372 -0.2989 -0.0758   # line 10001
2500GRM C410000 15.310 8.449 0.000  -0.2492 -0.2394         # line 10002
2501GRM C110001 15.310 8.591 0.000  -0.2458 -0.7014         # line 10003
2501GRM C210002 15.433 8.662 0.000  0.0598 -0.9619          # line 10004

I have attached all the files in the below link:
https://drive.google.com/drive/folders/13diMVxlp-T9BXE_jnm_LL1jUPbz8eren

A: The problem is that you have either 8 or 9 data fields in file1 and 5 or 6 in file2. Either C3 9999
is one badly formatted field or C410000 should be two fields C4 and 10000.
To adjust the formatting depending on the number of fields you can

*

*use two format strings and switch between them

*save the number of array elements n when you split the line and take the last
three values a[n-2], a[n-1], a[n]

awk '
  BEGIN{
    fmt1="%8s %6s%5s %7.3f %7.3f %7.3f %7.4f %7.4f %7.4f" ORS
    fmt2="%8s %11s %7.3f %7.3f %7.3f %7.4f %7.4f %7.4f" ORS
  }
  (getline line < "file 1") > -1{
    n=split(line, a)
  }
  NF<=3{ print; next }                                                     # print original line
  NF==6{ printf fmt1, $1, $2, $3, $4, $5, $6, a[n-2], a[n-1], a[n]; next } # 6 + 3 fields
  { printf fmt2, $1, $2, $3, $4, $5, a[n-2], a[n-1], a[n] }                # 5 + 3 fields
' "file 2" > "file 3"

Output:
 ...
 2500GRM     C3 9999  15.433   8.378   0.000  0.2372 -0.2989 -0.0758
 2500GRM     C410000  15.310   8.449   0.000  0.2603 -0.2492 -0.2394
 2501GRM     C110001  15.310   8.591   0.000  0.0887 -0.2458 -0.7014
 2501GRM     C210002  15.433   8.662   0.000 -0.0788  0.0598 -0.9619
 ...


text:
Q: How do you parse an Intel Hex Record with applicative functors using the haskell parsec library? I would like to parse an Intel Hex Record with parsec using the applicative functor style.  A typical records looks like the following:
:10010000214601360121470136007EFE09D2190140
The first character is always ':', the next two characters are a hex string representing the number of bytes in the record.  The next four characters are a hex string identifying the start address of the data.  I had code like the following, but I don't know how to applicatively pass the byte count to the parser that parses the data bytes.  My non-working code looks like the following.
line = startOfRecord . byteCount . address . recordType . recordData . checksum
startOfRecord = char ':'
byteCount = toHexValue <$> count 2 hexDigit
address = toHexValue <$> count 4 hexDigit
recordType = toHexValue <$> count 2 hexDigit
recordData c = toHexValue <$> count c hexDigit
recordData c CharParser = count c hexDigit
checksum = toHexValue <$> count 2 hexDigit

toHexValue :: String -> Int
toHexValue = fst . head . readHex

Could anyone help me?  Thanks.

A: There are a number of things not included in your question that you need in order to use parsec. To define things like startOfRecord, we need to disable the dreaded monomorphism restriction. If we want to write type signatures for anything like startOfRecord we also need to enable FlexibleContexts. We also need to import parsec, Control.Applicative, and Numeric (readHex)
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE FlexibleContexts #-}

import Text.Parsec
import Control.Applicative
import Numeric (readHex)

I'm also going to use Word8 and Word16 from Data.Word since they exactly match the types used in intel hex records.
import Data.Word

Ignoring the recordData for a momement, we can define how to read hex values for bytes (Word8) and 16 bit integer addresses (Word16).
hexWord8 :: (Stream s m Char) => ParsecT s u m Word8
hexWord8 = toHexValue <$> count 2 hexDigit

hexWord16 :: (Stream s m Char) => ParsecT s u m Word16
hexWord16 = toHexValue <$> count 4 hexDigit

toHexValue :: (Num a, Eq a) => String -> a
toHexValue = fst . head . readHex

This lets us define all of the pieces except for recordData.
startOfRecord = char ':'
byteCount = hexWord8
address = hexWord16
recordType = hexWord8
checksum = hexWord8

Leaving out recordData, we can now write something like your line in Applicative style. Application in Applicative style is written as <*> (. is function composition or composition in Categorys).
line = _ <$> startOfRecord <*> byteCount <*> address <*> recordType <*> checksum

The compiler will tell us about the type of the hole _. It says
    Found hole `_'
      with type: Char -> Word8 -> Word16 -> Word8 -> Word8 -> b

If we had a function with that type, we could use it here and make a ParserT that reads something like a record, but still missing the recordData. We'll make a data type to hold all of an intel hex record except for the actual data.
data IntelHexRecord = IntelHexRecord Word8 Word16 Word8 {- [Word8] -} Word8

If we drop this into line (with const to discard the startOfRecord)
line = const IntelHexRecord <$> startOfRecord <*> byteCount <*> address <*> recordType <*> checksum

the compiler will tell us that the type of line is a parser for our pseudo-IntelHexRecord.
*> :t line
line :: Stream s m Char => ParsecT s u m IntelHexRecord

This is as far as we can go with Applicative style. Let's define how to read the recordData assuming we already somehow know the byteCount.
recordData :: (Stream s m Char) => Word8 -> ParsecT s u m [Word8]
recordData c = count (fromIntegral c) hexWord8

We'll also modify IntelHexRecord to have a place to hold the data.
data IntelHexRecord = IntelHexRecord Word8 Word16 Word8 [Word8] Word8

If you have an Applicative f, there's no way, in general, to choose the structure based on the contents. That's the big difference between an Applicative and a Monad; a Monad's bind, (>>=) :: forall a b. m a -> (a -> m b) -> m b, allows you to choose the structure based on the contents. This is exactly what we need to do to determine how to read the recordData based on the result we obtained earlier by reading the byteCount.
The easiest way to use one bind >>= in the definition of line is to switch entirely to Monadic style and do-notation.
line = do
    startOfRecord
    bc   <- byteCount
    addr <- address
    rt   <- recordType
    rd   <- recordData bc
    cs   <- checksum
    return $ IntelHexRecord bc addr rt rd cs

A: As far as my understanding goes, the limitation of Applicative Parsers (compared with Monadic Parsers) is that you are limited to parsing context-free expressions.
By this I mean that decisions about how to parse at a certain point cannot depend on values parsed before, only on the structure (i.e. a parser failed, so we try to apply a different one).
I find that this can be explained from the operators themselves:
(<*>) :: Applicative f => f (a -> b) -> f a -> f b
(>>=) :: Monad m => m a -> (a -> m b) -> m b

For <*> you can see that everything takes place at the level of the values 'contained in' the Applicative whereas for >>= the value can be used to influence the containing structure. This is precicely what makes Monads more powerful than Applicatives.
For your Problem this means that you nedd to use a monadic parser to stick all the individual pieces together, appoximaly like this:
parseRecord = do
  count <- byteCount
  ...
  rData <- recordData count
  ...
  return (count,rData,...)


text:
Q: Bluetooth Low Energy (BLE) GATT: How to expose a list? Suppose we have a BLE GATT server which can be triggered to execute a search. The search yields a list (e.g. of device names). The list can be (way) longer than 512 bytes, so the result cannot be stored in
a single characteristic.
What is the intended way to expose such a list via GATT? I can find no documentation about this. Is there any documentation in the BLE specification or in related documents discussing this which I overlooked?
None of the (standard) examples or specifications I can find (e.g. on https://www.bluetooth.com/specifications/gatt/) contain a list.
I can think of the following strategies:

*

*Expose a service which contains the result with n characteristics (dynamic, one per list entry). The service is created and exposed dynamically as a result of the search operation. The service will be removed after the client
confirms reading the data or after a certain time.

*Expose a service statically which contains the result with n characteristics (static, e.g 100). The service also contains a characteristic which contains the number of list entries).

*Expose a service statically which contains a "value" characteristic which offers the current value of the list. The service also contains a "next" characteristic which updates the "value" characteristic with the next value on write.

*Expose a service statically which contains a "value" characteristic. The client has to subscribe to this characteristic for notifications/indications. Write one list value to the characteristic after the other. The client has to combine the notifications
to a list.

Are one or more of the strategies the intended way to go? Or is there a different strategy that should be applied?


text:
Q: How to insert data as array values into MySQL? job_no is primaary key
i want save description as array, when i insert many description to one job in database, last description only saved in saved database i can't see other descriptions.
var_dump($description): ??
html: ??
php:
<?php
include ("connection.php");

$sel_type = $_POST["type"];
$ref_no = $_POST["refno"];
$in_date = date("Y-m-d", strtotime($_POST['date']));
$inv_to = $_POST["to"];
$inv_attn  = $_POST["attn"];
$job_no = $_POST["jobno"];
$subject = $_POST["subject"];
$description = $_POST["descrip"];

if(!$_POST["submit"]){
    echo "please fill out";
    header('Location: index.php');
    }
    else{
        if($description){
            foreach($description as $c){
$sql = "INSERT INTO student(sel_type,ref_no,in_date,inv_to,inv_attn,job_no,subject,description)
VALUES('$sel_type','$ref_no','$in_date','$inv_to','$inv_attn','$job_no','$subject','$c')";
        }}
if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();

}
?>

A: You want to be using a relationship table.
Create a new table, called job_description:
CREATE TABLE job_description (
    job_no_FK BIGINT,
    description TEXT,
    FOREIGN KEY (job_no_FK) REFERENCES student(job_no)
)

Then, you can add multiple descriptions for a job number
Your php will then become something like:
<?php
include ("connection.php");

$sel_type = $_POST["type"];
$ref_no = $_POST["refno"];
$in_date = date("Y-m-d", strtotime($_POST['date']));
$inv_to = $_POST["to"];
$inv_attn  = $_POST["attn"];
$job_no = $_POST["jobno"];
$subject = $_POST["subject"];
$description = $_POST["descrip"];

if(!$_POST["submit"]){
    echo "please fill out";
    header('Location: index.php');
    }
    else{
    $sql = "INSERT INTO student(sel_type,ref_no,in_date,inv_to,inv_attn,job_no,subject)
VALUES('$sel_type','$ref_no','$in_date','$inv_to','$inv_attn','$job_no','$subject');";
        if($description){
            foreach($description as $c){
         $sql.="INSERT INTO job_description(job_no_FK,description)
VALUES('$job_no','$c');";
        }}
if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "
" . $conn->error;
}

$conn->close();

}
?>

Also, you would then want to remove the description column from your first table:
ALTER TABLE student DROP COLUMN description

A: You can use the serialize function to store arrays to the database and use unserialize to use them in your PHP code as array.

A: You are creating insert SQL inside foreach loop. But the execution of the insert SQL is happening outside the foreach loop. So you need to move query execution function call inside foreach loop.
foreach($description as $c){
$sql = "INSERT INTO  student(sel_type,ref_no,in_date,inv_to,inv_attn,job_no,subject,description)
VALUES('$sel_type','$ref_no','$in_date','$inv_to','$inv_attn','$job_no','$subject','$c')";
if ($conn->query($sql) === TRUE) {
    echo "New record created successfully";
} else {
    echo "Error: " . $sql . "
" . $conn->error;
}

}
However keep in mind, executing database operation inside a loop is strictly no-no. It hampers performance. You can try with mapping table or multi-insert queries.

A: According to Your question, You should definitely use relationship table.
CREATE TABLE job_description (
  id INT NOT NULL AUTO_INCREMENT,
  description TEXT NULL,
  job_no INT NOT NULL,
  PRIMARY KEY (id),
  FOREIGN KEY (job_no) REFERENCES student(job_no) ON DELETE CASCADE
);

But if You really need to, use json_encode (on insert/update) and json_decode (on reading) to store arrays in MySQL. The advantage is that jsoned arrays are more human-readable than serialized arrays.


text:
Q: Assign a Server CPU core to execute a specific call Is there a way in which I can prioritize a specific call to be executed by a CPU core?
meaning, if this call is passed, a CPU core will be then dedicated to execute that call.

A: In Linux, system calls that are invoked by interrupts can be associated with cores using the IRQ mapping facility.  A high-level explanation is at https://access.redhat.com/documentation/en-us/red_hat_enterprise_linux/6/html/performance_tuning_guide/s-cpu-irq
If you are writing your own device driver, then the Linux kernel provides easy interfaces to run a function on a specific core.  The kernel function "smp_call_function_single()" is an example -- there are others in kernel/smp.c, and there are plenty of examples of the use of these functions in other bits of kernel code -- e.g., arch/x86/lib/msr-smp.c and arch/x86/kernel/cpuid.c are where I learned about these functions.
My experience with kernel code is quite limited, but I don't know of any mechanism to provide differential affinity control of the execution of functions that are accessed using the same interrupt number/IRQ.  Depending on the complexity of the function, it may be possible to create a simple driver that wraps the desired call in "smp_call_function_single()".


text:
Q: How to update large number of records via XML files? I'm the developer for a real estate syndication website and am currently having trouble figuring out a way to update massive numbers of listings/records efficiently (2,000,000+ listings).
We currently accept XML feeds, containing real estate listings, from about ~20 different websites. Most of the incoming feeds are small (~100 or so listings), but we have a couple of XML feeds that contain ~1,000,000 listings. The small feeds are parsed fast and easy, however, the large feeds are taking upwards of 2-3 hours each.
The current "live" database table that contains the listings for viewing on the site is MyISAM. I chose MyISAM because ~95% of the queries to the table are SELECTs. Really the only time there are writes (UPDATE/INSERT queries) are during the time the XML feeds are being processed.
The current process is as follows:

*

*There is a CRON in place that starts the main parsing script.

*It loops through a feeds table and grabs the external XML feed source files. It then runs through said file and for each record in the XML file it checks against the listings table to see if a listing needs to be updated or inserted (if it's a new listing).
This is all happening against the live table. What I'd like to find out is if anybody has any better logic to make these updates/inserts happen in the background so as to not slow down the production tables, and ultimately, the user experience.
Would a delta table be the best choice? Maybe do all the heavy work on a separate database and just copy the new table over to the production database? On a separate workhorse domain altogether? Should I have a separate listings table that does all the parsing which would be InnoDB instead of MyISAM?
What we're trying to accomplish is to have our system be able to update listings frequently throughout the day without slowing the site down. Our competitors boast that they are updating their listings every 5 minutes in some cases. I just don't see how that's even possible.
I'm working right now so this is more of a brain dump just to get the ball rolling. If anybody would like me to provide table schematics, I'd be more than happy.
In summary: I'm looking for a way to frequently update millions of records in our database (daily) via a couple dozen external XML feeds/files. I just need some logic on how to effectively, and efficiently, make this happen so as to not drag the production server down with it.

A: Firstly, for your existing 3 hour import, try wrapping every 100 inserts in a transaction. They will be written to the database in one go, and that might speed things up dramatically. Play around with the 100 value - the best value will depend on how resilient you want it, and how much memory your transaction cache has. (This will of course require you to switch to a different engine).
For providers that are known to offer larger files, try keeping a copy of the previous XML download, and then do a text diff between the old one and the new one. If you set your context settings (i.e. the number of unchanged lines around changed lines) sufficiently you might be able to capture the primary keys of changed items. You would then just do a small number of updates.
Of course, it would help if your providers maintain the order of their XML listing. If they don't, a text sort then a diff may still be faster than importing everything.
FWIW, I think a complete refresh every 5 minutes is probably not feasible. I expect your providers would not be happy with you downloading 1M records at this frequency!


text:
Q: Postgres jsonb. Heterogenous json fields If I have a table with a single jsonb column and the table has data like this:
 [{"body": {"project-id": "111"}},
  {"body": {"my-org.project-id": "222"}},
  {"body": {"other-org.project-id": "333"}}]

Basically it stores project-id differently for different rows.
Now I need a query where the data->'body'->'etc'., from different rows would coalesce into a single field 'project-id', how can I do that?
e.g.: if I do something like this:
select data->'body'->'project-id' projectid from mytable

it will return something like:
| projectid |
|       111 |

But I also want project-id's in other rows too, but I don't want additional columns in the results. i.e, I want this:
| projectid |
|       111 |
|       222 |
|       333 |

A: I understand that each of your rows contains a json object, with a nested object whose key varies over rows, and whose value you want to acquire.
Assuming the  'body' always has a single key, you could do:
select jsonb_extract_path_text(t.js -> 'body', x.k) projectid
from t
cross join lateral jsonb_object_keys(t.js -> 'body') as x(k)

The lateral join on jsonb_object_keys() extracts all keys in the object as rows. Then we use jsonb_extract_path_text() to get the corresponding value.
Demo on DB Fiddle:
with t as (
  select '{"body": {"project-id": "111"}}'::jsonb js
  union all select '{"body": {"my-org.project-id": "222"}}'::jsonb
  union all select '{"body": {"other-org.project-id": "333"}}'::jsonb
)
select jsonb_extract_path_text(t.js -> 'body', x.k) projectid
from t
cross join lateral jsonb_object_keys(t.js -> 'body') as x(k)

| projectid  |
| :--------- |
| 111        |
| 222        |
| 333        |


text:
Q: License Plate Permutations A state has changed its license plate numbering system for the three largest counties. Before the
change, each plate had the number 1, 2, or 3, followed by either one or two letters, followed by 3 digits. After the change, each plate has three letters followed by three numbers. How many more plates can the state issue under the new system?
My current attempt:
First, I found the second part of the question. There are $26*26*26*10*10*10 = 17,576,000$ possible plates under the new system.
However, I'm having some trouble with the "either" in the bolded font of the problem.
Obviously we have $3$ possible choices for the first number.
There are 10 choices for each digit, so $10*10*10$.
So we currently have $3 * 10 * 10 * 10$.
If the keyword is 'either', what should I do? Do I even need to acknowledge the fact the plate can only contain one letter? This could multiply it by $26$, or $26*26$.


text:
Q: CircularProgressIndicator causes 100% CPU on emulator or iOS simulator Should I block the animation for the CircularProgressIndicator? Such as?
This is the code:
Widget _loading() {
 return Column(
  children: <Widget>[
    Text(
      "Vai nelle informazioni per avere ulteriori consigli",
      style: TextStyle(color: Colors.white, fontSize: 18),
    ),
    SizedBox(
      height: 32,
    ),
     CircularProgressIndicator(
     backgroundColor: AccentPColor,
    ),
  ],
 );
}


text:
Q: regexp_substr not working when value changing I want the min and max marks for each student. Below are the sample marks,
I want the uc_min as whatever coming before / and uc_max as whatever coming as after /
Below is my code, It is not working for single digit
select distinct  regexp_substr(marks,'[^/]+',1,1) uc_min,
        regexp_substr(marks,'[^/]+',4,1)  uc_max
   from std
  where student_id = 'YYY'

Expected output:
Sample marks   Expected uc_min    Expected uc_max
1/100          1                  100
20/30          20                 30
180/730        180                730
20/200         20                 200

A: A substr/ instr solution, assuming that there's a single "/"
select substr(marks, 1, instr(marks,'/') - 1) as uc_min,
       substr(marks, instr(marks,'/') + 1) as uc_max
from std;

DEMO

A: Try this:
WITH MARKS (SAMPLE_MARKS) AS
(SELECT '1/100' FROM DUAL UNION ALL
SELECT '20/30' FROM DUAL UNION ALL
SELECT '180/730' FROM DUAL UNION ALL
SELECT '20/200' FROM DUAL)
SELECT DISTINCT
    SAMPLE_MARKS,
    REGEXP_SUBSTR(SAMPLE_MARKS, '[^/]+', 1, 1) UC_MIN,
    REGEXP_SUBSTR(SAMPLE_MARKS, '[^/]+', 1, 2) UC_MAX -- start point(1) and position(2) was incorrect in your code
FROM
    MARKS

db<>fiddle demo
Cheers!!


text:
Q: Laravel relationships on a table with two types of flags I have two tables
products  and users
Both of this objects has images associated with it in a table
images
The schema for the images table is
id | image_id | resource_id | flag
1 | 567575 | 1 | user
2 | 423423 | 1 | product
Based on this flag i am identifying whether its a users image or whether its a products image.
If I need to eager load a users image how do it do it?
User model
<?php

namespace App\Entities;

use Illuminate\Database\Eloquent\Model;

class User extends Model implements Transformable
{
    use TransformableTrait;
    protected $table      = 'users';
    protected $primaryKey = 'users_id';
    public function images()
    {
        return $this->hasMany('App\Entities\Image','resource_id');
    }
}

Product model
<?php

namespace App\Entities;

use Illuminate\Database\Eloquent\Model;

class Product extends Model implements Transformable
{
    use TransformableTrait;
    protected $table      = 'products';
    protected $primaryKey = 'products_id';
    public function images()
    {
        return $this->hasMany('App\Entities\Image','resource_id');
    }
}

images model
<?php

    namespace App\Entities;

    use Illuminate\Database\Eloquent\Model;

    class Image extends Model implements Transformable
    {
        use TransformableTrait;
        protected $table      = 'images';
        protected $primaryKey = 'images_id';
        public function products()
        {
            return $this->hasOne('App\Entities\Product','products_id');
        }
       public function users()
        {
            return $this->hasOne('App\Entities\User','users_id');
        }
    }

Is there a way I can pass a flag in the relationship function of images() so that it will fetch the record based on the flags?
Please help out.

A: You can try this adding a conditional inside your images() method:
<?php

namespace App\Entities;

use Illuminate\Database\Eloquent\Model;

class User extends Model implements Transformable
{
    use TransformableTrait;
    protected $table      = 'users';
    protected $primaryKey = 'users_id';

    public function images($filtered=false)
    {
        if ($filtered) {
            return $this->hasMany('App\Entities\Image','resource_id')->where('flag','user');
        }
        return $this->hasMany('App\Entities\Image','resource_id');
    }
}

and try the same logic to your Product model

A: Change your Image model to:
<?php

namespace App\Entities;

use Illuminate\Database\Eloquent\Model;

class Image extends Model implements Transformable
{
    use TransformableTrait;

    protected $table      = 'images';
    protected $primaryKey = 'images_id';

    public function product()
    {
        return $this->belongsTo('App\Entities\Product', 'products_id', 'resource_id');
    }

    public function user()
    {
        return $this->belongsTo('App\Entities\User', 'users_id', 'resource_id');
    }
}

A: try with this way :
$user_id = 1;
$my_image= User::find($user_id)->images()->where('flag', '=', 'user')->first();


text:
Q: CPU spikes every 30 frames animating PNG's with JavaFX using Timeline I am trying to use the TimeLine in JavaFX to display 450 PNG files quickly after each other, every 80ms would be best.  I can't even do it at 1.5 seconds.  The files are around 60kb each.  The files are read and stored in memory before the animation starts
What happens:
The GC runs every +-30 frames and the animation completely stops
What I have tried:

*

*Displaying the SVGPath of each image

*Converting the SVGPath to a PNG and displaying that in the original animation

*Reading the files into an Image object and storing in a PriorityQueue.  Populating a single ImageView on the screen with the different Image objects

*Reading the files into different ImageView objects, populating the screen with all of them with setVisible(false) and then when the animation runs I set only one to setVisible(true)

*Change the way the animation is created, last incarnation can be seen in this post

*Changing the cycleCount to unlimited or setting it to 1 and then starting the TimeLine every time.  Actually I need it to be 1 and start the TimeLine every time, because I need to do other things before I animated.  This is for my 3D printer so the printer might need to do something before it displays a layer and after it displays a layer.  The user can configure that

*I tried changing VM options (I have more than 10GB free mem):
-Xms10680m -Xmx10680m -XX:PermSize=1256m -XX:MaxPermSize=1256m -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+UseCompressedOops -XX:NewSize=1200m -XX:MaxNewSize=1200m
-Upgraded the VM
What next
I am going to try viewport and see if that still spikes the CPU since it will be one large object, and just moving the view over it.  Hopefully it fixes the issue
Running the app
I start the app, load the model and before I start the animation the VM usage is sitting at 2.4GB, not at the specified 10GB.  When I start the app it buffers the images into the queue and the memory goes to 4.5GB, still not 10GB.  While the animation is running the memory increases to 5GB, actually fluctuates to just below and above 5GB
Java version
java version "1.8.0_40-ea"
Java(TM) SE Runtime Environment (build 1.8.0_40-ea-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.40-b18, mixed mode)
Upgraded Java version
java version "1.8.0_40"
Java(TM) SE Runtime Environment (build 1.8.0_40-b26)
Java HotSpot(TM) 64-Bit Server VM (build 25.40-b25, mixed mode)
Now it stops at every 40 frames, not every 30 anymore
GC log
 CMS: abort preclean due to time 232.460: [CMS-concurrent-abortable-preclean: 1.017/97.038 secs] [Times: user=28.11 sys=2.54, real=97.04 secs]
232.463: [GC (CMS Final Remark) [YG occupancy: 649460 K (1105920 K)]232.463: [Rescan (parallel) , 0.1360990 secs]232.599: [weak refs processing, 0.0000293 secs]232.599: [class unloading, 0.0278749 secs]232.627: [scrub symbol table, 0.0024514 secs]232.630: [scrub string table, 0.0006221 secs][1 CMS-remark: 1010091K(9707520K)] 1659552K(10813440K), 0.1735120 secs] [Times: user=0.66 sys=0.00, real=0.17 secs]
232.637: [CMS-concurrent-sweep-start]
236.988: [GC (Allocation Failure) 236.988: [ParNew: 1105126K->122880K(1105920K), 0.5563841 secs] 2115195K->2064334K(10813440K), 0.5564532 secs] [Times: user=2.64 sys=0.66, real=0.56 secs]
242.032: [CMS-concurrent-sweep: 0.760/9.395 secs] [Times: user=13.48 sys=1.01, real=9.39 secs]
242.032: [CMS-concurrent-reset-start]
242.094: [CMS-concurrent-reset: 0.062/0.062 secs] [Times: user=0.09 sys=0.06, real=0.06 secs]
246.489: [GC (Allocation Failure) 246.489: [ParNew: 1103611K->122880K(1105920K), 0.4099299 secs] 3045066K->2974070K(10813440K) icms_dc=6 , 0.4100021 secs] [Times: user=1.12 sys=1.36, real=0.41 secs]
253.224: [GC (CMS Initial Mark) [1 CMS-initial-mark: 2851190K(9707520K)] 3454329K(10813440K), 0.0044382 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
253.229: [CMS-concurrent-mark-start]
255.071: [CMS-concurrent-mark: 1.842/1.843 secs] [Times: user=3.84 sys=0.02, real=1.84 secs]
255.071: [CMS-concurrent-preclean-start]
255.103: [CMS-concurrent-preclean: 0.031/0.031 secs] [Times: user=0.03 sys=0.00, real=0.03 secs]
255.103: [CMS-concurrent-abortable-preclean-start]
 CMS: abort preclean due to time 260.113: [CMS-concurrent-abortable-preclean: 1.737/5.011 secs] [Times: user=3.28 sys=0.05, real=5.01 secs]
260.114: [GC (CMS Final Remark) [YG occupancy: 603138 K (1105920 K)]260.114: [Rescan (parallel) , 0.0107781 secs]260.125: [weak refs processing, 0.0000543 secs]260.125: [class unloading, 0.0321900 secs]260.157: [scrub symbol table, 0.0024284 secs]260.159: [scrub string table, 0.0005998 secs][1 CMS-remark: 2851190K(9707520K)] 3454329K(10813440K), 0.0517110 secs] [Times: user=0.09 sys=0.02, real=0.05 secs]
260.166: [CMS-concurrent-sweep-start]
260.932: [CMS-concurrent-sweep: 0.767/0.767 secs] [Times: user=0.78 sys=0.02, real=0.77 secs]
260.932: [CMS-concurrent-reset-start]
260.950: [CMS-concurrent-reset: 0.018/0.018 secs] [Times: user=0.02 sys=0.00, real=0.02 secs]
264.709: [Full GC (System.gc()) 264.709: [CMS: 2850762K->3328314K(9707520K), 6.1267248 secs] 3453901K->3328314K(10813440K), [Metaspace: 27214K->27214K(1073152K)] icms_dc=2 , 6.1282785 secs] [Times: user=5.93 sys=0.16, real=6.13 secs]
270.838: [GC (CMS Initial Mark) [1 CMS-initial-mark: 3328314K(9707520K)] 3341357K(10813440K), 0.0008962 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
270.839: [CMS-concurrent-mark-start]
282.708: [Full GC (System.gc()) 282.708: [CMS284.474: [CMS-concurrent-mark: 1.765/13.635 secs] [Times: user=4.57 sys=0.13, real=13.63 secs]
 (concurrent mode interrupted): 3328314K->3328357K(9707520K), 7.6842704 secs] 3364891K->3328357K(10813440K), [Metaspace: 27270K->27270K(1073152K)] icms_dc=7 , 7.6858220 secs] [Times: user=9.39 sys=0.01, real=7.69 secs]
302.308: [Full GC (System.gc()) 302.308: [CMS: 3328357K->3328494K(9707520K), 6.0054401 secs] 3362268K->3328494K(10813440K), [Metaspace: 27306K->27306K(1073152K)] icms_dc=7 , 6.0070951 secs] [Times: user=5.98 sys=0.02, real=6.01 secs]
308.316: [GC (CMS Initial Mark) [1 CMS-initial-mark: 3328494K(9707520K)] 3328494K(10813440K), 0.0008023 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
308.317: [CMS-concurrent-mark-start]
320.308: [Full GC (System.gc()) 320.308: [CMS322.084: [CMS-concurrent-mark: 1.777/13.768 secs] [Times: user=4.10 sys=0.13, real=13.77 secs]
 (concurrent mode interrupted): 3328494K->3328612K(9707520K), 7.1761016 secs] 3374259K->3328612K(10813440K), [Metaspace: 27340K->27340K(1073152K)] icms_dc=7 , 7.1777096 secs] [Times: user=8.91 sys=0.02, real=7.18 secs]
339.108: [Full GC (System.gc()) 339.108: [CMS: 3328612K->3328734K(9707520K), 4.7149083 secs] 3381859K->3328734K(10813440K), [Metaspace: 27356K->27356K(1073152K)] icms_dc=7 , 4.7166533 secs] [Times: user=4.71 sys=0.00, real=4.72 secs]
343.825: [GC (CMS Initial Mark) [1 CMS-initial-mark: 3328734K(9707520K)] 3338934K(10813440K), 0.0005971 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
343.826: [CMS-concurrent-mark-start]
355.908: [Full GC (System.gc()) 355.908: [CMS357.692: [CMS-concurrent-mark: 1.785/13.866 secs] [Times: user=4.26 sys=0.11, real=13.87 secs]
 (concurrent mode interrupted): 3328734K->3328845K(9707520K), 6.5141915 secs] 3395891K->3328845K(10813440K), [Metaspace: 27376K->27376K(1073152K)] icms_dc=7 , 6.5157445 secs] [Times: user=8.25 sys=0.03, real=6.52 secs]
374.308: [Full GC (System.gc()) 374.308: [CMS: 3328845K->3328969K(9707520K), 5.1376448 secs] 3399645K->3328969K(10813440K), [Metaspace: 27393K->27393K(1073152K)] icms_dc=7 , 5.1391948 secs] [Times: user=5.13 sys=0.00, real=5.14 secs]
379.447: [GC (CMS Initial Mark) [1 CMS-initial-mark: 3328969K(9707520K)] 3339169K(10813440K), 0.0006191 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
379.448: [CMS-concurrent-mark-start]
391.907: [Full GC (System.gc()) 391.907: [CMS393.678: [CMS-concurrent-mark: 1.772/14.231 secs] [Times: user=4.31 sys=0.14, real=14.23 secs]
 (concurrent mode interrupted): 3328969K->3329043K(9707520K), 7.0341647 secs] 3407161K->3329043K(10813440K), [Metaspace: 27454K->27454K(1073152K)] icms_dc=7 , 7.0357178 secs] [Times: user=8.75 sys=0.05, real=7.04 secs]
411.910: [Full GC (System.gc()) 411.910: [CMS: 3329043K->3329171K(9707520K), 5.7665632 secs] 3426534K->3329171K(10813440K), [Metaspace: 27477K->27477K(1073152K)] icms_dc=7 , 5.7681657 secs] [Times: user=5.77 sys=0.00, real=5.77 secs]
417.678: [GC (CMS Initial Mark) [1 CMS-initial-mark: 3329171K(9707520K)] 3329171K(10813440K), 0.0008204 secs] [Times: user=0.00 sys=0.00, real=0.00 secs]
417.679: [CMS-concurrent-mark-start]

Queue populating
I populate the queue using Executors
executorService = Executors.newFixedThreadPool(LAYER_PRODUCERS);
for (int i = -0; i < totalLayers; i++) {
    layerProducer = new LayerProducer(queueImage, i);
    executorService.submit(layerProducer);
}

Waiting for queue to fill then starting animation
I wait for the threads to populate the queue and then I start the animation with Platform.runLater(), because it needs to run in the screen Thread
new Thread() {
    @Override
    public void run() {
        try {
            while (true || executorService.isShutdown()) {
                Thread.sleep(1000);

                if (queueImage.size() >= (bufferSizeCalculated - 1)) {

                    break;
                }
            }

            Platform.runLater(() -> {
                runPrintThread();
            });
        } catch (InterruptedException ex) {
            Logger.getLogger(PrintingEngine.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}.start();

Animation loop
private void configureTimeLineContinuousNoBuildPlateMoveAnimation(Profile profile) {
    timeLocation = 0;
    List<KeyFrame> list = new ArrayList<>();
    ObservableList<KeyFrame> observableList = FXCollections.observableList(list);

    //create first frame
    KeyFrame firstKeyFrame = new KeyFrame(Duration.millis(timeLocation), (ActionEvent t) -> {
        GizmoSlice gizmoSlice = queueImage.poll();
        ImageView currentImageView = gizmoSlice.getFilledImage();
        currentImageView.setVisible(true);
        previousImageView = currentImageView;
        printEngineCallback.updateLog("Display Layer " + gizmoSlice.getName());
    });

    observableList.add(firstKeyFrame);

    for (int i = 0; i < totalLayers; i++) {
        //create a keyframe for each layer
        KeyFrame keyFrame = new KeyFrame(Duration.millis(timeLocation = timeLocation + projectionTime), (ActionEvent t) -> {
            previousImageView.setVisible(false);

            GizmoSlice gizmoSlice = queueImage.poll();
            ImageView currentImageView = gizmoSlice.getFilledImage();
            currentImageView.setVisible(true);
            previousImageView = currentImageView;
            printEngineCallback.updateLog("Display Layer " + gizmoSlice.getName());
        });

        observableList.add(keyFrame);

    }

    engineTimeLine = TimelineBuilder.create()
            .cycleCount(1)
            .keyFrames(list)
            .autoReverse(false).build();
}

Test code
I wrote a separate app that does this and the CPU doesn't spike at all.  So the code is probably fine and the VM is probably fine.  Not sure what the issue could be then.  Nothing else is running in the background, it is just a big JavaFX client application
package au.com.gizmo3dprinters;

import static au.com.gizmo3dprinters.Constants.GIZMO_SLICE;
import static au.com.gizmo3dprinters.Constants.TEMP_DIRECTORY;
import au.com.gizmo3dprinters.model.GizmoSlice;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;
import java.util.ResourceBundle;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.animation.KeyFrame;
import javafx.animation.Timeline;
import javafx.animation.TimelineBuilder;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.util.Duration;

/**
 *
 * @author kobus
 */
public class FXMLDocumentController implements Initializable {
    private static final int BUFFER_SIZE = 1; //larger number is a smaller buffer
    private static final int LAYER_PRODUCERS = 3; //larger is more memory and cpu power

    private int totalLayers;
    private PriorityQueue<GizmoSlice> queueImage;
    private int projectionTime;
    private Timeline engineTimeLine;

    @FXML
    private ImageView sliceImageView;

    @FXML
    private Label label;

    @FXML
    private void handleButtonAction(ActionEvent event) {
        Comparator<GizmoSlice> comparator = new GizmoSliceComparator();
        double bufferSizeCalculated = totalLayers / BUFFER_SIZE;
        queueImage = new PriorityQueue(Double.valueOf(bufferSizeCalculated).intValue(), comparator);
        String gizmoName = "noname_1428817659204.gizmo";

        ExecutorService executorService = Executors.newFixedThreadPool(LAYER_PRODUCERS);
        for (int i = -0; i < totalLayers; i++) {
            LayerProducer layerProducer = new LayerProducer(queueImage, i, gizmoName);
            executorService.submit(layerProducer);
        }
        executorService.shutdown();
        try {
            executorService.awaitTermination(3, TimeUnit.SECONDS);
        } catch (InterruptedException ex) {
            Logger.getLogger(FXMLDocumentController.class.getName()).log(Level.SEVERE, null, ex);
        }

        configureTimeLineContinuousNoBuildPlateMoveAnimation();
        engineTimeLine.playFromStart();
    }

    private void configureTimeLineContinuousNoBuildPlateMoveAnimation() {
        long timeLocation = 0;
        List<KeyFrame> list = new ArrayList<>();
        ObservableList<KeyFrame> observableList = FXCollections.observableList(list);

        //create first frame
        KeyFrame firstKeyFrame = new KeyFrame(Duration.millis(timeLocation), (ActionEvent t) -> {
            GizmoSlice gizmoSlice = queueImage.poll();
            System.out.println("display layer " + gizmoSlice.getLayer());
            Image currentImage = gizmoSlice.getFilledImage();
            sliceImageView.setImage(currentImage);
        });

        observableList.add(firstKeyFrame);

        for (int i = 0; i < totalLayers; i++) {
            //create a keyframe for each layer
            KeyFrame keyFrame = new KeyFrame(Duration.millis(timeLocation = timeLocation + projectionTime), (ActionEvent t) -> {
                GizmoSlice gizmoSlice = queueImage.poll();
                System.out.println("display layer " + gizmoSlice.getLayer());
                Image currentImage = gizmoSlice.getFilledImage();
                sliceImageView.setImage(currentImage);
            });

            observableList.add(keyFrame);

        }

        engineTimeLine = TimelineBuilder.create()
                .cycleCount(1)
                .keyFrames(list)
                .autoReverse(false).build();
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO
        totalLayers = 480;
        projectionTime = 400;
    }

    class LayerProducer implements Runnable {

        private final PriorityQueue<GizmoSlice> queueImage;
        private boolean stop = false;
        private final int layer;
        private final String gizmoName;

        public void stopProducing() {
            stop = true;
        }

        public boolean isStopped() {
            return stop;
        }

        public LayerProducer(PriorityQueue<GizmoSlice> queueImage, int layer, String gizmoName) {
            this.queueImage = queueImage;
            this.layer = layer;
            this.gizmoName = gizmoName;
        }

        @Override
        public void run() {
            String imageFilename = gizmoName + "fill" + layer + "." + GIZMO_SLICE + ".png";
            File imageFile = new File(TEMP_DIRECTORY + imageFilename);
            Image img = new Image(imageFile.toURI().toString());
            ImageView imageView = new ImageView(img);
            imageView.setVisible(false);

            GizmoSlice gizmoSlice = new GizmoSlice();
            gizmoSlice.setName(imageFilename);
            gizmoSlice.setFilledImage(img);
            gizmoSlice.setFilledImageView(imageView);
            gizmoSlice.setLayer(layer);
            queueImage.add(gizmoSlice);
        }
    }

    public class GizmoSliceComparator implements Comparator<GizmoSlice> {

        @Override
        public int compare(GizmoSlice x, GizmoSlice y) {
            Long layerX = x.getLayer();
            Long layerY = y.getLayer();

            return layerX.compareTo(layerY);
        }
    }

}

I am still working on this issue.
I changed the code to create a queue to read in the bytes of the images and then a second smaller queue that contained the bytes converted to images, but it was too much processing and too much memory.
I think I also figured out what my previous issue was with the CPU spikes.  I gave the VM 10GB of memory and the garbage collection caused problems.
I also tried off-heap memory, but all the tools need serialized objects.  I tried to serialize, but it was too slow.
I am now generating a movie from the image files using ffmpeg (Generate video with ffmpeg to play using JavaFX), but I have not been able to figure out how to get ffmpeg to generate movies that JavaFX can display.  Last night I tried code to use VLC viewer in JavaFX and that displayed all generated videos.  Just don't like using OS specific code.  Also it is using 50% CPU with an 8 core i7 so it might not work on a Raspberry PI.  I need to do more tests to see if I can align the images of the movie with the images of the ImageView object


text:
Q: How can I add existing files in mvc project? I have a controller, model, and view pages.
I want to add those file in a mvc razor .net project.
After I add and debug than it say "The resource cannot be found".
What is process of add those file in project?

A: Do you included those files in project?
Another way is that you add controllers manuelly, with the same names, and then copy-paste the rest of it.


text:
Q: Split a database by regular time intervals (6 months each = 131 days) I'm a beginner to R so please excuse me by advance if my question seems basic but I'm quite lost between all the functions that can be used to split a database (lubridate, split, daply...).
My data is composed by stock market index' daily returns from 1978 to 2017. I would like to regress Y1 on X1, X2, X3 and X4 every 6 months.
For information, there are 262 observations each year. So 6 months = 131 trading days.
Here is an extract of my (excel) database:

Date y1 x1 x2 x3 x4
01/06/78 -0,054728735 0,062336581 -0,017447642 0,018066145 0,0137291
01/09/78 -0,0633203 0,051713026 -0,025691177 -0,006909645 -0,015750265
01/10/78 -0,048852901 0,026756766 -0,00910902 -0,013302491 -0,025715185
01/11/78 -0,049357647 0,013119868 -0,005255487 -0,008035708 -0,01565239
01/12/78 -0,044503679 -0,029061109 -0,016565941 -0,01131818 -0,008933417
01/13/78 -0,027863545 -0,044460617 -0,012819194 -0,021071992 -0,015533829
01/16/78 -0,026495125 -0,056336531 -0,007379243 -0,003360595 0,01056797
01/17/78 -0,007670981 -0,041300771 0 -0,00111657 0,019498044
01/18/78 0,000662032 -0,031227275 0,003506725 -0,018967432 -0,003861009

I think that the best way to do that is (i) to split my database every 6 months, then (ii) to make a linear regression on each 6 month segment.
Could you tell me if it is the best way, according to you? If it is the case could you show me a code to split a database every 6 month?
Thanks you a lot for your help!

A: You could create a sequence of numbers cooresponding to the rows of your data:
i = c(seq(1,nrow(dat),by=131),nrow(dat))

And then use lapply to split the data:
lapply(seq_along(i)[-length(i)],function(x) dat[i[x]:(i[x+1]-1),])


text:
Q: Python turtle throws error when inputting RGB values to bgcolor() My code throws an error, which, summarized, reads:
"The built-in function for color in Turtle can't do the inequality used in determining color values using both a built-in function of Python and an integer"
from turtle import *

pen = Turtle()
screen = Screen()
screen.colormode(255)
screen.bgcolor('white')

def pen_color(i):
    print("Input a number between 1 and 255 for red")
    red = input
    print("Input a number between 1 and 255 for green")
    green = input
    print("Input a number between 1 and 255 for blue")
    blue = input
    screen.bgcolor(red, green, blue)

pen_color(pen)
pen.exitonclick()

A: There are several issues with your code:  As @PatrickHaugh notes:
print("Input a number between 1 and 255 for red")
red = input

isn't going to do what you want/expect.  Either do:
print("Input a number between 1 and 255 for red")
red = input()

Or better yet:
red = input("Input a number between 1 and 255 for red")

Next, this won't work as exitonclick() is a method of Screen not Turtle:
pen.exitonclick()

Finally, the reason you're running into problems with color, is that bgcolor() wants numeric argument and you passed it strings.  You need to do:
screen.bgcolor(int(red), int(green), int(blue))

Putting this all together:
from turtle import Screen, Turtle

def pen_color():
    red = input("Input a number between 1 and 255 for red: ")
    green = input("Input a number between 1 and 255 for green: ")
    blue = input("Input a number between 1 and 255 for blue: ")

    screen.bgcolor(int(red), int(green), int(blue))

screen = Screen()
screen.colormode(255)

pen_color()

pen = Turtle()

screen.exitonclick()


text:
Q: whats the difference of these two capture screen codes? i have two codes of taking screenshots and i would like to know what is the difference between them?
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("C:\\failure.png"));

and
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
**BufferedImage  fullImg = ImageIO.read(scrFile);**
FileUtils.copyFile(scrFile, new File("C:\\failure.png"));

so the row with ** ** is the difference but what she does? and why after her i can write:
Point point = element.getLocation();

int parkWidth = element.getSize().getWidth();
int parkHeight = element.getSize().getHeight();

BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(),
point.getY(),parkWidth, parkHeight);
ImageIO.write(eleScreenshot, "png", scrFile);

A:
i have two codes of taking screenshots and i would like to know what is the difference between them?
  so the row with ** ** is the difference but what she does?

The difference is that in the 2nd code block you define a new variable fullImg. However, it is not used so those 2 code blocks are the same (for capturing the screenshot).

and why after her i can write:

This is because you have defined the variable fullImg and are then using it:
BufferedImage eleScreenshot= fullImg.getSubimage(point.getX(), point.getY(),parkWidth, parkHeight);

Whereas in the first code block you don't have fullImg and thus this would error out.


text:
Q: My component keeps rerendering while using a path param I'm trying to use a path param which I fetch from the URL path as an ID for an entity which I'm trying to fetch. I've created a custom data fetching hook which triggers when either the path of the passed params change. I'm use useParams from react router dom to get the ID of the book from the URL.
Below is the component code:
const BookDetails: FC<BookDetailsProps> = () => {
  let { bookId } = useParams();

  const { response, loading, error } = useApi(`/books/v1/volumes/${bookId}`);

  return <Wrapper></Wrapper>;
};

export default BookDetails;

And below is my custom hook:
const useApi = (url: string, params = {}) => {
  const [response, setResponse] = useState<AxiosResponse>();
  const [error, setError] = useState<AxiosError>();
  const [loading, setLoading] = useState(true);

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const result = await api(url, { params: params });
      setResponse(result);
    } catch (err: any) {
      setError(err);
    } finally {
      setLoading(false);
    }
  }, [url, params]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  return { response, error, loading, fetchData };
};

export default useApi;

Now when I use my API hook with a component which fetches data using the params object everything is fine. The component doesn't rerender and I just get the data, but for some reason when I use it with path params it goes off.
Does anyone know how I should proceed?

A: I think the issue is that when no params object is passed to the useApi hook
useApi(`/books/v1/volumes/${bookId}`)

The params argument is initialized to a default empty object value.
const useApi = (url: string, params = {}) => {
  ...

This causes the params variable to be a new object reference anytime the component rerenders for any reason and will retrigger the useEffect hook because fetchData will be a newly recomputed reference.
  ...

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const result = await api(url, { params: params });
      setResponse(result);
    } catch (err: any) {
      setError(err);
    } finally {
      setLoading(false);
    }
  }, [url, params]); // <-- params new reference

  useEffect(() => {
    fetchData();
  }, [fetchData]); // <-- fetchData becomes new reference

  ...
};

I suggest not initializing param and only provide a fallback value when calling the api function.
Example:
const useApi = (url: string, params) => { // <-- don't initialize
  const [response, setResponse] = useState<AxiosResponse>();
  const [error, setError] = useState<AxiosError>();
  const [loading, setLoading] = useState(true);

  const fetchData = useCallback(async () => {
    setLoading(true);
    try {
      const result = await api(url, { params: params || {} }); // <-- provide fallback value
      setResponse(result);
    } catch (err: any) {
      setError(err);
    } finally {
      setLoading(false);
    }
  }, [url, params]);

  useEffect(() => {
    fetchData();
  }, [fetchData]);

  return { response, error, loading, fetchData };
};

export default useApi;

This way params will be an undefined value from render to render and not change shallow reference equality each render.

A: params gets a new object instance on each call so the dependency array in the useCallback will never be the same between different calls (you haven't pass a params argument to your useApi) and therefore the useEffect will be triggered on each render casing a re-render, hence the infinite rerendering


text:
Q: strace associate parent pid to child pid I'm tracing an application by running:
strace -f -y -qq -z -etrace=execve,... -o app.trace ./app

is there a way to identify which process spawned which child_process ?
My goal is to construct a graph that encodes the hierarchical relationship of (sub)processes for further analysis of the syscalls.
EDIT:
Here a more concrete example:
given the following hierarchy of processes:
p1
|
.---.
|   |
p2  p3
    |
    p4

I identify that p2 and p4 trigger syscalls of interest using strace.
Now I'd like to find the closest common ancestor, which in this case is p1.
Is it possible to create a dump that has all the information using strace, or do I have to use ps/pstree in parallel?
EDIT2:
I was not able to instrument pstree for my problem.
pstree seems to only give you a snapshot and many of my processes are very short lived making it impossible to reliably catch all of them by calling pstree repeatedly.
EDIT3:
I've noticed following entries in my trace:
23901 --- SIGCHLD {si_signo=SIGCHLD, si_code=CLD_EXITED, si_pid=23902, si_uid=1000, si_status=0, si_utime=0, si_stime=0} ---

Process 23901 logs SIGCHLD signal with si_pid=23902.
does it imply that process 23901 created childprocess 23902 ?

A: You should track the calls to clone. It tells who spawns who.


text:
Q: Trying to avoid scrollbar return to start after ajaxcall I'm working with FullCalendar, but when I use Ajax to update the state of events that are format conditioning, when I scroll lateral as the ajax is called the scrollbar resets to the start preventing the viewer to stand at the position he wanted to visualize.
I have tried setting a fixed width for the div containing Calendar class, no results maybe I didn't set it right
function ajaxcall1(calendar) {
  $.ajax({
    type: 'GET',
    url: "call for API",
    success: function(doc) {
      successAjax(doc, calendar);
    },
    error: function() {
      console.log("error");
    }
  }).done(function() {
    window.setTimeout(function() {
      ajaxcall2(calendar);
    }, 4000);
  });
}

function ajaxcall2(calendar) {
  $.ajax({
    type: 'GET',
    url: "call for API",
    success: function(doc) {
      successAjax(doc, calendar);
    },
    error: function() {
      console.log("error");
    }
  }).done(function() {
    window.setTimeout(function() {
      ajaxcall1(calendar);
    }, 4000);
  });
}

$(document).ready(function() {
  var calendarEl = document.getElementById('calendar');
  var calendar = new FullCalendar.Calendar(calendarEl, {
    schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source',
    plugins: ['interaction', 'resourceTimeGrid'],
    resourceGroupField: 'group',
    defaultView: 'resourceTimeGridDay',
    displayEventTime: false,
    slotEventOverlap: false,
    height: 700,
    scrollTime: starthour,
    resourceGroupField: 'groupId',
    slotLabelFormat: {
      hour: 'numeric',
      minute: '2-digit',
      omitZeroMinute: false,
      meridiem: 'short',
      hour12: false
    },
    resources: [{
      id: '1',
      title: 'R16/MOTORES',
      groupId: 'P16'
    }, {
      id: '2',
      title: 'R19/TRANSMISSÃO',
      groupId: 'P19'
    }, {
      id: '3',
      title: 'R26/CHASSIS',
      groupId: 'P26'
    }, {
      id: '4',
      title: 'R27/CHASSIS',
      groupId: 'P27'
    }, {
      id: '5',
      title: 'R40/CABINAS 1',
      groupId: 'p40'
    }, {
      id: '6',
      title: 'R54/CABINAS 2',
      groupId: 'p54'
    }, {
      id: '7',
      title: 'R56/KD',
      groupId: 'P56'
    }, {
      id: '8',
      title: 'TRUCK ON WHEELS',
      groupId: 'P56'
    }],
    nowIndicator: true,
    timeFormat: 'H:mm'
  });

  calendar.render();
  ajaxcall1(calendar);
})

`enter code here`.fc-time-grid .fc-slats td {
    height: 3.4em;
}

.fc-title {
    font-size: 15px;
}

#erro {
    background-color: #FF0000;
}

body {
    margin: 40px 10px;
    padding: 0;
    font-size: 14px;
    min-height: 100%;
}

#backDiv {
    background-size: 100% 120%;
    background-color: #FAFAFA;
    background-position: center;
    position: fixed;
    opacity: 0;
    height: 100%;
    width: 100%;
    top: 50px;
    left: 0;
    opacity: 1;
    z-index: -1;
}
#erro {
    background-color: #FF0000;
}

#warning {
    background-color: #D6001C;
    pointer-events: none;
    position: fixed;
    opacity: 0;
    height: 100%;
    width: 100%;
    top: 0px;
    left: 0;
    opacity: 0.5;
    z-index: 900 !important;
}
.fc table {
    table-layout: auto;
}

.fc-view > table {
    min-width: 0;
    width: auto;
}

.fc-axis {
    min-width: 70px; /*the width of times column*/
    width: 70px; /*the width of times column*/
}

.fc-day, .fc-resource-cell, .fc-content-col, .data-resource-id {
    min-width: 300px;
    width: 300px;
}

The code of successAjax()
enter code herefunction successAjax(doc, calendar) {
        allEvents = [];
        $(doc).each(function (idata) {
         $(location).each(function (iloc) {

                if (location[iloc] == "R16") {
                    allEvents.push({
                        id: idata,
                        resourceId: '1',
                        title: doc[idata].CARRIER_CODE_FOR_DISPLAY + " - " + licenseplate + "\n" + "Entry: " + entrada + "\n" + " - MUs: " + doc[idata].QuantityInside,
                        start: doc[idata].EDA,
                        end: dt,
                        allday: false,
                        backgroundColor: '#041E42',
                        textColor: '#FAFAFA',
                        arrival: doc[idata].PRU_GATE_ARRIVAL_DATE,
                        entry: doc[idata].PRU_GATE_ENTRY_DATE,
                        departure: doc[idata].PRU_GATE_DEPARTURE_DATE,
                        trailerId: doc[idata].TRAILER_ID,
                        description: doc[idata].CARRIER_CODE_FOR_DISPLAY,
                        hour: catchHour
                    });
                } else if (location[iloc] == "R19") {
                    allEvents.push({
                        id: idata,
                        resourceId: '2',
                        title: doc[idata].CARRIER_CODE_FOR_DISPLAY + " - " + licenseplate + "\n" + "Entry: " + entrada + "\n" + " - MUs: " + doc[idata].QuantityInside,
                        start: doc[idata].EDA,
                        end: dt,
                        allday: false,
                        backgroundColor: '#041E42',
                        textColor: '#FAFAFA',
                        arrival: doc[idata].PRU_GATE_ARRIVAL_DATE,
                        entry: doc[idata].PRU_GATE_ENTRY_DATE,
                        departure: doc[idata].PRU_GATE_DEPARTURE_DATE,
                        trailerId: doc[idata].TRAILER_ID,
                        description: doc[idata].CARRIER_CODE_FOR_DISPLAY,
                        hour: catchHour
                    });
                } else if (location[iloc] == "R26") {
                    allEvents.push({
                        id: idata,
                        resourceId: '3',
                        title: doc[idata].CARRIER_CODE_FOR_DISPLAY + " - " + licenseplate + "\n" + "Entry: " + entrada + "\n" + " - MUs: " + doc[idata].QuantityInside,
                        start: doc[idata].EDA,
                        end: dt,
                        allday: false,
                        backgroundColor: '#041E42',
                        textColor: '#FAFAFA',
                        arrival: doc[idata].PRU_GATE_ARRIVAL_DATE,
                        entry: doc[idata].PRU_GATE_ENTRY_DATE,
                        departure: doc[idata].PRU_GATE_DEPARTURE_DATE,
                        trailerId: doc[idata].TRAILER_ID,
                        description: doc[idata].CARRIER_CODE_FOR_DISPLAY,
                        hour: catchHour
                    });
                    ... Input of Events via API
                    try {

            calendar.getEventSources()[0].remove();

        } catch (err)
        {

        }

        calendar.addEventSource(allEvents);

The rest are logic to change color of events and relocate the excess of events in a certain hour


text:
Q: Is it possible to assign a class to :root? As I am thinking about solutions to another problem of mine, I am trying to understand to which extend CSS elements can inherit from other elements. Specifically, having the following definition
.dark {
  background-color: black;
}
.light {
  background-color: white
}

is it possible to programmatically assign (with JS, probably) one of these classes to the :root element?

A: It can be done easily with JS.

*

*Select the element:
const root = document.querySelector(':root')

*Assign the class to it:
root.classList.add('light')

All together:
const root = document.querySelector(':root')
root.classList.add('light')

Or, instead of having two classes, it might be better to have a :not() selector:
:root:not(.dark){
  background-color: white;
}
:root.dark{
  background-color: black;
}

A: I would use (and have used) CSS variables for this.
:root {
  --background-color: black;
}

.background {
  background-color: var(--background-color);
}

Then change the CSS variable with javascript.

A: In HTML, :root is equivalent to <html> (doc):

In HTML, :root represents the  element and is identical to the
  selector html, except that its specificity is higher.

A possible solution would be to apply the class to <html>:

document.getElementsByTagName("html")[0].classList.add('dark')
.dark {
  background-color: red;
}
<html>
hello
</html>


text:
Q: HTML hover shifting other parts of a page when hovered upon Here I have an image gallery that works all fine, however when the smaller images are selected the hover appears to shift all the small images down a bit, which appears to move the entire page which is annoying. I'm assuming it's something to do with margin or padding, and I've tried many combination's with little success. Here is the code:
HTML

HomeLobby

HomeLobby

HomeLobby

HomeLobby

HomeLobby

CSS:
.image_gallery {padding-top: 10px;
                text-align: center;}

.gallery_thumbnails img {height: 60px;
                         width: 106px;}

.gallery_thumbnails img:hover {
                               border: 3px solid #a22b2f;
                               cursor: pointer;}

.gallery_thumbnails {position: relative;}

.imagebox {display: inline;}

.text {display: none;
       position: absolute;
       left: 140px;
       top: -30px;
       font-family: Arial, Helvetica, sans-serif;
       font-size: 16px;
       color: white;
       font-weight: 700;}

.imagebox img:hover + .text {display: block;}

A: You are adding a border on hover. This creates 3 extra px and pushes everything down. If your background is a solid color, add the same border to the element normally then on hover just change the color.
or even better... just add box-sizing: border-box; to the element and the border will take up space in the block and not create 3 extra px.

A: Your border on hover is what's pushing down the elements, i'd suggest adding either
.gallery_thumbnails img:hover {
margin-top: -3px;
}

or
.gallery_thumbnails img {
border: 3px solid transparent;
}

A: Your problem happens because you are adding a border on hover which was not there before. This takes up space, so moves everything down to make room for the new border.
One solution is to add the same boder on the normal unhovered state, but give it a transparent colour, or the same colour as the background. This reserves the necessary space invisibly:
.gallery_thumbnails img {height: 60px;
                         width: 106px;
                         border: 3px solid transparent;

Another way is to use the outline property rather than a border (the syntax is the same):
.gallery_thumbnails img:hover {
                               outline: 3px solid #a22b2f;
                               cursor: pointer;}


text:
Q: How to check if SSRS Textbox text equals "0" I would like to know if there is a way to created some kind of a function is SSRS that checks the value of a given textbox. If the value == "0", then, change it's text to "" (empty).
The idea here is to hide the content if the value is 0. The value comes from the database query results.
I would need a generic function because I have to apply this to a lot of textboxes.

A: If these textboxes are going to have numbers in them, you can change the number formatting to not show the zeros. There's an option on the Text Box Properties/Format/Number for "Show zero as" and you can choose a blank.  You could then copy that format to your other textboxes.

A: "I would like to know if there is a way to created some kind of a function is SSRS that checks the value of a given textbox. If the value == "0", then, change it's text to "" (empty)."
You can use the ReportItems collection to access the textbox.
It is used in the same way as the Fields collection:
  =ReportItems!TextboxName.Value

So in your case the expression would be:
  =IIF(ReportItems!TextboxName.Value = 0, "",ReportItems!TextboxName.Value)


text:
Q: Iphone dev : how can I get a result from google currency converter? Sorry for my english ^^
I would know how I can have a result from the google converter tool for currency, available on http://www.google.com/finance/converter?a=1&from=USD&to=GBP for example.
I have already tried something like that :
    -(IBAction)getResponse:(id) sender{

     NSString *myURLString = @"http://www.google.com/finance/converter?a=1&from=USD&to=GBP";

     NSURL *myURL =  [NSURL URLWithString: myURLString];

     NSData *data = [NSData alloc];

     data=[NSData dataWithContentsOfURL:myURL];

     if(data!=nil && data != ""){

          NSString *response = [[[NSString alloc] initWithData:data]]

          [label setText: response];

     }

     else [label setText:@"not working"];
}

But when I click on my button, the label does not have a text (it is like it is empty).
Am I doing something wrong ?
Is it possible what I want to do ?
Thank you very much for your futures answers !
Olivier.

A: Yeah.. It is possible...
See the data that you are getting is an HTML file or can be treated as xml. Just parse that xml file and get the result. There ia lot of things in that file but you have to only extract

1 USD = 0.6118 GBP

Hey try this URL
http://www.google.com/ig/calculator?hl=en&q=1USD=?INR
This URL will return the JSON
{lhs: "1 U.S. dollar",rhs: "44.5097254 Indian rupees",error: "",icc: true}
Just parse it. :)

A: Try...

NSData *data = [[NSData alloc] init];

Then check you've got something in response
NSLog(@"%@", response);

Better yet, remove the NSData alloc/init
Replace with

NSData *data=[NSData dataWithContentsOfURL:myURL];

And, you'll need to parse the return result, because you're not going to get back what you expect. Response will contain HTML page.

A: You better use an asynchronous request to avoid blocking your app. Easy using ASIHTTPRequest:

- (IBAction)grabURLInBackground:(id)sender
{
   NSURL *url = [NSURL URLWithString:@"http://www.google.com/finance/converter?a=1&from=USD&to=GBP"];
   ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
   [request setDelegate:self];
   [request startAsynchronous];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
   // Use when fetching text data
   NSString *responseString = [request responseString];

   [label setText: responseString];

}

- (void)requestFailed:(ASIHTTPRequest *)request
{
   NSError *error = [request error]; //you can log the error description

   [label setText:@"not working"];

}

A: NSString *myURLString = @"http://www.google.com/finance/converter?a=1&from=USD&to=GBP";

NSURL *myURL =  [NSURL URLWithString: myURLString];

NSData *data = [NSData alloc];

data=[NSData dataWithContentsOfURL:myURL];

if(data!=nil){

    NSString *response = [[NSString alloc] initWithData:data encoding:NSISOLatin1StringEncoding];

    NSLog(@"%@",response);
}

Try this.
This API is giving HTML responce.


text:
Q: dev.example.com Frontend Login Creates Sessions for example.com (Can't login) I have two Magento 1.9.0.1 sites. One on example.com and one on dev.example.com
Production:
Cookie Path: (none)
Cookie Domain: example.com
Development:
Cookie Path: /
Cookie Domain: dev.example.com
I've cleared the /var/session/ directory from the development site, cleared the /var/cache/ directory, and removed any any all *.example.com cookies from my browser. As soon as I hit the homepage of the development site I get new cookies for both example.com and dev.example.com
The problem is that this is causing the famous "Can't login on the frontend" bug. Magento is seeing both cookies and cookies it should be reading.
Things I've tried to do to debug:

*

*Checked Default vs Website vs Store settings. The development server always has dev.example.com for it's settings, while the production server always has example.com

*Checked the frontend for iframes or other content loading example.com from dev.example.com Chrome Inspector shows nothing loading the production domain from the development site.

*I've also checked the usual stuff, like making sure that the form_key is present, etc. This is definitely an issue of Magento creating a session/cookie using the wrong domain name.

A: Using .example.com as a cookie domain means it'll take any cookie that contains .example.com in the domain. The only way to fix this would be to also specify a subdomain for the live webshop. For example; user .www.example.com as the cookie domain.


text:
Q: How can I add typing effect on PNG keyboard image in android app? I am developing an flip clock alarm app similar to Lost TV series clock. The screen displays a terminal and keyboard and the user typed code is displayed on terminal. The terminal and keyboard are PNG images, how can I let user click buttons on PNG image? by animation or something else?

A: I'd suggest not using an image for the keyboard.  The problem with that technique is that you need to know where each key is in order to overlay it with images and effects.  When you take scaling for screen size into account, that's problematic.  And a pain in the neck to keep track of every time the image changes.
A better technique would be to use a single background image and a separate image(s) for the keys-  that way you can easily apply an effect if the key is pressed by applying it when you draw the key image.


text:
Q: Why css animation dose not work on external elements? the following code is working fine

.wrapper {
    position: relative;
    overflow: hidden;
    width: 100px;
    height: 100px;
    border: 1px solid black;
}

#slide {
    position: absolute;
    left: -100px;
    width: 100px;
    height: 100px;
    background: blue;
    transition: 1s;
}

.wrapper:hover #slide {
    transition: 1s;
    left: 0;
}

but if i place the img tag outside of the wrapper then the code not works
so in that case what can i do?
but if i place the img tag outside of the wrapper then the code not works
so in that case what can i do?
but if i place the img tag outside of the wrapper then the code not works
so in that case what can i do?

.wrapper {
    position: relative;
    overflow: hidden;
    width: 100px;
    height: 100px;
    border: 1px solid black;
}

#slide {
    position: absolute;
    left: -100px;
    width: 100px;
    height: 100px;
    background: blue;
    transition: 1s;
}

.wrapper:hover #slide {
    transition: 1s;
    left: 0;
}

Thanks in advance :)

A: You can use the sibling selector +:
.wrapper:hover + #slide

Example:

.wrapper {
    position: relative;
    overflow: hidden;
    width: 100px;
    height: 100px;
    border: 1px solid black;
}

#slide {
    position: absolute;
    left: -100px;
    width: 100px;
    height: 100px;
    background: blue;
    transition: 1s;
}

.wrapper:hover + #slide {
    transition: 1s;
    left: 0;
}


text:
Q: txt tab delimited with columns to xls convert macro problem I have the next macro to convert txt with tab delimited columns to xlsx. For columns with short data in cells nor problem it does very good the macro. However with cells that has very long texts or maybe some special characters the macro trunks the data and is wrongly placed some information to column A or other places where it doesn't correspond. Check photo check the text with red circles that text is from previous row and it was truncated and passed there in column A next row. If I drag and drop manually (not using the macro) that txt with tab delimited columns in excel is processed very good no matter the length of the cells or special characters. If I convert with the macro as you see in red circles is truncated text to other columns/rows it doesn't correspond. What would be required to fix the script and avoid it truncates or destroy the text as seen in red circles.
Public Sub Read_TXT()
Dim Dir_p As String, File_to_Open As String
Dir_p = ActiveWorkbook.Path
File_to_Open = Dir(Dir_p & "\")
While File_to_Open <> ""
  If InStr(1, Right(File_to_Open, 3), "txt", vbTextCompare) <> 0 Then
    Workbooks.OpenText fileName:=Dir_p & "\" & File_to_Open, _
        Origin:=xlWindows, StartRow:=1, DataType:=xlDelimited, TextQualifier:= _
        xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, _
        Comma:=False, Space:=False, Other:=False, _
        TrailingMinusNumbers:=True
    ActiveWorkbook.SaveAs fileName:=Dir_p & "\" & Left(File_to_Open, Len(File_to_Open) - 3) & "xlsx" _
        , FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
    ActiveWorkbook.Close
  End If
  File_to_Open = Dir
Wend
End Sub

Thank you


text:
Q: How to prove one specific condition For a positive integer $n$, the equation $x^2=n+y^2$, $x,y$ integers does not have a solution if and only if
(a) $n=2$
(b) $n$ is a prime number
(c) $n$ is an odd number
(d) $n$ is an even number not divisible by $4$
I think answer should be $n$ is an even number not divisible by $4$, for then we will have $(x+y)(x-y)=2(2K+1)$ which is impossible. Please verify?

A: Hint:
If you want to prove the "only if" part, meaning that the equation does not have a solution only if $n \equiv 2$ mod $4$, then you need to show that it does have a solution if $n$ is odd or $n$ is divisible by 4.
To do that, when $n$ is odd, try letting $(x-y)=1$, and solving for $y$ in terms of $k$, in the equation $1(1+2y)=2k+1$.
When when $n$ is divisible by 4, try letting $(x-y)=2$, and solving for $y$ in terms of $k$, in the equation $2(2+2y)=4k$.


text:
Q: How can I create a default constructor c++? I'm currently learning how to code object oriented and I've created 2 classes (Applicant and OfferLetter) and trying to inherit those 2 classes into a third class (Software Engineer). I've gotten it structured for the most part however im getting an error code on my compiler that says "No default constructor exists for the class "OfferLetter". What can i do to fix this error?
#include <iostream>
using namespace std;

class Applicant{
    private:
        string Name;
        string JobTitle;
        string Degree;
        int YearsOfExpiremce;
        int Age;

    public:
        //Name
        void setName(string name){
            Name = name;
        }
        string getName(){
            return Name;
        }
        //JobTitle
        void setJobTitle(string jobtitle){
            JobTitle = jobtitle;
        }
        string getJobTitle(){
            return JobTitle;
        }
        //Degree
        void setDegree(string degree){
            Degree = degree;
        }
        string getDegree(){
            return Degree;
        }
        //Expirence
        void setExpirence(int expirence){
            YearsOfExpiremce = expirence;
        }
        int getExpirence(){
            return YearsOfExpiremce;
        }
        //Age
        void setAge(int age){
            Age = age;
        }
        int getAge(){
            return Age;
        }
            //Constructor
            Applicant(string name, string jobtitle, string degree, int expirence, int age){
                Name = name;
                JobTitle = jobtitle;
                Degree = degree;
                YearsOfExpiremce = expirence;
                Age = age;
            }
};

class OfferLetter{
    private:
        int BaseSalary;
        int SignOnBonus;
        int Stocks;
        int Incentives;

    public:
        //Base Salary
        void setSalary(int salary){
            BaseSalary = salary;
        }
        int getSalary(){
            return BaseSalary;
        }
        //Sign-On Bonus
        void setBonus(int bonus){
            SignOnBonus = bonus;
        }
        int getBonus(){
            return SignOnBonus;
        }
        //Stocks
        void setStocks(int stocks){
            Stocks = stocks;
        }
        int getStocks(){
            return Stocks;
        }
        //Incentives
        void setIncentives(int incentives){
            Incentives = incentives;
        }
        int getIncentives(){
            return Incentives;
        }
            //Constructor
            OfferLetter(int salary, int bonus, int stocks, int incentives){
                BaseSalary = salary;
                SignOnBonus = bonus;
                Stocks = stocks;
                Incentives = incentives;
            }
};

class SoftwareEngineer: public Applicant, public OfferLetter{
    public:
        string ProgrammingLanguage;
        string JobDescription;

        SoftwareEngineer(string name, string jobtitle, string degree, int expirence, int age, int salary, int bonus,
                        int stocks, int incentives, string language, string jd)

            :Applicant(name, jobtitle, degree, expirence, age)
            :OfferLetter(salary, bonus, stocks, incentives)

        {
            ProgrammingLanguage = language;
            JobDescription = jd;
        }

        void DisplaySEOfferLetter(){
            cout << "Congratulations on your job offer, Here is your total compensation. " << endl;
            cout << "Please respond to us in the next 5 days to confirm your Job Offer." << endl;
            cout << endl;
            cout << "Total Compensation " << endl;
            cout << "-------------------" << endl;
            cout << "Role: Software Engineer " << endl;
            cout << "Job Description: $" << endl;
            cout << "Base Salary  : $" << endl;
            cout << "Sign-On Bonus: $" << endl;
            cout << "Stocks       : $" << endl;
            cout << "Incentives   : $" << endl;
            cout << endl;
        }
};

A: I think the problem is not the default constructor missing, but that you have a syntax error in your code:
SoftwareEngineer(string name, string jobtitle, string degree,
                 int expirence, int age, int salary, int bonus,
                 int stocks, int incentives, string language, string jd)
    :Applicant(name, jobtitle, degree, expirence, age)
    :OfferLetter(salary, bonus, stocks, incentives)
{
}

You attempt to create two constructor initializer lists, which is wrong. A constructor have a single comma-separated list:
SoftwareEngineer(string name, string jobtitle, string degree,
                 int expirence, int age, int salary, int bonus,
                 int stocks, int incentives, string language, string jd)
    : Applicant(name, jobtitle, degree, expirence, age),  // Note comma here
      OfferLetter(salary, bonus, stocks, incentives)      // No colon on this line
{
}

Note that you can initialize member variables using the initializer list as well, and it's recommended to use that instead of assignment inside the constructor body:
SoftwareEngineer(string name, string jobtitle, string degree,
                 int expirence, int age, int salary, int bonus,
                 int stocks, int incentives, string language, string jd)
    : Applicant(name, jobtitle, degree, expirence, age),  // Note comma here
      OfferLetter(salary, bonus, stocks, incentives),      // No colon on this line
      ProgrammingLanguage(language),  // Added initialization
      JobDescription(jd)              // of member variables
{
    // Now this can be totally empty
}


text:
Q: How to automatically send emails in html I am making a form and I want it to email me whenever somebody completes it. Does anybody know if this can be done in HTML alone or if this has to utilize something more? So basically I want to know if it is possible for when a button is pressed, if that can send an email. Thank You!

A: <form action="mailto:yourmailadress@xxx.com?Subject=Mail Subject" method="post" enctype="text/plain">
Name:

<input type="text" name="name">

E-mail:

<input type="text" name="mail">

Comment:

<input type="text" name="comment" size="50">

<input type="submit" value="Send">
<input type="reset" value="Reset">
</form>

This is the process of sending mail that can be done with html without using a different language.


text:
Q: Отказывается работать загрузка файлов когда выполняется подгрузка формы через метод load Есть форма которая подгружается с помощью метода load и в эту форму пытаюсь подключить загрузку файлов jQuery File Upload. Если форма загружается сразу без метода load то загрузка файлов работает отлично. Но когда выполняется подгрузка формы через метод load то загрузка файлов работать отказывается не могу понять почему.
$('.katCatalog').live('change', function() {
    var id = $(this).val();
    var ident = $('.catalogs').val();
    $(".formAdds").load("/ks_tpl/modules/formsAdd.php",
        { id : id, ident : ident },
        function() {
            formSendsKat();
    });
});

function formSendsKat() {
  jQuery(".submitsFormsValid").live('click', function(e) {
    e.preventDefault();
    var m_data= jQuery('.addKatalogsData').serialize();
    jQuery.ajax({
      type: 'POST',
      url: '/ajax/addkatalogs.php',
      data: m_data,
      success: function(result) {
        if(result.result == true) {
          //alert();
        } else { } //$('#upload_form').slideUp(1000);
        jQuery('.resultFormAjax').html(result);
      }
    });
  });
}

Ничего необычного а в файле только стандартный код для подключения плагина.
Если необходимо вот ссылка на официальную страницу загрузчика http://blueimp.github.io/jQuery-File-Upload/


text:
Q: How to make Array Items Hyperlink in HTML using PHP(Code Ignitor) I'm trying to display a list of Meter Serial Number using Array, and when I click on any item of that array I want to display a new page and Meter Serial Number on which I clicked should carry to new page so that I can display information regarding to that serial number, here is my code to display the list which is working fine:

Meter Serial Number

<?php foreach($meterSerialNumber as $serial){ ?>

 <?php echo $serial ?>

<?php } ?>

All I want the code or trick to display new page with that serial number, I am new to web development so expecting little help here.

A: Use anchor helper function and pass serial number
<?php echo anchor('controller/function/'.$serial, 'Serial number') ?>