text:
Q: React native firebase notification shows while the app is running I've made an app using react native firebase 5.6.0. I'm getting notifications from firebase and displaying them with this piece of code:
 this.notificationListener = firebase
  .notifications()
  .onNotification((notification: Notification) => {
    notification.android
      .setChannelId('channel')
      .android.setSmallIcon('ic_launcher')
      .android.setPriority(firebase.notifications.Android.Priority.Max)

      .android.setColor('#121243');

    firebase.notifications().displayNotification(notification);
  });

The problem is push notifications showing even when the app is on foreground and running. I want them to only show when the app is on background.

A: I've solved the problem using AppState
  this.notificationListener = firebase
  .notifications()
  .onNotification((notification: Notification) => {
if (AppState.currentState != 'active') {
    notification.android
      .setChannelId('channel')
      .android.setSmallIcon('ic_launcher')
      .android.setPriority(firebase.notifications.Android.Priority.Max)

      .android.setColor('#121243');

    firebase.notifications().displayNotification(notification);
}
  });

So if the app is in active state the notification won't show.


text:
Q: asyncpg: How to construct SET strings with parameters What is the correct way to pass in parameters in a SET query?
this will return asyncpg.exceptions.PostgresSyntaxError: syntax error at or near "$1"
import asyncio

import asyncpg

async def main():
    conn = await asyncpg.connect(user="xx", password="yy", host="127.0.0.1", database="my_db")

    # works
    await conn.execute("select $1", "1")

    identity = "arn:aws:sts::123456:assumed-role/thing_1"

    # fails
    await conn.execute("set session iam.identity = $1", identity)

asyncio.run(main())

A: asyncpg has a function for this:
await conn.execute("select set_config('iam.identity', $1, false)", identity)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Glyphs disappearing from PDF run running PDF/X-1a preflight My printer needs PDF/X-1a. I have a document created in indesign that has a lot of illustrations in PDF created by other applications. The original PDF of the entire document looks fine.
When I run the PDF/X-1a preflight in Acrobat I get errors that glyphs are missing in the embedded subset and special characters in the illustration PDFs get replace by boxes.
"Glyphs missing in embedded font"
The special characters are correct in the file before running the preflight.
How might I correct this?

A: If your main concern is printing the document, print it as an image, rather than as mixed text and image.
You can also export the document by "printing" the PDF to PDF, again, as an image, effectively transforming the glyphs in a font to an image.


text:
Q: How to detect that iOS locale is in a place where numbers use comma instead of period between whole & fractional parts? I have a special requirement to learn whether the current locale uses comma-based or period-based numbers. Is there a simple way to learn this?

A: - (NSString *) getDecimalSeparator
{
return [[NSLocale currentLocale] objectForKey:NSLocaleDecimalSeparator];
}

Will return current separator. I use it for generating valid CSV files.

A: I suggest taking a look at the NSNumberFormatter class:
NSNumberFormatter class reference
Programming guide on doing this through CoreFoundation:
Data formatting programming guide
Its good that you are spending time on this, in my application I made use of my own timestamp format, while the system allows you to pick your own timestamp format... needless to say I had some angry users.


text:
Q: Disable, or at least detect, automatic semicolon insertion I always code in strict mode hoping to be shielded(or at least forcibly told to change my code) from problems with the Javascript language like using deprecated methods or misinterpretable syntax.
However I hit this problem today and I was wondering whether there was any way to disable semicolon insertion in the browser or otherwise have similar-to-strict-mode 'compile'-time errors?
JS[H/L]int doesn't happen to be able to pick up where JS interpreters would insert semicolons and flag them for us to mitigate would it?

EDIT
JShint and JSLint both error if a new line is present before a semicolon is found after a the return keyword. However, I don't know about the other caveats regarding automatic insertion and whether they are each detected too.
Regardless, if an answer actually solves the 'disabling' part, that would be more relevant.

A: The expression after return keyword MUST ALWAYS start on the same line that the keyword is, this is not interpreter related, it's defined by the ECMAScript standard, it's a bad part of the language but if you respect the rules of writing the JS code described by Douglas Crockford then you'll not encounter this again.
From "JavaScript: The Good Parts" by Douglas Crockford (Appendix A.3 Awful Parts):

JavaScript has a mechanism that tries to correct faulty programs by automatically inserting semicolons. Do not depend on this. It can mask more serious errors.
It sometimes inserts semicolons in places where they are not welcome. Consider the consequences of semicolon insertion on the return statement. If a return statement returns a value, that value expression must begin on the same line as the return:

return
{
    status: true
};

This appears to return an object containing a status member. Unfortunately, semicolon insertion turns it into a statement that returns undefined. There is no warning that semicolon insertion caused the misinterpretation of the program. The problem can be avoided if the { is placed at the end of the previous line and not at the beginning of the next line:

return {
    status: true
};

Also see the code conventions for JavaScript by Douglas Crockford: http://javascript.crockford.com/code.html

A: Just thought I'd help anyone who comes across this question.
I've started using Google's Closure Comiler to minify JS for a project and it gave me a few handy warnings.
   $> java -jar google_closure_compiler.jar  --language_in=ECMASCRIPT5_STRICT --js_output_file 'min.js' 'file1.js' 'file2.js'
   file1.js:152: WARNING - unreachable code
               getSomething(function() { return this.doThingo(''); });
               ^

   file2.js:203: WARNING - Suspicious code. The result of the 'add' operator is not being used.
               ' to ' + (typeof obj);
               ^

   0 error(s), 2 warning(s)

The offending code blocks were as follows (the comments describe what the code was missing that the compiler alerted me to):
file1.js:150
    return generateSomeObject(bunch, of, arguments)
        //the period before the function call was missing
        getSomething(function() { return this.doThingo(''); });
}

file2.js:201
if (someCondition)
    //trailing plus was missing from this line
    throw 'Could not set ' + last + ' of ' + (typeof root)
        ' to ' + (typeof obj);
return old;

I don't know whether it will recognise all mistakes that the browser tidies up (so I probably won't mark this as an answer), but it does a lot more than YUI's minifier was doing for me (which was ignoring all of these cases).
Also, compared to YUI, the compiler is able to take in multiple file inputs and so can give me line numbers per file for errors, and doesn't error on/redeact the debugger keyword).
Hopefully it'll help you too.


text:
Q: How to create partitioned tables from templates in BigQuery? I would like to create new tables with a table template.
My template is partitioned and I would also like the newly generated tables to be partitioned as well, but, from my tests, it seems that they aren't.
Is there a way to instruct that newly generated tables from a template should also be partitioned?


text:
Q: php - shell_exec , exec, etc.. can not get output like in terminal. even with 2>&1 First let's run the command via terminal:
$ echo 1; /etc/init.d/apache3 restart; echo 2;

result.. ( apache3 on purpose to see an error )
1
bash: /etc/init.d/apache3: No such file or directory
2

awsome.
now let's run this via php..
<?php

$command = "echo 1; /etc/init.d/apache3 restart; echo 2; 2>&1";
$response = shell_exec("$command");
echo $response;

?>

all I see on the browser is: 1 2
I tried all sorts of things. replaced the semi colons with "&&"..
tried all the php stuff such as..
passthru()
exec()
system()
popen()

i tried it all pretty much. been hours.. can not get it to show me the same stuff i see via terminal.

A: You have to use 2>&1 after the restart command
Your command :
$command = "echo 1; /etc/init.d/apache3 restart; echo 2; 2>&1";

yours has "2>&1" at the end which has no use.
Also you will add to 2>&1 after each command in case others uses STDERR
$command = "echo 1; /etc/init.d/apache3 restart 2>&1; echo 2 ";

A: Consider using exec. The basis function only returns the first line of the output:
$response = exec("$command"); // just the first line

But use the additional parameters to capture both the output (as an array) and the return value
$retval = NULL;
$output = NULL;
$response = shell_exec("$command", $output, $retval); // last two params are passed by reference and modified by the command

Also, as user993553 posted, the output captured by these cli functions in PHP will usually just return stdout and not stderr. You can append " 2>&1" to any given command (note the space before the 2) in order to route stderr into the output.
That said, your function becomes:
$command = "echo 1; /etc/init.d/apache3 restart 2>&1; echo 2;";
$retval = NULL;
$output = NULL;
$response = exec($command, $output, $retval);
var_dump($output);

and the output:
array(3) {
  [0] =>
  string(1) "1"
  [1] =>
  string(37) "sh: 1: /etc/init.d/apache3: not found"
  [2] =>
  string(1) "2"
}

EDIT: you can also check $retval for an error condition. If it's not empty or zero, then signifies an error.

A: From the manual of shell_exec:

ALSO, note that shell_exec() does not grab STDERR, so use "2>&1" to
  redirect it to STDOUT and catch it.


text:
Q: How to remove a set of chars from a string if it exists I have a file having below strings formats:
abc
xyz
statexyz_pqr_mho
dce
statelop_pqz_mho

I am in need to remove from all lines till '_' if state word exists in the beginning of the string
So the final list should be  -
abc
xyz
pqr_mho
dce
pqz_mho

A: You can use
sed '/^state/s/^[^_]*_//' foo.txt

Explanation
We first match state at the beginning of the line with /^state/.
Then we delete everything up to and including the first underscore by using the non-greedy matching ^[^_]*
On input:
abc
xyz
statexyz_pqr_mho
dce
statelop_pqz_mho

This will output
abc
xyz
pqr_mho
dce
pqz_mho


text:
Q: google maps API v3 not working with cordova I'm trying to use the google maps on an Android app. I include the Google Maps API with
<script type="text/javascript" src="http://maps.googleapis.com/maps/api /js?key=my key&sensor=false"></script>

Every website is whitelisted with
<access origin=".*"/>

in the .xml.
But i still get an error
Uncaught referenceError:google is not defined

So, the API couldn't be loaded.
The code works perfectly when running on my PC but this happen when I put it on the mobile device, showing that the problem may come from cordova.
My device of course has an internet connection, any idea on how to fix that?

A: Assuming this is just a typo, but you have a space in your url, and now I believe the url is: http://maps.google.com/maps/api/js?key=yourkey&sensor=false


text:
Q: Which gender suits which side of the force better? I finally got some time to play KOTOR, but not enough to replay it multiple times. While the most differentiating choice is between the light side of the force and the dark side, the choice of gender is probably also important (class as well, but I think I know which ones I choose there). So if I want to experience as much variety in the game as possible by playing only once for the light side and once for the dark side, which gender makes most sense for which side, and why?

A: So, the short answer is that you want to play things through once as each gender absolutely, since there is a romance option for both.
As to the relationship between each gender and your choices with regards to alignment... Well, going through with each combination Light/Male, Dark/Male, Light/Female, Light/Male is going to have a unique take on certain events at the endgame.
That said, the difference aren't so substantial that it won't be fairly obvious what those differences are once you get there.
I will say that if you enjoy playing up the somewhat cartoonish tone of evil of KOTOR's dark side path, play as a Dark Female. More detailed spoilers follow.

 Basically, there are two romance options. Female characters can fall for Carth, who is staunchly Light Side aligned through the end of the game. If you play as a Dark Side female, you get to completely torture and abandon Carth as he spends the entire game trying to save you. Male characters can romance Bastila, who is turned to the Dark Side later by Malak. In the end, Light Side players can choose to redeem Bastila, or to kill her. Dark side players can choose to make her their apprentice, or, again, to kill her.

