text:
Q: Rename files with incrementing number starting at certain number I have some files:
$ ls
00000.ABC
00001.ABC
00002.ABC
00003.ABC
00004.ABC
00005.ABC

I want to change these to start at a certain number, for example 00055.ABC so the new files look like:
$ ls
00055.ABC
00056.ABC
00057.ABC
00058.ABC
00059.ABC
00060.ABC

I understand about for loops to loop through each file, for example for file in ls { } but I'm not sure about the incrementing number starting at a certain number so appreciate any help.

A: You can do this easily with rename, which is actually just a Perl script, and which can be installed on macOS with homebrew using:
brew install rename

The command would then be:
rename --dry-run  -XN "00055" -e '$_ = $N' *ABC

Sample Output
'00001.ABC' would be renamed to '00055.ABC'
'00002.ABC' would be renamed to '00056.ABC'
'00003.ABC' would be renamed to '00057.ABC'
'00004.ABC' would be renamed to '00058.ABC'
'00005.ABC' would be renamed to '00059.ABC'

If that looks correct, you would remove the --dry-run and do it again. Using rename has the benefit that it will not clobber (overwrite) files and it will tell you what it is going to do, without actually changing anything, if you use the --dry-run option. It is also immensely powerful - it can do lowercase, camelcase, uppercase, remove control characters, call any Perl module and calculate any expression or substitution you can think of.

A: This should work:
for f in *.ABC; do
   num=$(basename "$f" .ABC)
   num2=$(printf "%05d" $((num + 55)))
   echo mv "$f" "$num2.ABC"
done

Notes:

*

*I am assuming your files all follow the pattern of digits followed by .ABC, so that basename $f .ABC extracts the number. You'll have to adjust the num= line if this assumption does not hold.

*$(( ... )) is the bash syntax to do arithmetic operations.

*(printf "%05d" ...) is here to pad zeroes in front of the number, otherwise you'd just get 55 etc.

*Remove the echo once you're convinced it's doing the right thing.

*EDIT Warning: the new set of filenames should not overlap the old set of filenames, or you might lose some files. Carefully choosing the order the mv commands are run could solve the issue, but putting the files in a new directory as they are renamed and moving them back after would be much simpler.
EDIT:
@MarkSetchell pointed out in the comments that you want sequential numbering that is not based on the original file names, in which case this loop would work instead:
i=55 # choose your starting destination file number here
for f in *.ABC; do
   dest=$(printf "%05d" $i).ABC
   echo mv "$f" "$dest"
   i=$((i + 1))
done


text:
Q: Slow Performance on Android implementing Offline Dictionary using JsonReader I am trying to implement an offline dictionary in a ebook reader app I am working on.
Let me explain the process. The dictionary is not part of the original app, rather will be downloaded in background. The original dictionary data is a json of 24MB long that is later reduced to 6MB upon compression.
I then download the compressed json and extract it on device. The dictionary json has around 150,000 entires that I am saving in a DB. I am using JsonReader to parse the json sequently, adding each entry in DB.
Below is the code for reading the json, parsing each entry and saving it in a DB (I hope it's self explanatory)
public void readFile() throws IOException {

    File jsonInputFile = new File(DownloadClassHelper.getOfflineDictionaryDownloadPath());

    InputStream inputStream = new FileInputStream(jsonInputFile);
    JsonReader reader = new JsonReader(new InputStreamReader(inputStream, "UTF-8"));

    try {
        readArray(reader);
    } finally {
        reader.close();
    }
}

public void readArray(JsonReader reader) throws IOException {

    reader.beginArray();
    while (reader.hasNext()) {
        readObject(reader);
    }
    reader.endArray();
}

public void readObject(JsonReader reader) throws IOException {

    String word = null;

    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();
        if (name.equals("word")) {
            word = reader.nextString();
        } else if (name.equals("meanings") && reader.peek() != JsonToken.NULL) {
            readMeaningsArray(word, reader);
        } else {
            reader.skipValue();
        }
    }
    reader.endObject();
}

public void readMeaningsArray(String word, JsonReader reader) throws IOException {

    reader.beginArray();
    while (reader.hasNext()) {
        readMeaningObject(word, reader);
    }
    reader.endArray();
}

public void readMeaningObject(String word, JsonReader reader) throws IOException {

    String definition = null, pos = null;

    reader.beginObject();
    while (reader.hasNext()) {
        String name = reader.nextName();

        if (name.equals("definition")) {
            definition = reader.nextString();
        } else if (name.equals("pos")) {
            pos = reader.nextString();
        } else {
            reader.skipValue();
        }

    }
    reader.endObject();

    addWord(word, definition, pos);

    Log.d(TAG, word + " | " + definition + " | " + pos);
}

/**
 * Add a word to the dictionary.
 * @return true or false if failed
 */
public boolean addWord(String word, String definition, String pos) {

    ContentValues initialValues = new ContentValues();
    initialValues.put(TableDictionary.COLUMN_WORD, word);
    initialValues.put(TableDictionary.COLUMN_DEFINITION, definition);
    initialValues.put(TableDictionary.COLUMN_POS, pos);

    return CPWrapper.insert(TableDictionary.TABLE_NAME, initialValues);
}

I am facing performance issue with my current approach since it is taking close to 30 minutes to parse the entire json.
What is the ideal method for implementing offline dictionary in Android apps? Do I need to change my current approach? If yes, then how should I ideal implement such system in android.
Any recommendations/tips are highly welcomed.

A: The best ways is using a prepopulated database for your application. So, instead downloading the JSON file, you can add the database file to your apk in the assets folder. You can use Android SQLiteAssetHelper

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using Fsolve to solve N-1 equations in N-1 unknowns I've been looking around but I can't seem to figure out how I should use fsolve to solve my system of nonlinear equations.
so I have a function k, and I know that I want .01 as the starting value (required input for fsolve I believe). I also know that k(1000) =12
Lastly, I have a formula for k,
    k(N) = (1/(k(N).^.5 + .9*k(N) -k(N+1))) - ((.94 * .5 *k(N+1)^(1-.5) + .9)/(k(N+1)^.5 +
   .9*k(N+1) - k(N+2)))

with N 1:1000. I figured I could just say fsolve(k(N), .01), but with the formula in place of k(N) (or is defining k(N) in a separate function necessary?), but I exceed the dimensions of N and also have issues with dimensions matching since there is N, N+1, and N+2 in the equation.
I think my issue may be stemming from the fact that I have defined vector valued functions where in reality I want them to be single valued, from 1:1000,but I don't know how to represent this in matlab (obviously I can't type in 1000 equations).
Any ideas, suggestions, or comments?


text:
Q: Agda : Ambiguous name _==_. It could refer to any one of What to do if I want to work with packages that provide colliding names, e.g.
  module Halp where
  open import Data.String
  open import Data.Char
  open import Data.Bool

  foo : String -> String -> String
  foo a b  with a == b
  ... | true = "foo"
  ... | false = "bar"

leads to
 Ambiguous name _==_. It could refer to any one of
  Data.String._==_ bound at ...\Data\String.agda:71,1-5
  Data.Char._==_   bound at ...\Data\Char.agda:40,1-5

is there an option to make agda figure out what function I mean by arguments if there is ambiguity?
For now I found a workaround of  doing _==s_ = Data.String._==_.
Is there other way?

A: You can make this work by using instance arguments, the Agda alternative to type classes. Unfortunately, the Agda library hasn't been written with instance arguments in mind (yet), so you have to define the Eq class and the instances for Char and String yourself:
open import Data.Bool

open import Data.Char hiding (_==_)
open import Data.String hiding (_==_)

-- The Eq type class
record Eq (A : Set) : Set₁ where
  field
    _==_ : A → A → Bool

-- Instance argument magic
open Eq {{...}}

-- Eq instance for Char
EqChar : Eq Char
EqChar = record { _==_ = Data.Char._==_ }

-- Eq instance for Bool
EqString : Eq String
EqString = record { _==_ = Data.String._==_ }

Now you can use _==_ for both Char and Bool:
test : Bool
test = ('a' == 'a') ∧ ("foo" == "foo")

