text:
Q: Modify an element in forEach doubles the entries I'm currently setting up this js exercise here however it seems it's not working corretcly as I got the duplication of all the entries, I cannot understand why.
Here's the code:
export function updateScore(scoreBoard, player, points) {
  scoreBoard[player] = scoreBoard[player] + points;
  return scoreBoard;
}

export function applyMondayBonus(scoreBoard) {
  Object.keys(scoreBoard).forEach((element) =>{
  updateScore(scoreBoard,element,scoreBoard[element] + 100)
  } );
  return scoreBoard;
}

Once I run the code: I got this output
Object {
-   "Amil Pastorius": 445,
-   "Jesse Johnson": 222,
-   "Min-seo Shin": 119,
+   "Amil Pastorius": 790,
+   "Jesse Johnson": 344,
+   "Min-seo Shin": 138,
  }

Instead of this
{
      'Amil Pastorius': 445,
      'Min-seo Shin': 119,
      'Jesse Johnson': 222,
    };

Thanks in advance
EDIT: My bad, that was a logical error as @Ivar said, I'm passing scoreBoard[element] + 100 as a parameter, then again use scoreBoard[element] in scoreBoard[player] + points.

A: You could very simply write:
export function applyMondayBonus(scoreBoard = {}){
   Object.keys(scoreBoard).forEach(player => {
      scoreBoard[player] += 100
   })
   return scoreBoard
}

My advice would be to just write the function logic directly in the forEach loop. For such small and direct logic, a separate function could be a hassle.


text: Q: Is there a way to pass a value from one swift script to another swift script? I am hoping to be able to reuse some functions in several different scripts. Is there any way I can create a like commonFunctions.swift file and access those functions from other swift scripts?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to order table after SELECT that generates table Basically I have a loop in which I change the Number of each value of my table, in the loop I have a variable in order to increase the number of the value, lets call it @IdTop where in each iteration of the loop it increases by 1. So I made the loop and now to change each value by order (each value has a sequential number) I made a select top x from table and then select top 1 from that select. So what I want is to order the table that I get from this SELECT TOP(@IdTop) * FROM tableX WHERE Constraint = 55510 by ID DESC and then Select the top 1 from it. This is what I tried but it isn't doing what I want:
Select TOP(1) T.ID FROM ((SELECT TOP(3) * FROM tableX WHERE Constraint = 55510) ORDER BY ID DESC) AS T

The table has the following values by row for example:

ID
SequentialNumber

123
3

134
4

155
5

156
2

180
1

Example of Iteration:
Iteration 1:
@IdTop = 1
Where the ID is 123 the SequentialNumber changes to 1
Iteration 2:
@IdTop = 2
Where the ID is 134 the SequentialNumber changes to 2
...
Iteration 5:
@IdTop = 5
Where the ID is 180 the SequentialNumber changes to 5
This is the loop that I made:
DECLARE @IdTop int = 1
WHILE @IdTop < (Select MAX(SequentialNumber) From OriginalTable WHERE Constraint = 55510)
BEGIN
    UPDATE OriginalTable SET SequentialNumber = @IdTop WHERE ID =
    (Select TOP(1) T.ID FROM (SELECT TOP(@IdTop) * FROM OriginalTable WHERE Constraint = 55510 ORDER BY ID DESC) AS T)
    SET @IdTop = @IdTop + 1
END

Table after the loop:

ID
SequentialNumber

123
1

134
2

155
3

156
4

180
5

A: I think that this:
(Select TOP(1) T.ID
 FROM (SELECT TOP(@IdTop) *
       FROM OriginalTable
       WHERE Constraint = 55510
       ORDER BY ID DESC
      ) AS T
)

is a difficult way of writing:
SELECT MAX(T.ID)
FROM OriginalTable
WHERE constraint = 55510
ORDER BY ID DESC

The result can also be reached by doing:
UPDATE OriginalTable
SET ID = t.R
FROM (SELECT
   id,
   row_number() over (order by id) as R
 FROM OriginalTable
 WHERE Constraint = 55510
) AS T
WHERE T.ID = OriginalTable.ID

A: I would recommend to use a Common Table Expression aka CTE instead, like this:
DECLARE @tbl TABLE(ID int, SeqNr int)

INSERT INTO @tbl VALUES (123, 3),(134, 4),(155, 5),(156, 2),(180, 1)

SELECT * FROM @tbl ORDER BY ID

;WITH MyFirstCTE AS
    (SELECT ID AS ROW_ID, ROW_NUMBER() OVER(ORDER BY ID ASC) AS ROW_NUM FROM @tbl)
UPDATE @tbl
SET    SeqNr = ROW_NUM
FROM   MyFirstCTE
WHERE  ID = ROW_ID

SELECT * FROM @tbl ORDER BY ID

Output from first SELECT:
ID          SeqNr
----------- -----------
123         3
134         4
155         5
156         2
180         1

Output from second SELECT:
ID          SeqNr
----------- -----------
123         1
134         2
155         3
156         4
180         5


text:
Q: How to add an import statement in a Go wrapper generated by SWIG I have a wrapper generated by SWIG for the Go language. In this wrapper, I inserted some Go code that needs the package reflect. Consequently, I need to add the line import "reflect" in this wrapper. Is there an example that illustrates how to do this in SWIG?

A: I think what you want is in section 23.4.10 Adding additional go code namely the part about

If you need to import other go packages, you can do this with %go_import. For example...

%go_import("fmt", _ "unusedPackage", rp "renamed/package")

%insert(go_wrapper) %{

func foo() {
  fmt.Println("Some string:", rp.GetString())
}

// Importing the same package twice is permitted,
// Go code will be generated with only the first instance of the import.
%go_import("fmt")

%insert(go_wrapper) %{

func bar() {
  fmt.Println("Hello world!")
}

%}


text:
Q: How to add text area in iOS app I am newbie for iPhone application. I want to add TextArea. I know how to add textField, however can someone help me how can I have Textare in my iPhone application?
I thought, I can increase the height of textfield and make it multi-line, however that option is not there.

A: You cannot increase the height of UITextField. for this you need to use UITextView.
In your Interface builder where you got UITextField, there is also an option of UITextView.
you can use UITextView same as UITextField in iPhone. UITextView is used for multiple lines
UITextView  *txt = [[UITextView  alloc]init];

//set frame

//add on view

[self.view addSubView:txt];

[txt release];

I hope this solves your problem Sample Code for TextView

A: UITextView  *txt = [[UITextView  alloc]initwithframe:CGRectMake(x, y, width,height)];

[self.view addSubView:txt];

[txt release];

A: You could simply do this by clicking on Mainstoryboard.storyboard or viewController.xib and dragging in a UITextView This will allow multi-line text. If you need to access the Textview, type:
.h file

{
  IBOutlet UIITextView *textView;
}

 @property (nonatomic, strong) IBOutlet UITextView* textView;

.m file
@synthesize textView;

EDIT
to get the users data, hook up the outlet in storyboards,
then use:
-(void)getUserText{
NSLog@"%@", self.textView);

}

This should print out whatever the user entered into the textView.


text:
Q: How to create summary of data with the ID the data would insert with I've a MySQL function that would generate the identifier-ID for given table. The table have composite key;
id - Auto_increment
act_id - BigInt(16). Its the ID obtained from the function below.

This function returns BigInt(16)
BEGIN
 DECLARE qid integer;
 SELECT max(id)+1 into qid from wi_activity;
 IF(qid IS NULL) THEN
    SET qid=1;
END IF;
RETURN convert(concat(6,DATE_FORMAT(CURDATE(),'%d%m%Y'),lpad(qid,7,'0')), unsigned integer);
END

Problem 1:
The website has multiple data-entry user who enter data in given table. There might be the case when multiple user tries to enter data simultaneously. This would read same value of ID that would generate same value of act_id.
Problem 2:
Before inserting to table, it is required to display all the data entered including the act_id key that it would acquire after insert and it also must prevent from duplicate act_id key generation.
How can these problem be solved?

A: You cannot reliably predict the ID value a record is going to have, except by actually inserting it into the database.
The best way to do it is to actually insert empty (or full, with some sort of status attached) rows into the database, and display their IDs in your page. Then later you can update those rows to be "accepted".
Any other approach will get you in trouble because only an actually inserted row has a reliable ID value.


text:
Q: Query either field with highest number I have 2 fields in a database table: "up" and "down" and they both have integer values.
up = 8
down = 4

To pull rows where up is more than down I use
$query = "SELECT * FROM table WHERE up > down";

Suppose I want to pull the value of either field that has the highest number. How would I do this in a query?

A: SELECT IF(a > b, a, b) AS max_value
  FROM (SELECT MAX(up) AS a,
               MAX(down) AS b
          FROM table) x

A: I found that the greatest() function is ideal for my case http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_greatest
SELECT GREATEST( up, down ) FROM table


text:
Q: Why does chrome sometimes fail to redraw the page when I expand the browser window? I'm currently working on a responsive design site prototype. So far so good, but for one really strange thing which I can only seem to reproduce in Chrome. When expanding the window, sometimes the browser seems to get trapped between states, showing duplicate elements, and two scrollbars - that is, until I click somewhere outside of the browser window, then everything gets redrawn and looks just fine.
Screenshot:

I've tried a plethora of "tricks" to get chrome to "re-jig" the interface programmatically, such as changing the padding of the body element, modifying the scrollY position, and about 10 or so others, but nothing seems to do the trick. Does anyone have any experience with this? Any advice?

A: This looks like a bug in Chrome.
I searched Chromium bugs and found a few that are similar:

*

*Issue 516127:    Rendering artifacts on osx when something moves above the browser (dock, other windows, etc)

*Issue 473933:    Visual rendering issue

*Issue 476909:    Page didn't redraw correctly

*Issue 245946:    Content isn't layout correctly when resizing window
But actually none of them seems to describe your problem exactly. If you think so too, you can report your bug here.
Note that this might be as well an issue related to your old Mac OS version or even the graphics card.

A: Try adding this just after <head> tag
<meta name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">

A: I had the same problem using cordova (hybrid html5/css3 mobile platform), when rotating the device the internal browser did not refresh correctly. I had a div containing everything with a fixed position. After some tries, I used style width/height: 100% and when rotating the browser refreshed correctly.

A: I second the suggestion to check plugins installed in case there's a conflict.
Looking on Google's forums, the issue has arisen before and was scheduled for a bugfix. Noticed while reading there that they also removed the support for browser window resizing via javascript :/

A: I'm guessing you have a retina display Mac and another external display connected? I see this sometimes on my setup and have tentatively narrowed it down to this situation. When using just the native screen I never see it and not in all screen configurations either.
Try and see if it happens when you use only the built in screen. If that works try switching which screen is the main screen or switch to another external screen altogether.
Sorry for the no fix, but maybe it will get you closer to a solution in your setup at least.


text:
Q: Do I need Playstation Plus to play Splitscreen? Can I play Star Wars Battlefront (2015) without having Playstation Plus? What about Splitscreen mode?

A: There is a "training mode" available for single-player offline play. Splitscreen is also available offline. You don't need PS Plus for either. You only need PS Plus to play online.


text:
Q: Using variable vs. using number Imagine a function in those versions:
int faculty(const unsigned int n) {
    return n == 1 ? n : n * faculty(n - 1);
}

int faculty(const unsigned int n) {
    return n == 1 ? 1 : n * faculty(n - 1);
}

The only difference is that I return n in the first and 1 in the second one, depending on n. The result is the same but is there any other difference you could be aware of while ignoring the significance?
I know there is a high chance the compiler will make the same assembly instructions out of it, but hey, I'm just curious.

