text:
Q: IE compatible markup for ARIA combobox I'm taking another stab at finding a way to make Ext JS Combobox components to be compatible with IE/JAWS. Presently we're using the following markup:

        Choose:

                <input id="combobox-1011-inputEl" type="text" name="choose"
                    role="combobox" aria-readonly="false"
                    aria-haspopup="true" aria-expanded="true"
                    aria-autocomplete="none" aria-owns="boundlist-1014-listEl"/>

Option 1

Option 2

This works reasonably well in Firefox with JAWS and NVDA; however JAWS in IE will announce the input field as "edit" when focused.
After reading WAI-ARIA Combobox pattern until cross-eyed and experimenting for several days I'm ready to admit that IE is just too buggy to make combos work reliably. Or maybe it's not IE itself but rather MSAA/UIA bridge as suggested in this comment. This could as well be true because I found at least one combination of ARIA attributes that appeared to be working well in IE8/XP with JAWS (uses MSAA) but did not work in IE11/Win7 with JAWS (MSAA/UIA).
The markup can be changed to some degree; what I cannot change is the existence of the wrapping elements like bodyEl, triggerWrap, and inputWrap. These elements are necessary to apply relevant CSS classes, render error indicator elements when input validation fails, etc.
Another constraint is that the listbox element is rendered outside of the component element. This can be changed but not easily; also rendering it adjacent to the input does not seem to help at all. It should be worth mentioning that the list itself is rendered dynamically on first expand, with aria-owns attribute added after the fact.
What I tried so far:

*

*Placing role="combobox" on the outer element. Does not do anything useful, combo is not recognized as such.

*Placing role="combobox" and relevant attributes on the inputWrap. This way IE will announce "Choose edit combo" when input is focused directly; when tabbing from another element it will announce that element's role instead, along with the combo label. Quite funny but not really helpful.

*Placing role="combobox" on the triggerWrap and assigning role="button" to the trigger pseudo-button. In theory this should be close to the first design pattern but combo is not recognized as such.

*Many other ad-hoc combinations, most of which I don't recall anymore.
The only quasi working way is placing combobox role on the inputWrap and making inputWrap tabbable instead of the actual input. This corresponds with markup in this example that appears to be more or less working with IE/JAWS; however this solution is very undesirable since it opens Pandora's box full of very hairy focus management bugs.
Unfortunately the Accessibility inspection tools are not entirely useful in this case because what I need is a workaround for bugs in the existing implementation, not stricter standard compliance.
Another obstacle to better understanding is ambiguity in the WAI-ARIA spec. For example, for the first pattern it is required that "the first element within the combobox is an input text field". Does that mean first structural element (i.e. non-presentational), or absolutely first child element? Modifying markup either way does not seem to make any difference for IE, unless the wrapper
 is tabbable.
Sorry if this post looks more like a rant ;) but it's actually a question: is there a way to work around IE deficiencies by applying ARIA attributes to our existing markup elements? If not, what can be changed to making it work (barring tabbable wrapper)? And ultimate bonus points for insights into why this is not working as expected.
I would appreciate any hints and suggestions. I'm very much concerned with our combos not being fully accessible in IE and would like to resolve this issue if possible. I still have a faint hope that someone out there might possess a secret ingredient recipe to make both IE and JAWS happy with each other. ;)
UPDATE: Here's an example fiddle. Note how combo is announced properly in Firefox but it's just "edit" in IE11 (tested with JAWS 16). For better results with the screen reader I recommend to use Open outside of Fiddle option that is available in Share menu.

A: I also faced the same problem for our custom combobox widget. I found that if you mark input field readonly and use role="combobox" on input field then JAWS on IE reads it as combobox. This solution has some issues like normal user can't type the text to filter the combobox.

A: I too have had all sorts of issue when trying to cater for JAWS & NVDA in various browsers. We solved the issue many times by using the aria-describedby property. When the focus is on the element, the screen reader will (in most cases) ready the corresponding text which is often hidden from view.
Here is the spec for it. https://www.w3.org/TR/WCAG20-TECHS/ARIA1.html


text:
Q: how to get json from this webservice http://docs.apis.is/ I'm having trouble to connect to docs.apis.is with php curl. Could anyone help get the connection with php and save the resource to json file witch I can work from.
This is what I have done so far
<?php
    $service_url ='http://apis.is/cinema';
    $curl = curl_init($service_url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $curl_response = curl_exec($curl);

    if ($curl_response === false) {
     $info = curl_getinfo($curl);
     curl_close($curl);
     die('Error occured during curl exec:'. var_export($info));
    }
   curl_close($curl);

   //get file and insert it into json
   $json_string = json_encode($data, JSON_PRETTY_PRINT);
   json_encode($curl, JSON_PRETTY_PRINT);
   file_put_contents('json/cinema_data.json', $curl_response);

 ?>

I dont seem do make the connection. So if you could help me to solve this and turn me in the right way to use ajax to display the json text to my html page.
Thank you

A: ...
curl_close($curl);
$json_string = json_encode(json_decode($curl_response), JSON_PRETTY_PRINT);
file_put_contents('json/cinema_data.json', $json_string);

Note JSON_PRETTY_PRINT improves readability of the JSON data for humans, but it also makes the file a lot bigger.
Also note that $curl_response is already a JSON string, it is just not "prettyfied".

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I Reset the Width in CSS? I am having a problem with some new CSS due to an update of our plugin. The page in question is here: https://www.renophil.com/event/ghostbusters-in-concert/
Basically from the title below the image down to the share icons should be a left column. Then the description that starts with "Kick off your Halloween weekend..." should be a larger right column.
We are using Wordpress and Visual Composer. The left column uses the class of vc_col-sm-4 and the right uses vc_col-sm-8. These are set to have the correct widths and work on mobile devices.
.vc_col-sm-4 {
    width: 33.33333333%;
}

.vc_col-sm-8 {
    width: 66.66666667%;
}

The problem is that the plugin we use for the events (The Events Calendar) has this CSS rule:
.tribe-events-single>.tribe_events>:not(.primary,.secondary,.tribe-events-related-events-title,.tribe-related-events) {
    order: 1;
    width: 100%;
}

which is overriding the width of my columns mentioned above. I thought I could fix it with width:auto but it didn't work. Is there a way to cancel it or do I have to add !important to the .vc-col-sm-4 and .vc-col-sm-8 code?

A: Try adding specificity to the classes controlling the widths when that overriding events class is present. This should help get you in the right direction.
@media (min-width: 768px) {
     .tribe-events-single > .tribe_events .vc_col-sm-4 {
         width: 33.33333333%;
     }
     .tribe-events-single > .tribe_events .vc_col-sm-8 {
         width: 66.66666667%;
     }
 }

A: The CSS rule:
.tribe-events-single>.tribe_events>:not(.primary,.secondary,.tribe-events-related-events-title,.tribe-related-events) {
    order: 1;
    width: 100%;
}

has a greater DOM precision and has priority. You can use !important as you said:
.vc_col-sm-4 {
    width: 33.33333333% !important;
}

.vc_col-sm-8 {
    width: 66.66666666% !important;
}

or add Additional CSS from the theme preview mode and target the id element #tribe-events-content
div#tribe-events-content div.vc_col-sm-4 {
    width: 33.33333333%%;
}

div#tribe-events-content div.vc_col-sm-8 {
    width: 66.66666666%;
}


text:
Q: Format a Date and returning a Date, not a String I need to get the Date of the current time with the following format "yyyy-MM-dd'T'HH:mm:ss"
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

I know how to format a Date using SimpleDateFormat. At the end I get a String. But I need to get the formatted Date, not String, and as far as I know, I cannot convert back a String to a Date, can I?
If I just return the Date, it is a Date but it is not properly formatted:
Timestamp ts = new Timestamp(new Date().getTime());

EDIT:
Unfortunately I need to get the outcome as a Date, not a String, so I cannot use sdf.format(New Date().getTime()) as this returns a String.
Also, the Date I need to return is the Date of the current time, not from a static String. I hope that clarifies

A:
But I need to get the formatted Date, not String, and as far as I know, I cannot convert back a String to a Date, can I?

Since you know the DateTime-Format, it's actually pretty easy to format from Date to String and vice-versa. I would personally make a separate class with a string-to-date and date-to-string conversion method:
public class DateConverter{

    public static SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    public static Date convertStringToDate(final String str){
        try{
            return DATE_FORMAT.parse(str);
        } catch(Exception ex){
            //TODO: Log exception
            return null;
        }
    }

    public static String convertDateToString(final Date date){
        try{
            return DATE_FORMAT.format(date);
        } catch(Exception ex){
            //TODO: Log exception
            return null;
        }
    }
}

Usage:
// Current date-time:
Date date = new Date();

// Convert the date to a String and print it
String formattedDate = DateConverter.convertDateToString(date);
System.out.println(formattedDate);

// Somewhere else in the code we have a String date and want to convert it back into a Date-object:
Date convertedDate = DateConverter.convertStringToDate(formattedDate);

A: tl;dr
ZonedDateTime.now()                                   // Capture the current moment as seen by the people of a region representing by the JVM's current default time zone.
    .format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )  // Generate a String representing that value using a standard format that omits any indication of zone/offset (potentially ambiguous).

java.time
The modern approach uses the java.time classes.
Capture the current moment in UTC.
Instant instant = Instant.now() ;

View that same moment through the wall-clock time used by the people of a particular region (a time zone).
ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
ZonedDateTime zdt = instant.atZone( z ) ;  // Same moment, same point on the timeline, different wall-clock time.

You want to generate a string representing this value in a format that lacks any indication of time zone or offset-from-UTC. I do not recommend this. Unless the context where read by the user is absolutely clear about the implicit zone/offset, you are introducing ambiguity in your results. But if you insist, the java.time classes predefine a formatter object for that formatting pattern: DateTimeFormatter.ISO_LOCAL_DATE_TIME.
String output = zdt.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME ) ;

About java.time
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.
Where to obtain the java.time classes?

*

*Java SE 8, Java SE 9, Java SE 10, and later

*

*Built-in.

*Part of the standard Java API with a bundled implementation.

*Java 9 adds some minor features and fixes.

*Java SE 6 and Java SE 7

*

*Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.

*Android

*

*Later versions of Android bundle implementations of the java.time classes.

*For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

A: Try this way
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

Date date = sdf.parse("2016-03-10....");

A: use my code, I hope it's works for you......
 SimpleDateFormat dateFormat= new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
 String str_date=dateFormat.format(new Date());

A: To format a data field do this
Date today = new Date();
        //formatting date in Java using SimpleDateFormat
        SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String date2= DATE_FORMAT.format(today);

        Date date;
        try {
            date = DATE_FORMAT.parse(date2);
             setDate(date); //make use of the date
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

The above works for me perfectly.

A: a parse method should be available to you. Use intellisense to check what methods your objects have :) Or simply look at the javadoc, most IDE's have an option to open the java files.
String dateString = "2016-01-01T00:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date d = sdf.parse(dateString);

A: Try this:
LocalDateTime ldt = Instant.now()
                    .atZone(ZoneId.systemDefault())
                    .toLocalDateTime()

A: If you want String to Date conversion, you need to parse Date in String format using DateFormat. This is an example -
    String target = "2016-03-10T15:54:49";
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
    Date result =  df.parse(target);

A: public String getCurrentDateTime() {
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
        // get current date time with Date()
        Date date = new Date();
        return dateFormat.format(date);

    }