To learn more about instance arguments, you can read about them on the Agda wiki (http://wiki.portal.chalmers.se/agda/pmwiki.php?n=ReferenceManual.InstanceArguments) or in the paper that introduced them (http://people.cs.kuleuven.be/~dominique.devriese/agda-instance-arguments/icfp001-Devriese.pdf).

A: Sadly, no, there is no way to make Agda pick one of those based on the types of the arguments. Agda can resolve ambiguous names only for constructors.
However, there are better ways of specifying which one to use than using _==s_.

*

*You can specify what functions you want to import into the global namespace:
open import Data.Char
  hiding (_==_)
open import Data.String

-- or the other way around
open import Data.Char
  using (Char) -- and other stuff you might need
open import Data.String
  using (String; _==_) -- etc.

*You can open modules locally inside a function:
import Data.Char
import Data.String

test : Type
test = expr -- use _==_ here
  where
  open Data.String
  -- unqualified names are only available inside expr

*You can open modules locally inside another module:
module UsesStringEq where
  open Data.String
    using (_==_)

  test : Type
  test = expr -- use _==_ here

open UsesStringEq public
-- make sure that other modules can use unqualified names
-- from UsesStringEq

*You can use fully qualified names:
test : String → String → String
test a b = if a Data.String.== b then "OK" else "Bad"

A:
For now I found a workaround of doing _==s_ = Data.String._==_.

You can also rename bindings when you open the module:
open import Data.String renaming (_==_ to _==s_)
open import Data.Char renaming (_==_ to _==c_)


text:
Q: Set Default Database for an OBDC DSN Connection .Net Is there any way to set the default database of an ODBC DSN, using the ODBC connection string in an OdbcConnection?
Edit:
If I already have a DSN setup and a normal connection works.
OdbcConnection connection =
    new OdbcConnection("DSN=TestDSN;UID=ADMIN;PWD=****;");

Is there a way I can change the default connection that is set when you create the DSN in Control Panel->Administrative Tools->Data Sources(ODBC) through the connection string.

A: Often you can add "Initial Catalog" or something similar to the connection string to start off in that database. What that key is named is going to vary based on what you're actually connecting to.
http://connectionstrings.com/ is a pretty good resource for looking up the details.


text:
Q: Alter the parameter name during serialization I am having struggles with the alteration on the parameter name during serialization with DRF.
My input would be a JSON with some parameters:
{
"limit": 10,
"type": "group",
[...]
}

and my serializer looks like:
class RankSerializer(serializers.Serializer):

    limit = serializers.IntegerField(default=100, min_value=1)
    type = serializers.CharField()

    def validate_type(self, t):
        # validation

But this doesn't sound right. Type is a reserved keyword in Python so I don't want to use it as a parameter name. I'd like to somehow map it to i.e result_type or something like this.
I already tried using the source= parameters as follows:
result_type = serializers.CharField(source='type')

but this doesn't seem to work on non-model inputs.
I cannot rename the parameter on the frontend level.
I'd appreciate any tips regarding this issue. Cheers.

A: I searched https://www.django-rest-framework.org/api-guide/fields/ of DRF docs but was unable to find a viable solution. So I subclassed the Serializer class provided by DRF and created a CustomSerializer. In that, I subclassed the run_validation method. In that, before calling super().run_validation(), I access the initial_data passed and change it to the desired mapping as you mentioned. This information of field mappings I store in the Meta class nested inside RankSerializer. So for example, you have fields F1, F2, F3(in JSON data, for example) whose values you want to populate in fields named M1, M2, M3, you just have to write in the Meta class in the field_mappings dictionary the following :
field_mappings = {
'M1': 'F1',
'M2':'F2',
'M3': 'F3'
}

The other fields will function normally.
Here is the code
import rest_framework.serializers as serializers
from .models import Rank
from rest_framework.fields import empty

class CustomSerializer(serializers.Serializer):
    def run_validation(self, data=empty):
        for (field, mapping) in self.Meta.field_mappings.items():
            data[field] = data[mapping]
            del data[mapping]
        return super().run_validation(data=data)

class RankSerializer(CustomSerializer):
    limit = serializers.IntegerField(default=100, min_value=1)
    result_type = serializers.CharField(required=True)
    class Meta:
        field_mappings = {
            'result_type': 'type'
        }
    def create(self, validated_data):
        print(validated_data)
    def update(self, instance, validated_data):
        print(validated_data)

'''
Please run the code below in the InteractiveShell to verify the result

from myapp.serializers import RankSerializer
serializer = RankSerializer(data={"limit":15, "type":"Hello"})
serializer.is_valid()
'''

After running the code in the multi line comments to verify the result here is the snapshot

A: The workaround I found was to modify the parameter name in the validate method as follows:
def validate(self, data):
    data = super(RankSerializer, self).validate(data)
    data['result_type'] = self.validate_result_type(self.initial_data.get('type'))
    return data

Not sure if this is the cleanest way to do it, but I prefer it over @punter147 answer.


text:
Q: Iterating over sequence in a 1000 nucleotide window I am trying to write in Python a code to go over each sequence in my fasta file and print a new list of each sequence using a 1000 nucleotide sliding window, but I am not sure what is wrong.
"Traceback (most recent call last):
 File "<stdin>", line 4, in <module>
TypeError: expected a string or other character buffer object"

Here is my code:
from Bio import SeqIO
for record in SeqIO.parse("fasta.txt", "fasta"):
    pos=0
    if pos<len(record)+1:
        dna_1000.write("\n"+">"+record.id+"_"+pos+"\n"+record[pos:pos+1000])
        pos=pos+1000

I tried it slightly differently:
from Bio import SeqIO
for record in SeqIO.parse("fasta.txt", "fasta"):
    for pos in range(0,len(record)+1,1000):
        dna_1000.write("\n"+">"+record.id+"_"+"\n"+record[pos:pos+1000])

but I also receive this message:
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
TypeError: expected a string or other character buffer object

Many thanks for taking a look at this!

A: Your original code fails with TypeError: cannot concatenate 'str' and 'int' objects because of the line dna_1000.write(...+'_'+pos+...)
 where you add the object '_' where type('_') = str to the object pos where type(pos) = int. This is impossible because Python never implicitly adds strings  and ints: you have to turn the int into a string before adding it: dna_1000.write(...+'_'+str(pos)+...).
Now we encounter your other error TypeError: expected a string or other character buffer object. This originates from the dna_1000.write method which complains that it doesn't know what to do with its argument. It expects something like a string but gets "\n"+">"+record.id+"_"+str(pos)+"\n"+record[pos:pos+1000]) which is a SeqRecord. This is because record is a SeqRecord, slicing a SeqRecord gives you a SeqRecord, and adding a string to a SeqRecord gives you a SeqRecord (with a modified nucleotide sequence).
To actually access the sliced record's underlying nucleotide sequence you need to use .seq, and to write it to a file you need to convert it to a string. So to make your code run without errors you could do something like:
from Bio import SeqIO
for record in SeqIO.parse("fasta.txt", "fasta"):
    pos=0
    if pos<len(record)+1:
        seqstr = str(record[pos:pos+1000].seq)
        dna_1000.write("\n"+">"+record.id+"_"+str(pos)+"\n"+seqstr)
        pos=pos+1000

Whether this is the best way to solve your problem (or whether this code even does what you expect) is another question that I don't have the background to answer. My only other suggestion is to read through http://biopython.org/wiki/SeqIO to see if any of the included IO functions would help.


text:
Q: Is it OK to pass (double ***) pointers using (void **)? I compile the code below with gcc using -Wall -Werror and it compiles cleanly, runs as expected; however, I'm just curious if it is OK, in ANSI and/or ISO C context, to pass a (double ***) pointer via (void **).
The ISO/IEC 9899:2017, section 6.6 - 9 says:

"The array-subscript [] and member-access . and -> operators,
  the address & and indirection * unary operators, and pointer
  casts may be used in the creation of an address constant, but the
  value of an object shall not be accessed by use of these operators."

In connection to this recommendation, the function allocateMatrix is, in fact, supposed to just allocate memory and return the corresponding address; so, please disregard the inner loop that assign values, it's there for test purposes only.
void allocateMatrix(int n, void **a) {
    int i = 0, j = 0;
    double **pTmp = calloc(n, sizeof(double *));

    for (i = 0; i < n; i++) {
        pTmp[i] = malloc(n * sizeof(double));

        // following loop is inserted to make sure code runs as expected
        // this does not exists in real code
        for (j = 0; j < n; j++) {
            pTmp[i][j] = (double)(i + 1) + (double)(j + 1) / 10.0f;
        }
    }

    *a = pTmp;
    return;
}

int main(int argc, char const *argv[]) {
    int i = 0, j = 0;
    int n = 5;
    double **a = NULL;

    // "a" is a (double **) pointer; so, "&a" is now a (double ***) pointer
    allocateMatrix(n, (void **)&a);

    // testing...
    for (i = 0; i < n; i++) {
        for (j = 0; j < n; j++) {
            printf("%6.2lf", a[i][j]);
        }

        printf("\n");
    }

    return 0;
}

A: The C standard allows for conversion to and from void *, however that lattitute does not exist for void **.
Change the function argument to void * and cast it appropriately and it will work.
void allocateMatrix(int n, void *a) {
    ...
    *(double ***)a = pTmp;
}

And change remove the cast from the function call:
allocateMatrix(n, &a);


text:
Q: org.apache.maven.surefire.booter.SurefireBooterForkException: There was an error in the forked process Test mechanism null When i am executing the tests through git bash i am getting build failure even after all tests are passing with the following error:
Git bash command - mvn clean install -B -Pdev -Dcucumber.options=-m -Dtest=EndToEndTestSuite
Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.22.2:test (default-test) on project acceptance-test: There are test failures.

 Please refer to dump files (if any exist) [date].dump, [date]-jvmRun[N].dump and [date].dumpstream.

 There was an error in the forked process
 Test mechanism :: null

 org.apache.maven.surefire.booter.SurefireBooterForkException: There was an error in the forked process
 Test mechanism :: null
at org.apache.maven.plugin.surefire
.booterclient.ForkStarter.fork(ForkStarter.java:656)
at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:282)
at org.apache.maven.plugin.surefire.booterclient.ForkStarter.run(ForkStarter.java:245)
at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeProvider(AbstractSurefireMojo.java:1183)
at org.apache.maven.plugin.surefire.AbstractSurefireMojo.executeAfterPreconditionsChecked(AbstractSurefireMojo.java:1011)
at org.apache.maven.plugin.surefire.AbstractSurefireMojo.execute(AbstractSurefireMojo.java:857)
at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:137)
         at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:210)
         at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:156)
         at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:148)
         at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:117)
         at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:81)
         at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:56)
         at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
         at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:305)
         at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:192)
         at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:105)
         at org.apache.maven.cli.MavenCli.execute(MavenCli.java:957)
         at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:289)
         at org.apache.maven.cli.MavenCli.main(MavenCli.java:193)
         at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
         at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
         at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
         at java.lang.reflect.Method.invoke(Method.java:498)
         at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:282)
         at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:225)
         at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:406)
         at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:347)

My surefire configurations in the pom.xml looks like this

<plugin>
  <artifactId>maven-surefire-plugin</artifactId>
  <version>3.0.0-M3</version>
  <configuration>
    <parallel>classes</parallel>
    <threadCount>2</threadCount>
    <useSystemClassLoader>false</useSystemClassLoader>
  </configuration>
</plugin>

Also, i am using junit version - 4.12
My intent here is to run tests parallelly so as to reduce build time.


text:
Q: Selecting specific links from large list I am new to javascript/jquery:
If i have a lot of links - how can i select specific ones. For example if i have 1000 links, each consisting of hrefs and link text - and i want to select 5 specific links, what is the easiest way to do this ?
My current solution is like so:
var firstLink = $('.link_list a').filter(function() {
        return $(this).text() === "Link One Text"; });
});
var secondLink = $('.link_list a').filter(function() {
        return $(this).text() === "Link Two Text"; });
});

