text:
Q: Ionic project with database I am trying to create a mobile project , which is my first project in Ionic platform.
for same , I have to learn Angular and Ionic. So I decided to make a simple mobile project.
I have googled too much for Database in mobile technology so I got many of  database like- MongoDb, SQLite, Firebase etc. so I was the bit  confused about which database should I use in the ionic mobile project?
And Is there any beginners documentation for any database that  helps me to implement the database in my ionic project?
Thank you so much.

A: Instead of try to get it all at once, for training purposes, I would suggest starting only with Angular itself. Then, on a second project, try Ionic.
Some good starting points for angular are:
https://www.codecademy.com/pt-BR/learn/learn-angularjs
http://www.learn-angular.org/
Then, for Ionic I used:
https://thinkster.io/ionic-framework-tutorial
Now, specifically about database:
Ionic works with cordova, which maker the link between web development and mobile native functions. It makes it through plugins.
Nativelly Android and IOS support SQLite. So, if you want to use the most native resources possible, I think SQLite is the best option.
The best plugin (IMHO) is https://github.com/litehelpers/Cordova-sqlite-storage.
It's very easy to use this plugin:
On a Ionic cordova project, run
cordova plugin add cordova-sqlite-storage
Then, in your code, access the DB with
var db = window.sqlitePlugin.openDatabase({name: 'my.db', location: 'default'}, successcb, errorcb);

Then, simply run your SQLs:
db.executeSql("select length('tenletters') as stringlength", [], function (res) {
      var stringlength = res.rows.item(0).stringlength;
      console.log('got stringlength: ' + stringlength);
      document.getElementById('deviceready').querySelector('.received').innerHTML = 'stringlength: ' + stringlength;
   });

On the plugin site, there are more completes examples.
But, once again, I suggest learn the peaces first.
EDIT
Responding to comment:
To add information on Database is simple, almost like the SELECT sample above. Just pass your data as an array, on 2º argument of executeSQL(). Like this:
db.executeSql('INSERT INTO MyTable VALUES (?)', ['test-value'], function (resultSet) {
  console.log('resultSet.insertId: ' + resultSet.insertId);
  console.log('resultSet.rowsAffected: ' + resultSet.rowsAffected);
}, function(error) {
  console.log('SELECT error: ' + error.message);
});

Take a look at the documentation, there are others examples there.

A: I have been swimming through article after article of "not quite what I am looking for" answers. I found a video in french. Here it is: Ionic 3 Store Data
That being said, here is how to setup your code to make ionic 3 cordova sqlite workable.
1) Import your native sqlite by running these 2 commands in your npm or cmd prompt.

*

*ionic cordova plugin add cordova-sqlite-storage

*npm install --save @ionic-native/sqlite
2) Import into your app.module.ts

*

*import { SQLite} from '@ionic-native/sqlite';
3) Add as a provider in your app.module.ts
providers: [
   ...
    SQLite,
   ...
  ]

4) Create a new folder(if you want to make it a different component) and make a database ts file. For the sake of ease I called mine database.ts
5) Add the following code (Please note this is not real code that I use. Just an example. Usernames and passwords should not be stored in this way):
import { Injectable } from '@angular/core';
import { SQLite, SQLiteObject } from '@ionic-native/sqlite';

 @Injectable()
export class Database {

    theConsole: string = "Console Messages";

    options: any = {
        name: data.db,
        location: 'default',
        createFromLocation: 1
    }

    private db: SQLiteObject;

    constructor(private sqlite: SQLite) {

        this.connectToDb();
    }

    private connectToDb():void {

        this.sqlite.create(this.options)
            .then((db: SQLiteObject) => {

                this.db = db;
                var sql = 'create table IF NOT EXISTS `user` (username VARCHAR(255), password VARCHAR(255))';
                //IF you move the below statment out of here then the db variable will not be initialized
                //before you can use it to execute the SQL.
                this.db.executeSql(sql, {})
                .then(() => this.theConsole += 'Executed SQL' + sql)
                .catch(e => this.theConsole += "Error: " + JSON.stringify(e));
            })
            .catch(e => this.theConsole += JSON.stringify(e));

    }

     addUser(username, password):void {

        var sql = "INSERT INTO `user` (username,password) VALUES ('"+username+"','"+ password+"')";

        this.db.executeSql(sql,{})
        .then(() => this.theConsole += "\n" + 'Executed SQL' + sql)
        .catch(e => this.theConsole += "Error: " + JSON.stringify(e));

    }
    getDealer() {
        var sql = "SELECT * FROM user";

        this.db.executeSql(sql, {})
            .then((result) => {
                this.theConsole += JSON.stringify(result);
                if (result.rows.length > 0) {
                    this.theConsole += 'Result' + result.rows.item(0);
                }
                this.theConsole += "\n" + result.rows.item(0).username+ result.rows.item(0).password;
                this.theConsole +=  "\n" +'Rows' + result.rows.length;

            })

            .catch(e => this.theConsole += JSON.stringify(e));
    }

    getConsoleMessages() {
        return this.theConsole;
    }
}

Then you just have to import the database component(Class) into one of your pages and you can access the database by running these functions or by making your own RunSQL function that you can throw whatever you want into it.
What is really the part that confused me from ionic's website was the fact that they were showing the create but not the reuse of the SQLiteObject.
By adding the:
private db: SQLiteObject;