A: Time Format should be same or else get time parser exception come
String dateString = "03/26/2012 11:49:00 AM";
    SimpleDateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss aa");
    Date convertedDate = new Date();
    try {
        convertedDate = dateFormat.parse(dateString);
    } catch t(ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(convertedDate);

A: Yes u can :)
you can convert back a String to a Date.
This method will help you:  Date parse(String date);
It returns Date class object. You just have to pass the date in String format in this method.
import java.text.*;
import java.util.*;

class Test {
    public static void main(String[] args)  throws Throwable {

    String date = "2016-03-10T04:05:00";

    SimpleDateFormat s = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");

    Date d = s.parse(date);

    System.out.println(d);
   }
}


text:
Q: Deterministic non-nullable truncate function for datetime I was looking for a deterministic truncate function for datetime and this one did the job:
DATEADD(dd, DATEDIFF(dd, 0, @date), 0)

But this is supposed to be the input to a persisted computed column which will be a part of the primary key, so it has to be non-nullable. So I made this:
ISNULL(DATEADD(dd, DATEDIFF(dd, 0, @date), 0), '01.01.1900')

But now the expression became non-deterministic. Can anyone tell me why, and how I can make it deterministic?
Thanks!

A: 01.01.1900 isn't deterministic...
This is:
ISNULL(DATEADD(dd, DATEDIFF(dd, 0, @date), 0), CONVERT(datetime, '19001010', 112)))

or this
ISNULL(DATEADD(dd, DATEDIFF(dd, 0, fooDT), 0), 0)

For more, see Why is my CASE expression non-deterministic? which leads to best way to convert and validate a date string

A: ISNULL(DATEADD(dd, DATEDIFF(dd, 0, @date), 0), 0)

That is, my guess is the non-deterministic part is '01.01.1900', because it depends on the locale settings.

A: Don't use string constant, use some arbitrary number instead of '01.01.1900'


text:
Q: How do I change the color of javascript text? So I have some JavaScript that creates separate text.
When I call it, to make the typing text, I do something like:

text here

But, the background of my webpage is black, and it prints the line ending array:
new Array("\\", "|", "/", "-"); return " " + ar[i.length % ar.length]; });

as black.
How would I make it white?

A: Remove the font tag first and foremost. It's not used anymore and you certainly don't need it in this case.
To colour the text, use the following code:
document.getElementById("w00t").style.color = "#FFFFFF";

A: First of all I would be careful of what tags you use.  have both been deprecated and soon won't be supported.
Use classes or styles to change the text color.
#w00t
{
color:white;
}

A: Since I'm assuming you're old school with the  tag, etc., add this to your  so it looks something like this:

A: Use CSS styling.  Set the style.color of the element to the color you want.


text:
Q: Set component state, from unreachable variable How I can get media.duration to live in a state environment ?
Right now I don't have access to it, even after trying to change state
  handleClick(e) {
        e.preventDefault();

    var reader = new FileReader();
    reader.readAsDataURL(this.state.uploadedFile);
    reader.onload = function() {
      var media = new Audio(reader.result);
      media.onloadedmetadata = function() {
        console.log(media.duration); // <-- THIS WORKS!!!!!!!!!!!!!!
      };
    };
    console.log(media.duration) //<------THIS DOES NOT WORK!!!!!!!!!!
    console.log("The link was clicked.");
    console.log(this.state.duration);
}

from: How to get duration of video when I am using filereader to read the video file?
_________________________________________
I tried this but it did not work
    this.setState({duration:media.duration},()=>{
console.log(this.state.duration)
})

A: It's because you use media variable is out of the scope.
Please try this one.
handleClick(e) {
    e.preventDefault();
    var reader = new FileReader();
    reader.readAsDataURL(this.state.uploadedFile);
    reader.onload = () => {
      var media = new Audio(reader.result);
      media.onloadedmetadata = () => {
        console.log(media.duration); // <-- THIS WORKS!!!!!!!!!!!!!!
        this.setState({duration: media.duration});
      };
    };
}


text:
Q: Fabric plugin in Android Studio Unable to connect to the network I have installed Fabric plugin in Android Studio. But I'm unable to work with it because when I'm trying to login "Unable to connect to the network" error appears. Web version only gives guidance on how to install the plugin. Vicious circle.
Android studio 2.3.3, Fabric for Android Studio plugin version 4.1.1.
Any ideas on the issue?
Update
Here is the screenshot of the error message:


text:
Q: What's a good way to reduce duplication in these two iterators? I wrote an iterator for easier access to some paged DB results but what's a good way to reduce the duplication?
foo_iterator.go
type FooIterator struct {
    hasNext   bool
    app       *App
    batchSize int
}

func NewFooIterator(app *App, batchSize int) *FooIterator {
    return &FooIterator{
        hasNext:   true,
        app:       app,
        batchSize: batchSize,
    }
}

func (it *FooIterator) HasNext() bool {
    return it.hasNext
}

func (it *FooIterator) Next() []*model.Foo {
    offset := 0
    batch := it.app.GetAllFoosInPages(offset, it.batchSize)
    if len(batch) < it.batchSize {
        it.hasNext = false
    }
    offset += it.batchSize
    return batch
}

bar_iterator.go
type BarIterator struct {
    hasNext   bool
    app       *App
    batchSize int
}

func NewBarIterator(app *App, batchSize int) *BarIterator {
    return &BarIterator{
        hasNext:   true,
        app:       app,
        batchSize: batchSize,
    }
}

func (it *BarIterator) HasNext() bool {
    return it.hasNext
}

func (it *BarIterator) Next() []*model.Bar {
    offset := 0
    batch := it.app.GetAllBarsInPages(offset, it.batchSize)
    if len(batch) < bi.batchSize {
        it.hasNext = false
    }
    offset += it.batchSize
    return batch
}

Usage
fooIterator := NewFooIterator(a, 100)

for fooIterator.HasNext() {
    fooBatch := rolesIterator.Next()
    // Do stuff
}

They're both so similar there must be some good way to share code but everything I have tried seems awkward.

A: Write a common iterator that calls a function to get more data:
type Iterator struct {
    more      func(offset int, batchSize int) (int, interface{})
    hasNext   bool
    batchSize int
    offset    int
}

func (it *Iterator) HasNext() bool {
    return it.hasNext
}

func (it *Iterator) Next() interface{} {
    n, batch := it.more(it.offset, it.batchSize)
    if n < it.batchSize {
        it.hasNext = false
    }
    it.offset += n
    return batch
}

Use it like this:
func NewFooIterator(app *App, batchSize int) *Iterator {
    return &Iterator{
        hasNext:   true,
        batchSize: batchSize,
        more: func(offset int, batchSize int) (int, interface{}) {
            batch := it.app.GetAllFoosInPages(offset, it.batchSize)
            return len(batch), batch
        },
    }
}

fooIterator := NewFooIterator(a, 100)

for fooIterator.HasNext() {
    fooBatch := fooIterator.Next().([]*model.Foo)
    // Do stuff
}


text:
Q: Error while executing c file developed using lex and yacc tools I am trying to develop a program which converts infix expression to postfix expression using lex and yacc tools.
Here is the source code :
(Lex program: ipi.l)
 ALPHA [A-Z a-z]
 DIGIT [0-9]
 %%
 {ALPHA}({ALPHA}|{DIGIT})*    return ID;
 {DIGIT}+                                      {yylval=atoi(yytext); return ID;}
 [\n \t]                                              yyterminate();
 .                                                      return yytext[0];
 %%

(Yacc program: ipi.y)
%{
#include <stdio.h>
#include <stdlib.h>
%}
%token    ID
%left    '+' '-'
%left    '*' '/'
%left    UMINUS

%%

S    :    E
E    :    E'+'{A1();}T{A2();}
     |    E'-'{A1();}T{A2();}
     |    T
     ;
T    :    T'*'{A1();}F{A2();}
     |    T'/'{A1();}F{A2();}
     |    F
     ;
F    :    '('E{A2();}')'
     |    '-'{A1();}F{A2();}
     |    ID{A3();}
     ;

%%

#include "lex.yy.c"
char st[100];
int top=0;

main()
{
 printf("Enter infix expression:  ");
 yyparse();
 printf("\n");
}

A1()
{
  st[top++]=yytext[0];
}

A2()
{
 printf("%c",st[--top]);
}

A3()
{
  printf("%c",yytext[0]);
}

However it is giving the following error :
/usr/lib/gcc/i686-linux-gnu/4.6/../../../i386-linux-gnu/liby.a(yyerror.o): In function `yyerror':
 (.text+0x1c): undefined reference to `rpl_fprintf'
 collect2: ld returned 1 exit status

Please help me out solving this.
Thanks in advance.

A: You should provide your own yyerror, like this one:
void yyerror (char *s) {
    fprintf (stderr, "%s\n", s);
}

Source:
http://lists.gnu.org/archive/html/help-bison/2012-01/msg00016.html


text:
Q: Vertically floating social icon buttons with jQuery Is there a way to create sticky (floating), vertical icon buttons for a page using jQuery or other library? The buttons are centered vertically on the left or the right of the screen as a bar, and remain in the same location when the user scrolls. Here's an example of a library that generates the buttons for Wordpress: http://www.clickonf5.org/cute-profiles
Thanks.

A: What you are looking for is a cross-browser implementation of the CSS position:fixed property.
There's the JQuery UI Position Plugin and other implementations like this.


text:
Q: ¿Como mostrar un dato de un archivo TXT consecutivamente en un Text View? Tengo un archivo txt con información (Datos) dentro de si, encapsulados mediante " ". De la siguiente forma:
"Dato uno"
"Dato dos"
"Dato tres"
...
"Dato N"

Entonces para leer la informacion utilizo:
val text:String
            val filename = "informacion.txt"
            val inputStream = resources.openRawResource(R.raw.informacion)
            var inputStreamReader: InputStreamReader = InputStreamReader(inputStream)
            var bufferedReader: BufferedReader = BufferedReader(inputStreamReader)
            text = bufferedReader.readLine().toString()

Y asi mismo la muestro en el TextView:
txtFrase?.setText(text)

Todo esto cada que se presiona un botón, pero al tocar el botón que llama todo esto, muestra solo el primer dato, vuelvo a presionar el botón y el mismo; Pretendo que cada que presione el botón se muestre el siguiente dato, se vuela a presionar y el siguiente
Desconozco como funcionan las clases BuferefReadere e inputStreamReader, por ende no sabría como implementarle un ciclo o algún contador, espero me puedan ayudar. Gracias.

A: Si tu archivo tiene pocas líneas puedes leer todas al principio y guardarlas en memoria. Luego simplemente almacenas el índice de la linea que estás mostrando y lo incrementas cada vez que presionas el botón
val lines = resources.openRawResource(R.raw.informacion).bufferedReader().readLines()
var currentLine = 0
txtFrase?.text = lines[0]
someButton.setOnClickListener {
    txtFrase?.text = lines.getOrElse(currentLine++) { "Fin de la lista" }
}

La otra opción es leer línea por línea. De esta forma no necesitas un contador pero tendrás que cerrar manualmente el reader cuando termines de usarlo
val reader = resources.openRawResource(R.raw.informacion).bufferedReader()
someButton.setOnClickListener {
    txtFrase?.text = reader.readLine() ?: "Fin de la lista"
}

A: Primero define una variable que se incrementarà y obtendrà el valor de la linea en el archivo:
var contador : Int = 0;

cuando des clic al botòn usas el valor de la variable contador que serà usado como indice para obtener el valor en la linea del archivo, este valor se incrementarà , asì que cada vez que des clic al botòn se obtendrà la siguiente linea de tu archivo:
        val inputStream = resources.openRawResource(R.raw.informacion)

        val lineList = mutableListOf<String>()
        inputStream.bufferedReader().forEachLine { lineList.add(it) }
        text = lineList.elementAt(contador) //Obtiene valor de linea en archivo.
        contador++

        txtFrase?.setText(text)


