text:
Q: Node-Red. Is it possible to install a node offline just with a copied node folder I have a node folder which was in node_modules directory copied from another device. Is it possible to install this folder into node-red offline in a new device?

A: This is how nodes are developed, updated and tested. See the section

Testing your node in Node-RED

in https://nodered.org/docs/creating-nodes/first-node

A: I have solution for install node-red in any of the system.
Here i have done this process in windows10 server os
Just copy your installed node-red directory and paste it to same directory in other system(without internet enable system).
Step 1:
First copy node.js installer in your (internet disable system) and installed it.
Step 2:
After successful installation of node.js with npm copy npm folder from below given directory
C:\Users\p\AppData\Roaming\npm
Step 3:
Paste this folder in same directory in non-internet system(may be path different).
And Now setup completed
Open your CMD and type happily node-red and Boooooooom.
https://discourse.nodered.org/u/parth_thaker/activity


text:
Q: MySQL Procedure (help) I have several tables in my database such as
comments
status
events
I'm trying to create an SQL query procedure which  counts data from these different tables based on the userID entered and then sum up the counts to create a unique valued. This is what i've tried so far but i'm having problems with the syntax. Where am I going wrong??
SELECT COUNT(user_id) AS comments FROM comment
WHERE user_id= userID
UNION ALL
SELECT COUNT(creator_id) AS events FROM event
WHERE creator_id=userID;

A: In a union, the fields are combined based on order.  So giving the count field a different name in each part of the union does not make two fields.  It becomes the same field in the end. To differentiate which value came from which table, add a hardcoded string literal like so:
SELECT COUNT(user_id) AS rows, 'comment' as tablename FROM comment
WHERE user_id= userID
UNION ALL
SELECT COUNT(creator_id) AS rows, 'event' as tablename FROM event
WHERE creator_id=userID;

redpajama_set_name: RedPajamaStackExchange


text:
Q: JavaFX8 How to set a label's ellipsis from the left-side not from the right-side? JavaFX 8 can auto ellipsisize Label's text started at the right side. For example, if there is a sentence 'Answer your own question', it may be ellipsisized to 'Answer your own que...' because there is no enough space to show the sentence completely.
But now, I want to ellipsize the left-side text, not the right-side. For example, if there is a sentence 'Answer your own question', I want to make it ellipsized to '...our own question'.
On Android, it can be easily implemented by setting the TextView's ellipsize attribute in a XML file, but on JavaFX, I have no idea to do that.

A: Use
label.setTextOverrun(OverrunStyle.LEADING_ELLIPSIS);

or
label.setTextOverrun(OverrunStyle.LEADING_WORD_ELLIPSIS);

depending on the exact behavior you want. (Documentation is here.)
You can also do this in FXML:
<Label text="Answer your own question" textOverrun="LEADING_ELLIPSIS"/>

or even in css:
.label {
    -fx-text-overrun: leading-ellipsis ;
}

(The latter will set the text overrun for all labels; you can use an id as the selector if you want to apply it to just one label.)


text:
Q: При нажатии на кнопку, вывод названия этой кнопки и определенного текста Нужно чтобы при выборе определенного набора radio выводился нужный текст
Пример:

    <input type="radio" data-id="1" name="group_1"></input>Радио 1

    <input type="radio" data-id="2" name="group_1"></input>Радио 2

    <input type="radio" data-id="3" name="group_2"></input>Радио 3

    <input type="radio" data-id="4" name="group_2"></input>Радио 4

<button id="click_me">Click ME</button>

Результат должен иметь такой вид:

*

*Название кнопки из 1-й группы: Название кнопки

*Название кнопки из 2-й группы: Название кнопки

*Название кнопки из n-ой группы: Название кнопки

*Определенный текст, который зависит от выбранных радио.

Желательно чтобы текст перед радио, и текст который получается при выборе кнопок, был в формате html - кода. Также это нужно сделать для любого количества радиокнопок

A:

let textObj = {
  '13': 'Text 13',
  '23': 'Text 23',
  '14': 'Text 14',
  '24': 'Text 24',
};
let textRadioObj = {
  'group_0': 'Aloha 1',
  'group_1': 'Aloha 2',
};

$('#click_me').click(function() {
  let textName = '';
  $('input[type=radio]').each(function() {
    if ($(this).prop("checked")) {
      textName += $(this).data("id");
      let name = $(this).prop("name");
      $('#text_' + name).html(textRadioObj[name] + ': ' + $(this).parent().text());
    }
  });
  if (textObj[textName]) {
    $('#text').html(textObj[textName]);
  }
});

    <input type="radio" data-id="1" name="group_0"></input>Радио 1

    <input type="radio" data-id="2" name="group_0"></input>Радио 2

    <input type="radio" data-id="3" name="group_1"></input>Радио 3

    <input type="radio" data-id="4" name="group_1"></input>Радио 4

<button id="click_me">Click ME</button>

Получается, что расширяя html и расширяя эти 2 объекта (textObj, textRadioObj) вы можете сделать для n radiobutton груп


text:
Q: Insert Item at index in sorted array I want to insert an item at an index in a sorted array. Should I be using binary search or is the below implementation good?
This below implementation does not work but the concept is clear. For some reason it gives me an error: "Value 'Double' has no member 0" but when I get rid of the && $1.0 > price it runs but doesn't do what I want. How would I insert a value in an array between two values using the method below or any better method?
It would be an added bonus if I could update the second (quantity) value if price was already there in the array. For example if in the original array the value is (20,5) where price is 20, I would want to update that index to be (20,9).
The array is an array of Doubles that represent a price and a quantity for that price. I cannot use a dict because it needs to remain in order.
I will have more than 10K items in the array.
Here is my code.
let largeArray = [(10, 3), (20, 5), (30, 6), (40, 1), (50, 3), (60, 3)]
let price = 45
if let indexInsert = largeArray.index(where: {$0.0 < price && $1.0 > price}) {
     self.sellSideOrderBook.insert(((45, 2)), at: indexInsert)
}


text:
Q: laravel 5.2 e-mail not delivered no exception I'm trying to reset a password in laravel 5.2 (upgraded from 5.2) and sending a password token to my mail (using laravels 5.2 new make:auth).

*

*Set mail driver to log

*Go to: http://localhost/public/password/reset

*Fill in e-mail address and click "send password reset link"

*The e-mail is stored in the log file

*Change mail driver to smtp

*Run php artisan config:cache

*Do action 2 and 3 again

*No error / exception is shown

*Message of laravel is "We have e-mailed your password reset link!"

My .env file
APP_ENV=local
APP_DEBUG=true
APP_KEY=xxxxxxxxxxxxxxxxxxxxxxxxx

DB_HOST=localhost
DB_DATABASE=xxxxxxxxxx
DB_USERNAME=root
DB_PASSWORD=

CACHE_DRIVER=file
SESSION_DRIVER=file
QUEUE_DRIVER=sync

MAIL_DRIVER=smtp
MAIL_HOST=xxxx.xxxxxx.xx
MAIL_PORT=25
MAIL_USERNAME=xxxx@xxxxxx.xx
MAIL_PASSWORD=xxxxxxxxxxxxx
MAIL_ENCRYPTION=tls

I configured in mail.php this line
 'from' => ['address' => 'xxx@xxx.com', 'name' => 'xxx'],

At first it gave exceptions since i did not use the right credentials / settings. That error is gone.
a) How can i check if the mail is sent?
b) How can i check why it's not delivered?
c) What am i doing wrong?

A: I am not sure what the exact problem is, but i will give you my working code (also using 5.2), and then you can check if there is something different between our codes:
.env
MAIL_DRIVER=smtp
MAIL_HOST=asmtp.unoeuro.com
MAIL_PORT=587
MAIL_USERNAME=hello@google.com
MAIL_PASSWORD=********
MAIL_ENCRYPTION=tls

Be sure that your mail server is using TLS, or disable this. They'll usually tell if they accept tls encryption.
mail.php
'driver' => env('MAIL_DRIVER', 'smtp'),
'host' => env('MAIL_HOST', 'asmtp.unoeuro.com'),
'port' => env('MAIL_PORT', 587),
'from' => ['address' => "hello@google.com", 'name' => "Hello World"],
'encryption' => env('MAIL_ENCRYPTION', 'tls'),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),