To put it another way:
If you prefer that your Light Side playthrough emphasize redemption, play male. If you prefer that it emphasize loyalty, play female.
If you prefer that your Dark Side playthrough emphasize cruelty, play female. If you prefer that it emphasize power and domination, play male.


text:
Q: How to replace multiple characters in the same string? I am not very versed in programming in general so please cut me some slack here.
Is there a more elegant way to tackle this process of replacing multiple characters in a string?
strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(godiacritics.Normalize(strings.ToLower(articles[i].Name)), "-", "_"), " ", "_"), ",", "_"), ".", ""), "/", ""), "€", ""), "%", ""), "12", "halb"), "14", "viertel")

A: Create a single strings.Replacer which contains all replaceable pairs:
r := strings.NewReplacer(
    "-", "_",
    " ", "_",
    ",", "_",
    ".", "",
    "/", "",
    "€", "",
    "%", "",
    "12", "halb",
    "14", "viertel",
)

And use it like this:
s2 := r.Replace(godiacritics.Normalize(strings.ToLower(articles[i].Name)))

strings.Replacer performs all replaces in a single step (it iterates over the string once). It's also safe for concurrent use, create the Replacer onces and reuse it whenever / wherever needed.
Example code to test it:
s := "test- ,./€%:12 14"
s2 := strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(strings.ReplaceAll(s, "-", "_"), " ", "_"), ",", "_"), ".", ""), "/", ""), "€", ""), "%", ""), "12", "halb"), "14", "viertel")
fmt.Println(s2)

r := strings.NewReplacer(
    "-", "_",
    " ", "_",
    ",", "_",
    ".", "",
    "/", "",
    "€", "",
    "%", "",
    "12", "halb",
    "14", "viertel",
)

s3 := r.Replace(s)
fmt.Println(s3)

Which outputs (try it on the Go Playground):
test___:halb_viertel
test___:halb_viertel


text:
Q: Horizontal slide to a certain length - iOS I have a view which contains a button named inbox. When i click on inbox button , number of uiviews appear depending on the count of inbox messages. Code is:
     int t=0;
     for(int i=0;i<countOfInboxMessages;i++){
         UIView *inboxView=[[UIView alloc]initWithFrame:CGRectMake(6, t, 309,80)];
         inboxView.backgroundColor= [UIColor whiteColor];
         [inbox addObject:inboxView];
         [viewInbox addSubview:inboxView];
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(20,4,250,20)];
         titleLabel.text = messageTitle[i];
       UILabel *createdDateLabel = [[UILabel alloc]initWithFrame:CGRectMake(4,17,250,20)];
         createdDateLabel.text = createdDate[i];
         createdDateLabel.font = [UIFont fontWithName:@"HelveticaNeue" size:8];
         createdDateLabel.textColor = [UIColor lightGrayColor];

         [inboxView addSubview:createdDateLabel];
         [inboxView addSubview:titleLabel];
          inboxView.userInteractionEnabled = YES;
             UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc]  initWithTarget:self action:@selector(handleSwipeFrom:)];
             swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
             [inboxView addGestureRecognizer:swipeLeft];

         t+=83;
     }

Say the value of countOfInboxMessages is 4. I would get 4 inboxViews. Now the task is I need to add swipe gesture to each inbox view. I am using the code:
        inboxView.userInteractionEnabled = YES;
       UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc]  initWithTarget:self action:@selector(handleSwipe:)];
         swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
         [inboxView addGestureRecognizer:swipeLeft];

But the inbox views are not sliding. What could be the reason?


text:
Q: Changing a keyboard's key color WP8 I have seen other posts surrounding the subject,
but i want to change only the enter(return) key, not the whole keyboard.
Just like in the windows phone 8 store
where the enter button has a white color.

A: You can change layout of the windows phone keyboard using InputScope property.
Try: <TextBox InputScope="Search" />
You can find all available layouts here: http://msdn.microsoft.com/en-us/library/ff426929(v=vs.95).aspx


text:
Q: How to extract frames from yuv 420 video clip and store them as different images, using matlab? How do I extract the frames from a yuv 420 video? Let's say i want to store them as still images. How?

A: Here's a submission from the MathWorks File Exchange that should do what you want:

*

*Convert YUV CIF 4:2:0 video file to image files by Da Yu
The function loadFileYuv from the above submission will load a YUV file and return an array of movie frames. Each movie frame is a structure with the following fields:

*

*cdata: A matrix of uint8 values. The dimensions are height-by-width-by-3.

*colormap: An N-by-3 matrix of doubles. It is empty on true color systems.

You can therefore extract the cdata field from each movie frame in the array and save/use it as an RGB image.
Your code might look something like this:
nFrames = 115;     %# The number of frames
vidHeight = 352;   %# The image height
vidWidth = 240;    %# The image width
mov = loadFileYuv('myVideo.yuv',vidHeight,vidWidth,1:nFrames);  %# Read the file
for k = 1:nFrames  %# Loop over the movie frames
  imwrite(mov(k).cdata,['myImage' int2str(k) '.bmp']);  %# Save each frame to
                                                        %#   a bitmap image file
end

A: sorry can't help with matlab but on the command line you can do it with ffmpeg
ffmpeg -i input.yuv -r 1 -f image2 images%05d.png

-r 1 means rate = every frame

A: You can use this code below:
vidObj1 = mmreader('testballroom_0.avi');  %# Create a video file object
nFrames = vidObj1.NumberOfFrames;   %# Get the number of frames
vidHeight1 = vidObj1.Height;         %# Get the image height
vidWidth1 = vidObj1.Width;           %# Get the image width

%# Preallocate the structure array of movie frames:

mov1(1:nFrames) = struct('cdata',zeros(vidHeight1,vidWidth1,3,'uint8'),...
                    'colormap',[]);  %# Note that colormap is empty!

You can access each frame from the matrix mov1 :)


text:
Q: MS pnp Taxonomy Control rendering on bottom I was trying to use the taxonomy control on my simple page. However, it always renders on the bottom of the page. The hidden field stays where it is, but the taxonomy control is always on the bottom.
On the rendered page I always have Test and blubb together and the taxonomy control comes after it:
Test
blubb
[Control]
Is there any known bug why this happens?
    <%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Import Namespace="Microsoft.SharePoint.ApplicationPages" %>
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="t.aspx.cs" Inherits="sptaxpicker2.Layouts.sptaxpicker2.t" DynamicMasterPageFile="~masterurl/default.master" %>

<asp:Content ID="PageHead" ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
    <link rel="stylesheet" type="text/css" href="style/taxonomypickercontrol.css">

</asp:Content>

<asp:Content ID="Main" ContentPlaceHolderID="PlaceHolderMain" runat="server">
   test
 <input type="hidden" id="txbox" />
blubb

</asp:Content>

<asp:Content ID="PageTitle" ContentPlaceHolderID="PlaceHolderPageTitle" runat="server">
simple test
</asp:Content>

<asp:Content ID="PageTitleInTitleArea" ContentPlaceHolderID="PlaceHolderPageTitleInTitleArea" runat="server" >
simpletest
</asp:Content>

Thanks!
Best,
Christian

A: Solution found: It is important to put the control inside a container like a div and not directly as a table data because the javascript behind uses parent element to move the item.


text: Q: Calculating bitrate box bufferSizeDB value for AAC track in MP4 file I am writing a custom fragmented MPEG-4 sink in media foundation. I have been able to figure out and get info on nearly everything but I am stuck on the bufferSizeDB item for an audio AAC "esds" container. The bitRateBox used in MP4 format includes the bufferSizeDB member to assist decoders. Does anyone know how this value is calculated or what the guidelines there are for setting it?