text:
Q: Different ways of setting properties in Ember What is the difference between:
myObject.set('some_property', 'myvalue');

and
Ember.set(myObject,'some_property', 'myvalue');

I am using the first syntax, but I noticed, that many people use the second one with Ember.set(). So what is the difference here?

A: @Igor,
myObject.set() vs Ember.set(myObject..) matters only if myObject is unknown.
If you are getting myObject as user input, then it's always better to use `Ember.set(myObject, 'some_property', 'myValue') since we will not be sure if myObject is empty or not. For example:
let myObject = {};
myObject.set('some_property', 'myValue');

Output will be: Uncaught TypeError: myObject.set is not a function(…). However, if use Ember.set, then
let myObject = {};
Ember.set(myObject, 'some_property', 'myValue');

The property will be set without throwing any error.
So, the ember tip would be to use Ember.set if the JS object is unknown otherwise, you can use .set().
Stefan Penner had given an amazing explanation regarding this in reddit. Here is the link: https://www.reddit.com/r/emberjs/comments/3mr5as/question_why_use_embergetthis_prop_instead_of/
Hope it helps.


text:
Q: Dropdown default option error in Laravel Blade In my laravel blade, I'm trying to display the default dropdown option which is Select role in French
{!! Form::select('roles', $roles, array_merge(['' => 'Veuillez sélectionner un rôle'], $roles), ['class' => 'form-control txt_txt']) !!}

But this keeps giving me an error,
array_merge(): Expected parameter 2 to be an array, object given

I'm populating that dropdown from the DB, with user roles, Following is my eloquent from the controller
$roles = Role::where('name','<>','Admin')->orderBy('name')->pluck('name', 'name');

How can I display the default option correctly?

A: You are using the Form::select incorrectly. It should be like:
Form::select(name, list, selected, selectAttributes, optionsAttributes, optgroupsAttributes);

So your code should be like this:
{!!
Form::select(
    'roles',
    array_merge(['' => 'Veuillez sélectionner un rôle'], $roles->toArray())
    '',
    array(
        'class' => 'form-control txt_txt'
    ))
!!}


text:
Q: how to get device information on Android app from IBM bluemix I have created an app using IOT boilerplate in IBM Bluemix and added a devices as described in http://www.ibm.com/developerworks/cloud/library/cl-mqtt-bluemix-iot-node-red-app/.
I have following queries

*

*Is there a way I can retrieve devices information (Authentication Token, Organization ID) from my Android app. As at present, after creating the devices I need to fill this information manually in my Android app which may not be feasible in real life scenario.

*Is there a way I can create this device on IBM Bluemix from Android App.
Regards,
Sengar

A: You can register a new device via the HTTP API. With this your android app can register it's self and will be given the required tokens to log into the service.


text:
Q: How to improve performance of the query joining on string basis? I have two table

*

*order Table

*marketplace_payment Table

An order table contain a field marketplace_ref_no Having Type varchar(24) Collation utf_general_ci
A marketplace_payment Table contains this field with same name marketplace_ref_no Having Type varchar(24) Collation utf_general_ci
However When I am trying to join both the tables, It is taking 2 minutes 48 second to execute. What are the measures should i take?

A: You might consider indexing the columns. This will have the effect of reducing the number of rows that must be searched. Read more here
https://dev.mysql.com/doc/refman/5.0/en/mysql-indexes.html


text:
Q: PHP cURL error: SSL certificate problem: self signed certificate Long story short, I had to reinstall php 7.4 on my Mac.  I have a php webapp that hits a .NET API.  Prior to the reinstall of php, I was able to hit a locally running version of my API at https://localhost:5001 using cURL in php but now I get a response code of 0 with this error:
Curl error: SSL certificate problem: self signed certificate

If I point the same php code to my production API, everything works fine.  I am able to successfully hit the local version of the API with Postman.
I tried the accepted answer from this post but it did not work for me even after restarting apache and my computer.  I tried both the php.ini and runtime approaches but neither solved my problem.

A: You should append the public key of your self signed certificate to the cacert.pem file. Then either of the solutions (setting curl.cainfo in php.ini OR explicitly specifying the path to the cacert.pem file using CURLOPT_CAINFO) proposed here should work just fine.
Make sure you respect the format of the cacert.pem file when adding your public key.


text:
Q: jsp java inline function call exits javascript I am attempting to call a java class function inside javascript that is inside a jsp page.
I've imported it...
<%@ page language="java" import="myPackage.*"%>

I've constructed the class
<%
    myClass myJavaInstance =new myClass();
    System.out.println("this worked!");
%>

I have a bit of javaScript with an alert message in it
<script>
    alert("hello ");
</script>

But when I add this line...
var thisHere = <%= myJavaInstance.getName() %>

before the alert it doesn't show up
<script>
    var thisHere = <%= myJavaInstance.getName() %>
    alert("hello ");
</script>

If I put it after the alert it shows up
<script>
    alert("hello ");
    var thisHere = <%= myJavaInstance.getName() %>
</script>

I know the method gets called because I put a println in it.
What am I missing here? It should work right?

A: The result of myJavaInstance.getName() is probably a string like "Nikos". The rendered output in JS will be:
var thisHere = Nikos

Which is not valid JS (Nikos is undefined). So surround it with quotes:
var thisHere = "<%= myJavaInstance.getName() %>";

Additionally you should escape the string for any quotes found inside it.

A: Use the console. Looks like you have a syntax error, you need to put quotes around strings in javascript. When the script errors out it stops executing the rest of the script. That's why when you put it before the alert and it errors out it wont execute the alert, but if you put it after it does the alert and then errors out.
<script>
    var thisHere = "<%= myJavaInstance.getName() %>"
    alert("hello " + thisHere);
</script>


text:
Q: Put projected Angular content into a component through routing In a context of a micro-front-end application I have a projected content in the app.module.ts that I want to put in a component that was instantiated via the router.
Here is a solution that does not work:

*

*I referenced the projected content as follow

  <ng-template #projected>
    <ng-content></ng-content>
  </ng-template>

  <router-outlet></router-outlet>

*I set the reference in a service

@ViewChild('projected', { static: true }) templateRef: TemplateRef<unknown>;
// ...
this.service.projectedRef = templateRef;

*use it in the component that was created by the router

 <ng-container [ngTemplateOutlet]="service.projectedRef"></ng-container>

Any idea why doesn't that work and how I can solve this problem?
Note: when I use <ng-container [ngTemplateOutlet]="service.projectedRef"></ng-container> inside the app.component.html, it works fine, but not inside the routed component.


text:
Q: How to render two uiOutput in order not synchronistically in Shiny? when input$variable change
uiOutput(1) and uiOutput(2) are rendered at the same time?
Is there any way render step by step not synchronistically?
The following is the steps I want.
1) input variable change
2) uiOutput(1) rendering
3) uiOutput(2) rendering
when input variable change shiny page is not working properly.
but after resizing the page window, the screen appears correctly.
Each time I change the input value, i have to recalibrate the page size.
ui.R
library(shiny)
library(shinydashboard)

sidebar <- dashboardSidebar(
  radioButtons(inputId = "sidebar_data_sell",
               label = "",
               choices = c("Sell-in" = "sell_in", "Sell-out" = "sell_out"),
               selected = "sell_out",
               inline = TRUE),
  uiOutput("summary_sidebar_ui")
)

ui <- dashboardPage(
  dashboardHeader(title = h5("Hi")),
  sidebar,
  uiOutput("dashboard_body")
)

server.R
convertMenuItem <- function(mi, tabName) {
  mi$children[[1]]$attribs['data-toggle'] = "tab"
  mi$children[[1]]$attribs['data-value'] = tabName
  mi
}

out_product_main <- function() {
  list(
    fluidPage(h5("product")))
}

product_items <- function() {
  list(
    selectInput("product_product_sell",
                "product",
                choices = list("product1" = "prd1", "product2" = "prd2"),
                selected = c("prd1"))
  )
}

in_overview_main <- function() {
  list(
    fluidPage(h5("overview")))
}

overview_items <- function() {
  list(
    radioButtons("overview_period_sell",
                 "period",
                 choices = c("year","month"),
                 inline = TRUE,
                 selected = "month")
  )
}

shinyServer(function(input, output) {
  output$summary_sidebar_ui <- renderUI({
    if (input$sidebar_data_sell == "sell_in")
    {
      sidebarMenu(id = "summary_item",
                  convertMenuItem(menuItem("Overview",
                                           tabName = "in_overview",
                                           icon = icon("signal", lib = 'font-awesome'),
                                           overview_items()),
                                  tabName = 'in_overview'))
    }
    else{
      sidebarMenu(id = "p_analysis_item",
                  convertMenuItem(menuItem("Product",
                                           tabName = "out_product",
                                           icon = icon("product-hunt", lib='font-awesome'),
                                           product_items()),
                                  tabName = 'out_product')
      )
    }

  })

  output$dashboard_body <- renderUI({
    if (input$sidebar_data_sell == "sell_in") {
      dashboardBody(tabItems(tabItem("in_overview", in_overview_main())))
    }
    else {
      dashboardBody(tabItems(tabItem("out_product", out_product_main())))
    }
  })

})


text:
Q: Difference between these two eigenvectors? i have a simple question regarding eigenvalues and eigenvectors. Consider the following matrix:
$\left(\begin{array}{ccc}
1 & 1 & 3 \\
1 & 5 & 1 \\
3 & 1 & 1 \end{array}\right)$
The eigenvalues are $\lambda = -2,3,6$
Supposedly the respective eigenvectors are:
$\frac{1}{\sqrt{2}}\left(\begin{array}{c}
-1 \\
0 \\
1 \end{array}\right)$,
$\frac{1}{\sqrt{3}}\left(\begin{array}{c}
1 \\
-1 \\
1 \end{array}\right)$, and
$\frac{1}{\sqrt{6}}\left(\begin{array}{c}
1 \\
2 \\
1 \end{array}\right)$.
Would the solution be wrong if i flipped the signs in the first eigenvector? That is, would an eigenvector of 1/$\sqrt{2} \left\{1; 0; -1\right\}$ be wrong and/or change the values of the other eigenvectors?

A: Let $v$ be an eigenvector of the matrix $A$ , then it is not hard to see that for every $0\neq \lambda \in \mathbb{C}$ we have $\lambda v$ is an eigenvector of $A$.

A: No, that is a valid eigenvector too. Adding a sign to one of the eigenvectors does not change the others.


text:
Q: How can I make partialy deployed solution Is it possible to create .NET MVC Core C# solution with multiple apps or modules and based on client selection of which app/module he wants to have I can deploy only selected apps/modules?
I need to deploy the only selected app/module and not include other apps/modules and the solution should work without breaking dependencies (such as classes).
I dont need to deploy each app in different C# application because that requires to install them on separate ports on IIS.
Similar scenarios I can refer to are: Zoho CRM or Odoo, user can select apps/modules that he likes to enable and start using them in his workspace