Setup a view with a controller and hardcode this in the controller, so that when you visit the view, the following code will run:
(Remember to assign $thename and $theemail or hardcode them
use Mail;

$mailvar = ['name' => $thename, 'email' => $theemail];

Mail::send('Mailtemplate.view', ['mailvar' => $mailvar], function ($message) use ($mailvar) {

        $message->from('noreply@google.com', 'google.com');
        $message->to($mailvar['email'], $mailvar['name'])->subject('You recieved a message');

    });

Remember to create the view Mailtemplate.view where the mail should be shown. You can use $name and $email in the view as variables.
Your mailtemplate should look something like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>

<head>
    <style type="text/css" media="screen">';

    </style>
</head>

<body>
Name: {{ $mailvar['name'] }}
Email: {{ $mailvar['email'] }}
</body>
</html>


text:
Q: How to add typescript types to a selected slice of AppState in Angular's NGRX library? I'm trying to type out my AppState(first time).
My app state only has one store.select('sunDial') which is an Object that
I'm really lost on how to properly add types when you select a slice from AppState.
Question: How can I properly add types to this simple example of a component and AppState.
I have a component:
import { Component, ChangeDetectionStrategy, OnInit } from '@angular/core';
import { Store } from '@ngrx/store';
import { AppState, SunDial } from '../app.interface';
import { Observable } from 'rxjs';

@Component({
  selector: 'sun-dial',
  templateUrl: 'sun-dial.component.html',
  styleUrls: ['sun-dial.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class SunDialComponent implements OnInit {
  private partOfDay: Observable<SunDial>; // is this an Observable??
  public activeInputField: SunDial; // Is this really referencing as a number?

  constructor(private store: Store<AppState>) { // I see this everywhere

    this.partOfDay = store.select<SunDial>('sunDial'); // select sunDial:SunDial?
  }
  ngOnInit() {
    this.partOfDay.subscribe(x => {
      this.activeInputField = x;
    });
  }
}

And my AppState.ts
export interface AppState {
  sunDial: SunDial; // store.select('sunDial') create an object/observable?
}

export interface SunDial { // Is this really an Observable?
  activeInputField: number
}

Nothing in my WebStorm IDE is throwing errors but I really don't know how to reason about the types (basically just guessing).  Could anyone help me understand how to completely annotate the types for my class SunDialComponent{}
Ref:
what is store.select in ngrx

A: If you take a look to the select interface :
export interface SelectSignature<T> {
  <R>(...paths: string[]): Observable<R>;
  <R>(mapFn: (state: T) => R): Observable<R>;
}

You'll notice that you can either pass a string or a function.
So instead of passing a string to the select method, pass a function like that :
this.store.select(state => state.sunDial);

You'll notice that your IDE will understand that the result of this line will be of type Observable<SunDial>.


text:
Q: C++ Message Processing Design Discussion I have recently coded up a multithreaded program that essentially handles two types of messages. The first is received and just pushed back in a list. Lets call this Msg_1. The second is does the same thing as Msg_1 and we shall call this Msg_2. The program is needs to monitor Msg_2 (which is received on the same network connection as Msg_1: i.e. same port/ip.) such that when it receives a valid Msg_2 it needs to look through all Msg_1's and find a match.
Right now I have the receive and pushing onto my two lists handled by one thread and the searching handled by another thread. There are pitfalls that I see in the code but it works (for now...). I had a few questions for the general community on best practices since I am also learning as I go along with this project...
First off - if I use a list and always pushback on the Msg_2 list but pop off the front will I run into an issue with how my lists are kept? I.e. If thread 1 is pushing while thread 2 is popping Msg_2 will there be an issue? Should I be locking this or at least storing what I am searching for then quickly popping as to let thread 1 be able to push if needed?
Secondly, I am getting major heartburn for how Msg_1 is handled... I push it back onto my list. When I get Msg_2 in I initialize an iterator to look through my list of Msg_1 until I either reach the end or find a match - again not with mutex's. Is there a better way to do this such that I do not have a lock for the entire duration of the search on the whole list? (The process is trying to match 2 integer fields.)
Any insight would be helpful as again I want to learn best practices for this type of solution.
I should also mention that I am limited to C++-03 and do not have access to boost. So there are some fancy things that I cannot do...


text:
Q: How do I import one class out of a file with many classes in Python? I'm confused with the syntaxes:
import module.package
from module import package

Does the from reference another folder or should I use it for one class out of many in the same file?

A: A package is any directory that contains a file in the uppermost level named __init__.py. A module is any Python file with a .py extension.
From those definitions, you can probably figure out that modules can't contain packages. It's the other way around; Packages contain modules. The only thing modules can contain is names which bind to Python objects (classes, functions, etc.)
When you import a package, you simply execute the __init__.py file. When you import a module, you simply execute the module file itself. When you import a module from a package using something like from package import module or import package.module, you execute both __init__.py from the package, and the module file itself.
To import only a class from a module, you must use the from X import Y statement, where X is [package1.[subpackage2.]]modulename and Y is the name binded to the object you're importing to the names. Note that even when you do this kind of import, __init__.py and the whole module script will still get executed. The only difference is what gets added to your namespace, which is just the object pointed to by Y.
Note that the from X import Y statement is kind of weird. Because if X refers to a package, then Y can refer to a module within the package. To overcome this confusion, it's best to think of packages and modules as being namespaces. The biggest difference is that packages are namespaces for modules and modules are namespaces for concrete Python objects.
It's good to note that you can import multiple names from one namespace using commas:
from collections import OrderedDict, Counter
And additionally, you can import all names from a namespace:
from itertools import *
However, this is not recommended because it needlessly pollutes the namespace. For the Python standard library, it's mostly okay, since you're unlikely to have name collisions with things like takewhile, but if you are working on a larger project with multiple libraries, it's good to keep your namespace as clean as possible to avoid collisions.


text:
Q: Arduino DualShock 4 C++ I'm trying to control an Arduino uno board using a DualShock 4(PS4). I'm having difficulty programming the joysticks PS4.getAnalogHat(LeftHatY) I want to control a motor using the joystick; I want the motor to go forward when I press up(++i), backward when I press down(--i), and no speed when I don't move the joystick. I'm able to move the motor in one direction and the speed increases but I can't get the other direction to work. I can't seem make a connection between the joystick values (PS4.getAnalogHat(LeftHatY) > 137 || PS4.getAnalogHat(LeftHatY) < 117) and the motor values (0 - 255).
I'm using a USB Shield and a Motor Shield.
I need help figuring out the first if statement.
Here's the code I have so far:
if (PS4.connected())
{
    if (PS4.getAnalogHat(LeftHatY) > 137)
    {
        M3->setSpeed(255));
        PS4.setLed(Green);
        PS4.setLedFlash(100 ,100);
    }
}

I want the value for M3 to increase as I increase joystick angle:
for (int i=0; i<=255; ++i)
    M3->setSpeed(i);

A: You need to add the condition of min(117) and max(137) tolerance to move motor. And then, map the posibles values of joystick to the range of motor's speed
if (PS4.connected())
{
    int analogValue = PS4.getAnalogHat(LeftHatY);
    if (analogValue  > 137 || analogValue < 117)
    {
        int motorValue = y = map(x, 117, 137 , 0, 255);
        M3->setSpeed(motorValue);
        PS4.setLed(Green);
        PS4.setLedFlash(100 ,100);
    }
}

It could be better with some error handling but you could start with it.

A:  uint16_t s = PS4.getAnalogHat(RightHatY);

if (PS4.getAnalogHat(RightHatY) < 117 )
{
 s = map (s, 117,  0, 0, 250);
 M3->run(FORWARD);
 M3->setSpeed(s);
 PS4.setLed(Green);
 PS4.setLedFlash(100, 100);
}

if (PS4.getAnalogHat(RightHatY) > 137)
{
 s = map (s, 137, 0, 0, -250);
 M3->run(BACKWARD);
 M3->setSpeed(s);
 PS4.setLed(Green);
 PS4.setLedFlash(100, 100);
}

This is the solution to the problem I originally asked. Variable speed control of a motor using a Dualshock 4 & Arduino Motor shield. Thanks a lot for the help. I was 3d Printing parts for the robot/chassis which is why I took time off programming.


text:
Q: Should I transform this char number to decimal and after that to binary or? Write a program that will input a  number on 8 bits of type char from the keyboard (-128  to  127). Convert  this  number  to binary  using a  helper  function get_bit that will take as input parameters the bit number to be tested and the initial number. The function will return 0 or 1 according to the bit tested. Create  an  array  of  8  values such  that  each  value  is  the  result  of get_bit for its corresponding index. Then display the values of the array.
I tried altoi and sscanf but my code shoud take a number that i type in and for whatever reason it seemes that is not working.
`
int main(void)
{ char *num;
int tr_num;
 uart_init(); // open the communication to the microcontroller
 io_redirect(); // redirect input and output to the communication
 printf("Type a number:");
 scanf("%c",&num);
 int val =atoi(num);
 printf("%d",val);

`


text:
Q: The Valar and their power to create In The Silmarillion it is said that only Eru possesses the Flame Imperishable, and thus only he can create life. For example, when Aulë tries to create the dwarves, these result in a kind of marionettes without life of their own. It's only when Eru intervenes, when dwarves are given a true life.
But then it's also said that forces of evil (particularly Morgoth) are sterile and can't create, but only mock and corrupt others' creations. I don't remember if something about this is said in the actual book, but at least is said in some of Tolkien's late essays (if someone could point to some passage in the book, it would be greatly appreciated).
Then, if this is so, what's the difference between Morgoth and the other Valar? The Valar can create things like mountains, just as Morgoth, but they can't create life either. Wouldn't they be "sterile" as well?

A: The Valar can create things like mountains and plants, because these things are not true life. Life here means sentience. Aulë tried and failed to create Life. Only Eru gave the dwarves sentience. Just like Morgoth can only make a mockery of Elves, Men, and Ents.
I will edit this when I find quotes from the appendix or Silmarillion.

A: Tolkien was specific about distinguishing 'creation' from 'sub-creation'.  Only Iluvatar could 'create'.  Everyone else was doing only sub-creation, and this act has a couple of related moral perils;

*

*Thinking that you are as as powerful as God, and that you are doing the same kind of thing that God does

*Thinking that your creations belong to you, because you created them, which leads to hoarding, and other anti-social behavior.

Remember the Telari making jewels and strewing them all along the beaches of Valinor?  That's good sub-creation.  Making the Silmarils and locking them away, and refusing to donate them to the common good is Feanor's huge moral mistake.
From a letter of Tolkien, 1951

[The sub-creative desire] has various opportunities of 'Fall'.  It may
  become possessive, clinging to the things made as its own, the
  sub-creator wishes to be the Lord and God of his private creation.  He
  will rebel against the laws of the Creator...both of these (alone or
  together) will lead to the desire for Power...and so to the Machine
  (or Magic)...The Enemy in successive forms is always 'naturally' concerned with sheer Domination, and so the Lord of magic and machines; but the problem; that this frightful evil can and does arise from an apparently good root, the desire to  benefit the world and others--speedily and according to the benefactors own plans- is a recurrent motive.

As for the Valar, Tolkien writes:

[The Valar] are as we should say angelic powers, whose function is to
  exercise delegated authority in their spheres (of rule and government,
  not creation, making, or re-making)

A: It appears as if certain Valar can shape (as Aulë did with dwarves and Yavanna with ents) or reshape (as Melkor/Morgoth did when transforming elves into orcs and ents into trolls) the corporeal forms of living beings.
This power alone is probably akin to shaping non-living things like mountains, by the way.
However, supplying living beings with actual sentience (which would have to be included in true creation of life) required the Flame Imperishable, which resided within Eru Ilúvatar himself, and was hence out of reach for any Vala, although Melkor sought the void for it, for a time.

A: The Valar could endue things with life, but not independent minds. They could also shape new things out of erma (prime matter) that Eru had created.

The Valar had power to endue things that they designed with corporeal life; but they could not make things with independent minds or spirits: sc. they could not make things of equal order, but only ones of lower order. In ultimate truth they did not in fact "make" even corporeal life, which proceeded from Eru. But they had assisted in the general design of Eä, and severally, in different degrees and modes, in the production from the erma (or prime substance) of things of many kinds. The idea of life and growth came from Eru, but the Valar, under Him, devised the shapes and forms of living things. When Eru gave being to this design, in general and particular, and it became Eä, unfolding in Time, He set in motion life and growth, or those processes which would in time lead to this. But when he permitted the Valar to descend into Time, to carry out in Eä (or reality) the things that they had designed in thought, then viewed in Time they appeared to make things which were alive. Indeed it is held that being themselves in Time they experienced the making as a new thing, differing in this experience little, save in degree of power
and art, from the makers or artists among the Incarnate. Neither they nor the Incarnate could make things utterly new; they could not "create" after the manner of Eru, but could only make things out of what already existed, the erma, or its later variations and combinations.
The Nature of Middle-earth - "The Powers of the Valar"

As far as the difference between Morgoth and the the other Valar, it seems that due to Morgoth's various flaws, everything he made would feel like an imperfect imitation of other things, and would be completely tied to his will.

It is said that of the Valar Manwë had the greatest knowledge, so that no lore or arts of any of the others were to him a mystery; but that he had less desire to make things of his own, great or small; and under the cares of the Kingship of Arda the desire ceased, for his mind and heart were given rather to healing and restoration. The harms and evils of Melcor were to him the greatest grief, and he ever sought to redress them or turn them to good.
Melcor on the other hand desired even with passion to make things of his own, being restless and unsatisfied with all that he did, were it lawful or unlawful. Within Eä he had small love for anything that had been, desiring always new things and strange. He would ever be altering what he had made, and would meddle with the works of the other Valar, changing them, if he could, or destroying them in wrath if he could not. Though his mind was swift and piercing, so that, if he would, he might have surpassed all his brethren in knowledge and understanding of Eä and all that is therein, he was impatient and overweening (believing his powers of mind greater than they were). Too quickly he assumed that he had grasped all the nature of a thing, or all the causes of an event; and his plans and works often went amiss for that reason. But he learned no wisdom from this, and charged his failures ever upon the malice of the Valar, or the jealousy of Eru.
Since he had no love even for the things that he had himself made, he came at length to reck not at all how things had come into being, considering neither their natures nor their purposes. Thus he desired only to possess things, to dominate them, denying to all minds any freedom outside his own will, and to other creatures any value save as they served his own plans. Thus it was seen in Arda that the things made or designed by Melcor were never "new" (though at first he strove to make them so) but were imitations or mockeries of works of others.
The Nature of Middle-earth - "The Powers of the Valar"


text:
Q: Issue with setting image UILabel swift - found nil while unwrapping optional Code currently looks like this:
    lazy var placeLabel: UILabel = {
        let label = UILabel()
        label.backgroundColor = UIColor(patternImage: UIImage(named: "placelabel")!)
        label.translatesAutoresizingMaskIntoConstraints = false

        return label
    }()

I'm not sure why but when I input label.backgroundColor() the program can't run and breaks on that line.
"fatal error: unexpectedly found nil while unwrapping an Optional value"
When I remove it and continue with my setup it seems to run fine. I've seen other comments on issues like this saying that the view isn't setup when the command is called but I'm pretty much doing the exact same thing with my buttons and whatnot and it's all working fine.
Any idea why this is happening?
Thanks

A: In this line, UIColor(patternImage: UIImage(named: "placelabel")!), you are forcing the unwrapping of the UIImage object using the !.  If no image named "placelabel" exists in your project, the app will crash, as you are trying to unwrap nil.

A: make sure you are using the correct asset name and spelling, and that the file actually exists on disk where its expected to be.


text:
Q: How can I correctly register event handlers for jQuery UI Autocomplete (Combobox) for Ajax submission? I am trying to get an autocomplete working and making an Ajax form submission on change, and so far the first is working but not the second. I am using jQuery UI Autocomplete with Combobox, http://jqueryui.com/demos/autocomplete/#combobox. From my Django template, I define a handler, presently beginning with an alert that seems never to have been triggered:
function update_autocomplete(event, ui)
    {
    alert("Reached update_autocomplete");
    var split_value = ui.item.value.split(".");
    var field = split_value[0];
    var id = split_value[1];
    $.ajax({
        data:
            {
            id: "Entity_" + field + "_" + {{ entity.id }},
            value: id,
            },
        url: "/ajax/save",
        });
    }

And later on:
$(function()
    {
    $("#department").combobox();
    $("#reports_to").combobox();
    $("#department").bind("autocompletechange",
        update_autocomplete);
    $("#department").bind("autocompleteselect",
        update_autocomplete);
    $("#reports_to").bind("autocompletechange",
        update_autocomplete);
    $("#reports_to").bind("autocompleteselect",
        update_autocomplete);
    });

In the webpage rendered, the UI seems show the desired behavior apart from triggering the save-related event. Neither Chrome nor Firefox report errors. And the alert provisionally put in seems not to have triggered even once.
Am I approaching this problem in the right way? If I have the wrong approach, what is the correct approach to make a jQuery UI autocomplete that will save on an entry being chosen?
Thanks,
--edit--
I've replaced the second snippet with:
$(function()
    {
    $(".autocomplete").combobox();
    $(".autocomplete").autocomplete({select: update_autocomplete});
    $(".autocomplete").bind({"autocompleteselect": update_autocomplete});
    $(".autocomplete").bind({"autocompletechange": update_autocomplete});
    });

The behavior seems to be unchanged.

A: This works for me:
I set the event handler in the original autocomplete method call. I'm assuming that #department is the autocompleted input.
$("#department").autocomplete({
    source: my_source,
    select: function(event, ui) {
        update_autocomplete(event, ui);
    }
});

Hope this helps.

A: might just be your sample you provided but looks like your JSON is illegal.
>   $.ajax({
>         data:
>             {
>             id: "Entity_" + field + "_" + {{ entity.id }},
>             value: id,
>             },
>         url: "/ajax/save",
>         });

remove the extra comas
  $.ajax({
        data:
            {
            id: "Entity_" + field + "_" + {{ entity.id }},
            value: id
            },
        url: "/ajax/save"
        });


text:
Q: Move file without using renameTo() In my Java program, I would like to display the progress of moving a file. I use the following snippet of code to copy files, which allows me to track the bytes copied and shows it in a progress bar. I was wondering if the code code be adapted to move files rather than just copy them?
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(sourceFile));
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(targetFile));

            int theByte;

            while((theByte = bis.read()) != -1)
            {
                bos.write(theByte);

            }

            bis.close();
            bos.close();