text:
Q: jQuery simple color picker, pallette won't close Recently I started using jQuery Simple Color picker (GITHUB) and encountered an annoying problem, with two or more color pickers on page, pallete won't disappear when I open second one (as you can see below). I am out of ideas about solution, because there is no onOpen or similar event, I cant even add onClick listener (don't know why, but my guess is, that its overridden somewhere in library). Is there anything I can do, I would really appreciate your advice, because I would hate to switch libraries.
Thanks for your help and have a nice day.
EDIT: Code like this is not working for me, tried same for clickable div, its cotainer and pallette div. Code is working on simple button.
  $('.simple_color').click(function(event) {
      $('.simple_color_custom_cell_size').closeChooser();
  });


text:
Q: How is the main image height always approximately 75% of the window size? http://www.apple.com/sg/
there is a giant image that will autosize such that it is always approximately 75% of the window height.
How is this done?
I found a css media query, but I can only discover this one:
@media only screen and (max-width: 1068px), only screen and (max-height: 800px) {
   .page-home .billboard.evergreen {
       height: 50%;
       min-height: 630px;
    }
}

How do I find out about the other media queries for different resolutions?

A: The easiest way will be:

.item
{
  height: 75vh;
  background-color: blue;
}

These are so called viewport units. They are supported pretty good.
You may also try to utilize vmax for this use case. This will always hold the  larger value of vw or vh.


text:
Q: Join under condition in Oracle SQL SELECT statement I'm trying to join two tables under a condition but I haven't been able to make it work. I've been searching and reading but couldn't find an answer for my case.
This is the basic idea of what I'm trying to achieve (what I wrote in lowercase is what I want to achieve in my own words, in case you wonder):
SELECT TABLE1.STR_FULLNAME, TABLE1.STR_MAILBIZ, TABLE2.STR_IP
FROM TABLE1
INNER JOIN TABLE2

     if TABLE2.STR_MACHINEUSER contains 'TEXT\' then join like this:
          ON TABLE1.STR_LOGIN = SELECT SUBSTR(STR_MACHINEUSER, 6) AS STR_MACHINEUSER FROM TABLE2 WHERE
          STR_MACHINEUSER LIKE 'TEXT\%'
     else join like this:
          ON TABLE1.STR_LOGIN = TABLE2.STR_MACHINEUSER

ORDER BY TABLE2.DT_INSERT DESC;

The content of Table1.STR_LOGIN and that of Table2.STR_MACHINEUSER are in some cases exactly the same and in some cases a prefix needs to be removed in Table2.STR_MACHINEUSER ('TEXT\'). I've seen that conditions should be handled with the CASE expression. I have tried different ways, but I couldn't make it work for what I need. I'm thinking that I might need a complete different approach, but I don't see what...
Does someone have a suggestion? Thanks in advance!

A: Maybe this is what you want:
SELECT TABLE1.STR_FULLNAME, TABLE1.STR_MAILBIZ, TABLE2.STR_IP
FROM TABLE1
INNER JOIN TABLE2 ON
  (not TABLE2.STR_MACHINEUSER LIKE 'TEXT\%' and TABLE1.STR_LOGIN = TABLE2.STR_MACHINEUSER)
  or
  (TABLE2.STR_MACHINEUSER LIKE 'TEXT\%' and TABLE1.STR_LOGIN = SUBSTR(TABLE2.STR_MACHINEUSER, 6))

Sure you could shorten your statement using some case construct like:
case
  when TABLE2.STR_MACHINEUSER LIKE 'TEXT\%'
  then SUBSTR(TABLE2.STR_MACHINEUSER, 6) else TABLE2.STR_MACHINEUSER
end

and compare this to TABLE1.STR_LOGIN but I find (IMHO) the first (logic) join better readable.


text:
Q: How to perform backup when deleting Site Collection automatically? I have requirement which is when user accidentally select delete button for site collection it has to perform backup operation automatically before it deleted is there any WSP solutions available please suggest me.
Many Thanks

A: I think no need for WSP solutions, the SharePoint already handles this operation by adding the deleted site collection in the Second stage when a user accidentally deletes a site collection from GUI Central Admin.

How to Restore Deleted the Site Collection
If you've accidentally deleted a site collection, you can restore it back within 30 days depends on the Site Quota using Restore-SPDeletedSite PowerShell.
Check also Delete and restore site collections in SharePoint Server

But if you need to keep the backup for a long time (> 30 days), you can handle this through the code, by developing your own Event Receiver to perform a backup when a site collection is being deleted

Now, you just need to know How to perform a backup to a site collection
Backup Site collection C# Code
SPFarm myFarm = SPFarm.Local;
SPServiceCollection myServices = myFarm.Services;
Guid serviceID = new Guid("21d91b29-5c5b-4893-9264-4e9c758618b4");
SPWebService webPubService = (SPWebService)myServices[serviceID];

// Get a reference to the Web application that hosts the
// site collection.
SPWebApplicationCollection myApps = webPubService.WebApplications;
Guid appID = new Guid("10ea4e6f-ae37-4909-b04f-f516c066bc37");
SPWebApplication myApp = myApps[appID];

// As alternative to the preceding three lines, you can use
// the following when you know the URL of the Web application:
//     SPWebApplication myApp = SPWebApplication.Lookup(url_of_Web_app)

// Get a reference to the Web application's collection of
// site collections.
SPSiteCollection mySiteCols = myApp.Sites;

// Back up a specified site collection.
mySiteCols.Backup(@"http://Server/sites/MySiteCollection", @"\\OtherServer\WSSBackups\SiteCollections\BackupOfMySiteCollection", true);

Check also How to: Programmatically Back Up and Restore a Single Site Collection


text:
Q: The way to index multi-lingual content by Lucene? I have an APP supporting search based on lucene.
or other method to support both Chinese and English searching?

A: Hello I don't totally understand your question but I think I have a rough idea of what you want to achieve.
If you want to search for languages separatly, I would suggest you to add a Lucene Field "Language" at index time. According to the language of the text you are indexing.
Since you can easily differentiate Chinese characters from english caracters using
Character.UnicodeBlock:
http://docs.oracle.com/javase/7/docs/api/java/lang/Character.UnicodeBlock.html
For example you want to check char 1 of the String "str":
if(Character.UnicodeBlock.of(**str[1]**) == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS)
{ do something }

This way at search time you can detect chinese input the same way and add a condition on your language field to the query.
Now if you want to have a mixed search I would suggest to build your custom Analyzer that analyzes each word and stores a translation for it in your index.


text:
Q: Flutter : Crhome view is not clear I have an app with flutter using facebook auth, when I click facebook login chrome app display with facebook page to login, but the page is not clear like this paic, when I try to use it the emulator not response:

Any one have an Idea tosolve this, I have chnged High Dpi settings and nothing change.


text:
Q: show activity after click on notification Im trying to reactivate my app after user clicked on the notification. I've found some examples and explanations but nothing worked for me. Please see my code below. The user can hide the app while it's running so the notification is informing about the running process. After it's finished or while it's running, I want the user to be able to show the app by clicking on the notification. How can I do that in this case? What's working now: The notification with a progress bar while process running. But nothing happens on click it.
    private void bgTasksStarter(final String doThis, final String thisFileName, final String thisCompPass, final String thisTestStr) {

    String sOut = "";
    switch(doThis) {
        case doEncrypt:
            sOut = lng.encryption;
            break;

        case doDecrypt:
            sOut = lng.decryption;
            break;
    }

    final String fsOut = sOut;

    final int id = 1;

    final NotificationManager mNotifyManager;
    final Builder mBuilder;

    mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    mBuilder = new NotificationCompat.Builder(this);
    mBuilder.setContentTitle(thisFileName)
        .setContentText(fsOut + " " + lng.isRunning)
        .setSmallIcon(R.drawable.ic_launcher);

    new Thread(
            new Runnable() {
                @Override
                public void run() {

                    bgTasks = new BgTasks();
                    bgTasks.execute(doThis, thisFileName, thisCompPass, thisTestStr);

                    mBuilder.setProgress(0, 0, true);
                    mNotifyManager.cancel(id);
                        mNotifyManager.notify(id, mBuilder.build());

                    while (busy) {

                        try {
                                Thread.sleep(1*1000);
                            } catch (InterruptedException e) {
                                Log.d("xxx", "sleep failure");
                            }
                    }
                        mBuilder.setContentText(fsOut + " " + lng.isFinished)
                            .setProgress(0,0,false);
                        mNotifyManager.notify(id, mBuilder.build());

                }
            }
        ).start();
}

A: You should add an intent through pendingIntent like so:
Intent intent = new Intent(context, desiredClass.class);

PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);

mBuilder.setContentIntent(pendingIntent);

Notice the flag FLAG_UPDATE_CURRENT and check if it is the right one for your case.

A: You need to use the setContentIntent method that will trigger the pending intent when you click on the notification.
Intent launcher = new Intent(context, YourActivity.class);
launcher.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

PendingIntent contentIntent = PendingIntent.getActivity(context, 0, launcher, PendingIntent.FLAG_UPDATE_CURRENT);

mBuilder.setContentIntent(launcher);


text:
Q: Simple drag`n`drop in Flash Builder 4 I have a very simple question, but I can not find solutions to it. I need to add multiple images that can be moved with the mouse. This components NumericStapper must be in the group with the image and move together.
http://img835.imageshack.us/img835/9341/323.jpg

A: Thanks, I found a reference
http://livedocs.adobe.com/flex/3/html/help.html?content=dragdrop_1.html


text:
Q: PearsonR TypeError: cannot perform reduce with flexible type r and p using scipy calculation issue
Any idea about the type error issue?
r, p = pearsonr(a, b)

TypeError: cannot perform reduce with flexible type
sample data:
enter image description here
a = DF['a']
b = DF['b']
c = DF['c']
d = DF['d']
e = DF['e']
f = DF['f']

r, p = pearsonr(a, b)


text:
Q: A function with a non-negative upper derivative must be increasing? I am trying to show that if $f$ is continuous on the interval $[a,b]$ and its upper derivative $\overline{D}f$ is such that $ \overline{D}f \geq 0$ on $(a,b)$, then $f$ is increasing on the entire interval. Here $\overline{D}f$ is defined by
$$
\overline{D}f(x) = \lim\limits_{h \to 0} \sup\limits_{h, 0 < |t| \leq h} \frac{f(x+t) - f(x)}{t}
$$
I am not sure where to begin, though. Letting $x,y \in [a,b]$ be such that $x \leq y$, suppose for contradiction that $f(x) > f(y)$, then continuity of $f$ means that there is some neighbourhood of $y$ such that $f$ takes on values strictly less than $f(x)$ on this neighbourhood. Now I think I would like to use this neighbourhood to argue that the upper derivative at $y$ is then negative, but I cannot see how to complete this argument.
Any help is appreciated! :)

A: Probably not the best approach, but here is an idea: show taht MVT holds in this case:
Lemma Let $[c,d]$ be a subinterval of $[a,b]$. Then there exists a point $e \in [c,d]$ so that
$$\frac{f(d)-f(c)}{d-c}=\overline{D}f(e)$$
Proof:
Let $g(x)=f(x)-\frac{f(d)-f(c)}{d-c}(x-c) \,.$
Then $g$ is continuous on $[c,d]$ and hence it attains an absolute max and an absolute minimum. Since $g(c)=g(d)$, then either $g$ is constant, or one of them is attatined at some point $e \in (c,d)$.
In the first case you can prove that $\overline{D}g=0$ on $[c,d]$, otherwise it is easy to conclude that $\overline{D}g(e)=0$.
Your claim follows immediately from here.

A: This is based on David's comment above.
Choose $u,v, \epsilon$ such that $ a < u < v < b$ and $ \epsilon > 0 $.
Let $$ S = \{ x \in [u,v] : f(x) + \epsilon x \geq f(u) + \epsilon u \}.$$ $S$ is not empty as $ u \in S$ and $S$ is closed as $f$ is continuous.
Let $\sup S = t$, $t$ is in $S$ as $S$ is closed. We will show $t=v$.
If $ t < v$, then define for $ \delta \in (0, v- t] $, $g(\delta) = \sup_{0 < h \leq \delta} \dfrac{f(t+h) - f(t)}{h}$.
Since $g(\delta)$ decreases to $\overline{D}f(t) \geq 0$  as $ \delta \to 0^+$, we must have $ g(\delta) > -\epsilon $ for sufficiently small positive $\delta$, and this means, the set $g(\delta)$ is a supremum of, must contain an element greater than $-\epsilon$. Hence there is a $t_1 \in (t,v]$ with $\dfrac{f(t_1) - f(t)}{t_1 - t} > -\epsilon$, we have $f(t_1) + \epsilon t_1 > f(t) + \epsilon t \geq f(u) + \epsilon u$, i.e., $t_1 \in S$. This contradiction implies $v = \sup S$ and $f(v) \geq f(u ) + \epsilon (v - u)$. Letting $\epsilon \to 0$, we have $f(v) \geq f(u)$. Hence $f$ is non-decreasing on $(a,b)$. This can be extended to all of $[a,b]$ by keeping $v$ fixed and letting $u \to a$ and keeping $u$ fixed and letting $v \to b$.

A: The following is in response to a recent comment to my answer of Dini or Right or upper derivative of Weierstrass function.
Corollary 11.4.1 on p. 128 of [1] (proved concisely on p. 128), and V.34.1 on pp. 200-201 of [2] (proved in detail on pp. 201-202), each state a result that is slightly stronger than the following, where $D^{+}f$ is the right upper Dini derivate of $f.$

Let $I$ be an open interval in $\mathbb R$ and let $f:I \rightarrow {\mathbb R}$ be a function. If $f$ is continuous and $D^{+}f \geq 0$ on $I$ for all but countably many $x \in I,$ then $f$ is non-decreasing on $I.$