A: As has been pointed out in comments, gcc will recognise the two to be identical. For what clang does to the code there is a follow-up question. Apart from clang going havoc, the difference is cosmetic.

There is however a subtle problem in your code. factorial(0) will make n-1 wrap around and recurse till it arrives at n==1 just to return the wrong value: 0 from a 0 * faculty(-1U) in the top-level n==0 call.  (0! is defined to be 1).
This is a overly verbose correct version:
int faculty(const unsigned int n) {
    const unsigned int stop_when_n_leq = 1;
    const int return_at_stop = 1;
    return n <= stop_when_n_leq ? return_at_stop : n * faculty(n - 1);
}


text:
Q: What is the boost way to determine if the given path contains a path delimiter? I have a boost::filesystem::path instance x. I would like to determine whether x contains any path delimiters in it.
Now, I can simply look for \\ and / in x.string(), but I am interested in the boost way to do it, meaning utilizing the boost::filesystem library, if possible.
Thanks.
EDIT

*

*Let me narrow the problem space. My tool is never going to be run on anything, but the Windows OS.

*I have forgotten the drive specifications (c:, etc...). I do not want them either.

A: You can't.
But do you really want to? For example c:a contains two path elements c: and a on windows. Why do you need to search for a path delimiter? What makes you think that such a thing exists on all platforms? What is a path delimiter in OpenVMS? E.g. in:
[a.b.c]a.txt;12

Morale: paths are more complicated beasts than people are used to think. And in fact boost::filesystem::path doesn't work well anywhere beyond POSIX paths. But this is another story.
EDIT: assuming that your question is how to check if a path consists of a single element then the answer is, well, count the number of elements:
boost::filesystem::path p = ...;
if(std::distance(p.begin(), p.end()) == 1)
    cout << "one element\n";


text:
Q: CORS for Google Cloud Storage Bucket (e.g. Firebase Storage) not fetching text in Safari when in iOS I set up CORS for my Google Cloud Storage Bucket according to this:
https://cloud.google.com/storage/docs/cross-origin#Configuring-CORS-on-a-Bucket
and by following this article:
https://bitmovin.com/faq/how-do-i-set-up-cors-for-my-google-cloud-storage-bucket/
My web page fetches the content of .txt and .jpg files contained in my Google Cloud Storage Bucket via a jscript routine.
While the set up described above works for the web and on Safari in iOS for the .jpg files, it does not work on Safari in iOS for the .txt files.
I tend to believe there is something wrong in the CORS headers. However, I'm still not able to figure this out.
Does anybody have any idea on this?

A: The answer was just out there in the right methods to use to SET the headers:
https://docs.cancergenomicscloud.org/docs/enabling-cross-origin-resource-sharing-cors
https://blogs.sap.com/2013/02/11/cors-or-how-to-make-that-damn-iphone-simulator-work/
http://excellencenodejsblog.com/handing-cors-for-your-mobile-app/


text:
Q: Choose $k$ numbers from $n$ numbers and what is the probability that they are divisible by given number $q$? I have $n$ numbers (from $1$ to $n$). I choose $k$ numbers from these. So I need to calculate the probability that these $k$ numbers are divisible by given number $q$.

A: Without loss of generality we may assume that $q$ is positive.
There are $\dbinom{n}{k}$ equally likely ways to choose $k$ numbers from $n$.
There are $m=\lfloor n/q\rfloor$ of our numbers that are divisible by $q$. (Here $\lfloor x\rfloor$ denotes the greatest integer which is $\le x$.)
So there are $\dbinom{m}{k}$ "favourable" outcomes.
Our probability is therefore $\dfrac{\binom{m}{k}}{\binom{n}{k}}$.


text:
Q: Resizing an image gives an Internal Server Error $image = new Imagick("Koala.jpg");

$imageprops = $image->getImageGeometry();

if ($imageprops['width'] > 640) {
    $image->resizeImage(640,425, imagick::FILTER_LANCZOS, 0.9, true);
    $image->writeImage("Koala_new.jpg");
}

I am trying to use Imagick to resize the Koala picture from the Windows 7 sample pictures. However, as soon as I run resizeImage, I get an error 500 200ms after sending the request to run this php file. I am running PHP 5.3.29, ImageMagick 6.8.6-9 and cgi/fastcgi are enabled in the configure command.
The error log shows the following:
[Mon Nov 03 20:19:56 2014] [warn] [client **.**.**.**] (104)Connection reset by peer: mod_fcgid: error reading data from FastCGI server
[Mon Nov 03 20:19:56 2014] [error] [client **.**.**.**] Premature end of script headers: imagetest.php

Is there something wrong with the FastCGI installation?

A: Hope you are doing well.
So below i have given the code.
<?php

$thumb = new Imagick();
$thumb->readImage('myimage.gif');
$thumb->resizeImage(320,240,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage('mythumb.gif');
$thumb->clear();
$thumb->destroy();

?>

Or, a shorter version of the same:
<?php

$thumb = new Imagick('myimage.gif');

$thumb->resizeImage(320,240,Imagick::FILTER_LANCZOS,1);
$thumb->writeImage('mythumb.gif');

$thumb->destroy();

?>

Beside that i have given you the two options for the same which ever is feasible with you can use.
Hope this may make your day !!
Waiting for you comments :)
Cheers :p :)


text:
Q: Rownames intersect of mutiple dataframes I have multiple data frames with the exact same columns, but different rows (and different row numbers). I want to find out if there are shared rownames between those data frames. It doesn't matter what are the values of those rows in each column, the only important thing is the row names.
I can do that for two data frames, like this: intersect(rownames(DF1),  rownames(DF2))
But this will take forever cause I have many datasets. Is there a way to check common row names for all of them together at the same time?
EDIT - here is a sample from one of the data frames:
structure(list(logFC = c(-6.9789425276725, -6.80564834512398,
-5.6476014320244, -6.26235013729251, -5.28269672881498, -3.09147686903668,
-4.96792335935695, -4.19915236394742, -4.83218090923083, -3.98281311064966,
-5.67532487307823, -5.61153529083818, -3.63779239727337, -5.51132458075007,
-5.84723411702433, -3.81087466017047, -6.63518445918401, -3.12684504261733,
-3.67427178247997, -3.55494509554008, -2.93288926187307, -3.34600996743472,
-6.95421793602619, -4.54818507041332, -4.40148611002215, -6.25233850951737,
-4.69560779360338, -3.48176941704349, -6.11632342272272, -4.65245863713412,
-3.93886612606331, -5.80739169944222, -6.91086035105093, -2.82629426029907,
-3.91313349601559, -2.15235576487352, -3.39637748720724, -3.31736956389026,
-3.23641283622935, -4.33878108141206, -4.49762339558376, -2.65451540161907,
-5.41165350920953, -5.94944402709093, -3.80784569069491, -2.83992888237486,
-4.79770162793385, -4.44954188156457, -2.64034862912764, -4.4751984037916
), CI.L = c(-8.67994440382904, -8.75329890267049, -7.33972836815489,
-8.10720823542097, -6.87728491837549, -4.05774266553713, -6.52757600952993,
-5.58307963784586, -6.45170192050377, -5.39488819005967, -7.63936737535009,
-7.58821634428815, -4.95285575867368, -7.54470153062114, -7.95005561275759,
-5.18806492548832, -9.11781751841251, -4.32080214140813, -5.12196476973559,
-4.98320918777515, -4.11606326830917, -4.68673311153421, -9.78640386618229,
-6.36301071764781, -6.20444870302627, -8.80996124532594, -6.60520029900126,
-4.92779850256981, -8.65559956418551, -6.59106405332152, -5.61846701732563,
-8.28675525942228, -9.87474093313019, -4.04871009769845, -5.62314782172317,
-3.10511637109949, -4.90291184721364, -4.79184235598173, -4.70738723812096,
-6.26409071259927, -6.52317179223395, -3.87446905381624, -7.88060413550419,
-8.67817242258957, -5.56793785199272, -4.15957023109633, -6.97818764981877,
-6.50898609325095, -3.89588719023542, -6.57866771201211), CI.R = c(-5.27794065151596,
-4.85799778757747, -3.95547449589392, -4.41749203916404, -3.68810853925447,
-2.12521107253623, -3.40827070918396, -2.81522509004899, -3.21265989795789,
-2.57073803123965, -3.71128237080637, -3.63485423738822, -2.32272903587306,
-3.47794763087899, -3.74441262129107, -2.43368439485263, -4.1525513999555,
-1.93288794382653, -2.22657879522435, -2.12668100330501, -1.74971525543697,
-2.00528682333523, -4.1220320058701, -2.73335942317883, -2.59852351701803,
-3.69471577370881, -2.78601528820549, -2.03574033151717, -3.57704728125992,
-2.71385322094672, -2.259265234801, -3.32802813946217, -3.94697976897167,
-1.6038784228997, -2.20311917030801, -1.19959515864755, -1.88984312720085,
-1.84289677179878, -1.76543843433774, -2.41347145022485, -2.47207499893357,
-1.4345617494219, -2.94270288291487, -3.2207156315923, -2.0477535293971,
-1.52028753365338, -2.61721560604892, -2.3900976698782, -1.38481006801987,
-2.37172909557108), AveExpr = c(2.84380439452138, -0.641350163188155,
1.9374612692823, -0.235638199101607, -0.435518029701078, 3.48510080561988,
1.87095233967784, 1.01628061150791, 1.22174650978923, 2.72177717639537,
-1.20309940325757, -0.857551814218222, 2.20260076015391, 4.80478044066334,
-1.13513003361954, 0.123295030736262, -0.675210875658111, 3.87956282628011,
2.64674998200021, 2.87011242677628, 5.51349257254121, 0.73720258641836,
2.15656931364667, -0.880676268215307, 2.38219307498489, 1.02322266480762,
-0.262985749060007, 2.39888745207399, -2.13290506986535, -1.59949076132351,
0.535926790059711, -1.04571229127454, -1.17629503943425, 0.774433319285671,
0.47146013212957, 3.70538014394418, 2.44644004853682, -0.156538084053944,
3.74986228626275, -1.65408242874073, -1.45872102403627, 3.31161564832369,
-1.17183730367653, -0.890754518007027, 2.41868054745353, 5.45111763272805,
-2.89316057050776, -2.22502982657658, 3.03149820351438, -2.1209576010754
), t = c(-8.67971178415031, -7.39228905582827, -7.06076205121055,
-7.18116415109683, -7.00854088575108, -6.76846004661448, -6.73856582234944,
-6.41902164094181, -6.31214655178395, -5.96695296657183, -6.11308339182853,
-6.00572682477871, -5.85209958519877, -5.73401160854389, -5.88258959067589,
-5.85397948220358, -5.65406688510248, -5.54036162493977, -5.36927047559566,
-5.26556350546633, -5.2440584137816, -5.2796921349758, -5.19453899631105,
-5.30180432734165, -5.16455723198513, -5.17161842960374, -5.20201485889234,
-5.09381834167428, -5.09566636573943, -5.0770749425756, -4.9611870222842,
-4.95520219816026, -4.93278163900794, -4.89123899468251, -4.84111490047663,
-4.77915087210746, -4.76933015577409, -4.75967794339552, -4.65456688053002,
-4.76746627545286, -4.69743671824526, -4.60322701266885, -4.63701021254403,
-4.61250179178841, -4.57682605412049, -4.55273135759758, -4.65479333272545,
-4.57073183768021, -4.44889026750723, -4.50087124759215), P.Value = c(1.55229424251649e-07,
1.30133609714356e-06, 2.33015419714361e-06, 1.88260870380903e-06,
2.55754415226669e-06, 3.94282455388895e-06, 4.16345462038873e-06,
7.50810099243057e-06, 9.17340525927766e-06, 1.77065831075769e-05,
1.33775331440198e-05, 1.64325937561506e-05, 2.2115888159301e-05,
2.7847395364839e-05, 2.08446126717148e-05, 2.20352317313369e-05,
3.25827813373579e-05, 4.07954068339292e-05, 5.73909145200287e-05,
7.07062567807361e-05, 7.38445843217097e-05, 6.87194358047315e-05,
8.16281452619761e-05, 6.57245741306385e-05, 8.67463223172338e-05,
8.5511928670405e-05, 8.04010139024611e-05, 0.000100171705417072,
9.9795109966445e-05, 0.000103650985838079, 0.000131395582252142,
0.000133020277243722, 0.000139292195697043, 0.000151726973454171,
0.000168257771930849, 0.000191272077639828, 0.000195205125031331,
0.000199151346374514, 0.000247795188234922, 0.000195960874195937,
0.000226635597310478, 0.000275812668466433, 0.000257033617226946,
0.000270521748860173, 0.000291459122749773, 0.000306528693840875,
0.000247678269149948, 0.000295197741620148, 0.000381128297979153,
0.000341717532639182), adj.P.Val = c(0.00241102341747661, 0.00794475515460126,
0.00794475515460126, 0.00794475515460126, 0.00794475515460126,
0.00923811102341111, 0.00923811102341111, 0.014576978076804,
0.0158312589430112, 0.0229002649926842, 0.0207779844792916, 0.0229002649926842,
0.0229002649926842, 0.0270328590504175, 0.0229002649926842, 0.0229002649926842,
0.0297691623371673, 0.0352019032746993, 0.0469155623328993, 0.0498675688558607,
0.0498675688558607, 0.0498675688558607, 0.0499016251196769, 0.0498675688558607,
0.0499016251196769, 0.0499016251196769, 0.0499016251196769, 0.0536505837426884,
0.0536505837426884, 0.0536635704012349, 0.0645647170671714, 0.0645647170671714,
0.0655601934414083, 0.0693124515202994, 0.0746679918179983, 0.0793133003048448,
0.0793133003048448, 0.0793133003048448, 0.0916370205634477, 0.0793133003048448,
0.0880026024356585, 0.0951982748137919, 0.0928429335527656, 0.0951982748137919,
0.097553432400939, 0.0991875765153432, 0.0916370205634477, 0.097553432400939,
0.116072249494357, 0.108317484019424), B = c(7.20297424220909,
5.12185903325429, 4.85086822927105, 4.82778189573735, 4.47878578846026,
4.45015062142229, 4.32665141548369, 3.68905526549073, 3.58105745979752,
3.07644941699046, 3.02010053423525, 2.91419323987163, 2.83925429337962,
2.70647282644387, 2.69778050078078, 2.64780216667016, 2.39793196132607,
2.34766742399694, 2.01017932857179, 1.82776636178526, 1.80163027812608,
1.72843647510305, 1.69294586705913, 1.66964379660484, 1.63598134270543,
1.63594094804558, 1.57140154178204, 1.49617298986084, 1.30350655559773,
1.21061838557398, 1.19176011624231, 1.14701956815954, 1.13326015821754,
1.0063098526262, 0.959474301794882, 0.917731867637779, 0.892661776963931,
0.720160756477969, 0.676375764639774, 0.665484835822247, 0.611282810384547,
0.581080152807092, 0.557812063513063, 0.545239611133442, 0.530816871649995,
0.463782969698698, 0.390941796344767, 0.286655122678496, 0.285729527776393,
0.185338863248642)), row.names = c("PLIN4", "LEP", "PLIN1", "SAA1",
"RBP4", "SEMA3G", "GPD1", "FMO3", "STMN2", "COL8A1", "SAA2",
"TUSC5", "PCSK5", "JCHAIN", "PCK1", "AQP7", "EPYC", "AOC3", "FNDC1",
"LYVE1", "FHL1", "AKR1C1", "COMP", "ADAMTS18", "G0S2", "ADIPOQ",
"CIDEC", "ITGBL1", "GABRA2", "C6", "AKR1C2", "ITLN2", "VSTM2B",
"ADCY5", "FHL5", "FAM46C", "NPNT", "EGFL6", "SLIT3", "LGALS12",
"TNMD", "PALMD", "ZIC5", "OLIG2", "FABP4", "LTBP2", "C14orf180",
"KERA", "MRVI1", "LBP"), class = "data.frame")