A: Okay, so a "move" operation is a copy with a "delete" at the end, for example...
BufferedInputStream bis = null;
BufferedOutputStream bos = null;

try {
    bis = new BufferedInputStream(new FileInputStream(sourceFile));
    bos = new BufferedOutputStream(new FileOutputStream(targetFile));

    int theByte;

    while((theByte = bis.read()) != -1)
    {
        bos.write(theByte);
    }

    bos.close();
    bis.close();
    // You may want to verify that the file's are the same (ie the file size for example)
    if (!sourceFile.delete()) {
        throw new IOException("Failed to remove source file " + sourceFile);
    }

} catch (IOException exp) {
    exp.printStackTrace();
} finally {
    try {
        bis.close();
    } catch (Exception exp) {
    }
    try {
        bos.close();
    } catch (Exception exp) {
    }
}


text:
Q: avoiding MySQL injections with the Zend_Db class I currently use Zend_Db to manage my queries.
I've written already code that preforms queries like the one below:
$handle->select()->from('user_id')
                   ->where('first_name=?', $id)
                   ->where('last_name=?', $lname)

I've done this without sanitizing the input, assuming Zend_Db will. Does Zend do this?
Another question:
Does Zend_Db sanitize insert('table', $data) and update queries?
Thanks.

A: Yes. See http://framework.zend.com/manual/en/zend.db.select.html .  Don't worry.  You're right to be skeptical.

A: I wrote a lot of the code for database parameters and quoting in Zend Framework while I was the team lead for the project (up to version 1.0).
I tried to encourage best practices where possible, but I had to strike a balance with ease of use.
Note that you can always examine the string value of a Zend_Db_Select object, to see how it has decided to do quoting.
print $select; // invokes __toString() method

Also you can use the Zend_Db_Profiler to inspect the SQL that is run on your behalf by Zend_Db.
$db->getProfiler()->setEnabled(true);
$db->update( ... );
print $db->getProfiler()->getLastQueryProfile()->getQuery();
print_r $db->getProfiler()->getLastQueryProfile()->getQueryParams();
$db->getProfiler()->setEnabled(false);

Here are some answers to your specific questions:

*

*Zend_Db_Select::where('last_name=?', $lname)
Values are quoted appropriately.  Although the "?" looks like a parameter placeholder, in this method the argument is actually quoted appropriately and interpolated.  So it's not a true query parameter.  In fact, the following two statements produce exactly the same query as the above usage:
$select->where( $db->quoteInto('last_name=?', $lname) );
$select->where( 'last_name=' . $db->quote($lname) );

However, if you pass a parameter that is an object of type Zend_Db_Expr, then it's not quoted.  You're responsible for SQL injection risks, because it's interpolated verbatim, to support expression values:
$select->where('last_modified < ?', new Zend_Db_Expr('NOW()'))

Any other part of that expression that needs to be quoted or delimited is your responsibility.  E.g., if you interpolate any PHP variables into the expression, safety is your responsibility.  If you have column names that are SQL keywords, you need to delimit them yourself with quoteIdentifier().  Example:
$select->where($db->quoteIdentifier('order').'=?', $myVariable)

*Zend_Db_Adapter_Abstract::insert( array('colname' => 'value') )
Table name and column names are delimited, unless you turn off AUTO_QUOTE_IDENTIFIERS.
Values are parameterized as true query parameters (not interpolated).  Unless the value is a Zend_Db_Expr object, in which case it's interpolated verbatim, so you can insert expressions or NULL or whatever.

*Zend_Db_Adapter_Abstract::update( array('colname' => 'value'), $where )
Table name and column names are delimited, unless you turn off AUTO_QUOTE_IDENTIFIERS.
Values are parameterized, unless they are Zend_Db_Expr objects, as in insert() method.
The $where argument is not filtered at all, so you're responsible for any SQL injection risks in that one.  You can make use of the quoteInto() method to help make quoting more convenient.

A: by default when you use value binding in your SQL queries like this:
where('first_name=?', $id);

Zend_Db uses appropriate quoting of values to prevent SQL injection. although it is strongly recommended (by books, articles, manuals and self experience) to sanitize/filter user input. Zend_Filter can be very helpful.

A: The bit that should make you feel safe is the ? marks in the where clauses. These are parameters, which are safely replaced with the second argument by the database system.

A: When you need it somewhere else (like in join) or you are unsure if it will be escaped then you can always use $this->getAdapter()->quoteInto('type = ?',1);

A: Filtering input is always good, because likely it'll be going somewhere other than just the DB, and you at least want sane data in your database at some level.

*

*Zend_Filter_Input on the way in

*Prepared statements (or quoteInto if not in a prepared)

*Escape filters on the way out (htmlentities, etc).

A: One thing about this, when value is NULL, you can achive not valid query
$value = NULL;
$select->where('prop=?', $value);

Result: SQL error


text:
Q: Android database using ORMLITE sqlite I have used sqlite database using ormlite.I have declared primary key in database as follows:In database i fetch the values and display in listview. when i delete some entry.in list view..primary key goes on increasing values.
@DatabaseField(generatedId = true,columnName = "teacher_id")
        int teacherid;

     try {
                                Toast.makeText(DetailListView.this, "Delete entry", Toast.LENGTH_LONG).show();
                                DeleteBuilder<TeacherDetails, Integer> deleteBuilder=teacherDao.deleteBuilder();
                                deleteBuilder.where().eq("teacher_address", set.teacheraddress);
                                deleteBuilder.delete();
                                stud_list = teacherDao.queryForAll();
                                //adapter = new UsersAdapter(DetailListView.this, stud_list);
                               // list.setAdapter(adapter);
                                list.invalidate();
                                teacherDao.executeRaw("delete from sqlite_sequence where name='teacher_details';");
                            } catch (SQLException e) {
                                // TODO Auto-generated catch block
                                e.printStackTrace();
                            }

//code for creating db.
@Override
    public void onCreate   (SQLiteDatabase sqliteDatabase,      ConnectionSource      connectionSource) {
    try {

        TableUtils.createTable(connectionSource, TeacherDetails.class);
        TableUtils.createTable(connectionSource, StudentDetails.class);

    } catch (SQLException e) {
        Log.e(DatabaseHelper.class.getName(), "Unable to create datbases", e);
    }
}

   @Override
   public void onUpgrade(SQLiteDatabase sqliteDatabase, ConnectionSource   connectionSource, int oldVer, int newVer) {
    try {

        TableUtils.dropTable(connectionSource, TeacherDetails.class, true);
        TableUtils.dropTable(connectionSource, StudentDetails.class, true);
        onCreate(sqliteDatabase, connectionSource);

    } catch (SQLException e) {
        Log.e(DatabaseHelper.class.getName(), "Unable to upgrade database from version " + oldVer + " to new "
                + newVer, e);
    }
}

For example before delete 1)primary key :1 2)primary key:2(if i delete this values) 3)primary key:3
After delete 1)primary key:1 2)primary key:3(not start with primary key value 2) 3)primary key 4
This is my requirement

A: This is how database sequences are supposed to work. Your example is simple, but imagine a table with 10000000 entries. Imagine them being with ids the first 10000000 natural numbers. Now imagine a person goes and deletes the 345346th, then 123344th and finally 234545th. How should it know which ids are vacant, without requiring a huge number of calculations.
If your case is specific and you have just few entries, which you need to be sequential, you will have to give up on autoincrements and code it yourself. But please, consider all corner cases, because i beleive they are quite a few.


text:
Q: Button click event not called I want to disable a button, only using javascript.
I have one button on the form. I want to disable that button from javascript. When I try to do this, the button submit click event is not calling.
I used following code on javascript:
document.getElementById('<%=imgSubmit.ClientID%>').disabled = true;

The button get disabled; but its button click event on server side is not being called.
When I remove this javascript then it is calling the server side click event. What is the issue with disabling the button from javascript??

A: Well if the button is disabled it is not going to fire the server side event. Try submitting the form from the client side.
document.getElementById('<%=imgSubmit.ClientID%>').disabled = true;
Form1.submit();


