text:
Q: Mysql2::Error: Specified key was too long; max key length is 767 bytes for table having only 87 db fields I have rails model with table of 87 db columns but when I tried adding any extra db column, it failed
ArbitaryDatum.columns.count
 => 87

ArbitaryDatum.table_name
 => "arbitary_data"

ActiveRecord::Migration.add_column :arbitary_data, :attr51, :string

-- add_column(:arbitary_data, :attr51, :string)
   (1.4ms)  ALTER TABLE `arbitary_data` ADD `attr51` varchar(255)
Mysql2::Error: Specified key was too long; max key length is 767 bytes: ALTER TABLE `arbitary_data` ADD `attr51` varchar(255)
ActiveRecord::StatementInvalid: Mysql2::Error: Specified key was too long; max key length is 767 bytes: ALTER TABLE `arbitary_data` ADD `attr51` varchar(255)

I checked which mysql version I am using,
mysql --version
mysql  Ver 14.14 Distrib 5.5.62, for debian-linux-gnu (i686) using readline 6.3

I am not getting why it does not allow to add extra table column
Q. Why I am not getting Mysql2::Error: Specified key was too long

A: MySQL has a prefix limitation of 767 bytes in InnoDB, and 1000 bytes in MYISAM,
Unfortunately there is no real solution to this. Your only options are to either reduce the size of the column, use a different character set (like UTF-8), or use a different engine (like MYISAM). In this case I switched the character set to UTF-8 which raised the maximum key length to 255 characters.
In Migration set charset to UTF8
reversible do |dir|
      dir.up {
        ActiveRecord::Migration.add_column :data, :attr51, "VARCHAR(255) CHARACTER SET utf8"
      }
    end

A: After struggling for 3 days for this issue, one thing which is said by @muistooshort in comment pulled me toward proper solution.
You might want to revisit your database design in his comment, haunted me for couple of days. All needed was proper direction(which was in that comment) & I solved this problem.
Note: Data provided in question was little manipulated to hide project schema structure.
I was getting issue while adding new column as described in question with error log but it was not due to adding new column in table. It was due to existing table structure in database.
I came to know when I copied table schema from config/schema.rb along with indexes, to create same new table arbitary_data_dup
  # replaced `arbitary_data` with `arbitary_data_dup`
  ActiveRecord::Migration.create_table "arbitary_data_dup", force: :cascade do |t|
    # code to add 87 columns for table
  end
  # following index threw error
  ActiveRecord::Migration.add_index "arbitary_data_dup", ["attr1", "arbitary_structure_id"], name: "index_arbitary_data_on_attr1_and_arbitary_structure_id", unique: true, using: :btree
  ActiveRecord::Migration.add_index "arbitary_data_dup", ["attr1"], name: "index_arbitary_data_on_attr1", length: {"attr1"=>191}, using: :btree
  ActiveRecord::Migration.add_index "arbitary_data_dup", ["id"], name: "index_arbitary_data_on_id", using: :btree
  ActiveRecord::Migration.add_index "arbitary_data_dup", ["arbitary_structure_id"], name: "index_arbitary_data_on_arbitary_structure_id", using: :btree

While running above code in rails console, it threw error same error and I got sure for which reason it was not allowing to add new column,
ActiveRecord::Migration.add_index "arbitary_data_dup", ["attr1", "arbitary_structure_id"], name: "index_arbitary_data_on_attr1_and_arbitary_structure_id", unique: true, using: :btree
-- add_index("arbitary_data_dup", ["attr1", "arbitary_structure_id"], {:name=>"index_arbitary_data_on_attr1_and_arbitary_structure_id", :unique=>true, :using=>:btree})
   (52.5ms)  CREATE UNIQUE INDEX `index_arbitary_data_on_attr1_and_arbitary_structure_id` USING btree ON `arbitary_data_dup` (`attr1`, `arbitary_structure_id`)
Mysql2::Error: Specified key was too long; max key length is 767 bytes: CREATE UNIQUE INDEX `index_arbitary_data_on_attr1_and_arbitary_structure_id` USING btree ON `arbitary_data_dup` (`attr1`, `arbitary_structure_id`)
ActiveRecord::StatementInvalid: Mysql2::Error: Specified key was too long; max key length is 767 bytes: CREATE UNIQUE INDEX `index_arbitary_data_on_attr1_and_arbitary_structure_id` USING btree ON `arbitary_data_dup` (`attr1`, `arbitary_structure_id`)

So I found reason for which It do not allow to add new column -> invalid name for existing index.
So I removed that index and thereafter I am able to add new columns.
ActiveRecord::Migration.remove_index "arbitary_data", ["attr1", "arbitary_structure_id"]
-- remove_index("arbitary_data", ["attr1", "arbitary_structure_id"])
   (148.6ms)  DROP INDEX `index_arbitary_data_on_attr1_and_arbitary_structure_id` ON `arbitary_data`
   -> 0.1698s
 => nil
ActiveRecord::Migration.add_column :arbitary_data, :attr51, :string
-- add_column(:arbitary_data, :attr51, :string)
   (523.3ms)  ALTER TABLE `arbitary_data` ADD `attr51` varchar(255)
   -> 0.5238s
 => nil

Added same index again using help

A: create database as utf8_general_ci then no problem


text:
Q: Help with a subset $A$ of the real line that has four distinctive derived sets distinct from each other. I have the following question: I need to provide a subset $A$ of the real line that has four distinctive derived sets distinct from each other.
 I'm stuck at finding the first derived set.
 If I let
 $\begin{gathered}
  {A^{\left( 4 \right)}} = \left\{ 0 \right\} \hfill \\
  {A^{\left( 3 \right)}} = \left\{ 0 \right\} \cup \left\{ {\frac{1}{n}: n \in \mathbb{N}, n \geq 2} \right\} \hfill \\
  {A^{\left( 2 \right)}} = \left\{ 0 \right\} \cup \left\{ {\frac{1}{n}:n \geq 2} \right\} \cup \left\{ {\frac{1}{n} + \frac{1}{k}\left( {\frac{1}{{n - 1}} - \frac{1}{n}} \right):k \geq 2} \right\} \hfill \\
\end{gathered} $
 Then I'm stuck at what ${A^{\left( 1 \right)}} = {A^d}$ will look like, and in return $A$? How do I construct the next set?
 I appreciate your help.

A: Observe what you do when moving from $A^{(3)}$ to $A^{(2)}$. You have $\{0\} ∪ \{\frac{1}{n}: n ∈ ℕ\}$ – a converging sequence. And what you do? To every gap $(\frac{1}{n + 1}, \frac{1}{n})$ you add a new sequence converging to $\frac{1}{n + 1}$ (and you do essentially the same thing for the first element of the sequence). This turns all the previously isolated point into the limit points of the first level… It is not clear how the corresponding formula would look like, but that is not important. The point is the general idea.

redpajama_set_name: RedPajamaStackExchange


text:
Q: xrandr changes X's orientation too slowly I'm changing X's orientation with following command
xrandr -o left
xrandr -o normal
...
When orientation is changing screen becomes black for a moment then it switches orientation.
So how to get rid of this black screen effect ? Maybe some other options should be added to xrandr ?
Regards,
Levon

A: Actually I found the reason of the problem and posted corresponding bug.
For details see in my blog
http://levonp.blogspot.com/2010/11/xserver-black-screen-delay-when.html

A: Sorry, because of the way X and randr works, this is not possible.

A: Actually the transition from normal mode to inverted is being done very smoothly. But transition from inverted to normal mode is being done with black screen effect.
Please provide more info on kernel mode settings concerning this


text:
Q: Comparing strings first letter how can i do this in java
if left(mystring,3)="adm" then ..