As you see in the example, the rows are genes. I basically want to find the common genes between all different data frames.

A: Using intersect with Reduce. Put your data frames in a list, lst <- list(df1, df2, ...), then do
Reduce(intersect, lapply(lst, rownames))
# [1] "49"  "18"  "100" "47"  "71"  "37"  "20"  "26"  "3"   "41"  "27"  "36"  "34"  "87"  "58"  "42"  "93"  "30"  "22"  "80"
# [21] "84"  "68"  "88"  "63"  "52"  "61"  "55"  "10"  "29"  "12"  "35"  "16"  "51"  "78"  "17"  "99"  "97"  "62"

Data:
d0 <- data.frame(matrix(0, 100, 2))
set.seed(42)
lst <- replicate(10, d0[sample(nrow(d0), 90), ], simplify=FALSE)


text:
Q: when calling refreshToken() get the message com.google.api.client.auth.oauth2.TokenResponseException: 401 Unauthorized when calling refreshToken(), I get the message:

com.google.api.client.auth.oauth2.TokenResponseException: 401
Unauthorized POST https://oauth2.googleapis.com/token

Here is my Credential creation code. I get accessToken and refreshToken using Spring Security. The application runs successfully until the expiration of the accessToken
  public void initCredential() {
    try {
      Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
      if (ObjectUtils.isEmpty(properties)) {
        properties = createAdsProperties(managerProvider);
      }
      authorizedClient = authorizedClientService.loadAuthorizedClient(
          ID_CLIENT_PROVIDER,
          authentication.getName());
      credential = new GoogleCredential.Builder()
          .setClientSecrets(properties.getProperty(CLIENT_ID),
              properties.getProperty(CLIENT_SECRET))
          .setJsonFactory(JSON_FACTORY)
          .setTransport(GoogleNetHttpTransport.newTrustedTransport())
          .build()
          .setAccessToken(authorizedClient.getAccessToken().getTokenValue())
          .setRefreshToken(authorizedClient.getRefreshToken().getTokenValue());

//      TokenResponse response =
//          new GoogleRefreshTokenRequest(GoogleNetHttpTransport.newTrustedTransport(),
//              JSON_FACTORY,
//              authorizedClient.getRefreshToken().getTokenValue(),
//              properties.getProperty(CLIENT_ID),
//              properties.getProperty(CLIENT_SECRET)).execute(); //TokenResponseException 401

        credential.refreshToken(); //TokenResponseException 401

    } catch (IOException | GeneralSecurityException e) {
      String errorMessage = e.getMessage();
      log.error(errorMessage);
      show(errorMessage);
      throw new CustomException(errorMessage, e);
    }
  }

the commented-out code also doesn't work
I have also aligned the areas in the code and in my account https://console.cloud .google.com/
spring.security.oauth2.client.registration.google.client-id=xxxx
spring.security.oauth2.client.registration.google.client-secret=xxxx
spring.security.oauth2.client.registration.google.redirect-uri=http://localhost:8080/login/oauth2/code/google
spring.security.oauth2.client.registration.google.scope=https://www.googleapis.com/auth/userinfo.email,\
  openid,\
  https://www.googleapis.com/auth/userinfo.profile
spring.security.oauth2.client.provider.google.token-uri=https://oauth2.googleapis.com/token
spring.security.oauth2.client.provider.google.authorization-uri=https://accounts.google.com/o/oauth2/auth?prompt=consent&access_type=offline
spring.security.oauth2.client.provider.google.user-info-uri=https://www.googleapis.com/oauth2/v3/userinfo

please help me!
Updated
example of DriveService initialization code
driveService = new Drive.Builder(
          GoogleNetHttpTransport.newTrustedTransport(),
          GoogleConnectionService.JSON_FACTORY, googleConnectionService.getCredential())
          .setApplicationName(GoogleConnectionService.APPLICATION_NAME)
          .build();

 driveService.channels().stop(channel).execute();

if you delete the credential.refreshToken() line of code, the code will work successfully... within 1 hour, the user can call the Google api
after that, the message above will appear
Q: how do I update the access token?


text:
Q: xpath finding two elements in a tr If I have

  John
  Smith

  John
  Bloggs

To find John using xpath I can use:
//tr[td//text()[contains(., 'John')]]"

However I would like to find the row that has elements both John and Smith?
//tr[td//text()[contains(., 'John')] && td//text()[contains(., 'Smith')]]"

A: I would use //tr[td[contains(., 'John')] and td[contains(., 'Smith')]].

A: You could just use //tr[contains(., 'John') and contains(., 'Smith')]


text:
Q: How many elements does the set of units contains? Given $\langle X^6+X^3+1\rangle \in \mathbb{F}_2[X]$ is an irreducible polynomial, let's define $R:= \mathbb{F}_2[X]/ \langle X^6+X^3+1 \rangle$

*

*How much elements does R contain?
$R$ contains $2^6=64$ elements

*How many elements does the set of units contain?
Here, I know that every non zero element is either a zero divisor or a unit, but since $X^6+X^3+1$ is irreducible, $R$ is a field and therefore there are no zerodivisor, but still, how do I know how many elements?

*

*What is the multiplicative order of the element $X + \langle X^6+X^3+1\rangle$?

I was thinking about reasoning as follow:
(but not sure exactly what to do)
$X^0=1$
$X^1=X$
$X^2=X^2$
$X^3=X^3$
$X^4=X^4$
$X^5=X^5$
$X^6=[-X^3-1]$
...
Any clue for this point, please ?
EDIT:
$X^6=[-X^3-1]$
$X^9=X^3[-X^3-1]=[-X^6-X^3]=-1$
$X^{15}=-X^6=[X^3+1]$
$X^{18}=X^3[X^3+1]=[X^6+X^3]=1$


text:
Q: calling initialization code on view which was created by loading nib from file I loaded a view created by interface builder as follows:
NSArray *array = [[NSBundle mainBundle] loadNibNamed:@"MyView" owner:self options:nil];
MyView *myView = [array objectAtIndex:0];

The view created in the nib also has a .h and .m UIView subclass associated with it.  I have initialization code within my .m source file.  What is the preferred method to call initialization code?

A: use -awakeFromNib. This will be called the first time the class is deserialized from the nib.


text:
Q: QTreeView dynamic height according to content, disclosure triangle I want to emulate a disclosure triangle / disclosure widget with QTreeWidget. For that, I created a QTreeWidget with only one top level item. Its background is transparent, its header is invisible.

Here is the code (mwe):
import sys
from PySide2.QtWidgets import ( QApplication,
                                QLabel,
                                QTreeWidget,
                                QTreeWidgetItem,
                                QVBoxLayout,
                                QWidget)

class DisclosureTree(QTreeWidget):

    def __init__(self):

        super().__init__()

        # Add content
        self.setColumnCount(1)
        parent_item = QTreeWidgetItem(self, ['Disclosure triangle'])
        self.addTopLevelItem(parent_item)
        parent_item.addChild(QTreeWidgetItem(parent_item, 'AAA'))
        parent_item.addChild(QTreeWidgetItem(parent_item, 'BBB'))
        parent_item.addChild(QTreeWidgetItem(parent_item, 'CCC'))

        # Cosmetics
        self.header().hide()
        self.setStyleSheet('background-color: transparent;')

