text:
Q: can not disable the data-val-date using .removeAttr("data-val-date"); inside my asp.net mvc I am working on an asp.net mvc-4 web application and i am using jQuery 1.11.2. and i have a field of type DateTime, where i defined a jQuery datepicker to populate its value as follow:-
@Html.DisplayNameFor(model => model.LiveDate)
@Html.TextBoxFor(model => model.LiveDate, new { @class = "datepicker", @Value = (Model != null && Model.LiveDate.HasValue) ? Model.LiveDate.Value.ToString("dd/MM/yyyy") : string.Empty }) *
@Html.ValidationMessageFor(model => model.LiveDate)

  $(".datepicker").datepicker({
            dateFormat: "dd/mm/yy",
            showOn: "both"

        });

here is the markup for the date field:-
<input Value="24/05/2016" class="datepicker" data-val="true" data-val-date="The field Live Date must be a date." id="LiveDate" name="LiveDate" type="text" value="24/05/2016 00:00:00" />

now when i try selecting a date from the jQuery date picker such as 17/05/2016 i will get the following error The field Live Date must be a date. only on Safari & Chrome web browsers, while on IE and Firefox it will work well. also if i select a date such as 01/05/2016 it will work on all the browsers,,, so can anyone advice on this please?
now i read a lot about this problem but could not find any approach that will work in my case.
Solution 1 as mentioned here linke, is to use the following script:-
$(function() {
    $.validator.methods.date = function (value, element) {
        if ($.browser.webkit) {

            //ES - Chrome does not use the locale when new Date objects instantiated:
            var d = new Date();

            return this.optional(element) || !/Invalid|NaN/.test(new Date(d.toLocaleDateString(value)));
        }
        else {

            return this.optional(element) || !/Invalid|NaN/.test(new Date(value));
        }
    };
});

but when i added this script inside the scripts section inside my view, i have noted that the client side validation for non-date fields have been disabled also,, which i do not want. for example if i leave a required int field empty , the page will reload before showing the validation error . this will happen when i added the above script, so seems the above script will affect non-date field client side validation also.
Solution 2 . is to use this inside my view, to remove the data-val-date,
$("input[data-val-date]").removeAttr("data-val-date");

now i added this at the end of my view, but it did not disable the client side validation for my Date fields.
so can anyone adivce on this please?

A: This worked for me:
$.validator.addMethod('date',
function (value, element) {
    return true; // since MVC4 data-val-date is put on EVERY vm date property. Default implementation does not allow for multiple cultures...
});