i've tried this but not success
if (mystring.charAt(3).equals("adm")) { ...

Could anyone tell me the correct way?

A: The method charAt() returns a primitive value char, the one at the given index. You can't call a method in a char value.
You could use
myString.startsWith("adm")

Instead.
The more important point is that all these methods are extensively documented. So don't assume what a method is doing. Study its javadoc instead.

A: You can achieve that using substring method
if (mystring.substring(0,3).equals("adm")) {

The String function substring(int j,int i) gives a substring of the original string from index j until index i, excluding character at i

A: You can use startsWith(string) like this :
if(mystring.startsWith("adm")){...


text:
Q: SET A, 0x1E vs SET A, 0x1F This is my first attempt at dpcu, I'm checking machine code generated by dpcu-16 assembly
I am using this emulator : http://dcpu.ru/
I am trying to compare code generated by
SET A, 0x1E
SET A, 0x1F

code generated is as follow :
fc01
7c01 001f

I don't get why operand size changes between those two values

A: That emulator appears to be using the next version of the DCPU-16 spec, which specifies that the same-word literal value for a permits values from 0xFFFF (-1) to 0x1E (30). This means that to get any literal value outside this range the assembler has to use the next-word literal syntax, which makes the operand one byte bigger.

A: 0x1F (dec:31) is no longer a short literal (values -1 to 30), so it has to be read as a "next word" argument.
The opcodes are thus:
SET A, 0x1E
SET =             00001
A   =        00000
1E  =  111111
op  =  1111110000000001 = fc01

SET A, 0x1F
SET =             00001
A   =        00000
NW  =  011111
op  =  0111110000000001 = 7c01 + 001f


text:
Q: Run a handler play and exit play if rc == 0 in ansible Hi is there a way I can run a handler play then exit the play if rc == 0. It can only do is exit the play using failed_when and proceed if rc != 0. I can't make notify: Service Guard execute. Been play with other approach like creating 2 play notify and exit no luck.
- name: Exit SG server from play
  command: /usr/local/cmcluster/bin/cmversion
  register: sg_check
  notify: Service Guard
  failed_when: sg_check.rc == 0

Here is new code I tried
- name: Check if Service Gurad then exit
  command: /usr/local/cmcluster/bin/cmversion
  register: sg_check
  notify: Service Guard
  changed_when: sg_check.rc == 0
  ignore_errors: true
- meta: end_play
  when: sg_check.rc == 0

but I get this:
ERROR! The conditional check 'sg_check.rc == 0' failed. The error was: error while evaluating conditional (sg_check.rc == 0): 'sg_check' is undefined
The error appears to have been in '/home/ansible/linuxpatchingv2/roles/applyPatch/tasks/main.yml': line 9, column 3, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
ignore_errors: true

*

*meta: end_play
^ here

A:
Q: "Run a handler play then exit the play if rc == 0"

A: This is not possible to accomplish in one task because a task can't be both changed and failed at the same time. These two actions must be split. For example, in the playbook below the command will succeed, notify the handler, and end the play
shell> cat pb.yml
- hosts: localhost
  gather_facts: false
  tasks:
    - command: "{{ cmd|default('/bin/true') }}"
      register: sg_check
      notify: Service Guard
      changed_when: sg_check.rc == 0
      ignore_errors: true
    - meta: end_play
      when: sg_check.rc == 0
    - debug:
        msg: Continue
  handlers:
    - name: Service Guard
      debug:
        msg: Service Guard notified

gives (abridged)
shell> ansible-playbook pb.yml
...
RUNNING HANDLER [Service Guard] ****
ok: [localhost] =>
  msg: Service Guard notified

PLAY RECAP ****
localhost: ok=2 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

The same playbook will continue if the command fails. For example
shell> ansible-playbook pb.yml -e "cmd=/bin/false"

PLAY [localhost] ****

TASK [command] ****
fatal: [localhost]: FAILED! => changed=false
  cmd:
  - /bin/false
  delta: '0:00:00.003035'
  end: '2020-08-24 09:33:22.039762'
  msg: non-zero return code
  rc: 1
  start: '2020-08-24 09:33:22.036727'
  stderr: ''
  stderr_lines: <omitted>
  stdout: ''
  stdout_lines: <omitted>
...ignoring

TASK [debug] ****
ok: [localhost] =>
  msg: Continue

PLAY RECAP ****
localhost: ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=1


text:
Q: Как подключить JS с импортами, чтобы в body.onload определился объект? Есть файл service.js, который начинается так:
import Access from "./controls/access.js"
import Menu from "./controls/menu.js"
import User from "./controls/user.js"
import Admin from "./controls/admin.js"

class Service
{ ...

Есть генерация странички на PHP:
$uri = $this->proto.$this->name."/public/";
$img = $uri."images";
$css = $uri."styles";
$js = $uri."scripts";
$html = <<<HTML
<html>
<head>
<title>My service</title>
<link rel="shortcut icon" type="image/x-icon" href="$img/favicon.ico">
<link rel="stylesheet" type="text/css" href="$css/style.css"/>
<script type="module" src="$js/service.js"></script>
</head>
<body onload="new Service('$this->control','$this->action');"></body>
</html>
HTML;

header("content-type: text/html; charset: UTF-8");
exit($html);

При загрузке страницы в консоли браузера сообщение Service is not defined. Если не использовать import в js и подгружать все скрипты напрямую с script type="application/javascript" вместо module, то всё работает. Если же просто поменять тип на application/javascript и оставить импорты, то получается ошибка import declarations may only appear at top level of a module.
Как правильно подключить скрипт с импортами (или как-то изменить его), чтобы это заработало?

A: Можно как-то так:
Добавить
<script>var data={control: '$this->control', action: '$this->action'}</script>

А в конце service.js:
new Service(data.control,data.action);


text:
Q: Django URL Routing misbehaving, routing to an unanticipated path I made some changes to model.py, foreignKey adjustments. (I realized I placed them on the wrong class). Deleted the database and created a new from scratch since I was that far in. When I felt like i corrected everything in the DB to run, and ran runserver again, i get an KeyError error, to a path it shouldn't be directed to.
When I type in the url 127.0.0.1:8000/add_tech/, or add_exp/ it loads the right form, when I submit, it shows it the function received the term tech or exp through the regex in urls.py, but disappointingly the stack trace output shows differently.
The views.py doesn't seem to routing correctly. Are there steps I should follow to help step through and debug this?
urls.py has the following
from django.conf.urls import patterns, include, url
from resume.views import add_entry, remove_entry

urlpatterns = patterns('',
    url(r'^add_(\w+)/$',add_entry),
    url(r'^remove_(\w+)/$',remove_entry),
)

It's being routed to views.py in resume/: (As seen)
def add_entry(request, option):
print "Print Option in Url is:"+option #<----- see console out below.
options={
    'job':add_job(request),
    'exp':add_exp(request),
    'tech':add_tech(request),
    'course':add_course(request),
    'project':add_project(request)
    }
form_html = options[option]
return form_html

This is what the print displays in console, it should be routed to add_exp, not sure how it's being routed to add_tech, as you see when an error is raised.:
[18/May/2014 17:01:21] "GET /add_exp/ HTTP/1.1" 200 1446

Print Option in Url is:**exp**

Internal Server Error: **/add_exp/**
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 115, in get_response
    response = callback(request, *callback_args, \*\*callback_kwargs)

File "/home/asilvajr/Repository/mysite/resume/views.py", line 120, in **add_entry**
    'tech':add_tech(request),

File "/home/asilvajr/Repository/mysite/resume/views.py", line 19, in **add_tech**
    return submit_tech(request)

File "/home/asilvajr/Repository/mysite/resume/views.py", line 76, in **submit_tech**
    if vals['tech_name']:

KeyError: 'tech_name'

---- End Console Output -----

Just the form, in tech_form (should be loaded before and after submit):
<form action="/add_tech/" method="POST">
Technolgy Used:
    <input type="text" name="tech_name">

    Type:
<select name="tech_type">
    <option name="L">Language</option>
    <option name="Fr">Framework</option>
    <option name="T">Tools</option>
    <option name="K">Kits</option>
    <option name="E">Extensions</option>
</select>

<input type="submit" name="submit">

</form>

Just the form, in exp_form (should be loaded before and after submit):
<form action="/add_exp/" method="POST">
Event:
    <input type="text" name="event">

    Description:
<textarea type="textarea" name="exp_descript"></textarea>

Technology Used:
{% for tech in techs %}
<input type="checkbox" class="tech_{{ tech.tech_type }}" name="technologies" value="{{ tech.id }}">{{ tech.name }} :: {{ tech.tech_type }}

{% endfor %}
<input type="submit" name="submit">

</form>

Both add_tech and add_exp are designed like so:
def add_tech(request):
    if 'submit' in request.POST:
        return submit_tech(request)
    techs = Technologies.objects.all()
    return render(request, 'tech_form.html',{'techs':techs})

Submit_tech as requested:
def submit_tech(request):
    vals = request.POST.dict()
    vals['errors']=[]
    if vals['tech_name']:
        try:
            exists=Technologies.objects.get(name=vals['tech_name'])
        except Technologies.DoesNotExist:
            exists=None
        if not exists:
            tech = Technologies(name=vals['tech_name'],tech_type=vals['tech_type'])
            tech.save()
        else:
            vals['errors'].append(exists.name + "already exists as a " + exists.tech_type)
    else:
        vals['errors'].append("Added Nothing, Text Feild was empty")
    vals['techs'] = Technologies.objects.all()
    return render(request, 'tech_form.html', vals)

A: I created a test project and copy paste your codes. It works fine here, I can successfully POST to /add_tech/, and a new Technologies was created in DB.
I suggest you to check the render() statement in your add_exp function, is the template name correct?
Additionally, two suggestions:
1). in add_entry funciton, add handling for invalid entry name; 2). in 3rd line of submit_tech function, use if vals.get('tech_name', None):, otherwise the codes will raise 500 error when somebody submit an invalid form


text:
Q: Show image in jsp from config.properties I need to load image from config.properties a show it in jsp page with cotroller. I need simple solution. How does it work?
Thank you
Edit:
Properties prop = new Properties();
try {
    prop.load(getClass().getClassLoader().getResourceAsStream("config.properties"));
    String path = prop.getProperty("filepath") + filename + ".jpg";

    BufferedImage image = ImageIO.read(new File(path));
    ByteArrayOutputStream byteimage = new ByteArrayOutputStream();
    ImageIO.write( image, "jpg", byteimage );
    byteimage.flush();
    byte[] imageInByte = byteimage.toByteArray();
    byteimage.close();

    model.addAttribute("image", Base64.getEncoder().encode(imageInByte));
} catch (IOException e) {
    e.printStackTrace();
}

I tried this but it doesnt work.

A: You can store in your *.properties file image in BASE64 format. Get it in controller via @Value private String image annotation, than sand to your view. In view show accepted image: <img src="data:image/gif;base64,HERE_BASE64_IMAGE/>.


text:
Q: Hash function that protects against collisions, not attacks. (Produces a random UUID-size result space) Using SHA1 to hash down larger size strings so that they can be used as a keys in a database.
Trying to produce a UUID-size string from the original string that is random enough and big enough to protect against collisions, but much smaller than the original string.
Not using this for anything security related.
Example:
# Take a very long string, hash it down to a smaller string behind the scenes and use
#     the hashed key as the data base primary key instead
def _get_database_key(very_long_key):
    return hashlib.sha1(very_long_key).digest()

Is SHA1 a good algorithm to be using for this purpose? Or is there something else that is more appropriate?

A: Python has a uuid library, based on RFC 4122.
The version that uses SHA1 is UUIDv5, so the code would be something like this:
import uuid

uuid.uuid5(uuid.NAMESPACE_OID, 'your string here')


text:
Q: How to optimize drag animation (useState + transform: translate) i have a Card component, which is draggable on mobile devices. on touch start it saves the initial point, on touch move it updates the current point state and on touch end it restores points and makes some logic with the swipe direction. it works fine when is testing on desktop but on mobile it is very sharp. how can i optimize drag animation so it works smooth?
i use "dragging" key to smooth relocate card on initial position if the distance is small
const Card = ({screens, title, overview, release_date, onSwipe}: props) => {
    const [initialPoint, setInitialPoint] = useState({x: 0, y: 0})
    const [currentPoint, setCurrentPoint] = useState({x: 0, y: 0})
    const [dragging, setDragging] = useState(false)

    const [currentStep, setCurrentStep] = useState(0)

    const touchStartHandler = (e: React.TouchEvent) => {
        setDragging(true)
        setInitialPoint({
            x: e.touches[0].pageX,
            y: e.touches[0].pageY
        })
        setCurrentPoint({
            x: e.touches[0].clientX,
            y: e.touches[0].clientY
        })
    }
    const touchMoveHandler = (e: React.TouchEvent) => {
        setCurrentPoint({
            x: e.touches[0].clientX,
            y: e.touches[0].clientY
        })
    }
    const touchEndHandler = () => {
        if(currentPoint.x - initialPoint.x === 0) {
            if(currentPoint.x > window.screen.width / 2) {if(currentStep < screens.length - 1) setCurrentStep(x => x + 1)}
            else if(currentStep > 0) setCurrentStep(x => x - 1)
        }
        setDragging(false)
        setCurrentPoint({x: 0, y: 0})
    }

    useEffect(() => {
        preload(screens)
    }, [screens])

    return (
        <div
            style={{
                transform: `translate(${currentPoint.x - initialPoint.x}px, ${currentPoint.y - initialPoint.y}px) rotate(${(window.screenX - currentPoint.x + initialPoint.x)/45}deg)`,
transition: dragging ? '0s' : '200ms'
            }}
            onTouchStart={touchStartHandler}
            onTouchMove={touchMoveHandler}
            onTouchEnd={touchEndHandler}
            className={`w-[100%] h-[100%] box-border rounded-2xl absolute overflow-hidden bg-black`}
        >
            <div style={{backgroundImage: `url('${screens[currentStep]}')`}} className={'w-[120%] h-[120%] box-border rounded-2xl bg-black bg-cover bg-center blur-lg absolute left-[-10%] top-[-10%] opacity-50'}/>
            <Stamps currentPoint={currentPoint} initialPoint={initialPoint}/>
            <div className={'bg-contain bg-center bg-no-repeat h-full absolute w-full top-0 rounded-2xl'} style={{backgroundImage: `url('${screens[currentStep]}')`}}/>
            <Counter current={currentStep} total={screens.length}/>

{title}

{release_date.split('-')[0]}, комедия, триллер

                    {overview}

Полностью на themoviedb.org

    );
};

const Stamps = ({currentPoint, initialPoint}: {currentPoint: point, initialPoint: point}) => {
    return (
        <>

НРАВИТСЯ

НУ ТАКОЕ

            <div style={Math.abs(currentPoint.x - initialPoint.x) < 50 ? {opacity: (-currentPoint.y + initialPoint.y - 50) / window.screen.height * 6} : {opacity: 0}}
                 className={'font-bold text-blue-400 text-4xl absolute bottom-56 z-30 border-4 border-blue-400 p-4 rounded-2xl -rotate-12 right-16'}>ПОСМОТРЮ

            <div style={Math.abs(currentPoint.x - initialPoint.x) < 50 ? {opacity: (currentPoint.y - initialPoint.y - 50) / window.screen.height * 6} : {opacity : 0}}
                 className={'font-bold text-gray-400 text-4xl absolute top-28 z-30 border-4 border-gray-400 p-4 rounded-2xl rotate-12 right-8'}>ПРОПУСТИТЬ

        </>
    );
};

const Counter = ({current, total}: props) => {
    const a = new Array(total).fill(false)
    return (

            {a.map((_, i) => {
                if(i === current) return <div key={`active-${i}`} className={'bg-gradient-to-br from-[#FDABDD] to-[#374A5A] rounded-full flex h-full w-full'}/>
                else return <div key={`passive-${i}`} className={'bg-rose-50 rounded-full flex h-full w-full'}/>
            })}

    );
};

also there is no more than 2 cards displayed in one time

A: lol, i just tried to add to Card class "will-change-transform" and it boosted my animation to 60 fps


text:
Q: How to import an SQL database file I'm following this recommended guide to create a SQLite database with pre-loaded data; however I cannot understand how to produce the required database file (.db).
I have used the software "DB Browser for SQLite" to write up my database, but can only seem to save the file as the commands to create a database (CREATE TABLE IF NOT EXISTS etc.).
How do I save my file into the required .db format?
This website's solution is why I think my file is in the wrong format.
For context, the error I am experiencing is as follows:
09-02 23:47:58.681 19704-19704/company.app W/SQLiteAssetHelper: copying database from assets...
09-02 23:47:58.682 19704-19704/company.app W/SQLiteAssetHelper: database copy complete
09-02 23:47:58.684 19704-19704/company.app E/SQLiteLog: (26) file is encrypted or is not a database
09-02 23:47:58.684 19704-19704/company.app E/DefaultDatabaseErrorHandler: Corruption reported by sqlite on database: /data/user/0/company.app /databases/app .db
09-02 23:47:58.684 19704-19704/company.app E/DefaultDatabaseErrorHandler: deleting the database file: /data/user/0/company.app /databases/app .db
09-02 23:47:58.686 19704-19704/company.app E/SQLiteLog: (14) cannot open file at line 32504 of [bda77dda96]
09-02 23:47:58.686 19704-19704/company.app E/SQLiteLog: (14) os_unix.c:32504: (2) open(/data/user/0/company.app /databases/app .db) -
09-02 23:47:58.687 19704-19704/company.app E/SQLiteDatabase: Failed to open database '/data/user/0/company.app /databases/app .db'.
                                                                        android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
                                                                            at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
                                                                            at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
                                                                            at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
                                                                            at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
                                                                            at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
                                                                            at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
                                                                            at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:808)
                                                                            at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:796)
                                                                            at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:696)
                                                                            at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:671)
                                                                            at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.returnDatabase(SQLiteAssetHelper.java:408)
                                                                            at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.createOrOpenDatabase(SQLiteAssetHelper.java:401)
                                                                            at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getWritableDatabase(SQLiteAssetHelper.java:176)
                                                                            at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getReadableDatabase(SQLiteAssetHelper.java:254)
                                                                            at company.app .MyDatabase.randomiseItBro(MyDatabase.java:33)
                                                                            at company.app .MainActivity.randomise(MainActivity.java:55)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at android.view.View$DeclaredOnClickListener.onClick(View.java:4695)
                                                                            at android.view.View.performClick(View.java:5612)
                                                                            at android.view.View$PerformClick.run(View.java:22285)
                                                                            at android.os.Handler.handleCallback(Handler.java:751)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                            at android.os.Looper.loop(Looper.java:154)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
09-02 23:47:58.688 19704-19704/company.app W/SQLiteAssetHelper: could not open database app .db - unknown error (code 14): Could not open database
09-02 23:47:58.689 19704-19704/company.app D/AndroidRuntime: Shutting down VM
09-02 23:47:58.689 19704-19704/company.app E/AndroidRuntime: FATAL EXCEPTION: main
                                                                        Process: company.app , PID: 19704
                                                                        java.lang.IllegalStateException: Could not execute method for android:onClick
                                                                            at android.view.View$DeclaredOnClickListener.onClick(View.java:4700)
                                                                            at android.view.View.performClick(View.java:5612)
                                                                            at android.view.View$PerformClick.run(View.java:22285)
                                                                            at android.os.Handler.handleCallback(Handler.java:751)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                            at android.os.Looper.loop(Looper.java:154)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
                                                                         Caused by: java.lang.reflect.InvocationTargetException
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at android.view.View$DeclaredOnClickListener.onClick(View.java:4695)
                                                                            at android.view.View.performClick(View.java:5612)
                                                                            at android.view.View$PerformClick.run(View.java:22285)
                                                                            at android.os.Handler.handleCallback(Handler.java:751)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                            at android.os.Looper.loop(Looper.java:154)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
                                                                         Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.database.sqlite.SQLiteDatabase.getVersion()' on a null object reference
                                                                            at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getWritableDatabase(SQLiteAssetHelper.java:178)
                                                                            at com.readystatesoftware.sqliteasset.SQLiteAssetHelper.getReadableDatabase(SQLiteAssetHelper.java:254)
                                                                            at company.app .MyDatabase.randomiseItBro(MyDatabase.java:33)
                                                                            at company.app .MainActivity.randomise(MainActivity.java:55)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at android.view.View$DeclaredOnClickListener.onClick(View.java:4695)
                                                                            at android.view.View.performClick(View.java:5612)
                                                                            at android.view.View$PerformClick.run(View.java:22285)
                                                                            at android.os.Handler.handleCallback(Handler.java:751)
                                                                            at android.os.Handler.dispatchMessage(Handler.java:95)
                                                                            at android.os.Looper.loop(Looper.java:154)
                                                                            at android.app.ActivityThread.main(ActivityThread.java:6123)
                                                                            at java.lang.reflect.Method.invoke(Native Method)
                                                                            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
                                                                            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)

A: When you click the "New Database" toolbar button, you create a SQLite database file. When you create tables and stuff, then click the "Write Changes" toolbar button, you update that database file. Once you have the database file the way that you want, that is the file that you include in your assets/ for use by SQLiteAssetHelper.
The Linux edition of DB Browser for SQLite does not apply a file extension by default to the file. You will want to add the .db yourself when creating the database file, or rename it after you create it.

A: You can create a file just like a myfunc.js file or index.html but this one is mydb.sql with the codes. Regular word file ex:
CREATE DATABASE activedb;
CREATE TABLE table_name (
    column1 datatype,
    column2 datatype,
    column3 datatype,
   ....
);
then you can use database_name < mydb.sql
I think that is what you are trying to do. I am not sure.

A: If you are taking care correctly in your application to transfer the database from the assets to your database directory, then you are probably missing one of the following two requirements:

*

*the primary key needs to be named _id

*the database needs one specific table that you need to craete: CREATE TABLE android_metadata (_id INTEGER PRIMARY KEY, locale TEXT)


text:
Q: How to return an variable from a AsyncTask class to an fragment I have created an multiple fragments which all require data from an server. So I created an reusable AsyncTask. Which connects to an server via sockets, transfers some packets and finaly receives the response. How can I 'dynamically' return the result (a.k.a the response) from onPostExecute? I have created an flowchart to explain myself better.

A: The AsyncTask can simply call a callback in the provided Fragment in onPostExecute, or the AsyncTask can be a nested class of the given fragment.
for example
public class MyFragment extends Fragment {

    void onResult(Result result) {...}

    private class MyTask extends AsyncTask<String, Void, Result> {
        doInBackground(...) {}
        onPostExecute(Result result)  {
            onResult(result);
        }
    }
}

This has the drawbacks of holding the reference of the fragment until your task is complete. If your task always terminates eventually and is not referenced by any static context, then it's fine since the memory will eventually be collected.

A: you can use a listener, which is implemented in every fragment using the async task. Define a method in the interface with the required result parameters.
You can pass the reference to the async task and store it there in a weak reference


text:
Q: How to work in team with visual studio 2008 net developer.Now a days we work on project with my team members.how to share a project so we can work on a single project and all changes applied on single project rather than we work on multiple projects and then we merge them please can anyone explain me how to do this

A: In a team, one uses a revision control tool, such as Subversion, Git, TFS, Mercurial or one of many others.


text:
Q: SendKeys through IIS Server I'm able to SendKeys.SendWait through IIS Server Express (debugging through Visual Studio) but it doesn't work when site is hosted on IIS Server. It seems that I need to run asp.net site as Administrator but I have no idea how to do that and need some steps to accomplish that.
Thanks in advance:)


text:
Q: Explain to me why this configuration redirects by apache I was finally able to duplicate my Magento store and now i'm able to develop in/with git.
The Copy is stored in /var/www.dev
So i thought i duplicate my apache/site-available/shop to dev.shop in the same folder, change the configuration from ServerName shop.com to dev.shop.com and that should be enought.
Unfortunatly all my requests for dev.shop.com become redirected to shop.com, and i can't figure out why.
Logs say it is a 302 redirect. So it cant be a Javascript, and since it is before the php stuff will run it has to be the apache Server.
Here is some config.
/etc/apache2/sites-available/shop.com
<VirtualHost *:80>
ServerAdmin it@shop.com
ServerName www.shop.com
ServerAlias shop.com

DocumentRoot /var/www
<Directory />
    Options FollowSymLinks
    AllowOverride All
</Directory>
<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride All
    Order Allow,Deny
</Directory>

ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
<Directory "/usr/lib/cgi-bin">
    AllowOverride None
    Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
    Order allow,deny
    Allow from all
</Directory>

ErrorLog ${APACHE_LOG_DIR}/error.log

# Possible values include: debug, info, notice, warn, error, crit,
# alert, emerg.
LogLevel warn

CustomLog ${APACHE_LOG_DIR}/access.log combined

Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
    Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>
</VirtualHost>
<VirtualHost *:443>
    ServerAdmin it@shop.com
    ServerName www.shop.com
    ServerAlias shop.com
    SSLEngine On
    SSLCertificateFile /etc/apache2/ssl/shop.com.crt
    SSLCertificateKeyFile /etc/apache2/ssl/shop.com.key
    SSLCACertificateFile /etc/apache2/ssl/SSL_CA_Bundle.pem

    DocumentRoot /var/www
    <Directory />
        Options FollowSymLinks
        AllowOverride All
    </Directory>
    <Directory /var/www/>
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order Allow,Deny
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
        AllowOverride None
        Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
        Order allow,deny
        Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error_ssl.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access_ssl.log combined

    Alias /doc/ "/usr/share/doc/"
    <Directory "/usr/share/doc/">
        Options Indexes MultiViews FollowSymLinks
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.0/255.0.0.0 ::1/128
    </Directory>
</VirtualHost>

And this is the /etc/apache2/sites-available/dev.shop.com
<VirtualHost *:80>
    ServerAdmin it@shop.com

    ServerName dev.shop.com
    ServerAlias dev.shop.com dev shop.com

    DocumentRoot /var/www.dev
    <Directory />
            Options FollowSymLinks
            AllowOverride All
    </Directory>
    <Directory /var/www.dev/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order Allow,Deny
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
            AllowOverride None
            Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
<VirtualHost *:443>
    ServerAdmin it@shop.com

    ServerName www.dev.shop.com
    ServerAlias dev.shop.com

    SSLEngine On
    SSLCertificateFile /etc/apache2/ssl/shop.com.crt
    SSLCertificateKeyFile /etc/apache2/ssl/shop.com.key
    SSLCACertificateFile /etc/apache2/ssl/SSL_CA_Bundle.pem

    DocumentRoot /var/www.dev
    <Directory />
            Options FollowSymLinks
            AllowOverride All
    </Directory>
    <Directory /var/www.dev/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order Allow,Deny
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
            AllowOverride None
 Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
            Order allow,deny
            Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error_ssl.log

    # Possible values include: debug, info, notice, warn, error, crit,
    # alert, emerg.
    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access_ssl.log combined

Alias /doc/ "/usr/share/doc/"
<Directory "/usr/share/doc/">
    Options Indexes MultiViews FollowSymLinks
    AllowOverride None
    Order deny,allow
    Deny from all
    Allow from 127.0.0.0/255.0.0.0 ::1/128
</Directory>
</VirtualHost>

A: Since your dev config file
/etc/apache2/sites-available/dev.shop.com

has
AllowOverride All

in the settings for the directory
/var/www.dev/

something else you might check for is whether your site is using Redirects in .htaccess
Look for the presence of this file
/var/www.dev/.htaccess

that contains entries with some version of Redirect in it.  It may be sending browsers that visit the dev host on to the production one.  This can happen when you simply copy all the files in the web root, or use some version control system to get the code deployed in both places not realizing that the .htaccess file has those Redirects.
If so, you just need to adjust the redirect rules to redirect to the dev site.


text:
Q: How to add image to kivy application? I'm having trouble importing images into my kivy application. Here's the error log, and my code is below.
C:\Users\sangu\Desktop\LibertyComm>python main.py
[INFO   ] [Logger      ] Record log in C:\Users\sangu\.kivy\logs\kivy_20-09-09_57.txt
[INFO   ] [deps        ] Successfully imported "kivy_deps.gstreamer" 0.1.18
[INFO   ] [deps        ] Successfully imported "kivy_deps.glew" 0.1.12
[INFO   ] [deps        ] Successfully imported "kivy_deps.sdl2" 0.1.23
[INFO   ] [Kivy        ] v1.11.1
[INFO   ] [Kivy        ] Installed at "C:\Users\sangu\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\__init__.py"
[INFO   ] [Python      ] v3.6.6rc1 (v3.6.6rc1:1015e38be4, Jun 12 2018, 07:51:23) [MSC v.1900 32 bit (Intel)]
[INFO   ] [Python      ] Interpreter at "C:\Users\sangu\AppData\Local\Programs\Python\Python36-32\python.exe"
[INFO   ] [Factory     ] 184 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_pil, img_gif (img_ffpyplayer ignored)
[INFO   ] [Window      ] Provider: sdl2
[INFO   ] [GL          ] Using the "OpenGL" graphics system
[INFO   ] [GL          ] GLEW initialization succeeded
[INFO   ] [GL          ] Backend used <glew>
[INFO   ] [GL          ] OpenGL version <b'4.6.0 - Build 26.20.100.8141'>
[INFO   ] [GL          ] OpenGL vendor <b'Intel'>
[INFO   ] [GL          ] OpenGL renderer <b'Intel(R) UHD Graphics 630'>
[INFO   ] [GL          ] OpenGL parsed version: 4, 6
[INFO   ] [GL          ] Shading version <b'4.60 - Build 26.20.100.8141'>
[INFO   ] [GL          ] Texture max size <16384>
[INFO   ] [GL          ] Texture max units <32>
[INFO   ] [Window      ] auto add sdl2 input provider
[INFO   ] [Window      ] virtual keyboard not allowed, single mode, not docked
[INFO   ] [Text        ] Provider: sdl2
[ERROR  ] [Image       ] Error reading file icons/unsplash2.jpg
[ERROR  ] [Image       ] Error reading file icons/unsplash1.jpg
[WARNING] [Lang        ] kv/homescreen.kv has already been included!
[WARNING] [Lang        ] kv/settingscreen.kv has already been included!
[ERROR  ] [Image       ] Error reading file icons/unsplash2.jpg
[ERROR  ] [Image       ] Error reading file icons/unsplash1.jpg
[INFO   ] [Base        ] Start application main loop
[INFO   ] [GL          ] NPOT texture support is available

Here is my code:
#: import utils kivy.utils
<HomeScreen>:
    FloatLayout:
        canvas:
            Color:
                rgb: utils.get_color_from_hex("#FFFFFF")
            Rectangle:
                size: self.size
                pos: self.pos
        GridLayout:
            rows: 1
            pos_hint: {"top": 1, "x": 1}
            size_hint: 1, .1
            Image:
                source: "icons/unsplash1.jpg"
                size: self.texture_size

I've been struggling with this for over an hour. Searching the web revealed absolutely nothing that worked, so hopefully, I'll be able to get a good response here. Thanks! (And yes, I'm sure the images are in the correct directory)


text:
Q: NPM install package: GeoFireX, error with google cloud functions I'm trying to install GeoFireX.
I did this steps like the documentation said:
npm install geofirex
# peer dependencies
npm install rxjs firebase

But when I install the packages I get this message:
npm WARN geofirex@0.0.6 requires a peer of firebase@5.2.0 but none is installed. You must install peer dependencies yourself.

So I tried installing firebase@5.2.0, but the message keeps coming.
I'm using the code for a google cloud function in typescript:
export const functionName = functions.https.onRequest(async (req, res)=>{
      const point = geo.point(40, -119);

      await admin.firestore().collection('myCollection').doc('myDoc')
      .update({'position': point.data});
      res.send(200);
});

The logs of Firebase give this error:
at GeoFirePoint.get [as geoPoint] (/srv/node_modules/geofirex/dist/index.cjs.js:1390:43)
    at GeoFirePoint.get [as data] (/srv/node_modules/geofirex/dist/index.cjs.js:1411:32)
    at exports.bgLocation.functions.https.onRequest (/srv/lib/index.js:590:101)
    at cloudFunction (/srv/node_modules/firebase-functions/lib/providers/https.js:49:9)
    at /worker/worker.js:783:7
    at /worker/worker.js:766:11
    at _combinedTickCallback (internal/process/next_tick.js:132:7)
    at process._tickDomainCallback (internal/process/next_tick.js:219:9)

What Am I doing wrong?
Thank you very much!


text:
Q: boost::geometry::difference providing custom point with attributes I'd like to use 2D points with attributes for the polygons.
The attributes should be assigned to any new points according to some kind of strategy.
Do you know if it is possible and how to do it?
Is there any doc describing how to do it?

A: Last time I looked at things it proved impossible. That's because the library does construct new points using the available (accessor) traits.
Similar/related questions:

*

*ID field intermittently lost in custom point class
In fact, let me dupe-vote that!


text:
Q: Mostrar los documentos donde el array tenga más de x elementos Tengo mi bd en MongoDB y estoy intentando trabajar en Java.
Mi problema es que tengo un campo que es un array y me gustaria conseguir mostrar los documetos los cuales este array tiene mas de 3 elementos. en mongo la consulta seria:
db.companies.find({products:{$exists: true}, $where: 'this.products.length>3'});

Intento pasarlo a JAVAJavapero no encuentro como utilizar el $where
Document results = new Document("products", new BasicDBObject("$where", "this.products.length>3"));
MongoCursor<?> cursor = collection.find(results).iterator();
try {
    while(cursor.hasNext()) {
        System.out.println(cursor.next().toString());
    }
} finally {
    cursor.close();
}

A: Una manera de hacerlo es con la clase com.mongodb.client.model.Filters.
MongoClient client = new MongoClient();
MongoDatabase db = client.getDatabase("miDatabase");
MongoCollection col = db.getCollection("miDatabase.companies");
MongoIterable iterator = col.find(
        Filters.and(
                Filters.exists("products"),
                Filters.where("this.products.length > 3")
        )
);
MongoCursor cursor = iterator.iterator();
while (cursor.hasNext()) {
    Document document = (Document) cursor.next();
    System.out.println(document);
}


text:
Q: Clojure XML Parsing I can not find any info on how to parse xml documents and access elements.
I have found two ways to parse the xml document
(clojure.zip/xml-zip (clojure.xml/parse file))

and
(parse-seq file)

but i can seem to find any info on how to process the resulting structure?
Source file's refers to zip-query.clj on how to query the result but that seems to missing too.

A: Suppose you have the following xml to parse in your file:
<high-node>
   <low-node>my text</low-node>
</high-node>

you load clojure.xml:
user=> (use 'clojure.xml)

when parsed, the xml will have the following structure:
{:tag :high-node, :attrs nil, :content [{:tag :low-node, :attrs nil, :content ["my text"]}]}

and then you can seq over the content of the file to get the content of the low-node:
user=> (for [x (xml-seq
              (parse (java.io.File. file)))
                 :when (= :low-node (:tag x))]
         (first (:content x)))

("my text")

Similarly, if you wanted to have access to the entire list of information on low-node, you would change the :when predicate to (= (:high-node (:tag x))):
user=> (for [x (xml-seq
              (parse (java.io.File. file)))
                 :when (= :high-node (:tag x))]
         (first (:content x)))

({:tag :low-node, :attrs nil, :content ["my text"]})

This works because the keywords can operate as functions. See Questions about lists and other stuff in Clojure and Data Structures: Keywords

A: The above answer works, but I find it a lot easier to use clojure.data.zip.xml (used to be clojure-contrib.zip-filter.xml prior to Clojure 1.3).
file:
myfile.xml:
<songs>
  <track id="t1"><name>Track one</name></track>
  <track id="t2"><name>Track two</name></track>
</songs>

code:
; Clojure 1.3
(ns example
  (:use [clojure.data.zip.xml :only (attr text xml->)]) ; dep: see below
  (:require [clojure.xml :as xml]
            [clojure.zip :as zip]))

(def xml (xml/parse "myfile.xml"))
(def zipped (zip/xml-zip xml))
(xml-> zipped :track :name text)       ; ("Track one" "Track two")
(xml-> zipped :track (attr :id))       ; ("t1" "t2")

Unfortunately, you need to pull in a dependency on data.zip to get this nice read/filter functionality.  It's worth the dependency :)  In lein it would be (as of 17-Aug-2013):
[org.clojure/data.zip "0.1.1"]

And as for docs for data.zip.xml ... I just look at the relatively small source file here to see what is possible.  Another good SO answer here, too.


text:
Q: parallelizing a task, how many threads? Say we have an embarrassingly parallel task, ants providing food for their queen for instance.
X = Amount of food needed
Y = Time it takes an ant to get a unit of food
Z = To get an ant to start foraging for food a single primary thread takes Z seconds.
The primary thread can spawn threads until the problem is fully solved but there is a threshold when creating new threads, diminishing returns take effect. To what percentage of progress into a task is it most efficient to stop creating new threads.
For a fixed X and Y value how many threads do I tell the primary thread to spawn?
Edit: operating environment is a nvidia gts250 gpu using CUDA over java wrapper

A: Do

*

*Set up some experiments.

*Run experiments, record results.

*Analyse results.

*Draw conclusions.

Until you have answered your question(s)
You write that your problem is embarrassingly parallel.  Such problems usually have an obvious 'dimension' along which they are EP.  For instance, rendering images in a movie is EP by frame (so send each frame to a separate process(or)) or by rendering sub-task (so set up a pipeline).  Rarely would you parallelise image rendering by chopping each image into sub-image tasks.  I guess that your problem is EP when decomposed along the dimension of 'ant'.  So, probably, you should create one task for each ant.  Then you should, probably, have no more ant tasks running at one time than you have available processors.  You might want fewer, less likely you may want more ants than processors.  But the best ratio of tasks to processors is something you have to figure out yourself.
Arguments about how threads should perform, what the o/s should do and how the hardware ought to cope are, occasionally, illuminating, but they are never a substitute for testing.
Incidentally, for foraging ants I suspect that fixing Y is a poor idea.
And if you want more pointed advice, you might want to show us a bit more of your technologies -- advice about threads appropriate for a Java program may well not apply if you are writing Fortran+OpenMP.

A: Just as a guess if we assume that each worker thread is CPU bound then it is not practical to create more threads than you have cores.


text:
Q: Veracode XSS on empty String value After Veracode scan passed. I have reported XSS problem with CWE ID 80 for XSS vulnerability in my jsp:
<%@ attribute name="styleId"%>
...
document.getElementById("${styleId}").value=""; (XSS here)

I can not understand what is the problem where? Do I have to escape empty string? Or styleId or Both?
Do I have to use EASPI.encodeForHTML ??

A: The problem here is that styleId can introduce XSS which to break the js.
So you have to escape the styleId with the rules for js.
SO I add in my custom tag library
in util.tag
<function>
        <name>escapeJavaScript</name>
        <function-class>org.apache.commons.lang.StringEscapeUtils</function-class>
        <function-signature>java.lang.String escapeJavaScript( java.lang.String )</function-signature>
    </function>

then
<%@ attribute name="styleId"%>
<%@ taglib prefix="util" uri="http://tags/util" %>
...
document.getElementById("${util:escapeJavaScript(styleId)").value="";

And the problem was fixed after next scan.


text:
Q: What's the JUnit 5 way for RunListeners In our environment we are using JUnit 4 TestListeners to report test results to a remote server.
What is the JUnit 5 way doing that?

A: You may use a TestExecutionListener:
http://junit.org/junit5/docs/current/user-guide/#launcher-api-listeners-custom

7.1.4. Plugging in Your Own Test Execution Listeners
In addition to the public Launcher API method for registering test execution listeners programmatically, custom TestExecutionListener implementations discovered at runtime via Java's java.util.ServiceLoader facility are automatically registered with the DefaultLauncher.

"JUnit 5", read the JUnit Platform, ships some example listeners. You can view their source here:
https://github.com/junit-team/junit5/tree/HEAD/junit-platform-launcher/src/main/java/org/junit/platform/launcher/listeners


text:
Q: MVC3 and Code First Migrations - "model backing the 'blah' context has changed since the database was created" I started off my project by using Entity Framework Code First. When I was ready I uploaded my database and code to my host provider. Everything worked.
I need to add a new field to one of my classes and I don't want to loose the data in the database. Thus, I tried following some blog posts about using Code First Migrations. I did the following:

*

*I backed up my remote (production) database.

*I attached this database locally

*I added the property to my class

*PM> Enable-Migrations

*PM> Add-Migration AddSortOrderToCar

*PM> Update-Database

*At this point I created a .bak file of the local database and then used that file to 'restore' to the remote one.

*Lastly, I published the code to the remote site.

When I visit the site I get the following error message:
The model backing the 'blahblah' context has changed since the database was created. Consider using Code First Migrations to update the database.
What am I doing wrong?

A: From my experience that suggests that migration table is out of sync (even if your data isn't), and that's been part of the db schema now (since 4.3 I think - under system tables).
There could be many reasons and ways to experience that error , but most of the time...
The problematic part is some combination of manually backing/restoring the full database with code changes alongside - I'm not entirely certain as to why always.
In short, even if Db-s are the same migration table data might not be - and hash comparison may fail (still full restore sounds like good enough - but you have 'two sides').

What works for me is to use
Update-Database -Script
That creates a script with a 'migration difference',
which you can manually apply as an SQL script on the target server database (and you should get the right migration table rows inserted etc.).
If that still doesn't work - you can still do two things...

*

*Remove the migration table (target - under system tables) - as per http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-automatic-migrations-walkthrough.aspx comments in there - that should fail back to previous behavior and if you're certain that your Db-s are the same - it's just going to 'trust you',

*As a last resort I used - make a Update-Database -Script of the full schema (e.g. by initializing an empty db which should force a 'full script'),
find the INSERT INTO [__MigrationHistory] records,
just run those, insert them into the database,
and make sure that your databases - and code match,
that should make things run in sync again.
(disclaimer: this is not a bullet proof to work at all times, you may need to try a few things given your local scenarios - but should get you in sync)

A: I think in step 6 you need to run Update-Database -Verbose
Also this link is very helpful for updating database in EF with Scaffolding
http://www.asp.net/mvc/overview/older-versions/hands-on-labs/aspnet-mvc-4-entity-framework-scaffolding-and-migrations


text:
Q: C - Macro contradiction I just started learning C and I am not sure about how everything works. Some of examples simply looks weird to me and I cannot predict what would it print. I am programming in GCC, I mean it is my compiler, so every code I test is in GCC.
I understood pointers etc how that all stuff work, but also as you know there are macros. Macros are very weird, and I discovered one example I have no explanation about. For example look at this code particular code:
#include <stdio.h>

int main(void){

  #define A 1

  if(A == 0){
    #define B 1
  }

  #ifdef B
    printf("B is defined, which means that A == 0.\n");
  #elif
    printf("B isn't defined, which means that A == 1.\n");
  #endif

  printf("Value of A is %d\n", A);

  return 0;
}

What should it print? Well, I though it is easy to guess, but now I see that it is not very easy. The result is not what i thought is.
This was my reasoning: we firstly define A to be 1 and then if A is 0 then define B to be 1. So, if B is defined it means that A == 0 and otherwise A == 1. But, surprisingly it prints:

B is defined, which means that A == 0.
  Value of A is 1

What? It just printed a contradiction. I am not sure if this is some weird thing in GCC (because I have no visual studio or other compiler to test it). However, I am 99% sure I somehow misunderstood macros. I tried using variables instead of macros and it works properly.
Is it an issue, or did I simply misunderstand how macros work? Please keep in mind that I'm C beginner, so take it easy :).
Thank you in advance.

A: Macros are part of the preprocessor before the code is actually compiled. The compiler will search the code for all preprocessor directives and modify the code accordingly. So when the compiler gets to if(A == 0) {#define B 1} it has already been expanded to if(0 == 1) { }.
Macros makes it easy to configure an aspect of your code or to replace magic numbers into meaningful defines. For example:
#define DO_HOUR_CALCULATION

#define NUMBER_OF_SECONDS_PER_MINUTE (60)
#define NUMBER_OF_SECONDS_PER_HOUR (NUMBER_OF_SECONDS_PER_MINUTE * 60)
...
#ifdef DO_HOUR_CALCULATION
int hours = time / NUMBER_OF_SECONDS_PER_HOUR;
int minutes = (time % NUMBER_OF_SECONDS_PER_HOUR) / NUMBER_OF_SECONDS_PER_MINUTE;
#endif // defined(DO_TIME_CALCULATION)

Another use is to simplify a repeated or configurable task:
#define DEBUG

#ifdef DEBUG
#define DPRINTF(fmt, args...) printf(fmt, ## args)
#else
#define DPRINTF(args...)   do {} while (0)
#endif
...
ret = read(fd, p_buffer, buf_size);
DPRINTF("read(fd) returned %d\n", ret);

Hope this helps you and happy coding!

A: Preprocessing directives are processed before non-preprocessing tokens are translated. And particularly, preprocessing directives are always evaluated at compile time, and never at runtime (cf. C standard, e.g. this draft).
If a token is a preprocessing token is defined as follows (all others are non-preprocessing tokens):

6.10 Preprocessing directives
(2) A preprocessing directive consists of a sequence of preprocessing
  tokens that begins with a # preprocessing token that (at the start of
  translation phase 4) is either the first character in the source file
  (optionally after white space containing no new-line characters) or
  that follows white space containing at least one new-line character

So if(A == 0) are non-preprocessing tokens (as the respective line does not start with a #, optionally with some space characters before), while #define B 1 is a preprocessing token.
According to the translation phases, preprocessing tokens are evaluated at translation time before the other tokens:

5.1.1.2 Translation phases
(4) Preprocessing directives are executed, macro invocations are
  expanded, and _Pragma unary operator expressions are executed.
(7) ... The resulting tokens are syntactically and semantically
  analyzed and translated as a translation unit.

So B will be defined already before if(A==0) will be translated, and particularly before if(A==0) will be executed. Thus, B will always be defined in your program.

A: The #define B 1 does not occur at run time.  It happens at compile time.  So #define B 1 is part of the compilation regardless of the result of A == 0, a run-time comparison
  if(A == 0){
    #define B 1
  }

The following code
  #ifdef B
    printf("B is defined, which means that A == 0.\n");
  #elif
    printf("B isn't defined, which means that A == 1.\n");
  #endif

is then the same as
  printf("B is defined, which means that A == 0.\n");


text:
Q: Entity Data Model, Dynamic Linq, multiple table dynamic Where clause, strongly typed return types When writing a method for an oData service I have the below linq, for which I need to have a dynamic "where" clause to filter the results (the "new"s in the joins are for composite PKs in the Entity Data Model):
var query = from pl in CurrentDataSource.ProductListing
             join pla in CurrentDataSource.ProductListingAttribute
                 on new {pl.ProductID, pl.WebCategoryID, pl.ParentProductID}
                 equals new {pla.ProductID, pla.WebCategoryID, pla.ParentProductID}
             join att in CurrentDataSource.Attribute
                 on pla.AttributeID
                 equals att.AttributeID
             join attItem in CurrentDataSource.AttributeItem
                 on pla.AttributeItemID
                 equals attItem.AttributeItemID
             select pl;

My Linq is not very good and I'm trying to use the DynamicQueryable class to generate a "where" clause at runtime (it's built from various variables):
var returnData = query.Where(whereClause);

Since the "where" clause filters on values in the Attribute and AttributeItem entities it invariably contains things like
"((Attribute.Value='foo' AND AttributeItem.Value='bar')
OR
(Attribute.Value='sna' AND AttributeItem.Value='fu'))"

which will fail at runtime since "No property or field 'Attribute' exists in type 'ProductListing'".
I have tried to build an anonymous type in the "select" which contains all elements of ProductListing entity and those from Attribute and AttributeItem which I require to filter by, but I need a strongly typed entity of type "ProductListing" to return from the method call.
Can ANYONE please help?? Should I be using dynamic Joins instead of dynamic Wheres? Is there a way of Where-ing against entities that you're not Selecting? Should I be selecting an anonymous type /"let" and building a strongly typed entity afterwards?
Please, any help is massively appreciated.
rposbo

A: The solution to my particular query was to do this:
            var query = from pl in CurrentDataSource.ProductListing
                             join pla in CurrentDataSource.ProductListingAttribute
                                 on new {pl.ProductID, pl.WebCategoryID, pl.ParentProductID}
                                 equals new {pla.ProductID, pla.WebCategoryID, pla.ParentProductID}
                             join att in CurrentDataSource.Attribute
                                 on pla.AttributeID
                                 equals att.AttributeID
                             join attItem in CurrentDataSource.AttributeItem
                                 on pla.AttributeItemID
                                 equals attItem.AttributeItemID
                        select new
                        {
                            ProductListing = pl,
                            att.AttributeName,
                            attItem.AttributeValue
                        };

            var returnData = query.Where(whereClause).Select(o => o.ProductListing);

i.e., select an anonymous type containing a concrete type, apply the where clause to that then select only the concrete type from the result.


text: Q: lsnrctl gices no errors nor any output though lsnr.ora file is correct I installed Oracle in my Ubuntu machine and though it got installed I cannot access the database. Though I have created the listener by running ./netca I cannot see any output when I run lsnrctl command. When I run ./netca, I can still see the previously created listeners. lsnrctl gives no ouput. Which means no errors nor any output. Please advice.


text:
Q: How to include variables with include_vars with the same name without overwriting previous I am having this let's call it include.yaml
#- name: "Playing with Ansible and Include files"
- hosts: localhost
  connection: local
  tasks:
    - find: paths="./" recurse=yes patterns="test.yaml"
      register: file_to_exclude
    - debug: var=file_to_exclude.stdout_lines
    - name: shell
      shell: "find \"$(pwd)\" -name 'test.yaml'"
      register: files_from_dirs
    - debug: var=files_from_dirs.stdout_lines
    - name: Include variable files
      include_vars: "{{ item }}"
      with_items:
        - "{{ files_from_dirs.stdout_lines }}"
    - debug: var=files

and 2 ore more test files
./dir1/test.yaml

that contains
files:
  - file1
  - file2

./dir2/test.yaml

that contains
files:
  - file3
  - file4

the result is
TASK [Include variable files] ******************************************************************************************
ok: [localhost] => (item=/mnt/c/Users/GFlorinescu/ansible_scripts/ansible/1st/test.yaml)
ok: [localhost] => (item=/mnt/c/Users/GFlorinescu/ansible_scripts/ansible/2nd/test.yaml)

TASK [debug] ***********************************************************************************************************
ok: [localhost] => {
    "files": [
        "file3",
        "file4"
    ]
}

How can I get all the values in files, at the moment the last included files variable from last file overrides the files from the previous files? Of course without changing the variables names in files test.yaml?
In other words I want files to be:
ok: [localhost] => {
    "files": [
        "file1",
        "file2",
        "file3",
        "file4"
    ]
}

To be more specific, I ask for any kind of solution or module, even not official or some github module, I don't want a specific include_vars module solution.

A: Put the included variables into the dictionaries with unique names. For example, create the names from the index of the loop. Then, iterate the names and concatenate the lists
    - command: "find {{ playbook_dir }} -name test.yaml"
      register: files_from_dirs

    - include_vars:
        file: "{{ item }}"
        name: "{{ name }}"
      loop: "{{ files_from_dirs.stdout_lines }}"
      loop_control:
        extended: true
      vars:
        name: "files_{{ ansible_loop.index }}"

    - set_fact:
        files: "{{ files|d([]) + lookup('vars', item).files }}"
      with_varnames: "files_[0-9]+"

    - debug:
        var: files

give
files:
  - file1
  - file2
  - file3
  - file4

Notes:

*

*You have to provide either a path relative to the home directory or an absolute path. See the example below

    - command: "echo $PWD"
      register: out
    - debug:
        var: out.stdout

give
out.stdout: /home/admin

For example, when you want to find the files relative to the directory of the playbook
    - command: "find {{ playbook_dir }} -name test.yaml"
      register: files_from_dirs
    - debug:
        var: files_from_dirs.stdout_lines

give
files_from_dirs.stdout_lines:
  - /export/scratch/tmp8/test-987/dir1/test.yaml
  - /export/scratch/tmp8/test-987/dir2/test.yaml

*

*The same is valid for the module find. For example,

    - find:
        paths: "{{ playbook_dir }}"
        recurse: true
        patterns: test.yaml
      register: files_from_dirs
    - debug:
        var: files_from_dirs.files|map(attribute='path')|list

give the same result
files_from_dirs.files|map(attribute='path')|list:
  - /export/scratch/tmp8/test-987/dir1/test.yaml
  - /export/scratch/tmp8/test-987/dir2/test.yaml

*

*Simplify the code and put the declaration of files into the vars. For example, the below declaration gives the same result

files: "{{ query('varnames', 'files_[0-9]+')|
           map('extract', hostvars.localhost, 'files')|
           flatten }}"

Example of a complete playbook for testing
- hosts: localhost

  vars:

    files: "{{ query('varnames', 'files_[0-9]+')|
               map('extract', hostvars.localhost, 'files')|
               flatten }}"

  tasks:

    - find:
        paths: "{{ playbook_dir }}"
        recurse: true
        patterns: test.yaml
      register: files_from_dirs

    - include_vars:
        file: "{{ item }}"
        name: "{{ name }}"
      loop: "{{ files_from_dirs.files|map(attribute='path')|list }}"
      loop_control:
        extended: true
      vars:
        name: "files_{{ ansible_loop.index }}"

    - debug:
        var: files

(maybe off-topic, see comments)
Q: "Is there a way to write the path where it was found?"
A: Yes, it is. See the self-explaining example below. Given the inventory
shell> cat hosts
host_1 file_1=alice
host_2 file_2=bob
host_3

the playbook
- hosts: host_1,host_2,host_3

  vars:

    file_1_list: "{{ hostvars|json_query('*.file_1') }}"
    file_2_list: "{{ hostvars|json_query('*.file_2') }}"
    file_1_dict: "{{ dict(hostvars|dict2items|
                          selectattr('value.file_1', 'defined')|
                          json_query('[].[key, value.file_1]')) }}"
    file_1_lis2: "{{ hostvars|dict2items|
                     selectattr('value.file_1', 'defined')|
                     json_query('[].{key: key, file_1: value.file_1}') }}"

  tasks:

    - debug:
        msg: |-
          file_1_list: {{ file_1_list }}
          file_2_list: {{ file_2_list }}
          file_1_dict:
            {{ file_1_dict|to_nice_yaml|indent(2) }}
          file_1_lis2:
            {{ file_1_lis2|to_nice_yaml|indent(2) }}
      run_once: true

gives
  msg: |-
    file_1_list: ['alice']
    file_2_list: ['bob']
    file_1_dict:
      host_1: alice

    file_1_lis2:
      -   file_1: alice
          key: host_1


text:
Q: Disable the Edit button on all the rows when Edit button is clicked on a particular row in GridView I have a gridView with 5 columns with Edit and Delete button on each row of GridView. Once an Edit button a particular row is clicked , I want to disable the edit and delete buttons on rest of the rows.
Below is my aspx
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" ShowFooter="True" EnableModelValidation="True"          onrowdatabound="GridView1_RowDataBound" onrowcommand="GridView1_RowCommand" onrowdeleting="GridView1_RowDeleting" EditRowStyle-ForeColor="Aqua"  onrowediting="GridView1_RowEditing" >

<asp:TemplateField HeaderText="Item#" >
<ItemTemplate>
<asp:Label ID="Item#" runat="server" Text='Label' ></asp:Label>
</ItemTemplate>
  </asp:TemplateField>

      ..........

  <asp:TemplateField >
<ItemTemplate>
<asp:Button ID="btnEdit" runat="server" CausesValidation ="false" Font-Size="Smaller" CommandName="Edit" Text="Edit" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>' Width="35px"/>
</ItemTemplate>
</asp:TemplateField>

<asp:TemplateField >
<ItemTemplate>
 <asp:Button ID="btnDelete" runat="server" CssClass="GridButton" CausesValidation="False" CommandName="Delete" Font-Size="Smaller" Text="Delete" CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>

   protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
    {
     if (e.CommandName == "Delete")
            {
                int x = Convert.ToInt32(e.CommandArgument.ToString());
                txtLineItemNumber.Text = (x + 1).ToString();
            }
            else
            {

               int x = Convert.ToInt32(e.CommandArgument.ToString());
               foreach (GridViewRow row in GridView1.Rows)
                {
                    if (row.RowIndex != x)
                    {
                        Button editButton = (Button)row.FindControl("btnEdit");
                        editButton.Enabled = false;
                        Button deleteButton = (Button)row.FindControl("btnDelete");
                        deleteButton.Enabled = false;
                    }
                    else
                    {
                        Button deleteButton = (Button)row.FindControl("btnDelete");
                        deleteButton.Text = "Cancel";
                        e.CommandName = "Cancel"; --- This is not possible...what should I do so that the Command Name is changed to Cancel and it does the cancel operation.
                    }

                }                 }
      }

Please help me to get it working.....

A: The approach you are taking will work fine. However the CommandArgument which is set in your markup CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>' is not a reference to the Button itsself but the index of the GridView row the Button resides in.
You will need to retrieve the index from the CommandArgument in the RowCommand event and then enable/disable all buttons on other rows like so:
void gridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    switch (e.CommandName.ToLower())
    {
        case "edit":
            {
                int rowIndex = Convert.ToInt32(e.CommandArgument);

                foreach (GridViewRow row in gridView1.Rows)
                {
                    if (row.RowIndex != rowIndex)
                    {
                        Button editButton = (Button)row.FindControl("btnEdit");
                        editButton.Enabled = false;
                        Button deleteButton = (Button)row.FindControl("btnDelete");
                        deleteButton.Enabled = false;
                    }
                }
            }break;
    }
}

Edit (based on comment)
Try moving the code that modifies the delete button to the RowEditing event handler like so:
void gridView1_RowEditing(object sender, GridViewEditEventArgs e)
{
    gridView1.EditIndex = e.NewEditIndex;

    DataBind();

    Button deleteButton = (Button)gridView1.Rows[e.NewEditIndex].FindControl("btnDelete");
    deleteButton.Text = "Cancel";
    deleteButton.CommandName = "Cancel";
}

void gridView1_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
{
    gridView1.EditIndex = -1;

    DataBind();
}

Hope this helps.

A: You could use javascript, outlined here, http://www.krissteele.net/blogdetails.aspx?id=92 . Add logic to not disable for the current row.


text:
Q: Hours and seconds are lost when storing a date in the database I'm storing a date (java.util.date) in an mysql database, before storage I have
Mon Feb 11 18:17:41 CET 2013

after storage just :
2013-02-11 00:00:00.0

The database field was declared this way :
`DATE_CREATION` date DEFAULT NULL,

and I'm using a  InnoDB engine
What can I do to avoid loosing the time?
thanks.

A: http://dev.mysql.com/doc/refman/5.1/en/datetime.html - change the data type in MySQl to DATETIME.

A: Use DATETIME data type instead of DATE for the column definition.


text:
Q: Dynamically create a object array in C# I need to add the parameters and the values to the following object dynamically. So far, I do it statically (hardcoded) by creating the object as follows:
object parameters = new { Param1 = UserNumber, Param2 = "201403", Param3 = true };

Then in the function, pass it as:
Helper.create(parameters);

^This works.
But, sometimes I just need to pass just one, none, or more than those three. The amount can change dynamically and not necessarily be named the same or it can be in a different order. So, I can't leave the name of the variables Param1, Param2 and Param3 statically. I also, don't control the behavior for the 'create()' function.
I tried this (and more):
List<Tuple<object, object>> tupleList = new List<Tuple<object, object>>();

tupleList.Add(new Tuple<object, object>("Number", UserNumber));
tupleList.Add(new Tuple<object, object>("Start", 201403));
tupleList.Add(new Tuple<object, object>("Show", true));

object tuptest = tupleList.Cast<object>().ToArray();

But it creates it as one array with objects inside.
When you go step by step in the debugging, they show up differently than what I need.
The Documentation example is:
Helper.create( new { Parameter1 = "Text", Parameter2 = 1000 } );

How can I create this dynamically?

A: Declare the method's signature using params object[] args, or a more specific type. This will allow you to pass any (or none) amount of parameters to the method, which you can then iterate inside the method.
E.g.:
public void Foo(params Tuple<object, object>[] args)
var a = new Tuple<object, object>("Number", UserNumber);
var b = tupleList.Add(new Tuple<object, object>("Start", 201403));
var c = tupleList.Add(new Tuple<object, object>("Show", true));

You'd then call it using Foo(a, b, c);

A: Why not creating a whole new specific type?
public class UserParameters {
     public UserNumber Number { get; set; }
     public string Start { get; set; }
     public bool Show { get; set; }
}

This way, you have compile-time errors if you mistype anything, and also compile-time type checking. You don't have to cast your generic object arguments to any type, which was very error-prone.
Also, you can dynamically add or remove properties, so in a way you are adding or removing parameters.
The create method can accept this object, and you would call it like this:
parent.create(new UserParameters() {
     Number = Session.UserNumber,
     Start = "201403",
     Show = true
});

Any property that is null is a parameter you didn't pass or defined.

A: You can create an ExpandoObject & pass it to create
var x = new ExpandoObject() as IDictionary<string, Object>;
            x.Add("Number", "UserNumber");
            x.Add("Start", 201403);
            x.Add("Show", true);
            Create(x);


text:
Q: Symfony - Neither the property "first_name" nor one of the methods exist and have public access in class "Symfony\Component\Form\FormView" I've been reading and finding a solution for this problem since hours now. But it seems that I can't really fix this error. I found out that only when I add the form in FOS/UserBundle/Form/Type/RegistrationFormType that's the only time where it shows in the twig. I think I'm having some problem calling for my UserBundle/Form/RegistrationFormType.
Badly need help on this one.
I'm using FOSUserBundle
Here's my User class:
<?php

namespace UserBundle\Entity;

use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Entity
 * @ORM\Table(name="fos_user")
 */
class User extends BaseUser
{
/**
 * @ORM\Id
 * @ORM\Column(type="integer")
 * @ORM\GeneratedValue(strategy="AUTO")
 */
protected $id;

/**
 * @ORM\Column(name="first_name", type="string", length=255, nullable=false)
 * @Assert\NotBlank(message="Please enter your first name", groups={"Registration", "Profile"})
 */
protected $firstName;

/**
 * @ORM\Column(name="middle_name", type="string", length=255, nullable=false)
 * @Assert\NotBlank(message="Please enter your middle name", groups={"Registration", "Profile"})
 */
protected $middleName;

/**
 * @ORM\Column(name="last_name", type="string", length=255, nullable=false)
 * @Assert\NotBlank(message="Please enter your last name", groups={"Registration", "Profile"})
 */
protected $lastName;

/**
 * @ORM\Column(name="position", type="string", length=255, nullable=false)
 * @Assert\NotBlank(message="Please enter your position/title", groups={"Registration", "Profile"})
 */
protected $position;

/**
 * @ORM\Column(name="gender", type="string", length=255, nullable=false)
 * @Assert\NotBlank(message="Please chose your gender", groups={"Registration", "Profile"})
 */
protected $gender;

/**
 * @ORM\Column(name="birth_date", type="string", nullable=true)
 */
protected $birthDate;

/**
 * @ORM\Column(name="address", type="string", length=255, nullable=true)
 */
protected $address;

/**
 * @ORM\Column(name="school", type="string", length=255, nullable=true)
 */
protected $school;

/**
 * @ORM\Column(name="hired_date", type="string", nullable=false)
 */
protected $hiredDate;

/**
 * @ORM\Column(name="end_date", type="string", nullable=false)
 */
protected $endDate;

// Change the targetEntity path if you want to create the group

/**
 * @ORM\ManyToMany(targetEntity="UserBundle\Entity\Group")
 * @ORM\JoinTable(name="fos_user_user_group",
 *      joinColumns={@ORM\JoinColumn(name="user_id", referencedColumnName="id")},
 *      inverseJoinColumns={@ORM\JoinColumn(name="group_id", referencedColumnName="id")}
 * )
 */
protected $groups;

public function __construct()
{
    parent::__construct();

}

/**
 * @return String
 */
public function getFirstName()
{
    return $this->firstName;
}

/**
 * @return String
 */
public function getMiddleName()
{
    return $this->middleName;
}

/**
 * @return String
 */
public function getLastName()
{
    return $this->lastName;
}

/**
 * @return String
 */
public function getPosition()
{
    return $this->position;
}

/**
 * @return String
 */
public function getGender()
{
    return $this->gender;
}

/**
 * @return String
 */
public function getBirthDate()
{
    return $this->birthDate;
}

/**
 * @return String
 */
public function getAddress()
{
    return $this->address;
}

/**
 * @return String
 */
public function getSchool()
{
    return $this->school;
}

/**
 * @return String
 */
public function getHiredDate()
{
    return $this->hiredDate;
}

/**
 * @return String
 */
public function getEndDate()
{
    return $this->endDate;
}

/**
 * @param String $firstName
 * @return User
 */
public function setFirstName($firstName)
{
    $this->firstName = $firstName;

    return $this;
}

/**
 * @param String $middleName
 * @return User
 */
public function setMiddleName($middleName)
{
    $this->middleName = $middleName;

    return $this;
}

/**
 * @param String $lastName
 * @return User
 */
public function setLastName($lastName)
{
    $this->lastName = $lastName;

    return $this;
}

/**
 * @param String $position
 * @return User
 */
public function setPosition($position)
{
    $this->position = $position;

    return $this;
}

/**
 * @param String $gender
 * @return User
 */
public function setGender($gender)
{
    $this->gender = $gender;

    return $this;
}

/**
 * @param String $birthDate
 * @return User
 */
public function setBirthDate($birthDate)
{
    $this->birthDate = $birthDate;

    return $this;
}

/**
 * @param String $address
 * @return User
 */
public function setAddress($address)
{
    $this->address = $address;

    return $this;
}

/**
 * @param String $school
 * @return User
 */
public function setSchool($school)
{
    $this->school = $school;

    return $this;
}

/**
 * @param String $hiredDate
 * @return User
 */
public function setHiredDate($hiredDate)
{
    $this->hiredDate = $hiredDate;

    return $this;
}

/**
 * @param String $endDate
 * @return User
 */
public function setEndDate($endDate)
{
    $this->endDate = $endDate;

    return $this;
}
}

Here's My RegistrationFormType:
<?php

namespace UserBundle\Form;

use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;

class RegistrationType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('firstName', 'text', array('label' => 'form.first_name', 'translation_domain' => 'FOSUserBundle'))
            ->add('middleName', 'text', array('label' => 'form.middle_name', 'translation_domain' => 'FOSUserBundle'))
            ->add('lastName', 'text', array('label' => 'form.last_name', 'translation_domain' => 'FOSUserBundle'))
            ->add('position', 'text', array('label' => 'form.position', 'translation_domain' => 'FOSUserBundle'))
            ->add('gender', 'text', array('label' => 'form.gender', 'translation_domain' => 'FOSUserBundle'))
            ->add('birthDate', 'date', array('label' => 'form.birth_Date', 'translation_domain' => 'FOSUserBundle'))
            ->add('address', 'text', array('label' => 'form.address', 'translation_domain' => 'FOSUserBundle'))
            ->add('school', 'text', array('label' => 'form.school', 'translation_domain' => 'FOSUserBundle'))
            ->add('hiredDate', 'date', array('label' => 'form.hired_date', 'translation_domain' => 'FOSUserBundle'))
            ->add('endDate', 'text', array('label' => 'form.end_date', 'translation_domain' => 'FOSUserBundle'))
        ;
    }

    public function getParent()
    {
        return 'fos_user_registration';
    }

    public function getName()
    {
        return 'user_registration';
    }
}

Here's my services.yml:
services:
    app.form.registration:
        class: UserBundle\Form\RegistrationFormType
        tags:
            - { name: form.type, alias: user_registration }

Here's my config.yml:
fos_user:
db_driver: orm
firewall_name: main
user_class: UserBundle\Entity\User
group:
    group_class: UserBundle\Entity\Group
profile:
    form:
        type: UserBundle\Form\ProfileFormType
registration:
    form:
        name: user_registration

Here's my twig: I wanna call all the other entities I made
{{ form_widget(form.first_name) }}
{{ form_widget(form.last_name) }}
{{ form_widget(form.middle_name) }}
// and so on...

A: call it like that : {{ form_widget(form.firstName) }}
In your form, it's firstName, not first_name. Same for lastname middlename ...


text:
Q: how to access input element in a polymer web-component I've managed to setup a simple registration form with Polymer:
<polymer-element name="app-registration">

    <template>

            <paper-input class="username" .... ></paper-input>
            <paper-input class="password" .... ></paper-input>
            <paper-button label="Submit" on-tap="{{handleSubmit}}"></paper-button>

    </template>

</polymer-element>

It works fine, however, within the handleSubmit callback I'm not able to query the values from the other input fields. Whatever I query paper-input or by classname I receive null. Any suggestion how to do this ?

A: Those elements are in your shadow dom, so you need this.shadowRoot. this.querySelector() will give you light dom nodes.
this.shadowRoot.querySelector('.username').value

Better yet, would be to add an id:

  <paper-input class="username" .... ></paper-input>
  ...

and use node finding: this.$.container.querySelector('.username').value.

A: Not sure if it was already available in 0.5, but in 1.0 you can do
this.$$(selector)

your example:
this.$$('.username').value

-> same but shorter, and works on dynamically created nodes
https://www.polymer-project.org/1.0/docs/devguide/local-dom.html#work-with-local-dom


text:
Q: Any Protection Required for Rechargeable Battery Powered Device? I created a device which is powered with 6 NiMH AA rechargeable batteries. The device uses between 10-100mA current. It is nothing special about it, there are some foil and electrolyte capacitors from + to - to stabilize the power of some chips and there is a microcontroller.
As I understand, the NiMH rechargeable batteries are sensitive for short-circuits. So I wonder if over time an element fails this could lead to a short-circuit.
It there any protection for the rechargeable batteries necessary for a such setup to protect the batteries? Or more precise: Is it usual to add some protection for the rechargeable batteries in battery powered devices?

A: Luckily, the NiMH batteries are relatively tolerant to abuse, compared to other battery chemistries.
Fuse in series with the battery.  If could be a non-resettable fuse, or it could be a resettable PTC fuse.  If the load (i.e. circuit powered by the battery) develops a short, it will draw excessive current from the battery, which in turn will cause the fuse to open and break the short circuit.
The type and rating of the fuse would depend on the design and operation of your circuit that consumes the battery power.
Check the peak current consumption of your device.  Electric motors, for example, can draw a large current for short time when they start-up under nominal conditions.  This is normal, and it shouldn't trip fuses.  But if there is a short through the motor, that has to trip the fuse.  One way to address this is to use a slow fuse, which opens only after a high current has been sustained for some time.


text:
Q: How to Force Focus Loss on a Textbox when a button is pushed I have a pretty large wpf aplication that is built using the prism framework and MVVM concepts and if a user types a change into a textbox and presses the accept button without leaving the textbox first it causes the button action to not receive the changed values in the textbox.  My viewmodel has the following button code
private DelegateCommand<string> _myButtonAction;
public ICommand MyButtonAction
{
   get
   {
      if (_myButtonAction== null)
      {
         _myButtonAction= DelegateCommand<string>.FromAsyncHandler(
                    MyFunction,
                    s => true);
      }

      return _myButtonAction;
   }
}

private Task MyFunction(string arg)
{
   // this event calls a button.focus in the view
   EventAggregator.GetEvent<FocusObject>().Publish("");
   // this doesn't work either
   Keyboard.ClearFocus();
   using (new WaitCursor("my function"))
   {
       // do some stuff
   }
   return Task.FromResult<object>(null);
}

Despite trying a Keyboard.ClearFocus() and using a message event to call a MyButton.Focus(); in the view nothing seems to trigger the Textbox to lose focus once I am in this method.  Does anyone else have any suggestions for how to force an update of a bunch of textboxes (lets say 100+) from a viewmodel?

A: The sources of data for the TextBoxes are not being told to update.
I see that you are concerned about using UpdateSourceTrigger=PropertyChanged for validation reasons. However, I believe that to be a great solution for this problem still. To keep the TextBoxes from forcing validation with every keystroke you could add a Delay to your binding.
For example:
<TextBlock Text="{Binding someProperty, UpdateSourceTrigger=PropertyChanged, Delay=100}" />


text:
Q: What is the most secure way to handle invalid input in a Zend application? I have an application where the user arrives at a page from a link containing an ID value (e.g.: /students/view/42). In my code, I use Zend_Filter_Input, like this:
$input = new Zend_Filter_Input(array(), array(
    'id' => new Zend_Validate_Db_RecordExists(array (
        'table' => 'Students',
        'field' => 'id'
     )
), $this->_request->getParams());
if (!$input->isValid()) {
    // ???
}

I don't think there's anything Earth-shattering going on up to this point. However, what I am unclear about is what to do if the value for the id is invalid.
In his book Zend Framework: A Beginner's Guide, Vikram Vaswani has the user throw an exception  (Zend_Controller_Action_Exception('Page Not Found', 404)). Is this the best way to go about handling this, and if not, what other options are available?

A: You should redirect user to your page with 404 error description (you should use ErrorController for Exception messages rendering) or to the specific page with the message that such student does not exist.
Just throw exception and render the error page in your ErrorController.
You can do like this:
 $this->getResponse()->setHttpResponseCode(404);

or
throw new Zend_Controller_Action_Exception('This page does not exist', 404);

The typical ErrorController class is the following:
class ErrorController extends Zend_Controller_Action
{
    public function errorAction()
    {
        $errors = $this->_getParam('error_handler');

        switch ($errors->type) {
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
                // 404 error -- controller or action not found
                $this->getResponse()
                     ->setRawHeader('HTTP/1.1 404 Not Found');

                // ... get some output to display...
                break;
            default:
                // application error; display error page, but don't
                // change status code
                break;
        }
    }
}


text:
Q: Does the phrase 'die in surprise' exist? In my country, when people surprised so much we speak:

I almost died in surprise.

When you get astonished so much, you feel a bit of pain in your heart. And you feel you might die from it.
But I don't get any google hit with the phrase 'die in surprise'.
I searched also 'die on surprise', 'die by surprise', and 'die from surprise'.
I don't get any google hit on the first page.
Do you use this expression? If not, what would be the closet thing to this phrase?

A: You got close, but the phrase in English uses "of".
Google search "die of surprise"
For example: "I might die of surprise..."


text:
Q: Is there any site which covers Chromium OS? Which site in the network covers development related questions about the Chromium OS?
I mean questions about the OS itself, like the internals, libraries and kernel level stuff.
Also, which site covers questions from users of the Chromium OS like getting around errors, web applications, mods, personalizations ?

A: There is no dedicated Chromium OS Stack Exchange.
In general, programming questions (including issues with programming tools) belong on Stack Overflow.
Questions regarding OS setup and hardware (in a professional capacity) can go to Server Fault.
Conceptual issues (whiteboard questions) go on Programmers Stack Exchange.
General usage questions would go to Super User.
Questions specific to web applications can go to Web Apps Stack Exchange.