if __name__ == '__main__':
    app = QApplication()

    vbox = QVBoxLayout()
    disclosuretree = DisclosureTree()
    label = QLabel('Plenty of space above…')
    vbox.addWidget(disclosuretree)
    vbox.addWidget(label)
    vbox.addStretch()

    widget = QWidget()
    widget.setLayout(vbox)
    widget.show()

    sys.exit(app.exec_())

The problem is that I want the widget height to automatically resize whether it is collapsed or expanded, like here for example:

Does anybody know how to do that? Thanks a lot and let me know if I can help!

A: You have to update the maximum height of the widget, based on its contents. For each top item you need to get the height for that row using rowHeight() and do the same recursively for child items whenever the item is expanded. Also, you need to overwrite the sizeHint and minimumSizeHint.
class DisclosureTree(QTreeWidget):
    def __init__(self):
        # ...
        self.expanded.connect(self.updateHeight)
        self.collapsed.connect(self.updateHeight)

    def updateHeight(self):
        self.setMaximumHeight(self.sizeHint().height())

    def getHeight(self, parent=None):
        height = 0
        if not parent:
            parent = self.rootIndex()
        for row in range(self.model().rowCount(parent)):
            child = self.model().index(row, 0, parent)
            height += self.rowHeight(child)
            if self.isExpanded(child) and self.model().hasChildren(child):
                    height += self.getHeight(child)
        return height

    def sizeHint(self):
        hint = super().sizeHint()
        hint.setHeight(self.getHeight() + self.frameWidth() * 2)
        return hint

    def minimumSizeHint(self):
        return self.sizeHint()


text:
Q: Why it doesn't store unless when I trying to set a name for a radio button during change? I apologize for the newbie question. So I have 3 radio buttons in my windows form application where the user selects one of them. I have these 3 in a group box and attempted to identify it as a string and use it in a message box later in my code.
string NAME;
if (radiobutton1.checked == true){
  NAME = radiobutton1.Text;
}
else if (radiobutton2.Checked == true) {
NAME = radiobutton2.Text;
}

Then I have a button which displays the message:
message box.show("Welcome " + NAME + "How are you?");

The output of this is welcome how are you instead of welcome Bob how are you? unless I have selected one radio button then changed and pressed a different one. Can someone please explain what is happening here and why it is only displaying the name if the radio button is changed?

A: Might be this code helps you
   string value = "";
   bool isChecked = radioButton1.Checked;
   if(isChecked )
   value=radioButton1.Text;
   else
   value=radioButton2.Text;

   MessageBox.show("Welcome " + value + "How are you?");

A: To fix this issue you can set the 'checked' property to true in property box for your default radio button.

A: In your code, name stays empty as long as no radiobutton is selected.
Try it like this:
string name = null;

if( radiobutton1.Checked )
    name = radiobutton1.Text;
else if( radiobutton2.Checked )
    name = radiobutton2.Text;
else if( radiobutton3.Checked )
    name = radiobutton3.Text;

if( name != null )
    MessageBox.Show( "Welcome " + name + ". How are you?" );
else
    MessageBox.Show( "Please select a name!" );


text:
Q: Importing large xml dataset into symfony2 application I have a fairly large xml file - 7G - to import into a symfony2 app, storing in mongodb.
Are there any symfony2 components, or preferred ways to do this?

A: Try XMLReader - http://www.php.net/manual/en/book.xmlreader.php .
As far as I know XMLReader streams the file rather than reading the whole file in before doing anything with it.
From there you can convert it to a simplexml object if you would prefer it like http://posterous.richardcunningham.co.uk/using-a-hybrid-of-xmlreader-and-simplexml
Not sure about a Symfony specific component though.


text:
Q: How can I display an image in a JS array? Every method I try, I receive either underfined, or the description of the item, not the picture itself. Here's my code (with the different methods I've tried):
Add
show all
  Name
  <input id="Name" />

  <button onclick="searchByName()" class="btn btn-info">
    Search by Name
  </button>
  <input id="Search" />
  Search

My Contacts


text:
Q: OpenLayers 4 and MapServer 7.0.4 HTML template I would like to know if it is possible to render directly a HTML template retrieved from a MapServer WMS GetFeatureInfo call.
The documentation explains that the API uses ol.Format.GML2 to read features Here the API DOC. No mention about HTML.
Here the template I would like to render: HTML template by MapServer
I would like to not know if there is a "direct" way, not as shown in this
example.

A: Looking at this purely from the WMS interface standards perspective, we can see that there is no default format for a GetFeatureInfo request (so if OpenLayers suggests it is GML, then that is a mistake).
Looking at WMS 1.1.1 we can see that the info_format parameter is optional (so any software compliant to this specification can define its own default).  As far as I can tell both GeoServer and MapServer default to plain text as the default when making a WMS 1.1.1 GetFeatureInfo request and not specifying the info_format parameter, or specifying the parameter as empty like info_format&
For the WMS 1.3.0 specification there is still no default format specified, but this time there is a requirement to supply an info_format parameter as part of your GetFeatureInfo request.
It might be that OpenLayers defaults to using GML as the info_format for a GetFeatureInfo request, and if so it can only guarantee such a format by requesting it using the info_format parameter.
To ensure an HTML response you would be wise to always specify that format using the INFO_FORMAT=text/html& as part of your GetFeatureInfo request.


text:
Q: Parsing Conditional Expressions to String I'm looking for a way of parsing a conditional expression to a string.
The best example I can think of is LINQ-to-SQL. It uses ExpressionVisitors to format "Where" clauses. Example:
from a in b where a.x == 5 && a.y < 3 select a

That would translate into the following string (approximately, MSSQL is not current for me):
"SELECT * FROM b WHERE x = 5 AND y < 3"

From what I've read, this was done using the ExpressionVisitor class, as explained in this article: Link
Now the problem is that I don't use LINQ, but I need this particular functionality. Is there a way of parsing a condition like that? I'm willing to do anything with reflection, delegates, lambda, etc.
Honestly, I don't think it's possible, but my brain is a bit fried (read: be nice if the question is ridiculous), so I figured I might just as well give S/O a try.
EDIT: Final usage example:
// Usage:
foo.Bar(foo => foo.X == 5 && foo.Y < 3)

// Ideal string output (variable name (foo) is not needed):
"foo.X == 5 && foo.Y < 3"

EDIT 2: Yes, a number can be lower than 3 and equal to 5. Told you my brain is fried.

A: If it is about about building the expression tree itself, then you could leverage C# compiler abilities.
It is legal to pass a lambda expression to a function acception an Expression>, as long as type arguments of Func are known. For example
 private static void PrintExpression(Expression<Func<int, bool>> lambda)
 {
      Console.WriteLine(lambda.ToString());
 }

can be called as
 PrintExpression(a=> a > 0 && a < 5);

You can improvise with generics as
private static void PrintExpression<T1,T2>(Expression<Func<T1, T2>> lambda)
{
      Console.WriteLine(lambda.ToString());
}

and calling it with
   PrintExpression<int, bool>(a=> a > 0 && a < 5);

For custom printing of the expression part, you can write a simple recursive function that prints an expression or any other logic that suits you.
Remember, the lambda expression is compiled into an Expression at compile time - so can't subsititute it with already compiled Func.
As an alternative to this, you can always build a custom query provider, but that would be slightly deviating from the purpose - as you'd need to bind it some sort of queryable (custom again).

A: Try something like this:
static string GetExpressionString<T>(Expression<Func<T, bool>> expression)
{
    return expression.Body.ToString();
}

Usage as so:
string s = GetExpressionString<Foo>(foo => foo.X == 5 && foo.Y < 3);

Which will return:
((foo.X = 5) && (foo.Y < 3))


text:
Q: Sum in a table created by a script EDIT
now I have this html:

                    Semana
                    Consumo de alimento diario
                    Total Semana
                    Acumulado
                    Consumo Diario
                    Consumo por pollo semana
                    Consumo Acumulado

                    Lunes
                    Martes
                    Miércoles
                    Jueves
                    Viernes
                    Sábado
                    Domingo

                    1
                    <input class="con_sem_1" name="con_lun[]" type="text"
                        onkeypress="numeric(event)" size="6" value="">
                    <input class="con_sem_1" name="con_mar[]" type="text"
                        onkeypress="numeric(event)" size="6" value="">
                    <input class="con_sem_1" name="con_mie[]" type="text"
                        onkeypress="numeric(event)" size="6" value="">
                    <input class="con_sem_1" name="con_jue[]" type="text"
                        onkeypress="numeric(event)" size="6" value="">
                    <input class="con_sem_1" name="con_vie[]" type="text"
                        onkeypress="numeric(event)" size="6" value="">
                    <input class="con_sem_1" name="con_sab[]" type="text"
                        onkeypress="numeric(event)" size="6">
                    <input class="con_sem_1" name="con_dom[]" type="text"
                        onkeypress="numeric(event)" size="6" value="">
                    <input id="tot_sem_1" disabled="disabled" size="7">
                    <input id="acum_sem_1" disabled="disabled" size="7">
                    <input id="con_diario_sem_1" disabled="disabled" size="7">
                    <input id="con_x_pollo_sem_1" disabled="disabled" size="7">
                    <input id="con_acum_sem_1" disabled="disabled" size="7">

and this javascript code:
function calcular() {
    var total = 0;

    $(".con_sem_1").each(function(){
        if (!isNaN(this.value)) {
            total += parseInt(this.value);
        }
    });

    $("#tot_sem_1").val(total);
}

$(document).ready(function() {
    $("#consumo").on("keyup", ".con_sem_1", calcular());
});

and it still does not work.

A: We can simplify this js code down very easily. So long as you put the table into the html and have values for them you could use something like this:

<title>

</title>

<input class="fieldToAdd" type="text" value="1" />

<input class="fieldToAdd" type="text" value="2" />

<input class="fieldToAdd" type="text" value="3" />


text:
Q: Openlayers 4 - Load WMS image layer require authentication I try to load WMS image layer with openlayers 4.6 and angular 5, the code is:
const syr_layer = new ol_layer_Image({
  source: new ol_source_ImageWMS({
      url: 'serverurl', crossOrigin: 'anonymous', serverType: 'geoserver',
      params: { 'LAYERS': 'tst:syr'},
      projection: 'EPSG:4326'
    });
});

But it throws an error:

GET (myserverurl) 401 (An Authentication object was not found in the
  SecurityContext)

How can I send authentication header with the GET request sent by openlayers?

A: Thanks @Thomas, your answer isn't correct 100% but it clear the way for me to get the correct answer.
This is the tileLoader function that worked for me:
private tileLoader(tile, src) {
  const client = new XMLHttpRequest();

  client.open('GET', src);
  client.responseType = 'arraybuffer';
  client.setRequestHeader('Authorization', 'Basic ' + btoa(user + ':' + pass));

  client.onload = function () {
    const arrayBufferView = new Uint8Array(this.response);
    const blob = new Blob([arrayBufferView], { type: 'image/png' });
    const urlCreator = window.URL || (window as any).webkitURL;
    const imageUrl = urlCreator.createObjectURL(blob);
    tile.getImage().src = imageUrl;
  };

  client.send();
}