text:
Q: Use error handler to let users try submitting the form again if it didn't work in the first time So, I am building a userform which multiple people will fill. The common database file will be kept at the Sharepoint. The form works perfectly fine only until 2 people arent pressing submit button at the same time.
To counter this issue, I thought of an error handler which will show up when a second user is trying to submit the form at the same time and the message will say someone else is using the form, please try again later.
This is my current Submit code:
Sub Submit()
    On Error GoTo eh
    Application.DisplayAlerts = False
    Application.ScreenUpdating = False
    Application.AutomationSecurity = msoAutomationSecurityLow
    If frmForm.txtAE.Value = "" Or frmForm.txtAPL.Value = "" Or frmForm.txtBatches.Value = "" Or frmForm.txtProject.Value = "" Or frmForm.txtQA.Value = "" Or frmForm.txtTeam.Value = "" Or frmForm.cmbDS.Value = "" Or frmForm.cmbPriority.Value = "" Or frmForm.cmbRelease.Value = "" Then
        MsgBox ("Complete All fields marked with (*) to proceed")
    Else
        Dim strFileName As String
        Dim strFileExists As String
        'Call Downloadtest
        strFileName = ""
        strFileExists = Dir(strFileName)

        If strFileName <> "" Then
            MsgBox ("Another user is currently submitting a booking. Please wait for a minute, and then try again.")
        Else

            Dim nwb As Workbook
            Set nwb = Workbooks.Open("sharepoint link")

            nwb.Sheets("Sheet1").Unprotect Password:="password"
            Dim emptyRow As Long
            emptyRow = WorksheetFunction.CountA(nwb.Sheets("Sheet1").Range("A:A")) + 1

            Dim arDate As Variant
            arDate = Split(frmForm.dtPlanned.Value, "/")
            With nwb.Sheets("Sheet1")

                .Cells(emptyRow, 1) = emptyRow - 1
                .Cells(emptyRow, 2) = Date
                .Cells(emptyRow, 3) = frmForm.txtProject.Value
                .Cells(emptyRow, 4) = frmForm.txtTeam.Value
                .Cells(emptyRow, 5) = frmForm.txtAPL.Value
                .Cells(emptyRow, 6) = frmForm.txtQA.Value
                .Cells(emptyRow, 7) = frmForm.txtAE.Value
                .Cells(emptyRow, 8) = frmForm.cmbRelease.Value
                .Cells(emptyRow, 9) = frmForm.cmbDS.Value
                .Cells(emptyRow, 10) = frmForm.txtBatches.Value
                .Cells(emptyRow, 11) = frmForm.dtReview.Value
                .Cells(emptyRow, 12) = frmForm.dtSubmission.Value
                .Cells(emptyRow, 13) = frmForm.dtRelease.Value
                If frmForm.dtPlanned.Value = "" Then .Cells(emptyRow, 14) = "" Else .Cells(emptyRow, 14) = DateSerial(arDate(2), arDate(1), arDate(0))
                .Cells(emptyRow, 15) = frmForm.cmbPriority.Value
                .Cells(emptyRow, 16) = "Pending"
                .Cells(emptyRow, 17) = frmForm.txtRemarks.Value
                .Cells(emptyRow, 18) = Application.UserName

            End With
            nwb.Sheets("Sheet1").Protect Password:="password"
            'nwb.SaveAs ("sharepoint link")

            nwb.SaveAs Filename:="sharepoint link"
            nwb.Close
            'Kill ("C:\Users\username\Downloads\Planning Sheet\KF 6.0_checkout.xlsm")
            MsgBox ("Your Entry has been recorded.")
        End If
    End If
    Unload frmForm
eh:
    MsgBox("Someone else using the file")
End Sub

Please ignore the strFilename, strFileexists, I have to clean up that part.
The problem with this is that the form closes, after we click ok on the error.
Any way that we can add a Try again button on the error MsgBox, that users can press so that they can try submitting the form again after few seconds? And also it should prevent closing the userform, as I dont want them to fill the whole thing again if an error is happening.
Please help, thank you