PROOF: (adapted from [1] and [2]) We first prove the weaker result that $D^{+}f(x) > 0$ (strict inequality) for all but countably many $x \in I$ implies that $f$ is non-decreasing on $I.$ Let $Z = \{x \in I: \; D^{+}f(x) \leq 0\}$ be the countable set at which $D^{+}f(x) > 0$ is not assumed. (Note that we are not claiming that $D^{+}f(x) \leq 0$ for all $x \in Z.)$ For a later contradiction, assume that $f$ is not non-decreasing on $I.$ Then there exist $a \in I$ and $b \in I$ such that $a < b$ and $f(b) < f(a).$ Choose $y_0 \in I$ such that $f(b) < y_0 < f(a)$ and $y_0 \notin f(Z) = \{f(x): \; x \in Z\}.$ This is clearly possible because there are uncountably many numbers between $f(b)$ and $f(a)$ and only countably many numbers in $f(Z).$ Let $E = \{x \in [a,b]: \; y_0 \leq f(x)\}.$ Note that $E \neq \emptyset$ because $a \in E.$ Thus, $\sup E$ exists. Let $x_0 = \sup E.$ I claim that $f(x_0) = y_{0}.$ For a later contradiction, suppose $f(x_0) > y_{0}.$ (Yes, a proof by contradiction within a proof by contradiction. This means careful reading is needed.) Since $f(b) < y_{0},$ it follows that $x_0 \neq b.$ Now by definition of $x_{0},$ we have $f(x) < y_0$ for all $x$ such that $x_0 < x \leq b.$ Hence, $\lim_{x \rightarrow x_{0}^{+}}f(x) \leq y_0.$ (Note that strict $<$ becomes $\leq$ after the limit is applied to both sides of $f(x) < y_0.)$ But we also have $y_0 < f(x_0)$ by our assumption (to be contradicted), so it follows that $\lim_{x \rightarrow x_{0}^{+}}f(x) < f(x_0),$ which contradicts (right) continuity of $f$ at $x = x_{0}.$ (In fact, both [1] and [2] deal with a weaker assumption than right continuity that also provides a contradiction at this point in the proof.) A proof that $f(x_0) < y_{0}$ also leads to a contradiction can be done in a similar way, so I'll skip the details. Thus, we have $f(x_0) = y_{0},$ and hence $D^{+}f(x_0) \leq 0,$ which contradicts our choice of $y_0$ as not being an element of $Z.$ (Recall that the only possible points where $D^{+}$ can fail to be strictly positive are the points in $Z.)$
To prove the stronger result that $D^{+}f(x) \geq 0$ (non-strict inequality) for all but countably many $x \in I$ implies that $f$ is non-decreasing on $I,$ roughly what is done is to apply the just proved result to functions of the form $f_{\epsilon}(x) = f(x) + {\epsilon}x$ and let $\epsilon \rightarrow 0.$ The details are in [2] (top half of p. 202), but I believe this is a standard technique that can be found in many real analysis texts.
Incidentally, note that although the assumption is that $D^{+}f(x) \geq 0$ for all but countably many $x \in I,$ the result itself implies (among other things) that $D^{+}f(x) \geq 0$ for ALL $x \in I,$ because for non-decreasing functions $f$ we have $D^{+}f(x) \geq 0$ everywhere (indeed, all four Dini derivates will be $\geq 0$ everywhere).
[1] Andrew Michael Bruckner, Differentiation of Real Functions, 2nd edition, CRM Monograph Series #5, American Mathematical Society, 1994, xii + 195 pages. Review in Bull. AMS of 1980 1st edition [Note: The result above is also in the 1980 1st edition, same chapter-section-item number, but the page numbers are different.]
[2] Edward James McShane, Integration, Princeton Mathematical Series #7, Princeton University Press, 1944, viii + 392 pages. Review in Bull. AMS [No other editions were published, but the later re-printings are viii + 394 pages due to the addition of a 2-page Appendix at the end.]

A: The statement is not true. The Weierstrass function has upper derivative greater than zero everywhere, it is continuous, and it is not an increasing function. This question comes as an error in Royden, and should read that the lower derivative of $f$ is greater than or equal to zero, per this errata.
http://www2.math.umd.edu/~pmf/docs/Real%20Analysis.pdf

A: Let $ f:[a,b]→\Bbb{R}$ be a continuous function such that one of Dini's one-sided derivatives exists and positive. Then it can be shown $f$ is monotonically non-decreasing on $[a,b]$.
Assume, $D^{+} f(t):=lim sup_{\delta \to
 0+} {\frac{f(t+\delta )−f(t)}{\delta}}$ exists and positive i.e $D^+{f(x)} >0, \space \forall x\in [a, b]$
Claim: $f$ is monotonically non-decreasing on $[a,b]$.
Suppose, $f$ fails to be non-decreasing on $[a,b]$.
Then, $\exists  c, d $ with $a\le c<d\le b$ such that $f(c) >f(d) $
Let, $y\in (f(d), f(c)) $
Since, $f\in C[a, b]$ , by Intermediate Value Theorem, $\exists t \in [c, d]$ such that $ f(t) =y$
Then, the set $\{x : f(x) =y\}\cap [c, d] $ is non empty.
Suppose, $x_o=Sup\{x : f(x) =y\}\cap [c, d]  \}$
Now, $f(d) <y$ and $f$ is continuous implies $x_o<d$
Thus, $f(x) <y, \forall x\in (x_o, d]$
And the set $\{x : f(x) =y \}$  is closed as $f$ is continuous, so $f(x_o) =y$
And, this implies that $D^+ { f(x_o) } \le 0$
Hence, a contradiction.
Hence, if $f$ is continuous and $D^+{f(x)} > 0,\space \forall x\in [a, b] $ then $f$ must be non -decreasing on $[a, b]$ $($ in fact, $f$ is strictly increasing on $[a, b]) $


text:
Q: How prove this identity $\prod_{k=1}^{n-1}\sin{\frac{k\pi}{tn}}=\frac{\sqrt[t]{n}}{2^{n-1}}$
show that:
$$\prod_{k=1}^{n-1}\sin{\dfrac{k\pi}{tn}}=\dfrac{\sqrt[t]{n}}{2^{n-1}}?(not, true),t\in N^{+}$$

maybe for $t$is real numbers also true?
I can show when $t=1$ case.
because I use
$$z^{n-1}-1=(z-x_{1})(z-x^2_{1})\cdots (z-x^{n-1}_{1}),x_{1}=\cos{\dfrac{2\pi}{n}}+i\sin{\dfrac{2\pi}{n}}$$
also see Prove that $\prod_{k=1}^{n-1}\sin\frac{k \pi}{n} = \frac{n}{2^{n-1}}$
But for $t\neq 1$,I can't use this identity

A: Another reason for which the formula cannot be true is that $\log(\sin x)$ is an integrable function over $(0,1)$, hence for $t\in\mathbb{N}$ it is expected that:
$$\sum_{k=1}^{n-1}\log\sin\frac{\pi k}{t n}\approx n\int_{0}^{\pi/t}\log\sin x\,dx \approx -n\frac{1+\log\frac{t}{\pi}}{t}$$
by Riemann sums, while:
$$\log\frac{\sqrt[t]{n}}{2^{n-1}}\approx -n\log 2+\frac{\log n}{t}$$
has the wrong magnitude.
To compute the product, a possibility is given by the Fourier series identity:
$$-\log\sin x = -\log 2-\sum_{k\geq 1}\frac{\cos(2kx)}{k}. $$


text:
Q: Passing arguments to non interactive script interactively Does anyone have an idea how to pass something interactively to a script which does not support interactive mode? Is there any shell feature / application etc. or any other way to wrap the script / application by something in such a way that I could pass arguments and then hide them? I don't want my sensitive data such as password were visible in keyboard buffer, on the process list etc. Is it possible?

A: *

*First, check if this is really necessary. Some software rewrites its command line after startup.

*If your executable is a binary, there are ways to dynamically load your program into an existing process.

*You were talking about a script. Assuming it is Bash or compatible, you can easily write a wrapper that reads your secret, then sources the existing script.

Because no new process is generated, the secret will not be part of any command line, but it will be available as shell parameter (here $1) while yourscript is executing:
#!/bin/bash
read secret
. <yourscript> "$secret"


text:
Q: How to prevent twisted exception python.failure.Failure twisted.internet.error.ConnectionDone I am using
scrapy shell https://www.mon-panier-bio.com/distributeur/local/ou-trouver-panier-bio-france/

which results
twisted.python.failure.Failure twisted.internet.error.ConnectionDone:
Connection was closed cleanly.>,
<twisted.python.failure.Failuretwisted.web.http._DataLoss: >]
Traceback(most recent call last):File "/usr/local/bin/scrapy",
line 11, in <module>sys.exit(execute())
File "/usr/local/lib/python2.7/dist-packages/scrapy/cmdline.py"
,line 143, in execute  _run_print_help(parser, _run_command, cmd,args, opts)
File "/usr/local/lib/python2.7/dist-packages/scrapy/cmdline.py", line
89, in _run_print_help
func(*a, **kw)File "/usr/local/lib/python2.7/dist-packages/scrapy/cmdline.py", line 150, in _run_command
cmd.run(args, opts)
File "/usr/local/lib/python2.7/dist-
packages/scrapy/commands/shell.py", line 50, in run
shell.start(url=url, spider=spider)
File "/usr/local/lib/python2.7/dist-packages/scrapy/shell.py", line
45, in start self.fetch(url, spider)
File "/usr/local/lib/python2.7/dist-packages/scrapy/shell.py", line
90, in fetch reactor, self._schedule, request, spider)
File "/usr/local/lib/python2.7/distpackages/twisted/internet/threads.py", line
122, in blockingCallFromThread
result.raiseException()
File "<string>", line 2, in raiseException
twisted.web._newclient.ResponseFailed:
[<twisted.python.failure.Failure
twisted.internet.error.ConnectionDone: Connection was closed
cleanly.>, <twisted.python.failure.Failure twisted.web.http._DataLoss:
>]

Guide me what should I to prevent from this exception. I am using scrapy 1.1.1 and twisted 16.3.0


text:
Q: Django admin. Text does not fit into manytomany field widget Inside my django admin, I have a many-to-many field in which I want to fit a string.

Is there any way to fix this?

A: Create a template base_site.html in templates/admin directory with the following content:
{% extends "admin/base.html" %}
{% load static %}

{% block title %} {{ title }} | {{ site_title|default:_('Django site admin') }}

{% endblock %}

{% block extrastyle %}
<link rel="stylesheet" href="{% static 'admin.css' %}">

{% endblock %}

After that create css file in your static directory like admin.css with following styles:
select > option {
white-space: pre-line;
margin-bottom: 20px;
border: 1px solid black;
}


text:
Q: Is connecting a 2 A adapter to a 1.3 A electrical device safe? Is connecting a higher-amp (e.g. 2 A) adapter to a lower-amp (e.g. 1.3 A) electrical device safe?
I wonder if it will cause the adapter to over heat and cause fire or cause damage to the electrical device.

A: No it won't overheat the adapter. That's designed to deliver up to 2 A, and everything less than that is safe. If you disconnect the device the current will be zero, and that's also safe. The adapter will supply the required current, not the current it can supply.
Never do the inverse: connecting a 2 A device to a 1.3 A adapter, though.


text:
Q: Materialize carousel failing to disable draggable property I'm using materialize carousel library, and the default is having it draggable (Mobile UX benefits I guess). I want to disable it since it's interrupts scrolling on mobile devices.
I've tried to apply draggable property as false, yet it still continues to work.
Here is my slider code

//Slider
$('.carousel.carousel-slider').carousel({
        fullWidth: true,
        indicators: true,
        draggable: false
});
autoplay();
function autoplay() {
        $('.carousel.carousel-slider').carousel('next');
        setTimeout(autoplay, 5500);
}
.carousel{
    height: 100vh;
}

Real time tracking

                        Our devices allows you to track you employee in real time.

                        Gives you full control on your mine personnel.

                        Incase of injuries, you know where to search.

                        Knowing how to deploy your forces.

                        Efficiency at her best.