A: For you purpose, you may want to use tileLoadFunction (API doc) from ol.source.ImageWMS
To illustrate, you can look below. The 2 "secrets" are customLoader and for authentication to uncomment client.setRequestHeader("Authorization", "Basic " + window.btoa(user + ":" + pass));
<!DOCTYPE html>

    <title>Tiled WMS</title>
    <link rel="stylesheet" href="https://openlayers.org/en/v4.6.5/css/ol.css" type="text/css">

The answer is mainly borrowed from How to add a http header to openlayers3 requests? but with some adaptations as the syntax provided was not working.


text:
Q: Setting up SSH client in Smart Git Here's my story, I'm not a software person; However, I'm huge fan of the fascinating world of software, and all the good in it. Through my previous employment and academic history, I have never dealt with software version control programs, let alone software development. Long story short, I got myself into this software position out of necessity to work, and although I work with wonderful and extremely helpful people who helped me set it up before, I found myself now stuck trying to set up git again. So I'm posting here as a last resort, I really hope I can resolve it since smartgit is much more intuitive and easy for me to use than git bash.
I have downloaded and installed git version 2.27.0 for windows, and SmartGit 18.1.0, and added git.exe to executables in smartgit:

Generated the SSH key and stored it in the my personal Users folder using ssh-keygen -t rsa. Then I copied the public key and added it to the Bitbucket Server, I verified it's matching and logged out then back in to make sure it takes it, I even tried to delete the browser cache in an attempt to resolve the problem below.
For the first clone, I was told that I must first clone from GIT Bash prior to cloning from SmartGIT for the first time. The clone wasn't allowed at first, I discovered there was an .ssh folder created in the c drive, after coping the key there it allows a clone (using the command git clone ssh...), but it's missing a sub-module from the repository. I execute the following commands and that sub-module gets updated with the most recent files:

I go to smart git: Remote -> Submodule -> initialize and pull, and Success it works!
I try to pull and it works as well. However, when I try to change the Authentication in Preferences to use SmartGit as SSH client,

and then try to pull, it fails and gives this reason

When I try to clone a new repo in smartgit while setting the Authentication in Preferences to use system SSH client, it clones the repo but misses that submodule.
When I try to clone a new repo in smartgit while setting the Authentication in Preferences to use Smartgit as SSH client, I get an error regarding not being able to read from the same sub-module which was missing from the clone mentioned earlier.

I am positive that I have access rights to that sub-module and that it exists, and I think the fact that I was able to check it out using the commands proves the same. I would appreciate any help or suggestions or suggestions regarding why smartgit is not allowed to read that submodule. Did I miss something in the setup? Thank you so much.


text:
Q: relative paths: difference between "./" and "../" ? I'm  struggling to find the answer of the difference between ./ and ../ in relative paths .
I know ../somepath will look in the parent folder, but where do ./somepath and /somepath point at ?

A: *

*./ points to your current folder/directory

*../ points to the Parent folder/directory ie) One level up

*and / points to the root folder

Eg: Root/Parent/Current.txt

A: Menu>Inner>Core
If you are inside Inner folder,
./menu will point to nothing since there is no menu folder inside Inner folder,
/core will point to Core folder.


text:
Q: Printing areas on several sheets through I would like to know if I can "manually" (through VBA) reorganize the order in which printing areas are printed.
Let's say I have an Excel document with 4 sheets, Sheet1 to Sheet4.
In Sheet2 and Sheet3, depending on situations, I may have 1 or several printing areas (i.e. several pages to print), 1 printing area = 1 full page. Other sheets are "regular" (single printing area, single sheet of paper printed)
IF I have only one page in each case, it's piece of cake... I print SheetX to page X.
BUT users can click a button to create one (or several) new page (s) in Sheet2 and/or Sheet3. I do NOT want to let them create new sheets as they will mess up all. Depending on previous choices, some sheets are displayed or hidden; in this case of several pages in the same sheet, printing areas are defined in VBA today.
IF I have several pages/areas defined in sheet2 and Sheet3, I would like to print them in this order:
Sheet1, Sheet2-area1, Sheet3-area1, Sheet2-area2, Sheet3-area2, Sheet4.
In any case, the printing of the document goes through a VBA macro and a user defined button.
My other solution would be to change page numbers with VBA and print all sheets in order, then users will have to reorder pages manually. Not a big deal with 10-20 pages documents, but still a source of mistakes and complaints.
I think I am more in need of a general idea of how to do it than code snippets. I cannot see where this can be done. I know how to use
ActiveWorkbook.SheetX.PageSetup.printArea = "B2:J34","L2:,S34"

I would need something like
ActiveWorkbook.PageSetup.printArea = Sheet1!"A1:H20", Sheet2!"B2:J34", Sheet3!"B2:L50", Sheet2!"L2:S34", Sheet3!"N2:V50", Sheet4!"A2:K22"

Any clue?

A: Just an idea but what if you use a macro to assemble all the print areas into a new workbook as individual sheets. Put the sheets in the order you want them printed and then print that workbook and close it. It's probably a little more overhead with all the range copying but could give you more control.


text:
Q: Convert Tensor of Integers to Tensor of Floats (Java) I have loaded an image into a tensor of Uint8s. I'm now trying to convert this to a tensor of floats so I can load it into my trained model.
For reference, here is how I got the Tensor of Uint8s:
ReadFile readFile = tf.io.readFile(fileName);
DecodeJpeg.Options options = DecodeJpeg.channels(3L);
DecodeJpeg decodeImage = tf.image.decodeJpeg(readFile.contents(), options);
Tensor image = runner.fetch(decodeImage).run().get(0);

Shape imageShape = runner.fetch(decodeImage).run().get(0).shape();
//reshape the tensor to 4D for input to model
Reshape<TUint8> reshape = tf.reshape(decodeImage,
   tf.array(1,
      imageShape.asArray()[0],
      imageShape.asArray()[1],
      imageShape.asArray()[2]
   )
);

But when I try to load this into my model via:
        Tensor reshapeTensor = s.runner().fetch(reshape).run().get(0);

I get the following error:
org.tensorflow.exceptions.TFInvalidArgumentException: Expects arg[0] to be float but uint8 is provided


text:
Q: What is the value per user in purchase revenue metric in Firebase A/B test We ran a Firebase experiment having the purchase revenue user property as a secondary metric. After some time the value per user metric started showing these huge values.
The attached image shows the purchase revenue metric having total revenue of $2k and the number of users is 10k in each group. Still the estimate for the value per user is $170k-$300k, which doesn't make any sense.
What is the value per user estimate? Should it be the total value divided by the number of users or is it something else?
The client app platform is iOS built in Unity3d with Firebase Unity SDK. The purchases are for subscription products.

A: The discrepancy in the results shown in the question were caused by a bug in the Firebase console. The bug has now been fixed and the correct value per user seems to be the total value divided by the number of users.


text:
Q: Нерекурсивный обход директорий Мне нужно нерекурсивно обойти директорию и получить из нее список папок и файлов. Я нашел пример, но что-то у меня он не работает.
recursive = 0

dst_sav = "D:\\savorsk"
src = "D:\\Project\\2014\\archdata"

for root, dirs, files in os.walk(src):
    if not recursive:
        while len(dirs) > 0:
            dirs.pop()
            print dirs

recursive = 0 это я уже дописал сам т.к. очевидно, что тут переменная задается. Хотя могу ошибаться. Однако указанный скрипт у меня выводит только один каталог и все. Что не так?
Мне нужно получить список файлов и папок в нем.
Non-recursive os.walk()

A: for path, dirs, files in os.walk(.....)

path - текущий каталог куда смотрит цикл (строка)
dirs - массив имен директорий в текущем каталоге
files - массив имен файлов в текущем каталоге

for path, dirs, files in os.walk(...):
   for fname in files:
       print os.path.join(path, fname)


text:
Q: Automatically sync Trac and git on post-receive (using Bitnami on windows) So I have trac installed with the trac-git plugin on Bitnami trac stack on windows. All is working fine however whenever I commit to my git repo I have to open use_trac.bat and then call trac-admin ProjectName repository resync before I can see the changes in trac.
Now what I want to do is call this line in the post-receive hook of the repository but I'm struggling with how to call this from a bat file.
Anyone have any ideas how I can do this?
EDIT:
So far I have this in my post-receive
echo "Resync repo"
"C:/path/to/repos/resync_git.bat"

Calling this bat file I wrote manually works but this isn't calling. I wonder if its because the hook isn't setup right for win?
Here's the contents of that file:
@echo off
CALL "C:\PROGRA~1\Trac\scripts\setenv.bat"
cd "C:\Program Files\Trac"
START "BitNami Trac Stack Environment" cmd
trac-admin C:/path/to/project changeset added "prjname"

I may use trac-admin C:/path/to/project repository resync "prjname" here later...
This is what happens when that calls:
remote: Resync repo
remote: ./resync_git.bat: line 1: @echo: command not found
remote: ./resync_git.bat: line 2: CALL: command not found
remote: ./resync_git.bat: line 5: trac-admin: command not found

A: For one thing, the slashes in your pathname are backwards for a Windows system.  That's probably not enough to derail the script, though.
When I've had issues with hook scripts failing but working when run manually, it's often come down to one of two things: what the script sees as the "current working directory" at the time it's executed, and the user account under which the script runs.  You can solve the first problem by using absolute paths inside the script or by explicitly changing to a specific directory as the first line of the script.  The second problem can be a bit trickier.  Sometimes it's caused by permissions issues, and sometimes it's caused by the script running as a user that has a different PATH.
Either way, you need some more debugging information in order to figure out exactly what's going on here.  In the command that launches the script, redirect stdout and stderr to log files so that you can capture any relevant output.  Add the result into your question and I should be able to give you a more specific answer.
Another possibility worth trying is to eliminate the extra .bat file and simply place the 'trac-admin' call directly into the hook script.
Are you certain that your post-commit hook is running at all?  Try adding a command like "echo [%TIME%] Hook script running >>C:\test.txt" to the top of the hook script and verify that something actually gets logged.  If not, then git might not be seeing your hook script at all.


text:
Q: What are some good practices when trying to teach declarative programming to imperative programmers? I offered to do a little bit training in F# at my company and they seemed to show some interest. They are generally VB6 and C# programmers who don't follow programming with too much passion. That being said I feel like it is easier to write correct code when you think in a functional matter so they should definitely get some benefit out of it.
Can anyone offer up some advice on how I should approach this?
Ideas

*

*Don't focus on the syntax, instead focus on how this language and the idioms it promotes can be used.

*Try and think of examples that are a pain to write in an imperative fashion but translates to elegant code when written in a declarative fashion.

A: Functional programming is an odd beast for me.  I learned F# and Haskell, wrote a few simple programs and love using them, but never had the "flash of revelation" that some people talk about.  But slowly, I noticed that more and more I was writing code that was meant to be immutable, breaking up tasks into more, smaller functions, and trying to use delegates a lot more.  Its a thing that, if you like it, creeps into your work because the value of those techniques are self-evident.
Now, more practically for training:
I find that two concepts really click Functional Programming as a style to me.
First, FP style is based on structure of data, not composition as in OOP.  I looked at something like List in C# as being a clever trick to generate type-safe lists, something that composed the type (string) into the other type (list).  After learning FP, I look at generics more like Monads now.  List is a structured form that code can take, and it decorates the strings.
Second, and perhaps more useful to C#/ASP programmers, is the idea that FP works on recursion and repetition, while OOP works on mutability and looping. I tend to think of the ASP page lifecycle as a kind of FP now: each request is processed from scratch through the entire life-cycle, so the entire page is, in effect, one big slowly recursing program.  If you can narrow that notion down, you get a better idea of how an imperative program can be structured around loops of functions that take in data, operate over it, and return out new data instead of modifying the old.
The trickiest hurdle, at least for me, to overcome with this approach is that sinking feeling that you're wasting tons of resources when using mutable objects would save a ton of memory.  In GC we trust, and I just had to learn to let go of performance concerns until I'd actually seen the program run and verified if there even were any, and if so to use a profiler to see exactly where the problems were.