A: You can try calling msgbox with vbAbortRetryCancel or vbOKCancel argument, enter link description here and restructure the sub in a way like:
Sub Submit()
     On Error ...
     iStat = vbRetry
     Do While iStat = vbRetry
        ...
         Unload frmForm
         iStat = vbOK
     eh:
         iStat = MsgBox ("Someone...
     Loop


text:
Q: Cusotm Recycler View [Android & Kotlin] How can I display the downloaded data as consecutive steps with links to neighboring elements, similar to the attached picture?

Maybe I can use Recycler View? If so, how?

A: Well you can use this lib
TimeLineView Android Lib
In image that is given is generally called Timeline View
Well from the above given lib you can customise the lib by importing module in your project as per your need...this will help you
I hope my answer will help you
Thankyou


text:
Q: split-sequence- delimit sequence by double space I know how to delimit a string sequence by a space:
(defun ff-cols (dir file)
  (with-open-file (ff-cols-str pathname :direction :input)
    (length (split-sequence #\Space (read-line ff-cols-str nil 'eof)))))

But how do you delimit a sequence by a double space? Often flat files have
columns separated by double spaces.
(split-sequence "  " "1  2  3  4")

returns
("1  2  3  4") ;
10

Also,
(split-sequence #\Space "1  2  3  4")

returns
("1" "" "2" "" "3" "" "4") ;
10

A: Try this instead:
(split-sequence-if (lambda (s) (equal s "  ")) "1  2  3  4")

Or this:
(split-sequence #\Space "1  2  3  4" :remove-empty-subseqs t)

A: (ql:quickload "cl-ppcre")
(cl-ppcre:split "\\s\\s" "One  Two Three  Four   Five")
("One" "Two Three" "Four" " Five")

Obviously, whatever you could've learned from other languages which also make use of regular expressions applies.

A: This could be because your string is not seperated by double spaces
(split-sequence "  " "1 2 3 4")

try
(split-sequence "  " "1  2  3  4")


text:
Q: Change text color when clicking button in Javascript I am getting back into learning Javascript and am running into trouble with changing text color when clicking a button.
A lot of the other questions have referenced changing the color of the button itself, and the code I have does not seem to have an error.

My First Web Page

Exciting stuff! This is my first web page.

<button id= "color">Change color!</button>

However, the line
document.getElementById('color').onclick = changeColor; var currentColor = "red";

generates an error saying that it is an illegal token. Initially, I thought the issue had to do with not putting the code in a form. The instructional video's demonstration seemed to work fine, but I keep getting this error. Can anyone provide an idea what is going wrong?

A: Your code works perfectly but you use incorrect syntax. Change " to "
quotation marks.
Also, you do not need to use return statement inside the function, which represents onclick event handler.

My First Web Page

Exciting stuff! This is my first web page.

<button id= "color">Change color!</button>


text:
Q: Xamarin.Forms Font is obsolete When I am trying to create anew label on Xamarin.Forms, I get the following Warning:
about = new Label { Text = "" ,
                TextColor=Color.Black,
                Font = Font.SystemFontOfSize(16),//Warning occurred here
                XAlign = TextAlignment.End,
                HorizontalOptions = LayoutOptions.EndAndExpand};

'Xamarin.Forms.Label.Font' is obsolete: 'Please use the Font
  attributes which are on the class itself. Obsoleted in v1.3.0'

What this warning means and what I should do?

A: Use the FontSize, FontFamily, and FontAttributes properties of the Label class instead.
https://developer.xamarin.com/guides/xamarin-forms/user-interface/text/fonts/

A: You should just listen to the warning and change it to FontSize.
In next releases of Xamarin.Forms this property can be removed and your code no longer will compile.
Marking some method/property as obsolete is very often used by maintainers of libraries to warn users that this particular member can be removed in next releases of library.


text:
Q: python FTP error when dowloading all files in a list does someone know why python is not downloading all the files in the list below? The first file downloads and then i get an 'error2' for the second file.
fdnload1 = ['AAA092214.TXT', '092214 REPORT TOTALS.TXT']
try:
    # DOWNLOAD FILES
    for fdn in fdnload1:
        ftrans1 = open(fdn,'wb')
        ftp.retrbinary('RETR ' + fdn, ftrans1.write)
        print 'Downloading...' + fdn
except:
    print 'error2'

results:
Downloading...AAA092214.TXT
error2

when i run the program without actually downloading the files, it iterates through all files:
try:
    # DOWNLOAD FILES
    for fdn in fdnload1:
        print 'Downloading...' + fdn
except:
    print 'error2'

results:
Downloading...AAA092214.TXT
Downloading...092214 REPORT TOTALS.TXT
[Finished in 0.3s]

E D I T # 1:
i was able to get all files in fdnload1 to download by creating a separate function to download files, but i am still getting errors, and they are coming from the actual download process (see my results are printing 'error in download1() function'. does anyone know why?
also, i just checked the files that were downloaded and they are empty, so they did not actually download properly...
def download1(fdn):
    os.chdir('C:/directory10')
    try:
        ftrans1 = open(fdn,'wb')
        ftp.retrbinary('RETR ' + fdn, ftrans1.write)
        print 'file: ' + fdn + 'download complete...'
    except:
        print 'error in download1() function'

modified the original code to run the download() function:
try:
    # DOWNLOAD FILES
    for fdn in fdnload1:
        print 'Downloading... ' + fdn
        download1(fdn)
except:
    print 'error2'

results:
Downloading... AAA092214.TXT
error in download1() function
Downloading... 092214 REPORT TOTALS.TXT
error in download1() function

A: it was user permissions error on the ftp side.
ftplib.error_perm: 550 AASN092214.PCI: Permission denied.
logged in under superuser and i was able to download all files with and without the download1() function...
thanks


text:
Q: Connected App: Use external ClientId in JWT As per this link, The issuer (iss) must be the OAuth client_id **or** the connected app for which the developer registered their certificate. Does this mean can I use external application client id instead of connected app's client Id ?
Another question is "Can client_id be used instead of iss parameter to pass in client_id" ?
Use Case:
External App user who wants to connect with Salesforce says they have restrictions in modifying existing JWT format and since they are currently using clinet_id to pass clientId, they want to continue using same instead of modifying it to iss. Also they want to use their existing clientId instead of using Salesforce connected app client Id.

A: tl;dr: No on both questions. Your external user is just going to need to suck it up and make the changes.
The documentation you linked doesn't go into detail about exactly what it means by "the connected app", but I suspect it means the API name of your connected app.
I would be very surprised if you could use the client_id of any OAuth enabled thing out there. I don't have anything I could try this with myself, so the quickest way for you to verify this would be to try it yourself.
The role of the (Salesforce) connected app in all of this is to provide a way for administrators to audit the authentication attempts, and some coarse-grained permission control. The connected app is also how Salesforce provides their (Salesforce's) authentication to external systems.
On your second question, the documentation is pretty clear on that.

The developer must create a valid JWT bearer token that conforms to RSA SHA256 according to the following rules.

*

*The issuer (iss) must be the OAuth client_id or the connected app for which the developer registered their certificate.

*The audience (aud) must be https://login.salesforce.com, https://test.salesforce.com, or, if implementing for a community, https://acme.force.com/customers (where acme.force.com/customers is your community URL).

*The subject (sub) must be the username of the desired Salesforce user or, if implementing for a community, the Salesforce community user. For backward compatibility, you can use principal (prn) instead of subject (sub). If both are specified, prn is used.

*The validity (exp) must be the expiration time of the assertion within 5 minutes, expressed as the number of seconds from 1970-01-01T0:0:0Z measured in UTC.

*The JWT must be signed using RSA SHA256.

*The JWT must conform with the general format rules specified here: https://datatracker.ietf.org/doc/html/draft-jones-json-web-token.

If your external user is using 'client_id' in a JWT, that's non-standard (but allowed by the ietf rules linked above in documentation). Salesforce requires that you use "iss", "aud", "sub", and "exp"


text:
Q: Forcing unordered struct fields in C I'm working on converter of object-oriented language into C for optimizing puproses and I've run into design issue.
Consider converter being provided with following class in pseudo-language:
class C {
    int a;
    double b;
    int c;

    constructor C(int value) {
        this.a = value;
        this.b = this.a / 10.0;
        this.c = 0;
    }

    void say() {
        print(this.b);
    }
}

When going straightforward, we can express this class in C as struct like that (skipping error checks):
typedef struct {
    int a;
    double b;
    int c;
} _class_C;

_class_C* _ctor_C(int value) {
    this = malloc(sizeof(_class_C));

    this->a = value;
    this->b = this->a / 10.0;
    this->c = 0;

    return this;
}

void _method_C_say(_class_C *this) {
    printf("%.2f", this->b);
}

void _dtor_C(_class_C *this) {
    free(this);
}

This solution suffers from the promise C compilers are bound with — do not add, remove or change order of fields in struct. So despite the fact fields a and c are not used, they will bloat the code.
How can I achieve "unordered fields" behavior? If I had only one static C, it could be written as follows:
int _staticfield_C_a;
double _staticfield_C_b;
int _staticfield_C_c;

void _ctor_C(int value) {
    _staticfield_C_a = value;
    _staticfield_C_b = _staticfield_C_a / 10.0;
    _staticfield_C_c = 0;
}

void _staticmethod_C_say() {
    printf("%.2f", _staticfield_C_b);
}

so compiler can optimize out redundant or unused fields up to sole _staticfield_C_b, but what solution should I use when C can be instantiated in dynamic, and I don't mind the order of fields, memory layout and code human-readability at all?
Update: It should be noted that I'm not trying to enforce compiler to do magic with structs, I want some replacement for them acting like struct with unordered field — much like that I've provided in static example, regardless of level of readablility.
Update: There is a popular opinion in the comments that my problem is related to design of converter itself, like if I chose wrong paradigm or language for it. Converter itself is written in Python, and it takes source of generic object-oriented program, processes it and outputs equivalent C code to be compiled, so you can think of it as cross-language compiler. I'm pleased with good intentions of explaining me where and how I should use structures, but in this case I need some help in magic to easen up optimization :)

A: It sounds like you're trying to get the compiler (or linker -- the "remove unused objects" optimization you mention is actually done there) to automatically detect unused structure fields for you.  It can't, because it's impossible.  That's a global optimization -- you need to know that no code anywhere in the universe that references a given field.  But what if the code will bind dynamically to something in the future (code not part of the current link) that references that field?  What about compiling a library with the same header. How big should the compiler make the struct, given that it doesn't know how it will be used?
If you want to do this optimization, I'm afraid you'll have to do it yourself.  The C language doesn't have the tools available.

A: Have you looked into Unions as an alternative to Structs?
If you're using only one field at a time and are worried about memory, this is the perfect data structure.


text:
Q: Upload Folder of Images to Firestore Storage and Put Download URLs in Firestore I have roughly 10,000 images that I want to upload to Firebase Storage (it adds up to around 800mb).
Using Javascript, I am looking for a way to:

*

*Upload them to Firebase Storage

*Grab their URL upon upload and create Cloud Firestore documents for each using their file names with a field called "downloadURL" or something like that that my website can then use for  tags.

So say one file is 4670.jpg. I want to upload the file, grab its persistent URL and then create a Cloud Firestore document called 4670 that has a text field with it's persistent URL. I know how to do this for a single file, but I'm dealing with thousands.
Edit: A huge thanks for, Renaud Tarnec who gave me a working solution
HTML
// File selector

<input type="file" multiple onchange="processSelectedFiles(this)">

// CDN for Firebase, Cloud Firestore, and Firebase Storage
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.11.0/firebase-firestore.js"></script>
<script src="https://www.gstatic.com/firebasejs/4.12.0/firebase-storage.js"></script>

<script>
  // Initialize Firebase
  var config = {
    apiKey: "********************",
    authDomain: "********************",
    databaseURL: "********************",
    projectId: "********************",
    storageBucket: "********************",
    messagingSenderId: "********************"
  };
  firebase.initializeApp(config);

var db = firebase.firestore();

</script>

<script src="script.js"></script>

Javascript
function processSelectedFiles(fileInput) {
  var files = fileInput.files;

  var promises = []

  for (var i = 0; i < files.length; i++) {

    var file = files[i]

      promises.push(uploadAndSavePromise(file))
  }

    Promise.all(promises);
}

function uploadAndSavePromise(file) {
     var storageRef = firebase.storage().ref();
     var fileName = file.name
     // Remove extension
     var trimmedFileName = fileName.slice(0, -4)

     var imageRef = storageRef.child('test/'+fileName);

    return imageRef.put(file).then(function(snapshot) {

        db.collection("maincollection").doc(trimmedFileName).set({
        imageURL: snapshot.downloadURL,

})

});

}

A: You say that you know how to do for one single file.
You probably have a process based on promises which does something like (in pseudo code):
({Upload_to_Firebase_Storage_Promise})
.then(function(urlOfFile) {
    {create__Firestore_doc_Promise}
})
.catch(....)

What you should do is to use Promise.all() following this pattern (a mix of JavaScript and pseudo code):
var promises = [];

{forEach file to upload} (
  //Create a Promise that upload the file and save the url and add this promise to the array, as follow
  promises.push(uploadAndSavePromise(fileToUpload))
)

//and call
Promise.all(promises);

where uploadAndSavePromise is a function implementing the initial promise chain:
function uploadAndSavePromise(file) {
    return ({Upload_to_Firebase_Storage_Promise(file)})
    .then(function(urlOfFile) {
        {create__Firestore_doc_Promise}
    });
}

Now, one thing that I would consider is how is this is going to work if you want to upload 10000 images in a row...


text:
Q: It selects links of a particular user from DB but the error is if '%.png' is not found it displays all the other files of every user on database links is the table name and link is the column name.
$gettingemail = $_SESSION['email'];

$sql = "SELECT * FROM links WHERE username='".$gettingemail."' AND
link LIKE '%.png' OR link LIKE '%.jpeg' OR link LIKE '%.exif' OR link LIKE '%.tiff'";

A: You just need to add your OR clause in one condition as:
$sql = "SELECT * FROM links WHERE username='".$gettingemail."'
AND (link LIKE '%.png' OR
     link LIKE '%.jpeg' OR
     link LIKE '%.exif' OR
     link LIKE '%.tiff')";

Here i am using OR condition as one block (condition OR condition):
(link LIKE '%.png' OR link LIKE '%.jpeg' OR link LIKE '%.exif' OR link LIKE '%.tiff')

Side Note:
Also note that, your query is open for SQL injection, for preventing SQL injection you can use Prepared Statements
Also note that, don't know which extension are you using for execute your query, as per your tag if you are using mysql_* than note that, its deprecated and closed in PHP 7.


text:
Q: conflict exists with definition friendlist in namespace internal flex error in my variable i am getting error
private var friendsList:VBox;

"conflict exists with definition friendlist in namespace internal" what it is ? thanks in advance

A: I suppose you have an other definition with name friendsList. Just rename one of them.


text:
Q: What is wrong with this proof by induction for the value of $2+3+\cdots+n$?
For all $n >= 0$, $2+3+\cdots+n=n(n+1)/2$

This is surely wrong,but why we can use induction to prove it is true?See the below:
Let $P(n)$ be the proposition that  $2+3+\cdots+n=n(n+1)/2$
Base step: P(0) is true
Inductive step: Let P(k) be true,therefore
$2+3+\cdots+k=k(k+1)/2$.
Now check when the $n$ equals to $k+1$,so we have $2+3+\cdots+k+k+1=k(k+1)/2+k=(k+1)(k+2)/2$,this is also true.
Therefore,we can say that P(k) implies P(k+1).
Since we have both  P(0) and P(k) implies P(k+1),we can say
that P(n) is true.
But P(n) is wrong actually ! What is wrong with the prove?

A: Some people are saying you have to start from $n=2$. That's not technically correct, though usually how people do it.
Instead, you can take $P(k)$ to be the statement:

$P(k):$ either $k\lt 2$, or else $2+\cdots+k=k(k+1)/2$.

(Better than interpreting the sum as empty, but you can also do that...)
But then your inductive argument only holds if $k\geq 2$; so your argument, as far as it goes, only proves:

*

*$P(0)$ holds

*If $k\geq 2$, then $P(k)\implies P(k+1)$.

So you need separate proofs for $P(0)\implies P(1)$ and for $P(1)\implies P(2)$. Or for $P(1)$ and $P(2)$.
Now, if you use the formulation I give above, then $P(0)\implies P(1)$ (or more directly, $P(1)$) holds because $P(1)$ is true; but then $P(1)\implies P(2)$ does not hold (because $P(2)$ does not hold). So your inductive step is incomplete and you cannot conclude things work.
If you use the formulation to interpret the sum on the left as emtpy when $k\lt 2$, then you run into trouble with $P(0)\implies P(1)$; because $P(1)$ would give you $0=1(2)/2$, which is false.
Either way, your inductive step proof is incomplete, and when you try to fill it in, you run into one case that does not hold, invalidating the whole thing.

For a classical example of an incorrect inductive proof that flounders because the inductive step argument only works for sufficiently large $k$, but fails for small $k$, look at the example worked out under item 4 in this answer

A: We can't use $P(0)$ since the sum starts from $2$, we should use at least $n=2$ as base case which leads to $2=3$.


text:
Q: Append to the end of an element with querySelector How do I get the nodeValue when using the querySelector?
http://jsbin.com/cavowacaho/1/edit?html,js,console
var input = document.querySelector(".input");

input.nodeValue += " thanks!";

A: I ended up using outerHTML which worked fine, this also prevents against appending to the end of the element's parent - which appendChild would do.
http://jsbin.com/mezemosuye/1/edit?html,js,output


text:
Q: Affine scaling method in Matlab I am trying to code the affine scaling method for maximization LP problem and I used the following code.
function [X,y,k] = affsm(A,x,c)
xx(:,1)=x';
er=1e-5
 k=1;
test=1;
r=2/3;
theta=1
while test>er/theta
D = diag(xx(:,k).^2);
AD = A*D;
dx = -(D-AD'*(AD*A')^(-1)*AD)*c';
 theta =r*min([xx(:,k)./abs(dx);1]);
 xx(:,k+1) = xx(:,k) + theta*dx ;
 test=max([c*dx ,norm(dx)]);
 k=k+1;
end
y=xx(:,k);
X=xx;
end

I am trying to solve the following problem
\begin{array}{c}{\max \quad Z=3 x+5 y} \\ {x+3 y \leq 60} \\ {3 x+4 y \leq 120} \\ {x \geq 10} \\ {x, y \geq 0}\end{array}

but it gives me wrong results what I am doing wrong in the above code ?.
Note: The optimal solution must be $(x,y)=(12,24)$ with $z=132$

A: I don't know what your function is supposed to do since there is no explaination, but to resolve this kind of linear equation with constraints you can use linprog
% define the constraints
% Every constraints have this format: x1*x(1) + x2*x(2) ≤ n
% Where x(1) and x(2) are your variable and x1,x2 and n are integers.
A = [1 3
    3 4
    -1 0
     0 -1
    -1 0];

b = [60 120 -10 0 0];
% define the objective function
f = [-3 -5];
% solve
x = linprog(f,A,b)

Result:
x =
    24
    12

Noticed that I've reversed the sign of the objective function in order to maximize the solution (by default linprog will minimize the solution)


text:
Q: Change Credit Card Information (Stripe) I finally figured out how to implement Stripes Monthly Billing using this tutorial.
http://railscasts.com/episodes/288-billing-with-stripe
So far, A User can Create & Delete their Subscription with Stripe.
But how can a User change his Credit Card Information once they have created a subscription
This is my Code with Comments and Questions. Please help new to rails. :)
CONTROLLER
class SubscriptionsController < ApplicationController

  def new
    plan = Plan.find(params[:plan_id])
    @subscription = plan.subscriptions.build
    @subscription.user_id = current_user.id
  end

  def create
    @subscription = Subscription.new(params[:subscription])
    if @subscription.save_with_payment
      redirect_to @subscription, :notice => "Thank you for subscribing!"
    else
      render :new
    end
  end

  def update
    @subscription = current_user.subscription
     if @subscription.save
      redirect_to edit_subscription_path, :success => 'Updated Card.'
    else
      flash.alert = 'Unable to update card.'
      render :edit
    end
  end

end

MODELS
class Subscription < ActiveRecord::Base
  attr_accessible :plan_id, :user_id, :email, :stripe_customer_token, :last_4_digits,
              :card_token, :card_name, :exp_month, :exp_year, :stripe_card_token

  attr_accessor :stripe_card_token

  belongs_to :plan
  belongs_to :user

  def save_with_payment
    if valid?
      save_with_stripe_payment
    end
  end

  def save_with_stripe_payment
    customer = Stripe::Customer.create(card: stripe_card_token, email: email, plan: plan_id, description: "Unlimited Comics")
    self.stripe_customer_token = customer.id
    self.card_token = customer.cards.data.first["id"]
    self.card_name = customer.cards.data.first["type"]
    self.exp_month = customer.cards.data.first["exp_month"]
    self.exp_year = customer.cards.data.first["exp_year"]
    self.last_4_digits = customer.cards.data.first["last4"]
    save!
  rescue Stripe::InvalidRequestError => e
    logger.error "Stripe error while creating customer: #{e.message}"
    errors.add :base, "There was a problem with your credit card."
    false
  end

  def update_card
    customer = Stripe::Customer.retrieve(stripe_customer_token)
    card = customer.cards.retrieve(card_token)

    *** This Update works, but how do I pass a new Credit Card Number, Expiration Date etc.
    card.name = "My new name"
    customer.save
  rescue Stripe::StripeError => e
    logger.error "Stripe Error: " + e.message
    errors.add :base, "#{e.message}."
    false
  end

end

VIEWS
<%= form_for @subscription do |f| %>
  <%= render 'shared/error_messages', object: f.object %>

  <%= f.hidden_field :plan_id %>
  <%= f.hidden_field :user_id %>
  <%= f.hidden_field :stripe_card_token %>

Change Credit Card

     <%= label_tag :card_number, "Credit Card Number" %>
     <%= text_field_tag :card_number, nil, name: nil %>

     <%= label_tag :card_code, "Security Code on Card (CVV)" %>
     <%= text_field_tag :card_code, nil, name: nil %>

     <%= label_tag :card_month, "Card Expiration" %>
     <%= select_month nil, {add_month_numbers: true}, {name: nil, id: "card_month"} %>
     <%= select_year nil, {start_year: Date.today.year, end_year: Date.today.year+15}, {name: nil, id: "card_year"} %>

   <%= f.submit "Change Credit Card", :class => "btn btn-primary" %>

<% end %>

ROUTES
App::Application.routes.draw do
  resources :subscriptions
end

SCHEMA
create_table "subscriptions", :force => true do |t|
  t.integer  "plan_id"
  t.integer  "user_id"
  t.string   "email"
  t.string   "card_name"
  t.string   "exp_month"
  t.string   "exp_year"
  t.string   "card_token"
  t.string   "stripe_customer_token"
  t.string   "last_4_digits"
  t.datetime "created_at",                     :null => false
  t.datetime "updated_at",                     :null => false
end

A: You can update the credit card details like this (PHP CODE)

*

*First collect the card details and the customer stripe id (that you must have saved in your database while creation of this customer).

*Create Stripe token and forward the same to server like this:
 Stripe.setPublishableKey('pk_test_6pRNASCoBOKtIshFeQd4XMUh');
  function stripeResponseHandler(status, response) {
  var $form = $('#payment-form');

  if (response.error) {
    // Show the errors on the form
    $form.find('.payment-errors').text(response.error.message);
    $form.find('button').prop('disabled', false);
  } else {
    // response contains id and card, which contains additional card details
    var token = response.id;
    alert('The Token Is: '+token);
    // Insert the token into the form so it gets submitted to the server
    $form.append($('<input type="hidden" name="stripeToken" />').val(token));
    // and submit
    $form.get(0).submit();
  }
};

  jQuery(function($) {
  $('#payment-form').submit(function(event) {
    var $form = $(this);

    // Disable the submit button to prevent repeated clicks
    $form.find('button').prop('disabled', true);

    Stripe.card.createToken($form, stripeResponseHandler);

    // Prevent the form from submitting with the default action
    return false;
  });
});

*and in the server you can update the details like this:
  $customer_id = trim($_REQUEST['cus_select']);
  $query = "SELECT cus_stripe_id FROM customer_details_tbl WHERE id=$customer_id";
  $customer_query = mysqli_query($db_conn,$query);
  $row_customer = mysqli_fetch_row($customer_query);
  $cus_stripe_id = $row_customer[0];

   Stripe::setApiKey("sk_test_BQokikJOvBiI2HlWgH4olfQ2");

   $error = '';
   $success = '';
   try {
    if (!isset($_POST['stripeToken']))
      throw new Exception("The Stripe Token was not generated correctly");
    $customer = Stripe_Customer::retrieve($cus_stripe_id);
    $customer->source = $_POST['stripeToken'];
    $customer->save();
    echo "Card Details Updated Successfully";
   }
   catch (Exception $e) {
    $error = $e->getMessage();
    echo $error;
   }
 }

That is it. This will overwrite the existing card with the new details.

A: 2015-02-18
The cards and default_card attributes are no longer returned on Customers. You should now use sources and default_source respectively. The customer.card.* and customer.bank_account.* webhooks are now named customer.source.*. If you only have cards attached to customers (as opposed to payment sources of other types) then you can use the new attributes exactly as you would the old ones. If you have payment sources of multiple types, then the sources list contains heterogeneous objects and you can check the object attribute of each source to determine its format. Older API versions return both the new and the old attributes.

A: This answer has been updated thanks to the note from @TimSullivan
I had to do the same thing in my app. Stripe does not permit updating the card number. This leaves you with two options: 1) Create a new card and delete the original card; and 2) Create a new card, set it as the default_card and leave the original card. I chose the second route.
Here's how I did it:
models/subscriber.rb
def update_card(subscriber, stripe_card_token)
  customer = Stripe::Customer.retrieve(subscriber.stripe_customer_token)
  card = customer.sources.create(card: stripe_card_token)
  card.save
  customer.default_source = card.id
  customer.save
rescue Stripe::InvalidRequestError => e
  logger.error "Stripe error while updating card info: #{e.message}"
  errors.add :base, "#{e.message}"
  false
end

controllers/subscribers_controller.rb
def edit_card
  @subscriber = current_subscriber
end

def update_card
  @subscriber = current_subscriber
  if @subscriber.update_card(@subscriber, params[:stripe_card_token])
    flash[:success] = 'Saved. Your card information has been updated.'
    redirect_to @subscriber
  else
    flash[:warning] = 'Stripe reported an error while updating your card. Please try again.'
    redirect_to @subscriber
  end
end

views/subscribers/edit_card.html.erb
<%= form_for @subscriber, url: update_card_path, html: { class: 'update_subscriber' } do |f| %>

    <%= label_tag        :number, 'Card Number', class: 'col-sm-3 control-label' %>

      <%= text_field_tag :number, nil, class: 'form-control', placeholder: 'We accept Visa, MasterCard, AMEX and Discover' %>

    <%= label_tag        :cvc, 'Security Code', class: 'col-sm-3 control-label' %>

      <%= text_field_tag :cvc, nil, class: 'form-control', placeholder: 'The code on the back of your card (CVC)' %>

    <%= label_tag        :exp_month, 'Expiration Date', class: 'col-sm-3 control-label' %>

      <%= select_month   nil, { add_month_numbers: true }, { id: 'exp_month', class: 'form-control btm-space' } %>

      <%= select_year    nil, { start_year: Date.today.year, end_year: Date.today.year+15 }, { id: 'exp_year', class: 'form-control btm-space' } %>

      <%= submit_tag 'Update', class: 'btn btn-success btn-block' %>

  <%= f.hidden_field :stripe_card_token %>
<% end %>

config/routes.rb
match '/edit_card',   to: 'subscribers#edit_card',   via: 'get'
match '/update_card', to: 'subscribers#update_card', via: 'post'

app/js/update_card.js
var subscription;

jQuery(function() {
  Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'));
  return subscription.setUpForm();
});

subscription = {
  setUpForm: function() {
    return $('.update_subscriber').submit(function() {
      $('input[type="submit"]').attr('disabled', true);
      if ($('#card_number').length) {
        subscription.updateCard();
        return false;
      } else {
        return true;
      }
    });
  },
  updateCard: function() {
    var card;
    card = {
      number: $('#card_number').val(),
      cvc: $('#card_code').val(),
      expMonth: $('#card_month').val(),
      expYear: $('#card_year').val()
    };
    return Stripe.createToken(card, subscription.handleStripeResponse);
  },
  handleStripeResponse: function(status, response) {
    if (status === 200) {
      $('#subscriber_stripe_card_token').val(response.id);
      return $('.update_subscriber')[0].submit();
    } else {
      $('#stripe_error').text(response.error.message);
      return $('input[type="submit"]').attr('disabled', false);
    }
  }
};

Hope this helps.

A: Use Stripe.js like Tim Sullivan suggests. Here is his code updated for the newer Stripe API.
def update_card(subscriber, stripe_token)
  customer = Stripe::Customer.retrieve({CUSTOMER_ID})
  card = customer.sources.create(card: params[:stripeToken])
  customer.default_source = card.id
  customer.save
rescue Stripe::InvalidRequestError => e
  logger.error "Stripe error while updating card info: #{e.message}"
  errors.add :base, "#{e.message}"
  false
end

A: The accepted answer here is dangerously unsafe to use. It does an end-run around the security that Stripe encourages. Your own server should never get the credit card details.
You should instead be using Stripe.js to pass the card to Stripe directly (similar to how it is already done in the Railscast you link to) and retrieving a token, then creating the card based on the token.
def update_card(subscriber, stripe_token)
  customer = Stripe::Customer.retrieve(subscriber.stripe_customer_token)
  card = customer.cards.create(card: stripe_token)
  card.save
  customer.default_card = card.id
  customer.save
rescue Stripe::InvalidRequestError => e
  logger.error "Stripe error while updating card info: #{e.message}"
  errors.add :base, "#{e.message}"
  false
end

A: So Stripe's ruby library has the update method, you already have card.name but for the expiration date you can use card.exp_month and card.exp_year, check out update method for all the arguments.
You'll notice it doesn't have an update card number on there, so my suggestion would be to have the user create another card if they want to change their credit card number and then update the customer to have that card as their default credit card (check out create card and update a customer in the stripe ruby library documentation).
Hope this helps


text:
Q: how to return async await promise I am currently working on getting all the Data object from a certain user. I thought I am already getting it, but then I noticed that it only return a DATA the second time I click the button ( means async is not working ) If you can advice, that would be a great help! Thanks!
async getData(UID) {
let container = [];
var firebaseRef = this.afd.database.ref();

  let qwee = await firebaseRef.child('AllData/')
  .orderByChild("UserID")
  .equalTo(UID)
  .on("child_added", function(snapshot) {

      container.push(snapshot.val());

  });

return container;
}

This is the calling function
async LoadUserData(){
this.Data = await this.provider.getData("Tom");
}

A: You seem to be mixing callbacks and promises.
You will need to wrap the callback in a promise and then await it.
async getData(UID) {
    let container = [];
    var firebaseRef = this.afd.database.ref();

    let qwee = await new Promise(function(resolve,reject){
       return firebaseRef.child('AllData/')
          .orderByChild("UserID")
          .equalTo(UID)
          .on("child_added", function(snapshot) {
              resolve(snapshot.val());
              //container.push(snapshot.val());

           });
        });
    container.push(qwee);
    return container;
}


text:
Q: error when trying to merge audio and video with fluent-ffmpeg Hello I need to combine a video track and an audio track, I get the video and audio from a url.
the problem is that the audio is only added to the middle of the video, and then the video goes silent I hope you understand me, my English is not very good.
dependencies
import ffmpegInstaller from '@ffmpeg-installer/ffmpeg';
import ffmpeg from 'fluent-ffmpeg';

ffmpeg.setFfmpegPath(ffmpegInstaller.path);

code
ffmpeg()
.addInput(video)
.addInput(audio)
.output('videoNuevo.mp4')
.outputOptions(['-map 0:v', '-map 1:a', '-c:v copy'])
.on('progress', progress => {
    console.log(progress)
}).on('end', () => {
    console.log('process finish!')
}).on('error', err => {
    console.log(err)
})
.run()


text:
Q: ASP.net session variables information required I have an ASP.net WebForms application. I have used session variables in my application. I have a requirement of getting the memory used by the session variables on the aspx.cs pages. How do i do that. For a start I know that i can get it done like this.
int totalSessionBytes;
BinaryFormatter b = new BinaryFormatter();
MemoryStream m;
b.Serialize(m, Session["table1"]);
totalSessionBytes = m.Length;

Any other suitable way other than this? Some of my session variables also save DataTables. Will i be able to capture the mem of such session variables?

A: Getting the total-memory-used by the session store only works if you're using the InProc store - if you're using an external store for session-state like Redis or SQL-Server then the answer is zero.
Your proposed approach will at least double the apparent memory usage of session-state because you're performing a copy (of serialized data!) to a MemoryStream which parents a Byte[] and then you never Dispose it, leaving it up to the GC gods to decide when to lower your memory pressure. Your approach also only returns data for the current user's session state, rather than that of all users.
The problem is also compounded if you consider things like String Interning (where identical string values in the .NET runtime are shared by multiple string references) - because those string values could be shared by different users' different session-states.
The only way to find out exactly how much memory being used is to use a memory-profiling tool like JetBrains dotMemory or MemProfiler or the CLR/GC analysis tools in WinDBG and Visual Studio's Diagnostics Tools window.


text:
Q: jQuery script works only once, then TypeError: $(...) is not a function I've downloaded this script for use conditional fields in forms:
(function ($) {
  $.fn.conditionize = function(options) {

    var settings = $.extend({
        hideJS: true
    }, options );

    $.fn.showOrHide = function(is_met, $section) {
      if (is_met) {
        $section.slideDown();
      }
      else {
        $section.slideUp();
        $section.find('select, input').each(function(){
            if ( ($(this).attr('type')=='radio') || ($(this).attr('type')=='checkbox') ) {
                $(this).prop('checked', false).trigger('change');
            }
            else{
                $(this).val('').trigger('change');
            }
        });
      }
    }

    return this.each( function() {
      var $section = $(this);
      var cond = $(this).data('condition');

      // First get all (distinct) used field/inputs
      var re = /(#?\w+)/ig;
      var match = re.exec(cond);
      var inputs = {}, e = "", name ="";
      while(match !== null) {
        name = match[1];
        e = (name.substring(0,1)=='#' ? name : "[name=" + name + "]");
        if ( $(e).length && ! (name in inputs) ) {
            inputs[name] = e;
        }
        match = re.exec(cond);
      }

      // Replace fields names/ids by $().val()
      for (name in inputs) {
        e = inputs[name];
        tmp_re = new RegExp("(" + name + ")\\b","g")
        if ( ($(e).attr('type')=='radio') || ($(e).attr('type')=='checkbox') ) {
          cond = cond.replace(tmp_re,"$('" + e + ":checked').val()");
        }
        else {
          cond = cond.replace(tmp_re,"$('" + e + "').val()");
        }
      }

      //Set up event listeners
      for (name in inputs) {
        $(inputs[name]).on('change', function() {
          $.fn.showOrHide(eval(cond), $section);
        });
      }

      //If setting was chosen, hide everything first...
      if (settings.hideJS) {
        $(this).hide();
      }
      //Show based on current value on page load
      $.fn.showOrHide(eval(cond), $section);
    });
  }
}(jQuery));

I'm trying this because I need to use conditionize() in one of my tabs and when I reload the tab, all works but if I go to other tab and I return to the previous tab(where I need this works), I get that error.
When I change tabs, I'm only reloading one part of the page.
When I load the page this works perfectly, but if I try to call function again from browser console, it tells me that TypeError: $(...)conditionize() is not a function.
I have included the script in header tag and I'm calling it with this script on the bottom of body:
<script type="text/javascript">
     $('.conditional').conditionize();
</script>

EDIT:
I have written
<script type="text/javascript">
    console.log($('.conditional').conditionize);
    setTimeout(function () {console.log($('.conditional').conditionize);}, 2);
</script>

and this print me at console the function, and when 2 milliseconds have passed, it print me undefined

A: I have found the solution.
Because any reason, the $ object and jQuery object are not the same in my code.
I have discovered it using this on browser console:
$===jQuery
This return false (This was produced because in other JS, I was using the noConflict(), which give me the problem)
Explanation: noConflict()
So I have solved it changing the last line of my JS by:
//Show based on current value on page load
      $.fn.showOrHide(eval(cond), $section);
    });
  }
}($));