Put it in your script section.
Got this from this thread (although it wasn't the accepted answer).


text:
Q: Is there a mime type or file extension for a "\n" or a "Linebreak Separated Value" list? If a .csv mime type denotes a "Comma Separated Value" list, I would like to know if there is an equivalent for a list of values, with the delimeter being a \n linebreak?
I would rather use this, as my values that I am listing include commas, but not linebreaks.

A: What you are describing sounds like simply text/plain. While this sort of formatting is common, there is no explicit standard, and so, it would probably be futile for MIME to try to articulate one which genuinely provides value for interoperablility while being flexible enough for all the various uses of "data" text files.
(CSV is a thorny counter-example because there are several mutually incompatible dialects. Still, it is reasonably well-standardized in that everyone will think they know what you mean when you say CSV.)

A: A Tab Separated Value List, with the extension .tsv is the best alternative, given that it uses newlines as a delimiter on rows, and tabs as a delimiter on columns.
This also will grant expandability if you wish to ever add any additonal data to each list item, and even the added benefit of being able to import the item into a database. Just make sure the first line serves as a header for each column.

redpajama_set_name: RedPajamaStackExchange


text:
Q: jquery/css wrap text bottom up I am trying to wrap text in a div using css and/or jQuery such that the bottom line is the longest.
so rather than
__________
|this is |
|text    |
|________|

it would say
__________
|this    |
|is text |
|________|

I can easily wrap the text using
    white-space: pre-wrap;

But i can't find anything that would let me do this.
(one thought i had would be to reverse the text, find where the line wrapping happens, apply a
 in the same places, with the text going forward.. but i dont know how to check where the line wraps)

A: Their is a plugin in jquery called bacon
With this you can wrap text according to your needs in any shape you want, I know you have to do a stuff over it but I think it may help you .
$(".baconMe").bacon({
    'type' : 'bezier',
    'c1' : { x : 10,        y : 0  },
    'c2' : { x : -115,      y : 170 },
    'c3' : { x : 35,        y : 340 },
    'c4' : { x : 15,        y : 480 },
    'align'  : 'right'
}

A: I ended up taking the route, of reversing, checking where the line breaks were, and then inserting them accordingly. Please feel free to use my function. This function accepts a jQuery element (with text that already wraps), and re-wraps it's text upward.
function wrapUp(element){
    width = element.width();
    string = element.text().split(' ');
    element.text('');
    reversed = string.reverse();
    var height = 0;
    for (var i=0;i<reversed.length;i++){
        reversed[i] += ' ';
        element.text(element.text()+reversed[i]);
        if (height != element.height()){
            reversed.splice(i,0,"
");
            i++;
        }
        height = element.height();
        console.log(element.height());
    }
    element.html(reversed.reverse().join(''));
}


text:
Q: Saving html and inline styles - created by jquery ui draggable and resizable I created a layout builder using jQuery UI, it allow users to resize/ rotate / drag and change basic styles( background color, font size, etc) of selected element.
the elements included are: images, div, spans and svg.
my query is what would be correct approach on  saving this to the server side:

*

*Upon user clicking save, grab the content using .html() and place it in hidden textarea, once ready post the content to server using ajax.  but not sure if there are any limit on the size or  amount of data submitted this way.

*Save each element status individually (bit more complex, there can be few hundreds of elements) , will send ajax request every time a element is created or edited.

*other options...?

thanks,


text:
Q: how to scroll to top of the iframe I'm using a different website(already active) into my webpage, but that website page is too big in height. So after restricting its height to 100vh (or some height). Scrolling down through the iframe is okay, but I need a floating 'scroll to top button' for iframe which will bring the iframe scroll to the top (NOT the parent window scroll).
I have used this code in .ts file of Angular, and it worked for the parent window scroll, but NOT for <iframe>
P.S - I'm using Angular 7
scrollToTop(){
    window.scroll(0,0);
  }

.html code
<button (click)="scrollToTop()">TOP</button>
Thank you in advance.
Update: I have tried the following suggested way
document.getElementById("myIframe").scroll(0,0);
I'm able to print the innerHtml, that means getElementById is working fine, the issue is with .scroll(0,0) Had tried .scrollTo(0,0) & .scrollBy(0,0) too but results the same

A: Just do the same but replace the window with the iframe element:
document.getElementById(<iFrameId>).scroll(0,0);


text:
Q: INDEX Creation Advice Oracle I have a table that has time data of 2 billion records obtained from the clients. The data has two main columns, date and entity_id.
The attributes date, and entity_id would make a unique pair.
Data is made into range partitions on the date field across several tablespaces.  However, the script to create the index is a normal CREATE INDEX script which does not mention any tablespace or partition name.
I would like to create a combined index on both columns as the queries could use both columns, however the index data file exceeds disk space availability.  I am not sure of the choice of index type.
I do not want to touch the existing index.
create table interval_date
(
  person_id   NUMBER(5) NOT NULL,
  last_name   VARCHAR2(30),
  dob         DATE
)
partition by range (dob)
INTERVAL(numtoyminterval(1,'MONTH'))
STORE in (uwdata)
(
  partition p1 values LESS THAN (to_date('2008-03-15','YYYY-MM-DD'))
)

A: Whether you use a local index or a global index will have (practically) no impact on the amount of space required for the index.  If you are running out of space to create the index, you'll need to allocate additional disk space to the tablespace (or tablespace(s) if you create a local index where the index partitions are stored in different tablespaces).  If you are building an index that involves the column you are partitioning on, you would almost always want to create a local index-- there is no benefit to creating a global index in this case.
Assuming that the dob column stores dates of birth and that the time component of that column is always set to midnight, you can probably reduce the space required for the index by making the dob column the leading column of the index and by using index compression.  In your case, you probably want to specify COMPRESS 1 since you would only want to compress the dob column, not the person_id column assuming that person_id has many fewer repeated values.


text:
Q: Странное поведение функции any hits = [
    [False, False, False],
    [False, False, False],
    [False, False, False],
]

print(any(hits))

Почему возвращает результат True?

A: Потому что any не просматривает значения во вложенных списках. Python любой непустой список интерпретирует как True, поэтому и результатом является True. Если вы хотите просмотреть все значения, то это можно сделать так:
print(any(map(any, hits)))


text:
Q: Google spreadsheet: Value parameter can not be parsed I'm using this script to integrate ImportJSON inside my google sheet.
The command I'm performing is:
=IF(B4="";"";VALUE(ImportJSON("https://min-api.cryptocompare.com/data/price?fsym="&B4&"&tsyms=USD";"/USD";"noHeaders";$L$1))*$C$2)

Where B4 contains: "BTC" and this is the value I got returned.
Now I see my value in an errorbox:

Value parameters 1423.42 can not be parsed to a number.

The number contains a dot ('.'). I don't know if that's the problem?
Someone knows how to fix this in my case?

A: This formula gives no error for me:
=IF(B4="","",VALUE(ImportJSON("https://min-api.cryptocompare.com/data/price?fsym=BTC&tsyms=USD","/USD","noHeaders","/feed/entry/title,/feed/entry/content")))

A: This worked for me
=IF(B4="";"";VALUE(substitute(ImportJSON("https://min-api.cryptocompare.com/data/price?fsym="&B4&"&tsyms=EUR";"/EUR";"noHeaders";$L$1);".";","))*$C$2)

A: You can try splitting the number which is being detected as text with "," and "." and then individually using VALUE function before combining it into desired output.


text:
Q: Core Data - Saving & Retrieving Attributes - Sample Code I've gone through quite a few Core Data tutorials. Most of them show how to add a new object to an entity and how to display the updated array of fetched objects.
My goal, however, is much simpler: I'd like one Table View Controller to change and save an attribute (in tableView didSelectRowAtIndexPath:) of an entity and another Table View Controller to display the new list of attributes of that entity (in tableView cellForRowAtIndexPath:). Like in the iPhone Sounds settings:
Sounds and
Ringtones
I still haven't figured out how the Managed Object should interact with those two Table View Controllers.
Do you know of a helpful tutorial/sample code explaining that very simple process?
Thanks very much in advance!
Saeppi

A: Check out this tutorial.core data.


text:
Q: parquet file format for snowflake connector I am writing a table in Hadoop to Snowflake using the Spark Connector, but my file in Hadoop is in Apache Parquet.
While writing in Snowflake it is writing in csv format, and it applies the default delimiter "," but I need to apply "^" as the delimiter. How can I do that?
df.write.format(SNOWFLAKE_SOURCE_NAME).options(sfOptions).option("dbtable", "t24122018").mode(SaveMode.Overwrite).save


text:
Q: rails associations & object identity: maintaining object identity through a series of changes `First of all, the fact that I am even asking this question implies that I am consciously choosing not to (strictly) obey the law of Demeter.
Since sometime (probably rails 3?) referring to model.association.first results in a new object each time, unless you use .to_a on the association:
campaign.campaign_shirts.first.to_s
=> "#<CampaignShirt:0x007fdd02c7fd58>"
campaign.campaign_shirts.first.to_s
=> "#<CampaignShirt:0x007fdd02ca6318>"
c.campaign_shirts.to_a.first.to_s
=> "#<CampaignShirt:0x007fdd02d13170>"
c.campaign_shirts.to_a.first.to_s
=> "#<CampaignShirt:0x007fdd02d13170>"

I've worked on several Rails 3/4 applications without even noticing this, probably because I do try to respect Demeter as much as is practical.
In this case I want Campaign to be in control, because it is a big state machine where many of its state changes involve transactionally coordinating changes in itself and various child objects.
Is there a way to freeze the association arrays at create and/or fetch time?
EDIT: I noticed almost immediately that they are frozen when you use Campaign.includes(...).find, which I am doing in my app. However I still have a problem in specs where the objects are factories created by FactoryGirl. Is there a way to say "freeze all the associations on this object" or do I have to call .to_a on each of them?
EDIT 2: I still have a problem when I refer to campaign through a belongs_to on user. (this seemed like a separate question, so I asked it here).
EDIT 3: the problem with the belongs_to includes extension was just syntax, so I'm removing the details of that.
So, my remaining problem is to get User.selected_campaign to act like it does in my app when it is built up by FactoryGirl. I'm going to try just doing a .reload at the start of each spec, which should trigger the includes extensions, at the cost of some spec performance.

A: I don't know the (gory) details of your setup, but what if you just memoize first on the Campaign object?
def Campaign
  def first_campaign_shirt
    @first_campaign_shirt ||= campaign_shirts.first
  end
end

I think this way you obey the Law of Demeter again? But it might get annoying if you need more  getters than just first_shirt. So consider this just a suggestion that won't fit in a comment box. :)

A: All of my in-app use cases were solved by carefully choosing where to add includes(..) to associations and scopes.
I was only able to solve the factory girl problem by calling reload on a factory object after creating it.


text:
Q: How to make a condition test correspond to subcolumns of an ODM decision table? I'm using ODM 8.5 (the successor to JRules), and I'm mimicking the steps described in IBM's tutorial - Editing Decision Tables; however, I can't generate a legal test.  In the tutorial, they create the following test:
the customer's age of the 'current rental agreement' is at least <min> and less than <max>

If I use Eclipse's completion feature () to generate legal completions for the table I want to create, I can't generate <min> or <max>, but I can generate <a string>.  However, this generates the following warning, and does not create subcolumns.

I don't know what the warning is trying to tell me (and I resent getting a warning when I am using a suggested replacement).  ("Lexicographically greater than" is a function I've defined that takes two string arguments; however, changing to a predefined function like "contains", makes no difference.)  If I manually change the occurrences of <a string> to <min> and <max>, I get an error:

How can I make my decision table act like the one in the tutorial?

A: One problem is how to use the <min> and <max> terms instead of <a string>.  This is dependent on the verbalization of the method created in the BOM, as described in the answer to this question.  In summary, you need to create a method with a verbalization like:
{0} is in the range {1,min} to {2,max}

to get the words "min" and "max" to appear.
Then, when you edit the Condition Column of your decision table, you create a Test something like:
the modified ep code of 'the work assignment input'
is in the range <min> to <max>

At this point, the Expression Placeholders text box will be empty.  Click OK in the Condition Column dialog and the appropriate min and max subcolumns will be produced in the table.  Thereafter, editing the Condition Column will include entries in the Expression Placeholders text box, that can be edited via the Sub-column Title text box.


text:
Q: PHP Iframe | Refresh every X time and flip through array of pages This is the javascript code for refreshing the content of the IFRAME every 60 seconds.
   <script type="text/javascript">
        var timer;
        function refreshIframe(){
        if(timer)
        clearInterval(timer)
        timer = setTimeout(refreshIframe,60000)
        var iframe = document.getElementById('dashboard');
        iframe.src='XXXX.php';
        }

        refreshIframe();
    </script>

The actual Iframe looks like this:
<iframe id="dashboard" width="100%" height="1250" src="XXXX.php" frameborder="0" style="border:0; padding:0; margin:0" allowfullscreen></iframe>

I have managed to refresh the page (content only), but currently I do not know where to start with multiple pages.
As an example I have page1.php, page2.php and page3.php and I would like that on load up of the page will be page1.php and after each refresh 1-2-3-1-2-3-1-2-3 .... continuously
Any suggestions, samples, where to move to make this happens will be appreciated.
Thank you
P.S. - v1
I can assume, that that should assign a link to a variable, then put this variable inside the array and scroll through them??? - This is an idea, I'm not 100% sure how to do it.

A: Take pages in an array pages and a counter count , which increment with every time src for iframe changes. And code will be like:
var timer,
        pages = ["abc.php", "cde.php", "xyz.php"],
        count = pages.length,
        i = 1;
function refreshIframe() {
    if (timer)
        clearInterval(timer)
    timer = setTimeout(refreshIframe, 60000)
    var iframe = document.getElementById('dashboard');
    iframe.src = pages[(i - 1) % count];
    i++;
}

refreshIframe();


text:
Q: Permanent magnet synchronous motor (PMSM) equivalent circuit I am trying to model a PMSM (permanent magnet synchronous motor) in LTspice and in order to do so I need to form an equivalent circuit. Through some research I believe the circuit should be formed in the dq reference frame as follows:

ref. https://ieeexplore.ieee.org/stamp/stamp.jsp?tp=&arnumber=6508040
with a back emf source along with resistor and inductance components.
Using the equations below and through the parks transformation I have made some progress:

I have tried rearranging the equations but the derivatives of the flux $$\frac{d\psi}{dt}$$ being unknown has confused me. Has anyone done something similar or can point me in the direction of some more comprehensive reading than I have found so far.
I have values for Ld, Lq, torque, resistance, initial values for va, vb and vc and the torque constant, voltage constant, speed and number of motor poles. Is this enough to work out the other values in the circuit. Are there any other parameters I require?
Any help would be much appreciated

A: This might give you an idea of how to do the derivative, you can use laplace transforms in LT spice.

The model will be difficult to run if the model needs to run on more than one frequency
\$\omega_r\psi_d\$ will be a difficult parameter if it needs to vary over the course of the simulation, if it doesn't , just hard code in the parameter with a b-source.
For \$\phi_q=L_q i_q\$a bv source with
the parameter of the be source being:
V=omega*((inductorvalue*I(inductor))
Inductorvalue is the value of the inductor I(inductor) is the current through the inductor. Omega could be a .param statement

If omega needs to vary then you will have to find some way to turn it into a voltage signal or current signal (I suppose you could use a circuit of some type) and then turn that into a V(omega) statement.

A: Speaking solely for the Q part, this is what you have:

And given the equations, the derivative part is marked with the arrow. That voltage is the actual derivative, so when you write the equation for the magnetomotive force for the R axis as \$-\omega\Psi_{dr}\$, you simply take the integral of it, as shown with B2.
Note: I am showing the induction motor equivalent circuit, it's up to you to transform to your own.


text:
Q: rm -f  command returns "invalid Argument" mv, chmod met with same output Below I've included a truss of the command, I've tried various ways to rm, but each one is met with the same output:
NOTE: this was run on an isilon NAS cluster (their Technical support is also stumped.)
Cluster-1# rm -f "478.ts"
rm: 478.ts: Invalid argument

Cluster-1# truss -a rm 478.ts
mmap(0x0,32768,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANON,-1,0x0) = 34366148608 (0x80061d000)
issetugid(0x80081da80,0x7fffffffefd8,0x40,0x0,0xffff80080081eaa8,0x0) = 0 (0x0)
lstat("/etc",{ mode=drwxr-xr-x ,inode=93955,size=3072,blksize=16384 }) = 0 (0x0)
lstat("/etc/libmap.conf",{ mode=-rw-r--r-- ,inode=102839,size=47,blksize=16384 }) = 0 (0x0)
open("/etc/libmap.conf",O_CLOEXEC,01760)         = 3 (0x3)
fstat(3,{ mode=-rw-r--r-- ,inode=102839,size=47,blksize=16384 }) = 0 (0x0)
mmap(0x0,47,PROT_READ,MAP_PRIVATE,3,0x0)         = 34366181376 (0x800625000)
close(3)                                         = 0 (0x0)
lstat("/usr",{ mode=drwxr-xr-x ,inode=23492,size=512,blksize=16384 }) = 0 (0x0)
lstat("/usr/local",{ mode=drwxr-xr-x ,inode=23507,size=512,blksize=16384 }) = 0 (0x0)
lstat("/usr/local/etc",{ mode=drwxr-xr-x ,inode=23846,size=1024,blksize=16384 }) = 0 (0x0)
lstat("/usr/local/etc/libmap.d",{ mode=drwxr-xr-x ,inode=24971,size=512,blksize=16384 }) = 0 (0x0)
open("/usr/local/etc/libmap.d",O_NONBLOCK|O_DIRECTORY|O_CLOEXEC,0165) = 3 (0x3)
__sysctl(0x7fffffffc0d8,0x2,0x80081e6bc,0x7fffffffc0d0,0x0,0x0) = 0 (0x0)
fstatfs(0x3,0x7fffffffc118,0x80081e6bc,0x7fffffffc0d0,0x0,0x0) = 0 (0x0)
mmap(0x0,36864,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANON,-1,0x0) = 34366185472 (0x800626000)
getdirentries(0x3,0x800623000,0x1000,0x800622028,0x0,0x0) = 80 (0x50)
lstat("/usr",{ mode=drwxr-xr-x ,inode=23492,size=512,blksize=16384 }) = 0 (0x0)
lstat("/usr/local",{ mode=drwxr-xr-x ,inode=23507,size=512,blksize=16384 }) = 0 (0x0)
lstat("/usr/local/etc",{ mode=drwxr-xr-x ,inode=23846,size=1024,blksize=16384 }) = 0 (0x0)
lstat("/usr/local/etc/libmap.d",{ mode=drwxr-xr-x ,inode=24971,size=512,blksize=16384 }) = 0 (0x0)
lstat("/usr/local/etc/libmap.d/mft.conf",{ mode=-rw-r--r-- ,inode=25013,size=50,blksize=16384 }) = 0 (0x0)
open("/usr/local/etc/libmap.d/mft.conf",O_CLOEXEC,0165) = 4 (0x4)
fstat(4,{ mode=-rw-r--r-- ,inode=25013,size=50,blksize=16384 }) = 0 (0x0)
mmap(0x0,50,PROT_READ,MAP_PRIVATE,4,0x0)         = 34366222336 (0x80062f000)
close(4)                                         = 0 (0x0)
munmap(0x80062f000,50)                           = 0 (0x0)
getdirentries(0x3,0x800623000,0x1000,0x800622028,0x50,0x8080808080808080) = 0 (0x0)
close(3)                                         = 0 (0x0)
munmap(0x800625000,47)                           = 0 (0x0)
open("/var/run/ld-elf.so.hints",O_CLOEXEC,0162)  = 3 (0x3)
read(3,"Ehnt\^A\0\0\0\M^@\0\0\0m\0\0\0\0"...,128) = 128 (0x80)
lseek(3,0x80,SEEK_SET)                           = 128 (0x80)
read(3,"/lib:/usr/lib:/usr/lib/compat:/u"...,109) = 109 (0x6d)
close(3)                                         = 0 (0x0)
access("/lib/libc.so.7",0)                       = 0 (0x0)
open("/lib/libc.so.7",O_CLOEXEC,030503770)       = 3 (0x3)
fstat(3,{ mode=-r--r--r-- ,inode=103356,size=1721078,blksize=16384 }) = 0 (0x0)
mmap(0x0,4096,PROT_READ,MAP_PRIVATE|MAP_PREFAULT_READ,3,0x0) = 34366181376 (0x800625000)
mmap(0x0,3821568,PROT_NONE,MAP_PRIVATE|MAP_ANON|MAP_NOCORE,-1,0x0) = 34368253952 (0x80081f000)
mmap(0x80081f000,1507328,PROT_READ|PROT_EXEC,MAP_PRIVATE|MAP_FIXED|MAP_NOCORE|MAP_PREFAULT_READ,3,0x0) = 34368253952 (0x80081f000)
mmap(0x800b8e000,49152,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_FIXED|MAP_PREFAULT_READ,3,0x16f000) = 34371854336 (0x800b8e000)
mmap(0x800b9a000,172032,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_FIXED|MAP_ANON,-1,0x0) = 34371903488 (0x800b9a000)
munmap(0x800625000,4096)                         = 0 (0x0)
close(3)                                         = 0 (0x0)
munmap(0x800629000,24576)                        = 0 (0x0)
mmap(0x0,102400,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANON,-1,0x0) = 34366197760 (0x800629000)
sysarch(0x81,0x7fffffffd0a8,0x4,0x0,0xffffffffffaac5e0,0xf0000000) = 0 (0x0)
sigprocmask(SIG_BLOCK,SIGHUP|SIGINT|SIGQUIT|SIGKILL|SIGPIPE|SIGALRM|SIGTERM|SIGURG|SIGSTOP|SIGTSTP|SIGCONT|SIGCHLD|SIGTTIN|SIGTTOU|SIGIO|SIGXCPU|SIGXFSZ|SIGVTALRM|SIGPROF|SIGWINCH|SIGINFO|SIGUSR1|SIGUSR2,0x0) = 0 (0x0)
sigprocmask(SIG_SETMASK,0x0,0x0)                 = 0 (0x0)
readlink("/etc/malloc.conf",0x7fffffffc7d0,1024) ERR#2 'No such file or directory'
issetugid(0x80096477e,0x7fffffffc7d0,0xffffffffffffff00,0x2,0x40,0xffffffff0fffffff) = 0 (0x0)
mmap(0x0,262144,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANON,-1,0x0) = 34366300160 (0x800642000)
munmap(0x800642000,262144)                       = 0 (0x0)
mmap(0x0,520192,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANON,-1,0x0) = 34366300160 (0x800642000)
munmap(0x800642000,253952)                       = 0 (0x0)
munmap(0x8006c0000,4096)                         = 0 (0x0)
sigprocmask(SIG_BLOCK,SIGHUP|SIGINT|SIGQUIT|SIGKILL|SIGPIPE|SIGALRM|SIGTERM|SIGURG|SIGSTOP|SIGTSTP|SIGCONT|SIGCHLD|SIGTTIN|SIGTTOU|SIGIO|SIGXCPU|SIGXFSZ|SIGVTALRM|SIGPROF|SIGWINCH|SIGINFO|SIGUSR1|SIGUSR2,0x0) = 0 (0x0)
sigprocmask(SIG_SETMASK,0x0,0x0)                 = 0 (0x0)
sigprocmask(SIG_BLOCK,SIGHUP|SIGINT|SIGQUIT|SIGKILL|SIGPIPE|SIGALRM|SIGTERM|SIGURG|SIGSTOP|SIGTSTP|SIGCONT|SIGCHLD|SIGTTIN|SIGTTOU|SIGIO|SIGXCPU|SIGXFSZ|SIGVTALRM|SIGPROF|SIGWINCH|SIGINFO|SIGUSR1|SIGUSR2,0x0) = 0 (0x0)
sigprocmask(SIG_SETMASK,0x0,0x0)                 = 0 (0x0)
geteuid()                                        = 0 (0x0)
sigaction(SIGINFO,{ 0x402280 SA_RESTART ss_t },{ SIG_DFL SA_RESTART ss_t }) = 0 (0x0)
ioctl(0,TIOCGETA,0xffffd970)                     = 0 (0x0)
lstat("478.ts",{ mode=-rwxrwxrwx ,inode=57420697287,size=0,blksize=8192 }) = 0 (0x0)
access("478.ts",2)                               = 0 (0x0)
unlink("478.ts")                                 ERR#22 'Invalid argument'
rm: write(2,"rm: ",4)                            = 4 (0x4)
478.tswrite(2,"478.ts",6)                                = 6 (0x6)
: write(2,": ",2)                                        = 2 (0x2)
mmap(0x0,262144,PROT_READ|PROT_WRITE,MAP_PRIVATE|MAP_ANON,-1,0x0) = 34366816256 (0x8006c0000)
stat("/usr/share/nls/C/libc.cat",0x7fffffffd290) ERR#2 'No such file or directory'
stat("/usr/share/nls/libc/C",0x7fffffffd290)     ERR#2 'No such file or directory'
stat("/usr/local/share/nls/C/libc.cat",0x7fffffffd290) ERR#2 'No such file or directory'
stat("/usr/local/share/nls/libc/C",0x7fffffffd290) ERR#2 'No such file or directory'
madvise(0x8006c1000,0x1000,0x5,0xaaaaaaaaaaaaaaab,0x8006c0030,0x800bc2c40) = 0 (0x0)
madvise(0x8006c2000,0x1000,0x5,0xaaaaaaaaaaaaaaab,0x7fffffffc790,0x800bc2c40) = 0 (0x0)
Invalid argument
write(2,"Invalid argument\n",17)                 = 17 (0x11)
sigprocmask(SIG_BLOCK,SIGHUP|SIGINT|SIGQUIT|SIGKILL|SIGPIPE|SIGALRM|SIGTERM|SIGURG|SIGSTOP|SIGTSTP|SIGCONT|SIGCHLD|SIGTTIN|SIGTTOU|SIGIO|SIGXCPU|SIGXFSZ|SIGVTALRM|SIGPROF|SIGWINCH|SIGINFO|SIGUSR1|SIGUSR2,0x0) = 0 (0x0)
sigprocmask(SIG_SETMASK,0x0,0x0)                 = 0 (0x0)
sigprocmask(SIG_BLOCK,SIGHUP|SIGINT|SIGQUIT|SIGKILL|SIGPIPE|SIGALRM|SIGTERM|SIGURG|SIGSTOP|SIGTSTP|SIGCONT|SIGCHLD|SIGTTIN|SIGTTOU|SIGIO|SIGXCPU|SIGXFSZ|SIGVTALRM|SIGPROF|SIGWINCH|SIGINFO|SIGUSR1|SIGUSR2,0x0) = 0 (0x0)
sigprocmask(SIG_SETMASK,0x0,0x0)                 = 0 (0x0)
sigprocmask(SIG_BLOCK,SIGHUP|SIGINT|SIGQUIT|SIGKILL|SIGPIPE|SIGALRM|SIGTERM|SIGURG|SIGSTOP|SIGTSTP|SIGCONT|SIGCHLD|SIGTTIN|SIGTTOU|SIGIO|SIGXCPU|SIGXFSZ|SIGVTALRM|SIGPROF|SIGWINCH|SIGINFO|SIGUSR1|SIGUSR2,0x0) = 0 (0x0)
sigprocmask(SIG_SETMASK,0x0,0x0)                 = 0 (0x0)
process exit, rval = 1
Cluster-1#```

A: The "Invalid argument" is likely coming from perror, reporting an errno of EINVAL set by unlink.
According to the man page, EINVAL can only occur with unlinkat, not for unlink, and the truss output shows an unlink call, so the situation seems impossible. Yet here we are.
I've found some other reports of utilities reporting 'Invalid argument' when the underlying filesystem couldn't handle the filename's encoding.
That's probably not the issue for you, since your filename seems to just be simple ASCII characters, but I would suspect that here too EINVAL is being set by filesystem-specific code being invoked by the unlink syscall, so this would depend what filesystem you're using.
On an Isilon NAS cluster, that's probably OneFS, unless it's in a strange location (like tmpfs, or a FUSE mount), or on removable media.
If that's the case, you'll probably need to get an actual engineer at Isilon to dig into the code to find out what could cause an EINVAL on unlink.


text:
Q: Infinite Scroller duplicating list results [ReactJS] so I'm working on a pokedex project that is linked to the PokeAPI. I have the main page that loads up the list ans the code for PokemonList.js is as follows:
import React, { Component } from "react";
import PokemonCard from "./PokemonCard";
import axios from "axios";
import InfiniteScroll from "react-infinite-scroller";

export default class PokemonList extends Component {
  state = {
    url: "https://pokeapi.co/api/v2/pokemon?limit=20&offset=0.",
    pokemon: null,
    itemsCountPerPage: 20,
    activePage: 1,
    count: 365,
    previous: null
  };

  loadPokemon = () => {
    axios
      .get(this.state.url)
      .then(res => {
        this.setState(prevState => {
          return {
            pokemon: [...prevState.pokemon, ...res.data.results],
            url: res.data.next
          };
        });
      })
      .catch(function(error) {
        // handle error
        console.log(error);
      });
  };

  async componentDidMount() {
    const res = await axios.get(this.state.url);
    this.setState({ pokemon: res.data["results"] });
  }

  render() {
    console.log(this.state.pokemon);
    return (
      <React.Fragment>
        {this.state.pokemon ? (

            <InfiniteScroll
              pageStart={1}
              loadMore={this.loadPokemon}
              hasMore={true}
              loader={

                  Loading ...

              }
            >
              {this.state.pokemon.map((pokemon, i) => (
                <PokemonCard
                  key={pokemon.name + i}
                  name={pokemon.name}
                  url={pokemon.url}
                />
              ))}
            </InfiniteScroll>

        ) : (

Loading Pokemon

        )}
      </React.Fragment>

      /*<React.Fragment>
        {this.state.pokemon ? (

            {this.state.pokemon.map(pokemon => (
              <PokemonCard
                key={pokemon.name}
                name={pokemon.name}
                url={pokemon.url}
              />
            ))}

        ) : (

Loading Pokemon

        )}
      </React.Fragment>*/
    );
  }
}

For some reason, the first 20 PokemonCards are loaded in from the API, but once I reach the 20th one, the infinite scroller loads up the first 20 again before eventually loading the next 20-40, then 40-60. It is only the first set amount that is duplicated.
This is a screenshot of the console being returned

As you can see, Bulbasaur is repeated after the 20th data in the list.

A: I ended up changing my state from
pokemon: null,

to
pokemon: [],

And I added
const pokemon = prevState.pokemon;

to my loadPokemon Function

A: In your componentDidMount function, you need to set your this.state.url, just like you do each time loadPokemon is called. You are calling the base url twice for the first page currently, once in componentDidMount and again in loadPokemon.

A: You should not called the loadPokemon function inside your componentDidMount(). Remove it and it should work as expected!
import React, { Component } from "react";
import PokemonCard from "./PokemonCard";
import axios from "axios";
import InfiniteScroll from "react-infinite-scroller";

export default class PokemonList extends Component {
  state = {
    url: "https://pokeapi.co/api/v2/pokemon?limit=20&offset=0.",
    pokemon: [],
    itemsCountPerPage: 20,
    activePage: 1,
    count: 365,
    previous: null
  };

  loadPokemon = () => {
    axios
      .get(this.state.url)
      .then(res => {
        this.setState(prevState => {
          return {
            pokemon: [...prevState.pokemon, ...res.data.results],
            url: res.data.next
          };
        });
      })
      .catch(function(error) {
        // handle error
        console.log(error);
      });
  };

  render() {
    console.log(this.state.pokemon);
    return (
      <React.Fragment>
        {this.state.pokemon ? (

            <InfiniteScroll
              pageStart={1}
              loadMore={this.loadPokemon}
              hasMore={true}
              loader={

                  Loading ...

              }
            >
              {this.state.pokemon.map((pokemon, i) => (
                <PokemonCard
                  key={pokemon.name + i}
                  name={pokemon.name}
                  url={pokemon.url}
                />
              ))}
            </InfiniteScroll>

        ) : (

Loading Pokemon

        )}
      </React.Fragment>
    );
  }
}


text:
Q: subset function in r returns o rows with unexplained reason I have the following kind of dataset.
'data.frame':   3204 obs. of  270 variables:
     $ group.investment              : chr  "27four Global Equity Prescient FF A1" "27four Global Equity Prescient FF A2" "27four Global Equity Prescient FF A3" "27four Global Equity Prescient FF A5" ...
     $ ASISA.classification          : chr  " Global EQ General" " Global EQ General" " Global EQ General" " Global EQ General" ...
     $ domicile                      : chr  "South Africa" "South Africa" "South Africa" "South Africa" ..

I wanted to subset by $ASISA.classification and have used the following codes alternatively. It returns o rows. I think, i missed something basic may be. Please, needing help.
dom.e <- filter(df$ASISA.classification, ASISA.classification == "Global EQ General")
dom.e <- df %>% filter(paste(ASISA.classification == "Global EQ General"))
dom.e <- df[df$ASISA.classification == 'Global EQ General',]


text:
Q: WPF datagrid not updating changes when bound I have a datagrid that's loaded when a combobox selection is changed, using the item directly from the combobox (it's bound to an object inside an entity framework context). But when I edit/add/remove on the datagrid and try to save the changes, it doesn't do anything, so I was wondering how would I fix that
public class ProgramControl: DbContext
{
    public DbSet<Asignaturas> Asigns { get; set; }

    public DbSet<Alumno> Alumnos { get; set; }

    public DbSet<Profesor> Profes { get; set; }

    public DbSet<Aula> Aulas { get; set; }

    public DbSet<Curso> Cursos { get; set; }
    public DbSet<Calificacion> Califications { get; set; }

    public ProgramControl()
    {
    }
}

public class Asignaturas
{
    [Key]
    public string Asign { get; set; }
    public List<string> correlativas = new List<string>();
    public List<Alumno> inscriptos = new List<Alumno>();
}

private void AlumnosPorMateria_Click(object sender, RoutedEventArgs e)
{
    legajoAlumno.Visibility = Visibility.Collapsed;
    elegirCursoTexto.Visibility = Visibility.Visible;
    elegirAsig.Visibility = Visibility.Visible;
    elegirCursoTexto.Text = "Elija la materia de la que desea ver los alumnos";
    var dset = db.Asigns;
    DbSet<Asignaturas> qry = dset;
    qry.Load();

    elegirAsig.ItemsSource = dset.Local.ToBindingList();
    alumnosGrid.Visibility = Visibility.Collapsed;
    confirmButton.Visibility = Visibility.Collapsed;
    cursoBox.Visibility = Visibility.Collapsed;
    confirmButton.Content = "Confirmar";
}

private void ElegirCurso_SelectionChanged(object sender,
    SelectionChangedEventArgs e)
{
    Asignaturas asig =(Asignaturas)elegirAsig.SelectedItem;
    db.Asigns.Load();
    var dset = db.Asigns;
    DbSet<Asignaturas> qry = dset;
    qry.Load();
    foreach (var item in dset)
    {
        if (item.Asign.Equals(asig.Asign))
        {
            asig = item;
        }
    }

    alumnosGrid.Visibility = Visibility.Visible;
    alumnosGrid.ItemsSource = asig.inscriptos;

    confirmButton.Visibility = Visibility.Visible;
}


text:
Q: tkinter button function calls: multiple presses calling same function multiple times I'm trying to make a Raspberry Pi Media Player, using omxplayer and tkinter.
I grab upto 16 video from a USB drive(or in local folder) and display them as thumbnails on a grid of buttons. When a button is pressed, it plays that video with omxplayer in fullscreen(at which point you cant access the tkinter window anymore until the video ends). Basically I want to enable selection of video only when there isn't a video playing already.
The problem I'm facing is with multiple presses on one button, or presses on other buttons before the video gets to play. This causes all the videos to queue up and immediately play one after another. I don't want subsequent presses to register until the first video (played from the first button press) is done playing. I try to set a boolean variable video_is_playing, and check its state in the function call, but it never enters the else case.
I tried to disable all buttons after you press any of them, then enabling them all after the video is done playing, I tried to use a variable to check if a video is done playing, and pretty much anything else I could think of doing to prevent multiple button presses.
Here is some parts of my code (sorry if it seems long, but I think everything included is relevant):
class TkinterGUI:
    def __init__(self):
        self.folder_name="videos"
        self.vid_path = f"{os.path.split(os.getcwd())[0]}/{os.path.split(os.getcwd())[1]}/{self.folder_name}/"
        self.videos = []
        self.video_is_playing = False
        self.vidbuttons = []

        for f in os.listdir(f"{self.vid_path}"):
            if '.mp4' in f:
                self.videos.append(f)
        self.videos.sort()
        self.videos_iterator = iter(self.videos)

    def pack_thumbnail(self, path, button):
        #putting video thumbnail in button with imageio
        pass

    def disable_buttons(self, window):
        for b in self.vidbuttons:
            b.config(state=tk.DISABLED)
        window.update()
        print(">>all buttons diabled")

    def enable_buttons(self, window):
        for b in self.vidbuttons:
            b.config(state=tk.NORMAL)
        window.update()
        print(">>all buttons enabled")

    def play_vid(self, i, j, window):
        try:
            self.disable_buttons(window)
            if self.video_is_playing == False:
                self.video_is_playing=True
                k = (i*4)+j
                video = self.videos[k]
                path = f"{self.vid_path}/{video}"
                print(f">>now playing: {video} of duration {self.vid_duration(path)}")
                omxp = Popen(['omxplayer', path])
                omxp.wait()
                print(f"video {video} is done playing!")
            else:
                print("a video seems to be playing already")
                return
        except Exception as e:
            print(e)
        finally:
            self.video_is_playing = False
            self.enable_buttons(window)

    def video_player_window(self):
        window = tk.Tk()
        window.attributes("-fullscreen", True)

        #left side frame(blank for now)
        frame1 = tk.Frame(master=window, width=200, height=100, bg="white")
        frame1.pack(fill=tk.Y, side=tk.LEFT)

        #main video player frame(contains 4x4 grid of video thumbnails)
        frame2 = tk.Frame()
        for i in range(4):
            frame2.columnconfigure(i, weight=1, minsize=75)
            frame2.rowconfigure(i, weight=1, minsize=50)

            for j in range(4):
                frame = tk.Frame(master=frame2, relief=tk.FLAT, borderwidth=1)
                frame.grid(row=i, column=j, padx=5, pady=5)

                vid=next(self.videos_iterator, "end")
                print(vid)

                if vid != "end":
                    button = tk.Button(master=frame, highlightcolor="black", text=f"Row {i}\nColumn {j}", command= partial(self.play_vid, i, j, window))
                    self.pack_thumbnail(self.vid_path+f"{vid}", button)
                    button.pack(padx=5, pady=5)
                    self.vidbuttons.append(button)
                else:
                    img = Image.open(f"vidnotfound.png")
                    img = img.resize((424, 224))
                    image = ImageTk.PhotoImage(img)
                    label = tk.Label(master=frame, text=f"Row {i}\nColumn {j}", image=image)#, compound='center')
                    label.image = image
                    label.pack(padx=5, pady=5)
        frame2.pack()
        window.bind("<Escape>", lambda x: window.destroy())
        window.mainloop()

tkin = TkinterGUI()
tkin.video_player_window()

I used functools.partial() to pass i, j indices to the play_vid function, so I can use those indices to know which video from the list to play. Here is everything I imported:
import tkinter as tk
import imageio
from PIL import ImageTk, Image
from pathlib import Path
from functools import partial

import subprocess
from subprocess import Popen

on a side note: is there a better way to accomplish what I want to do with the button grid? I'd like each button to call the same function but play different videos, is there any attribute I could use or anything?


text:
Q: How to auto attach any putty or kitty console to ConEmu Is it possible to auto attach any putty.exe or kitty.exe console windows to ConEmu?
If yes, then how can it be done?

A: I was looking to do the same thing and found this link
http://www.thecrumb.com/2013/03/04/configuring-conemu-and-putty/
I think it's basically what Maximus was saying but you will do this from inside ConEmu

A: Guys I just found the way! Totally possible without create shortcut for every session to load.
I just found that CMDER has a default task named {Putty}. It just launches Putty.exe directly (so putty.exe should be in path, or you should specify the full path of putty.exe).

Create a shortcut of CMDer with arguments:
<full-path-to-cmder.exe> /task Putty

Open it, and the Putty prompt shows. Load your session as usual, and it now shows in Cmder instead of putty, voila!

I knew such a common requirement has a solution in CMDER. Perfect!
Except that you have no control over the tab title, but we cannot ask for more...
EDIT:
I just found that we can specify the window title in Putty when we use Cmder, so now my solution becomes more than perfect.
In putty, we can set a window title in "Window" - "Behaviour", and in Cmder, we set the tab to use putty window title in "Main" - "Tab bar" - "Tab templates" - "Console" (%s represents the title, as shown in the tips above "Console".)
Another two screenshots:

A: As an alternative simply use SSH
ssh root@somehost

For example add the tools packaged with Git to your path
set PATH=%PATH%;C:\Program Files (x86)\Git\cmd

Or powershell path
# %UserProfile%\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
# Add linux tools from git
$env:Path += ";C:\Program Files (x86)\Git\bin"

*

*https://technet.microsoft.com/en-us/magazine/2008.10.windowspowershell.aspx
... And if going down that tangent consider only asking for your key passphrase once and Powershell with Posh git

*

*http://haacked.com/archive/2011/12/19/get-git-for-windows.aspx/

*http://haacked.com/archive/2011/12/13/better-git-with-powershell.aspx/

A: Single click? I think you are meaning "shortcut click".
So, change your shortcut properties.
Example 1
ConEmuC.exe /ATTACH /ROOT PuTTY.exe <your PuTTY switches>

Example 2
ConEmu.exe /single /cmd PuTTY.exe <your PuTTY switches>

Thought, you need to use full paths to executables.

A: AntonioCS has the correct link.
I was struggling with this too. The key is not to put the full path for putty in the conemu task command. Instead, make sure the path to putty is in your Windows, User profile environment variable, and then just call out putty by itself:
Putty.exe -new_console -load "(name of session)"

A: Adding to KCD's answer, yet another option is using SSH under Cmder for Windows[http://cmder.net/], as shown in this article:

*

*http://richb-hanover.com/cmder-for-windows-alternative-to-putty/
One needs only to type:

ssh user@hostname

A great advantage pointed in the article is that "Cmder is easy on the eyes, with attractive fonts, default Monokai color scheme, and resizable windows".


text:
Q: How to show the default beautiful popup message in ubuntu using python? http://tinypic.com/r/5dv7kj/7
How can i show the message like in the picture(top right)?
I'm new to linux and now tring to use pygtk to make a client application to show/popup some random hint/mems.
Using traditional winodw is OK,but this one is much more friendly to me.I have tried scanning through the pygtk guide but still missing the solution.Other
Is there any body could give me some hint?Any python GUI libs are also OK.

A: Quick and Dirty codes in python
import pynotify

# Only Text Notification
pynotify.init('Basic')
pynotify.Notification("Title", "simple text").show()

# Lets try with an image
pynotify.init('Image')
## Use absolute Path of the photo
pynotify.Notification("Title", "My Photo here!!", "/home/nafis/Pictures/me.png").show()

# Try Markup
pynotify.init("markup") ## all smallerCase "markup"
# but in parameter, first letter capital
pynotify.Notification("Markup",
  '''
  bold, italic, underline
  and even links are supported!
  '''
).show()

Also You can use it from shell (I use lubuntu, it works here.)
#!/bin/bash
### try it in terminal

notify-send -t 900 "Title" "Message"

A: It's an Ubuntu specific thing called NotifyOSD. There are examples of programming for it here.

A: A simple method without any additional packages.
you can execute commands via os.system.
import os

def message(title, message):
  os.system(f"notify-send '{title}' '{message}'")

message("Title", "Im message")


text:
Q: A2K Error 3011 on TransferSpreadsheet method I'm jut trying to import a spreadsheet into a table in Access 2000.
The spreadsheet is called cc-ledgcodebalances.xls with no field names.
My code is
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel3, "tmptmp", VFileName, 0

This seemed to work once but since then I now get this;

The Microsoft Jet database engine could not find the object
  ''cc-ledgcodebalances$''.  Make sure the object exists and that you
  spell its name and the path name correctly. 3011

Google searches aren't really turning up much that is useful. I'm trying to
import the whole thing and I don't think this is to do with named ranges.
Bit stumped by this, any help?

A: I answered this elsewhere that you asked it:
The error you're getting often occurs when the saved import spec is out of synch with either the source data or the target table. Try starting the import with the wizard, then load the saved import spec and it will likely throw an error or reveal what's no longer accurate.

A: I just had a similar problem under 2007 using direct range references instead of named ranges. It seems that dollar signs in the range reference can cause this error. Using Replace() on "$" and replacing with "" solved this issue in my case.


text:
Q: How does the switch statement work without the break I'm using the switch statement without the breaks and it seems it defaults to the last case even if it does not meet the condition.
function getLetter(s) {
    let letter;
    // Write your code here
    console.log(s[0])
    switch (s[0]){
        case 'a':
        case 'e':
        case 'i':
        case 'o':
        case 'u':
          letter = 'A';

        case 'b':
        case 'c':
        case 'd':
        case 'f':
        case 'g':
           letter = 'B';

        case 'h':
        case 'j':
        case 'k':
        case 'l':
        case 'm':
            letter = 'C';

        case 'n':
        case 'p':
        case 'q':
        case 'r':
        case 's':
        case 't':
        case 'v':
        case 'w':
        case 'x':
        case 'y':
        case 'z':
            letter ='D';
        }
  return letter;

}
console.log(getLetter('abcj'));

I expected the code to return A since it does not match any of the other cases statements but instead it returned D which does not match the expression. I did add the "break" and it worked as expected but I'm curious as to why what I had above did not work.

A: The switch statement continues to function without the break statement, but all cases following the first match are also processed. This implies that until a break or the end of the switch block is reached, each case is assessed and performed in succession if there is no break statement.


text:
Q: Check progress of download operation which started in background task I have an application where users can download some files and these files can be also downloaded via BackgroundTask triggered by push notification for example.
When the app is not running and I receive push notification, BackgroundTask starts to download the file. If I launch the app and the file is still downloading I would like to see progress of it.
I am able to get all downloading files BackgroundDownloader.GetCurrentDownloadsAsync().
If I have list of DownloadOperation, am I able to somehow check current progress of each operation? I mean if I can attach some IProgress<T> method to already running download operations.
Or is there any other approach how to check progress of DownloadOperation which started in BackgroundTask?

UPDATE
If I need to see progress of downloading file I can use this approach:
await downloadOperation.StartAsync().AsTask(token, new Progress<DownloadOperation>(...));

However, if I have just instance of DownloadOperation which is already downloading a file, How can I check progress of the operation and inform view about any progress? There is Progress property which has current progress, but there is not any "progress changed event" or something like that.

A: Handle ProgressChanged event of Progress<T> class.
  var progress = new Progress<DownloadOperation>();
      progress.ProgressChanged += ProgressOnProgressChanged;

 private void ProgressOnProgressChanged(object sender, string s)
    {
      // your logic here
    }

A: If you already have a DownloadOperation which was started elsewhere (in previous app run, background task) then you should just Attach to it. So as I think, after getting list of downloads, you should be able to attach to them, similar way like you have started:
var downloads = await BackgroundDownloader.GetCurrentDownloadsAsync();

foreach(var operation in downloads)
    await operation.AttachAsync().AsTask(token, new Progress<DownloadOperation>(...)); // of course for each operation there will be some changes


text:
Q: Transformation from XML to Excel 2010 file How do I create a Template for the XSLT transformation from XML file to Excel 2010 file or Word 2010 ?
This is our Template for the Transformation in Execel 2003. But now I need it for 2010 ?
Thanks for Help !
    <xsl:stylesheet xmlns="urn:schemas-microsoft-com:office:spreadsheet"
                xmlns:xs="http://www.w3.org/2001/XMLSchema"
                xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:xslex="urn:XsltExtension"
                xmlns:html="http://www.w3.org/TR/REC-html40"
                xmlns:o="urn:schemas-microsoft-com:office:office"
                xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
                xmlns:x="urn:schemas-microsoft-com:office:excel"
                version="2.0">
  <xsl:output method="xml" indent="yes" />
   <xsl:output method="xml" version="1.0"/>
   <xsl:template match="/NewDataSet">
      <xsl:variable name="elements"          select="xs:schema/xs:element/xs:complexType/xs:choice/xs:element/xs:complexType/xs:sequence/*" />

      <xsl:variable name="columnAppearances" select="ColumnAppearances/*" />

      <xsl:processing-instruction name="mso-application">
         <xsl:text>progid="Excel.Sheet"</xsl:text>
      </xsl:processing-instruction>
      <Workbook>
     <DocumentProperties xmlns="urn:schemas-microsoft-com:office:office" />
     <ExcelWorkbook xmlns="urn:schemas-microsoft-com:office:excel">
        <ProtectStructure>False</ProtectStructure>
        <ProtectWindows>False</ProtectWindows>
</ExcelWorkbook>
    </xsl:styleshee>

A: The open XML format used by Excel 2007+ consists of many XML's inside a ZIP package. The overall format is very different than the single-file XML format you mention. If you have a working solution now, I suggest you leave it as is, and use interop to convert it to a newer format. If you want to avoid interop, then you should use the OpenXML SDK instead. Doing it with XSLT would be very painful, if not impossible, and it is certainly off-topic here because it's a vast amount of work.


text:
Q: How can a PLSQL function return a result of an UPDATED...RETURNING query? I have a function which needs to:

*

*call another function

*and then return the result of an update statement

*not fail at atomicity

The function looks something like this:
CREATE OR REPLACE FUNCTION bal_update_balances(_acct Accounts, _amount INT, _currency INT)
  RETURNS SETOF Balances AS $$
DECLARE
  --   rv SETOF Balances;
BEGIN
  -- STEP 0: initialize balances (make sure they are present in the DB)
  PERFORM bal_initialize_balances(_acct, _currency);

  -- STEP 1: update & return balances
  RETURN QUERY (
    UPDATE Balances
    SET amount   = amount + _amount,
    updated_at = now()
    WHERE id IN (SELECT id
    FROM bal_get_balances(_acct, _currency))
    RETURNING *
  );
END;
$$ LANGUAGE plpgsql;

And so far I have failed thusly:

*

*if I try to put the output of the UPDATE..RETURNING in a variable (rv) and then return that variable:

*

*the declaration of the variable fails (rv SETOF Balances fails with invalid type name "SETOF Balances")

*and then how to put the output of the UPDATE..RETURNING into rv is also a good question

*if I try do do a RETURN QUERY then it fails with a syntax error at or near "UPDATE"

*if I try to wrap the update statement into a select statement(SELECT * FROM (UPDATE ... RETURNING)) then the compiler complains about the SET part of the nested update statement (syntax error at or near "SET")

*if I rewrite the whole thing to iterate over bal_get_balances(_acct, _currency)) output (a SETOF Balances) and do RETURN NEXT then again the problem 1-2 arises, how do I put the output of UPDATE..RETURNING into a psql variable?

The general idea is that I can run this function from the main software (Ruby, but irrelevant) from within a transaction as a simulation of sorts and then depending on some kind of complex business logic in the main app decide whether to go through with the transaction, or throw it away depending on the exact state of the balances - it's so far the only way I thought of to combine complex and very dynamic app  business logic with ACID requirements.

A: Use a variable of type record in a loop:
declare
    r record;
begin
    -- ...
    for r in
        update balances
        set updated_at = now()
        -- ...
        returning *
    loop
        return next r;
    end loop;

A: create table t(i serial primary key, x int);
insert into t(x) select random()*10 from generate_series(1,10);

create function f() returns setof t language plpgsql as $$
declare
  r t[];
begin
  -- How to get result into the variable and return it
  with a as (update t set x = x*2 where i > 5 returning *)
    select array_agg(a.*) into r from a;
  return query select * from unnest(r);

  -- How to return result of update (just remove parenthesizes around it)
  return query
    update t set x = x*2 where i > 5 returning *;
end
$$;

select * from f();

http://rextester.com/OUZM15941

A: just wrap it with CTE, like here:
t=# CREATE OR REPLACE FUNCTION s161()
  RETURNS SETOF s151 AS $$
DECLARE
BEGIN
  RETURN QUERY (
    with u as (UPDATE s151
    SET t= t||'***'
    RETURNING *
    )
    select * from u
  );
END;
$$ LANGUAGE plpgsql;
CREATE FUNCTION
Time: 1.109 ms
t=# begin;
BEGIN
Time: 0.117 ms
t=# select * from s161() limit 3;
       t
---------------
 s141***
 events***
 tg_rep_que***
(3 rows)


text:
Q: Build in branch tests in IntelliJ like those in Sonar I'm using now the build-in plugin for Code Coverage in IntelliJ. But I need more detailed information about my unit tests. How can I get some branch test statistic in this IDE ?

A: As far as I know, there's nothing comparable to how sonar branch testing works in IntelliJ out of the box.
For example if a line of code has multiple execution paths, IntelliJ will mark it green if just one of the paths is executed.
In contrast, sonar will tell you that (for example) 1 of 3 possible paths were executed.
Your best bet is to run sonar locally or on a server and use sonar a plugin, for which I see 2 options that seem to be fairly up to date:
http://plugins.jetbrains.com/plugin/7168?pr=idea
http://plugins.jetbrains.com/plugin/7238?pr=idea
Good luck.


text:
Q: MongoDB or CouchDB or something else? I know this is another question on this topic but I am a complete beginner in the NoSQL world so I would love some advice. People at SO told me MySQL might be a bad idea for this dataset so I'm asking this. I have lots of data in the following format:
TYPE 1
ID1: String String String ...
ID2: String String String ...
ID3: String String String ...
ID4: String String String ...

which I am hoping to convert into something like this:
TYPE 2
ID1: String
ID1: String
ID1: String
ID1: String
ID2: String
ID2: String

This is the most inefficient way but I need to be able to search by both the key and the value. For instance, my queries would look like this:

*

*I might need to know what all strings a given ID contains and then intersect the list with another list obtained for a different ID.

*I might need to know what all IDs contain a given string

I would love to achieve this without transforming Type 1 into Type 2 because of the sheer space requirements but would like to know if either MongoDB or CouchDB or something else (someone suggested NoSQL so started Googling and found these two are very popular) would help me out in this situation. I can a 14 node cluster I can leverage but would love some advice on which one is the right database for this usecase. Any suggestions?
A few extra things:

*

*The input will mostly be static. I will create new data but will not modify any of the existing data.

*The ID is 40 bytes in length whereas the strings are about 20 bytes

A: MongoDB will let you store this data efficiently in Type 1. Depending on your use it will look like one these (data is in JSON):
Array of Strings
{ "_id" : 1, "strings" : ["a", "b", "c", "d", "e"] }
Set of KV Strings
{ "_id" : 1, "s1" : "a", "s2" : "b", "s3" : "c", "s4" : "d", "s5" : "e" }
Based on your queries, I would probably use the Array of Strings method. Here's why:

I might need to know what all strings
  a given ID contains and then intersect
  the list with another list obtained
  for a different ID.

This is easy, you get one Key Value look-up for the ID. In code, it would look something like this:
db.my_collection.find({ "_id" : 1});

I might need to know what all IDs contain a given string

Similarly easy:
db.my_collection.find({ "strings" : "my_string" })
Yeah it's that easy. I know that "strings" is technically an array, but MongoDB will recognize the item as an array and will loop through to find the value. Docs for this are here.
As a bonus, you can index the "strings" field and you will get an index on the array. So the find above will actually perform relatively fast (with the obvious trade-off that the index will be very large).
In terms of scaling a 14-node cluster may almost be overkill. However, Mongo does support auto-sharding and replication sets. They even work together, here's a blog post from a 10gen member to get you started (10gen makes Mongo).


text:
Q: folder permissions: Full control granted to all users I'm working on an application which stores some files in the CommonApplicationData folder. My application has to modify these files. I managed to create a custom action to grant fullcontrol rights to my application folder in the CommonApplicationData folder. But this didn't solve the problem for non-admin users. When I log on as a user and try to modify one of these files, I get the "Access Denied" message.
How can I solve this problem? Thanks.
Here is the code which I used in the Custom Action:
public void GetUsers()
        {
            SelectQuery sQuery = new SelectQuery("Win32_UserAccount", "Domain='" + System.Environment.UserDomainName.ToString() + "'");
            try
            {
                ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(sQuery);
                foreach (ManagementObject mObject in mSearcher.Get())
                {
                    Permission(mObject["Name"].ToString());
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        private void Permission(string user)
        {
            string directory = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
            string CompanyFolderPath = Path.Combine(directory, "naseelco\\lms2004");
            DirectoryInfo myDirectoryInfo = new DirectoryInfo(CompanyFolderPath);
            DirectorySecurity myDirectorySecurity = myDirectoryInfo.GetAccessControl();
            string User = System.Environment.UserDomainName + "\\" + user;
            myDirectorySecurity.AddAccessRule(new FileSystemAccessRule(User, FileSystemRights.FullControl, AccessControlType.Allow));
            myDirectoryInfo.SetAccessControl(myDirectorySecurity);
        }

EDIT:
For those who would like to know the solution for this problem:
Instead of granting Access Rights to the parent folder, the individual files int that folder are granted Access Rights for each user. The Permission method in the code above has been modified as follows:
private void Permission(string user)
{
  string directory = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
  string filePath = Path.Combine(directory, "naseelco\\lms2004\\fms.txt");
  FileSecurity fSecurity = File.GetAccessControl(filePath);
  FileSystemAccessRule rule = new FileSystemAccessRule(user, FileSystemRights.FullControl, AccessControlType.Allow);
  fSecurity.SetAccessRule(rule);
  File.SetAccessControl(filePath, fSecurity);
}

A: A good solution is to grant full control to Everyone using xcacls.exe or any other ACL tool. This tool can be added as a custom action in your setup project.
Granting privileges to each user is not recommended because future accounts will not be covered. Also, doing this through custom code doesn't always work. Windows permissions are a bit tricky when it comes to controlling them through code.


text:
Q: How can I change the bitmap in a PPT picture? The answer here doesn't replace the bitmap, it adds to it. Is there a way to replace the bitmap in a picture?
Using PowerPoint COM interop (not VSTO).
The code is:
        /// <summary>
        /// Create or update a picture (bitmap) tag.
        /// </summary>
        private static PowerPointTagLocation CreateOrUpdatePictureTag(PowerPointTagLocation tagLoc, bool isUpdate, Image picture,
            string text, Slide slide)
        {

            // get a unique name for the picture
            string name = FileUtils.MakeValidFileName("wr_bitmap", true) + rand.Next(9999);
            // we need a physical file as the bitmap to display.
            string filename = name + ".png";
            filename = Path.Combine(Path.GetTempPath(), filename);
            if (File.Exists(filename))
            {
                Trap.trap();
                File.Delete(filename);
            }

            // if it's an update for a picture, we just update the AlternativeText.
            // And the bitmap if we get it.
            if (isUpdate && tagLoc.IsPicture) {
                tagLoc.TagShape.AlternativeText = text;
                if (picture != null) {
                    picture.Save(filename, ImageFormat.Png);
                    tagLoc.TagShape.Fill.UserPicture(filename);
                    File.Delete(filename);
                }
                return tagLoc;
            }

            if (picture == null)
                CommonBitmaps.photo_scenery.Save(filename, ImageFormat.Png);
            else
                picture.Save(filename, ImageFormat.Png);

            Shape shape;
            using (Bitmap bitmap = new Bitmap(filename)) {
                PictHandler.GetPictureSize(tagLoc.Tag, bitmap, 0, out var width, out var height);

                // position/extent in points. Place in middle of slide
                float x, y;
                try
                {
                    PageSetup page = ((Presentation)slide.Parent).PageSetup;
                    x = (page.SlideWidth - (width / 20f)) / 2f;
                    y = (page.SlideHeight - (height / 20f)) / 2f;

                }
                catch (Exception) {
                    x = y = 0;
                }
                shape = slide.Shapes.AddPicture(filename, MsoTriState.msoFalse, MsoTriState.msoTrue, x, y, width / 20f, height / 20f);
                // set select
                shape.AlternativeText = text;
                shape.Name = name;
            }

            // copy properties across
//          if (copyPicture)
//              pic.AssignProperties(tagLoc.TagRange.Picture);
            // delete the old picture as we wrote a new one.
            if (isUpdate)
                tagLoc.Delete();

            // delete the temp file
            File.Delete(filename);

            return new PowerPointTagLocation(tagLoc.Tag, shape);
        }

A: I put this in as a support ticket to Microsoft and the answer I finally got back was you cannot replace the picture.


text:
Q: Listener en JavaFX Buenas noches, me he topado con un pequeño problema al escribir el código de una interfaz. La parte del código que falla es:
final BooleanBinding activarComprobacion = campo1.textProperty().isEqualsTo("");
activarComprobacion.addListener((ObservableValue<? extends Bolean> observable, Boolean oldValue, Boolean newValue) -> {
    System.out.println("Tendria que salir esto al seleccionar alguna opcion de campo1");
}

No da error de compilación ni nada por el estilo, de hecho, antes utilizaba un botón para la comprobación y todo iba bien. Dentro de la función lambda hacía varias cosas, pero lo he quitado porque era irrelevante.

A: he probado esta solución con un TextField y funciona haciendo uso de un ChangeListener. Hazme saber si resuelve tu problema, Saludos.
campo1.textProperty().addListener((observable, oldValue, newValue) -> {
        if(newValue.equals("")){
            System.out.println("Tendria que salir esto al seleccionar alguna opcion de campo1");
        }
    });


text:
Q: Black screen when swiping "after" with UIPageViewController subclass I tried looking for my answer in existing questions where people faced the same problem, but the solutions for those are things I already address. Here's my code:
AppDelegate.swift
import UIKit

@UIApplicationMain
final class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(_ application: UIApplication,
                     didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        let onboardingCoordinator = OnboardingViewCoordinator()
        let onboardingPageViewController = WarmPushPageViewController(coordinator: onboardingCoordinator)
        self.window = UIWindow(frame: UIScreen.main.bounds)
        guard let window = self.window else { return false }
        window.rootViewController = onboardingPageViewController
        window.makeKeyAndVisible()

        return true
    }
}

Your typical App Delegate, tried to keep it as small as possible.
Coordinator.swift
import UIKit

enum PageViewDirection {
    case before
    case after
}

typealias Index = Int

protocol PageViewCoordinator: class {
    var currentIndex: Index { get set }
    var viewControllers: [UIViewController] { get set }
    func present(direction: PageViewDirection) -> UIViewController?
}

OnboardingViewCoordinator.swift
import UIKit

final class OnboardingViewCoordinator: PageViewCoordinator {
    var currentIndex: Index
    var viewControllers: [UIViewController]

    init() {
        self.viewControllers = [
            OnboardingTaglineViewController(nibName: nil, bundle: nil),
            OnboardingSourcesViewController(nibName: nil, bundle: nil)
        ]
        self.currentIndex = 0
    }

    func present(direction: PageViewDirection) -> UIViewController? {
        switch direction {
        case .before:
            if self.currentIndex == 0 {
                return nil
            }
            self.currentIndex -= 1
            let beforeVC = self.viewControllers[self.currentIndex]
            return beforeVC
        case .after:
            if self.currentIndex == (self.viewControllers.count - 1) {
                return nil
            }
            self.currentIndex += 1
            let afterVC = self.viewControllers[self.currentIndex]
            return afterVC
        }
    }
}

WarmPushPageViewController.swift
import UIKit

class WarmPushPageViewController: UIPageViewController {
    var coordinator: PageViewCoordinator? = nil

    convenience init(coordinator: PageViewCoordinator) {
        self.init(transitionStyle: .scroll,
                  navigationOrientation: .horizontal,
                  options: nil)
        self.setViewControllers([coordinator.viewControllers[coordinator.currentIndex]],
                                direction: .forward,
                                animated: true,
                                completion: nil)
        self.coordinator = coordinator
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.delegate = self
        self.dataSource = self
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

extension WarmPushPageViewController: UIPageViewControllerDataSource {
    func pageViewController(_ pageViewController: UIPageViewController,
                            viewControllerBefore viewController: UIViewController) -> UIViewController? {
        guard let coordinator = self.coordinator else { return nil }
        guard let beforeVC = coordinator.present(direction: .before) else { return nil }
        return beforeVC
    }

    func pageViewController(_ pageViewController: UIPageViewController,
                            viewControllerAfter viewController: UIViewController) -> UIViewController? {
        guard let coordinator = self.coordinator else { return nil }
        guard let afterVC = coordinator.present(direction: .after) else { return nil }
        return afterVC
    }
}

Thanks in advance!
Best,
Kiren :)


text:
Q: How to solve this equation $ (c^2+v^2)(\dot u )^2 = (\dot v)^2$? $ (c^2+v^2)(\dot u )^2  = (\dot v)^2$
$\dot u$ means diffrential of u, and c is a constant,
does the answer is $u = \log(v+ \sqrt{v^2+c^2}) + constant$ ??

A: $$(c^2+v^2)\left(\frac{du}{dt} \right)^2=\left(\frac{dv}{dt} \right)^2$$
$$\frac{du}{dv}=\pm \frac{1}{\sqrt{c^2+v^2}}$$
$$u=\pm\int \frac{dv}{\sqrt{c^2+v^2}}$$
$$u=\pm \ln\left| v\pm\sqrt{c^2+v^2}\right|+C$$
In order to not loosing a part of the solutions, do not forget the $\pm$ and the absolute value.


text:
Q: Pandas sorting and merging df by date I have a problem with merging my data.
I have two tables. One with data about a customers order and the another one with shipment details.
An order is identified by the customer and the date the shipment has to be done (those are the keys)
the shipment can only be identified by the ordernumber and the date it is send.
I want to join both tables to see, what amount was ordered and shiped (to see if there are differences)
Here comes the clue. The dates (keys) are not the same and can be delayed by some days or be send ahead of time.
How can I join those tables? Between two orders of a customer no other shipment to that costumer is done.
Example of the data.
Indexe Customer Date       Amount
1.     12       2020-10-29    x
2.     12       2020-12-29    x
3.     14       2021-01-15    x
4.     15       2021-03-14    x
5.     16       2021-04-01    x
6.     16       2021-04-10    x

Table of shipments

Index Customer Date       Amount
1.    12       2020-11-01  x
2.    12       2021-01-05  x
3.    14       2021-03-16  x
4.    15       2016-05-12  x
5.    16       2017-03-16  x
6.`   16       2021-04-05  x
7.    16       2021-04-12  x

Outcome
Index  Customer Date_x      Date_y       Amount_x  Amount_y
1.     12       2020-10-29  2020-11-01     x        x
2.     12       2020-12-29  2021-01-05     x        x
3.     14       2021-01-15  2021-03-16     x        x
4.     16       2021-04-01  2021-04-05     x        x
5.     16       2021-04-10  2021-04-12     x        x

Many Thanks in advance.
I tried to cover all special cases.

A: I was did a not perfect solution. I cut the date so its presented as yyyy-mm and then merged both frames on key customer and date with an inner join. there are cases, where this solution is not working like row 1. in the example, but it was a quick fix for me.
I will not mark the question as answered, because this solution is nor fully accurate for the problem.


text:
Q: Javascript .test() & .exec() function inconsistent result? JS .test() & .exec() function produced inconsistent result, after execution the result flip.
while .match() still consistent
Is it because of the unicode ?

const REGEX = /@([+]?[a-z]+)\u00AD/gm;
const text = `@test`;

console.log('-------------------------------------------------------')
console.log(`REGEX.test(text) ${REGEX} ${text} ${REGEX.test(text)}`)
console.log(`REGEX.test(text) ${REGEX} ${text} ${REGEX.test(text)}`)
console.log(`REGEX.test(text) ${REGEX} ${text} ${REGEX.test(text)}`)
console.log(`REGEX.test(text) ${REGEX} ${text} ${REGEX.test(text)}`)
console.log('-------------------------------------------------------')
console.log(`REGEX.exec(text) ${REGEX} ${text}`, REGEX.exec(text))
console.log(`REGEX.exec(text) ${REGEX} ${text}`, REGEX.exec(text))
console.log(`REGEX.exec(text) ${REGEX} ${text}`, REGEX.exec(text))
console.log(`REGEX.exec(text) ${REGEX} ${text}`, REGEX.exec(text))
console.log('-------------------------------------------------------')
console.log(`text.match(REGEX) ${REGEX} ${text}`, text.match(REGEX))
console.log(`text.match(REGEX) ${REGEX} ${text}`, text.match(REGEX))
console.log(`text.match(REGEX) ${REGEX} ${text}`, text.match(REGEX))
console.log(`text.match(REGEX) ${REGEX} ${text}`, text.match(REGEX))


text:
Q: How to use multiple query on mongodb using pymongo? I have a collection on mongodb, which has 1000 object like this one:
{
"_id":3,
"list": ["item1","item2", "item3"]
}

And i have a python list of 10 item. And i want to check any object from the collection has values from the list or not.
I've tried to do this:
from pymongo import MongoClient

mylist = ["item4","item5", "item6", "item1"]
database_uri = "mongodb_uri"
client = MongoClient(database_uri)

collection = client["database"]["collection"]
exists = []
for i in mylist:
    data = collection.find_one({"list":i})
    if data:
        exists.append(i)
print (exists)

result:
['item1']

But it takes a long time to complete. I wanted to do this in a single query. How can i do this?

A: First, if possible, create a multikey index on the embedded list:
db.collection.createIndex({"list":1})

This will add a lot of storage, but it will improve your query response times a lot.
Next, you can do the same thing in a single query use $or or $in.
I'm not 100% sure of the syntax, but I think this should work:
exists = set([])
results = collection.find({"list":{"$elemMatch":{"$in":mylist}}})
for result in results:
  exists.update(result.list)

The downside of this is that you will send all records that matches any of the items to your python client, and let python do the extraction and sorting out.
You can also do the extraction and sorting server side, and only send the aggregated list of matched items to the python client, by using a mongo aggregation pipeline, but that's slightly more complicated.


text:
Q: Error in value[[3L]](cond) in shiny but runs locally I'm trying to deploy an app which runs flawlessly on my local machine. But the error message within the shiny logs doesn't help me at all. Is there any way to track down so I know at least where it occurs? Then I could at least figure out why it does..
The shiny log:
2022-05-23T07:08:50.240280+00:00 shinyapps[5948139]: ✔ dplyr   1.0.8     ✔ forcats 0.5.1
2022-05-23T07:08:50.240342+00:00 shinyapps[5948139]: ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
2022-05-23T07:08:50.240401+00:00 shinyapps[5948139]: ✖ dplyr::filter()     masks plotly::filter(), stats::filter()
2022-05-23T07:08:50.240455+00:00 shinyapps[5948139]: ✖ dplyr::group_rows() masks kableExtra::group_rows()
2022-05-23T07:08:50.240511+00:00 shinyapps[5948139]: ✖ dplyr::lag()        masks stats::lag()
2022-05-23T07:08:50.240568+00:00 shinyapps[5948139]: Registered S3 methods overwritten by 'ggfortify':
2022-05-23T07:08:50.240620+00:00 shinyapps[5948139]:   method                 from
2022-05-23T07:08:50.240939+00:00 shinyapps[5948139]:   autoplot.ets           forecast
2022-05-23T07:08:50.240886+00:00 shinyapps[5948139]:   autoplot.decomposed.ts forecast
2022-05-23T07:08:50.240673+00:00 shinyapps[5948139]:   autoplot.Arima         forecast
2022-05-23T07:08:50.240728+00:00 shinyapps[5948139]:   autoplot.acf           forecast
2022-05-23T07:08:50.240780+00:00 shinyapps[5948139]:   autoplot.ar            forecast
2022-05-23T07:08:50.241087+00:00 shinyapps[5948139]:   autoplot.stl           forecast
2022-05-23T07:08:50.240831+00:00 shinyapps[5948139]:   autoplot.bats          forecast
2022-05-23T07:08:50.241241+00:00 shinyapps[5948139]:   fortify.ts             forecast
2022-05-23T07:08:50.241285+00:00 shinyapps[5948139]:   residuals.ar           forecast
2022-05-23T07:08:50.241009+00:00 shinyapps[5948139]:   autoplot.forecast      forecast
2022-05-23T07:08:50.241192+00:00 shinyapps[5948139]:   fitted.ar              forecast
2022-05-23T07:08:50.241145+00:00 shinyapps[5948139]:   autoplot.ts            forecast
2022-05-23T07:08:50.241498+00:00 shinyapps[5948139]:
2022-05-23T07:08:50.241549+00:00 shinyapps[5948139]: The following object is masked from 'package:dplyr':
2022-05-23T07:08:50.241601+00:00 shinyapps[5948139]:
2022-05-23T07:08:50.241391+00:00 shinyapps[5948139]:
2022-05-23T07:08:50.241335+00:00 shinyapps[5948139]: Welcome! Want to learn more? See two factoextra-related books at https:// goo.gl/ve3WBa
2022-05-23T07:08:50.241653+00:00 shinyapps[5948139]:     combine
2022-05-23T07:08:50.241445+00:00 shinyapps[5948139]: Attaching package: 'gridExtra'
2022-05-23T07:08:50.241757+00:00 shinyapps[5948139]: Loading required package: RColorBrewer
2022-05-23T07:08:50.241822+00:00 shinyapps[5948139]: Loading required package: NLP
2022-05-23T07:08:50.241870+00:00 shinyapps[5948139]:
2022-05-23T07:08:50.241705+00:00 shinyapps[5948139]:
2022-05-23T07:08:50.241960+00:00 shinyapps[5948139]:
2022-05-23T07:08:50.242019+00:00 shinyapps[5948139]: The following object is masked from 'package:ggplot2':
2022-05-23T07:08:50.241915+00:00 shinyapps[5948139]: Attaching package: 'NLP'
2022-05-23T07:08:50.242063+00:00 shinyapps[5948139]:
2022-05-23T07:08:50.242115+00:00 shinyapps[5948139]:     annotate
2022-05-23T07:08:50.242163+00:00 shinyapps[5948139]:
2022-05-23T07:08:50.242215+00:00 shinyapps[5948139]:
2022-05-23T07:08:50.242267+00:00 shinyapps[5948139]: Attaching package: 'stopwords'
2022-05-23T07:08:50.242314+00:00 shinyapps[5948139]:
2022-05-23T07:08:50.242357+00:00 shinyapps[5948139]: The following object is masked from 'package:tm':
2022-05-23T07:08:50.242405+00:00 shinyapps[5948139]:
2022-05-23T07:08:50.242454+00:00 shinyapps[5948139]:     stopwords
2022-05-23T07:08:50.242585+00:00 shinyapps[5948139]:
2022-05-23T07:08:50.242687+00:00 shinyapps[5948139]: Warning in lapply(X = X, FUN = FUN, ...) : NAs introduced by coercion
2022-05-23T07:08:50.242749+00:00 shinyapps[5948139]: Warning in lapply(X = X, FUN = FUN, ...) : NAs introduced by coercion
2022-05-23T07:08:50.242854+00:00 shinyapps[5948139]: Error in value[[3L]](cond) :
2022-05-23T07:08:50.242798+00:00 shinyapps[5948139]: Warning in lapply(X = X, FUN = FUN, ...) : NAs introduced by coercion
2022-05-23T07:08:50.242907+00:00 shinyapps[5948139]:   invalid multibyte string at '<a0>38793<2e>49'
2022-05-23T07:08:50.242955+00:00 shinyapps[5948139]: Calls: local ... tryCatch -> tryCatchList -> tryCatchOne -> <Anonymous>
2022-05-23T07:08:50.242997+00:00 shinyapps[5948139]: Execution halted
2022-05-23T07:08:50.243047+00:00 shinyapps[5948139]: Shiny application exiting ...

The app consists of global.R, ui.R and server.R and consists in total of around 1300 lines.
Meanwhile, I tried to comment out quite a lot of code blocks but I didn't come any closer.

A: Motivated by the fact, that the error always occured immediately after loading the stopwords (which I wasn't aware of at the beginning at this is also the end of the code), I rearranged the package loadings slightly and since then it works.
It's weird because I didn't change anything related to this but however, it is working now. The order is now this:
library(tm)
library(tmap)
library(tidytext)
library(stopwords)
library(wordcloud)


text:
Q: Alternative to boost deadline timer In my app, i need to run the function once the time runs out or when some asynchronous operation completes (before the time runs out).
Boosts deadline_timer does what i need, it fires once the timer runs out, and when i cancel it. However, in my situation, i don't need to use the io_service and timers constructor won't let me ommit it.
I could ofcourse create a temp io_service, but i don't consider it wise.
Are there alternatives? What should i use to achieve what i want? Maybe there is a way to use boosts deadline timer without the ioservice?

A: you can implement Timer wheel (google for implementation), very accurate and light weighted timer


text: Q: Convert my server video url to rtsp url I am playing video from a server url in VideoView in Android. But I read that for playing video from server RTSP is necessary. I did not understand how I can convert my video in RTSP?


text:
Q: BEMSimpleLineGraph X-Axis Labels not showing for phones newer than iPhone 5 I've created a line graph using BEMSimpleLineGraph Pod, but, for the life of me, can't figure out why the x-Axis labels aren't showing up on any device newer that an iPhone 5.
EDIT: I should mention enableXAxisLabel = YES by default.
Here is the code to lay out the graph:
#import "WeightChartCell.h"

@implementation WeightChartCell

@synthesize viewCell, arrayPlots, myGraph, labelWeightHistory;

- (void)awakeFromNib {
}

- (void)layoutSubviews {
    [super layoutSubviews];

    float width = viewCell.bounds.size.width;

    self.myGraph = [[BEMSimpleLineGraphView alloc] initWithFrame:CGRectMake(-20, 40, width+20, 150.0)];
    self.myGraph.dataSource = self;
    self.myGraph.delegate = self;
    self.myGraph.colorTop = [UIColor whiteColor];
    self.myGraph.colorBottom = [UIColor colorWithRed:190/255.0 green:218/255.0 blue:246/255.0 alpha:1];
    self.myGraph.colorLine = [UIColor colorWithRed:124/255.0 green:181/255.0 blue:236/255.0 alpha:1];
    self.myGraph.colorPoint = [UIColor colorWithRed:124/255.0 green:181/255.0 blue:236/255.0 alpha:1];
    self.myGraph.widthLine = 3;
    self.myGraph.sizePoint = 10;
    self.myGraph.alwaysDisplayDots = YES;
    self.myGraph.colorXaxisLabel = [UIColor lightGrayColor];
    self.myGraph.colorBackgroundXaxis = [UIColor clearColor];
    self.myGraph.enableYAxisLabel = YES;
    self.myGraph.colorYaxisLabel = [UIColor clearColor];
    self.myGraph.colorBackgroundYaxis = [UIColor clearColor];
    self.myGraph.enableReferenceYAxisLines = YES;
    self.myGraph.colorReferenceLines = [UIColor lightGrayColor];
    self.myGraph.enableLeftReferenceAxisFrameLine = NO;
    self.myGraph.enablePopUpReport = YES;
    self.myGraph.enableReferenceAxisFrame = YES;

    [viewCell addSubview:self.myGraph];

    labelWeightHistory.text = NSLocalizedString(@"Progress", nil);
    [self sendSubviewToBack:self.myGraph];

}

- (NSInteger)numberOfPointsInLineGraph:(BEMSimpleLineGraphView *)graph {
    return [arrayPlots count];
}

- (NSInteger)numberOfGapsBetweenLabelsOnLineGraph:(BEMSimpleLineGraphView *)graph {
    return 1;
}

- (NSString *)lineGraph:(BEMSimpleLineGraphView *)graph labelOnXAxisForIndex:(NSInteger)index {
    NSString *dateStr = [[arrayPlots objectAtIndex:index] valueForKey:@"created_at"];
    // Convert string to date object
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-MM-dd"];
    NSDate *date = [dateFormat dateFromString:dateStr];

    // Convert date object to desired output format
    [dateFormat setDateFormat:@"d.MMM"];
    dateStr = [dateFormat stringFromDate:date];
    return dateStr;
}

- (CGFloat)lineGraph:(BEMSimpleLineGraphView *)graph valueForPointAtIndex:(NSInteger)index {
    NSInteger yPoint = [[[arrayPlots objectAtIndex:index] valueForKey:@"weight"] floatValue];
    return yPoint;
}

@end

It comes out as expected on an iPhone 5 device and the iPhone 5 simulator:

But they don't show up at all on anything newer than iPhone 5. This is for iPhone 5s:

A: Please see this issue on github. It contains a temporary fix while we work on the official fix.
Thanks!


text:
Q: Within a pnpm workspace, how to work with local copy of a fork of a public package I'm using pnpm and its workspace feature to build several apps that share some code put in private libraries.
Aside private dependencies, I also reference a bunch of public packages from the npm registry.
This is working fine.
However, the public reference are sometime facing some bugs I'd like to help to resolve. This requires to work on a fork of the project before eventually submitting a PR.
Pnpm allows to declare a dependency to a git project, but how can I reference the local clone of the forked library ?
I'd like to avoid having to push any code to the forked project unless it has been tested locally.
Because I'm working within a pnpm workspace, the workspace is itself a whole git repo, which doesn't allow me to work with the fork within my workspace

A: You can use a link. Just replace you dependency with a link with relative path to the forked repository. For instance:
{
  "dependencies": {
    "foo": "link:../foo"
  }
}

If this package is not a direct dependency of any of the project, use overrides:
{
  "pnpm": {
    "overrides": {
      "foo": "link:../foo"
    }
  }
}


text:
Q: Controlling a Minecraft server with Ruby on Rails I have a website I am running in rails. This is for testing and learning nothing fancy or that will have a lot traffic. I am running a minecraft server for friends and was wanting to create a rails app to interact with it. Just Because. My question is what would be the best way to do this. Once you start minecraft server it runs until you kill it. All log information is shown on the server screen as you play. You can type in commands on the server as well to control the world. So what I want is a way to record new info put out by server and log in the database as well as send new commands. If this is hard that is fine im just looking for experience.

A: The Minecraft server has output on both the stdout and stderr. It also takes input from stdin. For more information on Standard streams read the wikipedia article.
The project you're speaking of is pretty advanced, and requires knowledge Unix processes and threading.
Typically, your program would need to:

*

*create streams for stdout, stderr and stdin to streams which your program has a handle over

*fork
Then in the child process:

*

*redirect stdout, stdin and stderr to the created streams

*exec the Minecraft server

In the parent:

*

*start a thread that listens to the Minecraft server stdout and stderr

*start a thread that listens for stdin and can interact with the Minecraft server

*optionally, all the communication to the Minecraft server should be done inside it's own thread

If you're just starting out with Ruby/Rails or the other technologies mentioned this can be intimidating. A few years ago I wrote Tartar, a Rails application that does essentially what you're looking to do. I suggest having a look, perhaps it can help you get started. I would start in the minecraft:start rake task. Note that this was 2 years ago and it may not be compatible with the Minecraft server anymore.
NOTE: This will not work on Windows.


text:
Q: How to set data breakpoint from within C++ code on android? I have the following problem:
I need to set breakpoint on writing to some memory region. There is a string in that region, and it is somehow corrupted, I need to find how. Memory is allocated multiple times, so I need to set breakpoint each time it is allocated and remove it on deallocation.
It takes a lot of iteration for memory corruption to appear, so I can't do it manually. Is there any way to set data breakpoints from inside the program?
I found some documentation on debug registers, but I cannot get if they are useful to me.
mprotect is useless for me, as when I create a string big enough for mprotect, memory allocation changes and bug disappears. ASAN also didn't help, there is no corruption with it.
My program is written in C++ and Kotlin and is running on Android. Problem is purely in c++ part, kotlin at the moment only calls my c++ function.


text:
Q: How can I successfully configure Common.Logging? I'm attempting to use NuGet packages to configure Common.Logging to use NLog2 in an ASP.Net MVC project. Based on the information provided at the URLs below, I believe my loggers are configured properly, but I continue to get configuration errors.
Common.Logging Configuration Instructions
NLog Configuration Tutorial
I've added the following to web.config as per the instructions:
<configuration>
  <configSections>

      <sectionGroup name="common">

      </sectionGroup>
    </configSections>
    <common>
      <logging>
        <factoryAdapter type="Common.Logging.NLog.NLogLoggerFactoryAdapter, Common.Logging.NLog20">
            <arg key="configType" value="INLINE" />
        </factoryAdapter>
      </logging>
    </common>
    <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
      <targets>
        <target name="logfile" xsi:type="file" filename="e:\logfile.txt" layout="${date:format=yyyy/MM/dd HH:mm:ss} ${message}" />
      </targets>
      <rules>
        <logger name="*" minlevel="Trace" writeTo="logfile" />
      </rules>
    </nlog>
    <runtime>
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
        <dependentAssembly>
          <assemblyIdentity name="Common.Logging" publicKeyToken="af08829b84f0328e" culture="neutral" />
          <bindingRedirect oldVersion="0.0.0.0-2.0.0.0" newVersion="2.0.0.0" />
        </dependentAssembly>
      </assemblyBinding>
    </runtime>
</configuration>

As far as I can tell, this is everything I should need to do but I'm getting configuration errors when I try to run the web project...

Parser Error Message: An error occurred creating the configuration section handler for common/logging: Unable to create type 'Common.Logging.NLog.NLogLoggerFactoryAdapter, Common.Logging.NLog20'

Can anyone offer suggestions on what's missing or in error?

A: The problem seems to be that the default configuration added by the Common.Logging NuGet package (v2.0.0) is incorrect.
The runtime section in web.config needs to be changed to the following:
<dependentAssembly>
   <assemblyIdentity name="Common.Logging" publicKeyToken="af08829b84f0328e" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-65535.65535.65535.65535" newVersion="2.0.0.0" />
  </dependentAssembly>

Note the oldVersion value. This seems to be what was causing the error (at least based on the scenario that I outlined in the question above).
See also this related GitHub issue: Possible Issues with Common.Logging / Common.Logging.NLog20 NuGet packages.

A: Worked for me by using
<factoryAdapter type="Common.Logging.NLog.NLogLoggerFactoryAdapter, Common.Logging.NLog2">

instead of
<factoryAdapter type="Common.Logging.NLog.NLogLoggerFactoryAdapter, Common.Logging.NLog20">

notice 20 vs 2 at the end.


text:
Q: could I return a struct in main function? In C++ code, I want to return a struct in the function so that the function output can be called in Matlab. for example, when we create a DLL file, and call it in Matlab, the command in Matlab is usually written as:
  [output] = calllib(filename, function, arguments);

To my knowledge, return can give the output of the function, something like that:
int main(argument){
   .....;
   return output;
}

and the type of output should be the same as the type of the function(here, the function is main).
Could the type of the output be struct? or return multi results, like that:
int main(argument){
   .....;
   return output1, output2, output3;
}

Here, I paste my code, please help me to correct or give me some advice? Thanks a lot.
The cpp file is:
#define _CRT_SECURE_NO_WARNINGS
#include <string>
#include "pch.h"
#include "windows.h"
#include<vector>
#include<algorithm>
#include <iostream>
#include <stdio.h>

using namespace std;

void addStructFields(struct c_struct st, struct s_struct ot) {

    double* vector4;

    vector4 = new double[st.p5];

    int i = 0;
    while (i < st.p5) {
        vector4[i] = *st.p4;
        st.p4++;
        i++;
    }

    double t = st.p1 + st.p2 + st.p3 + vector4[st.p5 - 1];
    double t2 = st.p1 - st.p2 - st.p3 - vector4[st.p5 - 1];

    ot.o1 = t;
    ot.o2 = t2;

    //return 0;
};

the header file is :
#ifndef PCH_H
#define PCH_H

// add headers that you want to pre-compile here

struct c_struct {
    double p1;
    short p2;
    long p3;
    double* p4;
    int p5;
};

struct s_struct {
    double o1;
    double o2;
};

#ifdef __cplusplus
extern "C"
{
#endif
    __declspec(dllexport) void addStructFields(struct c_struct st, struct s_struct ot);

#ifdef __cplusplus
}
#endif

#endif


text:
Q: Storing streamed tweets in a list for further analysis I am building a data mining app to collect tweets using the Twitter streaming API (via tweepy) and run a suite of NLP algorithms on it. So far all I have been able to do is get the tweets to be written into an external file. Due to the volume of tweets I am going to collect is a 100 at a time (pretty small) and deployment concerns, I wish to collect these tweets to a dictionary or list for further analysis. However, I have failed in doing this. The code I have so far is given below:
import tweepy

class MyStreamListener(tweepy.StreamListener):
    def __init__(self, api=None):
        super(MyStreamListener, self).__init__()
        self.num_tweets = 0
        self.tweets = []

    def on_status(self, status):
        #print(status.text)
        self.num_tweets += 1
        self.tweets.append(status.text)
        if self.num_tweets > 100:
            return False

def getstreams(keyword):
    CONSUMER_KEY    = ''
    CONSUMER_SECRET = ''
    ACCESS_TOKEN  = ''
    ACCESS_SECRET = ''
    auth = tweepy.OAuthHandler(CONSUMER_KEY, CONSUMER_SECRET)
    auth.set_access_token(ACCESS_TOKEN, ACCESS_SECRET)
    api = tweepy.API(auth, wait_on_rate_limit=True)
    myStreamListener = MyStreamListener()
    myStream = tweepy.Stream(auth = api.auth,listener=myStreamListener)
    tweet_list = myStream.filter(track=[keyword])
    return tweet_list.tweets

getstreams('Starbucks')

However when I run this, all I get is:
AttributeError: 'NoneType' object has no attribute 'tweets'

pointing to the line:
return tweet_list.tweets

I'd be grateful if anyone could answer how to overcome this issue and shed insight on how to collect n number of tweets into a list.

A: You can use the on_data function in your class.
def on_data(self, data):
    # Converting data , which is an object, into JSON
    tweet = json.loads(data)

    # my_tweet is our list declared globally
    my_tweet.append(tweet)


text:
Q: JS: Find URLs in Text, Make Links What would be the following PHP code rewritten in JS be, so that url links inside of text blobs could be replaced with html links? I've started a jsfiddle.
<?php

// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

// The Text you want to filter for urls
$text = "The text you want to filter goes here. http://google.com";

// Check if there is a url in the text
if(preg_match($reg_exUrl, $text, $url)) {

   // make the urls hyper links
   echo preg_replace($reg_exUrl, "{$url[0]} ", $text);

} else {

   // if no urls in the text just return the text
   echo $text;

}
?>

A: Use this:
var text = "The text you want to filter goes here. http://google.com";
text = text.replace(
    /((http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?)/g,
    '$1'
);

Explanation:
The g here is a global flag; it will replace all urls.
I also added an capture group for the entire expression, so I could use the backreference $1.