to my code in the declaration of class variables and in the initializing of the db object:
 ...
 this.sqlite.create(this.options)
            .then((db: SQLiteObject) => {

                this.db = db;
 ...

I was able to reuse the db variable without having to open the db connection over and over again.
6) Import your component class into a page
import { Database } from '../../data/database';

I used this site: ionic native sqlite to get the main understanding of how to set it up and the french video mentioned earlier. I wish I would have found  I hopefully can help others hitting this same sqlite wall. I wish I would have found what I found today sooner. I hopefully can help others hitting this same sqlite wall.


text:
Q: Get system region in Safari for iOS In my web app there is an input for the amount with currency.
I'm using React Currency Input Field to format it.
On my phone I have language set to Spanish and region set to Taiwan.
Their decimal separators are comma , and dot . respectively.
The problem is that iOS displays the numeric keyboard with dot as a separator, while the library expects a comma. In a result it is not possible to insert a separator at all.
Standard keyboard would affect the UX so it is out of the question.
The method window.navigator.locale returns language code: es-ES. However, in my case I need to retrieve a device's region.
Is there any method to retrieve system region? If not, shall the web app have region defined as the optional settings?

A: After brainstorming, we concluded that it was impossible to determine system preferences.
We have added an optional separate configuration for language and region so that the user can decide whether to stick with the system configuration or overwrite it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Undefined reference to 'bootmain'" error during xv6 installation through cygwin I am trying to get xv6 running on my windows laptop through cygwin and it shows this error: undefined reference to bootmain.
Help please. (screen text given below)
gcc -fno-pic -static -fno-builtin -fno-strict-aliasing -O2 -Wall -MD -ggdb -m32 -Werror -fno-omit-frame-pointer -fno-stack-protector -fno-pie -no-pie -fno-pic -O -nostdinc -I. -c bootmain.c
gcc -fno-pic -static -fno-builtin -fno-strict-aliasing -O2 -Wall -MD -ggdb -m32 -Werror -fno-omit-frame-pointer -fno-stack-protector -fno-pie -no-pie -fno-pic -nostdinc -I. -c bootasm.S
ld -m    elf_i386 -N -e start -Ttext 0x7C00 -o bootblock.o bootasm.o bootmain.o
ld: bootasm.o:/home/kaulv/xv6-public/bootasm.S:66: undefined reference to `bootmain'
make: *** [Makefile:106: bootblock] Error 1


text:
Q: Filtering data from API using dropdown in React How would I go about filtering results from an API using the dropdown?
I currently have a select tag like so
  <select value={selectMonthFilter} onChange={e=> setSelectMonthFilter(e.currentTarget.value)}>
    {console.log(selectMonthFilter)}
    <option value="">---</option>
    <option value="">Jan</option>
    <option value="">Feb</option>
    <option value="">Mar</option>
    ...
  </select>

The list is also displaying all the results from the API with
  const [data, setData] = useState([]);

  const [selectMonthFilter, setSelectMonthFilter] = useState(data)

Example of what the API returns
{
"id": 1,
"first_name": "Bob",
"last_name": "Smith",
"birthdate": "1970-04-19T08:56:27Z",
},

Where 1970 is the year, 04 is the month, 19 is the day and the string after is time.
How would I implement so if the user selects Mar on the dropdown, it filters all the people that have their birthdays in March?
I tried testing the following but it doesn't seem to select anything
  const selectMonths = (selectMonthFilter) => {
    setSelectMonthFilter(selectMonthFilter)
    console.log(selectMonthFilter)
  };

<select value={selectMonthFilter} onChange={event => selectMonths(event.target.value)} >

https://codesandbox.io/s/api-test-c4swl?file=/src/pages/home.jsx

A: *

*Provide month option values that match the month portion of the birthdate dateTime string.
<label>
  Select Month
  <select
    value={selectMonthFilter}
    onChange={(e) => setSelectMonthFilter(e.currentTarget.value)}
  >
    <option value="">---</option>
    <option value="01">Jan</option>
    <option value="02">Feb</option>
    <option value="03">Mar</option>
    <option value="04">Apr</option>
    <option value="05">May</option>
    <option value="06">Jun</option>
    <option value="07">Jul</option>
    <option value="08">Aug</option>
    <option value="09">Sep</option>
    <option value="10">Oct</option>
    <option value="11">Nov</option>
    <option value="12">Dec</option>
  </select>
</label>

*You can split the birthdate by "T" to get the date prefix, then split that by "-" and take the month part.
const getMonthValue = (dateTime) =>
  dateTime.toLowerCase().split("t")[0].split("-")[1];

*Once you've the month value you can filter your data by birthdates that match the selected month value. If there is no month to filter by then return true to include all data.
{data
  .filter(({ birthdate }) =>
    selectMonthFilter
      ? getMonthValue(birthdate) === selectMonthFilter
      : true
  )
  .map((el) => (
    // map your JSX here
  ))}

If you have more filters you can combine them in the single .filter callback.
Example:
{data
  .filter(({ birthdate, first_name, last_name, preferred_name }) =>
    selectMonthFilter || searchNameFilter
      ? (selectMonthFilter &&
          getMonthValue(birthdate) === selectMonthFilter) ||
        (searchNameFilter &&
          [first_name, last_name, preferred_name]
            .join(" ")
            .toLowerCase()
            .includes(searchNameFilter))
      : true
  )
  .map((el) => (
    ...
  ))}

It's up to you to decide if all the conditions need to be met (logical AND all conditions), or if any of them can match (logical OR all conditions).


text:
Q: Is there a name for this collection of sorted arrays data structure? Is there a name for the following data structure? Are there papers and citations available?
One way to implement an efficient set abstract data type is to have a collection of sorted arrays, where each array has a unique power-of-2 size.
For example, a set of 13 elements {1, 2, ..., 13} can be represented by this collection of sorted arrays: {[5], [2, 3, 9, 13], [1, 4, 6, 7, 8, 10, 11, 12]}.
In general, the arrays that are in the collection have sizes that correspond to the 1 bits in the binary representation of the size of the set. The data structure is efficient because insertion can be performed in amortized O(1) time, and search can be performed in O((log n)2) time (which is better than linear search). Also, it uses only O(log n) space overhead for pointers, unlike balanced binary trees and B-trees which use O(n) extra space for pointers. Thus, almost all the space is used for payload data.
I've looked at Wikipedia's list of data structures but didn't find a match. It's true that the book Introduction to Algorithms ("CLRS") describes this data structure as a homework problem in the "Amortized Analysis" section, but because it's a question rather than an example, the book doesn't say much about it.

A: A similar idea dates back at least to Jean Vuillemin's original publication on binomial heaps in the April 1978 issue of CACM. I would expect the paper that introduced this data structure to cite or be cited by Vuillemin, but none of the papers on the "references" and "cited by" lists look promising.
If I were you, I would ask cstheory and then write to CLRS, but given the suboptimal bounds and lack of deletion, I don't expect anything to turn up unless the succinct data structure community took an interest at some point.
Is there something in particular you wanted to know?


text: Q: What test should be used to find if a COVID-19 has had significant effect on monthly sales? I have 10 years of monthly Drink sales (in litres per capita). Sales of some drink categories dropped sharply in April and May 2020 when COVID-19 restrictions were imposed by government (eg. "Stay home"). What test should I perform to examine whether the drop in sales is statistically significant?


text:
Q: Spaces around Cyrillic emdash (babel) There is the command "--- (Cyrillic emdash) defined in the babel package (for the Russian language). It is shorter than the usual English dash --- and has shorter spaces around it (also they are non-breaking as I can see). What is the width of such spaces? Is it equal to the width of the \, space?

A: The command \cyrdash is responsible of printing the dash; when the current language is Russian, it prints character 22 (the same slot as the em-dash, but in T2A encoded fonts it is shorter) or does
\hbox to 0.8em{--\hss--}

when the current encoding is not T2A, which means it superimposes two en-dashes so that the overall width is 0.8em (so changing with the font). The definition of "- is a bit complicated:
\declare@shorthand{russian}{"-}{%
  \def\russian@sh@tmp{%
    \if\russian@sh@next-\expandafter\russian@sh@emdash
    \else\expandafter\russian@sh@hyphen\fi}%
  \futurelet\russian@sh@next\russian@sh@tmp}
\def\russian@sh@hyphen{\nobreak\-\bbl@allowhyphens}
\def\russian@sh@emdash#1#2{\cdash-#1#2}
\def\cdash#1#2#3{\def\tempx@{#3}%
\def\tempa@{-}\def\tempb@{~}\def\tempc@{*}%
 \ifx\tempx@\tempa@\@Acdash\else
  \ifx\tempx@\tempb@\@Bcdash\else
   \ifx\tempx@\tempc@\@Ccdash\else
    \errmessage{Wrong usage of cdash}\fi\fi\fi}
\def\@Acdash{\ifdim\lastskip>\z@\unskip\nobreak\hskip.2em\fi
  \cyrdash\hskip.2em\ignorespaces}%
\def\@Bcdash{\leavevmode\ifdim\lastskip>\z@\unskip\fi
 \nobreak\cyrdash\penalty\exhyphenpenalty\hskip\z@skip\ignorespaces}%
\def\@Ccdash{\leavevmode
 \nobreak\cyrdash\nobreak\hskip.35em\ignorespaces}%

Basically it means that "- produces \russian@sh@hyphen, whereas "-- does \russian@sh@emdash.
The former issues \nobreak so the preceding word part can be hyphenated; then inserts a discretionary hyphen, allowing the following word part to be hyphenated.
The latter looks at the next two tokens (the first is still -); there are four cases according to the third character

*

*"--- issues \@Acdash;

*"--~ issues \@Bcdash;

*"--* issues \@Cdash;

*None of the above, so "-- is followed by (ignored) spaces and another token than -, ~ or ~.

In the fourth case the error Wrong usage of cdash is raised.

*

*The case "--- removes a preceding space if present and, in this case, inserts a nonbreaking space of width 0.2em, followed by \cyrdash and a further nonbreaking space of width 0.2em.

*The case "--~ removes a preceding space if present, inserts \cyrdash and then a penalty like for an explicit hyphen, ignoring following spaces.

*The case "--* is for "dialogues": no space before and the \cyrdash is followed by a space of 0.35em, ignoring following spaces.
There is an error in the definitions: "--- at the beginning of a paragraph can produce unexpected results. There should be \leavevmode at the beginning like for the other two macros.
\documentclass{article}
\usepackage[T2A]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[russian]{babel}

%% fix the error
\makeatletter
\def\@Acdash{\leavevmode\ifdim\lastskip>\z@\unskip\nobreak\hskip.2em\fi
  \cyrdash\hskip.2em\ignorespaces}%
\makeatother

\begin{document}

\verb|"-|: a"-b

\verb|"---|: a"---b a "--- b

\verb|"--~|: a"--~b a "--~ b

\verb|"--*|: "--*a "--* a

\end{document}


text:
Q: Maven plugin MOJO brakes the build when resolving dependency Example to reproduce: https://github.com/g4s8/example-plugin
I'm trying to create Maven Plugin which works with compiled test classes. Before accessing test-classes files it has to resolve the classpath. I observed classpath resolving mechanism in surefire-maven-plugin sources, but my implementation is simpler (see https://github.com/g4s8/example-plugin/blob/master/example-maven-plugin/src/main/java/wtf/g4s8/RunWithClasspathMojo.java#L43-L49):
// resolve all dependencies for current project
final Set<Artifact> artifacts = this.repos.resolve(
        new ArtifactResolutionRequest()
            .setArtifact(this.project.getArtifact())
            .setLocalRepository(this.lrep)
            .setRemoteRepositories(this.project.getRemoteArtifactRepositories())
            .setResolveTransitively(true)
).getArtifacts();

This plugin is working fine, but after first run it breaks all next build of the project (see example-project): maven-jar-plugin is failing with error:

[ERROR] Failed to execute goal org.apache.maven.plugins:maven-jar-plugin:3.0.2:jar (default-jar) on project example-project: You have to use a classifier to attach supplemental artifacts to the project instead of replacing them. -> [Help 1]

If I disable my plugin with -DskipTests or just remove
the code to resolve dependencies, target project will be built successfully.
I suppose ArtifactRepository.resolve somehow affects current build.
What's wrong with this code and how to resolve dependencies classpaths for Maven project from plugin correctly?

A: In the top line of the Mojo (where you also define the phase etc.), you need to set the @requiresDependencyResolution to test.


text:
Q: Send Mail with Outlook on Exchange Account I want to send EMails with C# and the Microsoft.Office.Interop.Outlook library.
I am locked in, on my Outlook account with a@domain.com and got the rights on the exchange server to send mails from b@domain.com and c@domain.com.
I don't find any way to send a mail with B or C.
I got everything working for my user account which has the mail a@domain.com.
Now I can't find a way to get the account of b@domain.com and send a mail in the name of B.
My Question:
How do I get access to the other accounts?
That's the code I have:
using Outlook = Microsoft.Office.Interop.Outlook;
        public static Outlook.Account GetAccountForEmailAddress(Outlook.Application application, string smtpAddress)
    {

        // Loop over the Accounts collection of the current Outlook session.
        Outlook.Accounts accounts = application.Session.Accounts;
        if (_IsDebug)
            Console.WriteLine($"Anzahl Accounts: {accounts.Count}");
        foreach (Outlook.Account account in accounts)
        {
            // When the e-mail address matches, return the account.
            if (_IsDebug)
                Console.WriteLine($"Account: {account.SmtpAddress}");
            if (String.Compare(account.SmtpAddress, smtpAddress, true) == 0)
            {
                return account;
            }
        }
        throw new System.Exception(string.Format("No Account with SmtpAddress: {0} exists!", smtpAddress));
    }
        static void SendEMail(string emailadress)
    {
        try
        {
            var outlookApplication = new Outlook.Application();
            var outlookMailItem = (Outlook.MailItem)outlookApplication.CreateItem(Outlook.OlItemType.olMailItem);

            outlookMailItem.SendUsingAccount = GetAccountForEmailAddress(outlookApplication, ConfigurationManager.AppSettings[SENDER]);

            if (_IsDebug)
                Console.WriteLine($"Absender: {outlookMailItem?.SendUsingAccount?.SmtpAddress}");

            outlookMailItem.HTMLBody = ConfigurationManager.AppSettings[BODY];

            if (_IsDebug)
                Console.WriteLine($"Body: {outlookMailItem?.HTMLBody}");

            var file = GetPDFFile();
            if (_IsDebug)
                Console.WriteLine($"File: {file?.Name}");

            if (file == null)
            {
                Console.WriteLine("Keine Datei gefunden!");
                return;
            }

            string attachementDisplayName = file.Name;

            int attachementPosition = outlookMailItem.HTMLBody.Length + 1;
            int attachementType = (int)Outlook.OlAttachmentType.olByValue;

            if (_IsDebug)
                Console.WriteLine($"Dateianhang: {file.FullName}");

            Outlook.Attachment outlookAttachement = outlookMailItem.Attachments.Add(file.FullName, attachementType, attachementPosition, attachementDisplayName);

            outlookMailItem.Subject = ConfigurationManager.AppSettings[SUBJECT];

            Outlook.Recipients outlookRecipients = outlookMailItem.Recipients;
            Outlook.Recipient outlookRecipient = outlookRecipients.Add(emailadress);

            outlookRecipient.Resolve();

            outlookMailItem.Send();

            outlookRecipient = null;
            outlookRecipients = null;
            outlookMailItem = null;
            outlookApplication = null;

            if (_IsDebug)
                Console.ReadLine();
        }
        catch (Exception)
        {
            throw;
        }
    }

A: You have to grant the owner of the sending mailbox Send As permissions on the mailboxes you want to send the emails from.  Send on behalf of permissions will work but will say "A on behalf of B" as the sender.


text:
Q: Calling a method on object directly(obj.fnName) vs calling that method using apply on the same object(obj.fnName.apply(obj, arguments))))? Today I have come across two ways of calling an object method. This I have seen in a kind of API which when expose certain functions to the external world. In those methods I have found following way obj.MyFn.apply(obj, arguments) to call the encapsulated methods which they dont want to expose to the outside world.
So my question is:
What is the difference(context here is in terms of encapsulation of API's internal methods, here its MyFn) between following two ways of calling a method of an object?

*

*obj.MyFn() and

*obj.MyFn.apply(obj, arguments);

Assumption:
I have an object obj having defined a method named as MyFn.


text:
Q: Extend an entity class in JPA throws Unknown column 'DTYPE' in 'field list' error @Entity
@Table(name = "PERSON")
@Inheritance(strategy=InheritanceType.SINGLE_TABLE)
public class Person {
    @Id
    @GeneratedValue
    @Column(name = "PERSON_ID")
    private Long personId;

    @Column(name = "FIRSTNAME")
    private String firstname;

    @Column(name = "LASTNAME")
    private String lastname;

    // Constructors and Getter/Setter methods,
}

Employee class extends Person
@Entity
public class Employee extends Person {

    @Transient
    private Date joiningDate;

    // Copy Constructors and Getter/Setter methods,
}

The Employee class has only a transient object So I am not sure about using of @DiscriminatorColumn and @DiscriminatorValue, When i tried without using Discriminator that throws error
session.save(employee);

I am trying to save Employee object that throws Unknown column 'DTYPE' in 'field list' error

A: I have encountered the same issue using EclipseLink and I have tried to use @discriminator annotation ... without success
because in this solution, a specific column must be added in 2 tables.
I don't have the possibility to add columns in tables, so I have found following solution :
@Entity
@Table(name = "PERSON")
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Person {

I have just changed inheritance type from SINGLE_TABLE to TABLE_PER_CLASS
I have found useful explanation on Thoughts on Java
Just for information, my 2 tables are in reality 1 table and a view on same table with 2 or 3 joins.

A: You should use @DiscriminatorColumn and @DiscriminatorValue. You can find a good example here.

A: D_TYPE is basically name of your child class.
Let's suppose you have:

*

*Abstract Employee(id, name);

*class FullTimeEmployee extends Employee(Double salary)

*with Inheritence.SINGLE_TABLE strategy.

A table employee will be created with these columns
Employee (D_TYPE, id, name, salary)

where D_TYPE will be name of your child classes.
employeeRepository.insert(Employee emp);

where you can pass emp as new FullTimeEmployee(id, name, salary);
After insert it will automatically populate d_type as Full_Time_Employee
If you want to change the name of D_TYPE column use
@DiscriminatorColumn(name="customizedNameofD_TYPE")
Just FYI: mostly used strategy is InheritanceType.JOINED

A: Persist child entity rather than persisting parent entity.
@MappedSuperclass
public class Person {

And
@Entity
@Table(name = "PERSON")
public class Employee extends Person {

This should resolve your issue.


text:
Q: Decryption of .png and .jpg files I'm trying to modify graphic assets of the software I'm using (for aesthetic puroposess, I guess it's hard to do something harmful with graphic assets) but developer encrypted them. I'm not sure why he decided to do that since I used and modified a bunch of similar softwares and developers of those didn't bother (as I can see no reason why encrypting those assets would be necessary).
So anyway here are examples of those encrypted graphic assets:
http://www.mediafire.com/view/sx2yc0w5wkr9m2h/avatars_50-alpha.jpg
http://www.mediafire.com/download/i4fc52438hkp55l/avatars_80.png
Is there a way of decrypting those? If so how should I go about this?

A: The header "CF10" seems to be a privately added signature to signify the rest of the file is "encoded". This is a very simple XOR encoding: xor 8Dh was the first value I tried, and I got it right first time too. The reasoning behind trying that as the first value is that the value 8D occurs very frequently in the first 100 bytes-or-so, where they typically could be lots of zeroes.
"Decrypting" is thus very straightforward: if a file starts with the four bytes CF10, remove them and apply xor 8Dh on the rest of the file. Decoding the files show the first "JPG" is in fact a tiny PNG image (and not a very interesting one to boot), the second is indeed a PNG file:

The file extension may or may not be the original file extension; the one sample called ".jpg" is in fact also a PNG file, as can be seen by its header signature.
The following quick-and-dirty C source will decode the images. The same program can be adjusted to encode them as well, because the xor operation is exactly the same. The only thing needed is add a bit of logic flow:

*

*read the first 4 bytes (maximum) of the input file and test if this forms the string CF10

*if not, the file is not encoded:
a. write CF10 to the output file
b. encode the image by applying xor 8Dh on each byte

*if so,
b. decode the image by applying xor 8Dh on each byte.

As you can see, there is no "3a" and both "b" steps are the same.
#include <stdio.h>
#include <string.h>

#ifndef MAX_PATH
    #define MAX_PATH    256
#endif

#define INPUTPATH "c:\\documents"
#define OUTPUTPATH ""

int main (int argc, char **argv)
{
    FILE *inp, *outp;
    int i, encode_flag = 0;
    char filename_buffer[MAX_PATH];
    char sig[] = "CF10", *ptr;

    if (argc != 3)
    {
        printf ("usage: decode [input] [output]\n");
        return -1;
    }

    filename_buffer[0] = 0;
    if (!strchr(argv[1], '/') && !strchr(argv[1], 92) && !strchr(argv[1], ':'))
        strcpy (filename_buffer, INPUTPATH);
    strcat (filename_buffer, argv[1]);

    inp = fopen (filename_buffer, "rb");
    if (inp == NULL)
    {
        printf ("bad input file '%s'\n", filename_buffer);
        return -2;
    }
    ptr = sig;
    while (*ptr)
    {
        i = fgetc (inp);
        if (*ptr != i)
        {
            encode_flag = 1;
            break;
        }
        ptr++;
    }
    if (encode_flag)
    {
        /* rewind file because we already read some bytes */
        fseek (inp, 0, SEEK_SET);
        printf ("encoding input file: '%s'\n", filename_buffer);
    } else
        printf ("decoding input file: '%s'\n", filename_buffer);

    filename_buffer[0] = 0;
    if (!strchr(argv[2], '/') && !strchr(argv[2], 92) && !strchr(argv[2], ':'))
        strcpy (filename_buffer, OUTPUTPATH);
    strcat (filename_buffer, argv[2]);

    outp = fopen (filename_buffer, "wb");
    if (outp == NULL)
    {
        printf ("bad output file '%s'\n", filename_buffer);
        return -2;
    }
    printf ("output file: '%s'\n", filename_buffer);

    if (encode_flag)
        fwrite (sig, 1, 4, outp);
    do
    {
        i = fgetc(inp);
        if (i != EOF)
            fputc (i ^ 0x8d, outp);
    } while (i != EOF);
    fclose (inp);
    fclose (outp);
    printf ("all done. bye bye\n");
    return 0;
}

A: Ok so when it comes to practical usage of the code provided by @Jongware that was unclear to me - I figured it out with some help:)

*

*I compiled the code using Visual Studio (you can find guides on how to do that, basically create new Visual C++ project and in Project -> Project Propeties choose C/C++ -> All options and  Compile as C Code (/TC)).

*Then I opened program in command prompt using parameter "program encrypted_file decrypted_file".

Thanks a lot for help Jongware!


text:
Q: 2 TextWatchers for 1 EditText I'm working on a simple android app project for myself. I found an article that made me decided to use TextWatcher. So simply, I add TextWatcher into my code. But here's the thing. I have designed 2 RadioButtons and 1 EditText. Both RadioButton will determine the format of my one and only EditText.
Here's how I want the apps to be reproduced:

*

*If the user pressed Button A, then the input format for the Edittext will be like this:

ABCD  1234  EFGH  5678

So, it has space in every 4 characters

*If the user pressed Button B, then the input format for the EditText will be like this:

ABCD1234EFGH5678

So, it has no space in every 4 characters
Even the user pressed the opposites again, the format of the EditText will follow the condition
This is What I've tried:
Use the if-else condition, and even create 2 TextWatchers, but still, the flow will be like this:
Make 2 TextWatchers to determine the case, but still here's what I've got:

*

*The user pressed Button B, the Edittext format will be like ABCD1234EFGH5678

*Then, The user pressed Button A, the Edittext format will be like ABCD  1234  EFGH  5678

*When The user pressed Button B again, the Edittext format will be like ABCD  1234  EFGH  5678 instead of ABCD1234EFGH5678
How am I supposed to do to reach this approach?
Here's my MainViewGenerator.java:
this.editTextNumberSpaceTextWatcher = new EditTextNumberSpaceTextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        super.onTextChanged(s, start, before, count);
        editTextString = s.toString();
    }
};

this.editTextNumberNormalTextWatcher = new EditTextNumberNormalTextWatcher() {
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        super.onTextChanged(s, start, before, count);
        editTextString = s.toString().replaceAll(" ", "");
    }
};

withId(R.id.my_main_editText, new Anvil.Renderable() {
    @Override
    public void view() {
        if (!btnRadioGroupValue.isEmpty()){
            if (btnRadioGroupValue.equals(valueButtonA)){
                onTextChanged(EditTextNumberSpaceTextWatcher);
                text(editTextString);
            } else if (btnRadioGroupValue.equals(valueButtonB)){
                onTextChanged(EditTextNumberNormalTextWatcher);
                text(editTextString);
            }
        }
    }
});

Here's my EditTextNumberSpaceTextWatcher.java:
public abstract class EditTextNumberSpaceTextWatcher extends PhoneTextWatcher {
    private static final String MY_NUMBER_FORMAT = "**** **** **** **** **** **** **** ****";

    public EditTextNumberSpaceTextWatcher() {
        super(MY_NUMBER_FORMAT );
    }

    @Override
    public char[] getSeparatorCharacters() {
        return new char[]{' '};
    }
}

Here's my EditTextNumberNormalTextWatcher.java:
public abstract class EditTextNumberNormalTextWatcherextends PhoneticTextWatcher {
    private static final String MY_NUMBER_FORMAT = "********************************";

    public EditTextNumberNormalTextWatcher() {
        super(MY_NUMBER_FORMAT );
    }
}

A: I think you can use just one TextWatcher:
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
//here evaluate the value of radio button
 if(mRadioButton1.isChecked()){
      //set pattern
   }else if(mRadioBUtton2.isChecked()){
     //set another pattern
   }
}


text:
Q: How to change the background color of an li through a button and to use the same button to return the li to its original color? everyone!
I wrote the function below:
`function addClickEventToButton(buttonId, classReceiver) {
  let buttonChangeColors = document.getElementById(buttonId);
  let eventReceiver = document.getElementsByClassName(classReceiver);
  buttonChangeColors.addEventListener('click', function () {
    for (let i = 0; i < eventReceiver.length; i += 1) {
      if (eventReceiver[i].style.backgroundColor = 'rgb(238,238,238)') {
      eventReceiver[i].style.backgroundColor = 'white';
      } else {
        eventReceiver[i].style.backgroundColor = 'rgb(238,238,238)';
      }
    }
  });`

The objective is to change the background color of 3 li's to white whenever I click a button. This part worked. The next thing I want to do is, when I click the same button again, to return their background color to the original color. Can anyone tell me what I'm doing wrong and how to fix it?


text:
Q: MailChimp API, Groups, Segments, and Lists I have a few questions about MailChimp and am looking for a "best practices" answer from someone who knows better than I do. I have several hundred subscribers in a specific list on MailChimp. What I want to do is essentially "classify" them into different groups or segments (I don't know which) based on match calculations like (purchased between 1 and 4 weeks ago, 5-10 weeks ago, etc).
We would like to create specific email campaigns and then blast the subscribers based on the math. I am not sure whether I should use "Groups" or "Segments". We are wanting to run a weekly chron job to reclassify everyone. So we would like to first clear (not delete segments or groups or unsubsribe users) the group or segment and then start looping through our user base and do API calls to reclassify them where we need them to be.
Can anyone help me understand this? I have read the KB (http://kb.mailchimp.com/lists/groups-and-segments/about-segments-and-groups) but I am still not clear on how I should approach this (groups vs. segments I think).
Any guidance would be appreciated.

A: I suggest that you create a group for each "match-calculation", you'll have a group for "purchased between 1 and 4 weeks ago" and one more for "5-10 weeks ago", then, you'll create a segment for each group (List->Manage Subscribers->Create Segment). When creating a campaign you'll be able to select a segment.

So we would like to first clear (not delete segments or groups or
  unsubsribe users) the group or segment and then start looping through
  our user base and do API calls to reclassify them where we need them
  to be.

You don't have to clear the segment when executing your cron job, you could update your groups for each user (which would update the members in each segment). Here's an example of updating a subscriber.

( POST request to
  https://us8.api.mailchimp.com/2.0/  lists/update-member )

{
  "apikey":"Key"
  "id":"listID",
  "email":{
    "email":"email@domain.com"
  },
  "merge_vars":{
    "GROUPINGS":[
      {
        "id":groupingsID,
        "groups":{
          "four_weeks":"four_weeks",
          "ten_weeks":"ten_weeks"
        }
      }
    ]
  },
  "email_type":"html"
}

Above I'm adding the subscriber to two groups (thereby to the two segments).
Angel


text:
Q: devtools equivalent of RStudio Build panel buttons I am making an R package using RStudio.  I am comfortable using the buttons on the Build panel.  I have a script that I would like to run each time I Build & Reload or Clean and Rebuild.  I'd like to write a function that runs my script and then executes the devtools commands associated with one of those buttons, but I am having trouble finding documentation of the correspondence between those buttons and devtools commands.  The buttons are as follows:

*

*Build & Reload

*Check

*Load All

*Clean and Rebuild

*Test Package

*Check Package

*Build Source Package

*Build Binary Package

For each of the items in that list, what devtools R code would I run to cause the exact same behavior?

A: To execute the Clean & Rebuilt action from RStudio inside R you can use the R function
system()
Executing
system("R CMD INSTALL
--preclean
--no-multiarch
--with-keep.source <your_package_name>")

Executes the Shell command from within your R session. Be aware that you will have to refer to the correct location of your package if you run this outside the Package Project (e.g. from another project or session)

A: In RStudio you can check "Use devtools package functions if available" in Project Options > Build Tools and you can see what devtools functions will be used. If you look at the build console pane, you can check out what RStudio runs. General cases if using devtools:

*

*Build & Reload

*

*devtools::build()

*devtools::reload() is possibly an option but Rstudio uses R CMD INSTALL --no-multiarch --with-keep.source <pkgNameGoesHere>

*Check

*

*devtools::check()

*Load All

*

*devtools::load_all(".")

*Clean and Rebuild

*

*R CMD INSTALL --preclean --no-multiarch --with-keep.source <pkgNameGoesHere>

*Test Package

*

*devtools::test()

*Check Package

*

*devtools::check() (same as Check button)

*Build Source Package

*

*devtools::build()

*Build Binary Package

*

*devtools::build(binary = TRUE, args = c('--preclean'))
More info at the readme in the devtools repo.


text:
Q: Drillthorough from Matrix Values power BI I have a report like this
                                                                            |Sales|

Country
Q1
Q2

America
122
50

India
100
100

England
55
142

Hope you understand it is a matrix. Having regionwise sales and pivoted with quater.
I have another summary report with sales details. I want to drillthrough the values and move to detail report.
For example. When I click on Q1 America sales value , which is 122. I want to drill through that value and move to detailed report which should filter me the detailed data based on Q1 and America.
Basically I want to drill through from values applying country and quarter together.
How to achieve this in Power BI


text:
Q: CodeChef Morning Commute wrong answer Here's the question:
The Chef commutes to work every day using the city's underground metro. The schedule for the trains has recently been changed and he wants to know how long it will take to travel from the station nearest to his house and the station nearest to his restaurant.
The Chef doesn't want to change the route he took before, so he simply has to find out how long it will take to reach his restaurant along his usual route. This route is given by a sequence of stations s0, s1, ..., sn where s0 is the station where the Chef enters the metro and sn is the station where the Chef exits the metro.
Trains are scheduled to run between every two consecutive stations si-1 and si. Such a schedule is specified by three integers xi, li, and fi. This means that the first train on this line starts operating at time xi. The time it takes this train to travel from si-1 and si is exactly li units. Finally, a train departs from station si-1 every fi minutes following the previous train. That is, a train departs at time xi, xi+fi, xi+2fi, and so on.
The Chef is very experienced at navigating the metro so the time it takes him to transfer between trains at a given station is essentially zero. Thus, if the Chef arrives at a station, say si, the moment that the train from si to si+1 is scheduled to depart, he skillfully hops on this next train. However, if the Chef arrives when no train to si+1 is scheduled to depart, he must wait until the scheduled departure time.
Help the Chef figure out how long it will take him to travel from station s0 to station sn. You may assume that the Chef is already at station s0 at time 0.
Input
The first line consists of a single integer denoting the number of test cases (at most 50). Each test case begins with a line containing a single integer n between 1 and 1000 indicating the number of lines the Chef must traverse (so there are n+1 stations s0, s1, ..., sn). The next n lines describe the train schedules between stations, one per line. The i'th such line gives the values xi, li, and fi for the train that travels between stations si-1 and si.
The xi values will be between 0 and 1000 and the li and fi values will be between 1 and 1000.
Output
For each test case you are to output a single integer denoting the minimum time t for which the Chef can reach station sn using the given route. Remember, the Chef starts at s0 at time 0.
Example
Input:
3
2
0 4 7
0 6 5
2
0 1 2
6 2 10
2
1 2 3
0 2 3
Output:
11
8
5
Here's the link to the problem: http://www.codechef.com/problems/COMMUTE/
I've tried multiple solutions but couldn't figure out why Codechef is giving me "wrong answer" messages. Note that my program produced the same output as the example output in Codechef, and I even made up some of my own numbers and plug them in, and my program still gives the correct (I calculated them by myself) result.
My thought process is:

*

*---- for starting time

*____ for traveling time

*++++ for waiting time

In this case, the time required for traveling from station1 to station2 is starting time+traveling time for station2:
------_____++++++
-----------------------____+++|+++|+++

In this case, the time required for traveling from station2 to station3 is starting time, treveling time and 2 waiting time of station3.
-----------------------____+++|+++|+++
-------______________++++|++++|++++|++++|

And the total time would be the same from station2 to station3. Because it's linear?
Here's my code:
public static void main(String[] args) {
    Scanner in = new Scanner(System.in);

    int cases = in.nextInt();
    int n = 0;

    int [] t = new int [cases];
    for(int i = 0; i < cases; i++) {
        int stations = in.nextInt();
        int [] start = new int [stations];
        int [] travel = new int [stations];
        int [] gap = new int [stations];

        for(int j = 0; j < stations; j++) {
            start[j] = in.nextInt();
            travel[j] = in.nextInt();
            gap[j] = in.nextInt();
        }
        for(int j = 0; j < (stations-1); j++) {
            n = 0;
            if(j==0) {
                if(start[j] + travel[j] > start[j+1]+(n*gap[j+1])) {
                    while(start[j] + travel[j] > start[j+1]+(n*gap[j+1])) {
                        n++;
                    }
                    t[i] = start[j+1] + (n*gap[j+1]) + travel[j+1];
                } else {
                    t[i] = start[j+1] + travel[j+1];
                }
            } else {
                if(t[i] > start[j+1]+(n*gap[j+1])) {
                    while(t[i] > start[j+1]+(n*gap[j+1])) {
                        n++;
                    }
                    t[i] = start[j+1] + (n*gap[j+1]) + travel[j+1];
                } else {
                    t[i] = start[j+1] + travel[j+1];
                }
            }
        }
    }
    for(int i = 0; i < cases; i++) {
        System.out.println(t[i]);
    }
}


text:
Q: Read a floating point matrix using Regular expressions I am trying to read a matrix from a file using RegEx. The file consists of several strng, \n characteres, white spaces and floating point numbers. I would like to read only sets of three or more consecutive floating points. An exemple of code is as follow:
Data.txt
$Nodes
5
1 0 0 0
2 1 0 0
3 1 1 0
4 0 1 0
5 0.5 0.5 0
$EndNodes
$Values
5
1 1.5 3.6
2 1.5 3.4
3 1.5 3.3
4 1.5 3.5
5 1.5 3.1
$EndValues

In my read_file.py, I have:
def read_file(filename):
    text = str()
    with open(filename) as file:
        lines = file.readlines()
        for line in lines:
            text += line
    return text

The final output of my read_file functions is a big string containing the whole text, so I could use RegEx to find whatever I like all at once.
Well, I would like to read all the sets of three numbers (After $Nodes\n5 and before $EndNodes\n).
I tried many things, like re.compile(r'\$Nodes (.*)\$EndNodes') and many others combinations of characters, but nothing seems to work.
What I need, in the end, is something like:
list_of_nodes = [('1', '0', '0', '0'), ('2', '1', '0', '0'), ('3', '1', '1', '0'), ('4', '0', '1', '0'), ('5', '0.5', '0.5', '0')]

Any help would be apreciated. Thanks in advance,

A: You're really close. The regex you wrote would work with the re.DOTALL flag. In regex, . represents 'any character except newline'. When you use the re.DOTALL flag, . includes the newlines as well.
Demo


text:
Q: Why is DRF serializer returning errors with required fields? When I make a post request to register a user, the data sent is complete and in order, but the RegisterationSerializer serializer returns an error for the username and password fields. The error reads This field is required. for both fields.
My first guess was that the serializer is not receiving the data sent but that's false but the serializer receives the data.
What am I doing wrong?
Could the validated_data parameter in the create method not be populated. I tested it by printing it out on the terminal when making a request but it didn't print.
For the model, I'm using the built-in user model.
Serializer
from django.contrib.auth.models import User
from rest_framework import serializers

class RegisterationSerializer(serializers.ModelSerializer):
    """Registeration serializer"""

    class Meta:
        model = User
        fields = ["id", "username", "first_name", "last_name", "email", "password"]
        extra_kwargs = {"password": {"write_only": True}}

    def create(self, validated_data):

        username = validated_data["username"]
        first_name = validated_data["first_name"]
        last_name = validated_data["last_name"]
        email = validated_data["email"]
        password = validated_data["password"]

        user = User.objects.create_user(
            username=username,
            first_name=first_name,
            last_name=last_name,
            email=email,
            password=password,
        )

        return user

Views
from authentication.serializers import RegisterationSerializer

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.authtoken.models import Token

class RegisterationView(APIView):
    """Registeration View"""

    def post(self, request):
        serializer = RegisterationSerializer(data=request.data)

        # Generate tokens for existing users
        for user in User.objects.all():

            if not user:
                break
            else:
                try:
                    Token.objects.get(user_id=user.id)
                except Token.DoesNotExist:
                    Token.objects.create(user=user)

        if serializer.is_valid():
            user = serializer.save()
            token = Token.objects.create(user=user)

            return Response(
                {
                    "user": {
                        "first_name": serializer.data["first_name"],
                        "last_name": serializer.data["last_name"],
                        "username": serializer.data["username"],
                        "email": serializer.data["email"],
                    },
                    "status": {
                        "message": "user created",
                        "code": status.HTTP_201_CREATED,
                    },
                    "token": token.key,
                }
            )

        return Response(
            {
                "error": serializer.errors,
                "status": status.HTTP_203_NON_AUTHORITATIVE_INFORMATION,
            }
        )


text:
Q: Remove Duplicate Query The below query gives me 1716,
select distinct ce_email from comm_list where clp_no = 585

When I add a c_no to the query the results go up by one to 1717. Is there a way to only show the MAX(c_no) and ce_email so I don't have duplicate ce_emails? I need all the emails but I can't have duplicates and I need to associate them with a c_no.

A: Use Group By like this:
SELECT ce_email,max(c_no)
FROM comm_list
WHERE clp_no = 585
GROUP BY ce_email;

SQL Fiddle Demo


text:
Q: One token vs. multiple tokens to prevent CSRF attacks I'm using Codeigniter and I want to prevent CSRF attacks attempts that may happen. And to achieve this I add a hidden input tag with a random token to each form I want to protect, and in the same time I keep this token in a session to compare against when begin handling this form data.
  // set a token to prevent CSRF attacks
  $csrf_token = md5(uniqid(rand(), true));
  $this->session->set_userdata("csrf_token", $csrf_token);

And the form will look like this:
<form action="path/to/handler/page" method="post">
    <input type="text" name="title">
    <input type="text" name="date">
    <textarea name="content"></textarea>
    <input type="hidden" name="csrf_token" value="<?php echo $this->session->userdata("csrf_token") ?>">
    <input type="submit" name="submit" value="Save">
</form>

And in the page where I handle submitted data I check CSRF attacks something like this:
  // make sure there is no CSRF attack attempt
  $csrf_token = $this->session->userdata("csrf_token");
  if (empty($csrf_token) || $csrf_token !== $this->input->post("csrf_token")) {
    die("Some message here!!");
  }

And that works pretty good. But as you see I generate a random token for each page containing a form and in some cases this causes a problem if for example I opened another tab in the browser to perform some another action. Consider this scenario:

*

*I opened add.php page to add a new item.

*I filled in all required data, but I didn't submit the form.

*Now I decided to open edit.php page in another tab in the browser to edit an existing item.

*Then I went back to the add.php page that was filled in and tried to submit the data.

At this point I will get an error because value of the token that has been stored in the session when I opened add.php page has been changed and replaced with another token when I open the edit.php page. So how can I fix this problem? Should I generate just one token for each user when he successfully login and then use this token in all pages that he may deal with? Does this approach has any risks or any cons?

A: I scanned your post and don't see a reason why not to use the base codeigniter CSRF protection? It seems you are reinventing the wheel and creating problems that don't exist within its standard implementation.
Not to mention you are violating DRY principles by trying to print your tokens to every form. Any reason why not to keep it simple?
Codeigniter has build in CSRF protection that can be enabled in /application/config/config.php
$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrf_token_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;

A: To solve this problem, you could create a token string with a unique key and store the pairs of keys/tokens in the session (as userdata in CodeIgniter).
Considering this scenario, You'll need these steps:

*

*Creating a unique token key.

*Creating a token string.

*Storing the key/token pair in the session (userdata).

*Creating 2 hidden <input> elements for CSRF key and token.

*Validating the posted key/token by checking the existence of key/token in the session.

Getting to work:
$csrf_key   = "TOKEN_" . mt_rand(0, mt_getrandmax());
$csrf_token = hash("sha512", mt_rand(0, mt_getrandmax()));
// Store the key/token pair in session
$this->session->set_userdata($csrf_key, $csrf_token);

Adding hidden inputs:
<form action="path/to/handler/page" method="post">
    <!-- form input elements -->
    <input type="hidden" name="csrf_key" value="<?php echo $csrf_key; ?>">
    <input type="hidden" name="csrf_token" value="<?php echo $this->session->userdata($csrf_key); ?>">
</form>

Validating the posted key/token:
if (count($_POST)) {
    if (! isset($_POST['csrf_key']) or ! isset($_POST['csrf_token'])) {
        die('No CSRF token found, invalid request.');
    }

    $key   = $this->input->post('csrf_key');
    $token = $this->input->post('csrf_token');

    if ($token !== $this->session->userdata($key)) {
        die('Invalid CSRF token, access denied.');
    }
}


text:
Q: SAPUI5 table - changing font size and font color conditionally (in SAP) - how to do it right? Due to the fact that there are lots of threads on this on SCN and also here where People are trying to find out how to Change font Color and font size conditionally, you will find a solution manipulating the CSS or the DOM via jQuery - thats not the way it is supposed to be.
I want to Show the way how to set this up, Controlling Color and font by the SAP backend!
Easy example, you are showing negative and positive values in an SAPUI5 table - lets say positive values:
You Need to more attributes in your entity, one for design and one for class:

Then you enhance your method in ABAP with the respective values (explained later in Detail which values are available):

and finally in UI5 table Definition a reference:

and there you go, highlighted one single row with a positive meaning (sorry for the black ... it is not meant for the public ;-) all other rows are not bold and not green)

Available Options in SAP:
https://openui5.hana.ondemand.com/#docs/api/symbols/sap.ui.commons.TextViewDesign.html
https://openui5.hana.ondemand.com/#docs/api/symbols/sap.ui.commons.TextViewColor.html

A: There is no official way to do something like this besides creating your own implementation of a sap.ui.table.Column.
Anyways you can add conditional style classes using this little workaround here:
var oColumn = new sap.ui.table.Column({
    label: new sap.ui.commons.Label({
        text: "Last Name"
    }),
    template: new sap.ui.commons.TextView({
        text: {
            path: 'Counter',
            formatter: function(sValue) {
                // in here this refers to your TextView
                // get the cell (depending on your template you might have to add more getParent calls here for nested controls)
                var oCell = this.getParent();

                // remove all possible style classes first because table cells might get reused
                oCell.removeStyleClass("newStyleClass");
                oCell.removeStyleClass("otherStyleClass");

                // add conditional style
                if (whatever) {
                    oCell.addStyleClass("newStyleClass");
                } else {
                    oCell.addStyleClass("otherStyleClass");
                }

                // just statically return the text since we are not interested in changing it
                return sValue;
            }
        }
    })
});

I've just written this down and didn't execute but it should be enough to guide you ;)
To do this 'from the backend' you will just have to provide an additional field in your service, say 'styleClass', which you bind to any property of your template and use a formatter to set the style classes as illustrated above.
BR
Chris


text:
Q: How can I increase each button's size in this python code? What do I have to do if I want to make every button 5 times bigger in the following code?
Is there any specific property which I need to set?
from gi.repository import Gtk

class GridWindow(Gtk.Window):

    def __init__(self):
        Gtk.Window.__init__(self, title="Grid Example")

        grid = Gtk.Grid()
        self.add(grid)

        button1 = Gtk.Button(label="Button 1")
        button2 = Gtk.Button(label="Button 2")
        button3 = Gtk.Button(label="Button 3")
        button4 = Gtk.Button(label="Button 4")
        button5 = Gtk.Button(label="Button 5")
        button6 = Gtk.Button(label="Button 6")

        grid.add(button1)
        grid.attach(button2, 1, 0, 2, 1)
        grid.attach_next_to(button3, button1, Gtk.PositionType.BOTTOM, 1, 2)
        grid.attach_next_to(button4, button3, Gtk.PositionType.RIGHT, 2, 1)
        grid.attach(button5, 1, 2, 1, 1)
        grid.attach_next_to(button6, button5, Gtk.PositionType.RIGHT, 1, 1)

win = GridWindow()
win.connect("delete-event", Gtk.main_quit)
win.show_all()
Gtk.main()

A: width = 5 * button1.get_allocation().width
height = 5 * button1.get_allocation().height

button1.set_size_request(width, height)

http://zetcode.com/gui/pygtk/firststeps/


text:
Q: Custom "View Item" Button I want to create a custom View Item button similar to the Edit Item button, without the use of SharePoint Designer?
Can anyone guide me to achieve this?

A: Note:
in June 2017, Microsoft disabled the use of JavaScript in a Calculated Column
That means given answers may not apply  for newer SharePoint versions
For long explanation and work arounds see:
June 13th 2017 Microsoft blocked handling HTML markup in SharePoint calculated fields - how to get the same functionality back

**Original answer:**

*

*Create a Calculated Column View

*set Datatype=Number (will output String as HTML)

*Add the Formula:
  =""

Onclick it captures the ID value from the TR node
Builts the correct url
Displays a message (every click in a webpage should give an immediate response IMHO)
goes to the url
I am not 100% sure if those IID functions exist in 2010, if not see the examples below for alternative code
More:

*

*Clone/Duplicate item: Set default values in new controls on custom form

*Start a Workflow: Can I add a start workflow link to a column in a list view?
ICC


text:
Q: Scaling the Apache Flink In Kubernetes I have my Flink streaming job up and running in local Kubernetes. The job reads from a Kafka topic, does some (stateless) computation it and writes back to another Kafka topic. The job's checkpoints are saved in S3.
The Flink's command-line tool deploys the job in single pod (replicas), so how do I increase the replicas to increase the operation on data in parallel & throughput of the job?

A: You have (at least) two options:

*

*Manually stop the job triggering a savepoint (access the flink cluster in k8s in any way as described in here) and issue a stop with savepoint command), and then recreate the application cluster k8s resources with an updated jobmanager parallelism count (so the job is launched with the new parallelism), taskmanager replicas count (so there are enough Task Managers/slots for the job parallelism) and adding the --fromSavepoint option in the jobmanager args pointing to the created savepoint.

*Use reactive mode (still in MVP). See documentation. Once configured to be in reactive mode (scheduler-mode: reactive, see example config in docs: flink-reactive-mode-configuration-configmap.yaml) you only need to change the replica count in the flink-taskmanager k8s deployment (taskmanager-job-deployment.yaml file in docs) and the scheduler will automatically create a savepoint, rescale the app/cluster and restart from the checkpoint.


text:
Q: What is the set $\{x\in\Bbb R\mid \forall q\in\Bbb Q: q^x\in\Bbb Q\}$? What is the set $\{x\in\Bbb R\mid \forall q\in\Bbb Q: q^x\in\Bbb Q\}$?
Of course $\Bbb Z$ is a subset of this set.
Are there any other? if not what is the proof? is there a good reference for it?

A: It is known that if $2^c$, $3^c$, and $5^c$ are all rational then $c$ is a nonnegative integer. It follows from the Six Exponentials Theorem, q.v.
On the 1971 Putnam, it was asked to show that if $2^c,3^c,4^c,\dots$ are all integers then $c$ is a nonnegative integer.

A: Expansion of Gerry Myerson/MJD answer.
If $x$ is rational but not integer, then $2^x$ is irrational by unique factorization.  Now suppose $x$ is irrational.
Let's use the "Six Exponentials Theorem", which states:
Let $x_1, x_2, x_3, y_1, y_2$ be complex numbers, assume $x_1, x_2, x_3$ are linearly independent over $\mathbb Q$ and $y_1, y_2$ are linearly independent
over $\mathbb Q$.  Then at least one of $\exp(x_iy_j)$ is transcendental.
Take $x_1 = \log 2, x_2 = \log 3, x_3 = \log 5, y_1 = 1, y_2 = x$.  Then $\log 2, \log 3, \log 5$ are linearly independent by unique factorization.  And $1,x$ are linearly independent since $x$ is irrational.  Conclusion: at least one of
$$
2, 3, 5, 2^x, 3^x, 5^x
$$
is transcendental.  So, in particular, they are not all rational.

A: Note that $-1$ is rational.  If $x$ satisfies the condition, in particular $(-1)^x$ is rational.  Taking that to mean
$e^{i\pi x}$ is rational, and thus real, I conclude that $x$ is an integer.


text: Q: Want to build a embedded link to open pdf in web view I want to build an application that opens pdf in web view. For that i need a embedded link of google docs. The link should be like this https://docs.google.com/viewer?embedded = true&url. But I am not able to make it cam someone tell how can I make it.


text:
Q: How to use appium scrollto function to scroll to an element using its ID I want to scroll to an element by its ID using appium scrollto.
How do I do that? Currently only text can be entered in the scrollto function.

A: I am using some Javascript code to achieve this. Maybe this can also help you. But again each solution is specific to the problem (i.e. App). Now at the same I don't know how you got an upvote for your question as it shows zero research and gives no information.
No mention of Android OS or iOS,
No mention of application type - Hybrid, Native, etc.
No mention of what you have achieved until now with scrollto any snippet etc.

Having said that I am going to share some of the Javascript that I am using in my code. Again this is specific to my app. Maybe you require a more tailored solution for your problem.
public class Scroll extends Driver{

    public static void scrolldown(){
        //Scroll JS
        JavascriptExecutor js = (JavascriptExecutor) Ad ;
        HashMap<String, String> scrollObject = new HashMap<String, String>();
        scrollObject.put("direction", "down");
        js.executeScript("mobile: scroll", scrollObject);
    }

    public static void scrollup(){
        //Scroll JS
        JavascriptExecutor js = (JavascriptExecutor) Ad ;
        HashMap<String, String> scrollObject = new HashMap<String, String>();
        scrollObject.put("direction", "up");
        js.executeScript("mobile: scroll", scrollObject);
    }
}


text:
Q: Flexbox bug in Internet Explorer <= Edge My problem is regarding flexbox layout. Check the demo from modern browsers and Internet Explorer.

Code Snippet:

.features-section {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  width: 100%;
  -webkit-flex-flow: row wrap;
}
.features-section .custom-col-6 {
  padding: 1em;
  margin: 0;
  align-self: center;
  width: 50%;
  box-sizing: border-box;
}
.features-section .not-for-mobile {
  display: block;
}
.features-section .not-for-desktop {
  display: none;
}
.features-section .feature-image {
  height: 490px;
  background-position: center center;
  background-repeat: no-repeat;
  background-size: cover;
}
.features-section .feature-image-1 {
  background-image: url(https://images.unsplash.com/photo-1430806746135-4c9775bfea07?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&s=f98a2e705cc92fdba353e0d973176aff);
}
.features-section .feature-image-2 {
  background-image: url(https://images.unsplash.com/photo-1430806746135-4c9775bfea07?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&s=f98a2e705cc92fdba353e0d973176aff);
}
.features-section .feature-image-3 {
  background-image: url(https://images.unsplash.com/photo-1430806746135-4c9775bfea07?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&s=f98a2e705cc92fdba353e0d973176aff);
}
.features-section .feature-image-4 {
  background-image: url(https://images.unsplash.com/photo-1430806746135-4c9775bfea07?ixlib=rb-0.3.5&q=80&fm=jpg&crop=entropy&cs=tinysrgb&s=f98a2e705cc92fdba353e0d973176aff);
}
.features-section .feature-item .item-header {
  font-size: 0.857em;
  text-transform: uppercase;
  line-height: 2.8em;
  color: black;
}
.features-section .feature-item .item-text {
  color: #333;
  line-height: 2.1em;
}
.features-section .feature-item i {
  font-size: 3em;
}
.features-section .feature-style-1,
.features-section .feature-style-2 {
  text-align: center;
}
.features-section .feature-style-1 p,
.features-section .feature-style-2 p {
  padding: 0 60px;
}
.features-section .feature-style-3 {
  text-align: left;
}
.features-section .feature-style-3 .icon-wrapper {
  padding: 2px 20px 0 45px;
  float: left;
}
.features-section .feature-style-3 .text-wrapper {
  display: inline-block;
  width: 80%;
  padding: 0 35px 0 0;
}
.features-section .feature-style-4 {
  text-align: right;
}
.features-section .feature-style-4 .icon-wrapper {
  padding: 2px 45px 0 20px;
  float: right;
}
.features-section .feature-style-4 .text-wrapper {
  display: inline-block;
  width: 80%;
  padding: 0 0 0 35px;
}

multipurpose template

Would you like to pop in a CD and have a better quality of life, and even self improvement? There are three ways you can use music to accomplish this.

multipurpose template

Would you like to pop in a CD and have a better quality of life, and even self improvement? There are three ways you can use music to accomplish this.

multipurpose template

Would you like to pop in a CD and have a better quality of life, and even self improvement? There are three ways you can use music to accomplish this.

CodePen

So, in IE all flex items are in one row, but I need every item to occupy half of the row.


text:
Q: Unable to get COUNT(*) result from structured SQL statement I've been working on a SQL statement that checks the database to see if feedback has been left for a specific qr_id from a specific uuid within 24 hours. The original code works as intended, but obviously to be more secure I wanted to change the code to a structed SQL statement instead.
$uuid = "DB8962A3-BC7A-481F-9D7E-C1FC7F74E50E";
$qrid = "2147483647";
$query = sprintf("SELECT COUNT(*) FROM `feedback` WHERE uuid = '%s' AND qr_id = '%s' AND created_on > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 DAY))", mysql_real_escape_string($uuid), $qrid);
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$size = $row['COUNT(*)'];
if ($size > 0){
    echo 'Unable to leave feedback as user has left feedback for this employee within 24 hours.';
}else{
    echo 'User has not left feedback for this employee within 24 hours, continue.';
}

The above works perfectly fine, if the count is above 0 then it stops the user posting. Here's my attempt at converting it to a structured SQL statement:
$stmt = $this->conn->prepare("SELECT COUNT(*) FROM `feedback` WHERE uuid = ? AND qr_id = ? AND created_on > UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 1 DAY))");
    $stmt->bind_param('si', $uuid, $qrID);
    $result = $stmt->execute();
    $size = $result['COUNT(*)'];
    $stmt->close();
    if ($size = 0){
        // do post, return true
        return true;
    }else{
        return false;
        // do not post, return false
    }

I have tried printing the result value and it's always 1, and trying to echo the $size variable returns nothing.

A: You need to fetch the result, try this:
$stmt->bind_param('si', $uuid, $qrID);
$stmt->execute();
//here you bind result to variable $size
$stmt->bind_result($size);
$stmt->fetch()
$stmt->close();
if ($size == 0){
    // do post, return true
    return true;
}else{
    return false;
    // do not post, return false
}


text:
Q: ISSN format in c++, trouble with space, bool function, and array I am trying to return a Boolean function asking to enter a ISSN number, if it's the right format for a correct ISSN, it should return true, otherwise false.
Thing is, as you can see, the ISSN has to start with ISSN then 4 digits then - then another 4 digts. But, I'm having trouble dealing with the space between ISSN and the numbers**. Also, I was considering using istringstream to have the full ISSN back like : **ISSN 0395-2037****.
Here's my code:
#include<iostream>
#include<ctype.h>
#include<string>
#include<string.h>
#include <sstream>
using namespace std;

int main()
{
    string issn;
    string space;
    string arr[10];
    istringstream is("ISSN 0395-2037");
    is >> issn;
    is >> space;
    for (int i = 0; i < space.length(); i++)
    {
        arr[i] = space[i];
    }
    if (issn != "ISSN"
        and arr[4] != "-")
    {
        return false;
    }
    return 0;
}

Should I stock it all in an array to make it easier to manipulate?
Thanks!


text:
Q: Which is fastest way to get 10 lines randomly inside a file with 10.000 lines? I have a file with ~ 10.000 lines inside. I want every time user access my website, it auto pick 10 lines randomly among them.
Code I currently used:
$filelog = 'items.txt';
$random_lines = (file_exists($filelog))? file($filelog) : array();
$random_count = count($random_lines);
$random_file_html = '';
if ($random_count > 10)
{
    $random_file_html = '

';
    for ($i = 0; $i < 10; $i++)
    {
        $random_number = rand(0, $random_count - 1); // Duplicate are accepted
        $random_file_html .= '
'.$random_lines[$random_number]."
\r\n";
    }
    $random_file_html .= '

';
}

When I have < 1000 lines, every things is ok. But now, with 1000 lines. It make my website slow dow significantly.
That I'm thinking to other methods, like:
Divide file to 50 files, select randomly them, then select 10 lines randoms inside the selected file.
-- or --
I knew total lines (items). Make 10 numbers randomly, then read file use
$file = new SplFileObject('items.txt');
$file->seek($ranđom_number);
echo $file->current();

(My server does not support any type of SQL)
Maybe you have other methods that best suit for me. What is best method for my problem? Thank you very much!

A: The fastest way would be apparently not to pick 10 lines randomly out of a file with ~ 10.000 lines inside on every user's request.
It's impossible to answer more as we know no details of this "XY problem".

A: If it is possible to adjust the contents of the file then simply pad each of the lines so they have a common length. Then you can access the lines in the file using random access.
  $lineLength = 50; // this is the assumed length of each line

  $total = filesize($filename);
  $numLines = $total/$lineLength;

  // get ten random numbers
  $fp = fopen($filename, "r");
  for ($x = 0; $x < 10; $x++){
       fseek($fp, (rand(1, $numLines)-1)*$lineLength, SEEK_SET);
       echo fgets($fp, 50);
  }
  fclose($fp);

A: try:
$lines = file('YOUR_TXT_FILE.txt');
$rand  = array_rand($lines);

echo $lines[$rand];

for 10 of them just put it in a loop:
$lines = file('YOUR_TXT_FILE.txt');
for ($i = 0; $i < 10; $i++) {
   $rand = array_rand($lines);
   echo $lines[$rand];
}

NOTE: ** the above code does not guarantee that **2 same lines wont be picked. In order to guarantee uniqueness you need to add extra while loop and an array that holds all randomly generated indexes, so next time it generates it and it already exists in an array, generate another one until its not in the array.
The above solution might not be fastest but might fulfill your needs. Since your server does not support any type of SQL, maybe switch to a different server? Because I am wondering how you are storing User Data? Are those stored in files also?


text:
Q: How to access html function from Script# code? In Script# how do I access a function defined in the html on the page?
On the html page is this pre-existing function:

I load up the generated script from scriptsharp and need access to the "Global" makeStuffHappen function in that generated script. Basically, from Scriptsharp I need to be able to call the function
makeStuffHappen("#usefulplace");
How can I call makeStuffHappen from inside the scriptsharp?

A: I figured out how to do it. I created a scriptsharp class file and did IgnoreNamespace, Imported, and ScriptAlias all three to get it to map to the function in the html, as follows:
using System.Runtime.CompilerServices;

namespace TestNamespace
{
    ///
    ///
    ///
    [IgnoreNamespace]
    [Imported]
    public static class ImportedPageFunctions
    {
        ///
        ///
        ///
        /// <param name="selector"></param>
        [ScriptAlias("makeStuffHappen")]
        public static void makeStuffHappen(string selector)
        {

        }
    }
}


text:
Q: Error thrown while using datamapper to map date in Mule Below is the portion of the mapping in data mapper
dateTimeFormatter = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
output.Date_of_Rate_Float__c = (isnull(input.Date_of_Rate_Float) ? null : dateTimeFormatter.format(input.Date_of_Rate_Float));
output.Loan_Create_Date__c = (isnull(input.loan_create_date) ? null : dateTimeFormatter.format(input.loan_create_date));
output.Estimated_Closing_Date__c = (isnull(input.estimated_closing_date) ? null : dateTimeFormatter.format(input.estimated_closing_date));
this throws the below exception
1. DateConverter does not support default String to 'Date' conversion. (org.apache.commons.beanutils.ConversionException)
  org.apache.commons.beanutils.converters.DateTimeConverter:468 (null)

Root Exception stack trace:
org.apache.commons.beanutils.ConversionException: DateConverter does not support default String to 'Date' conversion.
    at org.apache.commons.beanutils.converters.DateTimeConverter.toDate(DateTimeConverter.java:468)
    at org.apache.commons.beanutils.converters.DateTimeConverter.convertToType(DateTimeConverter.java:343)
    at org.apache.commons.beanutils.converters.AbstractConverter.convert(AbstractConverter.java:156)
    at org.apache.commons.beanutils.ConvertUtilsBean.convert(ConvertUtilsBean.java:544)
    at com.mulesoft.datamapper.transform.converter.ScalarValueConversion.convert(ScalarValueConversion.java:126)
    at com.mulesoft.datamapper.transform.DataRecordContext.put(DataRecordContext.java:87)
    at com.mulesoft.datamapper.transform.DataRecordContext.put(DataRecordContext.java:24)
    at org.mvel2.optimizers.impl.refl.ReflectiveAccessorOptimizer.optimizeSetAccessor(ReflectiveAccessorOptimizer.java:308)
    at org.mvel2.compiler.CompiledAccExpression.setValue(CompiledAccExpression.java:54)
    at org.mvel2.ast.DeepAssignmentNode.getReducedValueAccelerated(DeepAssignmentNode.java:92)
    at org.mvel2.MVELRuntime.execute(MVELRuntime.java:85)
    at org.mvel2.compiler.CompiledExpression.getDirectValue(CompiledExpression.java:123)
    at org.mvel2.compiler.CompiledExpression.getValue(CompiledExpression.java:119)
    at org.mvel2.compiler.CompiledExpression.getValue(CompiledExpression.java:113)
    at org.mvel2.MVEL.executeExpression(MVEL.java:942)
    at org.mule.el.mvel.MVELExpressionExecutor.execute(MVELExpressionExecutor.java:50)
    at com.mulesoft.datamapper.transform.DataMapperExpressionLanguage.evaluate(DataMapperExpressionLanguage.java:106)
    at com.mulesoft.datamapper.transform.MelRecordTransform.transform(MelRecordTransform.java:56)
    at org.jetel.component.Reformat.execute(Reformat.java:273)
    at org.jetel.graph.Node.run(Node.java:465)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:724)

********************************************************************************

I'am unable to find as what is causing this exception, I would like to seek help in resolving this issue.
Thank you in advance

A: It looks like a null value is being passed to the format method.  To see how you can make it "null safe" you can look at the example at Format a Date, allowing null


text:
Q: flatting and sorting nested arrays In javascript nodejs I have an array that outputs multiple arrays  if some of the codes match they output in the same array  how do i  separate them  for example this is my array
[
[ [ '0011', 6, 96, '2021-08-16' ], [ '0011', 2, 4, '2021-08-17' ] ],
  [ [ '0032', 20, 26, '2021-08-16' ] ],
  [ [ '0098', 6, 246, '2021-08-16' ], [ '0098', 0, 0, '2021-08-17' ] ],
  [ [ '0093', 2, 30, '2021-08-16' ] ],
  [ [ '0051', 32, 229, '2021-08-16' ] ],
  [ [ '0053', 27, 63, '2021-08-16' ], [ '0053', 2, 38, '2021-08-17' ] ],
  [ [ '0022', 4, 2, '2021-08-16' ], [ '0022', 6, 12, '2021-08-17' ] ],
  [ [ '0067', 2, 144, '2021-08-16' ] ],
  [ [ '0166', 4, 102, '2021-08-16' ] ],
  [ [ '0015', 4, 96, '2021-08-16' ] ],
]

how do I get the values with two or more values in their array  and put it in so each  there are seperate within the array if that makes sense
so ideally I would like this
[
[ [ '0011', 6, 96, '2021-08-16' ]],
[[ '0011', 2, 4, '2021-08-17' ] ],
  [ [ '0032', 20, 26, '2021-08-16' ] ],
  [ [ '0098', 6, 246, '2021-08-16' ],
[ [ '0098', 0, 0, '2021-08-17' ] ],
  [ [ '0093', 2, 30, '2021-08-16' ] ],
  [ [ '0051', 32, 229, '2021-08-16' ] ],
  [ [ '0053', 27, 63, '2021-08-16' ]],
  [ [ '0053', 2, 38, '2021-08-17' ] ],
  [ [ '0022', 4, 2, '2021-08-16' ]],
  [ [ '0022', 6, 12, '2021-08-17' ] ],
  [ [ '0067', 2, 144, '2021-08-16' ] ],
  [ [ '0166', 4, 102, '2021-08-16' ] ],
  [ [ '0015', 4, 96, '2021-08-16' ] ],
]

or even better would be
[
[  '0011', 6, 96, '2021-08-16' ],
[ '0011', 2, 4, '2021-08-17' ],
  [  '0032', 20, 26, '2021-08-16'  ],
  [  '0098', 6, 246, '2021-08-16' ],
[  '0098', 0, 0, '2021-08-17' ],
  [  '0093', 2, 30, '2021-08-16'  ],
  [ '0051', 32, 229, '2021-08-16'  ],
  [ '0053', 27, 63, '2021-08-16' ],
  [ '0053', 2, 38, '2021-08-17' ],
  [ '0022', 4, 2, '2021-08-16' ],
  [  '0022', 6, 12, '2021-08-17'  ],
  [  '0067', 2, 144, '2021-08-16' ],
  [ '0166', 4, 102, '2021-08-16'  ],
  [ '0015', 4, 96, '2021-08-16'  ],
]

I tried to use flatten but adds the arrays in the same array together which isnt my desired result

A: hy try this:
let myarray = [
 [ [ '0011', 6, 96, '2021-08-16' ], [ '0011', 2, 4, '2021-08-17' ] ],
 [ [ '0032', 20, 26, '2021-08-16' ] ],
 [ [ '0098', 6, 246, '2021-08-16' ], [ '0098', 0, 0, '2021-08-17' ] ],
 [ [ '0093', 2, 30, '2021-08-16' ] ],
 [ [ '0051', 32, 229, '2021-08-16' ] ],
 [ [ '0053', 27, 63, '2021-08-16' ], [ '0053', 2, 38, '2021-08-17' ] ],
 [ [ '0022', 4, 2, '2021-08-16' ], [ '0022', 6, 12, '2021-08-17' ] ],
 [ [ '0067', 2, 144, '2021-08-16' ] ],
 [ [ '0166', 4, 102, '2021-08-16' ] ],
 [ [ '0015', 4, 96, '2021-08-16' ] ],
 ];

  let cleanArry = [];

  myarray.forEach(item=>{
  item.forEach(nItem=>{
    cleanArry.push(nItem)
  })
  })

  //this is the array that you want
  console.log(cleanArry);

A: I don't understand why don't you use flat()?
It is the same output as the accepted answer.
I post this answer just in case you miss it.

const array = [
  [
    ["0011", 6, 96, "2021-08-16"],
    ["0011", 2, 4, "2021-08-17"],
  ],
  [["0032", 20, 26, "2021-08-16"]],
  [
    ["0098", 6, 246, "2021-08-16"],
    ["0098", 0, 0, "2021-08-17"],
  ],
  [["0093", 2, 30, "2021-08-16"]],
  [["0051", 32, 229, "2021-08-16"]],
  [
    ["0053", 27, 63, "2021-08-16"],
    ["0053", 2, 38, "2021-08-17"],
  ],
  [
    ["0022", 4, 2, "2021-08-16"],
    ["0022", 6, 12, "2021-08-17"],
  ],
  [["0067", 2, 144, "2021-08-16"]],
  [["0166", 4, 102, "2021-08-16"]],
  [["0015", 4, 96, "2021-08-16"]],
];

const output = array.flat();

console.log(output);

same output as the accepted answer.


text:
Q: Website cannot connect to database after web publish I am getting the following error:
Server Error in '/' Application.

The system cannot find the file specified
  Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

 Exception Details: System.ComponentModel.Win32Exception: The system cannot find the file specified

Source Error:

 An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[Win32Exception (0x80004005): The system cannot find the file specified]

[SqlException (0x80131904): A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)]
   System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +6564850
   System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +815
   System.Data.SqlClient.TdsParser.Connect(ServerInfo serverInfo, SqlInternalConnectionTds connHandler, Boolean ignoreSniOpenTimeout, Int64 timerExpire, Boolean encrypt, Boolean trustServerCert, Boolean integratedSecurity, Boolean withFailover) +6590016
   System.Data.SqlClient.SqlInternalConnectionTds.AttemptOneLogin(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean ignoreSniOpenTimeout, TimeoutTimer timeout, Boolean withFailover) +219
   System.Data.SqlClient.SqlInternalConnectionTds.LoginNoFailover(ServerInfo serverInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString connectionOptions, SqlCredential credential, TimeoutTimer timeout) +6592544
   System.Data.SqlClient.SqlInternalConnectionTds.OpenLoginEnlist(TimeoutTimer timeout, SqlConnectionString connectionOptions, SqlCredential credential, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance) +6592983
   System.Data.SqlClient.SqlInternalConnectionTds..ctor(DbConnectionPoolIdentity identity, SqlConnectionString connectionOptions, SqlCredential credential, Object providerInfo, String newPassword, SecureString newSecurePassword, Boolean redirectedUserInstance, SqlConnectionString userConnectionOptions, SessionData reconnectSessionData) +878
   System.Data.SqlClient.SqlConnectionFactory.CreateConnection(DbConnectionOptions options, DbConnectionPoolKey poolKey, Object poolGroupProviderInfo, DbConnectionPool pool, DbConnection owningConnection, DbConnectionOptions userOptions) +1162
   System.Data.ProviderBase.DbConnectionFactory.CreatePooledConnection(DbConnectionPool pool, DbConnection owningObject, DbConnectionOptions options, DbConnectionPoolKey poolKey, DbConnectionOptions userOptions) +72
   System.Data.ProviderBase.DbConnectionPool.CreateObject(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +6596173
   System.Data.ProviderBase.DbConnectionPool.UserCreateRequest(DbConnection owningObject, DbConnectionOptions userOptions, DbConnectionInternal oldConnection) +103
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, UInt32 waitForMultipleObjectsTimeout, Boolean allowCreate, Boolean onlyOneCheckConnection, DbConnectionOptions userOptions, DbConnectionInternal& connection) +2102
   System.Data.ProviderBase.DbConnectionPool.TryGetConnection(DbConnection owningObject, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal& connection) +116
   System.Data.ProviderBase.DbConnectionFactory.TryGetConnection(DbConnection owningConnection, TaskCompletionSource`1 retry, DbConnectionOptions userOptions, DbConnectionInternal oldConnection, DbConnectionInternal& connection) +1079
   System.Data.ProviderBase.DbConnectionInternal.TryOpenConnectionInternal(DbConnection outerConnection, DbConnectionFactory connectionFactory, TaskCompletionSource`1 retry, DbConnectionOptions userOptions) +6600667
   System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry) +233
   System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry) +278
   System.Data.SqlClient.SqlConnection.Open() +239
   System.Data.Entity.SqlServer.<>c__DisplayClass1.<Execute>b__0() +15
   System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +263
   System.Data.Entity.Core.EntityClient.EntityConnection.Open() +522

[EntityException: The underlying provider failed on Open.]
   System.Data.Entity.Core.EntityClient.EntityConnection.Open() +722
   System.Data.Entity.Core.Objects.ObjectContext.EnsureConnection() +154
   System.Data.Entity.Core.Objects.ObjectContext.ExecuteInTransaction(Func`1 func, IDbExecutionStrategy executionStrategy, Boolean startLocalTransaction, Boolean releaseConnectionOnSuccess) +61
   System.Data.Entity.Core.Objects.<>c__DisplayClassb.<GetResults>b__9() +162
   System.Data.Entity.SqlServer.DefaultSqlExecutionStrategy.Execute(Func`1 operation) +263
   System.Data.Entity.Core.Objects.ObjectQuery`1.GetResults(Nullable`1 forMergeOption) +262
   System.Data.Entity.Core.Objects.ObjectQuery`1.<System.Collections.Generic.IEnumerable<T>.GetEnumerator>b__0() +49
   System.Lazy`1.CreateValue() +14308960
   System.Lazy`1.LazyInitValue() +524
   System.Data.Entity.Internal.LazyEnumerator`1.MoveNext() +88
   System.Linq.Enumerable.Single(IEnumerable`1 source) +188
   System.Linq.Queryable.Count(IQueryable`1 source) +298
   PDBScaffold.Controllers.HomeController.Index() in c:\PDBLite\Proofs of Concept\PDBScaffold\Controllers\HomeController.cs:33
   lambda_method(Closure , ControllerBase , Object[] ) +79
   System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters) +217
   System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters) +39
   System.Web.Mvc.Async.AsyncControllerActionInvoker.<BeginInvokeSynchronousActionMethod>b__36(IAsyncResult asyncResult, ActionInvocation innerInvokeState) +12
   System.Web.Mvc.Async.WrappedAsyncResult`2.CallEndDelegate(IAsyncResult asyncResult) +139
   System.Web.Mvc.Async.AsyncInvocationWithFilters.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3c() +112
   System.Web.Mvc.Async.<>c__DisplayClass45.<InvokeActionMethodFilterAsynchronouslyRecursive>b__3e() +452
   System.Web.Mvc.Async.<>c__DisplayClass30.<BeginInvokeActionMethodWithFilters>b__2f(IAsyncResult asyncResult) +15
   System.Web.Mvc.Async.<>c__DisplayClass28.<BeginInvokeAction>b__19() +32
   System.Web.Mvc.Async.<>c__DisplayClass1e.<BeginInvokeAction>b__1b(IAsyncResult asyncResult) +231
   System.Web.Mvc.Controller.<BeginExecuteCore>b__1d(IAsyncResult asyncResult, ExecuteCoreState innerState) +29
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +111
   System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult) +53
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +19
   System.Web.Mvc.MvcHandler.<BeginProcessRequest>b__4(IAsyncResult asyncResult, ProcessRequestState innerState) +51
   System.Web.Mvc.Async.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult) +111
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +606
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +288

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.34009

I am not sure what this means as the webconfig is present and I verified the connection strings are correct.  I even pointed my dev environment at the DB to validate it is right.  I am using the VS web publish feature.  It looks like all files are installed to the right directory and in IIS the site is up.

A: Your error states it is using named pipes, named pipes is used when doing IPC (Inter Process Communication), set your SQL SERVER up for TCP/IP and make sure you have a connection string that works with that configuration.

A: You should check the DbContext and change DefaultConnection from name of conection you use.
public class UsersContext : DbContext
 {
    public UsersContext()
        : base("MyDBContext")
    {
    }
 }


text:
Q: New Yorker's Possessive of Title in Quote Marks The New Yorker does possessive of titles in quotes like this (even if it's a movie title, they use quotes):
"Saturday Night Live" 's cast
"Jeopardy!" 's host Alex Trebek
"What's Going On?" 's lyrics
They use a space after the ending quote mark and then follow it with an apostrophe plus "s," as shown in the three examples above.
My question is, if we have a title that already ends in "s" inside the quotes, would we still, per New Yorker style, add the apostrophe plus "s" after "The Sopranos" below (as shown)?
"The Sopranos" 's David Chase...