Putting the $ instead of 'jQuery'


text:
Q: Second argument replacing first scala I am trying to define a function in scala ( ^ ), which takes 2 values and prints them like
 2
x

Here is what I have so far...
class $ (val text2D: Array[Array[Char]])
{
  def ^(that: $) =
  {
    " " ++ s"${this.text2D(0)(0)}" ++
    "\n" ++ s"${that.text2D(0)(0)}"
  }

  def +(that: $) = this.text2D + "+" + that.text2D

  override def toString = s"${this.text2D(0)(0)}"
}

object $ {
  val array = Array.ofDim[Char](1,1)
  def apply(x: String): $ = {
    array (0)(0) = x.charAt(0)
    new $ (array)
  }
}

val x = $("x")
println(x)

val x2 = $("x") ^ $("2")
println(x2)

When I run this, I do not get the output I am expecting, instead I get
 2
2

Why is it only taking the second element? Any help would be appreciated.

A: object creates a singleton, so the (mutable) array that you use is shared between calls to apply. You need to allocate that array inside the apply call.
def apply(x: String): $ = {
  val array = Array.ofDim[Char](1,1)
  array (0)(0) = x.charAt(0)
  new $ (array)
}

Also, slightly unrelated, but I believe you have your arguments backward. To get the output you want, you need
" " ++ s"${that.text2D(0)(0)}" ++
"\n" ++ s"${this.text2D(0)(0)}"