EUROTECH

It's all about efficiency & safety

                      You can either choose to work harder or you can work smarter

Avoiding the next disaster

                      Together we can prevent the next case with unique underground tracking devices,

                      digital solutions and advanced mining products.

              Scroll

Here is the result
How can I disable mobile draggable carousel option? Or solve the scrolling down sensitivity issue.


text:
Q: C# .NET Core: translate Identity reference SID to display value for Active Directory groups and users I'm switching an API from .NET Framework to .NET Core and running into some differences in the behavior of Directory.Services.AccountManagement vs System.IO.FileSystem.AccessControl in .NET Core 3.1.
The issue in the .NET Core code is I'm trying to get the Active Directory group name (or user name) for each rule for a file. I can get the sid, but the FileSystemAccessRule.IdentifyReference.Translate() method throws an exception for AD groups.
Here's what I have: I can get the SID in the id variable, but I need the actual group name (or user name)
using System.Security.AccessControl;
using System.Security.Principal;

namespace ConsoleCoreAclsPoc
{
    class Program
    {
        static void Main(string[] args)
        {
            var fn = args[0];

            var rules = new FileSecurity(fn, AccessControlSections.All | AccessControlSections.Access)
                               .GetAccessRules(true,true,typeof(NTAccount));

            foreach (AuthorizationRule rule in rules)
            {
                FileSystemAccessRule fileRule = rule as FileSystemAccessRule;

                if (fileRule != null)
                {
                    var id = fileRule.IdentityReference;//.Translate(typeof(NTAccount));
                    var read = fileRule.FileSystemRights.HasFlag(FileSystemRights.ReadAndExecute);
                    var write = fileRule.FileSystemRights.HasFlag(FileSystemRights.Modify);
                    var admin = fileRule.FileSystemRights.HasFlag(FileSystemRights.FullControl);

                    if (!admin)
                    {
                        // do stuff to the non-admins
                    }
                }
            }
        }
    }
}

A: I tested your code and found an exception in Access Control Sections. The compiler does not allow access to all security When you want to access the permissions of a file. Change AccessControlSections to AccessControlSections.Access. Then I did not find any error.
var rules = new FileSecurity(fn, AccessControlSections.Access)
             .GetAccessRules(true, true, typeof(NTAccount));


text:
Q: $P(x,n) = \frac{x(n-1)!}{n^{x}(n-x)! }$ -- What is the name of this probability distribution? $$
P(x,n) = \frac{x(n-1)!}{n^{x}(n-x)! }
$$
I'm having a really tough time describing what this distribution does, but it's simple in code.  So if you know code, then read on:
// example with n = 10
// keep incrementing x until it is greater than random number between 0 and 10
// note that the random number is generated after each iteration
var i = 0;
while (i++ < Math.random() * 10){};
i = i - 1;
// P(3, 10) = the odds that i will end up being 3

What is the name of this distribution?

A: Let $X$ be a random variable with probability mass function
$$
    p_m = \mathbb{P}\left(X=m\right) = \frac{m}{n^m} \frac{(n-1)!}{(n-m)!} [ 1 \leqslant m \leqslant n ]
$$
The pmf satisfies a simple recurrence equation:
$$
    \frac{p_{m+1}}{p_m} = \frac{n-m}{n} \frac{m+1}{m}
$$
discrete distributions whose pmf satisfy first order difference equation with polynomial coefficients were studies by Katz (see Johnson, Kemp, Kotz), who considered them discrete analogs of Pearson distribution family.
It remains to prove that the sampling procedure is correct. The probability of the event that the sampling code above yields $m$, is equivalent to the probability that
$$
   \mathbb{P}\left(U_1 > \frac{1}{n}, U_2 > \frac{2}{n}, \ldots, U_{m-1} > \frac{m-1}{n}, U_m < \frac{m}{n} \right) = \frac{m}{n}\prod_{k=1}^{m-1} \left(1-\frac{k}{n}\right) = \frac{m}{n^m} \frac{(n-1)!}{(n-m)!}
$$
where $U_k$ are iid continuous random variables, uniformly distributed on the unit interval.

Actually this particular distribution is known as Naor's distribution, which arises in an urn model.


text:
Q: Convert normal web service to wcf I have a normal web service.  Many java and .net users are accessing it.  Can I update it to wcf without anyone having to change their code?  Any tutorials?

A: You should be able to use WCF with Basic binding. It supports non-wcf clients with "legacy asmx" (is this what you call normal web service?).


text:
Q: Exception with Entity Framework in VS2010 I am facing an exception while running the below code,
// Create a connection object for entity connection.
EntityConnection con = new EntityConnection(connString);

The exception message is

The specified store provider cannot be found in the configuration, or is not valid

and the inner exception is

Unable to find the requested .Net Framework Data Provider. It may not be installed

in System.Data.Entity dll.
The above mentioned issue occurs only when run the project on .NET 4.0 and all other framework projects are executing fine with provided connection.
Could anyone please let me know, why exception while working with Entity Framework in 4.0 .NET framework?
Regards,
Amal Raj


text:
Q: How to describe a array of integers whose available digits are positive integers It is more of a language question as I am working on translating a technical document into English. The current description is as below:
The value of this parameter can be an array of integers or an integer range. The integers start from 0. Examples: '0-2' and '1,2,3'.
My question is: does this description cause confusion to imply that the value must start from 0 which makes the second example look incorrect on first sight?


text:
Q: Is there a word for dried blueberries? There are words for dried grapes and dried plums; raisins and prunes. Is there a word for dried blueberries, which is also common as a fruit?
As an example,

I am having _________, which are dried blueberries.

A: Wikipedia says

Nearly half of the dried fruits sold are raisins, followed by dates, prunes, figs, apricots, peaches, apples and pears. These are referred to as "conventional" or "traditional" dried fruits: fruits that have been dried in the sun or in heated wind tunnel dryers. Many fruits such as cranberries, blueberries, cherries, strawberries and mango are infused with a sweetener (e.g. sucrose syrup) prior to drying.

Note there is no word for dried apricots, peaches, figs, apples or pears. Likewise there is no word for dried blueberries.


text:
Q: The current directory is invalid on Windows 8 I've been trying to run the following command through command prompt as administrator
netstat -a -b

However I get the following error
The current directory is invalid.

I tried to follow http://support.microsoft.com/kb/257996 but I don't think mine has anything to do with Logon Scripts
UPDATE
Running netstat -a as normal user through command prompt works fine. However I need to know which process ID using -b option which requires elevation.

A: I tried the same command "netstat -a -b" WITH ADMINISTRATIVE PRIVILEGES
There isnt any issue at all.
Here is your Problem:
Like any other program netstat.exe is also a program which is located on the windows directory
Browse to C:\Windows\system32> and then type so you should face the program locational issue.
If you are unsure whether c: or d: is the windows root directory.
1.Open the cmd file with Admin Previleges
2.type "cd %windir%\system32"
3.The above step should automatically switch to your root win folder


text:
Q: XSL FO - Different page numbering in footer for each element Sample XML:
<ResultSet>
  <WC>
   <Id>1</Id>
  </WC>
  <WC>
   <Id>2</Id>
  </WC>
  <WC>
   <Id>3</Id>
  </WC>
</ResultSet>

I'm trying to start page numbering from 1 and count only the amount of pages for each WC element.
For example, if the first WC element have 2 pages, the first page will 1/2 and the second 2/2 and for the second WC element which have 3 page, it will start the count from 1, and first page will be 1/3 and so on.
Is that possible to achieve?
I'm using Apache FOP.
Any help will be appreciated.
EDIT:
<xsl:stylesheet version="1.0" xmlns:fo="http://www.w3.org/1999/XSL/Format" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output method="html" version="1.0" encoding="UTF-8"/>

        <xsl:template match="/">

            <fo:root>
                <fo:layout-master-set>
                    <fo:simple-page-master master-name="A4" page-height="279.5mm" page-width="216mm">
                        <fo:region-body region-name="xsl-region-body" margin="62mm 10.4mm 16mm 10.4mm" />
                        <fo:region-after region-name="xsl-region-after" extent="16mm"/>
                        <fo:region-start region-name="xsl-region-start" extent="10mm"/>
                    </fo:simple-page-master>
                </fo:layout-master-set>

                <xsl:for-each select="ResultSet">
                    <fo:page-sequence master-reference="A4" >

                        <fo:static-content flow-name="xsl-region-after" >
                            <fo:block font-size="9pt" font-weight="normal" font-family="Helvetica" margin="0mm 10.4mm 0mm 0mm"></fo:block>
                            <fo:block>Page <fo:page-number/> of <fo:page-number-citation ref-id="last-page" /></fo:block>
                        </fo:static-content>

                        <fo:static-content flow-name="xsl-region-start">
                            <fo:block-container border="1px solid black" height="256mm" width="195mm" margin-top="6.5mm" margin-left="10mm">
                                <fo:block> </fo:block>
                            </fo:block-container>
                        </fo:static-content>

                        <fo:flow flow-name="xsl-region-body">
                            <fo:block-container font-size="9pt" font-weight="normal" font-family="Helvetica">
                                <fo:block id="last-page"> </fo:block>
                            </fo:block-container>
                        </fo:flow>
                    </fo:page-sequence>
                </xsl:for-each>
            </fo:root>
        </xsl:template>

</xsl:stylesheet>

A: Basically you need to start a new <page-sequence> for each WC element, this will allow you to restart the page numbering from 1.
Then you need a unique identifier for each number citation, to retrieve the page number of each section. I am assuming that the Id tag can be used for that.
This should do the job (please note that FOP is quite buggy regarding the retrieval of the last page number in some cases - a commercial product like Antenna House Formatter works much better):
<xsl:template match="/">
    <fo:root>
        <fo:layout-master-set>
            <fo:simple-page-master master-name="A4" page-height="279.5mm" page-width="216mm">
                <fo:region-body region-name="xsl-region-body" margin="16mm 10.4mm 16mm 10.4mm" />
                <fo:region-after region-name="xsl-region-after" extent="16mm"/>
                <fo:region-start region-name="xsl-region-start" extent="10mm"/>
            </fo:simple-page-master>
        </fo:layout-master-set>
        <xsl:apply-templates />
    </fo:root>
</xsl:template>

<xsl:template match="WC">
    <xsl:variable name="id.wc">id_<xsl:value-of select="normalize-space(Id/text())" /></xsl:variable>
    <fo:page-sequence master-reference="A4" initial-page-number="1">

        <fo:static-content flow-name="xsl-region-after">
            <fo:block font-size="9pt" font-weight="normal" font-family="Helvetica"
                margin="0mm 10.4mm 0mm 0mm">
                <fo:block>Page <fo:page-number/> of <fo:page-number-citation ref-id="{$id.wc}"
                /></fo:block>
            </fo:block>
        </fo:static-content>

        <fo:static-content flow-name="xsl-region-start">
            <fo:block-container border="1px solid black" height="256mm" width="195mm"
                margin-top="6.5mm" margin-left="10mm">
                <fo:block> </fo:block>
            </fo:block-container>
        </fo:static-content>

        <fo:flow flow-name="xsl-region-body">
            <fo:block-container font-size="9pt" font-weight="normal" font-family="Helvetica">
                <!-- Process the content of the WC here... -->
                <xsl:apply-templates />
                <!-- This empty block is used to retrieve the last page number of the current section -->
                <fo:block id="{$id.wc}" />
            </fo:block-container>
        </fo:flow>
    </fo:page-sequence>