A: I would recommend:

*

*the presentation Taming Effects with Functional Programming by Simon Peyton-Jones

*the book Real World Functional Programming: With Examples in F# and C# by Tomas Petricek and Jon Skeet

A: Many imperative programming languages (Ada, C/C++, Turbo Pascal, FoxPro) have the ability to define pointer to functions or procedure name literals that can be evaluated (and the procedures named after the literal invoked) at run time.
The traditional example is qsort in C. Build on that the notion that you can define algorithms that execute other algorithms on data structures. Obviously this is just a fraction of what functional programming is. But I've found that this is a good starting point to get the idea to sink in.
Once that sinks in, then you can start delving into other things (immutability, share-nothing, etc.)

A:
Can anyone offer up some advice on how I should approach this?

Sure:

*

*Pick your examples carefully so your F# code not only solves a problem elegantly but also much more elegantly than is possible with C#/VB. Pattern matching and type inference are your friends here.

*Use one example to highlight the benefits of new feature found in F#, e.g. asynchronous workflows, active patterns.

*Don't be afraid to give impure examples using mutable data structures when appropriate. F# is impure for a reason.

*Don't present F# as a panacea. Describe applications for which F# is not well suited as well as those for which it is much better suited than other .NET languages.

*Point at toy samples they can study as well as successful real-world projects that used F# (Bing AdCenter, Halo 3 etc.).

*Explain everything in terms of how F# can help them to solve problems more easily. Avoid religious debates. Stay positive about F#, not negative about other languages. Arm them with facts and evidence but let them draw their own conclusions.


text:
Q: How can I analyze the consecutive persistence of signals (1s and 0s) in dataset in R? Let's say we have a data set that reflects a series of binary signals--either "1" or "0" over some time period. The goal is to measure the consecutive instances of 1, and sum the total. So, for instance, if 1 occurred four times in a row, the cumulative signal would be 4 for the fourth time period. If the next period--the fifth period--was 0, the counter resets until/if the 1 signal returns. I'm looking for a way to record the equivalent of rolling frequencies of consecutive instances of 1s. I've tried for loops and apply(), but can't seem to find the right mix. Any suggestions would be greatly appreciated. As a test, let's create some fake data. Any ideas on how to use R to solve this question? Thanks!
 library(xts)
 set.seed(5)
 x <- xts(cbind(sample(0:1,50,replace=T)), order=Sys.Date()-100 + 1:50)

 > head(x)
       [,1]
 2014-08-26    0
 2014-08-27    1
 2014-08-28    1
 2014-08-29    0
 2014-08-30    0
 2014-08-31    1

A: Another approach using ave:
cbind(x, newCol = ave(x, cumsum(c(FALSE, (as.logical(diff(x)))[-1])),
                      FUN = function(i) seq_along(i) * i))

The result:
           ..1 newCol
2014-08-26   0      0
2014-08-27   1      1
2014-08-28   1      2
2014-08-29   0      0
2014-08-30   0      0
2014-08-31   1      1
2014-09-01   1      2
2014-09-02   1      3
2014-09-03   1      4
2014-09-04   0      0
.
.
.


text:
Q: SSH forwarding with wayland host and x11 client OS: Ubuntu 21.10
I have a host computer running Wayland.
Client running gnome X11 session. I remote ssh to host ssh -Y host
running simple remote application like xterm on the client works, but other applications like nautilus or gnome-terminal are not. Is there a way to fix that. I thought that you do not need to run a window manager of any kind in order to forward application to a client running X11.


text:
Q: Why does my embedded YouTube video work in Firefox, but not Internet Explorer? I'm using the following code to display a YouTube video.
<object width="425" height="344">
    <param name="movie"
           value="**URL**">
    </param>
    <param name="allowFullScreen"
           value="true">
    </param>
    <embed src="**URL**"
           type="application/xshockwave-flash"
           allowfullscreen="true"
           width="425"
           height="344">
    </embed>
</object>

It works in Firefox, but why doesn't it in Internet Explorer?
I'm a totally new to web development, so I'm running into all these wonderful inconsistencies that you veterans are used to ;)

A: To elucidate, it doesn't work because the object tag is incomplete. Firefox gives up on the object element and uses the fallback old-school embed element instead. IE doesn't support embed so you get nothing.
An object element must at least have a type attribute telling it what plugin to use and a data attribute telling it what to send the plugin. In IE you also need to mirror the data attribute in a <param name="movie"> value inside the object because it runs plugins differently.
IE won't 'stream' partially-loaded Flash files this way though. To get that, you have to use an ActiveX classid instead of the type to tell it which plugin to use. If you care about this (and you might not: for small files, stub loaders, and files that are useless until complete, it makes no difference) then you have to start serving combinations of nested objects or embeds, which quickly becomes confusing.

A: Try this:
<object type="application/x-shockwave-flash" data="VID_URL" width="425" height="344">
    <param name="movie" value="VID_URL" />
</object>

A: Previously wasted a few hours working through the same issue. Different cause though...
For IE9, YouTube embeds (at least iframes) were not working because I had previously added Tracking Protection to IE for Google ad servers. In this case, I had to disable the tracking protection (Safety > Tracking Protection) or click the button immediately to the right of the address bar ('Some content is filtered on this site') that alerts end users to filtered content.


text:
Q: Twisted web client IPV6 DNS lookup failed Thanks for the recent IPV6 fix:
https://github.com/twisted/twisted/commit/1c4f621548b5721ae69c4024b41bac3bb12d792c
But I'm getting a "DNS lookup failed: address '[::1]' not found: [Errno -2] Name or service not known" after the patch.
My code:
from twisted.trial import unittest
from urllib import urlencode
from base64 import b64encode
from twisted.python.log import err
from twisted.web.client import Agent, readBody
from twisted.internet import reactor
from twisted.internet.ssl import ClientContextFactory
from twisted.web.http_headers import Headers
from zope.interface import implements
from twisted.internet.defer import succeed
from twisted.web.iweb import IBodyProducer

class StringProducer(object):
    implements(IBodyProducer)

    def __init__(self, body):
        self.body = body
        self.length = len(body)

    def startProducing(self, consumer):
        consumer.write(self.body)
        return succeed(None)

    def pauseProducing(self):
        pass

    def stopProducing(self):
        pass

class WebClientContextFactory(ClientContextFactory):
    def getContext(self, hostname, port):
        return ClientContextFactory.getContext(self)

class HttpsClientTestCases(unittest.TestCase):
    def test_https_client(self):
        def cbRequest(response):
            print 'Response version:', response.version
            print 'Response code:', response.code
            print 'Response phrase:', response.phrase
            print 'Response headers:[{}]'.format(list(response.headers.getAllRawHeaders()))
            d = readBody(response)
            d.addCallback(cbBody)
            return d

        def cbBody(body):
            print 'Response body:'
            print body

        contextFactory = WebClientContextFactory()
        agent = Agent(reactor, contextFactory)

        authorization = b64encode(b"username:password")
        data = StringProducer({'hello': 'world'})
        d = agent.request(
            'POST',
            'https://[::1]',
            headers = Headers(
                {
                    'Content-Type': ['application/x-www-form-urlencoded'],
                    'Authorization': ['Basic ' + authorization]
                }
            ),
            bodyProducer = data
        )

        d.addCallbacks(cbRequest, err)
        d.addCallback(lambda ignored: reactor.stop())
        return d


text:
Q: 'process.bat' is not recognized as an internal command I'm following the following tutorial to try to use the inline dataloader, and now in the last step I'm getting this error:
C:\Users\ThaisCarolyne>process.bat "C:\Users\ThaisCarolyne\dataloader\v54.0.0\samples\conf" comissaoUpsertProcess
'process.bat' is not recognized as an internal command
or external, an operable program or a batch file.

what could i be doing wrong? I will be grateful to anyone who can help
tutorials I'm following:
https://developer.salesforce.com/docs/atlas.en-us.234.0.dataLoader.meta/dataLoader/command_line_import_data.htm
https://www.mirketa.com/scheduling-of-data-loader-through-command-line/

A: This error occurs because the file is not in your PATH (an "environment variable" that tells DOS/Windows where executables are located), and you are not in the correct directory. You can fix this by switching to the "bin" directory where the process.bat file resides, specifying the full path to the process.bat file, or adding it to your PATH variable.
Switch Working Directory
In the second link you posted, they show how to switch to the correct directory:
Cd C:\Program Files(x86)\salesforce.com\Apex Data Loader 22.0\bin

Make sure you're using the correct path name (e.g. it may be Apex Data Loader 53.0).
Specify Full Path
C:\Users\ThaisCarolyne>"C:\Program Files (x86)\salesforce\Apex Data Loader 53.0\bin\process.bat" "C:\Users\ThaisCarolyne\dataloader\v54.0.0\samples\conf" comissaoUpsertProcess

Update Path
This varies between various versions of Windows, but any modern system should be able to get you to the correct screen by clicking on the start menu or pressing the Windows key (typically four squares, found between Ctrl/Fn and Alt), then typing "path" (without quotes) into the search box, and clicking on either "Edit the system environment variables" or "Edit environment variables for your account".
Once there, you can double-click on the Path variable, which should give you a semicolon separated list of values to edit (just add your path to the end), or an editor that allows you to add a new entry. Either way, once your PATH is set up correctly, you'll should be able to use process.bat from cmd (Command Terminal), ps (PowerShell), or even third-party shells like Bash.
Alternatives
Of course, you can just create a new batch file yourself. Just create a new text file, put in a series of commands, such as demonstrated in the second link you posted, and save it with ".bat" at the end. Of course, this file will also need to be either in your working directory or on the PATH, but you can place such files on your desktop, for example, or your HOMEPATH (e.g. C:\Users\ThaisCarolyne) for easy access.


text:
Q: Can one use If/Else statements in HTML side of Google Script WebApp? This question is a follow-on question to: Can one create an Interactive web app with GAS?
I am writing a script that should do the following:

*

*Ask the user for their user number

*Ask the user for a row number from a spreadsheet (if they know it) and some additional info.

*

*If they don't know the row, get the row for them and display it.

*Ask them for the additional info.

This obviously requires an if/else statement. I just don't know how to form it.
I have attempted to put the code on the client and server side and neither works. I have also realized that some JS seems to run on the client side and some does not Accordingly, I have researched client side JS, in general, but not found specific rules for what works and doesn't.
html
<!DOCTYPE html>

    <base target="_top">

Enter your User ID below. If you are re-using a row in your Catalog Spreadsheet (meaning you know the row number),

enter it below in the "Song ID" field, enter the Song Title, and then click the "Continue" button. Else, enter your

User ID only and click the "Continue" button. We will find the next avalable empty row at the end of your Catalog

Spreadsheet and display its value to you. Then you may enter it and your Song Title. After you do, click the

"Continue" button to create the lyric sheet and add the new song to your Catalog Spreadsheet.

Note: We will automatically add your name to the lyric sheet as the songwriter. Add additional writers manually

on the lyric sheet.

<input id="user" type="text" placeholder="User ID">

<input id="song" type="text" placeholder="Song ID">

<input id="title" type="text" placeholder="Song Title">