A: I think what you need is something like this:
class $(val text2D: Array[String]) {
  def ^(that: $): $ = {
    if (this.text2D.length == 0)
      that
    else if (that.text2D.length == 0)
      this
    else {
      val thisW = this.text2D(0).length
      val thatW = that.text2D(0).length

      // cross-pad arrays to have the same width
      val padThisRight = " " * thatW
      val padThatLeft = " " * thisW
      val thisPaddedW = this.text2D.map(_ + padThisRight)
      val thatPaddedW = that.text2D.map(padThatLeft + _)
      // first lines comes from that!
      new $(thatPaddedW ++ thisPaddedW)
    }
  }

  def +(that: $): $ = {
    if (this.text2D.length == 0)
      that
    else if (that.text2D.length == 0)
      this
    else {
      val thisH = this.text2D.length
      val thatH = that.text2D.length
      val thisW = this.text2D(0).length
      val thatW = that.text2D(0).length

      // pad arrays to have the same height
      val emptyThis = " " * thisW
      val emptyThat = " " * thatW
      val thisPaddedH = if (thisH >= thatH) this.text2D else Array.fill(thatH - thisH)(emptyThis) ++ this.text2D
      val thatPaddedH = if (thisH <= thatH) that.text2D else Array.fill(thisH - thatH)(emptyThat) ++ that.text2D

      new $(thisPaddedH.zip(thatPaddedH).map(p => p._1 + p._2))
    }
  }

  override def toString = text2D.mkString("\n")
}

object $ {
  def apply(x: String): $ = {
    new $(Array[String](x))
  }
}

and then
val x2 = $("x") ^ $("2")
println(s"x2:\n$x2")
println("----------------------------")

val z = x2 + $(" + ") + y2
println(s"z:\n$z")
println("----------------------------")

val zz = x2 + $(" + ") + (y2 ^ $("3"))
println(s"zz:\n$zz")
println("----------------------------")

produces following output
x2:
 2
x
----------------------------
z:
 2    2
x  + y
----------------------------
zz:
       3
 2    2
x  + y
----------------------------

The main idea here is that operations on $ produce another instance of $ rather than String (I use String instead of Array[Char] as it seems much easier and has no obvious drawbacks). In such way you don't have to re-parse String splitting it by new lines and have to wonder how to handle cases when the string is not well-aligned. So now operators ^ and + is just an exercise in aligning two 2d-arrays to have either the same width or the same height and then joining them.


text:
Q: How many combinations are there of the word "clementine" with a maximum with 3 repeated consonants?" I'm having an issue with a math question:
"How many combinations are there of the word "clementine" with a maximum with 3 repeated consonants?"
The issue I have is understanding how to account for the combinations of the consonants.
As there are 4 vowels and 6 consonants but at most only 3 consonants should be next to each other, so...
(1 C)
(1 L)
(2 N)
(1 M)
(1 T) <- Consonants
(3 E) (1 I) <- Vowels

So far I believe I'm on the correct path however I am confused on calculating how many spaces the 3 letters can fit into:
4!/(2!1) X 6!/(3!1)X (the number of spaces that 3 consonants can group in?)
Any help in understanding the process for this question better would be appreciated. I'm aware there are many questions on the subject on stackoverflow and have looked at a number including :
How many permutations of a word do not contain consecutive vowels?
However, I'm uncertain how to handle the specific instance of having multiple consonants together in the space.

