Q:

An item with the same key has already been added. Is the following way Correct?

I know this is a duplicate post but my context is different.
I went through the solution for this problem from here.
And I some how changed as follows:
    private static Mutex _sessionMutex = new Mutex();
    public void OpenMySessionFactory(string conStr)
        {
            try
            {
                _sessionMutex.WaitOne();
                config = Fluently.Configure()
                .Database(MySQLConfiguration.Standard.ConnectionString(conStr))
                .Mappings(m => m.FluentMappings.AddFromAssembly(System.Reflection.Assembly.GetExecutingAssembly()))
                .BuildConfiguration();
                sessionFactory = config.BuildSessionFactory();
                _sessionMutex.ReleaseMutex();
            }
            catch (Exception)
            {
                throw;
            }
        }

Is there any impact if I implement as above?
Reason behind error :

An item with the same key has already been added

is occuring when I double click on any button that has to do something with data access using Fluent NHibernate.

A:

Note that if an exception does occur, you will never unlock the mutex (the control will jump to the catch block and skip the unlocking). Use a finally block to do this:
public void OpenMySessionFactory(string conStr)
{
    _sessionMutex.WaitOne();
    try
    {
        config = Fluently.Configure()
        .Database(MySQLConfiguration.Standard.ConnectionString(conStr))
        .Mappings(m => m.FluentMappings.AddFromAssembly(System.Reflection.Assembly.GetExecutingAssembly()))
        .BuildConfiguration();
        sessionFactory = config.BuildSessionFactory();
    }
    catch (Exception)
    {
        throw;
    }
    finally
    {
        _sessionMutex.ReleaseMutex();
    }
}


Q:

Upgraded Tortoise version, used Upgrade Working Copy, Commit then failed .svn/tmp/svn

I reinstalled windows and thus grabbed a newer copy of Tortoise (1.8) and found that I needed to use the "Upgrade Working Copy" of my local repo in order to use the features available.
After doing so I then attempted to commit and received the following error:
Can't create temporary file from template mypath /.svn/tmp/svn-XXXXXX: No such file or directory

A:

I was able to resolve this by creating the tmp folder inside of the .svn folder as it seems to have been missing.  Afterwards it appears to have committed.


Q:

How to handle JSON nested lists with python

I'm training a dataset on mask rcnn. I've annotated roughly 1500 images on labelIMG tool (https://github.com/tzutalin/labelImg).
Long story short, I need to get value of x and y co-ordinates from segmentation list in JSON files.
How can I access the list using Python programming?
OR is there any other way i can use .xml annotation on mask Rcnn.
This is form a dataset converted from VOC PASCAL to COCO. Xml were converted to JSON syntax.
Code
import json
import codecs

data = json.load(codecs.open('example.json', 'r', 'utf-8-sig'))

for i in data['annotations']:
    print(data['annotations'][0]) #want to output segmentation values in JSON files

JSON File
{
    "images": [
        {
          "file_name": "out538.png",
          "height": 720,
          "id": 20180000001,
          "width": 1280
        },
        {
          "file_name": "3 0751.jpg",
          "height": 720,
          "id": 20180000002,
          "width": 1280
        }
    ],
    "type": "instances",
    "annotations": [
        {
            "segmentation": [
            [
                935,
                372,
                935,
                554,
                1195,
                554,
                1195,
                372
            ]
            ],
            "area": 47320,
            "iscrowd": 0,
            "ignore": 0,
            "image_id": 20180000001,
            "bbox": [
            935,
            372,
            260,
            182
            ],
            "category_id": 1,
            "id": 1
        },
        {
            "segmentation": [
            [
                743,
                317,
                743,
                480,
                962,
                480,
                962,
                317
            ]
            ],
            "area": 35697,
            "iscrowd": 0,
            "ignore": 0,
            "image_id": 20180000001,
            "bbox": [
            743,
            317,
            219,
            163
            ],
            "category_id": 1,
            "id": 2
        }
    ],
    "categories": [
      {
        "supercategory": "none",
        "id": 1,
        "name": "bike"
      },
      {
        "supercategory": "none",
        "id": 2,
        "name": "Bike"
      }
    ]

}

i want values of segmentation list: e.g. 935,
                372,
                935,
                554,
                1195,
                554,
                1195,
                372
but all I'm getting is the error "list indices must be integers or slices, not dict"

A:

The i variable in your for i in data['annotations']: loop will be a dictionary, since annotations is a list of dictionaries. In order to access the segmentation list, you will need to do something like this:
for annotation in data['annotations']:
    segmentation = annotation['segmentation']
    actual_segment_data = segmentation[0]

The last line of code is necessary because segmentation is a list within a list.
This should return the following: [935, 372, 935, 554, 1195, 554, 1195, 372].


Q:

Android Problem with Eclipse

I am kind of new to android programming, and I had to reinstall eclipse because there was a problem. Now, Eclipse isn't recognizing any android commands or there are red exclamation points next to the folders. Thanks

A:

there can be multiple reasons to this..
The red exclamation mark basically means that something is wrong on the build path of the affected project. Check "context menu > Build Path > Configure Build Path..."
(e.g. make sure you have the right JRE System Library on the Libraries
tab). Or open the Problems view, group by Java Problem Type, and check
the Fatal Errors.
The build path is stored in the .classpath file. Maybe you find the
problem when you check the file's contents before and after "switching"
Android API levels.
if problem persists
Try reinstalling the jre,jdk,android sdk again


Q:

Polymer+Firebase Element - Show spinner while updating data

I'm trying to learn Polymer, but I have some questions and can't find the solutions anywhere.
I want to put a loading spinner in my app, while the data is being retrieved from firebase (using firebase-element) to fill the screen info. How can I detect that all data/elements are already loaded in light DOM, so I can hide the spinner?
I know there is a polymer-ready event, but it doesn't take in count the firebase-element data, or I guess so.
Thanks

A:

firebase-element has a dataReady property that specifies if a location's data has been loaded at least once.


Q:

Input box putting margin to right in a table with full width

When I try to put an input box in a table which has a width of 100%, it puts margin to right. I just want inputs to fit the table without expanding the table.
http://jsfiddle.net/aKznJ/1/
table {
    border-collapse: collapse;
    border-spacing: 0;
}
.fullWidth table {
    border: 1px solid #ccc;
    width: 100%;
    text-align: left;
}
.fullWidth td, .fullWidth th{
    border: 1px solid #ccc;
    padding: 3px;
}

A:

Thats how tables work, it calculates the width of each column based on how big the content is in relation to the other cells. The TextBox is larger than all the others cells text, so that column get more of the percentage.
You can add a fixed width for the cell, for example like so:

    <input type="text"/>

Here is an example

OR if you want the cells to be evenly spread, you can add a percentage to the cells with CSS like so:
table tr td {
    width: 33%;
}

Here is an example
But keep in mind that this will apply to all tables, so if different tables have different number of columns then you would need to do different ones for each table, for example:
table.threecolumns tr td {
    width: 33%;
}

table.twocolumns tr td {
    width: 50%;
}

The HTML for this might look like the following:

   ...

Here is an example


Q:

Create a temporary file, then upload it using FTP (Java webapp)

Users of my web application have an option to start a process that generates a CSV file (populated by some data from a database) and uploads it to an FTP server (and another department will read the file from there). I'm just trying to figure out how to best implement this. I use commons net ftp functionality. It offers two ways to upload data to the FTP server:

storeFile(String remote, InputStream local)
storeFileStream(String remote)

It can take a while to generate all the CSV data so I think keeping a connection open the whole time (storeFileStream) would not be the best way. That's why I want to generate a temporary file, populate it and only then transfer it.
What is the best way to generate a temporary file in a webapp? Is it safe and recommended to use File.createTempFile?

A:

As long as you don't create thousands of CSV files concurrently the upload-time doesn't matter from my point of view. Databases usually output the data row by row and if this is already the format you need for the CSV file I strongly recommend not to use temporary files at all - just do the conversion on-the-fly:
Create an InputStream implementation that reads the database data row by row, converts it to CSV and publish the data via it's read() methods.
BTW: You mentioned that the conversion is done by a web application and that it can take a long time - this can be problematic as the default web client has a timeout. Therefore the long lasting process should be better done by a background thread only triggered by the webapp interface.


Q:

How can I pass an argument to a Scala Macro Annotation impl?

I have success when the annotation's argument is a constant, like:
@Annotation(2)
class AnnotatedClass

since I can get the value in the macro's impl with:
c.prefix.tree match {
  case Apply(_, List(Literal(Constant(x)))) => x.toInt
}

But I'm stumped when the annotation's argument is not a constant, like:
object Obj {val n = 2}

@Annotation(Obj.n)
class AnnotatedClass

Similar to the false-start in this question, I can match c.prefix.tree again and pull out the names Obj and n, but how do I get the value of Obj.n?

A:

Unfortunately, at the moment it's virtually impossible. Evaluation of trees is essentially not supported by our macro system (we have c.eval, but its current implementation is slow and only works reliably with literal arguments). This is one of the things that we're experimenting with in Project Palladium.


Q:

4 column (sub)query search, get results from related table

Sorry for the strange title, but I have no idea how to put this in words.
I think it's best to give an example, there are 4 columns I want to include in this query (using DB2);
employee    keyword    employee_keyword    keyword_linked
--------    -------    ----------------    --------------
firstname   value      employee_id         key_id1
lastname    ....       keyword_id          key_id2
...                    ....                ...

Pretty straightforward really, there's an employee having a many-to-many relation with keywords, joined together by employee_keyword. The keyword_linked table 'links' keywords with eachother, so that the keyword 'IT' can be 'linked' to the keyword 'java' for example. What I would want is when someone searches for the keyword 'java', thet get all employees having 'java' as keyword + all employees that have a keyword that links to 'java' (so in this case all employees having 'IT' as a keyword). And that's where i'm stuck...
I've tried numerous queries but i'm not really getting anywhere. My current query doesn't include the keyword_linked table;
select * from TABLE e
left join TABLE.function f on (f.id = e.function_id)
left join TABLE.employee_service es on (e.id = es.employee_id)
left join TABLE.service s on (es.service_id = s.id)
left join TABLE.employee_keyword ek on (e.id = ek.employee_id)
left join TABLE.keyword k on (ek.keyword_id = k.id)
left join TABLE.employee_keyword ek2 on (e.id = ek2.employee_id)
left join TABLE.keyword k2 on (ek2.keyword_id = k2.id)
left join TABLE.employee_service es2 on (e.id = es2.employee_id)
left join TABLE.service s2 on (es2.service_id = s2.id)
and e.deleted is null

So this is my current query that needs to be expanded with the keyword_linked table. I think I have to use a subquery, where I ask all key_id2's (in thekeyword_linked table) of which the key_id1 is id of the keyword entered by the user....I hope I'm not too confusing :-)
So maybe something like this;
select e.firstname, k.value from TABLE  e
left join  employee_keyword ek on e.id = ek.employee_id
left join keyword k on k.id = ek.keyword_id
left join keyword_linked kl on k.id = kl.key_id1
where k.id in (select kkl.key_id1 from TABLE.keyword_linked kkl)

But this isn't really it. If someone could help me, that would be highly appreciated! Also can you include an explanation in your answer, queries aren't really my strong point and i'm trying to understand what i'm doing wrong.
Thnx in advanced!

A:

If you work only with explicitly interlinked keywords, the query should be as follows:
    select  emp.*
    from    employee emp
            join employee_keyword emp_kw ON emp_kw.employee_id = emp.id
    where   emp_kw.keyword_id in (
        /*keyword iteslf*/
        select  id from keyword where value = 'java'
        union
        /*keywords linked with this word*/
        select  key_id2 key_id
        from    kw_linked_x lnk
                join keyword kw on kw.id = key_id1
        where   kw.value = 'java'
        /*keywords this word is linked with*/
        union
        select  key_id1 key_id
        from    kw_linked_x lnk
                join keyword kw on kw.id = key_id2
        where   kw.value = 'java'
    )

But there's also a way to establish implicit linkage between the keywords, which should give you more value:
    with kw_linked_x  as (
        /* Ensure that key_id2 is greater than key_id1 */
        select  least(key_id1,key_id2) key_id1,
                greatest(key_id1, key_id2) key_id2
        from    keyword_linked
    )
    select  emp.*
    from    employee emp
            join employee_keyword emp_kw ON emp_kw.employee_id = emp.id
    where   emp_kw.keyword_id in
    (
        /* go down the 'tree'*/
        select  key_id1
        from    kw_linked_x lnk
                join keyword kw on KW.id = lnk.key_id1
        start with kw.value='java'
        connect by prior key_id2 = key_id1
        union
        /* go up the tree */
        select  key_id1
        from    kw_linked_x lnk
                join keyword kw on KW.id = lnk.key_id1
        start with kw.value='java'
        connect by prior key_id1 = key_id2
    )

Hope this helps.
PS: In both queries 'java' should be replaced with the keyword you are quering for.


Q:

Is GNU GRUB installed under a OS, or not under any OS?

BIOS, a boot loader, is installed not under any OS.
Is GNU GRUB, another boot loader, installed under a OS, or not under any OS?
Thanks!

A:

BIOS is not a bootloader.  It tries to load a bootloader off of a boot device.  It does this by loading the first sector of of a device.  There is not a lot of space in a device's sector, so typically, the very tiny program in this sector will load a "second stage bootloader" that is more capable, such as the Windows boot manager or GRUB.
When a bootloader has control of the system, an OS is not running.
OSes can install bootloaders - this is done by modifying the first sector of the hard drive involved to contain the first-stage bootloader code, and then placing other files where needed or expected, according to the bootloader in question.
I'm unclear whether UEFI, BIOS's replacement, can act as a bootloader - this is typically not done with Windows systems, though.  Other firmwares for other platforms such as U-Boot can understand a couple filesystems and load a kernel off of it directly - they have bootloader capability unlike the PC platform's BIOS.


Q:

Unable to modify ulimit

I am on Ubuntu 18.04
Trying to modify max number of processes (hard limit) via the following command, and getting the respective error:
$ ulimit -H -u 500
bash: ulimit: max user processes: cannot modify limit: Invalid argument

In the mean time ...
$ ulimit -Hu
46955

Any idea why?

A:

You have to lower the soft limit before you can lower the hard limit.
You can see the differences between them using the relevant flags. For example:
$ ulimit -Su
900

$ ulimit -Hu
900

Here, my hard limit and soft limit are the same. If I attempt to lower my soft limit, it succeeds:
$ ulimit -Su 800
$ ulimit -Su
800

But if I try to lower my hard limit below the soft limit, it fails:
$ ulimit -Hu 700
bash: ulimit: max user processes: cannot modify limit: Invalid argument

So, I first need to lower my soft limit so that I can set the new hard limit:
$ ulimit -Su 700
$ ulimit -Hu 700
$ ulimit -Su
700
$ ulimit -Hu
700


Q:

GetHashCode(obj): why in some cases it's designed with an argument?

I've just noticed that e.g. interface IEqualityComparer<T> provides public int GetHashCode(T obj).
I've seen more often public int GetHashCode() variant in another interfaces/classes. Why it's designed with an input argument? I understand that in 'with argument' case returned value won't be based on caller object, but method's argument. The only way it's needed seems to me to GetHashCode of null object, is it?
And the last question: what should be the caller object(i.e. owner of GetHashCode method)?
Thanks!

UPD. Marked the earliest from right existed answers as the answer. Thanks a lot!

A:

Because IEqualityComparer<T> compares other objects, not itself. Thus it needs two arguments for Equals (compare two other objects) and one argument for GetHashCode (get hash code of other object).


Q:

How to get the contents of ckeditor on change?

I have the following code for detecting changes on the ckeditor surface.
CKEDITOR.instances['editor1'].on("instanceReady", function(){
this.document.on("keyup", function(){
console.log("sth changed");
});
});

I would like to get the contents of editor on change for counting the words in it. How can I reach it using CKEDITOR.instances?

A:

The only correct way to retrieve contents of the editor is:
CKEDITOR.instances.yourInstanceName.getData();

You can also try this.on( 'key', function() { ... } ); because editor fires key events.
Additionally I recommend you the ticket regarding onchange event and monitoring changes in the editor.
And the last but not least: The wordcount plugin which has already been implemented and does your job ;)


Q:

Getting json file on angular

I'm trying to show the data collected from a json file but I do not get any output. What should I change in the code to make it work?. It's the first time I work with angular and it's costing me a lot of work. I can not find how to solve this. I appreciate your help very much.
JSON file (localhost/alertas.php):
[{
    "ID_ANUNCIO": "1",
    "TITULO": "Alerta1",
    "CUERPO": "Prueba de alerta1",
    "FECHA_INI": "2018-07-01",
    "FECHA_FIN": "2018-08-31",
    "TIPO_ANUNCIO": "1"
}, {
    "ID_ANUNCIO": "2",
    "TITULO": "Alerta2",
    "CUERPO": "No deberia mostrarse",
    "FECHA_INI": "2018-07-01",
    "FECHA_FIN": "2018-07-15",
    "TIPO_ANUNCIO": "1"
}, {
    "ID_ANUNCIO": "3",
    "TITULO": "Alerta3",
    "CUERPO": "Mostrando la alerta3",
    "FECHA_INI": "2018-07-09",
    "FECHA_FIN": "2018-10-11",
    "TIPO_ANUNCIO": "2"
}, {
    "ID_ANUNCIO": "4",
    "TITULO": "Alerta 4",
    "CUERPO": "No deberia mostrarse",
    "FECHA_INI": "2018-08-31",
    "FECHA_FIN": "2018-10-31",
    "TIPO_ANUNCIO": "2"
}]

Services:
import { Injectable } from '@angular/core';
import { ialerta } from './ialerta';
import { Http, Response } from '@angular/http';
import { map } from "rxjs/operators"

@Injectable()
export class ServicioAlertas{
    constructor(private http: Http){

    }
    getAlertas() {
        return this.http.get('http://localhost/alertas.php').pipe(map((res: Response) => res.json()));
    }
}

Interface ialerta:
export interface ialerta{
    id_anuncio: string;
    titulo: string;
    cuerpo: string;
    fecha_ini: string;
    fecha_fin: string;
    tipo_anuncio: string;
}

Components:
import { Component, OnInit } from '@angular/core';
import { ServicioAlertas } from './alertas.services';
import { ialerta } from './ialerta';

@Component({
  selector: 'app-alertas',
  templateUrl: './alertas.component.html',
  styleUrls: ['./alertas.component.css'],
  providers: [ServicioAlertas]
})
export class AlertasComponent implements OnInit {

  alertas: ialerta[] = null;
    constructor(private empService: ServicioAlertas) {
  }

  ngOnInit() {
    this.empService.getAlertas().subscribe((empData) => this.alertas = empData);
  }

}

HTML:

{{ alerta.CUERPO }}

A:

You dont have to use .data just
*ngFor = "let alerta of alertas"


Q:

RestSharp JsonDeserializer list object

I want to deserialize a JSON with array using RestSharp deserialize.
public class details
{
    public string id { get; set; }
    public string tran_id { get; set; }
    public string tran_type { get; set; }
    public string tran_status { get; set; }
    public string expiry_date_time { get; set; }
    public string number { get; set; }
}

My JSON as below:
{
"details": [
    {
        "id": "ebca66079b44",
        "tran_id": "c9b1bce025f5",
        "tran_type": "A",
        "tran_status": "B",
        "expiry_date_time": "2018-11-26T06:33:04+00:00",
        "number": "12345678ABC"
    },
    {
        "id": "ebca66079b44",7c2445c8-a5ba-4ad2-a38e-3ea682c60edf",
        "tran_id": "3ea682c60edf",
        "tran_type": "A",
        "tran_status": "B",
        "expiry_date_time": "2018-11-26T06:26:28+00:00",
        "number": "22345678ABC"
    },
    {
        "id": "ebca66079b44",
        "tran_id": "e40c45817985",
        "tran_type": "A",
        "tran_status": "B",
        "expiry_date_time": "2018-11-26T06:26:06+00:00",
        "number": "32345678ABC"
    }
]
}

And my code is:
IRestResponse response = client.Execute(request);
//Deserialize Json
return new JsonDeserializer().Deserialize<List<details>>(response);

I am able to get 'details', but not the list inside the object.

A:

You need to use an object contain your JSON array data, because the outermost layer is an object instead of an array.
public class JsonModel
{
    public List<Detail> details { get; set; }
}

public class Detail
{
    public string id { get; set; }
    public string tran_id { get; set; }
    public string tran_type { get; set; }
    public string tran_status { get; set; }
    public string expiry_date_time { get; set; }
    public string number { get; set; }
}

use like this.
new JsonDeserializer().Deserialize<JsonModel>(response);

Note
There is a json data might throw an error  from "ebca66079b44",7c2445c8-a5ba-4ad2-a38e-3ea682c60edf", data.
There is two way can create model easily.

You can use Web Essentials in Visual Studio, use Edit > Paste special > paste JSON as a class, you can easier to know the relation between Json and model.
If you can't use Web Essentials you can instead of use https://app.quicktype.io/?l=csharp online JSON to Model class.

You can try to use those models to carry your JSON Format.


Q:

Deleting a type in Common Lisp

Does Common Lisp provide a facility for undefining types created with  deftype?
I've not found anything in the Hyperspec about it.

A:

I would just unintern the derived type specifier:
T1> (deftype foo () 'fixnum)
FOO
T1> (let ((bar 1))
      (check-type bar foo))
NIL
T1> (unintern 'foo)
T
T1> (let ((bar 1))
      (check-type bar foo))

Unknown type specifier: FOO
   [Condition of type SIMPLE-ERROR]

Also, if you are really concerned about deleting every trace of the type for some reason, you can always write implementation-dependent code to achieve it, even if such functionality is not mentioned in the standard. For example, in CCL (untested, I just skimmed the relevant code):
(defun delete-type (derived-type-specifier)
  (ccl::clear-type-cache)
  (remhash derived-type-specifier ccl::%deftype-expanders%)
  (setf (documentation derived-type-specifier 'type) nil))

And here we go:
T1> (deftype foo () "frob" 'fixnum)
FOO
T1> (documentation 'foo 'type)
"frob"
T1> (let ((bar 1))
      (check-type bar foo))
NIL
T1> (delete-type 'foo)
NIL
T1> (documentation 'foo 'type)
NIL
T1> (let ((bar 1))
      (check-type bar foo))

Unknown type specifier: FOO
   [Condition of type SIMPLE-ERROR]


Q:

Simple encoder by a beginner

I decided to make a quick little encoder in Python as a little challenge for myself. I decided to submit my program as I am very interested in improving my programming skills and learning better ways to code. My program simply asks for a string and for a key. The key could be +3, +4, etc. The key will add the number inputted to the number corresponding to each letter, then return the new letters.
dic = {"A": 0, "B": 1, "C": 2, "D": 3, "E": 4, "F": 5, "G": 6, "H": 7, "I": 8, "J": 9, "K": 10, "L": 11, "M": 12, "N": 13, "O": 14, "P": 15, "Q": 16, "R": 17, "S": 18, "T": 19, "U": 20, "V": 21, "W": 22, "X": 23, "Y": 24, "Z": 25, " ": 26}
dic2 = {}
for x,v in dic.items():
    dic2[v] = x

program = True

while program:
    list = []
    encodeNums = []
    encodeStr = []
    task = input("Would you like to encode or decode?: ").lower()
    if task == "encode":
        string = input("What would you like to encode?: ").upper()
        key = input("What key would you like to use?: ")
        for x in string:
            list.append(dic[x])
        for x in list:
            encodeNums.append(eval("{}{}".format(x,key)) % 27)
        for x in encodeNums:
            encodeStr.append(dic2[x])
        print("".join(encodeStr))

A:

I'd highly suggest learning comprehensions. The simplest is a list comprehension. This allows you to change say:

list = []
for x in string:
    list.append(dic[x])

To:
list = [dic[x] for x in string]

However, you can get better memory usage by using a generator comprehension, this works in roughly the same way as a list, however you can't index it. Which for this code is fine. To do this replace the square brackets with curved ones:
gen = (dic[x] for x in string)

You can also use a dictionary comprehension to simplify your creation of dic2:
dic2 = {v: k for k, v in dic.items()}

Purge all memory of eval, it leads to poor code and has severe security vulnerabilities. Instead cast the users input to an int. This can simplify decoding too. However you have to make sure the user does actually enter a number.
I don't like list = [] being outside the if statement. There's not much of a need for this. However it's fixed when using comprehensions.
I also think you should use while True rather than while program:. As you never change program.

Merging this all together gets you:
dic = {"A": 0, "B": 1, "C": 2, "D": 3, "E": 4, "F": 5, "G": 6, "H": 7, "I": 8, "J": 9, "K": 10, "L": 11, "M": 12, "N": 13, "O": 14, "P": 15, "Q": 16, "R": 17, "S": 18, "T": 19, "U": 20, "V": 21, "W": 22, "X": 23, "Y": 24, "Z": 25, " ": 26}
dic2 = {v: k for k, v in dic.items()}

while True:
    task = input("Would you like to encode or decode?: ").lower()
    if task == "encode":
        string = input("What would you like to encode?: ").upper()
        while True:
            try:
                key = int(input("What key would you like to use?: "))
                break
            except ValueError:
                pass
        list = (dic[x] for x in string)
        encodeNums = ((x + key) % 27 for x in list)
        encodeStr = (dic2[x] for x in encodeNums)
        print("".join(encodeStr))

Going forward, I'd change your code to encode and decode with the same code. This is as the Caesar cipher is a symmetric cypher, so simply using key = -key allows you to decode the encoding.
Allowing:
dic = {"A": 0, "B": 1, "C": 2, "D": 3, "E": 4, "F": 5, "G": 6, "H": 7, "I": 8, "J": 9, "K": 10, "L": 11, "M": 12, "N": 13, "O": 14, "P": 15, "Q": 16, "R": 17, "S": 18, "T": 19, "U": 20, "V": 21, "W": 22, "X": 23, "Y": 24, "Z": 25, " ": 26}
dic2 = {v: k for k, v in dic.items()}

while True:
    string = input("What would you like cypher?: ").upper()
    task = input("Would you like to encode or decode?: ").lower()
    while True:
        try:
            key = int(input("What key would you like to use?: "))
            break
        except ValueError:
            pass
    if task == "decode":
        key = -key

    list = (dic[x] for x in string)
    encodeNums = ((x + key) % 27 for x in list)
    encodeStr = (dic2[x] for x in encodeNums)
    print("".join(encodeStr))


Q:

PHP How to change text encoding of a CSV file

I have a CSV file that I need to change the encoding of. I want to be able to do this using PHP. I know there is the mb_convert_encoding function but that is only for strings.
Is there a function I can use to change the encoding of an entire csv file?
Cheers,
Updates: Turns out the solution to my problem would be to remove the BOM from my file.
I am using @treehouse code below and modified it to replace bom but it just fills the temp file forever whats wrong?
$sourcePath = 'EstablishmentExport.csv';
$tempPath = $sourcePath . 'temp';
$source = fopen($sourcePath, 'r');
$target = fopen($tempPath, 'w');
while(!feof($source)) {
    $line = preg_replace('/[\x00-\x1F\x80-\xFF]/', '', $source);
    fwrite($target, $line);
}
fclose($source);
fclose($target);
unlink($sourcePath);
rename($tempPath, $sourcePath);

A:

Since you are dealing with a very big file I suggest leaving this task to the operating system by the means of exec, shell_exec or bactick operator.
See here about methods on how to do just that
http://mindspill.net/computing/linux-notes/determine-and-change-file-character-encoding/
Best way to convert text files between character sets?
Example:
shell_exec ( 'iconv -f utf-16le -t utf-8 1.csv > 2.csv' );


Q:

Extract value from JSON with key name includes # in bigquery

I have a table called test in bigquery. It has one column called attributes.
The value is in JSON with "# of items" being the key, for example: {"# of items": "100"}
When I executed the query below
SELECT JSON_EXTRACT(attributes, "$['# of items']") AS num_items
FROM test
I hit the following error:
Error: JSONPath parse error at: ['# of items']
what is the easiest way to access its value?

A:

It fails for BigQuery Legacy SQL
Use BigQuery Standard SQL instead and you will be fine
#standardSQL
WITH `project.dataset.test` AS (
  SELECT '{"# of items": "100"}' AS attributes
)
SELECT JSON_EXTRACT(attributes, "$['# of items']") AS num_items
FROM `project.dataset.test`

with result as
Row num_items
1   "100"

If for some reason you are bound to BQ Legacy SQL - use below trick
#legacySQL
SELECT JSON_EXTRACT(REPLACE(attributes, '"# of items"', "'number of items'"), "$['number of items']") AS num_items
FROM [project:dataset.test]


Q:

How to specify sbt dependency along with the intended JDK version

How do I specify the JDK version of a dependency in my Build.sbt?
I encounter such a case with the Aspose library, where the filename is postfixed with JDK version, i.e. aspose-email-4.8.0-jdk17.jar instead of the plain aspose-email-4.8.0.jar. So, specifying the dependency normally, e.g.
"com.aspose" % "aspose-email" % "4.8.0"

will cause sbt to complain with the following error, as the poor SBT tries to download a non-existing file:
[warn]  [FAILED     ] com.aspose#aspose-email;4.8.0!aspose-email.jar:  (0ms)
[warn] ==== local: tried
[warn]   /Users/developer/.ivy2/local/com.aspose/aspose-email/4.8.0/jars/aspose-email.jar
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/com/aspose/aspose-email/4.8.0/aspose-email-4.8.0.jar
[warn] ==== Aspose: tried
[warn]   http://maven.aspose.com/artifactory/simple/ext-release-local/com/aspose/aspose-email/4.8.0/aspose-email-4.8.0.jar
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::              FAILED DOWNLOADS            ::
[warn]  :: ^ see resolution messages for details  ^ ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: com.aspose#aspose-email;4.8.0!aspose-email.jar
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
sbt.ResolveException: download failed: com.aspose#aspose-email;4.8.0!aspose-email.jar

Update
Then I figured that appending the JDK version to the version number might fix it:
"com.aspose" % "aspose-email" % "4.8.0-jdk17"

Unfortunately it will to another error caused by SBT thinking the POM file is located at aspose-email-4.8.0-jdk17.pom, while it should instead be aspose-email-4.8.0.pom.
[info] Resolving com.aspose#aspose-email;4.8.0-jdk17 ...
[warn]  module not found: com.aspose#aspose-email;4.8.0-jdk17
[warn] ==== local: tried
[warn]   /Users/ganeshwara/.ivy2/local/com.aspose/aspose-email/4.8.0-jdk17/ivys/ivy.xml
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/com/aspose/aspose-email/4.8.0-jdk17/aspose-email-4.8.0-jdk17.pom
[warn] ==== Aspose: tried
[warn]   http://maven.aspose.com/artifactory/simple/ext-release-local/com/aspose/aspose-email/4.8.0-jdk17/aspose-email-4.8.0-jdk17.pom
[info] Resolving net.sf.proguard#proguard-base;5.1 ...
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  ::          UNRESOLVED DEPENDENCIES         ::
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]  :: com.aspose#aspose-email;4.8.0-jdk17: not found
[warn]  ::::::::::::::::::::::::::::::::::::::::::::::
[warn]
[warn]  Note: Unresolved dependencies path:
[warn]    com.aspose:aspose-email:4.8.0-jdk17 (/Users/ganeshwara/DropMyEmail/backup-server/project/Build.scala#L290)
[warn]      +- Dropmysite:common_2.11:1.0-296020c84e74fa1fd65cd5361b563519ff9c4a5d
sbt.ResolveException: unresolved dependency: com.aspose#aspose-email;4.8.0-jdk17: not found

I think if you look into the repo, you'll see that the problem is due to differing naming convention - where the jarfile is postfixed with the intended JDK version but the POM file is not.

A:

After some googling, I've found that Maven actually has an optional extra coordinate, the classifier, which is appended just after the version number (source).
To use it in sbt, you should define your dependency as
"com.aspose" % "aspose-email" % "4.8.0" classifier "jdk17"

(source)


Q:

Chromatic number transition for random graphs?

If one plotted the chromatic number $\chi( G_n(p) )$ of an
Erdős-Rényi random
graph $G_n(p)=G(n,p)$, for a fixed $n$, with respect to probability $p$, what would it
look like? For sufficiently large $n$, is there a significant change
from low $\chi$ to large $\chi$ at some transition probability $p^*$?
And if so, where is that transition probability $p^*$, as a function of $n$?
I assume this is all known, or at least well-studied ...

A:

For convenience, define $b = \frac1{1-p}$. Then we have $$\chi(G_{n,p}) \sim \frac{n}{2 \log_b np}$$ with high probability, which is shown for constant $p$ in (Bollobás, 1988) and for $p \gg \frac1n$ in (Łuczak, 1991).
To give some intuition for this value, the denominator $2 \log_b np$ is the asymptotic value of the independence number $\alpha(G_{n,p})$. So in the random graph, we can take almost all color classes to be almost as large as the maximum possible color class.
The second of these papers also proves bounds on $\chi(G_{n,p})$ when $p = \frac dn$, but we now know much more about that case from (Achlioptas and Naor, 2005). Here, we know that $\chi(G_{n,p})$ is one of two values $\{k_d, k_{d}+1\}$ with high probability, where $k_d$ is the least integer $k$ satisfying $d < 2k\log k$.
(The chromatic number sort of shuffles probability mass from one of these values to the other sufficiently slowly that you "can catch it in the middle" when it can be either value with positive probability; for many values of $d$, we can actually say that it's one or the other.)


Q:

The implication $\sqrt{(x-2)^2+(y-1)^2+(z-1)^2+(w-3)^2}<b\implies |xyzw-6|<a$

Given a real number $a>0$ find a $b>0$ such that
$\sqrt{(x-2)^2+(y-1)^2+(z-1)^2+(ω-3)^2}<b\Longrightarrow |xyzω-6|<a$
I tried the procedure followed in another one of my questions, but it doesn't work.

A:

It seems the following.
The question seems to be a numerical adjustment of the continuity of multiplication.  Assume that $$\sqrt{(x-2)^2+(y-1)^2+(z-1)^2+(w-3)^2}<b.$$ Then $|x-2|<b$, $|y-1|<b$, $|z-1|<b$, and $|w-3|<b$.
We have $2\cdot 1\cdot 1\cdot 3=6$ and
$$|xyzw-6|\le$$ $$|xyzw-xyz\cdot 3|+|xyz\cdot 3-xy\cdot 2\cdot 3|+$$ $$|xy\cdot 2\cdot 3 - x\cdot 1\cdot 2\cdot 3|+
|x\cdot 1\cdot 2\cdot 3- 1\cdot 1\cdot 2\cdot 3|=$$ $$
|xyz|\cdot|w-3|+|xy||z-2|\cdot 3+|x||y-1|\cdot 2\cdot 3+
|x- 1|\cdot 1\cdot 2\cdot 3<$$ $$|xyz|\cdot b+|xy|\cdot b\cdot 3+|x|\cdot b \cdot 6+
b \cdot 6.$$
If we additionally assume that $b<1$ then $1<x<3$,  $0<y<2$, $0<z<2$, and $2<w<4$. Hence
$$|xyz|\cdot b+|xy|\cdot b\cdot 3+|x|\cdot b \cdot 6+b \cdot 6<
3\cdot 2\cdot 2\cdot b+3\cdot 2\cdot b\cdot 3+3\cdot b \cdot 6+b \cdot 6=
54b.$$
Thus it suffices to put $b=\min\{1, a/54\}$.
Update. Such breaking down is a standard trick, used in analysis and based on the triangle inequality.
The usage of $\min$ is a standard and simple act to show that $b$ should be small. The smallness is typical here,   because the continuity of function in a point is based on its behavior in small neighborhoods of this point. If we reject this approach, we may obtain a formula for $b$, which uses a polynomials or roots of $a$ and which is more complex than the minimum of a constant and a linear function.
For instance,  we have $|x|<2+b$, $|y|<1+b$, $|z|<1+b$, and $|w|<3+b$. Then
$$|xyz|\cdot b+|xy|\cdot b\cdot 3+|x|\cdot b \cdot 6+b \cdot 6<$$
$$(2+b)(1+b)^2\cdot b+(2+b)(1+b)\cdot b\cdot 3+(2+b)\cdot b \cdot 6+b \cdot 6=$$ $$
b(b^3+13b^2+23b+17)<b(b^3+15b^2+75b+125) = b(b+5)^3.$$
Then for the given $a$ we have to find $b$ such that  $b(b+5)^3<a$. It suffices to put $b=\frac a{a+6^3}$. Indeed,
$$\frac a{a+6^3}\left(\frac a{a+6^3}+5\right)^3<\frac a{a+6^3}6^3<a.$$
We can deal with your next inequality as follows. Put $$f=\sqrt{(x-2)^2+(y-1)^2+(z-1)^2}.$$ For given $a>0$ similarly to the above we find positive $b_1, b_2, b_3$ such that
$f<b_1$ implies $|x^2yz−4|<a/\sqrt{3},$
$f<b_2$ implies $|xy^2z−2|<a/\sqrt{3},$
$f<b_3$ implies $|xyz^2−2|<a/\sqrt{3}.$
Then if $f<\min\{b_1, b_2, b_3\}$ we have $$\sqrt{(x^2yz−4)^2+(x y^2z−2)^2+(xyz^2−2)^2}<\sqrt{3\cdot a^2/3}=a.$$
If you insist on avoiding $\min$, you can put $b=\frac{b_1b_2b_3}{b_1b_2+b_1b_3+b_2b_3}<\min\{b_1, b_2, b_3\}$.


Q:

How does angular escape bound values?

Let's take this simple angular snippet:
<input type="text" ng-model="name" />

Hello {{name}}

If I enter the text  it looks as this is not executed but displayed as is. But if have a look at the generated HTML I see the script tag without any escapes.
I expected to see the angular brackets as HTML escape characters. So how does angular make sure this code is not executed?
(See Plunker http://plnkr.co/DeUCP74RZSGE2ypLqyRY)

A:

It is actually html encoding it, which is why it isn't running. If you're using the chrome dev tools, it is showing them as regular angle brackets just for readability.
If you right click on the value and click "Edit as HTML", you'll see the content html encoded.


Q:

Order of evaluation example

I'm trying to set in my mind once and for all how expressions are being evaluated. And with this quest of mine I came up with this example which I don't know what to make of.
#include <iostream>
using namespace std;
typedef void(*func)(int);

void r( int i )
{
    cout << i << endl;
}
func f( int i )
{
   cout << i << endl;
   return &r;
}

int main()
{
   int i = 0;
   f(++i)(++i);
   return 0;
}

Having this piece of code compiled with MVSC 2008 will produce this output: 2 2. The same code but compiled with gcc 4.8.1 will raise an warning(operation on i may be undefined) and will produce this output: 1 2.
What I'm trying to understand is why gcc 4.8.1 considers that there might be a case of undefined behavior? The side-effects of both pre-increments are sequenced relative to each other.
Cheers,
Andrei

A:

The side-effects of both pre-increments are sequenced relative to each other.

No they're not. Each argument evaluation is sequenced before its function call, and the function calls are sequenced with each other; but both could be evaluated before the first call, in which case there's nothing to sequence them with each other.


Q:

Look up python dict value by expression

I have a dict that has unix epoch timestamps for keys, like so:
lookup_dict = {
    1357899: {} #some dict of data
    1357910: {} #some other dict of data
}

Except, you know, millions and millions and millions of entries. I'd like to subset this dict, over and over again. Ideally, I'd love to be able to write something like I can in R, like:
lookup_value = 1357900
dict_subset = lookup_dict[key >= lookup_value]
# dict_subset now contains {1357910: {}}

But I confess, I can't find any actual proof that this is something Python can do without having, one way or the other, to iterate over every row. If I understand Python correctly (and I might not), key lookup of the form key in dict uses binary search, and is thus very fast; any way to do a binary search, on dict keys?

A:

To do this without iterating, you're going to need the keys in sorted order. Then you just need to do a binary search for the first one >= lookup_value, instead of checking each one for >= lookup_value.
If you're willing to use a third-party library, there are plenty out there. The first two that spring to mind are bintrees (which uses a red-black tree, like C++, Java, etc.) and blist (which uses a B+Tree). For example, with bintrees, it's as simple as this:
dict_subset = lookup_dict[lookup_value:]

And this will be as efficient as you'd hope—basically, it adds a single O(log N) search on top of whatever the cost of using that subset. (Of course usually what you want to do with that subset is iterate the whole thing, which ends up being O(N) anyway… but maybe you're doing something different, or maybe the subset is only 10 keys out of 1000000.)
Of course there is a tradeoff. Random access to a tree-based mapping is O(log N) instead of "usually O(1)". Also, your keys obviously need to be fully ordered, instead of hashable (and that's a lot harder to detect automatically and raise nice error messages on).
If you want to build this yourself, you can. You don't even necessarily need a tree; just a sorted list of keys alongside a dict. You can maintain the list with the bisect module in the stdlib, as JonClements suggested. You may want to wrap up bisect to make a sorted list object—or, better, get one of the recipes on ActiveState or PyPI to do it for you. You can then wrap the sorted list and the dict together into a single object, so you don't accidentally update one without updating the other. And then you can extend the interface to be as nice as bintrees, if you want.


Q:

Need to identify correct searchVIew Listener method for button to prepare to close searchView

Need to get the right searchView Listener method to place my code to change my erase typed up search result (round X) button to become a close the searchView entirely white (X) button.
Here's my code to create searchView in action bar:
@Override
public boolean onCreateOptionsMenu(final Menu menu) {

 MenuItem item =menu.findItem(menuSearch);
    final  SearchView searchView = (SearchView) item.getActionView();

In the 1st picture when I tap on the Search Icon, the following pops up and my code for it:
    searchView.setOnSearchClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

     ImageView searchClose = searchView.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
            searchClose.setImageResource(R.drawable.ic_close_black_24dp);

        }
    });

So you can click on the (X) above and just close the searchView. Or you can start typing on the keyboard to search and you get the following: Notice now the (X) turned into a (round X) which means to delete what you're typing in keyboard.

Here's the code for above:
       @Override
        public boolean onQueryTextChange(String newText) {

            ImageView searchCancel = searchView.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
            searchCancel.setImageResource(R.drawable.ic_cancel_black_24dp);

            return false;
        }
    });

Now, if I click that (round X) again, I need it to go back to the original white (X) to be able to close the searchView Completely. So i'd need to use the first code with R.drawable.ic_close_black_24dp again.
It doesn't work on the following methods:
   searchView.setOnQueryTextListener
   searchView.setOnCloseListener

I know the right code, I'm just missing the right searchView Listener method. Which Listener method do I use to turn that (round X) back to white (X) when the (round X) is clicked on.
(I hope I explained it thoroughly, if not, I'd like my searchView to work like in Snapchat, you'll see it uses 2 different X's, one to delete what user typed, one to close the searchView completely).
So I just need the correct Listener method to use not the code that goes inside the method.

A:

onQueryTextChange() is called when input is cancelled with a zero-length string. In essence, you want to show one type of "X" is the length is zero-length, otherwise, another type.  Something like this:
@Override
public boolean onQueryTextChange(String newText) {
    ImageView searchCancel =
            searchView.findViewById(android.support.v7.appcompat.R.id.search_close_btn);
    searchCancel.setImageResource(
            (newText.length() > 0)
            ? R.drawable.ic_cancel_black_24dp:
            : R.drawable.[the other type of "X"]);
    return false;
}


Q:

How to generate a word file programmatically from collected data in iPhone sdk

I have an iPhone app consisting of a few forms in which I collect data from users. Now at the end of these forms, after user has filled all data, I want that all the collected data is exported and a MS word .doc file is generated. The data too is not simple text. There are headings, tables along with normal text in it. Is there any way I can accomplish this?

A:

Short answer yes, long answer:
You can't do this to create "proper" Word documents, however you should be able to acomplish this on any platform by building the word doc from HTML and saving it with a .doc extension (instead of HTML). You can put anything in there, custom layouts - I'd probably stick to paragraphs and tables and floated elements (like imgs and such).
There may be extra code you will need in the HTML doc (for instance to make it open in page view rather than in HTML view) but you can figure all that out by saving a word doc in HTML format. :) There's also a lot of information on the internet about it if you know where to look.
I did something like this not long ago. I'll see if I can find an example and post it here.
Update
This is the only "custom" stuff I have in my html word doc:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns:v="urn:schemas-microsoft-com:vml"
    xmlns:o="urn:schemas-microsoft-com:office:office"
    xmlns:w="urn:schemas-microsoft-com:office:word"
    xmlns="http://www.w3.org/TR/REC-html40">

And this - to make it open in Page view:
<!--[if gte mso 9]><xml>
     <w:WordDocument>
      <w:View>Print</w:View>
      <w:Zoom>100</w:Zoom>
     </w:WordDocument>
    </xml><![endif]-->

The rest of it is just standard HTML and CSS (remember to put CSS INSIDE the HTML document in <style> tags - word isn't going to remotely fetch your css files).


Q:

Dual screen with JUST extended desktop

Im using a dual monitor set-up a lot, but i have a problem. I need to forbid to clone the dektop, i want to use just the extended desktop feature. Can it be done somehow?
It's a problem because, when is start my system with two monitor it starts automaticaly with cloned desktop. When i use the hotkey to switch beatween monitors the same problem occours. Always going to the screen resolution options is pain in the *.
I have a intel hd3000 videocard (sandy bridge)
Thanx a lot

A:

Don't use hotkeys, set it in xorg.conf or a configuration utility.
Try: system settings -> displays -> detect (once it's connected)
Then you can switch your screen orientation and enable displays.


Q:

Can I load and unload gallery with jQuery?

I'm making a portfolio site in which each project expands on click and inside there's a image gallery.
The problem I'm facing is that the site gets pretty slow once many images are loaded. Is there a way to load the content on click and once I click some other project, the previous gallery content to be completely unloaded ?
I'm not very experienced with jQuery so an example of this would help a lot.

A:

Once you click, create a new div, load everything you want to show inside that div and show it to the user. Have a button there to close it. Once you do, destroy the div.
To create the div read: Creating a div element in jQuery
To destroy it just $('#div_id').remove();


Q:

How can I be successful at Lana's trial?

I reached Lana's trial in Pokemon Ultra Sun, and I chose Litten as my starter Pokémon. I have been defeated countless times, and my team consists of a Torracat, Flaafy, and a Pichu. What would you suggest that I do to win against the Araquanid and the Dewpider?

A:

First let's look at Araquanid's weaknesses.
It has the double type of water/bug, so it is weak against electric, flying and rock moves. Torracat has none of these, but you have Flaaffy and Pichu as electric pokémon, so that's a good starting point.
A second thing to know is stat-related: Araquanid has a low base speed. Even when this stat is powered-up at the start, it stays quite slow.
But here's three problems:

Flaaffy has a good special attack stat, but it will not be faster after Araquanid's power-up.
Pichu is quite weak in special attack (as it is a baby-stage pokémon), however it will be faster than Araquanid.
Neither has very powerful electric moves.

Knowing that Araquanid is at level 20, I'm guessing your pokémon are around this level.
So I will conclude with some tips based on your situation:

Level up your team. Flaaffy evolves at 30 into Ampharos and Pichu evolves with happiness into Pikachu. Both are, of course, stronger.
Teach Charge Beam (TM57) to Flaaffy and Pichu, that move should be more powerful than anything they should know at that point. This move can be found at Brooklet Hill, at the south of the second trial pond. (So the trial you are currently trying to do)

And I will end with more general advice for anyone with the same problem but with a different team:

Level up your team.
Use healing items, like Super Potion.
During the battle, Araquanid can summon a Dewpider or Masquerain. I think the best strategy would be to focus only on Araquanid to defeat it as fast as you can.
Catch fast pokémon with electric moves, preferably electric type pokémon giving a power bonus of x1.5 at electric moves (This mechanic is called STAB). Araquanid is also weak against flying and rock type moves, but it has water and ice attacks, so flying and rock type pokémon could be defeated easily.
Give your pokémon berries (such as Sitrus Berry), which can heal them when their HP decreases below 50%. However watch out for Bug Bite from the helper Dewpider and Masquerain who will upon successfully hitting your pokemon with this move eat the held berry.


Q:

iCalendar YEARLY rrule without BYMONTH value

I am building something that takes an icalendar event and calculate all occurrences of a repeating event.
I have discovered a problem which returns me a few YEARLY events every month.
Those event has a yearly frequency but only have bymonthday without bymonth value.
Is this specified in the RFC-5545 or is this just a bug from my calendar tool. (PS: This is actually in my Google Calendar and this event displays correctly there)
BEGIN:VEVENT
DTSTART;VALUE=DATE:20110814
DTEND;VALUE=DATE:20110815
RRULE:FREQ=YEARLY;BYMONTHDAY=14
DTSTAMP:20170328T223152Z
UID:388B4AE8602346DAA7BD9C1906FC390200000000000000000000000000000000
CREATED:20110610T073603Z
DESCRIPTION:
LAST-MODIFIED:20160811T230008Z
LOCATION:
SEQUENCE:0
STATUS:CONFIRMED
SUMMARY:Some BDAY
TRANSP:OPAQUE
CATEGORIES:http://schemas.google.com/g/2005#event
BEGIN:VALARM
ACTION:AUDIO
TRIGGER:-P1DT15H
ACKNOWLEDGED:20160811T230006Z
ATTACH;VALUE=URI:Basso
UID:26C6C0F7-8B77-4E20-8EFD-E82A614B0751
X-WR-ALARMUID:26C6C0F7-8B77-4E20-8EFD-E82A614B0751
END:VALARM
BEGIN:VALARM
ACTION:NONE
TRIGGER;VALUE=DATE-TIME:19760401T005545Z
END:VALARM
END:VEVENT

A:

In the RFC 5545 - page 44 to be exact - the BYMONTHDAY is specified to expand a yearly rule, i.e. to generate more results that only 1 per year.
Furthermore on the next page it gives an example of how a rrule must be evaluated:

DTSTART;TZID=America/New_York:19970105T083000
  RRULE:FREQ=YEARLY;INTERVAL=2;BYMONTH=1;BYDAY=SU;BYHOUR=8,9;
  BYMINUTE=30

First, the "INTERVAL=2" would be applied to "FREQ=YEARLY" to
    arrive at "every other year".  Then, "BYMONTH=1" would be applied
    to arrive at "every January, every other year".  Then, "BYDAY=SU"
    would be applied to arrive at "every Sunday in January, every
    other year".  Then, "BYHOUR=8,9" would be applied to arrive at
    "every Sunday in January at 8 AM and 9 AM, every other year".
    Then, "BYMINUTE=30" would be applied to arrive at "every Sunday in
    January at 8:30 AM and 9:30 AM, every other year".

As you can see, even if FREQ is YEARLY, the rule will return "every Sunday in January at 8AM and 9AM, every other year", i.e. much more than 1 occurrence every two year. That is in a nutshell the concept of expanding the behavior of FREQ.
Now applying to this rule:

RRULE:FREQ=YEARLY;BYMONTHDAY=14

It means "every 14th of the month, every year". So you will get 12 occurrences per year.
Edit: That being said, after re-reading the RFC, the definition of BYMONTHDAY is:

The BYMONTHDAY rule part specifies a COMMA-separated list of days of the month.

This could be interpreted as "list of days of the month" as in "only the month specified by DTSTART property". However this interpretation does not make sense with other values of FREQ (MONTHLY, DAILY, etc.), so that would be a special case only for FREQ=YEARLY and BYMONTH is missing... Personally I do not believe it is correct, but I must admit the RFC is slightly ambiguous.
Unfortunately there isn't any example of BYMONTHDAY with FREQ=YEARLY without BYMONTH, so there is no clear definite answer
Conclusion: To avoid any problem you should add a BYMONTH if you want only "the 14th of a given month".
Answer to your comment
The rule "FREQ=MONTHLY;BYMONTHDAY=14" indeed produces the same result. The differences would appear with INTERVAL greater than 1, or other BYxxx.


Q:

Get IMEI for iOS7 programmatically

in XCode 4.6, iOS 6.1, we use CoreTelephony to obtain IMEI, the same way mentioned in get IMEI on iPhone with CoreTelephony? question, but after switching to iOS7 and XCode 5 it doesn't work anymore.
My system considers IMEI as an unbreakable way to identify a cellphone and guarantee it is linked to a specific user, also other security issues depend on this identifier.
With the new iOS the code is not working and we hadn't found a way to obtain it.
My central question is: What options do I have to obtain IMEI in iOS7 / XCode 5?
Variations are:
 - How else could I guarantee a cellphone belongs to a specific person? Identity is very important in my system and ownership of device is a requisite.
 - What other options do we have to keep secure the system without the need to rewrite too much?

A:

Unless there is a private API solution found - our organization is moving forward with placing the IMEI and phone# into our Enterprise Applications as a guarded Application Settings.
With the new camera based barcode recognition of iOS7 - the IMEI can even be scanned from the phone box during initial kitting and deployment rather than entered by hand.
We also considered  tracking the identifierForVendor UUID in a database etc. linking to IMEI/Phone# but since it can change and since our historical data is all IMEI based - didn't make sense to add that layer of tracking complexity to a semi-useless identifier that doesn't trace back to a universal meaningful tracking mechanism like Phone/IMEI.


Q:

How to get min by value only in Scala Map

I have a map that has SomeClass -> Double I want to get the SomeClass associated with the smallest value. How do I go about doing this? Ties do not matter and can be broken arbitrarily if that is an issue.

A:

Use minBy:
Map("a" -> 3.0, "b" -> 1.0, "c" -> 2.0).minBy(_._2)._1

This gives "b" as expected.


Q:

Non seulement... mais (aussi) : surenchère et opposition, avec ou sans adverbe après la conjonction ?

On voit que quelqu'un comme Cicéron employait non solum... sed etiam (non seulement... mais aussi), ainsi que non solum... sed (non seulement... mais). Au TLFi on remarque que dans ce contexte d'opposition ou de gradation positive avec non seulement, le deuxième terme est fréquemment coordonné avec mais (mais encore, mais aussi, mais même, mais en outre, mais en plus, mais également). Larousse a deux entrées : l'une traitant l'opposition avec non seulement... mais encore(aussi), et l'autre indiquant l'opposition et le renforcement avec non seulement... mais encore. La BDL en relève trois (...mais encore/aussi/en outre) au titre de la surenchère. Le LBU14 (Grevisse et Goosse, ed. Duculot, §§ 1027, 1029) note qu'en l'absence de second terme pour l'opposition, on utilise pas seulement au lieu de non seulement, alors que non n'est pas remplaçable quand non seulement est en tête d'une sous-phrase qui s'oppose à une autre et on propose l'exemple :

(A) Non seulement elle le supporte, mais elle l'aime.

Il m'apparaît difficile d'ajouter aussi ici et je ne sais pas exactement pourquoi (...mais elle l'aime aussi, comme quelqu'un d'autre l'aime ?? ; ...mais aussi elle l'aime, bizarre ? ; ...mais l'aime-t-elle aussi, demanderait une inversion du verbe au premier terme pour être usuel ?).

On peut explorer des variantes de présentation du premier et du deuxième terme :

(1) Non seulement le meilleur, mais aussi le plus abordable.(2) Non
  seulement le meilleur, mais le plus abordable.(3) C'est non
  seulement le meilleur, mais c'est aussi le plus abordable.(4) C'est
  non seulement le meilleur, mais aussi le plus abordable.(5) C'est
  non seulement le meilleur, mais le plus abordable.(6)
  C'est pas seulement le meilleur, c'est le plus abordable !

On a employé cela est, différemment d'avec (A). On n'est pas nécessairement plus éclairé...

En quoi consiste la différence entre l'emploi de la locution en
opposition et l'emploi en surenchère et est-ce relié à la syntaxe, à l'adverbe qui suit la conjonction mais, à la sémantique ou s'agit-il du même concept qu'on aborde différemment ?

À quoi ressemblerait un emploi marquant exclusivement l'opposition  et non la surenchère ?

Y a-t-il une différence entre la tournure non seulement... mais sans adverbe, et
celle suivie d'un adverbe (aussi, encore), ou la première n'est-elle que la deuxième par ellipse de celui-ci ?
L'ajout de aussi dans (A) changerait-il le sens et
affaiblirait-il même l'idée de surenchère ; pourquoi ça semble moins important avec (1-6), le cas échéant ?

A:

Pour la première question : par sa construction, Non seulement... mais... est une opposition, mais au sens que peut avoir non... mais... dans d'autres usages. "Il faut parler à son interlocuteur non comme à un inférieur ou un supérieur mais comme à un égal". Non ce qui est faux, mais ce qui est vrai.
La tournure non seulement... mais... utilise donc le gabarit de l'opposition non... mais... pour en faire une surenchère.
Dans l'exemple (A), ce qui est faux = "seulement elle le supporte" (tournure qui, hors de la locution non seulement, est incorrecte, mais dont le sens est clair : elle ne fait que le supporter), ce qui est vrai = en plus de le supporter, elle l'aime.
On passe de "non ce qui est faux, mais ce qui est vrai" à "non seulement ce qui est vrai, mais ce qui est vrai aussi". Un emploi exprimant purement l'opposition se passerait tout simplement donc de seulement, uniquement et de leurs cousins pour ne garder que non... mais....
Pour la deuxième question, l'adverbe aussi, encore, en plus... est purement optionnel et ne change pas grand chose au sens. Il ajoute tout au plus de l'emphase. "Non seulement elle le supporte, mais en plus elle l'aime !" exprime bien plus l'incrédulité ou l'étonnement que "Non seulement elle le supporte, mais elle l'aime."
Enfin, ajouter aussi dans (A) affaiblirait peut-être le sens (en fait, je trouverais surtout la phrase maladroite), mais en plus est tout à fait à sa place. Cela tient peut-être à l'ambiguïté du sens de aussi qui peut sous-entendre qu'elle l'aime en plus d'autres personnes. Dans les autres exemples, cette ambiguïté n'est pas présente : c'est aussi le plus abordable, même si on sous-entend c'est par ellipse, est tout à fait clair : aussi se rapporte forcément aux autres qualités du produit, pas à un autre produit qui serait aussi abordable. Ce dernier point me semble toutefois assez subjectif.


Q:

CORE DATA objectId changes constantly

I have some data that I export into an XML file and put in a remote FTP Server.
I have to identified each object with a unique attribute, it doesn't matter wich is, but must be persistent always => it can never change.
I don't want to create a unique attribute, sequence, serial, etc.
I'm using the objectID but every time I use it a get a new reference.
I know that before the object has been saved, it has a 'temporal id', but once it's saved, it gets the definitive.
I'm not seeing this, never.
When I export, just fetch all data and loop, and always I get a new reference:
NSURL *objectID = [[personalDataObject objectID] URIRepresentation];

// some of id received for the SAME OBJECT (no changes made, saved, ...)
// 61993296
// 62194624

thanks,
r.
edit
I was using %d instead of %@, now the returned data is:
x-coredata://F46F3300-8FED-4876-B0BF-E4D2A9D80913/DataEntered/p1
x-coredata://F46F3300-8FED-4876-B0BF-E4D2A9D80913/DataEntered/p2

A:

The NSManagedObjectID is not guaranteed to be consistent.  It can change based on a number of factors including data migration and other factors.  If you are using this as a unique identifier for your objects, stop.
The only time you want to use the NSManagedObjectID is when you need to pass references between threads.  Other than that situation you should not rely upon it for anything.
If you need a unique id then create one and store it in your entities.

A:

I think this maybe a reporting problem. The numbers you show that are supposed to be a URI/UUID are way, way to short.
They should look like:

UUIDs (Universally Unique
  Identifiers), also known as GUIDs
  (Globally Unique Identifiers) or IIDs
  (Interface Identifiers), are 128-bit
  values guaranteed to be unique. A UUID
  is made unique over both space and
  time by combining a value unique to
  the computer on which it was
  generated—usually the Ethernet
  hardware address—and a value
  representing the number of
  100-nanosecond intervals since October
  15, 1582 at 00:00:00.
The standard format for UUIDs
  represented in ASCII is a string
  punctuated by hyphens, for example
  68753A44-4D6F-1226-9C60-0050E4C00067.
  The hex representation looks, as you
  might expect, like a list of numerical
  values preceded by 0x. For example,
  0xD7, 0x36, 0x95, 0x0A, 0x4D, 0x6E,
  0x12, 0x26, 0x80, 0x3A, 0x00, 0x50,
  0xE4, 0xC0, 0x00, 0x67 . To use a
  UUID, you simply create it and then
  copy the resulting strings into your
  header and C language source files.
  Because a UUID is expressed simply as
  an array of bytes, there are no
  endianness considerations for
  different platforms.

I think you're seeing different values because your only getting a piece, and a different piece at that, each time you check the UUID. Represented as a URI, they should look more like a URL. They definitely won't look like an integer.


Q:

Does multi-classing into a martial class make you a member of martial class?

A character who has taken a class-specific multiclass feat counts as a member of that class for the purpose of meeting prerequisites for taking other feats and qualifying for paragon paths.

As a member of a martial class via a multi-classing feat, are you eligible for feats that can only be taken by martial classes? For instance, could a dwarven warlock, who took "Twilight Adept", gain access to this feat:

Resilience of Stone
Prerequisite: Dwarf, any martial class
Benefit: You can use your second wind as an immediate interrupt when you are damaged by an attack.

Or is your class Warlock, and only Rogue for the purpose of rogue feats?

A:

There's a thread on the WotC boards from Nov '11 discussing a very similar question.
The rules themselves are apparently a bit unclear about the issue, and there is a PHB FAQ (see here, #33) stating that you don't gain the other class's role by taking a MC feat:

33. Does taking a fighter multiclass feat qualify you for feats and paragon paths that require the defender role?
No, you do not gain the role of the class that you multiclass into.

However, the consensus on pretty much the whole board (and the official character builders) seems to clearly favor the obvious solution:

A: fighter is a martial defender
B: taking the fighter MC feat makes you a fighter for feats, paragon paths, etc
A + B: if you take the fighter MC feat you are a member of a martial class and have the defender role for all stated purposes


Q:

Can you have advantage/disadvantage on your Initiative check?

From the rules, it seems that an initiative check is just an ability check. There are numerous effects that give Disadvantage on ability checks, and some that give Advantage.
I don't see it called out anywhere specifically, so should I assume that you can have advantage/disadvantage on these checks as normal?
Some examples; using inspiration to get Advantage on an initiative check, or getting Disadvantage if you're poisoned or exhausted.
(I ask because I'm used to initiative checks being special cases, and also because the Alert feat gives a flat +5 to those checks, when I'd expect it to grant Advantage if that's possible. On the other hand, it doesn't actually say Initiative is anything special.)

A:

Yes
Barbarian's 7th level feature does just that:

Feral Instinct
By 7th level, your instincts are so honed that you have advantage on initiative rolls.
Additionally, if you are surprised at the beginning of combat and aren't incapacitated, you can act normally on your first turn, but only if you enter your rage before doing anything else on that turn.

For a more general understanding, rather than a specific case, the rules for advantage say:

Sometimes a special ability or spell tells you that you have advantage or disadvantage on an ability check, a saving throw, or an attack roll.

and the rules for initiative say:

When combat starts, every participant makes a Dexterity check to determine their place in the initiative order

Because Dexterity checks are ability checks, you can have advantage on them as you can on any other ability check.

A:

Yep.
Initiative is just a Dexterity check and therefore anything that would grant you advantage or disadvantage on a Dexterity check would also carry to Initiative (unless the text would preclude its use specifically for Initiative).

Initiative At the beginning of every combat, you roll initiative by making a Dexterity check. Initiative determines the order of creatures’ turns in combat, as described in chapter 9.

The Sentinel Shield (as one example of a magical item) also grants advantage specifically to Initiative checks and since it is a d20 roll for an ability check Inspiration will also grant you advantage as well.
As Nitsua60 mentions an often overlooked condition that affects a number of things is exhaustion.

A:

Yes
Anything that grants you advantage/disadvantage to Dexterity checks in general will also grant advantage/disadvantage to Initiative.
Below is a (likely incomplete) list of examples of sources of both for Dex checks, and therefore Initiative, or those that impose it on Initiative explicitly.
Sources of Advantage:

DM Inspiration
Enhance Ability
Foresight
The Help action
Natural Explorer (Unearthed Arcana, Revised Ranger)

Sources of Disadvantage:

Hex
Bestow Curse
Fear
Resurrection (to the caster, not the target, if target has been dead > 1 year)
Wearing armor you are not proficient with
Frightened condition
Exhaustion (1 level)
Encumbrance (variant, carrying weight in excess of 10 times your Str score)


Q:

how to save iptables rules permanently?

I want to keep some iptables rules permanence, so I just only add the rules manually:
/sbin/iptables -I OUTPUT -p tcp --sport 80 -j QUEUE

I am sure that the command works, because I could see it after executing iptables -vnL. Unfortunately, I find it disappearing without rebooting or restarting iptables after an hour or so because I could not see it after executing iptables -vnL later on.
First of all, I am sure there is no one executing command like iptables -F. I also find one related row in /var/log/message:
Dec 18 10:10:50 zt_21_23 kernel: ip_tables: (C) 2000-2006 Netfilter Core Team

I find this is a kernel behavior completely after Google. Someone said iptables would rebuild the rules, but he didn't tell me the triggering condition. and I check the iptables configuration file (/etc/sysconfig/iptables-config), but I could not find any configuration item that could make iptables rebuilding the rules.
I have to add the rules at set intervals by using crontab if I want to keep it permanence.
To sum up:

How to stop iptables from reverting the rules I add?
When will iptables rebuild its rules and what is the triggering condition?
Which rule would be reloaded when iptables rebuilt and where these rules are saved?

PS. Modifying /etc/sysconfig/iptables, or using iptables-save and iptables-restore could work, but the rules still disappear after an hour or so.
I am using Linux (2.6.18-308.24.1.el5 x86_64).

A:

Something or someone is removing your rules or restarting the iptables service. The kernel doesn't just do that automatically. To stop it, you first need to figure out what is doing it. I'd start with checking to see if something is restarting the iptables service. To figure this out, add the following to /etc/init.d/iptables:
date >> /tmp/iptables-service.log
ps -f $PPID >> /tmp/iptables-service.log

Then after your rules "disappear" check the /tmp/iptables-service.log file to see who/what ran the iptables service script.
If you don't see a /tmp/iptables-service.log file, then something ran the /sbin/iptables command directly. To find what is running this command, rename /sbin/iptables to /sbin/iptables.real and then create the following script and save it as /sbin/iptables:
#!/bin/bash
date >> /tmp/iptables-cmd.log
ps -f $PPID >> /tmp/iptables-cmd.log
/sbin/iptables $*

Don't forget to set the script as executable: chmod a+x /sbin/iptables. Also note that your actual iptables command might actually be something like /sbin/iptables-multi-1.4.7 depending on how you have alternatives configured.
Then as before, look at the /tmp/iptables-cmd.log file to see who/what is running the command. Once you know the cause, you should be able to prevent it.


Q:

Let $n$ be the positive integer such that $5^n$ and $2^n$ begin with same digit. Which digit is that?

This is my first time posting here so sorry if I done something wrong, and also my first time encountering a problem like this.
Besides trivial $0$, the only solution I found by simply writing down the powers of $2$ and $5$ parallely, is $5$ ($5^5=3125$, $2^5=32$). I couldn't find any kind of period. I've done problems which are about last digit, but not about the first one.
Hopefully I could get a hint. Thanks.

A:

Hint: $5^n\times2^n=10^n$. ${}$


Q:

Set Default NFS v4 when connecting from Mac OS X Lion

I have installed an NFS File Server on Ubuntu 11.10, and that is working well.
I am only able to connect to the NFS server from my Mac with this command:
 mount -t nfs -o vers=4 10.0.10.26:/srv /Users/admin/Desktop/mount

But I cannot connect via Finder (nfs://10.0.10.26:/srv) or through any third party programs that don't allow for the version parameter. The Syslog error is

mount_nfs: can't mount /srv from 10.0.10.26 onto
  /Users/admin/Desktop/mount: Program version wrong

Is there any way to set this to V4 by default? Either server side or on my Mac? I need to be able to connect without the extra parameters.
Thanks

A:

Hmmm, seems we need to have this question re-answered every major release of OS X.
So I can only say this works on 10.10.x :)
From OS X's man page for mount_nfs
"nfs.conf(5) can be used to configure some NFS client options. In particular, nfs.client.mount.options can be used to specify default mount options"
To get the Finder to default to using NFS v4 add the following to /etc/nfs.conf using the terminal command "sudo vi /etc/nfs.conf"
 nfs.client.mount.options = vers=4

Again, to check after mounting use "nfsstat -m" and check the "NFS parameters".

A:

The syntax for using NFS v4 (and passing options in general) is :
nfs://vers=4,10.0.10.26/srv

You can check the mount afterwards from the Terminal using :
nfsstat -m


Q:

VSCode terminal windows - git-bash aliases getting ignored

I've created aliases in c:\Users\user\.bash_profile and in C:\Program Files\Git\etc\profile.d\aliases.sh but both configs getting ignored by VSCode integrated terminal, which is configured to use git bash:
"terminal.integrated.shell.windows": "C:\\Program Files\\Git\\bin\\bash.exe",

if I open GitBash itself - aliases works fine
how do I force integrated terminal to respect the configs?

A:

You can try adding to the settings:
// The command line arguments to use when on the Windows terminal.
"terminal.integrated.shellArgs.windows": [
    "--login", "-i"
],

-i - force the shell to run interactively.
--login - make this shell act as if it had been directly invoked by login. When Bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable.

When invoked as an interactive shell with the name sh, Bash looks for the variable ENV, expands its value if it is defined, and uses the expanded value as the name of a file to read and execute. Since a shell invoked as sh does not attempt to read and execute commands from any other startup files, the --rcfile option has no effect. A non-interactive shell invoked with the name sh does not attempt to read any other startup files.

Read more.

As an alternative you can use the .bashrc file instead of .bash_profile.


Q:

how to remove code behind CSS using jquery?

i am using jquery for enabling and disabling a button
$(function () {
$('.CSSCheck').click(function () {
    if ($("[id$='Chkbox']:checked").length > 0) {
        $("#<%=Button1.ClientID %>").removeAttr('disabled');
    }
    else {
        $("#<%=Button1.ClientID %>").attr('disabled', 'disabled');

    }
});
});

on code behind i am adding a css to datalist image button on Select_Command
DataListItemCollection xxx = datalist1.Items;
int index = id;
int count = 0;
foreach (DataListItem x in xxx )
{
   if (count == index)
        {
          (x.FindControl("btn1") as ImageButton).BorderColor = System.Drawing.Color.Blue;
          (x.FindControl("btn1") as ImageButton).BorderWidth = 1;
        }
}

how to remove this css using the same jquery?

A:

This should work
$("#<%=Button1.ClientID %>").css('border', '');

It is recommended however to use classes
$("#<%=Button1.ClientID %>").removeClass('myborder');

in code-behind:
(x.FindControl("btn1") as ImageButton).CssClass = "myborder";

Style definition:
.myborder { border: 1px solid Blue; }


Q:

Interface using generics "Cannot implicitly convert type"

If i have a class which accepts a generic type derived from IUser, how can i avoid this error message

Cannot implicitly convert type ElimCMS.Service.Users.someclass<ElimCMS.DataModel.Users.User> to ElimCMS.Service.Users.Isomeclass<ElimCMS.DataModel.Users.IUser>. An explicit conversion exists (are you missing a cast?)

Example
   public interface Isomeclass<TUser>
   where TUser : class, IUser
   {

    string test(TUser user);
    TUser returnUser();
   }

   public class someclass<TUser> : Isomeclass<TUser>
   where TUser : class, IUser, new()
   {
    public string test(TUser user)
    {
        string email = user.EMail;
        user.EMail = "changed:" + email;

        return email;
    }

    public TUser returnUser()
    {
        throw new NotImplementedException();
    }
}

 Isomeclass<ElimCMS.DataModel.Users.IUser> servicetest = new someclass<ElimCMS.DataModel.Users.User>();

A:

This happens because generics which have different types are not compatible with eachother. To get around this, you can declare your generic parameter to Isomeclass to be covariant using
public interface Isomeclass<out TUser>
   where TUser : class, IUser
{

    string test(TUser user);
    TUser returnUser();
}

However, this will break the test method since it will no longer be type safe. To get around this you can change the paramter user type to IUser and it will work as before.
This is dependent on the version of C# that you are using. For some older versions generics cannot be declared as covariant, which means you have to change the assignment target to be of the same type as the object you assign to it.


Q:

run script at reboot

I would like to run this script everytime computer starts up. I'm using crontab/gnome schduler:
#!/bin/bash
while true
do
    fileName=$(inotifywait -e create /home/posto-11v/Documents/Processo | sed -r 's/^.*CREATE(,ISDIR)*\s+(.*)$/\2/g')
    zenity --warning --text="$fileName"
done

this is the crontab -e file:
@reboot sh /home/posto-11v/Documents/personaproject/Programa/scripts/recebe_processo # JOB_ID_9

I've changed script permissions using chmod +x.
I'm not able to run it automatically, only by hand. what i'm doing wrong? Can the script start whithout starting the terminal?
thks in advance!

A:

This script can't be executed at reboot: it needs a graphical environment. You need to log in first, to start a graphical environment where you can run zenity. Run the script from your session startup. See Adding programs to session startup in the Ubuntu community documentation.


Q:

How can I stop a HTML checkbox from getting focus on click?

Anyone know how to prevent an HTML checkbox from getting focus when clicked? I still want it to change state, just not get focus.

A:

You can prevent the focus by using preventDefault() in a mousedown handler:
$('input[type=checkbox]').mousedown(function (event) {
    // Toggle checkstate logic
    event.preventDefault(); // this would stop mousedown from continuing and would not focus
});

In pure JavaScript:
checkbox.onmousedown = function (event) {
    // Toggle checkstate logic
    event.preventDefault(); // this would stop mousedown from continuing and would not focus
}


Q:

sql - how to split fullname into first and last name

If I have a table with a column that contains fullnames such as :
fullname
------------
Joe Bloggs
Peter Smith
Mary Jones and Liz Stone

How can I retried the first and last name from each of the entries in the full name column  using SQL. I'm not worried about the second name in the 3rd entry in my  example i.e. Liz Stone.
So basically to retrieve
Firstname
---------
Joe
Peter
Mary

Lastname
--------
Bloggs
Smith
Jones

A:

Here is a pre SQL Server 2016 method, which uses basic string functions to isolate the first and last names.
SELECT SUBSTRING(fullname, 1, CHARINDEX(' ', fullname) - 1) AS Firstname,
       SUBSTRING(fullname,
                 CHARINDEX(' ', fullname) + 1,
                 LEN(fullname) - CHARINDEX(' ', fullname)) AS Lastname
FROM yourTable

Note that this solution assumes that the fullname column only contains a single first name and a single last name (i.e. no middle names, initials, etc.).

A:

This is a slippery slope and there are no easy answers.  That said, consider the following
Declare @YourTable table (FullName varchar(50))
Insert Into @YourTable values
('Joe Bloggs'),
('Peter Smith'),
('Betty Jane Martinez'),
('Mary Jones and Liz Stone')

Select A.*
      ,FirstName = Pos1+case when Pos3 is not null then ' '+Pos2 else '' end
      ,LastName  = case when Pos3 is null then Pos2 else Pos3 end
 From @YourTable A
 Cross Apply (
    Select Pos1 = xDim.value('/x[1]','varchar(max)')
          ,Pos2 = xDim.value('/x[2]','varchar(max)')
          ,Pos3 = xDim.value('/x[3]','varchar(max)')
          ,Pos4 = xDim.value('/x[4]','varchar(max)')
          ,Pos5 = xDim.value('/x[5]','varchar(max)')
          ,Pos6 = xDim.value('/x[6]','varchar(max)')
     From  (Select Cast('<x>' + replace((Select substring(FullName,1,charindex(' and ',FullName+' and ')-1) as [*] For XML Path('')),' ','</x><x>')+'</x>' as xml) as xDim) as A
 ) B

Returns
FullName                    FirstName   LastName
Joe Bloggs                  Joe         Bloggs
Peter Smith                 Peter       Smith
Betty Jane Martinez         Betty Jane  Martinez
Mary Jones and Liz Stone    Mary        Jones

If it helps with the visual, the CROSS APPLY generates


Q:

Why this application controller won't return correct value to controller who called?

Why do I get empty when I execute this? Asumming User's point is 2500. It should return 83
posts_controller
@user = User.find(params[:id])
@user.percentage = count_percentage(@user)
@user.save

application_controller
def count_percentage(user)
    if user

        if user.point > 2999
            percentage = ((user.point / 5000.0) * 100 ).to_i
        elsif user.point > 1999
            percentage = ((user.point / 3000.0) * 100 ).to_i
        end

        return percentage

    end
end

A:

It looks like there is some lack of basic understanding, so I try to focus on a few points here.
count_percentage belongs to your model. It is a method which does things that are tied to your User records. In your example, the code can only be used with a User record. Therefore it belongs to your User class!
class User < ActiveRecord::Base
  def percentage
    if self.point > 2999
        return ((self.point / 5000.0) * 100 ).to_i
    elsif user.point > 1999
        return ((self.point / 3000.0) * 100 ).to_i
    else
        # personally, I'd add a case for points range 0...3000
    end
  end

As you said, you want to put that value into your "side menu", so this allows to e.g @user.percentage there which gives you the desired percentage.
According to your description (if I understood it the right way) you want to store the calculated value in your user model. And here we go again: Model logic belongs into your model class. If you want to keep your percentage value up to date, you'd add a callback, like:
class User < ActiveRecord::Base
  before_save :store_percentage

  def precentage
    # your code here
  end

  private

  def store_percentage
    self.my_percentage_field_from_my_database = self.percentage
  end
end

To your actual problem: user.point may be NULL (db) / nil (ruby), so you should convert it to_i before actually calculating with it. Also that's why I've suggested an else block in your condition; To return a value wether or not your user.point is bigger than 1999 (if it even is an integer.. which I doubt in this case).


Q:

Why should return-by-value be const for non-builtin types but not const for builtin types?

Solutions 4 and 5 on GotW #6 Const-Correctness mention this:

Point GetPoint( const int i ) {
    return points_[i];
}

Return-by-value should normally be const for non-builtin return types ..

int GetNumPoints() {
    return points_.size();
}

.. since the int is already an rvalue and to put in 'const' can interfere with template instantiation and is confusing, misleading, and probably fattening.

I have the following questions

Which template instantiation are we interfering with here ?!
What exactly is misleading here and why?
Why this differentiation between non-builtins and builtins. I thought this was a bad practice!

A:

Return-by-value should normally be const for non-builtin return types ..

That is not correct- one of the relatively few mistakes in the GotW. const rvalues were questionable in C++03 and definitely very bad in C++11.
The problem is that in C++03, rvalues can have any member function called on them- even non-const. This is great because you can "swaptimize" or perform method chains and other things, which are perfectly fine and make absolute sense, but it's also bad because the compiler can't catch you when you do something stupid, like assign to it or something. Generally, it's a bad idea to restrict everyone from doing good things because the caller might do something stupid. The intention is good, but it's not right.
In C++11 this is fixed because you can disallow member functions from being called on rvalues, and secondly, because in order for move semantics to work correctly the rvalue must be mutable. You can't take resources from an rvalue if it's const.
Just as a note, the reason this is different is because primitive types have always had special wording built into the language which made e.g. assigning to rvalues illegal, so there was no need to try and enforce that yourself by making it const.
As for the template instantiations, I'm actually uncertain. This practice was already known to be bad by the time I started coding C++, so it's not something I ever had to deal with.

A:

Personally, I disagree with the recommendation to put const on the return value independent of move semantics: the value is already an rvalue and as a result there isn't much danger of accidentally modifying it. This is the part of why to put a const on non-built-in types: they may contain some sort of a backdoor to the value. For example, std::vector<T> has a swap() method which can be used to "steal" the content of a non-const rvalue:
std::vector<int> f();
std::vector<int> value;
f().swap(value);

Similarly, streams have some member operators which allow you to use them with certain built-in functions which effectively extract a reference from the stream, e.g.:
std::string word;
std::istringstream("hello, world") >> std::skipws >> word;

Without the std::skipws the stream is an rvalue which can't be bound to the first argument of std::operator>> (std::istream&, std::string&) but using the member operator for manipulators returns a non-const reference to the stream.
The const on build-in types actually has no effect at all. In particular, when passing the result of a function on to a function template (in C++2003) it can't distinguish between a const or a non-const return being passed on. As a result, it may appear as if the const has an effect on built-in returns although it actually doesn't.
As I said, I disagree with the rule and in C++2011 it definitely doesn't hold because you want to be able to move off a non-built-in anyway which would be prevented by the const return.


Q:

Postgres ordering of UTF-8 characters

I'm building a small app that includes Esperanto words in my database, so I have words like ĉapelojn and brakhorloĝo, with "special" characters.
Using PostgreSQL 9.4.4 I have a words table with the following schema:
lingvoj_dev=# \d words
                                      Table "public.words"
   Column    |            Type             |                     Modifiers
-------------+-----------------------------+----------------------------------------------------
 id          | integer                     | not null default nextval('words_id_seq'::regclass)
 translated  | character varying(255)      |
 meaning     | character varying(255)      |
 times_seen  | integer                     |
 inserted_at | timestamp without time zone | not null
 updated_at  | timestamp without time zone | not null
Indexes:
    "words_pkey" PRIMARY KEY, btree (id)

But the following query gives some strange output:
lingvoj_dev=# SELECT w."translated" FROM "words" AS w ORDER BY w."translated" desc limit 10;
translated
------------
 ĉu
 ŝi
 ĝi
 ĉevaloj
 ĉapelojn
 ĉapeloj
 ĉambro
 vostojn
 volas
 viro
(10 rows)

The ordering is inconsistent - I'd be okay with all of the words starting with special characters being at the end, but all of the words starting with ĉ should be grouped together and they're not! Why do ŝi and ĝi come in between ĉu and ĉevaloj?
The server encoding is UTF8, and the collation is en_AU.UTF-8.
edit: It looks like it's sorting all of the special characters as equivalent - it's ordering correctly based on the second character in each word. How do I make PostgreSQL see that ĉ, ŝ and ĝ are not equivalent?

A:

I'd be okay with all of the words starting with special characters
  being at the end...

Use collate "C":
SELECT w."translated"
FROM "words" AS w
ORDER BY w."translated" collate "C" desc limit 10;

See also Different behaviour in “order by” clause: Oracle vs. PostgreSQL
The query can be problematic using an ORM. A solution could be to recreate the database with the option LC_COLLATE=C (as OP suggested in a comment). There is one more option - to change a collation for a single column:
ALTER TABLE "words" ALTER COLUMN "translated" TYPE text COLLATE "C";


Q:

How to unomount file system mounted on "/"

I want to unmount / file system because my disk space is full and I want to extend
my directory. Problem is my disk has errors and I have to run fsck on it.
When I try to unmount my directory, my file is mounted on:
/dev/mapper/vg_carlocentos-lv_root      100%      /

I want to be able to unmount the file system but I can't seem to unmount it.
It says resource is busy whenever  I try to unmount file:
umount /

init 1
umount: /: device is busy.

How do I fix this?

A:

Your / is busy because you are attempting to unmount the root filesystem of the system you are actively running. The only way to cleanly do what you are thinking of doing is booting from another system & then mount the one you need to clean it & extend the volume.


Q:

What is the advantage of running a Ripple masternode?

There is one thing that I cannot stop wondering about:
Why would someone run a Ripple masternode?
Before you mark this as a duplicate, I understand how the transaction fees work in Ripple and also the mechanism of distributed consensus.
The point is - for other currency types, the usual rewards for providing services keeping them alive are transaction fees. If the masternodes don't collect any fees, what is the reason to operate one and bear the associated costs?

A:

The same reason someone would run a bitcoin full node. If you want to transact on the network, you either have to run your own node or use someone else's. If you choose to use someone else's, you are relying on them to give you a proper view of the network and run their server reliably. If you run your own, you are independent. You also help improve the stability and reliability of the network for everyone.
Strictly speaking, you could just run a node that's not a validator. But there is almost no additional effort to running a validator -- it's literally just one extra command you enter once. It's nothing like mining.
If nobody is using the XRP Ledger or deriving any value from it, then it makes no difference who validates or, for that matter, whether anyone validates at all. If there are people using the XRP Ledger and deriving value from it, then they have a stake in ensuring that the network continues to operate reliably and that its rules continue to be the rules that make the network useful to them. This acts as incentive to run a validator, considering that there is no additional cost.

A:

There are two types of ripple nodes:
Stock Server-Basically just follows along with the network with a local copy of the ledger.
Validators-Nodes which participate in the consensus.
Neither of these have any rewards but if you run your own stock server you can have a local copy of the ledger and therefore have admin rights, you will not have to trust anyone elses server and you can control your workload.
Likewise if you run your own validator you can have your say in how the Ripple network evolves because changes to the protocols at devoted on by validators.
Sources:
https://ripple.com/build/rippled-setup/
https://www.xrpchat.com/topic/3772-ripple-validator-profits/


Q:

In a Thunderbird extension, how can different javascript files refer to each other?

I have developed a very simple Thunderbird extension. There is one simple .xul file which refers via script-tag to a .js file. In that javascript-file I am implementing an event listener on the compose-send-message event. When the send-button is clicked, I want to encrypt the message in the mail-body and replace it with that newly encrypted text before sending. Replacing text in the body-part of Thunderbird worked well, but I am not able to refer to another javascript file with a simple function call like
var encryptedData = encryption.encrypt(data);

for the file encryption.js, which exclusively handles the encryption of said email-text before sending. Both files are in the same directory, so normally they should be able to refer to each other, shouldn't they? But for me that reference never seems to work. Would you know what I can do to make it work as intended? I don't seem to be able to figure that one out by myself. Thanks in advance.

A:

I don't have experience with add-ons for Thunderbird, but do with add-ons for Firefox. However, I believe the same mechanisms apply to Thunderbird.
You have two options (or perhaps more, that I am unaware of):

Include the needed extra javascript file in the xul file, before the main javascript file (or did you try this already?):
<script type="application/javascript" src="chrome://path/to/extra.js"/>
<script type="application/javascript" src="chrome://path/to/main.js"/>

Load the needed extra javascript file from inside the main javascript file, as a subscript, with the subscript loader service, through loadSubScript():
var mozIJSSubScriptLoader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
                                      .getService(Components.interfaces.mozIJSSubScriptLoader);

mozIJSSubScriptLoader.loadSubScript( 'chrome://path/to/extra.js', optionalScope, 'UTF-8' );

The optionalScope lets you load the scripts variables into a designated object. If omitted, the scripts variables will be loaded into the current scope of the loadSubScript() caller.
The charset argument is optional as well, by the way.


Q:

Register multiple header supplementary view in the same UICollectionView through storyboards

So I have a UICollectionView that I want to use to display multiple UICollectionViewCells and different headers depending on the state the user is in. The problem is I can't seem to register multiple UICollectionResuableView (header) views within the storyboard. If I try to register one as a footer and use it as a header the app crashes. I also do not see anywhere in the storyboard to declare the number of sections, which would alleviate the problem. For now I'm having to use multiple UICollectionViews and hide/unhide the collectionview I want to display based on the header I need. Is there a better way to do this, or a way to register multiple header views in the same UICollectionView within the storyboard?

A:

You cannot register more than one header in a UICollectionView in a storyboard, but you can register an arbitrary number of them in code.  You should create however many headers as you want in nib files (One nib per header, with the header as the top level object), and register them with your collection view instance in viewDidLoad.
You would do this with the registerNib:forSupplementaryViewOfKind:withReuseIdentifier: method.


Q:

Do military pilots use amphetamines or other stimulants?

Related to this question: Do military pilots have flight & rest hours regulation?
According to the wikipedia article, amphetamines were commonly given to Allied pilots.
Are they still in use today?

A:

The U.S. Air Force (and Navy) still uses, and has used off and on since WWII,  what are commonly referred to as "Go Pills" for instances when pilots need to be up for long periods of time - in wartime, sometimes longer than the crew rest regulation. (These pills can also be used for altering sleep cycles, along with "no-go" pills; for example, when changing from day to night).
The most common go pill is Dexedrine, which is an amphetamine. You can find some more information in this article.


Q:

Testing viewsets with UploadedFile

I'm trying to test a particular viewset view which takes formData which contains  a csv file. My test looks like this:
    @staticmethod
    def _create_file(rows: List[List[Any]], content_type: str = 'text/csv') -> UploadedFile:
        f = StringIO()
        csv.writer(f).writerows(rows)
        return UploadedFile(file=f.read(), name='test.csv', content_type=content_type)

    def test_upload_valid(self):
        """ Asserts that the upload view works correctly with valid information. """
        response = self.client.post(reverse('core_api:upload-upload'), {
            'file_type': self.file_type,
            'file': self._create_file([['Test', 'Test', 'Test', 'Test'], [1, 'Test', 'tokyo', 2]])
        })
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.content['process_status'], DemoConsumerDataParser.SUCCESS_STATUS)
        self.assertEqual(len(response.content['errors']), 0)

However this fails here:
'file': self._create_file([self.header, self.acceptable_row])

With the following error:
AttributeError: 'str' object has no attribute 'read'

How can I modify the post so it correctly sends this file?

A:

So I've gotten around this by using SimpleUploadedFile, but I'm not sure why this works:
    @staticmethod
    def _create_file(rows: List[List[Any]]) -> SimpleUploadedFile:
        f = StringIO()
        csv.writer(f).writerows(rows)
        file = SimpleUploadedFile('test.csv', f.getvalue().encode(), content_type='text/csv')
        f.close()
        return file