<input type="button" value="Continue" onclick="saveUserInput()">

gs
function doGet() {
  return HtmlService.createHtmlOutputFromFile('Index');
}

function getSongId(uObj) {
  var userId = uObj.userId;
  var songId = uObj.songId;
  var songTitle = uObj.songTitle;

   if(songId !=""){

Code not included to keep this brief, but it has been tested in other applications of this project and works and what it does is: if the user has entered a Song ID, this code creates the new lyric sheet and adds the new song name to the Catalog SS.

      }
     else{

This code does this:
     return ('The next available row for the new song is '+songId);
        }
}

When I run what I have the Execution Transcript output is:

*

*[19-05-29 07:54:16:951 EDT] Starting execution

*[19-05-29 07:54:16:959 EDT] HtmlService.createHtmlOutputFromFile([Index]) [0 seconds]

*[19-05-29 07:54:16:961 EDT] HtmlOutput.getContent() [0 seconds]

*[19-05-29 07:54:16:961 EDT] HtmlOutput.getTitle() [0 seconds]

*[19-05-29 07:54:16:962 EDT] Execution succeeded [0.003 seconds total runtime]

A: Revised/Corrected html
Got this completely working. revised html is below. The final piece of the puzzle was to make the songId equal to 0 when it is not entered and then test for zero in the gs side. Because, if the songId field is left blank, it renders as "undefined" which was breaking the if/else statement on the gs side.
<!DOCTYPE html>

    <base target="_top">

Enter your User ID below.

<input id="user" type="text" placeholder="User ID">

<input id="song" type="text" placeholder="Song ID">

<input id="title" type="text" placeholder="Song Title">

<input type="button" value="Continue" onclick="saveUserInput()">


text: Q: Desplegar spring boot aplicación VPS Java 1.8 Tomcat 8 tenemos un servicio desarrollado con spring boot, con java 1.8 y tomcat 8, necesitamos desplegarlo en un sitio web. Ya que tenemos que guardar muchas imágenes, optamos por pagar un vps. Alguien nos podrìa orientar que debemos de tener en cuenta. La  idea es contratar un servidor linux y correr una aplicaciòn en angular que consuma el servicio. Gracias


text:
Q: What are pro's and cons of cookies versus sessions? Can someone give me some good reading material on what's best in different cases?
I guess when you have a small website with not a lot of users, you could go for sessions since they are stored on a server. But for a bigger amount of users it may be better to go with cookies? And how do they both score on safety?

A: Session management is divided into two methodologies -- server side and client side. The use of cookies places trust on the client side, as well as the physical state management portion of your application. Not all browsers support cookies, and users have the option to either enable to disable cookies based on their discretion. This places a unique road block in the face of many developers, as they cannot be entirely dependent on the clients system to ensure that they are actively accepting cookies. Clients can kill active cookies at any time. The upside to using cookies is that it is managed by the client, and can live on the client system, being used to track visits to your site and other data that needs to be persisted for long periods of time.
Sessions on the other hand are server side technology. They are actively managed by the server, and their state lives and dies with the server respectively. They are a good way to ensure, regardless of the client system, that the developer is able to maintain some sort of state across browsers. Sessions can be more complex in nature due to concepts such as web farms, but can be overcome by choosing the appropriate type of session state management and storage. The downsides to using sessions are that they are usually short lived and are created to manage a unique visit to your site, without persisting over long periods of time.

A: Sessions almost always use cookies to associate the session with a user (although it is possible to pass strings in the query string or form data with every request).
Cookies:

*

*Have to be included in every HTTP request

*Have limits on the amount of data you can store