A: We will count the ways we can assign positions to the consonants, then count the number of ways the consonants and vowels can be assigned to their designated positions.
An arrangement of the word CLEMENTINE in which no more than three consonants are consecutive has the form
$$\square v \square v \square v \square v \square$$
where $v$ represents the position of a vowel and the squares represent the possible positions of the consonants.  Let $x_k$ represent the number of consonants placed in the $k$th square from the left.  Since there are six consonants and no more than three consonants can be placed in each position represented by a square,
$$x_1 + x_2 + x_3 + x_4 + x_5 = 6 \tag{1}$$
where $x_k \leq 3, 1 \leq k \leq 5$.  Equation 1 is an equation in the non-negative integers.  A particular solution corresponds to the placement of four addition signs in a row of six ones.  For instance,
$$1 + 1 + + 1 1 1 + 1$$
represents the solution $x_1 = x_2 = 1$, $x_3 = 0$, $x_4 = 3$, and $x_5 = 1$, while
$$1 + 1 + 1 + 1 + 1 1$$
represents the solution $x_1 = x_2 = x_3 = x_4 = 1$, and $x_5 = 2$. Therefore, the number of solutions of equation 1 in the nonnegative integers is the number of ways four addition signs can be placed in a row of six ones, which is
$$\binom{6 + 4}{4} = \binom{10}{4}$$
since we must choose which four of the ten positions (six addition signs and four addition signs) will be filled with addition signs.
However, we have counted solutions of equation 1 in which one or more of the variables is larger than $3$.  We must exclude these.  Note that at most one variable can exceed $3$ since $2 \cdot 4 = 8 > 6$.
Suppose $x_1 > 3$.  Since $x_1$ is an integer, $x_1 \geq 4 \implies y_1 = x_1 - 4$ is a nonnegative integer.  Substituting $y_1 + 4$ for $x_1$ in equation 1 yields
\begin{align*}
y_1 + 4 + x_2 + x_3 + x_4 + x_5 & = 6\\
y_1 + x_2 + x_3 + x_4 + x_5 & = 2 \tag{2}
\end{align*}
Equation 2 is an equation in the nonnegative integers.  The number of solutions of equation 2 is the number of ways four addition signs can be placed in a row of two ones, which is
$$\binom{2 + 4}{4} = \binom{6}{4}$$
By symmetry, this is the number of solutions in which $x_k > 3$, $1 \leq k \leq 5$.  Hence, the number of solutions of equation 1 in which none of the variables exceeds $3$ is
$$\binom{10}{4} - \binom{5}{1}\binom{6}{4}$$
Thus far, we have counted the number of ways we can designate positions for the consonants.  Once we have chosen the positions where the consonants will be located (which determines the positions where the vowels will be located), we must arrange the consonants and vowels in those positions.  There are six consonants, of which there are $2$ N's, $1$ C, $1$ L, $1$ M, and $1$ T.  We choose two of the six positions for the $N$'s, then can place the remaining four consonants in the four remaining positions designated for the consonants.  This can be done in
$$\binom{6}{2}4!$$
ways.  That leaves the four positions for the four vowels, of which there are $3$ E's and $1$ I.  Choosing which of the four positions will be assigned an I completely determines how the vowels will be arranged in their designated positions.  Hence, the number of possible arrangements of the letters of the word CLEMENTINE in which no more than three vowels are consecutive is
$$\left[\binom{10}{4} - \binom{5}{1}\binom{6}{4}\right] \cdot \binom{6}{2}4! \cdot 4$$

A: It may be simplest to find the number of words with exactly six consecutive consonants, then exactly five consecutive consonants, then exactly four consecutive consonants, add them up, and subtract this total from the total number of words possible.
The total number of configurations possible (without constraints) is $10!/(3! 2!) = 302,400$, where the denominator is for the fact that there are three $e$s and two $n$s.
six consecutive consonants
Of the ten "slots" for letters, if there are exactly six consecutive consonants, the first one must appear in slot 1 or slot 2 or slot 3 or slot 4 or slot 5.  That's all.  For each such "starting slot", you have $c$, $l$, $m$, $n$ and $t$ (with $n$ appearing twice).  The number of distinct ways to fill in those six slots is then $6!/2!$.  For each of these, you have the four vowel slots for the 3 $e$ and one $i$.  There are only four places to put the $i$, and the remaining $e$s are "forced."
five consecutive consonants
If there are exactly five consecutive consonants, the first "slot" must be slot 1 or slot 2 or slot 3 or slot 4 or slot 5 or slot 6.  For each of these, however, there is a different number of places where the sixth consonant can be placed.  As above, once the consonants have been placed, there are only four possible words, corresponding to the four possible positions for the $i$.
four consecutive consonants
The same logic as above holds, but is a bit more complex.
Hope this helps!


text:
Q: how to plot with multiple component in r I want to plot all components and group points by clusterNum column. However, as I tried to learn so far, we can plot only in 2D and 3D ways. So, I would like to know normally how to plot or represent graphs with these all PCs?
This is what the sample looks like:

            PC1         PC2         PC3        PC4        PC5 clusterNum
1    -2.3779857  0.85818117  0.77918535  0.1967346  0.9826036          2
2    -1.4290545  0.09556012 -0.06358622  1.3468587 -0.1525576          2
3     1.5621954  2.53686714 -2.57818785  0.0111326  0.2755555          1
4     1.9915498  0.19282116  1.34349507  0.0578331 -1.0146932          3
5    -0.4431131  1.38970833  2.34020611 -0.8359105  0.1402896          2
6    -1.9892596  0.37200044  2.00614197  0.5013188 -1.5358936          2
7    -2.6111509 -0.31112666  1.44419058  0.7313908  0.2597182          2
1977 -1.8662394  1.74827166 -2.37657231  0.4158580  1.1100287          4
1978  2.3477702 -2.24859797 -0.47305695  0.3690514 -1.1667859          3
1979  2.0797897 -0.14012792 -0.82941643 -1.2233560 -0.4523913          1

data <- structure(list(PC1 = c(-2.37798570730988, -1.42905447617503,1.56219540602943, 1.99154980323715, -0.443113128962729, -1.98925960995357,-2.6111508923784, -1.86623936673779, 2.3477701685881, 2.07978972115199), PC2 = c(0.858181174741465, 0.0955601160006672, 2.53686714046073,0.192821161122631, 1.38970832915268, 0.372000440681993, -0.31112665937417,1.74827166020088, -2.24859797467832, -0.140127921225955), PC3 = c(0.779185345162976,-0.0635862220559265, -2.57818784684844, 1.34349506727208, 2.34020610639405,2.00614196687586, 1.44419058101111, -2.37657231100357, -0.473056945068265,-0.829416434702976), PC4 = c(0.196734648339808, 1.34685865526758,0.0111326028445577, 0.0578331048357187, -0.83591054343165, 0.501318761327088,0.731390845165095, 0.415858033401411, 0.369051391354487, -1.22335597705293), PC5 = c(0.982603621624129, -0.152557597364265, 0.275555453841701,-1.01469324992585, 0.140289629133083, -1.53589363488684, 0.259718249982426,1.11002871887763, -1.16678589524657, -0.452391297542505), clusterNum = c(2L,2L, 1L, 3L, 2L, 2L, 2L, 4L, 3L, 1L)), row.names = c(1L, 2L, 3L,4L, 5L, 6L, 7L, 1977L, 1978L, 1979L), class = "data.frame")

Thank you in advance.

A: You could do a line plot with multiple lines, like this:
data <- structure(list(PC1 = c(-2.37798570730988, -1.42905447617503,1.56219540602943, 1.99154980323715, -0.443113128962729, -1.98925960995357,-2.6111508923784, -1.86623936673779, 2.3477701685881, 2.07978972115199), PC2 = c(0.858181174741465, 0.0955601160006672, 2.53686714046073,0.192821161122631, 1.38970832915268, 0.372000440681993, -0.31112665937417,1.74827166020088, -2.24859797467832, -0.140127921225955), PC3 = c(0.779185345162976,-0.0635862220559265, -2.57818784684844, 1.34349506727208, 2.34020610639405,2.00614196687586, 1.44419058101111, -2.37657231100357, -0.473056945068265,-0.829416434702976), PC4 = c(0.196734648339808, 1.34685865526758,0.0111326028445577, 0.0578331048357187, -0.83591054343165, 0.501318761327088,0.731390845165095, 0.415858033401411, 0.369051391354487, -1.22335597705293), PC5 = c(0.982603621624129, -0.152557597364265, 0.275555453841701,-1.01469324992585, 0.140289629133083, -1.53589363488684, 0.259718249982426,1.11002871887763, -1.16678589524657, -0.452391297542505), clusterNum = c(2L,2L, 1L, 3L, 2L, 2L, 2L, 4L, 3L, 1L)), row.names = c(1L, 2L, 3L,4L, 5L, 6L, 7L, 1977L, 1978L, 1979L), class = "data.frame")

library(tidyverse)
data %>%
  rownames_to_column() %>%
  select(-clusterNum) %>%
  mutate(rowname = factor(rowname, levels = rowname)) %>%
  pivot_longer(-rowname) %>%
  ggplot(aes(rowname, value, group = name, color = name)) +
  geom_line()

I don't think that is a common thing to do with PCA results though. Look here, here and here to learn what common practices for visualizing PCA results are.

A: In additional the excellent resources mentioned by Till, I'd just like to leave a note here that in my field of study, people often use principal components to do neighbour embedding. This loses all numerical interpretation of axes, but it puts more similar rows closer than disparate rows.
library(ggplot2)
library(uwot)

data <- structure(list(PC1 = c(-2.37798570730988, -1.42905447617503,1.56219540602943, 1.99154980323715, -0.443113128962729, -1.98925960995357,-2.6111508923784, -1.86623936673779, 2.3477701685881, 2.07978972115199), PC2 = c(0.858181174741465, 0.0955601160006672, 2.53686714046073,0.192821161122631, 1.38970832915268, 0.372000440681993, -0.31112665937417,1.74827166020088, -2.24859797467832, -0.140127921225955), PC3 = c(0.779185345162976,-0.0635862220559265, -2.57818784684844, 1.34349506727208, 2.34020610639405,2.00614196687586, 1.44419058101111, -2.37657231100357, -0.473056945068265,-0.829416434702976), PC4 = c(0.196734648339808, 1.34685865526758,0.0111326028445577, 0.0578331048357187, -0.83591054343165, 0.501318761327088,0.731390845165095, 0.415858033401411, 0.369051391354487, -1.22335597705293), PC5 = c(0.982603621624129, -0.152557597364265, 0.275555453841701,-1.01469324992585, 0.140289629133083, -1.53589363488684, 0.259718249982426,1.11002871887763, -1.16678589524657, -0.452391297542505), clusterNum = c(2L,2L, 1L, 3L, 2L, 2L, 2L, 4L, 3L, 1L)), row.names = c(1L, 2L, 3L,4L, 5L, 6L, 7L, 1977L, 1978L, 1979L), class = "data.frame")

umap <- umap(data[,-ncol(data)], n_neighbors = 2) # Go up to 15 or so for larger data

umap <- cbind(as.data.frame(umap), clusterNum = data$clusterNum)

ggplot(umap, aes(V1, V2)) +
  geom_point(aes(colour = factor(clusterNum)))

Created on 2021-07-07 by the reprex package (v1.0.0)


text:
Q: How to align child views of a toolbar vertically on a baseline? I would like to use the Android Toolbar with two child views.
Both child views have the same text size but different fonts.
The following snippet centers both children vertically but the button is a bit heighter than the TextView.
My question is: How can I align both children on a real baseline?
Thank you.
<android.support.v7.widget.Toolbar
     android:id="@+id/toolbar"
     android:layout_width="match_parent"
     android:layout_height="wrap_content"
     android:minHeight="?attr/actionBarSize"
     android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
     app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

        <TextView
           android:id="@+id/title"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:textSize="18sp"
           app:font="@{@string/font_1}" />

        <Button
           android:id="@+id/button"
           android:layout_width="wrap_content"
           android:layout_height="wrap_content"
           android:layout_gravity="right"
           android:background="@null"
           android:gravity="center_vertical|right"
           android:textSize="18sp"
           app:font="@{@string/font_2}" />
 </android.support.v7.widget.Toolbar>