This is keeping in mind, I want to only select specific links, see Select link by text (exact match).
This seems a bit messy to have a lot of variables defined using the same filter function over and over. Any other ideas ?

A: turn it into a function?
function getLinkByText(text){
   return $('.link_list a').filter(function() {
        return $(this).text() === text; });
   });
}

var firstLink = getLinkByText("Link One Text");
var secondLink = getLinkByText("Link Two Text");


text:
Q: Why isn't main.css found? NOTE: I'm using Jekyll
I was trying to link an external style sheet but it doesn't find the file (which is main.css)so I tried to check again its path and its name and it still didn't work. May I have your help please?
Here you can see an image of my folder and my code:

A: Try adding type="text/css" to your <link>:
<link href="_layouts/main.css" type="text/css" rel="stylesheet">

A: Your folder structures seems that you are using jekyll if yes! then you need to change folder name _layouts is reversed folder for layout in jekyll


text: Q: Mavericks server configuration for Rails app I have just downloaded OS X Server for Mavericks and now I want to run my Rails app through the server. I have downloaded and installed Passenger. My server runs under username.no-ip.biz and my Rails app is in Users/Username/documents/Developer/Rails/railsapp. First, how do I add a subdomain for the server like sub.username.no-ip.biz and second how do I setup the Server to use this subdomain to run my Rails app?


text:
Q: Select text of QLineEdit on focus I have created a dialog using QtDesigner. There is a QLineEdit object in the dialog with some default content. When the dialog initializes and the focus goes to the QLineEdit, I want the default content to be auto selected, so once the user start writing, the previous content will be overwritten.
EDIT:
In constructor:
dialog->accept();

and
connect( dialog, SIGNAL(accepted()), QlineObj, SLOT( selectAll() ) );

A: There is a simpler method to get almost the same behaviour, which is to set the default content using setPlaceholderText() instead of setText(). This will show the default content grayed out and as soon as the QLineEdit gains focus, it will disappear.

A: This is an older question, but nevertheless, I ended up here searching for a solution this exact problem. It can be solved in the following way:
Create a class derived from QLineEdit and override the focusInEvent in the header:
void focusInEvent(QFocusEvent *event) override;

Then implement it like so:
void MyLineEdit::focusInEvent(QFocusEvent *event)
{
    // First let the base class process the event
    QLineEdit::focusInEvent(event);
    // Then select the text by a single shot timer, so that everything will
    // be processed before (calling selectAll() directly won't work)
    QTimer::singleShot(0, this, &QLineEdit::selectAll);
}

Just in case anybody else wonders how this can be done ;-)

A: Call
lineEdit->selectAll();

after you set the default text. (In the dialog constructor, perhaps.)

A: You can use QApplication::focusChanged along with QTimer::singleShot to select all the text on a changed focus.
Normally your QApplication is declared in main, so use QObject::connect there, eg:
int main(int argc, char *argv[]) {
    QApplication a(argc, argv);
    My_Main_Window w();
    QObject::connect(&a, SIGNAL(focusChanged(QWidget*, QWidget*)),
                     &w, SLOT(my_focus_changed_slot(QWidget*, QWidget*)));
    w.show();

    return a.exec();
}

Remember to make the public slot in the My_Main_Window class:
public slots:
void my_focus_changed_slot(QWidget*, QWidget*);

Then in your definition of my_focus_changed_slot, check if the second QWidget* (which points to the newly focused widget) is the same as the QLineEdit you wish to select all of, and do so using QTimer::singleShot so that the event loop gets called, then the QLineEdit has the selectAll slot called immediately after, eg
void My_Main_Window::focus_changed(QWidget*, QWidget* new_widget) {
    if (new_widget == my_lineedit) {
        QTimer::singleShot(0, my_lineedit, &QLineEdit::selectAll);
    }
}

where my_lineedit is a pointer to a QLineEdit and is part of the My_Main_Window class.


text:
Q: How do Java TCP/IP sockets report transmission success or failure to the application? I am having a problem with Java TCP/IP sockets: my Java application will continue endlessly to send data to a server even if the server gets switched off (without a proper TCP/IP disconnect) in the meantime.
I am using the following code to send the data:
PrintWriter out = PrintWriter(socket.getOutputStream(), true);
out.write("text");

if (out.checkError()) {
   System.err.println("Error sending string!");
}

In another Stack Overflow question, I found the following answer:

TCP/IP (and therefor java sockets)
  will guarantee that you either
  successfully send the data OR get an
  error (exception in the case of java)
  eventually.

Is my code sufficient for getting informed about the TCP/IP stack not being able to successfully send my string or do I need to do something additionally?
Btw: was it correct to open a new question even though the other question was similar? It did not answer my question satisfactorily and I was only able to add a new answer, not a new comment.

A: You might have two problems: PrintWriter is a strange beast in the Java Stream/Reader/Writer world in that it swallows exceptions and requires you to explicitly check for errors.
The only use for this (in my opinion) are the standard streams (System.out and System.err), where failure to write output should not halt the application (for example if no standard output is available).
Replace that with an OutputStreamWriter and you'll be informed about errors as soon as Java knows about them.
That brings me to the second possible problem: TCP/IP doesn't have any automated keep-alive packets: so if your connection gets severed in some way, you won't actually notice it until you attempt to send data.
So if you connect to some socket, send some packets, wait a bit and then get disconnected, you will only be notified of the fact when you next try to send some data. This is inherent in the TCP/IP protocol and not the fault of Java.
If you want to reduce the problem, then you could send periodic keep-alive/ping messages with no actual effect, except that they check if the connection is still alive.

A: Your question is different enough I'd say. Google has a lot to say about this sort of thing though. The keep-alives (SO_KEEPALIVE) are not designed for this sort of thing. From what I have read the TCP spec says that they should not be sent more than once every two hours and it is up to your OS to manage it so you don't have much control. I emphasize from what I have read.
Whether you can use them more than once every two hours doesn't matter in your case though since you are continually sending data. Keep-alives are only needed if you want to detect a broken connection while you are not sending data.
If you were using the OutputStream of the Socket directly, it would throw an exception when you attempt to send to an unavailable destination (for whatever reason that may be). Since you are using PrintWriter, you need to check for errors manually using checkError().
So, in summary: Yes, it is sufficient for your purpose.

A: What I didn't mention (as I thought it was not relevant at that time) is that I am trying to do this on Android.
After several weeks of testing, though, it seems that Android's implementation of the standard Java networking classes is behaving very differently from the Oracle JRE. On Android, it is apparently impossible to reliably detect if the connection has been closed, even if I closed it myself. [Stream].write() will try writing for several minutes. So on Android, it appears that you will always need to send your own keep-alives (and check for reception!) for detecting a broken connection.
The other answers to this question will work fine with the Oracle JRE. Thanks again!
If anyone can provide further information on this topic, please do so.

A: Sometimes even though the server has died, your client application is not informed about it.  Usually this is a bad router somewhere failing to shut down both sides of the connection.  You should set up keep-alives so you can detect this kind of failure.
Depending on your OS there are ways to change the keep-alive test interval.

A: One special condition applies when you are closing the socket. Depending on the socket opt SO_LINGER (see this article) you set, the close() call will either return immediately or wait until all pending TCP transmissions were either  successful or an error occured, which is then signalled by an IOException thrown from the close() implementation.
Also SO_TIMEOUThas an effect on when retries will time out.


text:
Q: TopAnchor of viewController changin in iMessage Extension between presentation modes I'm making a survey iMessage app (yeah I know) and having a problem moving between the presentation modes. The series of screenshots below shows that when the app launches, all is fine in the compact mode. When expanded everything is still correct but then when I go back to compact the content is shifted down by what looks like the same height as the large messages nav bar (86 I believe)

I've tried setting the top constraint to be -86 when switching back to the compact view, however, this either does nothing or sends it back to where is should be and then subtracts 86 so it dissapears too high up. I've based this project on the IceCream example project from app so not sure where this issue is coming from (probably autolayout but everything is pinned to the layout guides)
Here's the code that adds the view controller:
func loadTheViewController(controller: UIViewController) {
    // Remove any existing child controllers.
    for child in childViewControllers {
        child.willMove(toParentViewController: nil)
        child.view.removeFromSuperview()
        child.removeFromParentViewController()
    }

    // Embed the new controller.
    addChildViewController(controller)

    controller.view.frame = view.bounds
    controller.view.translatesAutoresizingMaskIntoConstraints = true
    view.addSubview(controller.view)

    controller.view.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
    controller.view.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    controller.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
    controller.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true

    controller.didMove(toParentViewController: self)
}

I've been working on this for what feels forever so any suggestions welcome.

A: You are setting up constraints on view but you have set translatesAutoresizingMaskIntoConstraints to true. The autoresizing mask constraints will likely conflict with the constraints you are adding, cause unexpected results. You should change to:
controller.view.translatesAutoresizingMaskIntoConstraints = false

Also rather than pinning to view.topAnchor, you should pin to the topLayoutGuide, which will take the top navigation bar into account.
controller.view.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor).isActive = true

Similarly,
controller.view.bottomAnchor.constraint(equalTo: bottomLayoutGuide.topAnchor).isActive = true


text:
Q: jquery validate date field must be future I have a method
$.validator.addMethod("dateDDMMYYYY",
    function(value, element) {
        return value.match(/^(0?[1-9]|[12][0-9]|3[0-2])[.,/ -](0?[1-9]|1[0-2])[.,/ -](19|20)?\d{2}$/);
    },
    "* Please enter a valid date (dd/mm/yyyy)"
);

to check if a date entered is a valid dd/mm/yyyy date but I would like to modify (or create a new method) to check that the date entered is in the future and also check how far in the future.
For example I would like to show a message if the date entered is less than 2 days in the future but don't show the message if the date is greater than 2 days in the future.
Thanks in advance

A: Once you're certain it's a valid date, you could parse it and compare that with the current date:
// Assuming value is the date string.
var date = new Date(value);

// Create a new date, stripping the time away.
var today = new Date(new Date().toDateString());

// Subtracting one date from another gives you the number
//  of milliseconds between the two. Divide that down to days.
var daysInTheFuture = (date - today) / 1000 / 60 / 60 / 24;