*Expose the data you store to the user (and anyone who can sniff their traffic if you don't use SSL)

*Allow users to edit the data directly

*Can be set to persist for some time

Sessions don't.

But for a bigger amount of users it may be better to go with cookies?

If you are storing that much data, then you either have a tiny, tiny hard disk or you are going to exceed the cookie size limits … so no.

A: I think you should use them in different situations, because both have pros and cons.
The biggest con of sessions is that a session is often destroyed when the browser is closed. Cookies on the other hand don't get destroyed that easy.
Cookies aren't always supported while sessions almost always are.
They are both not safe. And as far as I know cookies use slightly more performance. A safer (safer not safe) way to store data on the client side, is by verifying the session information to a hash saved in the database. Store a session ID with the hash in the database. And look it up. next time. If you really want to be secure. Use a token, and generate a new one everytime the information is looked up.
So I'd have to make such a decision. If the information has to be stored for multiple browser sessions. use cookies. But if you just have to save the information for a couple of pageswitches, just use sessions.
Edit: So okay I ran it over my apache server and tracked RAM and CPU activity. (No significant results) Also I checked the time it took the server to set and unset 1000 variables (containing 30 character long string) into sessions and Cookies. Did all tests a couple times and took the avg. result. Here are the results.
COOKIES
  Set: 0.001863 seconds.
  Unset: 0.004932 seconds.

SESSIONS:
  Set: 0.000494 seconds. (very consistent results)
  Unset: 0.000502 seconds. (Again very consistent)

So sessions are quite a lot faster and way more consistent. If you're able to use sessions. I'd definitely go for sessions.


text:
Q: How to set domain for cookie while getting the domain from flexform I want to use a cookie across several sub-domains (say www.website.com, shop.website.com). Furthermore the base-domain (at least I believe it's the base-domain, say website.com) has to be provided by the user of the Content Management System via an input field provided by the system. I then have to read that string and set it as domain for the cookie in JavaScript. The difficulty is that I don't know how to get that string from the input field. I'm using flexforms of the TYPO3 CMS (to let the user provide the domain as a string).
I definitly need help with that question.
Flexform is a technique of TYPO3 to provide custom configuration options for a website (frontend or backend) built by this CMS.

A: I found a solution on my own: I pass the value from the flexform via viewhelper ...

contentOfTheDiv

... as data element to an html element (of the template) and grab it from there with jQuery via ...
$(".className").data("value");


text:
Q: Angular download csv file with Web Api 2 I am trying to download a csv file using web api 2 and angular js.
This is my controller code
public IHttpActionResult ExportCsvData()
{
    var stream = new FileStream("Testcsv.csv", FileMode.Open, FileAccess.Read);
    var response = new HttpResponseMessage(HttpStatusCode.OK);
    response.Content = new StreamContent(stream);
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = "Testcsv.csv"
    };

    return Ok(response);
 }

This is my angular code,
var filename = 'testcsv.csv';
var contentType = 'text/csv;charset=utf-8';
var blob = new Blob([data], { type: contentType });
if (navigator.msSaveBlob) {
    navigator.msSaveBlob(blob, filename);
}

I am using IE 11, but when I open the file in excel, it looks like this,
{   "version": {
    "major": 1
    "minor": 1
    "build": -1
    "revision": -1
    "majorRevision": -1
    "minorRevision": -1   }   "content": {
    "headers": [
      {
        "key": "Content-Type"
        "value": [
          "application/octet-stream"
        ]
      }
      {
        "key": "Content-Disposition"
        "value": [
          "attachment; filename=testcsv.csv"
        ]
      }
    ]

What am I doing wrong?
Thanks !

A: You need to return a response message. The Ok() will serialize the HttpResponseMessage as is.
public IHttpActionResult ExportCsvData()
{

        var stream = new FileStream("Testcsv.csv", FileMode.Open, FileAccess.Read);
        var response = new HttpResponseMessage(HttpStatusCode.OK);
        response.Content = new StreamContent(stream);
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "Testcsv.csv"
        };

        return ResponseMessage(response);
 }


text:
Q: For random generating string how to fix "for loop initial declaration used outside c99 mode"? Random string generator using C programming. How to fix "for loop initial declaration used outside c99 mode"?
void generate_string(char **string){

    srand(time(NULL));
    int numOfChars=rand()%9+1;
    int i=0;
    char temp[numOfChars];
     for(i=0;i<numOfChars;i++){
        char tmp ='A'+rand()%26;
        temp[i]=tmp;

     }
     temp[i+1]='\0';
    strcpy(*string,temp);
}

    int main()
    {
    char *str;
    str= (char*)malloc(11 * sizeof(char));
    generate_string(&str);
    int len=(int)strlen(str);
        printf("Random String:");
    for(int i=0;i<len;i++) {
        printf("%c",*str);
        str++;
       }
    return 0;
}


text:
Q: Using PHP how do I include Saturday into my business days? I've managed to get the following code to work for 'weekdays' and exclude my special days, however:
I'm offering a '7 business days no deposit layby' though my shop is only closed on Sundays. So I need my 'weekday' to include all Saturday's.
$tdate = date("Y-m-d");
$specialdays = ['22-09-2017', '03-10-2017', '14-11-2017', '17-12-2017'];
$i = 7;
$sevenbusinessdays = date('d-m-Y', strtotime($tdate . ' +' . $i . '
Weekday'));

while (in_array($sevenbusinessdays, $specialdays)) {
   $i++;
   $sevenbusinessdays = date('d-m-Y', strtotime($tdate . ' +' . $i . ' Weekday'));
}

I believe using the above code the answer is something to do with
date('w', strtotime($tdate)) == 6

Though I'm unsure how to incorporate it. I've tried the following but it's not working:
$tdate = date("Y-m-d");
$specialdays = ['22-09-2017', '03-10-2017', '14-11-2017', '17-12-2017'];
$i = 7;
$sevenbusinessdays = date('d-m-Y', strtotime($tdate . ' +' . $i . ' Weekday' . date('w', strtotime($tdate)) == '6'));

while (in_array($sevenbusinessdays, $specialdays)) {
    $i++;
    $sevenbusinessdays = date('d-m-Y', strtotime($tdate . ' +' . $i . ' Weekday' . date('w', strtotime($tdate)) == '6'));
}

print $sevenbusinessdays;

This completely failed haha, any guidance and help would be greatly appreciated. I think I'm close, just not getting it.
Thanks for any help, it's greatly appreciated it. :-)

A: You need to to a loop, adding days if:

*

*it's not a sunday OR

*it's not in the special days list

until you've added 7 days
<?php
$tdate = date("Y-m-d");
$specialdays = ['15-09-2017', '20-09-2017', '14-11-2017', '17-12-2017'];
$days = 0;
$i = 0;
while ($days < 7) {
    $i++;
    $day = strtotime($tdate . ' +' . $i . ' day');
    if (date("w", $day) === "0" || in_array(date("d-m-Y", $day), $specialdays)) {
        continue;
    }
    $days++;
}
$sevenbusinessdays = date('d-m-Y', strtotime($tdate . ' +' . $i . ' day'));
echo $sevenbusinessdays;

Demo


text:
Q: How to use Python requests module and TeamCity API to trigger a build? There is a cURL example in section Triggering a Build of TeamCity 9.x Documentation:
curl -v -u user:password http://teamcity.server.url:8111/app/rest/buildQueue --request POST --header "Content-Type:application/xml" --data-binary @build.xml
I'd like to know how to convert it into an equivalent Python script (using POST request from the requests module)?

BTW, I tried the following Python script but got such a response code 400 (Bad Request):
url = "http://myteamcity.com:8111/httpAuth/app/rest/buildQueue/"
headers = {'Content-Type': 'application/json'}
data = json.dumps({'buildTypeId': 'MyTestBuild'})
r = requests.post(url, headers=headers, data=data, auth=("username", "password"), timeout=10)
print "r = ", r

>> r =  <Response [400]>

If change the Content-Type in headers into Accept, got another response code 415 (Unsupported Media Type):
headers = {'Accept': 'application/json'}

>> r =  <Response [415]>

A: The documentation for triggering a build shows you need to send XML, not JSON:
<build>
    <buildType id="buildConfID"/>
</build>

The TeamCity REST API is a bit of a mixed bag; some methods accept both XML and JSON, some only accept XML. This is one of those latter methods. They'll respond with either XML or JSON, based on what you set the Accept header to.
Send the above with your required build ID; for an XML document that simply you could use templating:
from xml.sax.saxutils import quoteattr

template = '<build><buildType id={id}/></build>'

url = "http://myteamcity.com:8111/httpAuth/app/rest/buildQueue/"
headers = {'Content-Type': 'application/xml'}
build_id = 'MyTestBuild'
data = template.format(id=quoteattr(build_id))

r = requests.post(url, headers=headers, data=data, auth=("username", "password"), timeout=10)

Note that I used the xml.sax.saxutils.quotattr() function to make sure the value of build_id is properly quoted for inclusion as a XML attribute.
This'll produce XML; add 'Accept': 'application/json' to the headers dictionary if you want to process a JSON response.

A: FYI json request works in TeamCity 10.

A: Since this question was written & answered, a contemporary OSS alternative now exists: pyteamcity.
Pip command to install (or add pyteamcity to requirements.txt, etc.)
pip install pyteamcity

Code:
from pyteamcity import TeamCity
tc = TeamCity('username', 'password', 'server', 'port')
result = tc.trigger_build('build_id')
print(f'Build triggered. Web URL: {result['webUrl']}')


text:
Q: Automaton backedge arrows running into other states I am trying to draw a finite-state automaton using the automata package in TikZ and am having trouble getting an edge to "clear" the other states (that is, not run into them).  Having read this answer, I used bend for the edge from q1 to q8; while that edge "clears" q5 and q6, when I tried the same for the backedge from q7 to q2, it didn't work.  I also tried in and out from this answer to no avail.
It seems any combination of bend, in, and out parameters that I try still causes that edge to run into q3 and q4.  I know I'm missing something, but what?  The documentation on the automata package is a bit thin in this regard.
Here's my current MWE:
\documentclass{article}
\usepackage[utf8]{inputenc}

\usepackage{tikz}
\usetikzlibrary{automata,arrows,topaths}

\let\oldepsilon\epsilon
\renewcommand{\epsilon}{\varepsilon}

\begin{document}

\begin{tikzpicture}[>=stealth',node distance=1.5cm,semithick,auto]
    \node                   (l)                             {$\cdots$};
    \node[state]            (q1)    [right of=l]            {$1$};
    \node[state]            (q2)    [right of=q1]           {$2$};
    \node[state]            (q3)    [above right of=q2]     {$3$};
    \node[state]            (q4)    [right of=q3]           {$4$};
    \node[state]            (q5)    [below right of=q2]     {$5$};
    \node[state]            (q6)    [right of=q5]           {$6$};
    \node[state]            (q7)    [below right of=q4]     {$7$};
    \node[state]            (q8)    [right of=q7]           {$8$};
    \node                   (r)     [right of=q8]           {$\cdots$};

    \path[->]   (l)     edge                        node        {}              (q1)
                (q1)    edge                        node        {$\epsilon$}    (q2)
                        edge [bend right=60]        node[swap]  {$\epsilon$}    (q8)
                (q2)    edge                        node        {$\epsilon$}    (q3)
                        edge                        node        {$\epsilon$}    (q5)
                (q3)    edge                        node        {a}             (q4)
                (q4)    edge                        node        {$\epsilon$}    (q7)
                (q5)    edge                        node        {b}             (q6)
                (q6)    edge                        node        {$\epsilon$}    (q7)
                (q7)    edge                        node        {$\epsilon$}    (q8)
                        edge [in=90,out=90,above]   node        {$\epsilon$}    (q2)
                (q8)    edge                        node        {}              (r);
\end{tikzpicture}

\end{document}

A: Thanks to percusse's comment, I found that adding the distance option to the edge did the trick, adjusting the in and out values to get it just right:
\documentclass{article}
\usepackage[utf8]{inputenc}

\usepackage{tikz}
\usetikzlibrary{automata,arrows,topaths}

\let\oldepsilon\epsilon
\renewcommand{\epsilon}{\varepsilon}

\begin{document}

\begin{tikzpicture}[>=stealth',node distance=1.5cm,semithick,auto]
    \node                   (l)                             {$\cdots$};
    \node[state]            (q1)    [right of=l]            {$1$};
    \node[state]            (q2)    [right of=q1]           {$2$};
    \node[state]            (q3)    [above right of=q2]     {$3$};
    \node[state]            (q4)    [right of=q3]           {$4$};
    \node[state]            (q5)    [below right of=q2]     {$5$};
    \node[state]            (q6)    [right of=q5]           {$6$};
    \node[state]            (q7)    [below right of=q4]     {$7$};
    \node[state]            (q8)    [right of=q7]           {$8$};
    \node                   (r)     [right of=q8]           {$\cdots$};

    \path[->]   (l)     edge                                    node        {}              (q1)
                (q1)    edge                                    node        {$\epsilon$}    (q2)
                        edge [bend right=60]                    node[swap]  {$\epsilon$}    (q8)
                (q2)    edge                                    node        {$\epsilon$}    (q3)
                        edge                                    node        {$\epsilon$}    (q5)
                (q3)    edge                                    node        {a}             (q4)
                (q4)    edge                                    node        {$\epsilon$}    (q7)
                (q5)    edge                                    node        {b}             (q6)
                (q6)    edge                                    node        {$\epsilon$}    (q7)
                (q7)    edge                                    node        {$\epsilon$}    (q8)
                        edge [in=120,out=60,above,distance=2cm] node        {$\epsilon$}    (q2)
                (q8)    edge                                    node        {}              (r);
\end{tikzpicture}

\end{document}


text:
Q: Setting labels on axis ticks in D3 V5 I'm trying to set the x-axis labels to date strings I create.  I tried using scaleTime() but found that to be a nightmare and not really required for what I want to do.
I've tried scaleLinear() and scaleOrdinal() with 'almost' success, but didn't get there totally
In the examples below 'xlabels' is an array of about 23 strings, like:
["02 JAN 2020", "03 JAN 2020" ... etc]
First trying scaleLinear:
   function draw_Xscale() {
      var xScale1 = d3.scaleLinear()
              .domain([0, xlabels.length])
              .range([0, width]);

      const g = svg.append("g")
              .attr("class", "axis")
              .attr("transform", `translate(0, ${height - 10})`);

      let x_axis = d3.axisBottom(xScale1).ticks(tlabels.length);
      g.call(x_axis).selectAll("line,path").style("stroke", "brown");
   }

This draws an axis but the tick labels are numbers [0 .. 22] - not what I want.  I tried stuff from some online examples something like the following tacked on:
      .selectAll("text")
        .style("text-anchor", "end")
        .attr("dx", "-.8em")
        .attr("dy", ".15em")
        .attr("transform", "rotate(-65)");

but simply couldnt get it to work - probably some subtlety of the syntax I don't understand.
I also tried scaleOrdinal:
   function draw_OrdScale() {
      let arr = Array.from({length: xlabels.length}, (e, i) => i);

      var ordinalScale = d3.scaleOrdinal()
         .domain(xlabels)
         .range([0, width]);

      const g = svg.append("g")
         .attr("class", "axis")
         .attr("transform", `translate(0, ${height-100})`);

      let x_axis = d3.axisBottom(ordinalScale).ticks(tlabels.length);
      g.call(x_axis).selectAll("line,path").style("stroke", "brown");
   }

This drew an axis with the labels I specified, but half of them were piled up on top of each other on the left and the other half on the right.  Obviously I have the range wrong but not sure what it wants to be.  I tried setting the range to:
.range([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22]);

But this just had them a scrunched up into a black smear on the left.
I spent most of the day looking for examples of what I want to do but the few that looked like they should work, didn't.
TIA for any insights

A: We're going to try to make the scale a bit more generic, in case you have more data.
Suppose that data is an array of objects, with a date property. The first step is to get the date to an usable state:
function toTitleCase(str) {
    return str.replace(/[^-'\s]+/g, function(word) {
        return word.replace(/^./, function(first) {
        return first.toUpperCase();
        });
    });
}

var data = data.map(d => toTitleCase(d.date.toLowerCase()))

This will convert every date from "02 JAN 2020" to "02 Jan 2020".
Afterwards, we need to use a date parser. This will convert every date to a real date object:
var parseTime = d3.timeParse("%d %b %Y");
data = data.map(d => parseTime(d.date);

Finally, we can now use a time scale, using d3.extent() to find the min and max value in your dataset. d3.extent() will return an array with two values, the min and the max, and it works on dates, like the rest of D3:
d3
  .scaleTime()
  .domain(d3.extent(d => d.date))
  .nice() // Make the scale look prettier.

That'll give you a scale that works automatically with any date and will work as you add more values.


text:
Q: Unity GetKeyDown seems to register two times I was working on an interactable button script for a 3D game in unity, when I noticed that if I pressed the interact button(e) for a bit longer the script ran twice despite having used the "GetKeyDown" command which should only run for one frame. I have two instances of those buttons, so I created a "buttonId" variable to differentiate each of them. However, when I looked at the console I saw that both messages came from the same button at the exact same time. If I release the button fast enough(meaning I barely tap it), the script only runs once and everything works just fine. This said, I have no idea what's wrong.
public float radius = 3;

public int buttonId = 0;
//changed in editor for every instance of the script

void Update()
{
    Collider[] hitColliders = Physics.OverlapSphere(transform.position, radius);
    //look for colliders in a radius

    for (int i = 0; i < hitColliders.Length; i++)
    {
        if (hitColliders[i].CompareTag("Player"))
        //checks if the collider it's looking at is the player's collider
        {
            // *other stuff*

            if (Input.GetKeyDown("e"))
            //checks whether it's the frame where e was pressed or not
            {
                Debug.Log("E pressed\nButton ID: " + buttonId);
                // *do stuff*
            }
        }
    }
}

Console feed:

"E pressed  Button ID: 1 UnityEngine.Debug:Log(Object)
ButtonScript:Update() (at Assets/Scripts/ButtonScript.cs:90)"

this, but two times
unity version: "Unity 2019.3.14f1 Personal <DX11>"

A: Your logic is a bit backwards; you're doing:

Every frame, scan for close Colliders and if the Player clicks E, do something for each of them

but should be doing:

Every frame, check if Player clicks E and if someone is close, do something

Given the code supplied, it could probably be refactored to something like:
Collider[] hitColliders = Physics.OverlapSphere(transform.position, radius);

var playerCollided = hitColliders.FirstOrDefault(x => x.CompareTag("Player")) != null;

if (playerCollided)
{
    // *other stuff*
}

if (playerCollided && Input.GetKeyDown("e"))
{
    Debug.Log("E pressed\nButton ID: " + buttonId);
}

A: My bad, the player had two objects on it with the "player" tag so the script ran for both of them. I already fixed it


text:
Q: How to find users in a particular tablespace in oracle 11g? I have created a new tablespace and also some users. I have assigned those users to the tablespace. What is the query for finding out the users for the tablespace?

A:  SELECT TABLESPACE_NAME,USERNAME
 FROM  DBA_TS_QUOTAS
 WHERE TABLESPACE_NAME = '<your_tablespace>';

If Tablespace quotas are not available, then:
select USERNAME, DEFAULT_TABLESPACE, TEMPORARY_TABLESPACE
from DBA_USERS
where DEFAULT_TABLESPACE='<your_tablespace>';