text:
Q: What does @() mean in Objective-C? For example,
CABasicAnimation *rotate = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
[rotate setToValue:@(M_PI)];
[rotate setDuration:0.1f];
[[aView layer] addAnimation:rotate forKey:@"myRotationAnimation"];

where M_PI is defined as a macro in math.h,
#define M_PI  3.14159265358979323846264338327950288   /* pi */

A: NeXT and Apple Obj-C runtimes have long included a short-form way to create new strings, using the literal syntax @"a new string". Using this format saves the programmer from having to use the longer initWithString or similar methods when doing certain operations.
When using Apple LLVM compiler 4.0 or later, arrays, dictionaries, and numbers (NSArray, NSDictionary, NSNumber classes) can also be created using literal syntax instead of methods. Literal syntax uses the @ symbol combined with [], {}, (), to create the classes mentioned above, respectively.
So, basically it's not only for id or NSNumber object!
thanks to wiki.

A: It's Shorthand writing
In Objective-C, any character, numeric or boolean literal prefixed with the '@' character will evaluate to a pointer to an NSNumber object (In this case), initialized with that value. C's type suffixes may be used to control the size of numeric literals.
'@' is used a lot in the objective-C world. It is mostly used to avoid taking english words and making them reserved (for example, you can't have a variable called float in C/Objective-C because this is a reserved word).
Use this link To have detailed knowledge of '@' symbol.
In Modern Objective C, '@' symbol is used extensively.
What You can do with it:

*

*calculate an expression: @(<Expression>)

*wrap any value like int,bool,float,char in same way

Reasons to use:

*

*Easy to write, Less code required

*Less chances of mistakes. Compare [NSNumber numberWithInt:3] with @3.

*Get rid of typecasting issues in simple cases.

A: It's a pointer to an NSNumber object. It's called a boxed literal, because the mental picture is of putting a primitive value of expression inside into a "box", that is, an object.
See official documentation if in doubt. Note that pointer can be to a "real" NSNumber object or it can (theoretically, don't know whether this will work in practice) be a tagged pointer (see, e.g., my question).
Note that you can also do things like @"string" and @5, which will create constants in compile time. But you need parentheses to use something which is not a literal, e.g. @(2 + 3). Parentheses form can be used for any expression, even those that compiler cannot compute at compile-time (although if it can, it will just put an expression result into code).

A: It represent id Object
that you can use any expression in it or return any object.
Syntax :     @(<#expression#>) it will return id object.
So in your case it will returning NSNumber object to setToValue method.


text:
Q: How to convert XML array format to readable format I am getting data from XML file into an array and I want to show it in a readable format for the user so he can understand the result i will show to them . This is what I am getting from my XML file in array format
SimpleXMLElement Object
  (
  [@attributes] => Array
  (
  [ID] => xmlReport
  )

  [root] => SimpleXMLElement Object
  (
  [record] => Array
  (
  [0] => SimpleXMLElement Object
  (
  [@attributes] => Array
  (
  [no] => 1
  )

  [sol_id] => 0413
  [acctNum] => 041305500446
  [tran_date] => 22-DEC-2016
  [tran_particular] => B/F
  [tran_rmks] => -
  [instrmnt_num] => -
  [part_tran_type] => -
  [dr_tran_amt] => -
  [cr_tran_amt] => -
  [bal_amt] => 15212.75
  [ini_sol_desc] => -
  )

  [1] => SimpleXMLElement Object
  (
  [@attributes] => Array
  (
  [no] => 2
  )

  [sol_id] => 0413
  [acctNum] => 041305500446
  [tran_date] => 23-Dec-2016
  [tran_particular] => AKC MOTORS /009557/HDFC
  [tran_rmks] => SMS FACTORY
  [instrmnt_num] => -
  [part_tran_type] => C
  [dr_tran_amt] => 0.00
  [cr_tran_amt] => 8000.00
  [bal_amt] => 23212.75
  [ini_sol_desc] => RPC - LUDHIANA
  )

  [2] => SimpleXMLElement Object
  (
  [@attributes] => Array
  (
  [no] => 3
  )

  [sol_id] => 0413
  [acctNum] => 041305500446
  [tran_date] => 26-Dec-2016
  [tran_particular] => TRFR FROM*MAGNIFIQUE GROUP
  [tran_rmks] => -
  [instrmnt_num] => -
  [part_tran_type] => C
  [dr_tran_amt] => 0.00
  [cr_tran_amt] => 20000.00
  [bal_amt] => 43212.75
  [ini_sol_desc] => MODEL TOWN LUDHIANA
  )

  [3] => SimpleXMLElement Object
  (
  [@attributes] => Array
  (
  [no] => 4
  )

  [sol_id] => 0413
  [acctNum] => 041305500446
  [tran_date] => 28-Dec-2016
  [tran_particular] => BHARTI AIRTEL LTD
  [tran_rmks] => The zone serial is [ 15].
  [instrmnt_num] => 44936
  [part_tran_type] => D
  [dr_tran_amt] => 3663.00
  [cr_tran_amt] => 0.00
  [bal_amt] => 39549.75
  [ini_sol_desc] => RPC - LUDHIANA
  )

  )

  )

  )

and the result i want
 sol_id : 0413
  acctNum : 041305500446

and so on

redpajama_set_name: RedPajamaStackExchange


text:
Q: Зачем нужны разные типы ссылок в Java? Углубляю познания о джаве. Наткнулся на статью о типах ссылок. Понял, что существуют 4 типа ссылок:

*

*Strong reference

*Weak Reference

*Soft Reference

*Phantom Reference

Незнаю, правильно ли я понял, поэтому прошу подправить.
1 Тип сильная ссылка (Strong reference)
Object object = new Object();//создал обьект
object = null;//теперь может быть собран сборщиком мусора

2 Тип слабая ссылка (Weak Reference)
// какой-то объект
Object object= new Object ();

// слабая ссылка на него
WeakReference<Object > weakStudent = new WeakReference<Object >(object);

// теперь объект Object  может быть собран сборщиком мусора
object= null;

3 Тип мягкая ссылка (Soft Reference)
// какой-то объект
Object object= new Object ();

// слабая ссылка на него
SoftReference<Object > softStudent = new SoftReference<Object >(object)

// теперь объект Student может быть собран сборщиком мусора
// но это случится только в случае сильной необходимости JVM в памяти
object= null;

4 Тип фантомная ссылка (ничего не понял про него)

A: Более-менее рассказано в документации к пакету java.lang.ref:

Soft references are for implementing memory-sensitive caches, weak references are for implementing canonicalizing mappings that do not prevent their keys (or values) from being reclaimed, and phantom references are for scheduling post-mortem cleanup actions. Post-mortem cleanup actions can be registered and managed by a Cleaner.

Подробнее и по-русски, в порядке убывания жёсткости:

*

*Сильные, они же обычные, нужны для указания на объекты, которые должны обязательно оставаться в памяти всё то время, что эти ссылки на него существуют. Если не складывается, получите OutOfMemoryError.

*Мягкие ссылки полезны для кэшей, чувствительных к доступному объёму оперативной памяти. Объекты по ним могут зачиститься, но только в случае необходимости. Например, если нужно насоздавать ещё объектов с сильными ссылками, а уже негде, лучше освободить кэш и замедлить работу, чем уронить процесс напрочь.

*Слабые ссылки полезны для сопоставления объектов чему-нибудь без удерживания их от зачистки когда они больше не нужны (а-ля Map<Ключ, WeakRef<Значение>>). На возможность зачистки они не влияют вообще никак, слабые ссылки будут очищены при очередном запуске сборщика.

*Фантомные ссылки возникают, когда объект уже признан мусором, финализирован и находится в процессе зачистки, о чём можно узнать с помощью класса Cleaner и выполнить в это время какие-то собственные действия.

Плюс общее правило: политика зачистки для некоего объекта и очистки ссылок на него определяется самыми жёсткими из всех ссылок, что на него указывают.

Глоссарий не вполне очевидных переводов:

*

*зачистить, зачистка — reclaim, reclamation

*очистить — clear


text:
Q: R data.table: how to use R variables that contain column names? I've read the data.table documentation several times but I still can't wrap my head around how to do some operations; more generally I still haven't understood the underlying "philosophy" on how to work with variable names. Consider this example problem:
I have a data table with variables 'a', 'b', 'c', 'd':
> dt <- data.table(a=c(1,1,2), b=1:3, c=11:13, d=21:23)
> dt
   a b  c  d
1: 1 1 11 21
2: 1 2 12 22
3: 2 3 13 23

Suppose my script interactively asks the user to input a column name and corresponding value that should be used to select rows. These two variables are stored in rowselectname and rowselectvalue:
> rowselectname
[1] "a"
> rowselectvalue
[1] 1

The script also interactively asks the user to select some row names of interest; their names are stored in colselectnames:
> colselectnames
[1] "b" "d"

Now I want to create a new data table from dt, with the rows for which rowselectname has the value rowselectvalue, and with the columns given by colselectnames. The only way I finally managed to do this is as follows:
> newdt <- dt[get(rowselectname)==rowselectvalue, ..colselectnames]
> newdt
   b  d
1: 1 21
2: 2 22

What I don't understand is why I have to use get() for the first selection and .. for the second. Why not get() for both (it doesn't work)? Or why not .. for both (doesn't work either)? This seems inconsistent to me, but maybe there's another way of doing this with a more consistent syntax. I think the most obvious should simply be newdt <- dt[rowselectname==rowselectvalue, colselectnames], which is how the rest of R seems to work.
I'd really appreciate someone explaining to me how to look at this to make sense of the syntax.

A: We can specify the colselectnames in .SDcols and select the .SD - as we are providing the column name as a string, get is used to return the value of the column.  It can also be done by converting to symbol and evaluate (eval(as.name(rowselectname)))
dt[get(rowselectname)==rowselectvalue, .SD, .SDcols =  colselectnames]
   b  d
1: 1 21
2: 2 22

If we want to use .. operator, use that in the j
dt[dt[, ..rowselectname][[1]] == rowselectvalue, ..colselectnames]
   b  d
1: 1 21
2: 2 22

A: From data.table version 1.14.3 on, get has been retired, and you're now able to use the new env parameter:

A new interface for programming on data.table has been added, closing #2655 and many other linked issues. It is built using base R's substitute-like interface via a new env argument to [.data.table. For details see the new vignette programming on data.table, and the new ?substitute2 manual page.

# install dev version
install.packages("https://github.com/Rdatatable/data.table/archive/master.tar.gz",  repo = NULL, type = "source")

library(data.table)

dt[rowselectname==rowselectvalue, ..colselectnames, env=list(rowselectname=rowselectname)]

   b  d
1: 1 21
2: 2 22

A: data.table allows for fast subsetting using the on argument and seconday indices (see the vignette Secondary indices and auto indexing, in particular chapter 2).
Using the on argument we can write
library(data.table)
dt[.(rowselectvalue), on = rowselectname, ..colselectnames]

       b     d
   <int> <int>
1:     1    21
2:     2    22

This concise code is similar to a data.table join where the second data.table is created on-the-fly.

In case rowselectvalue is not found in column  rowselectname, the result can be controlled by the nomatch argument.
By default, NA columns are returned, e.g.,
dt[.(rowselectvalue + 10), on = rowselectname, ..colselectnames]

       b     d
   <int> <int>
1:    NA    NA

The argument nomatch = NULL ensures that an empty data.table is returned, e.g.,
dt[.(rowselectvalue + 10), on = rowselectname, ..colselectnames, nomatch = NULL]

Empty data.table (0 rows and 2 cols): b,d


text:
Q: swagger widdershins slate html markup issue I need to compile swagger files into html files. I do:
Create json file on editor.swagger.io.
Generate markdown by the command:
widdershins endpoint.json -o ./endpoint.html.md

Then generate html by command:
middleman build

Then I copy files to apache, but final html markup is quite different than I expected. Sometimes parameter sections are absent, or POST parameters are not shown. Are there any compatibility issue? I use
https://github.com/lord/slate
https://github.com/Mermade/widdershins

A: Author of Widdershins here. Please raise an issue on github with a link to your swagger/openapi definition, and we'll try and debug it.


text:
Q: IE ignores styles for dynamically loaded content I've seen a couple similar questions here with no real answers. Hopefully someone notices this...
IE 8 and below are refusing to apply styles from the css stylesheet defined in the header when they are loaded in a document.ready jquery call.
Paranoid client wants NOBODY to see code or the dev site so I'll have to give a short example.
The client wants the site to render only the relevant portion of HTML on a nearly exclusively "ajaxed" site. So, the site is like a grid. If you load the homepage you get this:

Title

Hi There!

Then onload I use jquery to render the surrounding pages...
$(document).ready(function(){
    $('#content').append('

About Us

');
});

IE can handle this much, but when it comes to respecting my carefully plotted css, it just ignores the styles and laughs at me.
The site is entirely positioned with absolute positioning, tons of z-indexing and a horrendous amount of jquery animation. The kind of thing you do not want to have recreate in some extra stupid way for some inferior yet dominantly used browser. Dear god please tell me someone has figured out some way to get IE to respect defined styles on elements created after load.
Have ye any ideas?

*

*I know chunks of real code are preferred but this is succinct and tells you enough without having a full blown audit. Even if the only defined style is #about{ display:none; } it is ignored. The about section is written as requested but it is display block by default.

*I also know this is not technically ajaxing, but I'm using technical jargon to attempt to clarify the order of page loading in as much as it is not standard loaded html.
THE SOLUTION
$('#content').append($('
').attr('id', 'about').html('
About Us

some text
'));

Properly applies the element as well as the css for this and all children. Not sure why nested elements are read properly by IE without having to be declared the same way, but I am definitely grateful. Thanks jfriend00 and everyone else who helped.

A: The problem is that this line of code does not generate the desired set of HTML objects in IE7/IE8:
$('#content').append('

About Us

');

If you look in the IE DOM inspector, you don't see the desired tags nested appropriately so the DOM is messed up and thus the style rules don't work appropriately.  The issue is how things are getting inserted into the DOM by jQuery.  I think it's a jQuery interaction problem with IE more than anything else.
Without stepping through the code in detail on IE, I can't say whether it's actually a jQuery issue or an IE issue or just one of those weired combo bugs.  Obviously, IE has earned the right of first blame for it's previous transgressions, but it's probably better to just avoid this bug by using some more straightforward code.
Breaking down the code a bit, this code works for me in IE7:  Here, we create a single tag, add some innerHTML to it and then insert that root tag using append() rather than give HTML to append.
$(document).ready(function() {
    var section = $("
");
    section.attr("id", "about");
    section.html('
About Us
');
    $('#content').append(section);
});

You can see the revised code work here: http://jsfiddle.net/jfriend00/vEST8/
I don't know why IE has a problem with appending an whole HTML string directly via jQuery, but I have seen this problem before.

A: To be safe, use jQuery to apply said classes after the append:
$('#content').append('

About Us

');
$("#about").addClass("foo");


text:
Q: App crashes on ValueChanged of UIDatePicker for UITextField in UIAlertController I instantiate an UIAlertController and assign an UIDatePicker to one of its UITextField(s) as the input view. I also assigned a ValueChanged event handler to the picker. The UIDatePicker correctly shows when the mentioned UITextField gets focus, but when I change the value of the date the app crashes.
Please consider the code below.
var d = UIAlertController.Create( "Confirm", "Fill below with the required info.", UIAlertControllerStyle.Alert);

d.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, ((UIAlertAction obj) => SubmitAction(obj, d))));
d.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null));

d.AddTextField((delegate(UITextField obj) {
    UIDatePicker picker = new UIDatePicker ();
    picker.ValueChanged += (object sender, EventArgs e) => { obj.Text = picker.Date.Description; };
    obj.InputView = picker;
}));

PresentViewController(d, true, null);

Again, the picker shows up fine. The app crashes on the ValueChanged event even with an EMPTY handler picker.ValueChanged += (object sender, EventArgs e) => {};.
No crashes without adding the event handler!
This code is in a button TouchUpInside event handler.
Where am I doing wrong?

A: I think you have confused event methods in your code sample. TouchUpInside won't fire for the picker. If you want to update the text view's content if a new date value is selected, you will need to use:
picker.ValueChanged += (pickerSender, pickerArgs) =>
{
        obj.Text = picker.Date.Description;
};

To prevent this from crashing, you'll need to keep a reference to the UIDatePicker instance around, otherwise it will be collected too early. Easiest way is to move the date picker to class scope:
public override void ViewDidLoad ()
{
    base.ViewDidLoad ();

    // Perform any additional setup after loading the view, typically from a nib.
    this.btnTest.TouchUpInside += HandleTouchUpInside;
}

UIDatePicker picker;

void HandleTouchUpInside (object sender, EventArgs e)
{
    var d = UIAlertController.Create( "Confirm", "Fill below with the required info.", UIAlertControllerStyle.Alert);

    d.AddAction(UIAlertAction.Create("OK", UIAlertActionStyle.Default, ((UIAlertAction obj) => {})));
    d.AddAction(UIAlertAction.Create("Cancel", UIAlertActionStyle.Cancel, null));

    d.AddTextField((delegate(UITextField obj) {
        picker = new UIDatePicker ();
        picker.ValueChanged += (pickerSender, pickerArgs) =>
        {
            obj.Text = picker.Date.Description;
        };
        obj.InputView = picker;
    }));
    PresentViewController(d, true, null);
}


text:
Q: populating DB with million entries I want to populate MySQL database with million entries,
I tried using Data generator, but i was able to get only 200 entries though i give 1000 as input, which takes a lot of time for populating.
Also tried using .txt file LOAD FILE LOCAL INFILE method for populating, but get an error as FILE NOT FOUND though the file exists in my local directory (ERRCODE: 2 & ERRCODE: 22).
I was thinking is there any better way for populating DB with million entries for performance and if so can somebody suggest me with ideas resolving my query?????
how to populate my db with million values????

A: Try data generator. It allows you to generate precisely the data you want (you can choose columns, etc...).

A: Check out generate-dummy-test-data-for-mysql-using-routines
or generating-dummy-data-for-my-web-application-looking-for-dictionaries


text:
Q: mysql tuner - optimize table and cnf I want to optimize my database and decided to start by running mysqltuner, but it showed me so many errors that I don't know what to undertake, I couldn't advise what configuration I should specify based on my server settings

*

*My tarif on Linode is:
   4    GB RAM
   2    CPU Cores
   80   GB SSD Storage
   4    TB Transfer
   40   Gbps Network In
   4000 Mbps Network Out

I start my mysql tuner:
[--] Skipped version check for MySQLTuner script
[OK] Currently running supported MySQL version 5.6.43-log
[OK] Operating on 64-bit architecture

-------- Log file Recommendations ------------------------------------------------------------------
[--] Log file: /var/log/mysql/mysqld.log(0B)
[OK] Log file /var/log/mysql/mysqld.log exists
[OK] Log file /var/log/mysql/mysqld.log is readable.
[!!] Log file /var/log/mysql/mysqld.log is empty
[OK] Log file /var/log/mysql/mysqld.log is smaller than 32 Mb
[OK] /var/log/mysql/mysqld.log doesn't contain any warning.
[OK] /var/log/mysql/mysqld.log doesn't contain any error.
[--] 0 start(s) detected in /var/log/mysql/mysqld.log
[--] 0 shutdown(s) detected in /var/log/mysql/mysqld.log

-------- Storage Engine Statistics -----------------------------------------------------------------
[--] Status: +ARCHIVE +BLACKHOLE +CSV -FEDERATED +InnoDB +MEMORY +MRG_MYISAM +MyISAM +PERFORMANCE_SCHEMA
[--] Data in InnoDB tables: 766.8M (Tables: 110)
[OK] Total fragmented tables: 0

-------- Analysis Performance Metrics --------------------------------------------------------------
[--] innodb_stats_on_metadata: OFF
[OK] No stat updates during querying INFORMATION_SCHEMA.

-------- Security Recommendations ------------------------------------------------------------------
[OK] There are no anonymous accounts for any database users
[OK] All database users have passwords assigned
[!!] There is no basic password file list!

-------- CVE Security Recommendations --------------------------------------------------------------
[--] Skipped due to --cvefile option undefined

-------- Performance Metrics -----------------------------------------------------------------------
[--] Up for: 34d 20h 2m 32s (117M q [38.983 qps], 1M conn, TX: 1265G, RX: 20G)
[--] Reads / Writes: 99% / 1%
[--] Binary logging is disabled
[--] Physical Memory     : 3.9G
[--] Max MySQL memory    : 4.1G
[--] Other process memory: 150.6M
[--] Total buffers: 3.5G global + 1.1M per thread (151 max threads)
[--] P_S Max memory usage: 403M
[--] Galera GCache Max memory usage: 0B
[!!] Maximum reached memory usage: 4.0G (104.78% of installed RAM)
[!!] Maximum possible memory usage: 4.1G (106.26% of installed RAM)
[!!] Overall possible memory usage with other process exceeded memory
[OK] Slow queries: 0% (8K/117M)
[OK] Highest usage of available connections: 65% (99/151)
[OK] Aborted connections: 0.04%  (465/1327070)
[!!] name resolution is active : a reverse name resolution is made for each new connection and can reduce performance
[!!] Query cache may be disabled by default due to mutex contention.
[OK] Query cache efficiency: 49.1% (54M cached / 110M selects)
[OK] Query cache prunes per day: 0
[OK] Sorts requiring temporary tables: 0% (9 temp sorts / 3M sorts)
[!!] Joins performed without indexes: 122027
[OK] Temporary tables created on disk: 16% (9M on disk / 57M total)
[OK] Thread cache hit rate: 99% (6K created / 1M connections)
[OK] Table cache hit rate: 73% (366 open / 499 opened)
[OK] Open file limit used: 0% (47/10K)
[OK] Table locks acquired immediately: 100% (23M immediate / 23M locks)

-------- Performance schema ------------------------------------------------------------------------
[--] Memory used by P_S: 403.9M
[--] Sys schema isn't installed.

-------- ThreadPool Metrics ------------------------------------------------------------------------
[--] ThreadPool stat is disabled.

-------- MyISAM Metrics ----------------------------------------------------------------------------
[!!] Key buffer used: 18.3% (1M used / 8M cache)
[OK] Key buffer size / total MyISAM indexes: 8.0M/101.0K
[OK] Read Key buffer hit rate: 100.0% (77M cached / 4 reads)
[!!] Write Key buffer hit rate: 0.0% (41M cached / 30 writes)

-------- InnoDB Metrics ----------------------------------------------------------------------------
[--] InnoDB is enabled.
[--] InnoDB Thread Concurrency: 0
[OK] InnoDB File per table is activated
[OK] InnoDB buffer pool / data size: 1.0G/766.8M
[!!] Ratio InnoDB log file size / InnoDB Buffer pool size (50 %): 256.0M * 2/1.0G should be equal 25%
[!!] InnoDB buffer pool <= 1G and Innodb_buffer_pool_instances(!=1).
[--] InnoDB Buffer Pool Chunk Size not used or defined in your version
[OK] InnoDB Read buffer efficiency: 100.00% (27261013604 hits/ 27261058993 total)
[!!] InnoDB Write Log efficiency: 81.25% (48468 hits/ 59653 total)
[OK] InnoDB log waits: 0.00% (0 waits / 108121 writes)

-------- Replication Metrics -----------------------------------------------------------------------
[--] Galera Synchronous replication: NO
[--] No replication slave(s) for this server.
[--] Binlog format: STATEMENT
[--] XA support enabled: ON
[--] Semi synchronous replication Master: Not Activated
[--] Semi synchronous replication Slave: Not Activated
[--] This is a standalone server

-------- Recommendations ---------------------------------------------------------------------------
General recommendations:
    Reduce your overall MySQL memory footprint for system stability
    Dedicate this server to your database for highest performance.
    Configure your accounts with ip or subnets only, then update your configuration with skip-name-resolve=1
    Adjust your join queries to always utilize indexes
    Consider installing Sys schema from https://github.com/mysql/mysql-sys
    Before changing innodb_log_file_size and/or innodb_log_files_in_group read this:
Variables to adjust:
  *** MySQL's maximum memory usage is dangerously high ***
  *** Add RAM before increasing MySQL buffer variables ***
    query_cache_size (=0)
    query_cache_type (=0)
    join_buffer_size (> 256.0K, or always use indexes with JOINs)
    innodb_log_file_size should be (=128M) if possible, so InnoDB total log files size equals to 25% of buffer pool size.
    innodb_buffer_pool_instances (=1)

And my.cnf
 datadir=/var/lib/mysql
    socket=/var/lib/mysql/mysql.sock
    bind-address = 127.0.0.1
    ignore-db-dir = lost+found
    explicit_defaults_for_timestamp = 1
    # Disabling symbolic-links is recommended to prevent assorted security risks
    symbolic-links=0

    # Recommended in standard MySQL setup
    sql_mode=NO_ENGINE_SUBSTITUTION,STRICT_TRANS_TABLES

    query_cache_limit       = 1048576
    query_cache_size        = 2684354560
    query_cache_type        = 1

    innodb_flush_method     = O_DIRECT
    innodb_file_per_table   = 1
    innodb_buffer_pool_size = 1024M
    innodb_log_file_size = 256M
    innodb_flush_log_at_trx_commit = 2

    long_query_time=5
    slow_query_log=1
    slow_query_log_file= /var/log/mysql/log-slow-queries.log

    # Set unicode by default
    character-set-server  = utf8mb4
    collation-server      = utf8mb4_general_ci

    [mysqld_safe]
    log-error=/var/log/mysql/mysqld.log
    pid-file=/var/run/mysqld/mysqld.pid

How can I optimize my file based on this information?
Why do I ask because all tables have indexes, but requests are processed very slowly which affects the visits and usability of the site

A: The tool almost always recommends OPTIMIZE TABLE.  Don't bother.  It is almost always more trouble than benefit.
There is no reliable formula for maximum memory.  So ignore those [!!].
Joins performed without indexes: 122027 may or may not be an issue.  Is your system running slower than you would like?  If so, what are your 'slow' queries?
Key buffer used: 18.3% (1M used / 8M cache) and Write Key buffer hit rate -- bogus.  You are not using MyISAM; this is a trivial amount being wasted.
For deeper analysis, follow the instructions here.


text:
Q: Add some data in laravel paginate As the tittle said, Here is my Controller
$book = Data::where('userId','1')->paginate(3);

return response()->json($book);

And get the json data like this:
data:[{id: 1, userId: 1, vendorId: 1, name: "Alfreda Berge PhD", phone: "1-850-813-5950 x96169",…},…]
from:1
last_page:2
next_page_url: "http:/localhost/XX/public/user/book/list/1?page=2"
perpage:4
prev_page_url:null
to:4
total:5
// if I want to add a new column and value here ,what should I do?

I tried to do this :
$book = Data::where('userId','1')->paginate(3);
$book->printWord = 'Hellow!';
return response()->json($book);

But, It seem will remove the column printWord.
Any idea?

A: If you use the Illuminate\Pagination\LengthAwarePaginator class "manually", there's the option of extending it and overriding the toArray method:
return new class(
    $collection,
    $count,
    $limit,
    $page,
    // https://github.com/laravel/framework/blob/6.x/src/Illuminate/Pagination/LengthAwarePaginator.php#L40
    // values here will become properties of the object
    [
        'seed' => $seed
    ]
) extends LengthAwarePaginator {
    public function toArray()
    {
        $data = parent::toArray();
        // place whatever you want to send here
        $data['seed'] = $this->seed;
        return $data;
    }
};

Result
current_page    1
data    []
first_page_url  "/finder?max_miles=100&zip_code=10001&seed=0.2&page=1"
from    null
last_page   1
last_page_url   "/finder?max_miles=100&zip_code=10001&seed=0.2&page=1"
next_page_url   null
path    "/finder"
per_page    20
prev_page_url   null
to  null
total   0
seed    0.2 // <-- our custom prop

There's some extra work involved with instantiating LengthAwarePaginator yourself, but it gets the job done.

A: You can create collection with custom data manually and use merge() helper:
$book = Data::where('userId','1')->paginate(3);

$custom = collect(['my_data' => 'My custom data here']);

$data = $custom->merge($book);

return response()->json($data);

Just checked, it works just fine.

A: The paginate function will return an object of the type Illuminate\Pagination\LengthAwarePaginator, it is not possible to just add another field to this.
I think the best solution for you would be to add the pagination object and the other values in an array and convert this array to json. This way your books data is seperated from the other data you want to add.
Like so:
return response()->json([
    'books' => $books,
    'foo' => 'bar'
]);

In this case your json object will look like this:
{
    books: {
        // Pagination object with books
    }
    foo: 'bar'
}

A: You can also obtain data from your model using eloquent, for example, let say that each Data has a list of cars, books, and pets. Your Data model file should have a method that declares the "has many" relations with those classes, like below:
Data model file
namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Data extends Model{

protected $table = 'data';

protected $fillable = [
    'id', 'user_id', 'vendorId', 'name', 'phone'
];

public function cars(){
    return $this->hasMany(Car::class);
}

public function books(){
    return $this->hasMany(Book::class);
}

public function pets(){
    return $this->hasMany(Pet::class);
}

Also, you must have the "belongsTo" method in every Car, Book, and Pet model.
Car model file
...
public function data(){
    return $this->belongsTo(Data::class);
}
...

Finally, to obtain your results paginated and with all the data related to cars, books, and pets, the implementation should be:
Method in your Controller
$data_elements = Data::where('userId','1')->paginate(3);

foreach($data_elements as $d){
    $d->cars;
    $d->books;
    $d->pets;
}

return response()->json($data_elements);

I hope this alternative be useful for you or for some other developer!

A: Finally figured this out. If you are trying to return a json or array result, just change the paginated data to an array first. Then add the attributes you need to the array.
$results = $data->paginate()->toArray();
$results['new_attribute'] = 'Attribute Value';
return response()->json($result);

Merging or appending to the paginated data doesn't work because it gets lost when the json() method converts it to an array. So by converting it to an array first, you can modify the end results.

A: Modify exiting pagination data send update response.
    $itemsPaginated = $this->items()
         ->paginate(15);

    $itemsTransformed = $itemsPaginated
        ->getCollection()
        ->map(function($item) {
            return [
                'id' => $item->id,
            ];
    })->toArray();

    $itemsTransformedAndPaginated = new \Illuminate\Pagination\LengthAwarePaginator(
        $itemsTransformed,
        $itemsPaginated->total(),
        $itemsPaginated->perPage(),
        $itemsPaginated->currentPage(), [
            'path' => \Request::url(),
            'query' => [
                'page' => $itemsPaginated->currentPage()
            ]
        ]
    );

A: I believe the proper way is to create a resource (see https://laravel.com/docs/8.x/eloquent-resources) and use the additional() method for this. A common use case is displaying a paged result set while showing the grand total for the entire collection.
// collect the grand total
$grandTotal = $customer->invoices()->sum('amount_excl');

// prepare the result set
$data = InvoiceResource::collection($customer->invoices()->paginate(10));

// inject additional data
$data->additional(['extra'=>['total_amount' => $grandTotal]]);
return $data;

You'll get the proper response with metadata, and your added data in the separate 'extra' property.
{
 data: [{id: 15922, identifier: "12345", amount_excl: 143.27,…},…]
 extra: {total_amount: 6554.35}
 links: {first: "https://your.url.com/customers/80/invoices?page=1",…}
 meta: {current_page: 1, from: 1, last_page: 5, path:
}

A: $book = Data::where('userId','1')->paginate(3);
$book = $book->toArray();
$book['printWord'] = 'Hellow!';
return response()->json($book);

This will work. you can convert paginate object to array, then you need to add element into the array


text:
Q: Identical notification bubbles keep re-appearing I have just recently noticed this problem occurring. When I receive an email, the on-screen notification bubbles 'keep popping up'. By this, I mean it will pop-up and tell me I have received an email, then it will disappear, and an identical bubble, telling me about the same email, will pop-up again. This will happen anywhere between 4-9 times. As you can imagine, it is getting pretty annoying, especially considering the volume of emails one receives these days.
I have ubuntu 12.04, and have installed notify-OSD, but have only used it to change the position and 'click to dismiss' properties of the bubbles. I have thunderbird (with my gmail account in it) and lightning installed (but only use TB to interact with my gmail calendar). I also use Chromium to check my gmail.
Has anyone got any ideas of what may be causing this? Is it a Chromium extension problem, or a thunderbird problem, or an OS/notification daemon problem?
Cheers,
Dave

A: So I think I have figured out what was wrong, and how to fix it.
I had installed Unity Webapps extension (e.g. to integrate Youtube, Google Docs, etc into the desktop). I had a look in my Chromium extensions, and there was 4 unity webapps extensions installed. I disabled 3 of them, and now the email pop-up only occurs once!
If anyone else has this problem, this is exactly how I fixed it:
In Chromium, go Tools>Extensions. Then, ensure only one (1) Unity WebApps Chromium extension is enabled.


text:
Q: WooCommerce custom slug for specific product category I try to create a custom permalink for products in a specific product category but it works really weird.
I try to achieve URLs like:

*

*domain.com/category_name/product-name - for products in a specific category,

*domain.com/default_slug/product-name - for the rest of products

I tried to add the %type% rule to product permalinks by using a two-step approach to (1) generate proper URLs and (2) show respective product page:
function custom_permalink($permalink, $post_id, $leavename) {
  if (strpos($permalink, '%type%') === FALSE) return $permalink;

  // Get post
  $post = get_post($post_id);
  if (!$post) return $permalink;

  // Get taxonomy terms
  $terms = wp_get_object_terms($post->ID, 'product_cat');
  if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) {
    if ($terms[0]->slug == 'category_name') {
      $taxonomy_slug = $terms[0]->slug;
    } else {
      $taxonomy_slug = 'default_slug';
    }
  }
  else {
    $taxonomy_slug = 'default_slug';
  }

  return str_replace('%type%', $taxonomy_slug, $permalink);
}
add_filter('post_link', 'custom_permalink', 10, 3);
add_filter('post_type_link', 'custom_permalink', 10, 3);

function rewrite_product_base_tag() {
  add_rewrite_tag( '%type%', '([^&]+)', 'in-type=' );
}
add_action( 'init', 'rewrite_product_base_tag', 10, 0 );

It works fine except it shows products even if I use any random slug. The following URLs will show the product based on its name (every single URL shows the "product-name" product):

*

*domain.com/default_slug/product-name

*domain.com/category_name/product-name

*domain.com/ANY_RANDOM_STRING/product-name

I also tried to use different regex to limit available slugs. It only shows the second option (category_name) properly. The first one (default_slug) shows the Archive page. It works exactly the same even if those are changed with each other: the first one shows the Archive page, the second one works fine.
Adding a rewrite_rule function doesn't work at all.

function rewrite_product_base_tag() {
  add_rewrite_tag( '%type%', '(default_slug|category_name)', 'in-type=' );
}
add_action( 'init', 'rewrite_product_base_tag', 10, 0 );

A: add_action( 'save_post', 'add_custom_attributes_to_permalink', 10, 3 );
function add_custom_attributes_to_permalink( $post_id, $post, $update ) {

    //make sure we are only working with Products
    if ($post->post_type != 'product' || $post->post_status == 'auto-draft') {
        return;
    }

    //get the product
    $_product = wc_get_product($post_id);

    //get the "clean" permalink based on the post title
    $clean_permalink = sanitize_title( $post->post_title, $post_id );

    //next we get all of the attribute slugs, and separate them with a "-"
    $attribute_slugs = array(); //we will be added all the attribute slugs to this array
    foreach ($_product->get_attributes(); as $attribute_slug => $attribute_value) {
        $attribute_slugs[] = $attribute_value;
    }
    $attribute_suffix = implode('-', $attribute_slugs);

    //then add the attributes to the clean permalink
    $full_permalink = $clean_permalink.$attribute_suffix;

    // unhook the save post action to avoid a broken loop
    remove_action( 'save_post', 'add_custom_attributes_to_permalink', 10, 3 );

    // update the post_name (which becomes the permalink)
    wp_update_post( array(
        'ID' => $post_id,
        'post_name' => $full_permalink
    ));

    // re-hook the save_post action
    add_action( 'save_post', 'add_custom_attributes_to_permalink', 10, 3 );
}


text:
Q: opencv python bindings coverage I know of some opencv C++ API functions and classes that don't have python bindings.
Instead of finding these, one by one, every time I need them -- which is annoying -- is there any document, site, way of knowing what part of opencv C++ API has or has not python bindings?
I mean a summary of the coverage. I know that in the online documentation you can see if a function or class has a python interface -- but even then sometimes I wonder if the documentation is updated and maybe there is a binding somewhere. I don't want to do a binding myself unless it is absolutely necessary.


text:
Q: Forking from GitHub to Bitbucket I'm working on a project based on CakePHP, that's hosted on GitHub. My project is being hosted on Bitbucket. Both of them use git. Basically I'd like to create a 'fork' (I don't know if I'm using the right terms, since I'm new to git) of CakePHP in my Bitbucket repository, in order to be able to get the updates without the need to download all the CakePHP zip/tar and replace the folder, then commit and push, but maybe with a 'merge'(?).

A: The workflow below adds the github repository as a a new remote called sync and the bitbucket remote as origin. It also adds a branch called github to track the github repository and a branch called master to track the bitbucket repository. It assumes you have a bitbucket repository called "myrepository" which is empty.
Setup remotes
# setup local repo
mkdir myrepository
cd myrepository
git init

# add  bitbucket remote as "origin"
git remote add origin ssh://git@bitbucket.org/aleemb/myrepository.git

# add github remote as "sync"
git remote add sync https://github.com/aleemb/laravel.git

# verify remotes
git remote -v
# should show fetch/push for "origin" and "sync" remotes

Setup branches
# first pull from github using the "sync" remote
git pull sync

# setup local "github" branch to track "sync" remote's "master" branch
git branch --track github sync/master

# switch to the new branch
git checkout github

# create new master branched out of github branch
git checkout -b master

# push local "master" branch to "origin" remote (bitbucket)
git push -u origin master

Now you should have the local github branch tracking the github repo's master branch. And you should have the local master branch tracking the bitbucket repo (master branch by default).
This makes it easy to do a pull on the github branch, then merge those changes onto the master branch (rebase preferred over merge though) and then you can push the master branch (will push it to bitbucket).

A: I have noticed that since @Martin Geisler 's answer, Bitbucket has enabled a feature to import repositories from github.com
I was able to successfully import a private repo from github.com into a private repo on bitbucket.org
Here are the steps:

*

*Click on the Create button and select Repository ('+' > Repository)

*Now, instead of creating a new repository select a import repository from the top right corner of the modal that pops up.

*fill in your github repo's URL and your authentication credentials on the new modal for importing the repository.

*That's it. Everything imports into bitbucket from github smoothly.

Note the import repository link on right top corner of the screenshot

A: If you want to keep your repo up to date, use two remotes: Github (upstream) and Bitbucket (origin) like this:
# Clone original CakePHP source code from Github
git clone --mirror https://github.com/cakephp/cakephp
cd cakephp
# Rename remote from `origin` to `upstream`
git remote rename origin upstream
# Add your Bitbucket repo (this is where your code will be pushed)
git remote add origin https://bitbucket/your/repo.git
# Push everything to Bitbucket
git push --mirror origin

To pull updates to CakePHP from Github:
git pull upstream master

To push your code changes to Bitbucket:
git push origin master

A: It's not possible to send "pull request" across different sites today. I've added a feature request for this in the Bitbucket issue tracker: #3288. I suggest you add yourself as a follower if you want to track this.
However, you can still move the source from GitHub to Bitbucket without having to download any zip files or tarballs. You make a clone from GitHub and push to Bitbucket:
$ git clone https://github.com/cakephp/cakephp
$ cd cakephp
$ git push git@bitbucket.org:mg/cakephp.git master

I created mg/cakephp as an empty Git repository in Bitbucket first. That way you can push/pull changesets from GitHub to Bitbucket.

A: When creating a new repository in BitBucket, click the button Import repository at the top right. Enter the https url found when clicking Clone or download in Github for the repository you want to fork.
Give your repository a name, configure your privacy settings, and there you go!

A: I'm guessing you just want to easily download the repository with your project... and that you will NOT be contributing the cakePHP, correct?
if so, you just need to add a external reference to your repo.
SVN:externals equivalent in GIT?
And later, even if you want to contribute to cakePHP, you can just do so at the original repo just fine.


text:
Q: Updating Git tagger emails I used the wonderful git filter-branch script to rewrite all author and committer emails. I even used --tag-name-filter cat to rewrite the tags:
git filter-branch --tag-name-filter cat --env-filter '
    if test "$GIT_AUTHOR_EMAIL" = "foo@example.com"
    then
        GIT_AUTHOR_EMAIL=bar@example.com
    fi
    if test "$GIT_COMMITTER_EMAIL" = "foo@example.com"
    then
        GIT_COMMITTER_EMAIL=bar@example.com
    fi
' -- --all

Everything seemed to work OK, except that the rewritten tags still have a "tagger" property with the email set to foo@example.com. I read the [filter-branch documentation][1], yet I can't find anything similar to TAGGER_EMAIL.
How can I change the tagger email when updating the Git history?


text:
Q: this error occurs when i press on the create button in create post form An unhandled exception occurred while processing the request sql exception asp.net core .
SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_Posts_AspNetUsers_AuthorId". The conflict occurred in database "LostKidsDb", table "dbo.AspNetUsers", column 'Id'.
Here is the Post Model
    [Key]
    public int PostId { get; set; }

    [Required]
    public string Title { get; set; }

    public string Descripition { get; set; }

    public string  Image { get; set; }

    public string Address{ get; set; }

    [Display(Name ="Category")]
    public int CategoryId{ get; set; }

    [ForeignKey("CategoryId")]
    public Category Category{ get; set; }

    [Display(Name = "Sub-Category")]
    public int SubCategoryId { get; set; }

    [ForeignKey("SubCategoryId")]
    public SubCategory SubCategory { get; set; }

    [Display(Name = "Author-Id")]
    [Required]
    public string AuthorId { get; set; }

    [ForeignKey("AuthorId")]
    public ApplicationUser ApplicationUser { get; set; }
    [Required]
    [Display(Name = "Author-Name")]
    public string AuthorName { get; set; }

    public enum PostStatus
    {
        Pending,
        Approved,
        Rejected
    }
    public PostStatus Status { get; set; }

Here is the Application user model
public class ApplicationUser:IdentityUser
{
    public string Name { get; set; }

    public string StreetAddress { get; set; }

    public string PostalCode { get; set; }
    public string Governorate { get; set; }

    public string  City { get; set; }
}

This is the create razor view page in user controller:

            @if (SignInManager.IsSignedIn(User))
            {
                {
                    ApplicationUser applicationUser = await UserManager.GetUserAsync(User);

                    <input readonly asp-for="Post.AuthorName" value=" @applicationUser.Name " class="form-control" />

                }
            }

            @if (SignInManager.IsSignedIn(User))
            {
                {
                    ApplicationUser applicationUser = await UserManager.GetUserAsync(User);

                    <input type="hidden" asp-for="Post.AuthorId" value=" @applicationUser.Id " class="form-control" />

                }
            }

Here is the Create Method in Post Controller in User Area:
    [HttpGet]
    public IActionResult Create()
    {

        return View(PostVM);
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    [ActionName("Create")]
    public async Task<IActionResult> CreatePost()
    {
        //if (ModelState.IsValid)
        //{

            //in case the user didn't upload an image while creating a post a default image will be uploaded with the post

            string ImagePath = @" \Images\download.png";

            //uploaded images of the created post will be saved into this static file
            var files = HttpContext.Request.Form.Files;
            if (files.Count > 0)
            {
                string webroot = webHostEnvironment.WebRootPath;

                // change the name of images uploaded to avoid duplicate names so every uploaded image
                // will take the name of the date of its uploading
                string ImageName = DateTime.Now.ToFileTime().ToString() + Path.GetExtension(files[0].FileName);

                FileStream fileStream = new FileStream(Path.Combine(webroot, "Images", ImageName), FileMode.Create);
                files[0].CopyTo(fileStream);

                ImagePath = @"\Images\" + ImageName;
            //}
            PostVM.Post.Image = ImagePath;
            db.Posts.Add(PostVM.Post);
            await db.SaveChangesAsync();
            return RedirectToAction(nameof(Index));

        }
        return View(PostVM);
    }


text: Q: How to run a external class from controller passing context and UserManager as paremeters? I am using asp.net mvc core 2.1 and need to run a external class from controller but passing parameter context for manipulate sql server and UserManager object because I want to get a specific claim from "User.Identities.First" command. Thank you in advance.


text:
Q: Efflux velocity vessel filled with air and fluid I want to calculate the effelux velocity for this open vessel with area $A_1$ with a small outlet with area $A_2$ as a function of time. The atmospheric pressure is $p_0$.
The vessel has height $h = h_{air} + h_{fluid}$ and is filled with a fluid. I want to take into account the velocity and potential head losses of the air. I am not interested in other losses.
An idea is to calculate the velocity starting from this equation.
$$(p_0-\rho_{air}g(h_{air}+h_{air} - z) -\frac{1}{2}\rho_{air}v^2)+\frac{1}{2}\rho_{fluid}v^2+\rho_{fluid}gz = p_0 + \rho_{fluid}\frac{A_1^2}{2A_2^2} v^2$$
I am in doubt as I don't know how to deal with the equilibrium at the interface between the fluid and the air. I know that in principle Bernouilli is not valid for a flow with two different fluids.

A: I think the point of the question may be that the air contribution is completely negligible.  You are simply converting the potential energy of the still water at height $h_\text{fluid}$ to kinetic energy at the bottom.
If you did want to account for the air head anyway, simply assume $P_0$ at the top of the water is $P_0+\rho g h_\text{air}$ instead. This would also be the same if it were a closed tank, with pressurized gas, what's called Ullage Pressure.


text:
Q: can define a new column because it is factor I have a dataset like this:

risk earthquake
platarea
magnitude
area

0.4
no
5
30

0.5
no
6
20

5.5
yes
6
20

I would like to create a new column
i gave that code
df$newrisk <- 0.5*df$magnitude + 0.6*df$aarea + 3*df$platarea

I got an error message for df$platarea?
BUt the platarea will only increase when it is "yes".
How can I code that???? the code is right if I omit df$platarea, but i would also include df$platarea but don't know how??

A: We can create a logical vector
i1 <- df$platarea == "yes"
df$newrisk[i1] <- with(df, 0.5 * magnitude[i1] + 0.6 * area[i] + 3)

If it is only to change the + 3 *, multiply by the logical vector so that FALSE (or 0 will return 0 and TRUE for 'yes' will return 3 as -3 *1 = 3)
df$newrisk <- with(df, 0.5 * magnitude + 0.6 * area + 3 *i1)

A: There are three common ways to add a new column to a data frame in R:

*

*Use the $ Operator

df$new <- c(3, 3, 6, 7, 8, 12)

*Use Brackets

df['new'] <- c(3, 3, 6, 7, 8, 12)

*Use Cbind

df_new <- cbind(df, new)
I leave some examples for further explanation:
#create data frame
df <- data.frame(a = c('A', 'B', 'C', 'D', 'E'),
                 b = c(45, 56, 54, 57, 59))

#view data frame
df

  a  b
1 A 45
2 B 56
3 C 54
4 D 57
5 E 59

Example 1: Use the $ Operator

    #define new column to add
new <- c(3, 3, 6, 7, 8)

#add column called 'new'
df$new <- new

#view new data frame
df

  a  b new
1 A 45   3
2 B 56   3
3 C 54   6
4 D 57   7
5 E 59   8

Example 2: Use Brackets
#define new column to add
new <- c(3, 3, 6, 7, 8)

#add column called 'new'
df['new'] <- new

#view new data frame
df

  a  b new
1 A 45   3
2 B 56   3
3 C 54   6
4 D 57   7
5 E 59   8

Example 3: Use Cbind
#define new column to add
new <- c(3, 3, 6, 7, 8)

#add column called 'new'
df_new <- cbind(df, new)

#view new data frame
df_new

  a  b new
1 A 45   3
2 B 56   3
3 C 54   6
4 D 57   7
5 E 59   8


text:
Q: C++ malloc/realloc weird behavior I was programming a dynamic array for my own use, that i wanted pre-set with zeros.
template <class T>
dynArr<T>::dynArr()
{
rawData = malloc(sizeof(T) * 20); //we allocate space for 20 elems
memset(this->rawData, 0, sizeof(T) * 20); //we zero it!
currentSize = 20;
dataPtr = static_cast<T*>(rawData); //we cast pointer to required datatype.
}

And this part works - iterating by loop with dereferencind the dataPtr works great. Zeros.
Yet, reallocation behaves (in my opinion) at least a bit strange. First you have to look at reallocation code:
template <class T>
void dynArr<T>::insert(const int index, const T& data)
{

    if (index < currentSize - 1)
    {
        dataPtr[index] = data; //we can just insert things, array is zero-d
    }

    else
    {
        //TODO we should increase size exponentially, not just to the element we want

        const size_t lastSize = currentSize; //store current size (before realloc). this is count not bytes.

        rawData = realloc(rawData, index + 1); //rawData points now to new location in the memory
        dataPtr = (T*)rawData;
        memset(dataPtr + lastSize - 1, 0, sizeof(T) * index - lastSize - 1); //we zero from ptr+last size to index

        dataPtr[index] = data;
        currentSize = index + 1;
    }

}

Simple, we realloc data up to index+1, and set yet-non-zeroed memory to 0.
As for a test, i first inserted 5 on position 5 on this array. Expected thing happened - 0,0,0,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0
Yet, inserting something else, like insert(30,30) gives me strange behavior:
0, 0, 0, 0, 0, 5, 0, -50331648, 16645629, 0, 523809160, 57600, 50928864, 50922840, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 30,

What the hell, am i not understanding something here? shouldnt realloc take all the 20 previously set memory bytes into account? What sorcery is going on here.

A: Problem 1:
You are using the wrong size in the call to realloc. Change it to:
rawData = realloc(rawData, sizeof(T)*(index + 1));

If rawData is of type T*, prefer
rawData = realloc(rawData, sizeof(*rawData)*(index + 1));

Problem 2:
The last term of the following is not right.
memset(dataPtr + lastSize - 1, 0, sizeof(T) * index - lastSize - 1);

You need to use:
memset(dataPtr + lastSize - 1, 0, sizeof(T) * (index - lastSize - 1));
                               //  ^^              ^^
                               // size      *  The number of objects

Problem 3:
Assigning to dataPtr using
dataPtr[index] = data;

is a problem when memory is obtained using malloc or realloc. malloc family of functions return just raw memory. They don't initialize objects.
Assigning to uninitialized objects is a problem for all non-POD types.
Problem 4:
If T is type with virtual member functions, using memset to zero out memory will most likely lead to problems.

Suggestion for fixing all the problems:
It will be much better to use new and delete since you are in C++ land.
template <class T>
dynArr<T>::dynArr()
{
   currentSize = 20;
   dataPtr = new T[currentSize];
   // Not sure why you need rawData
}

template <class T>
void dynArr<T>::insert(const int index, const T& data)
{
   if (index < currentSize - 1)
   {
      dataPtr[index] = data;
   }

   else
   {
      const size_t lastSize = currentSize;
      T* newData = new T[index+1];
      std::copy(dataPtr, dataPtr+lastSize, newData);
      delete [] dataPtr;
      dataPtr = newData;
      dataPtr[index] = data;
      currentSize = index + 1;
   }
}

Please note that the suggested change will work only if T is default constructible.
This will also take care of the problems 3 and 4 outlined above.


text:
Q: Why is the pdf output of my QGIS map different from the one I see in the Print Composer? I'm working on a map of migrant deaths and missings in and around the Medditerranean Sea. It includes a legend. When I work in the print composer mode, the legend seems to be looking fine. Here it is:

When I look at the pdf output of my map, however, it looks different:

The key issues here are the extra pink moon-like shape on the left, and the extra "1" at the bottom of the graduated circles.
I suppose this has something to do with the fact that I'm trying to hide part of the "wrong" graduated circles, which I'm overlapping with two images: correct version and a white image to cover the remaining bits. One can see the outlines of these images over here:

Question: why is the output of the legend in the pdf of the map different from the one in the print layout, and how can I make sure QGIS generates the correct output?


text:
Q: No access to my Apple developer team in Xcode I have 2 Apple accounts. One of them is a developer paid account. The other is a free account  added to the team of the paid developer account. When I'm logged in with the free account on the Apple dev website, I see the name of the dev team (the team that has been created by the paid dev account).
My issue is that I can't add the dev team in my Xcode project. I only have the personal team accessible. Then I don't have paid dev team privileges.
How can I fix this? Do I have to pay a developer account for both accounts? Thank you for the help!

A: I have to pay a developer account for both accounts.
For example: a team of 4 developers has to buy 4 developer account for each in order to get developer privileges.


text:
Q: Auto-Encoders to classify images? I am currently a student and I am developing a project of a Neural Network to classify a dataset of images. Since this images are not labeled I would need a unsupervised method of learning.
It has been suggested to me I should use Auto-Encoders, is it possible to use an Auto-Encoder to 'discover' important features and then use the features learnt in the 'Hidden Layer' into a Multilayer Perceptron Network for instance, so I can classify images?
Thank you all for your help.

A: Classification is inherently a supervised problem. To do this, you would need to have labeled images that the classifier can learn to predict. Your problem sounds like clustering. Here, you'd assign images to discrete categories (clusters) based on some notion of similarity; images assigned to the same cluster are more similar to each other than those assigned to different clusters. Many clustering algorithms are available. If you wanted, you could perform clustering on the hidden layer representations of an autoencoder. You could think of this as clustering the images after mapping them nonlinearly into a feature space.


text:
Q: Ktor Server: How to find out when a client has finished downloading a file? I want to run code when a HTTP client has finished downloading a file from Ktor Server. The most simple approach does not work:
routing {
    get("/download") {
        call.response.header(
            ContentDisposition,
            Attachment.withParameter(FileName, file.fileName).toString()
        )
        call.respondFile(file)
        // client has not finished downloaded when we reach this point
    }
}

I already tried intercepting pipelines, writing out the file in byte arrays myself, but all that detects a completed download too soon. If I for example stop the webserver and related services too soon, the client isn't able to actually complete the download.
So is there a way to reliably detect when the client has ACKed the last bytes of the file?


text:
Q: Are there names for function which doesn't have all items in it's domain as defined?
Consider a function similar to the one above where except for a few points in the domain, the function is bijective. Is there a name given for this kind of function similar to bijectivity?
My initial guess was discontinuous functions but I'm not sure how well that concept works for discrete functions.

A: A discontinuous function is still defined on every point in its domain, discontinuity is defined in terms of limits. What you're describing is called a 'partial function', I believe the term sees some use in computer science, but you're unlikely to find it in a standard mathematics course.


text:
Q: Laravel upgrade broke model paths I've performed a long-overdue update on a Laravel project from v5.7 to v9 and ran into a Target class does not exist error. I found this guide and used the first method to resolve the error (adding the namespace into the RoutesServiceProvider.php boot function). This resolved that error but now, everything is giving me Class "App\Whatever" not found.
I did notice that models are now stored in a Models directory within the app directory rather than directly in app, so have moved them to Models. I figured that might be breaking my use App\Whatever; lines at the top of my controllers, so I've tried use App\Models\Whatever and also use app\Models\Whatever (since the "a" is lowercase in the directory name) but no effect.
I should note I don't really have a good grasp of namespaces, MVC frameworks etc. so ELI5 etc :-)
Some of my controller:
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Thing;
use App\AnotherThing;
...
    public function thing_summary($id) // show the summary view of the thing

    {

        if(Auth::check()) {

            $thing = Thing::find($id);
...

A: Laravel 7/8/9 sticks with strict namespacing. When you move the models to a new directory, you need to update the namespace in the models themselves (if specified at all) and any file that has a use for the model. If the models move from app/ to app/models, the namespace must be changed to App/Models


text:
Q: How can I display path on right side of terminal screen instead of before prompt? I'd like to show the current working directory on the right side of screen in bash terminal and no path before the prompt where it is shown now.
Ubuntu 18.04 LTS


text:
Q: Can we say "Had Einstein used his spare time on something more useful for the society, ..." The complete sentence is :

Had Einstein used his spare time on something more useful for the society, the improvement of our knowledge of the nature of the universe would have been greatly delayed.

I move "Had" to the head of the sentence to make it a little uncommon.

A: That is a proper conditional statement, so yes, you can certainly frame it like this.


text:
Q: Why is XPath syntax not working in DomDocument60? I'm trying to parse a set of FX quotes in a daily download from an ECB URL. It seems to work using DOMDocument but doesn't work when I switch to DOMDocument60. I've included both approaches in the code below. I believe I've got the XPath syntax correct -- to identify all Cube nodes with a "time" element so as to be able to identify each new day's quotations in the time series.
Can anyone tell me what I'm doing wrong?
Sub XMLDom60vs30()
    Dim oXMLHTTP As Object
    Dim sURL As String
    Dim XmlMapResponse As String
    Dim strXML As String

    Dim xDoc  As Object
    Dim xDoc60  As MSXML2.DOMDocument60

    Dim xNodeList As Object
    Dim xNodeList60 As MSXML2.IXMLDOMNodeList

    ' This URL access daily FX history from an ECB website.
    sURL = "https://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist.xml?affd3fe4c0ac916ce2e9d1ccfea2327c"
    Set oXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP")
    Set xDoc = CreateObject("MSXML2.DOMDocument")
    Set xDoc60 = New MSXML2.DOMDocument60

    oXMLHTTP.Open "GET", sURL, False
    oXMLHTTP.send
    XmlMapResponse = oXMLHTTP.responseText
    strXML = XmlMapResponse

    With xDoc
        .async = False
        .validateOnParse = False
        .LoadXML (strXML)
    End With

    With xDoc60
        .async = False
        .validateOnParse = False
        .LoadXML (strXML)
    End With

    Set xNodeList = xDoc.SelectNodes("//Cube[@time]")
    Set xNodeList60 = xDoc60.SelectNodes("//Cube[@time]")
    Debug.Print "List Length: xNodes = " & xNodeList.Length & ", XNodes60 = " & xNodeList60.Length & ", finished at " & Format(Now(), "hh:mm:ss")

End Sub


text:
Q: Does webdriver support media query? I am executing automated tests via cucumber on iOS and Android everything is green on iOS however the same tests, same code running on Android fail because of missing content in the browser. After speaking to one of our front end devs he suggested I find out if webdriver for android supports media query as checking manually in the browser (not using webdriver) works fine.
Thanks in advance,
Ian


text:
Q: neighborhood classification with postgis I need to build a web application to explore some survey data, but I am struggeling a bit to find the right tools. PostGIS looks quite interesting, but I am not sure if it fits my needs or is maybe overkill.
The dataset (table 1) contains rows (events in Los Angeles) with a spatial attribute, i.e. a long/lat field. I have another dataset (table 2) defining areas in Los Angeles. Can I do the following in PostGIS?

*

*SELECT only the datapoints from table 1 from a certain area defined in table 2?

*Tabulate a categorical variable by area? E.g count number of males and females for every area?

*Do binning of a numeric variable by area? E.g. to get the age distribution, show how many people per area are of age [0-9), [10-19), [20-29), etc?

Furthermore, I was wondering if it is safe to have the PostGIS database directly queried by javascript (using geojson), or should I always have an application layer in between (code injection ,etc)?

A: Answer to your points is yes, yes, and yes.  After installing PostGIS, you will be able to do all of this (assuming table 1 has these attributes).
SELECT only the datapoints from table 1 from a certain area defined in table 2?

*

*Yes, in a few manners.  Is the data in table 2 defined as polygons, or is it a list of points?  List of points is a bit harder to do, but works...much easier if you have polygons here.  (after looking at your link,  use the shape (shp) file.

Tabulate a categorical variable by area? E.g count number of males and females for every area?

*

*Count is in the select clause, the geo component is in the where clause.  As long as these attributes exist in table 1, you can do these counts by any value you want.

Do binning of a numeric variable by area? E.g. to get the age distribution, show how many people per area are of age [0-9), [10-19), [20-29), etc?

*

*Yep, same answer as above.  Binning might require a case statement, but as long as you can group by it, you can count by it.  heh

Not sure if I can answer the last question though...


text:
Q: How to update customized listview on incoming messages..? Currently am working on a project where text messages from a particular person is stored and displayed. Am using customized list view for displaying the stored messages. Till this part my code is fine. But i need to update my list view when a new messages arrives when the activity is on foreground. Unfortunately the list view only updates the new message when the activity goes to onCreate() method again. I need to update the listview if it is on foreground. Any ideas.....???

A: Keep your refresh code in onResume() instead of putting it in onCreate().
   On every time you get the new message call adapter.notifyDataSetChanged() method to update the layout


text:
Q: AttributeError: type object 'Split' has no attribute 'Train' I'm following a simple tutorial using Google colab.
(train_data,validation_data),test_data=tfds.load(name='imdb_reviews',
          split=((tfds.Split.Train.subsplit([6,4])),tfds.Split.Test),
          as_supervised=True)

After writing this code I'm getting the error as shown below:
AttributeError                            Traceback (most recent call last)
<ipython-input-10-facc01319dcb> in <module>()

         1 (train_data,validation_data),test_data=tfds.load(name='imdb_reviews',
    ----> 2           split=((tfds.Split.Train.subsplit([6,4])),tfds.Split.Test),
          3           as_supervised=True)

AttributeError: type object 'Split' has no attribute 'Train'

A: .subsplit was part of the deprecated API, so cannot be used anymore.
Instead you should use the new subsplit API: https://www.tensorflow.org/datasets/splits
ds1, ds2 = tfds.load(..., split=[ 'train[:50%]', 'train[50%:]'])

According the issue 1998.


text:
Q: Register namespace with libxml++ for XPath I wrote a C++ XPath parser with the libxml++ library, which was built on the C libxml2 library. It works great when the xmlns is not present in xml but it breaks when that namespace is added.
Sample xml:
<A xmlns="http://some.url/something">
  <B>
    <C>hello world</C>
  <B>
</a>

Sample XPath:
string xpath = "/A/B/C" // returns nothing when xmlns is present in the XML

I found this answer and tried adjusting my XPath to the following, which does work but it makes the XPath kind of obnoxious to read and write.
string xpath = "/*[name()='A']/*[name()='B']/*[name()='C']"

Ideally I want to register the namespace so I can use normal XPaths. I've also searched through the libxml++ documentation and found a Node.set_namespace but it just causes an exception when I try to use it.
root_node->set_namespace("http://some.url/something");
// exception: The namespace (http://some.url/something) has not been declared.

However, the root_node is definitely aware of the namespace when it parses the XML document:
cout << "namespace uri: " << root_node->get_namespace_uri();
// namespace uri: http://some.url/something

At this point I am out of ideas so help is greatly appreciated.
EDIT Also tried:
Element *root_node = parser->get_document()->get_root_node();
root_node->set_namespace_declaration("http://some.url/something","x");
cout << "namespace uri: " << root_node->get_namespace_uri() << endl;
cout << "namespace prefix: " << root_node->get_namespace_prefix() << endl;
// namespace uri: http://some.url/something
// namespace prefix:

Does not complain but doesn't appear to register the namespace.

A: The online documentation for libxml++ does not mention how to use namespaces with xpaht expression.
But as you pointed out  libxml++ is a wrapper to libxml2.
For libxml2 have a look to xmlXPathRegisterNs.
As always with wrapper the hide complexity and even (most likely) functionality.
Having a look to the libxml++ sourcecode shows that there are find overloads which make use of xmlXPathRegisterNs.
using PrefixNsMap = std::map<Glib::ustring, Glib::ustring>
NodeSet find(const Glib::ustring& xpath, const PrefixNsMap& namespaces);

Therefor try to call  find with the PrefixNsMap, with  the prefix as key.
Update:
 xmlpp::Node::PrefixNsMap nsmap;
 nsmap["x"] = "http://some.url/something";
 auto set = node->find(xpath, nsmap);
 std::cout << set.size() << " nodes have been found:" << std::endl;

Comment to strange discussion about namespaces:

*

*A default namespace is often used in xml documents

*The default namespace in a xml document could be changed in any node and is valid until the next change.

*A namespace with prefix is only valid for nodes with this prefix.

*Form xpath point of view the used prefix in xml does not really matter. You need to know in wich namesapace (uri) the nodes are. Each namespace need to be register for use in xpaht with an unique namespace prefix.

*Avoid using this  *[name()='A'] or *[local-name()='A']`stuff.

A: When you use prefix for your xmlns I believe your xml should be :
<x:A xmlns:x="http://some.url/something">
  <x:B>
    <x:C>hello world</x:C>
  </x:B>
</x:A>

and the xpath expression /x:A/x:B/x:C/text() would yield 'hello world'


text:
Q: Best way to have a defined argument follow an argument with default value in ES6? In ES6 with default value syntax for function parameters, what's the best way to define the 2nd argument while using the default value for the 1st one in a function call?
function test(arg1 = 2, arg2 = 3) {
    return arg1 + arg2;
}

test() // returns 5;
test(undefined, 2) // returns 4; is this the most concise way?

Also, does the second method call work according to the standard? I only tested it with my cross-compiler which just inserts a statement setting the arguments value if it's equal to undefined; not sure if in actual ES6 engines it looks as the way the function was actually called.

A:
What's the best way to define the 2nd argument while using the default value for the 1st one in a function call?

Yes, passing undefined is the correct way.

Is this working according to the standard? Not sure if it actually looks at the way the function was called.

No, undefined is equivalent to a parameter not passed in the arguments list - in both directions. If you explicitly pass undefined, the default initialiser will be run just as if you had passed nothing. If you don't pass anything, all parameters (without defaults) will be assigned undefined just as if you had passed it explictly.
The only way to distinguish them would be using arguments.length.

Is this the most concise way?

Yes. Elisions (like in the array [,,,]) are syntactically invalid in function calls. You could shorten undefined to void 0, but that's not really idiomatic (only a minifier would do this).


text:
Q: ASP.NET Core routing error I have a route like http://localhost:63037/api/futuresMarginRuns/7/data which is working however another controller API with route http://localhost:63037/api/futuresMarginRuns/2018-07-11/data is not working, even the breakpoint in the controller API is not hit.
Here are the API signatures
    [HttpGet]
    [Route("/api/futuresMarginRuns/{id}/data")]
    public async Task<IActionResult> GetFuturesMarginRunDataAsync(long id)
    {
        var data = await _repository.GetAllAsync(id).ConfigureAwait(false);
        return Ok(data);
    }

    [HttpGet]
    [Route("/api/futuresMarginRuns/{runDate}/data")]
    public async Task<IActionResult> GetFuturesMarginRunDataByDateAsync(DateTime runDate)
    {
        var data = await _repository.GetAllAsync(runDate).ConfigureAwait(false);
        return Ok(data);
    }

In the first case I get json data but in the second one the breakpoint is not hit so looks like the route is not mapped to the API properly in which case I would expect an error, but i get empty []
How can I the API to work?
Thanks

A: You need to add some route constraints to your routes.  Route constraints tell the routing engine that if id is supposed to be an int, only match that route if the text in that spot can be converted to an int (and similarly with dates, etc).
So I would change your routes to the following:
[HttpGet]
[Route("/api/futuresMarginRuns/{id:long}/data")]
public async Task<IActionResult> GetFuturesMarginRunDataAsync(long id)

[HttpGet]
[Route("/api/futuresMarginRuns/{runDate:datetime}/data")]
public async Task<IActionResult> GetFuturesMarginRunDataByDateAsync(DateTime runDate)


text:
Q: App Domain Unloaded while debugging plugin I am creating a plugin on Disassociate message of Project (custom entity); having N:N relationship with User entity. It's not working. Here is the code.
        IOrganizationService service = localContext.OrganizationService;
        IPluginExecutionContext context = localContext.PluginExecutionContext;

        // Get Primary Entity
        EntityReference target = (EntityReference)context.InputParameters["Target"];

        if (target.LogicalName == "new_project" || target.LogicalName == "systemuser")
        {
            Relationship relationShip = (Relationship)context.InputParameters["Relationship"];

            // Get Related Entities
            EntityReferenceCollection relatedentities = (EntityReferenceCollection)context.InputParameters["RelatedEntities"];
            foreach (EntityReference rel in relatedentities)
            {
                // Check Related Entity Logical & Schema name
                if (rel.LogicalName == "new_project" && relationShip.SchemaName == "new_systemuser_new_project")
                {
                    Entity user = service.Retrieve("systemuser", target.Id, new ColumnSet(true));
                    Entity project = service.Retrieve("new_project", rel.Id, new ColumnSet(true));

                    // Grant access
                    RevokeAccessRequest revokeAccessRequest = new RevokeAccessRequest
                    {
                       Revokee=target,
                        Target = rel
                    };

                    service.Execute(revokeAccessRequest);
                }
            }
        }

But I am not able to debug this plugin using plugin registration tool.It returns the message "App Domain Unloaded".

I don't know what is wrong with this plugin. Please Help.

A: I have solved this problem.
I had registered this plugin in update message, then changed RegisterFile.crmregister
MessageName="Disassociate" and PrimaryEntityName=""
also changed the default constructor of the my plugin class.
base.RegisteredEvents.Add(new Tuple<int, string, string, Action<LocalPluginContext>>(10, "Disassociate", "", new Action<LocalPluginContext>(ExecutePreValidateProjectUpdate)));

Hope this will help someone facing same problem.


text:
Q: How to perform If Statement in Field Calculator of ArcGIS for Desktop? I have a shapefile containing two numeric fields ("Dist_1" and "Dist_2").  I want a Field Calculation that will populate an additional field ("Result") with one of three answers:
First if Dist_1 is greater than Dist_2 populate Result with 'True'
Second if Dist_1 is less than Dist_2 populate with 'False'
and Third if Dist_1 and Dist_2 are equal populate with "Equal"

A:
Parser:
Python
Code block:
def calc(f1,f2):

    if f1 > f2:
        return "True"
    elif f1 < f2:
        return "False"
    else:
        return "Equal"

Expression:
calc(!Dist_1!, !Dist_2!)
Or graphically (you cannot see all of the code block here unfortunately)


text:
Q: Can azure cognitive search provide aggregate sums? Suppose I have a lot of documents with facets and text fields, additionally they have a field like amount: 3. I want to support a query which returns the sum of the amount of documents matching the search criteria.
Is this a supported feature in Azure Cognitive Search? I can't seem to find the documentation on how to do a query which would return the aggregate sum, but I know you can do it in Elastic Search.
Can I do a raw lucene query?


text:
Q: Strange issue with loading an UIImage from core dara directly using KVC I am in the middle of an app project with core data where I stricty use KVC only with regard to the NSManagedObjects. The purpose of consequentally doing that is simply to get an understanding of advantages and disadvanages. I may have discovered a disadvangate. However, I cannot explain why.
I came across this when I used some very well established principle (used that in other apps already) of saving a scetch that the user drew with his fingers (a signature to a document) in core data and fetch and display or print to PDF respectively it later.
It turned out that I was able to get the UIImage from the view, store it in core data and instanly receive it from core data again using KVC (no save/fetch in between) and display it in another view for testing purposes. But I was unable to actually save it, fetch the data from persistant storage and re-display it on the screen.
So I did a lot of debugging, analysed the sqlite file etc. Eventually I nailed it down to the following strange behaviour:
Situation:
The image was stored into core data successfully by doing this:
[self.detailItem setValue:UIImagePNGRepresentation(image) forKey:kSignatureImage];

with image being an UIImage object and self.detailItem is the NSManagedOBject. Keys and references and everything is fine.
Then it comes to displaying the view again. The following is independent from whether the context was saved in between or even the app was closed and restartet or not:
self.signatureCanvas.image = [UIImage imageWithData:[self.detailTextLabel valueForKey:kSignatureImage]];

with self.signatureCanvas beeing an UIImageView subclass object. The image is not shown on screen.
NSData *data = [self.detailItem valueForKey:kSignatureImage];

NSLog(@"UIImage   a: %@", [UIImage imageWithData:[self.detailTextLabel valueForKey:kSignatureImage]]);
NSLog(@"UIImage   b: %@", [UIImage imageWithData:data]);

self.testImage.image =  [UIImage imageWithData:[self.detailTextLabel valueForKey:kSignatureImage]];

self.signatureCanvas.image = [UIImage imageWithData:data];

self.testImage is a second plain UIImageView withn the same view (but smaller). Now the image is visible in signatureCanvas but not in testImage. (could be vice versa, tried that)
The output give a hint on what was happening but no actual explanation:
2013-03-22 12:43:37.746 MyApp[1595:c07] UIImage   a: (null)
2013-03-22 12:43:37.769 MyApp[1595:c07] UIImage   b: <UIImage: 0x7c973a0>

Until now I would have thought that the lines of code were kinda equivalent and that the compiler may even optimize the data object away. But why is the image (null) in one case and not in the other.
So I found the problem root cause and a workaround. Therefore this is not urgent any more. But I do not understand it. Any clues?
Environment is: SDK 6.1, xcode 4.6, ARC, core data on sqlite, iPad only so far. All this happens in a UITableViewCell subclass (prototype cell within storyboard) naturally in a UITableViewController subclass.

A: I assume that self.detailTextLabel in
self.testImage.image =  [UIImage imageWithData:[self.detailTextLabel valueForKey:kSignatureImage]];

should be self.detailItem.


text:
Q: A nonrectifiable curve $C$ I was asked by one of my student to prove the following problem:

Prove that the graph of the continous function
  $$
y=f(x) = \left\{
        \begin{array}{ll}
            \sqrt{x}\cos\left(\pi/x\right) & \quad 0<x \leq 1 \\
           0 & \quad x = 0
        \end{array}
    \right.
$$
  shown as

is a nonrectible curve $C$.

I think, I should prepare a solid judgment based on discontinuity of $f'(x)$. What do you think? Please make me sure. Thanks for your time.

A: I think it would be more convincing to estimate the length of each zig or zag its vertical height, and then show that the sum of these (under)estimates does not converge.
More precisely for $n\ge 2$, the length of the part of the curve between $x=\frac1n$ and $x=\frac{1}{n-1}$ is at least $\sqrt{\frac1n}$, and $\sum_n n^{-1/2}$ grows faster than the harmonic series.

A: Find a lower bound for the length which is easy to calculate.
Solve $f(x)=0$ and $f(x)=+-\sqrt{x}$.
Consider the poligonal made joining those points, show it's a lower bound.
Calculate the length of this poligonal (it'll be an infinite sum instead of the original integral), in case it's infinite as the length of the curve is bigger it'll be infinite too.


text:
Q: Spring Boot, cannot use thymeleaf in html file SpringBoot maven project using NetBeans 8.1.
If I create a html file inside templates folder in src/main/resources and i add xmlns:th="http://www.thymeleaf.org" to the html tag I have the error Attribute with  the local name "xmlns:th" is not serializable as XML 1.0.

    <title></title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

thymeleaf dependencies are declared in pom.xml and downloaded in Dependencies.

A: I'm using the following without errors:
<!DOCTYPE html>

...rest of the file content...

A: Mine is defined like this:


text:
Q: Wordpress website - Lost I had problems in my public_html directory in my web hosting.  I deleted the public_html then i upload the same directory again (public_html) with sames pages, files, everything the same.
When  i tried to open my website, the wordpress installer came, I lost my wordpress website and everything.
What should i do ? i have my database and my public_html, I tried to restore the database with the public_html folder, my theme is working but all the posts, contencts, plugins, widgets have been removed. It's like i just installed the theme right now :/
If i contact the hosting service, they should have done a backup for my wordpress and every file in the hosting ? or a system restore.. i don't know

A: The public_html folder does not contain your database.  You need to login to CPanel and use the database restore tool. Ask your web host to assist if you're not sure about this. Almost everything that makes up your website is contained in the database, without it you will just have a blank theme with no pages (other than the theme default ones) and posts.
I recommend making a full site backup as well as a full database backup in future.  Speak to your host about setting this up and possibly scheduling it to happen automatically if you're not sure.


text:
Q: expression in join clause? Oracle tables
The following query works as START_TIME_ and DT.LABEL_DATE_TIME_15MIN_INT output is like for like.  I have to admit it's the first time I've written a join like this, is it acceptable or is there a more efficient/proper way of accomplishing this?
select
  A.ID,
  trunc(A.START_TIME,'dd') + (round(to_char(A.START_TIME,'sssss') / 900) / 96) as START_TIME_,
  DT.LABEL_DATE_TIME_15MIN_INT
from TBL_A A
  inner join DATE_TIME DT
    on ((trunc(A.IN_TIME_START,'dd') + (round(to_char(A.IN_TIME_START,'sssss') / 900) / 96)) = DT.DATE_TIME_15MIN_INT)
order by A.ID;

Reason for approach: A.START_TIME is TIMESTAMP(6) GMT-5 DT table has EPOCH time Keys in GMT with corresponding "Formatted Labels" adjusted to GMT-5.  Instead of converting A.START_TIME to EPOCH, adjusting for timezone, and joining on the key I performed the arithmetic to A to the correct 15min interval then joined to the label.  Am I missing a really simple solution here?

A: I would go for a more concise approach:
SELECT
    a.id,
    a.start_time_,
    dt.label_date_time_15min_int
FROM
    date_time dt
        JOIN (
            SELECT
                id,
                TRUNC(in_time_start,'dd') + (ROUND(TO_CHAR(in_time_start,'sssss') / 900) / 96) AS in_time_start_,
                TRUNC(start_time,'dd') + (ROUND(TO_CHAR(start_time,'sssss') / 900) / 96) AS start_time_
            FROM
                tbl_a
        ) a ON a.in_time_start_ = dt.date_time_15min_int
ORDER BY
    a.id
;

But fundamentally there's not much difference. Your join is valid, and you could also put it in the where clause if you wanted to. At this point there's not much you can do to optimize it without structural and applicative changes.


text:
Q: How to handle foreign key in FactoryGirl I have a user model and a follower model, such that a user can have many followers. So in schema of follower model I have user_id column and a follower_by_user_id column. So in follower model a user can be followed by many followers. User id's are stored in user_id column and followers id's are  whose id's are stored in  as followed_by_user_id.
class User < ActiveRecord::Base
 has_many :followed_users, :class_name => 'Follower', :foreign_key => 'user_id'
 has_many :followers, :class_name => 'Follower', :foreign_key => 'followed_by_user_id'

 validates :email, presence: true, format:{ with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i}

 validates :name,presence:true
end

Above is user model
class Follower < ActiveRecord::Base
 belongs_to :user
 belongs_to :followed_by_user, :class_name => 'User', :foreign_key => 'followed_by_user_id'

 validates :user, :followed_by_user, presence:true
 validates_associated :user, :followed_by_user
end

above is follower model
FactoryGirl.define do
factory :user do
  name {Faker::Name.name}
  email {Faker::Internet.email}
end

factory :follower do
  user
  followed_by_user_id
end

followed_by_user_id is basically a user id only, or we can say user_id is foreign key for followed_by_user_id column. Im plain English followed_by_user_id is an id of an user who is following to some other user. So If any body can help how to include this foreign key relationship in follower factory for follower_by_user_id column?
Thanks in advance.

A: You don't need so much complexity, use just:
followed_by_user factory: :user

This works like a charm.

A: You can use association in your factory, like this (more info in the docs):
association :followed_by_user, factory: :user


text:
Q: Use onActivityResult to call a function I have an PopUpActivity which pops up a window and i'm very satisfied with that.
However, I want to be able to return information from the popup window back to the parent activity, but also be able to call a function on the parent activity once the popup window is closed. Could someone help me?
Here is my code in the PopUpActivity:
public void closePopUpAndSendResultBack(){ // and how can i pass data to the previous activity?
    //https://developer.android.com/training/basics/intents/result
    Intent data = new Intent();
    data.putExtra("data", "yo");
    //startActivityForResult(data, 1);  // gives me the error : android.content.ActivityNotFoundException: No Activity found to handle Intent { (has extras) }
    setResult(Activity.RESULT_OK, data);
    finish();

}

and here is my parent(MainActivity) function that I want to get called once the popUpWindow is closed:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    if (requestCode == 1) {
        if (resultCode == RESULT_OK) {

            nameTextField.setText(""); // how can i get Yo inside here?
            showTheButton(); // and how can this function get called?

        }

    }
}}

Also, here is how I make that window Pop up from my Mainactivity:
     theOkButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent pop_up_that_window = new Intent(MainActivity.this,PopActivity.class);
            pop_up_that_window.putExtra("first", "Velkommen du der!");
            startActivity(pop_up_that_window);

        }
    });

 }

Could someone help me please?

A: In MainActivity use:
theOkButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {

        Intent pop_up_that_window = new Intent(MainActivity.this,PopActivity.class);
        pop_up_that_window.putExtra("first", "Velkommen du der!");
        MainActivity.this.startActivityForResult(pop_up_that_window, 1);

    }
});

And still in MainActivity in onActivityResult() use this code:
String yo = data.getStringExtra("data")
nameTextField.setText(yo);


text:
Q: Pyparsing for Python 3 I have recently installed PyParsing, but I saw that it's only available on Python 2, but I use Python 3.
I just don't want to learn Python 2, so is there a way to configure/port PyParsing to Python 3?

A: My suggestion would be to learn python-2.x. It isn't exactly learning, since you already know the language, you just need to familiarize yourself with the syntax, for which this link and this link help.


text:
Q: Messages removed from Outlook 2013 are still preset in All Mail folder in Gmail (Google Apps) Currently I have only 2% free space left on my Gmail account (google apps). That's why I decided to create locally saved archive (.pst file) in my Outlook 2013.
All emails older than 24 months were moved succesfully - for both inbox and all mail folder. Inbox synced ok with Gmail web interface - only half of all threats are left, however all emails in Gmail\All Mail folder are left. They are not visible in Outlook anymore (only in my pst archive).
I am syncing via IMAP.
According to topic on another website I have set following settings, however it was not succesfull:

Can you advice anything to not delete emails in All Mail folder manually? I am running out of free space now.

A: Did you right click and choose subscribe ? I do not know outlook menu but from what I see in thunderbird there is a subscribe menu. It might be in the account settings dialog.
Below was suggested but that was when I did not understand the situation. Its to delete mails on the server (I thought they were deleted on client but not on server)
Are you using IMAP or POP? IMAP supports that feature you have posted in image.
Either way you can search for mails before a date, online in gmail.
https://mail.google.com/mail/u/0/?shva=1#apps/before%3A2012%2F1%2F1
Can use http://www.yuki-onna.co.uk/html/encode.html to encide decode the date part - before%3A2012%2F1%2F1
After search - Click the select all (checkbox), gmail shows a message on top of the mail list: All 20 conversations on this page are selected. Select all conversations that match this search
Click 'Select all conversations' and then delete.


text:
Q: jQuery / javascript caching elements for efficiency? Right so I guess the common sense is that for elements you're going to be accessing a lot, the best way is to cache them like so:
var myEl = $('.myclass');

And then you can just access $(myEl) in the future and you don't need to search the DOM again, correct? Ok lets say I have a fairly complex html structure where I need to access several different elements a lot, like 20-30. It's very ugly todo this type of thing 30 times!
var elA = $('.myela'),
    elB = $('.myelb');

Etc etc, you get the idea.. so is there anything "bad" in doing it like this, keep the same class on all those elements, but give them an unique id, then do this:
var myElementObject={};
$('.myelems').each(function(){
     myElementObject[$(this).attr('id')] = $(this);
});

This way it's like I get an object.whateverId and thats the cached element, so now I can use them as I like without re-querying the DOM all the time, is this assumption correct, is this a bad practice? How do you guys go about it?
Thanks!

A: If you're going to assign ids, then just use $('#id') since it uses getElementById which is very fast and probably is not much slower than putting them in some object hash.
Also consider applying a common class to these elements or grouping them in some other way so that you can cache $('.mycommonclass')

A: It's a good way to do it if you're sure that you're going to access these elements(else it would be wasted resources). Another small thing: it would be best if you access the element in your first example by using myEl and not $(myEl) since $(myEl) has to execute a function(jQuery).


text:
Q: Reading stream char by char I'm using this function to read, char by char, a text file or a stdin input
void readLine(FILE *stream, char **string) {
    char c;
    int counter = 0;

    do {
        c = fgetc(stream);
        string[0] = (char *) realloc (string[0], (counter+1) * sizeof(char));
        string[0][counter++] = c;
    } while(c != ENTER && !feof(stream));

    string[counter-1] = '\0';
}

But when I call it, my program crashed and I really don't know why, because I don't forget the 0-terminator and I'm convinced that I stored correctly the char sequence. I've verified the string length, but it appears alright.

A: This is an error:
do {
    c = fgetc(stream);
    // What happens here?!?
} while(c != ENTER && !feof(stream));

"What happens here" is that you add c to string before you've checked for EOF,  whoops.
This is very ungood:
    string[0] = (char *) realloc (string[0], (counter+1) * sizeof(char));

in a loop.  realloc is a potentially expensive call and you do it for every byte of input! It is also a silly and confusing interface to ask for a pointer parameter that has (apparently) not been allocated anything -- passing in the pointer usually indicates that is already done.  What if string were a static array?  Instead, allocate in chunks and return a pointer:
char *readLine (FILE *stream) {
// A whole 4 kB!
    int chunksz = 4096;
    int counter = 0;
    char *buffer = malloc(chunksz);
    char *test;
    int c;
    if (!buffer) return NULL;

    while (c = fgetc(stream) && c != ENTER && c != EOF) {
        buffer[counter++] = (char)c;
        if (counter == chunksz) {
            chunksz *= 2;
            test = realloc(buffer, chunksz);
        // Abort on out-of-memory.
            if (!test) {
                free(buffer);
                return NULL;
            } else buffer = test;
        }
    }
// Now null terminate and resize.
    buffer[counter] = '\0';
    realloc(buffer, counter + 1);
    return buffer;
}

That is a standard "power of 2" allocation scheme (it doubles). If you really want to submit a pointer, pre-allocate it and also submit a "max length" parameter:
void *readLine (FILE *stream, char *buffer, int max) {
    int counter = 0;
    int c;

    while (
        c = fgetc(stream)
        && c != ENTER
        && c != EOF
        && counter < max - 1
    ) buffer[counter++] = (char)c;
// Now null terminate.
    buffer[counter] = '\0';
}

A: Change this line
string[counter-1] = '\0';

to
string[0][counter-1] = '\0';

You want to terminate string stored at string[0].

A: There are a few issues in this code:

*

*fgetc() returns int.

*Don't cast the return value of malloc() and friends, in C.

*Avoid using sizeof (char), it's just a very clumsy way of writing 1, so multiplication by it is very redundant.

*Normally, buffers are grown more than 1 char at a time, realloc() can be expensive.

*string[0] would be more clearly written as *string, since it's not an array but just a pointer to a pointer.

*Your logic around end of file means it will store the truncated version of EOF, not very nice.