</xsl:template>


text:
Q: how to generate an xml file by taking the first record from a large xml file of size 10gb without getting memory error? i have a large xml file of size 10 gb and i want to create a new xml file which is generated from the first record of the large file.i tried to do this in java and python but i got memory error since i'm loading the entire data.
In another post,someone suggested XSLT is the best solution for this.I'm new to XSLT,i don't know how to do this in xslt,pls suggest some style sheet to do this...
Large XML file(10gb) sample:
<MemberDataExport xmlns="http://www.payback.net/lmsglobal/batch/memberdataexport" xmlns:types="http://www.payback.net/lmsglobal/xsd/v1/types">
    <MembershipInfoListItem>
        <MembershipIdentifier>PB00000000001956044</MembershipIdentifier>
        <ParticipationStatus>1</ParticipationStatus>
        <DataSharing>1</DataSharing>
        <MasterInfo>
          <Gender>1</Gender>
          <Salutation>1</Salutation>
          <FirstName>Hazel</FirstName>
          <LastName>Sweetman</LastName>
          <DateOfBirth>1957-03-25</DateOfBirth>
        </MasterInfo>
    </MembershipInfoListItem>
  <Header>
    <BusinessPartner>CHILIS_US</BusinessPartner>
    <FileType>mde</FileType>
    <FileNumber>17</FileNumber>
    <FormatVariant>1</FormatVariant>
    <NumberOfRecords>22</NumberOfRecords>
    <CreationDate>2016-06-07T12:00:46-07:00</CreationDate>
  </Header>
       <MembershipInfoListItem>
        <MembershipIdentifier>PB00000000001956044</MembershipIdentifier>
        <ParticipationStatus>1</ParticipationStatus>
        <DataSharing>1</DataSharing>
        <MasterInfo>
          <Gender>1</Gender>
          <Salutation>1</Salutation>
          <FirstName>Hazel</FirstName>
          <LastName>Sweetman</LastName>
          <DateOfBirth>1957-03-25</DateOfBirth>
        </MasterInfo>
    </MembershipInfoListItem>
.....
.....
 </MemberDataExport>

I want to create a file like this..
    <MemberDataExport xmlns="http://www.payback.net/lmsglobal/batch/memberdataexport" xmlns:types="http://www.payback.net/lmsglobal/xsd/v1/types">
        <MembershipInfoListItem>
            <MembershipIdentifier>PB00000000001956044</MembershipIdentifier>
            <ParticipationStatus>1</ParticipationStatus>
            <DataSharing>1</DataSharing>
            <MasterInfo>
              <Gender>1</Gender>
              <Salutation>1</Salutation>
              <FirstName>Hazel</FirstName>
              <LastName>Sweetman</LastName>
              <DateOfBirth>1957-03-25</DateOfBirth>
            </MasterInfo>
        </MembershipInfoListItem>
</MemberDataExport>

is there any other way i can do this without getting any memory error? pls suggest that too.

A: You didn't show your code, so we can't possibly know what you're doing right or wrong. However, I'd bet any parser would need to load the entire file just to check if syntax is OK, no missing tags etc. and that will surely cause an OutOfMemory error for a 10 GB file.
So, just in this case, my approach would be to read the file line by line using a BufferedStreamReader (see How to read a large text file line by line using Java?) and just stop when you reach a line that contains your closing tag, i.e. </MembershipInfoListItem>:
StringBuilder sb = new StringBuilder("<MemberDataExport xmlns=\"http://www.payback.net/lmsglobal/batch/memberdataexport\" xmlns:types=\"http://www.payback.net/lmsglobal/xsd/v1/types\">");
sb.append(System.lineSeparator());
try (BufferedReader br = new BufferedReader(new FileReader(file))) {
    String line;
    while ((line = br.readLine()) != null) {
        // process the line
        sb.append(line);
        sb.append(System.lineSeparator());
        if (line.contains("</MembershipInfoListItem>")) {
            break;
        }
    }
    sb.append("</MemberDataExport>");
} catch (IOException | AnyOtherExceptionNeeded ex) {
    // log or rethrow
}

Now sb.toString() will return what you want.

A: In Python (which you mentioned besides Java) you could use ElementTree.iterparse and then break parsing when you have found the element(s) you want to copy:
import xml.etree.ElementTree as ET
count = 0
copy = 1 # set this to the number of second level (i.e. children of the root) elements you want to copy
level = -1

for event, elem in ET.iterparse('input1.xml', events = ('start', 'end')):
    if event == 'start':
        level = level + 1
        if level == 0:
            result = ET.ElementTree(ET.Element(elem.tag))

    if event == 'end':
        level = level - 1
        if level == 0:
            count = count + 1
            if count <= copy:
                result.getroot().append(elem)
            else:
                break

result.write('result1.xml', 'UTF-8', True, 'http://www.payback.net/lmsglobal/batch/memberdataexport')

As for better namespace prefix preservation, I have had some success using the event start-ns and registering the collected namespaces on the ElementTree:
import xml.etree.ElementTree as ET
count = 0
copy = 1 # set this to the number of second level (i.e. children of the root) elements you want to copy
level = -1

for event, elem in ET.iterparse('input1.xml', events = ('start', 'end', 'start-ns')):
    if event == 'start':
        level = level + 1
        if level == 0:
            result = ET.ElementTree(ET.Element(elem.tag))

    if event == 'end':
        level = level - 1
        if level == 0:
            count = count + 1
            if count <= copy:
                result.getroot().append(elem)
            else:
                break

    if event == 'start-ns':
        ET.register_namespace(elem[0], elem[1])

result.write('result1.xml', 'UTF-8', True)


text:
Q: Virtualhost pulling from the same site? I have my httpd.conf on fedora 8 that I am setting the virtual host file. Here is what I have:
DocumentRoot "/var/www/html"
<Directory />
    Options FollowSymLinks
    AllowOverride None
</Directory>

<Directory "/var/www/html">
    Options Indexes FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
</Directory>

then below I am trying to setup a vhost to have multiple sites on the server:
NameVirtualHost *:80

<VirtualHost *:80>
ServerName kadence.tv
DocumentRoot /var/www/html/
</VirtualHost>

<VirtualHost *:80>
ServerName nacc.biz
DocumentRoot /var/www/html/nacc/
</VirtualHost>

also in the /var/www/html/ directory I have the index.php file for the kadence site...when I do to either site I get the index for the kadence site...any ideas what I am doing wrong
EDIT the full contents of my httpd configuration file are here.

A: If the name you're using doesn't match one of the virtualhost sections, it will default to using the first one.  My guess would be that you're accessing www.nacc.biz.  The www is significant.  The name has to match exactly.  Since apache doesn't have a virtualhost section for www.nacc.biz, it is using the first one (kadence.tv) as the default.
Take a look at the ServerAlias directive, and use it to specify all of the server names you expect to use.

A: 1 Check active NameVirtualHost. Open /etc/apache2/ports.conf file:
NameVirtualHost *:80

2 Check DNS
# ping app.local
PING localhost.localdomain (127.0.0.1) 56(84) bytes of data.

# ping john.app.local
PING localhost.localdomain (127.0.0.1) 56(84) bytes of data.

3 Check Apache config(/etc/apache2/sites-enabled/000-default):
<VirtualHost *:80>
        ServerName app.local
        DocumentRoot /var/www
        <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>
</VirtualHost>

<VirtualHost *:80>
        ServerName john.app.local
        DocumentRoot /var/www/john
</VirtualHost>

$ sudo apache2ctl configtest
Syntax OK

$ sudo  apache2 -S
VirtualHost configuration:
wildcard NameVirtualHosts and _default_ servers:
*:80                   is a NameVirtualHost
         default server app.local (/etc/apache2/sites-enabled/000-default:1)
         port 80 namevhost app.local (/etc/apache2/sites-enabled/000-default:1)
         port 80 namevhost john.app.local (/etc/apache2/sites-enabled/000-default:12)

4 Test Apache:
$ curl http://john.app.local
john
$ curl http://app.local

It works!

This is the default web page for this server.

The web server software is running but no content has been added, yet.


text:
Q: Firebase Analytics debugging mode? I am starting to use Firebase Analytics in Android. I am familiar with Google Analytics and I would like to switch to FA. In GA, you can use another tracking-id when you're debugging (in tracker-config.xml), than the tracking ID used in release versions. That is to prevent the many times you start up the app during debugging, to appear in the Analytics results. Is there a way to achieve that effect in Firebase Analytics? I couldn't figure out how.
My app also doesn't have that many users, so most of the analytics would come from me using the app while debugging.
Thanks

A: One way to approach this would be to register a second "debug" app in your Firebase project that uses a different package name. Then, the google-services.json will contain two mobilesdk_app_id's -- one for your debug app and one for your release app.  These are effectively your tracking IDs.  Their reporting will be kept separate in the Analytics reports for your project.


text:
Q: 2 JSON Curl Requests in a PHP file in sequence? I have PHP code to execute 2 Curl calls to the same URL with different data. It works but there is some lag (a few seconds) between the first and the 2nd.
i have looked at curl multi but cannot figure out how to use it for JSON arrays.
please help?
<?php
$data = array("epic" => $epic, "expiry" => "DFB");
$data_string = json_encode($data);

$headers = array(
'Content-Type: application/json; charset=UTF-8',
'Accept: application/json; charset=UTF-8',
'X-IG-API-KEY: '.$xapikey,
'Version: 1',
'X-SECURITY-TOKEN: '.$_SESSION['api_xtoken'],
'CST: ' .$_SESSION['api_cst'],
'_method: DELETE',

);
$ch = curl_init('' . $trading_url . '');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);

$data2 = array("currencyCode" => "GBP", "direction" => $tv_direction);
$data_string2 = json_encode($data2);

$ch2 = curl_init('' . $trading_url . '');
curl_setopt($ch2, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch2, CURLOPT_VERBOSE, 1);
curl_setopt($ch2, CURLOPT_HEADER, 1);
curl_setopt($ch2, CURLOPT_POSTFIELDS,$data_string2);
curl_setopt($ch2, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch2, CURLOPT_HTTPHEADER, $headers2);

$result2 = curl_exec($ch2);

A: You are opening curl connection two times also you have not closed the connection once the request has been completed you need to close the connection
can try something like this
$data_string = json_encode($data);

$headers = array(
'Content-Type: application/json; charset=UTF-8',
'Accept: application/json; charset=UTF-8',
'X-IG-API-KEY: '.$xapikey,
'Version: 1',
'X-SECURITY-TOKEN: '.$_SESSION['api_xtoken'],
'CST: ' .$_SESSION['api_cst'],
'_method: DELETE',

);
$ch = curl_init('' . $trading_url . '');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_VERBOSE, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);

$data2 = array("currencyCode" => "GBP", "direction" => $tv_direction);
$data_string2 = json_encode($data2);

curl_setopt($ch, CURLOPT_POSTFIELDS,$data_string2);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);