text:
Q: Extracting unique values from multiple files in Perl I have several data files that are tab delimited. I need to extract all the unique values in a certain column of these data files (say column 25) and write these values into an output file for further processing. How might I do this in Perl? Remember I need to consider multiple files in the same folder.
edit: The code I've done thus far is like this.
#!/usr/bin/perl

use warnings;
use strict;

my @hhfilelist  = glob "*.hh3";

for my $f (@hhfilelist) {
  open F, $f || die "Cannot open $f: $!";
  while (<F>) {
    chomp;
    my @line = split /\t/;

    print "field is $line[24]\n";
  }
  close (F);
}

The question is how do I efficiently create the hash/array of unique values as I read each line of each file. Or is it faster if I populate the whole array and then remove duplicates?

A: For Perl solution, please use Text::CSV module to parse flat (X-separated) files - the constructor accepts a parameter specifying a separator character. Do this for every file in a loop, with file list generated by either glob() for files in a given directory or File::Find for subdirectories as well
Then, to get the unique values, for each row, store the column #25 in a hash.
E.g. after retrieving the values:
 $colref = $csv->getline($io);
 $unique_values_hash{ $colref->[24] } = 1;

Then, iterate over hash keys and print to a file.

For non-Perl shell solution, you can simply do:
cat MyFile_pattern | awk -F'\t' 'print $25' |sort -u > MyUniqueValuesFile

You can replace awk with cut
Please note that non-Perl solution only works if the files don't contain TABs in the fields themselves and the columns aren't quoted.

A: Some tips on how to handle the problem:

*

*Find files

*

*For finding files within a directory, use glob: glob '.* *'

*For finding files within a directory tree, use File::Find's find function

*Open each file, use Text::CSV with \t character as the delimiter, extract wanted values and write to file

A: perl -F/\\t/ -ane 'print"$F[24]\n" unless $seen{$F[24]}++' inputs > output

perl -F/\\t/ -ane 'print"$F[24]\n" unless $seen{$F[24]}++' *.hh3 > output

Command-line switches -F/\\t/ -an mean iterate through every line in every input file and split the line on the tab character into the array @F.
$F[24] refers to the value in the 25-th field of each line (between the 24-th and 25-th tab characters)
$seen{...} is a hashtable to keep track of which values have already been observed.
The first time a value is observed, $seen{VALUE} is 0 so Perl will execute the statement print"$F[24]\n". Every other time the value is observed, $seen{VALUE} will be non-zero and the statement won't be executed. This way each unique value gets printed out exactly once.

In a similar context to your larger script:
my @hhfilelist  = glob "*.hh3";
my %values_in_field_25 = ();
for my $f (@hhfilelist) {
  open F, $f || die "Cannot open $f: $!";
  while (<F>) {
    my @F = split /\t/;
    $values_in_field_25{$F[24]} = 1;
  }
  close (F);
}

my @unique_values_in_field_25 = keys %values_in_field_25; # or sort keys ...