A: the duration of two days in milliseconds is:
var twoDays = 2 * 24 * 60 * 60 * 1000

So you can create a date two days in the future like so:
var now = new Date()
var future = new Date(now.getTime() + twoDays)

Javascript also has a Date constructor like so:
new Date(year, month [, day, hour, minute, second, millisecond]);

So just extract the entered date using your regex (I'll let you do that)
var year = ...
var month = ...
var day = ...

var entered = new Date(year, month, day)

Then your test is:
entered - now > twoDays

if that expression is true, they have entered a date more than two days in the future.


text:
Q: Experiencing an undefined function error, using SQL queries with Javascript I am simply trying to have this one button implement a function that simply shows the users scores for the game overall. This data is updated in an Access DB each time the user plays the game. I don't know if this is an issue with my SQL queries or with my JavaScript coding. I simply need a popup window to display this information when the user clicks this button. Code is as follows:(Just a portion of the code that's supposed to display the popup window, nothing more.)
<button onclick="showscores()" style=" top: 155px; left: 160px; position: absolute;"> Show scores

var user = "FOO";

var myDB = new ACCESSdb("C:\\Users\\FOO\\Users.mdb", {showErrors:true});

function showscores(){
    // select and retrieve the user info data , containing the score data
    window.alert(myDB.query("SELECT * FROM userInfo WHERE UserName = 'username'));
}

A: You have a syntax error in your query - a missing closing double quote. It should be:
window.alert(myDB.query("SELECT * FROM userInfo WHERE UserName = 'username'"));

A: myDB should be declared within the function unless declared globally, its not clear in your example if that is the case.
function showscores(){
    var myDB = new ACCESSdb("C:\\Users\\FOO\\Users.mdb", {showErrors:true});
    // select and retrieve the user info data , containing the score data
    window.alert(myDB.query("SELECT * FROM userInfo WHERE UserName = 'username'"));
}


text:
Q: Angular + Ngrx : best practice to select a value in component and in function I have pretty much the same question as in ngrx get value in function , but I'm wondering if the answer (see comment in that topic) is still the best practice nowadays.
My situation is:

*

*I want to get 2 values from the store to show in my component --> I use a selector and the async pipe

*I need to pass those same values to an Angular Material dialog, to work with them in the dialogcomponent.

I have a working solution: I use subscribe functions in ngOnInit() and set a local variable with the value from the Observable. So I don't need to use the async pipe anymore and I can easily pass the value to some functions... This one sounds like the best option, but everywhere I look for answers I see "avoid using subscriptions".
So I'm wondering:

*

*is there a better way of handling this scenario?

*Or is this "the ngrx/rxjs way of handling this scenario"?

*Or do I use the selector Observable and async pipe to show the value in the component AND subscribe to the Observable to create a local variable to pass to my function (this seems a bit redundant...)

*Or ...?

My problem is that I want a consistent approach of handling ngrx values, but now it looks like I need to use 2 approaches depending on the scenario:

*

*Async pipe for showing values in component (preferred approach according to the community)

*Subscription when using values in local functions (community advises against the use of subscriptions "unless necessary")

(To my surprise: it's hard to find a clear answer on the internet ...)

A: Right, you need to avoid subscriptions. Use async pipe with as, ideally you'll have 0 subscriptions in your code.
In the component class we create a stream that selects data from store
export class MyComponent implements OnDestroy {
    public readonly data$: Observable<{
        user: User,
        items: Array<Item>,
    }>;

    constructor(protected readonly store: Store<StoreState>) {
        this.data$ = combineLatest([
            this.store.select(currentUser),
            this.store.select(someItems),
        ]).pipe(
            map(([user, items]) => ({
                user,
                items,
            })),
        );
    }

    public submit(user: User, item: Item): void {
        // some logic here
    }
}

and then in its template we have a wrapper that resolves it.
<ng-container *ngIf="data$ | async as data">

header

    <button *ngFor="let item of data.items" (click)="submit(data.user, item)">{{data.user.name}} {{item.name}}</button>

footer

</ng-container>


text:
Q: How to change a column value, based on a combination of values from two other columns in R? I have panel data for 300K individuals (ID's). Each ID has 1 row per year (2013-2016). Based on 'Code', the status of 'Name' is determined (per Year). However, there are still some errors. If one ID in my dataframe has a certain Name in a certain Year, I want to give everybody with the same Code and Year, also that Name for the same Code and Year. In case nobody has a name at Name for a specific Code and Year, then a NA would be sufficient. It is kinda tricky, because ID's can switch with Codes over the years (not within a year)..
For example: For ID #2, the Name for 2014 should change from NA to PIZZA, based on the fact that another ID in the dataframe (here #1) has 'PIZZA' for the same Code and Year. However, ID#3 and ID#4 stay both NA for 2016, because nobody with Code 05/1234 and Year 2016 has a Name in the dataframe.
    > str(Poging23)
tibble [16 x 5] (S3: tbl_df/tbl/data.frame)
 $ ID           : num [1:16] 1 1 1 1 2 2 2 2 3 3 ...
 $ Date_of_birth: POSIXct[1:16], format: "2000-05-25" "2000-05-25" "2000-05-25" "2000-05-25" ...
 $ Code         : chr [1:16] "01/1234" "01/1234" "01/1234" "01/1234" ...
 $ Year         : num [1:16] 2013 2014 2015 2016 2013 ...
 $ Name         : chr [1:16] "PIZZA" "PIZZA" "NA" "NA" ...

> dput(Poging23)
structure(list(ID = c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4,
4, 4, 4), Date_of_birth = structure(c(959212800, 959212800, 959212800,
959212800, 25315200, 25315200, 25315200, 25315200, 277862400,
277862400, 277862400, 277862400, 1267574400, 1267574400, 1267574400,
1267574400), class = c("POSIXct", "POSIXt"), tzone = "UTC"),
    Code = c("01/1234", "01/1234", "01/1234", "01/1234", "01/1234",
    "01/1234", "01/1234", "01/1234", "01/1234", "01/1234", "05/1234",
    "05/1234", "05/1234", "05/1234", "05/1234", "05/1234"), Year = c(2013,
    2014, 2015, 2016, 2013, 2014, 2015, 2016, 2013, 2014, 2015,
    2016, 2013, 2014, 2015, 2016), Name = c("PIZZA", "PIZZA",
    "NA", "NA", "NA", "NA", "PIZZA", "NA", "NA", "PIZZA", "NA",
    "NA", "PASTA", "PASTA", "PASTA", "NA")), row.names = c(NA,
-16L), class = c("tbl_df", "tbl", "data.frame"))

Unfortunately, these codes didn't work properly (didn't take changes in code over the years into account): How to change an ID's NA to character value, based on other ID's cell values/characteristics in R?.
Edit: I named NA to "NA" because I made a preview in Excel first.
It's is also okay to change all the Names to 1, and NA's to 0 if that makes it easier.
Hopefully someone can help me/give tips!
Thank you!

A: Function aggregate Name by Code and Year will show Names for each pair of factors. For each pair you can see if at least one name exist
aggregate(Name ~ Year + Code, dfx, function(x) {x[x != "NA"]})
  Year    Code         Name
1 2013 01/1234        PIZZA
2 2014 01/1234 PIZZA, PIZZA
3 2015 01/1234        PIZZA
4 2016 01/1234
5 2013 05/1234        PASTA
6 2014 05/1234        PASTA
7 2015 05/1234        PASTA
8 2016 05/1234

I will assume that each pair Year, Code must have always the same Name (could be repeated as in line 2) and only need the first
uu <- aggregate(Name ~ Year + Code, dfx, function(x) {x[x != "NA"][1]})
> uu
  Year    Code  Name
1 2013 01/1234 PIZZA
2 2014 01/1234 PIZZA
3 2015 01/1234 PIZZA
4 2016 01/1234  <NA>
5 2013 05/1234 PASTA
6 2014 05/1234 PASTA
7 2015 05/1234 PASTA
8 2016 05/1234  <NA>

Then for each row of uu matching rows in dfx, the corresponding Name can be assigned from uu$Name
for (i in 1:nrow(uu)) {
  dfx[
     dfx$Name=="NA"
     & dfx$Code == uu[i, "Code"]
     & dfx$Year == uu[i, "Year"] , "Name" ] <- uu[i, "Name"]
}
> dfx
   ID Date_of_birth    Code Year  Name
1   1    2000-05-25 01/1234 2013 PIZZA
2   1    2000-05-25 01/1234 2014 PIZZA
3   1    2000-05-25 01/1234 2015 PIZZA
4   1    2000-05-25 01/1234 2016  <NA>
5   2    1970-10-21 01/1234 2013 PIZZA
6   2    1970-10-21 01/1234 2014 PIZZA
7   2    1970-10-21 01/1234 2015 PIZZA
8   2    1970-10-21 01/1234 2016  <NA>
9   3    1978-10-22 01/1234 2013 PIZZA
10  3    1978-10-22 01/1234 2014 PIZZA
11  3    1978-10-22 05/1234 2015 PASTA
12  3    1978-10-22 05/1234 2016  <NA>
13  4    2010-03-03 05/1234 2013 PASTA
14  4    2010-03-03 05/1234 2014 PASTA
15  4    2010-03-03 05/1234 2015 PASTA
16  4    2010-03-03 05/1234 2016  <NA>

A: A possible solution within the tidyverse universe can be carried out as following. I divided the procedure in steps so it is more clear and understandable.
First, we create a lookup table that contains, for each combination of Code and Year, all the values in Name that are different from "NA"
library(tidyverse)

lookup <- Poging23 %>%
  group_by(Code, Year) %>%
  group_modify(~unique(.$Name) %>% enframe(name = NULL, value = "Name")) %>%
  filter(Name != "NA")

# A tibble: 6 x 3
# Groups:   Code, Year [6]
#   Code     Year Name
#   <chr>   <dbl> <chr>
# 1 01/1234  2013 PIZZA
# 2 01/1234  2014 PIZZA
# 3 01/1234  2015 PIZZA
# 4 05/1234  2013 PASTA
# 5 05/1234  2014 PASTA
# 6 05/1234  2015 PASTA

Afterwards, we use a left join between the original dataset and this lookup table
Poging23 %>%
  select(-Name) %>%
  left_join(lookup, by = c("Code", "Year"))

The final output should be as you expect
# A tibble: 16 x 5
#       ID Date_of_birth       Code     Year Name
#    <dbl> <dttm>              <chr>   <dbl> <chr>
#  1     1 2000-05-25 00:00:00 01/1234  2013 PIZZA
#  2     1 2000-05-25 00:00:00 01/1234  2014 PIZZA
#  3     1 2000-05-25 00:00:00 01/1234  2015 PIZZA
#  4     1 2000-05-25 00:00:00 01/1234  2016 NA
#  5     2 1970-10-21 00:00:00 01/1234  2013 PIZZA
#  6     2 1970-10-21 00:00:00 01/1234  2014 PIZZA
#  7     2 1970-10-21 00:00:00 01/1234  2015 PIZZA
#  8     2 1970-10-21 00:00:00 01/1234  2016 NA
#  9     3 1978-10-22 00:00:00 01/1234  2013 PIZZA
# 10     3 1978-10-22 00:00:00 01/1234  2014 PIZZA
# 11     3 1978-10-22 00:00:00 05/1234  2015 PASTA
# 12     3 1978-10-22 00:00:00 05/1234  2016 NA
# 13     4 2010-03-03 00:00:00 05/1234  2013 PASTA
# 14     4 2010-03-03 00:00:00 05/1234  2014 PASTA
# 15     4 2010-03-03 00:00:00 05/1234  2015 PASTA
# 16     4 2010-03-03 00:00:00 05/1234  2016 NA

If you want to avoid dividing the procedure in smaller steps, just combine the chunks of code as following
library(tidyverse)

Poging23 %>%
  select(-Name) %>%
  left_join(Poging23 %>%
              group_by(Code, Year) %>%
              group_modify(~unique(.$Name) %>% enframe(name = NULL, value = "Name")) %>%
              filter(Name != "NA"),
            by = c("Code", "Year"))


text:
Q: Why do I keep getting "The type of the SQL statement could not be determined." error in my Firebird 2.5.3 EntityFramework 6 Code First project? I have been messing around with a code first project using the Firebird Entity Framework Provider 4.9.0, Firebird ADO.NET Data provider 4.9.0 and EntityFramework 6.1.3 with a Firebird 2.5.3 database server. Here is the Git Repo .
I have tried to keep this sample super simple. I want to point out that in my sample borrowed some code from a post about EntityValidationErrors and it work excellent.
When the sample is run the database is generated but this error and stacktrace are returned:
System.ArgumentException was unhandled
  HResult=-2147024809
  Message=The type of the SQL statement could not be determined.
Statement: -- Tables

-- Foreign Key Constraints

-- EOF.
  Source=FirebirdSql.Data.FirebirdClient
  StackTrace:
       at FirebirdSql.Data.Isql.FbScript.Parse()
       at FirebirdSql.Data.EntityFramework6.FbProviderServices.DbCreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection) in C:\Users\Jiri\Documents\devel\NETProvider\working\NETProvider\src\FirebirdSql.Data.FirebirdClient\FirebirdClient\FbProviderServices.cs:line 417
       at System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection connection, Nullable`1 commandTimeout, StoreItemCollection storeItemCollection)
       at System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase()
       at System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection)
       at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
       at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
       at System.Data.Entity.Internal.DatabaseCreator.CreateDatabase(InternalContext internalContext, Func`3 createMigrator, ObjectContext objectContext)
       at System.Data.Entity.Internal.InternalContext.CreateDatabase(ObjectContext objectContext, DatabaseExistenceState existenceState)
       at System.Data.Entity.Database.Create(DatabaseExistenceState existenceState)
       at System.Data.Entity.CreateDatabaseIfNotExists`1.InitializeDatabase(TContext context)
       at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf`1.<CreateInitializationAction>b__e()
       at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
       at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
       at System.Data.Entity.Internal.LazyInternalContext.<InitializeDatabase>b__4(InternalContext c)
       at System.Data.Entity.Internal.RetryAction`1.PerformAction(TInput input)
       at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action`1 action)
       at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
       at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
       at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
       at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
       at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
       at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
       at System.Data.Entity.DbSet`1.Add(TEntity entity)
       at FirebirdEF6Test.Program.Main(String[] args) in C:\Users\Todd\Documents\VSTesting\FirebirdEF6Test\FirebirdEF6Test\Program.cs:line 19
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException:

I am a novice to the Entitiy Framework.  But in most of the tutorials I saw it was possible to generate the database and tables without having to completely define the table in code.  Is this not the case with Firebird?
Thanks for any guidance. Have an amazing day!

A: I want to give credit to @Mark Rotteveel for pointing me in the right direction and @Jiri Cincura for fixing the bug.  After upgrading my test project to the latest versions:

EntityFramework.Firebird 4.10.0.0 & FirebirdSql.Data.FirebirdClient 4.10.0.0

The project built the database as expected. Its very nice. I have updated the GitRepo to be a working sample. Couple of issues: I am not sure if it is the package manager or me, but, first I had issues with "Set-ExecutionPolicy" in powershell the package manager did not allow me to use update-package. I got a error about the policy.  Changed the policy to "Unrestricted" did not help.  So I right clicked the project and tried to update them with the package manager there and it did.  But sadly when I looked at the references they were missing.  Utimately:

*

*I restarted VS2015

*Removed each package 1 by 1.

*Restarted again

*Added EntityFramework.Firebird 4.10.0.0 back.

*Updated FirebirdSql.Data.FirebirdClient from 4.5.0.0(default) to 4.10.0.0

All that to say be careful when using the package manager my experience has told me it does not always behave like you would expect.  Also make sure that you check you app.config that it updated correctly
  <runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
  <dependentAssembly>
    <assemblyIdentity name="FirebirdSql.Data.FirebirdClient" publicKeyToken="3750abcc3150b00c" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-4.10.0.0" newVersion="4.10.0.0" />
  </dependentAssembly>
</assemblyBinding>

Have an amazing and fruitful day!


text:
Q: How to pass JSON data from MVC4 to Flot without writing an adapter I am generating data for Jquery flot in my MVC controller and want to use more sophisticated structure where I would be able to change colors for each bar etc..
to do this I need to pass data structure that looks following
{
label: "y = 3",
data: [[0, 3], [10, 3]]
}

I had no problem passing data when it was simple array by simply getting the data and shaping it like following
var data = topAgents.Select(agent => new List<object>
        {
            agent.User != null ? string.Format("{0}", agent.User).Replace("SAGANTGB\\", "") : null,
            agent.Amount
        }).ToList();

        return Json(data, JsonRequestBehavior.AllowGet);

and in javascript side:
function onAgentDataReceived(series) {
        $("#agents").empty();
        $.plot("#agents", [series], { bars: { show: true, barWidth: 0.6, align: "center" }, xaxis: { mode: "categories", tickLength: 0 } });
    }

However now I can't seem to be able to shape data into such a structure that would fit what $.plot is expecting.
So far I have tried:
KeyValue pair:
var grouped = result.GroupBy(o => o.CREATE_USER_ID).Select(agent => new
                {
                    data = new KeyValuePair<string,int>(
                    agent.Key != null ? string.Format("{0}", agent.Key).Replace("SAGANTGB\\", "") : null, agent.Count()
                        ),
                    color = "yellow"
                }).ToList();

Object with properties:
var grouped =  result.GroupBy(o => o.CREATE_USER_ID).Select(agent => new
                {
                    data = new { A=
                    agent.Key != null ? string.Format("{0}", agent.Key).Replace("SAGANTGB\\", "") : null, B = agent.Count()
                        },
                    color = "yellow"
                }).ToList();

Name Value collection
var grouped =    result.GroupBy(o => o.CREATE_USER_ID).Select(agent => new
                {
                    data = new NameValueCollection
                    {{
                        agent.Key != null ? string.Format("{0}", agent.Key).Replace("SAGANTGB\\", "") : null,  agent.Count().ToString()}
                    },
                    color = "yellow"
                }).ToList();

Anonymous object array
var grouped = result.GroupBy(o => o.CREATE_USER_ID).Select(agent => new
                {
                    data = new object[] { agent.Key != null ? string.Format("{0}", agent.Key).Replace("SAGANTGB\\", "") : null,  agent.Count()},
                    color = "yellow"
                }).ToList();

but none of them flied
IMHO simple data = new object { agent.Key,  agent.Count()},
should work but it fails on build with: Error  16  Invalid anonymous type member declarator. Anonymous type members must be declared with a member assignment, simple name or member access..
I could reshape the data in JS after retrieving it however would like to avoid this unnecessary step.
How do I pass data from MVC to javascript without having to reshape it on JS end?

A: After writing this question for 20 minutes, succeeded on next try
 var grouped =
   result.GroupBy(o => o.CREATE_USER_ID).Select(agent => new
    {
        data = new List<List<object>>
        {
            new List<object>
            {
                agent.Key != null ? string.Format("{0}", agent.Key).Replace("SAGANTGB\\", "") : null,
                agent.Count()
            }
        },
        color = "yellow"
    }).ToList();

return Json(grouped, JsonRequestBehavior.AllowGet);

Apparently you need to double wrap it in list.
Forgot to mention there is no longer need to wrap in in array on JS side
 $.ajax({
        url: '/dashboard/Home/CancellationAgents/',
        type: "GET",
        dataType: "json",
        success: onCancellationAgentsReceived
    });

    function onCancellationAgentsReceived(series) {
        $("#agentcancellations").empty();
        $.plot("#agentcancellations", series, {
            bars: { show: true, barWidth: 0.7, align: "center" }, xaxis: {mode: "categories", tickLength: 0, position: "bottom"}});
    }

Hope this saves you some time


text:
Q: Why use an IDE? This may be too opinionated, but what I'm trying to understand why some companies mandate the use of an IDE. In college all I used was vim, although on occasion I used netbeans for use with Java. Netbeans was nice because it did code completion and had some nice templates for configuration of some the stranger services I tried.
Now that my friends are working at big companies, they are telling me that they are required to use eclipse or visual studio, but no one can seem to give a good reason why.
Can someone explain to me why companies force their developers into restricted development environments?

A: IDE vs Notepad
I've written code in lots of different IDEs and occasionally in notepad.  You may totally love notepad, but at some point using notepad is industrial sabatoge, kind of like hiring a gardener who shows up with a spoon instead of a shovel and a thimble instead of a bucket.  (But who knows, maybe the most beautiful garden can be made with a spoon and a thimble, but it sure isn't going to be fast)
IDE A vs IDE B
Some IDE's have team and management features.  For example, in Visual Studio, there is a screen that finds all the TODO: lines in source code. This allows for a different workflow that may or may not exist in other IDEs.  Ditto for source control integration, static code analysis, etc.
IDE old vs IDE new
Big organizations are slow to change. Not really a programming related problem.

A: Because companies standardize on tools, as well as platforms--if your choice of tools is in conflict with their standards then you can either object, silently use your tool, or use the required tool.
All three are valid; provided your alternative doesn't cause other team-members issues, and provided that you have a valid argument to make (not just whining).
For example: I develop in Visual Studio 2008 as required by work, but use VS2010 whenever possible.  Solutions/Projects saved in 2010 can't be opened in 2008 without some manual finagling--so I can't use the tool of my choice because it would cause friction for other developers.  We also are required to produce code according to documented standards which are enforced by Resharper and StyleCop--if I switched to a different IDE I would have more difficulty in ensuring the code I produced was up to our standards.

A: If you're good at using vim and know everything there is to know about it, then there is no reason to switch to an IDE. That said, many IDEs will have lots of useful features that come standard. Maintaining an install of Eclipse is a lot easier than maintaining an install of Vim with plugins X, Y, and Z in order to simulate the same capabilities.

*

*IntelliSense is incredibly useful. I realize that vim has all sorts of auto-completion, but it doesn't give me a list of overloaded methods and argument hints.

*Multiple panes to provide class hierarchies/outlines, API reference, console output, etc.. can provide you more information than is available in just multiple text buffers. Yes, I know that you have the quickfix window, but sometimes it's just not enough.

*Compile as you type. This doesn't quite work for C++, but is really nice in Java and C#. As soon as I type a line, I'll get feedback on correctness. I'm not arrogant enough as a programmer to assume that I never make syntax errors, or type errors, or forget to have a try/catch, or... (the list goes on)

And the most important of all...

*

*Integrated Debuggers. Double click to set a break point, right click on a variable to set a watch, have a separate pane for changing values on the fly, detailed exception handling all within the same program.

I love vim, and will use it for simple things, or when I want to run a macro, or am stuck with C code. But for more complicated tasks, I'll fire up Eclipse/Visual Studio/Wing.

A: Sufficiently bad developers are greatly assisted by the adoption of an appropriately-configured IDE.  It takes a lot of extra time to help each snowflake through his own custom development environment; if somebody doesn't have the chops to maintain their own dev environment independently, it gets very expensive to support them.
Corporate IT shops are very bad at telling the difference between "sufficiently bad" and "sufficiently good" developers.  So they just make everybody do the same thing.
Disclaimer: I use Eclipse and love it.

A: Theoretically, it would decrease the amount of training needed to get an unexperienced developer to deal with the problems of a particular IDE if all the team uses that one tool.
Anyway, most of the top companies don't force developers to use some specific IDE for now...
I agree with this last way of thinking: You don't need your team to master one particular tool, having team knowledge in many will improve your likelyhood to know better ways to solve a particular roblems.

A: For me, I use Visual Studio with ReSharper.  I cannot be nearly as productive (in .Net) without it.  At least, nobody has ever shown me a way to be more productive... Vim, that is great.  You can run Vim inside of Visual Studio + R# and get all the niceties that the IDE provides, like code navigation, code completion and refactoring.

A: Same reason we use a hammer to nail things instead of rocks.  It's a better tool.
Now if you are asking why you are forced to use a specific IDE over another, well that's a different topic.
A place that uses .NET will use Visual Studio 99% of the time, at least that's what I've seen.  And I haven't found anything out there that is better than Visual Studio for writing .NET applications.

A: Features like these aren't available in vim:

*Refactoring

*Integrated debuggers

*Knowing your code base as an integrated whole (e.g., change a Java class name; have the change reflected in a Spring XML configuration)

*Being able to run an app server right inside the IDE so you can deploy and debug your code.

Those are the reasons I choose IntelliJ.  I could go back to sticks and bones, but I'd be a lot less productive.

A: There is much more than code completion into an IDE:

*

*debugging facilities

*XML validation

*management of servers

*automatic imports

*syntax checking

*graphical modeling

*support of popular technologies like Hibernate, TestNG or Spring

*integration of source code management

*indexing of file names for quick opening

*follow "links" in code: implementation, declaration

*integration of source code control

*searching for classes or methods

*code formatting

*process monitoring

*one click/button debugging/building

*method/variable/field/... renaming

etc
Nothing to do with incompetence from the programmers. Anybody would be A LOT less productive using vim for developing a big Java EE application.

A: How big were you projects at college? A couple of classes in a couple of files? Or rather a couple of hundreds of classes in a couple of hundreds of files?
Today I had the "honor" of looking at a file in a rather large project where the programmer opted to use vi (yes vi, not vim) and a handcrafted commandline compiler call (no make). The file contained on function spanning about 900 lines with a series of if-else-if-else-constructs (because that way you have all your code in one place!!!!!!). Macho-Programmer at his finest.

A: OK there are very good reasons for enforcing a particular toolset within a production environment:

*

*Companies want to standardize everything so that if an employee leaves they can replace that person with minimal effort.

*Commercial IDEs provide a complex enough environment to support a single interface for a variety of development needs and supporting varying levels of code access. For instance the same file-set could be used by the developer, by non-programmers (graphics designers etc.) and document writers.

*Combine this with integrated version control and code management without the need of someone learning a particular version control system, all of a sudden IDEs start to look nicer and nicer.

*It also streamlines maintenance of build systems in a multi-homed environment.

*IDEs are easier to give tutorials to via phone or video, and probably come with those.
etc. etc. and so forth.
The business decision making behind enforcing a standardized environment goes beyond the preference of a single programmer or for that matter perhaps the understanding of the programming team.

A: Using an IDE helps an employee to work with huge projects with minimal training. Learn a few key combos - and you will comfortably work with multi-thousand-file project in Eclipse, IDE handles most of the work for you under the hood. Just imagine how many years of learning it takes to feel comfortable developing such projects in Vim.
Besides, with an IDE it is easy to support common coding standards across the entire team: just set a couple of options and an IDE will force you to write code in a standardized way.
Plus, IDE gives a few added bonuses like refactoring tools (especially good in Eclipse), integrated debugging (especially good in Visual Studio), intellisense, integrated unit tests, integrated version control system etc.
The advantages and disadvantages of using an IDE also greatly depends on the development platform. Some platforms are geared towards the use of IDEs, others are not. As a rule of thumb, you should use IDE for Java and .Net development (unless you're extremely advanced); you should not use IDE for ruby, python, perl, LISP etc development (unless you're extremely new to these languages and associated frameworks).

A: As said before, the question about using an IDE is basicaly productivity. However there is some questions that should be considered by the company when choosing a specific IDE. that includes:

*

*Company culture

*Standardize use of tool, making it accessible for all developers. That easies training, reduces costs and improve the speed of learn curve.

*Requirements from specific contract. As an example, there are some development packages that are fully supported (i.e. plugins) by some IDE and not by anothers. So, if you are working with the support contract you will want to work with the supported IDE. A  concrete example is when you are working with not common OS like VxWorks, where you can work with the Workbench (that truely is an eclipse with lot of specific plugins for eclipse).

*Company policy (and also I include the restriction on company budget)

*Documentation relating to the IDE

*Comunity (A strong one can contribute and develop still further the IDE and help you with your doubts)

*Installed Base (no one wants to be the only human to use that IDE on the world)

*Support from manufacturers (an IDE about to be discontinued probably will not be a good option)

*Requirements from the IDE. (i.e. cross platform or hardware requirements that are incompatible with some machines of the company)

Of course, there is a lot more. However, I think that this short list help you to see that there is some decisions that are not so easy to take, when we are talking about money and some greater companies.
And if you start using your own IDE think what mess will be when another developer start doing maintenance into your code. How do you think will the application be signed at the version manager ? Now think about a company with 30+ developers each using its own IDE (each with its own configuration files, version and all that stuff)...

A: http://xkcd.com/378/
Real programmers use the best tools available to get the job done.  Some companies have licenses for tools but there's nothing saying you can't license/use another IDE and then just have the other IDE open to copy/paste what you've done in your local IDE.

A: The question is a bit open-ended, perhaps you can make it community wiki...
As you point out, the IDE can be useful, or even a must have, for some operations, like refactoring, or even project exploring: I use Eclipse at my work, on Java projects, and I find very useful to get a list of all occurrences of the usage of a public method or a class in a project. Likely, I appreciate to be able to rename it from where it is defined, and having all these occurrences automatically updated.
The fact I have the JavaDoc displayed when hovering over a name is very nice too. Like autocompletion, jump to a class name, etc.
And, of course, debugging facilities...
Now, usage of Eclipse isn't mandatory in our shop! Some years ago, some people used the Delphi IDE (forgot its name), I tried NetBeans, etc. But I think we de facto standardized on Eclipse, but it was a natural evolution rather than a company policy. And we often just open files in a text editor when we need a quick update...


text:
Q: Change Instance Variable Based on Controller Name - RoR I am looking to make things DRY with the following partial:
<div class="controls <%= 'hide' if @videos.total_pages == 1 and !administrator? %>">
  <% if administrator? %>
    <%= link_to "New #{controller_name.capitalize.singularize}", new_video_path, {:style => "margin-right: 10px;"} %>
  <% end %>
  <%= will_paginate @videos, :class => "pagination", :inner_window => 1 %>

As you can see there is @videos appearing twice. Can I change these based solely on the controller name, similar to the link_to?

A: I would advise against this type of refactoring. There's a fine line between DRY-ness and readability. Too much abstraction can make your code difficult to understand and debug later, both for you and other people. So in my opinion, repeating an instance variable name a few times throughout a template is not a bad thing because you can tell at a glance what the code is supposed to be doing without thinking about the different contexts in which it will run.
Similarly, your link_to name is a bit too clever. I would also change it to simply say "New Video". Yeah, you may need a few identical partials (one for each controller) but their purpose and the way they execute will be a lot more clear.
Lastly, it looks like you're calling hide on video controls based on whether the user is an administrator. That's not very good design though since anyone who reads through the page's source can unhide the controls by changing the visibility/display values. I don't know what the rest of your code does though so maybe you're OK with that.

A: So while it may be just better not to go to crazy with the refactoring; the code below would solve the issue, if the technique would be needed:
<% @group = instance_variable_get("@#{controller_name}") %>

<div class="controls <%= 'hide' if @group.total_pages == 1 and !administrator? %>">
  <% if administrator? %>
    <%= link_to "New #{controller_name.capitalize.singularize}", controller: "#{controller_name}", action: "new", :style => "margin-right: 10px;" %>
  <% end %>
  <%= will_paginate @group, :class => "pagination", :inner_window => 1 %>

Now, the partial is usable across several views with similar functionality (ie photos)


text:
Q: How to remove a session variable after leaving the page?
After clicking on the search button I am saving the search string in a session variable and then loading the index again.

$(document).on('click', '#search', function(e) {
  var search_key = $("#key").val().toLowerCase();
  var pathname = window.location.pathname;
  var arr = pathname.split("/");
  var urlStr = window.location.protocol + "//" + window.location.host + "/" + arr[1] + "/" + arr[2] + "/SearchData?key=" + search_key;

  $.get(urlStr, function(data) {         //calling SearchData action
    console.log(window.location);
    urlStr = window.location.protocol + "//" + window.location.host + pathname;
    window.location.href = urlStr;       //calling index action for loading the data
  });
});

[HttpPost]
public void SearchData(string key) {
  Session.Add("search_key", key);
}

If the any session variable exist for search key the the index action returns data according to the search value otherwise returns all data. and also sending the search key through ViewBag.

ViewBag.search_key = search_key;

<input type="text" id="key" placeholder="Search data" name="search" value="@(ViewBag.search_key != null ? ViewBag.search_key : string.Empty)" />

Fetching the search key from ViewBag for showing the search key even after loading the page  with search results.
What I want is to remove search key and show all data after the page is fully refreshed or navigated to another page. is that possible to do? It should not remove the search key if only pagination index changes within the same page.

A: if you need that, you can use localStorage it is very useful and easy.
you can try it.
https://www.w3schools.com/jsref/prop_win_localstorage.asp

A: I think you can use Session.Remove("search_key").
Another way could be, to set the session variable for "search_key" to an invalid value e.g. string.Empty and evaluate this in your index.


text:
Q: lsmeans contrast for interaction term I'm attempting use lsmeans and its contrast for an F-test on an interaction. Basically, I'd like to replicate what Stata does with its contrast command. I'd like to do this for two reasons:

*

*within a regression model that has an interaction between factor variables;

*within an ANOVA to help decompose a three-way interaction.
For this question, I'll ask about the three-way interaction.
library(haven)
threeway <- read_spss("https://stats.idre.ucla.edu/wp-content/uploads/2016/02/threeway.sav")
threeway$ID <- row.names(threeway)

library(afex)
three_fit <- aov_ez("ID", "y", data = threeway, between = c("a", "b", "c"))
three_fit

> three_fit
Anova Table (Type 3 tests)

Response: y
  Effect    df  MSE          F ges p.value
1      a 1, 12 1.33 112.50 *** .90  <.0001
2      b 1, 12 1.33       0.50 .04     .49
3      c 2, 12 1.33  47.84 *** .89  <.0001
4    a:b 1, 12 1.33 120.13 *** .91  <.0001
5    a:c 2, 12 1.33     6.84 * .53     .01
6    b:c 2, 12 1.33    8.47 ** .59    .005
7  a:b:c 2, 12 1.33    6.97 ** .54    .010
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '+' 0.1 ' ' 1

The three-way interaction is significant. Now, from the UCLA page on Stata, Stata can use the code:
contrast b#c@a

This will produce an F-test for the b*c interaction at the levels of a.
I'm trying to do the same thing with lsmeans in R. But, I just can't get it. Here's what I've tried:
library(lsmeans)
lsm <- lsmeans(three_fit, c("b", "c"), by="a")
test(contrast(lsm, "consec"), joint=TRUE)

That gets me an F-test, but it is not correct (or at least it is not the one I want). Any help in replicating the Stata results would be appreciated. I'd really like to stay within lsmeans to do this, but if something else works, I'll take it.

A: I think what you're looking for is
test(contrast(lsm, interaction = "consec"), joint=TRUE)

That is, you want to test interaction contrasts, not comparisons among means. You can see what it is you're testing (I recommend that!) by running that contrast call without wrapping it in test. Try it with and without the interaction keyword.


text:
Q: How to make custom dialogs I have 9 imageButton in my activity view and they're defined by id's such as imageButton1 ~ imageButton9 I need to create dialog/alert/popup either of them in order to show more details regarding to each image button.
Question
As this is my very first attempt with android studio and I've read docs also some websites posts about dialogs yet it is very confusing to me, so the question is how do i create dialogs for each of imageButtons?
Code
xml file
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#00FFFFFF"
        android:drawingCacheQuality="high"
        tools:context=".ShapesActivity">

    <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:background="?attr/colorPrimary"
            android:theme="@style/ThemeOverlay.AppCompat.ActionBar" />

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="65dp"
            android:orientation="horizontal"
            android:weightSum="3">

        <ImageButton
                android:id="@+id/imageButton1"
                android:layout_width="0dp"
                android:layout_height="146dp"
                android:layout_weight="1"
                android:background="#006B2D2D"
                android:contentDescription="@string/triangleDesc"
                android:scaleType="fitCenter"
                app:srcCompat="@drawable/triangle" />

        <ImageButton
                android:id="@+id/imageButton2"
                android:layout_width="0dp"
                android:layout_height="146dp"
                android:layout_weight="1"
                android:background="#006B2D2D"
                android:contentDescription="@string/trapezoidDesc"
                android:scaleType="fitCenter"
                app:srcCompat="@drawable/trapezoid" />

        <ImageButton
                android:id="@+id/imageButton3"
                android:layout_width="0dp"
                android:layout_height="146dp"
                android:layout_weight="1"
                android:background="#006B2D2D"
                android:contentDescription="@string/starDesc"
                android:scaleType="fitCenter"
                app:srcCompat="@drawable/star" />
    </LinearLayout>

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="210dp"
            android:orientation="horizontal"
            android:weightSum="3">

        <ImageButton
                android:id="@+id/imageButton4"
                android:layout_width="0dp"
                android:layout_height="146dp"
                android:layout_weight="1"
                android:background="#006B2D2D"
                android:contentDescription="@string/squareDesc"
                android:scaleType="fitCenter"
                app:srcCompat="@drawable/square" />

        <ImageButton
                android:id="@+id/imageButton5"
                android:layout_width="0dp"
                android:layout_height="146dp"
                android:layout_weight="1"
                android:background="#006B2D2D"
                android:contentDescription="@string/rectangleDesc"
                android:scaleType="fitCenter"
                app:srcCompat="@drawable/rectangle" />

        <ImageButton
                android:id="@+id/imageButton6"
                android:layout_width="0dp"
                android:layout_height="146dp"
                android:layout_weight="1"
                android:background="#006B2D2D"
                android:contentDescription="@string/octagonDesc"
                android:scaleType="fitCenter"
                app:srcCompat="@drawable/octagon" />
    </LinearLayout>

    <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="357dp"
            android:orientation="horizontal"
            android:weightSum="3">

        <ImageButton
                android:id="@+id/imageButton7"
                android:layout_width="0dp"
                android:layout_height="146dp"
                android:layout_weight="1"
                android:background="#006B2D2D"
                android:contentDescription="@string/heartDesc"
                android:scaleType="fitCenter"
                app:srcCompat="@drawable/heart" />

        <ImageButton
                android:id="@+id/imageButton8"
                android:layout_width="0dp"
                android:layout_height="146dp"
                android:layout_weight="1"
                android:background="#007E2F2F"
                android:contentDescription="@string/diamondDesc"
                android:scaleType="fitCenter"
                app:srcCompat="@drawable/diamond" />

        <ImageButton
                android:id="@+id/imageButton9"
                android:layout_width="0dp"
                android:layout_height="146dp"
                android:layout_weight="1"
                android:background="#00E040FB"
                android:contentDescription="@string/circleDesc"
                android:scaleType="fitCenter"
                app:srcCompat="@drawable/circle" />
    </LinearLayout>

</RelativeLayout>

kotlin file
import android.content.Intent
import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.*
import androidx.appcompat.widget.Toolbar

class ShapesActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_shapes)

        val toolbar = findViewById(R.id.toolbar) as Toolbar;
        setSupportActionBar(toolbar);

    //menu items actions
    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        val inflater = menuInflater as MenuInflater
        inflater.inflate(R.menu.items, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) {
        R.id.settings_page -> {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
                val intent = Intent(this, SettingActivity::class.java);
                startActivity(intent);
            };
            true
        }

        else -> {
            // If we got here, the user's action was not recognized.
            // Invoke the superclass to handle it.
            super.onOptionsItemSelected(item)
        }
    }
}

Logic
I need to have 4 item in each dialog (different data for each imageButton),

*

*Image

*Text

*Play sound Button

*Dialog Close Button

Any idea?
Update
Based on answer below here is latest codes that I have
dialog_custom.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent" android:layout_height="match_parent">

    <ImageView
        android:id="@+id/dialog_imageview"
        android:layout_width="294dp"
        android:layout_height="246dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_centerInParent="true"
        android:layout_marginStart="68dp"
        android:layout_marginTop="274dp"
        android:layout_marginEnd="69dp"
        android:layout_marginBottom="270dp"
        android:foregroundGravity="center"
        tools:srcCompat="@tools:sample/avatars[0]" />

    <TextView
        android:id="@+id/tv_text"
        android:layout_width="298dp"
        android:layout_height="104dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="54dp"
        android:layout_marginTop="474dp"
        android:layout_marginEnd="59dp"
        android:layout_marginBottom="154dp"
        android:gravity="center_vertical"
        android:text="TextView"
        android:textAlignment="center"
        android:textSize="30sp" />

    <Button
        android:id="@+id/close_btn"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="274dp"
        android:layout_marginTop="680dp"
        android:layout_marginEnd="70dp"
        android:layout_marginBottom="63dp"
        android:background="#F50057"
        android:gravity="center"
        android:text="Close"
        android:textAlignment="center"
        android:textColor="#FFFFFF" />

    <Button
        android:id="@+id/play_btn"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_marginStart="52dp"
        android:layout_marginTop="680dp"
        android:layout_marginEnd="292dp"
        android:layout_marginBottom="63dp"
        android:background="#00E676"
        android:gravity="center"
        android:text="Play"
        android:textAlignment="center" />
</RelativeLayout>

activity kotlin file
class BuildingsActivity : BaseActivity() {

    lateinit var mAdView : AdView;
    lateinit var context : Context

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_buildings)

        // open dialog
        val imageButton1 = this.findViewById(R.id.imageButton1) as ImageButton;
        imageButton1.setOnClickListener() {
            openDialog();
        }

    }

    // button dialog
    public fun openDialog() {
        val dialog = Dialog(context)
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setContentView(R.layout.dialog_custom)

        val tv_text = dialog.findViewById(R.id.tv_text)as TextView
        val btn_close = dialog.findViewById(R.id.close_btn) as Button
        val btn_play = dialog.findViewById(R.id.play_btn) as Button
        val imageView = dialog.findViewById(R.id.dialog_imageview) as ImageView

        imageView.setImageResource(R.drawable.school) //set image here
        tv_text.setText("School")  // set description here

        //insert your button function here
        btn_close.setOnClickListener {
            fun onClick(v: View) {
                dialog.dismiss()
            }
        }

        btn_play.setOnClickListener {
            fun onClick(v: View) {
                val mp: MediaPlayer? = MediaPlayer.create(this, R.raw.a)
                mp?.start();
            }
        }

        dialog.show();
    }
}

Problem
when I click on image that supposed to open this dialog my screen becomes blank and return to main activity.
Ideas?

A: Try this, your btnclose and btnplay have unnecessary codes
class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        var imageButton1 = findViewById(R.id.imageButton1) as ImageButton //add your imagebuttons here

        imageButton1.setOnClickListener { // provide/add setsetOnClickListener for all imagebutton

            val description = imageButton1.getContentDescription().toString()
            val drawable = imageButton1.getDrawable()
            val mp = MediaPlayer.create(R.raw.imageButton1soundDialogCustom())

            openDialog(drawable, description, mp)
        }

    }

     fun openDialog(drawable: Drawable, description: String, mp: MediaPlayer ) {
        val dialog = Dialog(this@MainActivity)
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE)
        dialog.setContentView(R.layout.dialog_custom)

        val tvtext  = dialog.findViewById(R.id.tv_text)as TextView
        val btnclose = dialog.findViewById(R.id.close_btn) as Button
        val btnplay = dialog.findViewById(R.id.play_btn) as Button
        val imageView = dialog.findViewById(R.id.dialog_imageview) as ImageView

        imageView.setImageDrawable(drawable)//set image here
        tvtext.setText(description)

        btnclose.setOnClickListener {

                dialog.dismiss()

        }

        btnplay.setOnClickListener {

            val mp: MediaPlayer? = MediaPlayer.create(this, R.raw.a)
            mp?.start()
        }

         dialog.show()
    }
}


text:
Q: NSSortDescriptor can't count numbers at all With this
    NSSortDescriptor *lessonDescriptor = [[NSSortDescriptor alloc] initWithKey:@"lesson" ascending:YES];
[resultArray sortUsingDescriptors:[NSArray arrayWithObject:lessonDescriptor]];

it's sorting the "lesson"-objects to
(
    {
    lesson = 9;
    subject = bg;
},
    {
    lesson = 8;
    subject = bg;
},
    {
    lesson = 11;
    subject = CAE;
},
    {
    lesson = 11;
    subject = CAE;
},
    {
    lesson = 10;
    subject = CAE;
},
    {
    lesson = 10;
    subject = CAE;
},
    {
    lesson = 5;
    subject = Gg;
},
    {
    lesson = 4;
    subject = G;
},
    {
    lesson = 3;
    subject = G;
},
    {
    lesson = 2;
    subject = M;
},
    {
    lesson = 1;
    subject = M;
}

)
as you can see it's not counting correctly.. Can somebody help?
thanks alot
edit:
don't know how to implement the value thing =)
else if ([currentElement isEqualToString:@"lesson"])
{

    NSString *trimmedString = [string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    NSLog(@"trimmed: %@",trimmedString);
    int value = [trimmedString intValue];   ??
    [currentSummary appendString:value];  ??

    [currentSummary appendString:trimmedString];
}

A: You have to trim the string before converting the 'lesson' into numbers in order for the sort descriptors to work correctly. Otherwise, the sort descriptor sees only string values not numbers. This is how you remove the whitespace and newline characters:
NSString *stringValue = [parsedValue stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];

A call to [stringValue intValue] will get the integer value of the string
int value = [stringValue intValue];

Save this value into the array before calling the sort descriptors on this attribute.
Tell me if it works.

A: It sorted it just right.  After all, every entry is a string, and in a string "10" is before "9" after all...
Now if you wanted to sort it the way you expected to sort it, you either need to hold NSNuumber objects and sort that, or have strings held in normalized form like "08", "09", "10", and then possibly trim off leading 0's from the string later.

A: [NSSortDescriptor sortDescriptorWithKey:@"self"
                              ascending:YES
                             comparator:^(id obj1, id obj2){
    return [(NSString*)obj1 compare:(NSString*)obj2
                            options:NSNumericSearch];
 }];

sorts a range from 0 - 1000000..... onwards.


text:
Q: User access to documents in Umbraco - think I am doing something wrong As I understand it, the only way to control which documents an editor can create/edit/delete/publish is by choosing their start node?
In the case, say, of an intranet, there might be users who can edit 'news' documents but nothing else.
Would I then create a news 'root' node, with news items being allowable child documents.
But if I then give those users the news 'root' node as their starting point, yes, they can create news documents as planned, but surely they can also edit, unpublish (!) or even delete (!!!!!!!!!!!!!) the 'root' node which destroys everything.
My testing seems to support this.
Is there another way?

A: You are right in your understanding of the "start node" concept, as well as your editors being able to mess with the root node. But realistically, will they do that, just because they can?
In the past, we've used a simple true/false property on all nodes to determine whether the node can be deleted. We called it "undeletable", and set in on nodes that were extra important not to get removed by accident. It does NOT prevent users from going to that node, remove the check mark in "Undeletable?", save the node, and THEN delete it, but then it's no longer by accident.
We hooked into miscellaneous events and checked for the property - if undeletable == true on the node or any of its children, trashing/deleting/unpublishing would be cancelled.
I've made a quick update to the methods to use ContentService, but I haven't tested them. Grab'em from here: https://gist.github.com/jannikanker/b1864522fa0b86da89903f05d107518a


text:
Q: angularjs sub-controller - accessing variables Assume I have the following:

{{person.name}}

[LOTS OF COMPLICATED DATA RELATED TO A PERSON THAT I NEED TO ORGANIZE IN A CONTROLLER]

then I have two controllers
app.controller('PeopleCtrl', ['$scope', function($scope){ $scope.people = [etc, etc, etc ];}];
app.controller('PersonCtrl', ['$scope', function($scope){ HOW DO I ACCESS THE PERSON OBJECT IN THIS CONTROLLER? }];

In the above PersonCtrl, how do I access the "person" object referred to in ng-repeat?

A: You can simply access it under $scope.person in the PersonCtl. Nested scopes inherit from their upper scope.
See an example at http://plnkr.co/edit/EeFOoUEagmsIHL3XlUBx?p=preview:
HTML:

          First Name: {{person.firstName}}

          Last Name: {{person.lastName}}

          Full Name (from PersonCtrl): {{person.fullName}}

JS:
var app = angular.module('plunker', []);

app
.controller('MainCtrl', function($scope) {
  $scope.name = 'World';
})
.controller('PeopleCtrl', function($scope) {
  $scope.people = [
    { id: '0', lastName: 'White', firstName: 'Walt'},
    { id: '1', lastName: 'Black', firstName: 'Hank'}
  ];
})
.controller('PersonCtrl', function($scope) {
  console.log('PersonCtrl');
  console.log($scope.person);

  $scope.person.fullName = $scope.person.lastName + ', ' + $scope.person.firstName;
});

A:  app.controller('PersonCtrl', ['$scope', function($scope){
      $scope.name;
 });

A: It will be available under the same name as the parent controller. To see what variables have been inherited simply go into the child controller and console.log($scope) this is an object and in the debugger console you can expand it and see if you have set up your inheritance correctly.
As controllers inherit from each other using prototypical inheritance they will look further up the chain for the name if it it not found on their current scope.
Here is a plunkr:
http://plnkr.co/edit/WwZC8tMW0swjKDAS7n4B
angular.module('app', [])
 .controller('PeopleCtrl', function($scope) {
$scope.people = [{name: 'Bob'}, {name: 'Steve'}, {name: 'Jim'}]
 })

.controller('PersonCtrl', function($scope) {
   console.log($scope.people)
 });

HTML:

{{person.name}}

[LOTS OF COMPLICATED DATA RELATED TO A PERSON THAT I NEED TO ORGANIZE IN A CONTROLLER]