A: Your guess is entirely correct.
Google finds the quote

several of "The Sopranos" 's directors

here on "The New Yorker" 's website.

A: As @Mazura commented,

Having ceased using underling for titles, the rest of the world now uses italics.

You need to note that just because The New Yorker used a certain type of style doesn't necessarily mean it applies to other publishers or authors.
Other Stack Exchange sites related with moves and TV shows, Science Fiction & Fantasy SE and Movies & TV SE use italic for name of works as indicated in the question below:
Are there official style rules for names of works?
Regarding your question, the answer is you can follow your style guide or manual. There could be three popular choices:

The Sopranos' David Chase...
The Sopranos' David Chase...
"The Sopranos" 's David Chase...


text:
Q: Have IIS notify ASP.NET when last chunk of file download sent I'm currently using this code to know if the final chunk of a file download was sent or not, and it works, but not a good design, so looking for better options:
    Response.ClearHeaders()
    Response.ClearContent()
    Response.Clear()
    Response.ContentType = "application/octet-stream"
    Response.AddHeader("Content-Disposition", "attachment;filename=""WebInstall.exe""")

    Response.BufferOutput = False

    Response.AddHeader("Content-Length", bytes.Length())

    Dim bytesSent As Integer = 0

    Do While Response.IsClientConnected And (bytesSent < bytes.Length())

        Dim len As Integer
        Dim bytesLeft As Integer = bytes.Length() - bytesSent
        If bytesLeft > 80 * 1024 Then
            len = 80 * 1024
        Else
            len = bytesLeft
        End If

        Response.OutputStream.Write(bytes, bytesSent, len)
        Response.OutputStream.Flush()

        bytesSent += len

    Loop

    If Response.IsClientConnected Then
        AddToWebLog("Download completed")
        NotifyAdProvider()
    Else
        AddToWebLog("Disconnected before download completed")
    End If

    Response.End()