$result2 = curl_exec($ch);
    curl_close($ch);

A: You can start them simultaneously using stream_socket_client()
You can also use stream_socket_client() to make calls to two of your own php scripts where each of your curl requests are in each script.
You then call your two scripts using stream_socket_client() where the urls used are to your own scripts.
It's not simple to use sockets, so I included some code I wrote 10 years ago.  As I remember it took a day or two to get it working
What this script does is validate webpages using the W3C CSS and HTML validator tools and webpage speed test to evaluate how well a webpage was designed.  Calling them in parallel reduced the time significantly vs making the requests serially.
You may want to use a newer user agent.
  ini_set('user_agent', 'Mozilla/5.0 (Windows NT 5.1; rv:22.0) Gecko/20100101 Firefox/22.0');
  set_time_limit (60);
  $timeout = 120;
  $result = array();
  $sockets = array();
  $buffer_size = 8192;
  $id = 0;
  $urls = array();
  $path = $url;
  $url = urlencode("$url");
  $urls[] = array('host' => "jigsaw.w3.org",'path' => "/css-validator/validator?uri=$url&profile=css3&usermedium=all&warning=no&lang=en&output=text");
  $urls[] = array('host' => "validator.w3.org",'path' => "/check?uri=$url&charset=%28detect+automatically%29&doctype=Inline&group=0&output=json");
  $urls[] = array('host' => "validator.w3.org",'path' => "/check?uri=$url&charset=%28detect+automatically%29&doctype=XHTML+Basic+1.1&group=0&output=json");
  $urls[] = array('host' => "www.webpagetest.org",'path' => "/runtest.php?f=xml&bwDown=10000&bwUp=1500&latency=40&fvonly=1&k=1a736137bdd4ea914a6fc7ca06f71a&url=$url");
  $err = '';
  foreach($urls as $path){
    $host = $path['host'];
    $path = $path['path'];
    $http = "GET $path HTTP/1.0\r\nHost: $host\r\n\r\n";
  //  echo "
\n=>$host
\n=>$path
\n=>$http
\n";
    $stream = stream_socket_client("$host:80", $errno,$errstr, 120,STREAM_CLIENT_ASYNC_CONNECT|STREAM_CLIENT_CONNECT);
    if ($stream) {
      $sockets[] = $stream;  // supports multiple sockets
      $start[] = microtime(true);
      fwrite($stream, $http);
    }
    else {
   $err .=  "$id Failed
\n";
    }
  }

while (count($sockets)) {
  $read = $sockets;
  stream_select($read, $write = NULL, $except = NULL, $timeout);
  if (count($read)) {
    foreach ($read as $r) {
      $id = array_search($r, $sockets);
      $data = fread($r, $buffer_size);
      if (strlen($data) == 0) {
     //   echo "$id Closed: " . date('h:i:s') . "\n\n\n";
        $closed[$id] = microtime(true);
        fclose($r);
        unset($sockets[$id]);
      }
      else {
        $result[$id] .= $data;
      }
    }
  }
  else {
 //   echo 'Timeout: ' . date('h:i:s') . "\n\n\n";
    break;
  }
}


text:
Q: Self-referenced type restriction on inferred type argument in Typescript I want to have an object builder that should infer types similar to how zod.js does.
It should receive fallbacks as an argument and return an object to work with.
Fallback could be a value or a function that returns a value. That function should also be able to use other fields as an argument.
In a simple case it should be something like this:
type TypeOf<T> =
    T extends (...args: any) => any ? TypeOf<ReturnType<T>> | null :
    T extends object ? { [K in keyof T]: TypeOf<T[K]> } : T;

type Without<T, K> = Pick<T, Exclude<keyof T, K>>;

type Fields<T> = {
    [K in keyof T]: string | (<A extends Without<T, K>>(arg: A) => string);
};

declare function build<T>(fallbacks: Fields<T>) : TypeOf<T>;

// `obj` should have inferred type `{ simple: string, fallback: string }`
const obj = build({
    simple: "test",
    fallback: (obj) => `hello, ${obj.simple}`, //  <--  obj has unknown type
});

console.log(obj); // { simple: "test", fallback: "hello, test" }

obj.simple = "world";
console.log(obj); // { simple: "world", fallback: "hello, world" }

obj.fallback = "custom";
console.log(obj); // { simple: "world", fallback: "custom" }

obj.fallback = null;
console.log(obj); // { simple: "world", fallback: "hello, string" }

It is working if I strictly define my type:
type MyType = {
    simple: string
    fallback: string | null
}

const obj = build<MyType>({ ... });

Or if I remove constrictions on the fallback function argument:
type Fields<T> = {
    [K in keyof T]: string | ((arg: any) => string);
};

So, either type inference not working or the fallback function argument isn't well typed.
As I understand, the main issue is the type argument could be in "inference" mode that resolves types from what it has or in "restriction" mode that checks values by passed types.
Is there a way to have a partial self-referenced type restriction on inferred type argument?


text:
Q: How to list all consumers that are listening to an address on a vertex event bus? I have a vert.x program. I am creating a message consumer and attach it to listen on an address on the vertx event bus . later in the program I am unregistering that consumer . How do I know if the consumer is unregistered successfully ?
following code snippet shows how i register a consumer on an address on vertex event bus
MessageConsumer<JsonObject> consumer = vertx.eventBus().consumer("my_channel", eventHandler)

later after sometime i am unregistering the consumer
consumer.unregister( res -> {
  if(res.succeeded()) { System.out.println("consumer deregistered")}
});

so my question is suppose i have reference to an vertx event bus  vert.eventBus() object how can i verify it if there any consumers on it ?

A: As for the first question, you can safely assume consumer is unregistered successfully when res.succeeded() returns true inside unregister handler (as per your example).
For the second part, afaik the event bus does not maintain the list of consumers registered to it, you have to maintain it yourself. The goal would be to have a map or some other collection where you store references for consumers when you register them with .consumer(...) method and remove them after unregister handler returns succeeded.
I think this would be the issue you are referring to (with the advice by the lead architect of vertx): https://groups.google.com/g/vertx/c/d70YlHLL7KU?pli=1


text:
Q: Encryption error after upgrading mule from 3.8 to 3.9 Have anyone got below error, Please help.
java.lang.RuntimeException: org.mule.security.encryption.MuleEncryptionException: Could not encrypt the data

This never got while using mule version 3.8,
but started getting after upgrading to mule 3.9.

A: This issue was resolved by using new encryption connector configuration.


text:
Q: Setting up Git osxkeychain error I'm setting up Git and I am following http://lifehacker.com/5983680/how-the-heck-do-i-use-github along with the regular tutorial Git provides.
My problem is I don't want to have to type in my password each time so I am following this tutorial and when I arrive at the step where you input the git config —global credential.helper osxkeychain command, I get the error
error: key does not contain a section: —global.

If I ls it, it shows the git-credential-osxkeychain in my current directory but I'm not sure what this error means and how to fix it... Any help is much appreciated.

A: You probably typed '—' (the long dash) instead of the expected double hyphen
 git config --global credential.helper osxkeychain

Note the '--' in front of global, instead of '—'
The lifehacker blog posts incrrectly replace the '--' by '—'.


text:
Q: Display parent-child relation yii2 I am looking for some way to implement the following thing with yii2:
Lets imagine we have the following structure:
- authors table.
- Books table
Each author -> has written 1 or more books.
What I want to do is to display on a view, the details of an author, and under it, a gridview of all the books it has written. After that, control buttons to create/ remove new books for that current author, along with a gridview of the books which belongs to the current author... In some other words, a master-detail view.
How I should retrieve the data of the books? From the same controller for Authors?
I have already implemented the table relations between authors and books, in the Author's model
Thanks in advance, any help is welcome!!

A: If the you have the following relation in your Author model:
public function getBooks()
{
    return $this->hasMany(Books::className(), ['author_id' => 'id']);
}

After declaring relations, getting relational data is as easy as accessing a component property that is defined by the corresponding getter method:
$author = Author::findOne(1);
$books = $author->books;

http://www.yiiframework.com/doc-2.0/guide-db-active-record.html

A: The solution I found at the end was to :

*

*On the Author's controller, I modified the "view" action, so I could a "books" activeDataprovider, and then filtering it by "author id":
public function actionView($id)
    {
        //get current author
         $author=$this->findModel($id);
    $books_search = new BookSearch();

    //get the related books for current author

 $written_books =  $books_search->search(['bookSearch'=>['id_author'=>$id]]);
        return $this->render('view', [
        'author' => $author,
        'books_search'=> $books_search,
        'books'=>$written_books,
    ]);
}

Then I could create on the Author's view, a gridview with the books written by the current author


text:
Q: I Want to verify that Sum of 3 Row values is equal to the first row in on my WebTable using Selenium C#. The Rows are Row3, Row6 & Row8 IList<IWebElement> rows = _driver.FindElements(By.XPath("//div[@id='data_3']/div/div/div[3]/table/tbody/tr[@class]"));
for (int i = 1; i <= rows.Count; i++)
{
    IList<IWebElement> columns = _driver.FindElements(By.XPath("//div[@id='data_3']/div/div/div[3]/table/tbody/tr[@class][" + i + "]/td[@class]"));

    for (int j = 1; j <= columns.Count; j++)
    {

    }
}