text:
Q: Terms aggregation with nested wildcard path Given the following nested object of nested objects
{
  [...]
  "nested_parent":{
    "nested_child_1":{
      "classifier":"one"
    },
    "nested_child_2":{
      "classifier":"two"
    },
    "nested_child_3":{
      "classifier":"two"
    },
    "nested_child_4":{
      "classifier":"five"
    },
    "nested_child_5":{
      "classifier":"six"
    }
  [...]
}

I'm wanting to aggregate on the wildcard-ish field nested_parent.*.classifier, along the lines of
{
  "size": 0,
  "aggs": {
    "termsAgg": {
      "nested": {
        "path": "nested_parent.*"
      },
      "aggs": {
        "termsAgg": {
          "terms": {
            "size": 1000,
            "field": "nested_parent.*.classifier"
          }
        }
      }
    }
  }
}

which does not seem to work -- possibly because the path and field are not defined clearly enough.
How can I aggregate on nested objects with dynamically created nested mappings which share most of their properties, including the classifier on which I intend to terms-aggregate?

A: Tdlr;
A bit late to the party.
I would suggest a different approach as I don't see a possible solution using wildcards.
My solution would involve using the copy_to to create a field that you will be able to access using aggregation.
Solution
The idea is to create a field that will store the values of all your classifiers.
Which you can be doing aggregation on.
PUT /54198251/
{
  "mappings": {
    "properties": {
      "classifiers": {
        "type": "keyword"
      },
      "parent": {
        "type": "nested",
        "properties": {
          "child": {
            "type": "nested",
            "properties": {
              "classifier": {
                "type": "keyword",
                "copy_to": "classifiers"
              }
            }
          },
          "child2": {
            "type": "nested",
            "properties": {
              "classifier": {
                "type": "keyword",
                "copy_to": "classifiers"
              }
            }
          }
        }
      }
    }
  }
}

POST /54198251/_doc
{
  "parent": {
    "child": {
      "classifier": "c1"
    },
    "child2": {
      "classifier": "c2"
    }
  }
}

GET /54198251/_search
{
  "aggs": {
    "classifiers": {
      "terms": {
        "field": "classifiers",
        "size": 10
      }
    }
  }
}

Will give you:
  "aggregations": {
    "classifiers": {
      "doc_count_error_upper_bound": 0,
      "sum_other_doc_count": 0,
      "buckets": [
        {
          "key": "c1",
          "doc_count": 1
        },
        {
          "key": "c2",
          "doc_count": 1
        }
      ]
    }
  }


text:
Q: How to change field value in array by incoming ID How to change field value in array by incoming ID
For example, comes $ cityID = '2'; it means that UF_DEFAULT should be changed to 1 for the city of Tver, and 0 for the city of Moscow
or comes $ cityID = '10' ; is not existing, leave everything as it is without overwriting UF_DEFAULT
$cityID = '2'; // 2 - есть | 10 - нет
$arr = array(
        '1'=>array('ID'=>'1', 'NAME'=>'Moscow', 'UF_DEFAULT'=>'1', 'UF_CITY_CORD'=>'55.76, 37.64'),
        '2'=>array('ID'=>'2', 'NAME'=>'Tver', 'UF_DEFAULT'=>'0', 'UF_CITY_CORD'=>'55.76, 37.64'),
        '3'=>array('ID'=>'3', 'NAME'=>'Nahodka', 'UF_DEFAULT'=>'0', 'UF_CITY_CORD'=>'55.76, 37.64'),
        '4'=>array('ID'=>'4', 'NAME'=>'Omsk', 'UF_DEFAULT'=>'0', 'UF_CITY_CORD'=>'55.76, 37.64'),
);
foreach($arr as $key => $arSection)
{
    $arSectionsResult[$arSection['ID']] = $arSection;
}
unset($key, $arSection);
echo "<pre>";print_r($arSectionsResult);echo "</pre>";

Thanks in any case.

A: $cityID = '10'; // 2 - есть | 10 - нет
$arr = array(
    '1'=>array('ID'=>'1', 'NAME'=>'Moscow', 'UF_DEFAULT'=>'1', 'UF_CITY_CORD'=>'55.76, 37.64'),
    '2'=>array('ID'=>'2', 'NAME'=>'Tver', 'UF_DEFAULT'=>'0', 'UF_CITY_CORD'=>'55.76, 37.64'),
    '3'=>array('ID'=>'3', 'NAME'=>'Nahodka', 'UF_DEFAULT'=>'0', 'UF_CITY_CORD'=>'55.76, 37.64'),
    '4'=>array('ID'=>'4', 'NAME'=>'Omsk', 'UF_DEFAULT'=>'0', 'UF_CITY_CORD'=>'55.76, 37.64'),
);

// first we find - if we should change UF_DEFAULT
$changeDefault = false;
foreach ($arr as $item) {
    // find item with same ID and UF_DEFAULT != 1
    if ($item['ID'] === $cityID && $item['UF_DEFAULT'] != 1) {
        $changeDefault = true;
        break;
    }
}

// if you have to `changeDefault` - iterate over
// array again and change according to `cityID`
if ($changeDefault) {
    foreach ($arr as &$item) {
        $item['UF_DEFAULT'] = $item['ID'] == $cityID ? 1 : 0;
    }
}

print_r($arr);

A: Even though I don't really understand the logic behind you problem, this would one way to do this.
First check if the given key exists with array_key_exists. If so, set the UF_DEFAULT to 0 for all except for the given ID.
if (array_key_exists($cityId, $arr)) {
    foreach ($arr as $k => $city) {
        $arr[$k]["UF_DEFAULT"] = 0;
    }
    $arr[$cityId]["UF_DEFAULT"] = 1;
} else {
    // Key not existent...
}

A: Only perform one loop.  Only change values that need changing.  Quit iterating asap.
I am "modifying the input array by reference" in the loop.  To avoid issue downscript with $row, I unset it when the loop concludes.
Code: (Demo)
$cityID = '2';
$oldCityFound = false;
$newCityFound = false;
$arr = [
        '1' => ['ID'=>'1', 'NAME'=>'Moscow', 'UF_DEFAULT'=>'1', 'UF_CITY_CORD'=>'55.76, 37.64'],
        '2' => ['ID'=>'2', 'NAME'=>'Tver', 'UF_DEFAULT'=>'0', 'UF_CITY_CORD'=>'55.76, 37.64'],
        '3' => ['ID'=>'3', 'NAME'=>'Nahodka', 'UF_DEFAULT'=>'0', 'UF_CITY_CORD'=>'55.76, 37.64'],
        '4' => ['ID'=>'4', 'NAME'=>'Omsk', 'UF_DEFAULT'=>'0', 'UF_CITY_CORD'=>'55.76, 37.64'],
];
foreach ($arr as &$row) {
    if ($row['ID'] == $cityID) {
        if ($row['UF_DEFAULT'] == 1) {
            break; // nothing to change
        }
        $row['UF_DEFAULT'] = 1;
        $newCityFound = true;
    } elseif ($row['UF_DEFAULT'] == 1) {
        $row['UF_DEFAULT'] = 0;
        $oldCityFound = true;
    }
    if ($newCityFound && $oldCityFound) {
        break; // both jobs done ...efficiently
    }
}
unset($row); // best practice
var_export($arr);

In my answer, I am assuming the outer keys are not trusted as the ID value.  If the outer keys always equal the ID value within, then you can perform two shortcuts prior to looping:
if (!isset($arr[$cityID])) {
    // cityID not found, now what?
}

And
if ($arr[$cityID]['UF_DEFAULT']  == 1) {
    // nothing to change
}


text:
Q: Where the categorical encoding should be done in a k fold - cv procedure? I want to apply a cross validation method in my machine learning models. I these models, I want a Feature Selection and a GridSearch to be applied as well. Imagine that I want to estimate the performance of K-Nearest-Neighbor Classifier by applying a feature selection technique based on an F-score (ANOVA) that chooses the 10 most relevant features. The code would be as follows:
# 10-times 10-fold cross validation
n_repeats = 10
rkf = RepeatedKFold(n_splits=10, n_repeats = n_repeats, random_state=0)

# Data standardization
scaler = StandardScaler()

# Variable to contain error measures and counter for the splits
error_knn = []
split = 0

for train_index, test_index in rkf.split(X, y):

    # Print a dot for each train / test partition
    sys.stdout.write('.')
    sys.stdout.flush()

    X_train, X_test = X[train_index], X[test_index]
    y_train, y_test = y[train_index], y[test_index]

    # Standardize the data
    scaler.fit(X_train, y_train)
    X_train = scaler.transform(X_train)
    X_test = scaler.transform(X_test)

    ###- In order to select the best number of neighbors -###
    # Pipeline for training the classifier from previous notebooks
    pipeline = Pipeline([ ('knn', KNeighborsClassifier()) ])
    N_neighbors = [1, 3, 5, 7, 11, 15, 20, 25, 30]
    param_grid = { 'knn__n_neighbors': N_neighbors }

    # Evaluate the performance in a 5-fold cross-validation
    skfold = RepeatedStratifiedKFold(n_splits=5, n_repeats=1, random_state=split)

    # n_jobs = -1 to use all processors
    gridcv = GridSearchCV(pipeline, cv=skfold, n_jobs=-1, param_grid=param_grid, \
                          scoring=make_scorer(accuracy_score))

    result = gridcv.fit(X_train, y_train)

    ###- Results -###
    # Mean accuracy and standard deviation
    accuracies = gridcv.cv_results_['mean_test_score']
    std_accuracies = gridcv.cv_results_['std_test_score']

    # Best value for the number of neighbors
    # Define KNeighbors Classifier with that best value
    # Method fit(X,y) to fit each model according to training data
    best_Nneighbors = N_neighbors[np.argmax(accuracies)]
    knn = KNeighborsClassifier(n_neighbors = best_Nneighbors)
    knn.fit(X_train, y_train)

    # Error for the prediction
    error_knn.append(1.0 - np.mean(knn.predict(X_test) == y_test))

    split += 1

However, my columns are categorical (except binary label) and I need to do a categorical encoding. I can not remove this columns because they are essential.
Where would you perform this encoding and how the problems of categorical encoding of unseen labels in each fold would be solved?

A: Categorical encoding should be performed as the first step, precisely to avoid the problem you mentioned regarding unseen labels in each fold.
Additionally, your current implementation suffers from data leakage.
You're performing feature scaling on the full X_train dataset before performing your inner cross-validation.
This can be solved by including StandardScaler on the pipeline used for your GridSearchCV:
...

X_train, X_test = X[train_index], X[test_index]
y_train, y_test = y[train_index], y[test_index]

###- In order to select the best number of neighbors -###
# Pipeline for training the classifier from previous notebooks
pipeline = Pipeline(
    [ ('scaler', scaler), ('knn', KNeighborsClassifier()) ]
)
N_neighbors = [1, 3, 5, 7, 11, 15, 20, 25, 30]
param_grid = { 'knn__n_neighbors': N_neighbors }

...

Another couple of tips:

*

*GridSearchCV has a best_estimator_ attribute that can be used to extract the estimator with the best set of hyperparameters found.

*When using GridSearchCV with refit=True (the default), you can use the object directly to perform predictions, e.g. gridcv.predict(X_test).

EDIT: Perhaps I was too general when it came to when to perform categorical enconding. Your approach should depend on your problem/dataset.
If you know beforehand how many categorical features exist and you want to train your inner CV classifiers with this knowledge, you should perform categorical enconding as the first step.
If at training time you do not know how many categorical features you are going to see or you want to train your CV classifiers without knowledge of the full range of categorical features, you should perform categorical enconding at each fold.
When using the former your classifiers will all be trained on the same feature space while that's not guaranteed for the latter.
If using the latter, the above pipeline can be extended to incorporate categorical encoding:
pipeline = Pipeline(
    [
        ('enc', OneHotEncoder()),
        ('scaler', StandardScaler(with_mean=False)),
        ('knn', KNeighborsClassifier()),
    ],
)

I suggest you read the Encoding categorical features section of scikit-learn's User Guide carefully.


text:
Q: Creating drop-down menu in Google Script custom dialogue, with options from data in a Google Sheet I am looking to create a drop down menu in a custom dialogue when you run a script. I have been successful in doing so, and also able to create a loop in a  element that creates a drop down list from a static array [i.e. an array of months and create a drop down menu]. However, I have been unsuccessful in being able to bull data from a google sheet, and using that data to create the drop-down menu.
Example code that works for creating drop-down menu from array:

<form>
<select name="Month-test" id="month-selector-test" autofocus="autofocus" autocorrect="off" autocomplete="off">
  <option value="" selected="selected" id="todays-month"></option>
   <script>
   // select this element
  var currentDayList = document.getElementById('month-selector-test');
  // array of all months
  var allMonthsAbv = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
  // for every element in the array, add an option
  for (var i=0; i<allMonthsAbv.length; i++) {
    currentDayList.innerHTML += '<option value=' + allMonthsAbv[i] + '>' + allMonthsAbv[i] + '</option>';
  }
  </script>
</select>
</form>

Example code that does not work for creating drop down menu from data in sheet:

<form>
<select name="Month" id="month-selector" autofocus="autofocus" autocorrect="off" autocomplete="off">
  <option value="" selected="selected"></option>
    <script>
    var monthList = document.getElementById('month-selector');

    var allData = SpreadsheetApp.openById('###ID###').getSheetByName('###NAME###').getDataRange().getValues();
    var list = [];
    for (var i=1;i<allData.length;i++) {
      var schoolName = allData[i][1];
      if (schoolName != "") {
      list.push(schoolName);
      }
    }
   for (var i = 0;i<list.length;i++) {
    monthList.innerHTML += '<option value=' + list[i] + '>' + list[i] + '</option>';
  }
  </script>
</select>
</form>

A: You are using pop incorrectly. Change list.pop to list.push
  var monthList = document.getElementById('month-selector');

  var allData = SpreadsheetApp.openById('###ID###').getSheetByName('###NAME###').getDataRange().getValues();
  var list = [];
  for (var i=1;i<allData.length;i++) {
      var schoolName = allData[i][1];
      if (schoolName != "") {
        list.push(schoolName);
      }
    }
   for (var i = 0;i<list.length;i++) {
    monthList.innerHTML += '<option value=' + list[i] + '>' + list[i] + '</option>';
  }

A: I have certainly written, and routinely use, code that does what you want. So I can say, for certain, that it can be done.
I should add the note that it is very very useful to do this.  The spreadsheet, is something that non-coders can update happily and then we generate code from that.
The thing that puzzles me about the code you have offered is your use of SpreadsheetApp   in HTML.
I have only ever done that in GAS code.  You may know something that I don't or that maybe will be the beginning of answering your question.
I make a lot of use of google.script.run Do you?

A: So the next question is - can you move easily, and routinely, between the foreground (HTML) and the background (GAS)
I ask this because it was the key for me

A: OK - I have done what I should have done before and tried running your code and have come up with a number of quite distinct (ie separate, but very definite) issues. I am left with one that I have yet to resolve but I thought I should keep you posted. I will try to address them all before putting in the working code.

*

*When does the code get triggered? This must happen in the HTML body onload event for the drop-down to be populated. The only way I know for code to be made to be triggered at that point in GAS is via a "successHandler" for a GAS call.
Hence:

The nullFunction() (GAS, ie backend) does nothing, it just causes addMonths() to be called when the body has loaded and then populate the drop-down.

*What attributes does the select tag support?
You were using id and the associated getElementById() call but select does not support the id attribute, hence:

You then have to get your head around the fact that getElementsByName() returns a node-list, so you need to add to the innerHtml of [0] in that list. Hence:
  var currentDayList = document.getElementsByName('month-selector-test')[0];

*Where should the  block be placed?
There are two aspects to this. You had put it within the  block. However, if it is in there it will be handled by your code as part of the innerHtml, so it must not go there!
If you put it in the  it will not yet have loaded when onload is fired so it must go at the end of

Here is the working code:
    <!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
<body onload='google.script.run.withSuccessHandler(addMonths).nullFunction();'>
  x x x
<select name="month-selector-test">
</select>
   <script>
  var currentDayList = document.getElementsByName('month-selector-test')[0];
   function addMonth(monthAbv){
   text=currentDayList.innerHTML;
  var firstPart='\<option value=\"';
  var secondPart='\"\>';
  var thirdPart='\<\/option\>';
  text=text + firstPart+name  + secondPart  + monthAbv + thirdPart;
  currentDayList.innerHTML+=text;
  }
  function addMonths(){
  var allMonthsAbv = ["Jan","Feb"];
  //"Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
  // for every element in the array, add an option
  for (var i=0; i<allMonthsAbv.length; i++) {
   addMonth(allMonthsAbv[i]);
    }
  }
  </script>
  </body>
</html>


text:
Q: read from stdin for libxml2 in C I would like to know the best way to parse a large amount of xml from stdin (data getting piped) into a program  I am writing using libxml2.  I can parse fine using a reader from the function xmlTextReaderPtr reader = xmlNewTextReaderFilename(filename) when I have a char * to the name of the file.  I would preferably like to wind up with a reader so the rest of my program remains the same.
Thank you.

A: I believe the best thing to do is to use the opening function that contains a file descriptor as the parameter and pass STDIN_FILENO.
http://www.xmlsoft.org/html/libxml-xmlreader.html#xmlReaderNewFd


text:
Q: How can I duplicate a mac user account including username and password? I have an account on my friends mac that I would like to move to my mac, so is there any way to duplicate everything in that account, including username and password? By the way, I am using OS X Mavericks and my friend is running on OS X Yosemite.

A: You can create the core UID with this info, then use cp, scp or a 3rd party utility to move the data.
Create a User Account from Terminal
Use the dscl command. This example would create the user "luser", like so:
dscl . -create /Users/luser
dscl . -create /Users/luser UserShell /bin/bash
dscl . -create /Users/luser RealName "Lucius Q. User"
dscl . -create /Users/luser UniqueID "1010"
dscl . -create /Users/luser PrimaryGroupID 80
dscl . -create /Users/luser NFSHomeDirectory /Users/luser

You can then use passwd to change the user's password, or use:
dscl . -passwd /Users/luser password

You'll have to create /Users/luser for the user's home directory and change ownership so the user can access it, and be sure that the UniqueID is in fact unique.
This line will add the user to the administrator's group:
dscl . -append /Groups/admin GroupMembership luser

A: One of user-friendly ways will be to use Migration Assistant(http://support.apple.com/en-us/HT4889). This GUI app will let you transfer (copy) all the account settings and file (user profile, etc) between two Macs using LAN or Thunderbolt cable.


text:
Q: Writing output to excel file in python I am new in Python. I use xlwt so I am having a problem with writing outputs to excel file.
I have an output data like:
[['Alex'], [23, 40], ['Food', 'Clothes']]
[['Andy'], [10, 23], ['Telephone', 'Games']]

I just want data is written like this

A: It looks that your input is some collections of lists. You can create an empty Dataframe and add each list as new rows separately. See below:
import pandas as pd

df=pd.DataFrame(columns=['Name', 'Amount', 'Spendings'])

for x in your_lists:
    for i in range(len(x[1])):
        df.loc[len(df)]=[x[0][0], x[1][i], x[2][i]]

df.set_index('Name', inplace=True)

>>> print(df)

     Amount  Spendings
Name
Alex     23       Food
Alex     40    Clothes
Andy     10  Telephone
Andy     23      Games


text:
Q: Don't pass controller for method instantiating services In a class (name it a) I have a method, that instantiates multiple objects of the same class (name it b) (based on some conditions, that are irrelevant). Both classes are registered as services in my container.
Currently I am passing my controller to the method to make it able to request instances of the class b, like so:
class a {

    public method createBs(ContainerInterface $container) {
        foreach ($x as $y) {
            $b = $container->get('b');
            //do some shit with b
        }
    }
}

But it bugs me to pass the container, because I think it is bad code design. Has anyone an idea how i can get rid of the passed container?

A: You could pass a factory to it instead, where the factory handles creating objects of class b:
class BFactory
{
    private $container;

    public function __construct($container)
    {
        $this->container = $container;
    }

    public function create()
    {
        return $container->get('b');
    }
}

That way, the method within a will only ever be able to create objects of b. However, you'd just end up sending the container to the factory so it can create objects of b, so it's really a matter of who you want to have the container exposed to.
Another option is to apply the same factory pattern, but instead specify it  with a lambda, something like:
$container; // Predefined
$lambda = function() use (&$container) {
    return $container->get('b');
}
$a = new a();
$a->createBs($lambda);

Then in a, you'd do:
public function createBs($factory) {
    $b = $factory();
}


text:
Q: Seed in Geoserver doesn't work I have a fresh installation of Geoserver 2.8.2 in linux. I have enabled Disc Quota (set 500 MB space) and in Caching Defaults I have set "Enable direct integration with GeoServer WMS" option. Next, I have added new GeoTif store and layer (native and declared srs are the same). And here trouble starts. When I'm trying to seed this layer using GeoWebCache, the process stops. I can find these logs in Geoserver:
2016-02-01 01:40:33,205 INFO [seed.SeedTask] - GWC Seeder Thread-4 begins seeding layer : qqq:alingsas
2016-02-01 01:40:33,206 INFO [geoserver.wms] -
Request: getServiceInfo
2016-02-01 01:40:33,258 ERROR [geoserver.ows] -
org.geoserver.platform.ServiceException: Error rendering coverage on the fast path
    at org.geoserver.wms.map.RenderedImageMapOutputFormat.produceMap(RenderedImageMapOutputFormat.java:344)
    at org.geoserver.wms.map.RenderedImageMapOutputFormat.produceMap(RenderedImageMapOutputFormat.java:259)
    at org.geoserver.wms.map.RenderedImageMapOutputFormat.produceMap(RenderedImageMapOutputFormat.java:132)
    at org.geoserver.wms.GetMap.executeInternal(GetMap.java:505)
    at org.geoserver.wms.GetMap.run(GetMap.java:249)
    at org.geoserver.wms.GetMap.run(GetMap.java:119)
    at org.geoserver.wms.DefaultWebMapService.getMap(DefaultWebMapService.java:320)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:319)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
    at org.geoserver.kml.WebMapServiceKmlInterceptor.invoke(WebMapServiceKmlInterceptor.java:34)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.geoserver.gwc.wms.CacheSeedingWebMapService.invoke(CacheSeedingWebMapService.java:62)
    at org.geoserver.gwc.wms.CacheSeedingWebMapService.invoke(CacheSeedingWebMapService.java:36)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.geoserver.gwc.wms.CachingWebMapService.invoke(CachingWebMapService.java:74)
    at org.geoserver.gwc.wms.CachingWebMapService.invoke(CachingWebMapService.java:55)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.geoserver.ows.util.RequestObjectLogger.invoke(RequestObjectLogger.java:55)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
    at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
    at com.sun.proxy.$Proxy93.getMap(Unknown Source)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.geoserver.ows.Dispatcher.execute(Dispatcher.java:845)
    at org.geoserver.ows.Dispatcher.handleRequestInternal(Dispatcher.java:275)
    at org.springframework.web.servlet.mvc.AbstractController.handleRequest(AbstractController.java:153)
    at org.geoserver.gwc.GWC.dispatchOwsRequest(GWC.java:1223)
    at org.geoserver.gwc.layer.GeoServerTileLayer.dispatchGetMap(GeoServerTileLayer.java:625)
    at org.geoserver.gwc.layer.GeoServerTileLayer.getMetatilingReponse(GeoServerTileLayer.java:569)
    at org.geoserver.gwc.layer.GeoServerTileLayer.seedTile(GeoServerTileLayer.java:764)
    at org.geowebcache.seed.SeedTask.doActionInternal(SeedTask.java:136)
    at org.geowebcache.seed.GWCTask.doAction(GWCTask.java:76)
    at org.geowebcache.seed.MTSeeder.call(MTSeeder.java:36)
    at org.geowebcache.seed.MTSeeder.call(MTSeeder.java:25)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.geoserver.platform.ServiceException: java.lang.IllegalArgumentException: Angle 6,611,011,917.022 is too high.
    at org.geoserver.wms.map.RenderedImageMapOutputFormat.directRasterRender(RenderedImageMapOutputFormat.java:1055)
    at org.geoserver.wms.map.RenderedImageMapOutputFormat.produceMap(RenderedImageMapOutputFormat.java:342)
    ... 44 more
Caused by: java.lang.IllegalArgumentException: Angle 6,611,011,917.022 is too high.
    at org.geotools.measure.AngleFormat.format(AngleFormat.java:703)
    at org.geotools.measure.AngleFormat.format(AngleFormat.java:940)
    at org.geotools.measure.AngleFormat.format(AngleFormat.java:862)
    at org.geotools.measure.Angle.toString(Angle.java:165)
    at java.text.MessageFormat.subformat(MessageFormat.java:1271)
    at java.text.MessageFormat.format(MessageFormat.java:860)
    at java.text.Format.format(Format.java:157)
    at org.geotools.resources.IndexedResourceBundle.getString(IndexedResourceBundle.java:491)
    at org.geotools.resources.i18n.Errors.format(Errors.java:77)
    at org.geotools.referencing.operation.projection.MapProjection.verifyGeographicRanges(MapProjection.java:508)
    at org.geotools.referencing.operation.projection.MapProjection.access$000(MapProjection.java:86)
    at org.geotools.referencing.operation.projection.MapProjection$Inverse.transform(MapProjection.java:1066)
    at org.geotools.referencing.operation.projection.MapProjection$Inverse.transform(MapProjection.java:1105)
    at org.geotools.referencing.operation.transform.AbstractMathTransform.transform(AbstractMathTransform.java:237)
    at org.geotools.referencing.operation.transform.ConcatenatedTransformDirect.transform(ConcatenatedTransformDirect.java:67)
    at org.geotools.referencing.CRS.transform(CRS.java:1340)
    at org.geotools.referencing.CRS.transform(CRS.java:1408)
    at org.geotools.geometry.jts.ReferencedEnvelope.transform(ReferencedEnvelope.java:688)
    at org.geotools.geometry.jts.ReferencedEnvelope.transform(ReferencedEnvelope.java:634)
    at org.geotools.renderer.crs.ProjectionHandler.preProcess(ProjectionHandler.java:412)
    at org.geotools.renderer.lite.gridcoverage2d.GridCoverageReaderHelper.reduceEnvelope(GridCoverageReaderHelper.java:410)
    at org.geotools.renderer.lite.gridcoverage2d.GridCoverageReaderHelper.computeReadingGeometry(GridCoverageReaderHelper.java:378)
    at org.geotools.renderer.lite.gridcoverage2d.GridCoverageReaderHelper.readCoverageInEnvelope(GridCoverageReaderHelper.java:290)
    at org.geotools.renderer.lite.gridcoverage2d.GridCoverageReaderHelper.readCoverages(GridCoverageReaderHelper.java:203)
    at org.geotools.renderer.lite.gridcoverage2d.GridCoverageRenderer.renderImage(GridCoverageRenderer.java:800)
    at org.geotools.renderer.lite.gridcoverage2d.GridCoverageRenderer.renderImage(GridCoverageRenderer.java:768)
    at org.geoserver.wms.map.RenderedImageMapOutputFormat.directRasterRender(RenderedImageMapOutputFormat.java:947)
    ... 45 more
2016-02-01 01:40:33,259 INFO [seed.GWCTask] - Thread group finished SEED task after 0.054 seconds
2016-02-01 01:40:33,259 ERROR [seed.MTSeeder] - Problem communicating with GeoServer
org.geowebcache.GeoWebCacheException: Problem communicating with GeoServer
    at org.geoserver.gwc.layer.GeoServerTileLayer.getMetatilingReponse(GeoServerTileLayer.java:575)
    at org.geoserver.gwc.layer.GeoServerTileLayer.seedTile(GeoServerTileLayer.java:764)
    at org.geowebcache.seed.SeedTask.doActionInternal(SeedTask.java:136)
    at org.geowebcache.seed.GWCTask.doAction(GWCTask.java:76)
    at org.geowebcache.seed.MTSeeder.call(MTSeeder.java:36)
    at org.geowebcache.seed.MTSeeder.call(MTSeeder.java:25)
    at java.util.concurrent.FutureTask.run(FutureTask.java:262)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalStateException: Expected: RenderedImageMap, got null
    at org.geoserver.gwc.layer.GeoServerTileLayer.dispatchGetMap(GeoServerTileLayer.java:628)
    at org.geoserver.gwc.layer.GeoServerTileLayer.getMetatilingReponse(GeoServerTileLayer.java:569)
    ... 9 more

I can't work out what is wrong. Tiff file must be correct, because it works on other Geoserver. When I'm on Tile Caching-> Tile Layers -> click Preview, then tiles are generating fine and in summary I have information how many tiles were created on disk.
How can I make seeding layers work correctly?
Update 1
I have made some progress - I found out that after installation Geoserver 2.5.5 seeding works perfectly. In version 2.6.x seeding doesn't work. The difference between them is that 2.5 uses java 6 and 2.6 uses java 7. In linux I have installed java 1.7.0_91.
I forgot to mention that I had been seeding in standard EPSG:900913 / png.

A: I had this problem a number of time in the past and then I realized it's an Authentication problem between GWC and Geoserver. As was also noted by @Nuno Oliviera or Geosever dev team, GWC has not notion of security and it's uses ROLE_ADMINISTRATOR pricipal to authenticate user for GWC Administration purpose (which include Seed, Reseed, ReloadConfiguration).
Possible Causes: You are using a different Role Service as the Active role service in Security->Setting->Active role service.
If you have to do this because maybe you want to store use JDBC Role Service, migrate the ADMIN and GROUP_ADMIN roles to the new Role Service.
Why? As of this the time of writing this Geoserver 2.13.0 and below, GWC use hard coded ADMIN role to authenticate the administrator under the ROLE_ADMINISTRATOR principal. Any thing that is not ADMIN will not work.
Cause 2: Data Rules. Any data rule on the layer or child layers of the layer group you are trying will prohibit seeding and reseeding tasks on that layer or layer group. temporarily remove the data rule so as to seed.
Cause 3: (Which I can't figure out). Any Custome Gridset like WebMercator or something which is not shipped with Geoserver (i.e EPSG:4326 and 900913) will cause this problem.


text:
Q: Counting the number of co-occurrences during a given time window using Redis So I have a set of users and a set of websites. For a given user, I know which website he visited and when. I am interested in building an API using Redis to answer questions in the form: "How many unique days are contained in the browsing history of user u for website w during a time window [t0, t1]"? Let's call that number f(u,w,t0,t1). Each day is identified by an integer d (e.g., the number of days since EPOCH)
I see two ways to model the browsing data using Redis:

*

*create a sorted set for each pair ( u, w ). Each element of the sorted set is ( score=d, element=d ) where d is the day when u visited w. In other words, a set element is identical to its score. Then f(u,w,t0,t1) is simply ZCOUNT( u:w, t0, t1 )

*create a set for each pair ( u, w ). Each element of the set is d. Then to get f(u,w,t0,t1), I need to iterate over the set and count the number of days between t0 and t1
My current understanding is that there is a compromise between memory usage and speed (to answer a query): the first solution is the fastest (I don't have to iterate over the whole set), although it is wasting memory (the same number d is used both as the score and the set element).
My questions are:

*

*is my understanding correct?

*are there better solutions?

A: Your understanding is correct... but here's an optimization to the 2nd approach that is likely to perform better: provided t0 and t1 to query for, build a temporary set that contains all d values between these. Then, do an SINTERSTORE between that temporary set and the one for (u,w). To obtain the count, SCARD the resulting set.


text:
Q: Intellij create sample struts web project with java,then show this error Failed to download 'http://central.maven.org/maven2/org/apache/struts/struts2-core/2.5.14.1/struts2-core-2.5.14.1.jar':
central.maven.org

A: If you have URL to Maven Central Repository in your pom.xml defined like:
    <repository>
        <id>Maven Central</id>
        <name>Maven Central Repository</name>
        <url>http://central.maven.org/maven2</url>
    </repository>

then url needs to be updated, to
    <repository>
        <id>Maven Central</id>
        <name>Maven Central Repository</name>
        <url>https://repo1.maven.org/maven2</url>
    </repository>

because: "Beginning January 15, 2020, The Central Repository will no longer support communication over HTTP" (https://blog.sonatype.com/central-repository-moving-to-https)


text:
Q: VS2005/VS2008 DataSet designer, insert a row into a table that has an autogenerated guid column I have a strongly typed DataTable created with the VS2005/VS2008 DataSet designer.
The table has a Primary Key column that is a guid, which gets populated by SQL server.  The problem is when I want add a row (or multiple rows) to my DataTable and then call the DataAdapter.Update method (passing in the DataTable).  When DataAdapter.Update is called I get a SQL exception saying that I cannot insert NULL into the primary key column.
How do I tell the designer that this is an autogenerated column and I do not want to provide a value for new rows?  I just want the value generated by SQL.
Am I missing something here, or is this a limitation of the DataSet designer?
I know how achieve this using LINQ to SQL, but unfortunatley I do not have it at my disposal for this project.

A: Possibly one of these:

*

*If you don't need the column in your DataSet for your app, then remove it.

*If you want the column but don't care to give it a value, then change it to allow DBNull.

*You can always turn off constraint enforcement (probably a bad idea): DataSet.EnforceConstraints = false

*You could fill the column with a surrogate key that does not get sent to the DB.

For the first two options, if you want the convenience of letting the designer keep your structure in sync with your database, then you could remove the column or allow null programmatically, perhaps right next to a "// HACK: " comment explaining why.

A: You're problably using DEFAULT NEWID() on your SQL Server table definition so the problem may be that the Dataset designer doesn't see this column as auto-generated.
Maybe generating guid in your application code could be a solution? If not, then you could set default value in you Dataset but then you're probably have to also change DataAdapter Insert/Update statements so that this default value doesn't get inserted into Sql Server table.
There could also be some other solution that I'm not aware of...


text:
Q: Can I run a linear probability model or logistic regression if my binary dependent variable only has 4 1's and 150 0's? I am trying to estimate a linear probability model (LPM) / logit model with about 3 covariates. The main dependent variable is an extremely imbalanced binary variable (there are 4 1's and 150 0's in the whole data). Why would this regression not work?

A: There doesn't have to be a problem. For instance, consider
n = 154
set.seed(11) # I choose this seed by hand to get 3 positives.

x1 = rnorm(n)
x2 = rnorm(n)
x3 = rnorm(n)

a0 = -2.5
a1 = a2 = a3 = 1

z = a0 + a1*x1 + a2*x2 + a3*x3 + rnorm(n)
y = z > 1

sum(y) # 3

mod = glm(y ~ x1 + x2 + x3, binomial(link = "probit"))
summary(mod)

The summary doesn't look too bad:
Coefficients:
            Estimate Std. Error z value Pr(>|z|)
(Intercept)  -3.7928     1.1936  -3.178  0.00149 **
x1            1.3886     0.6931   2.003  0.04514 *
x2            1.1549     0.5122   2.255  0.02416 *
x3            0.5848     0.5449   1.073  0.28314


text:
Q: ionic 4: dateStart and dateEnd have 2 hours difference I'm using a little kind of code for saving local dateTime in localStorage for starting an account and closing it.
 //Save end date of cancelation action
this.WarrentItem.dateStart = this.timeNow;
this.WarrentItem.dateEnd = this.timeNow;

in my localStorage, i've got something like this.
Start date: 06/03/2019 07:00:00
End date: 06/03/2019 09:00:00
The problem is that is not two hours of difference. And im confused whats wrong.


text:
Q: What are the benefits of a self signed certificate on a live site? Are there any benefits of a self signed certificate on a live site?
I know in IIS 7 you have the ability to self sign a certificate and I was wondering if using that as a precurser to buying one from a CA would be a good idea.
Do you get the same encryption benefits that you get from a CA signed cert or am I confusing terms? (running off the https protocol)

A: You get the same encryption benefits, but everyone viewing your site will get a warning that your certificate is untrusted (or from an untrusted source). The advantage of getting one of the main stream certs is that they are already in the browser as trusted.
In IE 7, go to Tools, Internet Options, Content, Certificates, Trusted Root Certification Authorities. Those are all the authorities IE trusts by default.

A: Trust.  A self-signed certificate gives the same encryption.
But I trust a CA.  I do not trust you.
So why shouldn't I trust you? Because there's no guarantee that the name on the certificate ("Discount Bob's Hanggliding and BBQ Emporium") was the person who actually created the certificate.  I could create a certificate that said "Discount Bob's Hanggliding and BBQ Emporium" and when you go to ritter.vg it'd say "Discount Bob's Hanggliding and BBQ Emporium".
But when I ask a CA to sign my certificate that says "Discount Bob's Hanggliding and BBQ Emporium", they'll ask "Sure, show me some credentials" and I don't have any, so they'll tell me to piss off.  But the actual Discount Bob will have those credentials, the CA will sign it.  So when you see the certificate, signed by the CA, you'll know that it actually is Discount Bob, because if it weren't the CA wouldn't have signed it.
The purpose of a signed certificate is to verify that the person is actually who he says he.  Because the CA said he is, and I trust the CA.
The encryption isn't directly relevant to a certificate - it just gets added in because it's good to have and it goes hand in hand.

A: Pros of self-signed cert:

*

*Free

*Same encryption technology as CA signed

Cons:

*

*Browser will display some form of security warning requiring user interaction to view the site.  This can be suppressed by the user choosing to trust the cert.

*The trust you are implying is against the signer of the cert.  Anybody's cert can enable SSL encrypted connections.  The trust policy protects the user form man-in-the-middle attacks.  No one can issue a signed cert but the CA it came from and only to be used on the server it was created for.  Therefore, it's contents cannot come from another source or be modified in transit.

Quick scenario:  If someone setup a rogue wifi access point in an internet cafe, it's then possible to transparently proxy victim users' activity and watch it in a network sniffer.  Normally, SSL is encrypted and the data is unusable.  However, tools exist to proxy the user's HTTPS requests and inspect the victim's content in transit.  This has a side effect of giving the affected user an unauthentic cert that is typically not trusted.
If you go to log into your bank's site and get an SSL security warning, DO NOT proceed.  You may be a target.
Some might recognize this as the Hak5 Pineapple.

A: Since you asked specifically for the benefits of a self-signed cert, I suppose the "benefits" would be that it's cheap (ie free) and quicker to set up initially. These are obviously far outweighed by the negatives of all of your site visitors having to add an exception to their browsers' security policies to allow them to view your site.
If you haven't listened to them already, you may find some of the past Security Now Podcasts of interest - SSL is discussed at length in a number of episodes.

A: You're confusing encryption with authentication.
Any cert will provide encryption.
A CA cert also proves that CA is vouching that you are who you say you are.
A self-signed cert provides encryption but not authentication.

A: The encryption is not a property of the certificate or where it is signed from.  The benefit you get from a CA signed cert is that it is automatically trusted by web browsers (and other SSL-aware applications).  A self-signed certificate will pop up a warning that the certificate is not trusted.  In more recent browsers, such as FireFox 3, the default action is to refuse to show the page and the user has to take deliberate actions to enable use of a self-signed (or expired, for that matter) certificate.
If you can talk to everyone who will use the web page (if this is for your family only, for example), this isn't a problem.  Tell them to expect that warning and how to handle it in their browser and it's a one-time issue.
However, if this is for any use that requires anything approaching real security, you probably want a true, signed, not self-signed certificate.

A: Main benefit is you do not need to visit a 3rd party to handle your site's security. You can do this yourself. The problem is it's complicated to get right.
Their browser would need to "trust" the self-signed certificate. If you change the cert in the future, the same dialog should appear. Some answers explain how to do this. This is still bad, since users would be more susceptible to attacks, such as man-in-the-middle when they are trained to accept self signed certificates. I've seen companies where this is standard procedure! Too bad for those users!
Ideally, you would have a process to install a custom root cert on their box prior to attempting to hit your site. This root cert would then issue your site's cert. This way, their browser would trust your self signed cert prior to connecting to your site the 1st time, without displaying a trust error.


text:
Q: Can I mint 1 NFT few time(20 times) on Solana candy machine v2? I have 10 images(NFT) I need to mint each image at least 20 times(10 * 20 = 200 times) is it possible to make it in Solana with Metaplex?
If yes can you please share link to docs or another website?
Thank you in advance!

A: Yes. You could mint them all as NFTs with the metaplex source code.
Using the candymachine V2 is one way: https://docs.metaplex.com/
When "preparing the assets" in this step: https://docs.metaplex.com/candy-machine-v2/preparing-assets I would just set 0-10.png to be all the same image and with whatever metadata you want.
Note: a technical aspect of this to remember is that these will be minted as NFTs so even though they have the same image they have a different mint hash. If this doesn't matter than this is a perfectly fine method to use.


text:
Q: DC/OS on GCE Ubuntu Is there any link/documentation available around installing DC/OS on Google Compute Engine where instances are ubuntu 16.04 instances including the bootstrap node instead of CentOS 7?
Currently , the documents I find use Ansible and CentOS 7 on GCE as below.
https://dcos.io/docs/1.7/administration/installing/cloud/gce/

A: Short answer: Debian based distributions are currently (at least up to DC/OS 1.10) not supported.
Long answer: It's possible, but requires some extra steps.
DC/OS doesn't use any RedHat specific features. Most important differences could be solved by symlinks for few system binaries, as RedHat systems have different paths and systemd doesn't support $PATH variable in service definition. You'll need following:
sudo apt-get install libcurl3-nss ipset selinux-utils curl unzip bc
sudo ln -s /bin/mkdir /usr/bin/mkdir
sudo ln -s /bin/ln /usr/bin/ln
sudo ln -s /bin/tar /usr/bin/tar
sudo ln -s /bin/rm /usr/bin/rm
sudo ln -s /usr/sbin/useradd /usr/bin/useradd
sudo ln -s /bin/bash /usr/bin/bash
sudo ln -s /sbin/ipset /usr/sbin/ipset

Another requirements are:

*

*systemd with version >=200

*Docker >=1.6
Slightly outdated scripts from John Omernik, there's also puppet module (I'm the author). For further details see discussion on DC/OS Jira.
Next step is manual DC/OS compilation (it might sound scary, but actually it's very easy). C++ components (especially mesos-slave) are dependent on system libraries and they'd better be linked to proper libraries.
apt install python3-venv build-essential git
git clone https://github.com/dcos/dcos
./build_local.sh

Resulting "image" will be located in:
$HOME/dcos-artifacts/testing/`whoami`/dcos_generate_config.sh

You can copy it to your bootstrap server and extract:
bash dcos_generate_config.sh --genconf

after updating genconf/config.yaml you can start a container for serving the installation scripts:
docker run -d -p 9090:80 -v $PWD/genconf/serve:/usr/share/nginx/html:ro nginx

On a new node simply fetch the installation script:
rm -rf /tmp/dcos && mkdir /tmp/dcos && cd /tmp/dcos && curl -O http://bootstrap.example.com:9090/dcos_install.sh
bash dcos_install.sh slave

Unless you don't want to run packages from DC/OS Universe (like Elastic, Kafka, etc.) that depends on libmesos-bundle, you might be just fine. The bundle is fetched into each executor's directory, it includes numerous libraries, such as libmesos.so
...
-rwxr-xr-x 1 nobody nogroup 55077256 Jun 28 19:50 libmesos-1.4.0.so
-rwxr-xr-x 1 nobody nogroup     1487 Jun 28 19:50 libmesos.la
lrwxrwxrwx 1 nobody nogroup       17 Jun 28 19:50 libmesos.so -> libmesos-1.4.0.so
-rwxr-xr-x 1 nobody nogroup   398264 Jun 28 19:53 libpcre.so.1
-rwxr-xr-x 1 nobody nogroup   121296 Jun 28 19:53 libsasl2.so.3
-rwxr-xr-x 1 nobody nogroup   155744 Jun 28 19:53 libselinux.so.1
-rwxr-xr-x 1 nobody nogroup   454008 Jun 28 19:53 libssl.so.10
-rwxr-xr-x 1 nobody nogroup   999944 Jun 28 19:53 libstdc++.so.6
-rwxr-xr-x 1 nobody nogroup    79000 Jun 28 19:53 libsvn_delta-1.so.0
-rwxr-xr-x 1 nobody nogroup  1820208 Jun 28 19:53 libsvn_subr-1.so.0
-rwxr-xr-x 1 nobody nogroup    20040 Jun 28 19:53 libuuid.so.1
-rwxr-xr-x 1 nobody nogroup    90664 Jun 28 19:53 libz.so.1
drwxr-xr-x 3 nobody nogroup     4096 Jun 28 19:53 mesos
drwxr-xr-x 2 nobody nogroup     4096 Jun 28 19:37 pkgconfig

Some libraries might be compatible with your system, but the versions between CentOS and Debian might (and will) differ. You might encounter errors like:
libmesos-bundle/lib/libcurl.so.4: version `CURL_OPENSSL_3' not found (required by curl)

which will cause that all agent based health checks that use curl won't work, therefore most instances will refuse to start.


text:
Q: Getting error of not a single group function in aggregated function CREATE TABLE test1 (
    e_id       NUMBER(1),
    e_ques_id  NUMBER(10)
);

INSERT INTO test1 VALUES(1,3);
INSERT INTO test1 VALUES(1,4);

CREATE TABLE test_ref (
    code     NUMBER(1),
    c_value  VARCHAR2(20)
);

INSERT INTO test_ref VALUES(3,'May');
INSERT INTO test_ref VALUES(4,2022);

COMMIT;

Tool Used: SQL Developer(18c)

There are two tables test1 and test_ref and I want to fetch the value from the test_ref table in order to bring month and year column value.
Expected Output:
+------+------------+
| e_id | month_year |
+------+------------+
|    1 | May 2022   |
+------+------------+

My attempt:
SELECT t.e_id,
LISTAGG(c_value,' ')month_year
FROM test1 t
JOIN test_ref tr ON(t.e_ques_id = tr.code)
WHERE t.e_ques_id IN(3,4)
GROUP BY t.e_id;

This is giving me the exact result that I am looking for but I need to add this logic in the existing view for which I need to use aggregated or case expression to bring the result. Hence I tried using CASE and MAX but it is giving me an error of not a single group function
My attempt (resulting in an error):
SELECT t.e_id,
MAX(CASE
WHEN t.e_ques_id IN(3,4) THEN LISTAGG(c_value,' ')
END )month_year
FROM test1 t
JOIN test_ref tr ON(t.e_ques_id = tr.code)
GROUP BY t.e_id;

A: To me, it is kind of difficult to guess why existing view requires  aggregate function or case expression.
Anyway: if you use max in its analytic form, skip case expression and - instead - move e_ques_id condition into the where clause (as you already did in query that works), you'd get this:
SQL>   SELECT t.e_id,
  2           MAX (LISTAGG (c_value, ' ') WITHIN GROUP (ORDER BY code))
  3              OVER (ORDER BY NULL) month_year
  4      FROM test1 t JOIN test_ref tr ON t.e_ques_id = tr.code
  5     WHERE t.e_ques_id IN (3, 4)
  6  GROUP BY t.e_id;

      E_ID MONTH_YEAR
---------- ---------------
         1 May 2022

SQL>

I have no idea whether this would (or would not) work in that view, but - you may try it.

A: You can use conditional aggregation inside LISTAGG:
SELECT t.e_id,
       LISTAGG(CASE WHEN t.e_ques_id IN (3,4) THEN c_value END, ' ')
         WITHIN GROUP (ORDER BY t.e_ques_id) AS month_year
FROM   test1 t
       JOIN test_ref tr ON(t.e_ques_id = tr.code)
GROUP BY t.e_id;

Which, for the sample data:
CREATE TABLE test1 (e_id, e_ques_id) AS
SELECT 1, LEVEL FROM DUAL CONNECT BY LEVEL <= 5;

CREATE TABLE test_ref (code, c_value) AS
SELECT 1, 'Not this'        FROM DUAL UNION ALL
SELECT 3, 'May'             FROM DUAL UNION ALL
SELECT 4, '2022'            FROM DUAL UNION ALL
SELECT 5, 'Not this either' FROM DUAL;

Outputs:

E_ID
MONTH_YEAR

1
May 2022

db<>fiddle here

A: This is how you can use Max() OVER() though I don't understand what you want to do, but maybe this can help...
WITH
    test1 AS
        (
            SELECT 1 "E_ID", 3 "E_QUES_ID" FROM DUAL UNION ALL
            SELECT 1 "E_ID", 4 "E_QUES_ID" FROM DUAL UNION ALL
            SELECT 1 "E_ID", 5 "E_QUES_ID" FROM DUAL UNION ALL
            SELECT 1 "E_ID", 6 "E_QUES_ID" FROM DUAL
        ),
    test_ref AS
        (
            SELECT 3 "CODE", 'May' "C_VALUE" FROM DUAL UNION ALL
            SELECT 4 "CODE", '2022' "C_VALUE" FROM DUAL UNION ALL
            SELECT 5 "CODE", 'Jun' "C_VALUE" FROM DUAL UNION ALL
            SELECT 6 "CODE", '2022' "C_VALUE" FROM DUAL
        )
SELECT
    E_ID,
    Max(LISTAGG(MY, ' ') WITHIN GROUP (ORDER BY E_ID, E_QUES_ID)) OVER() "MONTH_YEAR"
FROM
    (
        SELECT
            t.E_ID,
            t.E_QUES_ID,
            CASE WHEN t.E_QUES_ID IN(3, 4) THEN tr.C_VALUE END "MY"
        FROM
            test1 t
        INNER JOIN
            test_ref tr ON(t.E_QUES_ID = tr.CODE)
        ORDER BY
            t.E_ID,
            t.E_QUES_ID
    )
GROUP BY
    E_ID


text:
Q: Trouble installing tensorflow on linux I am having trouble while importing tensorflow in vs code in ubuntu linux. I have installed it using pip(my cpu is intel pentium g2020) and this is what I get afterimport tensorflow as tf and I get
enter image description here
also my tensorflow version is 2.7
and python version is 2.7.18

A: Maybe your env is incompatible. you can try to create a virtual env for your code ,such as :
conda create -n yourname_env


text:
Q: angular-nvd3, how to combine scatterChart and bar? I want to make a multichart using bar and scatterChart, the requirement is to show a dot above each bar representing some data.
I've tried a lot of things but none of them work, here is my current code:
$scope.options = {
    chart: {
        type: 'multiChart',
        height: 450,
        margin : {
            top: 30,
            right: 60,
            bottom: 50,
            left: 70
        },
        color: d3.scale.category10().range(),
        //useInteractiveGuideline: true,
        transitionDuration: 500,
        xAxis: {
            tickFormat: function(d){
                return d3.format(',f')(d);
            }
        },
        yAxis1: {
            tickFormat: function(d){
                return d3.format('.02f')(d);
            }
        },
        yAxis2: {
            tickFormat: function(d){
                return d3.format('.02f')(d);
            }
        }
    }
};

$scope.data = [
    {
        key: 'X',
        type: 'scatterChart',
        values: [
            { x: 1, y: 125, size: Math.random(), shape: 'circle' },
            { x: 2, y: 125, size: Math.random(), shape: 'circle' },
            { x: 3, y: 140, size: Math.random(), shape: 'circle' }
        ],
        yAxis: 1
    },
    {
        key: 'Y',
        type: 'bar',
        values: [
            {x:1, y:109, label:'C2.1'},
            {x:2, y:102, label:'C2.2'},
            {x:3, y:105, label:'C2.3'}
        ],
        yAxis: 1
    },
    {
        key: 'Z',
        type: 'line',
        values: [
            { x: 1, y: 115 },
            { x: 2, y: 120 },
            { x: 3, y: 130 }
        ],
        yAxis: 1
    }
];

The bar and line charts shows up correctly but the scatter representing the dots above the bars dont.
Thanks a lot for your help

A: here is a working plunker for a multichart with bar and scatter.
Hope that resolves your request :)
var app = angular.module('plunker', ['nvd3']);

app.controller('MainCtrl', function($scope) {
$scope.options = {
chart: {
  type: 'multiChart',
  height: 450,
  margin: {
    top: 30,
    right: 60,
    bottom: 50,
    left: 70
  },
  color: d3.scale.category10().range(),
  useInteractiveGuideline: true,
  duration: 500,
  x: function(d){return d.x;},
  y: function(d){return d.y;},
  xAxis: {
    axisLabel: 'Months',
    showMaxMin: true,
    tickFormat: function(d) {
      return d3.format(',.f')(d);
    }
  },
  yAxis: {
    axisLabel: 'Occupancies',
    axisLabelDistance: -20,
    tickFormat: function(d) {
      return d3.format(',.1f')(d);
    }
  }
}
};

$scope.data = $scope.data = [{
"key": "occ_n",
"values": [{
  "x": 1,
  "y": 0
}, {
  "x": 2,
  "y": 0
}, {
  "x": 3,
  "y": 0
}, {
  "x": 4,
  "y": 62
}, {
  "x": 5,
  "y": 4519
}, {
  "x": 6,
  "y": 7911
}, {
  "x": 7,
  "y": 14631
}, {
  "x": 8,
  "y": 15745
}, {
  "x": 9,
  "y": 3245
}, {
  "x": 10,
  "y": 0
}, {
  "x": 11,
  "y": 0
}, {
  "x": 12,
  "y": 0
}],
"type": "bar",
"yAxis": 1
}, {
"key": "occ_n_1",
"values": [{
  "x": 1,
  "y": 0
}, {
  "x": 2,
  "y": 0
}, {
  "x": 3,
  "y": 0
}, {
  "x": 4,
  "y": 726
}, {
  "x": 5,
  "y": 6000
}, {
  "x": 6,
  "y": 8205
}, {
  "x": 7,
  "y": 14596
}, {
  "x": 8,
  "y": 15129
}, {
  "x": 9,
  "y": 3396
}, {
  "x": 10,
  "y": 0
}, {
  "x": 11,
  "y": 0
}, {
  "x": 12,
  "y": 0
}],
"type": "scatter",
"yAxis": 1
}];
});

A: The type "scatterChart" does not exist in angular-nvd3. You have to specify the type "scatter".
$scope.data = [
{
    key: 'X',
    type: 'scatter',
    values: [
        { x: 1, y: 125, size: Math.random(), shape: 'circle' },
        { x: 2, y: 125, size: Math.random(), shape: 'circle' },
        { x: 3, y: 140, size: Math.random(), shape: 'circle' }
    ],
    yAxis: 1
}