The problem with the code above is that my ASP.NET code can't return to IIS until the last chunk of download is written.  Those who work with ASP.NET a lot know why this is a bad design -- it ties up one of the few available worker threads, among other reasons.
I need to know this info for logging, and also to pay people that sent me the visitor, so it is pretty important (15% of visitors don't actually download, probably due to warnings they get from browsers, anti-virus, etc, etc -- so I don't want to pay an extra 15%, and my ad providers are fine with that).
IIS has this info, because the IIS logs have a "64" for the status code if the connection was closed before complete.  So looking for a way to either have IIS call me again when the request is "done" or some other robust methods you guys might have used, maybe an API to access the IIS log or something (reading the file itself probably will not work, since it is cached and doesn't get written to right away).  I have seen some asynchronous methods for ASP.NET pages that need to do "long running tasks" but they seem very complex so I'm saving that as a last resort.
I'm using ASP.NET 3.5 and IIS 6.

A: The more I read about pageasyntask, it actually doesn't look too bad. I think using BeginWrite will be the way to go.


text:
Q: How to use secrets.yml in ruby on rails 4 to store a password in database.yml I have a ruby on rails 4 project and my config/secrets.yml looks like this:
development:
  secret_key_base: verylongnumber
  postgres: 'mypassword'

My config/database.yml
default: &default
  adapter: postgresql
  encoding: unicode
  # For details on connection pooling, see rails configuration guide
  # http://guides.rubyonrails.org/configuring.html#database-pooling
  pool: 5
  host: localhost
  username: myusername
  password: 'mypassword' # <-- Problem here

What do I need to type in password in my config/database.yml, to get the password from secrets.yml?
I tried:
password: <%= ENV['postgres'] %>
password: <%= ENV["postgres"] %>
password: <%= ENV[postgres] %>
password: ENV['postgres']
password: ENV["postgres"]
password: ENV[postgres]

But neither of these solutions worked. Where did I go wrong? Thanks in advance!

A: You need to use <%= Rails.application.secrets[:your_key] %> to access the value of secrets.yml.
The below should work
<%= Rails.application.secrets[:postgres] %>
I strongly recommend you to have a look at this blog
https://launchschool.com/blog/managing-environment-configuration-variables-in-rails


text:
Q: tensorflow...whl is not a supported wheel on this platform although PEP425 tags seem correct So I am getting "not a supported wheel on this platform" message even though I have installed earlier versions of these wheels from the same repository. Dump:
nvidia@tegra-ubuntu:~/Downloads$ sudo -H pip install tensorflow-1.8.0-cp27-cp27mu-linux_aarch64.whl
tensorflow-1.8.0-cp27-cp27mu-linux_aarch64.whl is not a supported wheel on this platform.

Digging a little deeper I dumped the PEP supported tags.
nvidia@tegra-ubuntu:~/Downloads$ python -c "from pip import pep425tags;print(pep425tags.supported_tags)"
[('cp27', 'cp27mu', 'linux_aarch64'), ('cp27', 'none', 'linux_aarch64'), ('py2', 'none', 'linux_aarch64'), ('cp27', 'none', 'any'), ('cp2', 'none', 'any'), ('py27', 'none', 'any'), ('py2', 'none', 'any'), ('py26', 'none', 'any'), ('py25', 'none', 'any'), ('py24', 'none', 'any'), ('py23', 'none', 'any'), ('py22', 'none', 'any'), ('py21', 'none', 'any'), ('py20', 'none', 'any')]

The wheel file name seems to match the very first tag (PEP 425 standard), so as far as I can tell it should install it. Maybe the definitive tags are stored internally and are different? But I could not find a utility to dump them from a wheel, and I also get the same error message when I try on the old 1.6 wheel that I successfully installed a few months back.
I am thinking something broke when I upgraded my pip to version 10 yesterday (duh... but that pesky message kept coming up), but then the dumped supported tags should have changed then too.
I don't really want to flatten this machine which would surely fix this. Anyone have some ideas how I can get pip to install this wheel?
More information on how pip finds the tags (does it really just look at the file name?) would help as well. I tried messing with the tags in the name and that did not change a thing.
Update:
I am running Linux4Tegra on a Nvidia Jetson TX2 - Jetpack 3.2 - it seems L4T is very Ubuntu-like, I am guessing it is kind of based on that.
Here is the uname output:
nvidia@tegra-ubuntu:~/Downloads$ uname -a
Linux tegra-ubuntu 4.4.38-tegra #1 SMP PREEMPT Fri Dec 1 06:08:28 PST 2017 aarch64 aarch64 aarch64 GNU/Linux

A: Following a suggestion I received here, I reinstalled pip from bootstrap.pypa.io which is more authoritative (I think) than whatever apt-get finds and then it worked fine. Too bad in a way, would have liked to know what was broken. But at least I can on with TensorFlowing...
This is what worked:
$ curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
$ sudo python get.pip.py

Docs here: https://pip.pypa.io/en/stable/installing/


text:
Q: Mail attachment not work android I tried the following code for attaching images to email. Images may be captured or selected from gallery.
Intent i = new Intent(Intent.ACTION_SEND_MULTIPLE);
i.setType("image/*");
i.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
i.putExtra(Intent.EXTRA_EMAIL, new String[]{"abc@xyz.com"});
i.putExtra(Intent.EXTRA_CC, new String[]{"ppp@qqq.com"});
i.putExtra(Intent.EXTRA_TEXT,Html.fromHtml(email_body));
i.putExtra(Intent.EXTRA_SUBJECT,"Vehicle Details");
i.putParcelableArrayListExtra(Intent.EXTRA_STREAM, Vehicle_images.uris);
startActivity(Intent.createChooser(i,"Share"));

Here abc@xyz.com and ppp@qqq.com are dummy email ids and Vehicle_images.uris is a array list of uris.
The problem is that i cant to attach images from a Minno tablet, but this works on other devices. Minno tablet runs on Android 4.1 (Jelly Bean). Is this a known issue?

A: Try this it works for me
 Uri uri = Uri.parse("file:///sdcard/"+"rec1.jpg");
 i.putExtra(Intent.EXTRA_STREAM, uri);