A: From what I understand, you need to sum values from three rows and check if it is equal to the value from the first one. I will use the path you have provided.
public int GetRowValue(int rowNumber)
{
    var row = _driver.FindElements(By.XPath("//div[@id='data_3']/div/div/div[3]/table/tbody/tr[@class]"))[rowNumber - 1] // decreased by 1, because if you would like to get first row, it would have 0th index in the array
    var columns = row.FindElements(By.XPath("./td"); // find all tds of the given row.
    int value = 0;
    foreach(var column in columns)
      {
          if (String.IsNullOrEmpty(column.Text)) continue;
          result += Int32.Parse(column.Text);
      }
      return value;
}

With that, you can easily check what you want.
var row1Value = GetRowValue(1);
var sum = GetRowValue(3);
sum += GetRowValue(6);
sum += GetRowValue(8)
Assert.Equals(row1Value, sum);


text:
Q: ToYAML instances for Map and StrMap The purescript-yaml library defines ToYAML instances for simple types such as Tuple, Array etc.
How can I obtain or derive a ToYAML instance for Map or StrMap?
I read somewhere that purescript-generics-rep could be used, but how?

A: This seems to work to convert StrMap a...
import Data.Map as M
import Data.StrMap as StrMap

instance strMapToYAML :: (ToYAML a) => ToYAML (StrMap a) where
  toYAML strMap = YObject $ StrMap.fold (\acc key value ->
    M.insert key (toYAML value) acc
  ) M.empty strMap

The current implementation use YObject as an type alias for Map String YValue  So this instance converts the StrMap a into a Map String YValue, and then wraps it using the YObject data constructor.
An instance for Map a b could be defined similarly, but you'd have to make sure a can be converted into a string, and b can be converted into a YValue.
Edit - I just realized you will have an orphan instance if you try and put this in your own code.  This will need to go in the core library. You can either wait for a pull request to the author, or fork the repo and add that instance to the Data.YAML.Foreign.Encode module.


text:
Q: Template specialization for two types I have a static member function lerp() inside my class template AnimCurve which I want to specialize for Quaternions, this way:
template<>
inline Quatf AnimCurve<Quatf>::lerp(
    const Quatf& start,
    const Quatf& end,
    float time
    )
{
    return start.slerp(time, end);
}

However, this is not generic enough because one may also use Quatd. Is it possible to write a function which would work for both, since both Quatf and Quatd are type definitions of Quaternion<T>?
Here is the current definition of AnimCurve:
template< typename T >
class AnimCurve {
public:
    AnimCurve() {}
    void addKeyframe(float time, T value);
    T getvalue(float time) const;
private:
    static inline T lerp( const T& start, const T& end, float time );
    std::map<float, T> mKeyframes;
};

A:
Is it possible to write a function which would work for both, since both Quatf and Quatd are type definitions of Quaternion?

If you want to specialize your lerp algorithm for exactly those two instantiations of the Quaternion class template, and no other instantiations, then no, you have to explicitly specialize both of them: once for AnimCurve<Quatf> and once for AnimCurve<Quatd>.


text:
Q: If $f(x)$ and $f(x)-x$ have only one real root, then $f(f(x))-x$ has only one real root. First edition was: Let $f(x)$ be a polynomial such that $f(x)$ and  $f(x)-x$ have only one real root. How to prove, without derivatives, that
$f(f(x))-x$ also has only one real root?
Second edition: Let $f(x)=a_3 x^3 + a_2 x^2 + a_1 x + a_0$.  All $a_i \neq 0$. $f(x)$ and $f(x)-x$ have only one real root. How to prove, without derivatives, that
$f(f(x))-x$ also has only one real root?

A: More generally, $f(x)=-x^{2n-1}$ gives a counterexample for each positive integer $n$.
A counterexample for the second edition: $f(x)=-x^3-x^2-x-1$.

A: As Jonas Meyer has pointed out, the problem is actually not true.
As suggested, let $f(x)= -x$. Then $f(x) -x = -x -x = -2x$. Considering $f(f(x)) -x= f(-x) -x = -(-x) -x = 0$. That is to say, for $f(x)=-x$, we have shown $f(x) -x$ has only one real root, namely $x=0$, while $f(f(x))-x=0$ has infinitely many real roots.
Response to comments:
Let $f(x)=x^3 - 2 x^2 + 5 x - 1$. Then, $$f(x) -x = x^3 -2x^2 +5x -1 =x^3 -2x^2 +4x -1$$ Solving for $x$ (by Wolfram Alpha) we have that $x \approx 0.284775$ and that there is only one real root. Considering $f(f(x))-x$ we have the following, $$f(f(x))-x = (x^3 -2x^2 +4x -1)^3 - 2(x^3 -2x^2 +4x -1)^2 +4(x^3 -2x^2 +4x -1) -1$$ which can be "simplifed" to, $$f(f(x))-x = x^9-6 x^8+24 x^7-61 x^6+116 x^5-156 x^4+155 x^3-102 x^2+44 x-8$$
Which has only one real root $x \approx 0.379555$. So, you have shown that there does exist a polynomial, namely $f(x) = x^3 -2x^2 +5x -1$ for which it is true. But this does not show in general that your conjecture is true, since there exists at least one counterexample.
@Jonas: I can't think of another counterexample off the top of my head, I don't want to try to hard at thinking about this.

A: Here's a more general way of making counterexamples.  Choose any real numbers $a < b$.  Let $g(x)$ be any polynomial of odd degree whose leading coefficient is positive. Take $f(x) = a + b - x -  \varepsilon (x-a)(x-b) g(x)$, choosing $\varepsilon \ge 0$ small enough that $f$ is decreasing, and thus $f(x)$ and $f(x) - x$ each have only one zero.  But $f(a) = b$ and $f(b)=a$, so $a$ and $b$ are zeros of
$f(f(x))-x$.


text:
Q: Why aren't my HTTP resources being cached? I have several bundles configured for my MVC5 website.  Client-side caching is working for my images, but all of the bundles are being downloaded on every page load.

The query strings on the bundles do not change, and the content of the bundles is not being changed. (As far as I know, anyway -- I'm just reloading the page.)

The cache-related headers look like they should be caching these bundles, yet I'm downloading them every time.  What am I missing?


text:
Q: Type safety and runtime checking of type I was mildly surprised to find this function in our code base:
public static double ToDouble( object value )
{
   if ( value is double )
   {
      return (double)value;
   }
   else if ( value is decimal )
   {
      return decimal.ToDouble( (decimal)value );
   }
   else
   {
      return double.Parse(
        value.ToString(),
        System.Globalization.CultureInfo.InvariantCulture );
   }
}

It is called from several places in the project, including:

*

*with the ScannedQty column from a deserialised DataTable,

*with the Qty and ScannedQty columns in an unrelated DataTable received from an ADO.NET connection.

I consider it typically unsafe, dangerous, and fraught with evasive errors, whereas the author, and my colleague, disagrees. He wrote it as a universal one-for-all device to read a double from an object regardless of the source and type of the underlying data and uses it while reading an incoming XML and while loading data from the database. Sometimes, he said, the actual value may be a double, sometimes a decimal, and sometimes (e.g. when it comes from an .XML file) a string.
I proposed that he rewrite access to the various data sources using explicit casting to the appropriate type, which is stable for every use case, e.g.:
public static double DblFromDblObj( object value )
{  return ( double )value;  }

public static double DblFromDecObj( object value )
{  return ( double )( decimal )value;  }

public static double DblFromStrObj( object value )
{  return Double.Parse( ( string )value, CultureInfo.InvariantCulture );  }

and replace all invocations of ToDouble() with one of these, depending on the actual data type involved, but he is loth to do so because
a. it will be a waste of time since the code works as is, and
b. if a data type changes in the database or the incoming XML file the program will break.
In my opinion, a strict and unambiguous protocol shall be established, and enforced in the implementation by means of clean access functions that shall fail in case of type mismatch, indicating an error in the data and a violation of the protocol. This kind of fragility is the basis of reliability.
If the programmer cannot decide the type of a field in the payload and writes dynamic type checking for so trivial a task, there is clearly something amiss, such as lack of attention to the data exchange protocol or mere laziness on part of the programmer that prevented him from studying which type is returned where. For example, when querying a database via ADO.NET or another SQL-based mechanism, it is dead wrong to sweep the dust under the carpet:
object valueObj = myDataRow["ScannedQty"];
double value =  Convert.ToDouble( value );

Direct type-casting is cleaner, faster, and more transparent (because it shows the unambiguous internal type to the reader of the code):
double value = ( double )( decimal )myDataRow["ScannedQty"]; // NOT NULL field

Therefore, the refactoring that I propose is not a waste of time but a useful improvement that makes the code cleaner and the program more reliable. It is also very well that the program will stop working if the underlying type of the object changes, because by this token we shall know that somebody broke the protocol.
These arguments of mine, however, failed to convince my colleague, so I should be grateful for others' opinions to help us come to a common understanding. How do you resolve such conflicts at your job?
P.S.: This seeming a more informal forum than StackOverflow, I hope it will not be downvoted and closed as opinion-based. Please, let me know if I am wrong and then be so good as to suggest a better place to ask my question.
P.P.S.: Please, be polite to both of us, for I will show this question to my colleague.

A: Here is my opinion about both of your conversion approaches. In short, both can be "the correct" solution, it depends on the case. The approach of your colleague has certain use cases where it fits clearly better, but same is true for yours (and the gist of your conflict is probably that each of you only sees "his" use case).
Your approach is IMHO more appropriate when

*

*the input data is very strictly typed

*it is a clear error when the input data does not have the exact expected type, and there is no room for variance

Of course, you already told us that you prefer to establish such protocols, and in an ideal world, every data source provides enough and 100% correct meta data to allow this. Unfortunately, we are not working in an ideal world, software is not perfect, and it is not always in our own hands how protocols and meta data look like (especially when something like a database or xml is provided by a 3rd party).
So for cases where some variance is needed and tolerable, the approach of your colleague is IMHO more appropriate. It actually follows the well-known robustness principle - be liberal in what you accept (and conservative in what you do). And that is not error-prone, quite the opposite, it is often necessary for keeping bigger systems manageable.
So my advice is: look at the data source!

*

*do you have it full under your control?

*does it provide all the meta data for the required type checking?

*is it really a hard error when the provided types do not exactly match the expected ones? Or can a value be accepted as double when it is technically not a double, but convertible by, for example, a string conversion?

*are you sure a slight change in a third party component will not cause a huge cascade of changes in your type conversion code, which could be avoided by using your colleagues approach?

If you can answer all those 4 questions honestly with "yes", then your approach will fit better, otherwise I would recommend the one of your colleague.


text:
Q: Javascript trying to get the ID of the image which the mouse moves over I want to get the id of the image the mouse hovers. But I do not understand how to get the ID. Can some one help me :). TY!
function placeImage(x){
var div = document.getElementById("thumbnails");
div.innerHTML = ""; // clear images
for (var i =0; i <= x; i++) {

var image=document.createElement("img");
image.className += " Atributes";
image.src="images/foto_klein_"+i+".jpg";
image.width="135";
image.height="90";
image.alt="foto_klein_"+i;
image.id="image"+i;
image.position="relative";
div.appendChild(image);
image.style.marginRight = '10px';
_img.push(image);

}
};

With the placeImage function i place the images. Now I want to add an mouse event and change the class of the image who is targeted.

I added a mouse over to all the thumbnails. But I cannot get the id of the image of which the mouse hovers. I want to call the id or change the image.className of that particlair image. But I do not know how to call it. Now it only alerts "thumbnial"
function mouseOver(e){
 alert(e.id);
}

A: Use this keyword:

function mouseOver(e){
   alert(e.id);
}

Edit from the comments:
var image=document.createElement("img");
   image.className += " Atributes";
   image.src="images/foto_klein_"+i+".jpg";
   image.width="135";
   image.height="90";
   image.alt="foto_klein_"+i;
   image.id="image"+i;
   image.mouseover = mouseOver;
   image.position="relative";
   div.appendChild(image);
   image.style.marginRight = '10px';
   _img.push(image);

}

Note the mouseOver function being called when the image is hovered.  this will refer to the image element and not the div.

A: To get the id of an image when you hover over it, try this:
function placeImage(x){
    var div = document.getElementById("thumbnails");
    div.innerHTML = ""; // clear images
    for (var i =0; i <= x; i++) {
        var image=document.createElement("img");
        image.className += " Atributes";
        image.src="images/foto_klein_"+i+".jpg";
        image.width="135";
        image.height="90";
        image.alt="foto_klein_"+i;
        image.id="image"+i;
        image.position="relative";
        image.onmouseover = mouseOver;    // <-- Added this
        div.appendChild(image);
        image.style.marginRight = '10px';
        _img.push(image);
    }
}

function mouseOver(e) {
    alert(this.id);
}

A: Hope this helps, though I'm not sure about it working on a dynamically added image.
document.ready = function () {
    var thumbnails = document.getElementById("thumbnails");

    var imgs = thumbnails.getElementsByTagName("img");

    for( var i=0; i<imgs.length; i++ ) {
        imgs[i].onmouseover = function() {
            alert( this.id );
        }
    }
};